From 79cf5fcda17aa5770d584b97f90110c4e083a435 Mon Sep 17 00:00:00 2001 From: hermes Date: Sat, 14 Nov 2026 12:00:00 +0000 Subject: [PATCH] agent: abort also ends a hanging request and compaction --- crates/hx-core/src/agent.rs | 46 +++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index bef76c1..2085791 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -433,7 +433,12 @@ impl Agent { ) -> Result>, Error> { let mut wait = self.retry_ms; for attempt in 1..=4 { - match self.provider.stream(req.clone()).await { + let mut ab = self.abort.clone(); + let r = tokio::select! { + r = self.provider.stream(req.clone()) => r, + _ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted), + }; + match r { Err(hx_ai::Error::Api { status, .. }) if attempt < 4 && transient(status) => { self.emit(Event::Info(format!( "api error {status}; retry {attempt}/3 in {wait}ms" @@ -477,8 +482,12 @@ impl Agent { if self.aborted() { return Err(Error::Aborted); } + let mut ab = self.abort.clone(); if self.window.should_compact(&self.session.messages()) - && self.compact(KEEP_MESSAGES).await? + && tokio::select! { + r = self.compact(KEEP_MESSAGES) => r?, + _ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted), + } { self.emit(Event::Info("context compacted".into())).await; } @@ -919,6 +928,39 @@ mod tests { (r, n) } + struct Hang; + #[async_trait] + impl Provider for Hang { + async fn stream( + &self, + _: Request, + ) -> hx_ai::Result>> { + std::future::pending().await + } + } + + #[tokio::test] + async fn abort_ends_a_request_that_never_answers() { + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, h) = Agent::new( + Arc::new(Hang), + Registry::default(), + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + let t = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + h.abort(); + }); + let r = tokio::time::timeout(std::time::Duration::from_secs(5), a.run("go")).await; + t.await.unwrap(); + assert!(matches!(r, Ok(Err(Error::Aborted)))); + } + #[tokio::test] async fn transient_api_errors_are_retried() { let (r, n) = flaky_run(1, 529).await;