Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent_servers: Add inactive v2 session cancellation (#65674)
Ben Brandtdf51ce9d4c5a
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex dda463aa577..c70eae242e8 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -4139,8 +4139,9 @@ impl AcpThread {}}- /// Settles receipt observations without declaring that remote execution stopped.- pub fn disconnect_submissions(&mut self, cx: &mut Context<Self>) {+ /// Ends receipt and cancellation observations without declaring remote execution stopped.+ pub fn handle_connection_lost(&mut self, cx: &mut Context<Self>) {+ self.activity.close_observation();let changed = self.submissions.disconnect();if !changed.is_empty() {for id in changed {@@ -4210,7 +4211,7 @@ impl AcpThread {.is_some_and(agent_client_protocol::is_incoming_transport_closed)}){- this.disconnect_submissions(cx);+ this.handle_connection_lost(cx);}let state = match &response {Ok(Some(SubmissionResponse::Accepted(receipt))) => {@@ -6642,12 +6643,17 @@ impl AcpThread {cx: &mut Context<Self>,f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp_v1::PromptResponse>,) -> Submission {+ let cancel_task = match self+ .request_cancellation(RequestPermissionOutcome::InterruptedByFollowUp, cx)+ {+ Ok(task) => task,+ Err(error) => return self.track_submission(id, None, cx, async move |_, _| Err(error)),+ };self.clear_completed_plan_entries(cx);self.had_error = false;self.local_execution_error = None;let (tx, rx) = oneshot::channel();- let cancel_task = self.cancel_inner(RequestPermissionOutcome::InterruptedByFollowUp, cx);self.turn_id += 1;let turn_id = self.turn_id;@@ -6657,8 +6663,13 @@ impl AcpThread {id: turn_id,first_entry_index,send_task: cx.spawn(async move |this, cx| {- cancel_task.await;- tx.send(f(this, cx).await).ok();+ let response = match cancel_task.await {+ Ok(()) => f(this, cx).await,+ Err(error) => Err(error),+ };+ if let Err(Err(error)) = tx.send(response) {+ log::debug!("Legacy submission observer was released: {error:#}");+ }}),});self.set_foreground_state(@@ -6810,30 +6821,40 @@ impl AcpThread {})}- pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {- self.cancel_inner(RequestPermissionOutcome::Cancelled, cx)+ /// Receipt sessions wait for reported Idle without withdrawing pending prompt RPCs.+ pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {+ match self.request_cancellation(RequestPermissionOutcome::Cancelled, cx) {+ Ok(task) => task,+ Err(error) => Task::ready(Err(error)),+ }}- fn cancel_inner(+ fn request_cancellation(&mut self,permission_outcome: RequestPermissionOutcome,cx: &mut Context<Self>,- ) -> Task<()> {+ ) -> Result<Task<Result<()>>> {self.flush_streaming_text(cx);if self.uses_reported_activity() {- self.cancel_generic_permission_requests(cx);- let receiver = self.activity.wait_for_idle();- if receiver.is_some() || self.has_unsettled_submissions() {- self.connection.cancel(self.session_id(), cx);+ self.activity.ensure_observable()?;+ if self.foreground_activity() != ForegroundActivity::Idle+ || self.has_unsettled_submissions()+ {+ self.connection.cancel(self.session_id(), cx)?;}+ self.cancel_generic_permission_requests(cx);+ let receiver = self.activity.wait_for_idle()?;let Some(receiver) = receiver else {- return Task::ready(());+ return Ok(Task::ready(Ok(())));};- return cx.spawn(async move |_, _| {- if receiver.await.is_err() {- log::debug!("Session released before foreground cancellation completed");- }- });+ return Ok(cx.spawn(async move |_, _| {+ receiver+ .await+ .context("Agent connection lost before cancellation was confirmed")+ }));+ }+ if self.running_turn.is_some() {+ self.connection.cancel(self.session_id(), cx)?;}self.cancel_outstanding_elicitations(cx);@@ -6842,11 +6863,10 @@ impl AcpThread {for id in request_ids {self.cancel_permission_request_with_outcome(id, permission_outcome.clone(), cx);}- return Task::ready(());+ return Ok(Task::ready(Ok(())));};self.shrink_message_source_capacity(turn.first_entry_index);self.mark_pending_entries_as_canceled(permission_outcome, cx);- self.connection.cancel(self.session_id(), cx);self.set_foreground_state(acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),cx,@@ -6854,7 +6874,10 @@ impl AcpThread {cx.emit(AcpThreadEvent::StatusChanged);// Wait for the send task to complete- cx.background_spawn(turn.send_task)+ Ok(cx.background_spawn(async move {+ turn.send_task.await;+ Ok(())+ }))}fn update_idle_sleep_prevention(&mut self, cx: &mut Context<Self>) {@@ -7011,12 +7034,12 @@ impl AcpThread {// Cancel any in-progress generation before restoringlet cancel_task = self.cancel(cx);- let rewind = self.rewind(client_id.clone(), cx);let git_store = self.project.read(cx).git_store().clone();- cx.spawn(async move |_, cx| {- cancel_task.await;- rewind.await?;+ cx.spawn(async move |this, cx| {+ cancel_task.await?;+ this.update(cx, |this, cx| this.rewind(client_id, cx))?+ .await?;if let Some(checkpoint) = checkpoint {git_store.update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx))@@ -7859,7 +7882,7 @@ mod tests {use futures::stream::StreamExt as _;use futures::{channel::mpsc, future::LocalBoxFuture, select};use gpui::UpdateGlobal as _;- use gpui::{App, AsyncApp, TestAppContext, WeakEntity};+ use gpui::{App, AsyncApp, TaskExt as _, TestAppContext, WeakEntity};use indoc::indoc;use project::{AgentId, FakeFs, Fs, RemoveOptions};use rand::{distr, prelude::*};@@ -7943,7 +7966,7 @@ mod tests {.streaming_content_target(None, false, false).expect("streaming target");assert_eq!(target.markdown.read(cx).source(), "before");- thread.cancel(cx).detach();+ thread.cancel(cx).detach_and_log_err(cx);assert_eq!(target.markdown.read(cx).source(), "before buffered");assert!(thread.streaming_text_buffer.is_none());target.markdown@@ -11096,6 +11119,57 @@ mod tests {(thread, connection)}+ #[gpui::test]+ async fn test_cancel_send_failure_preserves_legacy_turn(cx: &mut TestAppContext) {+ init_test(cx);+ let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ let connection = Rc::new(StubAgentConnection::new());+ let thread = cx+ .update(|cx| {+ connection.clone().new_session(+ project,+ PathList::new(&[Path::new(path!("/test"))]),+ cx,+ )+ })+ .await+ .expect("legacy session");+ let complete = connection.defer_next_prompt_response();+ let running = thread.update(cx, |thread, cx| thread.send(vec!["original".into()], cx));+ cx.run_until_parked();+ let before = thread.read_with(cx, |thread, _| {+ (+ thread.turn_id,+ thread.entries.len(),+ thread.activity_generation(),+ )+ });+ connection.set_next_cancel_error(anyhow!("cancel send failed"));+ let rejected = thread.update(cx, |thread, cx| thread.send(vec!["follow-up".into()], cx));+ assert_eq!(+ rejected+ .await+ .expect_err("failed cancellation prevents follow-up")+ .to_string(),+ "cancel send failed"+ );+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ (+ thread.turn_id,+ thread.entries.len(),+ thread.activity_generation()+ ),+ before+ );+ assert_eq!(thread.status(), ThreadStatus::Generating);+ });+ complete+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))+ .expect("original request remains live");+ running.await.expect("original turn completes");+ }+#[gpui::test]async fn test_receipt_disconnect_settles_waiters_and_preserves_recovery(cx: &mut TestAppContext,@@ -11137,8 +11211,8 @@ mod tests {cx,).expect("confirmed echo");- thread.disconnect_submissions(cx);- thread.disconnect_submissions(cx);+ thread.handle_connection_lost(cx);+ thread.handle_connection_lost(cx);assert!(!thread.has_unsettled_submissions());assert!(!thread.is_idle_for_retention());assert!(@@ -11200,7 +11274,7 @@ mod tests {.expect("reported activity");let submission =thread.submit_receipt(vec!["ready".into()], Task::ready(response), cx);- thread.disconnect_submissions(cx);+ thread.handle_connection_lost(cx);submission});let id = submission.id;@@ -11267,7 +11341,7 @@ mod tests {let id = submission.id;cx.run_until_parked();thread.update(cx, |thread, cx| {- thread.disconnect_submissions(cx);+ thread.handle_connection_lost(cx);assert!(matches!(thread.submission(id).expect("still pending").state,SubmissionState::Pending@@ -11705,7 +11779,10 @@ mod tests {let response = connection.defer_next_receipt_response();let submission = thread.update(cx, |thread, cx| thread.send(vec!["pending".into()], cx));let id = submission.id;- thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ thread+ .update(cx, |thread, cx| thread.cancel(cx))+ .await+ .expect("cancellation succeeds");assert_eq!(connection.take_cancel_calls(),[thread.read_with(cx, |thread, _| thread.session_id().clone())]@@ -11731,7 +11808,10 @@ mod tests {assert!(!thread.had_error());assert!(thread.entries().is_empty());});- thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ thread+ .update(cx, |thread, cx| thread.cancel(cx))+ .await+ .expect("cancellation succeeds");assert!(connection.take_cancel_calls().is_empty());}@@ -12237,7 +12317,7 @@ mod tests {cx.spawn({let cancelled = cancelled.clone();async move |_| {- cancel.await;+ cancel.await.expect("cancellation succeeds");cancelled.set(true);}})@@ -12821,7 +12901,7 @@ mod tests {cx,).expect("buffer before cancellation");- thread.cancel(cx).detach();+ thread.cancel(cx).detach_and_log_err(cx);assert!(thread.streaming_text_buffer.is_none());current});@@ -13874,7 +13954,10 @@ mod tests {));});- thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ thread+ .update(cx, |thread, cx| thread.cancel(cx))+ .await+ .expect("cancellation succeeds");thread.read_with(cx, |thread, _| {assert!(matches!(@@ -18393,7 +18476,7 @@ mod tests {));thread.update(cx, |thread, cx| {- thread.cancel(cx).detach();+ thread.cancel(cx).detach_and_log_err(cx);});thread.read_with(cx, |thread, _| {let Some((_, elicitation)) = thread.elicitation(&entry_id) else {@@ -18462,7 +18545,7 @@ mod tests {});thread.update(cx, |thread, cx| {- thread.cancel(cx).detach();+ thread.cancel(cx).detach_and_log_err(cx);});thread.read_with(cx, |thread, _| {let Some((_, elicitation)) = thread.elicitation(&entry_id) else {@@ -18797,7 +18880,7 @@ mod tests {});thread.update(cx, |thread, cx| {- thread.cancel(cx).detach();+ thread.cancel(cx).detach_and_log_err(cx);});assert_eq!(@@ -19417,7 +19500,7 @@ mod tests {acp_v2::CreateElicitationResponse::new(acp_v2::ElicitationAction::Decline),cx,);- thread.cancel(cx).detach();+ thread.cancel(cx).detach_and_log_err(cx);});assert_eq!(@@ -19747,7 +19830,9 @@ mod tests {})}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn truncate(&self,@@ -21589,7 +21674,7 @@ mod tests {acp_v1::StopReason::Cancelled,))).expect("parent backend should still be running");- parent_cancel.await;+ parent_cancel.await.expect("cancellation succeeds");parent_request.await.expect("parent turn should complete");assert_eq!(cx.active_idle_sleep_preventions(), 2);@@ -21650,7 +21735,7 @@ mod tests {complete.send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))).expect("backend should still be running");- cancel.await;+ cancel.await.expect("cancellation succeeds");request.await.expect("turn should complete");assert_eq!(cx.active_idle_sleep_preventions(), 0);}@@ -21864,7 +21949,7 @@ mod tests {.send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))).expect("backend should still be running");if let Some(cancel) = cancel {- cancel.await;+ cancel.await.expect("cancellation succeeds");}request.await.expect("turn should complete");thread.read_with(cx, |thread, _| {@@ -22305,7 +22390,7 @@ mod tests {acp_v1::StopReason::Cancelled,))).expect("backend should still be running");- cancel.await;+ cancel.await.expect("cancellation succeeds");request.await.expect("turn should complete");assert_eq!(cx.active_idle_sleep_preventions(), 0);}@@ -22478,7 +22563,7 @@ mod tests {acp_v1::StopReason::Cancelled,))).expect("backend should still be running");- cancel.await;+ cancel.await.expect("cancellation succeeds");request.await.expect("turn should complete");}@@ -22749,12 +22834,15 @@ mod tests {assert!(thread.is_idle_for_retention());cancellation});- cancellation.await;+ cancellation.await.expect("cancellation succeeds");assert!(matches!(response.await,RequestPermissionOutcome::Cancelled));- thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ thread+ .update(cx, |thread, cx| thread.cancel(cx))+ .await+ .expect("cancellation succeeds");assert_eq!(*events.borrow(), [(true, id), (false, id)]);}@@ -23802,7 +23890,7 @@ mod tests {complete.send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))).expect("backend still running after local cancellation");- cancellation.await;+ cancellation.await.expect("cancellation succeeds");}turn.await.expect("turn settles");} else if matches!(lifecycle, "local refusal" | "local refusal after tool") {@@ -23840,9 +23928,12 @@ mod tests {).expect("reported cancellation completion");});- cancellation.await;+ cancellation.await.expect("cancellation succeeds");} else {- thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ thread+ .update(cx, |thread, cx| thread.cancel(cx))+ .await+ .expect("cancellation succeeds");}thread.update(cx, |thread, cx| {assert_eq!(diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rsindex 19b53e0afe1..e64e9fc9800 100644--- a/crates/acp_thread/src/connection.rs+++ b/crates/acp_thread/src/connection.rs@@ -232,7 +232,8 @@ pub trait AgentConnection {None}- fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App);+ /// Requests cancellation; success does not establish that execution stopped.+ fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App) -> Result<()>;/// Request-scoped elicitations are connection-level because they can arrive before a session/// thread exists. Session-scoped elicitations stay in the thread timeline, but use@@ -930,6 +931,7 @@ mod test_support {next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,set_title_calls: Arc<Mutex<Vec<(acp_v2::SessionId, SharedString)>>>,cancel_calls: Arc<Mutex<Vec<acp_v2::SessionId>>>,+ next_cancel_error: Arc<Mutex<Option<anyhow::Error>>>,supports_receipt_submissions: bool,supports_retry: bool,supports_load_session: bool,@@ -968,6 +970,7 @@ mod test_support {next_truncate: Default::default(),set_title_calls: Default::default(),cancel_calls: Default::default(),+ next_cancel_error: Default::default(),permission_requests: HashMap::default(),sessions: Arc::default(),supports_receipt_submissions: false,@@ -1036,6 +1039,10 @@ mod test_support {std::mem::take(&mut *self.cancel_calls.lock())}+ pub fn set_next_cancel_error(&self, error: anyhow::Error) {+ assert!(self.next_cancel_error.lock().replace(error).is_none());+ }+pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {let (sender, receiver) = oneshot::channel();assert!(self.next_truncate.lock().replace(receiver).is_none());@@ -1331,18 +1338,24 @@ mod test_support {.then(|| Rc::new(StubAgentSessionRetry) as Rc<dyn AgentSessionRetry>)}- fn cancel(&self, session_id: &acp_v2::SessionId, _cx: &mut App) {+ fn cancel(&self, session_id: &acp_v2::SessionId, _cx: &mut App) -> Result<()> {self.cancel_calls.lock().push(session_id.clone());+ if let Some(error) = self.next_cancel_error.lock().take() {+ return Err(error);+ }if let Some(end_turn_tx) = self.sessions.lock().get_mut(session_id)- .unwrap()+ .ok_or_else(|| anyhow::anyhow!("Session not found"))?.response_tx.take(){- end_turn_tx.send(acp_v1::StopReason::Cancelled).unwrap();+ end_turn_tx+ .send(acp_v1::StopReason::Cancelled)+ .map_err(|_| anyhow::anyhow!("Prompt observer was released"))?;}+ Ok(())}fn set_title(diff --git a/crates/acp_thread/src/submission.rs b/crates/acp_thread/src/submission.rsindex 574ce0fc5d8..5ebccf54c1c 100644--- a/crates/acp_thread/src/submission.rs+++ b/crates/acp_thread/src/submission.rs@@ -335,6 +335,7 @@ pub(crate) struct SessionActivity {duration: Option<Duration>,first_entry_index: usize,cancel_waiters: Vec<oneshot::Sender<()>>,+ observation_closed: bool,}impl Default for SessionActivity {@@ -346,6 +347,7 @@ impl Default for SessionActivity {duration: None,first_entry_index: 0,cancel_waiters: Vec::new(),+ observation_closed: false,}}}@@ -402,12 +404,26 @@ impl SessionActivity {}}- pub(crate) fn wait_for_idle(&mut self) -> Option<oneshot::Receiver<()>> {+ pub(crate) fn ensure_observable(&self) -> anyhow::Result<()> {+ anyhow::ensure!(+ !self.observation_closed,+ "Agent connection lost before cancellation was confirmed"+ );+ Ok(())+ }++ pub(crate) fn close_observation(&mut self) {+ self.observation_closed = true;+ self.cancel_waiters.clear();+ }++ pub(crate) fn wait_for_idle(&mut self) -> anyhow::Result<Option<oneshot::Receiver<()>>> {+ self.ensure_observable()?;if self.phase() == ForegroundActivity::Idle {- return None;+ return Ok(None);}let (sender, receiver) = oneshot::channel();self.cancel_waiters.push(sender);- Some(receiver)+ Ok(Some(receiver))}}diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex a1807fc36e7..3c881d11634 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -3401,11 +3401,12 @@ impl acp_thread::AgentConnection for NativeAgentConnection {.try_for_each(UserMessageContent::validate_content_block)}- fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App) {+ fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App) -> Result<()> {log::info!("Cancelling on session: {}", session_id);self.0.update(cx, |agent, _cx| {agent.cancel_session(session_id);});+ Ok(())}fn truncate(@@ -3660,7 +3661,7 @@ impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {let acp_thread = self.acp_thread.clone();cx.spawn(async move |cx| {// Preparation is session-owned and may precede the model turn.- cancellation.await;+ cancellation.await?;let usage = thread.update(cx, |thread, cx| {thread.truncate(client_user_message_id, cx)?;anyhow::Ok(thread.latest_token_usage())@@ -4835,7 +4836,8 @@ mod internal_tests {);});- cx.update(|cx| connection.cancel(&session_id, cx));+ cx.update(|cx| connection.cancel(&session_id, cx))+ .expect("cancellation succeeds");cx.run_until_parked();assert_eq!(completion@@ -4978,7 +4980,7 @@ mod internal_tests {});let submission_id = submission.id;cx.run_until_parked();- cancellation.await;+ cancellation.await.expect("cancellation succeeds");assert!(submission.await@@ -5017,7 +5019,7 @@ mod internal_tests {cx.run_until_parked();assert_eq!(fake.pending_completions_for(&model).len(), 1);let cancellation = acp_thread.update(cx, |thread, cx| thread.cancel(cx));- cancellation.await;+ cancellation.await.expect("cancellation succeeds");assert_eq!(accepted.await.expect("accepted execution cancelled"),acp_v2::StopReason::Cancelled@@ -5176,7 +5178,8 @@ mod internal_tests {);assert!(second_completion.peek().is_none());cx.run_until_parked();- cx.update(|cx| connection.cancel(&session_id, cx));+ cx.update(|cx| connection.cancel(&session_id, cx))+ .expect("cancellation succeeds");assert_eq!(second_completion.await@@ -5398,7 +5401,8 @@ mod internal_tests {.any(|text| text.contains(command)),"reload retry must not send an unprepared command to the model");- cx.update(|cx| connection.cancel(&session_id, cx));+ cx.update(|cx| connection.cancel(&session_id, cx))+ .expect("cancellation succeeds");completion.await.expect("retry driver completed")@@ -5731,7 +5735,8 @@ mod internal_tests {.any(|text| text.contains("restored instructions") && text.contains("do work")));assert!(!texts.iter().any(|text| text.contains("/:retry-skill")));- cx.update(|cx| connection.cancel(&session_id, cx));+ cx.update(|cx| connection.cancel(&session_id, cx))+ .expect("cancellation succeeds");assert_eq!(completion.await@@ -5815,7 +5820,8 @@ mod internal_tests {request.intent,Some(CompletionIntent::ThreadContextSummarization));- cx.update(|cx| connection.cancel(&session_id, cx));+ cx.update(|cx| connection.cancel(&session_id, cx))+ .expect("cancellation succeeds");assert_eq!(completion.await@@ -9674,7 +9680,8 @@ mod internal_tests {cx.run_until_parked();turn.acp_thread.update(cx, |thread, cx| thread.cancel(cx))- .await;+ .await+ .expect("cancellation succeeds");send.await.unwrap();cx.run_until_parked();assert_eq!(@@ -9801,7 +9808,8 @@ mod internal_tests {turn.acp_thread.update(cx, |thread, cx| thread.cancel(cx))- .await;+ .await+ .expect("cancellation succeeds");send.await.unwrap();cx.run_until_parked();assert_eq!(diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rsindex f89cab41839..b4382df7b93 100644--- a/crates/agent/src/tests/mod.rs+++ b/crates/agent/src/tests/mod.rs@@ -4496,7 +4496,8 @@ async fn test_agent_connection(cx: &mut TestAppContext) {});// Test cancel- cx.update(|cx| connection.cancel(&session_id, cx));+ cx.update(|cx| connection.cancel(&session_id, cx))+ .expect("cancellation succeeds");request.await.expect("prompt should fail gracefully");// Explicitly close the session and drop the ACP thread.@@ -6406,7 +6407,10 @@ async fn test_subagent_tool_call_cancellation_during_task_prompt(cx: &mut TestAp// cx.run_until_parked();- acp_thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ acp_thread+ .update(cx, |thread, cx| thread.cancel(cx))+ .await+ .expect("cancellation succeeds");cx.run_until_parked();diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex 7a27ba82491..91bd984673c 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -172,7 +172,7 @@ impl ForegroundWorkItem for ClientDisconnectWork {if let Some(thread) = thread.upgrade() {thread.update(cx, |thread, cx| {thread.cancel_outstanding_elicitations(cx);- thread.disconnect_submissions(cx);+ thread.handle_connection_lost(cx);cx.notify();});}diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rsindex 3d492f0a5e6..5df68e996d1 100644--- a/crates/agent_servers/src/acp/v1.rs+++ b/crates/agent_servers/src/acp/v1.rs@@ -1644,12 +1644,15 @@ impl AgentConnection for AcpConnection {})}- fn cancel(&self, session_id: &acp_v2::SessionId, _cx: &mut App) {+ fn cancel(&self, session_id: &acp_v2::SessionId, _cx: &mut App) -> Result<()> {+ let params = acp::CancelNotification::new(acp::SessionId::new(session_id.0.clone()));+ self.connection+ .send_notification(params)+ .map_err(map_acp_error)?;if let Some(session) = self.sessions.borrow_mut().get_mut(session_id) {session.suppress_abort_err = true;}- let params = acp::CancelNotification::new(acp::SessionId::new(session_id.0.clone()));- self.connection.send_notification(params).log_err();+ Ok(())}fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {@@ -1968,7 +1971,7 @@ pub mod test_support {self.inner.retry(session_id, cx)}- fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App) {+ fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App) -> Result<()> {self.inner.cancel(session_id, cx)}@@ -2427,7 +2430,8 @@ mod tests {).data(data);*response_error.lock().expect("response error") = original.clone();- cx.update(|cx| harness.connection.cancel(&session_id, cx));+ cx.update(|cx| harness.connection.cancel(&session_id, cx))+ .expect("cancellation succeeds");assert!(harness.connectiondiff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rsindex e95d3aaf595..5b018b2ea27 100644--- a/crates/agent_servers/src/acp/v2.rs+++ b/crates/agent_servers/src/acp/v2.rs@@ -753,8 +753,21 @@ impl AgentConnection for AcpV2Connection {})}- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {- log::warn!("Session cancellation is not yet implemented by the inactive ACP v2 backend");+ fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) -> Result<()> {+ anyhow::ensure!(+ self.sessions+ .borrow()+ .get(session_id)+ .is_some_and(|session| session.thread.upgrade().is_some()),+ "Session has been released"+ );+ anyhow::ensure!(+ !self.connection.is_incoming_closed(),+ "Agent connection is closed"+ );+ self.connection+ .send_notification(acp::CancelSessionNotification::new(session_id.clone()))+ .map_err(map_acp_error)}fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {@@ -1007,6 +1020,7 @@ mod tests {client: Rc<AcpV2Connection>,project: Entity<Project>,prompts: async_channel::Receiver<(acp::PromptRequest, Responder<acp::PromptResponse>)>,+ cancellations: async_channel::Receiver<acp::CancelSessionNotification>,new_requests: async_channel::Receiver<(acp::NewSessionRequest, acp::RequestId)>,new_responses:async_channel::Sender<Result<acp::NewSessionResponse, agent_client_protocol::Error>>,@@ -1045,6 +1059,7 @@ mod tests {>();let (close_sender, closes) = async_channel::unbounded();let (prompt_sender, prompts) = async_channel::unbounded();+ let (cancel_sender, cancellations) = async_channel::unbounded();let (sender, received) = futures::channel::oneshot::channel();let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();let agent_task = cx.background_spawn(@@ -1134,6 +1149,15 @@ mod tests {},agent_client_protocol::on_receive_request!(),)+ .on_receive_notification(+ async move |notification: acp::CancelSessionNotification, _| {+ cancel_sender+ .try_send(notification)+ .expect("cancel receiver");+ Ok(())+ },+ agent_client_protocol::on_receive_notification!(),+ ).connect_with(agent_transport, async move |agent| {assert!(sender.send(agent).is_ok());futures::future::pending::<Result<(), agent_client_protocol::Error>>().await@@ -1157,6 +1181,7 @@ mod tests {client: Rc::new(client),project,prompts,+ cancellations,new_requests,new_responses,config_requests,@@ -1224,6 +1249,103 @@ mod tests {.meta(meta("delivery-not-session"))}+ #[gpui::test]+ async fn v2_cancel_sdk_preserves_receipt_and_waits_for_reported_idle(cx: &mut TestAppContext) {+ use acp_thread::{ForegroundActivity, SubmissionResponse, SubmissionState};+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let thread = harness.thread(cx).await;+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ session_id.clone(),+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(+ acp::RunningStateUpdate::new(),+ )),+ ))+ .expect("reported running");+ cx.run_until_parked();+ let submission = thread.update(cx, |thread, cx| thread.send(vec!["question".into()], cx));+ let id = submission.id;+ let (_, responder) = bounded(harness.prompts.recv(), cx)+ .await+ .expect("pending prompt");+ let request_cancellation = responder.cancellation();+ let mut cancellation = thread.update(cx, |thread, cx| thread.cancel(cx));+ let notification = bounded(harness.cancellations.recv(), cx)+ .await+ .expect("session cancel");+ assert_eq!(notification.session_id, session_id);+ assert!(+ !request_cancellation.is_cancelled(),+ "session cancel is not RPC withdrawal"+ );+ responder+ .respond(acp::PromptResponse::new("accepted"))+ .expect("accepted during cancellation");+ assert!(matches!(bounded(submission, cx).await.expect("acceptance"),+ Some(SubmissionResponse::Accepted(receipt)) if receipt.message_id == "accepted".into()));+ assert!((&mut cancellation).now_or_never().is_none());+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Running+ );+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ session_id,+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Idle(+ acp::IdleStateUpdate::new().stop_reason(acp::StopReason::Cancelled),+ )),+ ))+ .expect("confirmed idle");+ bounded(cancellation, cx)+ .await+ .expect("cancellation succeeds");+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert!(matches!(+ thread.submission(id).expect("receipt retained").state,+ SubmissionState::Accepted { echoed: false, .. }+ ));+ });+ }++ #[gpui::test]+ async fn v2_cancel_sdk_eof_fails_observation_without_inventing_idle(cx: &mut TestAppContext) {+ use acp_thread::ForegroundActivity;+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let thread = harness.thread(cx).await;+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ session_id,+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(+ acp::RunningStateUpdate::new(),+ )),+ ))+ .expect("reported running");+ cx.run_until_parked();+ let mut cancellation = thread.update(cx, |thread, cx| thread.cancel(cx));+ bounded(harness.cancellations.recv(), cx)+ .await+ .expect("session cancel");+ assert!((&mut cancellation).now_or_never().is_none());+ drop(harness._agent_task);+ drop(harness.agent);+ bounded(cancellation, cx)+ .await+ .expect_err("EOF cannot confirm cancellation");+ bounded(thread.update(cx, |thread, cx| thread.cancel(cx)), cx)+ .await+ .expect_err("new observers must not wait on a disconnected session");+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Running+ );+ }+#[gpui::test]async fn v2_receipt_sdk_correlates_echoes_without_completing_activity(cx: &mut TestAppContext) {use acp_thread::{diff --git a/crates/agent_servers/src/e2e_tests.rs b/crates/agent_servers/src/e2e_tests.rsindex a03524a3d77..9871327e84b 100644--- a/crates/agent_servers/src/e2e_tests.rs+++ b/crates/agent_servers/src/e2e_tests.rs@@ -277,7 +277,10 @@ wheretool_call.id.clone()});- thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ thread+ .update(cx, |thread, cx| thread.cancel(cx))+ .await+ .expect("cancellation succeeds");full_turn.await.unwrap();thread.read_with(cx, |thread, _cx| {let AgentThreadEntry::ToolCall(tool_call) = &thread.entries()[first_tool_call_ix] else {diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex 3f8a0102b35..171c2569738 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -7236,7 +7236,9 @@ mod tests {Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {self@@ -14101,7 +14103,9 @@ mod tests {Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {selfdiff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 4256fad77f2..791caca70b6 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -5172,7 +5172,7 @@ pub(crate) mod tests {editor.update_in(cx, |editor, window, cx| {editor.set_text("keep my draft", window, cx);});- thread.update(cx, |thread, cx| thread.disconnect_submissions(cx));+ thread.update(cx, |thread, cx| thread.handle_connection_lost(cx));cx.run_until_parked();assert_eq!(editor.read_with(cx, |editor, cx| editor.text(cx)),@@ -5228,6 +5228,77 @@ pub(crate) mod tests {});}+ #[gpui::test]+ async fn test_cancel_failure_preserves_draft_and_queued_messages(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(language_model::init);+ for action in ["stop", "interrupt", "queued"] {+ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;+ add_to_workspace(conversation_view.clone(), cx);+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("reported running");+ });+ let editor = message_editor(&conversation_view, cx);+ editor.update_in(cx, |editor, window, cx| {+ editor.set_text("keep my draft", window, cx)+ });+ let queued = thread_view.update_in(cx, |view, window, cx| {+ view.add_to_queue(vec!["first queued".into()], vec![], window, cx);+ view.add_to_queue(vec!["second queued".into()], vec![], window, cx);+ view.message_queue+ .iter()+ .map(|entry| (entry.id, entry.content.clone()))+ .collect::<Vec<_>>()+ });+ connection.set_next_cancel_error(anyhow!("cancel send failed"));+ thread_view.update_in(cx, |view, window, cx| match action {+ "stop" => view.cancel_generation(cx),+ "interrupt" => view.interrupt_and_send(window, cx),+ "queued" => {+ let id = view.message_queue.last_id().expect("queued message");+ view.send_queued_message_now(id, window, cx);+ }+ _ => unreachable!(),+ });+ cx.run_until_parked();+ assert!(+ connection.take_receipt_prompt().is_none(),+ "failed stop must not send"+ );+ assert_eq!(+ editor.read_with(cx, |editor, cx| editor.text(cx)),+ "keep my draft"+ );+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ acp_thread::ForegroundActivity::Running+ );+ thread_view.update_in(cx, |view, window, cx| {+ assert!(view.thread_error.is_some());+ assert_eq!(+ view.message_queue+ .iter()+ .map(|entry| (entry.id, entry.content.clone()))+ .collect::<Vec<_>>(),+ queued+ );+ assert!(+ !view.send_queued_message_after_generation_stopped(false, window, cx),+ "failed stop leaves queue paused"+ );+ });+ }+ }+#[gpui::test]async fn test_reported_stale_stop_and_token_limit_do_not_send_queue(cx: &mut TestAppContext) {init_test(cx);@@ -6286,7 +6357,9 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {self@@ -8666,7 +8739,9 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {self@@ -8797,7 +8872,9 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {self@@ -8909,7 +8986,9 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {self@@ -8981,7 +9060,9 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {self@@ -9155,7 +9236,7 @@ pub(crate) mod tests {unimplemented!()}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {unimplemented!()}@@ -9224,7 +9305,7 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {unimplemented!()}@@ -9339,7 +9420,9 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {self@@ -18475,7 +18558,9 @@ pub(crate) mod tests {Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))}- fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) {}+ fn cancel(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> anyhow::Result<()> {+ Ok(())+ }fn into_any(self: Rc<Self>) -> Rc<dyn Any> {selfdiff --git a/crates/agent_ui/src/conversation_view/message_queue.rs b/crates/agent_ui/src/conversation_view/message_queue.rsindex 1936f15b48c..5984ffd1863 100644--- a/crates/agent_ui/src/conversation_view/message_queue.rs+++ b/crates/agent_ui/src/conversation_view/message_queue.rs@@ -118,6 +118,16 @@ impl MessageQueue {self.entries.remove(index)}+ pub fn restore_after_failed_send(&mut self, entry: QueueEntry) {+ let index = self+ .entries+ .iter()+ .position(|queued| queued.id.0 > entry.id.0)+ .unwrap_or(self.entries.len());+ self.entries.insert(index, entry);+ self.pause();+ }+pub fn clear(&mut self) {self.entries.clear();self.can_fast_track = false;diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 23804335f20..45e186655ee 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -2209,12 +2209,16 @@ impl ThreadView {let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));cx.spawn_in(window, async move |this, cx| {- cancelled.await;+ if let Err(error) = cancelled.await {+ this.update(cx, |this, cx| this.handle_thread_error(error, cx))+ .log_err();+ return;+ }this.update_in(cx, |this, window, cx| {this.send_impl(message_editor, window, cx);})- .ok();+ .log_err();}).detach();}@@ -2342,11 +2346,21 @@ impl ThreadView {self.thread_retry_status.take();self.thread_error.take();self.message_queue.pause();- self._cancel_task = Some(self.thread.update(cx, |thread, cx| thread.cancel(cx)));+ self._cancel_task = Some(self.cancel_thread(&self.thread, cx));self.sync_generating_indicator(cx);cx.notify();}+ fn cancel_thread(&self, thread: &Entity<AcpThread>, cx: &mut Context<Self>) -> Task<()> {+ let cancellation = thread.update(cx, |thread, cx| thread.cancel(cx));+ cx.spawn(async move |this, cx| {+ if let Err(error) = cancellation.await {+ this.update(cx, |this, cx| this.handle_thread_error(error, cx))+ .log_err();+ }+ })+ }+pub fn retry_generation(&mut self, cx: &mut Context<Self>) {self.thread_error.take();@@ -2712,14 +2726,12 @@ impl ThreadView {self.message_editor.focus_handle(cx).focus(window, cx);- let content = entry.content;- let tracked_buffers = entry.tracked_buffers;-// A queued message can itself be a built-in command (e.g. the user typed// `/compact` while a turn was generating). Detect that so we run it as a// command turn without echoing it as a user message, matching the// non-queued path.- let is_native_command = content+ let is_native_command = entry+ .content.first().and_then(|block| match block {acp_v2::ContentBlock::Text(text) => Some(text.text.as_str()),@@ -2735,8 +2747,16 @@ impl ThreadView {let workspace = self.workspace.clone();let should_be_following = self.should_be_following;- let contents_task = cx.spawn_in(window, async move |_this, cx| {- cancelled.await;+ let contents_task = cx.spawn_in(window, async move |this, cx| {+ if let Err(error) = cancelled.await {+ this.update(cx, |this, cx| {+ this.message_queue.restore_after_failed_send(entry);+ this.sync_queue_flag_to_native_thread(cx);+ cx.notify();+ })+ .log_err();+ return Err(error);+ }if should_be_following {workspace.update_in(cx, |workspace, window, cx| {@@ -2745,7 +2765,7 @@ impl ThreadView {.ok();}- Ok(Some((content, tracked_buffers)))+ Ok(Some((entry.content, entry.tracked_buffers)))});self.send_content(contents_task, is_native_command, window, cx);@@ -4928,11 +4948,9 @@ impl ThreadView {.icon_size(IconSize::Small).icon_color(Color::Error).tooltip(Tooltip::text("Stop Subagent"))- .on_click(move |_, _, cx| {- thread.update(cx, |thread, cx| {- thread.cancel(cx).detach();- });- }),+ .on_click(cx.listener(move |this, _, _, cx| {+ this.cancel_thread(&thread, cx).detach();+ })),)}).child(@@ -11641,11 +11659,9 @@ impl ThreadView {.map(|view| view.read(cx).thread.clone()),|this, thread| {this.on_click(cx.listener(- move |_this, _event, _window, cx| {+ move |this, _event, _window, cx| {telemetry::event!("Subagent Stopped");- thread.update(cx, |thread, cx| {- thread.cancel(cx).detach();- });+ this.cancel_thread(&thread, cx).detach();},))},diff --git a/crates/eval_cli/src/main.rs b/crates/eval_cli/src/main.rsindex 52c1547da17..6abbbfb04ab 100644--- a/crates/eval_cli/src/main.rs+++ b/crates/eval_cli/src/main.rs@@ -859,12 +859,16 @@ async fn run_agent(},_ = sigterm_future.fuse() => {eprintln!("[eval-cli] received SIGTERM, cancelling...");- acp_thread.update(cx, |t: &mut acp_thread::AcpThread, cx| t.cancel(cx)).await;- Ok(AgentOutcome::Interrupted)+ acp_thread.update(cx, |thread: &mut acp_thread::AcpThread, cx| thread.cancel(cx))+ .await+ .context("cancelling agent after SIGTERM")+ .map(|()| AgentOutcome::Interrupted)},_ = timeout_future.fuse() => {- acp_thread.update(cx, |t: &mut acp_thread::AcpThread, cx| t.cancel(cx)).await;- Ok(AgentOutcome::Timeout { seconds: timeout.unwrap_or(0) })+ acp_thread.update(cx, |thread: &mut acp_thread::AcpThread, cx| thread.cancel(cx))+ .await+ .context("cancelling agent after timeout")+ .map(|()| AgentOutcome::Timeout { seconds: timeout.unwrap_or(0) })}};