Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent_servers: Preserve ACP updates before session creation (#65822)
Ben Brandt32f70854ff94
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex e915a2e66c0..907f9f35ec1 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -8,7 +8,7 @@ mod v2;use debug_log::AcpDebugLog;pub use debug_log::{AcpDebugMessage, AcpDebugMessageContent, AcpDebugMessageDirection};-use session_updates::{InboundSessionNotification, InboundSessionUpdate};+use session_updates::{InboundSessionNotification, InboundSessionUpdate, PendingSessionUpdates};pub use terminal_updates::{DecodedTerminalNotification, DecodedTerminalUpdate};#[cfg(any(test, feature = "test-support"))]pub use v1::test_support;@@ -136,6 +136,7 @@ impl<T> FlattenAcpResult<T> for Result<Result<T, acp::Error>, anyhow::Error> {/// Holds state needed by foreground work dispatched from background handler closures.struct ClientContext {sessions: Rc<RefCell<HashMap<acp_v2::SessionId, AcpSession>>>,+ pending_session_updates: Option<Rc<RefCell<PendingSessionUpdates>>>,session_list: Rc<RefCell<Option<Rc<AcpSessionList>>>>,request_elicitations: Entity<ElicitationStore>,// Legacy and ingress-only contexts do not track caller ownership of outgoing RPCs.@@ -179,6 +180,9 @@ impl ForegroundWorkItem for ClientDisconnectWork {if let Some(scopes) = &context.active_request_scopes {scopes.borrow_mut().clear();}+ if let Some(pending) = &context.pending_session_updates {+ pending.borrow_mut().clear();+ }let threads = context.sessions.borrow()@@ -355,16 +359,45 @@ pub struct AcpSession {/// Builds a v2 terminal-notification handler without selecting it for application connections./// Other session updates remain unclaimed so later inbound handlers can process them.pub fn v2_terminal_client_builder(- dispatch: impl FnMut(DecodedTerminalNotification) -> Result<(), agent_client_protocol::Error>+ mut dispatch: impl FnMut(DecodedTerminalNotification) -> Result<(), agent_client_protocol::Error>+ Send+ 'static,) -> V2Builder<Client, impl HandleDispatchFrom<Agent>> {- with_v2_terminal_notifications(Client.v2(), dispatch)+ with_v2_terminal_notifications(Client.v2(), false, move |notification, _| {+ dispatch(notification)+ })+}++struct NotificationByteCounter(usize);++impl std::io::Write for NotificationByteCounter {+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {+ self.0 = self.0.saturating_add(bytes.len());+ Ok(bytes.len())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}++fn notification_size(+ notification: &impl serde::Serialize,+) -> Result<usize, agent_client_protocol::Error> {+ let mut counter = NotificationByteCounter(0);+ serde_json::to_writer(&mut counter, notification).map_err(|_| {+ agent_client_protocol::Error::internal_error().data("Failed to size ACP session update")+ })?;+ Ok(counter.0)}fn with_v2_terminal_notifications<Handler: HandleDispatchFrom<Agent>>(builder: V2Builder<Client, Handler>,- mut dispatch: impl FnMut(DecodedTerminalNotification) -> Result<(), agent_client_protocol::Error>+ measure_payload: bool,+ mut dispatch: impl FnMut(+ DecodedTerminalNotification,+ usize,+ ) -> Result<(), agent_client_protocol::Error>+ Send+ 'static,) -> V2Builder<Client, impl HandleDispatchFrom<Agent>> {@@ -384,6 +417,11 @@ fn with_v2_terminal_notifications<Handler: HandleDispatchFrom<Agent>>(});}let notification = terminal_updates::parse_terminal_notification(&message)?;+ let encoded_bytes = if measure_payload {+ notification_size(¬ification)?+ } else {+ 0+ };let decoded = terminal_updates::decode_terminal_notification(notification).map_err(|error| {agent_client_protocol::Error::invalid_params().data(format!("{error:#}"))@@ -392,7 +430,7 @@ fn with_v2_terminal_notifications<Handler: HandleDispatchFrom<Agent>>(agent_client_protocol::Error::internal_error().data("Terminal notification was not decoded")})?;- dispatch(decoded)?;+ dispatch(decoded, encoded_bytes)?;Ok(Handled::Yes)},agent_client_protocol::on_receive_notification!(),@@ -401,13 +439,17 @@ fn with_v2_terminal_notifications<Handler: HandleDispatchFrom<Agent>>(fn with_v2_session_notifications<Handler: HandleDispatchFrom<Agent>>(builder: V2Builder<Client, Handler>,- mut dispatch: impl FnMut(InboundSessionNotification) -> Result<(), agent_client_protocol::Error>+ mut dispatch: impl FnMut(+ InboundSessionNotification,+ usize,+ ) -> Result<(), agent_client_protocol::Error>+ Send+ 'static,) -> V2Builder<Client, impl HandleDispatchFrom<Agent>> {builder.on_receive_notification(async move |notification: acp_v2::UpdateSessionNotification,connection: V2ConnectionTo<Agent>| {+ let encoded_bytes = notification_size(¬ification)?;let notification = match InboundSessionNotification::try_from(notification) {Ok(notification) => notification,Err(notification) => {@@ -417,7 +459,7 @@ fn with_v2_session_notifications<Handler: HandleDispatchFrom<Agent>>(});}};- dispatch(notification)?;+ dispatch(notification, encoded_bytes)?;Ok(Handled::Yes)},agent_client_protocol::on_receive_notification!(),@@ -430,18 +472,18 @@ fn with_v2_client_ingress<Handler: HandleDispatchFrom<Agent>>() -> V2Builder<Client, impl HandleDispatchFrom<Agent>> {let dispatch = {let dispatch_sender = dispatch_sender.clone();- move |notification| {+ move |notification, encoded_bytes| {enqueue_notification(&dispatch_sender,- notification,- handle_v2_session_notification,+ (notification, encoded_bytes),+ route_v2_session_notification,);Ok(())}};- let builder = with_v2_terminal_notifications(builder, {+ let builder = with_v2_terminal_notifications(builder, true, {let dispatch = dispatch.clone();- move |notification| dispatch(notification.into())+ move |notification, encoded_bytes| dispatch(notification.into(), encoded_bytes)});with_v2_session_notifications(builder, dispatch).on_receive_request(@@ -556,6 +598,70 @@ fn session_thread(.ok_or_else(|| acp::Error::internal_error().data(format!("unknown session: {session_id}")))}+fn route_v2_session_notification(+ (notification, encoded_bytes): (InboundSessionNotification, usize),+ cx: &mut AsyncApp,+ context: &ClientContext,+) {+ let registered = context+ .sessions+ .borrow()+ .contains_key(¬ification.session_id);+ let notification = if !registered && let Some(pending) = &context.pending_session_updates {+ match pending.borrow_mut().stage(notification, encoded_bytes) {+ None => return,+ Some(notification) => notification,+ }+ } else {+ notification+ };+ handle_v2_session_notification(notification, cx, context);+}++fn close_undelivered_session(+ (session_id, connection): (acp_v2::SessionId, V2ConnectionTo<Agent>),+ _cx: &mut AsyncApp,+ context: &ClientContext,+) {+ if let Some(pending) = &context.pending_session_updates {+ pending.borrow_mut().discard_session(&session_id);+ }+ if context.sessions.borrow().contains_key(&session_id) {+ return;+ }+ connection+ .prepare_request(acp_v2::CloseSessionRequest::new(session_id))+ .on_receiving_result(async move |result| {+ result.log_err();+ Ok(())+ })+ .log_err();+}++fn apply_v2_session_notification(+ notification: InboundSessionNotification,+ thread: &WeakEntity<AcpThread>,+ sessions: &RefCell<HashMap<acp_v2::SessionId, AcpSession>>,+ cx: &mut AsyncApp,+) -> Result<()> {+ if let InboundSessionUpdate::ConfigOptions(update) = ¬ification.update {+ let config_options = {+ let mut sessions = sessions.borrow_mut();+ let session = sessions+ .get_mut(¬ification.session_id)+ .filter(|session| session.thread.entity_id() == thread.entity_id())+ .context("Session was released or replaced before applying configuration")?;+ session+ .config_options+ .get_or_insert_with(|| ConfigOptions::new(Rc::new(RefCell::new(Vec::new()))))+ .clone()+ };+ *config_options.config_options.borrow_mut() = update.config_options.clone();+ config_options.tx.borrow_mut().send(()).log_err();+ }+ thread.update(cx, |thread, cx| notification.apply(thread, cx))?+}+fn handle_v2_session_notification(notification: InboundSessionNotification,cx: &mut AsyncApp,@@ -577,22 +683,7 @@ fn handle_v2_session_notification({session_list.send_info_update(notification.session_id.clone(), update.clone());}- if let InboundSessionUpdate::ConfigOptions(update) = ¬ification.update {- let config_options = {- let mut sessions = context.sessions.borrow_mut();- let Some(session) = sessions.get_mut(¬ification.session_id) else {- return;- };- session- .config_options- .get_or_insert_with(|| ConfigOptions::new(Rc::new(RefCell::new(Vec::new()))))- .clone()- };- *config_options.config_options.borrow_mut() = update.config_options.clone();- config_options.tx.borrow_mut().send(()).log_err();- }- thread- .update(cx, |thread, cx| notification.apply(thread, cx))+ apply_v2_session_notification(notification, &thread.downgrade(), &context.sessions, cx).log_err();}diff --git a/crates/agent_servers/src/acp/runtime.rs b/crates/agent_servers/src/acp/runtime.rsindex 84fefafa21f..70be35fd473 100644--- a/crates/agent_servers/src/acp/runtime.rs+++ b/crates/agent_servers/src/acp/runtime.rs@@ -205,6 +205,7 @@ mod tests {session_list: Rc::new(RefCell::new(None)),request_elicitations: store.clone(),active_request_scopes: None,+ pending_session_updates: None,};let (mut runtime, shutdown) = ClientRuntime::new(context, &mut cx.to_async());let (transport, peer) = agent_client_protocol::Channel::duplex();diff --git a/crates/agent_servers/src/acp/session_updates.rs b/crates/agent_servers/src/acp/session_updates.rsindex c22eb987750..6677913540a 100644--- a/crates/agent_servers/src/acp/session_updates.rs+++ b/crates/agent_servers/src/acp/session_updates.rs@@ -1,10 +1,147 @@use acp_thread::{AcpThread, MessageKind};use agent_client_protocol::schema::v2 as acp_v2;use anyhow::Result;+use collections::HashMap;use gpui::Context;+use std::collections::VecDeque;use super::terminal_updates::{DecodedTerminalNotification, DecodedTerminalUpdate};+pub(super) const MAX_PENDING_SESSION_UPDATES: usize = 1024;+const MAX_PENDING_SESSION_UPDATE_BYTES: usize = 16 * 1024 * 1024;++#[derive(Default)]+pub(super) struct PendingSessionUpdates {+ generation: u64,+ creations: HashMap<acp_v2::RequestId, PendingCreation>,+ updates: VecDeque<PendingUpdate>,+ encoded_bytes: usize,+}++struct PendingCreation {+ generation: u64,+ overflowed: bool,+}++struct PendingUpdate {+ generation: u64,+ encoded_bytes: usize,+ notification: InboundSessionNotification,+}++impl PendingSessionUpdates {+ #[cfg(test)]+ pub(super) fn counts(&self) -> (usize, usize, usize) {+ (self.creations.len(), self.updates.len(), self.encoded_bytes)+ }++ pub(super) fn begin(&mut self, request_id: acp_v2::RequestId) {+ let generation = self.generation.checked_add(1);+ if let Some(generation) = generation {+ self.generation = generation;+ }+ self.creations.insert(+ request_id,+ PendingCreation {+ generation: self.generation,+ overflowed: generation.is_none(),+ },+ );+ }++ pub(super) fn stage(+ &mut self,+ notification: InboundSessionNotification,+ encoded_bytes: usize,+ ) -> Option<InboundSessionNotification> {+ if !self.creations.values().any(|creation| !creation.overflowed) {+ return Some(notification);+ }+ if self.updates.len() >= MAX_PENDING_SESSION_UPDATES+ || encoded_bytes > MAX_PENDING_SESSION_UPDATE_BYTES.saturating_sub(self.encoded_bytes)+ {+ for creation in self.creations.values_mut() {+ creation.overflowed = true;+ }+ self.updates.clear();+ self.encoded_bytes = 0;+ log::warn!("ACP pre-response session update staging exceeded its limits");+ return None;+ }+ self.encoded_bytes += encoded_bytes;+ self.updates.push_back(PendingUpdate {+ generation: self.generation,+ encoded_bytes,+ notification,+ });+ None+ }++ pub(super) fn take(+ &mut self,+ request_id: &acp_v2::RequestId,+ session_id: &acp_v2::SessionId,+ ) -> Result<Vec<InboundSessionNotification>> {+ let creation = self+ .creations+ .remove(request_id)+ .ok_or_else(|| anyhow::anyhow!("Session creation is no longer pending"))?;+ if creation.overflowed {+ self.prune();+ anyhow::bail!("ACP pre-response session update staging exceeded its limits");+ }+ let mut notifications = Vec::new();+ // Session IDs correlate concurrent creations. The wire carries no request ID+ // on these notifications, so provisional ID reuse by the agent remains ambiguous.+ for update in std::mem::take(&mut self.updates) {+ if &update.notification.session_id == session_id+ && update.generation >= creation.generation+ {+ notifications.push(update.notification);+ } else {+ self.updates.push_back(update);+ }+ }+ self.prune();+ Ok(notifications)+ }++ pub(super) fn finish(&mut self, request_id: &acp_v2::RequestId) {+ self.creations.remove(request_id);+ self.prune();+ }++ pub(super) fn discard_session(&mut self, session_id: &acp_v2::SessionId) {+ self.updates+ .retain(|update| &update.notification.session_id != session_id);+ self.prune();+ }++ pub(super) fn clear(&mut self) {+ self.creations.clear();+ self.updates.clear();+ self.encoded_bytes = 0;+ }++ fn prune(&mut self) {+ let oldest = self+ .creations+ .values()+ .filter(|creation| !creation.overflowed)+ .map(|creation| creation.generation)+ .min();+ let mut encoded_bytes = 0;+ self.updates.retain(|update| {+ let keep = oldest.is_some_and(|oldest| update.generation >= oldest);+ if keep {+ encoded_bytes += update.encoded_bytes;+ }+ keep+ });+ self.encoded_bytes = encoded_bytes;+ }+}+#[derive(Debug)]pub struct InboundSessionNotification {pub session_id: acp_v2::SessionId,@@ -198,3 +335,86 @@ impl InboundSessionNotification {}}}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn request_id(value: i64) -> acp_v2::RequestId {+ serde_json::from_value(json!(value)).expect("request ID")+ }++ fn notification(session_id: &str, text: &str) -> InboundSessionNotification {+ acp_v2::UpdateSessionNotification::new(+ session_id,+ acp_v2::SessionUpdate::AgentMessage(+ acp_v2::AgentMessage::new(text).content(vec![text.into()]),+ ),+ )+ .try_into()+ .expect("supported notification")+ }++ #[test]+ fn later_creation_does_not_adopt_an_older_prefix() {+ let mut pending = PendingSessionUpdates::default();+ pending.begin(request_id(1));+ assert!(pending.stage(notification("reused", "old"), 10).is_none());+ pending.begin(request_id(2));+ assert!(+ pending+ .take(&request_id(2), &"reused".into())+ .expect("new creation")+ .is_empty()+ );+ pending.finish(&request_id(1));+ assert_eq!(pending.counts(), (0, 0, 0));+ assert!(+ pending+ .stage(notification("unknown", "no owner"), 10)+ .is_some()+ );+ }++ #[test]+ fn byte_limit_is_bounded_and_does_not_poison_later_creations() {+ let wire = acp_v2::UpdateSessionNotification::new(+ "session",+ acp_v2::SessionUpdate::AgentMessage(+ acp_v2::AgentMessage::new("message")+ .content(vec!["unicode é and \"quotes\"".into()]),+ ),+ );+ assert_eq!(+ super::super::notification_size(&wire).expect("counted"),+ serde_json::to_vec(&wire).expect("serialized").len()+ );+ let mut pending = PendingSessionUpdates::default();+ pending.begin(request_id(1));+ assert!(+ pending+ .stage(+ notification("first", "entry"),+ MAX_PENDING_SESSION_UPDATE_BYTES+ )+ .is_none()+ );+ assert!(+ pending+ .stage(notification("first", "overflow"), 1)+ .is_none()+ );+ pending.begin(request_id(2));+ assert!(pending.stage(notification("second", "fresh"), 3).is_none());+ assert!(pending.take(&request_id(1), &"first".into()).is_err());+ assert_eq!(+ pending+ .take(&request_id(2), &"second".into())+ .expect("fresh creation")+ .len(),+ 1+ );+ assert_eq!(pending.counts(), (0, 0, 0));+ }+}diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rsindex cd7e6a5b92d..61496557be1 100644--- a/crates/agent_servers/src/acp/v1.rs+++ b/crates/agent_servers/src/acp/v1.rs@@ -532,6 +532,7 @@ impl AcpConnection {session_list: client_session_list.clone(),request_elicitations: request_elicitations.clone(),active_request_scopes: None,+ pending_session_updates: None,};let (mut runtime, shutdown) = runtime::ClientRuntime::new(dispatch_context, cx);let dispatch_tx = runtime.sender();@@ -2186,6 +2187,7 @@ pub mod test_support {session_list: client_session_list.clone(),request_elicitations: request_elicitations.clone(),active_request_scopes: None,+ pending_session_updates: None,};let dispatch_task = cx.spawn({let mut dispatch_rx = dispatch_rx;@@ -7379,6 +7381,7 @@ exit 7session_list: client_session_list.clone(),request_elicitations: request_elicitations.clone(),active_request_scopes: None,+ pending_session_updates: None,};// `TestAppContext::spawn` hands out an `AsyncApp` by value, whereas the// production path uses `Context::spawn` which hands out `&mut AsyncApp`.@@ -7761,6 +7764,7 @@ exit 7session_list: Rc::new(RefCell::new(None)),request_elicitations: store.clone(),active_request_scopes: None,+ pending_session_updates: None,};let (dispatch_tx, mut dispatch_rx) = mpsc::unbounded::<ForegroundWork>();let dispatch_task = cx.spawn(move |mut cx| async move {@@ -7883,6 +7887,7 @@ exit 7session_list: Rc::new(RefCell::new(None)),request_elicitations: cx.new(|_| ElicitationStore::default()),active_request_scopes: None,+ pending_session_updates: None,};let (sender, mut receiver) = mpsc::unbounded::<ForegroundWork>();let cleanup = settle_after_disconnect(sender.clone()).boxed().shared();diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rsindex 53b9a4e22b1..32434908bfc 100644--- a/crates/agent_servers/src/acp/v2.rs+++ b/crates/agent_servers/src/acp/v2.rs@@ -1,6 +1,7 @@use super::{AcpDebugLog, AcpDebugMessage, AcpSession, ClientContext, ConfigOptions,- ContextServerConfiguration, ForegroundWork, UnsupportedVersion, drain_foreground_queue,+ ContextServerConfiguration, ForegroundWork, PendingSessionUpdates, UnsupportedVersion,+ apply_v2_session_notification, close_undelivered_session, drain_foreground_queue,enqueue_notification, first_class_terminal_auth_task, map_acp_error,mcp_configurations_for_project, runtime, transport, with_v2_client_ingress,work_dirs_from_session_info,@@ -58,6 +59,22 @@ fn finish_request(request_id: acp::RequestId, cx: &mut AsyncApp, context: &Clien});}+fn begin_session_creation(request_id: acp::RequestId, _cx: &mut AsyncApp, context: &ClientContext) {+ if let Some(pending) = &context.pending_session_updates {+ pending.borrow_mut().begin(request_id);+ }+}++fn finish_session_creation(+ request_id: acp::RequestId,+ _cx: &mut AsyncApp,+ context: &ClientContext,+) {+ if let Some(pending) = &context.pending_session_updates {+ pending.borrow_mut().finish(&request_id);+ }+}+#[derive(Debug, thiserror::Error)]#[error("ACP ordered response callback ended")]struct ResponseCallbackDropped;@@ -152,6 +169,7 @@ pub struct AcpV2Connection {debug_log: AcpDebugLog,dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,+ pending_session_updates: Rc<RefCell<PendingSessionUpdates>>,session_owners: Rc<RefCell<HashMap<acp::SessionId, SessionOwner>>>,_runtime: runtime::ClientRuntime,_stderr_task: Shared<Task<()>>,@@ -246,8 +264,10 @@ impl AcpV2Connection {) -> Result<Self> {let request_elicitations = cx.new(|_| ElicitationStore::default());let sessions = Rc::new(RefCell::new(HashMap::default()));+ let pending_session_updates = Rc::new(RefCell::new(PendingSessionUpdates::default()));let context = ClientContext {sessions: sessions.clone(),+ pending_session_updates: Some(pending_session_updates.clone()),session_list: Rc::new(RefCell::new(None)),request_elicitations: request_elicitations.clone(),active_request_scopes: Some(RefCell::new(Default::default())),@@ -306,6 +326,7 @@ impl AcpV2Connection {debug_log,dispatch_tx,sessions,+ pending_session_updates,session_owners: Rc::new(RefCell::new(HashMap::default())),_runtime: runtime,_stderr_task: stderr_task,@@ -941,14 +962,11 @@ impl AcpV2Connection {if application.is_none()&& let Some(session_id) = abandoned{- // Register cleanup, but never await later traffic in an ordered callback.- connection- .prepare_request(acp::CloseSessionRequest::new(session_id))- .on_receiving_result(async move |result| {- result.log_err();- Ok(())- })- .log_err();+ enqueue_notification(+ &dispatch_tx,+ (session_id, connection.clone()),+ close_undelivered_session,+ );}drain_foreground_queue(&dispatch_tx).await.log_err();Ok(())@@ -1050,36 +1068,98 @@ impl AgentConnection for AcpV2Connection {let request = acp::NewSessionRequest::new(context.cwd.clone()).additional_directories(context.additional_directories.clone()).mcp_servers(context.mcp_servers.clone());- let response = Self::ordered_request(+ let request = self.connection.prepare_request(request);+ let request_id = request.id().clone();+ let (response, applied) = Self::ordered_prepared_response(&self.connection,&self.dispatch_tx,request,- || Ok(()),+ {+ let dispatch_tx = self.dispatch_tx.clone();+ let request_id = request_id.clone();+ move || {+ enqueue_notification(&dispatch_tx, request_id, begin_session_creation);+ Ok(())+ }+ },|response| Some(response.session_id.clone()),+ );+ let response = {+ let dispatch_tx = self.dispatch_tx.clone();+ async move {+ let response = response.await?;+ drain_foreground_queue(&dispatch_tx).await?;+ Ok(response)+ }+ .boxed_local()+ };+ let response = Self::apply_ordered_response(+ response,+ applied,+ &self.dispatch_tx,{let this = self.clone();+ let request_id = request_id.clone();move |response, cx| {- cx.update(|cx| {- let thread = this.create_session_thread(- response.session_id,- project,- context,- None,- cx,- )?;- this.apply_initial_state(- &thread,- response.config_options,- response.available_commands,- cx,- )?;- Ok(thread)- })+ let session_id = response.session_id.clone();+ let notifications = this+ .pending_session_updates+ .borrow_mut()+ .take(&request_id, &session_id);+ let notifications = match notifications {+ Ok(notifications) => notifications,+ Err(error) => {+ enqueue_notification(+ &this.dispatch_tx,+ (session_id, this.connection.clone()),+ close_undelivered_session,+ );+ return Err(error);+ }+ };+ let thread = cx.update(|cx| {+ this.create_session_thread(session_id.clone(), project, context, None, cx)+ })?;+ let result = (|| {+ for notification in notifications {+ apply_v2_session_notification(+ notification,+ &thread.downgrade(),+ &this.sessions,+ cx,+ )?;+ }+ cx.update(|cx| {+ this.apply_initial_state(+ &thread,+ response.config_options,+ response.available_commands,+ cx,+ )+ })+ })();+ if let Err(error) = result {+ this.remove_session(&session_id, thread.entity_id());+ enqueue_notification(+ &this.dispatch_tx,+ (session_id, this.connection.clone()),+ close_undelivered_session,+ );+ return Err(error);+ }+ Ok(thread)}},cx,);- cx.foreground_executor().spawn(response)+ let cleanup = util::defer({+ let dispatch_tx = self.dispatch_tx.clone();+ move || enqueue_notification(&dispatch_tx, request_id, finish_session_creation)+ });+ cx.foreground_executor().spawn(async move {+ let _cleanup = cleanup;+ response.await+ })}fn supports_load_session(&self) -> bool {@@ -1627,6 +1707,9 @@ mod tests {new_requests: async_channel::Receiver<(acp::NewSessionRequest, acp::RequestId)>,new_responses:async_channel::Sender<Result<acp::NewSessionResponse, agent_client_protocol::Error>>,+ new_replies:+ async_channel::Receiver<(acp::NewSessionRequest, Responder<acp::NewSessionResponse>)>,+ hold_new_responses: Arc<Mutex<bool>>,config_requests: async_channel::Receiver<acp::SetSessionConfigOptionRequest>,config_responses: async_channel::Sender<Result<acp::SetSessionConfigOptionResponse, agent_client_protocol::Error>,@@ -1671,6 +1754,9 @@ mod tests {let (new_responses, new_received) = async_channel::unbounded::<Result<acp::NewSessionResponse, agent_client_protocol::Error>,>();+ let (new_reply_sender, new_replies) = async_channel::unbounded();+ let hold_new_responses = Arc::new(Mutex::new(false));+ let deferred_new = hold_new_responses.clone();let (list_sender, list_requests) = async_channel::unbounded();let (config_sender, config_requests) = async_channel::unbounded();let (config_responses, config_received) = async_channel::unbounded::<@@ -1719,8 +1805,14 @@ mod tests {responder: Responder<acp::NewSessionResponse>,agent: V2ConnectionTo<Client>| {new_sender- .try_send((request, responder.id().clone()))+ .try_send((request.clone(), responder.id().clone())).expect("record creation");+ if *deferred_new.lock().expect("new response mode") {+ new_reply_sender+ .try_send((request, responder))+ .expect("new reply receiver");+ return Ok(());+ }match new_received.recv().await.expect("new response") {Ok(response) => {let session_id = response.session_id.clone();@@ -1841,6 +1933,8 @@ mod tests {cancellations,new_requests,new_responses,+ new_replies,+ hold_new_responses,config_requests,config_responses,config_replies,@@ -1855,6 +1949,35 @@ mod tests {}}+ fn send_update(&self, session_id: &str, update: acp::SessionUpdate) {+ self.agent+ .send_notification(acp::UpdateSessionNotification::new(session_id, update))+ .expect("session update");+ }++ async fn drain_updates(&self, cx: &TestAppContext) {+ // A round trip also covers notifications not yet enqueued on the foreground.+ let error = bounded(+ self.agent+ .send_request(acp::CreateElicitationRequest::new(+ acp::ElicitationFormMode::new(+ acp::ElicitationSessionScope::new("unbound-barrier"),+ acp::ElicitationSchema::new(),+ ),+ "Inbound ordering barrier",+ ))+ .block_task(),+ cx,+ )+ .await+ .expect_err("barrier has no session owner");+ assert_eq!(+ error,+ agent_client_protocol::Error::internal_error()+ .data("unknown session: unbound-barrier")+ );+ }+fn create(&self, cx: &mut TestAppContext) -> Task<Result<Entity<AcpThread>>> {cx.update(|cx| {self.client.clone().new_session(@@ -2570,6 +2693,398 @@ doneassert!(harness.closes.is_empty());}+ #[gpui::test]+ async fn v2_new_sdk_correlates_concurrent_prefixes_by_response_id(cx: &mut TestAppContext) {+ use acp_thread::ForegroundActivity;+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ *harness.hold_new_responses.lock().expect("new mode") = true;+ let filesystem = fs::FakeFs::new(cx.executor());+ filesystem+ .insert_tree(session_path(""), json!({"b": {}}))+ .await;+ let second_project = Project::test(filesystem, [session_path("b").as_path()], cx).await;+ let mut first = harness.create(cx);+ let second = cx.update(|cx| {+ harness.client.clone().new_session(+ second_project.clone(),+ PathList::new(&[session_path("b")]),+ cx,+ )+ });+ let (request, response) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("first request");+ let (other_request, other_response) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("second request");+ let (first_response, second_response) = if request.cwd.0 == session_path("a") {+ assert_eq!(other_request.cwd.0, session_path("b"));+ (response, other_response)+ } else {+ assert_eq!(request.cwd.0, session_path("b"));+ assert_eq!(other_request.cwd.0, session_path("a"));+ (other_response, response)+ };+ harness.send_update(+ "first",+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(+ acp::RunningStateUpdate::new(),+ )),+ );+ harness.send_update(+ "second",+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::RequiresAction(+ acp::RequiresActionStateUpdate::new(),+ )),+ );+ harness.send_update(+ "first",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("first-message").content(vec!["first only".into()]),+ ),+ );+ harness.send_update(+ "second",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("second-message").content(vec!["second only".into()]),+ ),+ );+ harness.send_update(+ "second",+ acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate::new(vec![+ acp::SessionConfigOption::boolean("prefix", "Prefix", false),+ ])),+ );+ harness.send_update(+ "second",+ acp::SessionUpdate::AvailableCommandsUpdate(acp::AvailableCommandsUpdate::new(vec![+ acp::AvailableCommand::new("prefix", "Prefix"),+ ])),+ );+ cx.run_until_parked();+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts().0,+ 2+ );+ harness.drain_updates(cx).await;+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts().1,+ 6+ );+ let config = vec![acp::SessionConfigOption::boolean(+ "response", "Response", true,+ )];+ let commands = vec![acp::AvailableCommand::new("response", "Response")];+ second_response+ .respond(+ acp::NewSessionResponse::new("second")+ .config_options(config.clone())+ .available_commands(commands.clone()),+ )+ .expect("second replies first");+ let second_thread = bounded(second, cx).await.expect("second created");+ assert!((&mut first).now_or_never().is_none());+ second_thread.read_with(cx, |thread, cx| {+ assert_eq!(+ thread.foreground_activity(),+ ForegroundActivity::RequiresAction+ );+ assert!(thread.to_markdown(cx).contains("second only"));+ assert!(!thread.to_markdown(cx).contains("first only"));+ assert_eq!(thread.available_commands(), commands);+ });+ let options = cx+ .read(|cx| harness.client.session_config_options(&"second".into(), cx))+ .expect("second config");+ assert_eq!(options.config_options(), config);+ first_response+ .respond(acp::NewSessionResponse::new("first"))+ .expect("first replies last");+ let first_thread = bounded(first, cx).await.expect("first created");+ first_thread.read_with(cx, |thread, cx| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ assert!(thread.to_markdown(cx).contains("first only"));+ assert!(!thread.to_markdown(cx).contains("second only"));+ });+ let owners = harness.client.session_owners.borrow();+ assert_eq!(+ owners+ .get(&"first".into())+ .expect("first owner")+ .project_entity_id,+ harness.project.entity_id()+ );+ assert_eq!(+ owners+ .get(&"second".into())+ .expect("second owner")+ .project_entity_id,+ second_project.entity_id()+ );+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts(),+ (0, 0, 0)+ );+ }++ #[gpui::test]+ async fn v2_new_sdk_concurrent_failure_preserves_successful_prefix(cx: &mut TestAppContext) {+ for abandoned in [false, true] {+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ *harness.hold_new_responses.lock().expect("new mode") = true;+ let failed = harness.create(cx);+ let (_, failed_response) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("failed creation");+ let retained = harness.create(cx);+ let (_, retained_response) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("retained creation");+ harness.send_update(+ "failed",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("discarded").content(vec!["discarded".into()]),+ ),+ );+ harness.send_update(+ "retained",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("retained").content(vec!["retained".into()]),+ ),+ );+ harness.drain_updates(cx).await;+ if abandoned {+ drop(failed);+ failed_response+ .respond(acp::NewSessionResponse::new("failed"))+ .expect("abandoned success");+ assert_eq!(+ bounded(harness.closes.recv(), cx)+ .await+ .expect("close abandoned session"),+ acp::SessionId::new("failed")+ );+ } else {+ let rejection = agent_client_protocol::Error::new(-32042, "Creation rejected")+ .data(json!({"keep": [null, 7]}));+ failed_response+ .respond_with_error(rejection.clone())+ .expect("reject first");+ assert_eq!(+ bounded(failed, cx)+ .await+ .expect_err("rejection")+ .downcast_ref::<agent_client_protocol::Error>(),+ Some(&rejection)+ );+ }+ retained_response+ .respond(acp::NewSessionResponse::new("retained"))+ .expect("successful response");+ let thread = bounded(retained, cx)+ .await+ .expect("success survives unrelated rejection");+ thread.read_with(cx, |thread, cx| {+ assert!(thread.to_markdown(cx).contains("retained"));+ assert!(!thread.to_markdown(cx).contains("discarded"));+ });+ cx.run_until_parked();+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts(),+ (0, 0, 0)+ );+ let later = harness.create(cx);+ let (_, response) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("later creation");+ response+ .respond(acp::NewSessionResponse::new("failed"))+ .expect("later response");+ assert!(+ bounded(later, cx)+ .await+ .expect("later owner")+ .read_with(cx, |thread, _| thread.entries().is_empty())+ );+ }+ }++ #[gpui::test]+ async fn v2_new_sdk_staging_limit_is_observable_and_preserves_live_owners(+ cx: &mut TestAppContext,+ ) {+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let thread = harness.thread(cx).await;+ *harness.hold_new_responses.lock().expect("new mode") = true;+ let creation = harness.create(cx);+ let (_, responder) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("new request");+ for _ in 0..super::super::session_updates::MAX_PENDING_SESSION_UPDATES {+ harness.send_update(+ "overflowed",+ acp::SessionUpdate::SessionInfoUpdate(+ acp::SessionInfoUpdate::new().title("prefix"),+ ),+ );+ }+ harness.drain_updates(cx).await;+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts().1,+ super::super::session_updates::MAX_PENDING_SESSION_UPDATES+ );+ harness.send_update(+ "overflowed",+ acp::SessionUpdate::SessionInfoUpdate(acp::SessionInfoUpdate::new().title("overflow")),+ );+ harness.send_update(+ "session",+ acp::SessionUpdate::SessionInfoUpdate(+ acp::SessionInfoUpdate::new().title("Live owner"),+ ),+ );+ harness.drain_updates(cx).await;+ responder+ .respond(acp::NewSessionResponse::new("overflowed"))+ .expect("new response");+ assert!(+ bounded(creation, cx)+ .await+ .expect_err("staging limit")+ .to_string()+ .contains("limits")+ );+ assert_eq!(+ bounded(harness.closes.recv(), cx)+ .await+ .expect("close failed creation"),+ acp::SessionId::new("overflowed")+ );+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.title()),+ Some("Live owner".into())+ );+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts(),+ (0, 0, 0)+ );+ assert_eq!(+ harness+ .client+ .sessions+ .borrow()+ .get(&"session".into())+ .expect("live")+ .thread+ .entity_id(),+ thread.entity_id()+ );+ }++ #[gpui::test]+ async fn v2_new_sdk_abandoned_duplicate_does_not_close_a_live_owner(cx: &mut TestAppContext) {+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let thread = harness.thread(cx).await;+ *harness.hold_new_responses.lock().expect("new mode") = true;+ let creation = harness.create(cx);+ let (_, responder) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("new request");+ drop(creation);+ responder+ .respond(initial_response())+ .expect("duplicate late response");+ harness.drain_updates(cx).await;+ assert!(+ harness.closes.is_empty(),+ "abandoned cleanup cannot close an existing owner"+ );+ assert_eq!(+ harness+ .client+ .sessions+ .borrow()+ .get(&"session".into())+ .expect("live owner")+ .thread+ .entity_id(),+ thread.entity_id()+ );+ }++ #[gpui::test]+ async fn v2_new_sdk_preserves_pre_response_updates(cx: &mut TestAppContext) {+ use acp_thread::ForegroundActivity;+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ *harness.hold_new_responses.lock().expect("new mode") = true;+ let mut creating = harness.create(cx);+ let (_, responder) = bounded(harness.new_replies.recv(), cx)+ .await+ .expect("new request");+ for update in [+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(+ acp::RunningStateUpdate::new(),+ )),+ acp::SessionUpdate::SessionInfoUpdate(+ acp::SessionInfoUpdate::new()+ .title("Early title")+ .meta(meta("early")),+ ),+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("early-message").content(vec!["Early content".into()]),+ ),+ serde_json::from_value(json!({+ "sessionUpdate": "tool_call_update", "toolCallId": "early-tool",+ "title": "Early tool", "status": "in_progress",+ "content": [{"type": "content", "content": {"type": "text", "text": "tool prefix"}}]+ }))+ .expect("tool update"),+ serde_json::from_value(json!({+ "sessionUpdate": "tool_call_content_chunk", "toolCallId": "early-tool",+ "content": {"type": "content", "content": {"type": "text", "text": "tool suffix"}}+ }))+ .expect("tool chunk"),+ acp::SessionUpdate::TerminalUpdate(+ acp::TerminalUpdate::new("early-terminal")+ .command("echo")+ .output(acp::TerminalOutput::new("b2xk")),+ ),+ acp::SessionUpdate::TerminalOutputChunk(acp::TerminalOutputChunk::new(+ "early-terminal",+ "IQ==",+ )),+ ] {+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new("session", update))+ .expect("pre-response update");+ }+ harness.drain_updates(cx).await;+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts().1,+ 7+ );+ assert!((&mut creating).now_or_never().is_none());+ responder+ .respond(initial_response())+ .expect("creation response");+ let thread = bounded(creating, cx).await.expect("created owner");+ thread.read_with(cx, |thread, cx| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ assert_eq!(thread.session_info().title.as_deref(), Some("Early title"));+ assert!(thread.to_markdown(cx).contains("Early content"));+ let (_, tool) = thread.tool_call(&"early-tool".into()).expect("early tool");+ assert_eq!(tool.content().len(), 2);+ let terminal = thread+ .terminal("early-terminal".into())+ .expect("early terminal");+ assert_eq!(+ terminal.read(cx).inner().read(cx).get_content().trim_end(),+ "old!"+ );+ });+ }+#[gpui::test]async fn v2_session_sdk_registers_initial_state_before_immediate_notifications(cx: &mut TestAppContext,@@ -3576,14 +4091,38 @@ donecx: &mut TestAppContext,) {let harness = SessionHarness::new(session_capabilities(), Vec::new(), Vec::new(), cx).await;+ let unpublished = harness.create(cx);+ drop(unpublished);+ cx.run_until_parked();+ assert!(harness.new_requests.is_empty());+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts(),+ (0, 0, 0)+ );+ *harness.hold_new_responses.lock().expect("new mode") = true;let creation = harness.create(cx);- bounded(harness.new_requests.recv(), cx)+ let (_, responder) = bounded(harness.new_replies.recv(), cx).await.expect("request");+ harness.send_update(+ "session",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("staged").content(vec!["staged".into()]),+ ),+ );+ harness.drain_updates(cx).await;+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts().1,+ 1+ );drop(creation);- harness- .new_responses- .try_send(Ok(initial_response()))+ cx.run_until_parked();+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts(),+ (0, 0, 0)+ );+ responder+ .respond(initial_response()).expect("late response");assert_eq!(bounded(harness.closes.recv(), cx)@@ -3593,12 +4132,29 @@ done);assert!(harness.client.sessions.borrow().is_empty());let creation = harness.create(cx);- bounded(harness.new_requests.recv(), cx)+ let (_, _responder) = bounded(harness.new_replies.recv(), cx).await.expect("next request");+ harness.send_update(+ "session",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("next").content(vec!["next prefix".into()]),+ ),+ );+ harness.drain_updates(cx).await;+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts().1,+ 1+ );drop(harness._agent_task);+ drop(harness.agent);assert!(bounded(creation, cx).await.is_err());+ cx.run_until_parked();assert!(harness.client.sessions.borrow().is_empty());+ assert_eq!(+ harness.client.pending_session_updates.borrow().counts(),+ (0, 0, 0)+ );}#[gpui::test]@@ -3781,6 +4337,70 @@ done);}+ #[cfg(unix)]+ #[gpui::test]+ async fn v2_new_stdio_preserves_pre_response_updates_before_eof(cx: &mut TestAppContext) {+ use acp_thread::ForegroundActivity;+ cx.update(|cx| {+ let store = settings::SettingsStore::test(cx);+ cx.set_global(store);+ release_channel::init("0.0.0".parse().expect("version"), cx);+ });+ cx.executor().allow_parking();+ let directory = tempfile::tempdir().expect("working directory");+ let project = Project::example([directory.path()], &mut cx.to_async()).await;+ let command = AgentServerCommand {+ path: "/bin/sh".into(),+ args: vec!["-c".into(), r#"+while IFS= read -r request; do+ id=${request#*\"id\":}+ id=${id%%,*}+ case "$request" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":2,"info":{"name":"early-stdio","version":"1"},"capabilities":{"session":{}}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"stdio-session","update":{"sessionUpdate":"state_update","state":"running"}}}\n'+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"stdio-session","update":{"sessionUpdate":"agent_message","messageId":"first","content":[{"type":"text","text":"Early stdio message"}]}}}\n'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"stdio-session"}}\n' "$id"+ exit 0+ ;;+ *) exit 43 ;;+ esac+done+"#.into()],+ env: None,+ };+ let client = Rc::new(+ bounded(+ AcpV2Connection::stdio(+ AgentId::new("early-stdio"),+ project.clone(),+ command,+ WeakEntity::new_invalid(),+ &mut cx.to_async(),+ ),+ cx,+ )+ .await+ .expect("stdio connection"),+ );+ let creation = cx.update(|cx| {+ client+ .clone()+ .new_session(project, PathList::new(&[directory.path()]), cx)+ });+ let thread = bounded(creation, cx)+ .await+ .expect("new response precedes EOF");+ bounded(client.connection.incoming_closed(), cx).await;+ thread.read_with(cx, |thread, cx| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ assert!(thread.to_markdown(cx).contains("Early stdio message"));+ });+ assert_eq!(client.pending_session_updates.borrow().counts(), (0, 0, 0));+ }+#[cfg(unix)]#[gpui::test]async fn v2_session_stdio_applies_initial_state_and_authoritative_config(