Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Let parent threads own their subagent threads (#65918)
Ben Brandtf91e908cad4d
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 237b07166f8..fbfab0e6f5d 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3459,6 +3459,8 @@ fn stop_reason_from_v1(reason: &acp_v1::StopReason) -> Option<acp_v2::StopReasonpub struct AcpThread {session_info: AgentSessionInfo,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>>,provisional_title: Option<SharedString>,entries: Vec<AgentThreadEntry>,// Notices stay with the live session, but never enter conversation history or exports.@@ -3640,6 +3642,7 @@ pub enum AcpThreadEvent {/// The request left `Pending`; this does not imply delivery to its response waiter.ElicitationResponded(ElicitationEntryId),Retry(RetryStatus),+ /// A child session was registered; read it with [`AcpThread::subagent`].SubagentSpawned(acp_v2::SessionId),Stopped {activity_generation: u64,@@ -3837,6 +3840,7 @@ impl AcpThread {next_notice_id: 0,elicitations: ElicitationStore::default(),permission_requests: IndexMap::default(),+ subagents: IndexMap::default(),plans: HashMap::default(),visible_plan: None,provisional_title: None,@@ -5542,10 +5546,26 @@ impl AcpThread {cx.emit(AcpThreadEvent::TitleUpdated);}- pub fn subagent_spawned(&mut self, session_id: acp_v2::SessionId, cx: &mut Context<Self>) {+ /// Takes ownership of a child session. A session ID that is already registered+ /// keeps its existing thread. Callers must not register this session or one of its+ /// ancestors, since the registry holds children strongly.+ pub fn register_subagent(&mut self, subagent: Entity<AcpThread>, cx: &mut Context<Self>) {+ let session_id = subagent.read(cx).session_id().clone();+ if self.subagents.contains_key(&session_id) {+ return;+ }+ self.subagents.insert(session_id.clone(), subagent);cx.emit(AcpThreadEvent::SubagentSpawned(session_id));}+ pub fn subagent(&self, session_id: &acp_v2::SessionId) -> Option<&Entity<AcpThread>> {+ self.subagents.get(session_id)+ }++ pub fn subagents(&self) -> impl Iterator<Item = &Entity<AcpThread>> {+ self.subagents.values()+ }+pub fn update_token_usage(&mut self, usage: Option<TokenUsage>, cx: &mut Context<Self>) {if usage.is_none() {self.cost = None;@@ -22635,6 +22655,65 @@ mod tests {}}+ #[gpui::test]+ async fn test_register_subagent_keeps_the_first_thread_for_a_session(cx: &mut TestAppContext) {+ init_test(cx);+ let (parent, connection) = new_receipt_test_thread(cx).await;+ let parent_session_id = parent.read_with(cx, |thread, _| thread.session_id().clone());+ let new_child = |session_id: &str, cx: &mut TestAppContext| {+ let connection = connection.clone();+ let parent_session_id = parent_session_id.clone();+ let project = parent.read_with(cx, |thread, _| thread.project().clone());+ let session_id = acp_v2::SessionId::new(session_id);+ cx.update(|cx| {+ let action_log = cx.new(|_| ActionLog::new(project.clone()));+ cx.new(|cx| {+ AcpThread::new(+ Some(parent_session_id),+ None,+ None,+ connection,+ project,+ action_log,+ session_id,+ watch::Receiver::constant(acp_v2::PromptCapabilities::new()),+ cx,+ )+ })+ })+ };+ let first = new_child("child", cx);+ let duplicate = new_child("child", cx);+ let other = new_child("other", cx);+ let spawned = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&parent, {+ let spawned = spawned.clone();+ move |_, event, _| {+ if let AcpThreadEvent::SubagentSpawned(session_id) = event {+ spawned.borrow_mut().push(session_id.to_string());+ }+ }+ })+ });++ parent.update(cx, |parent, cx| {+ parent.register_subagent(first.clone(), cx);+ parent.register_subagent(duplicate.clone(), cx);+ parent.register_subagent(other.clone(), cx);+ });+ cx.run_until_parked();++ assert_eq!(*spawned.borrow(), ["child", "other"]);+ parent.read_with(cx, |parent, _| {+ assert_eq!(+ parent.subagent(&acp_v2::SessionId::new("child")),+ Some(&first)+ );+ assert_eq!(parent.subagents().collect::<Vec<_>>(), [&first, &other]);+ });+ }+#[gpui::test]async fn test_idle_sleep_prevention_overlaps_distinct_threads_and_subagent(cx: &mut TestAppContext,diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 8e2a0cc0c29..32b2fb95101 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -232,7 +232,6 @@ struct Session {acp_thread: WeakEntity<acp_thread::AcpThread>,execution: Option<NativeExecution>,pending_cancellation: watch::Sender<()>,- subagents: Vec<Entity<acp_thread::AcpThread>>,project_id: EntityId,/// Latest snapshot to persist. Overwritten in place on every save request;/// the single save worker drains it, coalescing bursts into one write.@@ -1071,7 +1070,6 @@ impl NativeAgent {acp_thread: acp_thread.downgrade(),execution: None,pending_cancellation: watch::channel(()).0,- subagents: Vec::new(),project_id,pending_save,last_streaming_save_key: None,@@ -2937,11 +2935,6 @@ impl NativeAgentConnection {thread.update_tool_call(update, cx)})??;}- ThreadEvent::SubagentSpawned(session_id) => {- acp_thread.update(cx, |thread, cx| {- thread.subagent_spawned(session_id, cx);- })?;- }ThreadEvent::Retry(status) => {if acp_thread::refusal_fallback_model_from_meta(&status.meta).is_some()@@ -3742,14 +3735,13 @@ impl NativeThreadEnvironment {.get(&parent_session_id).map(|s| s.project_id).context("parent session not found")?;- let acp_thread = agent.register_session(subagent_thread.clone(), project_id, cx);- let parent_session = agent- .sessions- .get_mut(&parent_session_id)- .context("parent session not found")?;- parent_session.subagents.push(acp_thread.clone());- Ok(acp_thread)+ Ok(agent.register_session(subagent_thread.clone(), project_id, cx))})??;+ self.acp_thread+ .update(cx, |parent, cx| {+ parent.register_subagent(acp_thread.clone(), cx)+ })+ .context("Parent thread no longer exists")?;let depth = current_depth + 1;@@ -9521,6 +9513,58 @@ mod internal_tests {assert!(weak_project.upgrade().is_none());}+ #[gpui::test]+ async fn test_only_created_subagents_are_registered_with_the_parent(cx: &mut TestAppContext) {+ init_test(cx);+ let fs = FakeFs::new(cx.executor());+ fs.insert_tree("/", json!({ "a": {} })).await;+ let thread_store = cx.new(|cx| ThreadStore::new(cx));+ let agent = cx+ .update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));+ let connection = Rc::new(NativeAgentConnection(agent.clone()));+ let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;+ let new_session = |cx: &mut TestAppContext| {+ cx.update(|cx| {+ connection+ .clone()+ .new_session(project.clone(), PathList::new(&[Path::new("")]), cx)+ })+ };+ let parent = new_session(cx).await.unwrap();+ let unrelated = new_session(cx).await.unwrap();+ let parent_session_id = parent.read_with(cx, |thread, _| thread.session_id().clone());+ let unrelated_session_id = unrelated.read_with(cx, |thread, _| thread.session_id().clone());+ let environment = NativeThreadEnvironment {+ agent: agent.downgrade(),+ thread: cx+ .update(|cx| native_thread_for_session(&agent, &parent_session_id, cx))+ .downgrade(),+ acp_thread: parent.downgrade(),+ };++ let child = cx+ .update(|cx| environment.create_subagent_thread("child".to_string(), None, cx))+ .unwrap();+ cx.update(|cx| environment.resume_subagent_thread(child.id(), cx))+ .expect("resume the child");+ // Resuming a session the parent did not create, including itself, must not make+ // the parent own it: that would be a reference cycle or a self-update.+ cx.update(|cx| environment.resume_subagent_thread(unrelated_session_id, cx))+ .expect("resume an unrelated live session");+ cx.update(|cx| environment.resume_subagent_thread(parent_session_id, cx))+ .expect("resume the parent's own session");++ parent.read_with(cx, |parent, cx| {+ assert_eq!(+ parent+ .subagents()+ .map(|subagent| subagent.read(cx).session_id().clone())+ .collect::<Vec<_>>(),+ [child.id()]+ );+ });+ }+#[gpui::test]async fn test_save_burst_preserves_in_flight_write(cx: &mut TestAppContext) {let fake = init_test(cx);diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rsindex 8cf42ea3923..48cb1624c92 100644--- a/crates/agent/src/tests/mod.rs+++ b/crates/agent/src/tests/mod.rs@@ -6134,6 +6134,13 @@ async fn test_subagent_tool_call_end_to_end(cx: &mut TestAppContext) {.upgrade().expect("subagent thread should be alive")});+ acp_thread.read_with(cx, |parent, _| {+ assert_eq!(+ parent.subagent(&subagent_session_id),+ Some(&subagent_thread),+ "the parent thread owns the spawned subagent"+ );+ });let request = fake.pending_completions_for(&model).pop().unwrap();fake.send_text(&model, &request, "subagent task response");@@ -6634,6 +6641,13 @@ async fn test_subagent_tool_resume_session(cx: &mut TestAppContext) {assert_eq!(running.len(), 1, "subagent should be running");assert_eq!(running[0], subagent_session_id, "should be same session");});+ acp_thread.read_with(cx, |parent, _| {+ assert_eq!(+ parent.subagents().collect::<Vec<_>>(),+ [&subagent_acp_thread],+ "resuming keeps the one registered subagent"+ );+ });// Subagent responds to follow-uplet request = fake.pending_completions_for(&model).pop().unwrap();diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex a2583e39d7a..618f45f0987 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -909,7 +909,6 @@ pub enum ThreadEvent {outcome: acp_thread::SelectedPermissionOutcome,},Elicitation(ElicitationRequest),- SubagentSpawned(acp_v2::SessionId),Retry(acp_thread::RetryStatus),ContextCompaction(acp_thread::ContextCompaction),ContextCompactionUpdate(acp_thread::ContextCompactionUpdate),@@ -6014,13 +6013,6 @@ impl ToolCallEventStream {.ok();}- pub fn subagent_spawned(&self, id: acp_v2::SessionId) {- self.stream- .sender- .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))- .ok();- }-/// Authorize a third-party tool (e.g., MCP tool from a context server).////// Unlike built-in tools, third-party tools don't support pattern-based permissions.diff --git a/crates/agent/src/tools/spawn_agent_tool.rs b/crates/agent/src/tools/spawn_agent_tool.rsindex 449c5ec907f..1096df0a6e0 100644--- a/crates/agent/src/tools/spawn_agent_tool.rs+++ b/crates/agent/src/tools/spawn_agent_tool.rs@@ -202,7 +202,6 @@ impl AgentTool for SpawnAgentTool {message_end_index: None,};- event_stream.subagent_spawned(subagent.id());event_stream.update_fields(|update| {update.meta(acp_v2::Meta::from_iter([(SUBAGENT_SESSION_INFO_META_KEY.into(),diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex e1cb4963d41..907f5f71470 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -749,6 +749,18 @@ fn resolve_outcome_from_selection(Some(selected_choice.build_outcome(is_allow))}+fn subagent_sessions_referenced_by_tool_calls(+ thread: &AcpThread,+) -> impl Iterator<Item = &acp_v2::SessionId> {+ thread.entries().iter().filter_map(|entry| match entry {+ AgentThreadEntry::ToolCall(call) => call+ .subagent_session_info+ .as_ref()+ .map(|info| &info.session_id),+ _ => None,+ })+}+fn affects_thread_metadata(event: &AcpThreadEvent) -> bool {match event {AcpThreadEvent::NewEntry@@ -1643,31 +1655,16 @@ impl ConversationView {cx.observe(&action_log, |_, _, cx| cx.notify()),];- let subagent_sessions = thread- .read(cx)- .entries()- .iter()- .filter_map(|entry| match entry {- AgentThreadEntry::ToolCall(call) => call- .subagent_session_info- .as_ref()- .map(|i| i.session_id.clone()),- _ => None,- })- .collect::<Vec<_>>();-- if !subagent_sessions.is_empty() {+ // Deferred because this view is only added to `threads` after it is built.+ if thread.read(cx).subagents().next().is_some()+ || subagent_sessions_referenced_by_tool_calls(thread.read(cx))+ .next()+ .is_some()+ {let parent_session_id = thread.read(cx).session_id().clone();cx.spawn_in(window, async move |this, cx| {this.update_in(cx, |this, window, cx| {- for subagent_id in subagent_sessions {- this.load_subagent_session(- subagent_id,- parent_session_id.clone(),- window,- cx,- );- }+ this.add_subagent_thread_views(&parent_session_id, window, cx);})}).detach();@@ -2016,7 +2013,9 @@ impl ConversationView {}}AcpThreadEvent::SubagentSpawned(subagent_session_id) => {- self.load_subagent_session(subagent_session_id.clone(), session_id, window, cx)+ if let Some(subagent) = thread.read(cx).subagent(subagent_session_id).cloned() {+ self.add_subagent_thread_view(subagent, window, cx);+ }}AcpThreadEvent::ToolAuthorizationRequested(_) => {self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);@@ -2511,11 +2510,65 @@ impl ConversationView {}}+ fn add_subagent_thread_views(+ &mut self,+ parent_session_id: &acp_v2::SessionId,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let Some(parent_thread) = self+ .thread_view(parent_session_id)+ .map(|view| view.read(cx).thread.clone())+ else {+ return;+ };+ let subagents = parent_thread+ .read(cx)+ .subagents()+ .cloned()+ .collect::<Vec<_>>();+ for subagent in subagents {+ self.add_subagent_thread_view(subagent, window, cx);+ }+ let referenced_subagent_ids =+ subagent_sessions_referenced_by_tool_calls(parent_thread.read(cx))+ .cloned()+ .collect::<Vec<_>>();+ for subagent_id in referenced_subagent_ids {+ self.load_subagent_session(subagent_id, parent_session_id.clone(), cx);+ }+ }++ fn add_subagent_thread_view(+ &mut self,+ subagent: Entity<AcpThread>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let Some(connected) = self.as_connected() else {+ return;+ };+ let subagent_session_id = subagent.read(cx).session_id().clone();+ if connected.threads.contains_key(&subagent_session_id) {+ return;+ }+ let conversation = connected.conversation.clone();+ conversation.update(cx, |conversation, cx| {+ conversation.register_thread(subagent.clone(), cx);+ });+ let view = self.new_thread_view(subagent, conversation, false, None, window, cx);+ if let Some(connected) = self.as_connected_mut() {+ connected.threads.insert(subagent_session_id, view);+ }+ }++ /// Restores a child session that a tool call references but its parent does not+ /// own, such as a native subagent from a thread loaded from the database. Children+ /// the parent already owns are never loaded: ACP forbids loading subagent sessions.fn load_subagent_session(&mut self,subagent_id: acp_v2::SessionId,parent_session_id: acp_v2::SessionId,- window: &mut Window,cx: &mut Context<Self>,) {let Some(connected) = self.as_connected() else {@@ -2526,12 +2579,17 @@ impl ConversationView {{return;}- let Some(parent_thread) = connected.threads.get(&parent_session_id) else {+ let Some(parent_thread) = connected+ .threads+ .get(&parent_session_id)+ .map(|view| view.read(cx).thread.clone())+ else {return;};+ if parent_thread.read(cx).subagent(&subagent_id).is_some() {+ return;+ }let work_dirs = parent_thread- .read(cx)- .thread.read(cx).work_dirs().cloned()@@ -2545,29 +2603,18 @@ impl ConversationView {cx,);- cx.spawn_in(window, async move |this, cx| {+ let parent_thread = parent_thread.downgrade();+ cx.spawn(async move |_, cx| {let subagent_thread = subagent_thread_task.await?;- this.update_in(cx, |this, window, cx| {- let Some(connected) = this.as_connected() else {- return;- };- let subagent_session_id = subagent_thread.read(cx).session_id().clone();- if connected.threads.contains_key(&subagent_session_id) {- return;- }- let conversation = connected.conversation.clone();- conversation.update(cx, |conversation, cx| {- conversation.register_thread(subagent_thread.clone(), cx);- });- let view =- this.new_thread_view(subagent_thread, conversation, false, None, window, cx);- let Some(connected) = this.as_connected_mut() else {- return;- };- connected.threads.insert(subagent_session_id, view);- })+ let registered = parent_thread.update(cx, |parent_thread, cx| {+ parent_thread.register_subagent(subagent_thread, cx);+ });+ if registered.is_err() {+ log::debug!("Subagent parent was released while its session loaded");+ }+ anyhow::Ok(())})- .detach();+ .detach_and_log_err(cx);}fn spawn_external_agent_login(@@ -6678,6 +6725,52 @@ pub(crate) mod tests {});}+ #[gpui::test]+ async fn test_registered_subagents_get_views_without_loading(cx: &mut TestAppContext) {+ init_test(cx);+ // This connection cannot load sessions, so views can only come from the registry.+ let connection = StubAgentConnection::new();+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;+ let root =+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());+ let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone());+ let (child, grandchild) = conversation_view.update(cx, |view, cx| {+ let child = create_test_acp_thread(+ Some(root_session_id),+ "child",+ Rc::new(connection.clone()),+ view.project.clone(),+ cx,+ );+ let grandchild = create_test_acp_thread(+ Some(acp_v2::SessionId::new("child")),+ "grandchild",+ Rc::new(connection.clone()),+ view.project.clone(),+ cx,+ );+ (child, grandchild)+ });++ // Registered before its parent has a view, as children replayed during a load are.+ child.update(cx, |child, cx| {+ child.register_subagent(grandchild.clone(), cx)+ });+ root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));+ cx.run_until_parked();++ conversation_view.read_with(cx, |view, cx| {+ for thread in [&child, &grandchild] {+ let session_id = thread.read(cx).session_id().clone();+ let thread_view = view+ .thread_view(&session_id)+ .unwrap_or_else(|| panic!("missing view for {session_id}"));+ assert_eq!(&thread_view.read(cx).thread, thread);+ }+ });+ }+#[gpui::test]async fn test_concurrent_subagent_loads_create_one_thread_view(cx: &mut TestAppContext) {init_test(cx);@@ -6699,12 +6792,11 @@ pub(crate) mod tests {})});- conversation_view.update_in(cx, |view, window, cx| {+ conversation_view.update(cx, |view, cx| {for _ in 0..2 {view.load_subagent_session(subagent_session_id.clone(),root_session_id.clone(),- window,cx,);}@@ -6742,13 +6834,8 @@ pub(crate) mod tests {active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());let root_session_id = root_thread.read_with(cx, |thread, _| thread.session_id().clone());let other_session_id = acp_v2::SessionId::new("other-session");- conversation_view.update_in(cx, |view, window, cx| {- view.load_subagent_session(- other_session_id.clone(),- root_session_id.clone(),- window,- cx,- );+ conversation_view.update(cx, |view, cx| {+ view.load_subagent_session(other_session_id.clone(), root_session_id.clone(), cx);});cx.run_until_parked();diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rsindex 112dc159d8c..97bdd6050f7 100644--- a/crates/sidebar/src/sidebar_tests.rs+++ b/crates/sidebar/src/sidebar_tests.rs@@ -4593,11 +4593,22 @@ async fn test_subagent_permission_request_marks_parent_sidebar_thread_waiting(save_test_thread_metadata(&parent_session_id, &project, cx).await;let subagent_session_id = acp::SessionId::new("subagent-session");- cx.update(|_, cx| {- let parent_thread = panel.read(cx).active_agent_thread(cx).unwrap();- parent_thread.update(cx, |thread: &mut AcpThread, cx| {- thread.subagent_spawned(subagent_session_id.clone(), cx);- });+ let parent_thread = cx.update(|_, cx| panel.read(cx).active_agent_thread(cx).unwrap());+ let subagent = cx+ .update(|_, cx| {+ let parent = parent_thread.read(cx);+ parent.connection().clone().load_session(+ subagent_session_id.clone(),+ parent.project().clone(),+ PathList::default(),+ None,+ cx,+ )+ })+ .await+ .expect("subagent session");+ parent_thread.update(cx, |thread: &mut AcpThread, cx| {+ thread.register_subagent(subagent, cx);});cx.run_until_parked();