Displays the work of a subagent the agent hands a task to. The subagent's commands stream in under it, followed by the report it sends back.
Loading GPUI…
use std::time::Duration;
use gpui::{div, prelude::*, px, relative, Context, Task, Window};
use crate::icons::{CIRCLE_CHECK, LOADER_CIRCLE};
use crate::theme::ActiveTheme;
use crate::ui::code_block::{CodeBlock, CodeBlockSize};
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::message::{Message, MessageAlign};
use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};
/// The subagent starts after 600ms and runs a command every second; its report lands 400ms
/// before the answer, which streams a word every 20ms.
const START: Duration = Duration::from_millis(600);
const STEP: Duration = Duration::from_millis(1000);
const REPORT: Duration = Duration::from_millis(400);
const CHUNK: Duration = Duration::from_millis(20);
const QUESTION: &str = "Why does image optimization rerun on every deploy?";
const SUMMARY: &str = "The cache is keyed on the commit SHA, so every deploy misses it and optimizes all 1,240 images again.";
const ANSWER: &str = "Image optimization reruns because its cache is keyed on the commit SHA, which changes on every deploy. Key the cache on a hash of public/images instead, and unchanged images will be skipped.";
const STEPS: [(&str, &str); 3] = [
("grep -rn cacheKey scripts", "scripts/optimize-images.ts:14: const cacheKey = process.env.COMMIT_SHA"),
(
"sed -n 13,15p scripts/optimize-images.ts",
"const cacheDir = \".next/cache/images\"\nconst cacheKey = process.env.COMMIT_SHA\nconst cached = await restoreCache(cacheDir, cacheKey)",
),
("ls public/images | wc -l", "1240"),
];
pub struct SubagentPattern {
/// `None` until the subagent reports progress; then how many commands have finished. The
/// next one is running.
done: Option<usize>,
/// Whether the subagent has sent its report, which finishes it.
reported: bool,
/// The subagent row opens when its first progress arrives; each command row starts closed.
open: bool,
step_open: [bool; 3],
/// Words of the answer shown so far.
words: usize,
busy: bool,
stream: Option<Task<()>>,
}
impl Default for SubagentPattern {
/// Starts on the finished transcript with the subagent open.
fn default() -> Self {
Self {
done: Some(STEPS.len()),
reported: true,
open: true,
step_open: [false; 3],
words: ANSWER.split_inclusive(' ').count(),
busy: false,
stream: None,
}
}
}
impl SubagentPattern {
fn replay(&mut self, cx: &mut Context<Self>) {
*self = Self { done: None, reported: false, words: 0, busy: true, ..Self::default() };
self.stream = Some(cx.spawn(async move |this, cx| {
cx.background_executor().timer(START).await;
for done in 0..STEPS.len() {
if this.update(cx, |this, cx| { this.done = Some(done); cx.notify(); }).is_err() {
return;
}
cx.background_executor().timer(STEP).await;
}
let _ = this.update(cx, |this, cx| {
this.done = Some(STEPS.len());
this.reported = true;
cx.notify();
});
cx.background_executor().timer(REPORT).await;
for _ in 0..ANSWER.split_inclusive(' ').count() {
cx.background_executor().timer(CHUNK).await;
if this.update(cx, |this, cx| { this.words += 1; cx.notify(); }).is_err() {
return;
}
}
let _ = this.update(cx, |this, cx| { this.busy = false; cx.notify(); });
}));
cx.notify();
}
}
impl Render for SubagentPattern {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let fg = theme.foreground;
let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
let line = if self.reported {
TraceLine::new("agent", "Ran the research subagent").icon(CIRCLE_CHECK)
} else {
TraceLine::new("agent", "Running the research subagent")
.icon(LOADER_CIRCLE).spin(true)
.status(TraceStatus::Running)
};
// Until the subagent reports progress there is nothing to open, so the row has no chevron.
let row = match self.done {
None => line.into_any_element(),
Some(done) => {
let steps = STEPS.iter().take((done + 1).min(STEPS.len())).enumerate().map(|(ix, (command, stdout))| {
if ix == done {
return TraceLine::new(("step", ix), format!("Running {command}"))
.icon(LOADER_CIRCLE).spin(true)
.status(TraceStatus::Running)
.into_any_element();
}
let line = TraceLine::new(("step", ix), format!("Ran {command}")).icon(CIRCLE_CHECK);
TraceCollapsible::new(("run", ix), self.step_open[ix], line)
.on_open_change(cx.listener(move |this, open: &bool, _, cx| {
this.step_open[ix] = *open;
cx.notify();
}))
.child(
// `max-h-64`, as shadcn's demo sets on the content.
div().max_h(px(256.0)).overflow_hidden().child(
CodeBlock::new(("stdout", ix), *stdout)
.size(CodeBlockSize::Sm)
.wrap(true)
.copy_button(false),
),
)
.into_any_element()
});
TraceCollapsible::new("row", self.open, line)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.child(
div()
.flex()
.flex_col()
.gap_3()
.child(Trace::new().children(steps))
.when(self.reported, |this| this.child(SUMMARY)),
)
.into_any_element()
}
};
div()
.w(px(384.0))
.min_h(px(288.0))
.flex()
.flex_col()
.gap_4()
.py_6()
.text_sm()
.child(
Message::new()
.align(MessageAlign::End)
.child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)),
)
.child(
Message::new().child(
div()
.flex()
.flex_col()
.gap_4()
.w_full()
.child(Trace::new().child(row))
.when(!answer.is_empty(), |this| {
this.child(div().line_height(relative(1.4286)).text_color(fg).child(answer))
}),
),
)
.when(!self.busy, |this| {
this.child(
div().mt_auto().flex().child(
Button::new("replay", "Replay")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Compact)
.rounded_full()
.on_click(cx.listener(|this, _, _, cx| this.replay(cx))),
),
)
})
}
}Installation
Add the components
$ cargo hyuskui add bubble button code-block message trace iconsUses Bubble, Button, Code Block, Message and Trace.
Copy the pattern
Paste the code into
src/ai/subagent.rsand declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.src/ai/subagent.rs use std::time::Duration; use gpui::{div, prelude::*, px, relative, Context, Task, Window}; use crate::icons::{CIRCLE_CHECK, LOADER_CIRCLE}; use crate::theme::ActiveTheme; use crate::ui::code_block::{CodeBlock, CodeBlockSize}; use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant}; use crate::ui::button::{Button, ButtonSize, ButtonVariant}; use crate::ui::message::{Message, MessageAlign}; use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus}; /// The subagent starts after 600ms and runs a command every second; its report lands 400ms /// before the answer, which streams a word every 20ms. const START: Duration = Duration::from_millis(600); const STEP: Duration = Duration::from_millis(1000); const REPORT: Duration = Duration::from_millis(400); const CHUNK: Duration = Duration::from_millis(20); const QUESTION: &str = "Why does image optimization rerun on every deploy?"; const SUMMARY: &str = "The cache is keyed on the commit SHA, so every deploy misses it and optimizes all 1,240 images again."; const ANSWER: &str = "Image optimization reruns because its cache is keyed on the commit SHA, which changes on every deploy. Key the cache on a hash of public/images instead, and unchanged images will be skipped."; const STEPS: [(&str, &str); 3] = [ ("grep -rn cacheKey scripts", "scripts/optimize-images.ts:14: const cacheKey = process.env.COMMIT_SHA"), ( "sed -n 13,15p scripts/optimize-images.ts", "const cacheDir = \".next/cache/images\"\nconst cacheKey = process.env.COMMIT_SHA\nconst cached = await restoreCache(cacheDir, cacheKey)", ), ("ls public/images | wc -l", "1240"), ]; pub struct SubagentPattern { /// `None` until the subagent reports progress; then how many commands have finished. The /// next one is running. done: Option<usize>, /// Whether the subagent has sent its report, which finishes it. reported: bool, /// The subagent row opens when its first progress arrives; each command row starts closed. open: bool, step_open: [bool; 3], /// Words of the answer shown so far. words: usize, busy: bool, stream: Option<Task<()>>, } impl Default for SubagentPattern { /// Starts on the finished transcript with the subagent open. fn default() -> Self { Self { done: Some(STEPS.len()), reported: true, open: true, step_open: [false; 3], words: ANSWER.split_inclusive(' ').count(), busy: false, stream: None, } } } impl SubagentPattern { fn replay(&mut self, cx: &mut Context<Self>) { *self = Self { done: None, reported: false, words: 0, busy: true, ..Self::default() }; self.stream = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(START).await; for done in 0..STEPS.len() { if this.update(cx, |this, cx| { this.done = Some(done); cx.notify(); }).is_err() { return; } cx.background_executor().timer(STEP).await; } let _ = this.update(cx, |this, cx| { this.done = Some(STEPS.len()); this.reported = true; cx.notify(); }); cx.background_executor().timer(REPORT).await; for _ in 0..ANSWER.split_inclusive(' ').count() { cx.background_executor().timer(CHUNK).await; if this.update(cx, |this, cx| { this.words += 1; cx.notify(); }).is_err() { return; } } let _ = this.update(cx, |this, cx| { this.busy = false; cx.notify(); }); })); cx.notify(); } } impl Render for SubagentPattern { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let theme = cx.theme(); let fg = theme.foreground; let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect(); let line = if self.reported { TraceLine::new("agent", "Ran the research subagent").icon(CIRCLE_CHECK) } else { TraceLine::new("agent", "Running the research subagent") .icon(LOADER_CIRCLE).spin(true) .status(TraceStatus::Running) }; // Until the subagent reports progress there is nothing to open, so the row has no chevron. let row = match self.done { None => line.into_any_element(), Some(done) => { let steps = STEPS.iter().take((done + 1).min(STEPS.len())).enumerate().map(|(ix, (command, stdout))| { if ix == done { return TraceLine::new(("step", ix), format!("Running {command}")) .icon(LOADER_CIRCLE).spin(true) .status(TraceStatus::Running) .into_any_element(); } let line = TraceLine::new(("step", ix), format!("Ran {command}")).icon(CIRCLE_CHECK); TraceCollapsible::new(("run", ix), self.step_open[ix], line) .on_open_change(cx.listener(move |this, open: &bool, _, cx| { this.step_open[ix] = *open; cx.notify(); })) .child( // `max-h-64`, as shadcn's demo sets on the content. div().max_h(px(256.0)).overflow_hidden().child( CodeBlock::new(("stdout", ix), *stdout) .size(CodeBlockSize::Sm) .wrap(true) .copy_button(false), ), ) .into_any_element() }); TraceCollapsible::new("row", self.open, line) .on_open_change(cx.listener(|this, open: &bool, _, cx| { this.open = *open; cx.notify(); })) .child( div() .flex() .flex_col() .gap_3() .child(Trace::new().children(steps)) .when(self.reported, |this| this.child(SUMMARY)), ) .into_any_element() } }; div() .w(px(384.0)) .min_h(px(288.0)) .flex() .flex_col() .gap_4() .py_6() .text_sm() .child( Message::new() .align(MessageAlign::End) .child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)), ) .child( Message::new().child( div() .flex() .flex_col() .gap_4() .w_full() .child(Trace::new().child(row)) .when(!answer.is_empty(), |this| { this.child(div().line_height(relative(1.4286)).text_color(fg).child(answer)) }), ), ) .when(!self.busy, |this| { this.child( div().mt_auto().flex().child( Button::new("replay", "Replay") .variant(ButtonVariant::Outline) .size(ButtonSize::Compact) .rounded_full() .on_click(cx.listener(|this, _, _, cx| this.replay(cx))), ), ) }) } }