mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-05 08:15:41 -08:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eba3c3bf0c | ||
|
|
ec45430eda | ||
|
|
615e98e11e | ||
|
|
a9e0bf49f0 | ||
|
|
31edc2d5c9 | ||
|
|
8b5932c351 | ||
|
|
59d226c2a6 | ||
|
|
ddbc85f73d | ||
|
|
91479b21a1 | ||
|
|
b629f5ef04 | ||
|
|
8c028c1ce0 | ||
|
|
6a93395148 | ||
|
|
98bdbc97c3 | ||
|
|
1d007737b1 | ||
|
|
4ced32be5c | ||
|
|
603c871720 |
No files matched your search
@@ -66,6 +66,8 @@ Key design points:
|
||||
- **Starting ticks are staged by the page, never answered by the server.** A `multi` row with `ticked: true` is seeded into the person's staged answer once (`seedStaged`, marked in `page.local.seeded`); an `answer` on the item would settle the card before anyone saw it, and a staged answer already flows through Send, drafts, the settled record and the reply words.
|
||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-relative-urls`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
|
||||
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in [the console file](./AGENTS-architecture-console.md), a `public/` file in [the page file](./AGENTS-architecture-console-page.md), a game file in [Activities](./AGENTS-architecture-activities.md) or the Ghoul Rush files), which the docs-table test (same file) checks.
|
||||
|
||||
**Every URL the page uses is page-relative** (`fetch("state")`, `href="app.css"`, never a leading `/`), and so is every link the server hands it (`uploads/<id>.jpg`): the macOS app's frame gets no cookie and is signed in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), so a slash-leading URL misses the prefix and gets a 403 there, and only there. `scripts/test-web-console-relative-urls.mjs` names each one, and `scripts/test-web-console-page-frame.mjs` runs the page under the prefix; a game module is resolved against the page (`new URL(entry.module, document.baseURI)`), since `import()` takes no bare path.
|
||||
@@ -109,6 +109,7 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md),
|
||||
| Page styles (`public/styles/*.css`) or `public/index.html` | `npm run test:page -- scripts/test-web-console-page-layout.mjs`, plus the page file of a screen whose own look changed (`test:page` unsets the app variables, takes `--test-name-pattern`, and is the way to run any page file) |
|
||||
| A music prototype (`prototypes/music/<game>/`) | `node prototypes/music/check.cjs <game>` (nothing in `npm test` reads `prototypes/`) |
|
||||
| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-<area>.mjs` (the loop's is `test-web-console-loop.mjs`, the Review Loop's `test-web-console-review-loop.mjs` with `test-web-console-page-review-loop.mjs`), and its `test-web-console-page-<area>.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` |
|
||||
| A URL the page uses, or a link the server builds for it | `node --test scripts/test-web-console-relative-urls.mjs scripts/test-web-console-page-frame.mjs` |
|
||||
| The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` |
|
||||
| A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) |
|
||||
| Dead Code (`src/plan2code-dead-code-scripts/`, `scripts/fixtures/dead-code/`) | `npm run build:skills`, then `node scripts/node-test.mjs scripts/test-script-dead-code.mjs` |
|
||||
|
||||
@@ -19,6 +19,7 @@ Which checks cover which files, read by PR Prep and Test (`test-map.mjs read` ch
|
||||
| Learning on the console | `src/web-console/learning.mjs`, `src/web-console/public/screens/learning-row.js`, `src/web-console/public/styles/learning.css` | `node scripts/node-test.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-page-learning.mjs` | no |
|
||||
| Review Loop on the console | `src/web-console/review-loop-setup.mjs`, `src/web-console/notes/review-loop.md`, `src/web-console/public/screens/review-loop-setup.js`, `src/web-console/public/loop-parts.js`, `src/web-console/public/review-loop-end.js` | `node scripts/node-test.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-loop.mjs && npm run test:page -- scripts/test-web-console-page-review-loop.mjs` | no |
|
||||
| Workflow prompts | `src/plan2code-*.md` | `node scripts/validate-char-count.js && node scripts/check-skill-table.mjs` | no |
|
||||
| App smoke scripts | `plan2code-app/scripts/smoke-*.mjs` | `node scripts/node-test.mjs scripts/test-app-smoke-agent.mjs scripts/test-app-smoke-frame.mjs` | no |
|
||||
| Desktop app | `plan2code-app/**` | `cd plan2code-app && cargo test` | no |
|
||||
| Metrics | `plan2code-metrics/**` | `cd plan2code-metrics && npm test` | no |
|
||||
| Bot | `plan2code-bot/**` | `cd plan2code-bot && npm test` | no |
|
||||
|
||||
@@ -178,6 +178,32 @@ jobs:
|
||||
echo "plan2code-app exited within 5s (exit code $?); smoke test failed"
|
||||
exit 1
|
||||
fi
|
||||
- name: Smoke-test the dashboard frame connects (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
# A window whose dashboard frame never signs in still passes the alive check above
|
||||
# (WebKit gives the frame no cookie, so macOS signs it in by a path prefix:
|
||||
# takeFramePrefix in routes.mjs). Here the app autostarts
|
||||
# scripts/smoke-agent.mjs, which opens a real console as an agent would, and
|
||||
# scripts/smoke-frame.mjs waits up to 60s for that console's /health to count the
|
||||
# frame as a browser. Runs only where the matrix has macOS: manual runs and pull
|
||||
# requests labeled `full-matrix`.
|
||||
run: |
|
||||
project="$(mktemp -d)"
|
||||
export PLAN2CODE_CONSOLE_HOME="$(mktemp -d)"
|
||||
export PLAN2CODE_CONSOLE_DIR="$GITHUB_WORKSPACE/src/web-console"
|
||||
export PLAN2CODE_APP_AGENT_BIN="$(pwd)/scripts/smoke-agent.mjs"
|
||||
# No browser of the console's own, so only the app's frame can count as one.
|
||||
export PLAN2CODE_NO_BROWSER=1
|
||||
target/release/plan2code-app --project "$project" --agent claude &
|
||||
pid=$!
|
||||
status=0
|
||||
node scripts/smoke-frame.mjs "$PLAN2CODE_CONSOLE_HOME" || status=$?
|
||||
kill "$pid" 2>/dev/null || true
|
||||
# The console is detached from the agent, so it outlives the app: stop it from the
|
||||
# project folder it was opened in, under the same console home.
|
||||
(cd "$project" && node "$PLAN2CODE_CONSOLE_DIR/console.mjs" stop --all) || true
|
||||
exit "$status"
|
||||
|
||||
node-tests:
|
||||
name: npm test (${{ matrix.os }})
|
||||
|
||||
@@ -161,7 +161,7 @@ Security, six controls, about 60 lines:
|
||||
1. Bind `127.0.0.1`.
|
||||
2. **`Host` header allowlist.** This is the DNS-rebinding defense and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
|
||||
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
|
||||
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free.
|
||||
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free. The macOS desktop app's frame is the exception: WebKit gives a cross-site frame no cookie, so there the 302 goes to `/f/<sha256(token)[0:32]>/` on the same `127.0.0.1` address, the router takes that exact prefix off the raw request line once, and a request under it passes the token gate. The page uses only page-relative URLs, so it works at `/` and under the prefix alike. Not a `<key>.localhost` host name: macOS tries it on `[::1]` first, where another process can take the port.
|
||||
5. `Origin` check on every mutating request.
|
||||
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
|
||||
|
||||
|
||||
@@ -133,6 +133,11 @@ this:
|
||||
visiting from talking to it through a DNS rebinding trick.
|
||||
- A 128-bit token in the link, swapped for an `HttpOnly; SameSite=Strict` cookie
|
||||
on first load so it leaves your address bar, your history and any screenshot.
|
||||
In the macOS desktop app the page's frame gets no cookie (WebKit blocks
|
||||
cookies for a frame from another site), so the link sends that frame to
|
||||
`/f/<key>/` on the same `127.0.0.1` address instead, where the key is a hash
|
||||
of the token, and the server lets in only requests under that exact prefix.
|
||||
The frame has no address bar, and a browser tab still gets the cookie.
|
||||
- A strict Content Security Policy with no inline script allowed.
|
||||
- Markdown written by the agent is turned into page elements directly and never
|
||||
into an HTML string, so a document that quotes a hostile README cannot run
|
||||
|
||||
@@ -120,5 +120,5 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- 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 → System → 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.
|
||||
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
|
||||
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome.
|
||||
- Never set a `Secure` cookie for the app's `tauri://localhost` frame (Linux and macOS): WebKit drops a Secure cookie sent over plain `http://127.0.0.1`, so every request after the sign-in got a 403 and the Linux app showed "its page did not show in this window" while working on Windows, where WebView2 counts loopback as secure. `cookieSameSite()` in `src/web-console/routes.mjs` sends Lax there and None; Secure only to `tauri.localhost`; check an embed change in a WebKit view, not only Chrome. On macOS WebKit gives the frame no cookie even with Lax, so it signs in by the path prefix `/f/<key>/` (`takeFramePrefix()` in `routes.mjs`), and every URL the page uses must be page-relative (`scripts/test-web-console-relative-urls.mjs`).
|
||||
- On Windows, treat a console the agent opened as dying with the agent: the app ends the agent's whole Job Object, so a `detached` server goes too, with no `exit` event. A `console.mjs post` still succeeds because it writes the session's files, so it proves nothing about the server; only the window's reconnect brings the page back. Every loop phase ends this way, and a reconnect budget that never refilled once lost the loop's stop card after Phase 3.
|
||||
@@ -4,6 +4,23 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
<!-- Format from 3.1.0 on: `## vX.Y.Z (YYYY-MM-DD)` with the date from version.json; a minor release opens with a three-bullet `### Highlights`; sections run Added, Changed, Fixed; game changes sit under one Activities line; tooling and test lines go under "For contributors". Older headings have no date and are not backfilled. -->
|
||||
|
||||
## v3.2.7 (2026-12-05)
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **Desktop app**: on macOS the dashboard now shows in the app's window. Before, WebKit gave that part of the window no sign-in cookie, so every request was refused.
|
||||
- **Desktop app**: on macOS and Linux, quitting now stops the running agent together with what it started, and the dashboards it opened, however you quit: the close button, the menu, the Dock, Ctrl+C, a closed terminal or a plain `kill`. An agent that ends by itself still leaves a dev server it was asked to keep running.
|
||||
- **Desktop app**: on macOS, Cmd+Q and the menu's Quit ask first while an agent is running, as the close button does, and one click answers the question even when the window was in the background.
|
||||
- **Desktop app**: on macOS and Linux, starting from the Dock, Finder or a desktop entry now finds Node and agents set up only in your shell's interactive config, such as nvm in `~/.zshrc`. A slow or hung shell profile holds up the start by about 5 seconds at most; before, there was no limit.
|
||||
- **Desktop app**: on macOS, Ctrl+V in the terminal reaches the agent, so Claude Code can take a pasted picture, and Cmd+V pastes without a Paste menu first.
|
||||
- **Desktop app**: on macOS, the Dock shows Planny's icon while the app runs, and the window opens in front of the terminal that started it.
|
||||
- **Desktop app**: after Change project, "The console stopped" no longer covers the new project, and Stop now in either loop no longer holds up the window while the agent ends.
|
||||
- **Web console and launcher**: on macOS, a folder picker that fails no longer acts like Cancel: Workspace says Browse is not available, and `plan2code` asks you to type the folder. On every system, Browse opens at the nearest folder still there when the last one is gone.
|
||||
- **Web console**: the Card width choices in User Preferences no longer run into each other at the Narrow width, and the page's closing signal is no longer refused in Safari and the macOS app.
|
||||
- **Quick Task**: the See it running card, shown after a build, no longer says that nothing has been changed yet.
|
||||
- **For contributors**: every URL the console page uses must be page-relative (`fetch("state")`, never `fetch("/state")`), because one that starts with a slash fails in the macOS app and nowhere else. `scripts/test-web-console-relative-urls.mjs` names any that does.
|
||||
- **For contributors**: on macOS, the `app` workflow now fails when the dashboard never connects inside the app (manual runs and pull requests labeled `full-matrix`), and the release checklist covers the macOS fixes above.
|
||||
|
||||
## v3.2.6 (2026-12-04)
|
||||
|
||||
### ✨ Added
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
Plan2Code is a spec-driven workflow for AI coding agents. You work through it on a page in your browser: the dashboard lists every step as a card, and each step's questions, progress and sign-offs arrive on that same page while your agent does the work. An approved plan becomes phase documents, and the agent builds to them one phase at a time.
|
||||
|
||||
Version 3.2.6 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 3.2.7 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "3.2.6",
|
||||
"version": "3.2.7",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
@@ -18,7 +18,7 @@
|
||||
"pretest": "node scripts/fix-line-endings.mjs",
|
||||
"test:fast": "node scripts/test-fast.mjs",
|
||||
"test:page": "node scripts/run-page-tests.mjs",
|
||||
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs",
|
||||
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-app-smoke-agent.mjs scripts/test-app-smoke-frame.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-frame.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-relative-urls.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs",
|
||||
"test:games": "node scripts/node-test.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-page-activities.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Generated
+5
-2
@@ -957,7 +957,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fake-agent"
|
||||
version = "3.2.6"
|
||||
version = "3.2.7"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"terminal_size",
|
||||
@@ -2647,10 +2647,13 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "plan2code-app"
|
||||
version = "3.2.6"
|
||||
version = "3.2.7"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"libc",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-foundation",
|
||||
"portable-pty",
|
||||
"reqwest",
|
||||
"serde",
|
||||
|
||||
@@ -33,6 +33,7 @@ There is no dot while busy or once a finished step has nothing left to press; a
|
||||
| `src-tauri/` | The Rust app |
|
||||
| `ui/` | The app page (plain HTML, CSS and JavaScript, no framework) |
|
||||
| `fake-agent/` | A stand-in agent program the tests run in a real pseudo-terminal |
|
||||
| `scripts/` | `vendor.mjs` (copies the xterm files into `ui/vendor/`), and CI's macOS frame check: `smoke-agent.mjs`, a stand-in agent that opens a real console, and `smoke-frame.mjs`, which waits for the console's `/health` to count the app's frame |
|
||||
| `package.json` | The app's own npm packages (xterm, the Tauri CLI). Separate from the repo root so the root and the console stay dependency-free |
|
||||
|
||||
## Build and run
|
||||
|
||||
@@ -37,11 +37,26 @@ file directly after checking it against the release's checksum list.
|
||||
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
||||
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
||||
- [ ] The desktop shortcut opens the folder menu (Choose a folder first, recent folders under it) and then the app
|
||||
- [ ] macOS: started from the desktop shortcut or `plan2code` in Terminal, the app's window opens in
|
||||
front of Terminal, as the active app
|
||||
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
|
||||
Security) lets it through, and `docs/desktop-app.md` describes what you saw
|
||||
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
|
||||
a machine where Node is only on PATH through nvm, Homebrew or Volta: the first-run checklist
|
||||
still finds Node and the installed CLIs, and the console and an agent still start
|
||||
- [ ] macOS: the same from Finder with Node set up by nvm in `~/.zshrc` only (not `~/.zprofile`):
|
||||
Node and the agent are still found. With Node and an agent on the login PATH instead
|
||||
(Homebrew, or nvm in `~/.zprofile`), `~/.zshrc` is not read at start, only on Check again;
|
||||
with Homebrew's Node there but the agent installed by npm under nvm in `~/.zshrc`, the agent
|
||||
is still found at start. A hung `~/.zprofile`
|
||||
delays the start by 3 s at most and a hung `~/.zshrc` by 2 s; only a slow `~/.zprofile`
|
||||
followed by a hung `~/.zshrc` reaches 5 s
|
||||
- [ ] macOS and Linux: when the installer puts the `plan2code` command in a folder that is not on
|
||||
PATH, its closing steps say so and name the line to add and the startup file to add it to;
|
||||
done as written, `plan2code` runs in a new terminal
|
||||
- [ ] macOS: canceling the folder picker (the `plan2code` launcher's, or Workspace's add folder)
|
||||
reads as a cancel; a picker that fails instead (an `osascript` error other than -128) shows
|
||||
an error in the console, and makes the launcher ask for the folder path to be typed
|
||||
- [ ] Windows: SmartScreen's **More info**, then **Run anyway**, lets it through, and
|
||||
`docs/desktop-app.md` describes what you saw
|
||||
- [ ] `plan2code update` updates the skills, the command and the app, including while the app is
|
||||
@@ -55,6 +70,8 @@ file directly after checking it against the release's checksum list.
|
||||
## The window (each system)
|
||||
|
||||
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
|
||||
- [ ] macOS: the frame signs in by itself (WebKit gives it no cookie, so the console moves it under
|
||||
its own `/f/<key>/` path on `127.0.0.1`); a blank frame or a sign-in page in it is a failure
|
||||
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
|
||||
- [ ] The bar shows the project folder; the permission note appears only while an agent started
|
||||
with checks off is running, never otherwise
|
||||
@@ -112,7 +129,9 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
- [ ] Pasting several lines
|
||||
- [ ] A line with Unicode and emoji
|
||||
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
|
||||
(macOS) copies the selection too; Ctrl+V / Cmd+V pastes
|
||||
(macOS) copies the selection too; Ctrl+V (Windows, Linux) or Cmd+V (macOS) pastes
|
||||
- [ ] macOS: Cmd+V pastes the text once, at once, with no **Paste** menu popping up first
|
||||
- [ ] macOS: Ctrl+V reaches the agent instead of pasting (Claude Code pastes a copied image with it)
|
||||
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
|
||||
just left of it
|
||||
|
||||
@@ -121,10 +140,22 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
- [ ] Start, then **New Session**: it confirms once, with Planny on a coffee break and no claim about unsaved
|
||||
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
|
||||
dashboard shows the pick-up chip with a brief that matches the session
|
||||
- [ ] macOS and Linux: once New Session's dashboard shows, `ps -Ao pid,command | grep server.mjs` lists
|
||||
the new console only; the old one stopped when the window moved on from it
|
||||
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
|
||||
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
|
||||
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
|
||||
- [ ] Cmd+Q on macOS asks the same
|
||||
- [ ] macOS: Cmd+Q and the app menu's Quit ask the same while an agent works, in the window; Quit
|
||||
from the Dock's menu quits at once with no question, and its cleanup still runs
|
||||
- [ ] macOS: with another app in front, the window's close button asks in front of it, and one
|
||||
click on Quit quits; Cmd+Q with the window minimized brings the window back with the question
|
||||
- [ ] macOS and Linux: after each way of quitting (Cmd+Q, the app menu's Quit, closing the window,
|
||||
a plain `kill` of the app, Ctrl+C or closing the terminal when the app's program was run from
|
||||
one, and on macOS Quit from the Dock), with an agent running, nothing is left:
|
||||
`ps -Ao pid,pgid,command | grep -E 'plan2code-app|server.mjs'` shows no app, no agent or
|
||||
process of its group, and no console the agent opened. After an agent that ended by itself,
|
||||
the same shows no app and no console it opened, while a process it left running in its
|
||||
group on purpose (a backgrounded dev server) is still there
|
||||
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
|
||||
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "fake-agent"
|
||||
version = "3.2.6"
|
||||
version = "3.2.7"
|
||||
description = "A stand-in agent program for the Plan2Code app's tests"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
//! leaves the folder)
|
||||
//! ENV <name> print the variable as `ENV <name>=<value>`
|
||||
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
||||
//! STRAY (macOS and Linux) start a child that ignores hangup and is never
|
||||
//! waited for, and print its process id as `STRAY <n>`; elsewhere
|
||||
//! say `STRAY unavailable`
|
||||
//! <other> echoed back as `echo: <line>`
|
||||
//!
|
||||
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
|
||||
@@ -56,6 +59,8 @@ pub enum Command {
|
||||
File(String, String),
|
||||
/// `HANG`: go silent, to model an agent that stops answering.
|
||||
Hang,
|
||||
/// `STRAY`: leave a hangup-ignoring child behind in the agent's process group.
|
||||
Stray,
|
||||
Echo(String),
|
||||
}
|
||||
|
||||
@@ -134,6 +139,24 @@ fn update_state(
|
||||
std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok()
|
||||
}
|
||||
|
||||
/// A child that ignores hangup, in this process's group, never waited for.
|
||||
#[cfg(unix)]
|
||||
fn start_stray() -> Option<u32> {
|
||||
std::process::Command::new("/bin/sh")
|
||||
.args(["-c", "trap '' HUP; exec sleep 300"])
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.ok()
|
||||
.map(|child| child.id())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn start_stray() -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn parse(line: &str) -> Command {
|
||||
let line = line.trim();
|
||||
if let Some(rest) = line.strip_prefix("STEP ") {
|
||||
@@ -176,6 +199,9 @@ pub fn parse(line: &str) -> Command {
|
||||
if line == "HANG" {
|
||||
return Command::Hang;
|
||||
}
|
||||
if line == "STRAY" {
|
||||
return Command::Stray;
|
||||
}
|
||||
Command::Echo(line.to_string())
|
||||
}
|
||||
|
||||
@@ -274,6 +300,10 @@ fn main() {
|
||||
thread::sleep(Duration::from_secs(3600));
|
||||
}
|
||||
}
|
||||
Command::Stray => match start_stray() {
|
||||
Some(pid) => say(&format!("STRAY {pid}")),
|
||||
None => say("STRAY unavailable"),
|
||||
},
|
||||
Command::Echo(text) => say(&format!("echo: {text}")),
|
||||
}
|
||||
}
|
||||
@@ -303,6 +333,7 @@ mod tests {
|
||||
Command::Report("{\"phase\":2}".into())
|
||||
);
|
||||
assert_eq!(parse("HANG\r\n"), Command::Hang);
|
||||
assert_eq!(parse("STRAY"), Command::Stray);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.2.6",
|
||||
"version": "3.2.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "plan2code-app",
|
||||
"version": "3.2.6",
|
||||
"version": "3.2.7",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.2.6",
|
||||
"version": "3.2.7",
|
||||
"private": true,
|
||||
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
|
||||
"scripts": {
|
||||
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env node
|
||||
// A stand-in agent for CI's smoke run of the built app (.github/workflows/app.yml).
|
||||
// Point PLAN2CODE_APP_AGENT_BIN at this file. Like a real agent, it opens a web
|
||||
// console dashboard, with the environment the app gave it, so the console
|
||||
// announces itself to the window and the dashboard frame has something to
|
||||
// connect to (smoke-frame.mjs then checks it did). The repo's fake-agent opens
|
||||
// no console, so it cannot stand in for this.
|
||||
//
|
||||
// It needs PLAN2CODE_CONSOLE_DIR (the folder holding console.mjs), ignores the
|
||||
// arguments the app passes a real agent, and then waits on its input until it
|
||||
// closes. It starts nothing else: the console server is detached, and the
|
||||
// smoke run stops it with `console.mjs stop --all`.
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const consoleDir = process.env.PLAN2CODE_CONSOLE_DIR;
|
||||
if (!consoleDir) {
|
||||
console.error('smoke-agent: PLAN2CODE_CONSOLE_DIR is not set; it names the folder holding console.mjs');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const open = spawnSync(process.execPath, [join(consoleDir, 'console.mjs'), 'open', '--workflow', 'dashboard'], {
|
||||
stdio: ['ignore', 'inherit', 'inherit'],
|
||||
});
|
||||
if (open.error || open.status !== 0) {
|
||||
console.error(`smoke-agent: console.mjs open failed (${open.error ? open.error.message : `exit ${open.status}`})`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('smoke-agent: dashboard open; waiting on input');
|
||||
process.stdin.resume();
|
||||
process.stdin.on('end', () => process.exit(0));
|
||||
@@ -0,0 +1,100 @@
|
||||
// Checks the app's dashboard frame connected to its console, for CI's macOS smoke
|
||||
// run (.github/workflows/app.yml). A window that comes up but never signs its
|
||||
// frame in looks alive to a process check; the console's own browser count
|
||||
// does not lie.
|
||||
//
|
||||
// node smoke-frame.mjs [<console home>] [--timeout-ms N]
|
||||
//
|
||||
// The console home defaults to PLAN2CODE_CONSOLE_HOME. Waits for a session
|
||||
// handle there (runtime/<project hash>/<sid>.json), then polls that session's
|
||||
// open GET /health until it counts a browser. Exit 0 once one connects; exit 1
|
||||
// when the time (60 s by default, for both waits together) runs out, with the
|
||||
// last answer printed; exit 2 for a usage error.
|
||||
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parseArgs } from 'node:util';
|
||||
|
||||
const POLL_MS = 500;
|
||||
const REQUEST_MS = 2000;
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseArgs({ allowPositionals: true, options: { 'timeout-ms': { type: 'string' } } });
|
||||
} catch (err) {
|
||||
usage(err.message);
|
||||
}
|
||||
const home = parsed.positionals[0] || process.env.PLAN2CODE_CONSOLE_HOME;
|
||||
if (!home) usage('no console home: pass one, or set PLAN2CODE_CONSOLE_HOME');
|
||||
const timeoutMs = Number(parsed.values['timeout-ms'] ?? 60000);
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) usage('--timeout-ms takes a positive number');
|
||||
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let last = null;
|
||||
while (Date.now() < deadline) {
|
||||
// Read again each round: a reconnect can resume the session on a new port.
|
||||
const handle = newestHandle(home);
|
||||
if (handle) {
|
||||
last = await health(handle);
|
||||
if (last.body && last.body.sid === handle.sid && last.body.browsers >= 1) {
|
||||
console.log(`smoke-frame: the dashboard frame connected (browsers ${last.body.browsers}, port ${handle.port})`);
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
||||
}
|
||||
if (!last) {
|
||||
console.error(`smoke-frame: no session appeared under ${home} within ${timeoutMs} ms`);
|
||||
} else {
|
||||
console.error(`smoke-frame: no browser connected within ${timeoutMs} ms; last /health answer from port ${last.port}: ${last.text}`);
|
||||
}
|
||||
process.exit(1);
|
||||
|
||||
function usage(message) {
|
||||
console.error(`smoke-frame: ${message}\nusage: node smoke-frame.mjs [<console home>] [--timeout-ms N]`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// The most recently written session handle under the home, or null.
|
||||
function newestHandle(consoleHome) {
|
||||
const runtime = join(consoleHome, 'runtime');
|
||||
let newest = null;
|
||||
for (const hash of safeList(runtime)) {
|
||||
for (const name of safeList(join(runtime, hash))) {
|
||||
if (!name.endsWith('.json')) continue;
|
||||
const file = join(runtime, hash, name);
|
||||
try {
|
||||
const handle = JSON.parse(readFileSync(file, 'utf8'));
|
||||
const mtime = statSync(file).mtimeMs;
|
||||
if (Number.isInteger(handle.port) && handle.sid && (!newest || mtime > newest.mtime)) newest = { ...handle, mtime };
|
||||
} catch {
|
||||
// Half written or removed between the listing and the read: the next round sees it whole.
|
||||
}
|
||||
}
|
||||
}
|
||||
return newest;
|
||||
}
|
||||
|
||||
function safeList(dir) {
|
||||
try {
|
||||
return readdirSync(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// One /health answer: the raw text for the failure message, and the body when it parsed.
|
||||
async function health(handle) {
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${handle.port}/health`, { signal: AbortSignal.timeout(REQUEST_MS) });
|
||||
const text = await res.text();
|
||||
let body = null;
|
||||
try {
|
||||
body = JSON.parse(text);
|
||||
} catch {
|
||||
// Not JSON: kept as text for the message.
|
||||
}
|
||||
return { port: handle.port, text: `${res.status} ${text}`, body };
|
||||
} catch (err) {
|
||||
return { port: handle.port, text: `no answer (${err.message})`, body: null };
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "plan2code-app"
|
||||
version = "3.2.6"
|
||||
version = "3.2.7"
|
||||
description = "Plan2Code desktop app"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
@@ -28,6 +28,13 @@ reqwest = { version = "0.13", default-features = false, features = ["blocking",
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Already pulled in by tauri itself; named directly here only to set the Dock
|
||||
# icon (`set_app_icon` in main.rs), which tauri does for dev builds alone.
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSImage", "NSResponder"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSData", "NSGeometry"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# Already pulled in by portable-pty itself; named directly here only for the
|
||||
# Job Object APIs it does not expose (ending a `cmd /c` npm shim's whole
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::thread;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
|
||||
use crate::log;
|
||||
use crate::pty_host::{PtyHost, StartOptions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
@@ -35,6 +36,12 @@ pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
|
||||
/// the manager.
|
||||
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// Runs once for each agent that ends, however it ends: by itself, by a stop,
|
||||
/// or replaced by Restart or a loop phase's fresh start. It can run with the
|
||||
/// manager's state locked, so it must return quickly and must not call back
|
||||
/// into the manager.
|
||||
pub type Ended = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// What the page needs to draw the bar. `generation` counts the agents started
|
||||
/// so far: a new number means a fresh agent, so the terminal clears.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -116,12 +123,17 @@ struct Shared {
|
||||
sink: Sink,
|
||||
before_fresh: Mutex<Option<BeforeFresh>>,
|
||||
forget_session: Mutex<Option<ForgetSession>>,
|
||||
ended: Mutex<Option<Ended>>,
|
||||
/// Environment every agent this manager starts gets, on top of its own:
|
||||
/// the in-app signal that sends the agent's console pages to this window.
|
||||
extra_env: Mutex<Vec<(String, String)>>,
|
||||
/// Bumped for every agent started. Output and exits from an older agent
|
||||
/// compare against it and are dropped.
|
||||
generation: AtomicU64,
|
||||
/// The threads that wait for each agent's end and finish the process group
|
||||
/// of one the app replaced, so a stop can wait for them.
|
||||
#[cfg(unix)]
|
||||
ends: Mutex<Vec<thread::JoinHandle<()>>>,
|
||||
inner: Mutex<Inner>,
|
||||
}
|
||||
|
||||
@@ -144,8 +156,11 @@ impl AgentManager {
|
||||
sink,
|
||||
before_fresh: Mutex::new(None),
|
||||
forget_session: Mutex::new(None),
|
||||
ended: Mutex::new(None),
|
||||
extra_env: Mutex::new(Vec::new()),
|
||||
generation: AtomicU64::new(0),
|
||||
#[cfg(unix)]
|
||||
ends: Mutex::new(Vec::new()),
|
||||
inner: Mutex::new(Inner {
|
||||
state: AgentState::Idle,
|
||||
running: None,
|
||||
@@ -177,6 +192,13 @@ impl AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `hook` once for every agent that ends (see `Ended`).
|
||||
pub fn set_ended(&self, hook: Ended) {
|
||||
if let Ok(mut slot) = self.shared.ended.lock() {
|
||||
*slot = Some(hook);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the app forget the console session it follows, so the next agent's
|
||||
/// `open` starts a new one.
|
||||
pub fn forget_session(&self) {
|
||||
@@ -366,6 +388,7 @@ impl AgentManager {
|
||||
self.shared.generation.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(old) = inner.running.take() {
|
||||
let _ = old.host.kill();
|
||||
self.shared.ended();
|
||||
}
|
||||
}
|
||||
match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
|
||||
@@ -455,7 +478,9 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
/// End the agent for good (quitting). Nothing starts afterwards, and the
|
||||
/// agent's process is gone when this returns.
|
||||
/// agent's process, with what is left of its process group on macOS and
|
||||
/// Linux, is gone when this returns. So is the group of an agent replaced
|
||||
/// a moment before, whose grace may still be running.
|
||||
pub fn stop(&self) {
|
||||
let host = {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
@@ -470,7 +495,12 @@ impl AgentManager {
|
||||
if let Some(host) = host {
|
||||
let _ = host.kill();
|
||||
let _ = host.wait();
|
||||
// The app may exit right after, before `kill`'s own grace runs out.
|
||||
host.end_group();
|
||||
self.shared.ended();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
self.shared.finish_ends();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,6 +543,42 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// An agent ended: run the `ended` hook, if one is set.
|
||||
fn ended(&self) {
|
||||
let hook = self.ended.lock().ok().and_then(|slot| slot.clone());
|
||||
if let Some(run) = hook {
|
||||
run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep an agent's end thread, so `finish_ends` can wait for it; threads
|
||||
/// already done are let go.
|
||||
#[cfg(unix)]
|
||||
fn keep_end(&self, end: thread::JoinHandle<()>) {
|
||||
let mut ends = self
|
||||
.ends
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
ends.retain(|kept| !kept.is_finished());
|
||||
ends.push(end);
|
||||
}
|
||||
|
||||
/// Wait until every agent started here has ended and the process group of
|
||||
/// each one the app stopped or replaced is gone: the app may exit straight
|
||||
/// after, which would cut a replaced agent's grace short.
|
||||
#[cfg(unix)]
|
||||
fn finish_ends(&self) {
|
||||
let ends = std::mem::take(
|
||||
&mut *self
|
||||
.ends
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner()),
|
||||
);
|
||||
for end in ends {
|
||||
let _ = end.join();
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(&self, inner: &Inner) {
|
||||
(self.sink)(AgentEvent::State(self.snapshot(inner)));
|
||||
}
|
||||
@@ -602,14 +668,25 @@ impl Shared {
|
||||
self.emit(inner);
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
thread::spawn(move || {
|
||||
let end = thread::spawn(move || {
|
||||
let reason = match host.wait_described() {
|
||||
Ok((_, Some(signal))) => format!("was ended by a signal ({signal})"),
|
||||
Ok((_, Some(signal))) => format!("{SIGNAL_REASON} ({signal})"),
|
||||
Ok((code, None)) => format!("exited with code {code}"),
|
||||
Err(e) => format!("stopped: {e}"),
|
||||
};
|
||||
shared.on_exit(generation, reason);
|
||||
// Only an agent the app stopped or replaced takes its process
|
||||
// group with it: after a Restart or New Session this finishes
|
||||
// what `kill`'s grace thread started (after a stop it finds the
|
||||
// group gone). An agent that ended by itself leaves its group
|
||||
// alone, so work the person asked it to leave running survives.
|
||||
if !shared.on_exit(generation, reason) {
|
||||
host.end_group();
|
||||
}
|
||||
});
|
||||
#[cfg(unix)]
|
||||
self.keep_end(end);
|
||||
#[cfg(not(unix))]
|
||||
drop(end);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -620,6 +697,7 @@ impl Shared {
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(old) = inner.running.take() {
|
||||
let _ = old.host.kill();
|
||||
self.ended();
|
||||
}
|
||||
let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone());
|
||||
inner.brief_note = hook.and_then(|run| run());
|
||||
@@ -644,19 +722,42 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// The agent's process ended. Stale if a newer agent has replaced it.
|
||||
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) {
|
||||
/// The agent's process ended. Stale if a newer agent has replaced it, or
|
||||
/// the app stopped it. True when it ended by itself (not stale).
|
||||
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) -> bool {
|
||||
let mut inner = lock(&self.inner);
|
||||
if self.generation.load(Ordering::SeqCst) != generation {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
inner.running = None;
|
||||
// Ended on its own: say why and start nothing.
|
||||
// Ended on its own: say why and start nothing. A signal nobody here
|
||||
// sent (stop and Restart move the generation on first) also goes to
|
||||
// the log, since the bar's reason is gone once a new agent starts.
|
||||
if let Some((choice, _)) = &inner.last_start {
|
||||
if let Some(line) = exit_log_line(choice.kind.id(), &reason) {
|
||||
log::line(&line);
|
||||
}
|
||||
}
|
||||
inner.state = AgentState::Ended { reason };
|
||||
self.emit(&inner);
|
||||
// Still locked: no fresh agent can start, and announce, before the
|
||||
// hook has taken what this one left.
|
||||
self.ended();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// How the bar's reason starts for an agent a signal ended.
|
||||
const SIGNAL_REASON: &str = "was ended by a signal";
|
||||
|
||||
/// The log line for an agent's end, from its id and the bar's reason: only
|
||||
/// an end by a signal gets one, since an exit code is the agent's own word.
|
||||
fn exit_log_line(agent: &str, reason: &str) -> Option<String> {
|
||||
reason
|
||||
.starts_with(SIGNAL_REASON)
|
||||
.then(|| format!("plan2code: the agent {agent} {reason}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replay_tests {
|
||||
use super::*;
|
||||
@@ -684,3 +785,24 @@ mod replay_tests {
|
||||
assert_eq!(replay, b"6789");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod exit_log_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_signal_gives_a_line_naming_the_agent_and_the_signal() {
|
||||
let reason = format!("{SIGNAL_REASON} (Killed: 9)");
|
||||
let line = exit_log_line("claude", &reason).expect("a signal is logged");
|
||||
assert!(line.contains("claude"), "{line}");
|
||||
assert!(line.contains("Killed: 9"), "{line}");
|
||||
assert!(line.starts_with("plan2code: "), "{line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exit_code_or_a_failed_wait_gives_no_line() {
|
||||
assert_eq!(exit_log_line("claude", "exited with code 0"), None);
|
||||
assert_eq!(exit_log_line("claude", "exited with code 1"), None);
|
||||
assert_eq!(exit_log_line("claude", "stopped: wait failed"), None);
|
||||
}
|
||||
}
|
||||
@@ -1150,6 +1150,34 @@ pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The command of every built-in and custom agent that the lookup searches
|
||||
/// PATH for by name, each once, in list order. A command with a folder in it
|
||||
/// runs from there, whatever PATH holds, so it is left out. The PATH lookup at
|
||||
/// start (`node_check::login_shell_path`) reads the shell's interactive config
|
||||
/// when none of these is on the login PATH.
|
||||
#[cfg(unix)]
|
||||
pub fn path_agent_commands() -> Vec<String> {
|
||||
let (custom, _) = custom_agents();
|
||||
path_commands(
|
||||
builtin_entries()
|
||||
.iter()
|
||||
.map(|entry| entry.command.as_str())
|
||||
.chain(custom.iter().map(|agent| agent.command.as_str())),
|
||||
)
|
||||
}
|
||||
|
||||
/// `path_agent_commands` over the given commands.
|
||||
#[cfg(unix)]
|
||||
fn path_commands<'a>(commands: impl Iterator<Item = &'a str>) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
commands
|
||||
.map(clean_command)
|
||||
.filter(|command| !command.is_empty() && !has_separator(command, false))
|
||||
.filter(|command| seen.insert(*command))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn clean_command(command: &str) -> &str {
|
||||
let command = command.trim();
|
||||
command
|
||||
@@ -1656,6 +1684,31 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_path_agent_commands_are_the_bare_names_each_once() {
|
||||
// The baked built-ins, then a custom list with a repeat, a quoted
|
||||
// name, a command with a folder in it and an empty one.
|
||||
let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
|
||||
let custom = [
|
||||
"codex",
|
||||
"\"opencode\"",
|
||||
"/opt/tools/bin/gemini",
|
||||
"./agent",
|
||||
" ",
|
||||
];
|
||||
assert_eq!(
|
||||
path_commands(
|
||||
builtins
|
||||
.builtins
|
||||
.iter()
|
||||
.map(|entry| entry.command.as_str())
|
||||
.chain(custom)
|
||||
),
|
||||
["claude", "devin", "codex", "opencode"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_baked_list_matches_the_shipped_agents_json() {
|
||||
// include_str! means the baked copy IS src/launcher/agents.json; this
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::io::{Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Serialize;
|
||||
@@ -119,6 +120,13 @@ fn node_command(console_dir: &Path) -> Command {
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
// Ctrl+C and a closing terminal signal the app's whole process group: a stop running there
|
||||
// would end before it stopped its console.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
}
|
||||
command
|
||||
}
|
||||
|
||||
@@ -403,22 +411,237 @@ impl ConsoleSupervisor {
|
||||
if self.stopped {
|
||||
return Ok(());
|
||||
}
|
||||
let output = node_command(&self.console_dir)
|
||||
.args(stop_args(&self.session.sid))
|
||||
.current_dir(&self.project_dir)
|
||||
.output()
|
||||
.map_err(err)?;
|
||||
self.stopped = true;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"console stop failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
let result = run_stop(&self.console_dir, &self.project_dir, &self.session.sid);
|
||||
// Only a stop that could not run at all leaves the flag clear, as before.
|
||||
if !matches!(result, Err(StopError::NotRun(_))) {
|
||||
self.stopped = true;
|
||||
}
|
||||
Ok(())
|
||||
result.map_err(StopError::into_message)
|
||||
}
|
||||
}
|
||||
|
||||
/// `console.mjs stop --session <sid> --force` for any session, run in the
|
||||
/// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console
|
||||
/// this app does not supervise (one an agent announced and the window has
|
||||
/// since moved on from).
|
||||
pub fn stop_console_session(
|
||||
console_dir: &Path,
|
||||
project_dir: &Path,
|
||||
sid: &str,
|
||||
) -> Result<(), String> {
|
||||
run_stop(console_dir, project_dir, sid).map_err(StopError::into_message)
|
||||
}
|
||||
|
||||
/// One console an agent announced. `left` once that agent has ended while the
|
||||
/// window still showed the console: nothing needs it after the window moves on.
|
||||
struct Announced {
|
||||
sid: String,
|
||||
left: bool,
|
||||
}
|
||||
|
||||
/// The console sessions this app's agents announced on macOS and Linux, by
|
||||
/// sid, in the order they came: the ones to stop when the agent that opened
|
||||
/// them ends, when the window moves on from one an ended agent left, or when
|
||||
/// the app quits. Consoles the app started itself are never recorded here, and
|
||||
/// one the app stopped for good is forgotten; the bar's stop, which keeps the
|
||||
/// session to start it again, leaves it recorded. Also holds the threads still
|
||||
/// stopping consoles after an agent's end or a new page, so a quit can wait for
|
||||
/// them.
|
||||
#[derive(Default)]
|
||||
pub struct AnnouncedConsoles {
|
||||
consoles: Mutex<Vec<Announced>>,
|
||||
stops: Mutex<Vec<std::thread::JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
impl AnnouncedConsoles {
|
||||
fn lock(&self) -> MutexGuard<'_, Vec<Announced>> {
|
||||
self.consoles
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
/// Remember `sid`, announced by a running agent; one already recorded is
|
||||
/// kept once, and is no longer left: the new agent joined it.
|
||||
pub fn record(&self, sid: &str) {
|
||||
let mut consoles = self.lock();
|
||||
match consoles.iter_mut().find(|known| known.sid == sid) {
|
||||
Some(known) => known.left = false,
|
||||
None => consoles.push(Announced {
|
||||
sid: sid.to_string(),
|
||||
left: false,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember `sid` as left by an agent that has ended; one a new agent
|
||||
/// announced in the meantime stays that agent's.
|
||||
fn leave(&self, sid: &str) {
|
||||
let mut consoles = self.lock();
|
||||
if !consoles.iter().any(|known| known.sid == sid) {
|
||||
consoles.push(Announced {
|
||||
sid: sid.to_string(),
|
||||
left: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop `sid` from the record: the app stopped that console itself.
|
||||
pub fn forget(&self, sid: &str) {
|
||||
self.lock().retain(|known| known.sid != sid);
|
||||
}
|
||||
|
||||
/// Every recorded sid, in record order, and an empty record after.
|
||||
pub fn take_all(&self) -> Vec<String> {
|
||||
std::mem::take(&mut *self.lock())
|
||||
.into_iter()
|
||||
.map(|known| known.sid)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every console left by an agent that has ended, but for the one the
|
||||
/// window follows, no longer recorded after.
|
||||
fn take_left(&self, followed: Option<&str>) -> Vec<String> {
|
||||
let mut consoles = self.lock();
|
||||
let (left, kept) = std::mem::take(&mut *consoles)
|
||||
.into_iter()
|
||||
.partition(|known| known.left && followed != Some(known.sid.as_str()));
|
||||
*consoles = kept;
|
||||
left.into_iter().map(|known| known.sid).collect()
|
||||
}
|
||||
|
||||
/// The window follows `followed` now: stop each console an agent that has
|
||||
/// ended left under it, with `stop` on a thread of its own, since a stop
|
||||
/// runs `node`. A console of an agent still running is never touched.
|
||||
pub fn stop_left<F>(&self, followed: &str, stop: F)
|
||||
where
|
||||
F: Fn(&str) + Send + 'static,
|
||||
{
|
||||
let sids = self.take_left(Some(followed));
|
||||
if sids.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.keep_stop(std::thread::spawn(move || {
|
||||
for sid in sids {
|
||||
stop(&sid);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/// Keep a thread that is stopping consoles, so `finish_stops` can wait
|
||||
/// for it; threads already done are let go.
|
||||
fn keep_stop(&self, stop: std::thread::JoinHandle<()>) {
|
||||
let mut stops = self
|
||||
.stops
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
stops.retain(|kept| !kept.is_finished());
|
||||
stops.push(stop);
|
||||
}
|
||||
|
||||
/// Wait for every console stop still running on a thread, after an agent's
|
||||
/// end or a new page: the app may exit straight after, which would cut it
|
||||
/// short.
|
||||
pub fn finish_stops(&self) {
|
||||
let stops = std::mem::take(
|
||||
&mut *self
|
||||
.stops
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner()),
|
||||
);
|
||||
for stop in stops {
|
||||
let _ = stop.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`):
|
||||
/// it takes every console `announced` holds at once, inside the hook, so a
|
||||
/// console the next agent announces later is never taken by mistake, then
|
||||
/// stops each with `stop` on a thread of its own, since a stop runs `node` and
|
||||
/// the hook must return quickly. The console the window follows (`followed`)
|
||||
/// is left to the supervisor and recorded again, as left: stopped under the
|
||||
/// window, the bar's health poll would only start it again as a server no one
|
||||
/// tracks. It is stopped once the window moves on (`stop_left`), here if that
|
||||
/// happened while this thread was deciding, or at the quit. `followed` is asked
|
||||
/// on that thread too: it takes the console lock, held across `node` runs,
|
||||
/// while the hook runs with the agent manager locked. A caller about to stop
|
||||
/// the followed console waits for the thread first (`finish_stops`), so it is
|
||||
/// never recorded again after that stop.
|
||||
/// The macOS and Linux stand-in for Windows' Job Object, which ends every
|
||||
/// console an agent opened along with it.
|
||||
pub fn stop_announced_on_end<K, F>(
|
||||
announced: Arc<AnnouncedConsoles>,
|
||||
followed: K,
|
||||
stop: F,
|
||||
) -> Arc<dyn Fn() + Send + Sync>
|
||||
where
|
||||
K: Fn() -> Option<String> + Send + Sync + 'static,
|
||||
F: Fn(&str) + Send + Sync + 'static,
|
||||
{
|
||||
let followed = Arc::new(followed);
|
||||
let stop = Arc::new(stop);
|
||||
Arc::new(move || {
|
||||
let sids = announced.take_all();
|
||||
if sids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (followed, stop, record) = (
|
||||
Arc::clone(&followed),
|
||||
Arc::clone(&stop),
|
||||
Arc::clone(&announced),
|
||||
);
|
||||
announced.keep_stop(std::thread::spawn(move || {
|
||||
let shown = followed();
|
||||
let mut left = false;
|
||||
for sid in sids {
|
||||
if shown.as_deref() == Some(sid.as_str()) {
|
||||
record.leave(&sid);
|
||||
left = true;
|
||||
} else {
|
||||
stop(&sid);
|
||||
}
|
||||
}
|
||||
if left {
|
||||
// A page that took the window since the question above found
|
||||
// nothing left to stop yet.
|
||||
for sid in record.take_left(followed().as_deref()) {
|
||||
stop(&sid);
|
||||
}
|
||||
}
|
||||
}));
|
||||
})
|
||||
}
|
||||
|
||||
/// Why a stop failed: it never ran (`node` could not be started), or it ran
|
||||
/// and the console said no.
|
||||
enum StopError {
|
||||
NotRun(String),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl StopError {
|
||||
fn into_message(self) -> String {
|
||||
match self {
|
||||
StopError::NotRun(message) | StopError::Failed(message) => message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_stop(console_dir: &Path, project_dir: &Path, sid: &str) -> Result<(), StopError> {
|
||||
let output = node_command(console_dir)
|
||||
.args(stop_args(sid))
|
||||
.current_dir(project_dir)
|
||||
.output()
|
||||
.map_err(|e| StopError::NotRun(err(e)))?;
|
||||
if !output.status.success() {
|
||||
return Err(StopError::Failed(format!(
|
||||
"console stop failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Is the session's folder still in the console's home. Unknown (no home
|
||||
/// directory) counts as there, so the answer never throws a session away. A
|
||||
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
|
||||
@@ -463,6 +686,241 @@ fn stop_args(sid: &str) -> [&str; 4] {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn announced_consoles_are_taken_once_in_order_without_duplicates() {
|
||||
let announced = AnnouncedConsoles::default();
|
||||
announced.record("s1");
|
||||
announced.record("s2");
|
||||
announced.record("s1");
|
||||
assert_eq!(announced.take_all(), vec!["s1", "s2"]);
|
||||
assert!(announced.take_all().is_empty(), "taking clears the record");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forget_drops_one_console_and_keeps_the_rest() {
|
||||
let announced = AnnouncedConsoles::default();
|
||||
announced.record("s1");
|
||||
announced.record("s2");
|
||||
announced.forget("s1");
|
||||
announced.forget("never-recorded");
|
||||
assert_eq!(announced.take_all(), vec!["s2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agents_end_asks_which_console_the_window_follows_off_its_own_thread() {
|
||||
// The hook runs with the agent manager locked, and the followed check
|
||||
// takes the console lock, which is held across `node` runs: asked
|
||||
// there, typing into the terminal stalled behind a console stop.
|
||||
let announced = Arc::new(AnnouncedConsoles::default());
|
||||
let asked_on = Arc::new(Mutex::new(Vec::new()));
|
||||
let log = Arc::clone(&asked_on);
|
||||
let hook = stop_announced_on_end(
|
||||
Arc::clone(&announced),
|
||||
move || {
|
||||
log.lock().unwrap().push(std::thread::current().id());
|
||||
None
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
announced.record("s1");
|
||||
|
||||
hook();
|
||||
announced.finish_stops();
|
||||
|
||||
let asked_on = asked_on.lock().unwrap();
|
||||
assert_eq!(asked_on.len(), 1, "asked once");
|
||||
assert_ne!(asked_on[0], std::thread::current().id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agents_end_leaves_the_console_the_window_follows_and_keeps_it_recorded() {
|
||||
// New Session ends the old agent while the window still shows its
|
||||
// console: stopping it there only had the bar's poll bring it back as
|
||||
// a server nobody tracked, which then outlived the quit.
|
||||
let announced = Arc::new(AnnouncedConsoles::default());
|
||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let log = Arc::clone(&stopped);
|
||||
let hook = stop_announced_on_end(
|
||||
Arc::clone(&announced),
|
||||
|| Some("followed".to_string()),
|
||||
move |sid| log.lock().unwrap().push(sid.to_string()),
|
||||
);
|
||||
announced.record("followed");
|
||||
announced.record("other");
|
||||
|
||||
hook();
|
||||
announced.finish_stops();
|
||||
|
||||
assert_eq!(*stopped.lock().unwrap(), vec!["other"]);
|
||||
assert_eq!(
|
||||
announced.take_all(),
|
||||
vec!["followed"],
|
||||
"kept for the quit, or until the window moves on"
|
||||
);
|
||||
}
|
||||
|
||||
/// An agent that ended while the window showed its console `sid`.
|
||||
fn left_under_the_window(sid: &'static str) -> Arc<AnnouncedConsoles> {
|
||||
let announced = Arc::new(AnnouncedConsoles::default());
|
||||
announced.record(sid);
|
||||
let hook = stop_announced_on_end(
|
||||
Arc::clone(&announced),
|
||||
move || Some(sid.to_string()),
|
||||
|sid| panic!("{sid} was stopped under the window"),
|
||||
);
|
||||
hook();
|
||||
announced.finish_stops();
|
||||
announced
|
||||
}
|
||||
|
||||
/// What `stop_left` stops once the window follows `followed`.
|
||||
fn stopped_by_moving_to(announced: &AnnouncedConsoles, followed: &str) -> Vec<String> {
|
||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let log = Arc::clone(&stopped);
|
||||
announced.stop_left(followed, move |sid| log.lock().unwrap().push(sid.into()));
|
||||
announced.finish_stops();
|
||||
let stopped = stopped.lock().unwrap().clone();
|
||||
stopped
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_moving_on_stops_the_console_an_ended_agent_left_once() {
|
||||
let announced = left_under_the_window("old");
|
||||
announced.record("new");
|
||||
assert!(stopped_by_moving_to(&announced, "old").is_empty(), "shown");
|
||||
assert_eq!(stopped_by_moving_to(&announced, "new"), vec!["old"]);
|
||||
assert!(stopped_by_moving_to(&announced, "new").is_empty(), "once");
|
||||
assert_eq!(announced.take_all(), vec!["new"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_moving_on_never_stops_a_running_agents_console() {
|
||||
// One agent may open a second session and still use the first.
|
||||
let announced = AnnouncedConsoles::default();
|
||||
announced.record("first");
|
||||
announced.record("second");
|
||||
assert!(stopped_by_moving_to(&announced, "second").is_empty());
|
||||
|
||||
// A new agent that joins the console an ended one left makes it its own.
|
||||
let announced = left_under_the_window("joined");
|
||||
announced.record("joined");
|
||||
announced.record("second");
|
||||
assert!(stopped_by_moving_to(&announced, "second").is_empty());
|
||||
assert_eq!(announced.take_all(), vec!["joined", "second"]);
|
||||
}
|
||||
|
||||
/// An agent's end whose console `old` the window shows, where `meanwhile`
|
||||
/// runs right after the hook asked which console that is: what it stopped.
|
||||
fn stopped_by_an_end_while<M>(meanwhile: M) -> (Vec<String>, Vec<String>)
|
||||
where
|
||||
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
|
||||
{
|
||||
let announced = Arc::new(AnnouncedConsoles::default());
|
||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let (log, record) = (Arc::clone(&stopped), Arc::clone(&announced));
|
||||
let shown = Mutex::new("old");
|
||||
let hook = stop_announced_on_end(
|
||||
Arc::clone(&announced),
|
||||
move || {
|
||||
let mut shown = shown.lock().unwrap();
|
||||
let answer = shown.to_string();
|
||||
if answer == "old" {
|
||||
*shown = meanwhile(&record);
|
||||
}
|
||||
Some(answer)
|
||||
},
|
||||
move |sid| log.lock().unwrap().push(sid.to_string()),
|
||||
);
|
||||
announced.record("old");
|
||||
hook();
|
||||
announced.finish_stops();
|
||||
let stopped = stopped.lock().unwrap().clone();
|
||||
(stopped, announced.take_all())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_that_takes_the_window_while_an_agents_end_decides_still_stops_the_old_console() {
|
||||
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
|
||||
announced.record("new");
|
||||
announced.stop_left("new", |sid| panic!("{sid} is not left yet"));
|
||||
"new"
|
||||
});
|
||||
assert_eq!(stopped, vec!["old"]);
|
||||
assert_eq!(recorded, vec!["new"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_agent_that_joins_the_console_while_an_agents_end_decides_keeps_it() {
|
||||
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
|
||||
announced.record("old");
|
||||
announced.record("new");
|
||||
"new"
|
||||
});
|
||||
assert!(stopped.is_empty(), "{stopped:?}");
|
||||
assert_eq!(recorded, vec!["old", "new"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finish_stops_waits_for_the_stop_a_new_page_started() {
|
||||
// Quitting right after New Session: the exit must not cut it short.
|
||||
let announced = left_under_the_window("old");
|
||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let log = Arc::clone(&stopped);
|
||||
announced.stop_left("new", move |sid| {
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
log.lock().unwrap().push(sid.to_string());
|
||||
});
|
||||
assert!(stopped.lock().unwrap().is_empty(), "it runs on a thread");
|
||||
announced.finish_stops();
|
||||
assert_eq!(*stopped.lock().unwrap(), vec!["old"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finish_stops_waits_for_the_stops_an_agents_end_still_has_running() {
|
||||
// Quitting right after an agent ended: the exit must not cut its
|
||||
// consoles' stops short.
|
||||
let announced = Arc::new(AnnouncedConsoles::default());
|
||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let log = Arc::clone(&stopped);
|
||||
let hook = stop_announced_on_end(
|
||||
Arc::clone(&announced),
|
||||
|| None,
|
||||
move |sid| {
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
log.lock().unwrap().push(sid.to_string());
|
||||
},
|
||||
);
|
||||
announced.record("s1");
|
||||
|
||||
hook();
|
||||
assert!(
|
||||
stopped.lock().unwrap().is_empty(),
|
||||
"the stop runs on a thread"
|
||||
);
|
||||
announced.finish_stops();
|
||||
|
||||
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_console_call_runs_in_a_process_group_of_its_own() {
|
||||
// Ctrl+C and a closing terminal signal the app's whole group: a stop
|
||||
// already running there ended before it stopped its console.
|
||||
let console = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
|
||||
let mut child = node_command(&console)
|
||||
.arg("help")
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.expect("node starts");
|
||||
let pid = child.id() as i32;
|
||||
// SAFETY: getpgid only reads; the child is not waited for yet, so its id is its own.
|
||||
let group = unsafe { libc::getpgid(pid) };
|
||||
let _ = child.wait();
|
||||
assert_eq!(group, pid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_apps_stop_calls_pass_force() {
|
||||
let args = stop_args("20261101-120000-abcdef");
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod attention;
|
||||
pub mod brief;
|
||||
pub mod console_supervisor;
|
||||
pub mod handoff;
|
||||
pub mod log;
|
||||
pub mod loop_commit;
|
||||
pub mod loop_driver;
|
||||
pub mod loop_notify;
|
||||
@@ -28,5 +29,7 @@ pub mod session_reader;
|
||||
pub mod settings;
|
||||
#[cfg(windows)]
|
||||
pub mod task_dialog;
|
||||
#[cfg(unix)]
|
||||
pub mod term_signal;
|
||||
pub mod ui_confirm;
|
||||
pub mod versions;
|
||||
@@ -0,0 +1,10 @@
|
||||
//! Lines for the app's log, its stderr, on the paths a quit takes. `eprintln!` panics when the
|
||||
//! write fails, as it does once the terminal the app was started from has closed: the quit's
|
||||
//! cleanup would end at its first line, with the app still open.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
/// Writes one line, or nothing when the log cannot be written to.
|
||||
pub fn line(text: &str) {
|
||||
let _ = writeln!(std::io::stderr(), "{text}");
|
||||
}
|
||||
@@ -10,8 +10,13 @@ use plan2code_app_lib::agents::{self, Agent, PermissionMode};
|
||||
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
||||
use plan2code_app_lib::attention::{self, Badge, Signal};
|
||||
use plan2code_app_lib::console_supervisor::{
|
||||
app_origin, origin_of, session_on_disk, ConsoleSupervisor,
|
||||
app_origin, origin_of, session_on_disk, AnnouncedConsoles, ConsoleSupervisor,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use plan2code_app_lib::console_supervisor::{
|
||||
find_console_dir, stop_announced_on_end, stop_console_session,
|
||||
};
|
||||
use plan2code_app_lib::log;
|
||||
use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot};
|
||||
use plan2code_app_lib::models;
|
||||
use plan2code_app_lib::node_check;
|
||||
@@ -44,6 +49,11 @@ struct AppState {
|
||||
page: PageChannel,
|
||||
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
|
||||
announce: Arc<Mutex<Option<AnnounceServer>>>,
|
||||
// Every console session an agent announced and the window took, to stop
|
||||
// when that agent ends or the app quits (macOS and Linux). On Windows the
|
||||
// agent's Job Object ends them, so nothing there records or reads this.
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
announced: Arc<AnnouncedConsoles>,
|
||||
// The Node check's result: it runs on a background thread after the
|
||||
// window opens (Task 9.10), so this is unchecked until it reports.
|
||||
node: Mutex<NodeReport>,
|
||||
@@ -152,13 +162,23 @@ fn platform_info() -> serde_json::Value {
|
||||
|
||||
// What the launch card offers per agent: whether its CLI is on PATH (else how
|
||||
// to install it), and whether it takes its own reasoning effort; plus the
|
||||
// warnings about agents.json.
|
||||
// warnings about agents.json. A refresh runs the person's login shell, which
|
||||
// can take seconds with a slow profile, so the work runs on a blocking thread:
|
||||
// a sync command would run on the main thread and freeze the window meanwhile.
|
||||
#[tauri::command]
|
||||
fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
|
||||
async fn agent_availability(refresh: Option<bool>) -> Result<serde_json::Value, String> {
|
||||
let refresh = refresh == Some(true);
|
||||
tauri::async_runtime::spawn_blocking(move || agent_list(refresh))
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// The agent list `agent_availability` answers with.
|
||||
fn agent_list(refresh: bool) -> serde_json::Value {
|
||||
// "Check again" also works the PATH out again and re-reads the shipped
|
||||
// agent list, so a CLI whose installer added a new folder to PATH, or a
|
||||
// list an update rewrote, is seen without restarting the app.
|
||||
if refresh == Some(true) {
|
||||
if refresh {
|
||||
node_check::refresh_path();
|
||||
agents::refresh_agent_list();
|
||||
}
|
||||
@@ -318,16 +338,62 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
||||
let agent = Arc::new(AgentManager::new(dir, sink));
|
||||
agent.set_before_fresh(before_fresh_hook(state));
|
||||
agent.set_forget_session(forget_session_hook(state));
|
||||
// On Windows the agent's Job Object already ends every console it opened.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let project_dir = agent.folder().clone();
|
||||
let console = Arc::clone(&state.console);
|
||||
agent.set_ended(stop_announced_on_end(
|
||||
Arc::clone(&state.announced),
|
||||
move || followed_sid(&console),
|
||||
move |sid| stop_announced_console(&project_dir, sid),
|
||||
));
|
||||
}
|
||||
*guard = Some(Arc::clone(&agent));
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
// The session the window's console supervisor follows, if any.
|
||||
#[cfg(unix)]
|
||||
fn followed_sid(console: &Mutex<Option<ConsoleSupervisor>>) -> Option<String> {
|
||||
console
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.as_ref()
|
||||
.map(|sup| sup.session().sid.clone())
|
||||
}
|
||||
|
||||
// The project's folder, or the current one with none chosen.
|
||||
#[cfg(unix)]
|
||||
fn project_folder(state: &AppState) -> std::path::PathBuf {
|
||||
state
|
||||
.project
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|p| p.as_ref().map(|p| p.dir.clone()))
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("."))
|
||||
}
|
||||
|
||||
// Stops one console an agent announced, from that agent's project folder; a
|
||||
// failure is only logged, since nothing is left to tell.
|
||||
#[cfg(unix)]
|
||||
fn stop_announced_console(project_dir: &std::path::Path, sid: &str) {
|
||||
let stopped = find_console_dir()
|
||||
.and_then(|console_dir| stop_console_session(&console_dir, project_dir, sid));
|
||||
if let Err(error) = stopped {
|
||||
log::line(&format!(
|
||||
"plan2code: could not stop the console {sid}: {error}"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// What New Session does before the fresh agent starts. It leaves the brief for
|
||||
// the dashboard, from the console session running now, then forgets that
|
||||
// session, so the fresh agent's `open` starts one of its own: a session that
|
||||
// joined the old one would carry its meter along, still red after the very
|
||||
// press the red meter asks for. The old console is left to shut itself down
|
||||
// once the frame moves on to the new page.
|
||||
// press the red meter asks for. The old console is left running under the
|
||||
// window until the new page takes over: on macOS and Linux the app stops it
|
||||
// then (`take_announced`); elsewhere it shuts itself down once its page is gone.
|
||||
fn before_fresh_hook(state: &AppState) -> BeforeFresh {
|
||||
let console = Arc::clone(&state.console);
|
||||
let announce = Arc::clone(&state.announce);
|
||||
@@ -371,11 +437,13 @@ fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
||||
// page from a loopback dev server, so the window is asked for its real URL.
|
||||
/// A page the agent's `open` announced: the supervisor follows it, or adopts
|
||||
/// it when the agent started the console (the app owns its stop from there).
|
||||
/// Says whether the window should show it. A session outside this app's
|
||||
/// console store is refused: `cargo test` run by the agent inside the app
|
||||
/// 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.
|
||||
/// Says whether the window should show it. The console an ended agent left
|
||||
/// under the window stops here, since the window has moved on from it (macOS
|
||||
/// and Linux). A session outside this app's console store is refused: `cargo
|
||||
/// test` run by the agent inside the app 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,
|
||||
@@ -392,6 +460,10 @@ fn take_announced(
|
||||
if notice.workflow == "setup" {
|
||||
return false;
|
||||
}
|
||||
// The agent opened it: it ends with that agent, or with the app (on
|
||||
// Windows the agent's Job Object ends it).
|
||||
#[cfg(unix)]
|
||||
state.announced.record(¬ice.sid);
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
match guard.as_mut() {
|
||||
Some(sup) => sup.follow(¬ice.url, ¬ice.sid),
|
||||
@@ -410,6 +482,13 @@ fn take_announced(
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let project_dir = project_folder(state);
|
||||
state.announced.stop_left(¬ice.sid, move |sid| {
|
||||
stop_announced_console(&project_dir, sid)
|
||||
});
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -687,6 +766,17 @@ fn confirm_quit(app: &tauri::AppHandle) {
|
||||
QuitCase::Waiting => MessageDialogKind::Info,
|
||||
QuitCase::Working => MessageDialogKind::Warning,
|
||||
};
|
||||
// A close button pressed on a window in the background leaves the app inactive, and the
|
||||
// window's web view does not take the first click on an inactive window, so the question
|
||||
// would need a click to activate the window before Quit or Stay is heard. A minimized window
|
||||
// would show it to nobody. So the window comes forward, as the key window, before it asks.
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
if window.is_minimized().unwrap_or(false) {
|
||||
let _ = window.unminimize();
|
||||
}
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
// Off Windows the shell's own modal asks, with Stay first and focused, so Stay is the default
|
||||
// answer everywhere (the plugin's box makes Quit the default). The OS box is the fallback for a
|
||||
// page that cannot show it. Both wait off the event loop.
|
||||
@@ -737,22 +827,10 @@ fn agent_is_active(app: &tauri::AppHandle) -> bool {
|
||||
|| current_agent(&state).is_some_and(|agent| agent.is_active())
|
||||
}
|
||||
|
||||
// Stops the loop, the agent, then the console, then exits. The loop goes first:
|
||||
// its record is dropped without a word to the page, so its watch thread never
|
||||
// takes the ended agent for a crash.
|
||||
// Stops everything this app's work left running, then exits.
|
||||
fn quit_app(app: &tauri::AppHandle) {
|
||||
let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take());
|
||||
let state = app.state::<AppState>();
|
||||
loop_driver::abandon(&state.loop_run);
|
||||
review_loop::abandon(&state.review_run);
|
||||
if let Some(agent) = current_agent(&state) {
|
||||
agent.stop();
|
||||
}
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
if let Some(mut console) = guard.take() {
|
||||
let _ = console.stop();
|
||||
}
|
||||
}
|
||||
shutdown(app);
|
||||
if let Some(plan) = restart {
|
||||
if let Err(error) = spawn_restart(&plan) {
|
||||
eprintln!("plan2code: restart failed: {error}");
|
||||
@@ -761,6 +839,76 @@ fn quit_app(app: &tauri::AppHandle) {
|
||||
app.exit(0);
|
||||
}
|
||||
|
||||
// The one cleanup every quit runs: from `quit_app`, and on macOS and Linux
|
||||
// from `RunEvent::Exit` too, for the routes that never pass through
|
||||
// `quit_app`. A second call finds nothing left to stop.
|
||||
fn shutdown(app: &tauri::AppHandle) {
|
||||
let state = app.state::<AppState>();
|
||||
shutdown_with(&state);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let project_dir = project_folder(&state);
|
||||
stop_other_announced(&state, |sid| stop_announced_console(&project_dir, sid));
|
||||
}
|
||||
}
|
||||
|
||||
// Stops the loops, the agent, then the console, each before returning: the app
|
||||
// may exit straight after, and a stop left to a thread would lose that race.
|
||||
// The loops go first: their records are dropped without a word to the page, so
|
||||
// their watch threads never take the ended agent for a crash.
|
||||
fn shutdown_with(state: &AppState) {
|
||||
loop_driver::abandon(&state.loop_run);
|
||||
review_loop::abandon(&state.review_run);
|
||||
if let Some(agent) = current_agent(state) {
|
||||
agent.stop();
|
||||
}
|
||||
settle_agent_ends(state);
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
if let Some(mut console) = guard.take() {
|
||||
if let Err(error) = stop_supervised(state, &mut console) {
|
||||
let sid = &console.session().sid;
|
||||
log::line(&format!(
|
||||
"plan2code: could not stop the console {sid}: {error}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// macOS and Linux, after `shutdown_with`: stops every console an agent
|
||||
// announced that is still recorded, each before returning. On Windows the
|
||||
// agent's Job Object ends those consoles.
|
||||
#[cfg(unix)]
|
||||
fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
|
||||
for sid in state.announced.take_all() {
|
||||
stop_sid(&sid);
|
||||
}
|
||||
}
|
||||
|
||||
// Waits for what an agent's end or a new page still has running on a thread
|
||||
// (macOS and Linux): stopping consoles, and, after an end, deciding whether to
|
||||
// keep the one the window follows recorded. Called before taking the console
|
||||
// lock to stop that console, since the end's thread takes the lock too, and a
|
||||
// decision made after the stop would record it again.
|
||||
fn settle_agent_ends(state: &AppState) {
|
||||
#[cfg(unix)]
|
||||
state.announced.finish_stops();
|
||||
#[cfg(not(unix))]
|
||||
let _ = state;
|
||||
}
|
||||
|
||||
// Stops the console the window follows and, on macOS and Linux, forgets it as
|
||||
// an announced one, so no later agent's end or quit stops it again. Call
|
||||
// `settle_agent_ends` before taking the console lock.
|
||||
fn stop_supervised(state: &AppState, sup: &mut ConsoleSupervisor) -> Result<(), String> {
|
||||
let stopped = sup.stop();
|
||||
#[cfg(unix)]
|
||||
state.announced.forget(&sup.session().sid);
|
||||
#[cfg(not(unix))]
|
||||
let _ = state;
|
||||
stopped
|
||||
}
|
||||
|
||||
// The console page's state, told on every change (`attention` from the page):
|
||||
// the taskbar's dot for this system, and one flash on a change into the
|
||||
// person's move or needs attention while the window is not focused. An
|
||||
@@ -1140,9 +1288,10 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
|
||||
agent.stop();
|
||||
}
|
||||
*state.agent.lock().map_err(|e| e.to_string())? = None;
|
||||
settle_agent_ends(state);
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
if let Some(mut sup) = guard.take() {
|
||||
let _ = sup.stop();
|
||||
let _ = stop_supervised(state, &mut sup);
|
||||
}
|
||||
}
|
||||
// The new project's agent asks the window which session is current and
|
||||
@@ -1310,8 +1459,13 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// Stop the console but keep its supervisor, so a start after a stop opens
|
||||
/// the same session again instead of finding nothing to start.
|
||||
/// the same session again instead of finding nothing to start. Unlike the
|
||||
/// other stops, this one leaves an announced console recorded: the supervisor
|
||||
/// keeps its session to start it again, and from then on it stops as any
|
||||
/// announced console does, with its agent, once the window moves on from one
|
||||
/// an ended agent left, or at the quit.
|
||||
fn console_stop_impl(state: &AppState) -> Result<(), String> {
|
||||
settle_agent_ends(state);
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(sup) = guard.as_mut() {
|
||||
sup.stop()?;
|
||||
@@ -1348,9 +1502,10 @@ fn console_setup_start_impl(state: &AppState, origin: &str) -> Result<serde_json
|
||||
// The setup console starts before the old one is stopped: a failed open
|
||||
// (a missing console.mjs, a dead session store) leaves what was showing.
|
||||
let sup = ConsoleSupervisor::start_with_workflow(dir, origin.to_string(), "setup")?;
|
||||
settle_agent_ends(state);
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(mut old) = guard.take() {
|
||||
let _ = old.stop();
|
||||
let _ = stop_supervised(state, &mut old);
|
||||
}
|
||||
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
|
||||
*guard = Some(sup);
|
||||
@@ -1591,7 +1746,7 @@ fn loop_stop_after_phase(
|
||||
// once. The page asked the person first ("End the agent now? This phase's
|
||||
// changes stay uncommitted."); the strip says Stopping, and the driver tells
|
||||
// the stop screen on its next look.
|
||||
#[tauri::command]
|
||||
#[tauri::command(async)]
|
||||
fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
let agent = current_agent(&state);
|
||||
// The event goes out before the agent is ended (which can take a while), so
|
||||
@@ -1696,7 +1851,7 @@ fn review_loop_stop_after(
|
||||
|
||||
// Stop now: the flag first, then the agent ends at once. Nothing more is
|
||||
// committed; the stop screen offers Keep or Discard for the partial changes.
|
||||
#[tauri::command]
|
||||
#[tauri::command(async)]
|
||||
fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
let agent = current_agent(&state);
|
||||
review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| {
|
||||
@@ -1882,9 +2037,10 @@ fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, Strin
|
||||
if let Some(agent) = current_agent(&state) {
|
||||
agent.stop();
|
||||
}
|
||||
settle_agent_ends(&state);
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(mut sup) = guard.take() {
|
||||
let _ = sup.stop();
|
||||
let _ = stop_supervised(&state, &mut sup);
|
||||
}
|
||||
let sup = ConsoleSupervisor::start(dir, origin)?;
|
||||
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
|
||||
@@ -1903,21 +2059,25 @@ fn first_launch(app: &tauri::AppHandle) -> bool {
|
||||
|
||||
// macOS gets a real menu bar: Plan2Code (About, Check for Updates, Help, Quit) and the standard Edit
|
||||
// menu, so Copy, Paste and Select All work in the page's fields. The three custom items tell the
|
||||
// page (the same actions as the bar's "..." menu); Quit is the predefined one, and the exit it asks
|
||||
// for goes through the quit check in the run loop below.
|
||||
// page (the same actions as the bar's "..." menu). Quit is the app's own item, id `quit` on Cmd+Q,
|
||||
// not the predefined one: that sends `terminate:`, which never raises `ExitRequested`, so it would
|
||||
// quit with no prompt while an agent works.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
|
||||
use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder};
|
||||
let about = MenuItemBuilder::with_id("about", "About Plan2Code").build(app)?;
|
||||
let check = MenuItemBuilder::with_id("check-updates", "Check for Updates...").build(app)?;
|
||||
let help = MenuItemBuilder::with_id("help", "Plan2Code Help").build(app)?;
|
||||
let quit = MenuItemBuilder::with_id("quit", "Quit Plan2Code")
|
||||
.accelerator("CmdOrCtrl+Q")
|
||||
.build(app)?;
|
||||
let app_menu = SubmenuBuilder::new(app, "Plan2Code")
|
||||
.item(&about)
|
||||
.item(&check)
|
||||
.separator()
|
||||
.item(&help)
|
||||
.separator()
|
||||
.quit()
|
||||
.item(&quit)
|
||||
.build()?;
|
||||
let edit = SubmenuBuilder::new(app, "Edit")
|
||||
.undo()
|
||||
@@ -1934,11 +2094,56 @@ fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
|
||||
let id = event.id().as_ref();
|
||||
if matches!(id, "about" | "check-updates" | "help") {
|
||||
let _ = app.emit("app-menu", id);
|
||||
} else if id == "quit" {
|
||||
request_quit(app.clone());
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// macOS takes an app's Dock and Cmd+Tab icon from its `.app` bundle, but the app ships as a bare
|
||||
// program (`tauri build --no-bundle`), so without this the Dock shows the generic "exec" icon.
|
||||
// Tauri sets the icon this way in dev builds only; this does the same in every build.
|
||||
#[cfg(target_os = "macos")]
|
||||
const APP_ICON_ICNS: &[u8] = include_bytes!("../icons/icon.icns");
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn app_icon_image() -> Option<objc2::rc::Retained<objc2_app_kit::NSImage>> {
|
||||
use objc2::AllocAnyThread;
|
||||
let data = objc2_foundation::NSData::with_bytes(APP_ICON_ICNS);
|
||||
objc2_app_kit::NSImage::initWithData(objc2_app_kit::NSImage::alloc(), &data)
|
||||
}
|
||||
|
||||
// Runs from `setup`, on the main thread AppKit requires; anywhere else it only logs.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_app_icon() {
|
||||
let Some(mtm) = objc2::MainThreadMarker::new() else {
|
||||
eprintln!("plan2code: the Dock icon can only be set on the main thread");
|
||||
return;
|
||||
};
|
||||
let Some(icon) = app_icon_image() else {
|
||||
eprintln!("plan2code: the app icon could not be read, so the Dock keeps the default one");
|
||||
return;
|
||||
};
|
||||
let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
|
||||
// SAFETY: called on the main thread (checked above) with a valid image, as AppKit requires.
|
||||
unsafe { app.setApplicationIconImage(Some(&icon)) };
|
||||
}
|
||||
|
||||
// A bare program the launcher starts from a terminal is not made the active app, so its window
|
||||
// opened behind that terminal. Once, at start: later shows of the window leave the active app
|
||||
// alone.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn activate_app() {
|
||||
let Some(mtm) = objc2::MainThreadMarker::new() else {
|
||||
eprintln!("plan2code: the app can only be activated on the main thread");
|
||||
return;
|
||||
};
|
||||
// `activate` needs macOS 14; this one works on every macOS the app runs on.
|
||||
#[allow(deprecated)]
|
||||
objc2_app_kit::NSApplication::sharedApplication(mtm).activateIgnoringOtherApps(true);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
tauri::Builder::default()
|
||||
@@ -2083,14 +2288,41 @@ fn main() {
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
build_mac_menu(app)?;
|
||||
#[cfg(target_os = "macos")]
|
||||
set_app_icon();
|
||||
#[cfg(target_os = "macos")]
|
||||
activate_app();
|
||||
// A plain `kill`, Ctrl+C or a closed terminal runs the quit cleanup, then exits,
|
||||
// instead of ending the app with its consoles still running. `shutdown`, not
|
||||
// `quit_app`: a signal never starts a pending update's restart.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let handle = app.handle().clone();
|
||||
if let Err(error) = plan2code_app_lib::term_signal::on_terminate(move || {
|
||||
shutdown(&handle);
|
||||
handle.exit(0);
|
||||
}) {
|
||||
eprintln!("plan2code: a signal may skip the quit cleanup: {error}");
|
||||
}
|
||||
}
|
||||
spawn_node_check(app.handle().clone());
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building the Plan2Code app")
|
||||
.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.
|
||||
// The app is going, by whatever route: clean up here too. On macOS,
|
||||
// Dock Quit sends `terminate:`, which raises only this and never asks
|
||||
// first, and a quit with no agent active still stops the console this
|
||||
// way. After `quit_app` this finds nothing left.
|
||||
#[cfg(unix)]
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
shutdown(app);
|
||||
}
|
||||
// An exit nobody asked for in code (`code: None`) asks first while an
|
||||
// agent works; one with `code` set is `quit_app`'s own. On macOS,
|
||||
// Cmd+Q and the app menu's Quit go through the app's own Quit item
|
||||
// (`build_mac_menu`), and Dock Quit never reaches here.
|
||||
if let tauri::RunEvent::ExitRequested {
|
||||
api, code: None, ..
|
||||
} = event
|
||||
@@ -2186,6 +2418,202 @@ mod tests {
|
||||
let_go(&state);
|
||||
}
|
||||
|
||||
// Windows' Job Object ends an agent's consoles with it: nothing is recorded there.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn only_an_accepted_announce_is_recorded_for_the_agents_end() {
|
||||
let state = state_for("project-a");
|
||||
// Refused: outside the console store.
|
||||
assert!(!take_announced(
|
||||
&state,
|
||||
¬ice("outside"),
|
||||
app_origin().to_string(),
|
||||
|_| false
|
||||
));
|
||||
// Refused: an announced setup page.
|
||||
let mut setup = notice("setup-console");
|
||||
setup.workflow = "setup".into();
|
||||
assert!(!take_announced(
|
||||
&state,
|
||||
&setup,
|
||||
app_origin().to_string(),
|
||||
|_| true
|
||||
));
|
||||
assert!(
|
||||
state.announced.take_all().is_empty(),
|
||||
"nothing refused is recorded"
|
||||
);
|
||||
|
||||
// Accepted while following a console, then while following none.
|
||||
*state.console.lock().unwrap() = Some(following_the_build());
|
||||
assert!(take_announced(
|
||||
&state,
|
||||
¬ice("followed"),
|
||||
app_origin().to_string(),
|
||||
|_| true
|
||||
));
|
||||
let_go(&state);
|
||||
assert!(take_announced(
|
||||
&state,
|
||||
¬ice("adopted"),
|
||||
app_origin().to_string(),
|
||||
|_| true
|
||||
));
|
||||
let_go(&state);
|
||||
assert_eq!(state.announced.take_all(), vec!["followed", "adopted"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn shutdown_stops_every_announced_console_once_and_is_safe_twice() {
|
||||
let state = state_for("project-a");
|
||||
state.announced.record("s1");
|
||||
state.announced.record("s2");
|
||||
let stopped = Mutex::new(Vec::<String>::new());
|
||||
let stop = |sid: &str| stopped.lock().unwrap().push(sid.to_string());
|
||||
|
||||
shutdown_with(&state);
|
||||
stop_other_announced(&state, stop);
|
||||
assert_eq!(
|
||||
*stopped.lock().unwrap(),
|
||||
vec!["s1", "s2"],
|
||||
"both, before returning"
|
||||
);
|
||||
|
||||
shutdown_with(&state);
|
||||
stop_other_announced(&state, stop);
|
||||
assert_eq!(
|
||||
stopped.lock().unwrap().len(),
|
||||
2,
|
||||
"a second shutdown stops nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn shutdown_never_stops_the_followed_console_a_second_time() {
|
||||
// The window follows the build's console, which the agent announced:
|
||||
// the supervisor stops it, so the announced list must skip it.
|
||||
let state = state_for("project-a");
|
||||
*state.console.lock().unwrap() = Some(following_the_build());
|
||||
state.announced.record("build");
|
||||
state.announced.record("other");
|
||||
let stopped = Mutex::new(Vec::<String>::new());
|
||||
|
||||
shutdown_with(&state);
|
||||
stop_other_announced(&state, |sid| stopped.lock().unwrap().push(sid.to_string()));
|
||||
|
||||
assert_eq!(*stopped.lock().unwrap(), vec!["other"]);
|
||||
assert!(
|
||||
state.console.lock().unwrap().is_none(),
|
||||
"the supervisor was taken"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn shutdown_waits_for_the_stops_an_agents_end_left_running() {
|
||||
// The agent ended a moment before the quit: its hook is still
|
||||
// stopping that agent's consoles on a thread the exit would cut short.
|
||||
let state = state_for("project-a");
|
||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let log = Arc::clone(&stopped);
|
||||
let ended = stop_announced_on_end(
|
||||
Arc::clone(&state.announced),
|
||||
|| None,
|
||||
move |sid| {
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
log.lock().unwrap().push(sid.to_string());
|
||||
},
|
||||
);
|
||||
state.announced.record("s1");
|
||||
ended();
|
||||
|
||||
shutdown_with(&state);
|
||||
|
||||
assert_eq!(
|
||||
*stopped.lock().unwrap(),
|
||||
vec!["s1"],
|
||||
"done before returning"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_new_page_stops_the_console_an_ended_agent_left_under_the_window() {
|
||||
// New Session: the old agent's console stayed up with no page in it,
|
||||
// until the next agent's end, the quit or its own idle limit.
|
||||
let state = state_for("project-a");
|
||||
*state.console.lock().unwrap() = Some(following_the_build());
|
||||
state.announced.record("build");
|
||||
let console = Arc::clone(&state.console);
|
||||
let ended = stop_announced_on_end(
|
||||
Arc::clone(&state.announced),
|
||||
move || followed_sid(&console),
|
||||
|_| {},
|
||||
);
|
||||
ended();
|
||||
state.announced.finish_stops();
|
||||
|
||||
assert!(take_announced(
|
||||
&state,
|
||||
¬ice("next"),
|
||||
app_origin().to_string(),
|
||||
|_| true
|
||||
));
|
||||
state.announced.finish_stops();
|
||||
|
||||
assert_eq!(state.announced.take_all(), vec!["next"]);
|
||||
let_go(&state);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_console_the_app_stopped_is_forgotten_so_no_later_end_stops_it_again() {
|
||||
// A project switch stops the console the window follows, which its
|
||||
// agent announced: still recorded, the next project's agent's end and
|
||||
// the quit each ran `console.mjs stop` on it again.
|
||||
let state = state_for("project-a");
|
||||
*state.console.lock().unwrap() = Some(following_the_build());
|
||||
state.announced.record("build");
|
||||
state.announced.record("other");
|
||||
|
||||
teardown_project(&state).unwrap();
|
||||
|
||||
assert_eq!(state.announced.take_all(), vec!["other"]);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn the_dock_icon_is_the_apps_own_icon_set_and_macos_can_read_it() {
|
||||
let icon = app_icon_image().expect("NSImage reads the bundled icon.icns");
|
||||
let size = icon.size();
|
||||
assert!(
|
||||
size.width > 0.0 && size.height > 0.0,
|
||||
"a drawable image, not an empty one: {size:?}"
|
||||
);
|
||||
// The same artwork the bundle lists for macOS (`bundle.icon` in
|
||||
// tauri.conf.json), not a copy: a renamed bundle icon fails here
|
||||
// instead of leaving the Dock and the bundle apart.
|
||||
let config: serde_json::Value = serde_json::from_slice(
|
||||
&std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tauri.conf.json")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
config["bundle"]["icon"]
|
||||
.as_array()
|
||||
.is_some_and(|icons| icons
|
||||
.iter()
|
||||
.any(|icon| icon.as_str() == Some("icons/icon.icns"))),
|
||||
"the bundle lists icons/icon.icns: {}",
|
||||
config["bundle"]["icon"]
|
||||
);
|
||||
assert_eq!(
|
||||
APP_ICON_ICNS,
|
||||
std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/icons/icon.icns")).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_from_the_console_store_is_followed() {
|
||||
let state = state_for("project-a");
|
||||
@@ -2429,7 +2857,7 @@ mod tests {
|
||||
// Every entry carries the shared lookup's state: found (on PATH),
|
||||
// outside (needing setup, not missing) or missing, with `folder` for
|
||||
// where an outside hit lives.
|
||||
let json = agent_availability(None);
|
||||
let json = agent_list(false);
|
||||
let entries = json["agents"].as_array().unwrap();
|
||||
assert!(!entries.is_empty());
|
||||
let mut builtins = 0;
|
||||
@@ -2448,6 +2876,17 @@ mod tests {
|
||||
assert!(builtins >= 3, "claude, devin and codex are listed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_availability_command_is_awaited_not_run_on_the_ui_thread() {
|
||||
// Check again re-runs the login shell, then the interactive config
|
||||
// (up to 5 s with slow ones). A sync command runs on the main thread and freezes the
|
||||
// window that long, so the command is a future that hands the work
|
||||
// to a blocking thread; awaiting it gives the same list.
|
||||
let json = tauri::async_runtime::block_on(agent_availability(None))
|
||||
.expect("the blocking task finished");
|
||||
assert_eq!(json, agent_list(false));
|
||||
}
|
||||
|
||||
/// A real console, the same way `tests/console_supervisor.rs` sets one
|
||||
/// up (see `console_test_env`). Keep the guard until the test ends: the
|
||||
/// console's variables must not change while its session is in use.
|
||||
@@ -2534,6 +2973,50 @@ mod tests {
|
||||
let _ = state.console.lock().unwrap().take().unwrap().stop();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_console_the_bar_stopped_and_started_again_still_stops_at_the_quit() {
|
||||
// The bar's Reconnect (or a skills update) stops the console its
|
||||
// agent announced and starts it again on the same session. When the
|
||||
// window then follows the next agent's page, the quit must still stop
|
||||
// that console: once forgotten at the stop, it outlived the app.
|
||||
let Some((_env, sup)) = real_console() else {
|
||||
return;
|
||||
};
|
||||
let state = state_for("project-a");
|
||||
let sid = sup.session().sid.clone();
|
||||
*state.console.lock().unwrap() = Some(sup);
|
||||
state.announced.record(&sid);
|
||||
|
||||
console_stop_impl(&state).unwrap();
|
||||
console_start_impl(&state).expect("a start after a stop works");
|
||||
assert!(take_announced(
|
||||
&state,
|
||||
¬ice("next"),
|
||||
app_origin().to_string(),
|
||||
|_| true
|
||||
));
|
||||
let stopped_at_quit = Mutex::new(Vec::new());
|
||||
stop_other_announced(&state, |sid| {
|
||||
stopped_at_quit.lock().unwrap().push(sid.to_string())
|
||||
});
|
||||
|
||||
// Stop the real console before asserting, so a failure leaves nothing running.
|
||||
let console_dir = PathBuf::from(std::env::var("PLAN2CODE_CONSOLE_DIR").unwrap());
|
||||
let project =
|
||||
std::env::temp_dir().join(format!("p2c-main-test-project-{}", std::process::id()));
|
||||
let _ = plan2code_app_lib::console_supervisor::stop_console_session(
|
||||
&console_dir,
|
||||
&project,
|
||||
&sid,
|
||||
);
|
||||
assert!(
|
||||
stopped_at_quit.lock().unwrap().contains(&sid),
|
||||
"the quit stops the console the bar started again: {:?}",
|
||||
stopped_at_quit.lock().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_health_check_never_holds_the_console_lock() {
|
||||
// A server that takes the connection and never answers: the check
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,7 +19,7 @@ pub const BATCH_INTERVAL: Duration = Duration::from_millis(16);
|
||||
/// On macOS and Linux the kill is a hang-up signal, which a program can ignore.
|
||||
/// This long after it, a command that is still running is killed outright.
|
||||
#[cfg(unix)]
|
||||
const HANGUP_GRACE: Duration = Duration::from_secs(2);
|
||||
pub const HANGUP_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// What to run, where, and how big the terminal starts.
|
||||
pub struct StartOptions {
|
||||
@@ -43,6 +43,11 @@ pub struct PtyHost {
|
||||
/// a process id that may have been given to something else.
|
||||
#[cfg(unix)]
|
||||
exited: Arc<AtomicBool>,
|
||||
/// Set once `end_group` has seen the process group empty (or killed what
|
||||
/// was left of it), so `kill`'s late group kill never signals a group id
|
||||
/// that may since have been given to something else.
|
||||
#[cfg(unix)]
|
||||
group_done: Arc<AtomicBool>,
|
||||
/// A Windows Job Object the spawned process was assigned to, so ending
|
||||
/// it (`kill`, or this host simply being dropped) ends every process
|
||||
/// still in it, not just the one directly spawned: a `cmd /c` npm shim's
|
||||
@@ -150,6 +155,8 @@ impl PtyHost {
|
||||
pid,
|
||||
#[cfg(unix)]
|
||||
exited: Arc::new(AtomicBool::new(false)),
|
||||
#[cfg(unix)]
|
||||
group_done: Arc::new(AtomicBool::new(false)),
|
||||
#[cfg(windows)]
|
||||
job,
|
||||
})
|
||||
@@ -171,7 +178,9 @@ impl PtyHost {
|
||||
.map_err(err)
|
||||
}
|
||||
|
||||
/// End the command. Safe to call while `wait` is blocked in another thread.
|
||||
/// End the command and everything it started that is still in its process
|
||||
/// group (on Windows, its Job Object). Safe to call while `wait` is
|
||||
/// blocked in another thread.
|
||||
pub fn kill(&self) -> Result<(), String> {
|
||||
let result = self.killer.lock().map_err(err)?.kill().map_err(err);
|
||||
// The job object, when there is one, ends the whole process tree:
|
||||
@@ -187,22 +196,60 @@ impl PtyHost {
|
||||
if cfg!(windows) {
|
||||
return Ok(());
|
||||
}
|
||||
// portable-pty only sends SIGHUP on macOS and Linux; follow it with
|
||||
// SIGKILL if the command is still there after the grace period.
|
||||
// portable-pty only sends SIGHUP on macOS and Linux, and only to the
|
||||
// command itself. It starts the command under `setsid`, so the
|
||||
// command's pid is also its process group's id: hang up the whole
|
||||
// group too, then, after the grace period, kill whatever of the group
|
||||
// is still there. A process that left the group (`setsid`, a detached
|
||||
// child) is out of reach here.
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = self.pid {
|
||||
// SAFETY: plain signal to the command's own process group.
|
||||
unsafe { libc::kill(-(pid as i32), libc::SIGHUP) };
|
||||
let exited = Arc::clone(&self.exited);
|
||||
let group_done = Arc::clone(&self.group_done);
|
||||
thread::spawn(move || {
|
||||
thread::sleep(HANGUP_GRACE);
|
||||
if !exited.load(Ordering::SeqCst) {
|
||||
// SAFETY: plain signal to a process id the command still holds.
|
||||
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
||||
}
|
||||
// The group outlives its leader while any member is left; signal 0
|
||||
// only asks whether one is. Once `end_group` saw it gone, its id
|
||||
// may belong to another group by now: leave it alone.
|
||||
// SAFETY: plain signals to the command's own process group.
|
||||
if !group_done.load(Ordering::SeqCst)
|
||||
&& unsafe { libc::kill(-(pid as i32), 0) } == 0
|
||||
{
|
||||
unsafe { libc::kill(-(pid as i32), libc::SIGKILL) };
|
||||
}
|
||||
});
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// For after `kill` and `wait` when the app is about to exit: `kill`'s
|
||||
/// grace thread dies with the app, so this blocks until nothing of the
|
||||
/// command's process group is left, killing what is still there after
|
||||
/// `HANGUP_GRACE`. A no-op on Windows, where `kill` ended the Job Object.
|
||||
pub fn end_group(&self) {
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = self.pid {
|
||||
let group = -(pid as i32);
|
||||
let deadline = Instant::now() + HANGUP_GRACE;
|
||||
// SAFETY: signal 0 only asks whether the group still has members.
|
||||
while unsafe { libc::kill(group, 0) } == 0 {
|
||||
if Instant::now() >= deadline {
|
||||
// SAFETY: plain signal to the command's own process group.
|
||||
unsafe { libc::kill(group, libc::SIGKILL) };
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
self.group_done.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// Block until the command ends and return its exit code. A command ended by
|
||||
/// a signal reports 1.
|
||||
pub fn wait(&self) -> Result<u32, String> {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed) end a process at
|
||||
//! once by default, so the app's quit cleanup never ran and the consoles its agents had opened
|
||||
//! kept running. Here they are caught instead and handed to a thread of its own, which runs the
|
||||
//! cleanup it was given, once. The handler only writes one byte to a pipe, which a signal handler
|
||||
//! may safely do; the thread does the work.
|
||||
//! A second SIGTERM or SIGINT ends the process at once, so a cleanup that stalls never leaves a
|
||||
//! plain `kill` unable to end the app. A repeated SIGHUP does not: closing a terminal can send it
|
||||
//! twice at once, from the shell and from the terminal itself, and the commands the cleanup runs
|
||||
//! ignore it too.
|
||||
//! Unix only: Windows has none of these to catch.
|
||||
|
||||
use std::io;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
|
||||
|
||||
/// The signals that run the cleanup.
|
||||
const SIGNALS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP];
|
||||
|
||||
static INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||
static CAUGHT: AtomicBool = AtomicBool::new(false);
|
||||
static WRITE_END: AtomicI32 = AtomicI32::new(-1);
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
|
||||
unsafe fn errno() -> *mut libc::c_int {
|
||||
libc::__error()
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
unsafe fn errno() -> *mut libc::c_int {
|
||||
libc::__errno_location()
|
||||
}
|
||||
|
||||
extern "C" fn on_signal(signal: libc::c_int) {
|
||||
if CAUGHT.swap(true, Ordering::SeqCst) {
|
||||
if signal != libc::SIGHUP {
|
||||
// SAFETY: raise is async-signal-safe. SA_RESETHAND has put this signal's default
|
||||
// action back, so it ends the process as the handler returns.
|
||||
unsafe { libc::raise(signal) };
|
||||
}
|
||||
return;
|
||||
}
|
||||
let fd = WRITE_END.load(Ordering::Relaxed);
|
||||
if fd < 0 {
|
||||
return;
|
||||
}
|
||||
let byte = 1u8;
|
||||
// SAFETY: write is async-signal-safe, and the end is non-blocking, so it never hangs the
|
||||
// handler. errno is put back, since the code the signal interrupted may be about to read it.
|
||||
unsafe {
|
||||
let saved = *errno();
|
||||
libc::write(fd, (&byte as *const u8).cast(), 1);
|
||||
*errno() = saved;
|
||||
}
|
||||
}
|
||||
|
||||
fn last_error(what: &str) -> io::Error {
|
||||
let error = io::Error::last_os_error();
|
||||
io::Error::new(error.kind(), format!("{what}: {error}"))
|
||||
}
|
||||
|
||||
/// Runs `cleanup` on a thread of its own the first time the process gets SIGTERM, SIGINT or
|
||||
/// SIGHUP, instead of the process ending there; a second SIGTERM or SIGINT ends it. A signal the
|
||||
/// process was started with ignored (`nohup` ignores SIGHUP) stays ignored. Once per process: a
|
||||
/// second call is an error and changes nothing.
|
||||
pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
|
||||
if INSTALLED.swap(true, Ordering::SeqCst) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"the signal handler is already installed",
|
||||
));
|
||||
}
|
||||
let mut ends = [0; 2];
|
||||
// SAFETY: pipe fills the two-element array it is given.
|
||||
if unsafe { libc::pipe(ends.as_mut_ptr()) } != 0 {
|
||||
return Err(last_error("pipe"));
|
||||
}
|
||||
let [read_end, write_end] = ends;
|
||||
// SAFETY: fcntl on the two descriptors just made. Close-on-exec keeps them out of the
|
||||
// agents and consoles the app starts.
|
||||
unsafe {
|
||||
libc::fcntl(read_end, libc::F_SETFD, libc::FD_CLOEXEC);
|
||||
libc::fcntl(write_end, libc::F_SETFD, libc::FD_CLOEXEC);
|
||||
let flags = libc::fcntl(write_end, libc::F_GETFL);
|
||||
libc::fcntl(write_end, libc::F_SETFL, flags | libc::O_NONBLOCK);
|
||||
}
|
||||
WRITE_END.store(write_end, Ordering::SeqCst);
|
||||
std::thread::Builder::new()
|
||||
.name("quit-signal".into())
|
||||
.spawn(move || {
|
||||
let mut byte = 0u8;
|
||||
loop {
|
||||
// SAFETY: a one-byte read into a local; it blocks until the handler writes.
|
||||
let read = unsafe { libc::read(read_end, (&mut byte as *mut u8).cast(), 1) };
|
||||
if read == 1 {
|
||||
break;
|
||||
}
|
||||
if read < 0 && io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
// The pipe failed: no cleanup can be signalled any more, so none runs.
|
||||
return;
|
||||
}
|
||||
// For the commands the cleanup runs, which start with this process's ignored signals:
|
||||
// a repeated SIGHUP would end one before it has done its work.
|
||||
// SAFETY: ignoring a signal installs no handler.
|
||||
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
|
||||
cleanup();
|
||||
})?;
|
||||
for signal in SIGNALS {
|
||||
// SAFETY: a zeroed sigaction is a valid one to read the current action into, and, with the
|
||||
// handler set and an empty mask, to install. SA_RESTART resumes the calls the signal
|
||||
// interrupts elsewhere in the app, and SA_RESETHAND puts the default action back once the
|
||||
// handler has run, so a second one ends the app; SIGHUP goes without it.
|
||||
unsafe {
|
||||
let mut action: libc::sigaction = std::mem::zeroed();
|
||||
if libc::sigaction(signal, std::ptr::null(), &mut action) != 0 {
|
||||
return Err(last_error("sigaction"));
|
||||
}
|
||||
if action.sa_sigaction == libc::SIG_IGN {
|
||||
continue;
|
||||
}
|
||||
action = std::mem::zeroed();
|
||||
action.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
|
||||
action.sa_flags = libc::SA_RESTART;
|
||||
if signal != libc::SIGHUP {
|
||||
action.sa_flags |= libc::SA_RESETHAND;
|
||||
}
|
||||
libc::sigemptyset(&mut action.sa_mask);
|
||||
if libc::sigaction(signal, &action, std::ptr::null_mut()) != 0 {
|
||||
return Err(last_error("sigaction"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Plan2Code",
|
||||
"version": "3.2.6",
|
||||
"version": "3.2.7",
|
||||
"identifier": "com.plan2code.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../ui",
|
||||
|
||||
@@ -521,6 +521,197 @@ fn a_phase_start_runs_on_its_model_and_env_and_leaves_the_launch_choice_alone()
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
/// Counts the manager's `ended` calls.
|
||||
fn count_ends(h: &Harness) -> Arc<Mutex<usize>> {
|
||||
let ends = Arc::new(Mutex::new(0));
|
||||
let counter = Arc::clone(&ends);
|
||||
h.manager.set_ended(Arc::new(move || {
|
||||
*counter.lock().unwrap() += 1;
|
||||
}));
|
||||
ends
|
||||
}
|
||||
|
||||
/// Wait (briefly) for `ends` to reach `want`, then make sure it stays there.
|
||||
fn expect_ends(h: &mut Harness, ends: &Arc<Mutex<usize>>, want: usize, what: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while *ends.lock().unwrap() < want && Instant::now() < deadline {
|
||||
h.pump_for(Duration::from_millis(50));
|
||||
}
|
||||
// A late exit of an agent already counted must not count again.
|
||||
h.pump_for(Duration::from_millis(500));
|
||||
assert_eq!(*ends.lock().unwrap(), want, "{what}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ended_runs_once_for_an_agent_that_exits_by_itself() {
|
||||
let mut h = Harness::new();
|
||||
let ends = count_ends(&h);
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("EXIT 7");
|
||||
h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
|
||||
expect_ends(&mut h, &ends, 1, "one natural end");
|
||||
// Nothing is running now: a stop ends nothing more.
|
||||
h.manager.stop();
|
||||
expect_ends(&mut h, &ends, 1, "a stop with no running agent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ended_runs_once_for_a_stopped_agent_and_never_for_a_stop_of_none() {
|
||||
let mut h = Harness::new();
|
||||
let ends = count_ends(&h);
|
||||
h.manager.stop();
|
||||
expect_ends(&mut h, &ends, 0, "a stop before any start");
|
||||
h.start_and_wait_ready();
|
||||
h.manager.stop();
|
||||
expect_ends(&mut h, &ends, 1, "one stop of a running agent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ended_runs_once_for_the_old_agent_on_restart_and_on_a_fresh_start() {
|
||||
let mut h = Harness::new();
|
||||
let ends = count_ends(&h);
|
||||
h.start_and_wait_ready();
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
expect_ends(&mut h, &ends, 1, "the restarted agent's old one");
|
||||
h.manager
|
||||
.start_fresh("/plan2code next".to_string())
|
||||
.unwrap();
|
||||
h.wait_for_output(READY, 3);
|
||||
expect_ends(&mut h, &ends, 2, "the old agent a fresh start replaced");
|
||||
h.manager.stop();
|
||||
expect_ends(&mut h, &ends, 3, "the last agent, stopped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_agent_takes_the_consoles_it_announced_and_only_those() {
|
||||
use plan2code_app_lib::console_supervisor::{stop_announced_on_end, AnnouncedConsoles};
|
||||
|
||||
let mut h = Harness::new();
|
||||
let announced = Arc::new(AnnouncedConsoles::default());
|
||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let log = Arc::clone(&stopped);
|
||||
h.manager.set_ended(stop_announced_on_end(
|
||||
Arc::clone(&announced),
|
||||
|| None,
|
||||
move |sid| {
|
||||
log.lock().unwrap().push(sid.to_string());
|
||||
},
|
||||
));
|
||||
h.start_and_wait_ready();
|
||||
announced.record("s1");
|
||||
h.manager.stop();
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while stopped.lock().unwrap().is_empty() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
// Recorded after the end: it belongs to whatever comes next.
|
||||
announced.record("s2");
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
|
||||
assert_eq!(announced.take_all(), vec!["s2"], "s2 was never taken");
|
||||
}
|
||||
|
||||
/// Starts the harness's agent, has it leave a child that ignores the
|
||||
/// terminal's hangup in its process group, and returns that child's pid.
|
||||
#[cfg(unix)]
|
||||
fn start_with_stray(h: &mut Harness) -> u32 {
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("STRAY");
|
||||
h.wait_for_output("STRAY ", 1);
|
||||
let stray: u32 = h
|
||||
.seen
|
||||
.rsplit("STRAY ")
|
||||
.next()
|
||||
.unwrap()
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("the stray child's pid");
|
||||
assert!(process_alive(stray), "the stray child should be running");
|
||||
stray
|
||||
}
|
||||
|
||||
/// Waits out the hangup grace for `stray` to go, then kills it if it is
|
||||
/// still there, so a failing test leaves nothing running. True if it went.
|
||||
#[cfg(unix)]
|
||||
fn stray_gone(stray: u32) -> bool {
|
||||
use plan2code_app_lib::pty_host::HANGUP_GRACE;
|
||||
|
||||
let deadline = Instant::now() + HANGUP_GRACE + Duration::from_secs(2);
|
||||
while process_alive(stray) && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let gone = !process_alive(stray);
|
||||
if !gone {
|
||||
let _ = std::process::Command::new("kill")
|
||||
.args(["-9", &stray.to_string()])
|
||||
.status();
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// An agent that ends by itself leaves its process group alone: work the
|
||||
/// person asked it to leave running (a dev server it backgrounded) stays up,
|
||||
/// as it did before the app ended process groups at all.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_agent_that_exits_by_itself_leaves_its_process_group_running() {
|
||||
let mut h = Harness::new();
|
||||
let stray = start_with_stray(&mut h);
|
||||
h.type_line("EXIT 0");
|
||||
h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
|
||||
assert!(
|
||||
!stray_gone(stray),
|
||||
"the stray child was ended with an agent that exited by itself"
|
||||
);
|
||||
}
|
||||
|
||||
/// An agent the app stops (quit, a project switch) takes its process group
|
||||
/// with it, a child that ignores the terminal's hangup included.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_stopped_agent_takes_its_process_group_with_it() {
|
||||
let mut h = Harness::new();
|
||||
let stray = start_with_stray(&mut h);
|
||||
h.manager.stop();
|
||||
assert!(
|
||||
stray_gone(stray),
|
||||
"the stray child outlived its stopped agent"
|
||||
);
|
||||
}
|
||||
|
||||
/// A Restart or New Session replaces the agent, and its process group goes
|
||||
/// with the old one.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_replaced_agent_takes_its_process_group_with_it() {
|
||||
let mut h = Harness::new();
|
||||
let stray = start_with_stray(&mut h);
|
||||
h.manager.restart().unwrap();
|
||||
assert!(
|
||||
stray_gone(stray),
|
||||
"the stray child outlived its replaced agent"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
/// Quitting right after New Session: the replaced agent's grace is still
|
||||
/// running on a thread that would end with the app.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_stop_right_after_a_restart_waits_for_the_replaced_agents_process_group() {
|
||||
let mut h = Harness::new();
|
||||
let stray = start_with_stray(&mut h);
|
||||
h.manager.restart().expect("restart");
|
||||
h.manager.stop();
|
||||
let left = process_alive(stray);
|
||||
assert!(stray_gone(stray), "the stray child outlived its grace");
|
||||
assert!(!left, "the stray child was still there when stop returned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_start_with_no_launch_choice_is_refused() {
|
||||
let h = Harness::new();
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, ConsoleSupervisor};
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, stop_console_session, ConsoleSupervisor};
|
||||
|
||||
fn have_node() -> bool {
|
||||
Command::new("node")
|
||||
@@ -120,6 +120,38 @@ fn a_killed_console_is_dead_and_restarts() {
|
||||
sup.stop().expect("stop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_a_session_by_id_never_panics() {
|
||||
let Some(project) = setup() else { return };
|
||||
// The console has nothing to stop for a session it does not know: that is
|
||||
// not a failure.
|
||||
assert_eq!(
|
||||
stop_console_session(&repo_console_dir(), &project, "no-such-session"),
|
||||
Ok(())
|
||||
);
|
||||
// A folder with no console in it is.
|
||||
let empty = temp_dir("no-console");
|
||||
let error = stop_console_session(&empty, &project, "no-such-session")
|
||||
.expect_err("no console.mjs to run");
|
||||
assert!(error.starts_with("console stop failed"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_stopped_by_id_stops_answering() {
|
||||
let Some(project) = setup() else { return };
|
||||
let mut sup =
|
||||
ConsoleSupervisor::start(project.clone(), app_origin().to_string()).expect("start");
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
let sid = sup.session().sid.clone();
|
||||
|
||||
stop_console_session(&repo_console_dir(), &project, &sid).expect("stop by id");
|
||||
assert!(
|
||||
until_health(&sup, false),
|
||||
"the console still answered after stop_console_session()"
|
||||
);
|
||||
sup.stop().expect("a second stop is harmless");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_console_is_not_restarted() {
|
||||
let Some(project) = setup() else { return };
|
||||
|
||||
@@ -103,6 +103,102 @@ fn kill_ends_a_running_step() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A grandchild that ignores hangup is still in the agent's process group
|
||||
/// (portable-pty starts the agent under `setsid`), so `kill` must reach it
|
||||
/// through the group once the grace is up. An ordinary grandchild already dies
|
||||
/// with its shell, when the kernel hangs up the terminal, so it cannot show this.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() {
|
||||
use plan2code_app_lib::pty_host::HANGUP_GRACE;
|
||||
|
||||
let (host, pid) =
|
||||
start_sh_with_grandchild("trap '' HUP; sleep 300 & echo GRANDCHILD=$! END; wait");
|
||||
assert!(alive(pid), "the grandchild should be running before kill");
|
||||
|
||||
host.kill().unwrap();
|
||||
host.wait().unwrap();
|
||||
assert!(
|
||||
gone_within(pid, HANGUP_GRACE + Duration::from_secs(2)),
|
||||
"the hangup-ignoring grandchild outlived kill()"
|
||||
);
|
||||
}
|
||||
|
||||
/// An agent that ended by itself was never killed, so no grace thread of
|
||||
/// `kill`'s is there to finish its group: only `end_group` can end the
|
||||
/// grandchild that ignored the terminal's hangup.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn end_group_ends_what_a_command_that_exited_by_itself_left() {
|
||||
let (host, pid) = start_sh_with_grandchild(
|
||||
"(trap '' HUP; exec sleep 300) & echo GRANDCHILD=$! END; sleep 0.2; exit 0",
|
||||
);
|
||||
host.wait().unwrap();
|
||||
assert!(alive(pid), "the grandchild outlived its shell, as set up");
|
||||
|
||||
host.end_group();
|
||||
// Only the moment it takes the reaper to collect it.
|
||||
assert!(
|
||||
gone_within(pid, Duration::from_secs(1)),
|
||||
"the grandchild outlived end_group()"
|
||||
);
|
||||
}
|
||||
|
||||
/// `script` under `/bin/sh -c` on a pty; it must print `GRANDCHILD=<pid> END`.
|
||||
/// Returns the host and that pid.
|
||||
#[cfg(unix)]
|
||||
fn start_sh_with_grandchild(script: &str) -> (PtyHost, i32) {
|
||||
let (tx, rx) = channel();
|
||||
let host = PtyHost::start(
|
||||
StartOptions {
|
||||
program: "/bin/sh".to_string(),
|
||||
args: vec!["-c".to_string(), script.to_string()],
|
||||
env: vec![],
|
||||
cwd: None,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
},
|
||||
move |bytes| {
|
||||
let _ = tx.send(bytes);
|
||||
},
|
||||
)
|
||||
.expect("start the shell");
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, " END");
|
||||
let pid = seen
|
||||
.rsplit("GRANDCHILD=")
|
||||
.next()
|
||||
.unwrap()
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("the grandchild's pid");
|
||||
(host, pid)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn alive(pid: i32) -> bool {
|
||||
// SAFETY: signal 0 only asks whether the process exists.
|
||||
unsafe { libc::kill(pid, 0) == 0 }
|
||||
}
|
||||
|
||||
/// Whether `pid` is gone within `within`; killed on the way out either way,
|
||||
/// so a failing test leaves nothing behind.
|
||||
#[cfg(unix)]
|
||||
fn gone_within(pid: i32, within: Duration) -> bool {
|
||||
let deadline = Instant::now() + within;
|
||||
while alive(pid) && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let gone = !alive(pid);
|
||||
if !gone {
|
||||
// SAFETY: a process this test started.
|
||||
unsafe { libc::kill(pid, libc::SIGKILL) };
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real
|
||||
/// program (here, the fake agent) its grandchild. `kill` must end both, not
|
||||
/// just `cmd.exe` (Task 9.8).
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
//! The signals that end the app against the handler that turns them into its quit cleanup. A
|
||||
//! file of its own, so the handler lives in a test process of its own: without it, a signal below
|
||||
//! ends the whole process and the run fails. The handler installs once per process, so every
|
||||
//! other case runs in a child: this test binary again, running only `signal_child`.
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::io::{BufRead, BufReader, IsTerminal, Write};
|
||||
use std::os::fd::{FromRawFd, OwnedFd};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::sync::mpsc::channel;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::{log, term_signal};
|
||||
|
||||
/// Names the case, and is set only in the child process a test starts.
|
||||
const CHILD: &str = "P2C_TERM_SIGNAL_CHILD";
|
||||
|
||||
/// The child's exit codes: its cleanup ran to the end, or it did not when it should have.
|
||||
const CLEANED: i32 = 0;
|
||||
const NOT_CLEANED: i32 = 3;
|
||||
|
||||
#[test]
|
||||
fn a_sigterm_runs_the_cleanup_instead_of_ending_the_process() {
|
||||
let (tx, rx) = channel();
|
||||
term_signal::on_terminate(move || {
|
||||
let _ = tx.send(());
|
||||
})
|
||||
.expect("the handler installs");
|
||||
raise(libc::SIGTERM);
|
||||
rx.recv_timeout(Duration::from_secs(5))
|
||||
.expect("the cleanup ran after SIGTERM");
|
||||
// A second install is refused: one signal, one cleanup.
|
||||
assert!(term_signal::on_terminate(|| {}).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_c_and_a_closed_terminal_run_the_cleanup_too() {
|
||||
for case in ["sigint", "sighup"] {
|
||||
let status = outcome(child(case).spawn().expect("the child starts"));
|
||||
assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_signal_ends_the_app_while_its_cleanup_still_runs() {
|
||||
// A cleanup that stalls must not leave a plain `kill` or Ctrl+C unable to
|
||||
// end the app, whichever signal started it.
|
||||
for (case, ends_by) in [
|
||||
("sigterm twice", libc::SIGTERM),
|
||||
("sigint twice", libc::SIGINT),
|
||||
("sighup then sigterm", libc::SIGTERM),
|
||||
] {
|
||||
let status = outcome(child(case).spawn().expect("the child starts"));
|
||||
assert_eq!(status.signal(), Some(ends_by), "{case}: {status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_sighup_lets_the_cleanup_finish() {
|
||||
// Closing a terminal can send it twice at once: zsh passes it on to the
|
||||
// program in front, and the terminal's own hangup sends it again.
|
||||
let status = outcome(child("sighup twice").spawn().expect("the child starts"));
|
||||
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_the_app_was_started_with_ignored_stays_ignored() {
|
||||
// `nohup` starts a program with SIGHUP ignored, to outlive its terminal.
|
||||
let status = outcome(child("ignored sighup").spawn().expect("the child starts"));
|
||||
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_the_cleanup_runs_outlives_a_repeated_sighup() {
|
||||
// The cleanup stops consoles by running `node`, which the second SIGHUP of
|
||||
// a closed terminal would end before it stopped anything.
|
||||
let status = outcome(child("command").spawn().expect("the child starts"));
|
||||
assert_eq!(status.code(), Some(CLEANED), "{status:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cleanup_that_logs_after_its_terminal_is_gone_still_finishes() {
|
||||
for case in ["sighup, closed terminal", "sigterm, closed terminal"] {
|
||||
logs_to_a_closed_terminal(case);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the child on a terminal of its own, and closes that terminal once the
|
||||
/// child has its handler.
|
||||
fn logs_to_a_closed_terminal(case: &str) {
|
||||
let (mut master, mut slave) = (-1, -1);
|
||||
// SAFETY: openpty fills the two descriptors; the name and settings are optional.
|
||||
let opened = unsafe {
|
||||
libc::openpty(
|
||||
&mut master,
|
||||
&mut slave,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
assert_eq!(opened, 0, "openpty: {}", std::io::Error::last_os_error());
|
||||
// SAFETY: both descriptors were just opened, and nothing else owns them. Close-on-exec keeps
|
||||
// the terminal's other end out of the child, which would hold it open.
|
||||
let (master, slave) = unsafe {
|
||||
libc::fcntl(master, libc::F_SETFD, libc::FD_CLOEXEC);
|
||||
(OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave))
|
||||
};
|
||||
let mut child = child(case)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::from(slave))
|
||||
.spawn()
|
||||
.expect("the child starts");
|
||||
let stdout = child.stdout.take().expect("the child's stdout is piped");
|
||||
let ready = BufReader::new(stdout)
|
||||
.lines()
|
||||
.map_while(Result::ok)
|
||||
.any(|line| line.ends_with("ready"));
|
||||
assert!(ready, "the child installed the handler");
|
||||
drop(master);
|
||||
let status = outcome(child);
|
||||
assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}");
|
||||
}
|
||||
|
||||
fn raise(signal: libc::c_int) {
|
||||
// SAFETY: raise only sends this process a signal.
|
||||
assert_eq!(unsafe { libc::raise(signal) }, 0);
|
||||
}
|
||||
|
||||
/// This test binary again, running only `signal_child` on `case`.
|
||||
fn child(case: &str) -> Command {
|
||||
let mut command = Command::new(std::env::current_exe().expect("the test binary"));
|
||||
command
|
||||
.args(["--exact", "signal_child", "--test-threads=1", "--nocapture"])
|
||||
.env(CHILD, case)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
command
|
||||
}
|
||||
|
||||
/// How the child ended, within 30 s.
|
||||
fn outcome(mut child: Child) -> ExitStatus {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().expect("the child can be waited on") {
|
||||
return status;
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
panic!("the child neither ended nor exited within 30 s");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
/// Not a check on its own: the child process of the tests above. Run any other
|
||||
/// way, it returns at once.
|
||||
#[test]
|
||||
fn signal_child() {
|
||||
let Some(case) = std::env::var_os(CHILD) else {
|
||||
return;
|
||||
};
|
||||
// A signal this run was started with ignored (`nohup`, a script's `&`)
|
||||
// would stay ignored, and no case below means that one.
|
||||
for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
|
||||
// SAFETY: putting a signal's default action back installs no handler.
|
||||
unsafe { libc::signal(signal, libc::SIG_DFL) };
|
||||
}
|
||||
match case.to_str().expect("a case name") {
|
||||
"sigint" => cleans_up_after(&[libc::SIGINT]),
|
||||
"sighup" => cleans_up_after(&[libc::SIGHUP]),
|
||||
"sighup twice" => cleans_up_after(&[libc::SIGHUP, libc::SIGHUP]),
|
||||
"sigterm twice" => ends_during_the_cleanup(libc::SIGTERM, libc::SIGTERM),
|
||||
"sigint twice" => ends_during_the_cleanup(libc::SIGINT, libc::SIGINT),
|
||||
"sighup then sigterm" => ends_during_the_cleanup(libc::SIGHUP, libc::SIGTERM),
|
||||
"ignored sighup" => ignores_sighup(),
|
||||
"command" => runs_a_command_through_a_sighup(),
|
||||
"sighup, closed terminal" => logs_after_its_terminal_closed(libc::SIGHUP),
|
||||
"sigterm, closed terminal" => logs_after_its_terminal_closed(libc::SIGTERM),
|
||||
other => panic!("no such case: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cleanup takes a moment, so a signal that ends the app would cut it short.
|
||||
fn cleans_up_after(signals: &[libc::c_int]) {
|
||||
term_signal::on_terminate(|| {
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
std::process::exit(CLEANED);
|
||||
})
|
||||
.expect("the handler installs");
|
||||
for signal in signals {
|
||||
raise(*signal);
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
std::process::exit(NOT_CLEANED);
|
||||
}
|
||||
|
||||
fn ends_during_the_cleanup(first: libc::c_int, second: libc::c_int) {
|
||||
let (tx, rx) = channel();
|
||||
term_signal::on_terminate(move || {
|
||||
let _ = tx.send(());
|
||||
// A cleanup that never finishes.
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(60));
|
||||
}
|
||||
})
|
||||
.expect("the handler installs");
|
||||
raise(first);
|
||||
rx.recv_timeout(Duration::from_secs(5))
|
||||
.expect("the first signal started the cleanup");
|
||||
raise(second);
|
||||
// Still running: the second signal was swallowed.
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
std::process::exit(NOT_CLEANED);
|
||||
}
|
||||
|
||||
fn ignores_sighup() {
|
||||
// SAFETY: ignoring a signal installs no handler.
|
||||
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
|
||||
term_signal::on_terminate(|| std::process::exit(NOT_CLEANED)).expect("the handler installs");
|
||||
raise(libc::SIGHUP);
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
std::process::exit(CLEANED);
|
||||
}
|
||||
|
||||
fn runs_a_command_through_a_sighup() {
|
||||
term_signal::on_terminate(|| {
|
||||
let status = Command::new("/bin/sh")
|
||||
.args(["-c", "kill -HUP $$; exit 0"])
|
||||
.status()
|
||||
.expect("sh runs");
|
||||
std::process::exit(if status.success() {
|
||||
CLEANED
|
||||
} else {
|
||||
NOT_CLEANED
|
||||
});
|
||||
})
|
||||
.expect("the handler installs");
|
||||
raise(libc::SIGHUP);
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
std::process::exit(NOT_CLEANED);
|
||||
}
|
||||
|
||||
fn logs_after_its_terminal_closed(signal: libc::c_int) {
|
||||
assert!(std::io::stderr().is_terminal(), "stderr is a terminal");
|
||||
term_signal::on_terminate(|| {
|
||||
log::line("a line from the cleanup");
|
||||
std::process::exit(CLEANED);
|
||||
})
|
||||
.expect("the handler installs");
|
||||
println!("ready");
|
||||
// Closed once a write fails: macOS reports neither a hangup nor a lost terminal here.
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while std::io::stderr().write_all(b".").is_ok() {
|
||||
assert!(Instant::now() < deadline, "the terminal never closed");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
raise(signal);
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
std::process::exit(NOT_CLEANED);
|
||||
}
|
||||
+31
-2
@@ -972,6 +972,29 @@ let helloTimer = null;
|
||||
// Nothing has shown here yet: no agent has opened the dashboard. No polling,
|
||||
// no "reconnect" button makes sense until that first page lands.
|
||||
let consoleKnown = false;
|
||||
// Which console the checks below ask about. A project switch moves it on, so
|
||||
// an answer that comes back afterward is about a console that is gone.
|
||||
let consoleEpoch = 0;
|
||||
|
||||
// The project moved on, and its console was stopped on purpose: nothing is
|
||||
// known here again until the new agent opens a page. Left known, the next
|
||||
// poll found no console and put "The console stopped" over the new agent's
|
||||
// start, or the launch card; left in the frame, the old page showed its "Lost
|
||||
// contact" around it.
|
||||
function forgetConsole() {
|
||||
consoleEpoch += 1;
|
||||
consoleKnown = false;
|
||||
clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
clearTimeout(helloTimer);
|
||||
currentUrl = null;
|
||||
frameReady = false;
|
||||
// As for any page going away (loadFrame): its taskbar dot and its game go too.
|
||||
clearAttention();
|
||||
setGameFull(false);
|
||||
frame.src = 'about:blank';
|
||||
markConsoleAlive();
|
||||
}
|
||||
|
||||
function loadFrame(url) {
|
||||
currentUrl = url;
|
||||
@@ -1252,6 +1275,7 @@ setWindowTheme(document.documentElement.getAttribute('data-theme') === 'light' ?
|
||||
// No hello in time: ask the console why, and say so with a way forward.
|
||||
async function onNoHello() {
|
||||
if (frameReady || !consoleKnown || restarting) return;
|
||||
const epoch = consoleEpoch;
|
||||
// A page that does not answer cannot say it is done needing the person.
|
||||
clearAttention();
|
||||
// The next phase's console is on its way; the poll says so instead. Look
|
||||
@@ -1267,6 +1291,7 @@ async function onNoHello() {
|
||||
} catch {
|
||||
// The status check itself failed; treat it as a console that is not answering.
|
||||
}
|
||||
if (epoch !== consoleEpoch) return;
|
||||
if (!status || status.state !== 'running') {
|
||||
showState('The console stopped, so the page could not show.', 'Reconnect the console', reconnectConsole);
|
||||
} else {
|
||||
@@ -1434,12 +1459,15 @@ let pollTimer = null;
|
||||
// on its own session. The app never opens a dashboard on its own (the agent
|
||||
// does, by running the skill), so there is nothing to start before that.
|
||||
async function reconnectConsole() {
|
||||
const epoch = consoleEpoch;
|
||||
markConsoleAlive();
|
||||
showState('Reconnecting to the console...');
|
||||
try {
|
||||
const info = await invoke('console_start');
|
||||
if (epoch !== consoleEpoch) return;
|
||||
loadFrame(info.url);
|
||||
} catch (error) {
|
||||
if (epoch !== consoleEpoch) return;
|
||||
showErrorState(error, 'reach the console', 'Retry', reconnectConsole);
|
||||
// An old console cannot be framed: the fix is the skills update, so offer it.
|
||||
if (String(error).includes('too old')) setVersionState({ kind: 'too-old' });
|
||||
@@ -1453,8 +1481,10 @@ const RECONNECT_LIMIT = 3;
|
||||
let reconnects = 0;
|
||||
|
||||
async function pollConsole() {
|
||||
const epoch = consoleEpoch;
|
||||
try {
|
||||
const status = await invoke('console_status');
|
||||
if (epoch !== consoleEpoch) return;
|
||||
if (status.state === 'running') {
|
||||
markConsoleAlive();
|
||||
return;
|
||||
@@ -2115,8 +2145,7 @@ async function doChangeProject(prior = null) {
|
||||
setProjectDir(dir);
|
||||
if (appState) appState.projectDir = dir;
|
||||
restarting = false;
|
||||
currentUrl = null;
|
||||
frameReady = false;
|
||||
forgetConsole();
|
||||
// An agent was in use: start the same one (agent, model, effort and
|
||||
// permission mode) in the new folder, rather than leaving the launch card
|
||||
// and an empty terminal. Nothing to carry over: the launch card as before.
|
||||
|
||||
@@ -774,7 +774,10 @@ export function shortcutFromMessage(data) {
|
||||
* What a key press does in the terminal's clipboard handling: "copy" (Ctrl+Shift+C, Cmd+C, and
|
||||
* Ctrl+C while text is selected, the Windows Terminal rule: with nothing selected Ctrl+C is the
|
||||
* interrupt and returns null), "paste" (Ctrl+V, Ctrl+Shift+V, Cmd+V), or null. With `mac`, a plain
|
||||
* Ctrl+C is always the interrupt, as in every macOS terminal: copy there is Cmd+C.
|
||||
* Ctrl+C is always the interrupt, as in every macOS terminal: copy there is Cmd+C. Ctrl+V belongs to
|
||||
* the agent there too (Claude Code pastes an image with it), and Cmd+V returns null as well: it is
|
||||
* left to the webview's own paste event, which xterm takes as one paste, because reading the
|
||||
* clipboard from script makes WebKit ask with a Paste menu before the text arrives.
|
||||
*/
|
||||
export function clipboardAction(event, hasSelection, { mac = false } = {}) {
|
||||
if (!event || event.altKey) return null;
|
||||
@@ -784,7 +787,7 @@ export function clipboardAction(event, hasSelection, { mac = false } = {}) {
|
||||
if (event.ctrlKey && !event.metaKey) return event.shiftKey || (hasSelection && !mac) ? 'copy' : null;
|
||||
return null;
|
||||
}
|
||||
if (key === 'v' && (event.ctrlKey || event.metaKey)) return 'paste';
|
||||
if (key === 'v' && !mac && (event.ctrlKey || event.metaKey)) return 'paste';
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ export async function mountTerminal(container, { onInput, onResize, onFontSize,
|
||||
// Ctrl+C copies while text is selected and is the interrupt otherwise (the Windows Terminal
|
||||
// rule; on a Mac it is always the interrupt); Ctrl+Shift+C and Cmd+C always copy.
|
||||
// preventDefault on the paste keys: the browser's own paste event would otherwise reach the
|
||||
// terminal a second time.
|
||||
// terminal a second time. On a Mac no key is a paste key here: Cmd+V is that own paste event.
|
||||
const action = clipboardAction(event, term.hasSelection(), { mac: IS_MAC });
|
||||
if (action === 'copy') {
|
||||
copySelection();
|
||||
|
||||
@@ -540,6 +540,31 @@ test("app.js refills the reconnect budget on a new page and brings the page back
|
||||
assert.match(app.slice(app.indexOf("async function showLoopEnd"), app.indexOf("function applyLoopState")), /reconnectConsole\(\)/);
|
||||
});
|
||||
|
||||
test("app.js forgets the old project's console on a project switch, so no check of it covers the new agent's start or the launch card", () => {
|
||||
const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8");
|
||||
const at = app.indexOf("function forgetConsole");
|
||||
assert.ok(at > 0, "left known, the old console's poll put \"The console stopped\" over the new agent's start, or the launch card, five seconds after a switch");
|
||||
const forget = app.slice(at, app.indexOf("\n}\n", at));
|
||||
assert.match(forget, /consoleKnown = false/, "nothing is known again until the new agent opens a page");
|
||||
assert.match(forget, /clearInterval\(pollTimer\);\s*pollTimer = null/, "the poll stops, and showAnnounced can start it again");
|
||||
assert.match(forget, /clearTimeout\(helloTimer\)/, "a hello still awaited from the old page is not waited for");
|
||||
assert.match(forget, /markConsoleAlive\(\)/, "the bar drops a Console stopped it was showing");
|
||||
assert.match(forget, /frame\.src = 'about:blank'/, "the stopped console's page leaves the frame, or its Lost contact shows around the launch card");
|
||||
assert.match(forget, /clearAttention\(\);\s*setGameFull\(false\)/, "and takes its taskbar dot and its full-screen game with it, as loadFrame does");
|
||||
assert.match(forget, /consoleEpoch \+= 1/, "a check already under way can tell the project moved on");
|
||||
const change = app.slice(app.indexOf("async function doChangeProject"), app.indexOf("function changeProject"));
|
||||
assert.match(change, /forgetConsole\(\);[^}]*if \(prior\) await startPriorAgent\(prior\);\s*else afterProjectKnown\(\)/s, "forgotten before the new agent starts or the launch card shows");
|
||||
// Each check that waits on the app answers for the console it asked about.
|
||||
for (const name of ["onNoHello", "reconnectConsole", "pollConsole"]) {
|
||||
const from = app.indexOf(`async function ${name}`);
|
||||
const body = app.slice(from, app.indexOf("\n}\n", from));
|
||||
assert.match(body, /const epoch = consoleEpoch;/, `${name} notes which console it asks about`);
|
||||
const awaits = body.split("await invoke(").length - 1;
|
||||
const guards = body.split("if (epoch !== consoleEpoch) return;").length - 1;
|
||||
assert.ok(guards >= awaits, `${name} drops an answer that comes back after a switch (${guards} checks for ${awaits} waits)`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the window title says a loop is running, and when it needs the person", () => {
|
||||
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Build" }), "Loop: Phase 2 of 7 - lunch");
|
||||
assert.equal(loopWindowTitle("C:/git/lunch", { phase: 2, phases: 7, step: "Waiting on you" }), "Loop needs you: Phase 2 - lunch");
|
||||
@@ -1383,6 +1408,36 @@ test("clipboardAction: Ctrl+C copies only with a selection (else it is the inter
|
||||
assert.equal(clipboardAction(null, true), null);
|
||||
});
|
||||
|
||||
test("clipboardAction on a Mac: Ctrl+V goes to the agent, Cmd+V is left to the webview's own paste", () => {
|
||||
const ev = (key, mods = {}) => ({ key, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...mods });
|
||||
assert.equal(clipboardAction(ev("v", { ctrlKey: true }), false, { mac: true }), null, "xterm sends \\x16 to the agent (Claude Code's image paste)");
|
||||
assert.equal(clipboardAction(ev("V", { ctrlKey: true, shiftKey: true }), false, { mac: true }), null);
|
||||
assert.equal(clipboardAction(ev("v", { metaKey: true }), false, { mac: true }), null, "a script clipboard read makes WebKit ask with a Paste menu first");
|
||||
});
|
||||
|
||||
test("clipboardAction off a Mac: every key decides exactly as before the Mac rule", () => {
|
||||
// The rule as it was before Ctrl+V was left to the agent on a Mac.
|
||||
const before = (event, hasSelection) => {
|
||||
if (event.altKey) return null;
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === "c") {
|
||||
if (event.metaKey && !event.ctrlKey) return "copy";
|
||||
if (event.ctrlKey && !event.metaKey) return event.shiftKey || hasSelection ? "copy" : null;
|
||||
return null;
|
||||
}
|
||||
if (key === "v" && (event.ctrlKey || event.metaKey)) return "paste";
|
||||
return null;
|
||||
};
|
||||
for (const key of ["c", "C", "v", "V", "x"]) {
|
||||
for (let bits = 0; bits < 16; bits++) {
|
||||
const event = { key, ctrlKey: Boolean(bits & 1), metaKey: Boolean(bits & 2), shiftKey: Boolean(bits & 4), altKey: Boolean(bits & 8) };
|
||||
for (const sel of [true, false]) {
|
||||
assert.equal(clipboardAction(event, sel), before(event, sel), `${key} ${JSON.stringify(event)} selection ${sel}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("the terminal pastes once and in brackets, copies on select only by preference, and has a Copy / Paste / Clear menu", () => {
|
||||
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
||||
assert.match(term, /term\.paste\(text\)/, "bracketed paste, not onInput(text)");
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// Tests for plan2code-app/scripts/smoke-agent.mjs, the stand-in agent CI's
|
||||
// macOS smoke run starts in place of a real agent CLI. Run with:
|
||||
// node --test scripts/test-app-smoke-agent.mjs
|
||||
//
|
||||
// The stand-in has one job: open a real web console the way an agent would,
|
||||
// so the app's dashboard frame has something to connect to. This runs it
|
||||
// outside the app, under a throwaway console home, and checks a live session
|
||||
// appears and the stand-in ends when its input closes.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const AGENT = path.join(HERE, "../plan2code-app/scripts/smoke-agent.mjs");
|
||||
const CONSOLE_DIR = path.join(HERE, "../src/web-console");
|
||||
|
||||
// The desktop app's own variables would have the console announce itself to
|
||||
// a live window. Deleted from the spawned environment, never inherited.
|
||||
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_APP_VERSION", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_CONSOLE_SID"];
|
||||
|
||||
function outsideAppEnv(extra) {
|
||||
const env = { ...process.env, ...extra };
|
||||
for (const name of APP_VARS) delete env[name];
|
||||
return env;
|
||||
}
|
||||
|
||||
// Every session handle under a console home: runtime/<project hash>/<sid>.json.
|
||||
function handles(consoleHome) {
|
||||
const runtime = path.join(consoleHome, "runtime");
|
||||
if (!fs.existsSync(runtime)) return [];
|
||||
return fs.readdirSync(runtime).flatMap((hash) =>
|
||||
fs
|
||||
.readdirSync(path.join(runtime, hash))
|
||||
.filter((name) => name.endsWith(".json"))
|
||||
.map((name) => JSON.parse(fs.readFileSync(path.join(runtime, hash, name), "utf8")))
|
||||
);
|
||||
}
|
||||
|
||||
async function waitFor(check, ms) {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) {
|
||||
const value = check();
|
||||
if (value) return value;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
return check();
|
||||
}
|
||||
|
||||
function pidAlive(pid) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return err.code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
test("smoke agent: is an executable Node script with no dependencies", { skip: process.platform === "win32" }, () => {
|
||||
const source = fs.readFileSync(AGENT, "utf8");
|
||||
assert.ok(source.startsWith("#!/usr/bin/env node\n"), "starts with a node shebang");
|
||||
assert.ok((fs.statSync(AGENT).mode & 0o111) !== 0, "has its executable bits set");
|
||||
for (const [, name] of source.matchAll(/from\s+["']([^"']+)["']/g)) {
|
||||
assert.ok(name.startsWith("node:"), `imports only Node built-ins, not ${name}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("smoke agent: opens a live dashboard session, then ends when its input closes", async (t) => {
|
||||
const consoleHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-home-"));
|
||||
const project = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-project-"));
|
||||
const env = outsideAppEnv({ PLAN2CODE_CONSOLE_HOME: consoleHome, PLAN2CODE_NO_BROWSER: "1", PLAN2CODE_CONSOLE_DIR: CONSOLE_DIR });
|
||||
let agent;
|
||||
t.after(() => {
|
||||
if (agent && agent.exitCode === null) agent.kill("SIGKILL");
|
||||
// --all stops this folder's sessions, so it runs from the project, under the same home.
|
||||
spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, timeout: 15000 });
|
||||
fs.rmSync(consoleHome, { recursive: true, force: true });
|
||||
fs.rmSync(project, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
agent = spawn(process.execPath, [AGENT, "--some-agent-flag"], { cwd: project, env, stdio: ["pipe", "pipe", "pipe"] });
|
||||
let output = "";
|
||||
agent.stdout.on("data", (chunk) => (output += chunk));
|
||||
agent.stderr.on("data", (chunk) => (output += chunk));
|
||||
const exited = new Promise((resolve) => agent.on("exit", (code) => resolve(code)));
|
||||
|
||||
const handle = await waitFor(() => handles(consoleHome)[0], 20000);
|
||||
assert.ok(handle, `a session appeared under the console home; agent said: ${output}`);
|
||||
const health = await (await fetch(`http://127.0.0.1:${handle.port}/health`)).json();
|
||||
assert.equal(health.ok, true);
|
||||
assert.equal(health.sid, handle.sid, "the port answers for this session");
|
||||
const state = JSON.parse(fs.readFileSync(path.join(consoleHome, "sessions", handle.sid, "state.json"), "utf8"));
|
||||
assert.equal(state.workflow, "dashboard");
|
||||
|
||||
// Still running until its input closes, like an agent waiting for the person.
|
||||
assert.equal(agent.exitCode, null, "the stand-in waits on its input");
|
||||
agent.stdin.end();
|
||||
const code = await Promise.race([exited, new Promise((resolve) => setTimeout(() => resolve("timeout"), 10000))]);
|
||||
assert.equal(code, 0, `the stand-in exits cleanly once its input closes; agent said: ${output}`);
|
||||
|
||||
// The console outlives the agent (it is detached), so the stop below is what ends it.
|
||||
const stop = spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, encoding: "utf8", timeout: 15000 });
|
||||
assert.equal(stop.status, 0, stop.stderr);
|
||||
assert.equal(await waitFor(() => !pidAlive(handle.pid), 10000), true, "the console server is gone after stop --all");
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
// Tests for plan2code-app/scripts/smoke-frame.mjs, the check CI's macOS smoke
|
||||
// run uses to prove the app's dashboard frame connected to the console. Run with:
|
||||
// node --test scripts/test-app-smoke-frame.mjs
|
||||
//
|
||||
// No app and no real console: a session handle under a throwaway console home
|
||||
// points at a tiny local server whose /health answers with a browser count the
|
||||
// test controls.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const SCRIPT = path.join(HERE, "../plan2code-app/scripts/smoke-frame.mjs");
|
||||
const SID = "20261108-000000-abcdef";
|
||||
|
||||
// A /health server answering with `browsers()` for this session.
|
||||
async function healthServer(browsers) {
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.url !== "/health") return res.writeHead(404).end();
|
||||
res.writeHead(200, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify({ ok: true, sid: SID, browsers: browsers(), rev: 1, phase: "unknown" }));
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
return server;
|
||||
}
|
||||
|
||||
// A console home holding one session handle, the way server.mjs writes it.
|
||||
function consoleHomeFor(port) {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-frame-home-"));
|
||||
const dir = path.join(home, "runtime", "0123456789abcdef");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, `${SID}.json`), JSON.stringify({ v: 1, sid: SID, pid: process.pid, port, url: `http://127.0.0.1:${port}/` }));
|
||||
return home;
|
||||
}
|
||||
|
||||
function run(args, env = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, [SCRIPT, ...args], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
|
||||
let output = "";
|
||||
child.stdout.on("data", (chunk) => (output += chunk));
|
||||
child.stderr.on("data", (chunk) => (output += chunk));
|
||||
child.on("exit", (code) => resolve({ code, output }));
|
||||
});
|
||||
}
|
||||
|
||||
test("smoke frame: passes once /health counts a browser", async (t) => {
|
||||
let asked = 0;
|
||||
const server = await healthServer(() => (++asked < 3 ? 0 : 1));
|
||||
const home = consoleHomeFor(server.address().port);
|
||||
t.after(() => {
|
||||
server.close();
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const { code, output } = await run([home, "--timeout-ms", "10000"]);
|
||||
assert.equal(code, 0, output);
|
||||
assert.ok(asked >= 3, "it kept polling while no browser was connected");
|
||||
assert.match(output, /connected/);
|
||||
});
|
||||
|
||||
test("smoke frame: fails with the last answer printed when no browser ever connects", async (t) => {
|
||||
const server = await healthServer(() => 0);
|
||||
const home = consoleHomeFor(server.address().port);
|
||||
t.after(() => {
|
||||
server.close();
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const { code, output } = await run([home, "--timeout-ms", "1500"]);
|
||||
assert.equal(code, 1, output);
|
||||
assert.match(output, /"browsers":0/, "the last /health answer is printed");
|
||||
});
|
||||
|
||||
test("smoke frame: fails when no session ever appears, and reads the home from PLAN2CODE_CONSOLE_HOME", async (t) => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-frame-empty-"));
|
||||
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
|
||||
|
||||
const { code, output } = await run(["--timeout-ms", "1000"], { PLAN2CODE_CONSOLE_HOME: home });
|
||||
assert.equal(code, 1, output);
|
||||
assert.match(output, /no session/i);
|
||||
});
|
||||
|
||||
test("smoke frame: refuses to run with no console home", async () => {
|
||||
const env = { ...process.env };
|
||||
delete env.PLAN2CODE_CONSOLE_HOME;
|
||||
const result = await new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, [SCRIPT], { env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
let output = "";
|
||||
child.stderr.on("data", (chunk) => (output += chunk));
|
||||
child.on("exit", (code) => resolve({ code, output }));
|
||||
});
|
||||
assert.equal(result.code, 2, result.output);
|
||||
});
|
||||
|
||||
test("smoke frame: the CI step keeps the console from opening a browser, so only the frame can count", () => {
|
||||
// Inside the app the console opens no browser of its own. If the app's signal
|
||||
// to it were lost, `open` would start the runner's browser, which signs in by
|
||||
// cookie and would pass this check with the frame dead.
|
||||
const workflow = fs.readFileSync(path.join(HERE, "../.github/workflows/app.yml"), "utf8");
|
||||
const start = workflow.indexOf("- name: Smoke-test the dashboard frame connects (macOS)");
|
||||
assert.ok(start >= 0, "the frame step is there");
|
||||
// The step runs to the blank line that ends it.
|
||||
const end = workflow.indexOf("\n\n", start);
|
||||
const step = workflow.slice(start, end === -1 ? undefined : end);
|
||||
assert.match(step, /\n\s+export PLAN2CODE_NO_BROWSER=1\n/, step);
|
||||
assert.ok(step.indexOf("PLAN2CODE_NO_BROWSER") < step.indexOf("target/release/plan2code-app"), "set before the app starts");
|
||||
});
|
||||
@@ -42,7 +42,7 @@ export const BUDGETS = {
|
||||
"pathfinder.md": 2622, // raised by the UI prototype line's bytes only
|
||||
"plan.md": 1023, // raised by the UI prototype line's bytes only
|
||||
"pr-prep.md": 4500,
|
||||
"quick-task.md": 5194, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's and the Changes tab lines' bytes only
|
||||
"quick-task.md": 5238, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's, the Changes tab lines' and the post-build cards' nothingYet bytes only
|
||||
"review-loop.md": 4000, // its written size (3,564 bytes) plus 10 percent, rounded up to the next 100
|
||||
"review.md": 1190, // raised by the lessons card line's bytes, then the Review Loop pointer line's bytes only
|
||||
"revise-plan.md": 1422, // raised by the UI prototype line's bytes only
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"test-agent-lookup.mjs",
|
||||
"test-agents-file.mjs",
|
||||
"test-app-meter.mjs",
|
||||
"test-app-smoke-frame.mjs",
|
||||
"test-browser-helper.mjs",
|
||||
"test-check-console-openings.mjs",
|
||||
"test-check-doc-size.mjs",
|
||||
@@ -43,6 +44,7 @@
|
||||
"test-web-console-diff-parse.mjs",
|
||||
"test-web-console-git-board.mjs",
|
||||
"test-web-console-prototypes.mjs",
|
||||
"test-web-console-relative-urls.mjs",
|
||||
"test-web-console-send-state.mjs",
|
||||
"test-web-console-shape.mjs",
|
||||
"test-web-console-skills.mjs",
|
||||
@@ -52,6 +54,7 @@
|
||||
"test-web-console-tones.mjs"
|
||||
],
|
||||
"skipFast": [
|
||||
"test-app-smoke-agent.mjs",
|
||||
"test-console-stub.mjs",
|
||||
"test-console-wire-budgets.mjs",
|
||||
"test-fast.mjs",
|
||||
@@ -119,6 +122,7 @@
|
||||
"test-web-console-page-cards.mjs",
|
||||
"test-web-console-page-changes.mjs",
|
||||
"test-web-console-page-dashboard.mjs",
|
||||
"test-web-console-page-frame.mjs",
|
||||
"test-web-console-page-layout.mjs",
|
||||
"test-web-console-page-git.mjs",
|
||||
"test-web-console-page-help.mjs",
|
||||
|
||||
@@ -948,6 +948,34 @@ test("launcher app: modelFrom reads --model, --model= and Codex's -m", () => {
|
||||
assert.equal(modelFrom(["--verbose"], "claude"), null);
|
||||
});
|
||||
|
||||
// osascript exits 1 both on a cancel and on a failure; only the cancel has -128.
|
||||
test("launcher picker: on macOS an exit 1 is a cancel only with osascript's (-128); elsewhere an exit 1 with nothing picked stays a cancel", () => {
|
||||
const { pickerCancelled } = require(LAUNCHER);
|
||||
const cancel = "0:17: execution error: User canceled. (-128)\n";
|
||||
const failure = "0:4: execution error: The variable this is not defined. (-2753)\n";
|
||||
assert.equal(pickerCancelled(1, "", cancel, "darwin"), true);
|
||||
assert.equal(pickerCancelled(1, "", failure, "darwin"), false, "a failure falls through to the typed prompt");
|
||||
assert.equal(pickerCancelled(1, "", "", "darwin"), false);
|
||||
assert.equal(pickerCancelled(1, null, null, "darwin"), false);
|
||||
for (const platform of ["linux", "win32"]) {
|
||||
assert.equal(pickerCancelled(1, "", "", platform), true, platform);
|
||||
assert.equal(pickerCancelled(1, "", "Gtk-WARNING\n", platform), true, platform);
|
||||
assert.equal(pickerCancelled(3, "", "", platform), false, platform);
|
||||
}
|
||||
for (const platform of ["darwin", "linux", "win32"]) {
|
||||
assert.equal(pickerCancelled(0, "", "", platform), true, `${platform}: exit 0 with nothing picked`);
|
||||
assert.equal(pickerCancelled(0, "/some/folder\n", "", platform), false, `${platform}: a pick`);
|
||||
assert.equal(pickerCancelled(1, "/some/folder\n", cancel, platform), false, `${platform}: something printed is no cancel`);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher picker: pickFolder decides a cancel through pickerCancelled", () => {
|
||||
const source = fs.readFileSync(require.resolve(LAUNCHER), "utf8");
|
||||
const body = source.slice(source.indexOf("async function pickFolder"), source.indexOf("async function projectCwd"));
|
||||
assert.match(body, /pickerCancelled\(result\.status, result\.stdout, result\.stderr\)/);
|
||||
assert.doesNotMatch(body, /result\.status === 1/, "no cancel rule left beside it");
|
||||
});
|
||||
|
||||
test("launcher app: an app that starts and then exits with a failure falls back to the terminal flow", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
|
||||
@@ -52,6 +52,6 @@ test("it asks once per page", async () => {
|
||||
await load();
|
||||
await load();
|
||||
assert.equal(calls.length, 1);
|
||||
assert.deepEqual(calls[0], ["/spec-carry", "POST"]);
|
||||
assert.deepEqual(calls[0], ["spec-carry", "POST"]);
|
||||
assert.equal(typeof loadSpecCarry, "function");
|
||||
});
|
||||
@@ -280,7 +280,7 @@ test("the list names Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Sta
|
||||
assert.equal(ACTIVITIES[12].title, "Flock Dash");
|
||||
for (const a of ACTIVITIES) {
|
||||
assert.ok(Object.isFrozen(a), `${a.id} is frozen`);
|
||||
assert.equal(a.module, a.id === "ghoul" ? "/activities/ghoul-rush/ghoul.js" : `/activities/${a.id}.js`);
|
||||
assert.equal(a.module, a.id === "ghoul" ? "activities/ghoul-rush/ghoul.js" : `activities/${a.id}.js`);
|
||||
assert.equal(typeof a.title, "string");
|
||||
assert.ok(typeof a.blurb === "string" && a.blurb.length > 10, `${a.id} has a line for its picker card`);
|
||||
}
|
||||
|
||||
@@ -386,17 +386,19 @@ test("only an installed console's open leaves the console-dir pointer; status, h
|
||||
assert.match(usage.stderr, /keep/, "the usage line names every command");
|
||||
assert.equal(fs.existsSync(pointer), false);
|
||||
// A source checkout never points every skill stub at itself.
|
||||
// Each console is stopped before its assert, so a failing assert leaves no server running.
|
||||
const fromSource = cli(["open", "--no-open"], { env });
|
||||
assert.equal(fs.existsSync(pointer), false, "a source checkout leaves no pointer");
|
||||
const sourcePointer = fs.existsSync(pointer);
|
||||
cli(["stop", "--session", fromSource.json.sid, "--force"], { env });
|
||||
assert.equal(sourcePointer, false, "a source checkout leaves no pointer");
|
||||
// An installed console (a version folder) does.
|
||||
const installed = path.join(home, "9.9.9");
|
||||
fs.cpSync(path.join(ROOT, "src", "web-console"), installed, { recursive: true });
|
||||
const res = spawnSync(process.execPath, [path.join(installed, "console.mjs"), "open", "--no-open"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
assert.equal(fs.readFileSync(pointer, "utf8").trim(), installed);
|
||||
const sid = JSON.parse(res.stdout.trim().split(/\r?\n/)[0]).sid;
|
||||
spawnSync(process.execPath, [path.join(installed, "console.mjs"), "stop", "--session", sid, "--force"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
|
||||
assert.equal(fs.readFileSync(pointer, "utf8").trim(), installed);
|
||||
} finally {
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -2,27 +2,37 @@
|
||||
// variable unset the page's CSP keeps frame-ancestors 'none'; set to exactly
|
||||
// one allowed origin it names that origin; set to anything else it is ignored
|
||||
// and 'none' stands. Each case boots its own server with the variable in its
|
||||
// environment. Shared setup: ./web-console-test-helpers.mjs.
|
||||
// environment. Inside the macOS app the frame signs in by a path prefix on
|
||||
// 127.0.0.1 instead of by cookie, and only there. Shared setup:
|
||||
// ./web-console-test-helpers.mjs.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { cookieFor, ENV, HOME, ROOT } from "./web-console-test-helpers.mjs";
|
||||
import { cookieFor, ENV, HOME, JPEG, ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
|
||||
|
||||
// Boot a session server whose environment carries PLAN2CODE_EMBED_ORIGIN set
|
||||
// to `origin` (or does not carry it at all when origin is undefined). Returns
|
||||
// the child and its base URL; the caller always kills the child.
|
||||
async function bootServer(origin) {
|
||||
// the child and its base URL; the caller always kills the child. `platform`
|
||||
// fakes process.platform in the server before it loads (the whole server
|
||||
// sees it, not only frameKey()), so the macOS-only frame sign-in is tested on
|
||||
// every OS. `state` adds fields to state.json.
|
||||
async function bootServer(origin, { platform, token = "t", state = {} } = {}) {
|
||||
const dir = fs.mkdtempSync(path.join(HOME, "embed-"));
|
||||
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" }));
|
||||
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting", ...state }));
|
||||
const env = { ...ENV };
|
||||
if (origin === undefined) delete env.PLAN2CODE_EMBED_ORIGIN;
|
||||
else env.PLAN2CODE_EMBED_ORIGIN = origin;
|
||||
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`], {
|
||||
const fake = platform
|
||||
? ["--import", `data:text/javascript,Object.defineProperty(process,"platform",{value:${JSON.stringify(platform)}})`]
|
||||
: [];
|
||||
const child = spawn(process.execPath, [...fake, SERVER_JS, `--session=${dir}`, `--token=${token}`, `--project=${dir}`], {
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
windowsHide: true,
|
||||
@@ -36,7 +46,7 @@ async function bootServer(origin) {
|
||||
});
|
||||
child.on("exit", () => reject(new Error("server exited before it was ready")));
|
||||
});
|
||||
return { child, base: `http://127.0.0.1:${ready.port}` };
|
||||
return { child, dir, base: `http://127.0.0.1:${ready.port}`, port: ready.port };
|
||||
}
|
||||
|
||||
// Fetch the session page with its token cookie and resolve to the page's
|
||||
@@ -54,8 +64,8 @@ async function cspWith(origin) {
|
||||
}
|
||||
|
||||
// Fetch the sign-in redirect and resolve to its set-cookie header.
|
||||
async function cookieWith(origin) {
|
||||
const { child, base } = await bootServer(origin);
|
||||
async function cookieWith(origin, options) {
|
||||
const { child, base } = await bootServer(origin, options);
|
||||
try {
|
||||
const res = await fetch(`${base}/s/t/`, { redirect: "manual" });
|
||||
assert.equal(res.status, 302);
|
||||
@@ -89,7 +99,9 @@ test("the session cookie is Strict standalone and None; Secure under embed", asy
|
||||
// WebKit (the app on Linux and macOS) drops a Secure cookie sent over plain
|
||||
// http, so the page in the app's frame got a 403 after the sign-in.
|
||||
test("the session cookie is Lax and never Secure under the tauri://localhost embed", async () => {
|
||||
const embedded = await cookieWith("tauri://localhost");
|
||||
// Linux, where this frame signs in by cookie: on macOS it signs in by its
|
||||
// path prefix instead (the frame tests below).
|
||||
const embedded = await cookieWith("tauri://localhost", { platform: "linux" });
|
||||
assert.match(embedded, /SameSite=Lax/);
|
||||
assert.doesNotMatch(embedded, /Secure/);
|
||||
assert.match(embedded, /HttpOnly/);
|
||||
@@ -112,3 +124,214 @@ test("anything but exactly one allowed origin keeps frame-ancestors 'none'", asy
|
||||
assert.match(csp, /frame-ancestors 'none'$/, `${JSON.stringify(origin)}: ${csp}`);
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------- the macOS app's frame sign-in */
|
||||
|
||||
// fetch() will not send a Host header of the caller's choosing, and some of
|
||||
// these requests must, so they go through node:http. Resolves to status,
|
||||
// headers and body text; with `head` it resolves on the headers and drops
|
||||
// the connection (the event stream never ends).
|
||||
function raw(port, urlPath, { method = "GET", headers = {}, body, head = false } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: "127.0.0.1", port, path: urlPath, method, headers: { connection: "close", ...headers } }, (res) => {
|
||||
if (head) {
|
||||
resolve({ status: res.statusCode, headers: res.headers, body: "" });
|
||||
return req.destroy();
|
||||
}
|
||||
let text = "";
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (c) => (text += c));
|
||||
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: text }));
|
||||
});
|
||||
req.on("error", (e) => (head && e.code === "ECONNRESET" ? undefined : reject(e)));
|
||||
req.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
// The frame's key: a hash of the token, so the token the terminal prints
|
||||
// never sits in the frame's address, and still 128 bits.
|
||||
const frameKey = (token) => crypto.createHash("sha256").update(token).digest("hex").slice(0, 32);
|
||||
|
||||
// A real token's shape: 16 random bytes in base64url, uppercase included.
|
||||
const MIXED_TOKEN = "aB3xZ9-Qk_T7mN2pLw8RvY";
|
||||
|
||||
// A server in the macOS app's frame mode, its prefix, and the same-origin
|
||||
// headers the frame's page sends with an origin-checked POST.
|
||||
async function macFrame(options = {}) {
|
||||
const server = await bootServer("tauri://localhost", { platform: "darwin", token: MIXED_TOKEN, ...options });
|
||||
return { ...server, prefix: `/f/${frameKey(MIXED_TOKEN)}`, own: { origin: `http://127.0.0.1:${server.port}` } };
|
||||
}
|
||||
|
||||
test("the macOS app's frame signs in by a path prefix on 127.0.0.1, with no cookie", async () => {
|
||||
const { child, port, prefix, own } = await macFrame();
|
||||
try {
|
||||
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "iframe" } });
|
||||
assert.equal(signIn.status, 302);
|
||||
assert.equal(signIn.headers.location, `${prefix}/`, "the same host, a path, never a host name");
|
||||
assert.equal(signIn.headers["set-cookie"], undefined);
|
||||
|
||||
const page = await raw(port, `${prefix}/`);
|
||||
assert.equal(page.status, 200);
|
||||
assert.match(page.headers["content-security-policy"], /frame-ancestors tauri:\/\/localhost$/);
|
||||
assert.equal((await raw(port, `${prefix}/state`)).status, 200);
|
||||
assert.equal((await raw(port, `${prefix}/app.js`)).status, 200);
|
||||
const events = await raw(port, `${prefix}/events`, { head: true });
|
||||
assert.equal(events.status, 200);
|
||||
assert.match(String(events.headers["content-type"]), /^text\/event-stream/);
|
||||
|
||||
// An origin-checked route takes the page's own origin under the prefix.
|
||||
assert.equal((await raw(port, `${prefix}/bye`, { method: "POST", headers: own })).status, 200);
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
|
||||
test("under the frame's prefix the routes that read the raw request line answer, and still refuse `..`", async () => {
|
||||
const project = fs.mkdtempSync(path.join(HOME, "embed-project-"));
|
||||
const kept = "shot-1a2b3c4d.jpg";
|
||||
fs.mkdirSync(path.join(project, "spec", "attachments"), { recursive: true });
|
||||
fs.writeFileSync(path.join(project, "spec", "attachments", kept), JSON.stringify("not read as text"));
|
||||
const { child, dir, port, prefix, own } = await macFrame({ state: { worktree: project, specDir: "spec" } });
|
||||
try {
|
||||
const jpeg = { ...own, "content-type": "image/jpeg" };
|
||||
const upload = JSON.parse((await raw(port, `${prefix}/upload`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||
assert.equal((await raw(port, `${prefix}/uploads/${upload.id}.jpg`)).status, 200, "an upload");
|
||||
assert.equal((await raw(port, `${prefix}/uploads/../uploads/${upload.id}.jpg`)).status, 404, "`..` is still refused");
|
||||
|
||||
const note = JSON.parse((await raw(port, `${prefix}/notepad/image`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||
assert.ok(note.ok, JSON.stringify(note));
|
||||
const tab = /images\/([0-9a-f]{12})\//.exec(note.url)[1];
|
||||
assert.equal((await raw(port, `${prefix}/notepad/images/${tab}/${note.id}.jpg`)).status, 200, "a notepad picture");
|
||||
|
||||
fs.mkdirSync(path.join(dir, "shots"));
|
||||
fs.writeFileSync(path.join(dir, "shots", "run.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0]));
|
||||
assert.equal((await raw(port, `${prefix}/shots/run.png`)).status, 200, "a shot");
|
||||
assert.equal((await raw(port, `${prefix}/shots/../shots/run.png`)).status, 404, "`..` is still refused");
|
||||
|
||||
assert.equal((await raw(port, `${prefix}/attachments/${kept}`)).status, 200, "a kept attachment");
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
|
||||
test("the links the server hands the page are page-relative", async () => {
|
||||
const { child, port, prefix, own } = await macFrame();
|
||||
try {
|
||||
const jpeg = { ...own, "content-type": "image/jpeg" };
|
||||
const upload = JSON.parse((await raw(port, `${prefix}/upload`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||
assert.equal(upload.url, `uploads/${upload.id}.jpg`);
|
||||
const note = JSON.parse((await raw(port, `${prefix}/notepad/image`, { method: "POST", headers: jpeg, body: JPEG })).body);
|
||||
assert.match(note.url, /^notepad\/images\/[0-9a-f]{12}\/[0-9a-f-]{36}\.jpg$/);
|
||||
const pad = JSON.parse((await raw(port, `${prefix}/notepad`)).body);
|
||||
assert.equal(pad.images.length, 1);
|
||||
for (const img of pad.images) {
|
||||
assert.doesNotMatch(img.url, /^\//, img.url);
|
||||
assert.doesNotMatch(String(img.thumb ?? ""), /^\//, img.thumb);
|
||||
}
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
|
||||
test("a wrong or missing frame key is refused exactly as a request with no cookie is", async () => {
|
||||
const { child, port, prefix } = await macFrame();
|
||||
try {
|
||||
const key = frameKey(MIXED_TOKEN);
|
||||
const plain = await raw(port, "/state");
|
||||
assert.equal(plain.status, 403);
|
||||
const wrong = [
|
||||
`/f/${frameKey("someone-else")}/state`,
|
||||
`/f/${key.toUpperCase()}/state`,
|
||||
`/f/${key.slice(0, -1)}/state`,
|
||||
`/f/${key}x/state`,
|
||||
`/f//state`,
|
||||
`/f/state`,
|
||||
`/f/${key}`,
|
||||
`/F/${key}/state`,
|
||||
`/f/%${key.charCodeAt(0).toString(16)}${key.slice(1)}/state`,
|
||||
`/x/f/${key}/state`,
|
||||
];
|
||||
for (const p of wrong) {
|
||||
const res = await raw(port, p);
|
||||
assert.equal(res.status, plain.status, p);
|
||||
assert.equal(res.body, plain.body, `${p} says no more than a request with no cookie`);
|
||||
}
|
||||
// The prefix comes off once: a second one is just a path, and nothing serves it.
|
||||
assert.equal((await raw(port, `${prefix}${prefix}/state`)).status, 404);
|
||||
assert.equal((await raw(port, `/s/${MIXED_TOKEN}x/`, { headers: { "sec-fetch-dest": "iframe" } })).status, 403);
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
|
||||
test("a .localhost host name neither signs in nor passes the origin check", async () => {
|
||||
const { child, port, prefix } = await macFrame();
|
||||
try {
|
||||
const key = frameKey(MIXED_TOKEN);
|
||||
for (const host of [`${key}.localhost:${port}`, `x.localhost:${port}`, `${key}.localhost`]) {
|
||||
assert.equal((await raw(port, "/state", { headers: { host } })).status, 403, host);
|
||||
assert.equal((await raw(port, `${prefix}/state`, { headers: { host } })).status, 403, `${host} under the prefix`);
|
||||
}
|
||||
const foreign = await raw(port, `${prefix}/bye`, { method: "POST", headers: { origin: `http://${key}.localhost:${port}` } });
|
||||
assert.equal(foreign.status, 403);
|
||||
assert.equal((await raw(port, `${prefix}/bye`, { method: "POST", headers: { origin: "http://evil.localhost:80" } })).status, 403);
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
|
||||
test("a browser tab on the macOS app's console keeps the cookie and `/`", async () => {
|
||||
const { child, port, prefix } = await macFrame();
|
||||
try {
|
||||
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "document" } });
|
||||
assert.equal(signIn.status, 302);
|
||||
assert.equal(signIn.headers.location, "/");
|
||||
// The tauri://localhost cookie (cookieSameSite): Lax, never Secure,
|
||||
// since Safari drops a Secure cookie on plain http.
|
||||
assert.match(String(signIn.headers["set-cookie"]), /HttpOnly; SameSite=Lax;/);
|
||||
assert.doesNotMatch(String(signIn.headers["set-cookie"]), /Secure/);
|
||||
const cookie = cookieFor(`http://127.0.0.1:${port}`, MIXED_TOKEN);
|
||||
assert.equal((await raw(port, "/state", { headers: { cookie } })).status, 200);
|
||||
assert.ok(!String(signIn.headers.location).includes(prefix));
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
});
|
||||
|
||||
test("the frame prefix is off everywhere but the macOS app, where `/f/` is just a path", async () => {
|
||||
const cases = [
|
||||
{ origin: "tauri://localhost", platform: "win32" },
|
||||
{ origin: "tauri://localhost", platform: "linux" },
|
||||
{ origin: "http://tauri.localhost", platform: "darwin" },
|
||||
{ origin: "http://127.0.0.1:5173", platform: "darwin" },
|
||||
{ origin: undefined, platform: "darwin" },
|
||||
];
|
||||
for (const { origin, platform } of cases) {
|
||||
const label = `${origin} on ${platform}`;
|
||||
const { child, port } = await bootServer(origin, { platform, token: MIXED_TOKEN });
|
||||
try {
|
||||
const signIn = await raw(port, `/s/${MIXED_TOKEN}/`, { headers: { "sec-fetch-dest": "iframe" } });
|
||||
assert.equal(signIn.headers.location, "/", label);
|
||||
assert.match(String(signIn.headers["set-cookie"]), /HttpOnly/, label);
|
||||
const prefixed = `/f/${frameKey(MIXED_TOKEN)}/state`;
|
||||
assert.equal((await raw(port, prefixed)).status, 403, `${label}: no sign-in by path`);
|
||||
const cookie = cookieFor(`http://127.0.0.1:${port}`, MIXED_TOKEN);
|
||||
assert.equal((await raw(port, prefixed, { headers: { cookie } })).status, 404, `${label}: never stripped`);
|
||||
assert.equal((await raw(port, "/state", { headers: { cookie } })).status, 200, `${label}: the cookie route as before`);
|
||||
} finally {
|
||||
child.kill();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("the page-closed signal is a keepalive fetch, which carries the page's origin, not a beacon", () => {
|
||||
// A body-less sendBeacon is a no-cors POST: under the console's
|
||||
// `referrer-policy: no-referrer` it goes out with `Origin: null`, which /bye's
|
||||
// origin check refuses (WebKit showed it; the Fetch standard says every engine
|
||||
// does the same). A keepalive fetch is a cors request and sends the real origin.
|
||||
const core = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "core.js"), "utf8");
|
||||
const wire = core.slice(core.indexOf("export function wireChrome()"));
|
||||
const pagehide = wire.slice(0, wire.indexOf("});"));
|
||||
assert.match(pagehide, /fetch\("bye", \{ method: "POST", keepalive: true \}\)/, pagehide);
|
||||
assert.doesNotMatch(core, /navigator\.sendBeacon\(/, "no beacon call left anywhere in the page's core");
|
||||
});
|
||||
@@ -589,7 +589,7 @@ test("git board: the page draws it from git-board.js, with no inline styles", ()
|
||||
const dir = path.join(path.dirname(CONSOLE_CLI), "public");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8");
|
||||
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`);
|
||||
const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8");
|
||||
assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/);
|
||||
assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
|
||||
|
||||
@@ -9,7 +9,8 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
// The page's pure answer-shaping logic. app.js itself cannot be imported here
|
||||
@@ -166,6 +167,7 @@ import {
|
||||
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
|
||||
import {
|
||||
pickerCommand,
|
||||
pickerOutcome,
|
||||
pickFolder,
|
||||
WINDOWS_PICKER_SOURCE,
|
||||
WORKSPACE_PICKER_PROMPT,
|
||||
@@ -187,6 +189,7 @@ import { chatReplyLines } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
initialWorkspace,
|
||||
pendingWorkspaceChanges,
|
||||
pickerStart,
|
||||
readWorkspaceCursor,
|
||||
WORKSPACE_FILE,
|
||||
writeWorkspaceCursor,
|
||||
@@ -2297,7 +2300,7 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
assert.ok(pill, "the pill sits in .ident");
|
||||
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"'));
|
||||
for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) {
|
||||
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`);
|
||||
}
|
||||
// The CSP refuses style attributes and inline script: the new markup has neither.
|
||||
const added = [
|
||||
@@ -2351,31 +2354,106 @@ test("picker: the workspace picker cannot drift from the launcher's", () => {
|
||||
assert.equal(WORKSPACE_PICKER_PROMPT, "Choose a folder to add to the workspace");
|
||||
});
|
||||
|
||||
function fakeSpawn(code, output) {
|
||||
test("picker: the launcher and the workspace read a picker's exit the same way", () => {
|
||||
// Two copies of one rule (macOS: only osascript's (-128) is a cancel), each
|
||||
// with its own tests: this keeps an edit to one from leaving the other behind.
|
||||
const { pickerCancelled } = createRequire(import.meta.url)(path.join(ROOT, "src", "launcher", "plan2code.js"));
|
||||
const errors = ["", "0:17: execution error: User canceled. (-128)", "execution error: Not authorized to send Apple events. (-1743)", "(-1280)", "Gtk-WARNING\n"];
|
||||
for (const platform of ["darwin", "linux", "win32"]) {
|
||||
for (const code of [0, 1, 2]) {
|
||||
for (const stdout of ["", "/some/folder\n"]) {
|
||||
for (const stderr of errors) {
|
||||
const workspace = "cancelled" in pickerOutcome(code, stdout, stderr, platform);
|
||||
assert.equal(pickerCancelled(code, stdout, stderr, platform), workspace, JSON.stringify({ platform, code, stdout, stderr }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("picker: stderr is read only on macOS, where it tells a cancel from a failure", { skip: process.platform === "win32" ? "pickerCommand needs a POSIX picker here" : false }, async () => {
|
||||
for (const [platform, expected] of [["darwin", "pipe"], ["linux", "ignore"], ["win32", "ignore"]]) {
|
||||
// Linux's picker is zenity or kdialog, found on PATH: none on this machine, nothing to start.
|
||||
if (!pickerCommand(os.tmpdir(), "p", { platform })) continue;
|
||||
let stdio = null;
|
||||
const spy = (command, args, options) => {
|
||||
stdio = options.stdio;
|
||||
return fakeSpawn(0, "", "", platform)(command, args, options);
|
||||
};
|
||||
await pickFolder(os.tmpdir(), "p", { platform, spawnImpl: spy });
|
||||
assert.ok(stdio, `${platform}: the picker was started`);
|
||||
assert.equal(stdio[2], expected, platform);
|
||||
}
|
||||
});
|
||||
|
||||
function fakeSpawn(code, output, errorText = "", platform = process.platform) {
|
||||
return (command, args, options) => {
|
||||
assert.equal(options.windowsHide, true);
|
||||
assert.equal(options.stdio[2], platform === "darwin" ? "pipe" : "ignore", "stderr is piped on macOS only, where a cancel is told from a failure");
|
||||
const child = new EventEmitter();
|
||||
child.stdout = new PassThrough();
|
||||
child.stderr = new PassThrough();
|
||||
setImmediate(() => {
|
||||
if (output) child.stdout.write(output);
|
||||
if (errorText) child.stderr.write(errorText);
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
setImmediate(() => child.emit("close", code));
|
||||
});
|
||||
return child;
|
||||
};
|
||||
}
|
||||
|
||||
// What osascript prints on a cancel, and on a failure (a bad script here; a
|
||||
// missing default folder or a refused permission end the same way, exit 1).
|
||||
const MAC_CANCEL = "0:17: execution error: User canceled. (-128)\n";
|
||||
const MAC_FAILURE = "0:4: execution error: The variable this is not defined. (-2753)\n";
|
||||
|
||||
test(
|
||||
"picker: pickFolder reads a pick, a cancel and a failure off the picker's exit",
|
||||
{ skip: pickerCommand(os.tmpdir(), WORKSPACE_PICKER_PROMPT) ? false : "no folder picker on this machine" },
|
||||
async () => {
|
||||
const picked = path.join(os.tmpdir(), "picked");
|
||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(0, picked + "\n") }), { path: path.resolve(picked) });
|
||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(1, "") }), { cancelled: true });
|
||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(1, "", MAC_CANCEL) }), { cancelled: true });
|
||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(2, "") }), { error: "picker-failed" });
|
||||
}
|
||||
);
|
||||
|
||||
test("picker: on macOS only osascript's (-128) makes an exit 1 a cancel; any other exit 1 with no folder is a failure", async () => {
|
||||
const pick = (code, output, errorText) => pickFolder(os.tmpdir(), "p", { platform: "darwin", spawnImpl: fakeSpawn(code, output, errorText, "darwin") });
|
||||
assert.equal(pickerCommand(os.tmpdir(), "p", { platform: "darwin" }).command, "osascript");
|
||||
assert.deepEqual(await pick(1, "", MAC_CANCEL), { cancelled: true });
|
||||
assert.deepEqual(await pick(1, "", MAC_FAILURE), { error: "picker-failed" });
|
||||
assert.deepEqual(await pick(1, "", ""), { error: "picker-failed" }, "no stderr at all is no proof of a cancel");
|
||||
const picked = path.join(os.tmpdir(), "picked");
|
||||
assert.deepEqual(await pick(0, picked + "\n", ""), { path: path.resolve(picked) });
|
||||
});
|
||||
|
||||
test("picker: on Windows and Linux an exit 1 with no folder stays a cancel, whatever stderr says", async () => {
|
||||
assert.equal(pickerCommand(os.tmpdir(), "p", { platform: "win32" }).command, "powershell.exe");
|
||||
for (const errorText of ["", "Gtk-WARNING: some noise\n"]) {
|
||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { platform: "win32", spawnImpl: fakeSpawn(1, "", errorText, "win32") }), { cancelled: true });
|
||||
}
|
||||
// Linux's picker needs a display and zenity or kdialog on this host, so its
|
||||
// rule is checked on the outcome itself.
|
||||
for (const platform of ["linux", "win32"]) {
|
||||
assert.deepEqual(pickerOutcome(1, "", "", platform), { cancelled: true }, platform);
|
||||
assert.deepEqual(pickerOutcome(1, "", "(-2753)", platform), { cancelled: true }, platform);
|
||||
assert.deepEqual(pickerOutcome(0, "", "", platform), { cancelled: true }, platform);
|
||||
assert.deepEqual(pickerOutcome(3, "", "", platform), { error: "picker-failed" }, platform);
|
||||
}
|
||||
assert.deepEqual(pickerOutcome(1, "", MAC_CANCEL, "darwin"), { cancelled: true });
|
||||
assert.deepEqual(pickerOutcome(1, "", MAC_FAILURE, "darwin"), { error: "picker-failed" });
|
||||
});
|
||||
|
||||
test("picker: a picker that writes a lot to stderr still finishes, and its last words decide", async () => {
|
||||
// A real child writing far past a pipe's buffer: unread, it would block before exiting.
|
||||
const chatty = (command, args, options) =>
|
||||
spawn(process.execPath, ["-e", "process.stderr.write('Gtk-WARNING\\n'.repeat(100000)); process.stderr.write('User canceled. (-128)'); process.exitCode = 1"], options);
|
||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { platform: "darwin", spawnImpl: chatty }), { cancelled: true });
|
||||
});
|
||||
|
||||
test("ledger: a torn trailing line is skipped, then read once completed; an append after a fragment starts a new line", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-ledger-"));
|
||||
try {
|
||||
@@ -2708,6 +2786,26 @@ test("initialWorkspace names the original folder after itself and marks it origi
|
||||
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
||||
});
|
||||
|
||||
// Browse... opens beside the last folder added. When that folder is gone, a missing
|
||||
// start must not read as "Browse is not available here".
|
||||
test("pickerStart opens beside the last folder added, or at its nearest folder still on disk", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-picker-start-"));
|
||||
try {
|
||||
const project = path.join(root, "project");
|
||||
const kept = path.join(root, "kept");
|
||||
fs.mkdirSync(project);
|
||||
fs.mkdirSync(path.join(kept, "inner"), { recursive: true });
|
||||
assert.equal(pickerStart(initialWorkspace(project), project), project, "the original folder when nothing was added");
|
||||
const ws = initialWorkspace(project);
|
||||
ws.folders.push({ id: "f1", path: path.join(kept, "inner"), name: "inner", description: "" });
|
||||
assert.equal(pickerStart(ws, project), kept, "beside the last folder added");
|
||||
fs.rmSync(kept, { recursive: true, force: true });
|
||||
assert.equal(pickerStart(ws, project), root, "the nearest folder still on disk");
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The meter's tables are built from skills.js plus the events that are not a
|
||||
// skill's own. Held to their values when they were written by hand.
|
||||
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
|
||||
|
||||
@@ -144,14 +144,14 @@ test("pictures: JPEG only, listed oldest first, with thumbnails when sent", () =
|
||||
const first = addImage(folder, tab, JPEG);
|
||||
const second = addImage(folder, tab, JPEG);
|
||||
assert.match(first.id, IMAGE_ID_RE);
|
||||
assert.equal(first.url, `/notepad/images/${tab}/${first.id}.jpg`);
|
||||
assert.equal(first.url, `notepad/images/${tab}/${first.id}.jpg`);
|
||||
// Make the order unambiguous: the first is older.
|
||||
const older = new Date(Date.now() - 60_000);
|
||||
fs.utimesSync(path.join(tabDir(folder, tab), "images", first.id + ".jpg"), older, older);
|
||||
addThumb(folder, tab, second.id, JPEG);
|
||||
assert.deepEqual(readNotepad(folder).images, [
|
||||
{ id: first.id, url: first.url, thumb: null },
|
||||
{ id: second.id, url: second.url, thumb: `/notepad/images/${tab}/${second.id}.thumb.jpg` },
|
||||
{ id: second.id, url: second.url, thumb: `notepad/images/${tab}/${second.id}.thumb.jpg` },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -509,8 +509,8 @@ test("the first shape reads as one Notes tab, and the read writes nothing", () =
|
||||
[U1, U2],
|
||||
"oldest first",
|
||||
);
|
||||
assert.equal(read.images[0].url, `/notepad/images/${LEGACY_TAB_ID}/${U1}.jpg`);
|
||||
assert.equal(read.images[0].thumb, `/notepad/images/${LEGACY_TAB_ID}/${U1}.thumb.jpg`);
|
||||
assert.equal(read.images[0].url, `notepad/images/${LEGACY_TAB_ID}/${U1}.jpg`);
|
||||
assert.equal(read.images[0].thumb, `notepad/images/${LEGACY_TAB_ID}/${U1}.thumb.jpg`);
|
||||
assert.equal(read.images[1].thumb, null);
|
||||
assert.deepEqual(listTabs(folder), { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID });
|
||||
assert.equal(readNotepad(folder, LEGACY_TAB_ID).text, "old note\n");
|
||||
@@ -564,7 +564,7 @@ test("any first write migrates: a picture, a new tab, and an old picture can be
|
||||
const f2 = freshFolder("legacy");
|
||||
legacyNotepad(f2);
|
||||
const added = addImage(f2, LEGACY_TAB_ID, JPEG);
|
||||
assert.equal(added.url, `/notepad/images/${LEGACY_TAB_ID}/${added.id}.jpg`);
|
||||
assert.equal(added.url, `notepad/images/${LEGACY_TAB_ID}/${added.id}.jpg`);
|
||||
assert.equal(readNotepad(f2).images.length, 3);
|
||||
// A first-shape notepad with a picture and no note still migrates.
|
||||
const f3 = freshFolder("legacy");
|
||||
@@ -718,7 +718,10 @@ test("pictures through the routes: upload, thumb, fetch, delete and every refusa
|
||||
|
||||
const up = await postJpeg(s, "/notepad/image", JPEG);
|
||||
assert.equal(up.status, 200);
|
||||
const { id, url } = await up.json();
|
||||
const { id, url: link } = await up.json();
|
||||
assert.doesNotMatch(link, /^\//, "page-relative");
|
||||
// The page at / asks for it here.
|
||||
const url = `/${link}`;
|
||||
assert.match(id, IMAGE_ID_RE);
|
||||
|
||||
const unknownThumb = await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG);
|
||||
@@ -853,7 +856,7 @@ test("GET /notepad answers a notepad still in the first shape as a Notes tab, an
|
||||
assert.equal(res.body.text, "old note\n");
|
||||
assert.equal(res.body.images.length, 2);
|
||||
assert.deepEqual(treeOf(dir), before, "the read wrote nothing");
|
||||
const img = await fetch(`${s.base}${res.body.images[0].url}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
const img = await fetch(`${s.base}/${res.body.images[0].url}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
assert.equal(img.status, 200, "the picture is served from where it still is");
|
||||
// The unchanged page's save, with no tab named, lands in Notes and migrates.
|
||||
assert.equal((await s.send("/notepad/text", { text: "page save" })).status, 200);
|
||||
@@ -1004,16 +1007,18 @@ test("pictures through ?tab=: upload, thumb, fetch and delete, each under the ta
|
||||
const up = await postJpeg(s, `/notepad/image?tab=${a}`, JPEG);
|
||||
assert.equal(up.status, 200);
|
||||
const { id, url } = await up.json();
|
||||
assert.equal(url, `/notepad/images/${a}/${id}.jpg`);
|
||||
assert.equal(url, `notepad/images/${a}/${id}.jpg`);
|
||||
// Page-relative: the page at / asks for it here.
|
||||
const served = `/${url}`;
|
||||
assert.equal((await postJpeg(s, `/notepad/thumb?tab=${a}&id=${id}`, JPEG)).status, 200);
|
||||
assert.equal((await get(url)).status, 200);
|
||||
assert.equal((await get(served)).status, 200);
|
||||
assert.equal((await get(`/notepad/images/${a}/${id}.thumb.jpg`)).status, 200);
|
||||
// Not under another tab, not in the old shape, not under a tab that is not there.
|
||||
assert.equal((await get(`/notepad/images/${b}/${id}.jpg`)).status, 404);
|
||||
assert.equal((await get(`/notepad/images/${id}.jpg`)).status, 404);
|
||||
assert.equal((await get(`/notepad/images/ffffffffffff/${id}.jpg`)).status, 404);
|
||||
assert.deepEqual((await getJson(s, `/notepad?tab=${b}`)).body.images, []);
|
||||
assert.equal((await getJson(s, `/notepad?tab=${a}`)).body.images[0].thumb, `/notepad/images/${a}/${id}.thumb.jpg`);
|
||||
assert.equal((await getJson(s, `/notepad?tab=${a}`)).body.images[0].thumb, `notepad/images/${a}/${id}.thumb.jpg`);
|
||||
// A picture or thumb for a tab that is not there, and a delete from the wrong tab.
|
||||
const stray = await postJpeg(s, "/notepad/image?tab=ffffffffffff", JPEG);
|
||||
assert.equal(stray.status, 404);
|
||||
@@ -1022,12 +1027,12 @@ test("pictures through ?tab=: upload, thumb, fetch and delete, each under the ta
|
||||
assert.equal((await postJpeg(s, `/notepad/image?tab=nope`, JPEG)).status, 404);
|
||||
assert.equal((await s.send(`/notepad/image/delete?tab=${b}`, { id })).status, 404, "tab B does not hold it");
|
||||
assert.equal((await s.send(`/notepad/image/delete?tab=ffffffffffff`, { id })).status, 404);
|
||||
assert.equal((await get(url)).status, 200, "still there");
|
||||
assert.equal((await get(served)).status, 200, "still there");
|
||||
assert.equal((await s.send(`/notepad/image/delete?tab=${a}`, { id })).status, 200);
|
||||
assert.equal((await get(url)).status, 404);
|
||||
assert.equal((await get(served)).status, 404);
|
||||
// With no tab named, the picture goes to the last tab used.
|
||||
const unnamed = await (await postJpeg(s, "/notepad/image", JPEG)).json();
|
||||
assert.equal(unnamed.url.split("/")[3], b);
|
||||
assert.equal(unnamed.url.split("/")[2], b);
|
||||
assert.equal((await s.send("/notepad/image/delete", { id: unnamed.id })).status, 200);
|
||||
assert.deepEqual(await (await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG)).json(), { error: "not-found" });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
// Web console page tests: the page as the macOS app's frame has it. WebKit
|
||||
// gives that frame no cookie, so the console signs it in by a path prefix
|
||||
// (`/f/<key>/`, routes.mjs) and the page runs under it. Every request the page
|
||||
// makes there must stay under the prefix: one that leaves it gets a 403, and
|
||||
// only in the macOS app. This file opens the page that way in a browser
|
||||
// context with no cookie, uses the parts that fetch, and fails on any request
|
||||
// that left the prefix or was refused. Run with:
|
||||
// node --test scripts/test-web-console-page-frame.mjs
|
||||
|
||||
import crypto from "node:crypto";
|
||||
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 { until, HOME } from "./web-console-test-helpers.mjs";
|
||||
import { createTab, listTabs } from "../src/web-console/notepads.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||
|
||||
// The server takes the app's frame mode only on macOS, with the app's page as
|
||||
// the embed ancestor. On any other OS this makes the server alone believe it
|
||||
// runs on macOS (the CLI that starts it is left as it is), so CI's Linux run
|
||||
// checks the same thing. The whole server sees darwin, not only frameKey():
|
||||
// every macOS branch in it runs here too.
|
||||
const FAKE_MAC =
|
||||
"data:text/javascript," +
|
||||
encodeURIComponent('if (/server\\.mjs$/.test(process.argv[1] || "")) Object.defineProperty(process, "platform", { value: "darwin" });');
|
||||
const FRAME_ENV = { PLAN2CODE_EMBED_ORIGIN: "tauri://localhost", NODE_OPTIONS: `--import=${FAKE_MAC}` };
|
||||
|
||||
// The frame's key, as routes.mjs makes it from the session token.
|
||||
const frameKey = (token) => crypto.createHash("sha256").update(token).digest("hex").slice(0, 32);
|
||||
|
||||
test("under the frame's prefix, with no cookie, the dashboard draws, its stream connects, and nothing it asks for leaves the prefix", async (t) => {
|
||||
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, hideActivities: false } }));
|
||||
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||
const browser = await suite.browser();
|
||||
const s = await openSession(browser, { t, workflow: "dashboard", env: FRAME_ENV });
|
||||
if (!listTabs(s.project).tabs.length) createTab(s.project, "Notes");
|
||||
|
||||
const signIn = new URL(s.url);
|
||||
const token = /^\/s\/([^/]+)\/$/.exec(signIn.pathname)[1];
|
||||
const prefix = `/f/${frameKey(token)}/`;
|
||||
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
t.after(() => context.close().catch(() => {}));
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(60000);
|
||||
|
||||
const left = [];
|
||||
const refused = [];
|
||||
const errors = [];
|
||||
let streamed = false;
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
page.on("request", (r) => {
|
||||
const u = new URL(r.url());
|
||||
if (u.origin === signIn.origin && !u.pathname.startsWith(prefix)) left.push(`${r.method()} ${u.pathname}`);
|
||||
});
|
||||
page.on("response", (r) => {
|
||||
const u = new URL(r.url());
|
||||
if (u.origin !== signIn.origin) return;
|
||||
if (r.status() === 403 || r.status() === 404) refused.push(`${r.status()} ${u.pathname}`);
|
||||
if (u.pathname === `${prefix}events` && r.status() === 200) streamed = true;
|
||||
});
|
||||
|
||||
const res = await page.goto(signIn.origin + prefix, { waitUntil: "domcontentloaded" });
|
||||
assert.equal(res.status(), 200, "the page itself, under the prefix");
|
||||
await drawn(page);
|
||||
// Past Planny's wake-up, to the menu.
|
||||
const skip = page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.click();
|
||||
await skip.waitFor({ state: "hidden" });
|
||||
await page.locator("#main section.dash-group").first().waitFor();
|
||||
assert.deepEqual(await context.cookies(), [], "the frame signs in with no cookie");
|
||||
await until(() => streamed, 10000);
|
||||
assert.ok(streamed, "the event stream connected under the prefix");
|
||||
|
||||
// A step that waits on a request the server refused times out; the
|
||||
// requests that left the prefix or were refused are the reason, so they
|
||||
// are reported first.
|
||||
try {
|
||||
// The Notebook: its tab list and note come from the server.
|
||||
await page.click("#btn-notepad");
|
||||
await page.locator("#notepad-modal[open]").waitFor({ timeout: 15000 });
|
||||
await page.waitForFunction(
|
||||
() => {
|
||||
const c = document.querySelector(".notepad-cm-host")?.shadowRoot?.querySelector(".cm-content");
|
||||
return Boolean(c) && c.getAttribute("aria-readonly") !== "true";
|
||||
},
|
||||
null,
|
||||
{ timeout: 15000 }
|
||||
);
|
||||
await page.click("#notepad-close");
|
||||
|
||||
// User Preferences: a change of theme is saved to the server.
|
||||
await page.click("#btn-looks");
|
||||
await page.locator("#looks-modal[open]").waitFor({ timeout: 15000 });
|
||||
const saved = page.waitForResponse((r) => r.url().endsWith(`${prefix}looks`) && r.request().method() === "POST", { timeout: 15000 });
|
||||
await page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||
assert.equal((await saved).status(), 200, "the looks were saved");
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
// Activities: a game's module, loaded the first time it opens.
|
||||
await page.click("#btn-activities");
|
||||
await page.locator("#activities-modal[open]").waitFor({ timeout: 15000 });
|
||||
await page.locator('#activities-picker .activities-row[data-activity="snake"]').click();
|
||||
await page.locator("#activities-board").waitFor({ timeout: 15000 });
|
||||
} finally {
|
||||
await until(async () => {
|
||||
const n = refused.length + left.length;
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
return n === refused.length + left.length;
|
||||
}, 5000);
|
||||
assert.deepEqual(left, [], "every request stays under the prefix");
|
||||
assert.deepEqual(refused, [], "no request is refused or missing");
|
||||
}
|
||||
assert.deepEqual(errors, [], "no error on the page");
|
||||
});
|
||||
@@ -579,7 +579,7 @@ test("each tab keeps its own text and pictures, and switching never saves into t
|
||||
await tabNamed(s, "Ideas").click();
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1);
|
||||
const src = await s.page.locator("#notepad-strip img").getAttribute("src");
|
||||
assert.match(src, new RegExp(`^/notepad/images/${ideas}/`), "the picture's address names its tab");
|
||||
assert.match(src, new RegExp(`^notepad/images/${ideas}/`), "the picture's address names its tab");
|
||||
|
||||
// A save that cannot reach the server keeps you on the tab, with why.
|
||||
await s.page.route("**/notepad/text*", (route) => route.abort());
|
||||
@@ -1009,7 +1009,8 @@ test("the preview opens at the clicked picture, steps and wraps, and Esc closes
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
for (const color of ["#c33", "#3c3", "#33c"]) await addViaButton(s, color);
|
||||
const urls = stored(s).map((img) => img.url);
|
||||
// Page-relative: the page at / shows each one here.
|
||||
const urls = stored(s).map((img) => `/${img.url}`);
|
||||
const shown = () =>
|
||||
s.page.evaluate(() => ({
|
||||
src: new URL(document.getElementById("picview-img").src).pathname,
|
||||
|
||||
@@ -897,6 +897,48 @@ test("below 720 px the side list is a horizontal strip with no hints", async (t)
|
||||
await s.page.waitForFunction(() => document.getElementById("prefs-tabs").getAttribute("aria-orientation") === "vertical");
|
||||
});
|
||||
|
||||
// Every choice box in a looks row whose label overflows it, or that runs into the next box on its line.
|
||||
async function crampedChoices(s) {
|
||||
return s.page.evaluate(() => {
|
||||
const bad = [];
|
||||
for (const row of document.querySelectorAll("#prefs-panel-appearance .looks-row")) {
|
||||
const boxes = [...row.querySelectorAll(":scope > label")];
|
||||
boxes.forEach((box, i) => {
|
||||
const name = box.textContent.trim();
|
||||
if (box.scrollWidth > box.clientWidth + 1) bad.push(`${name}: its label overflows the box`);
|
||||
const next = boxes[i + 1];
|
||||
if (!next) return;
|
||||
const a = box.getBoundingClientRect();
|
||||
const b = next.getBoundingClientRect();
|
||||
if (Math.abs(a.top - b.top) < 2 && a.right > b.left + 1) bad.push(`${name}: runs into ${next.textContent.trim()}`);
|
||||
});
|
||||
}
|
||||
return bad;
|
||||
});
|
||||
}
|
||||
|
||||
test("with the Narrow card width in a wide window, no Appearance choice overflows or overlaps its neighbor", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// Wide enough that no window-width rule applies: only the dialog is narrow.
|
||||
await s.page.setViewportSize({ width: 1400, height: 900 });
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator("#looks-modal[open]").waitFor();
|
||||
await s.page.locator('input[name="looks-width"][value="narrow"]').check();
|
||||
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-width") === "narrow");
|
||||
assert.deepEqual(await crampedChoices(s), []);
|
||||
// The other widths stay clean too.
|
||||
for (const width of ["comfortable", "wide", "ultrawide"]) {
|
||||
await s.page.locator(`input[name="looks-width"][value="${width}"]`).check();
|
||||
// The default width leaves no attribute on the page.
|
||||
await s.page.waitForFunction((w) => (document.documentElement.getAttribute("data-width") ?? "comfortable") === w, width);
|
||||
assert.deepEqual(await crampedChoices(s), [], width);
|
||||
}
|
||||
// A small window still stacks the choices in one column, as before.
|
||||
await s.page.setViewportSize({ width: 600, height: 800 });
|
||||
await s.page.waitForFunction(() => getComputedStyle(document.querySelector("#prefs-panel-appearance .looks-row.four")).gridTemplateColumns.split(" ").length === 1);
|
||||
});
|
||||
|
||||
test("Set your role on the dashboard opens on Appearance with agents and models loaded", async (t) => {
|
||||
fs.mkdirSync(HOME, { recursive: true });
|
||||
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, skillLaunched: true } }));
|
||||
|
||||
@@ -432,7 +432,7 @@ test("kept attachments are served read-only from the session's spec, by their ex
|
||||
assert.match(kept, /realpathSync/);
|
||||
assert.match(kept, /path\.dirname\(real\)\.toLowerCase\(\) !== realDir\.toLowerCase\(\)/, "only files directly in attachments/");
|
||||
const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8");
|
||||
assert.match(render, /return "\/attachments\/" \+ kept\[1\]\.toLowerCase\(\)/);
|
||||
assert.match(render, /return "attachments\/" \+ kept\[1\]\.toLowerCase\(\)/);
|
||||
assert.match(render, /function isComment\(t\)/, "HTML comments are not shown");
|
||||
assert.match(render, /"!": \{ mark: "!", label: "blocked"/, "a blocked task gets its marker");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
// Web console tests, the page's URLs: every URL the page uses is page-relative.
|
||||
// The macOS app's frame gets no cookie, so it signs in by a path prefix
|
||||
// (`/f/<key>/`, routes.mjs) and the page is served under it there, while a
|
||||
// browser tab has it at `/`. A relative `state` reaches the server either
|
||||
// way; a slash-leading `/state` drops the prefix and gets a 403, in the macOS
|
||||
// app only, so no other test would notice. This guard reads the page's source
|
||||
// (and the links the server hands it) and names each slash-leading one.
|
||||
// Run with: node --test scripts/test-web-console-relative-urls.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const CONSOLE_DIR = path.join(ROOT, "src", "web-console");
|
||||
const PUBLIC_DIR = path.join(CONSOLE_DIR, "public");
|
||||
|
||||
const WHY = "the macOS app serves the page under /f/<key>/, so a slash-leading URL misses the prefix and gets a 403 there; drop the leading slash";
|
||||
|
||||
// Slash-leading text that is not a URL. Any literal opening `/plan2code` is a
|
||||
// slash command (no route starts so); anything else is named here, by file
|
||||
// and exact literal, with its reason.
|
||||
const SLASH_COMMAND = /^.\/plan2code(?![\w/])|^.\/plan2code-/;
|
||||
const TEXT = new Map([
|
||||
["answers.js", new Set(["`/${offer.skill}`"])], // a skill offer's slash command
|
||||
["diff-parse.js", new Set(['"/dev/null"'])], // git's name for no file in a diff header, compared, never fetched
|
||||
["loop-parts.js", new Set(['"/api/webhooks/"'])], // a path test on a Discord address the person typed
|
||||
["skills.js", new Set(['"/"'])], // `"/" + entry.skill`, a skill's slash command
|
||||
]);
|
||||
|
||||
// Every page file the rule reads: scripts, the page and stylesheets under
|
||||
// public/, vendored code aside, as paths relative to it with forward slashes.
|
||||
function pageFiles(rel = "") {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(path.join(PUBLIC_DIR, rel), { withFileTypes: true })) {
|
||||
const p = rel ? `${rel}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "vendor") out.push(...pageFiles(p));
|
||||
} else if (/\.(js|html|css)$/.test(e.name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Each string literal in `text` (double quotes, single quotes or backticks)
|
||||
* that makes a slash-leading URL, as `{ line, literal }`, in three shapes:
|
||||
* text opening with `/` and a path character (a letter, digit, `_`, `.`, `-`
|
||||
* or `${`); a lone `"/"` that starts an expression joined on with `+`
|
||||
* (`fetch("/" + route)`; one joined in the middle of a path is fine); and
|
||||
* markup in a string whose `src`, `href` or like attribute opens with `/`
|
||||
* (`` `<img src="/x">` ``). A comment line and anything after a `//` outside
|
||||
* a string are skipped; `//` opening a string is the protocol-relative case,
|
||||
* which render.js blocks on its own. Quotes are tracked one line at a time, so
|
||||
* a template literal that spans lines, or a regex literal holding a quote,
|
||||
* can put the scan out of step for the rest of that line: a URL there goes
|
||||
* unflagged, and only the frame page test, which loads the dashboard alone,
|
||||
* would catch it at run time.
|
||||
*/
|
||||
function scriptUrls(text) {
|
||||
const hits = [];
|
||||
text.split("\n").forEach((line, i) => {
|
||||
const t = line.trim();
|
||||
if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return;
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const c = line[j];
|
||||
if (c === "/" && line[j + 1] === "/") break;
|
||||
if (c !== '"' && c !== "'" && c !== "`") continue;
|
||||
let k = j + 1;
|
||||
while (k < line.length && line[k] !== c) k += line[k] === "\\" ? 2 : 1;
|
||||
const body = line.slice(j + 1, k);
|
||||
const opens = body[0] === "/" && /[A-Za-z0-9_.$-]/.test(body[1] || "");
|
||||
const joined = body === "/" && /^\s*\+/.test(line.slice(k + 1)) && STARTS_EXPRESSION.test(line.slice(0, j));
|
||||
if (opens || joined || ATTRIBUTE_URL.test(body)) hits.push({ line: i + 1, literal: line.slice(j, k + 1) });
|
||||
j = k;
|
||||
}
|
||||
});
|
||||
return hits;
|
||||
}
|
||||
|
||||
// What may come right before an expression's first operand: nothing, an
|
||||
// opening bracket, a separator, an operator or `return`.
|
||||
const STARTS_EXPRESSION = /(?:^|[([{,=:?!&|>]|\breturn)\s*$/;
|
||||
|
||||
// An attribute that holds a URL, opening with `/` (but not `//`), in markup a
|
||||
// script builds, quoted or not and with its quote escaped or not.
|
||||
const ATTRIBUTE_URL = /\b(?:src|srcset|href|action|poster|data)=\\?["']?\/(?![/\\])/;
|
||||
|
||||
/** Each `src`, `srcset`, `href`, `action`, `poster` or `data` value opening with `/`, in either quotes. */
|
||||
function htmlUrls(text) {
|
||||
return text
|
||||
.split("\n")
|
||||
.flatMap((l, i) =>
|
||||
[...l.matchAll(/\b(?:src|srcset|href|action|poster|data)=(?:"(\/[^"]*)"|'(\/[^']*)')/g)].map((m) => ({ line: i + 1, literal: m[1] ?? m[2] }))
|
||||
);
|
||||
}
|
||||
|
||||
/** Each `url(/...)` or `@import "/..."`. */
|
||||
function cssUrls(text) {
|
||||
return text
|
||||
.split("\n")
|
||||
.flatMap((l, i) => [...l.matchAll(/url\(\s*["']?(\/[^)"']*)|@import\s+["'](\/[^"']*)/g)].map((m) => ({ line: i + 1, literal: m[1] || m[2] })));
|
||||
}
|
||||
|
||||
// A link the server builds for the page: a slash-leading literal given to a
|
||||
// name holding `url`, `href` or `src` (`url: "/uploads/..."`, `imageUrl = (...) => "/..."`).
|
||||
const SERVER_LINK = /\b\w*(?:url|href|src)\w*\s*[:=]\s*(?:\([^)]*\)\s*=>\s*)?["'`]\/(?!\/)/i;
|
||||
|
||||
function pageOffenders() {
|
||||
const out = [];
|
||||
for (const f of pageFiles()) {
|
||||
const text = fs.readFileSync(path.join(PUBLIC_DIR, f), "utf8");
|
||||
if (f.endsWith(".html")) {
|
||||
out.push(...htmlUrls(text).map((h) => ({ file: f, ...h })));
|
||||
continue;
|
||||
}
|
||||
if (f.endsWith(".css")) {
|
||||
out.push(...cssUrls(text).map((h) => ({ file: f, ...h })));
|
||||
continue;
|
||||
}
|
||||
for (const h of scriptUrls(text)) {
|
||||
if (SLASH_COMMAND.test(h.literal) || TEXT.get(f)?.has(h.literal)) continue;
|
||||
out.push({ file: f, ...h });
|
||||
}
|
||||
}
|
||||
return out.map((h) => `public/${h.file}:${h.line} ${h.literal}`);
|
||||
}
|
||||
|
||||
test("the scanner finds slash-leading literals and leaves comments, other schemes and slash commands alone", () => {
|
||||
const found = (src) => scriptUrls(src).map((h) => h.literal);
|
||||
assert.deepEqual(found('fetch("/state");'), ['"/state"']);
|
||||
assert.deepEqual(found("x('/looks', `/${a}.mp3`)"), ["'/looks'", "`/${a}.mp3`"]);
|
||||
assert.deepEqual(found('a("state"); b("https://x/y"); c("//cdn"); d("/");'), []);
|
||||
assert.deepEqual(found('// fetch("/state")'), []);
|
||||
assert.deepEqual(found(' * see "/state"'), []);
|
||||
assert.deepEqual(found('go(); // then "/state"'), []);
|
||||
assert.deepEqual(found('q("a\\"/b", "/c")'), ['"/c"']);
|
||||
// A slash joined on at the start of an expression, and markup holding one.
|
||||
assert.deepEqual(found('fetch("/" + route); x = "/" + y; return "/" + z;'), ['"/"', '"/"', '"/"']);
|
||||
assert.deepEqual(found('a("notepad/images/" + tab + "/" + id); b(sep ? "/" : "")'), []);
|
||||
assert.deepEqual(found('box.innerHTML = `<img src="/uploads/${id}.jpg">`;'), ['`<img src="/uploads/${id}.jpg">`']);
|
||||
assert.deepEqual(found("h = '<a href=\\'/state\\'>'; s = \"<img src=\\\"/x.png\\\">\";").length, 2);
|
||||
assert.deepEqual(found('h = `<img src="uploads/${id}.jpg"><a href="//cdn/x">`'), []);
|
||||
assert.ok(SLASH_COMMAND.test('"/plan2code"') && SLASH_COMMAND.test('"/plan2code-review"'));
|
||||
assert.ok(!SLASH_COMMAND.test('"/plan2codex"') && !SLASH_COMMAND.test('"/plan2code/x"'));
|
||||
assert.deepEqual(htmlUrls('<link href="/app.css" /><script src="app.js"></script>'), [{ line: 1, literal: "/app.css" }]);
|
||||
assert.deepEqual(htmlUrls("<img src='/x.png' srcset=\"/y.png 2x\">"), [
|
||||
{ line: 1, literal: "/x.png" },
|
||||
{ line: 1, literal: "/y.png 2x" },
|
||||
]);
|
||||
assert.deepEqual(cssUrls("a { background: url(/x.png) } @import \"/y.css\";"), [
|
||||
{ line: 1, literal: "/x.png" },
|
||||
{ line: 1, literal: "/y.css" },
|
||||
]);
|
||||
assert.ok(SERVER_LINK.test('url: "/uploads/" + id'));
|
||||
assert.ok(SERVER_LINK.test('const imageUrl = (tab, id) => "/notepad/images/" + tab'));
|
||||
assert.ok(!SERVER_LINK.test('url: "uploads/" + id') && !SERVER_LINK.test('{ path: "/state", run }'));
|
||||
});
|
||||
|
||||
test("every URL in the page is page-relative", () => {
|
||||
const offenders = pageOffenders();
|
||||
assert.deepEqual(offenders, [], `${offenders.length} slash-leading URL(s) in the page (${WHY}):\n${offenders.join("\n")}`);
|
||||
});
|
||||
|
||||
test("every link the server hands the page is page-relative", () => {
|
||||
const offenders = [];
|
||||
for (const f of fs.readdirSync(CONSOLE_DIR).filter((n) => n.endsWith(".mjs"))) {
|
||||
fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8")
|
||||
.split("\n")
|
||||
.forEach((l, i) => {
|
||||
if (!l.trim().startsWith("//") && SERVER_LINK.test(l)) offenders.push(`${f}:${i + 1} ${l.trim()}`);
|
||||
});
|
||||
}
|
||||
assert.deepEqual(offenders, [], `slash-leading link(s) the server builds for the page (${WHY}):\n${offenders.join("\n")}`);
|
||||
});
|
||||
|
||||
test("every name the rule lets through is still in its file", () => {
|
||||
for (const [file, literals] of TEXT) {
|
||||
const found = new Set(scriptUrls(fs.readFileSync(path.join(PUBLIC_DIR, file), "utf8")).map((h) => h.literal));
|
||||
for (const literal of literals) assert.ok(found.has(literal), `${file} no longer has ${literal}: drop it from TEXT`);
|
||||
}
|
||||
});
|
||||
@@ -83,7 +83,7 @@ test("the page carries its first state, title and badge, so the first paint need
|
||||
assert.ok(html.includes(`<h1 id="title">Lunch </script><script>alert(1)</script> $& $' app</h1>`));
|
||||
assert.ok(html.includes('<span class="pill is-accent is-caps badge" id="badge">Building</span>'));
|
||||
assert.ok(html.includes("Starting Implement"), "the static starting screen names the skill");
|
||||
assert.ok(html.includes('rel="modulepreload" href="/app.js"'));
|
||||
assert.ok(html.includes('rel="modulepreload" href="app.js"'));
|
||||
cli(["stop", "--session", res.json.sid, "--force"]);
|
||||
});
|
||||
|
||||
@@ -948,6 +948,19 @@ test("notes/quick-task.md has the finished quick task offer Back to the dashboar
|
||||
assert.ok(bullet.includes("Review it now"));
|
||||
});
|
||||
|
||||
// A review card says "Nothing has been changed yet" unless it sends nothingYet:false
|
||||
// (screens/cards.js), and both of these come after the build is on disk.
|
||||
test("notes/quick-task.md has its post-build review cards drop the nothing-changed-yet line", () => {
|
||||
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8");
|
||||
const bullet = md.slice(md.indexOf("**See it running, before the finish:**"), md.indexOf("**Archive a finished folder:**"));
|
||||
for (const title of ["See it running", "Does it look right?"]) {
|
||||
const at = bullet.indexOf(`\`review\` "${title}" (`);
|
||||
assert.ok(at >= 0, `the ${title} card is specified`);
|
||||
const spec = bullet.slice(at, bullet.indexOf("with `--wait`", at));
|
||||
assert.ok(spec.includes('"nothingYet":false'), `the ${title} card sends nothingYet:false`);
|
||||
}
|
||||
});
|
||||
|
||||
// Show me it working: a screenshot saved under <session>/shots/ posts as an
|
||||
// image block and is served back; nothing else is reachable through /shots/.
|
||||
test("an image block under the session's shots folder round-trips, and /shots/ serves nothing else", async () => {
|
||||
|
||||
@@ -685,8 +685,8 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
|
||||
assert.deepEqual([...bytes.slice(0, 4)], [0x89, 0x50, 0x4e, 0x47]);
|
||||
|
||||
const html = await (await fetch(baseUrl + "/", { headers: { cookie: cookieFor(baseUrl, token) } })).text();
|
||||
assert.ok(html.includes('href="/favicon.svg"'));
|
||||
assert.ok(html.includes('href="/favicon.png"'));
|
||||
assert.ok(html.includes('href="favicon.svg"'));
|
||||
assert.ok(html.includes('href="favicon.png"'));
|
||||
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/);
|
||||
});
|
||||
|
||||
@@ -1006,7 +1006,7 @@ test("an upload is stored under a server-chosen name inside the session's upload
|
||||
const uploads = path.join(fs.realpathSync.native(session), "uploads");
|
||||
assert.equal(path.dirname(file).toLowerCase(), uploads.toLowerCase());
|
||||
assert.equal(path.basename(file), id + ".jpg");
|
||||
assert.equal(url, `/uploads/${id}.jpg`);
|
||||
assert.equal(url, `uploads/${id}.jpg`);
|
||||
assert.equal(name, "../../evil name.png", "the name comes back as a label");
|
||||
assert.equal(res.json.kind, "image");
|
||||
assert.equal(res.json.size, JPEG.length);
|
||||
@@ -1035,7 +1035,8 @@ test("an upload that is not a JPEG, or is too large, is refused", async () => {
|
||||
});
|
||||
|
||||
test("an upload is served back by its own url, and nothing else under /uploads/ is", async () => {
|
||||
const { url } = (await uploadJpeg()).json;
|
||||
// Page-relative: the page at / asks for it here.
|
||||
const url = `/${(await uploadJpeg()).json.url}`;
|
||||
const res = await raw("GET", url);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers["content-type"], "image/jpeg");
|
||||
@@ -1048,7 +1049,8 @@ test("an upload is served back by its own url, and nothing else under /uploads/
|
||||
});
|
||||
|
||||
test("deleting an upload removes its file, once, and only from this origin", async () => {
|
||||
const { url, path: file } = (await uploadJpeg()).json;
|
||||
const { url: link, path: file } = (await uploadJpeg()).json;
|
||||
const url = `/${link}`;
|
||||
assert.equal((await raw("DELETE", url, undefined, { origin: "http://evil.example.com" })).status, 403);
|
||||
assert.ok(fs.existsSync(file));
|
||||
assert.equal((await raw("DELETE", url)).status, 204);
|
||||
|
||||
@@ -516,7 +516,7 @@ test("prefs: the new modules are served and preloaded, and Preferences' styles l
|
||||
"screens/agents/agents-form.js",
|
||||
]) {
|
||||
assert.ok(SERVABLE.has(m), `${m} is servable`);
|
||||
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`);
|
||||
}
|
||||
for (const sheet of ["styles/prefs.css", "styles/agents.css"]) {
|
||||
const css = publicSource(sheet);
|
||||
|
||||
@@ -497,7 +497,7 @@ test("music: a song plays from its file, fades in toward its level, says when it
|
||||
withSongs(async () => {
|
||||
const [name] = TRAILS_TRACKS;
|
||||
assert.equal(music(name, 1, 1, { restart: true }), "playing");
|
||||
const el = FakeAudio.made.find((a) => a.src === `/${trailsSfx.songs[name]}`);
|
||||
const el = FakeAudio.made.find((a) => a.src === trailsSfx.songs[name]);
|
||||
assert.ok(el, "an element for the song's file");
|
||||
assert.ok(!el.paused && el.plays === 1, "it plays");
|
||||
for (let i = 0; i < 20; i++) {
|
||||
@@ -520,7 +520,7 @@ test("music: a song no longer asked for fades out and pauses where it was, and a
|
||||
withSongs(async () => {
|
||||
const [first, second] = TRAILS_TRACKS;
|
||||
music(first, 1, 0.5);
|
||||
const el = FakeAudio.made.findLast((a) => a.src === `/${trailsSfx.songs[first]}`);
|
||||
const el = FakeAudio.made.findLast((a) => a.src === trailsSfx.songs[first]);
|
||||
const loads = el.loads;
|
||||
await sleep(800);
|
||||
assert.ok(el.paused, "paused once it stops being asked for");
|
||||
@@ -544,7 +544,7 @@ test("music: a song plays nothing while Play sounds is off, at a volume of 0, or
|
||||
assert.equal(music(name, 1, 0), undefined);
|
||||
globalThis.Audio = undefined;
|
||||
assert.equal(music(name, 1, 1), undefined);
|
||||
assert.ok(FakeAudio.made.filter((a) => a.src === `/${trailsSfx.songs[name]}`).every((a) => a.paused), "nothing plays");
|
||||
assert.ok(FakeAudio.made.filter((a) => a.src === trailsSfx.songs[name]).every((a) => a.paused), "nothing plays");
|
||||
}));
|
||||
|
||||
test("music: every Sunset Drive road has a song, and every song is a real track", () => {
|
||||
|
||||
@@ -1559,6 +1559,17 @@ function isEmptyFolder(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a finished picker means the person canceled. Pickers exit 0 or 1 with nothing printed
|
||||
* when canceled, but osascript also exits 1 when it fails, so on macOS an exit 1 is a cancel
|
||||
* only when stderr carries its "User canceled" number, -128.
|
||||
*/
|
||||
function pickerCancelled(status, stdout, stderr, platform = process.platform) {
|
||||
if ((stdout || '').trim()) return false;
|
||||
if (status === 0) return true;
|
||||
return status === 1 && (platform !== 'darwin' || String(stderr || '').includes('(-128)'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
|
||||
* Returns the folder, or null when the person canceled.
|
||||
@@ -1577,10 +1588,10 @@ async function pickFolder() {
|
||||
windowsHide: true,
|
||||
});
|
||||
const folder = (result.stdout || '').trim();
|
||||
// Pickers exit 0 or 1 with nothing printed when canceled; anything else means the picker
|
||||
// itself failed, so fall through to the typed prompt rather than giving up.
|
||||
// Anything but a pick or a cancel means the picker itself failed, so fall through to the
|
||||
// typed prompt rather than giving up.
|
||||
if (!result.error && folder && result.status === 0) return path.resolve(folder);
|
||||
if (!result.error && !folder && (result.status === 0 || result.status === 1)) return null;
|
||||
if (!result.error && pickerCancelled(result.status, result.stdout, result.stderr)) return null;
|
||||
}
|
||||
|
||||
const answer = (await ask(`Project folder ${c.green(`[${start}]`)}: `)).trim().replace(/^["']|["']$/g, '');
|
||||
@@ -2073,4 +2084,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { nodeVersionProblem, usageText, normalizeUpdateTagInput, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder };
|
||||
module.exports = { nodeVersionProblem, usageText, normalizeUpdateTagInput, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder, pickerCancelled };
|
||||
@@ -364,7 +364,9 @@ function imageEntries(dirs) {
|
||||
return [...seen.values()].sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||
}
|
||||
|
||||
const imageUrl = (tab, id, thumb) => "/notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg";
|
||||
// Page-relative, as every link the page uses is: the macOS app's frame has the
|
||||
// page under a path prefix (routes.mjs, takeFramePrefix).
|
||||
const imageUrl = (tab, id, thumb) => "notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg";
|
||||
|
||||
/**
|
||||
* The tabs, as `[{ id, name, sent? }]` in order (`sent` only on a tab sent
|
||||
|
||||
@@ -28,7 +28,7 @@ Read `building.md` first.
|
||||
```
|
||||
|
||||
A step that cannot be done is `- [!]` with the reason, not counted in `cleared`. A step added mid-build raises `headline.total` in the same post. Tick Verify boxes in the post that reports the checks. Do not `wait` until the build is done.
|
||||
- **See it running, before the finish:** once built, post `review` "See it running" (`"doc":"plan"`, verdicts `show` ("Show me it working"), `fine` ("No need, finish up"), tokens `show me` / `no`) with `--wait`, the `changes` doc in the same post (`notes/implement.md` → Sign-off, Changes tab); before "Does it look right?", run `diff` again and re-send its block. On `show`, see `notes/implement.md` → Show me it working; its one line goes in the finish `body`. `fine` settles the card in the finish post. After `show`, settle it in the post that shows it, then post `review` "Does it look right?" (`"doc":"shown"`, verdicts `fine` ("Looks right, finish up"), `changes` ("I want changes"), tokens `approved` / `needs changes`) with `--wait`. `changes`: make it, re-run `diff` and re-send its block, reshow if visible, reopen with a `thread` reply, wait again. Only `fine` leads to the finish.
|
||||
- **See it running, before the finish:** once built, post `review` "See it running" (`"doc":"plan"`, `"nothingYet":false`, verdicts `show` ("Show me it working"), `fine` ("No need, finish up"), tokens `show me` / `no`) with `--wait`, the `changes` doc in the same post (`notes/implement.md` → Sign-off, Changes tab); before "Does it look right?", run `diff` again and re-send its block. On `show`, see `notes/implement.md` → Show me it working; its one line goes in the finish `body`. `fine` settles the card in the finish post. After `show`, settle it in the post that shows it, then post `review` "Does it look right?" (`"doc":"shown"`, `"nothingYet":false`, verdicts `fine` ("Looks right, finish up"), `changes` ("I want changes"), tokens `approved` / `needs changes`) with `--wait`. `changes`: make it, re-run `diff` and re-send its block, reshow if visible, reopen with a `thread` reply, wait again. Only `fine` leads to the finish.
|
||||
- **Archive a finished folder:** launched on a diagnosed folder now Fixed or an upgrade folder now Done, with nothing past the diagnosis or brief, or on a folder of only prototypes now built, post `confirm` "Archive this bug?" ("Archive this upgrade?", "Archive this prototype?") in the same post as "See it running": dry run's `files` in `body`, with any prototype not built named there, `yesLabel` "Archive it", `noLabel` "Keep it in specs/", `consequences` naming `specs--completed/<name>/`. Yes: `node "<S>/specs.mjs" archive <spec>`, and say where it went in the finish `body`.
|
||||
- **Finish after the build:** `command` is the filled-in commit command in the project's format (AGENTS.md), `"where":"When you are happy with it, commit it from your terminal:"`, with `review` (**Review it now**), `"commit":true`, `"changelog":true` and `"dashboard":true`. Review and dashboard are required. Whichever button is pressed, what follows is `building-review.md`.
|
||||
- **Lessons first:** with lessons to offer (`references/lessons.md`, End), post its `card` as one `lessons` item with `--wait` before the finish.
|
||||
|
||||
+36
-20
@@ -17,8 +17,9 @@ import { spawn } from "node:child_process";
|
||||
|
||||
import { findAgent } from "./agent-lookup.mjs";
|
||||
|
||||
const IS_WINDOWS = process.platform === "win32";
|
||||
const IS_MAC = process.platform === "darwin";
|
||||
// How much of the picker's stderr is kept: the end is where osascript names
|
||||
// its error.
|
||||
const STDERR_TAIL_BYTES = 2048;
|
||||
|
||||
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
|
||||
|
||||
@@ -160,8 +161,8 @@ public static class Plan2CodeFolderPicker {
|
||||
* chosen folder, or nothing when the person cancels. Null when this OS has no
|
||||
* picker we can drive.
|
||||
*/
|
||||
export function pickerCommand(start, prompt) {
|
||||
if (IS_WINDOWS) {
|
||||
export function pickerCommand(start, prompt, { platform = process.platform } = {}) {
|
||||
if (platform === "win32") {
|
||||
const script = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
"try {",
|
||||
@@ -203,7 +204,7 @@ export function pickerCommand(start, prompt) {
|
||||
};
|
||||
}
|
||||
|
||||
if (IS_MAC) {
|
||||
if (platform === "darwin") {
|
||||
return {
|
||||
command: "osascript",
|
||||
args: [
|
||||
@@ -233,13 +234,26 @@ export function pickerCommand(start, prompt) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the picker and settle on what the person did: `{ path }` for a pick,
|
||||
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
|
||||
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
|
||||
* when canceled.
|
||||
* What a finished picker means: `{ path }` for a pick, `{ cancelled: true }`
|
||||
* when the person closed it, `{ error }` when the picker itself failed.
|
||||
* Pickers exit 0 or 1 with nothing printed when canceled, but osascript also
|
||||
* exits 1 when it fails, so on macOS an exit 1 is a cancel only when stderr
|
||||
* carries its "User canceled" number, -128.
|
||||
*/
|
||||
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
||||
const picker = pickerCommand(start, prompt);
|
||||
export function pickerOutcome(code, stdout, stderr, platform = process.platform) {
|
||||
const folder = String(stdout || "").trim();
|
||||
if (code === 0 && folder) return { path: path.resolve(folder) };
|
||||
if (!folder && code === 0) return { cancelled: true };
|
||||
if (!folder && code === 1 && (platform !== "darwin" || String(stderr || "").includes("(-128)"))) return { cancelled: true };
|
||||
return { error: "picker-failed" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the picker and settle on what the person did (see pickerOutcome), or
|
||||
* `{ error }` when this OS has no picker or it could not start.
|
||||
*/
|
||||
export function pickFolder(start, prompt, { spawnImpl = spawn, platform = process.platform } = {}) {
|
||||
const picker = pickerCommand(start, prompt, { platform });
|
||||
if (!picker) return Promise.resolve({ error: "picker-failed" });
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
@@ -252,9 +266,11 @@ export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
||||
try {
|
||||
child = spawnImpl(picker.command, picker.args, {
|
||||
env: { ...process.env, ...(picker.env || {}) },
|
||||
// stderr is ignored, not piped: a pipe nobody reads fills up and
|
||||
// blocks a chatty picker (GTK warnings) before it can exit.
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
// stderr is piped only on macOS, where osascript's (-128) there is
|
||||
// what tells a cancel from a failure, and is always read, keeping
|
||||
// only its end: a pipe nobody reads fills up and blocks a chatty
|
||||
// picker before it can exit. Elsewhere it is not needed.
|
||||
stdio: ["ignore", "pipe", platform === "darwin" ? "pipe" : "ignore"],
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch {
|
||||
@@ -265,12 +281,12 @@ export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
||||
child.stdout.setEncoding?.("utf8");
|
||||
child.stdout.on("data", (chunk) => (stdout += chunk));
|
||||
}
|
||||
let stderr = "";
|
||||
if (child.stderr) {
|
||||
child.stderr.setEncoding?.("utf8");
|
||||
child.stderr.on("data", (chunk) => (stderr = (stderr + chunk).slice(-STDERR_TAIL_BYTES)));
|
||||
}
|
||||
child.on("error", () => settle({ error: "picker-failed" }));
|
||||
child.on("close", (code) => {
|
||||
const folder = stdout.trim();
|
||||
if (code === 0 && folder) return settle({ path: path.resolve(folder) });
|
||||
if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true });
|
||||
settle({ error: "picker-failed" });
|
||||
});
|
||||
child.on("close", (code) => settle(pickerOutcome(code, stdout, stderr, platform)));
|
||||
});
|
||||
}
|
||||
@@ -29,7 +29,7 @@
|
||||
// per game. Adding a game is one file and one line here. No DOM access and no imports: the page and `node --test` both
|
||||
// import this file.
|
||||
|
||||
const entry = (id, title, blurb, more = {}) => Object.freeze({ id, title, blurb, module: `/activities/${id}.js`, ...more });
|
||||
const entry = (id, title, blurb, more = {}) => Object.freeze({ id, title, blurb, module: `activities/${id}.js`, ...more });
|
||||
|
||||
export const ACTIVITIES = Object.freeze([
|
||||
entry("snake", "Snake", "Eat, grow and dodge. Every level brings something new.", { music: 70 }),
|
||||
@@ -43,7 +43,7 @@ export const ACTIVITIES = Object.freeze([
|
||||
entry("fuse", "Hot Potato", "Pass the bomb before it blows. Last one standing wins."),
|
||||
entry("hop", "Crossing Rush", "Hop through traffic and rivers. Race your rivals to the top."),
|
||||
entry("bounce", "Bounce Road", "Toy-car mayhem: jump, stomp, fire rockets and beat five bosses. No two runs alike.", { music: 70 }),
|
||||
entry("ghoul", "Ghoul Rush", "Run and gun through a pitch-dark haunted house. Keep moving.", { music: 65, module: "/activities/ghoul-rush/ghoul.js" }),
|
||||
entry("ghoul", "Ghoul Rush", "Run and gun through a pitch-dark haunted house. Keep moving.", { music: 65, module: "activities/ghoul-rush/ghoul.js" }),
|
||||
entry("flock", "Flock Dash", "Lead your flock through the sunset sky. Dodge everything, keep the line.", { music: 70 }),
|
||||
]);
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ async function askAgain(button, status, reply) {
|
||||
button.disabled = true;
|
||||
button.textContent = "Asking…";
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [{ i: "__changes", type: "changes" }], reply }),
|
||||
|
||||
@@ -14,7 +14,7 @@ export function blockBody(b, doc) {
|
||||
if (typeof b.image !== "string") return md(b.md, "md");
|
||||
const fig = el("figure", "doc-figure");
|
||||
const img = el("img", "doc-img");
|
||||
img.src = "/shots/" + b.image.split("/").pop();
|
||||
img.src = "shots/" + b.image.split("/").pop();
|
||||
// The caption already says it: an alt repeating it is read twice, and shows
|
||||
// twice in an export whose picture would not load.
|
||||
img.alt = "";
|
||||
@@ -126,8 +126,9 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
// Only this session's uploaded images may ride along in a saved file: any other
|
||||
// address on this origin (/state, say) would copy session data into something
|
||||
// meant to be shared. A remote image keeps its own address; anything else on
|
||||
// this origin becomes its alt text.
|
||||
const INLINE_UPLOAD = /^\/(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i;
|
||||
// this origin becomes its alt text. Matched on the path below the page's own
|
||||
// folder: `/` in a browser tab, the frame's prefix in the macOS app.
|
||||
const INLINE_UPLOAD = /^(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i;
|
||||
|
||||
function imageToAlt(img) {
|
||||
const alt = img.getAttribute("alt") || "";
|
||||
@@ -148,7 +149,9 @@ async function inlineImage(img) {
|
||||
img.setAttribute("src", url.href);
|
||||
return;
|
||||
}
|
||||
if (!INLINE_UPLOAD.test(url.pathname) || url.search) return imageToAlt(img);
|
||||
const folder = new URL(".", location.href).pathname;
|
||||
const below = url.pathname.startsWith(folder) ? url.pathname.slice(folder.length) : "";
|
||||
if (!INLINE_UPLOAD.test(below) || url.search) return imageToAlt(img);
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
|
||||
@@ -69,8 +69,8 @@ export function setFavicon(state) {
|
||||
const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]');
|
||||
const pngLink = document.querySelector('link[rel="icon"][type="image/png"]');
|
||||
if (state === "plain") {
|
||||
if (svgLink) svgLink.href = "/favicon.svg";
|
||||
if (pngLink) pngLink.href = "/favicon.png";
|
||||
if (svgLink) svgLink.href = "favicon.svg";
|
||||
if (pngLink) pngLink.href = "favicon.png";
|
||||
return;
|
||||
}
|
||||
const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state));
|
||||
|
||||
@@ -5,74 +5,74 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>Plan2Code Console</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="stylesheet" href="app.css" />
|
||||
<!-- Every module up front. Without these the browser finds render.js and
|
||||
answers.js only once app.js has arrived and been parsed, and marked
|
||||
only once render.js has: three round trips in a row before the page
|
||||
can draw anything real. -->
|
||||
<link rel="modulepreload" href="/app.js" />
|
||||
<link rel="modulepreload" href="/answers.js" />
|
||||
<link rel="modulepreload" href="/skills.js" />
|
||||
<link rel="modulepreload" href="/spec-states.js" />
|
||||
<link rel="modulepreload" href="/state.js" />
|
||||
<link rel="modulepreload" href="/doc-files.js" />
|
||||
<link rel="modulepreload" href="/diff-view.js" />
|
||||
<link rel="modulepreload" href="/diff-parse.js" />
|
||||
<link rel="modulepreload" href="/send-state.js" />
|
||||
<link rel="modulepreload" href="/mention-box.js" />
|
||||
<link rel="modulepreload" href="/uploads.js" />
|
||||
<link rel="modulepreload" href="/sound.js" />
|
||||
<link rel="modulepreload" href="/looks.js" />
|
||||
<link rel="modulepreload" href="/selectors.js" />
|
||||
<link rel="modulepreload" href="/screens/core.js" />
|
||||
<link rel="modulepreload" href="/screens/ending.js" />
|
||||
<link rel="modulepreload" href="/screens/docs.js" />
|
||||
<link rel="modulepreload" href="/screens/cards.js" />
|
||||
<link rel="modulepreload" href="/screens/starting.js" />
|
||||
<link rel="modulepreload" href="/screens/dashboard.js" />
|
||||
<link rel="modulepreload" href="/screens/git-host.js" />
|
||||
<link rel="modulepreload" href="/screens/looks.js" />
|
||||
<link rel="modulepreload" href="/screens/prefs-dialog.js" />
|
||||
<link rel="modulepreload" href="/screens/agents-view.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-data.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-list-editor.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-summary.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-form.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-strengths.js" />
|
||||
<link rel="modulepreload" href="/strengths.js" />
|
||||
<link rel="modulepreload" href="/screens/cleanup.js" />
|
||||
<link rel="modulepreload" href="/screens/help-dialog.js" />
|
||||
<link rel="modulepreload" href="/screens/workspace.js" />
|
||||
<link rel="modulepreload" href="/screens/ask.js" />
|
||||
<link rel="modulepreload" href="/screens/notepad.js" />
|
||||
<link rel="modulepreload" href="/screens/activities.js" />
|
||||
<link rel="modulepreload" href="/screens/setup.js" />
|
||||
<link rel="modulepreload" href="/activities.js" />
|
||||
<link rel="modulepreload" href="/tones.js" />
|
||||
<link rel="modulepreload" href="/net.js" />
|
||||
<link rel="modulepreload" href="/render.js" />
|
||||
<link rel="modulepreload" href="/palette.js" />
|
||||
<link rel="modulepreload" href="/labels.js" />
|
||||
<link rel="modulepreload" href="/boot.js" />
|
||||
<link rel="modulepreload" href="/chat.js" />
|
||||
<link rel="modulepreload" href="/help.js" />
|
||||
<link rel="modulepreload" href="/tabs.js" />
|
||||
<link rel="modulepreload" href="/prefs.js" />
|
||||
<link rel="modulepreload" href="/starters.js" />
|
||||
<link rel="modulepreload" href="/workspace.js" />
|
||||
<link rel="modulepreload" href="/meter.js" />
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/app-bridge.js" />
|
||||
<link rel="modulepreload" href="/git-board.js" />
|
||||
<link rel="modulepreload" href="/git-board-view.js" />
|
||||
<link rel="modulepreload" href="/pr-url.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
<link rel="modulepreload" href="/notepad.js" />
|
||||
<link rel="modulepreload" href="/notepad-tabs.js" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/favicon.png" />
|
||||
<link rel="modulepreload" href="app.js" />
|
||||
<link rel="modulepreload" href="answers.js" />
|
||||
<link rel="modulepreload" href="skills.js" />
|
||||
<link rel="modulepreload" href="spec-states.js" />
|
||||
<link rel="modulepreload" href="state.js" />
|
||||
<link rel="modulepreload" href="doc-files.js" />
|
||||
<link rel="modulepreload" href="diff-view.js" />
|
||||
<link rel="modulepreload" href="diff-parse.js" />
|
||||
<link rel="modulepreload" href="send-state.js" />
|
||||
<link rel="modulepreload" href="mention-box.js" />
|
||||
<link rel="modulepreload" href="uploads.js" />
|
||||
<link rel="modulepreload" href="sound.js" />
|
||||
<link rel="modulepreload" href="looks.js" />
|
||||
<link rel="modulepreload" href="selectors.js" />
|
||||
<link rel="modulepreload" href="screens/core.js" />
|
||||
<link rel="modulepreload" href="screens/ending.js" />
|
||||
<link rel="modulepreload" href="screens/docs.js" />
|
||||
<link rel="modulepreload" href="screens/cards.js" />
|
||||
<link rel="modulepreload" href="screens/starting.js" />
|
||||
<link rel="modulepreload" href="screens/dashboard.js" />
|
||||
<link rel="modulepreload" href="screens/git-host.js" />
|
||||
<link rel="modulepreload" href="screens/looks.js" />
|
||||
<link rel="modulepreload" href="screens/prefs-dialog.js" />
|
||||
<link rel="modulepreload" href="screens/agents-view.js" />
|
||||
<link rel="modulepreload" href="screens/agents/agents-data.js" />
|
||||
<link rel="modulepreload" href="screens/agents/agents-list-editor.js" />
|
||||
<link rel="modulepreload" href="screens/agents/agents-summary.js" />
|
||||
<link rel="modulepreload" href="screens/agents/agents-form.js" />
|
||||
<link rel="modulepreload" href="screens/agents/agents-strengths.js" />
|
||||
<link rel="modulepreload" href="strengths.js" />
|
||||
<link rel="modulepreload" href="screens/cleanup.js" />
|
||||
<link rel="modulepreload" href="screens/help-dialog.js" />
|
||||
<link rel="modulepreload" href="screens/workspace.js" />
|
||||
<link rel="modulepreload" href="screens/ask.js" />
|
||||
<link rel="modulepreload" href="screens/notepad.js" />
|
||||
<link rel="modulepreload" href="screens/activities.js" />
|
||||
<link rel="modulepreload" href="screens/setup.js" />
|
||||
<link rel="modulepreload" href="activities.js" />
|
||||
<link rel="modulepreload" href="tones.js" />
|
||||
<link rel="modulepreload" href="net.js" />
|
||||
<link rel="modulepreload" href="render.js" />
|
||||
<link rel="modulepreload" href="palette.js" />
|
||||
<link rel="modulepreload" href="labels.js" />
|
||||
<link rel="modulepreload" href="boot.js" />
|
||||
<link rel="modulepreload" href="chat.js" />
|
||||
<link rel="modulepreload" href="help.js" />
|
||||
<link rel="modulepreload" href="tabs.js" />
|
||||
<link rel="modulepreload" href="prefs.js" />
|
||||
<link rel="modulepreload" href="starters.js" />
|
||||
<link rel="modulepreload" href="workspace.js" />
|
||||
<link rel="modulepreload" href="meter.js" />
|
||||
<link rel="modulepreload" href="subagents.js" />
|
||||
<link rel="modulepreload" href="mentions.js" />
|
||||
<link rel="modulepreload" href="favicon.js" />
|
||||
<link rel="modulepreload" href="app-bridge.js" />
|
||||
<link rel="modulepreload" href="git-board.js" />
|
||||
<link rel="modulepreload" href="git-board-view.js" />
|
||||
<link rel="modulepreload" href="pr-url.js" />
|
||||
<link rel="modulepreload" href="vendor/marked.esm.js" />
|
||||
<link rel="modulepreload" href="notepad.js" />
|
||||
<link rel="modulepreload" href="notepad-tabs.js" />
|
||||
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="favicon.png" />
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip" href="#main">Skip to the questions</a>
|
||||
@@ -4653,6 +4653,6 @@
|
||||
</footer>
|
||||
|
||||
<!-- p2c:boot -->
|
||||
<script type="module" src="/app.js"></script>
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -139,7 +139,7 @@ export async function syncLooks() {
|
||||
if (boot && "looks" in boot) saved = boot.looks ? { looks: boot.looks } : null;
|
||||
else {
|
||||
try {
|
||||
const res = await fetch("/looks");
|
||||
const res = await fetch("looks");
|
||||
if (res.ok) saved = await res.json();
|
||||
} catch {}
|
||||
}
|
||||
@@ -184,7 +184,7 @@ function pushLooks() {
|
||||
undo();
|
||||
return { ok: false, error: error || "Could not save." };
|
||||
};
|
||||
return fetch("/looks", {
|
||||
return fetch("looks", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
|
||||
@@ -61,7 +61,7 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
|
||||
host.className = "md-host" + (className ? " " + className : "");
|
||||
if (id) host.id = id;
|
||||
const root = host.attachShadow({ mode: "open" });
|
||||
const sheets = ["/notepad-editor.css", "/md-field.css"].map((href) => {
|
||||
const sheets = ["notepad-editor.css", "md-field.css"].map((href) => {
|
||||
const link = document.createElement("link");
|
||||
link.rel = "stylesheet";
|
||||
link.href = href;
|
||||
|
||||
@@ -413,7 +413,7 @@ let songTicker = null;
|
||||
|
||||
function songElement(name) {
|
||||
if (!songAudio.has(name)) {
|
||||
const el = new Audio(`/${SONGS[name]}`);
|
||||
const el = new Audio(SONGS[name]);
|
||||
el.preload = "auto";
|
||||
el.volume = 0;
|
||||
songAudio.set(name, el);
|
||||
|
||||
@@ -208,7 +208,7 @@ export function makeCodeMirrorEditor(parent, { onChange, label }) {
|
||||
const root = host.attachShadow({ mode: "open" });
|
||||
const sheet = document.createElement("link");
|
||||
sheet.rel = "stylesheet";
|
||||
sheet.href = "/notepad-editor.css";
|
||||
sheet.href = "notepad-editor.css";
|
||||
const mount = document.createElement("div");
|
||||
mount.className = "notepad-cm";
|
||||
root.append(sheet, mount);
|
||||
|
||||
@@ -73,7 +73,7 @@ function safeHref(href) {
|
||||
if (!href) return null;
|
||||
const trimmed = String(href).trim();
|
||||
const kept = KEPT_ATTACHMENT.exec(trimmed);
|
||||
if (kept) return "/attachments/" + kept[1].toLowerCase();
|
||||
if (kept) return "attachments/" + kept[1].toLowerCase();
|
||||
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
|
||||
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
|
||||
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
|
||||
|
||||
@@ -654,7 +654,9 @@ async function loadGame(entry) {
|
||||
if (games.has(entry.id)) return games.get(entry.id);
|
||||
if (!loading.has(entry.id)) {
|
||||
const made = (async () => {
|
||||
const def = entry.game || (await import(entry.module)).default;
|
||||
// `module` is page-relative, as every URL the page uses is, and import()
|
||||
// takes no bare path: resolved against the page, as fetch() would.
|
||||
const def = entry.game || (await import(new URL(entry.module, document.baseURI).href)).default;
|
||||
defs.set(entry.id, def);
|
||||
if (def.lowerIsBetter) lowerIsBetter.add(entry.id);
|
||||
else lowerIsBetter.delete(entry.id);
|
||||
|
||||
@@ -306,7 +306,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
let state = ctx.templateState.get(command) || "unknown";
|
||||
if (state === "unknown") {
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
const res = await fetch("agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command }),
|
||||
@@ -337,7 +337,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
rows.map(async (row) => {
|
||||
let state = "unknown";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
const res = await fetch("agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command: row.command }),
|
||||
@@ -355,7 +355,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
// The command's Test: where it would run from. Never saves.
|
||||
async function testCommand(command) {
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
const res = await fetch("agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command }),
|
||||
@@ -373,7 +373,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
// press is the one failure the status line gets.
|
||||
async function useFromHere(entry) {
|
||||
try {
|
||||
const res = await fetch("/agents/use-path", {
|
||||
const res = await fetch("agents/use-path", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ id: entry.id }),
|
||||
@@ -436,7 +436,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
const modelIds = [...ctx.saved.shipped[cli], ...sent].map((m) => m.id);
|
||||
const payload = { models: { ...ctx.saved.user, [cli]: sent } };
|
||||
if (ctx.modelsLoaded) payload.strengths = strengthsToSend(cli, key, modelIds);
|
||||
const { res, body } = await postJson("/models", payload);
|
||||
const { res, body } = await postJson("models", payload);
|
||||
if (!res.ok) {
|
||||
formMark({ ok: false, error: body.error || "Could not save." });
|
||||
return false;
|
||||
@@ -465,7 +465,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
const agents = ctx.saved.agents.map((a) => cleanAgent(a));
|
||||
agents.splice(at, isNew ? 0 : 1, cleanAgent(draft));
|
||||
try {
|
||||
const { res, body } = await postJson("/agents", replace ? { agents, replace: true } : { agents });
|
||||
const { res, body } = await postJson("agents", replace ? { agents, replace: true } : { agents });
|
||||
if (res.status === 409) {
|
||||
ctx.formError = { field: null, error: body.error || "Not saved." };
|
||||
ctx.formReplace = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
@@ -504,7 +504,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
return false;
|
||||
};
|
||||
try {
|
||||
const { res, body } = await postJson("/models", { models: ctx.saved.user, strengths: strengthsToSend(id, key, modelIds) });
|
||||
const { res, body } = await postJson("models", { models: ctx.saved.user, strengths: strengthsToSend(id, key, modelIds) });
|
||||
if (!res.ok) return strengthsFailed(body.error || "Saved, but the strengths could not be.");
|
||||
ctx.saved.strengths.user = body.strengths || {};
|
||||
} catch {
|
||||
@@ -526,7 +526,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
const agents = ctx.saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent);
|
||||
ctx.confirming = false;
|
||||
try {
|
||||
const { res, body } = await postJson("/agents", { agents });
|
||||
const { res, body } = await postJson("agents", { agents });
|
||||
if (!res.ok) {
|
||||
ctx.formError = { field: null, error: body.error || "Could not delete." };
|
||||
drawForm(ctx);
|
||||
@@ -592,8 +592,8 @@ export function mountAgentsView(container, opts = {}) {
|
||||
ctx.formReplace = null;
|
||||
ctx.confirming = false;
|
||||
const [agents, models] = await Promise.all([
|
||||
fetch("/agents").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
mode === "setup" ? Promise.resolve(null) : fetch("/models").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
fetch("agents").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
mode === "setup" ? Promise.resolve(null) : fetch("models").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
]);
|
||||
if (seq !== loadSeq) return;
|
||||
const problems = [];
|
||||
|
||||
@@ -592,7 +592,7 @@ async function postChat(pend) {
|
||||
let res = null;
|
||||
let body = {};
|
||||
try {
|
||||
res = await fetch("/chat", {
|
||||
res = await fetch("chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -641,7 +641,7 @@ async function newConversation() {
|
||||
let res = null;
|
||||
let body = {};
|
||||
try {
|
||||
res = await fetch("/chat", {
|
||||
res = await fetch("chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ reset: true, conversation: askConversation() }),
|
||||
@@ -674,7 +674,7 @@ async function decideChat(re, decision, text) {
|
||||
let ok = false;
|
||||
let body = {};
|
||||
try {
|
||||
const res = await fetch("/chat/decision", {
|
||||
const res = await fetch("chat/decision", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }),
|
||||
@@ -1176,7 +1176,7 @@ export async function saveSubagents() {
|
||||
};
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
const res = await postJson("subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) {
|
||||
|
||||
@@ -141,7 +141,7 @@ async function scanCleanup() {
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
const { status, body } = await postJson("cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
@@ -169,7 +169,7 @@ async function deleteCleanup() {
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
cleanupBusy = true;
|
||||
const { status, body } = await postJson("/cleanup", { delete: ids }).finally(() => {
|
||||
const { status, body } = await postJson("cleanup", { delete: ids }).finally(() => {
|
||||
cleanupBusy = false;
|
||||
});
|
||||
if (gen !== cleanupGen) return;
|
||||
|
||||
@@ -234,7 +234,7 @@ function fillNoteBox() {
|
||||
async function seedNoteBox(item, ns) {
|
||||
const tab = encodeURIComponent(ns.tab);
|
||||
try {
|
||||
const res = await fetch("/notepad?tab=" + tab, { cache: "no-store" });
|
||||
const res = await fetch("notepad?tab=" + tab, { cache: "no-store" });
|
||||
if (res.status === 404) {
|
||||
banner("That Notebook tab is gone; the box starts empty.", "warn");
|
||||
return;
|
||||
@@ -251,7 +251,7 @@ async function seedNoteBox(item, ns) {
|
||||
const files = await Promise.all(
|
||||
(ns.pictures || []).map(async (id) => {
|
||||
try {
|
||||
const r = await fetch("/notepad/images/" + tab + "/" + encodeURIComponent(id) + ".jpg", { cache: "no-store" });
|
||||
const r = await fetch("notepad/images/" + tab + "/" + encodeURIComponent(id) + ".jpg", { cache: "no-store" });
|
||||
return r.ok ? new File([await r.blob()], id + ".jpg", { type: "image/jpeg" }) : null;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -264,7 +264,7 @@ async function seedNoteBox(item, ns) {
|
||||
|
||||
async function pushDraft() {
|
||||
try {
|
||||
await fetch("/draft", {
|
||||
await fetch("draft", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ staged: page.local.staged, drafts: page.local.drafts, images: page.local.images, seeded: page.local.seeded }),
|
||||
@@ -284,7 +284,7 @@ function agentStale() {
|
||||
|
||||
export async function loadState() {
|
||||
try {
|
||||
const res = await fetch("/state", { cache: "no-store" });
|
||||
const res = await fetch("state", { cache: "no-store" });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const body = await res.json();
|
||||
// The same rev is the same state: adopting it again would redraw the page
|
||||
@@ -759,7 +759,7 @@ function markGone() {
|
||||
export function connect() {
|
||||
esErrors = 0;
|
||||
try {
|
||||
es = new EventSource(lastHave ? "/events?have=" + encodeURIComponent(lastHave) : "/events");
|
||||
es = new EventSource(lastHave ? "events?have=" + encodeURIComponent(lastHave) : "events");
|
||||
} catch {
|
||||
es = null;
|
||||
return startPolling();
|
||||
@@ -846,7 +846,7 @@ function retryStream() {
|
||||
// whether the agent is, whether a state frame went missing, and whether a
|
||||
// send is still waiting to be picked up.
|
||||
export function checkIn() {
|
||||
fetch("/ping", { method: "POST" })
|
||||
fetch("ping", { method: "POST" })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((body) => {
|
||||
if (!body) return;
|
||||
@@ -2194,7 +2194,7 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
||||
const ns = page.local.noteSent;
|
||||
if (ns && sentIds.has(ns.item)) {
|
||||
page.local.noteSent = null;
|
||||
fetch("/notepad/tab/sent", {
|
||||
fetch("notepad/tab/sent", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ id: ns.tab, workflow: ns.workflow, ...(ns.spec ? { spec: ns.spec } : {}) }),
|
||||
@@ -2223,7 +2223,7 @@ export async function askSuggestions(itemId) {
|
||||
const text = note ? note.text : "";
|
||||
const images = note ? note.images : [];
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -2275,7 +2275,7 @@ export async function send() {
|
||||
$("send-nudge").hidden = true;
|
||||
btn.textContent = "Sending…";
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions, reply: replyLines.join("\n") }),
|
||||
@@ -2327,7 +2327,7 @@ export async function send() {
|
||||
// server is the lost-contact state now, with its reconnect help; a server
|
||||
// still there was a blip, and Send is the whole fix.
|
||||
async function sendLost() {
|
||||
const up = await fetch("/state", { cache: "no-store" })
|
||||
const up = await fetch("state", { cache: "no-store" })
|
||||
.then((res) => res.ok)
|
||||
.catch(() => false);
|
||||
if (up) {
|
||||
@@ -2489,7 +2489,7 @@ let whereResizeTimer = null;
|
||||
// A link the console could not hand to a browser is shown, with a Copy
|
||||
// button, for the person to paste into one.
|
||||
async function openOutside(href) {
|
||||
const ok = await fetch("/open-link", {
|
||||
const ok = await fetch("open-link", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ url: href }),
|
||||
@@ -2503,8 +2503,11 @@ async function openOutside(href) {
|
||||
|
||||
export function wireChrome() {
|
||||
addEventListener("pagehide", () => {
|
||||
// A keepalive fetch, not sendBeacon: WebKit sends a beacon from a page
|
||||
// with `referrer-policy: no-referrer` with `Origin: null`, which /bye's
|
||||
// origin check refuses.
|
||||
try {
|
||||
navigator.sendBeacon("/bye");
|
||||
fetch("bye", { method: "POST", keepalive: true }).catch(() => {});
|
||||
} catch {}
|
||||
// A page that goes away leaves no dot on the app's taskbar behind it.
|
||||
tellAttention("plain");
|
||||
|
||||
@@ -387,7 +387,7 @@ function maybeWake() {
|
||||
page.wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() };
|
||||
wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
if (wakeHoldsChime && soundOn("snore")) {
|
||||
snore = new Audio("/sleeping.mp3");
|
||||
snore = new Audio("sleeping.mp3");
|
||||
snore.loop = true;
|
||||
snore.play().catch(() => {});
|
||||
}
|
||||
@@ -709,7 +709,7 @@ async function pickUpHandoff(h) {
|
||||
page.launchScoping = true;
|
||||
await hooks.syncWorkspaceScope(h.spec || "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }),
|
||||
@@ -741,7 +741,7 @@ async function readHandoff(h) {
|
||||
body.replaceChildren(el("p", "md-p", "Reading…"));
|
||||
$("handoff-modal").showModal();
|
||||
try {
|
||||
const res = await fetch("/handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" });
|
||||
const res = await fetch("handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" });
|
||||
if (res.status !== 200) throw new Error(String(res.status));
|
||||
mdInto(body, await res.text());
|
||||
} catch {
|
||||
@@ -836,14 +836,14 @@ export function pendingNotePick(entry) {
|
||||
// grayed, so each must be read). Read only: GET /notepad never writes.
|
||||
async function readNoteTabs(state) {
|
||||
try {
|
||||
const res = await fetch("/notepad", { cache: "no-store" });
|
||||
const res = await fetch("notepad", { cache: "no-store" });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const body = await res.json();
|
||||
const tabs = Array.isArray(body.tabs) ? body.tabs : [];
|
||||
const read = await Promise.all(
|
||||
tabs.map(async (t) => {
|
||||
try {
|
||||
const r = await fetch("/notepad?tab=" + encodeURIComponent(t.id), { cache: "no-store" });
|
||||
const r = await fetch("notepad?tab=" + encodeURIComponent(t.id), { cache: "no-store" });
|
||||
if (!r.ok) return null;
|
||||
const b = await r.json();
|
||||
return b && b.tab ? { text: typeof b.tab.text === "string" ? b.tab.text : "", images: Array.isArray(b.tab.images) ? b.tab.images : [] } : null;
|
||||
@@ -1243,7 +1243,7 @@ export async function launchSkill(entry) {
|
||||
page.launchScoping = true;
|
||||
await hooks.syncWorkspaceScope(target ? target.dir : "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -1390,7 +1390,7 @@ async function sendDeleteHandoff(h) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }),
|
||||
@@ -1422,7 +1422,7 @@ async function sendDelete(spec) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }),
|
||||
@@ -1512,7 +1512,7 @@ function learningBanner(sc) {
|
||||
// quiet: the nudge simply stays, as it did before.
|
||||
async function quietTidyNudge() {
|
||||
try {
|
||||
await postJson("/learning/tidy-quiet", {});
|
||||
await postJson("learning/tidy-quiet", {});
|
||||
} catch {}
|
||||
redraw();
|
||||
}
|
||||
@@ -1582,7 +1582,7 @@ export async function sendLearning(what) {
|
||||
if (what === "review" || what === "tidy") watchLearningBusy(busy);
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [learningAction(what)], reply: learningReply(what) }),
|
||||
|
||||
@@ -82,7 +82,7 @@ export async function sendBrief() {
|
||||
go.disabled = true;
|
||||
go.textContent = "Asking…";
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -322,7 +322,7 @@ export function renderAgentsDoc(main) {
|
||||
// default browser (the app's webview opens no windows, and a page served over
|
||||
// http cannot open a file:// link). A failure says so on the banner.
|
||||
async function openPrototypePage(spec, name) {
|
||||
const ok = await fetch("/open-prototype", {
|
||||
const ok = await fetch("open-prototype", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ spec, name }),
|
||||
|
||||
@@ -195,7 +195,7 @@ let loopLessons = { key: null, line: "" };
|
||||
function loopLessonsFor(key) {
|
||||
if (loopLessons.key === key) return loopLessons.line;
|
||||
loopLessons = { key, line: "" };
|
||||
fetch("/learning/state", { cache: "no-store" })
|
||||
fetch("learning/state", { cache: "no-store" })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((learning) => {
|
||||
const line = loopLessonsLine(learning);
|
||||
@@ -907,7 +907,7 @@ const AFTER_FINISH_REPLIES = { review: REVIEW_REPLY, done: DONE_REPLY, dashboard
|
||||
async function sendAfterBuild(kind, launch = null) {
|
||||
if (page.gone || page.pendingResult || page.local.afterBuild) return;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -1100,7 +1100,7 @@ async function goHome() {
|
||||
const payload = hooks.stagedPayload();
|
||||
payload.actions.push({ i: "__dashboard", type: "dashboard" });
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, HOME_REPLY].join("\n") }),
|
||||
@@ -1180,7 +1180,7 @@ async function stopSession(handoff = false) {
|
||||
const payload = hooks.stagedPayload();
|
||||
payload.actions.push(stopAction({ handoff }));
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }),
|
||||
|
||||
@@ -144,7 +144,7 @@ async function sendGit(op, fields = {}, wording = {}) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -281,7 +281,7 @@ function gitTabKeys(e) {
|
||||
// the action that follows has the agent re-read, which rebuilds the link.
|
||||
async function pickPrHost(host, kind) {
|
||||
if (gitLocked()) return;
|
||||
const res = await postJson("/pr-host", { host, kind });
|
||||
const res = await postJson("pr-host", { host, kind });
|
||||
if (res.status !== 200) {
|
||||
hooks.banner("That could not be saved. Try again in a moment.", "warn");
|
||||
return;
|
||||
|
||||
@@ -209,7 +209,7 @@ let helpTabs = null;
|
||||
async function renderHelpVersion() {
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const res = await fetch("version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
|
||||
@@ -86,7 +86,7 @@ function pauseSwitch(paused) {
|
||||
if (pausing) return;
|
||||
pausing = true;
|
||||
redraw();
|
||||
const { status } = await postJson("/learning/pause", { paused: !paused });
|
||||
const { status } = await postJson("learning/pause", { paused: !paused });
|
||||
pausing = false;
|
||||
if (status !== 200) {
|
||||
hooks.banner(
|
||||
@@ -567,7 +567,7 @@ async function openLessons() {
|
||||
body.replaceChildren(el("p", "md-p", "Reading…"));
|
||||
dlg.showModal();
|
||||
try {
|
||||
const res = await fetch("/learning/lessons", { cache: "no-store" });
|
||||
const res = await fetch("learning/lessons", { cache: "no-store" });
|
||||
if (res.status !== 200) throw new Error(String(res.status));
|
||||
const { files, follows } = await res.json();
|
||||
body.replaceChildren();
|
||||
|
||||
@@ -61,7 +61,7 @@ export async function openLoopSetup(spec) {
|
||||
const mine = page.loopSetup;
|
||||
let res;
|
||||
try {
|
||||
res = await fetch("/loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" });
|
||||
res = await fetch("loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" });
|
||||
} catch {
|
||||
res = null;
|
||||
}
|
||||
@@ -129,7 +129,7 @@ function ensureResolved(s) {
|
||||
s.facts.resolved = null;
|
||||
return;
|
||||
}
|
||||
fetch("/loop-setup?spec=" + encodeURIComponent(s.spec) + "&agent=" + encodeURIComponent(agent), { cache: "no-store" })
|
||||
fetch("loop-setup?spec=" + encodeURIComponent(s.spec) + "&agent=" + encodeURIComponent(agent), { cache: "no-store" })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.catch(() => null)
|
||||
.then((answer) => {
|
||||
@@ -371,7 +371,7 @@ async function askForSuggestion(s, words) {
|
||||
strengths: words,
|
||||
};
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [action], reply: `Suggest a strength for each phase left in ${s.spec}.` }),
|
||||
@@ -741,7 +741,7 @@ async function sendTest(s) {
|
||||
s.problems = [];
|
||||
page.loopNotifyTest = { waiting: true };
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s));
|
||||
const { status, body: answer } = await postJson("loop-setup", setupBody(f, s));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
page.loopNotifyTest = null;
|
||||
@@ -759,7 +759,7 @@ async function startLoop(s) {
|
||||
page.loopStart = null;
|
||||
s.starting = true;
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s));
|
||||
const { status, body: answer } = await postJson("loop-setup", setupBody(f, s));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
s.starting = false;
|
||||
|
||||
@@ -160,7 +160,7 @@ async function send() {
|
||||
sending = true;
|
||||
const sent = rev;
|
||||
const tab = saveTab;
|
||||
const res = await postJson("/notepad/text?tab=" + tab, { text: editor.getValue() });
|
||||
const res = await postJson("notepad/text?tab=" + tab, { text: editor.getValue() });
|
||||
sending = false;
|
||||
// The tab was deleted or left behind while this was out: nothing in the
|
||||
// answer applies to what is on screen now.
|
||||
@@ -231,7 +231,7 @@ async function makeEditor() {
|
||||
// be reached or answered oddly.
|
||||
async function readNote(tab) {
|
||||
try {
|
||||
const res = await fetch("/notepad" + (tab ? "?tab=" + encodeURIComponent(tab) : ""), { cache: "no-store" });
|
||||
const res = await fetch("notepad" + (tab ? "?tab=" + encodeURIComponent(tab) : ""), { cache: "no-store" });
|
||||
let body = null;
|
||||
try {
|
||||
body = await res.json();
|
||||
@@ -323,7 +323,7 @@ async function showTab(id, remember = true) {
|
||||
return false;
|
||||
}
|
||||
show(res.body);
|
||||
if (remember && activeId) postJson("/notepad/tab/last", { id: activeId });
|
||||
if (remember && activeId) postJson("notepad/tab/last", { id: activeId });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -349,7 +349,7 @@ async function reorder(order, focus) {
|
||||
tabBar.focusTab(focus);
|
||||
const at = order.indexOf(focus);
|
||||
if (at >= 0) inform(`Moved ${nameOf(focus)} to position ${at + 1} of ${order.length}`);
|
||||
const res = await postJson("/notepad/tab/order", { order });
|
||||
const res = await postJson("notepad/tab/order", { order });
|
||||
if (res.status === 200) return;
|
||||
// Refused: draw what the server has, and say why.
|
||||
tabs = before;
|
||||
@@ -438,7 +438,7 @@ function closeNameForm(toFocus = true) {
|
||||
async function createNamed(name) {
|
||||
// The tab on screen is saved first, then the new one is made and shown.
|
||||
if (!(await settled())) return nameError(STAY);
|
||||
const res = await postJson("/notepad/tab", { name });
|
||||
const res = await postJson("notepad/tab", { name });
|
||||
const id = res.body && res.body.id;
|
||||
if (res.status !== 200 || !TAB_ID_RE.test(String(id))) {
|
||||
return nameError(errorSentence(res.status === 0 ? null : res.body && res.body.error));
|
||||
@@ -456,7 +456,7 @@ async function createNamed(name) {
|
||||
|
||||
async function renameTo(name) {
|
||||
const id = activeId;
|
||||
const res = await postJson("/notepad/tab/rename", { id, name });
|
||||
const res = await postJson("notepad/tab/rename", { id, name });
|
||||
if (res.status !== 200) {
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
if (code !== "no-such-tab") return nameError(errorSentence(code));
|
||||
@@ -530,7 +530,7 @@ async function confirmDelete() {
|
||||
busy = true;
|
||||
drawTabs();
|
||||
paintDelete();
|
||||
const res = await postJson("/notepad/tab/delete", { id });
|
||||
const res = await postJson("notepad/tab/delete", { id });
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
busy = false;
|
||||
stage = "none";
|
||||
@@ -592,14 +592,14 @@ async function upload(entry) {
|
||||
entry.status = "uploading";
|
||||
if (live(entry)) drawStrip();
|
||||
if (!entry.id) {
|
||||
const res = await postJpeg("/notepad/image?tab=" + entry.tab, encoded.blob);
|
||||
const res = await postJpeg("notepad/image?tab=" + entry.tab, encoded.blob);
|
||||
const id = res.body && res.body.id;
|
||||
if (res.status !== 200 || !IMAGE_ID_RE.test(String(id))) return failed(entry, res);
|
||||
entry.id = id;
|
||||
// The server names the URL (it carries the tab).
|
||||
entry.url = res.body.url;
|
||||
}
|
||||
const res = await postJpeg("/notepad/thumb?id=" + entry.id + "&tab=" + entry.tab, encoded.thumbBlob);
|
||||
const res = await postJpeg("notepad/thumb?id=" + entry.id + "&tab=" + entry.tab, encoded.thumbBlob);
|
||||
if (res.status !== 200) return failed(entry, res);
|
||||
pending.delete(entry.key);
|
||||
entry.status = "ready";
|
||||
@@ -756,7 +756,7 @@ async function remove(entry) {
|
||||
if (entry.id) {
|
||||
entry.deleting = true;
|
||||
drawStrip();
|
||||
const res = await postJson("/notepad/image/delete?tab=" + entry.tab, { id: entry.id });
|
||||
const res = await postJson("notepad/image/delete?tab=" + entry.tab, { id: entry.id });
|
||||
entry.deleting = false;
|
||||
// The tab was left (or deleted) while this was out: nothing here to update.
|
||||
if (!live(entry)) return;
|
||||
|
||||
@@ -42,7 +42,7 @@ export async function openReviewLoopSetup(spec) {
|
||||
const mine = page.reviewLoopSetup;
|
||||
let res;
|
||||
try {
|
||||
res = await fetch("/review-loop-setup?facts=1" + (dir ? "&spec=" + encodeURIComponent(dir) : ""), { cache: "no-store" });
|
||||
res = await fetch("review-loop-setup?facts=1" + (dir ? "&spec=" + encodeURIComponent(dir) : ""), { cache: "no-store" });
|
||||
} catch {
|
||||
res = null;
|
||||
}
|
||||
@@ -97,7 +97,7 @@ function ensureResolved(s) {
|
||||
s.facts.resolved = null;
|
||||
return;
|
||||
}
|
||||
fetch("/review-loop-setup?agent=" + encodeURIComponent(agent), { cache: "no-store" })
|
||||
fetch("review-loop-setup?agent=" + encodeURIComponent(agent), { cache: "no-store" })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.catch(() => null)
|
||||
.then((answer) => {
|
||||
@@ -371,7 +371,7 @@ async function saveNotify(s) {
|
||||
if (url === (facts.notifyUrl || "") && f.notifyKind === (facts.notifyKind || "query") && param === (facts.notifyParam || "message")) return "";
|
||||
let current = null;
|
||||
try {
|
||||
const res = await fetch("/loop-setup", { cache: "no-store" });
|
||||
const res = await fetch("loop-setup", { cache: "no-store" });
|
||||
current = res.ok ? await res.json() : null;
|
||||
} catch {
|
||||
current = null;
|
||||
@@ -379,7 +379,7 @@ async function saveNotify(s) {
|
||||
if (!current) return "The notification address could not be saved. Try again.";
|
||||
// The loop's own screen drops these two before it saves; the store rejects them as unknown fields.
|
||||
const { remembered, saved, ...entry } = current;
|
||||
const { status, body } = await postJson("/loop-setup", { ...entry, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param });
|
||||
const { status, body } = await postJson("loop-setup", { ...entry, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param });
|
||||
if (status !== 200 || !body || body.ok !== true) {
|
||||
return Array.isArray(body && body.problems) && body.problems.length ? body.problems.join(" ") : "The notification address could not be saved. Try again.";
|
||||
}
|
||||
@@ -420,7 +420,7 @@ async function startReviewLoop(s) {
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
const { status, body } = await postJson("/review-loop-setup", reviewSetupBody(f));
|
||||
const { status, body } = await postJson("review-loop-setup", reviewSetupBody(f));
|
||||
if (page.reviewLoopSetup !== s) return;
|
||||
if (status !== 200 || !body || body.ok !== true) {
|
||||
s.starting = false;
|
||||
|
||||
@@ -54,7 +54,7 @@ async function onStart(entry) {
|
||||
page.local.setupStart = { id: entry.id, label, at: Date.now() };
|
||||
saveNow();
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
const res = await fetch("submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [{ i: "__start", type: "start", agent: entry.id }], reply: "Start with " + label }),
|
||||
|
||||
@@ -54,7 +54,7 @@ export async function syncWorkspaceScope(spec) {
|
||||
page.scopeMine = want;
|
||||
if ((page.wsFrame.scope || "") === want || scopeAsked === want) return;
|
||||
scopeAsked = want;
|
||||
const { status, body } = await postJson("/workspace/scope", { spec: want });
|
||||
const { status, body } = await postJson("workspace/scope", { spec: want });
|
||||
if (status === 200 && body && Array.isArray(body.folders)) page.wsFrame = { ...page.wsFrame, ...body };
|
||||
scopeAsked = null;
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
@@ -83,7 +83,7 @@ let wsBusy = false;
|
||||
export async function openWorkspace() {
|
||||
const dlg = $("workspace-modal");
|
||||
try {
|
||||
const res = await fetch("/workspace?check=1", { cache: "no-store" });
|
||||
const res = await fetch("workspace?check=1", { cache: "no-store" });
|
||||
if (res.ok) page.wsFrame = await res.json();
|
||||
} catch {}
|
||||
wsConfirm = null;
|
||||
@@ -203,7 +203,7 @@ function workspaceField(f, field, labelText) {
|
||||
input.value = saved();
|
||||
return showError("");
|
||||
}
|
||||
const { status, body } = await postJson("/workspace/edit", { id: f.id, [field]: value });
|
||||
const { status, body } = await postJson("workspace/edit", { id: f.id, [field]: value });
|
||||
// An earlier "Added as @x" is out of date once the list moves on.
|
||||
if (status === 200) {
|
||||
setAddMsg("");
|
||||
@@ -271,7 +271,7 @@ function paintWorkspaceRow(li, f) {
|
||||
go.type = "button";
|
||||
go.addEventListener("click", async () => {
|
||||
go.disabled = true;
|
||||
const { status } = await postJson("/workspace/remove", { id: f.id });
|
||||
const { status } = await postJson("workspace/remove", { id: f.id });
|
||||
wsConfirm = null;
|
||||
if (status === 200) setAddMsg("");
|
||||
if (status !== 200) setAddMsg(`@${f.name} could not be removed. Try again.`, "error");
|
||||
@@ -290,7 +290,7 @@ async function addWorkspaceFolder(path, name) {
|
||||
if (!trimmed || wsBusy || loopDriving()) return;
|
||||
wsBusy = true;
|
||||
$("workspace-add").disabled = true;
|
||||
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
|
||||
const { status, body } = await postJson("workspace/add", name ? { path: trimmed, name } : { path: trimmed });
|
||||
wsBusy = false;
|
||||
$("workspace-add").disabled = false;
|
||||
if (status === 200) {
|
||||
@@ -327,7 +327,7 @@ async function browseWorkspace() {
|
||||
if (b.disabled || loopDriving()) return;
|
||||
b.disabled = true;
|
||||
setAddMsg("Waiting for the folder picker…");
|
||||
const { status, body } = await postJson("/workspace/browse", {});
|
||||
const { status, body } = await postJson("workspace/browse", {});
|
||||
b.disabled = false;
|
||||
if (status === 200 && body.path) {
|
||||
setAddMsg("");
|
||||
|
||||
@@ -342,7 +342,7 @@ export function specFileTabs() {
|
||||
|
||||
async function fetchSpecFile(spec, kind) {
|
||||
try {
|
||||
const res = await fetch("/overview?spec=" + encodeURIComponent(spec) + "&file=" + kind, { cache: "no-store" });
|
||||
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() };
|
||||
@@ -382,7 +382,7 @@ export const prototypesTabShown = () => page.prototypes.key === overviewSpec() &
|
||||
|
||||
async function fetchPrototypeList(spec) {
|
||||
try {
|
||||
const res = await fetch("/prototypes?spec=" + encodeURIComponent(spec), { cache: "no-store" });
|
||||
const res = await fetch("prototypes?spec=" + encodeURIComponent(spec), { cache: "no-store" });
|
||||
if (res.status !== 200) return [];
|
||||
const body = await res.json();
|
||||
return Array.isArray(body.files) ? body.files : [];
|
||||
@@ -393,7 +393,7 @@ async function fetchPrototypeList(spec) {
|
||||
|
||||
async function fetchPrototypeDoc(spec, name) {
|
||||
try {
|
||||
const res = await fetch("/prototype?spec=" + encodeURIComponent(spec) + "&name=" + encodeURIComponent(name), { cache: "no-store" });
|
||||
const res = await fetch("prototype?spec=" + encodeURIComponent(spec) + "&name=" + encodeURIComponent(name), { cache: "no-store" });
|
||||
return res.status === 200 ? await res.text() : null;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -437,7 +437,7 @@ export async function loadSpecCarry() {
|
||||
if (specCarryAsked || !isDashboard() || !scan() || page.local.specSel !== undefined) return;
|
||||
specCarryAsked = true;
|
||||
try {
|
||||
const res = await fetch("/spec-carry", { method: "POST", cache: "no-store" });
|
||||
const res = await fetch("spec-carry", { method: "POST", cache: "no-store" });
|
||||
const { spec } = res.status === 200 ? await res.json() : {};
|
||||
if (!spec || page.local.specSel !== undefined || !specList().some((s) => s.dir === spec)) return;
|
||||
page.local.specSel = spec;
|
||||
@@ -458,7 +458,7 @@ export const agentsTabShown = () => isDashboard() && typeof page.agentsDoc.texts
|
||||
// keep its text; null when it is not there. Off the dashboard nothing is read.
|
||||
async function fetchAgentsDoc(rel) {
|
||||
try {
|
||||
const res = await fetch("/agents-doc?file=" + encodeURIComponent(rel), { cache: "no-store" });
|
||||
const res = await fetch("agents-doc?file=" + encodeURIComponent(rel), { cache: "no-store" });
|
||||
return res.status === 200 ? await res.text() : null;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -39,7 +39,7 @@ export const soundOn = (event) => looks.sound && looks[soundKey(event)];
|
||||
const soundPath = (event) =>
|
||||
PICKABLE_SOUNDS.includes(event) && looks[soundFileKey(event)] ? `sounds/${looks[soundFileKey(event)]}` : SOUND_EVENTS[event].file;
|
||||
|
||||
const audioFor = (path) => (SOUNDS[path] ||= new Audio(`/${path}.mp3`));
|
||||
const audioFor = (path) => (SOUNDS[path] ||= new Audio(`${path}.mp3`));
|
||||
|
||||
// The Audio a cue last played, so a pick changed mid-sound still stops the right one.
|
||||
const soundAudio = (event) => SOUNDS[playingPath[event] || soundPath(event)];
|
||||
|
||||
@@ -826,6 +826,14 @@ h4.md-h, h5.md-h, h6.md-h { font-size: var(--fs-base); }
|
||||
.modal-ranges .sound-row label { flex: 1 1 100%; padding: 4px 5px; }
|
||||
.sound-row select { flex: 1 1 auto; min-width: 0; }
|
||||
}
|
||||
/* In User Preferences the panel's own width decides too: at the Narrow card
|
||||
width the dialog is narrow inside a wide window, where four choices side by
|
||||
side squeezed "Comfortable" out of its box. Before the window rule below, so
|
||||
a small window still stacks them in one column. */
|
||||
.prefs-panels { container-type: inline-size; container-name: prefs-panel; }
|
||||
@container prefs-panel (max-width: 600px) {
|
||||
.looks-row.four { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.looks-row, .looks-row.four { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ import { step } from "./notepad.js";
|
||||
export const CHAT_IMAGES = "__chat";
|
||||
|
||||
// An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves
|
||||
// it at /uploads/<uuid>.<ext>.
|
||||
export const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop();
|
||||
// it at uploads/<uuid>.<ext>, relative to itself.
|
||||
export const uploadUrl = (img) => img.url || "uploads/" + String(img.path || "").split(/[\\/]/).pop();
|
||||
|
||||
// A page with its corner folded, drawn inline: the CSP allows no icon font.
|
||||
function pageIcon() {
|
||||
@@ -236,7 +236,7 @@ function setNoteImages(itemId, list) {
|
||||
|
||||
// Where an attachment is deleted from. Documents have no `url`, so their
|
||||
// route is built from the path, as uploadUrl does.
|
||||
export const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop();
|
||||
export const deleteUrl = (entry) => entry.url || "uploads/" + String(entry.path || "").split(/[\\/]/).pop();
|
||||
|
||||
// The files in a paste worth attaching: images and allowed documents. A paste
|
||||
// with none of them is left to paste as text.
|
||||
@@ -258,7 +258,7 @@ async function uploadBlob(itemId, key, blob) {
|
||||
let body = null;
|
||||
let status = 0;
|
||||
try {
|
||||
const res = await fetch("/upload", {
|
||||
const res = await fetch("upload", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": isFile ? "application/octet-stream" : "image/jpeg",
|
||||
|
||||
@@ -156,21 +156,24 @@ function noteEvent(dir, event) {
|
||||
|
||||
export function handle(req, res, ctx) {
|
||||
const port = ctx.port();
|
||||
if (!hostOk(req, ctx)) return send(res, 403, "", "text/plain");
|
||||
|
||||
// Before anything reads the path: the macOS app's frame comes in under its
|
||||
// prefix, which comes off here, once.
|
||||
const framed = takeFramePrefix(req, ctx);
|
||||
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
||||
const pathname = url.pathname;
|
||||
|
||||
if (!hostOk(req, port)) return send(res, 403, "", "text/plain");
|
||||
|
||||
let gated = false;
|
||||
for (const route of ROUTES) {
|
||||
if (!route.open && !gated) {
|
||||
if (!authed(req, ctx)) return send(res, 403, "Open the link the terminal printed.", "text/plain");
|
||||
if (!framed && !authed(req, ctx)) return send(res, 403, "Open the link the terminal printed.", "text/plain");
|
||||
ctx.touch();
|
||||
gated = true;
|
||||
}
|
||||
if (route.path !== undefined ? pathname !== route.path : !route.match(pathname, req)) continue;
|
||||
if (route.method && req.method !== route.method) continue;
|
||||
if (route.origin && !originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
if (route.origin && !originOk(req, ctx)) return json(res, 403, { error: "bad origin" });
|
||||
try {
|
||||
return route.run(req, res, ctx, url);
|
||||
} catch (e) {
|
||||
@@ -203,6 +206,16 @@ function signIn(req, res, ctx, url) {
|
||||
const given = url.pathname.slice(3).replace(/\/$/, "");
|
||||
if (!ctx.token || !timingSafeEq(given, ctx.token)) return send(res, 403, "Not found", "text/plain");
|
||||
ctx.touch();
|
||||
// The macOS app's frame goes under its prefix instead (takeFramePrefix):
|
||||
// WebKit on macOS gives that cross-site frame no cookie, Lax included. A
|
||||
// browser tab that sends `Sec-Fetch-Dest: document` keeps the cookie, so
|
||||
// the prefix stays out of its address bar. A client that sends no such
|
||||
// header gets the prefix, the answer that works for the frame.
|
||||
const key = frameKey(ctx);
|
||||
if (key && req.headers["sec-fetch-dest"] !== "document") {
|
||||
res.writeHead(302, baseHeaders({ location: `/f/${key}/` }));
|
||||
return res.end();
|
||||
}
|
||||
res.writeHead(
|
||||
302,
|
||||
baseHeaders({
|
||||
@@ -223,7 +236,9 @@ function signIn(req, res, ctx, url) {
|
||||
// arrives over plain http, so None; Secure never comes back and every
|
||||
// request after the sign-in is a 403: the app shows "its page did not show
|
||||
// in this window". Lax, without Secure, is kept and sent there (measured in
|
||||
// WebKitGTK 2.52 under both its cookie policies).
|
||||
// WebKitGTK 2.52 under both its cookie policies). macOS WebKit drops even
|
||||
// Lax in a cross-site frame, so the macOS app's frame never gets this
|
||||
// cookie: signIn() sends it under its path prefix instead (takeFramePrefix).
|
||||
function cookieSameSite(ancestor) {
|
||||
if (ancestor === "'none'") return "SameSite=Strict";
|
||||
if (ancestor === "tauri://localhost") return "SameSite=Lax";
|
||||
@@ -1430,7 +1445,8 @@ function upload(req, res, ctx) {
|
||||
id,
|
||||
kind: "image",
|
||||
path: file,
|
||||
url: "/uploads/" + id + ".jpg",
|
||||
// Page-relative, for the macOS app's frame prefix (takeFramePrefix).
|
||||
url: "uploads/" + id + ".jpg",
|
||||
name: uploadLabel(req, "image.jpg"),
|
||||
size: buf.length,
|
||||
});
|
||||
@@ -1532,7 +1548,7 @@ function uploads(req, res, ctx, url) {
|
||||
});
|
||||
}
|
||||
if (req.method === "DELETE") {
|
||||
if (!originOk(req, ctx.port())) return json(res, 403, { error: "bad origin" });
|
||||
if (!originOk(req, ctx)) return json(res, 403, { error: "bad origin" });
|
||||
const m = UPLOAD_ANY_ROUTE.exec(req.url);
|
||||
const file = m && m[0] === pathname ? uploadPath(ctx, m[1], m[2]) : null;
|
||||
if (!file || !fs.existsSync(file)) return json(res, 404, { error: "not found" });
|
||||
@@ -2105,6 +2121,40 @@ function authed(req, ctx) {
|
||||
return c ? timingSafeEq(c, ctx.token) : false;
|
||||
}
|
||||
|
||||
// The macOS app's frame signs in by a path prefix, not by cookie. The app's
|
||||
// page is tauri://localhost, cross-site to this server, and WebKit gives a
|
||||
// cross-site frame no cookie in any form (its third-party cookie blocking has
|
||||
// no switch). So the sign-in link sends that frame to /f/<key>/ on this same
|
||||
// 127.0.0.1 address, and a request under exactly that prefix is signed in.
|
||||
// The key is a hash of the token, still 128 bits, so the token itself never
|
||||
// sits in the frame's address. Unlike the HttpOnly cookie, the key is
|
||||
// readable by the page's own script (location.pathname), so this relies on
|
||||
// the page's strict CSP keeping any other script out. Off (null) everywhere
|
||||
// else, Windows and Linux included. Not a host name such as <key>.localhost:
|
||||
// macOS tries it on [::1] first, where another process can listen on the
|
||||
// same port and be handed the key.
|
||||
function frameKey(ctx) {
|
||||
if (process.platform !== "darwin" || embedAncestor() !== "tauri://localhost" || !ctx.token) return null;
|
||||
return crypto.createHash("sha256").update(ctx.token).digest("hex").slice(0, 32);
|
||||
}
|
||||
|
||||
// True, with the prefix taken off req.url, for a request under the frame's
|
||||
// prefix. It comes off the raw request line, not the parsed path, so the
|
||||
// routes that refuse anything URL parsing had to fold (`..`) still see it.
|
||||
// Only the first prefix comes off: a second is just a path, and nothing
|
||||
// serves it. The page asks for everything page-relative (no leading slash),
|
||||
// so the same page works at / in a browser tab and under the prefix here.
|
||||
const FRAME_PREFIX = /^\/f\/([^/]*)\//;
|
||||
|
||||
function takeFramePrefix(req, ctx) {
|
||||
const key = frameKey(ctx);
|
||||
if (!key) return false;
|
||||
const m = FRAME_PREFIX.exec(req.url);
|
||||
if (!m || !timingSafeEq(m[1], key)) return false;
|
||||
req.url = req.url.slice(m[0].length - 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The DNS-rebinding defense, and the highest-value check in this file.
|
||||
*
|
||||
@@ -2112,15 +2162,17 @@ function authed(req, ctx) {
|
||||
* 127.0.0.1 and then talk to this server as same-origin. That is not
|
||||
* theoretical: it is the exact shape of Vite's GHSA-vg6x-rcgg-rjx6.
|
||||
*/
|
||||
function hostOk(req, port) {
|
||||
function hostOk(req, ctx) {
|
||||
const host = req.headers.host;
|
||||
if (!host) return false;
|
||||
const port = ctx.port();
|
||||
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
|
||||
}
|
||||
|
||||
function originOk(req, port) {
|
||||
function originOk(req, ctx) {
|
||||
const origin = req.headers.origin;
|
||||
if (!origin) return true; // same-origin fetches and plain navigations send none
|
||||
const port = ctx.port();
|
||||
return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,27 @@ export function specKey(specDir) {
|
||||
.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function isFolder(p) {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Where the picker opens: beside the last folder added, else the original, else
|
||||
// `fallback`. A start deleted on disk walks up to its nearest folder still there,
|
||||
// since a picker cannot open at a missing folder and would fail as unavailable.
|
||||
export function pickerStart(ws, fallback) {
|
||||
const added = ws.folders.filter((f) => !f.original);
|
||||
const wanted = added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || fallback;
|
||||
for (let dir = wanted; dir; dir = path.dirname(dir)) {
|
||||
if (isFolder(dir)) return dir;
|
||||
if (path.dirname(dir) === dir) break;
|
||||
}
|
||||
return isFolder(fallback) ? fallback : os.homedir();
|
||||
}
|
||||
|
||||
function readStore() {
|
||||
const saved = readJson(WORKSPACES_FILE, null);
|
||||
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
||||
@@ -325,14 +346,6 @@ export function serverWorkspace(ctx) {
|
||||
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
|
||||
}
|
||||
|
||||
function isFolder(p) {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// A folder deleted on disk is marked missing, and unmarked when it comes back.
|
||||
function checkFolders(ws) {
|
||||
ws.missing = ws.missing || [];
|
||||
@@ -432,12 +445,6 @@ export function serverWorkspace(ctx) {
|
||||
return [200, { ok: true }];
|
||||
}
|
||||
|
||||
// Where the picker opens: beside the last folder added, else the original.
|
||||
function pickerStart(ws) {
|
||||
const added = ws.folders.filter((f) => !f.original);
|
||||
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || project;
|
||||
}
|
||||
|
||||
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
|
||||
// minutes, and every poll, chat message and `wait` health check has to keep
|
||||
// being answered meanwhile.
|
||||
@@ -452,7 +459,7 @@ export function serverWorkspace(ctx) {
|
||||
// Tests only: stands in for the person, so no dialog ever opens.
|
||||
const echo = process.env.PLAN2CODE_PICKER_ECHO;
|
||||
if (echo) return Promise.resolve([200, echo === "-" ? { cancelled: true } : { path: echo }]);
|
||||
const start = pickerStart(ws);
|
||||
const start = pickerStart(ws, sessionWorktree() || project);
|
||||
if (!pickerCommand(start, WORKSPACE_PICKER_PROMPT)) return Promise.resolve([404, { reason: "no-picker" }]);
|
||||
pickerBusy = true;
|
||||
return pickFolder(start, WORKSPACE_PICKER_PROMPT)
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "3.2.6",
|
||||
"version": "3.2.7",
|
||||
"description": "A structured workflow of six steps (Pathfinder, Plan, Document, Implement, Review, Finalize) for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-12-04",
|
||||
"releaseDate": "2026-12-05",
|
||||
"mode": "utility"
|
||||
}
|
||||
Reference in new issue
Block a user