Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Emit elicitation completion from state transitions (#64609)
Ben Brandt05958c4773e8
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 9dbfe169296..24c44be6f4d 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -422,9 +422,15 @@ pub enum ElicitationStatus {Completed,}+enum ElicitationChange {+ Responded,+ Updated,+}+#[derive(Clone, Debug)]pub enum ElicitationStoreEvent {ElicitationRequested(ElicitationEntryId),+ /// The request left `Pending`; this does not imply delivery to its response waiter.ElicitationResponded(ElicitationEntryId),ElicitationUpdated(ElicitationEntryId),}@@ -477,25 +483,24 @@ impl ElicitationStore {(id, response_rx)}- fn response_task<T>(- id: ElicitationEntryId,+ fn response_task(response_rx: oneshot::Receiver<acp::CreateElicitationResponse>,- cx: &mut Context<T>,- emit_responded: impl FnOnce(&mut T, &mut Context<T>, ElicitationEntryId) + 'static,- ) -> Task<acp::CreateElicitationResponse>- where- T: 'static,- {- cx.spawn(async move |this, cx| {- let response = response_rx.await.unwrap_or_else(|oneshot::Canceled| {+ cx: &App,+ ) -> Task<acp::CreateElicitationResponse> {+ cx.foreground_executor().spawn(async move {+ response_rx.await.unwrap_or_else(|oneshot::Canceled| {acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel)- });- this.update(cx, |this, cx| emit_responded(this, cx, id))- .ok();- response+ })})}+ fn emit_change(id: ElicitationEntryId, change: ElicitationChange, cx: &mut Context<Self>) {+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(id.clone()));+ if matches!(change, ElicitationChange::Responded) {+ cx.emit(ElicitationStoreEvent::ElicitationResponded(id));+ }+ }+fn respond_to_elicitation_entry(elicitation: &mut Elicitation,response: acp::CreateElicitationResponse,@@ -509,7 +514,9 @@ impl ElicitationStore {) else {return false;};- respond_tx.send(response).ok();+ if respond_tx.send(response).is_err() {+ log::debug!("Elicitation waiter closed before its response was delivered");+ }true}@@ -527,28 +534,27 @@ impl ElicitationStore {}}- fn cancel_elicitation_entry(- elicitation: &mut Elicitation,- cancel_accepted_url_elicitations: bool,- ) -> bool {+ fn cancel_elicitation_entry(elicitation: &mut Elicitation) -> Option<ElicitationChange> {match mem::replace(&mut elicitation.status, ElicitationStatus::Canceled) {ElicitationStatus::Pending { respond_tx } => {- respond_tx+ if respond_tx.send(acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel,))- .ok();- true+ .is_err()+ {+ log::debug!("Elicitation waiter closed before cancellation was delivered");+ }+ Some(ElicitationChange::Responded)}ElicitationStatus::Accepted- if cancel_accepted_url_elicitations- && matches!(&elicitation.request.mode, acp::ElicitationMode::Url(_)) =>+ if matches!(&elicitation.request.mode, acp::ElicitationMode::Url(_)) =>{- true+ Some(ElicitationChange::Updated)}previous_status => {elicitation.status = previous_status;- false+ None}}}@@ -571,15 +577,9 @@ impl ElicitationStore {Self::complete_url_elicitation_entry(elicitation)}- fn cancel_elicitation_by_id(- &mut self,- id: &ElicitationEntryId,- cancel_accepted_url_elicitations: bool,- ) -> bool {- let Some((_, elicitation)) = self.elicitation_mut(id) else {- return false;- };- Self::cancel_elicitation_entry(elicitation, cancel_accepted_url_elicitations)+ fn cancel_elicitation_by_id(&mut self, id: &ElicitationEntryId) -> Option<ElicitationChange> {+ let (_, elicitation) = self.elicitation_mut(id)?;+ Self::cancel_elicitation_entry(elicitation)}pub fn request_elicitation(@@ -601,11 +601,7 @@ impl ElicitationStore {cx.emit(ElicitationStoreEvent::ElicitationRequested(id.clone()));cx.notify();- let task = Self::response_task(id.clone(), response_rx, cx, |_store, cx, id| {- cx.emit(ElicitationStoreEvent::ElicitationResponded(id));- cx.notify();- });-+ let task = Self::response_task(response_rx, cx);Ok((id, task))}@@ -619,7 +615,7 @@ impl ElicitationStore {return;}- cx.emit(ElicitationStoreEvent::ElicitationUpdated(id.clone()));+ Self::emit_change(id.clone(), ElicitationChange::Responded, cx);cx.notify();}@@ -640,27 +636,26 @@ impl ElicitationStore {}pub fn cancel_elicitation(&mut self, id: &ElicitationEntryId, cx: &mut Context<Self>) {- if !self.cancel_elicitation_by_id(id, true) {+ let Some(change) = self.cancel_elicitation_by_id(id) else {return;- }+ };- cx.emit(ElicitationStoreEvent::ElicitationUpdated(id.clone()));+ Self::emit_change(id.clone(), change, cx);cx.notify();}pub fn cancel_all(&mut self, cx: &mut Context<Self>) {- let canceled_ids = self.cancel_pending(|_| true);- for id in canceled_ids {- cx.emit(ElicitationStoreEvent::ElicitationUpdated(id));+ for (id, change) in self.cancel_pending(|_| true) {+ Self::emit_change(id, change, cx);}cx.notify();}pub fn clear(&mut self, cx: &mut Context<Self>) {- let canceled_ids = self.cancel_pending(|_| true);+ let changes = self.cancel_pending(|_| true);self.elicitations.clear();- for id in canceled_ids {- cx.emit(ElicitationStoreEvent::ElicitationUpdated(id));+ for (id, change) in changes {+ Self::emit_change(id, change, cx);}cx.notify();}@@ -690,14 +685,14 @@ impl ElicitationStore {}pub fn cancel_request(&mut self, request_id: &acp::RequestId, cx: &mut Context<Self>) {- let canceled_ids = self.cancel_pending(|elicitation| {+ let changes = self.cancel_pending(|elicitation| {matches!(elicitation.request.scope(),acp::ElicitationScope::Request(scope) if &scope.request_id == request_id)});- for id in canceled_ids {- cx.emit(ElicitationStoreEvent::ElicitationUpdated(id));+ for (id, change) in changes {+ Self::emit_change(id, change, cx);}cx.notify();}@@ -740,14 +735,16 @@ impl ElicitationStore {fn cancel_pending(&mut self,mut should_cancel: impl FnMut(&Elicitation) -> bool,- ) -> Vec<ElicitationEntryId> {- let mut canceled_ids = Vec::new();+ ) -> Vec<(ElicitationEntryId, ElicitationChange)> {+ let mut changes = Vec::new();for elicitation in &mut self.elicitations {- if should_cancel(elicitation) && Self::cancel_elicitation_entry(elicitation, true) {- canceled_ids.push(elicitation.id.clone());+ if should_cancel(elicitation)+ && let Some(change) = Self::cancel_elicitation_entry(elicitation)+ {+ changes.push((elicitation.id.clone(), change));}}- canceled_ids+ changes}}@@ -2348,6 +2345,7 @@ pub enum AcpThreadEvent {ToolAuthorizationRequested(acp::ToolCallId),ToolAuthorizationReceived(acp::ToolCallId),ElicitationRequested(ElicitationEntryId),+ /// The request left `Pending`; this does not imply delivery to its response waiter.ElicitationResponded(ElicitationEntryId),Retry(RetryStatus),SubagentSpawned(acp::SessionId),@@ -3795,14 +3793,22 @@ impl AcpThread {self.push_entry(AgentThreadEntry::Elicitation(id.clone()), cx);cx.emit(AcpThreadEvent::ElicitationRequested(id.clone()));- let task =- ElicitationStore::response_task(id.clone(), response_rx, cx, |_thread, cx, id| {- cx.emit(AcpThreadEvent::ElicitationResponded(id))- });-+ let task = ElicitationStore::response_task(response_rx, cx);Ok((id, task))}+ fn emit_elicitation_change(+ entry_index: usize,+ id: &ElicitationEntryId,+ change: ElicitationChange,+ cx: &mut Context<Self>,+ ) {+ cx.emit(AcpThreadEvent::EntryUpdated(entry_index));+ if matches!(change, ElicitationChange::Responded) {+ cx.emit(AcpThreadEvent::ElicitationResponded(id.clone()));+ }+ }+pub fn respond_to_elicitation(&mut self,id: &ElicitationEntryId,@@ -3816,7 +3822,7 @@ impl AcpThread {return;}- cx.emit(AcpThreadEvent::EntryUpdated(ix));+ Self::emit_elicitation_change(ix, id, ElicitationChange::Responded, cx);}pub fn complete_url_elicitation(@@ -3844,11 +3850,11 @@ impl AcpThread {let Some(ix) = self.elicitation_entry_ix(id) else {return;};- if !self.elicitations.cancel_elicitation_by_id(id, true) {+ let Some(change) = self.elicitations.cancel_elicitation_by_id(id) else {return;- }+ };- cx.emit(AcpThreadEvent::EntryUpdated(ix));+ Self::emit_elicitation_change(ix, id, change, cx);}fn elicitation_entry_ix(&self, id: &ElicitationEntryId) -> Option<usize> {@@ -4316,11 +4322,8 @@ impl AcpThread {let Some(AgentThreadEntry::Elicitation(elicitation_id)) = self.entries.get(ix) else {continue;};- if self- .elicitations- .cancel_elicitation_by_id(elicitation_id, true)- {- cx.emit(AcpThreadEvent::EntryUpdated(ix));+ if let Some(change) = self.elicitations.cancel_elicitation_by_id(elicitation_id) {+ Self::emit_elicitation_change(ix, elicitation_id, change, cx);}}}@@ -9470,6 +9473,15 @@ mod tests {init_test(cx);enable_acp_beta(cx);let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));+ let responded_ids = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ let responded_ids = responded_ids.clone();+ cx.subscribe(&store, move |_, event, _| {+ if let ElicitationStoreEvent::ElicitationResponded(id) = event {+ responded_ids.borrow_mut().push(id.clone());+ }+ })+ });let response_task = store.update(cx, |store, cx| {store@@ -9512,6 +9524,10 @@ mod tests {});assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);+ assert_eq!(+ responded_ids.borrow().as_slice(),+ std::slice::from_ref(&elicitation_id)+ );store.read_with(cx, |store, _| {let Some((_, elicitation)) = store.elicitation(&elicitation_id) else {panic!("missing elicitation entry");@@ -9760,6 +9776,53 @@ mod tests {});}+ #[gpui::test]+ async fn test_request_elicitation_store_emits_response_when_waiter_is_dropped(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));+ let responded_ids = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ let responded_ids = responded_ids.clone();+ cx.subscribe(&store, move |_, event, _| {+ if let ElicitationStoreEvent::ElicitationResponded(id) = event {+ responded_ids.borrow_mut().push(id.clone());+ }+ })+ });++ let request_id = acp::RequestId::Number(1);+ let (elicitation_id, response_task) = store.update(cx, |store, cx| {+ store+ .request_elicitation_with_id(+ acp::CreateElicitationRequest::new(+ acp::ElicitationFormMode::new(+ acp::ElicitationRequestScope::new(request_id.clone()),+ acp::ElicitationSchema::new().string("name", true),+ ),+ "Provide a name",+ ),+ cx,+ )+ .expect("elicitation should succeed")+ });+ drop(response_task);+ cx.run_until_parked();++ store.update(cx, |store, cx| {+ store.cancel_request(&request_id, cx);+ });+ assert_eq!(+ responded_ids.borrow().as_slice(),+ std::slice::from_ref(&elicitation_id)+ );+ store.read_with(cx, |store, _| {+ let (_, elicitation) = store.elicitation(&elicitation_id).expect("elicitation");+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));+ });+ }+#[gpui::test]async fn test_request_elicitation_store_cancel_all_resolves_cancel(cx: &mut TestAppContext) {init_test(cx);@@ -10043,6 +10106,15 @@ mod tests {enable_acp_beta(cx);let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));let url_elicitation_id = acp::ElicitationId::new("url-1");+ let responded_ids = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ let responded_ids = responded_ids.clone();+ cx.subscribe(&store, move |_, event, _| {+ if let ElicitationStoreEvent::ElicitationResponded(id) = event {+ responded_ids.borrow_mut().push(id.clone());+ }+ })+ });let response_task = store.update(cx, |store, cx| {store@@ -10083,9 +10155,17 @@ mod tests {response_task.await.action,acp::ElicitationAction::Accept(_)));+ assert_eq!(+ responded_ids.borrow().as_slice(),+ std::slice::from_ref(&entry_id)+ );store.update(cx, |store, cx| {store.cancel_all(cx);});+ assert_eq!(+ responded_ids.borrow().as_slice(),+ std::slice::from_ref(&entry_id)+ );store.read_with(cx, |store, _| {let Some((_, elicitation)) = store.elicitation(&entry_id) else {panic!("missing elicitation entry");@@ -12639,6 +12719,45 @@ mod tests {assert_eq!(cx.active_idle_sleep_preventions(), 0);}+ #[gpui::test]+ async fn test_cancel_elicitation_after_waiter_drops_resumes_idle_sleep_prevention(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let (complete, request) = start_test_turn(&thread, cx);+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 1);++ let (elicitation_id, response) = request_test_form_elicitation(&thread, cx);+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ drop(response);+ cx.run_until_parked();++ thread.update(cx, |thread, cx| {+ thread.cancel_elicitation(&elicitation_id, cx)+ });+ cx.run_until_parked();+ thread.read_with(cx, |thread, _| {+ let (_, elicitation) = thread.elicitation(&elicitation_id).expect("elicitation");+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));+ assert!(!thread.is_waiting_for_confirmation());+ assert_eq!(thread.status(), ThreadStatus::Generating);+ });+ assert_eq!(+ cx.active_idle_sleep_preventions(),+ 1,+ "cancelling the request must refresh generation state even without a response waiter"+ );++ complete+ .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))+ .expect("turn should still be running");+ request.await.expect("turn should complete");+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ }+#[gpui::test]async fn test_idle_sleep_prevention_resumes_after_form_elicitation(cx: &mut TestAppContext) {init_test(cx);