Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent_servers: Share ACP connection lifecycle across v1 and v2 (#65601)
Ben Brandt0943bcb76cd5
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex 9ae13b2569d..665e69ec13c 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -1,4 +1,5 @@mod debug_log;+mod runtime;mod session_updates;mod terminal_updates;mod transport;@@ -29,7 +30,7 @@ use async_channel;use collections::{HashMap, HashSet};use futures::channel::mpsc;use futures::future::Shared;-use futures::{Future, FutureExt as _, StreamExt as _};+use futures::{Future, FutureExt as _};use project::agent_server_store::{AgentServerCommand, AgentServerStore, AllAgentServersSettings, CustomAgentServerSettings,};@@ -45,7 +46,6 @@ use task::SpawnInTerminal;use thiserror::Error;use util::ResultExt as _;use util::path_list::PathList;-use util::process::Child;use anyhow::{Context as _, Result};use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Subscription, Task, WeakEntity};@@ -335,14 +335,13 @@ pub struct AcpConnection {agent_capabilities: acp::AgentCapabilities,request_elicitations: Entity<ElicitationStore>,defaults: AcpConnectionDefaults,- child: Option<Child>,+ _child: Option<transport::OwnedChild>,session_list: Option<Rc<AcpSessionList>>,debug_log: AcpDebugLog,_settings_subscription: Subscription,- _io_task: Task<()>,+ _runtime: runtime::ClientRuntime,dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,- _dispatch_task: Task<()>,- _wait_task: Task<Result<()>>,+ _wait_task: Task<()>,_stderr_task: Shared<Task<()>>,}@@ -623,13 +622,11 @@ fn connect_client_future(transport: impl agent_client_protocol::ConnectTo<Client> + 'static,dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,connection_tx: futures::channel::oneshot::Sender<ConnectionTo<Agent>>,+ shutdown: impl Future<Output = ()> + Send + 'static,) -> impl Future<Output = Result<(), acp::Error>> {async move {- // Transport failures can bypass `on_close`; both paths share the same foreground cleanup.- let cleanup = cancel_elicitations_after_disconnect(dispatch_tx.clone())- .boxed()- .shared();- let result = client_builder(name, dispatch_tx)+ let cleanup = runtime::disconnect_cleanup(dispatch_tx.clone());+ let future = client_builder(name, dispatch_tx).on_close({let cleanup = cleanup.clone();async move |_connection: ConnectionTo<Agent>| cleanup.await@@ -637,20 +634,10 @@ fn connect_client_future(.connect_with(transport,move |connection: ConnectionTo<Agent>| async move {- if connection_tx.send(connection).is_err() {- log::error!("failed to send ACP connection handle — receiver was dropped");- }- // Keep the connection alive until the transport closes.- futures::future::pending::<Result<(), acp::Error>>().await+ runtime::publish_connection(connection, connection_tx, shutdown).await},- )- .await;- let cleanup_result = cleanup.await;- if let Err(error) = &cleanup_result {- log::warn!("ACP disconnect cleanup failed: {error}");- }- result?;- cleanup_result+ );+ runtime::finish_connection(future, cleanup).await}}@@ -932,12 +919,13 @@ impl AcpConnection {) -> Result<Self> {let original_command = command.clone();let transport::StdioProcess {- mut child,+ child,incoming,outgoing,stderr,debug_log,} = transport::spawn_stdio(&project, command, cx)?;+ let mut child = transport::OwnedChild(child);let sessions = Rc::new(RefCell::new(HashMap::default()));let (release_channel, version): (Option<&str>, String) = cx.update(|cx| {@@ -952,9 +940,14 @@ impl AcpConnection {Rc::new(RefCell::new(None));let request_elicitations = cx.new(|_| ElicitationStore::default());- // Set up the foreground dispatch channel for bridging Send handler- // closures to the !Send foreground thread.- let (dispatch_tx, dispatch_rx) = mpsc::unbounded::<ForegroundWork>();+ let dispatch_context = ClientContext {+ sessions: sessions.clone(),+ session_list: client_session_list.clone(),+ request_elicitations: request_elicitations.clone(),+ active_request_scopes: None,+ };+ let (mut runtime, shutdown) = runtime::ClientRuntime::new(dispatch_context, cx);+ let dispatch_tx = runtime.sender();let transport = Lines::new(outgoing, incoming);let stderr_task = cx@@ -964,13 +957,14 @@ impl AcpConnection {.shared();let (connection_tx, connection_rx) = futures::channel::oneshot::channel();- let connection_future =- connect_client_future("zed", transport, dispatch_tx.clone(), connection_tx);- let io_task = cx.background_spawn(async move {- if let Err(err) = connection_future.await {- log::error!("ACP connection error: {err}");- }- });+ let connection_future = connect_client_future(+ "zed",+ transport,+ dispatch_tx.clone(),+ connection_tx,+ runtime::shutdown_requested(shutdown),+ );+ runtime.start_io(connection_future, cx);let connection_rx = async move {connection_rx@@ -979,60 +973,27 @@ impl AcpConnection {}.boxed_local();let status_fut = child+ .0.status().map(|status| {status.map_err(|error| anyhow!("failed to wait for agent server exit: {error}"))}).boxed_local();- let (connection, status_fut) = match futures::future::select(connection_rx, status_fut)- .await- {- futures::future::Either::Left((connection, status_fut)) => (connection?, status_fut),- futures::future::Either::Right((status, _connection_rx)) => {- return Err(- exited_load_error_after_drain(status?, stderr_task, &debug_log, cx)- .await- .into(),- );- }- };-- // Set up the foreground dispatch loop to process work items from handlers.- let dispatch_context = ClientContext {- sessions: sessions.clone(),- session_list: client_session_list.clone(),- request_elicitations: request_elicitations.clone(),- active_request_scopes: None,- };- let dispatch_task = cx.spawn({- let mut dispatch_rx = dispatch_rx;- async move |cx| {- while let Some(work) = dispatch_rx.next().await {- work.run(cx, &dispatch_context);- }- }- });+ let (connection, status_fut, _) = runtime::race_startup(+ connection_rx,+ status_fut,+ stderr_task.clone(),+ &debug_log,+ cx,+ )+ .await?;let drained = {let connection = connection.clone();- let stderr_task = stderr_task.clone();- let dispatch_tx = dispatch_tx.clone();- async move {- let incoming = async move {- // EOF follows SDK dispatch, but model updates are still queued on the foreground.- connection.incoming_closed().await;- let (acknowledgment, received) = futures::channel::oneshot::channel();- let barrier: ForegroundWork = Box::new(ForegroundBarrier { acknowledgment });- if let Err(error) = dispatch_tx.unbounded_send(barrier) {- error.into_inner().reject();- return;- }- received- .await- .context("ACP foreground dispatch closed during exit drain")- .log_err();- };- futures::join!(incoming, stderr_task);- }+ runtime::drain_transport(+ async move { connection.incoming_closed().await },+ dispatch_tx.clone(),+ stderr_task.clone(),+ )};let initialize_response = connection@@ -1045,51 +1006,27 @@ impl AcpConnection {),).block_task()+ .map(|response| response.map_err(anyhow::Error::from)).boxed_local();- let (response, status_fut) =- match futures::future::select(initialize_response, status_fut).await {- futures::future::Either::Left((Ok(response), status_fut)) => (response, status_fut),- futures::future::Either::Left((Err(error), status_fut)) => {- let timer = cx- .background_executor()- .timer(std::time::Duration::from_millis(250))- .boxed_local();- if let futures::future::Either::Left((status, _timer)) =- futures::future::select(status_fut, timer).await- {- return Err(exited_load_error_after_drain(- status?, drained, &debug_log, cx,- )- .await- .into());- }-- return Err(error.into());- }- futures::future::Either::Right((status, _initialize_response)) => {- return Err(- exited_load_error_after_drain(status?, drained, &debug_log, cx)- .await- .into(),- );- }- };+ let (response, status_fut, drained) =+ runtime::race_startup(initialize_response, status_fut, drained, &debug_log, cx).await?;if response.protocol_version < MINIMUM_SUPPORTED_VERSION {return Err(UnsupportedVersion.into());}- let wait_task = cx.spawn({- let sessions = sessions.clone();- let debug_log = debug_log.clone();- async move |cx| {- let status = status_fut.await?;- let load_error =- exited_load_error_after_drain(status, drained, &debug_log, cx).await;- emit_load_error_to_all_sessions(&sessions, load_error, cx);- anyhow::Ok(())- }- });+ let wait_task = runtime::watch_process(+ status_fut,+ drained,+ debug_log.clone(),+ {+ let sessions = sessions.clone();+ move |load_error, cx| {+ emit_load_error_to_all_sessions(&sessions, load_error, cx);+ }+ },+ cx,+ );let agent_info = response.agent_info;let telemetry_id = agent_info@@ -1163,12 +1100,11 @@ impl AcpConnection {session_list,debug_log,_settings_subscription: settings_subscription,- _io_task: io_task,+ _runtime: runtime,dispatch_tx,- _dispatch_task: dispatch_task,_wait_task: wait_task,_stderr_task: stderr_task,- child: Some(child),+ _child: Some(child),})}@@ -1206,14 +1142,17 @@ impl AcpConnection {agent_capabilities,request_elicitations,defaults,- child: None,+ _child: None,session_list: None,debug_log: AcpDebugLog::default(),_settings_subscription: settings_subscription,- _io_task: io_task,+ _runtime: runtime::ClientRuntime::from_test_tasks(+ dispatch_tx.clone(),+ io_task,+ dispatch_task,+ ),dispatch_tx,- _dispatch_task: dispatch_task,- _wait_task: Task::ready(Ok(())),+ _wait_task: Task::ready(()),_stderr_task: Task::ready(()).shared(),}}@@ -1684,14 +1623,6 @@ fn emit_load_error_to_all_sessions(}}-impl Drop for AcpConnection {- fn drop(&mut self) {- if let Some(ref mut child) = self.child {- child.kill().log_err();- }- }-}-fn terminal_auth_task_id(agent_id: &AgentId, method_id: &acp_v2::AuthMethodId) -> String {format!("external-agent-{}-{}-login", agent_id.0, method_id.0)}@@ -2253,6 +2184,7 @@ pub mod test_support {};use super::*;+ use futures::StreamExt as _;#[derive(Clone, Default)]pub struct FakeAcpAgentServer {@@ -2711,6 +2643,7 @@ pub mod test_support {client_transport,dispatch_tx.clone(),connection_tx,+ futures::future::pending(),);let client_io_task = cx.background_spawn(async move {client_future.await.ok();@@ -2871,6 +2804,7 @@ mod tests {use std::sync::atomic::{AtomicUsize, Ordering};use super::*;+ use futures::StreamExt as _;use settings::Settings as _;#[test]@@ -2934,6 +2868,7 @@ mod tests {client_transport,harness.connection.dispatch_tx.clone(),connection_tx,+ futures::future::pending(),));Rc::get_mut(&mut harness.connection).expect("test harness should own the only ACP connection handle")@@ -7669,6 +7604,7 @@ exit 7client_transport,dispatch_tx.clone(),connection_tx,+ futures::future::pending(),);let client_io_task = cx.background_spawn(async move {client_future.await.ok();@@ -8095,6 +8031,7 @@ exit 7Lines::new(Box::pin(outgoing), incoming_rx),dispatch_tx,connection_tx,+ futures::future::pending(),));let _connection = connection_rx.await.expect("SDK connection handle");let (entry, response) = store.update(cx, |store, cx| {diff --git a/crates/agent_servers/src/acp/runtime.rs b/crates/agent_servers/src/acp/runtime.rsnew file mode 100644index 00000000000..8dd4f9e34d3--- /dev/null+++ b/crates/agent_servers/src/acp/runtime.rs@@ -0,0 +1,354 @@+use super::{+ AcpDebugLog, ClientContext, ForegroundWork, cancel_elicitations_after_disconnect,+ drain_foreground_queue, exited_load_error_after_drain,+};+use acp_thread::LoadError;+use agent_client_protocol::{Error, Result as RpcResult};+use anyhow::Result;+use futures::{+ Future, FutureExt as _, StreamExt as _,+ channel::{mpsc, oneshot},+ future::{BoxFuture, LocalBoxFuture, Shared},+};+use gpui::{AppContext as _, AsyncApp, Task};+use std::{process::ExitStatus, time::Duration};+use util::ResultExt as _;++type DisconnectCleanup = Shared<BoxFuture<'static, RpcResult<()>>>;+pub(super) type ProcessStatus = LocalBoxFuture<'static, Result<ExitStatus>>;++pub(super) struct ClientRuntime {+ dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,+ io_task: Option<Task<()>>,+ dispatch_task: Option<Task<()>>,+ shutdown: Option<oneshot::Sender<()>>,+}++impl ClientRuntime {+ pub(super) fn new(context: ClientContext, cx: &mut AsyncApp) -> (Self, oneshot::Receiver<()>) {+ let (dispatch_tx, mut dispatch_rx) = mpsc::unbounded::<ForegroundWork>();+ let dispatch_task = cx.spawn(async move |cx| {+ while let Some(work) = dispatch_rx.next().await {+ work.run(cx, &context);+ }+ });+ let (shutdown, received) = oneshot::channel();+ (+ Self {+ dispatch_tx,+ io_task: None,+ dispatch_task: Some(dispatch_task),+ shutdown: Some(shutdown),+ },+ received,+ )+ }++ pub(super) fn sender(&self) -> mpsc::UnboundedSender<ForegroundWork> {+ self.dispatch_tx.clone()+ }++ pub(super) fn start_io(+ &mut self,+ future: impl Future<Output = RpcResult<()>> + Send + 'static,+ cx: &AsyncApp,+ ) {+ self.io_task = Some(cx.background_spawn(async move {+ future.await.log_err();+ }));+ }++ #[cfg(any(test, feature = "test-support"))]+ pub(super) fn from_test_tasks(+ dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,+ io_task: Task<()>,+ dispatch_task: Task<()>,+ ) -> Self {+ Self {+ dispatch_tx,+ io_task: Some(io_task),+ dispatch_task: Some(dispatch_task),+ shutdown: None,+ }+ }+}++impl Drop for ClientRuntime {+ fn drop(&mut self) {+ // Raw test drivers have no cooperative shutdown callback and retain cancel-on-drop.+ if self.shutdown.take().is_some() {+ // SDK close callbacks must settle foreground owners before the dispatch task exits.+ if let Some(task) = self.io_task.take() {+ task.detach();+ }+ if let Some(task) = self.dispatch_task.take() {+ task.detach();+ }+ }+ }+}++pub(super) fn disconnect_cleanup(+ sender: mpsc::UnboundedSender<ForegroundWork>,+) -> DisconnectCleanup {+ cancel_elicitations_after_disconnect(sender)+ .boxed()+ .shared()+}++pub(super) async fn publish_connection<Connection>(+ connection: Connection,+ sender: oneshot::Sender<Connection>,+ shutdown: impl Future<Output = ()>,+) -> RpcResult<()> {+ if sender.send(connection).is_err() {+ return Err(Error::internal_error().data("ACP connection receiver dropped"));+ }+ shutdown.await;+ Ok(())+}++pub(super) async fn finish_connection(+ future: impl Future<Output = RpcResult<()>>,+ cleanup: DisconnectCleanup,+) -> RpcResult<()> {+ // Transport failures can bypass on_close; both paths await this one shared cleanup.+ let result = future.await;+ let cleanup_result = cleanup.await;+ if let Err(error) = &cleanup_result {+ log::warn!("ACP disconnect cleanup failed: {error}");+ }+ result?;+ cleanup_result+}++pub(super) async fn shutdown_requested(received: oneshot::Receiver<()>) {+ if received.await.is_err() {+ log::debug!("ACP connection owner dropped");+ }+}++pub(super) async fn race_startup<Value, Drain: Future<Output = ()>>(+ initialized: impl Future<Output = Result<Value>>,+ status: ProcessStatus,+ drained: Drain,+ debug_log: &AcpDebugLog,+ cx: &AsyncApp,+) -> Result<(Value, ProcessStatus, Drain)> {+ futures::pin_mut!(initialized);+ match futures::future::select(initialized, status).await {+ futures::future::Either::Left((Ok(value), status)) => Ok((value, status, drained)),+ futures::future::Either::Left((Err(error), status)) => {+ let timeout = cx.background_executor().timer(Duration::from_millis(250));+ futures::pin_mut!(timeout);+ if let futures::future::Either::Left((status, _)) =+ futures::future::select(status, timeout).await+ {+ return Err(+ exited_load_error_after_drain(status?, drained, debug_log, cx)+ .await+ .into(),+ );+ }+ Err(error)+ }+ futures::future::Either::Right((status, _)) => Err(exited_load_error_after_drain(+ status?, drained, debug_log, cx,+ )+ .await+ .into()),+ }+}++pub(super) async fn drain_transport(+ incoming_closed: impl Future<Output = ()>,+ sender: mpsc::UnboundedSender<ForegroundWork>,+ stderr: Shared<Task<()>>,+) {+ let incoming = async move {+ incoming_closed.await;+ drain_foreground_queue(&sender).await.log_err();+ };+ futures::join!(incoming, stderr);+}++pub(super) fn watch_process(+ status: ProcessStatus,+ drained: impl Future<Output = ()> + 'static,+ debug_log: AcpDebugLog,+ on_exit: impl FnOnce(LoadError, &mut AsyncApp) + 'static,+ cx: &AsyncApp,+) -> Task<()> {+ cx.spawn(async move |cx| match status.await {+ Ok(status) => {+ let error = exited_load_error_after_drain(status, drained, &debug_log, cx).await;+ on_exit(error, cx);+ }+ Err(error) => log::error!("ACP process wait failed: {error}"),+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::acp::connect_client_future;+ use acp_thread::{ElicitationStatus, ElicitationStore};+ use agent_client_protocol::schema::v2 as acp;+ use collections::HashMap;+ use gpui::TestAppContext;+ use std::{cell::RefCell, rc::Rc};++ #[gpui::test]+ async fn shared_runtime_v1_owner_drop_settles_retained_input(cx: &mut TestAppContext) {+ let store = cx.new(|_| ElicitationStore::default());+ let weak_store = store.downgrade();+ let context = ClientContext {+ sessions: Rc::new(RefCell::new(HashMap::default())),+ session_list: Rc::new(RefCell::new(None)),+ request_elicitations: store.clone(),+ active_request_scopes: None,+ };+ let (mut runtime, shutdown) = ClientRuntime::new(context, &mut cx.to_async());+ let (transport, peer) = agent_client_protocol::Channel::duplex();+ let (sender, received) = oneshot::channel();+ runtime.start_io(+ connect_client_future(+ "runtime-test",+ transport,+ runtime.sender(),+ sender,+ shutdown_requested(shutdown),+ ),+ &cx.to_async(),+ );+ let connection = received.await.expect("SDK handle");+ let (entry, response) = store.update(cx, |store, cx| {+ store+ .request_elicitation_with_id(+ acp::CreateElicitationRequest::new(+ acp::ElicitationFormMode::new(+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),+ acp::ElicitationSchema::new().string("name", true),+ ),+ "Retained input",+ ),+ cx,+ )+ .expect("retained input")+ });+ drop(runtime);+ let timeout = cx.background_executor.timer(Duration::from_secs(5));+ futures::pin_mut!(response, timeout);+ let response = match futures::future::select(response, timeout).await {+ futures::future::Either::Left((response, _)) => response,+ futures::future::Either::Right(_) => panic!("owner drop did not settle input"),+ };+ assert_eq!(response.action, acp::ElicitationAction::Cancel);+ store.read_with(cx, |store, _| {+ assert!(matches!(+ store.elicitation(&entry).expect("retained entry").1.status,+ ElicitationStatus::Canceled+ ));+ });+ drop(connection);+ drop(peer);+ drop(store);+ cx.run_until_parked();+ assert!(weak_store.upgrade().is_none(), "foreground owner leaked");+ }++ #[test]+ fn shared_runtime_abandoned_handle_rejects_without_waiting_for_shutdown() {+ let (sender, received) = oneshot::channel();+ drop(received);+ let error =+ futures::executor::block_on(publish_connection((), sender, futures::future::pending()))+ .expect_err("abandoned handle");+ assert_eq!(+ error.data,+ Some(serde_json::json!("ACP connection receiver dropped"))+ );+ }++ #[cfg(unix)]+ #[gpui::test]+ async fn shared_runtime_startup_exit_drains_stderr_in_both_arrival_orders(+ cx: &mut TestAppContext,+ ) {+ use crate::acp::debug_log::AcpDebugMessageDirection;+ use std::os::unix::process::ExitStatusExt as _;++ for initialize_fails_first in [false, true] {+ let debug_log = AcpDebugLog::default();+ let drained = {+ let debug_log = debug_log.clone();+ async move {+ debug_log.record_line(AcpDebugMessageDirection::Stderr, "runtime final stderr");+ }+ };+ let initialized = async move {+ if initialize_fails_first {+ Err::<(), _>(anyhow::anyhow!("initialize failed"))+ } else {+ futures::future::pending().await+ }+ };+ let status = async { Ok(ExitStatus::from_raw(7 << 8)) }.boxed_local();+ let error = race_startup(initialized, status, drained, &debug_log, &cx.to_async())+ .await+ .err()+ .expect("startup exit");+ let LoadError::Exited { status, stderr } = error+ .downcast_ref::<LoadError>()+ .expect("process exit supersedes initialization error")+ else {+ panic!("process exit error");+ };+ assert_eq!(status.code(), Some(7));+ assert_eq!(stderr.as_deref(), Some("runtime final stderr"));+ }+ }++ #[gpui::test]+ async fn shared_runtime_startup_preserves_error_while_process_remains_live(+ cx: &mut TestAppContext,+ ) {+ let error = race_startup(+ async { Err::<(), _>(anyhow::anyhow!("initialize rejected")) },+ futures::future::pending().boxed_local(),+ futures::future::pending(),+ &AcpDebugLog::default(),+ &cx.to_async(),+ )+ .await+ .err()+ .expect("initialization failure");+ assert_eq!(error.to_string(), "initialize rejected");+ }++ #[cfg(unix)]+ #[gpui::test]+ async fn shared_runtime_child_guard_kills_an_abandoned_process(cx: &mut TestAppContext) {+ cx.executor().allow_parking();+ let mut command = std::process::Command::new("/bin/sh");+ command.args(["-c", "IFS= read -r request"]);+ let child = util::process::Child::spawn(+ command,+ std::process::Stdio::piped(),+ std::process::Stdio::null(),+ std::process::Stdio::null(),+ )+ .expect("spawn waiting child");+ let mut child = crate::acp::transport::OwnedChild(child);+ let status = child.0.status();+ drop(child);+ let timeout = cx.background_executor.timer(Duration::from_secs(5));+ futures::pin_mut!(status, timeout);+ let status = match futures::future::select(status, timeout).await {+ futures::future::Either::Left((status, _)) => status.expect("wait for killed child"),+ futures::future::Either::Right(_) => panic!("child survived its owner"),+ };+ use std::os::unix::process::ExitStatusExt as _;+ assert_eq!(status.signal(), Some(9));+ }+}diff --git a/crates/agent_servers/src/acp/transport.rs b/crates/agent_servers/src/acp/transport.rsindex e2499bdfd39..86f3d0c9828 100644--- a/crates/agent_servers/src/acp/transport.rs+++ b/crates/agent_servers/src/acp/transport.rs@@ -9,7 +9,15 @@ use project::{Project, agent_server_store::AgentServerCommand};use remote::command::RemoteCommand;use std::{io, pin::Pin, process::Stdio};use task::{Shell, ShellBuilder};-use util::process::Child;+use util::{ResultExt as _, process::Child};++pub(super) struct OwnedChild(pub Child);++impl Drop for OwnedChild {+ fn drop(&mut self) {+ self.0.kill().log_err();+ }+}pub(super) struct StdioProcess {pub child: Child,diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rsindex 87b4cc24486..e943bfd2688 100644--- a/crates/agent_servers/src/acp/v2.rs+++ b/crates/agent_servers/src/acp/v2.rs@@ -1,8 +1,7 @@use super::{AcpDebugLog, AcpDebugMessage, ClientContext, ForegroundWork, UnsupportedVersion,- cancel_elicitations_after_disconnect, drain_foreground_queue, enqueue_notification,- exited_load_error_after_drain, first_class_terminal_auth_task, map_acp_error, transport,- with_v2_client_ingress,+ drain_foreground_queue, enqueue_notification, first_class_terminal_auth_task, map_acp_error,+ runtime, transport, with_v2_client_ingress,};use acp_thread::ElicitationStore;use agent_client_protocol::{@@ -11,15 +10,12 @@ use agent_client_protocol::{};use anyhow::{Context as _, Result, anyhow};use collections::HashMap;-use futures::{FutureExt as _, StreamExt as _, channel::mpsc, future::Shared};+use futures::{FutureExt as _, channel::mpsc, future::Shared};use gpui::{App, AppContext as _, AsyncApp, Entity, Task, WeakEntity};use project::{AgentId, AgentServerStore, Project, agent_server_store::AgentServerCommand};-use std::{cell::RefCell, rc::Rc, time::Duration};+use std::{cell::RefCell, rc::Rc};use task::SpawnInTerminal;-use util::{ResultExt as _, process::Child};--// Startup failures and dropped startup futures must also reap the spawned process.-struct OwnedChild(Child);+use util::ResultExt as _;fn cancel_auth_elicitations(request_id: acp::RequestId,@@ -49,12 +45,6 @@ fn finish_auth_request(request_id: acp::RequestId, cx: &mut AsyncApp, context: &});}-impl Drop for OwnedChild {- fn drop(&mut self) {- self.0.kill().log_err();- }-}-/// An unselected v2 connection foundation, not yet an `AgentConnection` session backend.pub struct AcpV2Connection {id: AgentId,@@ -65,25 +55,10 @@ pub struct AcpV2Connection {request_elicitations: Entity<ElicitationStore>,debug_log: AcpDebugLog,dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,- io_task: Option<Task<()>>,- dispatch_task: Option<Task<()>>,- shutdown: Option<futures::channel::oneshot::Sender<()>>,+ _runtime: runtime::ClientRuntime,_stderr_task: Shared<Task<()>>,_wait_task: Option<Task<()>>,- _child: Option<OwnedChild>,-}--impl Drop for AcpV2Connection {- fn drop(&mut self) {- // Let SDK shutdown finish its close callback before releasing the foreground owners.- drop(self.shutdown.take());- if let Some(task) = self.io_task.take() {- task.detach();- }- if let Some(task) = self.dispatch_task.take() {- task.detach();- }- }+ _child: Option<transport::OwnedChild>,}impl AcpV2Connection {@@ -101,7 +76,7 @@ impl AcpV2Connection {stderr,debug_log,} = transport::spawn_stdio(&project, command, cx)?;- let mut child = OwnedChild(child);+ let mut child = transport::OwnedChild(child);let stderr_task = cx.background_spawn(async move {stderr.await.log_err();@@ -139,51 +114,25 @@ impl AcpV2Connection {result.map_err(|error| anyhow!("failed to wait for agent server exit: {error}"))}).boxed_local();- let (mut connection, status) = match futures::future::select(initialized, status).await {- futures::future::Either::Left((Ok(connection), status)) => (connection, status),- futures::future::Either::Left((Err(error), status)) => {- let timeout = cx- .background_executor()- .timer(Duration::from_millis(250))- .boxed_local();- if let futures::future::Either::Left((status, _)) =- futures::future::select(status, timeout).await- {- return Err(exited_load_error_after_drain(- status?,- stderr_task,- &debug_log,- cx,- )- .await- .into());- }- return Err(error);- }- futures::future::Either::Right((status, _)) => {- return Err(- exited_load_error_after_drain(status?, stderr_task, &debug_log, cx)- .await- .into(),- );- }- };+ let (mut connection, status, stderr_task) =+ runtime::race_startup(initialized, status, stderr_task, &debug_log, cx).await?;let drained = {let sdk_connection = connection.connection.clone();- let dispatch_tx = connection.dispatch_tx.clone();- async move {- sdk_connection.incoming_closed().await;- drain_foreground_queue(&dispatch_tx).await.log_err();- stderr_task.await;- }+ runtime::drain_transport(+ async move { sdk_connection.incoming_closed().await },+ connection.dispatch_tx.clone(),+ stderr_task,+ )};- connection._wait_task = Some(cx.spawn(async move |cx| match status.await {- Ok(status) => {- let error = exited_load_error_after_drain(status, drained, &debug_log, cx).await;+ connection._wait_task = Some(runtime::watch_process(+ status,+ drained,+ debug_log,+ |error, _cx| {log::warn!("ACP v2 agent exited: {error}");- }- Err(error) => log::error!("ACP v2 process wait failed: {error}"),- }));+ },+ cx,+ ));connection._child = Some(child);Ok(connection)}@@ -204,42 +153,25 @@ impl AcpV2Connection {request_elicitations: request_elicitations.clone(),active_request_scopes: Some(RefCell::new(Default::default())),};- let (dispatch_tx, mut dispatch_rx) = mpsc::unbounded::<ForegroundWork>();- let dispatch_task = cx.spawn(async move |cx| {- while let Some(work) = dispatch_rx.next().await {- work.run(cx, &context);- }- });+ let (mut runtime, shutdown) = runtime::ClientRuntime::new(context, cx);+ let dispatch_tx = runtime.sender();let (sender, received) = futures::channel::oneshot::channel();- let (shutdown, shutdown_received) = futures::channel::oneshot::channel();- let io_task = cx.background_spawn({- let dispatch_tx = dispatch_tx.clone();- async move {- let cleanup = cancel_elicitations_after_disconnect(dispatch_tx.clone())- .boxed()- .shared();- let result = with_v2_client_ingress(Client.v2().name("zed-v2"), dispatch_tx)- .on_close({- let cleanup = cleanup.clone();- async move |_connection: V2ConnectionTo<Agent>| cleanup.await- })- .connect_with(transport, async move |connection| {- if sender.send(connection).is_err() {- return Err(agent_client_protocol::Error::internal_error()- .data("ACP v2 connection receiver dropped"));- }- if shutdown_received.await.is_err() {- log::debug!("ACP v2 connection owner dropped");- }- Ok(())- })- .await;- if let Err(error) = cleanup.await {- log::warn!("ACP v2 disconnect cleanup failed: {error}");- }- result.log_err();- }- });+ let cleanup = runtime::disconnect_cleanup(dispatch_tx.clone());+ let connection_future =+ with_v2_client_ingress(Client.v2().name("zed-v2"), dispatch_tx.clone())+ .on_close({+ let cleanup = cleanup.clone();+ async move |_connection: V2ConnectionTo<Agent>| cleanup.await+ })+ .connect_with(transport, async move |connection| {+ runtime::publish_connection(+ connection,+ sender,+ runtime::shutdown_requested(shutdown),+ )+ .await+ });+ runtime.start_io(runtime::finish_connection(connection_future, cleanup), cx);let connection = received.await.context("Failed to receive ACP v2 connection handle")?;@@ -274,9 +206,7 @@ impl AcpV2Connection {request_elicitations,debug_log,dispatch_tx,- io_task: Some(io_task),- dispatch_task: Some(dispatch_task),- shutdown: Some(shutdown),+ _runtime: runtime,_stderr_task: stderr_task,_wait_task: None,_child: None,@@ -402,7 +332,10 @@ mod tests {};use gpui::TestAppContext;use serde_json::json;- use std::sync::{Arc, Mutex};+ use std::{+ sync::{Arc, Mutex},+ time::Duration,+ };struct Harness {client: AcpV2Connection,