diff --git a/crates/hx-ai/src/claude_cli.rs b/crates/hx-ai/src/claude_cli.rs index dce473f..3b079e0 100644 --- a/crates/hx-ai/src/claude_cli.rs +++ b/crates/hx-ai/src/claude_cli.rs @@ -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::>(); 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 = None; let mut quota = Quota::default(); let mut uses: std::collections::HashMap = 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::(&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); +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::() + { + 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"))); + } } diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index cfa33de..5b27530 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -1140,7 +1140,18 @@ mod tests { async fn abort_during_tool_round_stops_it_and_answers_the_calls() { let p = Arc::new(Script( 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() }]), ]), Mutex::new(vec![]), diff --git a/crates/hx-core/src/approve.rs b/crates/hx-core/src/approve.rs index 8006074..3e20913 100644 --- a/crates/hx-core/src/approve.rs +++ b/crates/hx-core/src/approve.rs @@ -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>, &'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> { let q = crate::Question { text: "Implement this plan?".into(), @@ -214,7 +227,7 @@ async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> { other: true, 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") => { cx.state .allow @@ -239,17 +252,18 @@ async fn ask(cx: &ToolCtx, input: &Value) -> Option { let s = |k| o[k].as_str().unwrap_or_default().to_string(); (s("label"), s("description")) }); - let r = cx - .state - .choose(crate::Question { + let r = choose_or_abort( + cx, + crate::Question { text: text.into(), options: options.collect(), multi: q["multiSelect"].as_bool().unwrap_or(false), other: true, plan: None, - }) - .await - .ok()??; + }, + ) + .await + .ok()??; answers.insert(text.into(), r.join(", ").into()); } let mut out = input.clone(); diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 98ce67e..d45168d 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -621,6 +621,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { } Ui::Done(r) => { app.busy = false; + app.choose = None; + app.doc = None; + app.perm = None; { let mut a = agent.lock().await; if let Some(sw) = app.sw.end_turn(&mut a) {