Trim comments and docs to what the code needs

AI Assisted
This commit is contained in:
Seth committed 2026-12-05 13:19:59 -08:00
1 parent eba3c3bf0c
commit 0bd721fc27
33 files changed
+292 -392

No files matched your search

+5 -8
View File
@@ -36,10 +36,9 @@ pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
/// the manager.
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
/// Runs once for each agent that ends, however it ends: by itself, by a stop,
/// or replaced by Restart or a loop phase's fresh start. It can run with the
/// manager's state locked, so it must return quickly and must not call back
/// into the manager.
/// Runs once for each agent that ends: by itself, by a stop, or replaced by a
/// fresh agent. It can run with the manager's state locked, so it must return
/// quickly and must not call back into the manager.
pub type Ended = Arc<dyn Fn() + Send + Sync>;
/// What the page needs to draw the bar. `generation` counts the agents started
@@ -675,10 +674,8 @@ impl Shared {
Err(e) => format!("stopped: {e}"),
};
// Only an agent the app stopped or replaced takes its process
// group with it: after a Restart or New Session this finishes
// what `kill`'s grace thread started (after a stop it finds the
// group gone). An agent that ended by itself leaves its group
// alone, so work the person asked it to leave running survives.
// group with it. One that ended by itself leaves its group alone,
// so work the person asked it to leave running survives.
if !shared.on_exit(generation, reason) {
host.end_group();
}
+6 -7
View File
@@ -1150,11 +1150,10 @@ pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
.unwrap_or_default()
}
/// The command of every built-in and custom agent that the lookup searches
/// PATH for by name, each once, in list order. A command with a folder in it
/// runs from there, whatever PATH holds, so it is left out. The PATH lookup at
/// start (`node_check::login_shell_path`) reads the shell's interactive config
/// when none of these is on the login PATH.
/// The built-in and custom agent commands looked up on PATH by name, each once,
/// in list order. A command with a folder in it runs from there, whatever PATH
/// holds, so it is left out. `node_check::login_shell_path` reads the shell's
/// interactive config when none of these is on the login PATH.
#[cfg(unix)]
pub fn path_agent_commands() -> Vec<String> {
let (custom, _) = custom_agents();
@@ -1687,8 +1686,8 @@ mod tests {
#[cfg(unix)]
#[test]
fn the_path_agent_commands_are_the_bare_names_each_once() {
// The baked built-ins, then a custom list with a repeat, a quoted
// name, a command with a folder in it and an empty one.
// The baked built-ins, then custom commands: a repeat, a quoted name,
// two with a folder and a blank one.
let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
let custom = [
"codex",
@@ -412,7 +412,7 @@ impl ConsoleSupervisor {
return Ok(());
}
let result = run_stop(&self.console_dir, &self.project_dir, &self.session.sid);
// Only a stop that could not run at all leaves the flag clear, as before.
// Only a stop that could not run at all leaves the flag clear.
if !matches!(result, Err(StopError::NotRun(_))) {
self.stopped = true;
}
@@ -420,10 +420,8 @@ impl ConsoleSupervisor {
}
}
/// `console.mjs stop --session <sid> --force` for any session, run in the
/// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console
/// this app does not supervise (one an agent announced and the window has
/// since moved on from).
/// Runs `console.mjs stop --session <sid> --force` in the project folder, as
/// `ConsoleSupervisor::stop` does, for a console this app does not supervise.
pub fn stop_console_session(
console_dir: &Path,
project_dir: &Path,
@@ -440,13 +438,11 @@ struct Announced {
}
/// The console sessions this app's agents announced on macOS and Linux, by
/// sid, in the order they came: the ones to stop when the agent that opened
/// them ends, when the window moves on from one an ended agent left, or when
/// the app quits. Consoles the app started itself are never recorded here, and
/// one the app stopped for good is forgotten; the bar's stop, which keeps the
/// session to start it again, leaves it recorded. Also holds the threads still
/// stopping consoles after an agent's end or a new page, so a quit can wait for
/// them.
/// sid, in the order they came: stopped when the agent that opened them ends,
/// when the window moves on from one an ended agent left, or at the quit.
/// Consoles the app started itself are never recorded; the bar's stop, which
/// keeps the session to start it again, leaves one recorded. Also holds the
/// threads still stopping consoles, so a quit can wait for them.
#[derive(Default)]
pub struct AnnouncedConsoles {
consoles: Mutex<Vec<Announced>>,
@@ -554,21 +550,18 @@ impl AnnouncedConsoles {
}
}
/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`):
/// it takes every console `announced` holds at once, inside the hook, so a
/// console the next agent announces later is never taken by mistake, then
/// stops each with `stop` on a thread of its own, since a stop runs `node` and
/// the hook must return quickly. The console the window follows (`followed`)
/// is left to the supervisor and recorded again, as left: stopped under the
/// window, the bar's health poll would only start it again as a server no one
/// tracks. It is stopped once the window moves on (`stop_left`), here if that
/// happened while this thread was deciding, or at the quit. `followed` is asked
/// on that thread too: it takes the console lock, held across `node` runs,
/// while the hook runs with the agent manager locked. A caller about to stop
/// the followed console waits for the thread first (`finish_stops`), so it is
/// never recorded again after that stop.
/// The macOS and Linux stand-in for Windows' Job Object, which ends every
/// console an agent opened along with it.
/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`),
/// the macOS and Linux stand-in for Windows' Job Object. It takes every console
/// `announced` holds at once, inside the hook, so one the next agent announces
/// is never taken, then stops each with `stop` on a thread of its own: a stop
/// runs `node`, and the hook must return quickly. The console the window follows
/// (`followed`) is recorded again as left instead since, stopped under the
/// window, the bar's health poll would start it again as a server no one tracks;
/// it is stopped when the window moves on (`stop_left`) or at the quit.
/// `followed` is asked on that thread: it takes the console lock, held across
/// `node` runs, while the hook runs with the agent manager locked. A caller
/// about to stop the followed console calls `finish_stops` first, so it is not
/// recorded again after that stop.
pub fn stop_announced_on_end<K, F>(
announced: Arc<AnnouncedConsoles>,
followed: K,
@@ -602,8 +595,8 @@ where
}
}
if left {
// A page that took the window since the question above found
// nothing left to stop yet.
// A page that took the window after `followed()` was asked
// found nothing left to stop yet.
for sid in record.take_left(followed().as_deref()) {
stop(&sid);
}
@@ -709,8 +702,8 @@ mod tests {
#[test]
fn an_agents_end_asks_which_console_the_window_follows_off_its_own_thread() {
// The hook runs with the agent manager locked, and the followed check
// takes the console lock, which is held across `node` runs: asked
// there, typing into the terminal stalled behind a console stop.
// takes the console lock, held across `node` runs: asked in the hook,
// it would stall typing in the terminal behind a console stop.
let announced = Arc::new(AnnouncedConsoles::default());
let asked_on = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&asked_on);
@@ -735,8 +728,8 @@ mod tests {
#[test]
fn an_agents_end_leaves_the_console_the_window_follows_and_keeps_it_recorded() {
// New Session ends the old agent while the window still shows its
// console: stopping it there only had the bar's poll bring it back as
// a server nobody tracked, which then outlived the quit.
// console: stopped there, the bar's poll would start it again as a
// server no one tracks, which would outlive the quit.
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
@@ -810,7 +803,8 @@ mod tests {
}
/// An agent's end whose console `old` the window shows, where `meanwhile`
/// runs right after the hook asked which console that is: what it stopped.
/// runs right after the hook asked which console that is. Returns what was
/// stopped and what stays recorded.
fn stopped_by_an_end_while<M>(meanwhile: M) -> (Vec<String>, Vec<String>)
where
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
@@ -905,8 +899,6 @@ mod tests {
#[cfg(unix)]
#[test]
fn a_console_call_runs_in_a_process_group_of_its_own() {
// Ctrl+C and a closing terminal signal the app's whole group: a stop
// already running there ended before it stopped its console.
let console = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
let mut child = node_command(&console)
.arg("help")
+44 -60
View File
@@ -162,9 +162,8 @@ fn platform_info() -> serde_json::Value {
// What the launch card offers per agent: whether its CLI is on PATH (else how
// to install it), and whether it takes its own reasoning effort; plus the
// warnings about agents.json. A refresh runs the person's login shell, which
// can take seconds with a slow profile, so the work runs on a blocking thread:
// a sync command would run on the main thread and freeze the window meanwhile.
// warnings about agents.json. Async, so a refresh, which can spend seconds in
// the person's shell, runs on a blocking thread instead of freezing the window.
#[tauri::command]
async fn agent_availability(refresh: Option<bool>) -> Result<serde_json::Value, String> {
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.
/// A page the agent's `open` announced: the supervisor follows it, or adopts
/// it when the agent started the console (the app owns its stop from there).
/// Says whether the window should show it. The console an ended agent left
/// under the window stops here, since the window has moved on from it (macOS
/// and Linux). A session outside this app's console store is refused: `cargo
/// test` run by the agent inside the app once announced a test's throwaway
/// console, the window followed it, and when the test shut it down the
/// reconnect opened an empty dashboard, so the build's own page was never seen
/// again.
/// Says whether the window should show it. A session outside this app's
/// console store is refused: `cargo test` run by the agent inside the app
/// once announced a test's throwaway console, the window followed it, and
/// when the test shut it down the reconnect opened an empty dashboard, so the
/// build's own page was never seen again.
/// On macOS and Linux, a console an ended agent left under the window stops
/// here, since the window has moved on from it.
fn take_announced(
state: &AppState,
notice: &PageNotice,
@@ -766,10 +765,9 @@ fn confirm_quit(app: &tauri::AppHandle) {
QuitCase::Waiting => MessageDialogKind::Info,
QuitCase::Working => MessageDialogKind::Warning,
};
// A close button pressed on a window in the background leaves the app inactive, and the
// window's web view does not take the first click on an inactive window, so the question
// would need a click to activate the window before Quit or Stay is heard. A minimized window
// would show it to nobody. So the window comes forward, as the key window, before it asks.
// A window closed from the background leaves the app inactive, and its web view ignores the
// first click on an inactive window; a minimized one would show the question to nobody. So
// the window comes forward, as the key window, before it asks.
#[cfg(target_os = "macos")]
if let Some(window) = app.get_webview_window("main") {
if window.is_minimized().unwrap_or(false) {
@@ -839,9 +837,8 @@ fn quit_app(app: &tauri::AppHandle) {
app.exit(0);
}
// The one cleanup every quit runs: from `quit_app`, and on macOS and Linux
// from `RunEvent::Exit` too, for the routes that never pass through
// `quit_app`. A second call finds nothing left to stop.
// The cleanup every quit runs: from `quit_app`, and on macOS and Linux also
// from `RunEvent::Exit` for routes that skip `quit_app`. Safe to call twice.
fn shutdown(app: &tauri::AppHandle) {
let state = app.state::<AppState>();
shutdown_with(&state);
@@ -875,9 +872,8 @@ fn shutdown_with(state: &AppState) {
}
}
// macOS and Linux, after `shutdown_with`: stops every console an agent
// announced that is still recorded, each before returning. On Windows the
// agent's Job Object ends those consoles.
// After `shutdown_with`, stops every announced console still recorded, each
// before returning. On Windows the agent's Job Object ends those consoles.
#[cfg(unix)]
fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
for sid in state.announced.take_all() {
@@ -885,11 +881,10 @@ fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) {
}
}
// Waits for what an agent's end or a new page still has running on a thread
// (macOS and Linux): stopping consoles, and, after an end, deciding whether to
// keep the one the window follows recorded. Called before taking the console
// lock to stop that console, since the end's thread takes the lock too, and a
// decision made after the stop would record it again.
// Waits for the threads an agent's end or a new page started (macOS and Linux)
// to finish stopping consoles and deciding whether the followed one stays
// recorded. Call it before taking the console lock: an end's thread takes that
// lock too, and a decision made after the stop would record the console again.
fn settle_agent_ends(state: &AppState) {
#[cfg(unix)]
state.announced.finish_stops();
@@ -1459,11 +1454,9 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
}
/// Stop the console but keep its supervisor, so a start after a stop opens
/// the same session again instead of finding nothing to start. Unlike the
/// other stops, this one leaves an announced console recorded: the supervisor
/// keeps its session to start it again, and from then on it stops as any
/// announced console does, with its agent, once the window moves on from one
/// an ended agent left, or at the quit.
/// the same session again instead of finding nothing to start.
/// Unlike the other stops, it leaves an announced console recorded, since the
/// supervisor may start it again; it then stops as any announced console does.
fn console_stop_impl(state: &AppState) -> Result<(), String> {
settle_agent_ends(state);
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
@@ -2101,9 +2094,8 @@ fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
Ok(())
}
// macOS takes an app's Dock and Cmd+Tab icon from its `.app` bundle, but the app ships as a bare
// program (`tauri build --no-bundle`), so without this the Dock shows the generic "exec" icon.
// Tauri sets the icon this way in dev builds only; this does the same in every build.
// macOS takes the Dock and Cmd+Tab icon from an `.app` bundle, and the app ships as a bare program
// (`tauri build --no-bundle`), so it sets the icon itself, as Tauri does in dev builds only.
#[cfg(target_os = "macos")]
const APP_ICON_ICNS: &[u8] = include_bytes!("../icons/icon.icns");
@@ -2130,9 +2122,8 @@ fn set_app_icon() {
unsafe { app.setApplicationIconImage(Some(&icon)) };
}
// A bare program the launcher starts from a terminal is not made the active app, so its window
// opened behind that terminal. Once, at start: later shows of the window leave the active app
// alone.
// A bare program started from a terminal is not made the active app, so its window would open
// behind that terminal. Called once, at start; later shows leave the active app alone.
#[cfg(target_os = "macos")]
fn activate_app() {
let Some(mtm) = objc2::MainThreadMarker::new() else {
@@ -2292,9 +2283,8 @@ fn main() {
set_app_icon();
#[cfg(target_os = "macos")]
activate_app();
// A plain `kill`, Ctrl+C or a closed terminal runs the quit cleanup, then exits,
// instead of ending the app with its consoles still running. `shutdown`, not
// `quit_app`: a signal never starts a pending update's restart.
// A plain `kill`, Ctrl+C or a closed terminal still runs the quit cleanup. `shutdown`,
// not `quit_app`: a signal never starts a pending update's restart.
#[cfg(unix)]
{
let handle = app.handle().clone();
@@ -2311,18 +2301,16 @@ fn main() {
.build(tauri::generate_context!())
.expect("error while building the Plan2Code app")
.run(|app, event| {
// The app is going, by whatever route: clean up here too. On macOS,
// Dock Quit sends `terminate:`, which raises only this and never asks
// first, and a quit with no agent active still stops the console this
// way. After `quit_app` this finds nothing left.
// Every exit cleans up here, including a quit with no agent active and, on
// macOS, Dock Quit, whose `terminate:` raises only this event and never asks.
// After `quit_app` it finds nothing left.
#[cfg(unix)]
if let tauri::RunEvent::Exit = event {
shutdown(app);
}
// An exit nobody asked for in code (`code: None`) asks first while an
// agent works; one with `code` set is `quit_app`'s own. On macOS,
// Cmd+Q and the app menu's Quit go through the app's own Quit item
// (`build_mac_menu`), and Dock Quit never reaches here.
// An exit not asked for in code (`code: None`) asks first while an agent
// works; one with `code` set is `quit_app`'s own. On macOS, Cmd+Q goes through
// the app's own Quit item (`build_mac_menu`) and Dock Quit never reaches here.
if let tauri::RunEvent::ExitRequested {
api, code: None, ..
} = event
@@ -2541,8 +2529,8 @@ mod tests {
#[cfg(unix)]
#[test]
fn a_new_page_stops_the_console_an_ended_agent_left_under_the_window() {
// New Session: the old agent's console stayed up with no page in it,
// until the next agent's end, the quit or its own idle limit.
// New Session: the console the ended agent left under the window stops
// once the next agent's page is taken.
let state = state_for("project-a");
*state.console.lock().unwrap() = Some(following_the_build());
state.announced.record("build");
@@ -2570,9 +2558,8 @@ mod tests {
#[cfg(unix)]
#[test]
fn a_console_the_app_stopped_is_forgotten_so_no_later_end_stops_it_again() {
// A project switch stops the console the window follows, which its
// agent announced: still recorded, the next project's agent's end and
// the quit each ran `console.mjs stop` on it again.
// A project switch stops the followed console its agent announced and
// forgets it, so neither the next agent's end nor the quit stops it again.
let state = state_for("project-a");
*state.console.lock().unwrap() = Some(following_the_build());
state.announced.record("build");
@@ -2878,10 +2865,8 @@ mod tests {
#[test]
fn the_availability_command_is_awaited_not_run_on_the_ui_thread() {
// Check again re-runs the login shell, then the interactive config
// (up to 5 s with slow ones). A sync command runs on the main thread and freezes the
// window that long, so the command is a future that hands the work
// to a blocking thread; awaiting it gives the same list.
// A refresh can spend seconds in the person's shell, so the command is a
// future that hands the work to a blocking thread; awaited, it gives the same list.
let json = tauri::async_runtime::block_on(agent_availability(None))
.expect("the blocking task finished");
assert_eq!(json, agent_list(false));
@@ -2976,10 +2961,9 @@ mod tests {
#[cfg(unix)]
#[test]
fn a_console_the_bar_stopped_and_started_again_still_stops_at_the_quit() {
// The bar's Reconnect (or a skills update) stops the console its
// agent announced and starts it again on the same session. When the
// window then follows the next agent's page, the quit must still stop
// that console: once forgotten at the stop, it outlived the app.
// The bar's Reconnect (or a skills update) stops the console its agent
// announced and starts it again on the same session; once the window
// follows the next agent's page, the quit must still stop that console.
let Some((_env, sup)) = real_console() else {
return;
};
+62 -92
View File
@@ -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
/// this is unix only.
///
/// The rule: ask the login shell first, within `LOGIN_PATH_TIMEOUT` (3 s),
/// since Homebrew and most installers put their PATH lines in its files. Ask
/// again with the interactive config too (`.zshrc`, where nvm, fnm and asdf
/// usually put Node and the agents `npm install -g` adds under it), within
/// `INTERACTIVE_PATH_TIMEOUT` (2 s), only when `node` or every agent command
/// is missing from both the login and the inherited PATH, or on Check again
/// (`refresh_path`). Never after a login timeout, which would hang the same
/// way. So a hung login profile adds at most 3 s to the start, and the slowest
/// case 5 s. The interactive config is left out when it is not needed because
/// its terminal-only lines can start daemons that leave the shell's process
/// group, out of reach of any kill here. Details in `path_from_shell` and
/// `shell_path`.
/// Asks the login shell first, where Homebrew and most installers put their
/// PATH lines. Asks again with the interactive config (`.zshrc`, where nvm,
/// fnm and asdf usually put Node and the agents `npm install -g` adds there)
/// only when `node` or every agent command is missing from both the login and
/// inherited PATH, or on Check again, and never after a login timeout, which
/// would hang the same way. The interactive config is otherwise left out
/// because its terminal-only lines can start daemons that leave the shell's
/// process group, out of reach of the kill.
#[cfg(unix)]
fn login_shell_path(args: &[String], inherited: &str, always_interactive: bool) -> Option<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)
}
/// How long the shell may take as a login shell, then with its interactive
/// config when that is asked too (see `login_shell_path`).
/// How long the login run, and the interactive config run, may each take.
#[cfg(unix)]
const LOGIN_PATH_TIMEOUT: Duration = Duration::from_secs(3);
#[cfg(unix)]
@@ -141,11 +136,10 @@ const SHELL_POLL: Duration = Duration::from_millis(10);
#[cfg(unix)]
const LINGER_GRACE: Duration = Duration::from_millis(200);
/// SIGKILL to `child`'s whole process group (it leads one, through
/// `setsid`), then reap it, so nothing a profile started in that group
/// outlives the call. Called once the shell has exited too: while any member
/// is left, the id still names this group; once it is empty the kill finds
/// nothing, barring the id's reuse within that moment.
/// SIGKILL `child`'s whole process group (it leads one, through `setsid`),
/// then reap it, so nothing a profile started in that group outlives the call.
/// Also used after the shell exited: the id names the group while any member
/// is left, and the kill finds nothing once it is empty (barring id reuse).
#[cfg(unix)]
fn kill_process_group(child: &mut std::process::Child) {
if let Ok(pgid) = i32::try_from(child.id()) {
@@ -158,14 +152,12 @@ fn kill_process_group(child: &mut std::process::Child) {
let _ = child.wait();
}
/// The login shell's PATH, then the interactive config's when it is needed,
/// by the rule `login_shell_path` describes. The interactive answer holds the
/// login PATH as well, so it is used whole; when it fails, the login answer is
/// kept. (bash, asked either way, reads `.bash_profile`, `.bash_login` or
/// `.profile`, not `.bashrc`, as Terminal's login shells do.) `inherited` is
/// the PATH this app has without the shell (with the `--node` folder, when
/// there is one), `agents` the agent commands looked up by name
/// (`agents::path_agent_commands`; an empty list asks for none), and
/// The login shell's PATH, then the interactive config's when needed, by the
/// rule on `login_shell_path`. The interactive answer includes the login PATH,
/// so it is used whole; if it fails, the login answer is kept. bash reads its
/// profile files either way, not `.bashrc`, as Terminal's login shells do.
/// `inherited` is this app's PATH plus any `--node` folder, `agents` the agent
/// commands to look for (an empty list requires none), and
/// `always_interactive` is Check again.
#[cfg(unix)]
fn path_from_shell(
@@ -218,9 +210,8 @@ fn path_from_shell(
}
/// Whether one of `path`'s absolute folders holds an executable regular file
/// named `program` (a symlink to one counts). Nothing is run: this only
/// decides whether the interactive config is worth asking. A relative entry is
/// never searched, since what it names depends on where the app happens to run.
/// named `program` (a symlink to one counts). Relative entries are skipped:
/// what they name depends on the app's working directory.
#[cfg(unix)]
fn holds_program(path: &str, program: &str) -> bool {
use std::os::unix::fs::PermissionsExt;
@@ -240,14 +231,13 @@ fn is_csh(shell: &Path) -> bool {
.is_some_and(|name| name == "csh" || name == "tcsh")
}
/// The PATH `shell` ends up with as a login shell (and an interactive one
/// when `interactive`), or `None` when it fails, prints no PATH, or takes
/// longer than `timeout`. The shell has no input and no terminal, and its
/// whole process group is killed when it ends, by itself or at the timeout. A
/// shell that answered but lingers (a slow logout file, an EXIT trap) is ended
/// after `LINGER_GRACE` and its answer kept. csh and tcsh ignore
/// `interactive`: they get `-l` alone and the command on stdin, and their
/// `.cshrc` runs either way.
/// The PATH `shell` reports as a login shell (and interactive, when
/// `interactive`), or `None` when it fails, prints no PATH, or exceeds
/// `timeout`. It runs with no input and no terminal, and its whole process
/// group is killed when it ends. A shell that answered but lingers (a slow
/// logout file, an EXIT trap) is ended after `LINGER_GRACE`, its answer kept.
/// csh and tcsh ignore `interactive`: they get `-l` alone and the command on
/// stdin, and their `.cshrc` runs either way.
#[cfg(unix)]
fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<String> {
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());
// 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
// controlling terminal, so an interactive shell started under the
// launcher's terminal cannot take that terminal and be stopped; it is
// also a new process group, so the timeout's kill reaches every
// descendant.
// process, so it may run between fork and exec. The new session has no
// controlling terminal, so an interactive shell cannot take the launcher's
// terminal and be stopped, and its new process group lets the kill reach
// every descendant.
unsafe {
cmd.pre_exec(|| {
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 kept = sink.lock().unwrap_or_else(|e| e.into_inner());
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);
}
match answered_at {
// Answered, then lingering past the grace: a slow logout
// file or an EXIT trap, which would otherwise cost the
// answer (and, at login, the fallback's answer too).
// Answered but still running past the grace (a slow
// logout file, an EXIT trap): keep the answer rather than
// lose it at the timeout.
Some(at) if now >= at + LINGER_GRACE => {
kill_process_group(&mut child);
break None;
@@ -368,10 +356,9 @@ fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option<Stri
kill_process_group(&mut child);
return None;
}
// Something the profile started in the background can hold the pipe
// open after the shell exits: stop waiting once the end marker is in,
// and in any case once the timeout is up. Then end that job, as the
// linger and timeout paths do, which also lets the reader finish.
// A background job the profile started can hold the pipe open after
// the shell exits: wait only for the end marker or the deadline, then
// kill the group, which also lets the reader finish.
if let Some(reader) = reader {
while !reader.is_finished() && Instant::now() < deadline && !answered() {
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 path = &text[from..from + text[from..].find(&end)?];
// 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
// enough: a real PATH may also carry relative entries such as `.`.
// stands, so an answer needs one absolute folder to count as a PATH.
let is_a_path = path.split(':').any(|entry| entry.starts_with('/'));
is_a_path.then(|| path.to_string())
}
@@ -735,8 +721,7 @@ mod tests {
assert_eq!(shell_name(""), "sh");
}
/// A fresh, empty folder of this test's own, removed when the test ends,
/// whether it passes or fails.
/// A fresh, empty folder for one test, removed when it ends, pass or fail.
#[cfg(unix)]
struct Scratch(std::path::PathBuf);
@@ -768,16 +753,11 @@ mod tests {
/// 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.
///
/// It is run once before it is returned: macOS checks a newly written
/// script on its first run, one at a time, which took 230 to 680 ms with
/// five at once (later runs: about 15 ms), longer than a short timeout.
///
/// On Linux that first run can fail with ETXTBSY ("Text file busy"):
/// another test thread that forks while `write` still holds the file open
/// gives its child a copy of the write descriptor until that child execs
/// (rust-lang/rust#114554). The window is a few microseconds, so the run
/// is retried briefly; once one run has started, no write descriptor is
/// left anywhere and later runs are safe.
/// Run once before it is returned: macOS checks a new script on its first
/// run, one at a time, which can outlast a short timeout when tests run in
/// parallel. That run is retried on ETXTBSY: on Linux, a thread that forks
/// while `write` holds the file open passes the write descriptor to its
/// child until it execs (rust-lang/rust#114554).
#[cfg(unix)]
fn fake_shell(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
@@ -832,12 +812,12 @@ mod tests {
);
}
/// For a fake that hangs: the test waits this long, so it stays short.
/// Timeout for a fake that hangs: the test waits all of it.
#[cfg(unix)]
const SHORT: std::time::Duration = std::time::Duration::from_millis(300);
/// For a fake that answers: it returns as soon as the fake exits, so a
/// generous limit costs nothing and keeps a busy runner from failing it.
/// Timeout for a fake that answers: it returns as soon as the fake exits,
/// so a generous limit costs nothing and spares a busy runner.
#[cfg(unix)]
const ROOMY: std::time::Duration = std::time::Duration::from_secs(5);
@@ -848,9 +828,8 @@ mod tests {
let shell = fake_shell(
&dir,
"zsh",
// `echo "$last"` stands in for a profile that echoes or replays
// commands: the markers sit in the command only in halves, so the
// echoed command text can never pass for the answer.
// `echo "$last"` stands in for a profile that echoes commands; the
// markers sit in the command only in halves, so it cannot match.
"echo 'Welcome back'\nprintf 'no newline here'\necho \"$last\"\nPATH=/fake/a:/fake/b\neval \"$last\"\necho\necho 'see you'",
);
assert_eq!(
@@ -863,8 +842,7 @@ mod tests {
#[test]
fn shell_path_always_asks_as_a_login_shell() {
let dir = scratch("login");
// Answers only when `-l` comes first: the login profile is where
// Homebrew and most installers put their PATH lines.
// Answers only when `-l` comes first.
let shell = fake_shell(
&dir,
"zsh",
@@ -1084,12 +1062,10 @@ mod tests {
#[test]
fn an_answer_with_no_absolute_folder_is_no_path() {
let dir = scratch("not-a-path");
// A shell that does not expand "$PATH" (nushell, for one) prints it
// as it stands: joined into the app's PATH it would find nothing.
// nushell, for one, does not expand "$PATH" and prints it as is.
let literal = fake_shell(&dir, "nu", "PATH='$PATH'\neval \"$last\"");
assert_eq!(shell_path(&literal, true, ROOMY), None);
// A real PATH may carry relative entries too; one absolute folder
// is enough to show it is a PATH, and it is kept as it is.
// One absolute folder among relative entries is a PATH, kept as is.
let mixed = fake_shell(&dir, "zsh", "PATH=.:/usr/bin:bin\neval \"$last\"");
assert_eq!(
shell_path(&mixed, true, ROOMY).as_deref(),
@@ -1143,9 +1119,8 @@ mod tests {
fn a_csh_with_no_node_is_still_asked_once_even_on_check_again() {
let dir = scratch("csh-once-no-node");
let runs = dir.join("runs");
// Its answer has no node, which for another shell would mean asking
// again with the interactive config; csh has no lighter config to
// leave out, so a second run would only repeat the first.
// With no node in its answer another shell would be asked again with
// the interactive config; csh reads `.cshrc` either way, so it is not.
let shell = fake_shell(
&dir,
"csh",
@@ -1197,9 +1172,8 @@ mod tests {
path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(),
Some("/login/bin")
);
// A quick login answer, then the 2 s interactive timeout. Room for a
// busy runner, and far short of the 30 s sleep, so the hung config
// was not waited on.
// A quick login answer, then the interactive timeout: room for a busy
// runner, and far short of the 30 s sleep the hung config would take.
assert!(
started.elapsed() < INTERACTIVE_PATH_TIMEOUT + std::time::Duration::from_millis(1400),
"took {:?}",
@@ -1211,8 +1185,7 @@ mod tests {
#[cfg(unix)]
const NO_AGENTS: &[String] = &[];
/// A folder in `dir` holding an executable file named `node`, as nvm,
/// Homebrew or Volta leave one. `holds_program` never runs it.
/// A folder in `dir` holding an executable file named `node`.
#[cfg(unix)]
fn node_in(dir: &std::path::Path, folder: &str) -> String {
programs_in(dir, folder, &["node"])
@@ -1232,15 +1205,13 @@ mod tests {
bin.display().to_string()
}
/// The agent commands the tests below look for.
#[cfg(unix)]
fn agents(names: &[&str]) -> Vec<String> {
names.iter().map(|name| name.to_string()).collect()
}
/// A fake shell whose PATH is `login` as a login shell and `interactive`
/// when also given `-i`, and which leaves `<dir>/ran-interactive` behind
/// when given `-i`, so a test can tell whether the interactive config ran.
/// A fake shell whose PATH is `login`, or `interactive` when also given
/// `-i`, which also creates `<dir>/ran-interactive` for the test to check.
#[cfg(unix)]
fn two_config_shell(
dir: &std::path::Path,
@@ -1282,9 +1253,8 @@ mod tests {
std::fs::set_permissions(plain.join("node"), std::fs::Permissions::from_mode(0o644))
.unwrap();
assert!(!holds_program(&plain.display().to_string(), "node"));
// A relative entry names a folder that depends on where the app
// happens to run, so it is never searched, even one that reaches a
// real node from here.
// A relative entry is never searched, even one that reaches a real
// node from here.
assert!(!holds_program("", "node"));
let cwd = std::env::current_dir().unwrap();
let up = "../".repeat(cwd.components().count() - 1);
+12 -16
View File
@@ -43,9 +43,8 @@ pub struct PtyHost {
/// a process id that may have been given to something else.
#[cfg(unix)]
exited: Arc<AtomicBool>,
/// Set once `end_group` has seen the process group empty (or killed what
/// was left of it), so `kill`'s late group kill never signals a group id
/// that may since have been given to something else.
/// Set once `end_group` has seen the process group empty or killed it, so
/// `kill`'s late group kill never signals a group id that may be reused.
#[cfg(unix)]
group_done: Arc<AtomicBool>,
/// A Windows Job Object the spawned process was assigned to, so ending
@@ -196,12 +195,10 @@ impl PtyHost {
if cfg!(windows) {
return Ok(());
}
// portable-pty only sends SIGHUP on macOS and Linux, and only to the
// command itself. It starts the command under `setsid`, so the
// command's pid is also its process group's id: hang up the whole
// group too, then, after the grace period, kill whatever of the group
// is still there. A process that left the group (`setsid`, a detached
// child) is out of reach here.
// portable-pty sends SIGHUP only to the command, on macOS and Linux. It
// starts the command under `setsid`, so its pid is also its process
// group's id: hang up the group too, and kill what is left of it after
// the grace period. A process that left the group is out of reach.
#[cfg(unix)]
if let Some(pid) = self.pid {
// SAFETY: plain signal to the command's own process group.
@@ -214,9 +211,8 @@ impl PtyHost {
// SAFETY: plain signal to a process id the command still holds.
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
}
// The group outlives its leader while any member is left; signal 0
// only asks whether one is. Once `end_group` saw it gone, its id
// may belong to another group by now: leave it alone.
// Signal 0 asks whether any member of the group is left. Once
// `end_group` saw it gone, its id may have been reused.
// SAFETY: plain signals to the command's own process group.
if !group_done.load(Ordering::SeqCst)
&& unsafe { libc::kill(-(pid as i32), 0) } == 0
@@ -228,10 +224,10 @@ impl PtyHost {
result
}
/// For after `kill` and `wait` when the app is about to exit: `kill`'s
/// grace thread dies with the app, so this blocks until nothing of the
/// command's process group is left, killing what is still there after
/// `HANGUP_GRACE`. A no-op on Windows, where `kill` ended the Job Object.
/// Blocks until the command's process group is empty, killing what is left
/// after `HANGUP_GRACE`. For after `kill` and `wait` when the app is about to
/// exit, since `kill`'s grace thread dies with the app. A no-op on Windows,
/// where `kill` ends the Job Object.
pub fn end_group(&self) {
#[cfg(unix)]
if let Some(pid) = self.pid {
+10 -13
View File
@@ -1,12 +1,9 @@
//! SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed) end a process at
//! once by default, so the app's quit cleanup never ran and the consoles its agents had opened
//! kept running. Here they are caught instead and handed to a thread of its own, which runs the
//! cleanup it was given, once. The handler only writes one byte to a pipe, which a signal handler
//! may safely do; the thread does the work.
//! A second SIGTERM or SIGINT ends the process at once, so a cleanup that stalls never leaves a
//! plain `kill` unable to end the app. A repeated SIGHUP does not: closing a terminal can send it
//! twice at once, from the shell and from the terminal itself, and the commands the cleanup runs
//! ignore it too.
//! Catches SIGTERM (a plain `kill`), SIGINT (Ctrl+C) and SIGHUP (the terminal closed), which by
//! default end the app before its quit cleanup, and runs that cleanup once on a thread of its own.
//! The handler only writes one byte to a pipe, which is async-signal-safe.
//! A second SIGTERM or SIGINT ends the process at once, so a stalled cleanup never blocks `kill`.
//! A repeated SIGHUP does not: closing a terminal can send it twice, from the shell and the
//! terminal itself.
//! Unix only: Windows has none of these to catch.
use std::io;
@@ -99,8 +96,8 @@ pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
// The pipe failed: no cleanup can be signalled any more, so none runs.
return;
}
// For the commands the cleanup runs, which start with this process's ignored signals:
// a repeated SIGHUP would end one before it has done its work.
// The commands the cleanup runs inherit ignored signals, so a repeated SIGHUP
// cannot end one before it has done its work.
// SAFETY: ignoring a signal installs no handler.
unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) };
cleanup();
@@ -108,8 +105,8 @@ pub fn on_terminate(cleanup: impl FnOnce() + Send + 'static) -> io::Result<()> {
for signal in SIGNALS {
// SAFETY: a zeroed sigaction is a valid one to read the current action into, and, with the
// handler set and an empty mask, to install. SA_RESTART resumes the calls the signal
// interrupts elsewhere in the app, and SA_RESETHAND puts the default action back once the
// handler has run, so a second one ends the app; SIGHUP goes without it.
// interrupts elsewhere in the app, and SA_RESETHAND puts the default action back as the
// handler is entered, so a second one ends the app; SIGHUP goes without it.
unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
if libc::sigaction(signal, std::ptr::null(), &mut action) != 0 {
@@ -654,8 +654,7 @@ fn stray_gone(stray: u32) -> bool {
}
/// An agent that ends by itself leaves its process group alone: work the
/// person asked it to leave running (a dev server it backgrounded) stays up,
/// as it did before the app ended process groups at all.
/// person asked it to leave running (a dev server it backgrounded) stays up.
#[cfg(unix)]
#[test]
fn an_agent_that_exits_by_itself_leaves_its_process_group_running() {
@@ -698,8 +697,8 @@ fn a_replaced_agent_takes_its_process_group_with_it() {
h.manager.stop();
}
/// Quitting right after New Session: the replaced agent's grace is still
/// running on a thread that would end with the app.
/// A stop right after a replace waits for the old agent's process group: its
/// grace runs on a thread that would end with the app.
#[cfg(unix)]
#[test]
fn a_stop_right_after_a_restart_waits_for_the_replaced_agents_process_group() {
+5 -7
View File
@@ -103,10 +103,9 @@ fn kill_ends_a_running_step() {
);
}
/// A grandchild that ignores hangup is still in the agent's process group
/// (portable-pty starts the agent under `setsid`), so `kill` must reach it
/// through the group once the grace is up. An ordinary grandchild already dies
/// with its shell, when the kernel hangs up the terminal, so it cannot show this.
/// A grandchild that ignores hangup stays in the command's process group, so
/// `kill` must reach it through the group once the grace is up. An ordinary
/// grandchild dies when the kernel hangs up the terminal, so it cannot show this.
#[cfg(unix)]
#[test]
fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() {
@@ -124,9 +123,8 @@ fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() {
);
}
/// An agent that ended by itself was never killed, so no grace thread of
/// `kill`'s is there to finish its group: only `end_group` can end the
/// grandchild that ignored the terminal's hangup.
/// A command that exited by itself was never killed, so no `kill` grace thread
/// finishes its group: only `end_group` ends the hangup-ignoring grandchild.
#[cfg(unix)]
#[test]
fn end_group_ends_what_a_command_that_exited_by_itself_left() {
+4 -5
View File
@@ -1,6 +1,5 @@
//! The signals that end the app against the handler that turns them into its quit cleanup. A
//! file of its own, so the handler lives in a test process of its own: without it, a signal below
//! ends the whole process and the run fails. The handler installs once per process, so every
//! Checks that SIGTERM, SIGINT and SIGHUP run the app's quit cleanup. A file of its own, so the
//! handler lives in a test process of its own. The handler installs once per process, so every
//! other case runs in a child: this test binary again, running only `signal_child`.
#![cfg(unix)]
@@ -162,8 +161,8 @@ fn signal_child() {
let Some(case) = std::env::var_os(CHILD) else {
return;
};
// A signal this run was started with ignored (`nohup`, a script's `&`)
// would stay ignored, and no case below means that one.
// Undo signals this run was started with ignored (`nohup`, a script's `&`):
// the handler would leave them ignored, which no case below intends.
for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
// SAFETY: putting a signal's default action back installs no handler.
unsafe { libc::signal(signal, libc::SIG_DFL) };