End the agent's process group and the consoles it opened on every quit

AI Assisted
This commit is contained in:
Seth committed 2026-12-05 00:10:44 -08:00
1 parent 98bdbc97c3
commit 6a93395148
8 files changed
+1363 -58

No files matched your search

+444 -12
View File
@@ -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 <sid> --force` for any session, run in the
/// project folder: the same stop `ConsoleSupervisor::stop` runs, for a console
/// this app does not supervise (one an agent announced and the window has
/// since moved on from).
pub fn stop_console_session(
console_dir: &Path,
project_dir: &Path,
sid: &str,
) -> Result<(), String> {
run_stop(console_dir, project_dir, sid).map_err(StopError::into_message)
}
/// One console an agent announced. `left` once that agent has ended while the
/// window still showed the console: nothing needs it after the window moves on.
struct Announced {
sid: String,
left: bool,
}
/// The console sessions this app's agents announced on macOS and Linux, by
/// sid, in the order they came: the ones to stop when the agent that opened
/// them ends, when the window moves on from one an ended agent left, or when
/// the app quits. Consoles the app started itself are never recorded here, and
/// one the app stopped for good is forgotten; the bar's stop, which keeps the
/// session to start it again, leaves it recorded. Also holds the threads still
/// stopping consoles after an agent's end or a new page, so a quit can wait for
/// them.
#[derive(Default)]
pub struct AnnouncedConsoles {
consoles: Mutex<Vec<Announced>>,
stops: Mutex<Vec<std::thread::JoinHandle<()>>>,
}
impl AnnouncedConsoles {
fn lock(&self) -> MutexGuard<'_, Vec<Announced>> {
self.consoles
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// Remember `sid`, announced by a running agent; one already recorded is
/// kept once, and is no longer left: the new agent joined it.
pub fn record(&self, sid: &str) {
let mut consoles = self.lock();
match consoles.iter_mut().find(|known| known.sid == sid) {
Some(known) => known.left = false,
None => consoles.push(Announced {
sid: sid.to_string(),
left: false,
}),
}
}
/// Remember `sid` as left by an agent that has ended; one a new agent
/// announced in the meantime stays that agent's.
fn leave(&self, sid: &str) {
let mut consoles = self.lock();
if !consoles.iter().any(|known| known.sid == sid) {
consoles.push(Announced {
sid: sid.to_string(),
left: true,
});
}
}
/// Drop `sid` from the record: the app stopped that console itself.
pub fn forget(&self, sid: &str) {
self.lock().retain(|known| known.sid != sid);
}
/// Every recorded sid, in record order, and an empty record after.
pub fn take_all(&self) -> Vec<String> {
std::mem::take(&mut *self.lock())
.into_iter()
.map(|known| known.sid)
.collect()
}
/// Every console left by an agent that has ended, but for the one the
/// window follows, no longer recorded after.
fn take_left(&self, followed: Option<&str>) -> Vec<String> {
let mut consoles = self.lock();
let (left, kept) = std::mem::take(&mut *consoles)
.into_iter()
.partition(|known| known.left && followed != Some(known.sid.as_str()));
*consoles = kept;
left.into_iter().map(|known| known.sid).collect()
}
/// The window follows `followed` now: stop each console an agent that has
/// ended left under it, with `stop` on a thread of its own, since a stop
/// runs `node`. A console of an agent still running is never touched.
pub fn stop_left<F>(&self, followed: &str, stop: F)
where
F: Fn(&str) + Send + 'static,
{
let sids = self.take_left(Some(followed));
if sids.is_empty() {
return;
}
self.keep_stop(std::thread::spawn(move || {
for sid in sids {
stop(&sid);
}
}));
}
/// Keep a thread that is stopping consoles, so `finish_stops` can wait
/// for it; threads already done are let go.
fn keep_stop(&self, stop: std::thread::JoinHandle<()>) {
let mut stops = self
.stops
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
stops.retain(|kept| !kept.is_finished());
stops.push(stop);
}
/// Wait for every console stop still running on a thread, after an agent's
/// end or a new page: the app may exit straight after, which would cut it
/// short.
pub fn finish_stops(&self) {
let stops = std::mem::take(
&mut *self
.stops
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()),
);
for stop in stops {
let _ = stop.join();
}
}
}
/// The hook an agent manager runs when an agent ends (`AgentManager::set_ended`):
/// it takes every console `announced` holds at once, inside the hook, so a
/// console the next agent announces later is never taken by mistake, then
/// stops each with `stop` on a thread of its own, since a stop runs `node` and
/// the hook must return quickly. The console the window follows (`followed`)
/// is left to the supervisor and recorded again, as left: stopped under the
/// window, the bar's health poll would only start it again as a server no one
/// tracks. It is stopped once the window moves on (`stop_left`), here if that
/// happened while this thread was deciding, or at the quit. `followed` is asked
/// on that thread too: it takes the console lock, held across `node` runs,
/// while the hook runs with the agent manager locked. A caller about to stop
/// the followed console waits for the thread first (`finish_stops`), so it is
/// never recorded again after that stop.
/// The macOS and Linux stand-in for Windows' Job Object, which ends every
/// console an agent opened along with it.
pub fn stop_announced_on_end<K, F>(
announced: Arc<AnnouncedConsoles>,
followed: K,
stop: F,
) -> Arc<dyn Fn() + Send + Sync>
where
K: Fn() -> Option<String> + Send + Sync + 'static,
F: Fn(&str) + Send + Sync + 'static,
{
let followed = Arc::new(followed);
let stop = Arc::new(stop);
Arc::new(move || {
let sids = announced.take_all();
if sids.is_empty() {
return;
}
let (followed, stop, record) = (
Arc::clone(&followed),
Arc::clone(&stop),
Arc::clone(&announced),
);
announced.keep_stop(std::thread::spawn(move || {
let shown = followed();
let mut left = false;
for sid in sids {
if shown.as_deref() == Some(sid.as_str()) {
record.leave(&sid);
left = true;
} else {
stop(&sid);
}
}
if left {
// A page that took the window since the question above found
// nothing left to stop yet.
for sid in record.take_left(followed().as_deref()) {
stop(&sid);
}
}
}));
})
}
/// Why a stop failed: it never ran (`node` could not be started), or it ran
/// and the console said no.
enum StopError {
NotRun(String),
Failed(String),
}
impl StopError {
fn into_message(self) -> String {
match self {
StopError::NotRun(message) | StopError::Failed(message) => message,
}
}
}
fn run_stop(console_dir: &Path, project_dir: &Path, sid: &str) -> Result<(), StopError> {
let output = node_command(console_dir)
.args(stop_args(sid))
.current_dir(project_dir)
.output()
.map_err(|e| StopError::NotRun(err(e)))?;
if !output.status.success() {
return Err(StopError::Failed(format!(
"console stop failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
)));
}
Ok(())
}
/// Is the session's folder still in the console's home. Unknown (no home
/// directory) counts as there, so the answer never throws a session away. A
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
@@ -463,6 +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::<String>::new()));
let log = Arc::clone(&stopped);
let hook = stop_announced_on_end(
Arc::clone(&announced),
|| Some("followed".to_string()),
move |sid| log.lock().unwrap().push(sid.to_string()),
);
announced.record("followed");
announced.record("other");
hook();
announced.finish_stops();
assert_eq!(*stopped.lock().unwrap(), vec!["other"]);
assert_eq!(
announced.take_all(),
vec!["followed"],
"kept for the quit, or until the window moves on"
);
}
/// An agent that ended while the window showed its console `sid`.
fn left_under_the_window(sid: &'static str) -> Arc<AnnouncedConsoles> {
let announced = Arc::new(AnnouncedConsoles::default());
announced.record(sid);
let hook = stop_announced_on_end(
Arc::clone(&announced),
move || Some(sid.to_string()),
|sid| panic!("{sid} was stopped under the window"),
);
hook();
announced.finish_stops();
announced
}
/// What `stop_left` stops once the window follows `followed`.
fn stopped_by_moving_to(announced: &AnnouncedConsoles, followed: &str) -> Vec<String> {
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
announced.stop_left(followed, move |sid| log.lock().unwrap().push(sid.into()));
announced.finish_stops();
let stopped = stopped.lock().unwrap().clone();
stopped
}
#[test]
fn the_window_moving_on_stops_the_console_an_ended_agent_left_once() {
let announced = left_under_the_window("old");
announced.record("new");
assert!(stopped_by_moving_to(&announced, "old").is_empty(), "shown");
assert_eq!(stopped_by_moving_to(&announced, "new"), vec!["old"]);
assert!(stopped_by_moving_to(&announced, "new").is_empty(), "once");
assert_eq!(announced.take_all(), vec!["new"]);
}
#[test]
fn the_window_moving_on_never_stops_a_running_agents_console() {
// One agent may open a second session and still use the first.
let announced = AnnouncedConsoles::default();
announced.record("first");
announced.record("second");
assert!(stopped_by_moving_to(&announced, "second").is_empty());
// A new agent that joins the console an ended one left makes it its own.
let announced = left_under_the_window("joined");
announced.record("joined");
announced.record("second");
assert!(stopped_by_moving_to(&announced, "second").is_empty());
assert_eq!(announced.take_all(), vec!["joined", "second"]);
}
/// An agent's end whose console `old` the window shows, where `meanwhile`
/// runs right after the hook asked which console that is: what it stopped.
fn stopped_by_an_end_while<M>(meanwhile: M) -> (Vec<String>, Vec<String>)
where
M: Fn(&AnnouncedConsoles) -> &'static str + Send + Sync + 'static,
{
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let (log, record) = (Arc::clone(&stopped), Arc::clone(&announced));
let shown = Mutex::new("old");
let hook = stop_announced_on_end(
Arc::clone(&announced),
move || {
let mut shown = shown.lock().unwrap();
let answer = shown.to_string();
if answer == "old" {
*shown = meanwhile(&record);
}
Some(answer)
},
move |sid| log.lock().unwrap().push(sid.to_string()),
);
announced.record("old");
hook();
announced.finish_stops();
let stopped = stopped.lock().unwrap().clone();
(stopped, announced.take_all())
}
#[test]
fn a_page_that_takes_the_window_while_an_agents_end_decides_still_stops_the_old_console() {
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
announced.record("new");
announced.stop_left("new", |sid| panic!("{sid} is not left yet"));
"new"
});
assert_eq!(stopped, vec!["old"]);
assert_eq!(recorded, vec!["new"]);
}
#[test]
fn a_new_agent_that_joins_the_console_while_an_agents_end_decides_keeps_it() {
let (stopped, recorded) = stopped_by_an_end_while(|announced| {
announced.record("old");
announced.record("new");
"new"
});
assert!(stopped.is_empty(), "{stopped:?}");
assert_eq!(recorded, vec!["old", "new"]);
}
#[test]
fn finish_stops_waits_for_the_stop_a_new_page_started() {
// Quitting right after New Session: the exit must not cut it short.
let announced = left_under_the_window("old");
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
announced.stop_left("new", move |sid| {
std::thread::sleep(Duration::from_millis(300));
log.lock().unwrap().push(sid.to_string());
});
assert!(stopped.lock().unwrap().is_empty(), "it runs on a thread");
announced.finish_stops();
assert_eq!(*stopped.lock().unwrap(), vec!["old"]);
}
#[test]
fn finish_stops_waits_for_the_stops_an_agents_end_still_has_running() {
// Quitting right after an agent ended: the exit must not cut its
// consoles' stops short.
let announced = Arc::new(AnnouncedConsoles::default());
let stopped = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&stopped);
let hook = stop_announced_on_end(
Arc::clone(&announced),
|| None,
move |sid| {
std::thread::sleep(Duration::from_millis(300));
log.lock().unwrap().push(sid.to_string());
},
);
announced.record("s1");
hook();
assert!(
stopped.lock().unwrap().is_empty(),
"the stop runs on a thread"
);
announced.finish_stops();
assert_eq!(*stopped.lock().unwrap(), vec!["s1"]);
}
#[test]
fn the_apps_stop_calls_pass_force() {
let args = stop_args("20261101-120000-abcdef");