Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent_ui: Show each linked message to an ACP subagent as its own card (#66102)
Ben Brandt33d111eac45e
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex a16ce3147ef..73518eda782 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3652,6 +3652,10 @@ pub struct AcpThread {submissions: SessionSubmissions,activity: SessionActivity,received_session_state: bool,+ /// Each idle state a subagent reported, with how many entries it had then. The subagent+ /// reports one state for all its work, so this is what shows the outcome of an earlier+ /// message to it after it has received later ones.+ subagent_outcomes: Vec<(usize, acp_v2::StateUpdate)>,reported_usage: Option<ReportedTokenUsage>,token_usage: Option<TokenUsage>,cost: Option<SessionCost>,@@ -4013,6 +4017,7 @@ impl AcpThread {),activity: SessionActivity::default(),received_session_state: false,+ subagent_outcomes: Vec::new(),reported_usage: None,connection,token_usage: None,@@ -4303,6 +4308,14 @@ impl AcpThread {self.received_session_state}+ /// 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+ .iter()+ .find(|(entry_count, _)| *entry_count > entry_ix)+ .map(|(_, state)| state)+ }+pub fn foreground_activity(&self) -> ForegroundActivity {self.activity.phase()}@@ -4667,6 +4680,10 @@ impl AcpThread {let previous = self.foreground_activity();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()));+ }self.set_foreground_state(state, cx);if let Some(acp_v2::StateUpdate::Idle(idle)) = self.activity.state() {let stop_reason = idle.stop_reason.clone();diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex b6f53e76f07..390a7d42269 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -20563,7 +20563,7 @@ pub(crate) mod tests {"an idle subagent cannot be stopped");child.read_with(cx, |child, _| {- let card = subagent_card::SubagentCardState::from_acp_subagent(child);+ let card = subagent_card::SubagentCardState::from_acp_subagent(child, None);assert_eq!(card.status, subagent_card::SubagentStatus::Canceled);assert_eq!(card.title(Some("Own title".into())).as_ref(),@@ -20594,6 +20594,142 @@ pub(crate) mod tests {assert!(cx.debug_bounds("subagent-card-0").is_some());}+ #[gpui::test]+ async fn test_each_linked_message_to_an_acp_subagent_is_its_own_card(cx: &mut TestAppContext) {+ use subagent_card::{SubagentCardState, SubagentEntries, SubagentStatus};++ init_test(cx);+ let connection = StubAgentConnection::new();+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;+ add_to_workspace_with_size(conversation_view.clone(), true, cx);+ 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_session_id = acp_v2::SessionId::new("child");+ let child = conversation_view.update(cx, |view, cx| {+ create_test_acp_subagent(+ root_session_id.clone(),+ "child",+ Rc::new(connection.clone()),+ view.project.clone(),+ cx,+ )+ });+ // Each ACP notification is applied in its own update, as here.+ root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));+ let to_child = |message_id: &str| {+ acp_v2::SessionMessage::new(message_id)+ .sender_session_id(root_session_id.clone())+ .recipient_session_id(child_session_id.clone())+ .content(vec![message_id.into()])+ };+ let delegate = |sent: &str, received: &str, cx: &mut VisualTestContext| {+ root.update(cx, |root, cx| {+ root.upsert_session_message(+ to_child(sent).recipient_message_id(acp_v2::MessageId::new(received)),+ cx,+ )+ })+ .expect("outgoing view");+ child+ .update(cx, |child, cx| {+ child.upsert_session_message(+ to_child(received).sender_message_id(acp_v2::MessageId::new(sent)),+ cx,+ )+ })+ .expect("incoming view");+ };+ let report = |state: acp_v2::StateUpdate, cx: &mut VisualTestContext| {+ child+ .update(cx, |child, cx| child.update_session_state(state, cx))+ .expect("reported state");+ };+ let running = || acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new());+ let work = |message_id: &str, cx: &mut VisualTestContext| {+ child+ .update(cx, |child, cx| {+ child.upsert_assistant_message(+ acp_v2::AgentMessage::new(message_id).content(vec!["Working".into()]),+ cx,+ )+ })+ .expect("subagent work");+ };+ let cards = |cx: &mut VisualTestContext| {+ root.read_with(cx, |root, cx| {+ root.entries()+ .iter()+ .enumerate()+ .map(|(entry_ix, entry)| {+ let AgentThreadEntry::SessionMessage(message) = entry else {+ panic!("expected session messages, got {entry:?}");+ };+ subagent_card::acp_subagent_card(root, entry_ix, message, cx).map(|card| {+ let state = SubagentCardState::from_acp_subagent(+ card.subagent.read(cx),+ card.entries,+ );+ (card.entries, state.status)+ })+ })+ .collect::<Vec<_>>()+ })+ };+ let entries = |start, end| Some(SubagentEntries { start, end });++ delegate("launch", "task-1", cx);+ report(running(), cx);+ work("work-1", cx);+ // The second message arrives while the subagent still works on the first.+ delegate("follow-up", "task-2", cx);+ work("work-2", cx);+ assert_eq!(+ cards(cx),+ vec![+ Some((entries(0, Some(1)), SubagentStatus::Running)),+ Some((entries(2, None), SubagentStatus::Running)),+ ],+ "each message covers its part of the subagent, and an earlier one without an \+ outcome yet shows the current state"+ );++ report(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::Refusal),+ ),+ cx,+ );+ delegate("retry", "task-3", cx);+ report(running(), cx);+ // A later message the subagent's view does not link to stays a row.+ root.update(cx, |root, cx| {+ root.upsert_session_message(to_child("unlinked"), cx)+ })+ .expect("outgoing view");+ assert_eq!(+ cards(cx),+ vec![+ Some((entries(0, Some(1)), SubagentStatus::Failed)),+ Some((entries(2, Some(3)), SubagentStatus::Failed)),+ Some((entries(4, None), SubagentStatus::Running)),+ None,+ ],+ "an earlier message shows the first outcome after it"+ );++ cx.run_until_parked();+ for selector in ["subagent-card-0", "subagent-card-1", "subagent-card-2"] {+ assert!(cx.debug_bounds(selector).is_some(), "{selector}");+ }+ assert!(+ cx.debug_bounds("subagent-card-3").is_none()+ && cx.debug_bounds("session-message-participant-3").is_some(),+ "the unlinked message is drawn as a row"+ );+ }+#[gpui::test]async fn test_acp_subagent_titlebar_stops_only_with_cancel(cx: &mut TestAppContext) {init_test(cx);diff --git a/crates/agent_ui/src/conversation_view/subagent_card.rs b/crates/agent_ui/src/conversation_view/subagent_card.rsindex 094e7adad73..c4e511abe74 100644--- a/crates/agent_ui/src/conversation_view/subagent_card.rs+++ b/crates/agent_ui/src/conversation_view/subagent_card.rs@@ -30,16 +30,27 @@ impl fmt::Display for SubagentCardId {}}-/// The subagent whose card a session message in `thread` is drawn as, in place of its-/// message row. The message must be the first that `thread` sent to one of its own-/// subagents. Later messages to the same subagent stay message rows, because nothing yet-/// links each message to its part of the subagent's transcript or to its outcome, so one-/// card covers the whole subagent.+/// A session message that an ACP parent sent to one of its own subagents, drawn as a+/// subagent card in place of its message row.+pub(crate) struct AcpSubagentCard {+ pub id: SubagentCardId,+ pub subagent: Entity<AcpThread>,+ /// The subagent entries for this message; `None` covers the whole subagent.+ pub entries: Option<SubagentEntries>,+}++/// The subagent card that a session message in `thread` is drawn as, if any.+///+/// A message linked to the subagent's view of it gets a card for its part of the+/// subagent's transcript: from that view up to the next message from `thread`. Without a+/// link, only the first message to a subagent gets a card, which covers the whole subagent,+/// and later ones stay message rows.pub(crate) fn acp_subagent_card(thread: &AcpThread,entry_ix: usize,message: &SessionMessage,-) -> Option<(SubagentCardId, Entity<AcpThread>)> {+ cx: &App,+) -> Option<AcpSubagentCard> {let own_session_id = thread.session_id();let SessionMessageSide::Outgoing {recipient: Some(recipient),@@ -51,6 +62,34 @@ pub(crate) fn acp_subagent_card(let MessageIdentity::Keyed(message_id) = &message.identity else {return None;};+ let id = SubagentCardId::SessionMessage(message_id.clone());++ let subagent_thread = subagent.read(cx);+ if let Some(start) = subagent_thread.linked_session_message(message, own_session_id) {+ let next_message_ix = subagent_thread+ .entries()+ .iter()+ .enumerate()+ .skip(start + 1)+ .find_map(|(ix, entry)| {+ matches!(+ entry,+ AgentThreadEntry::SessionMessage(later)+ if later.side(recipient)+ == SessionMessageSide::Incoming { sender: Some(own_session_id) }+ )+ .then_some(ix)+ });+ return Some(AcpSubagentCard {+ id,+ subagent,+ entries: Some(SubagentEntries {+ start,+ end: next_message_ix.map(|next_message_ix| next_message_ix - 1),+ }),+ });+ }+let sent_earlier = thread.entries().get(..entry_ix)?.iter().any(|entry| {matches!(entry,@@ -59,7 +98,11 @@ pub(crate) fn acp_subagent_card(== SessionMessageSide::Outgoing { recipient: Some(recipient) })});- (!sent_earlier).then(|| (SubagentCardId::SessionMessage(message_id.clone()), subagent))+ (!sent_earlier).then_some(AcpSubagentCard {+ id,+ subagent,+ entries: None,+ })}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -177,10 +220,16 @@ impl SubagentCardState {}}- /// Builds the card for an ACP subagent. Without a link from the parent's message to the- /// subagent's entries, the card covers the subagent's whole transcript.- pub(crate) fn from_acp_subagent(thread: &AcpThread) -> Self {- let (status, error) = SubagentStatus::from_reported_state(thread.foreground_state());+ /// 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, that+ /// work continues alongside the later message's, and the card shows the current state.+ pub(crate) fn from_acp_subagent(thread: &AcpThread, entries: Option<SubagentEntries>) -> Self {+ let earlier_outcome = entries+ .filter(|entries| entries.end.is_some())+ .and_then(|entries| thread.subagent_outcome_after(entries.start));+ let (status, error) =+ SubagentStatus::from_reported_state(earlier_outcome.or(thread.foreground_state()));let can_cancel = thread.subagent_association().is_some_and(|association| association.can_cancel);@@ -190,7 +239,7 @@ impl SubagentCardState {status,error,can_stop: status == SubagentStatus::Running && can_cancel,- entries: None,+ entries,}}diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rsindex 84111171cb2..3e765597a5e 100644--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs@@ -364,7 +364,7 @@ impl ThreadSearchBar {}// Drawn as the subagent's card, which does not show the message.AgentThreadEntry::SessionMessage(message)- if acp_subagent_card(thread, entry_ix, message).is_some() => {}+ if acp_subagent_card(thread, entry_ix, message, cx).is_some() => {}_ => {for markdown in collect_markdowns(entry_ix, entry, &entry_view_state, cx) {let source = markdown.read(cx).source().clone();diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 740791f56b5..34032b1bd50 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -56,7 +56,9 @@ use workspace::{OpenOptions, SERIALIZATION_THROTTLE_TIME};use super::elicitation::{ElicitationCard, ElicitationCardHandlers, ElicitationFormState, should_render_elicitation,};-use super::subagent_card::{SubagentCardId, SubagentCardState, SubagentStatus, acp_subagent_card};+use super::subagent_card::{+ AcpSubagentCard, SubagentCardId, SubagentCardState, SubagentStatus, acp_subagent_card,+};use super::*;/// How a parent's view names a subagent. An ACP parent's own title for the subagent@@ -5208,7 +5210,7 @@ impl ThreadView {// An ACP subagent reports its own outcome; a native one's is its parent's tool call.let thread = self.thread.read(cx);if thread.subagent_association().is_some() {- return SubagentCardState::from_acp_subagent(thread)+ return SubagentCardState::from_acp_subagent(thread, None).status.is_failed_or_canceled();}@@ -7530,10 +7532,8 @@ impl ThreadView {}AgentThreadEntry::SessionMessage(message) => {let session_message =- match acp_subagent_card(self.thread.read(cx), entry_ix, message) {- Some((card_id, subagent)) => {- self.render_acp_subagent_card(entry_ix, &card_id, &subagent, window, cx)- }+ match acp_subagent_card(self.thread.read(cx), entry_ix, message, cx) {+ Some(card) => self.render_acp_subagent_card(entry_ix, &card, window, cx),None => self.render_session_message(entry_ix, message, window, cx),};if let Some(handle) = self@@ -8950,12 +8950,12 @@ impl ThreadView {fn render_acp_subagent_card(&self,entry_ix: usize,- card_id: &SubagentCardId,- subagent: &Entity<AcpThread>,+ card: &AcpSubagentCard,window: &Window,cx: &Context<Self>,) -> Div {- let subagent_session_id = subagent.read(cx).session_id().clone();+ let subagent = card.subagent.read(cx);+ let subagent_session_id = subagent.session_id().clone();let subagent_thread_view = self.server_view.upgrade()@@ -8964,8 +8964,8 @@ impl ThreadView {let content = self.render_subagent_card(self.thread.read(cx).session_id(),entry_ix,- card_id,- &SubagentCardState::from_acp_subagent(subagent.read(cx)),+ &card.id,+ &SubagentCardState::from_acp_subagent(subagent, card.entries),subagent_thread_view,&self.focus_handle(cx),window,