A list of steps such as an agent's searches, tool calls and edits, with status and expandable detail.
use std::time::Duration;
use gpui::{div, prelude::*, px, Context, Task, Window};
use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};
use crate::icons::{ARROW_UP_RIGHT, FILE, GLOBE, PENCIL, SEARCH, TERMINAL};
/// How long each simulated step runs.
const STEP: Duration = Duration::from_millis(1100);
const MONO: &str = "Geist Mono";
struct Step {
icon: &'static [u8],
title: &'static str,
/// Shown while the step runs, when the outcome is part of the finished title.
running_title: Option<&'static str>,
description: Option<&'static str>,
output: Option<&'static str>,
failed: bool,
link: bool,
}
const STEPS: [Step; 7] = [
Step {
icon: SEARCH,
title: "Searched for minimumReleaseAge",
running_title: None,
description: Some("3 results"),
output: None,
failed: false,
link: false,
},
Step {
icon: GLOBE,
title: "Read the pnpm settings docs",
running_title: None,
description: None,
output: None,
failed: false,
link: true,
},
Step {
icon: FILE,
title: "Read pnpm-workspace.yaml",
running_title: None,
description: Some("42 lines"),
output: None,
failed: false,
link: false,
},
Step {
icon: PENCIL,
title: "Edited pnpm-workspace.yaml",
running_title: None,
description: Some("+2 -1"),
output: None,
failed: false,
link: false,
},
Step {
icon: TERMINAL,
title: "Ran pnpm test, 1 failed",
running_title: Some("Running pnpm test"),
description: Some("4.2s"),
output: Some(
"FAIL registry/resolve.test.ts\nExpected minimumReleaseAge to be 1440, got \"1440\"",
),
failed: true,
link: false,
},
Step {
icon: PENCIL,
title: "Edited pnpm-workspace.yaml",
running_title: None,
description: Some("+1 -1"),
output: None,
failed: false,
link: false,
},
Step {
icon: TERMINAL,
title: "Ran pnpm test",
running_title: None,
description: Some("3.9s"),
output: Some("Test Files 12 passed (12)\n Tests 48 passed (48)"),
failed: false,
link: false,
},
];
/// Plays an agent's run back one step at a time, the way a streamed trace arrives.
#[derive(Default)]
pub struct TraceDemo {
/// Steps before this index are finished; this one is running.
progress: usize,
/// What the reader chose for each expandable row; `None` follows the step, open while
/// it runs.
open: [Option<bool>; STEPS.len()],
ticker: Option<Task<()>>,
}
impl Render for TraceDemo {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if self.ticker.is_none() {
self.ticker = Some(cx.spawn(async move |this, cx| loop {
cx.background_executor().timer(STEP).await;
let finished = this
.update(cx, |this, cx| {
this.progress += 1;
cx.notify();
this.progress >= STEPS.len()
})
.unwrap_or(true);
if finished {
break;
}
}));
}
let rows = STEPS.iter().enumerate().map(|(ix, step)| {
let status = if ix < self.progress {
if step.failed {
TraceStatus::Error
} else {
TraceStatus::Done
}
} else if ix == self.progress {
TraceStatus::Running
} else {
TraceStatus::Pending
};
let title = match (status, step.running_title) {
(TraceStatus::Running | TraceStatus::Pending, Some(running)) => running,
_ => step.title,
};
let line = TraceLine::new(("line", ix), title)
.icon(step.icon)
.status(status)
.when_some(
step.description.filter(|_| status != TraceStatus::Pending),
|this, description| this.description(description),
);
match step.output {
Some(output) => {
let open = self.open[ix].unwrap_or(status == TraceStatus::Running);
TraceCollapsible::new(("step", ix), open, line)
.on_open_change(cx.listener(move |this, open: &bool, _, cx| {
this.open[ix] = Some(*open);
cx.notify();
}))
.child(
div()
.font_family(MONO)
.text_xs()
.children(output.lines().map(|line| div().child(line))),
)
.into_any_element()
}
None if step.link => line
.indicator(ARROW_UP_RIGHT)
.on_click(|_, _, _| {})
.into_any_element(),
None => line.into_any_element(),
}
});
div()
.w(px(440.0))
.h(px(300.0))
.child(Trace::new().children(rows))
}
}Installation
Copies src/ui/trace.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/trace.rs.src/ui/trace.rs use std::{ f32::consts::{FRAC_PI_2, TAU}, ops::Range, time::Duration, }; use gpui::{ canvas, div, prelude::*, px, radians, relative, svg, Animation, AnimationExt, AnyElement, App, ClickEvent, ElementId, HighlightStyle, Pixels, SharedString, StyledText, TextAlign, Transformation, Window, }; use crate::theme::ActiveTheme; use crate::ui::collapsible::Collapsible; use crate::icons::CHEVRON_RIGHT; /// One shimmer sweep across a running title, like shadcn's `shimmer` utility (2s, linear). const SHIMMER: Duration = Duration::from_millis(2000); /// The shimmer band fades the title to this share of its alpha at its center. const SHIMMER_FLOOR: f32 = 0.2; /// One turn of a spinning icon, like Tailwind's `animate-spin`. const SPIN: Duration = Duration::from_secs(1); /// The title's font size (`text_sm`), used to measure where its glyphs fall. const TITLE_SIZE: Pixels = px(14.0); /// Hover group shared by a line and the chevron of the row that toggles it. const ROW_GROUP: &str = "trace-row"; /// A step's progress. A line without a status is done. #[derive(Clone, Copy, Default, PartialEq)] pub enum TraceStatus { #[default] Done, /// The title shimmers. Running, /// Failed work, in the destructive color. Say so in the title too. Error, /// Not started yet: dimmed. Pending, } type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; type OpenChangeHandler = Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// A list of steps, such as an agent's searches, tool calls and edits. #[derive(IntoElement, Default)] pub struct Trace { children: Vec<AnyElement>, } impl Trace { pub fn new() -> Self { Self::default() } } impl ParentElement for Trace { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for Trace { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { div() .flex() .flex_col() .items_start() .gap_2() .w_full() .min_w_0() .children(self.children) } } /// One step: an icon naming the action, a one-line title and an optional description such /// as a diff stat or a duration. #[derive(IntoElement)] pub struct TraceLine { id: ElementId, icon: Option<&'static [u8]>, title: SharedString, description: Option<SharedString>, indicator: Option<&'static [u8]>, status: TraceStatus, spin: bool, on_click: Option<ClickHandler>, /// Set when the line is the trigger of a `TraceCollapsible`, which owns the click. in_trigger: bool, } impl TraceLine { pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self { Self { id: id.into(), icon: None, title: title.into(), description: None, indicator: None, status: TraceStatus::default(), spin: false, on_click: None, in_trigger: false, } } /// A 16px SVG icon before the title, tinted with the line's color. pub fn icon(mut self, svg: &'static [u8]) -> Self { self.icon = Some(svg); self } /// Secondary text after the title. Unlike the title it never truncates. pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } /// A 16px SVG icon right after the title, e.g. an arrow-up-right on an external link. pub fn indicator(mut self, svg: &'static [u8]) -> Self { self.indicator = Some(svg); self } pub fn status(mut self, status: TraceStatus) -> Self { self.status = status; self } /// Spins the leading icon, one turn a second, e.g. a loader on a running step. pub fn spin(mut self, spin: bool) -> Self { self.spin = spin; self } /// Makes the line a link or the trigger of an overlay: pointer cursor, brighter on hover. pub fn on_click( mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self { self.on_click = Some(Box::new(handler)); self } } impl RenderOnce for TraceLine { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let error = self.status == TraceStatus::Error; let color = if error { theme.destructive } else { theme.muted_foreground }; let fg = theme.foreground; let interactive = self.on_click.is_some() || self.in_trigger; // Errors keep their color on hover; everything else brightens to the foreground. let brighten = interactive && !error; let icon = move |data: &'static [u8]| { svg() .data(data) .flex_none() .size(px(16.0)) .text_color(color) .when(brighten, |this| { this.group_hover(ROW_GROUP, move |style| style.text_color(fg)) }) }; // A title is one line, and both paths below shape it with `shape_line`, which asserts // there is no newline. let title_text: SharedString = if self.title.contains(['\n', '\r']) { self.title.replace(['\n', '\r'], " ").into() } else { self.title }; let title = if self.status == TraceStatus::Running { shimmer(div().id("title").min_w_0().truncate(), title_text, window) } else { ellipsized(title_text) }; let spin = self.spin; let leading = self.icon.map(|data| { if spin { icon(data) .with_animation("spin", Animation::new(SPIN).repeat(), |this, turn| { this.with_transformation(Transformation::rotate(radians(turn * TAU))) }) .into_any_element() } else { icon(data).into_any_element() } }); div() .id(self.id) .flex() .items_center() .gap_2() .max_w_full() .min_w_0() .text_sm() // A row is always 20px tall, even inside collapsible content's looser line height. .line_height(px(20.0)) .text_color(color) .when(self.status == TraceStatus::Pending, |this| { this.opacity(0.6) }) .when(self.on_click.is_some(), |this| { this.group(ROW_GROUP).cursor_pointer() }) .when(brighten, |this| { this.group_hover(ROW_GROUP, move |style| style.text_color(fg)) }) .when_some(self.on_click, |this, handler| { this.on_click(move |event, window, cx| handler(event, window, cx)) }) .children(leading) .child(title) .children(self.indicator.map(|data| icon(data).ml(px(-4.0)))) .children(self.description.map(|description| { div() .flex_none() .text_color(theme.muted_foreground.opacity(0.7)) .child(description) })) } } /// A one-line title that ends in an ellipsis when it doesn't fit, cut where the browser cuts it. /// GPUI's `truncate()` sums each character's advance on its own, which ignores kerning and /// overestimates Geist by about 10px over 50 characters, so it drops a character or two that /// would fit. Here the full title, kept invisible, sizes the box, and the visible text is shaped /// as a whole and cut to the longest prefix that fits with "…". fn ellipsized(title: SharedString) -> AnyElement { let visible = title.clone(); div() .id("title") .relative() .min_w_0() .overflow_hidden() .whitespace_nowrap() .child(div().invisible().child(title)) .child( canvas( |_, _, _| {}, move |bounds, _, window, cx| { let style = window.text_style(); let font_size = style.font_size.to_pixels(window.rem_size()); let line_height = style.line_height_in_pixels(window.rem_size()); let shape = |text: SharedString, window: &mut Window| { let run = style.to_run(text.len()); window.text_system().shape_line(text, font_size, &[run], None) }; let available = bounds.size.width; let mut line = shape(visible.clone(), window); if line.width > available { // The longest prefix that fits with the ellipsis, found by bisection // over character boundaries. let ends: Vec<usize> = visible.char_indices().map(|(ix, _)| ix).collect(); let (mut fit, mut over) = (0, ends.len()); while over - fit > 1 { let mid = (fit + over) / 2; let candidate: SharedString = format!("{}…", &visible[..ends[mid]]).into(); if shape(candidate, window).width <= available { fit = mid; } else { over = mid; } } line = shape(format!("{}…", &visible[..ends[fit]]).into(), window); } line.paint(bounds.origin, line_height, TextAlign::Left, None, window, cx).ok(); }, ) .absolute() .top_0() .left_0() .size_full(), ) .into_any_element() } /// shadcn's `shimmer`: a band where the title fades to a fifth of its alpha sweeps left to right /// every 2s. GPUI can't clip a gradient to text, so each glyph takes the gradient's alpha at its /// center. The band is `3ch + 40px` to each side of its center, easing linearly from the floor at /// the center back to full color at the edge, and travels from one band-width before the title to /// one past its end. fn shimmer( title: gpui::Stateful<gpui::Div>, text: SharedString, window: &mut Window, ) -> AnyElement { let style = window.text_style(); let shape = |text: SharedString, window: &mut Window| { let run = style.to_run(text.len()); window.text_system().shape_line(text, TITLE_SIZE, &[run], None) }; let line = shape(text.clone(), window); let ch = f32::from(shape("0".into(), window).width); let width = f32::from(line.width); let spread = 3.0 * ch + 40.0; let glyphs: Vec<(Range<usize>, f32)> = text .char_indices() .map(|(start, c)| { let end = start + c.len_utf8(); let center = (f32::from(line.x_for_index(start)) + f32::from(line.x_for_index(end))) / 2.0; (start..end, center) }) .collect(); title .with_animation("shimmer", Animation::new(SHIMMER).repeat(), move |this, t| { let band = -spread + t * (width + 2.0 * spread); let highlights = glyphs.iter().filter_map(|(range, x)| { let distance = (x - band).abs(); (distance < spread).then(|| { let alpha = SHIMMER_FLOOR + (1.0 - SHIMMER_FLOOR) * distance / spread; // A highlight color blends over the text's, so fade the current color instead; // like shadcn's `currentColor`, that also follows the hover color. let style = HighlightStyle { fade_out: Some(1.0 - alpha), ..Default::default() }; (range.clone(), style) }) }); this.child(StyledText::new(text.clone()).with_highlights(highlights.collect::<Vec<_>>())) }) .into_any_element() } /// A line that expands to show its detail, such as a command's output or nested steps. The /// parent view owns `open` and updates it in `on_open_change`. #[derive(IntoElement)] pub struct TraceCollapsible { id: ElementId, open: bool, line: TraceLine, content: Vec<AnyElement>, on_open_change: Option<OpenChangeHandler>, } impl TraceCollapsible { pub fn new(id: impl Into<ElementId>, open: bool, line: TraceLine) -> Self { Self { id: id.into(), open, line, content: Vec::new(), on_open_change: None, } } /// Receives the *next* open value. pub fn on_open_change( mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Box::new(handler)); self } } impl ParentElement for TraceCollapsible { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.content.extend(elements); } } impl RenderOnce for TraceCollapsible { fn render(mut self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let error = self.line.status == TraceStatus::Error; let chevron_color = if error { theme.destructive } else { theme.muted_foreground }; let fg = theme.foreground; self.line.in_trigger = true; self.line.on_click = None; let chevron = svg() .data(CHEVRON_RIGHT) .flex_none() .size(px(16.0)) .text_color(chevron_color) .when(!error, |this| { this.group_hover(ROW_GROUP, move |style| style.text_color(fg)) }) .when(self.open, |this| { this.with_transformation(Transformation::rotate(radians(FRAC_PI_2))) }); let trigger = div() .group(ROW_GROUP) .flex() .items_center() .gap_1() .max_w_full() .min_w_0() .child(self.line) .child(chevron); let content = div() .mt_2() .mb_1() .ml(px(7.0)) .pl_4() .pr_1() .min_w_0() .border_l_1() .border_color(theme.border) .text_sm() .line_height(relative(1.625)) .text_color(theme.muted_foreground) .children(self.content); let collapsible = Collapsible::new(self.id, self.open) .trigger(trigger) .content(content); div() .flex() .flex_col() .w_full() .min_w_0() .child(match self.on_open_change { Some(handler) => collapsible.on_open_change(handler), None => collapsible, }) } }Register the module
// src/ui/mod.rs pub mod trace;
Usage
use crate::ui::trace::*;API Reference
TraceStatus
A step's progress. A line without a status is done.
TraceStatus::DoneTraceStatus::RunningThe title shimmers.
TraceStatus::ErrorFailed work, in the destructive color. Say so in the title too.
TraceStatus::PendingNot started yet: dimmed.
Trace
A list of steps, such as an agent's searches, tool calls and edits.
Trace::new() -> SelfTraceLine
One step: an icon naming the action, a one-line title and an optional description such as a diff stat or a duration.
TraceLine::new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self.icon(svg: &'static [u8])A 16px SVG icon before the title, tinted with the line's color.
.description(description: impl Into<SharedString>)Secondary text after the title. Unlike the title it never truncates.
.indicator(svg: &'static [u8])A 16px SVG icon right after the title, e.g. an arrow-up-right on an external link.
.status(status: TraceStatus).spin(spin: bool)Spins the leading icon, one turn a second, e.g. a loader on a running step.
.on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)Makes the line a link or the trigger of an overlay: pointer cursor, brighter on hover.
TraceCollapsible
A line that expands to show its detail, such as a command's output or nested steps. The parent view owns open and updates it in on_open_change.
TraceCollapsible::new(id: impl Into<ElementId>, open: bool, line: TraceLine) -> Self.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.