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

+129 -8
View File
@@ -35,6 +35,12 @@ 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.
pub type Ended = Arc<dyn Fn() + Send + Sync>;
/// 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<Option<BeforeFresh>>,
forget_session: Mutex<Option<ForgetSession>>,
ended: Mutex<Option<Ended>>,
/// 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<Vec<(String, String)>>,
/// 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<Vec<thread::JoinHandle<()>>>,
inner: Mutex<Inner>,
}
@@ -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<Self>, 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<Self>, 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<String> {
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);
}
}