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: Render subagent cards from a source-independent state (#65923)

Ben Brandta484d108da91
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 907f5f71470..396f5694530 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -112,6 +112,7 @@ pub(crate) const DRAFT_PROMPT_PERSIST_DEBOUNCE: Duration = Duration::from_millis
pub(crate) mod elicitation;
mod message_queue;
+mod subagent_card;
mod thread_search_bar;
mod thread_view;
pub use message_queue::*;
@@ -6771,6 +6772,109 @@ pub(crate) mod tests {
});
}
+ #[gpui::test]
+ async fn test_subagent_card_state_follows_the_spawn_tool_call(cx: &mut TestAppContext) {
+ use super::subagent_card::{SubagentCardState, SubagentEntries, SubagentStatus};
+
+ init_test(cx);
+ let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;
+ let thread = cx.update(|cx| {
+ create_test_acp_thread(
+ None,
+ "parent",
+ Rc::new(StubAgentConnection::new()),
+ project,
+ cx,
+ )
+ });
+ 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: 2,
+ message_end_index: Some(5),
+ })
+ .expect("subagent session info should serialize"),
+ )]);
+
+ for (id, label, status, output, expected_status, expected_error) in [
+ (
+ "running",
+ "Explore",
+ acp_v2::ToolCallStatus::InProgress,
+ None,
+ SubagentStatus::Running,
+ None,
+ ),
+ (
+ "completed",
+ "Find the parser",
+ acp_v2::ToolCallStatus::Completed,
+ Some("Found it"),
+ SubagentStatus::Completed,
+ None,
+ ),
+ (
+ "failed",
+ "Fix the build",
+ acp_v2::ToolCallStatus::Failed,
+ Some("Model unavailable"),
+ SubagentStatus::Failed,
+ Some("Model unavailable"),
+ ),
+ (
+ "user-canceled",
+ "Explore",
+ acp_v2::ToolCallStatus::Failed,
+ Some("User canceled"),
+ SubagentStatus::Canceled,
+ None,
+ ),
+ (
+ "canceled",
+ "Explore",
+ acp_v2::ToolCallStatus::Cancelled,
+ None,
+ SubagentStatus::Canceled,
+ None,
+ ),
+ ] {
+ let mut update = acp_v2::ToolCallUpdate::new(id)
+ .title(label)
+ .status(status)
+ .meta(session_info.clone());
+ if let Some(output) = output {
+ update = update.content(vec![output.into()]);
+ }
+ thread
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(update, cx))
+ .expect("spawn tool call should apply");
+
+ let state = thread.read_with(cx, |thread, cx| {
+ let (_, tool_call) = thread
+ .tool_call(&acp_v2::ToolCallId::new(id))
+ .expect("spawn tool call should exist");
+ SubagentCardState::from_tool_call(tool_call, cx)
+ });
+ assert_eq!(state.status, expected_status, "{id}");
+ assert_eq!(state.error.as_deref(), expected_error, "{id}");
+ assert_eq!(
+ state.can_stop,
+ expected_status == SubagentStatus::Running,
+ "{id}"
+ );
+ assert_eq!(state.label.as_deref(), Some(label), "{id}");
+ assert_eq!(
+ state.entries,
+ Some(SubagentEntries {
+ start: 2,
+ end: Some(5),
+ }),
+ "{id}"
+ );
+ }
+ }
+
#[gpui::test]
async fn test_concurrent_subagent_loads_create_one_thread_view(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
new file mode 100644
index 00000000000..6f3cb12c27f
--- /dev/null
+++ b/crates/agent_ui/src/conversation_view/subagent_card.rs
@@ -0,0 +1,193 @@
+use acp_thread::{ToolCall, ToolCallContent, ToolCallStatus};
+use gpui::{App, SharedString};
+use std::ops::Range;
+
+/// Native subagent tool calls report a user cancellation as output with this text.
+const USER_CANCELED_OUTPUT: &str = "User canceled";
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum SubagentStatus {
+ Running,
+ Completed,
+ Failed,
+ Canceled,
+}
+
+impl SubagentStatus {
+ pub(crate) fn from_tool_call(tool_call: &ToolCall, cx: &App) -> Self {
+ match tool_call.status() {
+ ToolCallStatus::Pending
+ | ToolCallStatus::InProgress
+ | ToolCallStatus::WaitingForConfirmation => Self::Running,
+ _ if has_user_canceled_output(tool_call, cx) => Self::Canceled,
+ ToolCallStatus::Canceled => Self::Canceled,
+ ToolCallStatus::Failed | ToolCallStatus::Rejected => Self::Failed,
+ ToolCallStatus::Completed => Self::Completed,
+ }
+ }
+
+ pub(crate) fn is_failed_or_canceled(self) -> bool {
+ matches!(self, Self::Failed | Self::Canceled)
+ }
+}
+
+/// 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.
+ pub label: Option<SharedString>,
+ pub status: SubagentStatus,
+ pub error: Option<SharedString>,
+ pub can_stop: bool,
+ /// The subagent entries this card covers; `None` covers all of them.
+ pub entries: Option<SubagentEntries>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct SubagentEntries {
+ pub start: usize,
+ /// Inclusive; `None` extends through the latest entry.
+ pub end: Option<usize>,
+}
+
+impl SubagentCardState {
+ /// Builds the card for a native `spawn_agent` tool call. Each call covers the
+ /// subagent entries produced for that one message.
+ pub(crate) fn from_tool_call(tool_call: &ToolCall, cx: &App) -> Self {
+ let status = SubagentStatus::from_tool_call(tool_call, cx);
+ let label = tool_call.label.read(cx).source();
+ Self {
+ label: (!label.is_empty()).then(|| label.to_string().into()),
+ status,
+ error: tool_call_error(tool_call, cx),
+ can_stop: status == SubagentStatus::Running,
+ entries: tool_call
+ .subagent_session_info
+ .as_ref()
+ .map(|info| SubagentEntries {
+ start: info.message_start_index,
+ end: info.message_end_index,
+ }),
+ }
+ }
+
+ 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(),
+ })
+ }
+
+ /// The last `max_entries` of the entries this card covers.
+ pub(crate) fn preview_range(&self, total_entries: usize, max_entries: usize) -> Range<usize> {
+ let mut range = match self.entries {
+ Some(entries) => {
+ entries.start
+ ..entries
+ .end
+ .map(|end| (end + 1).min(total_entries))
+ .unwrap_or(total_entries)
+ }
+ None => 0..total_entries,
+ };
+ range.start = range.end.saturating_sub(max_entries).max(range.start);
+ range
+ }
+}
+
+fn has_user_canceled_output(tool_call: &ToolCall, cx: &App) -> bool {
+ tool_call.content().iter().any(|content| match content {
+ ToolCallContent::ContentBlock { block, .. } => {
+ block.text_content(cx) == Some(USER_CANCELED_OUTPUT)
+ }
+ _ => false,
+ })
+}
+
+fn tool_call_error(tool_call: &ToolCall, cx: &App) -> Option<SharedString> {
+ if tool_call.status() != ToolCallStatus::Failed {
+ return None;
+ }
+ tool_call.content().iter().find_map(|content| {
+ let ToolCallContent::ContentBlock { block, .. } = content else {
+ return None;
+ };
+ block
+ .text_content(cx)
+ .filter(|text| !text.is_empty() && *text != USER_CANCELED_OUTPUT)
+ .map(SharedString::from)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn card(
+ label: Option<&str>,
+ status: SubagentStatus,
+ entries: Option<SubagentEntries>,
+ ) -> SubagentCardState {
+ SubagentCardState {
+ label: label.map(|label| label.to_string().into()),
+ status,
+ error: None,
+ can_stop: false,
+ entries,
+ }
+ }
+
+ #[test]
+ fn title_prefers_the_thread_title_then_the_label_then_the_status() {
+ let labeled = card(Some("Explore"), SubagentStatus::Running, None);
+ assert_eq!(
+ labeled.title(Some("Fix the parser".into())).as_ref(),
+ "Fix the parser"
+ );
+ assert_eq!(labeled.title(None).as_ref(), "Explore");
+ for (status, title) in [
+ (SubagentStatus::Running, "Spawning Agent…"),
+ (SubagentStatus::Completed, "Spawning Agent…"),
+ (SubagentStatus::Failed, "Subagent Failed"),
+ (SubagentStatus::Canceled, "Subagent Canceled"),
+ ] {
+ assert_eq!(card(None, status, None).title(None).as_ref(), title);
+ }
+ }
+
+ #[test]
+ fn preview_range_shows_the_last_entries_the_card_covers() {
+ let whole_thread = card(None, SubagentStatus::Running, None);
+ assert_eq!(whole_thread.preview_range(20, 8), 12..20);
+ assert_eq!(whole_thread.preview_range(3, 8), 0..3);
+
+ let open_ended = card(
+ None,
+ SubagentStatus::Running,
+ Some(SubagentEntries {
+ start: 4,
+ end: None,
+ }),
+ );
+ assert_eq!(open_ended.preview_range(6, 8), 4..6);
+ assert_eq!(open_ended.preview_range(20, 8), 12..20);
+
+ let finished = card(
+ None,
+ SubagentStatus::Completed,
+ Some(SubagentEntries {
+ start: 4,
+ end: Some(6),
+ }),
+ );
+ assert_eq!(finished.preview_range(20, 8), 4..7);
+ assert_eq!(
+ finished.preview_range(5, 8),
+ 4..5,
+ "an end past the thread is clamped"
+ );
+ }
+}
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 44f1c201fb0..0d7960f9a69 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -55,6 +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::*;
const DATA_RETENTION_LEARN_MORE_URL: &str = "https://support.claude.com/en/articles/15425996-data-retention-practices-for-mythos-class-models";
@@ -5121,13 +5122,8 @@ impl ThreadView {
.thread
.read(cx)
.tool_call_for_subagent(&my_session_id)
- .is_some_and(|tc| {
- matches!(
- tc.status(),
- ToolCallStatus::Canceled
- | ToolCallStatus::Failed
- | ToolCallStatus::Rejected
- )
+ .is_some_and(|tool_call| {
+ SubagentStatus::from_tool_call(tool_call, cx).is_failed_or_canceled()
})
})
}
@@ -11686,8 +11682,9 @@ impl ThreadView {
let content = self.render_subagent_card(
active_session_id,
entry_ix,
+ &tool_call.id,
+ &SubagentCardState::from_tool_call(tool_call, cx),
subagent_thread_view,
- tool_call,
focus_handle,
window,
cx,
@@ -11696,12 +11693,15 @@ 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,
+ state: &SubagentCardState,
thread_view: Option<&Entity<ThreadView>>,
- tool_call: &ToolCall,
focus_handle: &FocusHandle,
window: &Window,
cx: &Context<Self>,
@@ -11728,29 +11728,12 @@ impl ThreadView {
let is_expanded = self
.entry_view_state
.read(cx)
- .is_tool_call_expanded(&tool_call.id);
+ .is_tool_call_expanded(card_id);
let files_changed = changed_buffers.len();
let diff_stats = DiffStats::all_files(changed_buffers, cx);
- let is_running = matches!(
- tool_call.status(),
- ToolCallStatus::Pending
- | ToolCallStatus::InProgress
- | ToolCallStatus::WaitingForConfirmation
- );
-
- let is_failed = matches!(
- tool_call.status(),
- ToolCallStatus::Failed | ToolCallStatus::Rejected
- );
-
- let is_cancelled = matches!(tool_call.status(), ToolCallStatus::Canceled)
- || tool_call.content().iter().any(|c| match c {
- ToolCallContent::ContentBlock { block, .. } => {
- block.text_content(cx) == Some("User canceled")
- }
- _ => false,
- });
+ let is_running = state.status == SubagentStatus::Running;
+ let is_failed_or_canceled = state.status.is_failed_or_canceled();
let model_name = thread_view
.and_then(|view| view.read(cx).as_native_thread(cx))
@@ -11763,60 +11746,44 @@ impl ThreadView {
.as_ref()
.and_then(|t| t.read(cx).title())
.filter(|t| !t.is_empty());
- let tool_call_label = tool_call.label.read(cx).source().to_string();
- let has_tool_call_label = !tool_call_label.is_empty();
-
- let has_title = thread_title.is_some() || has_tool_call_label;
- let has_no_title_or_canceled = !has_title || is_failed || is_cancelled;
-
- let title: SharedString = if let Some(thread_title) = thread_title {
- thread_title
- } else if !tool_call_label.is_empty() {
- tool_call_label.into()
- } else if is_cancelled {
- "Subagent Canceled".into()
- } else if is_failed {
- "Subagent Failed".into()
- } else {
- "Spawning Agent…".into()
- };
+
+ let has_title = thread_title.is_some() || state.label.is_some();
+ let has_no_title_or_canceled = !has_title || is_failed_or_canceled;
+
+ let title = state.title(thread_title);
let card_header_id = format!("subagent-header-{}", entry_ix);
let status_icon = format!("status-icon-{}", entry_ix);
let diff_stat_id = format!("subagent-diff-{}", entry_ix);
- let icon = h_flex().w_4().justify_center().child(if is_running {
- SpinnerLabel::new()
- .size(LabelSize::Small)
- .into_any_element()
- } else if is_cancelled {
- div()
- .id(status_icon)
- .child(
- Icon::new(IconName::Circle)
- .size(IconSize::Small)
- .color(Color::Custom(
- cx.theme().colors().icon_disabled.opacity(0.5),
- )),
- )
- .tooltip(Tooltip::text("Subagent Cancelled"))
- .into_any_element()
- } else if is_failed {
- div()
- .id(status_icon)
- .child(
- Icon::new(IconName::Close)
- .size(IconSize::Small)
- .color(Color::Error),
- )
- .tooltip(Tooltip::text("Subagent Failed"))
- .into_any_element()
- } else {
- Icon::new(IconName::Check)
- .size(IconSize::Small)
- .color(Color::Success)
- .into_any_element()
- });
+ let icon =
+ h_flex().w_4().justify_center().child(match state.status {
+ SubagentStatus::Running => SpinnerLabel::new()
+ .size(LabelSize::Small)
+ .into_any_element(),
+ SubagentStatus::Canceled => {
+ div()
+ .id(status_icon)
+ .child(Icon::new(IconName::Circle).size(IconSize::Small).color(
+ Color::Custom(cx.theme().colors().icon_disabled.opacity(0.5)),
+ ))
+ .tooltip(Tooltip::text("Subagent Cancelled"))
+ .into_any_element()
+ }
+ SubagentStatus::Failed => div()
+ .id(status_icon)
+ .child(
+ Icon::new(IconName::Close)
+ .size(IconSize::Small)
+ .color(Color::Error),
+ )
+ .tooltip(Tooltip::text("Subagent Failed"))
+ .into_any_element(),
+ SubagentStatus::Completed => Icon::new(IconName::Check)
+ .size(IconSize::Small)
+ .color(Color::Success)
+ .into_any_element(),
+ });
let has_expandable_content = thread
.as_ref()
@@ -11828,7 +11795,7 @@ impl ThreadView {
"Click to Preview"
};
- let error_message = self.subagent_error_message(&tool_call.status(), tool_call, cx);
+ let error_message = state.error.clone();
v_flex()
.w_full()
@@ -11946,12 +11913,12 @@ impl ThreadView {
),
)
.on_click(cx.listener({
- let tool_call_id = tool_call.id.clone();
+ 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(&tool_call_id);
- state.is_tool_call_expanded(&tool_call_id)
+ state.toggle_tool_call_expansion(&card_id);
+ state.is_tool_call_expanded(&card_id)
});
this.refresh_thread_search(window, cx);
telemetry::event!("Subagent Toggled", expanded);
@@ -11960,7 +11927,7 @@ impl ThreadView {
}))
}),
)
- .when(is_running && subagent_session_id.is_some(), |buttons| {
+ .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)
@@ -11998,7 +11965,7 @@ impl ThreadView {
.w_full()
.justify_center()
.border_t_1()
- .when(is_failed, |this| this.border_dashed())
+ .when(is_failed_or_canceled, |this| this.border_dashed())
.border_color(self.tool_card_border_color(cx))
.cursor_pointer()
.hover(|s| s.bg(cx.theme().colors().element_hover))
@@ -12039,7 +12006,8 @@ impl ThreadView {
this.when(is_expanded, |this| {
this.child(self.render_subagent_expanded_content(
thread_view,
- tool_call,
+ card_id,
+ state,
window,
cx,
))
@@ -12061,7 +12029,8 @@ impl ThreadView {
fn render_subagent_expanded_content(
&self,
thread_view: &Entity<ThreadView>,
- tool_call: &ToolCall,
+ card_id: &acp_v2::ToolCallId,
+ state: &SubagentCardState,
window: &Window,
cx: &Context<Self>,
) -> impl IntoElement {
@@ -12070,11 +12039,6 @@ impl ThreadView {
let subagent_view = thread_view.read(cx);
let session_id = subagent_view.thread.read(cx).session_id().clone();
- let is_canceled_or_failed = matches!(
- tool_call.status(),
- ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
- );
-
let editor_bg = cx.theme().colors().editor_background;
let overlay = {
div()
@@ -12091,19 +12055,7 @@ impl ThreadView {
let entries = subagent_view.thread.read(cx).entries();
let total_entries = entries.len();
- let mut entry_range = if let Some(info) = tool_call.subagent_session_info.as_ref() {
- info.message_start_index
- ..info
- .message_end_index
- .map(|i| (i + 1).min(total_entries))
- .unwrap_or(total_entries)
- } else {
- 0..total_entries
- };
- entry_range.start = entry_range
- .end
- .saturating_sub(MAX_PREVIEW_ENTRIES)
- .max(entry_range.start);
+ let entry_range = state.preview_range(total_entries, MAX_PREVIEW_ENTRIES);
let start_ix = entry_range.start;
let scroll_handle = self
@@ -12129,20 +12081,19 @@ impl ThreadView {
v_flex()
.w_full()
.border_t_1()
- .when(is_canceled_or_failed, |this| this.border_dashed())
+ .when(state.status.is_failed_or_canceled(), |this| {
+ this.border_dashed()
+ })
.border_color(self.tool_card_border_color(cx))
.overflow_hidden()
.child(
div()
.pb_1()
.min_h_0()
- // Include the tool call id so the same subagent session
+ // 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, tool_call.id.0
- ))
+ .id(format!("subagent-entries-{}-{}", session_id, card_id.0))
.track_scroll(&scroll_handle)
.children(rendered_entries),
)
@@ -12151,31 +12102,6 @@ impl ThreadView {
.into_any_element()
}
- fn subagent_error_message(
- &self,
- status: &ToolCallStatus,
- tool_call: &ToolCall,
- cx: &App,
- ) -> Option<SharedString> {
- if matches!(status, ToolCallStatus::Failed) {
- tool_call.content().iter().find_map(|content| {
- if let ToolCallContent::ContentBlock { block, .. } = content {
- if let Some(source) = block.text_content(cx).filter(|source| !source.is_empty())
- {
- if source == "User canceled" {
- return None;
- } else {
- return Some(SharedString::from(source));
- }
- }
- }
- None
- })
- } else {
- None
- }
- }
-
fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
cx.theme()
.colors()