Merge pull request 'Abort kills claude_cli process group and cancels plan/ask dialogs' (#237) from fix-abort-claude-cli into main
build / version (push) Successful in 11s
build / build (aarch64-apple-darwin) (push) Successful in 4m38s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m49s
build / release (push) Successful in 29s

This commit was merged in pull request #237.
This commit is contained in:
hermes committed 2026-11-25 11:40:49 +00:00
commit c2ce0e3fe4
4 files changed
+103 -8

No files matched your search

+69 -2
View File
@@ -200,6 +200,8 @@ impl Provider for ClaudeCli {
.stdout(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped())
.kill_on_drop(true); .kill_on_drop(true);
#[cfg(unix)]
cmd.process_group(0);
let mut child = cmd.spawn().map_err(|e| { let mut child = cmd.spawn().map_err(|e| {
Error::Http(format!( Error::Http(format!(
"cannot start {:?}: {e} (is claude installed?)", "cannot start {:?}: {e} (is claude installed?)",
@@ -208,17 +210,22 @@ impl Provider for ClaudeCli {
})?; })?;
let out = child.stdout.take().expect("piped"); let out = child.stdout.take().expect("piped");
let mut err = child.stderr.take().expect("piped"); let mut err = child.stderr.take().expect("piped");
let group = KillGroup(child.id());
let session = self.session.clone(); let session = self.session.clone();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<StreamEvent>>(); let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<StreamEvent>>();
tokio::spawn(async move { tokio::spawn(async move {
let _child = child; let _child = child;
let _group = group;
let mut lines = BufReader::new(out).lines(); let mut lines = BufReader::new(out).lines();
let (mut text, mut think) = (String::new(), String::new()); let (mut text, mut think) = (String::new(), String::new());
let mut done = false; let mut done = false;
let mut last: Option<Value> = None; let mut last: Option<Value> = None;
let mut quota = Quota::default(); let mut quota = Quota::default();
let mut uses: std::collections::HashMap<String, (String, Value)> = Default::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 { let Ok(v) = serde_json::from_str::<Value>(&l) else {
continue; continue;
}; };
@@ -325,7 +332,7 @@ impl Provider for ClaudeCli {
_ => {} _ => {}
} }
} }
if !done { if !done && !tx.is_closed() {
let mut e = String::new(); let mut e = String::new();
let _ = tokio::io::AsyncReadExt::read_to_string(&mut err, &mut e).await; let _ = tokio::io::AsyncReadExt::read_to_string(&mut err, &mut e).await;
let _ = tx.send(Err(Error::Http(format!( 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -419,4 +438,52 @@ mod tests {
assert_eq!(usage.cache_read_tokens, 91_000); assert_eq!(usage.cache_read_tokens, 91_000);
assert_eq!(usage.output_tokens, 7); 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")));
}
} }
+12 -1
View File
@@ -1140,7 +1140,18 @@ mod tests {
async fn abort_during_tool_round_stops_it_and_answers_the_calls() { async fn abort_during_tool_round_stops_it_and_answers_the_calls() {
let p = Arc::new(Script( let p = Arc::new(Script(
Mutex::new(vec![ Mutex::new(vec![
asst(vec![tu("1", "slow"), tu("2", "slow")]), asst(vec![
ContentBlock::ToolUse {
id: "1".into(),
name: "slow".into(),
input: json!({}),
},
ContentBlock::ToolUse {
id: "2".into(),
name: "slow".into(),
input: json!({}),
},
]),
asst(vec![ContentBlock::Text { text: "ok".into() }]), asst(vec![ContentBlock::Text { text: "ok".into() }]),
]), ]),
Mutex::new(vec![]), Mutex::new(vec![]),
+19 -5
View File
@@ -200,6 +200,19 @@ pub async fn serve(path: &Path, cx: ToolCtx, bus: Bus, mode: Unanswered) -> std:
} }
} }
async fn choose_or_abort(
cx: &ToolCtx,
q: crate::Question,
) -> Result<Option<Vec<String>>, &'static str> {
match cx.state.abort.get().cloned() {
Some(mut rx) => tokio::select! {
r = cx.state.choose(q) => r,
_ = async { rx.wait_for(|a| *a).await.is_ok() } => Ok(None),
},
None => cx.state.choose(q).await,
}
}
async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> { async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> {
let q = crate::Question { let q = crate::Question {
text: "Implement this plan?".into(), text: "Implement this plan?".into(),
@@ -214,7 +227,7 @@ async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> {
other: true, other: true,
plan: Some(plan.into()), plan: Some(plan.into()),
}; };
match cx.state.choose(q).await { match choose_or_abort(cx, q).await {
Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => { Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => {
cx.state cx.state
.allow .allow
@@ -239,15 +252,16 @@ async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
let s = |k| o[k].as_str().unwrap_or_default().to_string(); let s = |k| o[k].as_str().unwrap_or_default().to_string();
(s("label"), s("description")) (s("label"), s("description"))
}); });
let r = cx let r = choose_or_abort(
.state cx,
.choose(crate::Question { crate::Question {
text: text.into(), text: text.into(),
options: options.collect(), options: options.collect(),
multi: q["multiSelect"].as_bool().unwrap_or(false), multi: q["multiSelect"].as_bool().unwrap_or(false),
other: true, other: true,
plan: None, plan: None,
}) },
)
.await .await
.ok()??; .ok()??;
answers.insert(text.into(), r.join(", ").into()); answers.insert(text.into(), r.join(", ").into());
+3
View File
@@ -621,6 +621,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
} }
Ui::Done(r) => { Ui::Done(r) => {
app.busy = false; app.busy = false;
app.choose = None;
app.doc = None;
app.perm = None;
{ {
let mut a = agent.lock().await; let mut a = agent.lock().await;
if let Some(sw) = app.sw.end_turn(&mut a) { if let Some(sw) = app.sw.end_turn(&mut a) {