mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-05 16:15:41 -08:00
Trim comments and docs to what the code needs
AI Assisted
This commit is contained in:
1 parent
eba3c3bf0c
commit
0bd721fc27
33 files changed
+292
-392
No files matched your search
@@ -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 `<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.
|
**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.
|
**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` 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.
|
||||||
@@ -181,13 +181,12 @@ jobs:
|
|||||||
- name: Smoke-test the dashboard frame connects (macOS)
|
- name: Smoke-test the dashboard frame connects (macOS)
|
||||||
if: runner.os == 'macOS'
|
if: runner.os == 'macOS'
|
||||||
shell: bash
|
shell: bash
|
||||||
# A window whose dashboard frame never signs in still passes the alive check above
|
# A window whose dashboard frame never signs in (on macOS by a path prefix,
|
||||||
# (WebKit gives the frame no cookie, so macOS signs it in by a path prefix:
|
# takeFramePrefix in routes.mjs) still passes the alive check above. The app
|
||||||
# takeFramePrefix in routes.mjs). Here the app autostarts
|
# autostarts scripts/smoke-agent.mjs, which opens a real console, and
|
||||||
# scripts/smoke-agent.mjs, which opens a real console as an agent would, and
|
# scripts/smoke-frame.mjs waits up to 60s for its /health to count the frame.
|
||||||
# scripts/smoke-frame.mjs waits up to 60s for that console's /health to count the
|
# Runs only where the matrix has macOS: manual runs and pull requests labeled
|
||||||
# frame as a browser. Runs only where the matrix has macOS: manual runs and pull
|
# `full-matrix`.
|
||||||
# requests labeled `full-matrix`.
|
|
||||||
run: |
|
run: |
|
||||||
project="$(mktemp -d)"
|
project="$(mktemp -d)"
|
||||||
export PLAN2CODE_CONSOLE_HOME="$(mktemp -d)"
|
export PLAN2CODE_CONSOLE_HOME="$(mktemp -d)"
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ Security, six controls, about 60 lines:
|
|||||||
1. Bind `127.0.0.1`.
|
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.
|
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 `&`.
|
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. 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.
|
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. A path, not a `<key>.localhost` host name: macOS tries that on `[::1]` first, where another process can take the port.
|
||||||
5. `Origin` check on every mutating request.
|
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.
|
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
|
||||||
|
|
||||||
|
|||||||
@@ -136,8 +136,8 @@ this:
|
|||||||
In the macOS desktop app the page's frame gets no cookie (WebKit blocks
|
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
|
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
|
`/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.
|
of the token, and a request under that exact prefix is signed in. The frame
|
||||||
The frame has no address bar, and a browser tab still gets the cookie.
|
has no address bar, and a browser tab still gets the cookie.
|
||||||
- A strict Content Security Policy with no inline script allowed.
|
- A strict Content Security Policy with no inline script allowed.
|
||||||
- Markdown written by the agent is turned into page elements directly and never
|
- 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
|
into an HTML string, so a document that quotes a hostile README cannot run
|
||||||
|
|||||||
+12
-12
@@ -8,18 +8,18 @@ All notable changes to Plan2Code will be documented in this file.
|
|||||||
|
|
||||||
### 🐛 Fixed
|
### 🐛 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 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, 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 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, as the close button does, and one click answers the question even when the window was in the background.
|
- **Desktop app**: on macOS, Cmd+Q and the menu's Quit ask first while an agent is running.
|
||||||
- **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 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 reaches the agent, so Claude Code can take a pasted picture, and Cmd+V pastes without a Paste menu first.
|
- **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 while the app runs, and the window opens in front of the terminal that started it.
|
- **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 while the agent ends.
|
- **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 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 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**: 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.
|
- **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, shown after a build, no longer says that nothing has been changed yet.
|
- **Quick Task**: the See it running card no longer says 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**: 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 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.
|
- **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)
|
## v3.2.6 (2026-12-04)
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
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`):
|
- [ ] 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
|
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;
|
(Homebrew, or nvm in `~/.zprofile`), `~/.zshrc` is read only on Check again, not at start;
|
||||||
with Homebrew's Node there but the agent installed by npm under nvm in `~/.zshrc`, the agent
|
with Homebrew's Node but the agent installed by npm under nvm in `~/.zshrc`, the agent is
|
||||||
is still found at start. A hung `~/.zprofile`
|
still found at start. A hung `~/.zprofile` delays the start by 3 s at most and a hung
|
||||||
delays the start by 3 s at most and a hung `~/.zshrc` by 2 s; only a slow `~/.zprofile`
|
`~/.zshrc` by 2 s; only a slow `~/.zprofile` followed by a hung `~/.zshrc` reaches 5 s
|
||||||
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
|
- [ ] 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;
|
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
|
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
|
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
|
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
|
- [ ] 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**
|
- [ ] 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
|
(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
|
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
|
||||||
|
|||||||
@@ -1,15 +1,13 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
// A stand-in agent for CI's smoke run of the built app (.github/workflows/app.yml).
|
// 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
|
// point PLAN2CODE_APP_AGENT_BIN at it. Like a real agent, it opens a web console
|
||||||
// console dashboard, with the environment the app gave it, so the console
|
// dashboard with the environment the app gave it, so the console announces
|
||||||
// announces itself to the window and the dashboard frame has something to
|
// itself to the window and the dashboard frame has something to connect to
|
||||||
// connect to (smoke-frame.mjs then checks it did). The repo's fake-agent opens
|
// (smoke-frame.mjs checks it did). fake-agent opens no console.
|
||||||
// no console, so it cannot stand in for this.
|
|
||||||
//
|
//
|
||||||
// It needs PLAN2CODE_CONSOLE_DIR (the folder holding console.mjs), ignores the
|
// 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
|
// app's arguments, and waits until its input closes. The console server is
|
||||||
// closes. It starts nothing else: the console server is detached, and the
|
// detached; the smoke run stops it with `console.mjs stop --all`.
|
||||||
// smoke run stops it with `console.mjs stop --all`.
|
|
||||||
import { spawnSync } from 'node:child_process';
|
import { spawnSync } from 'node:child_process';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
// Checks the app's dashboard frame connected to its console, for CI's macOS smoke
|
// 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
|
// run (.github/workflows/app.yml). A window whose frame never signs in still
|
||||||
// frame in looks alive to a process check; the console's own browser count
|
// passes a process check; the console's own browser count does not.
|
||||||
// does not lie.
|
|
||||||
//
|
//
|
||||||
// node smoke-frame.mjs [<console home>] [--timeout-ms N]
|
// node smoke-frame.mjs [<console home>] [--timeout-ms N]
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -36,10 +36,9 @@ pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
|
|||||||
/// the manager.
|
/// the manager.
|
||||||
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
|
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
|
||||||
|
|
||||||
/// Runs once for each agent that ends, however it ends: by itself, by a stop,
|
/// Runs once for each agent that ends: by itself, by a stop, or replaced by a
|
||||||
/// or replaced by Restart or a loop phase's fresh start. It can run with the
|
/// fresh agent. It can run with the manager's state locked, so it must return
|
||||||
/// manager's state locked, so it must return quickly and must not call back
|
/// quickly and must not call back into the manager.
|
||||||
/// into the manager.
|
|
||||||
pub type Ended = Arc<dyn Fn() + Send + Sync>;
|
pub type Ended = Arc<dyn Fn() + Send + Sync>;
|
||||||
|
|
||||||
/// What the page needs to draw the bar. `generation` counts the agents started
|
/// What the page needs to draw the bar. `generation` counts the agents started
|
||||||
@@ -675,10 +674,8 @@ impl Shared {
|
|||||||
Err(e) => format!("stopped: {e}"),
|
Err(e) => format!("stopped: {e}"),
|
||||||
};
|
};
|
||||||
// Only an agent the app stopped or replaced takes its process
|
// Only an agent the app stopped or replaced takes its process
|
||||||
// group with it: after a Restart or New Session this finishes
|
// group with it. One that ended by itself leaves its group alone,
|
||||||
// what `kill`'s grace thread started (after a stop it finds the
|
// so work the person asked it to leave running survives.
|
||||||
// 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) {
|
if !shared.on_exit(generation, reason) {
|
||||||
host.end_group();
|
host.end_group();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1150,11 +1150,10 @@ pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
|
|||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The command of every built-in and custom agent that the lookup searches
|
/// The built-in and custom agent commands looked up on PATH by name, each once,
|
||||||
/// PATH for by name, each once, in list order. A command with a folder in it
|
/// in list order. A command with a folder in it runs from there, whatever PATH
|
||||||
/// runs from there, whatever PATH holds, so it is left out. The PATH lookup at
|
/// holds, so it is left out. `node_check::login_shell_path` reads the shell's
|
||||||
/// start (`node_check::login_shell_path`) reads the shell's interactive config
|
/// interactive config when none of these is on the login PATH.
|
||||||
/// when none of these is on the login PATH.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub fn path_agent_commands() -> Vec<String> {
|
pub fn path_agent_commands() -> Vec<String> {
|
||||||
let (custom, _) = custom_agents();
|
let (custom, _) = custom_agents();
|
||||||
@@ -1687,8 +1686,8 @@ mod tests {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn the_path_agent_commands_are_the_bare_names_each_once() {
|
fn the_path_agent_commands_are_the_bare_names_each_once() {
|
||||||
// The baked built-ins, then a custom list with a repeat, a quoted
|
// The baked built-ins, then custom commands: a repeat, a quoted name,
|
||||||
// name, a command with a folder in it and an empty one.
|
// two with a folder and a blank one.
|
||||||
let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
|
let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
|
||||||
let custom = [
|
let custom = [
|
||||||
"codex",
|
"codex",
|
||||||
|
|||||||
@@ -412,7 +412,7 @@ impl ConsoleSupervisor {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let result = run_stop(&self.console_dir, &self.project_dir, &self.session.sid);
|
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(_))) {
|
if !matches!(result, Err(StopError::NotRun(_))) {
|
||||||
self.stopped = true;
|
self.stopped = true;
|
||||||
}
|
}
|
||||||
@@ -420,10 +420,8 @@ impl ConsoleSupervisor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `console.mjs stop --session <sid> --force` for any session, run in the
|
/// Runs `console.mjs stop --session <sid> --force` in the project folder, as
|
||||||
/// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console
|
/// `ConsoleSupervisor::stop` does, for a console this app does not supervise.
|
||||||
/// this app does not supervise (one an agent announced and the window has
|
|
||||||
/// since moved on from).
|
|
||||||
pub fn stop_console_session(
|
pub fn stop_console_session(
|
||||||
console_dir: &Path,
|
console_dir: &Path,
|
||||||
project_dir: &Path,
|
project_dir: &Path,
|
||||||
@@ -440,13 +438,11 @@ struct Announced {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The console sessions this app's agents announced on macOS and Linux, by
|
/// 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
|
/// sid, in the order they came: stopped when the agent that opened them ends,
|
||||||
/// them ends, when the window moves on from one an ended agent left, or when
|
/// when the window moves on from one an ended agent left, or at the quit.
|
||||||
/// the app quits. Consoles the app started itself are never recorded here, and
|
/// Consoles the app started itself are never recorded; the bar's stop, which
|
||||||
/// one the app stopped for good is forgotten; the bar's stop, which keeps the
|
/// keeps the session to start it again, leaves one recorded. Also holds the
|
||||||
/// session to start it again, leaves it recorded. Also holds the threads still
|
/// threads still stopping consoles, so a quit can wait for them.
|
||||||
/// stopping consoles after an agent's end or a new page, so a quit can wait for
|
|
||||||
/// them.
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct AnnouncedConsoles {
|
pub struct AnnouncedConsoles {
|
||||||
consoles: Mutex<Vec<Announced>>,
|
consoles: Mutex<Vec<Announced>>,
|
||||||
@@ -554,21 +550,18 @@ impl AnnouncedConsoles {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`):
|
/// 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
|
/// the macOS and Linux stand-in for Windows' Job Object. It takes every console
|
||||||
/// console the next agent announces later is never taken by mistake, then
|
/// `announced` holds at once, inside the hook, so one the next agent announces
|
||||||
/// stops each with `stop` on a thread of its own, since a stop runs `node` and
|
/// is never taken, then stops each with `stop` on a thread of its own: a stop
|
||||||
/// the hook must return quickly. The console the window follows (`followed`)
|
/// runs `node`, and the hook must return quickly. The console the window follows
|
||||||
/// is left to the supervisor and recorded again, as left: stopped under the
|
/// (`followed`) is recorded again as left instead since, stopped under the
|
||||||
/// window, the bar's health poll would only start it again as a server no one
|
/// window, the bar's health poll would start it again as a server no one tracks;
|
||||||
/// tracks. It is stopped once the window moves on (`stop_left`), here if that
|
/// it is stopped when the window moves on (`stop_left`) or at the quit.
|
||||||
/// happened while this thread was deciding, or at the quit. `followed` is asked
|
/// `followed` is asked on that thread: it takes the console lock, held across
|
||||||
/// on that thread too: it takes the console lock, held across `node` runs,
|
/// `node` runs, while the hook runs with the agent manager locked. A caller
|
||||||
/// while the hook runs with the agent manager locked. A caller about to stop
|
/// about to stop the followed console calls `finish_stops` first, so it is not
|
||||||
/// the followed console waits for the thread first (`finish_stops`), so it is
|
/// recorded again after that stop.
|
||||||
/// 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>(
|
pub fn stop_announced_on_end<K, F>(
|
||||||
announced: Arc<AnnouncedConsoles>,
|
announced: Arc<AnnouncedConsoles>,
|
||||||
followed: K,
|
followed: K,
|
||||||
@@ -602,8 +595,8 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if left {
|
if left {
|
||||||
// A page that took the window since the question above found
|
// A page that took the window after `followed()` was asked
|
||||||
// nothing left to stop yet.
|
// found nothing left to stop yet.
|
||||||
for sid in record.take_left(followed().as_deref()) {
|
for sid in record.take_left(followed().as_deref()) {
|
||||||
stop(&sid);
|
stop(&sid);
|
||||||
}
|
}
|
||||||
@@ -709,8 +702,8 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn an_agents_end_asks_which_console_the_window_follows_off_its_own_thread() {
|
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
|
// The hook runs with the agent manager locked, and the followed check
|
||||||
// takes the console lock, which is held across `node` runs: asked
|
// takes the console lock, held across `node` runs: asked in the hook,
|
||||||
// there, typing into the terminal stalled behind a console stop.
|
// it would stall typing in the terminal behind a console stop.
|
||||||
let announced = Arc::new(AnnouncedConsoles::default());
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
let asked_on = Arc::new(Mutex::new(Vec::new()));
|
let asked_on = Arc::new(Mutex::new(Vec::new()));
|
||||||
let log = Arc::clone(&asked_on);
|
let log = Arc::clone(&asked_on);
|
||||||
@@ -735,8 +728,8 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn an_agents_end_leaves_the_console_the_window_follows_and_keeps_it_recorded() {
|
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
|
// 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
|
// console: stopped there, the bar's poll would start it again as a
|
||||||
// a server nobody tracked, which then outlived the quit.
|
// server no one tracks, which would outlive the quit.
|
||||||
let announced = Arc::new(AnnouncedConsoles::default());
|
let announced = Arc::new(AnnouncedConsoles::default());
|
||||||
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
let log = Arc::clone(&stopped);
|
let log = Arc::clone(&stopped);
|
||||||
@@ -810,7 +803,8 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// An agent's end whose console `old` the window shows, where `meanwhile`
|
/// 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<M>(meanwhile: M) -> (Vec<String>, Vec<String>)
|
fn stopped_by_an_end_while<M>(meanwhile: M) -> (Vec<String>, Vec<String>)
|
||||||
where
|
where
|
||||||
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
|
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
|
||||||
@@ -905,8 +899,6 @@ mod tests {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn a_console_call_runs_in_a_process_group_of_its_own() {
|
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 console = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
|
||||||
let mut child = node_command(&console)
|
let mut child = node_command(&console)
|
||||||
.arg("help")
|
.arg("help")
|
||||||
|
|||||||
@@ -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
|
// 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
|
// 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
|
// warnings about agents.json. Async, so a refresh, which can spend seconds in
|
||||||
// can take seconds with a slow profile, so the work runs on a blocking thread:
|
// the person's shell, runs on a blocking thread instead of freezing the window.
|
||||||
// a sync command would run on the main thread and freeze the window meanwhile.
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn agent_availability(refresh: Option<bool>) -> Result<serde_json::Value, String> {
|
async fn agent_availability(refresh: Option<bool>) -> Result<serde_json::Value, String> {
|
||||||
let refresh = refresh == Some(true);
|
let refresh = refresh == Some(true);
|
||||||
@@ -437,13 +436,13 @@ fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
|||||||
// page from a loopback dev server, so the window is asked for its real URL.
|
// 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
|
/// 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).
|
/// 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
|
/// Says whether the window should show it. A session outside this app's
|
||||||
/// under the window stops here, since the window has moved on from it (macOS
|
/// console store is refused: `cargo test` run by the agent inside the app
|
||||||
/// and Linux). A session outside this app's console store is refused: `cargo
|
/// once announced a test's throwaway console, the window followed it, and
|
||||||
/// test` run by the agent inside the app once announced a test's throwaway
|
/// when the test shut it down the reconnect opened an empty dashboard, so the
|
||||||
/// console, the window followed it, and when the test shut it down the
|
/// build's own page was never seen again.
|
||||||
/// reconnect opened an empty dashboard, so the build's own page was never seen
|
/// On macOS and Linux, a console an ended agent left under the window stops
|
||||||
/// again.
|
/// here, since the window has moved on from it.
|
||||||
fn take_announced(
|
fn take_announced(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
notice: &PageNotice,
|
notice: &PageNotice,
|
||||||
@@ -766,10 +765,9 @@ fn confirm_quit(app: &tauri::AppHandle) {
|
|||||||
QuitCase::Waiting => MessageDialogKind::Info,
|
QuitCase::Waiting => MessageDialogKind::Info,
|
||||||
QuitCase::Working => MessageDialogKind::Warning,
|
QuitCase::Working => MessageDialogKind::Warning,
|
||||||
};
|
};
|
||||||
// A close button pressed on a window in the background leaves the app inactive, and the
|
// A window closed from the background leaves the app inactive, and its web view ignores the
|
||||||
// window's web view does not take the first click on an inactive window, so the question
|
// first click on an inactive window; a minimized one would show the question to nobody. So
|
||||||
// would need a click to activate the window before Quit or Stay is heard. A minimized window
|
// the window comes forward, as the key window, before it asks.
|
||||||
// would show it to nobody. So the window comes forward, as the key window, before it asks.
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
if let Some(window) = app.get_webview_window("main") {
|
if let Some(window) = app.get_webview_window("main") {
|
||||||
if window.is_minimized().unwrap_or(false) {
|
if window.is_minimized().unwrap_or(false) {
|
||||||
@@ -839,9 +837,8 @@ fn quit_app(app: &tauri::AppHandle) {
|
|||||||
app.exit(0);
|
app.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The one cleanup every quit runs: from `quit_app`, and on macOS and Linux
|
// The cleanup every quit runs: from `quit_app`, and on macOS and Linux also
|
||||||
// from `RunEvent::Exit` too, for the routes that never pass through
|
// from `RunEvent::Exit` for routes that skip `quit_app`. Safe to call twice.
|
||||||
// `quit_app`. A second call finds nothing left to stop.
|
|
||||||
fn shutdown(app: &tauri::AppHandle) {
|
fn shutdown(app: &tauri::AppHandle) {
|
||||||
let state = app.state::<AppState>();
|
let state = app.state::<AppState>();
|
||||||
shutdown_with(&state);
|
shutdown_with(&state);
|
||||||
@@ -875,9 +872,8 @@ fn shutdown_with(state: &AppState) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// macOS and Linux, after `shutdown_with`: stops every console an agent
|
// After `shutdown_with`, stops every announced console still recorded, each
|
||||||
// announced that is still recorded, each before returning. On Windows the
|
// before returning. On Windows the agent's Job Object ends those consoles.
|
||||||
// agent's Job Object ends those consoles.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
|
fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
|
||||||
for sid in state.announced.take_all() {
|
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
|
// Waits for the threads an agent's end or a new page started (macOS and Linux)
|
||||||
// (macOS and Linux): stopping consoles, and, after an end, deciding whether to
|
// to finish stopping consoles and deciding whether the followed one stays
|
||||||
// keep the one the window follows recorded. Called before taking the console
|
// recorded. Call it before taking the console lock: an end's thread takes that
|
||||||
// lock to stop that console, since the end's thread takes the lock too, and a
|
// lock too, and a decision made after the stop would record the console again.
|
||||||
// decision made after the stop would record it again.
|
|
||||||
fn settle_agent_ends(state: &AppState) {
|
fn settle_agent_ends(state: &AppState) {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
state.announced.finish_stops();
|
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
|
/// 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
|
/// the same session again instead of finding nothing to start.
|
||||||
/// other stops, this one leaves an announced console recorded: the supervisor
|
/// Unlike the other stops, it leaves an announced console recorded, since the
|
||||||
/// keeps its session to start it again, and from then on it stops as any
|
/// supervisor may start it again; it then stops as any announced console does.
|
||||||
/// 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> {
|
fn console_stop_impl(state: &AppState) -> Result<(), String> {
|
||||||
settle_agent_ends(state);
|
settle_agent_ends(state);
|
||||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// macOS takes an app's Dock and Cmd+Tab icon from its `.app` bundle, but the app ships as a bare
|
// macOS takes the Dock and Cmd+Tab icon from an `.app` bundle, and the app ships as a bare program
|
||||||
// program (`tauri build --no-bundle`), so without this the Dock shows the generic "exec" icon.
|
// (`tauri build --no-bundle`), so it sets the icon itself, as Tauri does in dev builds only.
|
||||||
// Tauri sets the icon this way in dev builds only; this does the same in every build.
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
const APP_ICON_ICNS: &[u8] = include_bytes!("../icons/icon.icns");
|
const APP_ICON_ICNS: &[u8] = include_bytes!("../icons/icon.icns");
|
||||||
|
|
||||||
@@ -2130,9 +2122,8 @@ fn set_app_icon() {
|
|||||||
unsafe { app.setApplicationIconImage(Some(&icon)) };
|
unsafe { app.setApplicationIconImage(Some(&icon)) };
|
||||||
}
|
}
|
||||||
|
|
||||||
// A bare program the launcher starts from a terminal is not made the active app, so its window
|
// A bare program started from a terminal is not made the active app, so its window would open
|
||||||
// opened behind that terminal. Once, at start: later shows of the window leave the active app
|
// behind that terminal. Called once, at start; later shows leave the active app alone.
|
||||||
// alone.
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
fn activate_app() {
|
fn activate_app() {
|
||||||
let Some(mtm) = objc2::MainThreadMarker::new() else {
|
let Some(mtm) = objc2::MainThreadMarker::new() else {
|
||||||
@@ -2292,9 +2283,8 @@ fn main() {
|
|||||||
set_app_icon();
|
set_app_icon();
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
activate_app();
|
activate_app();
|
||||||
// A plain `kill`, Ctrl+C or a closed terminal runs the quit cleanup, then exits,
|
// A plain `kill`, Ctrl+C or a closed terminal still runs the quit cleanup. `shutdown`,
|
||||||
// instead of ending the app with its consoles still running. `shutdown`, not
|
// not `quit_app`: a signal never starts a pending update's restart.
|
||||||
// `quit_app`: a signal never starts a pending update's restart.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
let handle = app.handle().clone();
|
let handle = app.handle().clone();
|
||||||
@@ -2311,18 +2301,16 @@ fn main() {
|
|||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while building the Plan2Code app")
|
.expect("error while building the Plan2Code app")
|
||||||
.run(|app, event| {
|
.run(|app, event| {
|
||||||
// The app is going, by whatever route: clean up here too. On macOS,
|
// Every exit cleans up here, including a quit with no agent active and, on
|
||||||
// Dock Quit sends `terminate:`, which raises only this and never asks
|
// macOS, Dock Quit, whose `terminate:` raises only this event and never asks.
|
||||||
// first, and a quit with no agent active still stops the console this
|
// After `quit_app` it finds nothing left.
|
||||||
// way. After `quit_app` this finds nothing left.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
if let tauri::RunEvent::Exit = event {
|
if let tauri::RunEvent::Exit = event {
|
||||||
shutdown(app);
|
shutdown(app);
|
||||||
}
|
}
|
||||||
// An exit nobody asked for in code (`code: None`) asks first while an
|
// An exit not asked for in code (`code: None`) asks first while an agent
|
||||||
// agent works; one with `code` set is `quit_app`'s own. On macOS,
|
// works; one with `code` set is `quit_app`'s own. On macOS, Cmd+Q goes through
|
||||||
// Cmd+Q and the app menu's Quit go through the app's own Quit item
|
// the app's own Quit item (`build_mac_menu`) and Dock Quit never reaches here.
|
||||||
// (`build_mac_menu`), and Dock Quit never reaches here.
|
|
||||||
if let tauri::RunEvent::ExitRequested {
|
if let tauri::RunEvent::ExitRequested {
|
||||||
api, code: None, ..
|
api, code: None, ..
|
||||||
} = event
|
} = event
|
||||||
@@ -2541,8 +2529,8 @@ mod tests {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn a_new_page_stops_the_console_an_ended_agent_left_under_the_window() {
|
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,
|
// New Session: the console the ended agent left under the window stops
|
||||||
// until the next agent's end, the quit or its own idle limit.
|
// once the next agent's page is taken.
|
||||||
let state = state_for("project-a");
|
let state = state_for("project-a");
|
||||||
*state.console.lock().unwrap() = Some(following_the_build());
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
state.announced.record("build");
|
state.announced.record("build");
|
||||||
@@ -2570,9 +2558,8 @@ mod tests {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn a_console_the_app_stopped_is_forgotten_so_no_later_end_stops_it_again() {
|
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
|
// A project switch stops the followed console its agent announced and
|
||||||
// agent announced: still recorded, the next project's agent's end and
|
// forgets it, so neither the next agent's end nor the quit stops it again.
|
||||||
// the quit each ran `console.mjs stop` on it again.
|
|
||||||
let state = state_for("project-a");
|
let state = state_for("project-a");
|
||||||
*state.console.lock().unwrap() = Some(following_the_build());
|
*state.console.lock().unwrap() = Some(following_the_build());
|
||||||
state.announced.record("build");
|
state.announced.record("build");
|
||||||
@@ -2878,10 +2865,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_availability_command_is_awaited_not_run_on_the_ui_thread() {
|
fn the_availability_command_is_awaited_not_run_on_the_ui_thread() {
|
||||||
// Check again re-runs the login shell, then the interactive config
|
// A refresh can spend seconds in the person's shell, so the command is a
|
||||||
// (up to 5 s with slow ones). A sync command runs on the main thread and freezes the
|
// future that hands the work to a blocking thread; awaited, it gives the same list.
|
||||||
// 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))
|
let json = tauri::async_runtime::block_on(agent_availability(None))
|
||||||
.expect("the blocking task finished");
|
.expect("the blocking task finished");
|
||||||
assert_eq!(json, agent_list(false));
|
assert_eq!(json, agent_list(false));
|
||||||
@@ -2976,10 +2961,9 @@ mod tests {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn a_console_the_bar_stopped_and_started_again_still_stops_at_the_quit() {
|
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
|
// The bar's Reconnect (or a skills update) stops the console its agent
|
||||||
// agent announced and starts it again on the same session. When the
|
// announced and starts it again on the same session; once the window
|
||||||
// window then follows the next agent's page, the quit must still stop
|
// follows the next agent's page, the quit must still stop that console.
|
||||||
// that console: once forgotten at the stop, it outlived the app.
|
|
||||||
let Some((_env, sup)) = real_console() else {
|
let Some((_env, sup)) = real_console() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -79,18 +79,14 @@ fn node_override_dir(args: &[String]) -> Option<String> {
|
|||||||
/// launch never gets. Windows sets PATH outside any shell's startup files, so
|
/// launch never gets. Windows sets PATH outside any shell's startup files, so
|
||||||
/// this is unix only.
|
/// this is unix only.
|
||||||
///
|
///
|
||||||
/// The rule: ask the login shell first, within `LOGIN_PATH_TIMEOUT` (3 s),
|
/// Asks the login shell first, where Homebrew and most installers put their
|
||||||
/// since Homebrew and most installers put their PATH lines in its files. Ask
|
/// PATH lines. Asks again with the interactive config (`.zshrc`, where nvm,
|
||||||
/// again with the interactive config too (`.zshrc`, where nvm, fnm and asdf
|
/// fnm and asdf usually put Node and the agents `npm install -g` adds there)
|
||||||
/// usually put Node and the agents `npm install -g` adds under it), within
|
/// only when `node` or every agent command is missing from both the login and
|
||||||
/// `INTERACTIVE_PATH_TIMEOUT` (2 s), only when `node` or every agent command
|
/// inherited PATH, or on Check again, and never after a login timeout, which
|
||||||
/// is missing from both the login and the inherited PATH, or on Check again
|
/// would hang the same way. The interactive config is otherwise left out
|
||||||
/// (`refresh_path`). Never after a login timeout, which would hang the same
|
/// because its terminal-only lines can start daemons that leave the shell's
|
||||||
/// way. So a hung login profile adds at most 3 s to the start, and the slowest
|
/// process group, out of reach of the kill.
|
||||||
/// 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`.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn login_shell_path(args: &[String], inherited: &str, always_interactive: bool) -> Option<String> {
|
fn login_shell_path(args: &[String], inherited: &str, always_interactive: bool) -> Option<String> {
|
||||||
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
|
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)
|
path_from_shell(shell, &known, agents, always_interactive)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How long the shell may take as a login shell, then with its interactive
|
/// How long the login run, and the interactive config run, may each take.
|
||||||
/// config when that is asked too (see `login_shell_path`).
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
const LOGIN_PATH_TIMEOUT: Duration = Duration::from_secs(3);
|
const LOGIN_PATH_TIMEOUT: Duration = Duration::from_secs(3);
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -141,11 +136,10 @@ const SHELL_POLL: Duration = Duration::from_millis(10);
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
const LINGER_GRACE: Duration = Duration::from_millis(200);
|
const LINGER_GRACE: Duration = Duration::from_millis(200);
|
||||||
|
|
||||||
/// SIGKILL to `child`'s whole process group (it leads one, through
|
/// SIGKILL `child`'s whole process group (it leads one, through `setsid`),
|
||||||
/// `setsid`), then reap it, so nothing a profile started in that group
|
/// then reap it, so nothing a profile started in that group outlives the call.
|
||||||
/// outlives the call. Called once the shell has exited too: while any member
|
/// Also used after the shell exited: the id names the group while any member
|
||||||
/// is left, the id still names this group; once it is empty the kill finds
|
/// is left, and the kill finds nothing once it is empty (barring id reuse).
|
||||||
/// nothing, barring the id's reuse within that moment.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn kill_process_group(child: &mut std::process::Child) {
|
fn kill_process_group(child: &mut std::process::Child) {
|
||||||
if let Ok(pgid) = i32::try_from(child.id()) {
|
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();
|
let _ = child.wait();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The login shell's PATH, then the interactive config's when it is needed,
|
/// The login shell's PATH, then the interactive config's when needed, by the
|
||||||
/// by the rule `login_shell_path` describes. The interactive answer holds the
|
/// rule on `login_shell_path`. The interactive answer includes the login PATH,
|
||||||
/// login PATH as well, so it is used whole; when it fails, the login answer is
|
/// so it is used whole; if it fails, the login answer is kept. bash reads its
|
||||||
/// kept. (bash, asked either way, reads `.bash_profile`, `.bash_login` or
|
/// profile files either way, not `.bashrc`, as Terminal's login shells do.
|
||||||
/// `.profile`, not `.bashrc`, as Terminal's login shells do.) `inherited` is
|
/// `inherited` is this app's PATH plus any `--node` folder, `agents` the agent
|
||||||
/// the PATH this app has without the shell (with the `--node` folder, when
|
/// commands to look for (an empty list requires none), and
|
||||||
/// there is one), `agents` the agent commands looked up by name
|
|
||||||
/// (`agents::path_agent_commands`; an empty list asks for none), and
|
|
||||||
/// `always_interactive` is Check again.
|
/// `always_interactive` is Check again.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn path_from_shell(
|
fn path_from_shell(
|
||||||
@@ -218,9 +210,8 @@ fn path_from_shell(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether one of `path`'s absolute folders holds an executable regular file
|
/// Whether one of `path`'s absolute folders holds an executable regular file
|
||||||
/// named `program` (a symlink to one counts). Nothing is run: this only
|
/// named `program` (a symlink to one counts). Relative entries are skipped:
|
||||||
/// decides whether the interactive config is worth asking. A relative entry is
|
/// what they name depends on the app's working directory.
|
||||||
/// never searched, since what it names depends on where the app happens to run.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn holds_program(path: &str, program: &str) -> bool {
|
fn holds_program(path: &str, program: &str) -> bool {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
@@ -240,14 +231,13 @@ fn is_csh(shell: &Path) -> bool {
|
|||||||
.is_some_and(|name| name == "csh" || name == "tcsh")
|
.is_some_and(|name| name == "csh" || name == "tcsh")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The PATH `shell` ends up with as a login shell (and an interactive one
|
/// The PATH `shell` reports as a login shell (and interactive, when
|
||||||
/// when `interactive`), or `None` when it fails, prints no PATH, or takes
|
/// `interactive`), or `None` when it fails, prints no PATH, or exceeds
|
||||||
/// longer than `timeout`. The shell has no input and no terminal, and its
|
/// `timeout`. It runs with no input and no terminal, and its whole process
|
||||||
/// whole process group is killed when it ends, by itself or at the timeout. A
|
/// group is killed when it ends. A shell that answered but lingers (a slow
|
||||||
/// shell that answered but lingers (a slow logout file, an EXIT trap) is ended
|
/// logout file, an EXIT trap) is ended after `LINGER_GRACE`, its answer kept.
|
||||||
/// after `LINGER_GRACE` and its answer kept. csh and tcsh ignore
|
/// csh and tcsh ignore `interactive`: they get `-l` alone and the command on
|
||||||
/// `interactive`: they get `-l` alone and the command on stdin, and their
|
/// stdin, and their `.cshrc` runs either way.
|
||||||
/// `.cshrc` runs either way.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<String> {
|
fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<String> {
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
@@ -285,11 +275,10 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<Stri
|
|||||||
}
|
}
|
||||||
cmd.stdout(Stdio::piped()).stderr(Stdio::null());
|
cmd.stdout(Stdio::piped()).stderr(Stdio::null());
|
||||||
// SAFETY: setsid(2) is async-signal-safe and touches no memory of this
|
// SAFETY: setsid(2) is async-signal-safe and touches no memory of this
|
||||||
// process, so it may run between fork and exec. A new session has no
|
// process, so it may run between fork and exec. The new session has no
|
||||||
// controlling terminal, so an interactive shell started under the
|
// controlling terminal, so an interactive shell cannot take the launcher's
|
||||||
// launcher's terminal cannot take that terminal and be stopped; it is
|
// terminal and be stopped, and its new process group lets the kill reach
|
||||||
// also a new process group, so the timeout's kill reaches every
|
// every descendant.
|
||||||
// descendant.
|
|
||||||
unsafe {
|
unsafe {
|
||||||
cmd.pre_exec(|| {
|
cmd.pre_exec(|| {
|
||||||
if libc::setsid() == -1 {
|
if libc::setsid() == -1 {
|
||||||
@@ -322,7 +311,6 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<Stri
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
// The end marker is in: the answer is complete.
|
|
||||||
let answered = || {
|
let answered = || {
|
||||||
let kept = sink.lock().unwrap_or_else(|e| e.into_inner());
|
let kept = sink.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
kept.windows(end.len()).any(|w| w == end.as_bytes())
|
kept.windows(end.len()).any(|w| w == end.as_bytes())
|
||||||
@@ -341,9 +329,9 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<Stri
|
|||||||
answered_at = Some(now);
|
answered_at = Some(now);
|
||||||
}
|
}
|
||||||
match answered_at {
|
match answered_at {
|
||||||
// Answered, then lingering past the grace: a slow logout
|
// Answered but still running past the grace (a slow
|
||||||
// file or an EXIT trap, which would otherwise cost the
|
// logout file, an EXIT trap): keep the answer rather than
|
||||||
// answer (and, at login, the fallback's answer too).
|
// lose it at the timeout.
|
||||||
Some(at) if now >= at + LINGER_GRACE => {
|
Some(at) if now >= at + LINGER_GRACE => {
|
||||||
kill_process_group(&mut child);
|
kill_process_group(&mut child);
|
||||||
break None;
|
break None;
|
||||||
@@ -368,10 +356,9 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<Stri
|
|||||||
kill_process_group(&mut child);
|
kill_process_group(&mut child);
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
// Something the profile started in the background can hold the pipe
|
// A background job the profile started can hold the pipe open after
|
||||||
// open after the shell exits: stop waiting once the end marker is in,
|
// the shell exits: wait only for the end marker or the deadline, then
|
||||||
// and in any case once the timeout is up. Then end that job, as the
|
// kill the group, which also lets the reader finish.
|
||||||
// linger and timeout paths do, which also lets the reader finish.
|
|
||||||
if let Some(reader) = reader {
|
if let Some(reader) = reader {
|
||||||
while !reader.is_finished() && Instant::now() < deadline && !answered() {
|
while !reader.is_finished() && Instant::now() < deadline && !answered() {
|
||||||
std::thread::sleep(SHELL_POLL);
|
std::thread::sleep(SHELL_POLL);
|
||||||
@@ -384,8 +371,7 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<Stri
|
|||||||
let from = text.find(&start)? + start.len();
|
let from = text.find(&start)? + start.len();
|
||||||
let path = &text[from..from + text[from..].find(&end)?];
|
let path = &text[from..from + text[from..].find(&end)?];
|
||||||
// A shell that does not expand "$PATH" (nushell, for one) prints it as it
|
// A shell that does not expand "$PATH" (nushell, for one) prints it as it
|
||||||
// stands; with no absolute folder at all, the answer is not a PATH. One is
|
// stands, so an answer needs one absolute folder to count as a PATH.
|
||||||
// enough: a real PATH may also carry relative entries such as `.`.
|
|
||||||
let is_a_path = path.split(':').any(|entry| entry.starts_with('/'));
|
let is_a_path = path.split(':').any(|entry| entry.starts_with('/'));
|
||||||
is_a_path.then(|| path.to_string())
|
is_a_path.then(|| path.to_string())
|
||||||
}
|
}
|
||||||
@@ -735,8 +721,7 @@ mod tests {
|
|||||||
assert_eq!(shell_name(""), "sh");
|
assert_eq!(shell_name(""), "sh");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A fresh, empty folder of this test's own, removed when the test ends,
|
/// A fresh, empty folder for one test, removed when it ends, pass or fail.
|
||||||
/// whether it passes or fails.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
struct Scratch(std::path::PathBuf);
|
struct Scratch(std::path::PathBuf);
|
||||||
|
|
||||||
@@ -768,16 +753,11 @@ mod tests {
|
|||||||
/// that gets `-l [-i] -c <command>`, with `last` set to the command. Each
|
/// that gets `-l [-i] -c <command>`, with `last` set to the command. Each
|
||||||
/// body sets its own PATH, so no test touches this process's environment.
|
/// 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
|
/// Run once before it is returned: macOS checks a new script on its first
|
||||||
/// script on its first run, one at a time, which took 230 to 680 ms with
|
/// run, one at a time, which can outlast a short timeout when tests run in
|
||||||
/// five at once (later runs: about 15 ms), longer than a short timeout.
|
/// 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
|
||||||
/// On Linux that first run can fail with ETXTBSY ("Text file busy"):
|
/// child until it execs (rust-lang/rust#114554).
|
||||||
/// 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.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn fake_shell(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
|
fn fake_shell(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
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)]
|
#[cfg(unix)]
|
||||||
const SHORT: std::time::Duration = std::time::Duration::from_millis(300);
|
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
|
/// Timeout for a fake that answers: it returns as soon as the fake exits,
|
||||||
/// generous limit costs nothing and keeps a busy runner from failing it.
|
/// so a generous limit costs nothing and spares a busy runner.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
const ROOMY: std::time::Duration = std::time::Duration::from_secs(5);
|
const ROOMY: std::time::Duration = std::time::Duration::from_secs(5);
|
||||||
|
|
||||||
@@ -848,9 +828,8 @@ mod tests {
|
|||||||
let shell = fake_shell(
|
let shell = fake_shell(
|
||||||
&dir,
|
&dir,
|
||||||
"zsh",
|
"zsh",
|
||||||
// `echo "$last"` stands in for a profile that echoes or replays
|
// `echo "$last"` stands in for a profile that echoes commands; the
|
||||||
// commands: the markers sit in the command only in halves, so the
|
// markers sit in the command only in halves, so it cannot match.
|
||||||
// echoed command text can never pass for the answer.
|
|
||||||
"echo 'Welcome back'\nprintf 'no newline here'\necho \"$last\"\nPATH=/fake/a:/fake/b\neval \"$last\"\necho\necho 'see you'",
|
"echo 'Welcome back'\nprintf 'no newline here'\necho \"$last\"\nPATH=/fake/a:/fake/b\neval \"$last\"\necho\necho 'see you'",
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -863,8 +842,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn shell_path_always_asks_as_a_login_shell() {
|
fn shell_path_always_asks_as_a_login_shell() {
|
||||||
let dir = scratch("login");
|
let dir = scratch("login");
|
||||||
// Answers only when `-l` comes first: the login profile is where
|
// Answers only when `-l` comes first.
|
||||||
// Homebrew and most installers put their PATH lines.
|
|
||||||
let shell = fake_shell(
|
let shell = fake_shell(
|
||||||
&dir,
|
&dir,
|
||||||
"zsh",
|
"zsh",
|
||||||
@@ -1084,12 +1062,10 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn an_answer_with_no_absolute_folder_is_no_path() {
|
fn an_answer_with_no_absolute_folder_is_no_path() {
|
||||||
let dir = scratch("not-a-path");
|
let dir = scratch("not-a-path");
|
||||||
// A shell that does not expand "$PATH" (nushell, for one) prints it
|
// nushell, for one, does not expand "$PATH" and prints it as is.
|
||||||
// as it stands: joined into the app's PATH it would find nothing.
|
|
||||||
let literal = fake_shell(&dir, "nu", "PATH='$PATH'\neval \"$last\"");
|
let literal = fake_shell(&dir, "nu", "PATH='$PATH'\neval \"$last\"");
|
||||||
assert_eq!(shell_path(&literal, true, ROOMY), None);
|
assert_eq!(shell_path(&literal, true, ROOMY), None);
|
||||||
// A real PATH may carry relative entries too; one absolute folder
|
// One absolute folder among relative entries is a PATH, kept as is.
|
||||||
// is enough to show it is a PATH, and it is kept as it is.
|
|
||||||
let mixed = fake_shell(&dir, "zsh", "PATH=.:/usr/bin:bin\neval \"$last\"");
|
let mixed = fake_shell(&dir, "zsh", "PATH=.:/usr/bin:bin\neval \"$last\"");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
shell_path(&mixed, true, ROOMY).as_deref(),
|
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() {
|
fn a_csh_with_no_node_is_still_asked_once_even_on_check_again() {
|
||||||
let dir = scratch("csh-once-no-node");
|
let dir = scratch("csh-once-no-node");
|
||||||
let runs = dir.join("runs");
|
let runs = dir.join("runs");
|
||||||
// Its answer has no node, which for another shell would mean asking
|
// With no node in its answer another shell would be asked again with
|
||||||
// again with the interactive config; csh has no lighter config to
|
// the interactive config; csh reads `.cshrc` either way, so it is not.
|
||||||
// leave out, so a second run would only repeat the first.
|
|
||||||
let shell = fake_shell(
|
let shell = fake_shell(
|
||||||
&dir,
|
&dir,
|
||||||
"csh",
|
"csh",
|
||||||
@@ -1197,9 +1172,8 @@ mod tests {
|
|||||||
path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(),
|
path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(),
|
||||||
Some("/login/bin")
|
Some("/login/bin")
|
||||||
);
|
);
|
||||||
// A quick login answer, then the 2 s interactive timeout. Room for a
|
// A quick login answer, then the interactive timeout: room for a busy
|
||||||
// busy runner, and far short of the 30 s sleep, so the hung config
|
// runner, and far short of the 30 s sleep the hung config would take.
|
||||||
// was not waited on.
|
|
||||||
assert!(
|
assert!(
|
||||||
started.elapsed() < INTERACTIVE_PATH_TIMEOUT + std::time::Duration::from_millis(1400),
|
started.elapsed() < INTERACTIVE_PATH_TIMEOUT + std::time::Duration::from_millis(1400),
|
||||||
"took {:?}",
|
"took {:?}",
|
||||||
@@ -1211,8 +1185,7 @@ mod tests {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
const NO_AGENTS: &[String] = &[];
|
const NO_AGENTS: &[String] = &[];
|
||||||
|
|
||||||
/// A folder in `dir` holding an executable file named `node`, as nvm,
|
/// A folder in `dir` holding an executable file named `node`.
|
||||||
/// Homebrew or Volta leave one. `holds_program` never runs it.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn node_in(dir: &std::path::Path, folder: &str) -> String {
|
fn node_in(dir: &std::path::Path, folder: &str) -> String {
|
||||||
programs_in(dir, folder, &["node"])
|
programs_in(dir, folder, &["node"])
|
||||||
@@ -1232,15 +1205,13 @@ mod tests {
|
|||||||
bin.display().to_string()
|
bin.display().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The agent commands the tests below look for.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn agents(names: &[&str]) -> Vec<String> {
|
fn agents(names: &[&str]) -> Vec<String> {
|
||||||
names.iter().map(|name| name.to_string()).collect()
|
names.iter().map(|name| name.to_string()).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A fake shell whose PATH is `login` as a login shell and `interactive`
|
/// A fake shell whose PATH is `login`, or `interactive` when also given
|
||||||
/// when also given `-i`, and which leaves `<dir>/ran-interactive` behind
|
/// `-i`, which also creates `<dir>/ran-interactive` for the test to check.
|
||||||
/// when given `-i`, so a test can tell whether the interactive config ran.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
fn two_config_shell(
|
fn two_config_shell(
|
||||||
dir: &std::path::Path,
|
dir: &std::path::Path,
|
||||||
@@ -1282,9 +1253,8 @@ mod tests {
|
|||||||
std::fs::set_permissions(plain.join("node"), std::fs::Permissions::from_mode(0o644))
|
std::fs::set_permissions(plain.join("node"), std::fs::Permissions::from_mode(0o644))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(!holds_program(&plain.display().to_string(), "node"));
|
assert!(!holds_program(&plain.display().to_string(), "node"));
|
||||||
// A relative entry names a folder that depends on where the app
|
// A relative entry is never searched, even one that reaches a real
|
||||||
// happens to run, so it is never searched, even one that reaches a
|
// node from here.
|
||||||
// real node from here.
|
|
||||||
assert!(!holds_program("", "node"));
|
assert!(!holds_program("", "node"));
|
||||||
let cwd = std::env::current_dir().unwrap();
|
let cwd = std::env::current_dir().unwrap();
|
||||||
let up = "../".repeat(cwd.components().count() - 1);
|
let up = "../".repeat(cwd.components().count() - 1);
|
||||||
|
|||||||
@@ -43,9 +43,8 @@ pub struct PtyHost {
|
|||||||
/// a process id that may have been given to something else.
|
/// a process id that may have been given to something else.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
exited: Arc<AtomicBool>,
|
exited: Arc<AtomicBool>,
|
||||||
/// Set once `end_group` has seen the process group empty (or killed what
|
/// Set once `end_group` has seen the process group empty or killed it, so
|
||||||
/// was left of it), so `kill`'s late group kill never signals a group id
|
/// `kill`'s late group kill never signals a group id that may be reused.
|
||||||
/// that may since have been given to something else.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
group_done: Arc<AtomicBool>,
|
group_done: Arc<AtomicBool>,
|
||||||
/// A Windows Job Object the spawned process was assigned to, so ending
|
/// A Windows Job Object the spawned process was assigned to, so ending
|
||||||
@@ -196,12 +195,10 @@ impl PtyHost {
|
|||||||
if cfg!(windows) {
|
if cfg!(windows) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
// portable-pty only sends SIGHUP on macOS and Linux, and only to the
|
// portable-pty sends SIGHUP only to the command, on macOS and Linux. It
|
||||||
// command itself. It starts the command under `setsid`, so the
|
// starts the command under `setsid`, so its pid is also its process
|
||||||
// command's pid is also its process group's id: hang up the whole
|
// group's id: hang up the group too, and kill what is left of it after
|
||||||
// group too, then, after the grace period, kill whatever of the group
|
// the grace period. A process that left the group is out of reach.
|
||||||
// is still there. A process that left the group (`setsid`, a detached
|
|
||||||
// child) is out of reach here.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
if let Some(pid) = self.pid {
|
if let Some(pid) = self.pid {
|
||||||
// SAFETY: plain signal to the command's own process group.
|
// 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.
|
// SAFETY: plain signal to a process id the command still holds.
|
||||||
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
||||||
}
|
}
|
||||||
// The group outlives its leader while any member is left; signal 0
|
// Signal 0 asks whether any member of the group is left. Once
|
||||||
// only asks whether one is. Once `end_group` saw it gone, its id
|
// `end_group` saw it gone, its id may have been reused.
|
||||||
// may belong to another group by now: leave it alone.
|
|
||||||
// SAFETY: plain signals to the command's own process group.
|
// SAFETY: plain signals to the command's own process group.
|
||||||
if !group_done.load(Ordering::SeqCst)
|
if !group_done.load(Ordering::SeqCst)
|
||||||
&& unsafe { libc::kill(-(pid as i32), 0) } == 0
|
&& unsafe { libc::kill(-(pid as i32), 0) } == 0
|
||||||
@@ -228,10 +224,10 @@ impl PtyHost {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// For after `kill` and `wait` when the app is about to exit: `kill`'s
|
/// Blocks until the command's process group is empty, killing what is left
|
||||||
/// grace thread dies with the app, so this blocks until nothing of the
|
/// after `HANGUP_GRACE`. For after `kill` and `wait` when the app is about to
|
||||||
/// command's process group is left, killing what is still there after
|
/// exit, since `kill`'s grace thread dies with the app. A no-op on Windows,
|
||||||
/// `HANGUP_GRACE`. A no-op on Windows, where `kill` ended the Job Object.
|
/// where `kill` ends the Job Object.
|
||||||
pub fn end_group(&self) {
|
pub fn end_group(&self) {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
if let Some(pid) = self.pid {
|
if let Some(pid) = self.pid {
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
//! SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed) end a process at
|
//! Catches SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed), which by
|
||||||
//! once by default, so the app's quit cleanup never ran and the consoles its agents had opened
|
//! default end the app before its quit cleanup, and runs that cleanup once on a thread of its own.
|
||||||
//! kept running. Here they are caught instead and handed to a thread of its own, which runs the
|
//! The handler only writes one byte to a pipe, which is async-signal-safe.
|
||||||
//! cleanup it was given, once. The handler only writes one byte to a pipe, which a signal handler
|
//! A second SIGTERM or SIGINT ends the process at once, so a stalled cleanup never blocks `kill`.
|
||||||
//! may safely do; the thread does the work.
|
//! A repeated SIGHUP does not: closing a terminal can send it twice, from the shell and the
|
||||||
//! A second SIGTERM or SIGINT ends the process at once, so a cleanup that stalls never leaves a
|
//! terminal itself.
|
||||||
//! 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.
|
//! Unix only: Windows has none of these to catch.
|
||||||
|
|
||||||
use std::io;
|
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.
|
// The pipe failed: no cleanup can be signalled any more, so none runs.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// For the commands the cleanup runs, which start with this process's ignored signals:
|
// The commands the cleanup runs inherit ignored signals, so a repeated SIGHUP
|
||||||
// a repeated SIGHUP would end one before it has done its work.
|
// cannot end one before it has done its work.
|
||||||
// SAFETY: ignoring a signal installs no handler.
|
// SAFETY: ignoring a signal installs no handler.
|
||||||
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
|
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
|
||||||
cleanup();
|
cleanup();
|
||||||
@@ -108,8 +105,8 @@ pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
|
|||||||
for signal in SIGNALS {
|
for signal in SIGNALS {
|
||||||
// SAFETY: a zeroed sigaction is a valid one to read the current action into, and, with the
|
// 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
|
// 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
|
// interrupts elsewhere in the app, and SA_RESETHAND puts the default action back as the
|
||||||
// handler has run, so a second one ends the app; SIGHUP goes without it.
|
// handler is entered, so a second one ends the app; SIGHUP goes without it.
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut action: libc::sigaction = std::mem::zeroed();
|
let mut action: libc::sigaction = std::mem::zeroed();
|
||||||
if libc::sigaction(signal, std::ptr::null(), &mut action) != 0 {
|
if libc::sigaction(signal, std::ptr::null(), &mut action) != 0 {
|
||||||
|
|||||||
@@ -654,8 +654,7 @@ fn stray_gone(stray: u32) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// An agent that ends by itself leaves its process group alone: work the
|
/// 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,
|
/// 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)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn an_agent_that_exits_by_itself_leaves_its_process_group_running() {
|
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();
|
h.manager.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Quitting right after New Session: the replaced agent's grace is still
|
/// A stop right after a replace waits for the old agent's process group: its
|
||||||
/// running on a thread that would end with the app.
|
/// grace runs on a thread that would end with the app.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn a_stop_right_after_a_restart_waits_for_the_replaced_agents_process_group() {
|
fn a_stop_right_after_a_restart_waits_for_the_replaced_agents_process_group() {
|
||||||
|
|||||||
@@ -103,10 +103,9 @@ fn kill_ends_a_running_step() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A grandchild that ignores hangup is still in the agent's process group
|
/// A grandchild that ignores hangup stays in the command's process group, so
|
||||||
/// (portable-pty starts the agent under `setsid`), so `kill` must reach it
|
/// `kill` must reach it through the group once the grace is up. An ordinary
|
||||||
/// through the group once the grace is up. An ordinary grandchild already dies
|
/// grandchild dies when the kernel hangs up the terminal, so it cannot show this.
|
||||||
/// with its shell, when the kernel hangs up the terminal, so it cannot show this.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() {
|
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
|
/// A command that exited by itself was never killed, so no `kill` grace thread
|
||||||
/// `kill`'s is there to finish its group: only `end_group` can end the
|
/// finishes its group: only `end_group` ends the hangup-ignoring grandchild.
|
||||||
/// grandchild that ignored the terminal's hangup.
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[test]
|
#[test]
|
||||||
fn end_group_ends_what_a_command_that_exited_by_itself_left() {
|
fn end_group_ends_what_a_command_that_exited_by_itself_left() {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
//! The signals that end the app against the handler that turns them into its quit cleanup. A
|
//! Checks that SIGTERM, SIGINT and SIGHUP run the app's quit cleanup. A file of its own, so the
|
||||||
//! file of its own, so the handler lives in a test process of its own: without it, a signal below
|
//! handler lives in a test process of its own. The handler installs once per process, so every
|
||||||
//! 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`.
|
//! other case runs in a child: this test binary again, running only `signal_child`.
|
||||||
#![cfg(unix)]
|
#![cfg(unix)]
|
||||||
|
|
||||||
@@ -162,8 +161,8 @@ fn signal_child() {
|
|||||||
let Some(case) = std::env::var_os(CHILD) else {
|
let Some(case) = std::env::var_os(CHILD) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
// A signal this run was started with ignored (`nohup`, a script's `&`)
|
// Undo signals this run was started with ignored (`nohup`, a script's `&`):
|
||||||
// would stay ignored, and no case below means that one.
|
// the handler would leave them ignored, which no case below intends.
|
||||||
for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
|
for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
|
||||||
// SAFETY: putting a signal's default action back installs no handler.
|
// SAFETY: putting a signal's default action back installs no handler.
|
||||||
unsafe { libc::signal(signal, libc::SIG_DFL) };
|
unsafe { libc::signal(signal, libc::SIG_DFL) };
|
||||||
|
|||||||
@@ -976,11 +976,10 @@ let consoleKnown = false;
|
|||||||
// an answer that comes back afterward is about a console that is gone.
|
// an answer that comes back afterward is about a console that is gone.
|
||||||
let consoleEpoch = 0;
|
let consoleEpoch = 0;
|
||||||
|
|
||||||
// The project moved on, and its console was stopped on purpose: nothing is
|
// After a project switch, which stops the old console on purpose: nothing is
|
||||||
// known here again until the new agent opens a page. Left known, the next
|
// known here until the new agent opens a page. Otherwise the next poll finds no
|
||||||
// poll found no console and put "The console stopped" over the new agent's
|
// console and puts "The console stopped" over the new agent's start or the
|
||||||
// start, or the launch card; left in the frame, the old page showed its "Lost
|
// launch card, and the old page in the frame shows its "Lost contact".
|
||||||
// contact" around it.
|
|
||||||
function forgetConsole() {
|
function forgetConsole() {
|
||||||
consoleEpoch += 1;
|
consoleEpoch += 1;
|
||||||
consoleKnown = false;
|
consoleKnown = false;
|
||||||
|
|||||||
@@ -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", () => {
|
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) => {
|
const before = (event, hasSelection) => {
|
||||||
if (event.altKey) return null;
|
if (event.altKey) return null;
|
||||||
const key = event.key.toLowerCase();
|
const key = event.key.toLowerCase();
|
||||||
|
|||||||
@@ -2,10 +2,8 @@
|
|||||||
// macOS smoke run starts in place of a real agent CLI. Run with:
|
// macOS smoke run starts in place of a real agent CLI. Run with:
|
||||||
// node --test scripts/test-app-smoke-agent.mjs
|
// node --test scripts/test-app-smoke-agent.mjs
|
||||||
//
|
//
|
||||||
// The stand-in has one job: open a real web console the way an agent would,
|
// Runs it outside the app, under a throwaway console home, and checks a live
|
||||||
// so the app's dashboard frame has something to connect to. This runs it
|
// session appears and the stand-in ends when its input closes.
|
||||||
// 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 test from "node:test";
|
||||||
import assert from "node:assert/strict";
|
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 AGENT = path.join(HERE, "../plan2code-app/scripts/smoke-agent.mjs");
|
||||||
const CONSOLE_DIR = path.join(HERE, "../src/web-console");
|
const CONSOLE_DIR = path.join(HERE, "../src/web-console");
|
||||||
|
|
||||||
// The desktop app's own variables would have the console announce itself to
|
// The desktop app's own variables, removed so the console does not announce
|
||||||
// a live window. Deleted from the spawned environment, never inherited.
|
// 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"];
|
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_APP_VERSION", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_CONSOLE_SID"];
|
||||||
|
|
||||||
function outsideAppEnv(extra) {
|
function outsideAppEnv(extra) {
|
||||||
|
|||||||
@@ -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", () => {
|
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
|
// Without it, a lost in-app signal would let `open` start the runner's
|
||||||
// to it were lost, `open` would start the runner's browser, which signs in by
|
// browser, which signs in by cookie and passes the check with the frame dead.
|
||||||
// cookie and would pass this check with the frame dead.
|
|
||||||
const workflow = fs.readFileSync(path.join(HERE, "../.github/workflows/app.yml"), "utf8");
|
const workflow = fs.readFileSync(path.join(HERE, "../.github/workflows/app.yml"), "utf8");
|
||||||
const start = workflow.indexOf("- name: Smoke-test the dashboard frame connects (macOS)");
|
const start = workflow.indexOf("- name: Smoke-test the dashboard frame connects (macOS)");
|
||||||
assert.ok(start >= 0, "the frame step is there");
|
assert.ok(start >= 0, "the frame step is there");
|
||||||
|
|||||||
@@ -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
|
// 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
|
// 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`
|
// 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
|
// fakes process.platform for the whole server, so the macOS-only frame sign-in
|
||||||
// sees it, not only frameKey()), so the macOS-only frame sign-in is tested on
|
// is tested on every OS. `state` adds fields to state.json.
|
||||||
// every OS. `state` adds fields to state.json.
|
|
||||||
async function bootServer(origin, { platform, token = "t", state = {} } = {}) {
|
async function bootServer(origin, { platform, token = "t", state = {} } = {}) {
|
||||||
const dir = fs.mkdtempSync(path.join(HOME, "embed-"));
|
const dir = fs.mkdtempSync(path.join(HOME, "embed-"));
|
||||||
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting", ...state }));
|
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
|
// The frame's key, as routes.mjs makes it from the token.
|
||||||
// never sits in the frame's address, and still 128 bits.
|
|
||||||
const frameKey = (token) => crypto.createHash("sha256").update(token).digest("hex").slice(0, 32);
|
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.
|
// 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.status, 302);
|
||||||
assert.equal(signIn.headers.location, "/");
|
assert.equal(signIn.headers.location, "/");
|
||||||
// The tauri://localhost cookie (cookieSameSite): Lax, never Secure,
|
// 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.match(String(signIn.headers["set-cookie"]), /HttpOnly; SameSite=Lax;/);
|
||||||
assert.doesNotMatch(String(signIn.headers["set-cookie"]), /Secure/);
|
assert.doesNotMatch(String(signIn.headers["set-cookie"]), /Secure/);
|
||||||
const cookie = cookieFor(`http://127.0.0.1:${port}`, MIXED_TOKEN);
|
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", () => {
|
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
|
// 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
|
// `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
|
// origin check refuses. A keepalive fetch is a cors request and sends the real origin.
|
||||||
// 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 core = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "core.js"), "utf8");
|
||||||
const wire = core.slice(core.indexOf("export function wireChrome()"));
|
const wire = core.slice(core.indexOf("export function wireChrome()"));
|
||||||
const pagehide = wire.slice(0, wire.indexOf("});"));
|
const pagehide = wire.slice(0, wire.indexOf("});"));
|
||||||
|
|||||||
@@ -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", () => {
|
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
|
// One rule in two places (macOS: only osascript's (-128) is a cancel); this
|
||||||
// with its own tests: this keeps an edit to one from leaving the other behind.
|
// keeps an edit to one from leaving the other behind.
|
||||||
const { pickerCancelled } = createRequire(import.meta.url)(path.join(ROOT, "src", "launcher", "plan2code.js"));
|
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"];
|
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 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
|
// 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_CANCEL = "0:17: execution error: User canceled. (-128)\n";
|
||||||
const MAC_FAILURE = "0:4: execution error: The variable this is not defined. (-2753)\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], [[], [], ""]);
|
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Browse... opens beside the last folder added. When that folder is gone, a missing
|
// A start deleted on disk must not read as "Browse is not available here".
|
||||||
// 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", () => {
|
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-"));
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-picker-start-"));
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
// Web console page tests: the page as the macOS app's frame has it. WebKit
|
// Web console page tests: the page as the macOS app's frame has it, signed in
|
||||||
// gives that frame no cookie, so the console signs it in by a path prefix
|
// by the path prefix `/f/<key>/` (routes.mjs) with no cookie. A request that
|
||||||
// (`/f/<key>/`, routes.mjs) and the page runs under it. Every request the page
|
// leaves the prefix gets a 403, and only in the macOS app. This opens the page
|
||||||
// makes there must stay under the prefix: one that leaves it gets a 403, and
|
// that way, uses the parts that fetch, and fails on any request that left the
|
||||||
// only in the macOS app. This file opens the page that way in a browser
|
// prefix or was refused. Run with:
|
||||||
// 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
|
// node --test scripts/test-web-console-page-frame.mjs
|
||||||
|
|
||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
@@ -20,11 +18,9 @@ const suite = pageSuite(test);
|
|||||||
|
|
||||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
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
|
// Frame mode needs macOS and the app's page as the embed ancestor. This makes
|
||||||
// the embed ancestor. On any other OS this makes the server alone believe it
|
// only the server (not the CLI that starts it) see darwin, so CI's Linux run
|
||||||
// runs on macOS (the CLI that starts it is left as it is), so CI's Linux run
|
// checks it too; every macOS branch in the server runs, not only frameKey().
|
||||||
// checks the same thing. The whole server sees darwin, not only frameKey():
|
|
||||||
// every macOS branch in it runs here too.
|
|
||||||
const FAKE_MAC =
|
const FAKE_MAC =
|
||||||
"data:text/javascript," +
|
"data:text/javascript," +
|
||||||
encodeURIComponent('if (/server\\.mjs$/.test(process.argv[1] || "")) Object.defineProperty(process, "platform", { value: "darwin" });');
|
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);
|
await until(() => streamed, 10000);
|
||||||
assert.ok(streamed, "the event stream connected under the prefix");
|
assert.ok(streamed, "the event stream connected under the prefix");
|
||||||
|
|
||||||
// A step that waits on a request the server refused times out; the
|
// A step waiting on a refused request times out; the finally block reports
|
||||||
// requests that left the prefix or were refused are the reason, so they
|
// the requests that left the prefix or were refused instead, as the cause.
|
||||||
// are reported first.
|
|
||||||
try {
|
try {
|
||||||
// The Notebook: its tab list and note come from the server.
|
// The Notebook: its tab list and note come from the server.
|
||||||
await page.click("#btn-notepad");
|
await page.click("#btn-notepad");
|
||||||
|
|||||||
@@ -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);
|
await s.page.waitForFunction((w) => (document.documentElement.getAttribute("data-width") ?? "comfortable") === w, width);
|
||||||
assert.deepEqual(await crampedChoices(s), [], 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.setViewportSize({ width: 600, height: 800 });
|
||||||
await s.page.waitForFunction(() => getComputedStyle(document.querySelector("#prefs-panel-appearance .looks-row.four")).gridTemplateColumns.split(" ").length === 1);
|
await s.page.waitForFunction(() => getComputedStyle(document.querySelector("#prefs-panel-appearance .looks-row.four")).gridTemplateColumns.split(" ").length === 1);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
// Web console tests, the page's URLs: every URL the page uses is page-relative.
|
// 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
|
// The macOS app's frame signs in by a path prefix (`/f/<key>/`, routes.mjs) and
|
||||||
// (`/f/<key>/`, routes.mjs) and the page is served under it there, while a
|
// gets the page under it; a slash-leading `/state` drops the prefix and gets a
|
||||||
// browser tab has it at `/`. A relative `state` reaches the server either
|
// 403 there only, so no other test would notice. This reads the page's source,
|
||||||
// way; a slash-leading `/state` drops the prefix and gets a 403, in the macOS
|
// and the links the server hands it, and names each slash-leading URL.
|
||||||
// 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
|
// Run with: node --test scripts/test-web-console-relative-urls.mjs
|
||||||
|
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
@@ -43,19 +41,16 @@ function pageFiles(rel = "") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Each string literal in `text` (double quotes, single quotes or backticks)
|
* Each string literal in `text` (any quote) that makes a slash-leading URL, as
|
||||||
* that makes a slash-leading URL, as `{ line, literal }`, in three shapes:
|
* `{ line, literal }`: text opening with `/` and a path character (a letter,
|
||||||
* text opening with `/` and a path character (a letter, digit, `_`, `.`, `-`
|
* digit, `_`, `.`, `-` or `${`); a lone `"/"` starting an expression joined on
|
||||||
* or `${`); a lone `"/"` that starts an expression joined on with `+`
|
* with `+` (`fetch("/" + route)`, not one mid-path); and markup whose `src`,
|
||||||
* (`fetch("/" + route)`; one joined in the middle of a path is fine); and
|
* `href` or like attribute opens with `/`. Comment lines and anything after a
|
||||||
* markup in a string whose `src`, `href` or like attribute opens with `/`
|
* `//` outside a string are skipped; a string opening `//` is protocol-relative,
|
||||||
* (`` `<img src="/x">` ``). A comment line and anything after a `//` outside
|
* which render.js blocks itself. Quotes are tracked per line, so a template
|
||||||
* a string are skipped; `//` opening a string is the protocol-relative case,
|
* literal spanning lines or a regex holding a quote can hide a URL for the rest
|
||||||
* which render.js blocks on its own. Quotes are tracked one line at a time, so
|
* of that line; only the frame page test, which loads just the dashboard, could
|
||||||
* a template literal that spans lines, or a regex literal holding a quote,
|
* catch it at run time.
|
||||||
* 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) {
|
function scriptUrls(text) {
|
||||||
const hits = [];
|
const hits = [];
|
||||||
|
|||||||
@@ -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));
|
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-relative, for the macOS app's frame prefix (routes.mjs, takeFramePrefix).
|
||||||
// page under a path prefix (routes.mjs, takeFramePrefix).
|
|
||||||
const imageUrl = (tab, id, thumb) => "notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg";
|
const imageUrl = (tab, id, thumb) => "notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -266,10 +266,10 @@ export function pickFolder(start, prompt, { spawnImpl = spawn, platform = proces
|
|||||||
try {
|
try {
|
||||||
child = spawnImpl(picker.command, picker.args, {
|
child = spawnImpl(picker.command, picker.args, {
|
||||||
env: { ...process.env, ...(picker.env || {}) },
|
env: { ...process.env, ...(picker.env || {}) },
|
||||||
// stderr is piped only on macOS, where osascript's (-128) there is
|
// stderr is piped only on macOS, where osascript's (-128) tells a
|
||||||
// what tells a cancel from a failure, and is always read, keeping
|
// cancel from a failure. It is always read, keeping only its end: a
|
||||||
// only its end: a pipe nobody reads fills up and blocks a chatty
|
// pipe nobody reads fills up and blocks a chatty picker before it can
|
||||||
// picker before it can exit. Elsewhere it is not needed.
|
// exit.
|
||||||
stdio: ["ignore", "pipe", platform === "darwin" ? "pipe" : "ignore"],
|
stdio: ["ignore", "pipe", platform === "darwin" ? "pipe" : "ignore"],
|
||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -654,8 +654,8 @@ async function loadGame(entry) {
|
|||||||
if (games.has(entry.id)) return games.get(entry.id);
|
if (games.has(entry.id)) return games.get(entry.id);
|
||||||
if (!loading.has(entry.id)) {
|
if (!loading.has(entry.id)) {
|
||||||
const made = (async () => {
|
const made = (async () => {
|
||||||
// `module` is page-relative, as every URL the page uses is, and import()
|
// `module` is page-relative, and import() rejects a bare path and
|
||||||
// takes no bare path: resolved against the page, as fetch() would.
|
// 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;
|
const def = entry.game || (await import(new URL(entry.module, document.baseURI).href)).default;
|
||||||
defs.set(entry.id, def);
|
defs.set(entry.id, def);
|
||||||
if (def.lowerIsBetter) lowerIsBetter.add(entry.id);
|
if (def.lowerIsBetter) lowerIsBetter.add(entry.id);
|
||||||
|
|||||||
@@ -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; }
|
.modal-ranges .sound-row label { flex: 1 1 100%; padding: 4px 5px; }
|
||||||
.sound-row select { flex: 1 1 auto; min-width: 0; }
|
.sound-row select { flex: 1 1 auto; min-width: 0; }
|
||||||
}
|
}
|
||||||
/* In User Preferences the panel's own width decides too: at the Narrow card
|
/* Four choices in a narrow User Preferences panel (the Narrow card width in a
|
||||||
width the dialog is narrow inside a wide window, where four choices side by
|
wide window) go two to a row, or "Comfortable" overflows its box. Before the
|
||||||
side squeezed "Comfortable" out of its box. Before the window rule below, so
|
window rule below, so a small window still stacks them in one column. */
|
||||||
a small window still stacks them in one column. */
|
|
||||||
.prefs-panels { container-type: inline-size; container-name: prefs-panel; }
|
.prefs-panels { container-type: inline-size; container-name: prefs-panel; }
|
||||||
@container prefs-panel (max-width: 600px) {
|
@container prefs-panel (max-width: 600px) {
|
||||||
.looks-row.four { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
.looks-row.four { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
|
|||||||
+20
-26
@@ -158,8 +158,7 @@ export function handle(req, res, ctx) {
|
|||||||
const port = ctx.port();
|
const port = ctx.port();
|
||||||
if (!hostOk(req, ctx)) return send(res, 403, "", "text/plain");
|
if (!hostOk(req, ctx)) return send(res, 403, "", "text/plain");
|
||||||
|
|
||||||
// Before anything reads the path: the macOS app's frame comes in under its
|
// Before anything reads the path: strip the macOS app's frame prefix.
|
||||||
// prefix, which comes off here, once.
|
|
||||||
const framed = takeFramePrefix(req, ctx);
|
const framed = takeFramePrefix(req, ctx);
|
||||||
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
||||||
const pathname = url.pathname;
|
const pathname = url.pathname;
|
||||||
@@ -206,11 +205,10 @@ function signIn(req, res, ctx, url) {
|
|||||||
const given = url.pathname.slice(3).replace(/\/$/, "");
|
const given = url.pathname.slice(3).replace(/\/$/, "");
|
||||||
if (!ctx.token || !timingSafeEq(given, ctx.token)) return send(res, 403, "Not found", "text/plain");
|
if (!ctx.token || !timingSafeEq(given, ctx.token)) return send(res, 403, "Not found", "text/plain");
|
||||||
ctx.touch();
|
ctx.touch();
|
||||||
// The macOS app's frame goes under its prefix instead (takeFramePrefix):
|
// macOS WebKit gives the app's cross-site frame no cookie, Lax included, so
|
||||||
// WebKit on macOS gives that cross-site frame no cookie, Lax included. A
|
// the frame goes to its prefix instead (takeFramePrefix). A browser tab sends
|
||||||
// browser tab that sends `Sec-Fetch-Dest: document` keeps the cookie, so
|
// `Sec-Fetch-Dest: document` and keeps the cookie, so the prefix stays out of
|
||||||
// the prefix stays out of its address bar. A client that sends no such
|
// its address bar; a client that sends no such header gets the prefix.
|
||||||
// header gets the prefix, the answer that works for the frame.
|
|
||||||
const key = frameKey(ctx);
|
const key = frameKey(ctx);
|
||||||
if (key && req.headers["sec-fetch-dest"] !== "document") {
|
if (key && req.headers["sec-fetch-dest"] !== "document") {
|
||||||
res.writeHead(302, baseHeaders({ location: `/f/${key}/` }));
|
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
|
// 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
|
// 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
|
// 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
|
// Lax in a cross-site frame, so signIn() sends the macOS app's frame to its
|
||||||
// cookie: signIn() sends it under its path prefix instead (takeFramePrefix).
|
// path prefix instead (takeFramePrefix).
|
||||||
function cookieSameSite(ancestor) {
|
function cookieSameSite(ancestor) {
|
||||||
if (ancestor === "'none'") return "SameSite=Strict";
|
if (ancestor === "'none'") return "SameSite=Strict";
|
||||||
if (ancestor === "tauri://localhost") return "SameSite=Lax";
|
if (ancestor === "tauri://localhost") return "SameSite=Lax";
|
||||||
@@ -2121,29 +2119,25 @@ function authed(req, ctx) {
|
|||||||
return c ? timingSafeEq(c, ctx.token) : false;
|
return c ? timingSafeEq(c, ctx.token) : false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The macOS app's frame signs in by a path prefix, not by cookie. The app's
|
// The macOS app's frame signs in by the path prefix /f/<key>/, not a cookie:
|
||||||
// page is tauri://localhost, cross-site to this server, and WebKit gives a
|
// its page, tauri://localhost, is cross-site to this server, and macOS WebKit
|
||||||
// cross-site frame no cookie in any form (its third-party cookie blocking has
|
// gives a cross-site frame no cookie at all (its third-party cookie blocking
|
||||||
// no switch). So the sign-in link sends that frame to /f/<key>/ on this same
|
// has no switch). The key is a 128-bit hash of the token, so the token never
|
||||||
// 127.0.0.1 address, and a request under exactly that prefix is signed in.
|
// sits in the frame's address. Unlike the HttpOnly cookie, the page's own
|
||||||
// The key is a hash of the token, still 128 bits, so the token itself never
|
// script can read the key (location.pathname), so this relies on the page's
|
||||||
// sits in the frame's address. Unlike the HttpOnly cookie, the key is
|
// strict CSP keeping any other script out. Null outside the macOS app. Not a
|
||||||
// readable by the page's own script (location.pathname), so this relies on
|
// host name such as <key>.localhost: macOS tries it on [::1] first, where
|
||||||
// the page's strict CSP keeping any other script out. Off (null) everywhere
|
// another process can listen on the same port and be handed the key.
|
||||||
// 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) {
|
function frameKey(ctx) {
|
||||||
if (process.platform !== "darwin" || embedAncestor() !== "tauri://localhost" || !ctx.token) return null;
|
if (process.platform !== "darwin" || embedAncestor() !== "tauri://localhost" || !ctx.token) return null;
|
||||||
return crypto.createHash("sha256").update(ctx.token).digest("hex").slice(0, 32);
|
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
|
// 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
|
// prefix. It comes off the raw request line, not the parsed path, so routes
|
||||||
// routes that refuse anything URL parsing had to fold (`..`) still see it.
|
// that refuse a path URL parsing had to fold (`..`) still see it. Only the
|
||||||
// Only the first prefix comes off: a second is just a path, and nothing
|
// first prefix comes off; a second is just a path. The page uses only
|
||||||
// serves it. The page asks for everything page-relative (no leading slash),
|
// page-relative URLs, so it works at / in a browser tab and under the prefix.
|
||||||
// so the same page works at / in a browser tab and under the prefix here.
|
|
||||||
const FRAME_PREFIX = /^\/f\/([^/]*)\//;
|
const FRAME_PREFIX = /^\/f\/([^/]*)\//;
|
||||||
|
|
||||||
function takeFramePrefix(req, ctx) {
|
function takeFramePrefix(req, ctx) {
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ function isFolder(p) {
|
|||||||
|
|
||||||
// Where the picker opens: beside the last folder added, else the original, else
|
// 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,
|
// `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) {
|
export function pickerStart(ws, fallback) {
|
||||||
const added = ws.folders.filter((f) => !f.original);
|
const added = ws.folders.filter((f) => !f.original);
|
||||||
const wanted = added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || fallback;
|
const wanted = added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || fallback;
|
||||||
|
|||||||
Reference in new issue
Block a user