From 6a93395148934cfc0376ecaa57d9c8372b4105b6 Mon Sep 17 00:00:00 2001 From: Seth <40871381+sethalan@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:30:00 -0800 Subject: [PATCH] End the agent's process group and the consoles it opened on every quit AI Assisted --- plan2code-app/fake-agent/src/main.rs | 31 ++ plan2code-app/src-tauri/src/agent_manager.rs | 137 +++++- .../src-tauri/src/console_supervisor.rs | 456 +++++++++++++++++- plan2code-app/src-tauri/src/main.rs | 421 ++++++++++++++-- plan2code-app/src-tauri/src/pty_host.rs | 55 ++- .../src-tauri/tests/agent_manager.rs | 191 ++++++++ .../src-tauri/tests/console_supervisor.rs | 34 +- plan2code-app/src-tauri/tests/pty_host.rs | 96 ++++ 8 files changed, 1363 insertions(+), 58 deletions(-) diff --git a/plan2code-app/fake-agent/src/main.rs b/plan2code-app/fake-agent/src/main.rs index de35895..91b7078 100644 --- a/plan2code-app/fake-agent/src/main.rs +++ b/plan2code-app/fake-agent/src/main.rs @@ -19,6 +19,9 @@ //! leaves the folder) //! ENV print the variable as `ENV =` //! HANG say `HANGING`, then go silent for good (no more lines read) +//! STRAY (macOS and Linux) start a child that ignores hangup and is never +//! waited for, and print its process id as `STRAY `; elsewhere +//! say `STRAY unavailable` //! echoed back as `echo: ` //! //! A change in terminal size is reported on its own as `SIZE x`. @@ -56,6 +59,8 @@ pub enum Command { File(String, String), /// `HANG`: go silent, to model an agent that stops answering. Hang, + /// `STRAY`: leave a hangup-ignoring child behind in the agent's process group. + Stray, Echo(String), } @@ -134,6 +139,24 @@ fn update_state( std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok() } +/// A child that ignores hangup, in this process's group, never waited for. +#[cfg(unix)] +fn start_stray() -> Option { + std::process::Command::new("/bin/sh") + .args(["-c", "trap '' HUP; exec sleep 300"]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .ok() + .map(|child| child.id()) +} + +#[cfg(not(unix))] +fn start_stray() -> Option { + None +} + pub fn parse(line: &str) -> Command { let line = line.trim(); if let Some(rest) = line.strip_prefix("STEP ") { @@ -176,6 +199,9 @@ pub fn parse(line: &str) -> Command { if line == "HANG" { return Command::Hang; } + if line == "STRAY" { + return Command::Stray; + } Command::Echo(line.to_string()) } @@ -274,6 +300,10 @@ fn main() { thread::sleep(Duration::from_secs(3600)); } } + Command::Stray => match start_stray() { + Some(pid) => say(&format!("STRAY {pid}")), + None => say("STRAY unavailable"), + }, Command::Echo(text) => say(&format!("echo: {text}")), } } @@ -303,6 +333,7 @@ mod tests { Command::Report("{\"phase\":2}".into()) ); assert_eq!(parse("HANG\r\n"), Command::Hang); + assert_eq!(parse("STRAY"), Command::Stray); } #[test] diff --git a/plan2code-app/src-tauri/src/agent_manager.rs b/plan2code-app/src-tauri/src/agent_manager.rs index ce0724b..4b38032 100644 --- a/plan2code-app/src-tauri/src/agent_manager.rs +++ b/plan2code-app/src-tauri/src/agent_manager.rs @@ -35,6 +35,12 @@ pub type BeforeFresh = Arc Option + Send + Sync>; /// the manager. pub type ForgetSession = Arc; +/// Runs once for each agent that ends, however it ends: by itself, by a stop, +/// or replaced by Restart or a loop phase's fresh start. It can run with the +/// manager's state locked, so it must return quickly and must not call back +/// into the manager. +pub type Ended = Arc; + /// What the page needs to draw the bar. `generation` counts the agents started /// so far: a new number means a fresh agent, so the terminal clears. #[derive(Clone, Debug, Serialize)] @@ -116,12 +122,17 @@ struct Shared { sink: Sink, before_fresh: Mutex>, forget_session: Mutex>, + ended: Mutex>, /// Environment every agent this manager starts gets, on top of its own: /// the in-app signal that sends the agent's console pages to this window. extra_env: Mutex>, /// Bumped for every agent started. Output and exits from an older agent /// compare against it and are dropped. generation: AtomicU64, + /// The threads that wait for each agent's end and finish the process group + /// of one the app replaced, so a stop can wait for them. + #[cfg(unix)] + ends: Mutex>>, inner: Mutex, } @@ -144,8 +155,11 @@ impl AgentManager { sink, before_fresh: Mutex::new(None), forget_session: Mutex::new(None), + ended: Mutex::new(None), extra_env: Mutex::new(Vec::new()), generation: AtomicU64::new(0), + #[cfg(unix)] + ends: Mutex::new(Vec::new()), inner: Mutex::new(Inner { state: AgentState::Idle, running: None, @@ -177,6 +191,13 @@ impl AgentManager { } } + /// Run `hook` once for every agent that ends (see `Ended`). + pub fn set_ended(&self, hook: Ended) { + if let Ok(mut slot) = self.shared.ended.lock() { + *slot = Some(hook); + } + } + /// Make the app forget the console session it follows, so the next agent's /// `open` starts a new one. pub fn forget_session(&self) { @@ -366,6 +387,7 @@ impl AgentManager { self.shared.generation.fetch_add(1, Ordering::SeqCst); if let Some(old) = inner.running.take() { let _ = old.host.kill(); + self.shared.ended(); } } match self.shared.spawn(&mut inner, prompt, choice, extra_env) { @@ -455,7 +477,9 @@ impl AgentManager { } /// End the agent for good (quitting). Nothing starts afterwards, and the - /// agent's process is gone when this returns. + /// agent's process, with what is left of its process group on macOS and + /// Linux, is gone when this returns. So is the group of an agent replaced + /// a moment before, whose grace may still be running. pub fn stop(&self) { let host = { let mut inner = lock(&self.shared.inner); @@ -470,7 +494,12 @@ impl AgentManager { if let Some(host) = host { let _ = host.kill(); let _ = host.wait(); + // The app may exit right after, before `kill`'s own grace runs out. + host.end_group(); + self.shared.ended(); } + #[cfg(unix)] + self.shared.finish_ends(); } } @@ -513,6 +542,42 @@ impl Shared { } } + /// An agent ended: run the `ended` hook, if one is set. + fn ended(&self) { + let hook = self.ended.lock().ok().and_then(|slot| slot.clone()); + if let Some(run) = hook { + run(); + } + } + + /// Keep an agent's end thread, so `finish_ends` can wait for it; threads + /// already done are let go. + #[cfg(unix)] + fn keep_end(&self, end: thread::JoinHandle<()>) { + let mut ends = self + .ends + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + ends.retain(|kept| !kept.is_finished()); + ends.push(end); + } + + /// Wait until every agent started here has ended and the process group of + /// each one the app stopped or replaced is gone: the app may exit straight + /// after, which would cut a replaced agent's grace short. + #[cfg(unix)] + fn finish_ends(&self) { + let ends = std::mem::take( + &mut *self + .ends + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()), + ); + for end in ends { + let _ = end.join(); + } + } + fn emit(&self, inner: &Inner) { (self.sink)(AgentEvent::State(self.snapshot(inner))); } @@ -602,14 +667,25 @@ impl Shared { self.emit(inner); let shared = Arc::clone(self); - thread::spawn(move || { + let end = thread::spawn(move || { let reason = match host.wait_described() { - Ok((_, Some(signal))) => format!("was ended by a signal ({signal})"), + Ok((_, Some(signal))) => format!("{SIGNAL_REASON} ({signal})"), Ok((code, None)) => format!("exited with code {code}"), Err(e) => format!("stopped: {e}"), }; - shared.on_exit(generation, reason); + // Only an agent the app stopped or replaced takes its process + // group with it: after a Restart or New Session this finishes + // what `kill`'s grace thread started (after a stop it finds the + // group gone). An agent that ended by itself leaves its group + // alone, so work the person asked it to leave running survives. + if !shared.on_exit(generation, reason) { + host.end_group(); + } }); + #[cfg(unix)] + self.keep_end(end); + #[cfg(not(unix))] + drop(end); Ok(()) } @@ -620,6 +696,7 @@ impl Shared { self.generation.fetch_add(1, Ordering::SeqCst); if let Some(old) = inner.running.take() { let _ = old.host.kill(); + self.ended(); } let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone()); inner.brief_note = hook.and_then(|run| run()); @@ -644,19 +721,42 @@ impl Shared { } } - /// The agent's process ended. Stale if a newer agent has replaced it. - fn on_exit(self: &Arc, generation: u64, reason: String) { + /// The agent's process ended. Stale if a newer agent has replaced it, or + /// the app stopped it. True when it ended by itself (not stale). + fn on_exit(self: &Arc, generation: u64, reason: String) -> bool { let mut inner = lock(&self.inner); if self.generation.load(Ordering::SeqCst) != generation { - return; + return false; } inner.running = None; - // Ended on its own: say why and start nothing. + // Ended on its own: say why and start nothing. A signal nobody here + // sent (stop and Restart move the generation on first) also goes to + // the log, since the bar's reason is gone once a new agent starts. + if let Some((choice, _)) = &inner.last_start { + if let Some(line) = exit_log_line(choice.kind.id(), &reason) { + eprintln!("{line}"); + } + } inner.state = AgentState::Ended { reason }; self.emit(&inner); + // Still locked: no fresh agent can start, and announce, before the + // hook has taken what this one left. + self.ended(); + true } } +/// How the bar's reason starts for an agent a signal ended. +const SIGNAL_REASON: &str = "was ended by a signal"; + +/// The log line for an agent's end, from its id and the bar's reason: only +/// an end by a signal gets one, since an exit code is the agent's own word. +fn exit_log_line(agent: &str, reason: &str) -> Option { + reason + .starts_with(SIGNAL_REASON) + .then(|| format!("plan2code: the agent {agent} {reason}")) +} + #[cfg(test)] mod replay_tests { use super::*; @@ -684,3 +784,24 @@ mod replay_tests { assert_eq!(replay, b"6789"); } } + +#[cfg(test)] +mod exit_log_tests { + use super::*; + + #[test] + fn a_signal_gives_a_line_naming_the_agent_and_the_signal() { + let reason = format!("{SIGNAL_REASON} (Killed: 9)"); + let line = exit_log_line("claude", &reason).expect("a signal is logged"); + assert!(line.contains("claude"), "{line}"); + assert!(line.contains("Killed: 9"), "{line}"); + assert!(line.starts_with("plan2code: "), "{line}"); + } + + #[test] + fn an_exit_code_or_a_failed_wait_gives_no_line() { + assert_eq!(exit_log_line("claude", "exited with code 0"), None); + assert_eq!(exit_log_line("claude", "exited with code 1"), None); + assert_eq!(exit_log_line("claude", "stopped: wait failed"), None); + } +} diff --git a/plan2code-app/src-tauri/src/console_supervisor.rs b/plan2code-app/src-tauri/src/console_supervisor.rs index f401555..b911eea 100644 --- a/plan2code-app/src-tauri/src/console_supervisor.rs +++ b/plan2code-app/src-tauri/src/console_supervisor.rs @@ -6,6 +6,7 @@ use std::io::{Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use serde::Serialize; @@ -403,22 +404,237 @@ impl ConsoleSupervisor { if self.stopped { return Ok(()); } - let output = node_command(&self.console_dir) - .args(stop_args(&self.session.sid)) - .current_dir(&self.project_dir) - .output() - .map_err(err)?; - self.stopped = true; - if !output.status.success() { - return Err(format!( - "console stop failed: {}", - String::from_utf8_lossy(&output.stderr).trim() - )); + let result = run_stop(&self.console_dir, &self.project_dir, &self.session.sid); + // Only a stop that could not run at all leaves the flag clear, as before. + if !matches!(result, Err(StopError::NotRun(_))) { + self.stopped = true; } - Ok(()) + result.map_err(StopError::into_message) } } +/// `console.mjs stop --session --force` for any session, run in the +/// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console +/// this app does not supervise (one an agent announced and the window has +/// since moved on from). +pub fn stop_console_session( + console_dir: &Path, + project_dir: &Path, + sid: &str, +) -> Result<(), String> { + run_stop(console_dir, project_dir, sid).map_err(StopError::into_message) +} + +/// One console an agent announced. `left` once that agent has ended while the +/// window still showed the console: nothing needs it after the window moves on. +struct Announced { + sid: String, + left: bool, +} + +/// The console sessions this app's agents announced on macOS and Linux, by +/// sid, in the order they came: the ones to stop when the agent that opened +/// them ends, when the window moves on from one an ended agent left, or when +/// the app quits. Consoles the app started itself are never recorded here, and +/// one the app stopped for good is forgotten; the bar's stop, which keeps the +/// session to start it again, leaves it recorded. Also holds the threads still +/// stopping consoles after an agent's end or a new page, so a quit can wait for +/// them. +#[derive(Default)] +pub struct AnnouncedConsoles { + consoles: Mutex>, + stops: Mutex>>, +} + +impl AnnouncedConsoles { + fn lock(&self) -> MutexGuard<'_, Vec> { + self.consoles + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Remember `sid`, announced by a running agent; one already recorded is + /// kept once, and is no longer left: the new agent joined it. + pub fn record(&self, sid: &str) { + let mut consoles = self.lock(); + match consoles.iter_mut().find(|known| known.sid == sid) { + Some(known) => known.left = false, + None => consoles.push(Announced { + sid: sid.to_string(), + left: false, + }), + } + } + + /// Remember `sid` as left by an agent that has ended; one a new agent + /// announced in the meantime stays that agent's. + fn leave(&self, sid: &str) { + let mut consoles = self.lock(); + if !consoles.iter().any(|known| known.sid == sid) { + consoles.push(Announced { + sid: sid.to_string(), + left: true, + }); + } + } + + /// Drop `sid` from the record: the app stopped that console itself. + pub fn forget(&self, sid: &str) { + self.lock().retain(|known| known.sid != sid); + } + + /// Every recorded sid, in record order, and an empty record after. + pub fn take_all(&self) -> Vec { + std::mem::take(&mut *self.lock()) + .into_iter() + .map(|known| known.sid) + .collect() + } + + /// Every console left by an agent that has ended, but for the one the + /// window follows, no longer recorded after. + fn take_left(&self, followed: Option<&str>) -> Vec { + let mut consoles = self.lock(); + let (left, kept) = std::mem::take(&mut *consoles) + .into_iter() + .partition(|known| known.left && followed != Some(known.sid.as_str())); + *consoles = kept; + left.into_iter().map(|known| known.sid).collect() + } + + /// The window follows `followed` now: stop each console an agent that has + /// ended left under it, with `stop` on a thread of its own, since a stop + /// runs `node`. A console of an agent still running is never touched. + pub fn stop_left(&self, followed: &str, stop: F) + where + F: Fn(&str) + Send + 'static, + { + let sids = self.take_left(Some(followed)); + if sids.is_empty() { + return; + } + self.keep_stop(std::thread::spawn(move || { + for sid in sids { + stop(&sid); + } + })); + } + + /// Keep a thread that is stopping consoles, so `finish_stops` can wait + /// for it; threads already done are let go. + fn keep_stop(&self, stop: std::thread::JoinHandle<()>) { + let mut stops = self + .stops + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + stops.retain(|kept| !kept.is_finished()); + stops.push(stop); + } + + /// Wait for every console stop still running on a thread, after an agent's + /// end or a new page: the app may exit straight after, which would cut it + /// short. + pub fn finish_stops(&self) { + let stops = std::mem::take( + &mut *self + .stops + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()), + ); + for stop in stops { + let _ = stop.join(); + } + } +} + +/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`): +/// it takes every console `announced` holds at once, inside the hook, so a +/// console the next agent announces later is never taken by mistake, then +/// stops each with `stop` on a thread of its own, since a stop runs `node` and +/// the hook must return quickly. The console the window follows (`followed`) +/// is left to the supervisor and recorded again, as left: stopped under the +/// window, the bar's health poll would only start it again as a server no one +/// tracks. It is stopped once the window moves on (`stop_left`), here if that +/// happened while this thread was deciding, or at the quit. `followed` is asked +/// on that thread too: it takes the console lock, held across `node` runs, +/// while the hook runs with the agent manager locked. A caller about to stop +/// the followed console waits for the thread first (`finish_stops`), so it is +/// never recorded again after that stop. +/// The macOS and Linux stand-in for Windows' Job Object, which ends every +/// console an agent opened along with it. +pub fn stop_announced_on_end( + announced: Arc, + followed: K, + stop: F, +) -> Arc +where + K: Fn() -> Option + Send + Sync + 'static, + F: Fn(&str) + Send + Sync + 'static, +{ + let followed = Arc::new(followed); + let stop = Arc::new(stop); + Arc::new(move || { + let sids = announced.take_all(); + if sids.is_empty() { + return; + } + let (followed, stop, record) = ( + Arc::clone(&followed), + Arc::clone(&stop), + Arc::clone(&announced), + ); + announced.keep_stop(std::thread::spawn(move || { + let shown = followed(); + let mut left = false; + for sid in sids { + if shown.as_deref() == Some(sid.as_str()) { + record.leave(&sid); + left = true; + } else { + stop(&sid); + } + } + if left { + // A page that took the window since the question above found + // nothing left to stop yet. + for sid in record.take_left(followed().as_deref()) { + stop(&sid); + } + } + })); + }) +} + +/// Why a stop failed: it never ran (`node` could not be started), or it ran +/// and the console said no. +enum StopError { + NotRun(String), + Failed(String), +} + +impl StopError { + fn into_message(self) -> String { + match self { + StopError::NotRun(message) | StopError::Failed(message) => message, + } + } +} + +fn run_stop(console_dir: &Path, project_dir: &Path, sid: &str) -> Result<(), StopError> { + let output = node_command(console_dir) + .args(stop_args(sid)) + .current_dir(project_dir) + .output() + .map_err(|e| StopError::NotRun(err(e)))?; + if !output.status.success() { + return Err(StopError::Failed(format!( + "console stop failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + Ok(()) +} + /// Is the session's folder still in the console's home. Unknown (no home /// directory) counts as there, so the answer never throws a session away. A /// sid that is not a plain folder name (empty, `..`, a path) is never there. @@ -463,6 +679,222 @@ fn stop_args(sid: &str) -> [&str; 4] { mod tests { use super::*; + #[test] + fn announced_consoles_are_taken_once_in_order_without_duplicates() { + let announced = AnnouncedConsoles::default(); + announced.record("s1"); + announced.record("s2"); + announced.record("s1"); + assert_eq!(announced.take_all(), vec!["s1", "s2"]); + assert!(announced.take_all().is_empty(), "taking clears the record"); + } + + #[test] + fn forget_drops_one_console_and_keeps_the_rest() { + let announced = AnnouncedConsoles::default(); + announced.record("s1"); + announced.record("s2"); + announced.forget("s1"); + announced.forget("never-recorded"); + assert_eq!(announced.take_all(), vec!["s2"]); + } + + #[test] + fn an_agents_end_asks_which_console_the_window_follows_off_its_own_thread() { + // The hook runs with the agent manager locked, and the followed check + // takes the console lock, which is held across `node` runs: asked + // there, typing into the terminal stalled behind a console stop. + let announced = Arc::new(AnnouncedConsoles::default()); + let asked_on = Arc::new(Mutex::new(Vec::new())); + let log = Arc::clone(&asked_on); + let hook = stop_announced_on_end( + Arc::clone(&announced), + move || { + log.lock().unwrap().push(std::thread::current().id()); + None + }, + |_| {}, + ); + announced.record("s1"); + + hook(); + announced.finish_stops(); + + let asked_on = asked_on.lock().unwrap(); + assert_eq!(asked_on.len(), 1, "asked once"); + assert_ne!(asked_on[0], std::thread::current().id()); + } + + #[test] + fn an_agents_end_leaves_the_console_the_window_follows_and_keeps_it_recorded() { + // New Session ends the old agent while the window still shows its + // console: stopping it there only had the bar's poll bring it back as + // a server nobody tracked, which then outlived the quit. + let announced = Arc::new(AnnouncedConsoles::default()); + let stopped = Arc::new(Mutex::new(Vec::::new())); + let log = Arc::clone(&stopped); + let hook = stop_announced_on_end( + Arc::clone(&announced), + || Some("followed".to_string()), + move |sid| log.lock().unwrap().push(sid.to_string()), + ); + announced.record("followed"); + announced.record("other"); + + hook(); + announced.finish_stops(); + + assert_eq!(*stopped.lock().unwrap(), vec!["other"]); + assert_eq!( + announced.take_all(), + vec!["followed"], + "kept for the quit, or until the window moves on" + ); + } + + /// An agent that ended while the window showed its console `sid`. + fn left_under_the_window(sid: &'static str) -> Arc { + let announced = Arc::new(AnnouncedConsoles::default()); + announced.record(sid); + let hook = stop_announced_on_end( + Arc::clone(&announced), + move || Some(sid.to_string()), + |sid| panic!("{sid} was stopped under the window"), + ); + hook(); + announced.finish_stops(); + announced + } + + /// What `stop_left` stops once the window follows `followed`. + fn stopped_by_moving_to(announced: &AnnouncedConsoles, followed: &str) -> Vec { + let stopped = Arc::new(Mutex::new(Vec::::new())); + let log = Arc::clone(&stopped); + announced.stop_left(followed, move |sid| log.lock().unwrap().push(sid.into())); + announced.finish_stops(); + let stopped = stopped.lock().unwrap().clone(); + stopped + } + + #[test] + fn the_window_moving_on_stops_the_console_an_ended_agent_left_once() { + let announced = left_under_the_window("old"); + announced.record("new"); + assert!(stopped_by_moving_to(&announced, "old").is_empty(), "shown"); + assert_eq!(stopped_by_moving_to(&announced, "new"), vec!["old"]); + assert!(stopped_by_moving_to(&announced, "new").is_empty(), "once"); + assert_eq!(announced.take_all(), vec!["new"]); + } + + #[test] + fn the_window_moving_on_never_stops_a_running_agents_console() { + // One agent may open a second session and still use the first. + let announced = AnnouncedConsoles::default(); + announced.record("first"); + announced.record("second"); + assert!(stopped_by_moving_to(&announced, "second").is_empty()); + + // A new agent that joins the console an ended one left makes it its own. + let announced = left_under_the_window("joined"); + announced.record("joined"); + announced.record("second"); + assert!(stopped_by_moving_to(&announced, "second").is_empty()); + assert_eq!(announced.take_all(), vec!["joined", "second"]); + } + + /// An agent's end whose console `old` the window shows, where `meanwhile` + /// runs right after the hook asked which console that is: what it stopped. + fn stopped_by_an_end_while(meanwhile: M) -> (Vec, Vec) + where + M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static, + { + let announced = Arc::new(AnnouncedConsoles::default()); + let stopped = Arc::new(Mutex::new(Vec::::new())); + let (log, record) = (Arc::clone(&stopped), Arc::clone(&announced)); + let shown = Mutex::new("old"); + let hook = stop_announced_on_end( + Arc::clone(&announced), + move || { + let mut shown = shown.lock().unwrap(); + let answer = shown.to_string(); + if answer == "old" { + *shown = meanwhile(&record); + } + Some(answer) + }, + move |sid| log.lock().unwrap().push(sid.to_string()), + ); + announced.record("old"); + hook(); + announced.finish_stops(); + let stopped = stopped.lock().unwrap().clone(); + (stopped, announced.take_all()) + } + + #[test] + fn a_page_that_takes_the_window_while_an_agents_end_decides_still_stops_the_old_console() { + let (stopped, recorded) = stopped_by_an_end_while(|announced| { + announced.record("new"); + announced.stop_left("new", |sid| panic!("{sid} is not left yet")); + "new" + }); + assert_eq!(stopped, vec!["old"]); + assert_eq!(recorded, vec!["new"]); + } + + #[test] + fn a_new_agent_that_joins_the_console_while_an_agents_end_decides_keeps_it() { + let (stopped, recorded) = stopped_by_an_end_while(|announced| { + announced.record("old"); + announced.record("new"); + "new" + }); + assert!(stopped.is_empty(), "{stopped:?}"); + assert_eq!(recorded, vec!["old", "new"]); + } + + #[test] + fn finish_stops_waits_for_the_stop_a_new_page_started() { + // Quitting right after New Session: the exit must not cut it short. + let announced = left_under_the_window("old"); + let stopped = Arc::new(Mutex::new(Vec::::new())); + let log = Arc::clone(&stopped); + announced.stop_left("new", move |sid| { + std::thread::sleep(Duration::from_millis(300)); + log.lock().unwrap().push(sid.to_string()); + }); + assert!(stopped.lock().unwrap().is_empty(), "it runs on a thread"); + announced.finish_stops(); + assert_eq!(*stopped.lock().unwrap(), vec!["old"]); + } + + #[test] + fn finish_stops_waits_for_the_stops_an_agents_end_still_has_running() { + // Quitting right after an agent ended: the exit must not cut its + // consoles' stops short. + let announced = Arc::new(AnnouncedConsoles::default()); + let stopped = Arc::new(Mutex::new(Vec::::new())); + let log = Arc::clone(&stopped); + let hook = stop_announced_on_end( + Arc::clone(&announced), + || None, + move |sid| { + std::thread::sleep(Duration::from_millis(300)); + log.lock().unwrap().push(sid.to_string()); + }, + ); + announced.record("s1"); + + hook(); + assert!( + stopped.lock().unwrap().is_empty(), + "the stop runs on a thread" + ); + announced.finish_stops(); + + assert_eq!(*stopped.lock().unwrap(), vec!["s1"]); + } + #[test] fn the_apps_stop_calls_pass_force() { let args = stop_args("20261101-120000-abcdef"); diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index ace96fe..671f2d0 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -10,7 +10,11 @@ use plan2code_app_lib::agents::{self, Agent, PermissionMode}; use plan2code_app_lib::announce::{AnnounceServer, PageNotice}; use plan2code_app_lib::attention::{self, Badge, Signal}; use plan2code_app_lib::console_supervisor::{ - app_origin, origin_of, session_on_disk, ConsoleSupervisor, + app_origin, origin_of, session_on_disk, AnnouncedConsoles, ConsoleSupervisor, +}; +#[cfg(unix)] +use plan2code_app_lib::console_supervisor::{ + find_console_dir, stop_announced_on_end, stop_console_session, }; use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot}; use plan2code_app_lib::models; @@ -44,6 +48,11 @@ struct AppState { page: PageChannel, // This window's endpoint for pages the agent's `console.mjs open` wants shown here. announce: Arc>>, + // Every console session an agent announced and the window took, to stop + // when that agent ends or the app quits (macOS and Linux). On Windows the + // agent's Job Object ends them, so nothing there records or reads this. + #[cfg_attr(not(unix), allow(dead_code))] + announced: Arc, // The Node check's result: it runs on a background thread after the // window opens (Task 9.10), so this is unchecked until it reports. node: Mutex, @@ -318,16 +327,60 @@ fn agent_for_project(state: &AppState) -> Result, String> { let agent = Arc::new(AgentManager::new(dir, sink)); agent.set_before_fresh(before_fresh_hook(state)); agent.set_forget_session(forget_session_hook(state)); + // On Windows the agent's Job Object already ends every console it opened. + #[cfg(unix)] + { + let project_dir = agent.folder().clone(); + let console = Arc::clone(&state.console); + agent.set_ended(stop_announced_on_end( + Arc::clone(&state.announced), + move || followed_sid(&console), + move |sid| stop_announced_console(&project_dir, sid), + )); + } *guard = Some(Arc::clone(&agent)); Ok(agent) } +// The session the window's console supervisor follows, if any. +#[cfg(unix)] +fn followed_sid(console: &Mutex>) -> Option { + console + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .as_ref() + .map(|sup| sup.session().sid.clone()) +} + +// The project's folder, or the current one with none chosen. +#[cfg(unix)] +fn project_folder(state: &AppState) -> std::path::PathBuf { + state + .project + .lock() + .ok() + .and_then(|p| p.as_ref().map(|p| p.dir.clone())) + .unwrap_or_else(|| std::path::PathBuf::from(".")) +} + +// Stops one console an agent announced, from that agent's project folder; a +// failure is only logged, since nothing is left to tell. +#[cfg(unix)] +fn stop_announced_console(project_dir: &std::path::Path, sid: &str) { + let stopped = find_console_dir() + .and_then(|console_dir| stop_console_session(&console_dir, project_dir, sid)); + if let Err(error) = stopped { + eprintln!("plan2code: could not stop the console {sid}: {error}"); + } +} + // What New Session does before the fresh agent starts. It leaves the brief for // the dashboard, from the console session running now, then forgets that // session, so the fresh agent's `open` starts one of its own: a session that // joined the old one would carry its meter along, still red after the very -// press the red meter asks for. The old console is left to shut itself down -// once the frame moves on to the new page. +// press the red meter asks for. The old console is left running under the +// window until the new page takes over: on macOS and Linux the app stops it +// then (`take_announced`); elsewhere it shuts itself down once its page is gone. fn before_fresh_hook(state: &AppState) -> BeforeFresh { let console = Arc::clone(&state.console); let announce = Arc::clone(&state.announce); @@ -371,11 +424,13 @@ fn current_agent(state: &AppState) -> Option> { // page from a loopback dev server, so the window is asked for its real URL. /// A page the agent's `open` announced: the supervisor follows it, or adopts /// it when the agent started the console (the app owns its stop from there). -/// Says whether the window should show it. A session outside this app's -/// console store is refused: `cargo test` run by the agent inside the app -/// once announced a test's throwaway console, the window followed it, and -/// when the test shut it down the reconnect opened an empty dashboard, so the -/// build's own page was never seen again. +/// Says whether the window should show it. The console an ended agent left +/// under the window stops here, since the window has moved on from it (macOS +/// and Linux). A session outside this app's console store is refused: `cargo +/// test` run by the agent inside the app once announced a test's throwaway +/// console, the window followed it, and when the test shut it down the +/// reconnect opened an empty dashboard, so the build's own page was never seen +/// again. fn take_announced( state: &AppState, notice: &PageNotice, @@ -392,6 +447,10 @@ fn take_announced( if notice.workflow == "setup" { return false; } + // The agent opened it: it ends with that agent, or with the app (on + // Windows the agent's Job Object ends it). + #[cfg(unix)] + state.announced.record(¬ice.sid); if let Ok(mut guard) = state.console.lock() { match guard.as_mut() { Some(sup) => sup.follow(¬ice.url, ¬ice.sid), @@ -410,6 +469,13 @@ fn take_announced( } } } + #[cfg(unix)] + { + let project_dir = project_folder(state); + state.announced.stop_left(¬ice.sid, move |sid| { + stop_announced_console(&project_dir, sid) + }); + } true } @@ -737,22 +803,10 @@ fn agent_is_active(app: &tauri::AppHandle) -> bool { || current_agent(&state).is_some_and(|agent| agent.is_active()) } -// Stops the loop, the agent, then the console, then exits. The loop goes first: -// its record is dropped without a word to the page, so its watch thread never -// takes the ended agent for a crash. +// Stops everything this app's work left running, then exits. fn quit_app(app: &tauri::AppHandle) { let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take()); - let state = app.state::(); - loop_driver::abandon(&state.loop_run); - review_loop::abandon(&state.review_run); - if let Some(agent) = current_agent(&state) { - agent.stop(); - } - if let Ok(mut guard) = state.console.lock() { - if let Some(mut console) = guard.take() { - let _ = console.stop(); - } - } + shutdown(app); if let Some(plan) = restart { if let Err(error) = spawn_restart(&plan) { eprintln!("plan2code: restart failed: {error}"); @@ -761,6 +815,74 @@ fn quit_app(app: &tauri::AppHandle) { app.exit(0); } +// The one cleanup every quit runs: from `quit_app`, and on macOS and Linux +// from `RunEvent::Exit` too, for the routes that never pass through +// `quit_app`. A second call finds nothing left to stop. +fn shutdown(app: &tauri::AppHandle) { + let state = app.state::(); + shutdown_with(&state); + #[cfg(unix)] + { + let project_dir = project_folder(&state); + stop_other_announced(&state, |sid| stop_announced_console(&project_dir, sid)); + } +} + +// Stops the loops, the agent, then the console, each before returning: the app +// may exit straight after, and a stop left to a thread would lose that race. +// The loops go first: their records are dropped without a word to the page, so +// their watch threads never take the ended agent for a crash. +fn shutdown_with(state: &AppState) { + loop_driver::abandon(&state.loop_run); + review_loop::abandon(&state.review_run); + if let Some(agent) = current_agent(state) { + agent.stop(); + } + settle_agent_ends(state); + if let Ok(mut guard) = state.console.lock() { + if let Some(mut console) = guard.take() { + if let Err(error) = stop_supervised(state, &mut console) { + let sid = &console.session().sid; + eprintln!("plan2code: could not stop the console {sid}: {error}"); + } + } + } +} + +// macOS and Linux, after `shutdown_with`: stops every console an agent +// announced that is still recorded, each before returning. On Windows the +// agent's Job Object ends those consoles. +#[cfg(unix)] +fn stop_other_announced(state: &AppState, stop_sid: impl Fn(&str)) { + for sid in state.announced.take_all() { + stop_sid(&sid); + } +} + +// Waits for what an agent's end or a new page still has running on a thread +// (macOS and Linux): stopping consoles, and, after an end, deciding whether to +// keep the one the window follows recorded. Called before taking the console +// lock to stop that console, since the end's thread takes the lock too, and a +// decision made after the stop would record it again. +fn settle_agent_ends(state: &AppState) { + #[cfg(unix)] + state.announced.finish_stops(); + #[cfg(not(unix))] + let _ = state; +} + +// Stops the console the window follows and, on macOS and Linux, forgets it as +// an announced one, so no later agent's end or quit stops it again. Call +// `settle_agent_ends` before taking the console lock. +fn stop_supervised(state: &AppState, sup: &mut ConsoleSupervisor) -> Result<(), String> { + let stopped = sup.stop(); + #[cfg(unix)] + state.announced.forget(&sup.session().sid); + #[cfg(not(unix))] + let _ = state; + stopped +} + // The console page's state, told on every change (`attention` from the page): // the taskbar's dot for this system, and one flash on a change into the // person's move or needs attention while the window is not focused. An @@ -1140,9 +1262,10 @@ fn teardown_project(state: &AppState) -> Result<(), String> { agent.stop(); } *state.agent.lock().map_err(|e| e.to_string())? = None; + settle_agent_ends(state); if let Ok(mut guard) = state.console.lock() { if let Some(mut sup) = guard.take() { - let _ = sup.stop(); + let _ = stop_supervised(state, &mut sup); } } // The new project's agent asks the window which session is current and @@ -1310,8 +1433,13 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> { } /// Stop the console but keep its supervisor, so a start after a stop opens -/// the same session again instead of finding nothing to start. +/// the same session again instead of finding nothing to start. Unlike the +/// other stops, this one leaves an announced console recorded: the supervisor +/// keeps its session to start it again, and from then on it stops as any +/// announced console does, with its agent, once the window moves on from one +/// an ended agent left, or at the quit. fn console_stop_impl(state: &AppState) -> Result<(), String> { + settle_agent_ends(state); let mut guard = state.console.lock().map_err(|e| e.to_string())?; if let Some(sup) = guard.as_mut() { sup.stop()?; @@ -1348,9 +1476,10 @@ fn console_setup_start_impl(state: &AppState, origin: &str) -> Result) -> Result<(), String> { let agent = current_agent(&state); // The event goes out before the agent is ended (which can take a while), so @@ -1696,7 +1825,7 @@ fn review_loop_stop_after( // Stop now: the flag first, then the agent ends at once. Nothing more is // committed; the stop screen offers Keep or Discard for the partial changes. -#[tauri::command] +#[tauri::command(async)] fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { let agent = current_agent(&state); review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| { @@ -1882,9 +2011,10 @@ fn loop_dashboard(state: State<'_, AppState>) -> Result bool { // macOS gets a real menu bar: Plan2Code (About, Check for Updates, Help, Quit) and the standard Edit // menu, so Copy, Paste and Select All work in the page's fields. The three custom items tell the -// page (the same actions as the bar's "..." menu); Quit is the predefined one, and the exit it asks -// for goes through the quit check in the run loop below. +// page (the same actions as the bar's "..." menu). Quit is the app's own item, id `quit` on Cmd+Q, +// not the predefined one: that sends `terminate:`, which never raises `ExitRequested`, so it would +// quit with no prompt while an agent works. #[cfg(target_os = "macos")] fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> { use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder}; let about = MenuItemBuilder::with_id("about", "About Plan2Code").build(app)?; let check = MenuItemBuilder::with_id("check-updates", "Check for Updates...").build(app)?; let help = MenuItemBuilder::with_id("help", "Plan2Code Help").build(app)?; + let quit = MenuItemBuilder::with_id("quit", "Quit Plan2Code") + .accelerator("CmdOrCtrl+Q") + .build(app)?; let app_menu = SubmenuBuilder::new(app, "Plan2Code") .item(&about) .item(&check) .separator() .item(&help) .separator() - .quit() + .item(&quit) .build()?; let edit = SubmenuBuilder::new(app, "Edit") .undo() @@ -1934,6 +2068,8 @@ fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> { let id = event.id().as_ref(); if matches!(id, "about" | "check-updates" | "help") { let _ = app.emit("app-menu", id); + } else if id == "quit" { + request_quit(app.clone()); } }); Ok(()) @@ -2089,8 +2225,18 @@ fn main() { .build(tauri::generate_context!()) .expect("error while building the Plan2Code app") .run(|app, event| { - // Cmd+Q and the app menu's Quit on macOS end the app without closing the - // window first. An exit asked for in code (`code` is set) is `quit_app`'s own. + // The app is going, by whatever route: clean up here too. On macOS, + // Dock Quit sends `terminate:`, which raises only this and never asks + // first, and a quit with no agent active still stops the console this + // way. After `quit_app` this finds nothing left. + #[cfg(unix)] + if let tauri::RunEvent::Exit = event { + shutdown(app); + } + // An exit nobody asked for in code (`code: None`) asks first while an + // agent works; one with `code` set is `quit_app`'s own. On macOS, + // Cmd+Q and the app menu's Quit go through the app's own Quit item + // (`build_mac_menu`), and Dock Quit never reaches here. if let tauri::RunEvent::ExitRequested { api, code: None, .. } = event @@ -2186,6 +2332,171 @@ mod tests { let_go(&state); } + // Windows' Job Object ends an agent's consoles with it: nothing is recorded there. + #[cfg(unix)] + #[test] + fn only_an_accepted_announce_is_recorded_for_the_agents_end() { + let state = state_for("project-a"); + // Refused: outside the console store. + assert!(!take_announced( + &state, + ¬ice("outside"), + app_origin().to_string(), + |_| false + )); + // Refused: an announced setup page. + let mut setup = notice("setup-console"); + setup.workflow = "setup".into(); + assert!(!take_announced( + &state, + &setup, + app_origin().to_string(), + |_| true + )); + assert!( + state.announced.take_all().is_empty(), + "nothing refused is recorded" + ); + + // Accepted while following a console, then while following none. + *state.console.lock().unwrap() = Some(following_the_build()); + assert!(take_announced( + &state, + ¬ice("followed"), + app_origin().to_string(), + |_| true + )); + let_go(&state); + assert!(take_announced( + &state, + ¬ice("adopted"), + app_origin().to_string(), + |_| true + )); + let_go(&state); + assert_eq!(state.announced.take_all(), vec!["followed", "adopted"]); + } + + #[cfg(unix)] + #[test] + fn shutdown_stops_every_announced_console_once_and_is_safe_twice() { + let state = state_for("project-a"); + state.announced.record("s1"); + state.announced.record("s2"); + let stopped = Mutex::new(Vec::::new()); + let stop = |sid: &str| stopped.lock().unwrap().push(sid.to_string()); + + shutdown_with(&state); + stop_other_announced(&state, stop); + assert_eq!( + *stopped.lock().unwrap(), + vec!["s1", "s2"], + "both, before returning" + ); + + shutdown_with(&state); + stop_other_announced(&state, stop); + assert_eq!( + stopped.lock().unwrap().len(), + 2, + "a second shutdown stops nothing" + ); + } + + #[cfg(unix)] + #[test] + fn shutdown_never_stops_the_followed_console_a_second_time() { + // The window follows the build's console, which the agent announced: + // the supervisor stops it, so the announced list must skip it. + let state = state_for("project-a"); + *state.console.lock().unwrap() = Some(following_the_build()); + state.announced.record("build"); + state.announced.record("other"); + let stopped = Mutex::new(Vec::::new()); + + shutdown_with(&state); + stop_other_announced(&state, |sid| stopped.lock().unwrap().push(sid.to_string())); + + assert_eq!(*stopped.lock().unwrap(), vec!["other"]); + assert!( + state.console.lock().unwrap().is_none(), + "the supervisor was taken" + ); + } + + #[cfg(unix)] + #[test] + fn shutdown_waits_for_the_stops_an_agents_end_left_running() { + // The agent ended a moment before the quit: its hook is still + // stopping that agent's consoles on a thread the exit would cut short. + let state = state_for("project-a"); + let stopped = Arc::new(Mutex::new(Vec::::new())); + let log = Arc::clone(&stopped); + let ended = stop_announced_on_end( + Arc::clone(&state.announced), + || None, + move |sid| { + std::thread::sleep(std::time::Duration::from_millis(300)); + log.lock().unwrap().push(sid.to_string()); + }, + ); + state.announced.record("s1"); + ended(); + + shutdown_with(&state); + + assert_eq!( + *stopped.lock().unwrap(), + vec!["s1"], + "done before returning" + ); + } + + #[cfg(unix)] + #[test] + fn a_new_page_stops_the_console_an_ended_agent_left_under_the_window() { + // New Session: the old agent's console stayed up with no page in it, + // until the next agent's end, the quit or its own idle limit. + let state = state_for("project-a"); + *state.console.lock().unwrap() = Some(following_the_build()); + state.announced.record("build"); + let console = Arc::clone(&state.console); + let ended = stop_announced_on_end( + Arc::clone(&state.announced), + move || followed_sid(&console), + |_| {}, + ); + ended(); + state.announced.finish_stops(); + + assert!(take_announced( + &state, + ¬ice("next"), + app_origin().to_string(), + |_| true + )); + state.announced.finish_stops(); + + assert_eq!(state.announced.take_all(), vec!["next"]); + let_go(&state); + } + + #[cfg(unix)] + #[test] + fn a_console_the_app_stopped_is_forgotten_so_no_later_end_stops_it_again() { + // A project switch stops the console the window follows, which its + // agent announced: still recorded, the next project's agent's end and + // the quit each ran `console.mjs stop` on it again. + let state = state_for("project-a"); + *state.console.lock().unwrap() = Some(following_the_build()); + state.announced.record("build"); + state.announced.record("other"); + + teardown_project(&state).unwrap(); + + assert_eq!(state.announced.take_all(), vec!["other"]); + } + #[test] fn a_page_from_the_console_store_is_followed() { let state = state_for("project-a"); @@ -2534,6 +2845,50 @@ mod tests { let _ = state.console.lock().unwrap().take().unwrap().stop(); } + #[cfg(unix)] + #[test] + fn a_console_the_bar_stopped_and_started_again_still_stops_at_the_quit() { + // The bar's Reconnect (or a skills update) stops the console its + // agent announced and starts it again on the same session. When the + // window then follows the next agent's page, the quit must still stop + // that console: once forgotten at the stop, it outlived the app. + let Some((_env, sup)) = real_console() else { + return; + }; + let state = state_for("project-a"); + let sid = sup.session().sid.clone(); + *state.console.lock().unwrap() = Some(sup); + state.announced.record(&sid); + + console_stop_impl(&state).unwrap(); + console_start_impl(&state).expect("a start after a stop works"); + assert!(take_announced( + &state, + ¬ice("next"), + app_origin().to_string(), + |_| true + )); + let stopped_at_quit = Mutex::new(Vec::new()); + stop_other_announced(&state, |sid| { + stopped_at_quit.lock().unwrap().push(sid.to_string()) + }); + + // Stop the real console before asserting, so a failure leaves nothing running. + let console_dir = PathBuf::from(std::env::var("PLAN2CODE_CONSOLE_DIR").unwrap()); + let project = + std::env::temp_dir().join(format!("p2c-main-test-project-{}", std::process::id())); + let _ = plan2code_app_lib::console_supervisor::stop_console_session( + &console_dir, + &project, + &sid, + ); + assert!( + stopped_at_quit.lock().unwrap().contains(&sid), + "the quit stops the console the bar started again: {:?}", + stopped_at_quit.lock().unwrap() + ); + } + #[test] fn a_slow_health_check_never_holds_the_console_lock() { // A server that takes the connection and never answers: the check diff --git a/plan2code-app/src-tauri/src/pty_host.rs b/plan2code-app/src-tauri/src/pty_host.rs index e3a3555..4d881a9 100644 --- a/plan2code-app/src-tauri/src/pty_host.rs +++ b/plan2code-app/src-tauri/src/pty_host.rs @@ -19,7 +19,7 @@ pub const BATCH_INTERVAL: Duration = Duration::from_millis(16); /// On macOS and Linux the kill is a hang-up signal, which a program can ignore. /// This long after it, a command that is still running is killed outright. #[cfg(unix)] -const HANGUP_GRACE: Duration = Duration::from_secs(2); +pub const HANGUP_GRACE: Duration = Duration::from_secs(2); /// What to run, where, and how big the terminal starts. pub struct StartOptions { @@ -43,6 +43,11 @@ pub struct PtyHost { /// a process id that may have been given to something else. #[cfg(unix)] exited: Arc, + /// Set once `end_group` has seen the process group empty (or killed what + /// was left of it), so `kill`'s late group kill never signals a group id + /// that may since have been given to something else. + #[cfg(unix)] + group_done: Arc, /// A Windows Job Object the spawned process was assigned to, so ending /// it (`kill`, or this host simply being dropped) ends every process /// still in it, not just the one directly spawned: a `cmd /c` npm shim's @@ -150,6 +155,8 @@ impl PtyHost { pid, #[cfg(unix)] exited: Arc::new(AtomicBool::new(false)), + #[cfg(unix)] + group_done: Arc::new(AtomicBool::new(false)), #[cfg(windows)] job, }) @@ -171,7 +178,9 @@ impl PtyHost { .map_err(err) } - /// End the command. Safe to call while `wait` is blocked in another thread. + /// End the command and everything it started that is still in its process + /// group (on Windows, its Job Object). Safe to call while `wait` is + /// blocked in another thread. pub fn kill(&self) -> Result<(), String> { let result = self.killer.lock().map_err(err)?.kill().map_err(err); // The job object, when there is one, ends the whole process tree: @@ -187,22 +196,60 @@ impl PtyHost { if cfg!(windows) { return Ok(()); } - // portable-pty only sends SIGHUP on macOS and Linux; follow it with - // SIGKILL if the command is still there after the grace period. + // portable-pty only sends SIGHUP on macOS and Linux, and only to the + // command itself. It starts the command under `setsid`, so the + // command's pid is also its process group's id: hang up the whole + // group too, then, after the grace period, kill whatever of the group + // is still there. A process that left the group (`setsid`, a detached + // child) is out of reach here. #[cfg(unix)] if let Some(pid) = self.pid { + // SAFETY: plain signal to the command's own process group. + unsafe { libc::kill(-(pid as i32), libc::SIGHUP) }; let exited = Arc::clone(&self.exited); + let group_done = Arc::clone(&self.group_done); thread::spawn(move || { thread::sleep(HANGUP_GRACE); if !exited.load(Ordering::SeqCst) { // SAFETY: plain signal to a process id the command still holds. unsafe { libc::kill(pid as i32, libc::SIGKILL) }; } + // The group outlives its leader while any member is left; signal 0 + // only asks whether one is. Once `end_group` saw it gone, its id + // may belong to another group by now: leave it alone. + // SAFETY: plain signals to the command's own process group. + if !group_done.load(Ordering::SeqCst) + && unsafe { libc::kill(-(pid as i32), 0) } == 0 + { + unsafe { libc::kill(-(pid as i32), libc::SIGKILL) }; + } }); } result } + /// For after `kill` and `wait` when the app is about to exit: `kill`'s + /// grace thread dies with the app, so this blocks until nothing of the + /// command's process group is left, killing what is still there after + /// `HANGUP_GRACE`. A no-op on Windows, where `kill` ended the Job Object. + pub fn end_group(&self) { + #[cfg(unix)] + if let Some(pid) = self.pid { + let group = -(pid as i32); + let deadline = Instant::now() + HANGUP_GRACE; + // SAFETY: signal 0 only asks whether the group still has members. + while unsafe { libc::kill(group, 0) } == 0 { + if Instant::now() >= deadline { + // SAFETY: plain signal to the command's own process group. + unsafe { libc::kill(group, libc::SIGKILL) }; + break; + } + thread::sleep(Duration::from_millis(20)); + } + self.group_done.store(true, Ordering::SeqCst); + } + } + /// Block until the command ends and return its exit code. A command ended by /// a signal reports 1. pub fn wait(&self) -> Result { diff --git a/plan2code-app/src-tauri/tests/agent_manager.rs b/plan2code-app/src-tauri/tests/agent_manager.rs index 5d2de6b..b1d4b79 100644 --- a/plan2code-app/src-tauri/tests/agent_manager.rs +++ b/plan2code-app/src-tauri/tests/agent_manager.rs @@ -521,6 +521,197 @@ fn a_phase_start_runs_on_its_model_and_env_and_leaves_the_launch_choice_alone() h.manager.stop(); } +/// Counts the manager's `ended` calls. +fn count_ends(h: &Harness) -> Arc> { + let ends = Arc::new(Mutex::new(0)); + let counter = Arc::clone(&ends); + h.manager.set_ended(Arc::new(move || { + *counter.lock().unwrap() += 1; + })); + ends +} + +/// Wait (briefly) for `ends` to reach `want`, then make sure it stays there. +fn expect_ends(h: &mut Harness, ends: &Arc>, want: usize, what: &str) { + let deadline = Instant::now() + Duration::from_secs(5); + while *ends.lock().unwrap() < want && Instant::now() < deadline { + h.pump_for(Duration::from_millis(50)); + } + // A late exit of an agent already counted must not count again. + h.pump_for(Duration::from_millis(500)); + assert_eq!(*ends.lock().unwrap(), want, "{what}"); +} + +#[test] +fn ended_runs_once_for_an_agent_that_exits_by_itself() { + let mut h = Harness::new(); + let ends = count_ends(&h); + h.start_and_wait_ready(); + h.type_line("EXIT 7"); + h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. })); + expect_ends(&mut h, &ends, 1, "one natural end"); + // Nothing is running now: a stop ends nothing more. + h.manager.stop(); + expect_ends(&mut h, &ends, 1, "a stop with no running agent"); +} + +#[test] +fn ended_runs_once_for_a_stopped_agent_and_never_for_a_stop_of_none() { + let mut h = Harness::new(); + let ends = count_ends(&h); + h.manager.stop(); + expect_ends(&mut h, &ends, 0, "a stop before any start"); + h.start_and_wait_ready(); + h.manager.stop(); + expect_ends(&mut h, &ends, 1, "one stop of a running agent"); +} + +#[test] +fn ended_runs_once_for_the_old_agent_on_restart_and_on_a_fresh_start() { + let mut h = Harness::new(); + let ends = count_ends(&h); + h.start_and_wait_ready(); + h.manager.restart().unwrap(); + h.wait_for_output(READY, 2); + expect_ends(&mut h, &ends, 1, "the restarted agent's old one"); + h.manager + .start_fresh("/plan2code next".to_string()) + .unwrap(); + h.wait_for_output(READY, 3); + expect_ends(&mut h, &ends, 2, "the old agent a fresh start replaced"); + h.manager.stop(); + expect_ends(&mut h, &ends, 3, "the last agent, stopped"); +} + +#[test] +fn an_ended_agent_takes_the_consoles_it_announced_and_only_those() { + use plan2code_app_lib::console_supervisor::{stop_announced_on_end, AnnouncedConsoles}; + + let mut h = Harness::new(); + let announced = Arc::new(AnnouncedConsoles::default()); + let stopped = Arc::new(Mutex::new(Vec::::new())); + let log = Arc::clone(&stopped); + h.manager.set_ended(stop_announced_on_end( + Arc::clone(&announced), + || None, + move |sid| { + log.lock().unwrap().push(sid.to_string()); + }, + )); + h.start_and_wait_ready(); + announced.record("s1"); + h.manager.stop(); + + let deadline = Instant::now() + Duration::from_secs(5); + while stopped.lock().unwrap().is_empty() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + // Recorded after the end: it belongs to whatever comes next. + announced.record("s2"); + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(*stopped.lock().unwrap(), vec!["s1"]); + assert_eq!(announced.take_all(), vec!["s2"], "s2 was never taken"); +} + +/// Starts the harness's agent, has it leave a child that ignores the +/// terminal's hangup in its process group, and returns that child's pid. +#[cfg(unix)] +fn start_with_stray(h: &mut Harness) -> u32 { + h.start_and_wait_ready(); + h.type_line("STRAY"); + h.wait_for_output("STRAY ", 1); + let stray: u32 = h + .seen + .rsplit("STRAY ") + .next() + .unwrap() + .split(|c: char| !c.is_ascii_digit()) + .next() + .unwrap() + .parse() + .expect("the stray child's pid"); + assert!(process_alive(stray), "the stray child should be running"); + stray +} + +/// Waits out the hangup grace for `stray` to go, then kills it if it is +/// still there, so a failing test leaves nothing running. True if it went. +#[cfg(unix)] +fn stray_gone(stray: u32) -> bool { + use plan2code_app_lib::pty_host::HANGUP_GRACE; + + let deadline = Instant::now() + HANGUP_GRACE + Duration::from_secs(2); + while process_alive(stray) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + let gone = !process_alive(stray); + if !gone { + let _ = std::process::Command::new("kill") + .args(["-9", &stray.to_string()]) + .status(); + } + gone +} + +/// An agent that ends by itself leaves its process group alone: work the +/// person asked it to leave running (a dev server it backgrounded) stays up, +/// as it did before the app ended process groups at all. +#[cfg(unix)] +#[test] +fn an_agent_that_exits_by_itself_leaves_its_process_group_running() { + let mut h = Harness::new(); + let stray = start_with_stray(&mut h); + h.type_line("EXIT 0"); + h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. })); + assert!( + !stray_gone(stray), + "the stray child was ended with an agent that exited by itself" + ); +} + +/// An agent the app stops (quit, a project switch) takes its process group +/// with it, a child that ignores the terminal's hangup included. +#[cfg(unix)] +#[test] +fn a_stopped_agent_takes_its_process_group_with_it() { + let mut h = Harness::new(); + let stray = start_with_stray(&mut h); + h.manager.stop(); + assert!( + stray_gone(stray), + "the stray child outlived its stopped agent" + ); +} + +/// A Restart or New Session replaces the agent, and its process group goes +/// with the old one. +#[cfg(unix)] +#[test] +fn a_replaced_agent_takes_its_process_group_with_it() { + let mut h = Harness::new(); + let stray = start_with_stray(&mut h); + h.manager.restart().unwrap(); + assert!( + stray_gone(stray), + "the stray child outlived its replaced agent" + ); + h.manager.stop(); +} + +/// Quitting right after New Session: the replaced agent's grace is still +/// running on a thread that would end with the app. +#[cfg(unix)] +#[test] +fn a_stop_right_after_a_restart_waits_for_the_replaced_agents_process_group() { + let mut h = Harness::new(); + let stray = start_with_stray(&mut h); + h.manager.restart().expect("restart"); + h.manager.stop(); + let left = process_alive(stray); + assert!(stray_gone(stray), "the stray child outlived its grace"); + assert!(!left, "the stray child was still there when stop returned"); +} + #[test] fn a_phase_start_with_no_launch_choice_is_refused() { let h = Harness::new(); diff --git a/plan2code-app/src-tauri/tests/console_supervisor.rs b/plan2code-app/src-tauri/tests/console_supervisor.rs index 8293547..fab18fa 100644 --- a/plan2code-app/src-tauri/tests/console_supervisor.rs +++ b/plan2code-app/src-tauri/tests/console_supervisor.rs @@ -7,7 +7,7 @@ use std::path::PathBuf; use std::process::Command; use std::time::{Duration, Instant}; -use plan2code_app_lib::console_supervisor::{app_origin, ConsoleSupervisor}; +use plan2code_app_lib::console_supervisor::{app_origin, stop_console_session, ConsoleSupervisor}; fn have_node() -> bool { Command::new("node") @@ -120,6 +120,38 @@ fn a_killed_console_is_dead_and_restarts() { sup.stop().expect("stop"); } +#[test] +fn stopping_a_session_by_id_never_panics() { + let Some(project) = setup() else { return }; + // The console has nothing to stop for a session it does not know: that is + // not a failure. + assert_eq!( + stop_console_session(&repo_console_dir(), &project, "no-such-session"), + Ok(()) + ); + // A folder with no console in it is. + let empty = temp_dir("no-console"); + let error = stop_console_session(&empty, &project, "no-such-session") + .expect_err("no console.mjs to run"); + assert!(error.starts_with("console stop failed"), "{error}"); +} + +#[test] +fn a_session_stopped_by_id_stops_answering() { + let Some(project) = setup() else { return }; + let mut sup = + ConsoleSupervisor::start(project.clone(), app_origin().to_string()).expect("start"); + assert!(until_health(&sup, true), "the console URL never answered"); + let sid = sup.session().sid.clone(); + + stop_console_session(&repo_console_dir(), &project, &sid).expect("stop by id"); + assert!( + until_health(&sup, false), + "the console still answered after stop_console_session()" + ); + sup.stop().expect("a second stop is harmless"); +} + #[test] fn a_live_console_is_not_restarted() { let Some(project) = setup() else { return }; diff --git a/plan2code-app/src-tauri/tests/pty_host.rs b/plan2code-app/src-tauri/tests/pty_host.rs index c745945..1b40cf9 100644 --- a/plan2code-app/src-tauri/tests/pty_host.rs +++ b/plan2code-app/src-tauri/tests/pty_host.rs @@ -103,6 +103,102 @@ fn kill_ends_a_running_step() { ); } +/// A grandchild that ignores hangup is still in the agent's process group +/// (portable-pty starts the agent under `setsid`), so `kill` must reach it +/// through the group once the grace is up. An ordinary grandchild already dies +/// with its shell, when the kernel hangs up the terminal, so it cannot show this. +#[cfg(unix)] +#[test] +fn kill_ends_a_hangup_ignoring_grandchild_after_the_grace() { + use plan2code_app_lib::pty_host::HANGUP_GRACE; + + let (host, pid) = + start_sh_with_grandchild("trap '' HUP; sleep 300 & echo GRANDCHILD=$! END; wait"); + assert!(alive(pid), "the grandchild should be running before kill"); + + host.kill().unwrap(); + host.wait().unwrap(); + assert!( + gone_within(pid, HANGUP_GRACE + Duration::from_secs(2)), + "the hangup-ignoring grandchild outlived kill()" + ); +} + +/// An agent that ended by itself was never killed, so no grace thread of +/// `kill`'s is there to finish its group: only `end_group` can end the +/// grandchild that ignored the terminal's hangup. +#[cfg(unix)] +#[test] +fn end_group_ends_what_a_command_that_exited_by_itself_left() { + let (host, pid) = start_sh_with_grandchild( + "(trap '' HUP; exec sleep 300) & echo GRANDCHILD=$! END; sleep 0.2; exit 0", + ); + host.wait().unwrap(); + assert!(alive(pid), "the grandchild outlived its shell, as set up"); + + host.end_group(); + // Only the moment it takes the reaper to collect it. + assert!( + gone_within(pid, Duration::from_secs(1)), + "the grandchild outlived end_group()" + ); +} + +/// `script` under `/bin/sh -c` on a pty; it must print `GRANDCHILD= END`. +/// Returns the host and that pid. +#[cfg(unix)] +fn start_sh_with_grandchild(script: &str) -> (PtyHost, i32) { + let (tx, rx) = channel(); + let host = PtyHost::start( + StartOptions { + program: "/bin/sh".to_string(), + args: vec!["-c".to_string(), script.to_string()], + env: vec![], + cwd: None, + cols: 80, + rows: 24, + }, + move |bytes| { + let _ = tx.send(bytes); + }, + ) + .expect("start the shell"); + let mut seen = String::new(); + wait_for(&host, &rx, &mut seen, " END"); + let pid = seen + .rsplit("GRANDCHILD=") + .next() + .unwrap() + .split(|c: char| !c.is_ascii_digit()) + .next() + .unwrap() + .parse() + .expect("the grandchild's pid"); + (host, pid) +} + +#[cfg(unix)] +fn alive(pid: i32) -> bool { + // SAFETY: signal 0 only asks whether the process exists. + unsafe { libc::kill(pid, 0) == 0 } +} + +/// Whether `pid` is gone within `within`; killed on the way out either way, +/// so a failing test leaves nothing behind. +#[cfg(unix)] +fn gone_within(pid: i32, within: Duration) -> bool { + let deadline = Instant::now() + within; + while alive(pid) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + let gone = !alive(pid); + if !gone { + // SAFETY: a process this test started. + unsafe { libc::kill(pid, libc::SIGKILL) }; + } + gone +} + /// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real /// program (here, the fake agent) its grandchild. `kill` must end both, not /// just `cmd.exe` (Task 9.8).