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

@@ -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<Mutex<usize>> {
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<Mutex<usize>>, 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::<String>::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();
@@ -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 };
+96
View File
@@ -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=<pid> 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).