Displays the steps an agent took to reach an answer. The steps stay open while the agent researches, then fold behind a one-line summary when the answer starts.
Loading GPUI…
use std::time::Duration;
use gpui::{div, prelude::*, px, relative, Context, Task, Window};
use crate::icons::{ARROW_UP_RIGHT, CIRCLE_CHECK, GLOBE, LOADER_CIRCLE};
use crate::theme::ActiveTheme;
use crate::ui::code_block::{CodeBlock, CodeBlockSize};
use crate::ui::badge::{Badge, BadgeVariant};
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};
const MONO: &str = "Geist Mono";
/// Each tool call takes 900ms; the answer then streams a word every 20ms.
const STEP: Duration = Duration::from_millis(900);
const CHUNK: Duration = Duration::from_millis(20);
const QUESTION: &str = "Why is the checkout deploy so slow?";
const ANSWER: &str = "Image optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead.";
const BUILD_LOG: &str = "install 41s\ncompile 38s\nimages 3m 52s";
const RESULTS: [(&str, &str); 2] = [
("Image component | nextjs.org", "https://nextjs.org/docs/app/api-reference/components/image"),
("Build cache | vercel.com", "https://vercel.com/docs/deployments/troubleshoot-a-build"),
];
const FILES: [&str; 2] = ["next.config.ts", "scripts/optimize-images.ts"];
/// The three tool calls, as (running title, finished title).
const STEPS: [(&str, &str); 3] = [
("Reading the build log for dpl_8Kx2", "Read the build log for dpl_8Kx2"),
("Searching the web for next.js image cache key", "Searched the web for next.js image cache key"),
("Searching the code for cacheKey", "Searched the code for cacheKey"),
];
/// A tool call the agent has made.
#[derive(Clone, Copy)]
struct Step {
finished: bool,
/// Whether the row is open. The build log opens when its output arrives; the others stay
/// closed until the reader opens them.
open: bool,
}
pub struct ChainOfThoughtPattern {
steps: Vec<Step>,
/// Words of the answer shown so far.
words: usize,
/// The reader's choice for the summary row. `None` keeps it open while the agent researches
/// and closes it once the answer starts.
open: Option<bool>,
busy: bool,
stream: Option<Task<()>>,
}
impl Default for ChainOfThoughtPattern {
/// Starts on the finished transcript, folded behind its summary.
fn default() -> Self {
Self {
steps: (0..STEPS.len()).map(|ix| Step { finished: true, open: ix == 0 }).collect(),
words: ANSWER.split_inclusive(' ').count(),
open: None,
busy: false,
stream: None,
}
}
}
impl ChainOfThoughtPattern {
fn replay(&mut self, cx: &mut Context<Self>) {
self.steps.clear();
self.words = 0;
self.open = None;
self.busy = true;
self.stream = Some(cx.spawn(async move |this, cx| {
for ix in 0..STEPS.len() {
let started = this.update(cx, |this, cx| {
this.steps.push(Step { finished: false, open: false });
cx.notify();
});
if started.is_err() {
return;
}
cx.background_executor().timer(STEP).await;
let _ = this.update(cx, |this, cx| {
this.steps[ix] = Step { finished: true, open: ix == 0 };
cx.notify();
});
}
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 ChainOfThoughtPattern {
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 researching = self.busy && answer.is_empty();
let rows = self.steps.iter().enumerate().map(|(ix, step)| {
let (doing, done) = STEPS[ix];
if !step.finished {
// Nothing to show until the output arrives, so a running step has no chevron.
return TraceLine::new(("step", ix), doing)
.icon(LOADER_CIRCLE).spin(true)
.status(TraceStatus::Running)
.into_any_element();
}
let output = match ix {
0 => // `max-h-64`, as shadcn's demo sets on the content.
div().max_h(px(256.0)).overflow_hidden().child(
CodeBlock::new("build-log", BUILD_LOG)
.size(CodeBlockSize::Sm)
.wrap(true)
.copy_button(false),
)
.into_any_element(),
1 => Trace::new()
.children(RESULTS.iter().enumerate().map(|(result, (title, url))| {
TraceLine::new(("result", result), *title)
.icon(GLOBE)
.indicator(ARROW_UP_RIGHT)
.on_click(move |_, _, cx| cx.open_url(url))
}))
.into_any_element(),
_ => div()
.flex()
.flex_wrap()
.gap_1p5()
.font_family(MONO)
.children(FILES.iter().map(|file| Badge::new(*file).variant(BadgeVariant::Secondary)))
.into_any_element(),
};
TraceCollapsible::new(("row", ix), step.open, TraceLine::new(("step", ix), done).icon(CIRCLE_CHECK))
.on_open_change(cx.listener(move |this, open: &bool, _, cx| {
if let Some(step) = this.steps.get_mut(ix) {
step.open = *open;
}
cx.notify();
}))
.child(output)
.into_any_element()
});
let summary = if researching {
TraceLine::new("summary", "Researching").icon(LOADER_CIRCLE).spin(true).status(TraceStatus::Running)
} else {
TraceLine::new("summary", format!("Researched in {} steps", self.steps.len())).icon(CIRCLE_CHECK)
};
let chain = TraceCollapsible::new("chain", self.open.unwrap_or(researching), summary)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = Some(*open);
cx.notify();
}))
.child(Trace::new().children(rows));
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)),
)
.when(!self.steps.is_empty(), |this| {
this.child(
Message::new().child(
div()
.flex()
.flex_col()
.gap_4()
.w_full()
.child(Trace::new().child(chain))
.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 badge bubble button code-block message trace iconsCopy the pattern
Paste the code into
src/ai/chain_of_thought.rsand declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.src/ai/chain_of_thought.rs use std::time::Duration; use gpui::{div, prelude::*, px, relative, Context, Task, Window}; use crate::icons::{ARROW_UP_RIGHT, CIRCLE_CHECK, GLOBE, LOADER_CIRCLE}; use crate::theme::ActiveTheme; use crate::ui::code_block::{CodeBlock, CodeBlockSize}; use crate::ui::badge::{Badge, BadgeVariant}; 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}; const MONO: &str = "Geist Mono"; /// Each tool call takes 900ms; the answer then streams a word every 20ms. const STEP: Duration = Duration::from_millis(900); const CHUNK: Duration = Duration::from_millis(20); const QUESTION: &str = "Why is the checkout deploy so slow?"; const ANSWER: &str = "Image optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead."; const BUILD_LOG: &str = "install 41s\ncompile 38s\nimages 3m 52s"; const RESULTS: [(&str, &str); 2] = [ ("Image component | nextjs.org", "https://nextjs.org/docs/app/api-reference/components/image"), ("Build cache | vercel.com", "https://vercel.com/docs/deployments/troubleshoot-a-build"), ]; const FILES: [&str; 2] = ["next.config.ts", "scripts/optimize-images.ts"]; /// The three tool calls, as (running title, finished title). const STEPS: [(&str, &str); 3] = [ ("Reading the build log for dpl_8Kx2", "Read the build log for dpl_8Kx2"), ("Searching the web for next.js image cache key", "Searched the web for next.js image cache key"), ("Searching the code for cacheKey", "Searched the code for cacheKey"), ]; /// A tool call the agent has made. #[derive(Clone, Copy)] struct Step { finished: bool, /// Whether the row is open. The build log opens when its output arrives; the others stay /// closed until the reader opens them. open: bool, } pub struct ChainOfThoughtPattern { steps: Vec<Step>, /// Words of the answer shown so far. words: usize, /// The reader's choice for the summary row. `None` keeps it open while the agent researches /// and closes it once the answer starts. open: Option<bool>, busy: bool, stream: Option<Task<()>>, } impl Default for ChainOfThoughtPattern { /// Starts on the finished transcript, folded behind its summary. fn default() -> Self { Self { steps: (0..STEPS.len()).map(|ix| Step { finished: true, open: ix == 0 }).collect(), words: ANSWER.split_inclusive(' ').count(), open: None, busy: false, stream: None, } } } impl ChainOfThoughtPattern { fn replay(&mut self, cx: &mut Context<Self>) { self.steps.clear(); self.words = 0; self.open = None; self.busy = true; self.stream = Some(cx.spawn(async move |this, cx| { for ix in 0..STEPS.len() { let started = this.update(cx, |this, cx| { this.steps.push(Step { finished: false, open: false }); cx.notify(); }); if started.is_err() { return; } cx.background_executor().timer(STEP).await; let _ = this.update(cx, |this, cx| { this.steps[ix] = Step { finished: true, open: ix == 0 }; cx.notify(); }); } 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 ChainOfThoughtPattern { 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 researching = self.busy && answer.is_empty(); let rows = self.steps.iter().enumerate().map(|(ix, step)| { let (doing, done) = STEPS[ix]; if !step.finished { // Nothing to show until the output arrives, so a running step has no chevron. return TraceLine::new(("step", ix), doing) .icon(LOADER_CIRCLE).spin(true) .status(TraceStatus::Running) .into_any_element(); } let output = match ix { 0 => // `max-h-64`, as shadcn's demo sets on the content. div().max_h(px(256.0)).overflow_hidden().child( CodeBlock::new("build-log", BUILD_LOG) .size(CodeBlockSize::Sm) .wrap(true) .copy_button(false), ) .into_any_element(), 1 => Trace::new() .children(RESULTS.iter().enumerate().map(|(result, (title, url))| { TraceLine::new(("result", result), *title) .icon(GLOBE) .indicator(ARROW_UP_RIGHT) .on_click(move |_, _, cx| cx.open_url(url)) })) .into_any_element(), _ => div() .flex() .flex_wrap() .gap_1p5() .font_family(MONO) .children(FILES.iter().map(|file| Badge::new(*file).variant(BadgeVariant::Secondary))) .into_any_element(), }; TraceCollapsible::new(("row", ix), step.open, TraceLine::new(("step", ix), done).icon(CIRCLE_CHECK)) .on_open_change(cx.listener(move |this, open: &bool, _, cx| { if let Some(step) = this.steps.get_mut(ix) { step.open = *open; } cx.notify(); })) .child(output) .into_any_element() }); let summary = if researching { TraceLine::new("summary", "Researching").icon(LOADER_CIRCLE).spin(true).status(TraceStatus::Running) } else { TraceLine::new("summary", format!("Researched in {} steps", self.steps.len())).icon(CIRCLE_CHECK) }; let chain = TraceCollapsible::new("chain", self.open.unwrap_or(researching), summary) .on_open_change(cx.listener(|this, open: &bool, _, cx| { this.open = Some(*open); cx.notify(); })) .child(Trace::new().children(rows)); 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)), ) .when(!self.steps.is_empty(), |this| { this.child( Message::new().child( div() .flex() .flex_col() .gap_4() .w_full() .child(Trace::new().child(chain)) .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))), ), ) }) } }