fix: abort stops running tool calls and kills bash process group
Race the tool round against abort, check abort before starting tools, answer pending calls with an aborted result, deny permission prompts on abort, and kill the bash process group on drop. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
951b69837a
commit
8f0de9465d
3 files changed
+120
-9
No files matched your search
@@ -421,6 +421,25 @@ impl Agent {
|
||||
*self.abort.borrow()
|
||||
}
|
||||
|
||||
fn abort_calls(
|
||||
&mut self,
|
||||
calls: &[(String, String, serde_json::Value)],
|
||||
) -> Result<Message, Error> {
|
||||
let content = calls
|
||||
.iter()
|
||||
.map(|(id, ..)| ContentBlock::ToolResult {
|
||||
tool_use_id: id.clone(),
|
||||
content: "aborted by user".into(),
|
||||
is_error: true,
|
||||
})
|
||||
.collect();
|
||||
self.push(Message {
|
||||
role: Role::User,
|
||||
content,
|
||||
})?;
|
||||
Err(Error::Aborted)
|
||||
}
|
||||
|
||||
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
|
||||
let r = self.run_inner(prompt.into()).await;
|
||||
self.emit(Event::RunEnd {
|
||||
@@ -529,6 +548,9 @@ impl Agent {
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.aborted() {
|
||||
return self.abort_calls(&calls);
|
||||
}
|
||||
let mut results: Vec<Option<ContentBlock>> = vec![None; calls.len()];
|
||||
let mut runnable = vec![];
|
||||
for (i, (id, name, args)) in calls.iter().enumerate() {
|
||||
@@ -577,10 +599,12 @@ impl Agent {
|
||||
&self.cx,
|
||||
);
|
||||
tokio::pin!(round);
|
||||
let mut ab = self.abort.clone();
|
||||
loop {
|
||||
tokio::select! {
|
||||
outs = &mut round => break outs,
|
||||
outs = &mut round => break Some(outs),
|
||||
Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; }
|
||||
_ = async { ab.wait_for(|a| *a).await.is_ok() } => break None,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -590,6 +614,9 @@ impl Agent {
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.take();
|
||||
let Some(outs) = outs else {
|
||||
return self.abort_calls(&calls);
|
||||
};
|
||||
while let Ok(line) = nrx.try_recv() {
|
||||
self.emit(Event::Info(line)).await;
|
||||
}
|
||||
@@ -1093,6 +1120,62 @@ mod tests {
|
||||
assert!(matches!(a.run("again").await, Err(Error::Aborted)));
|
||||
}
|
||||
|
||||
struct Slow;
|
||||
#[async_trait]
|
||||
impl Tool for Slow {
|
||||
fn spec(&self) -> ToolSpec {
|
||||
ToolSpec {
|
||||
name: "slow".into(),
|
||||
description: "sleeps".into(),
|
||||
input_schema: json!({"type":"object","properties":{}}),
|
||||
}
|
||||
}
|
||||
async fn call(&self, _: Value, _: &crate::tool::ToolCtx) -> ToolResult {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
||||
ToolResult::ok("done")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
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::Text { text: "ok".into() }]),
|
||||
]),
|
||||
Mutex::new(vec![]),
|
||||
));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut tools = Registry::default();
|
||||
tools.add(Slow);
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, h) = Agent::new(
|
||||
p.clone(),
|
||||
tools,
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
h.abort();
|
||||
});
|
||||
let t = std::time::Instant::now();
|
||||
assert!(matches!(a.run("go").await, Err(Error::Aborted)));
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert!(a.run("again").await.is_ok());
|
||||
let reqs = p.1.lock().unwrap();
|
||||
let last = &reqs[1].messages;
|
||||
let results = last
|
||||
.iter()
|
||||
.flat_map(|m| &m.content)
|
||||
.filter(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
|
||||
.count();
|
||||
assert_eq!(results, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mask_boundary_waits_for_big_context_and_is_recorded() {
|
||||
let big = "z".repeat(8000);
|
||||
|
||||
@@ -135,7 +135,14 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S
|
||||
}
|
||||
}
|
||||
let rule = req.rule.clone();
|
||||
match ask(req).await {
|
||||
let decision = match cx.state.abort.get().cloned() {
|
||||
Some(mut rx) => tokio::select! {
|
||||
d = ask(req) => d,
|
||||
_ = async { rx.wait_for(|a| *a).await.is_ok() } => Decision::Deny,
|
||||
},
|
||||
None => ask(req).await,
|
||||
};
|
||||
match decision {
|
||||
Decision::Once => {}
|
||||
Decision::Always => allow().add(&rule),
|
||||
Decision::Edits => allow().allow_edits(),
|
||||
|
||||
Reference in new issue
Block a user