Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Shut down ACP v2 connections on teardown (#65873)

Ben Brandte70e0250a0ac
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index c4e406dc688..2c1359060ae 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -101,6 +101,11 @@ pub trait AgentConnection {
None
}
+ /// Initiate shutdown of connection-owned resources when their shared UI owner ends.
+ /// This is independent of session close and may leave retained models alive.
+ /// It does not wait for process exit or a complete protocol drain.
+ fn shutdown(&self) {}
+
fn new_session(
self: Rc<Self>,
project: Entity<Project>,
@@ -972,6 +977,7 @@ mod test_support {
next_close_responses: Arc<Mutex<VecDeque<oneshot::Receiver<Result<()>>>>>,
set_title_calls: Arc<Mutex<Vec<(acp_v2::SessionId, SharedString)>>>,
cancel_calls: Arc<Mutex<Vec<acp_v2::SessionId>>>,
+ shutdown_calls: Arc<AtomicUsize>,
next_cancel_error: Arc<Mutex<Option<anyhow::Error>>>,
supports_receipt_submissions: bool,
supports_retry: bool,
@@ -1018,6 +1024,7 @@ mod test_support {
next_close_responses: Default::default(),
set_title_calls: Default::default(),
cancel_calls: Default::default(),
+ shutdown_calls: Default::default(),
next_cancel_error: Default::default(),
permission_requests: HashMap::default(),
sessions: Arc::default(),
@@ -1043,6 +1050,10 @@ mod test_support {
*self.next_load_error.lock() = Some(error);
}
+ pub fn shutdown_calls(&self) -> usize {
+ self.shutdown_calls.load(Ordering::SeqCst)
+ }
+
pub fn set_next_prompt_updates(&self, updates: Vec<acp_v1::SessionUpdate>) {
*self.next_prompt_updates.lock() = updates
.into_iter()
@@ -1261,6 +1272,10 @@ mod test_support {
}
impl AgentConnection for StubAgentConnection {
+ fn shutdown(&self) {
+ self.shutdown_calls.fetch_add(1, Ordering::SeqCst);
+ }
+
fn agent_id(&self) -> AgentId {
self.agent_id.clone()
}
diff --git a/crates/agent_servers/src/acp/runtime.rs b/crates/agent_servers/src/acp/runtime.rs
index 70be35fd473..bdde13ced87 100644
--- a/crates/agent_servers/src/acp/runtime.rs
+++ b/crates/agent_servers/src/acp/runtime.rs
@@ -53,7 +53,10 @@ impl ClientRuntime {
future: impl Future<Output = RpcResult<()>> + Send + 'static,
cx: &AsyncApp,
) {
+ let dispatch_tx = self.dispatch_tx.clone();
self.io_task = Some(cx.background_spawn(async move {
+ // Retained API handles can keep senders alive after disconnect cleanup completes.
+ let _close_dispatch = util::defer(move || dispatch_tx.close_channel());
future.await.log_err();
}));
}
@@ -208,6 +211,7 @@ mod tests {
pending_session_updates: None,
};
let (mut runtime, shutdown) = ClientRuntime::new(context, &mut cx.to_async());
+ let retained_sender = runtime.sender();
let (transport, peer) = agent_client_protocol::Channel::duplex();
let (sender, received) = oneshot::channel();
runtime.start_io(
@@ -254,6 +258,7 @@ mod tests {
drop(store);
cx.run_until_parked();
assert!(weak_store.upgrade().is_none(), "foreground owner leaked");
+ drop(retained_sender);
}
#[test]
@@ -339,6 +344,8 @@ mod tests {
)
.expect("spawn waiting child");
let mut child = crate::acp::transport::OwnedChild(child);
+ // status() closes stdin, which must not end the child before the guard kills it.
+ let stdin = child.0.stdin.take().expect("child stdin");
let status = child.0.status();
drop(child);
let timeout = cx.background_executor.timer(Duration::from_secs(5));
@@ -349,5 +356,6 @@ mod tests {
};
use std::os::unix::process::ExitStatusExt as _;
assert_eq!(status.signal(), Some(9));
+ drop(stdin);
}
}
diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rs
index 2b954c33e0a..1338bce8d0a 100644
--- a/crates/agent_servers/src/acp/v2.rs
+++ b/crates/agent_servers/src/acp/v2.rs
@@ -196,10 +196,21 @@ pub struct AcpV2Connection {
sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
pending_session_updates: Rc<RefCell<PendingSessionUpdates>>,
session_owners: Rc<RefCell<HashMap<acp::SessionId, SessionOwner>>>,
- _runtime: runtime::ClientRuntime,
+ runtime: Rc<RefCell<Option<ConnectionRuntime>>>,
+}
+
+struct ConnectionRuntime {
+ _client: runtime::ClientRuntime,
_stderr_task: Shared<Task<()>>,
_wait_task: Option<Task<()>>,
_child: Option<transport::OwnedChild>,
+ _quit_subscription: Option<gpui::Subscription>,
+}
+
+struct StdioStartup {
+ child: transport::OwnedChild,
+ stderr_task: Shared<Task<()>>,
+ runtime: Rc<RefCell<Option<ConnectionRuntime>>>,
}
impl AcpV2Connection {
@@ -218,6 +229,13 @@ impl AcpV2Connection {
debug_log,
} = transport::spawn_stdio(&project, command, cx)?;
let mut child = transport::OwnedChild(child);
+ let status = child
+ .0
+ .status()
+ .map(|result| {
+ result.map_err(|error| anyhow!("failed to wait for agent server exit: {error}"))
+ })
+ .boxed_local();
let stderr_task = cx
.background_spawn(async move {
stderr.await.log_err();
@@ -230,10 +248,14 @@ impl AcpV2Connection {
.map(|channel| channel.display_name().to_owned()),
)
});
+ // Keep cleanup from killing the child before startup error arbitration can
+ // distinguish a protocol rejection from a natural process exit.
+ let startup_runtime = Rc::new(RefCell::new(None));
let initialized = {
let mut cx = cx.clone();
let debug_log = debug_log.clone();
let stderr_task = stderr_task.clone();
+ let runtime = startup_runtime.clone();
async move {
Self::connect(
agent_id,
@@ -241,22 +263,20 @@ impl AcpV2Connection {
Lines::new(outgoing, incoming),
info,
debug_log,
- stderr_task,
+ Some(StdioStartup {
+ child,
+ stderr_task,
+ runtime,
+ }),
&mut cx,
)
.await
}
}
.boxed_local();
- let status = child
- .0
- .status()
- .map(|result| {
- result.map_err(|error| anyhow!("failed to wait for agent server exit: {error}"))
- })
- .boxed_local();
- let (mut connection, status, stderr_task) =
- runtime::race_startup(initialized, status, stderr_task, &debug_log, cx).await?;
+ let result = runtime::race_startup(initialized, status, stderr_task, &debug_log, cx).await;
+ drop(startup_runtime);
+ let (connection, status, stderr_task) = result?;
let drained = {
let sdk_connection = connection.connection.clone();
runtime::drain_transport(
@@ -265,7 +285,11 @@ impl AcpV2Connection {
stderr_task,
)
};
- connection._wait_task = Some(runtime::watch_process(
+ let mut runtime = connection.runtime.borrow_mut();
+ let owned = runtime
+ .as_mut()
+ .context("Agent connection shut down during startup")?;
+ owned._wait_task = Some(runtime::watch_process(
status,
drained,
debug_log,
@@ -274,7 +298,7 @@ impl AcpV2Connection {
},
cx,
));
- connection._child = Some(child);
+ drop(runtime);
Ok(connection)
}
@@ -284,9 +308,13 @@ impl AcpV2Connection {
transport: impl ConnectTo<Client> + 'static,
info: acp::Implementation,
debug_log: AcpDebugLog,
- stderr_task: Shared<Task<()>>,
+ startup: Option<StdioStartup>,
cx: &mut AsyncApp,
) -> Result<Self> {
+ let (runtime, child, stderr_task) = match startup {
+ Some(startup) => (startup.runtime, Some(startup.child), startup.stderr_task),
+ None => (Rc::new(RefCell::new(None)), None, Task::ready(()).shared()),
+ };
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()));
@@ -297,8 +325,8 @@ impl AcpV2Connection {
request_elicitations: request_elicitations.clone(),
active_request_scopes: Some(RefCell::new(Default::default())),
};
- let (mut runtime, shutdown) = runtime::ClientRuntime::new(context, cx);
- let dispatch_tx = runtime.sender();
+ let (mut client_runtime, shutdown) = runtime::ClientRuntime::new(context, cx);
+ let dispatch_tx = client_runtime.sender();
let (sender, received) = futures::channel::oneshot::channel();
let cleanup = runtime::disconnect_cleanup(dispatch_tx.clone());
let connection_future =
@@ -315,7 +343,29 @@ impl AcpV2Connection {
)
.await
});
- runtime.start_io(runtime::finish_connection(connection_future, cleanup), cx);
+ client_runtime.start_io(runtime::finish_connection(connection_future, cleanup), cx);
+ *runtime.borrow_mut() = Some(ConnectionRuntime {
+ _client: client_runtime,
+ _stderr_task: stderr_task,
+ _wait_task: None,
+ _child: child,
+ _quit_subscription: None,
+ });
+ let quit = cx.update(|cx| {
+ cx.on_app_quit({
+ let runtime = Rc::downgrade(&runtime);
+ move |_| {
+ if let Some(runtime) = runtime.upgrade() {
+ let owned = runtime.borrow_mut().take();
+ drop(owned);
+ }
+ async {}
+ }
+ })
+ });
+ if let Some(runtime) = runtime.borrow_mut().as_mut() {
+ runtime._quit_subscription = Some(quit);
+ }
let connection = received
.await
.context("Failed to receive ACP v2 connection handle")?;
@@ -341,6 +391,10 @@ impl AcpV2Connection {
if initialize_response.protocol_version != ProtocolVersion::V2 {
return Err(UnsupportedVersion.into());
}
+ anyhow::ensure!(
+ runtime.borrow().is_some(),
+ "Agent connection shut down during startup"
+ );
Ok(Self {
id,
connection,
@@ -353,10 +407,7 @@ impl AcpV2Connection {
sessions,
pending_session_updates,
session_owners: Rc::new(RefCell::new(HashMap::default())),
- _runtime: runtime,
- _stderr_task: stderr_task,
- _wait_task: None,
- _child: None,
+ runtime,
})
}
@@ -1142,6 +1193,11 @@ impl AcpV2Connection {
}
impl AgentConnection for AcpV2Connection {
+ fn shutdown(&self) {
+ let runtime = self.runtime.borrow_mut().take();
+ drop(runtime);
+ }
+
fn agent_id(&self) -> AgentId {
self.id.clone()
}
@@ -2023,7 +2079,7 @@ mod tests {
client_transport,
acp::Implementation::new("test", "1"),
AcpDebugLog::default(),
- Task::ready(()).shared(),
+ None,
&mut cx.to_async(),
),
cx,
@@ -3779,7 +3835,14 @@ done
cx: &mut TestAppContext,
) {
use acp_thread::{SubmissionDisconnected, SubmissionResponse, SubmissionState};
- for outcome in ["cancelled", "echoed", "unechoed", "dropped", "eof"] {
+ for outcome in [
+ "cancelled",
+ "echoed",
+ "unechoed",
+ "dropped",
+ "eof",
+ "shutdown",
+ ] {
let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
let thread = harness
.resumed_thread(
@@ -3842,9 +3905,14 @@ done
receipt
.respond(acp::PromptResponse::new("unobserved"))
.expect("unobserved receipt");
- } else if outcome == "eof" {
- drop(harness._agent_task);
- drop(harness.agent);
+ } else if outcome == "eof" || outcome == "shutdown" {
+ if outcome == "shutdown" {
+ harness.client.shutdown();
+ harness.client.shutdown();
+ } else {
+ drop(harness._agent_task);
+ drop(harness.agent);
+ }
let error = bounded(sending, cx)
.await
.expect_err("receipt observes transport loss");
@@ -5951,7 +6019,7 @@ done
client_transport,
acp::Implementation::new("client-test", "1"),
AcpDebugLog::default(),
- Task::ready(()).shared(),
+ None,
&mut cx.to_async(),
),
cx,
@@ -6586,7 +6654,7 @@ done
client_transport,
acp::Implementation::new("client", "1"),
AcpDebugLog::default(),
- Task::ready(()).shared(),
+ None,
&mut cx.to_async(),
),
cx,
@@ -6667,7 +6735,7 @@ done
client_transport,
acp::Implementation::new("test", "1"),
AcpDebugLog::default(),
- Task::ready(()).shared(),
+ None,
&mut cx.to_async(),
),
cx,
@@ -6690,6 +6758,233 @@ done
assert_eq!(task.env.get("EXTRA").map(String::as_str), Some("2"));
}
+ #[cfg(unix)]
+ #[gpui::test]
+ async fn v2_stdio_shutdown_terminates_a_retained_connection(cx: &mut TestAppContext) {
+ 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;
+ for quitting in [false, true] {
+ let client = bounded(
+ AcpV2Connection::stdio(
+ AgentId::new("shutdown-test"),
+ project.clone(),
+ 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":"shutdown-agent","version":"1"}}}\n' "$id"
+ ;;
+ esac
+done
+exec sleep 60
+"#
+ .into(),
+ ],
+ env: None,
+ },
+ WeakEntity::new_invalid(),
+ &mut cx.to_async(),
+ ),
+ cx,
+ )
+ .await
+ .expect("initialize stdio");
+ let status = client
+ .runtime
+ .borrow_mut()
+ .as_mut()
+ .expect("live runtime")
+ ._child
+ .as_mut()
+ .expect("owned process")
+ .0
+ .status();
+ let pending = cx.background_spawn(
+ client
+ .connection
+ .send_request(acp::LogoutAuthRequest::new())
+ .block_task(),
+ );
+ cx.run_until_parked();
+ if quitting {
+ cx.update(|cx| cx.shutdown());
+ } else {
+ client.shutdown();
+ }
+ client.shutdown();
+ let status = bounded(status, cx)
+ .await
+ .expect("wait for terminated agent");
+ use std::os::unix::process::ExitStatusExt as _;
+ assert_eq!(status.signal(), Some(9));
+ assert!(
+ bounded(pending, cx).await.is_err(),
+ "shutdown settles pending RPCs"
+ );
+ assert!(client.runtime.borrow().is_none());
+ }
+ }
+
+ #[cfg(unix)]
+ #[gpui::test]
+ async fn v2_shutdown_terminates_a_process_during_initialization(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 = transport::OwnedChild(child);
+ // status() closes the child's stdin; keep it open so only shutdown ends the process.
+ let stdin = child.0.stdin.take().expect("child stdin");
+ let status = child.0.status();
+ let (transport, _peer) = agent_client_protocol::Channel::duplex();
+ let connecting = cx.spawn(async move |mut cx| {
+ AcpV2Connection::connect(
+ AgentId::new("pending-shutdown"),
+ WeakEntity::new_invalid(),
+ transport,
+ acp::Implementation::new("client", "1"),
+ AcpDebugLog::default(),
+ Some(StdioStartup {
+ child,
+ stderr_task: Task::ready(()).shared(),
+ runtime: Rc::new(RefCell::new(None)),
+ }),
+ &mut cx,
+ )
+ .await
+ });
+ cx.run_until_parked();
+ cx.update(|cx| cx.shutdown());
+ let status = bounded(status, cx)
+ .await
+ .expect("process terminated during startup");
+ use std::os::unix::process::ExitStatusExt as _;
+ assert_eq!(status.signal(), Some(9));
+ drop(stdin);
+ assert!(
+ bounded(connecting, cx).await.is_err(),
+ "initialization failed on shutdown"
+ );
+ }
+
+ #[cfg(unix)]
+ #[gpui::test]
+ async fn v2_stdio_startup_preserves_rejections_before_cleanup(cx: &mut TestAppContext) {
+ 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;
+ for (response, expected) in [
+ (
+ r#""error":{"code":-32022,"message":"Unsupported protocol version","data":{"requested":2,"supported":[1]}}"#,
+ Some(
+ agent_client_protocol::Error::new(-32022, "Unsupported protocol version")
+ .data(json!({"requested": 2, "supported": [1]})),
+ ),
+ ),
+ (
+ r#""error":{"code":-32602,"message":"Invalid initialize parameters","data":{"field":"capabilities"}}"#,
+ Some(
+ agent_client_protocol::Error::invalid_params()
+ .data(json!({"field": "capabilities"})),
+ ),
+ ),
+ (
+ r#""result":{"protocolVersion":1,"info":{"name":"v1-peer","version":"1"}}"#,
+ None,
+ ),
+ ] {
+ // Linux pidfd polling needs stable task wakers, not the test root's tracing wakers.
+ let connecting = cx.spawn({
+ let project = project.clone();
+ async move |mut cx| {
+ AcpV2Connection::stdio(
+ AgentId::new("startup-rejection"),
+ project,
+ AgentServerCommand {
+ path: "/bin/sh".into(),
+ args: vec![
+ "-c".into(),
+ r#"
+while IFS= read -r request; do
+ case "$request" in
+ *'"method":"initialize"'*)
+ id=${request#*\"id\":}
+ id=${id%%,*}
+ printf '{"jsonrpc":"2.0","id":%s,%s}\n' "$id" "$ACP_STARTUP_RESPONSE"
+ ;;
+ esac
+done
+exec sleep 60
+"#
+ .into(),
+ ],
+ env: Some(HashMap::from_iter([(
+ "ACP_STARTUP_RESPONSE".into(),
+ response.into(),
+ )])),
+ },
+ WeakEntity::new_invalid(),
+ &mut cx,
+ )
+ .await
+ }
+ });
+ let error = bounded(connecting, cx)
+ .await
+ .err()
+ .expect("startup rejection");
+ if let Some(expected) = expected {
+ let actual = error
+ .downcast_ref::<agent_client_protocol::Error>()
+ .unwrap_or_else(|| panic!("startup diagnostic was replaced: {error:?}"));
+ assert_eq!(actual.code, expected.code);
+ assert_eq!(actual.data, expected.data);
+ } else {
+ let actual = error
+ .downcast_ref::<agent_client_protocol::Error>()
+ .unwrap_or_else(|| panic!("version diagnostic was replaced: {error:?}"));
+ assert_eq!(
+ actual.code,
+ agent_client_protocol::Error::new(-32600, "Invalid request").code
+ );
+ assert!(
+ actual
+ .data
+ .as_ref()
+ .and_then(|data| data.as_str())
+ .is_some_and(
+ |message| message.contains("required ACP protocol version 2")
+ && message.contains("peer negotiated 1")
+ ),
+ "{actual:?}"
+ );
+ }
+ }
+ }
+
#[cfg(unix)]
#[gpui::test]
async fn v2_auth_stdio_uses_one_launcher_and_preserves_errors_and_exit_stderr(
diff --git a/crates/agent_ui/src/agent_connection_store.rs b/crates/agent_ui/src/agent_connection_store.rs
index 66b1ef2c21e..76e292280c6 100644
--- a/crates/agent_ui/src/agent_connection_store.rs
+++ b/crates/agent_ui/src/agent_connection_store.rs
@@ -1,4 +1,4 @@
-use std::rc::Rc;
+use std::rc::{Rc, Weak};
use acp_thread::{AgentConnection, LoadError};
use agent_servers::AcpConnection;
@@ -69,6 +69,8 @@ pub struct ActiveAcpConnection {
pub struct AgentConnectionStore {
project: Entity<Project>,
entries: HashMap<Agent, Entity<AgentConnectionEntry>>,
+ owned_connections: Vec<Weak<dyn AgentConnection>>,
+ shutdown: Option<watch::Sender<()>>,
_subscriptions: Vec<Subscription>,
}
@@ -76,10 +78,31 @@ impl AgentConnectionStore {
pub fn new(project: Entity<Project>, cx: &mut Context<Self>) -> Self {
let agent_server_store = project.read(cx).agent_server_store().clone();
let subscription = cx.subscribe(&agent_server_store, Self::handle_agent_servers_updated);
+ let (shutdown, _) = watch::channel(());
+ cx.on_release(|this, _| this.shutdown_connections())
+ .detach();
+ let quit = cx.on_app_quit(|this, _| {
+ this.shutdown_connections();
+ async {}
+ });
Self {
project,
entries: HashMap::default(),
- _subscriptions: vec![subscription],
+ owned_connections: Vec::new(),
+ shutdown: Some(shutdown),
+ _subscriptions: vec![subscription, quit],
+ }
+ }
+
+ fn shutdown_connections(&mut self) {
+ drop(self.shutdown.take());
+ // Cache replacement must not hide a connection retained by an older view or receipt.
+ for connection in self
+ .owned_connections
+ .drain(..)
+ .filter_map(|owner| owner.upgrade())
+ {
+ connection.shutdown();
}
}
@@ -300,14 +323,218 @@ impl AgentConnectionStore {
Some(loading_status_tx),
);
- let connect_task = server.connect(delegate, self.project.clone(), cx);
- let connect_task = cx.spawn(async move |_this, _cx| match connect_task.await {
- Ok(connection) => Ok(AgentConnectedState { connection }),
- Err(err) => match err.downcast::<LoadError>() {
- Ok(load_error) => Err(load_error),
- Err(err) => Err(LoadError::Other(SharedString::from(err.to_string()))),
- },
+ let shutdown = self.shutdown.as_ref().map(watch::Sender::receiver);
+ let connect_task =
+ shutdown.map(|shutdown| (server.connect(delegate, self.project.clone(), cx), shutdown));
+ let connect_task = cx.spawn(async move |this, cx| {
+ let owner_released = || LoadError::Other("Agent connection owner was released".into());
+ let Some((connect_task, mut shutdown)) = connect_task else {
+ return Err(owner_released());
+ };
+ let stopped = shutdown.changed();
+ futures::pin_mut!(stopped);
+ let result = match futures::future::select(connect_task, stopped).await {
+ futures::future::Either::Left((result, _)) => result,
+ futures::future::Either::Right(_) => return Err(owner_released()),
+ };
+ let connection = result.map_err(|error| match error.downcast::<LoadError>() {
+ Ok(error) => error,
+ Err(error) => LoadError::Other(error.to_string().into()),
+ })?;
+ let registered = this
+ .update(cx, |this, _| {
+ if this.shutdown.is_none() {
+ return false;
+ }
+ this.owned_connections
+ .retain(|connection| connection.strong_count() > 0);
+ this.owned_connections.push(Rc::downgrade(&connection));
+ true
+ })
+ .is_ok_and(|registered| registered);
+ if !registered {
+ connection.shutdown();
+ return Err(owner_released());
+ }
+ Ok(AgentConnectedState { connection })
});
(new_version_rx, loading_status_rx, connect_task)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::conversation_view::tests::{StubAgentServer, init_test};
+ use acp_thread::StubAgentConnection;
+ use fs::FakeFs;
+ use gpui::TestAppContext;
+ use std::{
+ any::Any,
+ path::Path,
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+ };
+
+ #[gpui::test]
+ async fn test_connection_owner_shutdown_includes_replaced_connections(cx: &mut TestAppContext) {
+ init_test(cx);
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree("/project", serde_json::json!({})).await;
+ let project = Project::test(fs, [Path::new("/project")], cx).await;
+ for quitting in [false, true] {
+ let store = cx.new(|cx| AgentConnectionStore::new(project.clone(), cx));
+ let original = StubAgentConnection::new();
+ let replacement = StubAgentConnection::new();
+ let entry = store.update(cx, |store, cx| {
+ store.request_connection(
+ Agent::Stub,
+ Rc::new(StubAgentServer::new(original.clone())),
+ cx,
+ )
+ });
+ let observer = entry.read_with(cx, |entry, _| entry.wait_for_connection());
+ let connected = observer.await.expect("connected");
+ cx.run_until_parked();
+ let other_view = connected.clone();
+ drop(connected);
+ assert_eq!(
+ original.shutdown_calls(),
+ 0,
+ "one observer is not the owner"
+ );
+ let replacement_entry = store.update(cx, |store, cx| {
+ store.restart_connection(
+ Agent::Stub,
+ Rc::new(StubAgentServer::new(replacement.clone())),
+ cx,
+ )
+ });
+ let connected = replacement_entry
+ .read_with(cx, |entry, _| entry.wait_for_connection())
+ .await
+ .expect("replacement connected");
+ cx.run_until_parked();
+ assert_eq!(
+ original.shutdown_calls(),
+ 0,
+ "restart preserves older views"
+ );
+ if quitting {
+ cx.update(|cx| cx.shutdown());
+ assert_eq!(original.shutdown_calls(), 1);
+ assert_eq!(replacement.shutdown_calls(), 1);
+ let late = store.update(cx, |store, cx| {
+ store.restart_connection(
+ Agent::Stub,
+ Rc::new(StubAgentServer::new(StubAgentConnection::new())),
+ cx,
+ )
+ });
+ assert!(
+ late.read_with(cx, |entry, _| entry.wait_for_connection())
+ .await
+ .is_err(),
+ "an ended owner cannot start another connection"
+ );
+ }
+ drop(store);
+ cx.update(|_| ());
+ cx.run_until_parked();
+ assert_eq!(original.shutdown_calls(), 1);
+ assert_eq!(replacement.shutdown_calls(), 1);
+ assert!(original.take_close_session_calls().is_empty());
+ assert!(replacement.take_close_session_calls().is_empty());
+ drop(other_view);
+ drop(connected);
+ }
+ }
+
+ struct PendingAgentServer {
+ started: Arc<AtomicBool>,
+ dropped: Arc<AtomicBool>,
+ }
+
+ impl AgentServer for PendingAgentServer {
+ fn logo(&self) -> ui::IconName {
+ ui::IconName::ZedAgent
+ }
+
+ fn agent_id(&self) -> project::AgentId {
+ "pending".into()
+ }
+
+ fn connect(
+ &self,
+ _delegate: AgentServerDelegate,
+ _project: Entity<Project>,
+ cx: &mut App,
+ ) -> Task<Result<Rc<dyn AgentConnection>>> {
+ let started = self.started.clone();
+ let dropped = self.dropped.clone();
+ cx.foreground_executor().spawn(async move {
+ let _guard = util::defer(move || dropped.store(true, Ordering::SeqCst));
+ started.store(true, Ordering::SeqCst);
+ futures::future::pending().await
+ })
+ }
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+ }
+
+ #[gpui::test]
+ async fn test_connection_owner_shutdown_cancels_pending_startup(cx: &mut TestAppContext) {
+ init_test(cx);
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree("/project", serde_json::json!({})).await;
+ let project = Project::test(fs, [Path::new("/project")], cx).await;
+ for quitting in [false, true] {
+ let store = cx.new(|cx| AgentConnectionStore::new(project.clone(), cx));
+ let started = Arc::new(AtomicBool::new(false));
+ let dropped = Arc::new(AtomicBool::new(false));
+ let entry = store.update(cx, |store, cx| {
+ store.request_connection(
+ Agent::Stub,
+ Rc::new(PendingAgentServer {
+ started: started.clone(),
+ dropped: dropped.clone(),
+ }),
+ cx,
+ )
+ });
+ let pending = entry.read_with(cx, |entry, _| entry.wait_for_connection());
+ cx.run_until_parked();
+ assert!(started.load(Ordering::SeqCst));
+ if quitting {
+ cx.update(|cx| cx.shutdown());
+ } else {
+ drop(store);
+ cx.update(|_| ());
+ }
+ assert!(pending.await.is_err());
+ cx.run_until_parked();
+ assert!(dropped.load(Ordering::SeqCst));
+ }
+ let store = cx.new(|cx| AgentConnectionStore::new(project.clone(), cx));
+ let connection = StubAgentConnection::new();
+ let entry = store.update(cx, |store, cx| {
+ store.request_connection(
+ Agent::Stub,
+ Rc::new(StubAgentServer::new(connection.clone())),
+ cx,
+ )
+ });
+ let pending = entry.read_with(cx, |entry, _| entry.wait_for_connection());
+ drop(store);
+ cx.update(|_| ());
+ assert!(
+ pending.await.is_err(),
+ "late success cannot outlive its owner"
+ );
+ assert_eq!(connection.shutdown_calls(), 1);
+ }
+}