Abort kills claude_cli process group and cancels pending plan/ask dialogs

- claude -p runs in its own process group; dropping the stream kills the group (its Bash children survived kill_on_drop)
- reader task stops when the stream is dropped
- exit_plan/AskUserQuestion race the question against abort
- TUI clears choose/doc/perm popups when a run ends
- fix abort_during_tool_round test (tu() always built echo calls, slow never ran)
This commit is contained in:
hermes committed 2026-11-25 09:07:38 +00:00
1 parent 7e428dfb39
commit fd0b0a77dc
4 files changed
+105 -10

No files matched your search

+69 -2
View File
@@ -200,6 +200,8 @@ impl Provider for ClaudeCli {
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
#[cfg(unix)]
cmd.process_group(0);
let mut child = cmd.spawn().map_err(|e| {
Error::Http(format!(
"cannot start {:?}: {e} (is claude installed?)",
@@ -208,17 +210,22 @@ impl Provider for ClaudeCli {
})?;
let out = child.stdout.take().expect("piped");
let mut err = child.stderr.take().expect("piped");
let group = KillGroup(child.id());
let session = self.session.clone();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<StreamEvent>>();
tokio::spawn(async move {
let _child = child;
let _group = group;
let mut lines = BufReader::new(out).lines();
let (mut text, mut think) = (String::new(), String::new());
let mut done = false;
let mut last: Option<Value> = None;
let mut quota = Quota::default();
let mut uses: std::collections::HashMap<String, (String, Value)> = Default::default();
while let Ok(Some(l)) = lines.next_line().await {
while let Some(Ok(Some(l))) = tokio::select! {
l = lines.next_line() => Some(l),
_ = tx.closed() => None,
} {
let Ok(v) = serde_json::from_str::<Value>(&l) else {
continue;
};
@@ -325,7 +332,7 @@ impl Provider for ClaudeCli {
_ => {}
}
}
if !done {
if !done && !tx.is_closed() {
let mut e = String::new();
let _ = tokio::io::AsyncReadExt::read_to_string(&mut err, &mut e).await;
let _ = tx.send(Err(Error::Http(format!(
@@ -341,6 +348,18 @@ impl Provider for ClaudeCli {
}
}
struct KillGroup(Option<u32>);
impl Drop for KillGroup {
fn drop(&mut self) {
#[cfg(unix)]
if let Some(pid) = self.0 {
let _ = std::process::Command::new("kill")
.args(["-KILL", &format!("-{pid}")])
.status();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -419,4 +438,52 @@ mod tests {
assert_eq!(usage.cache_read_tokens, 91_000);
assert_eq!(usage.output_tokens, 7);
}
#[cfg(unix)]
#[tokio::test]
async fn dropping_the_stream_kills_claude_and_its_children() {
let dir = std::env::temp_dir().join(format!("hx-kill-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let pidf = dir.join("pid");
let f = pidf.clone();
let p = ClaudeCli::new(vec![]).with_spawner(Arc::new(move |_| {
let f = f.clone();
Box::pin(async move {
let mut c = tokio::process::Command::new("sh");
c.args([
"-c",
&format!("sleep 60 & echo $! > {}; wait", f.display()),
"sh",
]);
c
})
}));
let req = Request {
model: "m".into(),
system: String::new(),
messages: vec![Message::user("hi")],
tools: vec![],
max_tokens: 100,
effort: crate::Effort::levels(crate::auth::Kind::Claude)[0],
};
let s = p.stream(req).await.unwrap();
let pid = loop {
if let Ok(x) = std::fs::read_to_string(&pidf)
&& let Ok(n) = x.trim().parse::<u32>()
{
break n;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
};
drop(s);
for _ in 0..100 {
match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
Err(_) => return,
Ok(x) if x.rsplit(") ").next().is_some_and(|r| r.starts_with('Z')) => return,
_ => {}
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
panic!("child {pid} survived: {:?}", std::fs::read_to_string(format!("/proc/{pid}/stat")));
}
}