Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent_servers: Order ACP v1 load responses and treat replayed subagent state as history (#66064)
Ben Brandtb0cac499da46
diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rsindex 670a81f39b4..d53fb5c8204 100644--- a/crates/agent_servers/src/acp/v1.rs+++ b/crates/agent_servers/src/acp/v1.rs@@ -17,7 +17,8 @@ use agent_client_protocol::schema::{v2 as acp_v2,};use agent_client_protocol::{- Agent, Builder, Client, ConnectionTo, HandleDispatchFrom, Lines, Responder, V2Builder,+ Agent, Builder, Client, ConnectionTo, HandleDispatchFrom, JsonRpcRequest, Lines, Responder,+ V2Builder,};use anyhow::anyhow;use async_channel;@@ -176,6 +177,38 @@ struct SessionConfigResponse {config_options: Option<Vec<acp::SessionConfigOption>>,}+/// Sends `request` and returns its response. Once the response arrives, the agent's later+/// messages wait until `applied` resolves, so none of them is applied before the caller has+/// applied the response. The subagents RFD makes a replaying load's response a boundary:+/// replayed subagent state before it is history, and current state after it is not.+async fn ordered_response<Request: JsonRpcRequest>(+ connection: &ConnectionTo<Agent>,+ request: Request,+ applied: futures::channel::oneshot::Receiver<()>,+) -> Result<Request::Response> {+ let (sender, received) = futures::channel::oneshot::channel();+ let request = connection.prepare_request(request);+ let cancellation = request.cancellation_handle();+ request+ .on_receiving_result(async move |result| {+ if sender.send(result).is_ok() {+ // The caller releases by sending or by dropping its sender.+ applied.await.ok();+ }+ Ok(())+ })+ .map_err(map_acp_error)?;+ // As with `block_task`, dropping the caller cancels the request.+ let guard = util::defer(move || {+ cancellation.cancel().log_err();+ });+ let response = received+ .await+ .context("ACP response callback was dropped")?;+ guard.abort();+ response.map_err(map_acp_error)+}+impl ConfigOptions {async fn set_config_option(&self,@@ -860,16 +893,21 @@ impl AcpConnection {self.agent_capabilities.session_capabilities.close.is_some()}+ /// `rpc_call` gets a receiver that resolves once its response has been applied, and+ /// holds the agent's later messages until then (see `ordered_response`). With+ /// `replays_history`, the response ends a history replay.fn open_or_create_session(self: Rc<Self>,session_id: acp_v2::SessionId,project: Entity<Project>,work_dirs: PathList,title: Option<SharedString>,+ replays_history: bool,rpc_call: impl FnOnce(ConnectionTo<Agent>,acp_v2::SessionId,SessionDirectories,+ futures::channel::oneshot::Receiver<()>,)-> futures::future::LocalBoxFuture<'static, Result<SessionConfigResponse>>+ 'static,@@ -892,7 +930,15 @@ impl AcpConnection {return cx.spawn(async move |cx| {task.await.log_err();cx.update(|cx| {- self.open_or_create_session(session_id, project, work_dirs, title, rpc_call, cx)+ self.open_or_create_session(+ session_id,+ project,+ work_dirs,+ title,+ replays_history,+ rpc_call,+ cx,+ )}).await});@@ -909,8 +955,15 @@ impl AcpConnection {}// Entity-release effects may not have run yet when a view reopens.self.release_session(session_id.clone(), thread, cx);- return self- .open_or_create_session(session_id, project, work_dirs, title, rpc_call, cx);+ return self.open_or_create_session(+ session_id,+ project,+ work_dirs,+ title,+ replays_history,+ rpc_call,+ cx,+ );}let directories = match self.session_directories_from_work_dirs(&work_dirs) {@@ -944,7 +997,7 @@ impl AcpConnection {let connection = self.connection.clone();let dispatch_tx = self.dispatch_tx.clone();let supports_close = self.agent_supports_session_close();- async move |_cx| {+ async move |cx| {if thread.upgrade().is_none() {if let Some(this) = this.upgrade() {this.remove_session(&session_id, thread.entity_id());@@ -953,8 +1006,10 @@ impl AcpConnection {return Ok(());}+ let (response_applied, applied) = futures::channel::oneshot::channel();let response =- rpc_call(connection.clone(), session_id.clone(), directories).await;+ rpc_call(connection.clone(), session_id.clone(), directories, applied)+ .await;if response.is_err() {// Do not let replay from a failed load reach its replacement.drain_foreground_queue(&dispatch_tx).await.log_err();@@ -974,7 +1029,7 @@ impl AcpConnection {}};- if let Some(_thread) = thread.upgrade() {+ if let Some(loaded_thread) = thread.upgrade() {{let mut sessions = connection_state.sessions.borrow_mut();let Some(session) = sessions@@ -990,10 +1045,17 @@ impl AcpConnection {session.session_modes = modes;session.config_options = config_options;}+ if replays_history {+ loaded_thread.update(cx, |thread, cx| {+ thread.invalidate_replayed_subagent_state(cx)+ });+ }connection_state.remove_pending_session(&session_id, thread.entity_id());return Ok(());}+ // Closing needs the agent's response, so its later messages must flow.+ drop(response_applied);drop(connection_state);let result = close_session_and_drain(&connection,@@ -1432,15 +1494,15 @@ impl AgentConnection for AcpConnection {project,work_dirs,title,- move |connection, session_id, directories| {+ true,+ move |connection, session_id, directories, applied| {Box::pin(async move {- let response = connection- .send_request(- directories.into_load_session_request(session_id.clone(), mcp_servers),- )- .block_task()- .await- .map_err(map_acp_error)?;+ let response = ordered_response(+ &connection,+ directories.into_load_session_request(session_id.clone(), mcp_servers),+ applied,+ )+ .await?;Ok(SessionConfigResponse {modes: response.modes,config_options: response.config_options,@@ -1476,16 +1538,15 @@ impl AgentConnection for AcpConnection {project,work_dirs,title,- move |connection, session_id, directories| {+ false,+ move |connection, session_id, directories, applied| {Box::pin(async move {- let response = connection- .send_request(- directories- .into_resume_session_request(session_id.clone(), mcp_servers),- )- .block_task()- .await- .map_err(map_acp_error)?;+ let response = ordered_response(+ &connection,+ directories.into_resume_session_request(session_id.clone(), mcp_servers),+ applied,+ )+ .await?;Ok(SessionConfigResponse {modes: response.modes,config_options: response.config_options,@@ -6307,9 +6368,10 @@ mod tests {project,PathList::new(&[std::path::Path::new("/a")]),None,+ false,{let returned = returned.clone();- |_, _, _| {+ |_, _, _, _| {async move {Ok(SessionConfigResponse {modes: None,@@ -6659,7 +6721,8 @@ mod tests {project.clone(),PathList::new(&[std::path::Path::new("/a")]),None,- move |_, _, _| {+ false,+ move |_, _, _, _| {async move {Ok(SessionConfigResponse {modes: None,@@ -6707,7 +6770,8 @@ mod tests {project,PathList::new(&[std::path::Path::new("/a")]),None,- move |_, _, _| {+ false,+ move |_, _, _, _| {async move {Ok(SessionConfigResponse {modes: None,@@ -7235,8 +7299,14 @@ exit 7Arc<std::sync::Mutex<Option<async_channel::Receiver<()>>>>,Task<anyhow::Result<()>>,) {- connect_fake_agent_with_new_session_behavior(close_session_gate, agent_sender, None, cx)- .await+ connect_fake_agent_with_new_session_behavior(+ close_session_gate,+ agent_sender,+ None,+ None,+ cx,+ )+ .await}struct NewSessionTestBehavior {@@ -7245,10 +7315,17 @@ exit 7updates: Vec<acp::SessionUpdate>,}+ /// A client that accepts v1 subagent updates, as once it advertises them, talking to an+ /// agent that sends `after_load_response` as soon as it answers a load.+ struct SubagentLoadTestBehavior {+ after_load_response: Vec<acp::SessionUpdate>,+ }+async fn connect_fake_agent_with_new_session_behavior(close_session_gate: Option<async_channel::Receiver<()>>,agent_sender: Option<futures::channel::oneshot::Sender<ConnectionTo<Client>>>,new_session_behavior: Option<NewSessionTestBehavior>,+ subagent_load_behavior: Option<SubagentLoadTestBehavior>,cx: &mut gpui::TestAppContext,) -> (Rc<AcpConnection>,@@ -7276,6 +7353,12 @@ exit 7Arc::new(std::sync::Mutex::new(None));let close_session_gate = Arc::new(std::sync::Mutex::new(close_session_gate));let new_session_behavior = Arc::new(Mutex::new(new_session_behavior));+ let accepts_subagent_updates = subagent_load_behavior.is_some();+ let after_load_response = Arc::new(std::sync::Mutex::new(+ subagent_load_behavior+ .map(|behavior| behavior.after_load_response)+ .unwrap_or_default(),+ ));let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();@@ -7359,6 +7442,7 @@ exit 7let load_count = load_count.clone();let load_session_updates = load_session_updates.clone();let load_session_gate = load_session_gate.clone();+ let after_load_response = after_load_response.clone();async move |req: acp::LoadSessionRequest, responder, cx| {load_count.fetch_add(1, Ordering::SeqCst);@@ -7388,7 +7472,19 @@ exit 7gate.recv().await.ok();}- responder.respond(acp::LoadSessionResponse::new())+ responder.respond(acp::LoadSessionResponse::new())?;+ let updates = std::mem::take(+ &mut *after_load_response+ .lock()+ .expect("after_load_response mutex poisoned"),+ );+ for update in updates {+ cx.send_notification(acp::SessionNotification::new(+ req.session_id.clone(),+ update,+ ))?;+ }+ Ok(())}},agent_client_protocol::on_receive_request!(),@@ -7464,7 +7560,7 @@ exit 7request_elicitations: request_elicitations.clone(),active_request_scopes: None,pending_session_updates: None,- accepts_subagent_updates: false,+ accepts_subagent_updates,};// `TestAppContext::spawn` hands out an `AsyncApp` by value, whereas the// production path uses `Context::spawn` which hands out `&mut AsyncApp`.@@ -8175,6 +8271,7 @@ exit 7acp::ContentChunk::new("First update immediately after creation".into()),)],}),+ None,cx,).await;@@ -8239,6 +8336,7 @@ exit 7respond: response_released,updates: Vec::new(),}),+ None,cx,).await;@@ -8298,6 +8396,7 @@ exit 7respond: response_released,updates: Vec::new(),}),+ None,cx,).await;@@ -8350,6 +8449,7 @@ exit 7respond: response_released,updates: Vec::new(),}),+ None,cx,).await;@@ -8401,6 +8501,7 @@ exit 7respond: response_released,updates: Vec::new(),}),+ None,cx,).await;@@ -8836,6 +8937,101 @@ exit 7);}+ #[gpui::test(iterations = 10)]+ async fn test_load_treats_replayed_subagent_state_as_history(cx: &mut gpui::TestAppContext) {+ let running = || acp::StateUpdate::Running(acp::RunningStateUpdate::new());+ let cancellable = || {+ acp::SubagentSessionCapabilities::new().cancel(acp::SessionCancelCapabilities::new())+ };+ let current_live_state = || {+ acp::SessionUpdate::SubagentUpdate(+ acp::SubagentUpdate::new("live")+ .capabilities(cancellable())+ .state(running()),+ )+ };+ let (connection, project, _, _, load_session_updates, _, _keep_agent_alive) =+ connect_fake_agent_with_new_session_behavior(+ None,+ None,+ None,+ Some(SubagentLoadTestBehavior {+ after_load_response: vec![current_live_state()],+ }),+ cx,+ )+ .await;+ *load_session_updates+ .lock()+ .expect("load_session_updates mutex poisoned") = vec![+ acp::SessionUpdate::SubagentUpdate(+ acp::SubagentUpdate::new("stale")+ .title("Worker")+ .capabilities(cancellable())+ .state(running()),+ ),+ current_live_state(),+ acp::SessionUpdate::SubagentUpdate(+ acp::SubagentUpdate::new("finished").state(running()),+ ),+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("finished").state(+ acp::StateUpdate::Idle(+ acp::IdleStateUpdate::new().stop_reason(acp::IdleStopReason::Cancelled),+ ),+ )),+ ];++ let thread = cx+ .update(|cx| {+ connection.clone().load_session(+ acp_v2::SessionId::new("parent"),+ project.clone(),+ PathList::new(&[std::path::Path::new("/a")]),+ None,+ cx,+ )+ })+ .await+ .expect("load_session failed");+ cx.run_until_parked();++ let subagent = |session_id: &str, cx: &mut gpui::TestAppContext| {+ thread+ .read_with(cx, |thread, _| thread.subagent(&session_id.into()).cloned())+ .expect("replayed subagent")+ };+ subagent("stale", cx).read_with(cx, |stale, _| {+ let association = stale.subagent_association().expect("subagent");+ assert_eq!(association.title.as_deref(), Some("Worker"));+ assert!(!association.can_cancel, "a replayed grant is history");+ assert_eq!(+ stale.foreground_activity(),+ acp_thread::ForegroundActivity::Unconfirmed,+ "replayed activity is history"+ );+ });+ subagent("finished", cx).read_with(cx, |finished, _| {+ assert!(+ matches!(+ finished.foreground_state(),+ Some(acp_v2::StateUpdate::Idle(idle))+ if idle.stop_reason == Some(acp_v2::StopReason::Cancelled)+ ),+ "a replayed outcome confirms no activity, so it stays"+ );+ });+ subagent("live", cx).read_with(cx, |live, _| {+ assert!(+ live.subagent_association().expect("subagent").can_cancel,+ "state sent right after the response is current"+ );+ assert_eq!(+ live.foreground_activity(),+ acp_thread::ForegroundActivity::Running+ );+ });+ }+#[gpui::test]async fn test_load_initializes_config_before_draining_queued_updates(cx: &mut gpui::TestAppContext,@@ -8855,10 +9051,11 @@ exit 7project,PathList::new(&[std::path::Path::new("/a")]),None,+ false,{let dispatch_tx = connection.dispatch_tx.clone();let updated_options = updated_options.clone();- move |_, session_id, _| {+ move |_, session_id, _, _| {async move {// Later notifications can already be queued when the response is ready.enqueue_notification(@@ -9223,9 +9420,10 @@ exit 7project.clone(),work_dirs.clone(),None,+ false,{let dispatch_tx = connection.dispatch_tx.clone();- move |_, session_id, _| {+ move |_, session_id, _, _| {async move {response_rx.await?;enqueue_notification(