Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent_servers: Route ACP subagent associations to child threads (#65976)
Ben Brandt6744a21e2d56
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 0bbd96a6391..cafc803c55f 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -9,6 +9,7 @@ pub mod elicitation;mod mention;pub mod notices;pub mod prompt_capabilities;+pub mod subagents;mod submission;mod terminal;pub use ::terminal::HeadlessTerminal;@@ -3491,6 +3492,8 @@ pub struct AcpThread {parent_session_id: Option<acp_v2::SessionId>,/// Child sessions this session owns, such as subagents, in registration order.subagents: IndexMap<acp_v2::SessionId, Entity<AcpThread>>,+ /// Set when this session is an ACP subagent announced by its parent.+ subagent_association: Option<subagents::SubagentAssociation>,provisional_title: Option<SharedString>,entries: Vec<AgentThreadEntry>,// Notices stay with the live session, but never enter conversation history or exports.@@ -3871,6 +3874,7 @@ impl AcpThread {elicitations: ElicitationStore::default(),permission_requests: IndexMap::default(),subagents: IndexMap::default(),+ subagent_association: None,plans: HashMap::default(),visible_plan: None,provisional_title: None,@@ -3908,15 +3912,34 @@ impl AcpThread {}}- /// Marks a session whose work the agent owns, such as an ACP subagent. Zed cannot+ /// Marks an ACP subagent session, whose work its parent agent owns. Zed cannot/// submit prompts to it, and its foreground state is unconfirmed until the agent/// reports one.pub fn agent_owned(mut self) -> Self {self.submissions = SessionSubmissions::new(SubmissionTransport::AgentOwned);self.activity.mark_unconfirmed();+ self.subagent_association = Some(subagents::SubagentAssociation::default());self}+ pub fn subagent_association(&self) -> Option<&subagents::SubagentAssociation> {+ self.subagent_association.as_ref()+ }++ pub fn update_subagent_association(+ &mut self,+ update: &acp_v2::SubagentUpdate,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ let association = self+ .subagent_association+ .as_mut()+ .context("Session is not an ACP subagent")?;+ association.apply(update);+ cx.notify();+ Ok(())+ }+pub fn parent_session_id(&self) -> Option<&acp_v2::SessionId> {self.parent_session_id.as_ref()}@@ -4558,6 +4581,21 @@ impl AcpThread {Ok(())}+ /// Forgets the reported foreground state without implying idle, as when an ACP+ /// subagent association clears its `state`. Work in progress stays in progress.+ pub fn clear_session_state(&mut self, cx: &mut Context<Self>) -> Result<()> {+ anyhow::ensure!(+ self.uses_reported_activity(),+ "Session does not report foreground state"+ );+ let previous = self.foreground_activity();+ self.activity.mark_unconfirmed();+ if previous != self.foreground_activity() {+ cx.emit(AcpThreadEvent::StatusChanged);+ }+ Ok(())+ }+pub fn cost(&self) -> Option<&SessionCost> {self.cost.as_ref()}diff --git a/crates/acp_thread/src/subagents.rs b/crates/acp_thread/src/subagents.rsnew file mode 100644index 00000000000..f0d889312a6--- /dev/null+++ b/crates/acp_thread/src/subagents.rs@@ -0,0 +1,170 @@+use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};+use anyhow::Result;+use gpui::SharedString;++/// What a parent ACP session has reported about a subagent session it owns.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct SubagentAssociation {+ /// The parent's label for the subagent, which can differ from the subagent's own title.+ pub title: Option<SharedString>,+ pub description: Option<SharedString>,+ /// Whether Zed may cancel the subagent's current work.+ pub can_cancel: bool,+}++impl SubagentAssociation {+ /// Omitted fields stay unchanged and `null` clears them. `state` is not stored here:+ /// it is the subagent's activity, which lives on the subagent's own thread.+ pub fn apply(&mut self, update: &acp_v2::SubagentUpdate) {+ if let Some(title) = update.title.as_opt_ref() {+ self.title = title.map(|title| title.clone().into());+ }+ if let Some(description) = update.description.as_opt_ref() {+ self.description = description.map(|description| description.clone().into());+ }+ if let Some(capabilities) = update.capabilities.as_opt_ref() {+ self.can_cancel =+ capabilities.is_some_and(|capabilities| capabilities.cancel.is_some());+ }+ }+}++/// Association metadata is not carried over: Zed does not use it, and v1 replaces it+/// where v2 patches it by key.+pub fn update_from_v1(update: acp_v1::SubagentUpdate) -> Result<acp_v2::SubagentUpdate> {+ let state = match update.state {+ MaybeUndefined::Undefined => MaybeUndefined::Undefined,+ MaybeUndefined::Null => MaybeUndefined::Null,+ MaybeUndefined::Value(state) => MaybeUndefined::Value(state_from_v1(state)?),+ };+ Ok(acp_v2::SubagentUpdate::new(update.session_id.0)+ .title(update.title)+ .description(update.description)+ .capabilities(update.capabilities.map_value(|capabilities| {+ acp_v2::SubagentSessionCapabilities::new()+ .cancel(+ capabilities+ .cancel+ .map(|cancel| acp_v2::SessionCancelCapabilities::new().meta(cancel.meta)),+ )+ .meta(capabilities.meta)+ }))+ .state(state))+}++/// The subagents RFD gives the v1 snapshot the same wire shape as the v2 `state_update`,+/// so converting through JSON keeps unknown states and stop reasons intact.+fn state_from_v1(state: acp_v1::StateUpdate) -> Result<acp_v2::StateUpdate> {+ Ok(serde_json::from_value(serde_json::to_value(state)?)?)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn v2_update(value: serde_json::Value) -> acp_v2::SubagentUpdate {+ serde_json::from_value(value).expect("v2 subagent update")+ }++ #[test]+ fn association_fields_follow_patch_semantics() {+ let mut association = SubagentAssociation::default();+ association.apply(&v2_update(json!({+ "sessionId": "child",+ "title": "Investigator",+ "description": "Looks into failures",+ "capabilities": {"cancel": {}},+ })));+ let announced = SubagentAssociation {+ title: Some("Investigator".into()),+ description: Some("Looks into failures".into()),+ can_cancel: true,+ };+ assert_eq!(association, announced);++ association.apply(&v2_update(json!({"sessionId": "child"})));+ assert_eq!(association, announced, "omitted fields are unchanged");++ association.apply(&v2_update(json!({+ "sessionId": "child",+ "title": null,+ "capabilities": {"cancel": null},+ })));+ assert_eq!(+ association,+ SubagentAssociation {+ title: None,+ description: Some("Looks into failures".into()),+ can_cancel: false,+ },+ "null clears a field, and capabilities are replaced as a whole"+ );++ association.apply(&v2_update(json!({+ "sessionId": "child",+ "capabilities": {"cancel": {}},+ })));+ association.apply(&v2_update(+ json!({"sessionId": "child", "capabilities": null}),+ ));+ assert!(!association.can_cancel, "null capabilities disable cancel");+ }++ #[test]+ fn v1_updates_convert_fields_and_state_snapshots() -> Result<()> {+ for (v1, expected) in [+ (+ json!({+ "sessionId": "child",+ "title": "Investigator",+ "description": null,+ "capabilities": {"cancel": {}},+ "state": {"state": "running"},+ "_meta": {"dropped": true},+ }),+ json!({+ "sessionId": "child",+ "title": "Investigator",+ "description": null,+ "capabilities": {"cancel": {}},+ "state": {"state": "running"},+ }),+ ),+ (+ json!({+ "sessionId": "child",+ "state": {+ "state": "idle",+ "stopReason": "error",+ "error": {"code": -32000, "message": "Authentication required"},+ },+ }),+ json!({+ "sessionId": "child",+ "state": {+ "state": "idle",+ "stopReason": "error",+ "error": {"code": -32000, "message": "Authentication required"},+ },+ }),+ ),+ (+ json!({"sessionId": "child", "state": {"state": "unknown"}}),+ json!({"sessionId": "child", "state": {"state": "unknown"}}),+ ),+ (+ json!({"sessionId": "child", "state": {"state": "_paused", "reason": "x"}}),+ json!({"sessionId": "child", "state": {"state": "_paused", "reason": "x"}}),+ ),+ (+ json!({"sessionId": "child", "state": null, "capabilities": null}),+ json!({"sessionId": "child", "state": null, "capabilities": null}),+ ),+ ] {+ let converted = update_from_v1(serde_json::from_value(v1.clone())?)?;+ assert_eq!(serde_json::to_value(&converted)?, expected, "{v1}");+ }+ Ok(())+ }+}diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex fc8c7ad5a3c..e613c8cd2c8 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -16,6 +16,7 @@ pub use v1::{AcpConnection, AcpSessionList, GEMINI_TERMINAL_AUTH_METHOD_ID};pub use v2::AcpV2Connection;use acp_thread::{AcpThread, AuthRequired, ElicitationStore, LoadError};+use action_log::ActionLog;use agent_client_protocol::schema::{v1::{self as acp, ErrorCode},v2 as acp_v2,@@ -28,7 +29,7 @@ use anyhow::{Context as _, Result, anyhow};use collections::{HashMap, HashSet};use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};use futures::{Future, channel::mpsc};-use gpui::{App, AsyncApp, Entity, SharedString, Subscription, Task, WeakEntity};+use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Subscription, Task, WeakEntity};use project::agent_server_store::{AgentServerCommand, AgentServerStore};use project::context_server_store::ContextServerConfiguration;use project::{AgentId, Project};@@ -246,6 +247,9 @@ struct ClientContext {request_elicitations: Entity<ElicitationStore>,// Legacy and ingress-only contexts do not track caller ownership of outgoing RPCs.active_request_scopes: Option<RefCell<HashSet<acp_v2::RequestId>>>,+ /// A v1 agent may only send `subagent_update` after Zed advertises the `subagents`+ /// client capability. v2 includes subagents in every session.+ accepts_subagent_updates: bool,}fn dispatch_queue_closed_error() -> acp::Error {@@ -743,12 +747,115 @@ fn close_undelivered_session(.log_err();}+/// Applies a `subagent_update` received on `parent`'s stream. The first update for a+/// session announces it: Zed creates its thread, routes the session's traffic on this+/// connection, and hands the thread to the parent. Later updates patch the association.+/// The update's `state` is left to the caller, since only v1 uses it as the subagent's+/// activity.+fn apply_subagent_update(+ parent: &Entity<AcpThread>,+ update: &acp_v2::SubagentUpdate,+ sessions: &Rc<RefCell<HashMap<acp_v2::SessionId, AcpSession>>>,+ cx: &mut App,+) -> Result<Entity<AcpThread>> {+ let parent_session_id = parent.read(cx).session_id().clone();+ let session_id = update.session_id.clone();+ if let Some(subagent) = parent.read(cx).subagent(&session_id).cloned() {+ subagent.update(cx, |subagent, cx| {+ subagent.update_subagent_association(update, cx)+ })?;+ return Ok(subagent);+ }+ // Announcing any other session this connection routes, including the parent itself,+ // would reparent it, so this also rules out cycles.+ anyhow::ensure!(+ !sessions.borrow().contains_key(&session_id),+ "Session {session_id} cannot become a subagent of {parent_session_id}"+ );++ let (connection, project, parent_action_log) = {+ let parent = parent.read(cx);+ (+ parent.connection().clone(),+ parent.project().clone(),+ parent.action_log().clone(),+ )+ };+ let action_log =+ cx.new(|_| ActionLog::new(project.clone()).with_linked_action_log(parent_action_log));+ let subagent = cx.new(|cx| {+ AcpThread::new(+ Some(parent_session_id),+ None,+ None,+ connection,+ project,+ action_log,+ session_id.clone(),+ watch::Receiver::constant(acp_v2::PromptCapabilities::default()),+ cx,+ )+ .agent_owned()+ });+ subagent.update(cx, |subagent, cx| {+ subagent.update_subagent_association(update, cx)+ })?;+ // Unlike a session Zed opened, releasing a subagent must not close it: the agent+ // releases subagents when their parent closes.+ let release_subscription = cx.observe_release(&subagent, {+ let sessions = Rc::downgrade(sessions);+ let session_id = session_id.clone();+ let thread_id = subagent.entity_id();+ move |_, _| {+ let Some(sessions) = sessions.upgrade() else {+ return;+ };+ let mut sessions = sessions.borrow_mut();+ if sessions+ .get(&session_id)+ .is_some_and(|session| session.thread.entity_id() == thread_id)+ {+ sessions.remove(&session_id);+ }+ }+ });+ sessions.borrow_mut().insert(+ session_id,+ AcpSession {+ thread: subagent.downgrade(),+ suppress_abort_err: false,+ session_modes: None,+ config_options: None,+ default_config_task: None,+ _release_subscription: release_subscription,+ },+ );+ parent.update(cx, |parent, cx| {+ parent.register_subagent(subagent.clone(), cx)+ });+ Ok(subagent)+}+fn apply_v2_session_notification(notification: InboundSessionNotification,thread: &WeakEntity<AcpThread>,- sessions: &RefCell<HashMap<acp_v2::SessionId, AcpSession>>,+ sessions: &Rc<RefCell<HashMap<acp_v2::SessionId, AcpSession>>>,cx: &mut AsyncApp,) -> Result<()> {+ if let InboundSessionUpdate::Subagent(update) = ¬ification.update {+ let parent = thread+ .upgrade()+ .context("Session was released before its subagent was announced")?;+ let parent_session_id = parent.read_with(cx, |parent, _| parent.session_id().clone());+ anyhow::ensure!(+ parent_session_id == notification.session_id,+ "Subagent update belongs to a different ACP session"+ );+ // In v2 the subagent's own `state_update` reports its activity; the parent's copy+ // only mirrors it.+ cx.update(|cx| apply_subagent_update(&parent, update, sessions, cx))?;+ return Ok(());+ }if let InboundSessionUpdate::ConfigOptions(update) = ¬ification.update {let config_options = {let mut sessions = sessions.borrow_mut();diff --git a/crates/agent_servers/src/acp/runtime.rs b/crates/agent_servers/src/acp/runtime.rsindex bdde13ced87..ffd788eed68 100644--- a/crates/agent_servers/src/acp/runtime.rs+++ b/crates/agent_servers/src/acp/runtime.rs@@ -209,6 +209,7 @@ mod tests {request_elicitations: store.clone(),active_request_scopes: None,pending_session_updates: None,+ accepts_subagent_updates: false,};let (mut runtime, shutdown) = ClientRuntime::new(context, &mut cx.to_async());let retained_sender = runtime.sender();diff --git a/crates/agent_servers/src/acp/session_updates.rs b/crates/agent_servers/src/acp/session_updates.rsindex 6677913540a..cc2bdf06b4d 100644--- a/crates/agent_servers/src/acp/session_updates.rs+++ b/crates/agent_servers/src/acp/session_updates.rs@@ -172,6 +172,9 @@ pub enum InboundSessionUpdate {Notice(acp_v2::Notice),Compaction(acp_v2::CompactionUpdate),CompactionSummary(acp_v2::CompactionSummaryChunk),+ /// Creates or patches a subagent session, so the connection applies it rather than+ /// the parent thread.+ Subagent(acp_v2::SubagentUpdate),}impl From<DecodedTerminalNotification> for InboundSessionNotification {@@ -245,6 +248,7 @@ impl TryFrom<acp_v2::UpdateSessionNotification> for InboundSessionNotification {acp_v2::SessionUpdate::CompactionSummaryChunk(chunk) => {InboundSessionUpdate::CompactionSummary(chunk)}+ acp_v2::SessionUpdate::SubagentUpdate(update) => InboundSessionUpdate::Subagent(update),update => {notification.update = update;return Err(notification);@@ -332,6 +336,9 @@ impl InboundSessionNotification {thread.append_context_compaction_summary(chunk, cx);Ok(())}+ InboundSessionUpdate::Subagent(_) => {+ anyhow::bail!("Subagent updates must be applied by the ACP connection")+ }}}}diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rsindex 4289e873ddd..9e8f7386633 100644--- a/crates/agent_servers/src/acp/v1.rs+++ b/crates/agent_servers/src/acp/v1.rs@@ -1,10 +1,10 @@use super::{AcpDebugLog, AcpDebugMessage, AcpSession, ClientContext, ConfigOptions, FlattenAcpResult as _,- ForegroundWork, UnsupportedVersion, drain_foreground_queue, enqueue_notification,- enqueue_request, first_class_terminal_auth_task, handle_v2_complete_elicitation,- handle_v2_create_elicitation, map_acp_error, mcp_configurations_for_project, respond_err,- respond_result, runtime, session_thread, terminal_auth_task_id, transport,- with_v2_client_ingress, work_dirs_from_session_info,+ ForegroundWork, UnsupportedVersion, apply_subagent_update, drain_foreground_queue,+ enqueue_notification, enqueue_request, first_class_terminal_auth_task,+ handle_v2_complete_elicitation, handle_v2_create_elicitation, map_acp_error,+ mcp_configurations_for_project, respond_err, respond_result, runtime, session_thread,+ terminal_auth_task_id, transport, with_v2_client_ingress, work_dirs_from_session_info,};use acp_thread::{AgentConnection, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,@@ -12,7 +12,7 @@ use acp_thread::{};use action_log::ActionLog;use agent_client_protocol::schema::{- ProtocolVersion,+ MaybeUndefined, ProtocolVersion,v1::{self as acp, ErrorCode},v2 as acp_v2,};@@ -526,6 +526,7 @@ impl AcpConnection {let client_session_list: Rc<RefCell<Option<Rc<AcpSessionList>>>> =Rc::new(RefCell::new(None));let request_elicitations = cx.new(|_| ElicitationStore::default());+ let client_capabilities = client_capabilities_for_agent(&agent_id);let dispatch_context = ClientContext {sessions: sessions.clone(),@@ -533,6 +534,7 @@ impl AcpConnection {request_elicitations: request_elicitations.clone(),active_request_scopes: None,pending_session_updates: None,+ accepts_subagent_updates: client_capabilities.subagents.is_some(),};let (mut runtime, shutdown) = runtime::ClientRuntime::new(dispatch_context, cx);let dispatch_tx = runtime.sender();@@ -587,7 +589,7 @@ impl AcpConnection {let initialize_response = connection.send_request(acp::InitializeRequest::new(ProtocolVersion::V1)- .client_capabilities(client_capabilities_for_agent(&agent_id))+ .client_capabilities(client_capabilities).client_info(acp::Implementation::new("zed", version).title(release_channel.map(ToOwned::to_owned)),@@ -2181,6 +2183,7 @@ pub mod test_support {request_elicitations: request_elicitations.clone(),active_request_scopes: None,pending_session_updates: None,+ accepts_subagent_updates: false,};let dispatch_task = cx.spawn({let mut dispatch_rx = dispatch_rx;@@ -5211,6 +5214,18 @@ mod tests {assert!(elicitation.url.is_some());}+ #[test]+ fn client_capabilities_do_not_advertise_subagents() {+ for agent_id in ["codex-acp", CURSOR_ID] {+ assert!(+ client_capabilities_for_agent(&AgentId::new(agent_id))+ .subagents+ .is_none(),+ "v1 subagent support must only be offered behind acp-beta"+ );+ }+ }+#[gpui::test]async fn request_scoped_elicitation_during_auth_uses_connection_store(cx: &mut gpui::TestAppContext,@@ -7449,6 +7464,7 @@ exit 7request_elicitations: request_elicitations.clone(),active_request_scopes: None,pending_session_updates: None,+ accepts_subagent_updates: false,};// `TestAppContext::spawn` hands out an `AsyncApp` by value, whereas the// production path uses `Context::spawn` which hands out `&mut AsyncApp`.@@ -7832,6 +7848,7 @@ exit 7request_elicitations: store.clone(),active_request_scopes: None,pending_session_updates: None,+ accepts_subagent_updates: false,};let (dispatch_tx, mut dispatch_rx) = mpsc::unbounded::<ForegroundWork>();let dispatch_task = cx.spawn(move |mut cx| async move {@@ -7947,6 +7964,143 @@ exit 7assert_eq!(error.code, ErrorCode::InternalError);}+ #[gpui::test]+ async fn v1_subagent_state_snapshots_drive_child_activity(cx: &mut gpui::TestAppContext) {+ use acp_thread::ThreadStatus;++ cx.update(|cx| {+ let store = settings::SettingsStore::test(cx);+ cx.set_global(store);+ });+ let project = project::Project::test(fs::FakeFs::new(cx.executor()), [], cx).await;+ let parent = cx+ .update(|cx| {+ Rc::new(acp_thread::StubAgentConnection::new()).new_session(+ project,+ PathList::default(),+ cx,+ )+ })+ .await+ .expect("parent session");+ let parent_session_id = parent.read_with(cx, |parent, _| parent.session_id().clone());+ let sessions = Rc::new(RefCell::new(HashMap::default()));+ sessions.borrow_mut().insert(+ parent_session_id.clone(),+ AcpSession {+ thread: parent.downgrade(),+ suppress_abort_err: false,+ session_modes: None,+ config_options: None,+ default_config_task: None,+ _release_subscription: Subscription::new(|| {}),+ },+ );+ let context_for = |accepts_subagent_updates, cx: &mut gpui::TestAppContext| ClientContext {+ sessions: sessions.clone(),+ session_list: Rc::new(RefCell::new(None)),+ request_elicitations: cx.new(|_| ElicitationStore::default()),+ active_request_scopes: None,+ pending_session_updates: None,+ accepts_subagent_updates,+ };+ let parent_id = parent_session_id.0.to_string();++ let unadvertised = context_for(false, cx);+ handle_session_notification(+ acp::SessionNotification::new(+ parent_id.clone(),+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("child")),+ ),+ &mut cx.to_async(),+ &unadvertised,+ );+ parent.read_with(cx, |parent, _| {+ assert_eq!(+ parent.subagents().count(),+ 0,+ "without the advertised capability, a v1 agent's subagent updates are ignored"+ );+ });+ assert!(+ !sessions+ .borrow()+ .contains_key(&acp_v2::SessionId::new("child"))+ );++ let context = context_for(true, cx);+ let notify =+ |session_id: &str, update: acp::SessionUpdate, cx: &mut gpui::TestAppContext| {+ handle_session_notification(+ acp::SessionNotification::new(session_id.to_string(), update),+ &mut cx.to_async(),+ &context,+ );+ };+ let subagent_state = |state| {+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("child").state(state))+ };++ notify(+ &parent_id,+ acp::SessionUpdate::SubagentUpdate(+ acp::SubagentUpdate::new("child")+ .title("Worker")+ .state(acp::StateUpdate::Running(acp::RunningStateUpdate::new())),+ ),+ cx,+ );+ notify(+ "child",+ acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Working".into())),+ cx,+ );+ let child = parent+ .read_with(cx, |parent, _| parent.subagent(&"child".into()).cloned())+ .expect("the parent owns the announced subagent");+ child.read_with(cx, |child, _| {+ assert_eq!(child.parent_session_id(), Some(&parent_session_id));+ assert_eq!(+ child+ .subagent_association()+ .and_then(|association| association.title.clone()),+ Some("Worker".into())+ );+ assert_eq!(child.status(), ThreadStatus::Generating);+ assert_eq!(child.entries().len(), 1, "child traffic reaches the child");+ });++ notify(&parent_id, subagent_state(MaybeUndefined::Null), cx);+ child.read_with(cx, |child, _| {+ assert_eq!(+ child.status(),+ ThreadStatus::Unconfirmed,+ "clearing the snapshot leaves activity unconfirmed, not idle"+ );+ });+ notify(+ &parent_id,+ subagent_state(MaybeUndefined::Value(acp::StateUpdate::Idle(+ acp::IdleStateUpdate::new().stop_reason(acp::IdleStopReason::Cancelled),+ ))),+ cx,+ );+ child.read_with(cx, |child, _| {+ assert_eq!(child.status(), ThreadStatus::Idle)+ });++ drop((parent, child));+ cx.run_until_parked();+ cx.update(|_| ());+ assert!(+ !context+ .sessions+ .borrow()+ .contains_key(&acp_v2::SessionId::new("child")),+ "the subagent is released with its parent"+ );+ }+#[gpui::test]async fn disconnect_cleanup_runs_once_for_both_completion_paths(cx: &mut gpui::TestAppContext) {let context = ClientContext {@@ -7955,6 +8109,7 @@ exit 7request_elicitations: cx.new(|_| ElicitationStore::default()),active_request_scopes: None,pending_session_updates: None,+ accepts_subagent_updates: false,};let (sender, mut receiver) = mpsc::unbounded::<ForegroundWork>();let cleanup = settle_after_disconnect(sender.clone()).boxed().shared();@@ -9556,6 +9711,23 @@ fn handle_read_text_file(.detach();}+fn apply_v1_subagent_update(+ parent: &Entity<AcpThread>,+ update: acp::SubagentUpdate,+ sessions: &Rc<RefCell<HashMap<acp_v2::SessionId, AcpSession>>>,+ cx: &mut App,+) -> Result<()> {+ let update = acp_thread::subagents::update_from_v1(update)?;+ let subagent = apply_subagent_update(parent, &update, sessions, cx)?;+ // A v1 subagent has no stream or prompt response of its own that reports its+ // activity, so the parent's snapshot is the only source.+ subagent.update(cx, |subagent, cx| match update.state {+ MaybeUndefined::Undefined => Ok(()),+ MaybeUndefined::Null => subagent.clear_session_state(cx),+ MaybeUndefined::Value(state) => subagent.update_session_state(state, cx),+ })+}+fn handle_session_notification(notification: acp::SessionNotification,cx: &mut AsyncApp,@@ -9615,10 +9787,25 @@ fn handle_session_notification(}// Abandoned loads can keep replaying until their wire operation settles.- let Some(_thread) = thread.upgrade() else {+ let Some(strong_thread) = thread.upgrade() else {return;};+ if let acp::SessionUpdate::SubagentUpdate(update) = notification.update {+ if !ctx.accepts_subagent_updates {+ log::warn!(+ "Ignoring subagent update for {session_id:?}: Zed did not advertise the subagents capability"+ );+ return;+ }+ if let Err(error) =+ cx.update(|cx| apply_v1_subagent_update(&strong_thread, update, &ctx.sessions, cx))+ {+ log::error!("Failed to apply subagent update for {session_id:?}: {error:?}");+ }+ return;+ }+// Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal.if let acp::SessionUpdate::ToolCall(tc) = ¬ification.update {if let Some(meta) = &tc.meta {diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rsindex 9fef46d0aff..11eda73ec4f 100644--- a/crates/agent_servers/src/acp/v2.rs+++ b/crates/agent_servers/src/acp/v2.rs@@ -337,6 +337,7 @@ impl AcpV2Connection {session_list: Rc::new(RefCell::new(None)),request_elicitations: request_elicitations.clone(),active_request_scopes: Some(RefCell::new(Default::default())),+ accepts_subagent_updates: true,};let (mut client_runtime, shutdown) = runtime::ClientRuntime::new(context, cx);let dispatch_tx = client_runtime.sender();@@ -1411,6 +1412,18 @@ impl AgentConnection for AcpV2Connection {if !self.supports_close_session() {return Task::ready(Err(anyhow!("Closing sessions is not supported")));}+ let is_subagent = self+ .sessions+ .borrow()+ .get(session_id)+ .and_then(|session| session.thread.upgrade())+ .is_some_and(|thread| thread.read(cx).subagent_association().is_some());+ if is_subagent {+ // ACP forbids closing a subagent; the agent releases it when its parent closes.+ return Task::ready(Err(anyhow!(+ "ACP subagent sessions are closed with their parent"+ )));+ }let owner = self.session_owners.borrow().get(session_id).map(|owner| {(owner.thread.clone(),@@ -2350,6 +2363,141 @@ mod tests {});}+ #[gpui::test]+ async fn v2_subagent_updates_route_and_patch_child_sessions(cx: &mut TestAppContext) {+ use acp_thread::{ThreadStatus, subagents::SubagentAssociation};+ use agent_client_protocol::schema::MaybeUndefined;++ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let parent = harness.thread(cx).await;+ harness.send_update(+ "session",+ acp::SessionUpdate::SubagentUpdate(+ acp::SubagentUpdate::new("child")+ .title("Investigator")+ .capabilities(+ acp::SubagentSessionCapabilities::new()+ .cancel(acp::SessionCancelCapabilities::new()),+ )+ .state(acp::StateUpdate::Running(acp::RunningStateUpdate::new())),+ ),+ );+ harness.send_update(+ "child",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("child-message").content(vec!["Looking".into()]),+ ),+ );+ harness.drain_updates(cx).await;++ let child = parent+ .read_with(cx, |parent, _| parent.subagent(&"child".into()).cloned())+ .expect("the parent owns the announced subagent");+ child.read_with(cx, |child, _| {+ assert_eq!(child.parent_session_id(), Some(&"session".into()));+ assert_eq!(+ child.subagent_association(),+ Some(&SubagentAssociation {+ title: Some("Investigator".into()),+ description: None,+ can_cancel: true,+ })+ );+ assert_eq!(child.entries().len(), 1, "child traffic reaches the child");+ assert_eq!(+ child.status(),+ ThreadStatus::Unconfirmed,+ "the parent's mirrored state does not report the child's activity"+ );+ });++ harness.send_update(+ "child",+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(+ acp::RunningStateUpdate::new(),+ )),+ );+ harness.send_update(+ "session",+ acp::SessionUpdate::SubagentUpdate(+ acp::SubagentUpdate::new("child").title(MaybeUndefined::Null),+ ),+ );+ // Neither reparenting nor self-reference creates an association.+ harness.send_update(+ "child",+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("session")),+ );+ harness.send_update(+ "session",+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("session")),+ );+ let _permission = harness+ .agent+ .send_request(acp::RequestPermissionRequest::new(+ "child",+ "Run tests",+ vec![acp::PermissionOption::new(+ "allow",+ "Allow",+ acp::PermissionOptionKind::AllowOnce,+ )],+ ));+ harness.drain_updates(cx).await;++ child.read_with(cx, |child, _| {+ assert_eq!(child.status(), ThreadStatus::Generating);+ assert_eq!(+ child.subagent_association(),+ Some(&SubagentAssociation {+ title: None,+ description: None,+ can_cancel: true,+ })+ );+ assert_eq!(child.subagents().count(), 0);+ assert_eq!(+ child.pending_permission_requests().count(),+ 1,+ "child requests route to the child"+ );+ });+ parent.read_with(cx, |parent, _| {+ assert_eq!(parent.parent_session_id(), None);+ assert_eq!(parent.subagents().collect::<Vec<_>>(), [&child]);+ });+ let error = bounded(+ cx.update(|cx| harness.client.clone().close_session(&"child".into(), cx)),+ cx,+ )+ .await+ .expect_err("subagents cannot be closed");+ assert!(+ error+ .to_string()+ .contains("ACP subagent sessions are closed with their parent")+ );++ drop((parent, child));+ cx.run_until_parked();+ cx.update(|_| ());+ assert_eq!(+ harness+ .client+ .sessions+ .borrow()+ .keys()+ .cloned()+ .collect::<Vec<_>>(),+ Vec::<acp::SessionId>::new(),+ "the subagent is released with its parent"+ );+ assert!(+ harness.closes.is_empty(),+ "releasing a subagent never closes it"+ );+ }+#[gpui::test]async fn v2_new_session_applies_defaults_before_delivery(cx: &mut TestAppContext) {use settings::AgentConfigOptionValue::{Boolean, ValueId};diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex ed87767fe50..bc94442fc0d 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -20096,6 +20096,72 @@ pub(crate) mod tests {}}+ fn create_test_acp_subagent(+ parent_session_id: acp_v2::SessionId,+ session_id: &str,+ connection: Rc<dyn AgentConnection>,+ project: Entity<Project>,+ cx: &mut App,+ ) -> Entity<AcpThread> {+ let action_log = cx.new(|_| ActionLog::new(project.clone()));+ cx.new(|cx| {+ AcpThread::new(+ Some(parent_session_id),+ None,+ None,+ connection,+ project,+ action_log,+ acp_v2::SessionId::new(session_id),+ watch::Receiver::constant(acp_v2::PromptCapabilities::new()),+ cx,+ )+ .agent_owned()+ })+ }++ #[gpui::test]+ async fn test_subagent_label_prefers_the_acp_parents_title(cx: &mut TestAppContext) {+ init_test(cx);+ let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());+ let (native_child, acp_child) = cx.update(|cx| {+ let parent = acp_v2::SessionId::new("parent");+ (+ create_test_acp_thread(+ Some(parent.clone()),+ "native-child",+ connection.clone(),+ project.clone(),+ cx,+ ),+ create_test_acp_subagent(parent, "acp-child", connection, project, cx),+ )+ });+ let label = |thread: &Entity<AcpThread>, cx: &mut TestAppContext| {+ thread.read_with(cx, |thread, _| thread_view::subagent_label(thread))+ };+ assert_eq!(label(&native_child, cx), "Subagent");++ for thread in [&native_child, &acp_child] {+ thread.update(cx, |thread, cx| {+ thread.update_session_info(acp_v2::SessionInfoUpdate::new().title("Own title"), cx)+ });+ }+ assert_eq!(label(&native_child, cx), "Own title");+ assert_eq!(label(&acp_child, cx), "Own title");++ acp_child.update(cx, |thread, cx| {+ thread+ .update_subagent_association(+ &acp_v2::SubagentUpdate::new("acp-child").title("Parent title"),+ cx,+ )+ .expect("ACP subagent")+ });+ assert_eq!(label(&acp_child, cx), "Parent title");+ }+#[gpui::test]async fn test_release_policy_does_not_disable_explicit_close(cx: &mut TestAppContext) {init_test(cx);diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 2e1a3d3ae8c..385cfabe5b2 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -58,6 +58,16 @@ use super::elicitation::{use super::subagent_card::{SubagentCardState, SubagentStatus};use super::*;+/// How a parent's view names a subagent. An ACP parent's own title for the subagent+/// describes it in that view, so it wins over the subagent's title for itself.+pub(super) fn subagent_label(thread: &AcpThread) -> SharedString {+ thread+ .subagent_association()+ .and_then(|association| association.title.clone())+ .or_else(|| thread.title())+ .unwrap_or_else(|| "Subagent".into())+}+const DATA_RETENTION_LEARN_MORE_URL: &str = "https://support.claude.com/en/articles/15425996-data-retention-practices-for-mythos-class-models";pub(super) struct ThreadRecovery {@@ -4329,7 +4339,7 @@ impl ThreadView {} else {Some(format!("Subagent: {} ({session_id})",- thread.title().unwrap_or_else(|| "Subagent".into())+ subagent_label(thread)))};cards.push(self.render_generic_permission_card(