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.

agent_ui: Show ACP subagents as inline cards (#66040)

Ben Brandtd93bf7408526
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index d1b6cfae98a..4e9cc92387d 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -3697,6 +3697,9 @@ pub enum OutputTokensUpdate {
#[derive(Debug)]
pub enum AcpThreadEvent {
StatusChanged,
+ /// The parent's title, description, or capabilities for this subagent changed. Views that
+ /// read them from the parent's side, such as its subagent card, observe this event.
+ SubagentAssociationUpdated,
/// Idle confirmed after unconfirmed or unknown activity, without completing
/// foreground work.
ActivityConfirmedIdle,
@@ -3865,6 +3868,7 @@ impl AcpThread {
| AcpThreadEvent::EntryUpdated(_)
| AcpThreadEvent::Retry(_)
| AcpThreadEvent::SubagentSpawned(_)
+ | AcpThreadEvent::SubagentAssociationUpdated
| AcpThreadEvent::Stopped { .. }
| AcpThreadEvent::Error
| AcpThreadEvent::ConnectionLost
@@ -3975,6 +3979,7 @@ impl AcpThread {
.as_mut()
.context("Session is not an ACP subagent")?;
association.apply(update);
+ cx.emit(AcpThreadEvent::SubagentAssociationUpdated);
cx.notify();
Ok(())
}
diff --git a/crates/agent_ui/src/agent_diff.rs b/crates/agent_ui/src/agent_diff.rs
index 91d5725bd10..31d22a5b78b 100644
--- a/crates/agent_ui/src/agent_diff.rs
+++ b/crates/agent_ui/src/agent_diff.rs
@@ -1477,6 +1477,7 @@ impl AgentDiff {
| AcpThreadEvent::TokenUsageUpdated(_)
| AcpThreadEvent::NoticesUpdated
| AcpThreadEvent::SubagentSpawned(_)
+ | AcpThreadEvent::SubagentAssociationUpdated
| AcpThreadEvent::EntriesRemoved(_)
| AcpThreadEvent::ToolAuthorizationRequested(_)
| AcpThreadEvent::ToolAuthorizationReceived(_)
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 124299aecc2..95234fc3c60 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -354,6 +354,7 @@ impl Conversation {
| AcpThreadEvent::EntriesRemoved(_)
| AcpThreadEvent::Retry(_)
| AcpThreadEvent::SubagentSpawned(_)
+ | AcpThreadEvent::SubagentAssociationUpdated
| AcpThreadEvent::Stopped { .. }
| AcpThreadEvent::Error
| AcpThreadEvent::ConnectionLost
@@ -789,6 +790,7 @@ fn affects_thread_metadata(event: &AcpThreadEvent) -> bool {
| AcpThreadEvent::ModeUpdated(_)
| AcpThreadEvent::ConfigOptionsUpdated(_)
| AcpThreadEvent::SubagentSpawned(_)
+ | AcpThreadEvent::SubagentAssociationUpdated
| AcpThreadEvent::NoticesUpdated
| AcpThreadEvent::PromptUpdated => false,
}
@@ -2034,6 +2036,9 @@ impl ConversationView {
self.add_subagent_thread_view(subagent, window, cx);
}
}
+ // The parent's card and permission rows read the association; the notify below
+ // redraws them.
+ AcpThreadEvent::SubagentAssociationUpdated => {}
AcpThreadEvent::ToolAuthorizationRequested(_) => {
self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
}
@@ -20253,16 +20258,17 @@ pub(crate) mod tests {
});
// Each ACP notification is applied in its own update, as here.
root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));
+ // An outgoing message to a subagent is its card, so this test uses its reply.
root.update(cx, |root, cx| {
root.upsert_session_message(
- acp_v2::SessionMessage::new("to-child")
- .sender_session_id(root_session_id.clone())
- .recipient_session_id(acp_v2::SessionId::new("child"))
- .content(vec!["Investigate the failure".into()]),
+ acp_v2::SessionMessage::new("from-child")
+ .sender_session_id(acp_v2::SessionId::new("child"))
+ .recipient_session_id(root_session_id.clone())
+ .content(vec!["Found it".into()]),
cx,
)
})
- .expect("outgoing message");
+ .expect("incoming message");
root.update(cx, |root, cx| {
root.upsert_session_message(
acp_v2::SessionMessage::new("from-unknown")
@@ -20294,7 +20300,7 @@ pub(crate) mod tests {
);
let link = cx
.debug_bounds("session-message-participant-0")
- .expect("the recipient links to its session");
+ .expect("the sender links to its session");
cx.simulate_click(link.center(), gpui::Modifiers::default());
cx.run_until_parked();
let active_session_id = active_thread(&conversation_view, cx)
@@ -20302,6 +20308,196 @@ pub(crate) mod tests {
assert_eq!(active_session_id, acp_v2::SessionId::new("child"));
}
+ #[gpui::test]
+ async fn test_first_message_to_an_acp_subagent_shows_its_card(cx: &mut TestAppContext) {
+ 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 = conversation_view.update(cx, |view, cx| {
+ create_test_acp_subagent(
+ root_session_id.clone(),
+ "child",
+ Rc::new(connection.clone()),
+ view.project.clone(),
+ cx,
+ )
+ });
+ child.update(cx, |child, cx| {
+ child
+ .update_subagent_association(
+ &acp_v2::SubagentUpdate::new("child").title("Investigator"),
+ cx,
+ )
+ .expect("ACP subagent")
+ });
+ child.update(cx, |child, cx| {
+ child
+ .update_session_state(
+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),
+ cx,
+ )
+ .expect("reported state")
+ });
+ // Each ACP notification is applied in its own update, as here.
+ root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));
+ for (message_id, text) in [
+ ("launch", "Check the failure"),
+ ("follow-up", "Also check Windows"),
+ ] {
+ root.update(cx, |root, cx| {
+ root.upsert_session_message(
+ acp_v2::SessionMessage::new(message_id)
+ .sender_session_id(root_session_id.clone())
+ .recipient_session_id(acp_v2::SessionId::new("child"))
+ .content(vec![text.into()]),
+ cx,
+ )
+ })
+ .expect("outgoing message");
+ }
+ cx.run_until_parked();
+
+ assert!(
+ cx.debug_bounds("subagent-card-0").is_some(),
+ "the first message to the subagent is its card"
+ );
+ assert!(
+ cx.debug_bounds("subagent-card-1").is_none()
+ && cx.debug_bounds("session-message-participant-1").is_some(),
+ "a later message to the same subagent stays a row"
+ );
+ assert!(
+ cx.debug_bounds("stop-subagent-0").is_none(),
+ "a subagent that does not advertise cancel cannot be stopped"
+ );
+
+ let thread_view = active_thread(&conversation_view, cx);
+ thread_view.update_in(cx, |view, window, cx| {
+ view.toggle_search(&crate::ToggleSearch, window, cx);
+ });
+ cx.run_until_parked();
+ let bar = thread_view
+ .read_with(cx, |view, _| view.thread_search_bar.clone())
+ .expect("search bar");
+ bar.update_in(cx, |bar, window, cx| {
+ bar.query_editor.update(cx, |editor, cx| {
+ editor.set_text("check", window, cx);
+ });
+ bar.update_matches(window, cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ bar.read_with(cx, |bar, _| bar.match_count()),
+ 1,
+ "the card does not show its message, so only the row's text matches"
+ );
+
+ child.update(cx, |child, cx| {
+ child
+ .update_subagent_association(
+ &acp_v2::SubagentUpdate::new("child").capabilities(
+ acp_v2::SubagentSessionCapabilities::new()
+ .cancel(acp_v2::SessionCancelCapabilities::new()),
+ ),
+ cx,
+ )
+ .expect("ACP subagent")
+ });
+ cx.run_until_parked();
+ let stop = cx
+ .debug_bounds("stop-subagent-0")
+ .expect("a running subagent that advertises cancel can be stopped");
+ cx.simulate_click(stop.center(), gpui::Modifiers::default());
+ cx.run_until_parked();
+ assert_eq!(
+ connection.take_cancel_calls(),
+ vec![acp_v2::SessionId::new("child")],
+ "stopping cancels only the subagent"
+ );
+
+ child.update(cx, |child, cx| {
+ child
+ .update_session_state(
+ acp_v2::StateUpdate::Idle(
+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::Cancelled),
+ ),
+ cx,
+ )
+ .expect("reported state")
+ });
+ cx.run_until_parked();
+ assert!(
+ cx.debug_bounds("stop-subagent-0").is_none(),
+ "an idle subagent cannot be stopped"
+ );
+ child.read_with(cx, |child, _| {
+ let card = subagent_card::SubagentCardState::from_acp_subagent(child);
+ assert_eq!(card.status, subagent_card::SubagentStatus::Canceled);
+ assert_eq!(
+ card.title(Some("Own title".into())).as_ref(),
+ "Investigator"
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_acp_subagent_titlebar_stops_only_with_cancel(cx: &mut TestAppContext) {
+ 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 = conversation_view.update(cx, |view, cx| {
+ create_test_acp_subagent(
+ root_session_id,
+ "child",
+ Rc::new(connection.clone()),
+ view.project.clone(),
+ cx,
+ )
+ });
+ child.update(cx, |child, cx| {
+ child
+ .update_session_state(
+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),
+ cx,
+ )
+ .expect("reported state")
+ });
+ root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));
+ cx.run_until_parked();
+ conversation_view.update_in(cx, |view, window, cx| {
+ view.navigate_to_thread(acp_v2::SessionId::new("child"), window, cx)
+ });
+ cx.run_until_parked();
+ assert!(
+ cx.debug_bounds("subagent-titlebar-stop").is_none(),
+ "a running subagent that does not advertise cancel cannot be stopped"
+ );
+
+ child.update(cx, |child, cx| {
+ child
+ .update_subagent_association(
+ &acp_v2::SubagentUpdate::new("child").capabilities(
+ acp_v2::SubagentSessionCapabilities::new()
+ .cancel(acp_v2::SessionCancelCapabilities::new()),
+ ),
+ cx,
+ )
+ .expect("ACP subagent")
+ });
+ cx.run_until_parked();
+ assert!(cx.debug_bounds("subagent-titlebar-stop").is_some());
+ }
+
#[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/subagent_card.rs b/crates/agent_ui/src/conversation_view/subagent_card.rs
index 6f3cb12c27f..119e3871c82 100644
--- a/crates/agent_ui/src/conversation_view/subagent_card.rs
+++ b/crates/agent_ui/src/conversation_view/subagent_card.rs
@@ -1,19 +1,120 @@
-use acp_thread::{ToolCall, ToolCallContent, ToolCallStatus};
-use gpui::{App, SharedString};
-use std::ops::Range;
+use acp_thread::{
+ AcpThread, AgentThreadEntry, MessageIdentity, SessionMessage, ToolCall, ToolCallContent,
+ ToolCallStatus,
+};
+use agent_client_protocol::schema::v2 as acp_v2;
+use gpui::{App, Entity, SharedString};
+use std::{fmt, ops::Range};
+
+use super::thread_view::{SessionMessageSide, session_message_side, subagent_label};
/// Native subagent tool calls report a user cancellation as output with this text.
const USER_CANCELED_OUTPUT: &str = "User canceled";
+/// The transcript entry a subagent card stands for. It keys the card's expansion state
+/// and element IDs, since the same subagent can have more than one card.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub(crate) enum SubagentCardId {
+ /// A native `spawn_agent` tool call.
+ ToolCall(acp_v2::ToolCallId),
+ /// An ACP parent's outgoing session message to the subagent.
+ SessionMessage(acp_v2::MessageId),
+}
+
+impl fmt::Display for SubagentCardId {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::ToolCall(id) => write!(f, "tool-call-{id}"),
+ Self::SessionMessage(id) => write!(f, "session-message-{id}"),
+ }
+ }
+}
+
+/// 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.
+pub(crate) fn acp_subagent_card(
+ thread: &AcpThread,
+ entry_ix: usize,
+ message: &SessionMessage,
+) -> Option<(SubagentCardId, Entity<AcpThread>)> {
+ let own_session_id = thread.session_id();
+ let SessionMessageSide::Outgoing {
+ recipient: Some(recipient),
+ } = session_message_side(message, own_session_id)
+ else {
+ return None;
+ };
+ let subagent = thread.subagent(recipient)?.clone();
+ let MessageIdentity::Keyed(message_id) = &message.identity else {
+ return None;
+ };
+ let sent_earlier = thread.entries().get(..entry_ix)?.iter().any(|entry| {
+ matches!(
+ entry,
+ AgentThreadEntry::SessionMessage(earlier)
+ if session_message_side(earlier, own_session_id)
+ == SessionMessageSide::Outgoing { recipient: Some(recipient) }
+ )
+ });
+ (!sent_earlier).then(|| (SubagentCardId::SessionMessage(message_id.clone()), subagent))
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SubagentStatus {
Running,
Completed,
Failed,
Canceled,
+ /// An ACP subagent that has reported no state yet, or reported that its state is unknown.
+ Unknown,
}
impl SubagentStatus {
+ /// An ACP subagent's status from the state it last reported, with the error to show for a
+ /// failure. Idle with no stop reason, or with one this version does not know, is a normal
+ /// end, as it is for any ACP session.
+ pub(crate) fn from_reported_state(
+ state: Option<&acp_v2::StateUpdate>,
+ ) -> (Self, Option<SharedString>) {
+ let Some(state) = state else {
+ return (Self::Unknown, None);
+ };
+ match state {
+ acp_v2::StateUpdate::Running(_) | acp_v2::StateUpdate::RequiresAction(_) => {
+ (Self::Running, None)
+ }
+ acp_v2::StateUpdate::Idle(idle) => match &idle.stop_reason {
+ Some(acp_v2::StopReason::Cancelled) => (Self::Canceled, None),
+ Some(acp_v2::StopReason::Error(error)) => (
+ Self::Failed,
+ error
+ .error
+ .as_ref()
+ .map(|error| error.message.trim())
+ .filter(|message| !message.is_empty())
+ .map(|message| message.to_string().into()),
+ ),
+ Some(acp_v2::StopReason::MaxTokens) => (
+ Self::Failed,
+ Some("The subagent reached its token limit.".into()),
+ ),
+ Some(acp_v2::StopReason::MaxTurnRequests) => (
+ Self::Failed,
+ Some("The subagent reached its limit of model requests.".into()),
+ ),
+ Some(acp_v2::StopReason::Refusal) => (
+ Self::Failed,
+ Some("The subagent's model refused to continue.".into()),
+ ),
+ _ => (Self::Completed, None),
+ },
+ _ => (Self::Unknown, None),
+ }
+ }
+
pub(crate) fn from_tool_call(tool_call: &ToolCall, cx: &App) -> Self {
match tool_call.status() {
ToolCallStatus::Pending
@@ -34,8 +135,12 @@ impl SubagentStatus {
/// What a subagent card shows, independent of the source it was built from.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SubagentCardState {
- /// The parent's label for the subagent. The card prefers the subagent thread's own title.
+ /// The parent's label for the subagent. A native card prefers the subagent thread's own
+ /// title; see `label_wins`.
pub label: Option<SharedString>,
+ /// An ACP parent's own label for the subagent describes it in the parent's view, so it
+ /// wins over the subagent's title for itself.
+ pub label_wins: bool,
pub status: SubagentStatus,
pub error: Option<SharedString>,
pub can_stop: bool,
@@ -58,6 +163,7 @@ impl SubagentCardState {
let label = tool_call.label.read(cx).source();
Self {
label: (!label.is_empty()).then(|| label.to_string().into()),
+ label_wins: false,
status,
error: tool_call_error(tool_call, cx),
can_stop: status == SubagentStatus::Running,
@@ -71,14 +177,37 @@ 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());
+ let can_cancel = thread
+ .subagent_association()
+ .is_some_and(|association| association.can_cancel);
+ Self {
+ label: Some(subagent_label(thread)),
+ label_wins: true,
+ status,
+ error,
+ can_stop: status == SubagentStatus::Running && can_cancel,
+ entries: None,
+ }
+ }
+
pub(crate) fn title(&self, thread_title: Option<SharedString>) -> SharedString {
- thread_title
- .or_else(|| self.label.clone())
- .unwrap_or_else(|| match self.status {
- SubagentStatus::Canceled => "Subagent Canceled".into(),
- SubagentStatus::Failed => "Subagent Failed".into(),
- SubagentStatus::Running | SubagentStatus::Completed => "Spawning Agent…".into(),
- })
+ let label = self.label.clone();
+ let title = if self.label_wins {
+ label.or(thread_title)
+ } else {
+ thread_title.or(label)
+ };
+ title.unwrap_or_else(|| match self.status {
+ SubagentStatus::Canceled => "Subagent Canceled".into(),
+ SubagentStatus::Failed => "Subagent Failed".into(),
+ SubagentStatus::Running | SubagentStatus::Completed | SubagentStatus::Unknown => {
+ "Spawning Agent…".into()
+ }
+ })
}
/// The last `max_entries` of the entries this card covers.
@@ -133,6 +262,7 @@ mod tests {
) -> SubagentCardState {
SubagentCardState {
label: label.map(|label| label.to_string().into()),
+ label_wins: false,
status,
error: None,
can_stop: false,
@@ -158,6 +288,93 @@ mod tests {
}
}
+ #[test]
+ fn an_acp_parents_label_wins_over_the_subagents_title() {
+ let acp_card = SubagentCardState {
+ label_wins: true,
+ ..card(Some("Investigator"), SubagentStatus::Running, None)
+ };
+ assert_eq!(
+ acp_card.title(Some("Own title".into())).as_ref(),
+ "Investigator"
+ );
+ let unlabeled = SubagentCardState {
+ label_wins: true,
+ ..card(None, SubagentStatus::Running, None)
+ };
+ assert_eq!(
+ unlabeled.title(Some("Own title".into())).as_ref(),
+ "Own title"
+ );
+ }
+
+ #[test]
+ fn reported_states_map_to_card_statuses() {
+ let idle = |stop_reason: Option<acp_v2::StopReason>| {
+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new().stop_reason(stop_reason))
+ };
+ let mut error = acp_v2::Error::internal_error();
+ error.message = "Context too small".into();
+ for (state, expected_status, expected_error) in [
+ (None, SubagentStatus::Unknown, None),
+ (
+ Some(acp_v2::StateUpdate::Running(
+ acp_v2::RunningStateUpdate::new(),
+ )),
+ SubagentStatus::Running,
+ None,
+ ),
+ (
+ Some(acp_v2::StateUpdate::RequiresAction(
+ acp_v2::RequiresActionStateUpdate::new(),
+ )),
+ SubagentStatus::Running,
+ None,
+ ),
+ (
+ Some(acp_v2::StateUpdate::Unknown(
+ acp_v2::UnknownStateUpdate::new(),
+ )),
+ SubagentStatus::Unknown,
+ None,
+ ),
+ (Some(idle(None)), SubagentStatus::Completed, None),
+ (
+ Some(idle(Some(acp_v2::StopReason::EndTurn))),
+ SubagentStatus::Completed,
+ None,
+ ),
+ (
+ Some(idle(Some(acp_v2::StopReason::Cancelled))),
+ SubagentStatus::Canceled,
+ None,
+ ),
+ (
+ Some(idle(Some(acp_v2::StopReason::Error(
+ acp_v2::ErrorStopReason::new().error(error),
+ )))),
+ SubagentStatus::Failed,
+ Some("Context too small"),
+ ),
+ (
+ Some(idle(Some(acp_v2::StopReason::Error(
+ acp_v2::ErrorStopReason::new(),
+ )))),
+ SubagentStatus::Failed,
+ None,
+ ),
+ (
+ Some(idle(Some(acp_v2::StopReason::Refusal))),
+ SubagentStatus::Failed,
+ Some("The subagent's model refused to continue."),
+ ),
+ ] {
+ let (status, error) = SubagentStatus::from_reported_state(state.as_ref());
+ assert_eq!(status, expected_status, "{state:?}");
+ assert_eq!(error.as_deref(), expected_error, "{state:?}");
+ }
+ }
+
#[test]
fn preview_range_shows_the_last_entries_the_card_covers() {
let whole_thread = card(None, SubagentStatus::Running, None);
diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
index 0a1aa6a42c4..84111171cb2 100644
--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs
+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
@@ -23,6 +23,7 @@ use theme_settings::ThemeSettings;
use ui::{IconButtonShape, Tooltip, prelude::*};
use util::paths::PathMatcher;
+use super::subagent_card::acp_subagent_card;
use crate::entry_view_state::EntryViewState;
actions!(
@@ -361,6 +362,9 @@ impl ThreadSearchBar {
snapshot,
});
}
+ // 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() => {}
_ => {
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.rs
index 32ef9a5dba9..f6cf1030f86 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -55,7 +55,7 @@ use workspace::{OpenOptions, SERIALIZATION_THROTTLE_TIME};
use super::elicitation::{
ElicitationCard, ElicitationCardHandlers, ElicitationFormState, should_render_elicitation,
};
-use super::subagent_card::{SubagentCardState, SubagentStatus};
+use super::subagent_card::{SubagentCardId, SubagentCardState, SubagentStatus, acp_subagent_card};
use super::*;
/// Which side of a session message a transcript shows, and the other participant when it
@@ -5249,7 +5249,15 @@ impl ThreadView {
return false;
};
- let my_session_id = self.thread.read(cx).session_id().clone();
+ // 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)
+ .status
+ .is_failed_or_canceled();
+ }
+
+ let my_session_id = thread.session_id().clone();
self.server_view
.upgrade()
@@ -5276,6 +5284,12 @@ impl ThreadView {
let thread = self.thread.clone();
let is_done = thread.read(cx).status() == ThreadStatus::Idle;
let is_canceled_or_failed = self.is_subagent_canceled_or_failed(cx);
+ // An ACP subagent can only be cancelled when its parent advertises `cancel` for it.
+ let can_stop = !is_done
+ && thread
+ .read(cx)
+ .subagent_association()
+ .is_none_or(|association| association.can_cancel);
let max_content_width = AgentSettings::get_global(cx).max_content_width;
@@ -5318,15 +5332,22 @@ impl ThreadView {
.child(
h_flex()
.gap_0p5()
- .when(!is_done, |this| {
+ .when(can_stop, |this| {
this.child(
- IconButton::new("stop_subagent", IconName::Stop)
- .icon_size(IconSize::Small)
- .icon_color(Color::Error)
- .tooltip(Tooltip::text("Stop Subagent"))
- .on_click(cx.listener(move |this, _, _, cx| {
- this.cancel_thread(&thread, cx).detach();
- })),
+ div()
+ .debug_selector(|| "subagent-titlebar-stop".into())
+ .child(
+ IconButton::new("stop_subagent", IconName::Stop)
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Error)
+ .tooltip(Tooltip::text("Stop Subagent"))
+ .on_click(cx.listener(
+ move |this, _, _, cx| {
+ this.cancel_thread(&thread, cx)
+ .detach();
+ },
+ )),
+ ),
)
})
.child(
@@ -7576,7 +7597,13 @@ impl ThreadView {
self.render_context_compaction(entry_ix, compaction, window, cx)
}
AgentThreadEntry::SessionMessage(message) => {
- let session_message = self.render_session_message(entry_ix, message, window, cx);
+ 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)
+ }
+ None => self.render_session_message(entry_ix, message, window, cx),
+ };
if let Some(handle) = self
.entry_view_state
.read(cx)
@@ -8979,6 +9006,39 @@ impl ThreadView {
)
}
+ fn render_acp_subagent_card(
+ &self,
+ entry_ix: usize,
+ card_id: &SubagentCardId,
+ subagent: &Entity<AcpThread>,
+ window: &Window,
+ cx: &Context<Self>,
+ ) -> Div {
+ let subagent_session_id = subagent.read(cx).session_id().clone();
+ let subagent_thread_view = self
+ .server_view
+ .upgrade()
+ .and_then(|server_view| server_view.read(cx).as_connected())
+ .and_then(|connected| connected.threads.get(&subagent_session_id));
+ let content = self.render_subagent_card(
+ self.thread.read(cx).session_id(),
+ entry_ix,
+ card_id,
+ &SubagentCardState::from_acp_subagent(subagent.read(cx)),
+ subagent_thread_view,
+ &self.focus_handle(cx),
+ window,
+ cx,
+ );
+
+ v_flex()
+ .mx_5()
+ .my_1p5()
+ .gap_3()
+ .debug_selector(move || format!("subagent-card-{entry_ix}"))
+ .child(content)
+ }
+
/// How this conversation names another of its sessions, or `None` when it has no thread
/// for that session.
pub(super) fn session_participant_label(
@@ -11920,7 +11980,7 @@ impl ThreadView {
let content = self.render_subagent_card(
active_session_id,
entry_ix,
- &tool_call.id,
+ &SubagentCardId::ToolCall(tool_call.id.clone()),
&SubagentCardState::from_tool_call(tool_call, cx),
subagent_thread_view,
focus_handle,
@@ -11931,13 +11991,11 @@ impl ThreadView {
v_flex().mx_5().my_1p5().gap_3().child(content)
}
- /// `card_id` keys the card's expansion state and element IDs, since the same
- /// subagent can have one card per message it was sent.
fn render_subagent_card(
&self,
active_session_id: &acp_v2::SessionId,
entry_ix: usize,
- card_id: &acp_v2::ToolCallId,
+ card_id: &SubagentCardId,
state: &SubagentCardState,
thread_view: Option<&Entity<ThreadView>>,
focus_handle: &FocusHandle,
@@ -11963,10 +12021,7 @@ impl ThreadView {
})
.is_some();
- let is_expanded = self
- .entry_view_state
- .read(cx)
- .is_tool_call_expanded(card_id);
+ let is_expanded = self.is_subagent_card_expanded(card_id, cx);
let files_changed = changed_buffers.len();
let diff_stats = DiffStats::all_files(changed_buffers, cx);
@@ -12021,6 +12076,15 @@ impl ThreadView {
.size(IconSize::Small)
.color(Color::Success)
.into_any_element(),
+ SubagentStatus::Unknown => div()
+ .id(status_icon)
+ .child(
+ Icon::new(IconName::CircleHelp)
+ .size(IconSize::Small)
+ .color(Color::Muted),
+ )
+ .tooltip(Tooltip::text("Subagent Status Unknown"))
+ .into_any_element(),
});
let has_expandable_content = thread
@@ -12154,10 +12218,7 @@ impl ThreadView {
let card_id = card_id.clone();
move |this, _, window, cx| {
let expanded =
- this.entry_view_state.update(cx, |state, _cx| {
- state.toggle_tool_call_expansion(&card_id);
- state.is_tool_call_expanded(&card_id)
- });
+ this.toggle_subagent_card_expansion(&card_id, cx);
this.materialize_tool_call_views(entry_ix, window, cx);
this.refresh_thread_search(window, cx);
telemetry::event!("Subagent Toggled", expanded);
@@ -12168,22 +12229,29 @@ impl ThreadView {
)
.when(state.can_stop && subagent_session_id.is_some(), |buttons| {
buttons.child(
- IconButton::new(format!("stop-subagent-{}", entry_ix), IconName::Stop)
- .icon_size(IconSize::Small)
- .icon_color(Color::Error)
- .tooltip(Tooltip::text("Stop Subagent"))
- .when_some(
- thread_view
- .as_ref()
- .map(|view| view.read(cx).thread.clone()),
- |this, thread| {
- this.on_click(cx.listener(
- move |this, _event, _window, cx| {
- telemetry::event!("Subagent Stopped");
- this.cancel_thread(&thread, cx).detach();
- },
- ))
- },
+ div()
+ .debug_selector(move || format!("stop-subagent-{entry_ix}"))
+ .child(
+ IconButton::new(
+ format!("stop-subagent-{}", entry_ix),
+ IconName::Stop,
+ )
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Error)
+ .tooltip(Tooltip::text("Stop Subagent"))
+ .when_some(
+ thread_view
+ .as_ref()
+ .map(|view| view.read(cx).thread.clone()),
+ |this, thread| {
+ this.on_click(cx.listener(
+ move |this, _event, _window, cx| {
+ telemetry::event!("Subagent Stopped");
+ this.cancel_thread(&thread, cx).detach();
+ },
+ ))
+ },
+ ),
),
)
}),
@@ -12265,10 +12333,31 @@ impl ThreadView {
.into_any_element()
}
+ fn is_subagent_card_expanded(&self, card_id: &SubagentCardId, cx: &App) -> bool {
+ let state = self.entry_view_state.read(cx);
+ match card_id {
+ SubagentCardId::ToolCall(id) => state.is_tool_call_expanded(id),
+ SubagentCardId::SessionMessage(id) => state.is_session_message_card_expanded(id),
+ }
+ }
+
+ /// Returns whether the card is expanded afterwards.
+ fn toggle_subagent_card_expansion(
+ &mut self,
+ card_id: &SubagentCardId,
+ cx: &mut Context<Self>,
+ ) -> bool {
+ self.entry_view_state.update(cx, |state, _| match card_id {
+ SubagentCardId::ToolCall(id) => state.toggle_tool_call_expansion(id),
+ SubagentCardId::SessionMessage(id) => state.toggle_session_message_card_expansion(id),
+ });
+ self.is_subagent_card_expanded(card_id, cx)
+ }
+
fn render_subagent_expanded_content(
&self,
thread_view: &Entity<ThreadView>,
- card_id: &acp_v2::ToolCallId,
+ card_id: &SubagentCardId,
state: &SubagentCardState,
window: &Window,
cx: &Context<Self>,
@@ -12332,7 +12421,7 @@ impl ThreadView {
// Include the card id so the same subagent session
// rendered in multiple parent cards gets distinct element
// ids for its inlined entries (avoids duplicate a11y ids).
- .id(format!("subagent-entries-{}-{}", session_id, card_id.0))
+ .id(format!("subagent-entries-{}-{}", session_id, card_id))
.track_scroll(&scroll_handle)
.children(rendered_entries),
)
diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs
index 143ee2bbc0d..0009183b74b 100644
--- a/crates/agent_ui/src/entry_view_state.rs
+++ b/crates/agent_ui/src/entry_view_state.rs
@@ -65,6 +65,8 @@ pub struct EntryViewState {
user_toggled_thinking_blocks: HashSet<(usize, usize)>,
expanded_compactions: HashSet<usize>,
expanded_tool_calls: HashSet<acp_v2::ToolCallId>,
+ /// Subagent cards shown for an ACP parent's outgoing session messages.
+ expanded_session_message_cards: HashSet<acp_v2::MessageId>,
}
impl EntryViewState {
@@ -87,6 +89,7 @@ impl EntryViewState {
user_toggled_thinking_blocks: HashSet::default(),
expanded_compactions: HashSet::default(),
expanded_tool_calls: HashSet::default(),
+ expanded_session_message_cards: HashSet::default(),
}
}
@@ -112,6 +115,17 @@ impl EntryViewState {
}
}
+ pub(crate) fn is_session_message_card_expanded(&self, message_id: &acp_v2::MessageId) -> bool {
+ self.expanded_session_message_cards.contains(message_id)
+ }
+
+ pub(crate) fn toggle_session_message_card_expansion(&mut self, message_id: &acp_v2::MessageId) {
+ if !self.expanded_session_message_cards.remove(message_id) {
+ self.expanded_session_message_cards
+ .insert(message_id.clone());
+ }
+ }
+
pub(crate) fn is_compaction_expanded(&self, entry_ix: usize) -> bool {
self.expanded_compactions.contains(&entry_ix)
}