Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent: Report native subagent state like ACP subagents (#66255)
Ben Brandt2e794a1ea7a2
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 73518eda782..55ba18f7851 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -4052,6 +4052,12 @@ impl AcpThread {self}+ /// Marks a subagent session whose parent runs in Zed, such as a native subagent. Unlike+ /// `agent_owned`, Zed still submits its prompts.+ pub fn set_subagent_association(&mut self, association: subagents::SubagentAssociation) {+ self.subagent_association = Some(association);+ }+pub fn subagent_association(&self) -> Option<&subagents::SubagentAssociation> {self.subagent_association.as_ref()}@@ -4308,6 +4314,32 @@ impl AcpThread {self.received_session_state}+ /// Restores the outcomes a subagent reported before it was saved, each with the entry+ /// count when it was reported, after its entries have been replayed. The last one is+ /// also its current state, unless entries followed it, as when Zed quit mid-run.+ pub fn restore_subagent_outcomes(+ &mut self,+ outcomes: Vec<(usize, acp_v2::StateUpdate)>,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ anyhow::ensure!(+ self.subagent_association.is_some(),+ "Session is not a subagent"+ );+ let current = outcomes+ .last()+ .filter(|(entry_count, _)| *entry_count == self.entries.len())+ .map(|(_, state)| state.clone());+ self.subagent_outcomes = outcomes;+ match current {+ Some(state) => self.update_session_state(state, cx),+ None => {+ cx.notify();+ Ok(())+ }+ }+ }+/// The first idle state this subagent reported after the entry at `entry_ix` arrived.pub fn subagent_outcome_after(&self, entry_ix: usize) -> Option<&acp_v2::StateUpdate> {self.subagent_outcomes@@ -4681,8 +4713,14 @@ impl AcpThread {let was_in_progress = self.activity.in_progress();self.received_session_state = true;if self.subagent_association.is_some() && matches!(state, acp_v2::StateUpdate::Idle(_)) {- self.subagent_outcomes- .push((self.entries.len(), state.clone()));+ let entry_count = self.entries.len();+ // An idle report with no entries since the previous one restates that outcome.+ match self.subagent_outcomes.last_mut() {+ Some((last_entry_count, last_state)) if *last_entry_count == entry_count => {+ *last_state = state.clone();+ }+ _ => self.subagent_outcomes.push((entry_count, state.clone())),+ }}self.set_foreground_state(state, cx);if let Some(acp_v2::StateUpdate::Idle(idle)) = self.activity.state() {diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 4d0f71a9037..3c35de39043 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -900,6 +900,9 @@ impl NativeAgent {let session_id = thread.id().clone();let parent_session_id = thread.parent_thread_id();let title = thread.title();+ let is_subagent = thread.is_subagent();+ // A native subagent's title is the label its parent gave it.+ let subagent_title = title.clone();let draft_prompt = thread.draft_prompt().map(Vec::from);let scroll_position = thread.ui_scroll_position();let token_usage = thread.latest_token_usage();@@ -918,6 +921,13 @@ impl NativeAgent {prompt_capabilities_rx,cx,);+ if is_subagent {+ acp_thread.set_subagent_association(acp_thread::subagents::SubagentAssociation {+ title: subagent_title,+ description: None,+ can_cancel: true,+ });+ }acp_thread.set_draft_prompt(draft_prompt, cx);acp_thread.set_ui_scroll_position(scroll_position);acp_thread.update_token_usage(token_usage, cx);@@ -1862,6 +1872,28 @@ impl NativeAgent {}).await.map_err(Arc::new)?;+ let outcomes = thread.read_with(cx, |thread, _| {+ thread+ .subagent_outcomes()+ .iter()+ .map(|outcome| {+ (+ outcome.entry_count,+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new()+ .stop_reason(outcome.stop_reason.clone()),+ ),+ )+ })+ .collect::<Vec<_>>()+ });+ if !outcomes.is_empty() {+ acp_thread+ .update(cx, |acp_thread, cx| {+ acp_thread.restore_subagent_outcomes(outcomes, cx)+ })+ .map_err(Arc::new)?;+ }Ok(acp_thread)}})@@ -3976,6 +4008,9 @@ impl SubagentHandle for NativeSubagentHandle {task.await} else {thread.update(cx, |thread, cx| thread.request_cancel(cx)).await;+ // Let the run report its own idle state first, so this run's outcome+ // reported below comes after it.+ task.await.log_err();Err(anyhow!("The agent is nearing the end of its context window and has been \stopped. You can prompt the thread again to have the agent wrap up \@@ -3988,6 +4023,7 @@ impl SubagentHandle for NativeSubagentHandle {&response,Ok(acp_v2::StopReason::Cancelled | acp_v2::StopReason::Refusal));+ let response_stop_reason = response.as_ref().ok().cloned();let result = match response {Ok(reason) => match reason {acp_v2::StopReason::Cancelled => Err(anyhow!("User canceled")),@@ -4029,7 +4065,7 @@ impl SubagentHandle for NativeSubagentHandle {}).ok();- if discard_partial_output {+ let result = if discard_partial_output {result} else {result.map_err(|error| {@@ -4040,7 +4076,53 @@ impl SubagentHandle for NativeSubagentHandle {anyhow!("{error:#}\n\nPartial subagent output (last 3 messages, up to 4096 characters each):\n\n{partial_output}")}})- }+ };++ // The run's own idle state only says how the model stopped. Report the verdict+ // the parent's tool call gets, so the subagent's cards agree with it.+ let stop_reason = match (&result, response_stop_reason) {+ (Ok(_), Some(reason))+ | (+ Err(_),+ Some(+ reason @ (acp_v2::StopReason::Cancelled+ | acp_v2::StopReason::MaxTokens+ | acp_v2::StopReason::MaxTurnRequests+ | acp_v2::StopReason::Refusal),+ ),+ ) => reason,+ (result, _) => {+ let mut error = acp_v2::Error::internal_error();+ error.message = match result {+ Ok(_) => "The subagent stopped without a reason".to_string(),+ Err(error) => error.to_string(),+ };+ acp_v2::StopReason::Error(acp_v2::ErrorStopReason::new().error(error))+ }+ };+ cx.update(|cx| {+ let entry_count = acp_thread.read(cx).entries().len();+ thread.update(cx, |thread, cx| {+ thread.record_subagent_outcome(+ SubagentOutcome {+ entry_count,+ stop_reason: stop_reason.clone(),+ },+ cx,+ )+ });+ acp_thread.update(cx, |acp_thread, cx| {+ acp_thread.update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(stop_reason),+ ),+ cx,+ )+ })+ })+ .log_err();++ result})}}diff --git a/crates/agent/src/db.rs b/crates/agent/src/db.rsindex e777ba9d159..83354f031f9 100644--- a/crates/agent/src/db.rs+++ b/crates/agent/src/db.rs@@ -1296,6 +1296,7 @@ mod tests {child_thread.subagent_context = Some(crate::SubagentContext {parent_thread_id: parent_id.clone(),depth: 1,+ outcomes: Vec::new(),});let mut grandchild_thread = make_thread(@@ -1305,6 +1306,7 @@ mod tests {grandchild_thread.subagent_context = Some(crate::SubagentContext {parent_thread_id: child_id.clone(),depth: 2,+ outcomes: Vec::new(),});let unrelated_thread = make_thread(@@ -1345,6 +1347,7 @@ mod tests {child_thread.subagent_context = Some(crate::SubagentContext {parent_thread_id: parent_id.clone(),depth: 2,+ outcomes: Vec::new(),});databasediff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rsindex b3b1580fd4e..0ea043ec581 100644--- a/crates/agent/src/tests/mod.rs+++ b/crates/agent/src/tests/mod.rs@@ -6883,6 +6883,7 @@ async fn test_max_subagent_depth_prevents_tool_registration(cx: &mut TestAppContthread.set_subagent_context(SubagentContext {parent_thread_id: acp_v2::SessionId::new("parent-id"),depth: MAX_SUBAGENT_DEPTH - 1,+ outcomes: Vec::new(),});thread});@@ -7362,6 +7363,101 @@ async fn test_subagent_context_limit_exceeded_without_partial_output(cx: &mut Teassert_eq!(test.fake.pending_completions(), Vec::new());}+#[gpui::test]+async fn test_native_subagent_reports_and_restores_each_runs_outcome(cx: &mut TestAppContext) {+ let test = SubagentCompactionTest::new(cx).await;+ test.configure_compaction(false, 1_000_000, None, cx);+ let session_id = test.handle.id();+ let subagent = test._agent.read_with(cx, |agent, _| {+ agent.sessions[&session_id].acp_thread.upgrade().unwrap()+ });+ subagent.read_with(cx, |subagent, _| {+ let association = subagent+ .subagent_association()+ .expect("a native subagent has an association");+ assert_eq!(association.title.as_deref(), Some("subagent"));+ assert!(association.can_cancel);+ });++ let send = test.send("first task", cx);+ let request = test.fake.pending_completions().pop().unwrap();+ test.fake.send_text(&test.model, &request, "done");+ test.fake.end_stream(&test.model, &request);+ assert_eq!(send.await.unwrap(), "done");+ let first_run_end = subagent.read_with(cx, |subagent, _| subagent.entries().len());++ // The run itself stops as cancelled, but its tool call reports a failure.+ let send = test.send("second task", cx);+ let request = test.fake.pending_completions().pop().unwrap();+ test.update_usage(1_000_000, cx);+ let error = send.await.unwrap_err().to_string();+ test.fake.end_stream(&test.model, &request);+ cx.run_until_parked();+ let second_run_end = subagent.read_with(cx, |subagent, _| subagent.entries().len());++ let mut failure = acp_v2::Error::internal_error();+ failure.message = error;+ let idle = |stop_reason: acp_v2::StopReason| {+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new().stop_reason(stop_reason))+ };+ let expected = vec![+ SubagentOutcome {+ entry_count: first_run_end,+ stop_reason: acp_v2::StopReason::EndTurn,+ },+ SubagentOutcome {+ entry_count: second_run_end,+ stop_reason: acp_v2::StopReason::Error(acp_v2::ErrorStopReason::new().error(failure)),+ },+ ];+ let assert_reported = |subagent: &Entity<AcpThread>, cx: &mut TestAppContext| {+ subagent.read_with(cx, |subagent, _| {+ for (entry_ix, outcome) in [(0, &expected[0]), (first_run_end, &expected[1])] {+ assert_eq!(+ subagent.subagent_outcome_after(entry_ix),+ Some(&idle(outcome.stop_reason.clone())),+ "the run starting at {entry_ix}"+ );+ }+ assert_eq!(+ subagent.foreground_state(),+ Some(&idle(expected[1].stop_reason.clone()))+ );+ });+ };+ test.thread.read_with(cx, |thread, _| {+ assert_eq!(thread.subagent_outcomes(), expected.as_slice())+ });+ assert_reported(&subagent, cx);++ let project = test+ .thread+ .read_with(cx, |thread, _| thread.project.clone());+ let SubagentCompactionTest {+ _agent: agent,+ _acp_thread,+ parent,+ thread,+ environment,+ handle,+ ..+ } = test;+ drop((_acp_thread, parent, thread, environment, handle, subagent));+ cx.run_until_parked();+ release_dropped_entities(cx);+ agent.read_with(cx, |agent, _| assert!(agent.sessions.is_empty()));++ let reloaded = agent+ .update(cx, |agent, cx| agent.open_thread(session_id, project, cx))+ .await+ .unwrap();+ reloaded.read_with(cx, |subagent, _| {+ assert_eq!(subagent.entries().len(), second_run_end);+ assert!(subagent.subagent_association().is_some());+ });+ assert_reported(&reloaded, cx);+}+#[gpui::test]async fn test_subagent_context_limit_preserves_result_after_turn_completes(cx: &mut TestAppContext,diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex 71c295546b5..aa435fc4e37 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -146,6 +146,18 @@ pub struct SubagentContext {/// Current depth level (0 = root agent, 1 = first-level subagent, etc.)pub depth: u8,++ /// How each run of this subagent ended, so its cards keep their outcomes after a reload.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub outcomes: Vec<SubagentOutcome>,+}++/// How one run of a subagent ended.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct SubagentOutcome {+ /// The number of entries in the subagent's transcript when the run ended.+ pub entry_count: usize,+ pub stop_reason: acp_v2::StopReason,}/// The ID of the user prompt that initiated a request.@@ -1386,6 +1398,7 @@ impl Thread {thread.subagent_context = Some(SubagentContext {parent_thread_id: parent_thread.read(cx).id().clone(),depth: parent_thread.read(cx).depth() + 1,+ outcomes: Vec::new(),});thread.inherit_parent_settings(parent_thread, cx);let model_selection = model_selection@@ -4585,6 +4598,23 @@ impl Thread {self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)}+ pub fn subagent_outcomes(&self) -> &[SubagentOutcome] {+ self.subagent_context+ .as_ref()+ .map_or(&[], |context| context.outcomes.as_slice())+ }++ pub fn record_subagent_outcome(&mut self, outcome: SubagentOutcome, cx: &mut Context<Self>) {+ let Some(context) = self.subagent_context.as_mut() else {+ return;+ };+ match context.outcomes.last_mut() {+ Some(last) if last.entry_count == outcome.entry_count => *last = outcome,+ _ => context.outcomes.push(outcome),+ }+ cx.notify();+ }+#[cfg(any(test, feature = "test-support"))]pub fn set_subagent_context(&mut self, context: SubagentContext) {self.subagent_context = Some(context);diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 6c412967821..7a4a621df89 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -6951,6 +6951,111 @@ pub(crate) mod tests {}}+ #[gpui::test]+ async fn test_finished_subagent_tool_call_shows_its_runs_reported_outcome(+ cx: &mut TestAppContext,+ ) {+ use super::subagent_card::{SubagentCardState, SubagentStatus};++ init_test(cx);+ let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());+ let parent = cx.update(|cx| {+ create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx)+ });+ let parent_session_id = parent.read_with(cx, |thread, _| thread.session_id().clone());+ let reporting = cx.update(|cx| {+ create_test_acp_subagent(+ parent_session_id.clone(),+ "reporting",+ connection.clone(),+ project.clone(),+ cx,+ )+ });+ let silent = cx.update(|cx| {+ create_test_acp_subagent(+ parent_session_id.clone(),+ "silent",+ connection.clone(),+ project.clone(),+ cx,+ )+ });+ let without_association = cx.update(|cx| {+ create_test_acp_thread(+ Some(parent_session_id),+ "unassociated",+ connection,+ project,+ cx,+ )+ });+ for subagent in [&reporting, &silent, &without_association] {+ subagent+ .update(cx, |subagent, cx| {+ subagent.upsert_assistant_message(+ acp_v2::AgentMessage::new("work").content(vec!["Working".into()]),+ cx,+ )+ })+ .expect("subagent work");+ }+ reporting+ .update(cx, |subagent, cx| {+ subagent.update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::Cancelled),+ ),+ cx,+ )+ })+ .expect("reported outcome");++ let spawn = |id: &str, status, end, cx: &mut TestAppContext| {+ let session_info = acp_v2::Meta::from_iter([(+ acp_thread::SUBAGENT_SESSION_INFO_META_KEY.into(),+ serde_json::to_value(acp_thread::SubagentSessionInfo {+ session_id: acp_v2::SessionId::new("child"),+ message_start_index: 0,+ message_end_index: end,+ })+ .expect("subagent session info should serialize"),+ )]);+ parent+ .update(cx, |thread, cx| {+ thread.upsert_wire_tool_call(+ acp_v2::ToolCallUpdate::new(id)+ .title("Explore")+ .status(status)+ .content(vec!["Found it".into()])+ .meta(session_info),+ cx,+ )+ })+ .expect("spawn tool call should apply");+ };+ spawn("finished", acp_v2::ToolCallStatus::Completed, Some(0), cx);+ spawn("running", acp_v2::ToolCallStatus::InProgress, None, cx);++ for (id, subagent, expected) in [+ ("finished", &reporting, SubagentStatus::Canceled),+ ("finished", &silent, SubagentStatus::Completed),+ ("finished", &without_association, SubagentStatus::Completed),+ ("running", &reporting, SubagentStatus::Running),+ ] {+ let state = cx.update(|cx| {+ let parent = parent.read(cx);+ let (_, tool_call) = parent+ .tool_call(&acp_v2::ToolCallId::new(id))+ .expect("spawn tool call should exist");+ SubagentCardState::for_subagent_tool_call(tool_call, Some(subagent.read(cx)), cx)+ });+ let subagent_id = subagent.read_with(cx, |subagent, _| subagent.session_id().clone());+ assert_eq!(state.status, expected, "{id} with {subagent_id}");+ }+ }+#[gpui::test]async fn test_referenced_subagents_load_only_without_the_subagents_rfd(cx: &mut TestAppContext,diff --git a/crates/agent_ui/src/conversation_view/subagent_card.rs b/crates/agent_ui/src/conversation_view/subagent_card.rsindex e185d41191f..d52704bc521 100644--- a/crates/agent_ui/src/conversation_view/subagent_card.rs+++ b/crates/agent_ui/src/conversation_view/subagent_card.rs@@ -220,6 +220,38 @@ impl SubagentCardState {}}+ /// Builds the card for a subagent tool call. Once the call has finished, a subagent that+ /// recorded an outcome for the call's run (as native subagents do) shows that outcome.+ /// Calls saved before outcomes were recorded, and subagents of agents that don't report+ /// state, show the tool call's status.+ pub(crate) fn for_subagent_tool_call(+ tool_call: &ToolCall,+ subagent: Option<&AcpThread>,+ cx: &App,+ ) -> Self {+ let card = Self::from_tool_call(tool_call, cx);+ let Some(SubagentEntries {+ start,+ end: Some(_),+ }) = card.entries+ else {+ return card;+ };+ let Some(outcome) = subagent+ .filter(|subagent| subagent.subagent_association().is_some())+ .and_then(|subagent| subagent.subagent_outcome_after(start))+ else {+ return card;+ };+ let (status, error) = SubagentStatus::from_reported_state(Some(outcome));+ Self {+ status,+ error,+ can_stop: false,+ ..card+ }+ }+/// Builds the card for an ACP subagent, covering `entries` of its transcript or all of/// it. The subagent reports one state for all its work, so a card for an earlier message/// shows the first outcome the subagent reported after receiving it. Until then, thatdiff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 4a3871c754c..dbcfaa9094a 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -5207,9 +5207,10 @@ impl ThreadView {return false;};- // An ACP subagent reports its own outcome; a native one's is its parent's tool call.+ // A subagent that reports its own state shows that. Otherwise, as for a native+ // subagent saved before it recorded outcomes, its outcome is its parent's tool call.let thread = self.thread.read(cx);- if thread.subagent_association().is_some() {+ if thread.subagent_association().is_some() && thread.has_received_session_state() {return SubagentCardState::from_acp_subagent(thread, None).status.is_failed_or_canceled();@@ -11957,11 +11958,16 @@ impl ThreadView {.and_then(|connected| connected.threads.get(&session_id))});+ let state = SubagentCardState::for_subagent_tool_call(+ tool_call,+ subagent_thread_view.map(|view| view.read(cx).thread.read(cx)),+ cx,+ );let content = self.render_subagent_card(active_session_id,entry_ix,&SubagentCardId::ToolCall(tool_call.id.clone()),- &SubagentCardState::from_tool_call(tool_call, cx),+ &state,subagent_thread_view,focus_handle,window,