diff --git a/.agents-docs/AGENTS-architecture-console-design.md b/.agents-docs/AGENTS-architecture-console-design.md
index 50d9463..905cfd2 100644
--- a/.agents-docs/AGENTS-architecture-console-design.md
+++ b/.agents-docs/AGENTS-architecture-console-design.md
@@ -70,4 +70,4 @@ Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `` 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/.jpg`): the macOS app's frame gets no cookie and is signed in by the path prefix `/f//` (`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.
+**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/.jpg`): the macOS app's frame gets no cookie and is signed in by the path prefix `/f//` (`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` flags any slash-leading 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.
diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml
index 5aeb9f5..20a0524 100644
--- a/.github/workflows/app.yml
+++ b/.github/workflows/app.yml
@@ -181,13 +181,12 @@ jobs:
- 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`.
+ # A window whose dashboard frame never signs in (on macOS by a path prefix,
+ # takeFramePrefix in routes.mjs) still passes the alive check above. The app
+ # autostarts scripts/smoke-agent.mjs, which opens a real console, and
+ # scripts/smoke-frame.mjs waits up to 60s for its /health to count the frame.
+ # 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)"
diff --git a/.readme/web-console-design.md b/.readme/web-console-design.md
index d3a791a..abd68ab 100644
--- a/.readme/web-console-design.md
+++ b/.readme/web-console-design.md
@@ -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//` 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//` 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 `.localhost` host name: macOS tries it on `[::1]` first, where another process can take the port.
+4. First `GET /s//` 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//` 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. A path, not a `.localhost` host name: macOS tries that 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.
diff --git a/.readme/web-console-internals.md b/.readme/web-console-internals.md
index 208048a..5f9ed66 100644
--- a/.readme/web-console-internals.md
+++ b/.readme/web-console-internals.md
@@ -136,8 +136,8 @@ this:
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//` 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.
+ of the token, and a request under that exact prefix is signed in. 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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0a76fea..357c6d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,18 +8,18 @@ All notable changes to Plan2Code will be documented in this file.
### 🐛 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.
+- **Desktop app**: on macOS the dashboard shows in the app's window. WebKit gives that frame no cookie, so it signs in by a path prefix.
+- **Desktop app**: on macOS and Linux, every quit (close button, menu, Dock, Ctrl+C, a closed terminal, `kill`) stops the agent, what it started and the dashboards it opened. An agent that ends by itself still leaves running what it was asked to keep running.
+- **Desktop app**: on macOS, Cmd+Q and the menu's Quit ask first while an agent is running.
+- **Desktop app**: on macOS and Linux, a start from the Dock, Finder or a desktop entry finds Node and agents set up in your shell's interactive config, such as nvm in `~/.zshrc`. A hung shell profile delays the start by about 5 seconds at most.
+- **Desktop app**: on macOS, Ctrl+V in the terminal goes to the agent, so Claude Code can take a pasted picture, and Cmd+V pastes without a Paste menu.
+- **Desktop app**: on macOS, the Dock shows Planny's icon 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.
+- **Web console and launcher**: on macOS, a failed folder picker says so instead of acting like Cancel. On every system, Browse opens at the nearest folder that still exists.
+- **Web console**: User Preferences' Card width choices no longer overlap at the Narrow width, and the page-closed signal is no longer refused in Safari and the macOS app.
+- **Quick Task**: the See it running card no longer says nothing has been changed yet.
+- **For contributors**: console page URLs must be page-relative (`fetch("state")`, not `fetch("/state")`). `scripts/test-web-console-relative-urls.mjs` enforces it.
+- **For contributors**: on macOS, the `app` workflow fails when the dashboard never connects inside the app (manual runs and pull requests labeled `full-matrix`), and the release checklist covers these fixes.
## v3.2.6 (2026-12-04)
diff --git a/plan2code-app/RELEASE-CHECKLIST.md b/plan2code-app/RELEASE-CHECKLIST.md
index 4d6a8e5..3c228d8 100644
--- a/plan2code-app/RELEASE-CHECKLIST.md
+++ b/plan2code-app/RELEASE-CHECKLIST.md
@@ -46,11 +46,10 @@ file directly after checking it against the release's checksum list.
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
+ (Homebrew, or nvm in `~/.zprofile`), `~/.zshrc` is read only on Check again, not at start;
+ with Homebrew's Node 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
@@ -141,7 +140,7 @@ Do each of Claude Code, Devin and Codex for a few minutes:
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
+ the new console only; the old one has stopped
- [ ] 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
diff --git a/plan2code-app/scripts/smoke-agent.mjs b/plan2code-app/scripts/smoke-agent.mjs
index bca3de2..7081820 100755
--- a/plan2code-app/scripts/smoke-agent.mjs
+++ b/plan2code-app/scripts/smoke-agent.mjs
@@ -1,15 +1,13 @@
#!/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.
+// A stand-in agent for CI's smoke run of the built app (.github/workflows/app.yml);
+// point PLAN2CODE_APP_AGENT_BIN at it. 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 checks it did). fake-agent opens no console.
//
-// 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`.
+// Needs PLAN2CODE_CONSOLE_DIR (the folder holding console.mjs), ignores the
+// app's arguments, and waits until its input closes. The console server is
+// detached; the smoke run stops it with `console.mjs stop --all`.
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/plan2code-app/scripts/smoke-frame.mjs b/plan2code-app/scripts/smoke-frame.mjs
index 0161b00..6701378 100644
--- a/plan2code-app/scripts/smoke-frame.mjs
+++ b/plan2code-app/scripts/smoke-frame.mjs
@@ -1,7 +1,6 @@
// 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.
+// run (.github/workflows/app.yml). A window whose frame never signs in still
+// passes a process check; the console's own browser count does not.
//
// node smoke-frame.mjs [] [--timeout-ms N]
//
diff --git a/plan2code-app/src-tauri/src/agent_manager.rs b/plan2code-app/src-tauri/src/agent_manager.rs
index 0caa121..be1c3b7 100644
--- a/plan2code-app/src-tauri/src/agent_manager.rs
+++ b/plan2code-app/src-tauri/src/agent_manager.rs
@@ -36,10 +36,9 @@ pub type BeforeFresh = Arc Option + Send + Sync>;
/// the manager.
pub type ForgetSession = Arc;
-/// 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.
+/// Runs once for each agent that ends: by itself, by a stop, or replaced by a
+/// fresh agent. 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;
/// What the page needs to draw the bar. `generation` counts the agents started
@@ -675,10 +674,8 @@ impl Shared {
Err(e) => format!("stopped: {e}"),
};
// 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.
+ // group with it. One 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();
}
diff --git a/plan2code-app/src-tauri/src/agents.rs b/plan2code-app/src-tauri/src/agents.rs
index 23d7d06..61bc0d6 100644
--- a/plan2code-app/src-tauri/src/agents.rs
+++ b/plan2code-app/src-tauri/src/agents.rs
@@ -1150,11 +1150,10 @@ pub fn custom_agents() -> (Vec, Vec) {
.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.
+/// The built-in and custom agent commands looked up on PATH 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. `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 {
let (custom, _) = custom_agents();
@@ -1687,8 +1686,8 @@ mod tests {
#[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.
+ // The baked built-ins, then custom commands: a repeat, a quoted name,
+ // two with a folder and a blank one.
let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
let custom = [
"codex",
diff --git a/plan2code-app/src-tauri/src/console_supervisor.rs b/plan2code-app/src-tauri/src/console_supervisor.rs
index c7ff274..8130628 100644
--- a/plan2code-app/src-tauri/src/console_supervisor.rs
+++ b/plan2code-app/src-tauri/src/console_supervisor.rs
@@ -412,7 +412,7 @@ impl ConsoleSupervisor {
return Ok(());
}
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.
+ // Only a stop that could not run at all leaves the flag clear.
if !matches!(result, Err(StopError::NotRun(_))) {
self.stopped = true;
}
@@ -420,10 +420,8 @@ impl ConsoleSupervisor {
}
}
-/// `console.mjs stop --session --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).
+/// Runs `console.mjs stop --session --force` in the project folder, as
+/// `ConsoleSupervisor::stop` does, for a console this app does not supervise.
pub fn stop_console_session(
console_dir: &Path,
project_dir: &Path,
@@ -440,13 +438,11 @@ struct Announced {
}
/// 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.
+/// sid, in the order they came: stopped when the agent that opened them ends,
+/// when the window moves on from one an ended agent left, or at the quit.
+/// Consoles the app started itself are never recorded; the bar's stop, which
+/// keeps the session to start it again, leaves one recorded. Also holds the
+/// threads still stopping consoles, so a quit can wait for them.
#[derive(Default)]
pub struct AnnouncedConsoles {
consoles: Mutex>,
@@ -554,21 +550,18 @@ impl AnnouncedConsoles {
}
}
-/// 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.
+/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`),
+/// the macOS and Linux stand-in for Windows' Job Object. It takes every console
+/// `announced` holds at once, inside the hook, so one the next agent announces
+/// is never taken, then stops each with `stop` on a thread of its own: a stop
+/// runs `node`, and the hook must return quickly. The console the window follows
+/// (`followed`) is recorded again as left instead since, stopped under the
+/// window, the bar's health poll would start it again as a server no one tracks;
+/// it is stopped when the window moves on (`stop_left`) or at the quit.
+/// `followed` is asked on that thread: 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 calls `finish_stops` first, so it is not
+/// recorded again after that stop.
pub fn stop_announced_on_end(
announced: Arc,
followed: K,
@@ -602,8 +595,8 @@ where
}
}
if left {
- // A page that took the window since the question above found
- // nothing left to stop yet.
+ // A page that took the window after `followed()` was asked
+ // found nothing left to stop yet.
for sid in record.take_left(followed().as_deref()) {
stop(&sid);
}
@@ -709,8 +702,8 @@ mod tests {
#[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.
+ // takes the console lock, held across `node` runs: asked in the hook,
+ // it would stall typing in the terminal 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);
@@ -735,8 +728,8 @@ mod tests {
#[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.
+ // console: stopped there, the bar's poll would start it again as a
+ // server no one tracks, which would outlive the quit.
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::::new()));
let log = Arc::clone(&stopped);
@@ -810,7 +803,8 @@ mod tests {
}
/// 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.
+ /// runs right after the hook asked which console that is. Returns what was
+ /// stopped and what stays recorded.
fn stopped_by_an_end_while(meanwhile: M) -> (Vec, Vec)
where
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
@@ -905,8 +899,6 @@ mod tests {
#[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")
diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs
index b82758d..317b9c7 100644
--- a/plan2code-app/src-tauri/src/main.rs
+++ b/plan2code-app/src-tauri/src/main.rs
@@ -162,9 +162,8 @@ 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. 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.
+// warnings about agents.json. Async, so a refresh, which can spend seconds in
+// the person's shell, runs on a blocking thread instead of freezing the window.
#[tauri::command]
async fn agent_availability(refresh: Option) -> Result {
let refresh = refresh == Some(true);
@@ -437,13 +436,13 @@ fn current_agent(state: &AppState) -> Option> {
// 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. 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.
+/// 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.
+/// On macOS and Linux, a console an ended agent left under the window stops
+/// here, since the window has moved on from it.
fn take_announced(
state: &AppState,
notice: &PageNotice,
@@ -766,10 +765,9 @@ 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.
+ // A window closed from the background leaves the app inactive, and its web view ignores the
+ // first click on an inactive window; a minimized one would show the question 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) {
@@ -839,9 +837,8 @@ 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.
+// The cleanup every quit runs: from `quit_app`, and on macOS and Linux also
+// from `RunEvent::Exit` for routes that skip `quit_app`. Safe to call twice.
fn shutdown(app: &tauri::AppHandle) {
let state = app.state::();
shutdown_with(&state);
@@ -875,9 +872,8 @@ fn shutdown_with(state: &AppState) {
}
}
-// 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.
+// After `shutdown_with`, stops every announced console 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() {
@@ -885,11 +881,10 @@ fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
}
}
-// 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.
+// Waits for the threads an agent's end or a new page started (macOS and Linux)
+// to finish stopping consoles and deciding whether the followed one stays
+// recorded. Call it before taking the console lock: an end's thread takes that
+// lock too, and a decision made after the stop would record the console again.
fn settle_agent_ends(state: &AppState) {
#[cfg(unix)]
state.announced.finish_stops();
@@ -1459,11 +1454,9 @@ 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. 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.
+/// the same session again instead of finding nothing to start.
+/// Unlike the other stops, it leaves an announced console recorded, since the
+/// supervisor may start it again; it then stops as any announced console does.
fn console_stop_impl(state: &AppState) -> Result<(), String> {
settle_agent_ends(state);
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
@@ -2101,9 +2094,8 @@ fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
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.
+// macOS takes the Dock and Cmd+Tab icon from an `.app` bundle, and the app ships as a bare program
+// (`tauri build --no-bundle`), so it sets the icon itself, as Tauri does in dev builds only.
#[cfg(target_os = "macos")]
const APP_ICON_ICNS: &[u8] = include_bytes!("../icons/icon.icns");
@@ -2130,9 +2122,8 @@ fn set_app_icon() {
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.
+// A bare program started from a terminal is not made the active app, so its window would open
+// behind that terminal. Called once, at start; later shows leave the active app alone.
#[cfg(target_os = "macos")]
fn activate_app() {
let Some(mtm) = objc2::MainThreadMarker::new() else {
@@ -2292,9 +2283,8 @@ fn main() {
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.
+ // A plain `kill`, Ctrl+C or a closed terminal still runs the quit cleanup. `shutdown`,
+ // not `quit_app`: a signal never starts a pending update's restart.
#[cfg(unix)]
{
let handle = app.handle().clone();
@@ -2311,18 +2301,16 @@ fn main() {
.build(tauri::generate_context!())
.expect("error while building the Plan2Code app")
.run(|app, event| {
- // 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.
+ // Every exit cleans up here, including a quit with no agent active and, on
+ // macOS, Dock Quit, whose `terminate:` raises only this event and never asks.
+ // After `quit_app` it 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.
+ // An exit not 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 goes 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
@@ -2541,8 +2529,8 @@ mod tests {
#[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.
+ // New Session: the console the ended agent left under the window stops
+ // once the next agent's page is taken.
let state = state_for("project-a");
*state.console.lock().unwrap() = Some(following_the_build());
state.announced.record("build");
@@ -2570,9 +2558,8 @@ mod tests {
#[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.
+ // A project switch stops the followed console its agent announced and
+ // forgets it, so neither the next agent's end nor the quit stops it again.
let state = state_for("project-a");
*state.console.lock().unwrap() = Some(following_the_build());
state.announced.record("build");
@@ -2878,10 +2865,8 @@ mod tests {
#[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.
+ // A refresh can spend seconds in the person's shell, so the command is a
+ // future that hands the work to a blocking thread; awaited, 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));
@@ -2976,10 +2961,9 @@ mod tests {
#[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.
+ // The bar's Reconnect (or a skills update) stops the console its agent
+ // announced and starts it again on the same session; once the window
+ // follows the next agent's page, the quit must still stop that console.
let Some((_env, sup)) = real_console() else {
return;
};
diff --git a/plan2code-app/src-tauri/src/node_check.rs b/plan2code-app/src-tauri/src/node_check.rs
index 0afd016..e2ce20b 100644
--- a/plan2code-app/src-tauri/src/node_check.rs
+++ b/plan2code-app/src-tauri/src/node_check.rs
@@ -79,18 +79,14 @@ fn node_override_dir(args: &[String]) -> Option {
/// launch never gets. Windows sets PATH outside any shell's startup files, so
/// this is unix only.
///
-/// The rule: ask the login shell first, within `LOGIN_PATH_TIMEOUT` (3 s),
-/// since Homebrew and most installers put their PATH lines in its files. Ask
-/// again with the interactive config too (`.zshrc`, where nvm, fnm and asdf
-/// usually put Node and the agents `npm install -g` adds under it), within
-/// `INTERACTIVE_PATH_TIMEOUT` (2 s), only when `node` or every agent command
-/// is missing from both the login and the inherited PATH, or on Check again
-/// (`refresh_path`). Never after a login timeout, which would hang the same
-/// way. So a hung login profile adds at most 3 s to the start, and the slowest
-/// case 5 s. The interactive config is left out when it is not needed because
-/// its terminal-only lines can start daemons that leave the shell's process
-/// group, out of reach of any kill here. Details in `path_from_shell` and
-/// `shell_path`.
+/// Asks the login shell first, where Homebrew and most installers put their
+/// PATH lines. Asks again with the interactive config (`.zshrc`, where nvm,
+/// fnm and asdf usually put Node and the agents `npm install -g` adds there)
+/// only when `node` or every agent command is missing from both the login and
+/// inherited PATH, or on Check again, and never after a login timeout, which
+/// would hang the same way. The interactive config is otherwise left out
+/// because its terminal-only lines can start daemons that leave the shell's
+/// process group, out of reach of the kill.
#[cfg(unix)]
fn login_shell_path(args: &[String], inherited: &str, always_interactive: bool) -> Option {
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
@@ -122,8 +118,7 @@ fn login_shell_path_for(
path_from_shell(shell, &known, agents, always_interactive)
}
-/// How long the shell may take as a login shell, then with its interactive
-/// config when that is asked too (see `login_shell_path`).
+/// How long the login run, and the interactive config run, may each take.
#[cfg(unix)]
const LOGIN_PATH_TIMEOUT: Duration = Duration::from_secs(3);
#[cfg(unix)]
@@ -141,11 +136,10 @@ const SHELL_POLL: Duration = Duration::from_millis(10);
#[cfg(unix)]
const LINGER_GRACE: Duration = Duration::from_millis(200);
-/// SIGKILL to `child`'s whole process group (it leads one, through
-/// `setsid`), then reap it, so nothing a profile started in that group
-/// outlives the call. Called once the shell has exited too: while any member
-/// is left, the id still names this group; once it is empty the kill finds
-/// nothing, barring the id's reuse within that moment.
+/// SIGKILL `child`'s whole process group (it leads one, through `setsid`),
+/// then reap it, so nothing a profile started in that group outlives the call.
+/// Also used after the shell exited: the id names the group while any member
+/// is left, and the kill finds nothing once it is empty (barring id reuse).
#[cfg(unix)]
fn kill_process_group(child: &mut std::process::Child) {
if let Ok(pgid) = i32::try_from(child.id()) {
@@ -158,14 +152,12 @@ fn kill_process_group(child: &mut std::process::Child) {
let _ = child.wait();
}
-/// The login shell's PATH, then the interactive config's when it is needed,
-/// by the rule `login_shell_path` describes. The interactive answer holds the
-/// login PATH as well, so it is used whole; when it fails, the login answer is
-/// kept. (bash, asked either way, reads `.bash_profile`, `.bash_login` or
-/// `.profile`, not `.bashrc`, as Terminal's login shells do.) `inherited` is
-/// the PATH this app has without the shell (with the `--node` folder, when
-/// there is one), `agents` the agent commands looked up by name
-/// (`agents::path_agent_commands`; an empty list asks for none), and
+/// The login shell's PATH, then the interactive config's when needed, by the
+/// rule on `login_shell_path`. The interactive answer includes the login PATH,
+/// so it is used whole; if it fails, the login answer is kept. bash reads its
+/// profile files either way, not `.bashrc`, as Terminal's login shells do.
+/// `inherited` is this app's PATH plus any `--node` folder, `agents` the agent
+/// commands to look for (an empty list requires none), and
/// `always_interactive` is Check again.
#[cfg(unix)]
fn path_from_shell(
@@ -218,9 +210,8 @@ fn path_from_shell(
}
/// Whether one of `path`'s absolute folders holds an executable regular file
-/// named `program` (a symlink to one counts). Nothing is run: this only
-/// decides whether the interactive config is worth asking. A relative entry is
-/// never searched, since what it names depends on where the app happens to run.
+/// named `program` (a symlink to one counts). Relative entries are skipped:
+/// what they name depends on the app's working directory.
#[cfg(unix)]
fn holds_program(path: &str, program: &str) -> bool {
use std::os::unix::fs::PermissionsExt;
@@ -240,14 +231,13 @@ fn is_csh(shell: &Path) -> bool {
.is_some_and(|name| name == "csh" || name == "tcsh")
}
-/// The PATH `shell` ends up with as a login shell (and an interactive one
-/// when `interactive`), or `None` when it fails, prints no PATH, or takes
-/// longer than `timeout`. The shell has no input and no terminal, and its
-/// whole process group is killed when it ends, by itself or at the timeout. A
-/// shell that answered but lingers (a slow logout file, an EXIT trap) is ended
-/// after `LINGER_GRACE` and its answer kept. csh and tcsh ignore
-/// `interactive`: they get `-l` alone and the command on stdin, and their
-/// `.cshrc` runs either way.
+/// The PATH `shell` reports as a login shell (and interactive, when
+/// `interactive`), or `None` when it fails, prints no PATH, or exceeds
+/// `timeout`. It runs with no input and no terminal, and its whole process
+/// group is killed when it ends. A shell that answered but lingers (a slow
+/// logout file, an EXIT trap) is ended after `LINGER_GRACE`, its answer kept.
+/// csh and tcsh ignore `interactive`: they get `-l` alone and the command on
+/// stdin, and their `.cshrc` runs either way.
#[cfg(unix)]
fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option {
use std::io::{Read, Write};
@@ -285,11 +275,10 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option Option Option= at + LINGER_GRACE => {
kill_process_group(&mut child);
break None;
@@ -368,10 +356,9 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option Option`, with `last` set to the command. Each
/// body sets its own PATH, so no test touches this process's environment.
///
- /// It is run once before it is returned: macOS checks a newly written
- /// script on its first run, one at a time, which took 230 to 680 ms with
- /// five at once (later runs: about 15 ms), longer than a short timeout.
- ///
- /// On Linux that first run can fail with ETXTBSY ("Text file busy"):
- /// another test thread that forks while `write` still holds the file open
- /// gives its child a copy of the write descriptor until that child execs
- /// (rust-lang/rust#114554). The window is a few microseconds, so the run
- /// is retried briefly; once one run has started, no write descriptor is
- /// left anywhere and later runs are safe.
+ /// Run once before it is returned: macOS checks a new script on its first
+ /// run, one at a time, which can outlast a short timeout when tests run in
+ /// parallel. That run is retried on ETXTBSY: on Linux, a thread that forks
+ /// while `write` holds the file open passes the write descriptor to its
+ /// child until it execs (rust-lang/rust#114554).
#[cfg(unix)]
fn fake_shell(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
@@ -832,12 +812,12 @@ mod tests {
);
}
- /// For a fake that hangs: the test waits this long, so it stays short.
+ /// Timeout for a fake that hangs: the test waits all of it.
#[cfg(unix)]
const SHORT: std::time::Duration = std::time::Duration::from_millis(300);
- /// For a fake that answers: it returns as soon as the fake exits, so a
- /// generous limit costs nothing and keeps a busy runner from failing it.
+ /// Timeout for a fake that answers: it returns as soon as the fake exits,
+ /// so a generous limit costs nothing and spares a busy runner.
#[cfg(unix)]
const ROOMY: std::time::Duration = std::time::Duration::from_secs(5);
@@ -848,9 +828,8 @@ mod tests {
let shell = fake_shell(
&dir,
"zsh",
- // `echo "$last"` stands in for a profile that echoes or replays
- // commands: the markers sit in the command only in halves, so the
- // echoed command text can never pass for the answer.
+ // `echo "$last"` stands in for a profile that echoes commands; the
+ // markers sit in the command only in halves, so it cannot match.
"echo 'Welcome back'\nprintf 'no newline here'\necho \"$last\"\nPATH=/fake/a:/fake/b\neval \"$last\"\necho\necho 'see you'",
);
assert_eq!(
@@ -863,8 +842,7 @@ mod tests {
#[test]
fn shell_path_always_asks_as_a_login_shell() {
let dir = scratch("login");
- // Answers only when `-l` comes first: the login profile is where
- // Homebrew and most installers put their PATH lines.
+ // Answers only when `-l` comes first.
let shell = fake_shell(
&dir,
"zsh",
@@ -1084,12 +1062,10 @@ mod tests {
#[test]
fn an_answer_with_no_absolute_folder_is_no_path() {
let dir = scratch("not-a-path");
- // A shell that does not expand "$PATH" (nushell, for one) prints it
- // as it stands: joined into the app's PATH it would find nothing.
+ // nushell, for one, does not expand "$PATH" and prints it as is.
let literal = fake_shell(&dir, "nu", "PATH='$PATH'\neval \"$last\"");
assert_eq!(shell_path(&literal, true, ROOMY), None);
- // A real PATH may carry relative entries too; one absolute folder
- // is enough to show it is a PATH, and it is kept as it is.
+ // One absolute folder among relative entries is a PATH, kept as is.
let mixed = fake_shell(&dir, "zsh", "PATH=.:/usr/bin:bin\neval \"$last\"");
assert_eq!(
shell_path(&mixed, true, ROOMY).as_deref(),
@@ -1143,9 +1119,8 @@ mod tests {
fn a_csh_with_no_node_is_still_asked_once_even_on_check_again() {
let dir = scratch("csh-once-no-node");
let runs = dir.join("runs");
- // Its answer has no node, which for another shell would mean asking
- // again with the interactive config; csh has no lighter config to
- // leave out, so a second run would only repeat the first.
+ // With no node in its answer another shell would be asked again with
+ // the interactive config; csh reads `.cshrc` either way, so it is not.
let shell = fake_shell(
&dir,
"csh",
@@ -1197,9 +1172,8 @@ mod tests {
path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(),
Some("/login/bin")
);
- // A quick login answer, then the 2 s interactive timeout. Room for a
- // busy runner, and far short of the 30 s sleep, so the hung config
- // was not waited on.
+ // A quick login answer, then the interactive timeout: room for a busy
+ // runner, and far short of the 30 s sleep the hung config would take.
assert!(
started.elapsed() < INTERACTIVE_PATH_TIMEOUT + std::time::Duration::from_millis(1400),
"took {:?}",
@@ -1211,8 +1185,7 @@ mod tests {
#[cfg(unix)]
const NO_AGENTS: &[String] = &[];
- /// A folder in `dir` holding an executable file named `node`, as nvm,
- /// Homebrew or Volta leave one. `holds_program` never runs it.
+ /// A folder in `dir` holding an executable file named `node`.
#[cfg(unix)]
fn node_in(dir: &std::path::Path, folder: &str) -> String {
programs_in(dir, folder, &["node"])
@@ -1232,15 +1205,13 @@ mod tests {
bin.display().to_string()
}
- /// The agent commands the tests below look for.
#[cfg(unix)]
fn agents(names: &[&str]) -> Vec {
names.iter().map(|name| name.to_string()).collect()
}
- /// A fake shell whose PATH is `login` as a login shell and `interactive`
- /// when also given `-i`, and which leaves `/ran-interactive` behind
- /// when given `-i`, so a test can tell whether the interactive config ran.
+ /// A fake shell whose PATH is `login`, or `interactive` when also given
+ /// `-i`, which also creates `/ran-interactive` for the test to check.
#[cfg(unix)]
fn two_config_shell(
dir: &std::path::Path,
@@ -1282,9 +1253,8 @@ mod tests {
std::fs::set_permissions(plain.join("node"), std::fs::Permissions::from_mode(0o644))
.unwrap();
assert!(!holds_program(&plain.display().to_string(), "node"));
- // A relative entry names a folder that depends on where the app
- // happens to run, so it is never searched, even one that reaches a
- // real node from here.
+ // A relative entry is never searched, even one that reaches a real
+ // node from here.
assert!(!holds_program("", "node"));
let cwd = std::env::current_dir().unwrap();
let up = "../".repeat(cwd.components().count() - 1);
diff --git a/plan2code-app/src-tauri/src/pty_host.rs b/plan2code-app/src-tauri/src/pty_host.rs
index 4d881a9..2e0fbc0 100644
--- a/plan2code-app/src-tauri/src/pty_host.rs
+++ b/plan2code-app/src-tauri/src/pty_host.rs
@@ -43,9 +43,8 @@ pub struct PtyHost {
/// a process id that may have been given to something else.
#[cfg(unix)]
exited: Arc,
- /// 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.
+ /// Set once `end_group` has seen the process group empty or killed it, so
+ /// `kill`'s late group kill never signals a group id that may be reused.
#[cfg(unix)]
group_done: Arc,
/// A Windows Job Object the spawned process was assigned to, so ending
@@ -196,12 +195,10 @@ impl PtyHost {
if cfg!(windows) {
return Ok(());
}
- // 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.
+ // portable-pty sends SIGHUP only to the command, on macOS and Linux. It
+ // starts the command under `setsid`, so its pid is also its process
+ // group's id: hang up the group too, and kill what is left of it after
+ // the grace period. A process that left the group is out of reach.
#[cfg(unix)]
if let Some(pid) = self.pid {
// SAFETY: plain signal to the command's own process group.
@@ -214,9 +211,8 @@ impl PtyHost {
// 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.
+ // Signal 0 asks whether any member of the group is left. Once
+ // `end_group` saw it gone, its id may have been reused.
// SAFETY: plain signals to the command's own process group.
if !group_done.load(Ordering::SeqCst)
&& unsafe { libc::kill(-(pid as i32), 0) } == 0
@@ -228,10 +224,10 @@ impl PtyHost {
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.
+ /// Blocks until the command's process group is empty, killing what is left
+ /// after `HANGUP_GRACE`. For after `kill` and `wait` when the app is about to
+ /// exit, since `kill`'s grace thread dies with the app. A no-op on Windows,
+ /// where `kill` ends the Job Object.
pub fn end_group(&self) {
#[cfg(unix)]
if let Some(pid) = self.pid {
diff --git a/plan2code-app/src-tauri/src/term_signal.rs b/plan2code-app/src-tauri/src/term_signal.rs
index 418e12f..4d9766b 100644
--- a/plan2code-app/src-tauri/src/term_signal.rs
+++ b/plan2code-app/src-tauri/src/term_signal.rs
@@ -1,12 +1,9 @@
-//! 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.
+//! Catches SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed), which by
+//! default end the app before its quit cleanup, and runs that cleanup once on a thread of its own.
+//! The handler only writes one byte to a pipe, which is async-signal-safe.
+//! A second SIGTERM or SIGINT ends the process at once, so a stalled cleanup never blocks `kill`.
+//! A repeated SIGHUP does not: closing a terminal can send it twice, from the shell and the
+//! terminal itself.
//! Unix only: Windows has none of these to catch.
use std::io;
@@ -99,8 +96,8 @@ pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
// 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.
+ // The commands the cleanup runs inherit ignored signals, so a repeated SIGHUP
+ // cannot end one before it has done its work.
// SAFETY: ignoring a signal installs no handler.
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
cleanup();
@@ -108,8 +105,8 @@ pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
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.
+ // interrupts elsewhere in the app, and SA_RESETHAND puts the default action back as the
+ // handler is entered, 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 {
diff --git a/plan2code-app/src-tauri/tests/agent_manager.rs b/plan2code-app/src-tauri/tests/agent_manager.rs
index b1d4b79..300828c 100644
--- a/plan2code-app/src-tauri/tests/agent_manager.rs
+++ b/plan2code-app/src-tauri/tests/agent_manager.rs
@@ -654,8 +654,7 @@ fn stray_gone(stray: u32) -> bool {
}
/// 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.
+/// person asked it to leave running (a dev server it backgrounded) stays up.
#[cfg(unix)]
#[test]
fn an_agent_that_exits_by_itself_leaves_its_process_group_running() {
@@ -698,8 +697,8 @@ fn a_replaced_agent_takes_its_process_group_with_it() {
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.
+/// A stop right after a replace waits for the old agent's process group: its
+/// grace runs 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() {
diff --git a/plan2code-app/src-tauri/tests/pty_host.rs b/plan2code-app/src-tauri/tests/pty_host.rs
index 1b40cf9..c7aa513 100644
--- a/plan2code-app/src-tauri/tests/pty_host.rs
+++ b/plan2code-app/src-tauri/tests/pty_host.rs
@@ -103,10 +103,9 @@ 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.
+/// A grandchild that ignores hangup stays in the command's process group, so
+/// `kill` must reach it through the group once the grace is up. An ordinary
+/// grandchild dies 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() {
@@ -124,9 +123,8 @@ fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() {
);
}
-/// 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.
+/// A command that exited by itself was never killed, so no `kill` grace thread
+/// finishes its group: only `end_group` ends the hangup-ignoring grandchild.
#[cfg(unix)]
#[test]
fn end_group_ends_what_a_command_that_exited_by_itself_left() {
diff --git a/plan2code-app/src-tauri/tests/term_signal.rs b/plan2code-app/src-tauri/tests/term_signal.rs
index d75173a..7add0f7 100644
--- a/plan2code-app/src-tauri/tests/term_signal.rs
+++ b/plan2code-app/src-tauri/tests/term_signal.rs
@@ -1,6 +1,5 @@
-//! 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
+//! Checks that SIGTERM, SIGINT and SIGHUP run the app's quit cleanup. A file of its own, so the
+//! handler lives in a test process of its own. The handler installs once per process, so every
//! other case runs in a child: this test binary again, running only `signal_child`.
#![cfg(unix)]
@@ -162,8 +161,8 @@ 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.
+ // Undo signals this run was started with ignored (`nohup`, a script's `&`):
+ // the handler would leave them ignored, which no case below intends.
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) };
diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js
index ec3f2ed..4d4e2dd 100644
--- a/plan2code-app/ui/app.js
+++ b/plan2code-app/ui/app.js
@@ -976,11 +976,10 @@ let consoleKnown = false;
// 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.
+// After a project switch, which stops the old console on purpose: nothing is
+// known here until the new agent opens a page. Otherwise the next poll finds no
+// console and puts "The console stopped" over the new agent's start or the
+// launch card, and the old page in the frame shows its "Lost contact".
function forgetConsole() {
consoleEpoch += 1;
consoleKnown = false;
diff --git a/scripts/test-app-meter.mjs b/scripts/test-app-meter.mjs
index 94b6f44..25c22e1 100644
--- a/scripts/test-app-meter.mjs
+++ b/scripts/test-app-meter.mjs
@@ -1416,7 +1416,7 @@ test("clipboardAction on a Mac: Ctrl+V goes to the agent, Cmd+V is left to the w
});
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.
+ // The rule without its Mac branch, written out on its own.
const before = (event, hasSelection) => {
if (event.altKey) return null;
const key = event.key.toLowerCase();
diff --git a/scripts/test-app-smoke-agent.mjs b/scripts/test-app-smoke-agent.mjs
index 99bb6f1..69dc6be 100644
--- a/scripts/test-app-smoke-agent.mjs
+++ b/scripts/test-app-smoke-agent.mjs
@@ -2,10 +2,8 @@
// 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.
+// 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";
@@ -19,8 +17,8 @@ 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.
+// The desktop app's own variables, removed so the console does not announce
+// itself to a live window.
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_APP_VERSION", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_CONSOLE_SID"];
function outsideAppEnv(extra) {
diff --git a/scripts/test-app-smoke-frame.mjs b/scripts/test-app-smoke-frame.mjs
index 9b8e107..ea40f3d 100644
--- a/scripts/test-app-smoke-frame.mjs
+++ b/scripts/test-app-smoke-frame.mjs
@@ -99,9 +99,8 @@ test("smoke frame: refuses to run with no console home", async () => {
});
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.
+ // Without it, a lost in-app signal would let `open` start the runner's
+ // browser, which signs in by cookie and passes the 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");
diff --git a/scripts/test-web-console-embed.mjs b/scripts/test-web-console-embed.mjs
index 6afdec1..c742993 100644
--- a/scripts/test-web-console-embed.mjs
+++ b/scripts/test-web-console-embed.mjs
@@ -20,9 +20,8 @@ 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. `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.
+// fakes process.platform for the whole server, 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", ...state }));
@@ -148,8 +147,7 @@ function raw(port, urlPath, { method = "GET", headers = {}, body, head = false }
});
}
-// 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.
+// The frame's key, as routes.mjs makes it from the token.
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.
@@ -287,7 +285,7 @@ test("a browser tab on the macOS app's console keeps the cookie and `/`", async
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.
+ // since WebKit 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);
@@ -327,8 +325,7 @@ test("the frame prefix is off everywhere but the macOS app, where `/f/` is just
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.
+ // origin check refuses. 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("});"));
diff --git a/scripts/test-web-console-logic.mjs b/scripts/test-web-console-logic.mjs
index 54b4dd0..81d838f 100644
--- a/scripts/test-web-console-logic.mjs
+++ b/scripts/test-web-console-logic.mjs
@@ -2355,8 +2355,8 @@ test("picker: the workspace picker cannot drift from the launcher's", () => {
});
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.
+ // One rule in two places (macOS: only osascript's (-128) is a cancel); 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"]) {
@@ -2405,7 +2405,7 @@ function fakeSpawn(code, output, errorText = "", platform = process.platform) {
}
// 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).
+// missing default folder or a refused permission also 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";
@@ -2786,8 +2786,7 @@ 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".
+// A start deleted on disk 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 {
diff --git a/scripts/test-web-console-page-frame.mjs b/scripts/test-web-console-page-frame.mjs
index e1e220a..8b69219 100644
--- a/scripts/test-web-console-page-frame.mjs
+++ b/scripts/test-web-console-page-frame.mjs
@@ -1,10 +1,8 @@
-// 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//`, 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:
+// Web console page tests: the page as the macOS app's frame has it, signed in
+// by the path prefix `/f//` (routes.mjs) with no cookie. A request that
+// leaves the prefix gets a 403, and only in the macOS app. This opens the page
+// that way, 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";
@@ -20,11 +18,9 @@ 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.
+// Frame mode needs macOS and the app's page as the embed ancestor. This makes
+// only the server (not the CLI that starts it) see darwin, so CI's Linux run
+// checks it too; every macOS branch in the server runs, not only frameKey().
const FAKE_MAC =
"data:text/javascript," +
encodeURIComponent('if (/server\\.mjs$/.test(process.argv[1] || "")) Object.defineProperty(process, "platform", { value: "darwin" });');
@@ -76,9 +72,8 @@ test("under the frame's prefix, with no cookie, the dashboard draws, its stream
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.
+ // A step waiting on a refused request times out; the finally block reports
+ // the requests that left the prefix or were refused instead, as the cause.
try {
// The Notebook: its tab list and note come from the server.
await page.click("#btn-notepad");
diff --git a/scripts/test-web-console-page-prefs.mjs b/scripts/test-web-console-page-prefs.mjs
index 177c633..1bfc3b7 100644
--- a/scripts/test-web-console-page-prefs.mjs
+++ b/scripts/test-web-console-page-prefs.mjs
@@ -934,7 +934,7 @@ test("with the Narrow card width in a wide window, no Appearance choice overflow
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.
+ // A small window still stacks the choices in one column.
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);
});
diff --git a/scripts/test-web-console-relative-urls.mjs b/scripts/test-web-console-relative-urls.mjs
index ab13e1a..e0a7cbf 100644
--- a/scripts/test-web-console-relative-urls.mjs
+++ b/scripts/test-web-console-relative-urls.mjs
@@ -1,10 +1,8 @@
// 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//`, 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.
+// The macOS app's frame signs in by a path prefix (`/f//`, routes.mjs) and
+// gets the page under it; a slash-leading `/state` drops the prefix and gets a
+// 403 there only, so no other test would notice. This reads the page's source,
+// and the links the server hands it, and names each slash-leading URL.
// Run with: node --test scripts/test-web-console-relative-urls.mjs
import test from "node:test";
@@ -43,19 +41,16 @@ function pageFiles(rel = "") {
}
/**
- * 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 `/`
- * (`` `` ``). 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.
+ * Each string literal in `text` (any quote) that makes a slash-leading URL, as
+ * `{ line, literal }`: text opening with `/` and a path character (a letter,
+ * digit, `_`, `.`, `-` or `${`); a lone `"/"` starting an expression joined on
+ * with `+` (`fetch("/" + route)`, not one mid-path); and markup whose `src`,
+ * `href` or like attribute opens with `/`. Comment lines and anything after a
+ * `//` outside a string are skipped; a string opening `//` is protocol-relative,
+ * which render.js blocks itself. Quotes are tracked per line, so a template
+ * literal spanning lines or a regex holding a quote can hide a URL for the rest
+ * of that line; only the frame page test, which loads just the dashboard, could
+ * catch it at run time.
*/
function scriptUrls(text) {
const hits = [];
diff --git a/src/web-console/notepads.mjs b/src/web-console/notepads.mjs
index d7a56c3..9dcbe7b 100644
--- a/src/web-console/notepads.mjs
+++ b/src/web-console/notepads.mjs
@@ -364,8 +364,7 @@ function imageEntries(dirs) {
return [...seen.values()].sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
}
-// Page-relative, as every link the page uses is: the macOS app's frame has the
-// page under a path prefix (routes.mjs, takeFramePrefix).
+// Page-relative, for the macOS app's frame prefix (routes.mjs, takeFramePrefix).
const imageUrl = (tab, id, thumb) => "notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg";
/**
diff --git a/src/web-console/picker.mjs b/src/web-console/picker.mjs
index c51ba81..e54370e 100644
--- a/src/web-console/picker.mjs
+++ b/src/web-console/picker.mjs
@@ -266,10 +266,10 @@ export function pickFolder(start, prompt, { spawnImpl = spawn, platform = proces
try {
child = spawnImpl(picker.command, picker.args, {
env: { ...process.env, ...(picker.env || {}) },
- // 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.
+ // stderr is piped only on macOS, where osascript's (-128) tells a
+ // cancel from a failure. It is always read, keeping only its end: a
+ // pipe nobody reads fills up and blocks a chatty picker before it can
+ // exit.
stdio: ["ignore", "pipe", platform === "darwin" ? "pipe" : "ignore"],
windowsHide: true,
});
diff --git a/src/web-console/public/screens/activities.js b/src/web-console/public/screens/activities.js
index 5b0fc7e..50e4d18 100644
--- a/src/web-console/public/screens/activities.js
+++ b/src/web-console/public/screens/activities.js
@@ -654,8 +654,8 @@ async function loadGame(entry) {
if (games.has(entry.id)) return games.get(entry.id);
if (!loading.has(entry.id)) {
const made = (async () => {
- // `module` is page-relative, as every URL the page uses is, and import()
- // takes no bare path: resolved against the page, as fetch() would.
+ // `module` is page-relative, and import() rejects a bare path and
+ // resolves against this module, so it is resolved against the page.
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);
diff --git a/src/web-console/public/styles/pieces.css b/src/web-console/public/styles/pieces.css
index ac820cc..2722870 100644
--- a/src/web-console/public/styles/pieces.css
+++ b/src/web-console/public/styles/pieces.css
@@ -826,10 +826,9 @@ 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. */
+/* Four choices in a narrow User Preferences panel (the Narrow card width in a
+ wide window) go two to a row, or "Comfortable" overflows 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)); }
diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs
index 20a5eb7..dc4bc07 100644
--- a/src/web-console/routes.mjs
+++ b/src/web-console/routes.mjs
@@ -158,8 +158,7 @@ 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.
+ // Before anything reads the path: strip the macOS app's frame prefix.
const framed = takeFramePrefix(req, ctx);
const url = new URL(req.url, `http://127.0.0.1:${port}`);
const pathname = url.pathname;
@@ -206,11 +205,10 @@ 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.
+ // macOS WebKit gives the app's cross-site frame no cookie, Lax included, so
+ // the frame goes to its prefix instead (takeFramePrefix). A browser tab sends
+ // `Sec-Fetch-Dest: document` and keeps the cookie, so the prefix stays out of
+ // its address bar; a client that sends no such header gets the prefix.
const key = frameKey(ctx);
if (key && req.headers["sec-fetch-dest"] !== "document") {
res.writeHead(302, baseHeaders({ location: `/f/${key}/` }));
@@ -237,8 +235,8 @@ function signIn(req, res, ctx, url) {
// 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). 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).
+// Lax in a cross-site frame, so signIn() sends the macOS app's frame to its
+// path prefix instead (takeFramePrefix).
function cookieSameSite(ancestor) {
if (ancestor === "'none'") return "SameSite=Strict";
if (ancestor === "tauri://localhost") return "SameSite=Lax";
@@ -2121,29 +2119,25 @@ 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// 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 .localhost:
-// macOS tries it on [::1] first, where another process can listen on the
-// same port and be handed the key.
+// The macOS app's frame signs in by the path prefix /f//, not a cookie:
+// its page, tauri://localhost, is cross-site to this server, and macOS WebKit
+// gives a cross-site frame no cookie at all (its third-party cookie blocking
+// has no switch). The key is a 128-bit hash of the token, so the token never
+// sits in the frame's address. Unlike the HttpOnly cookie, the page's own
+// script can read the key (location.pathname), so this relies on the page's
+// strict CSP keeping any other script out. Null outside the macOS app. Not a
+// host name such as .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.
+// prefix. It comes off the raw request line, not the parsed path, so routes
+// that refuse a path URL parsing had to fold (`..`) still see it. Only the
+// first prefix comes off; a second is just a path. The page uses only
+// page-relative URLs, so it works at / in a browser tab and under the prefix.
const FRAME_PREFIX = /^\/f\/([^/]*)\//;
function takeFramePrefix(req, ctx) {
diff --git a/src/web-console/workspace.mjs b/src/web-console/workspace.mjs
index af08775..a19b756 100644
--- a/src/web-console/workspace.mjs
+++ b/src/web-console/workspace.mjs
@@ -78,7 +78,7 @@ function isFolder(p) {
// 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.
+// since a picker cannot open at a missing folder.
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;