Displays a task an agent works through. Each task opens on its steps while it runs and folds away when it finishes.
Loading GPUI…
use std::time::Duration;
use gpui::{div, prelude::*, px, relative, Context, Task as GpuiTask, Window};
use crate::icons::{CIRCLE_CHECK, LOADER_CIRCLE};
use crate::theme::ActiveTheme;
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};
/// Each step 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 = "Add Open Graph metadata to the home page.";
const ANSWER: &str = "Added Open Graph defaults to app/layout.tsx and a title, description and image for the home page in app/page.tsx.";
struct TaskScript {
/// The title while running and once finished.
title: (&'static str, &'static str),
steps: &'static [(&'static str, &'static str)],
}
const TASKS: [TaskScript; 2] = [
TaskScript {
title: ("Finding the project files", "Found the project files"),
steps: &[
("Searching for generateMetadata", "Searched for generateMetadata"),
("Reading app/layout.tsx", "Read app/layout.tsx"),
("Reading app/page.tsx", "Read app/page.tsx"),
],
},
TaskScript {
title: ("Updating the page metadata", "Updated the page metadata"),
steps: &[
("Editing app/layout.tsx", "Edited app/layout.tsx"),
("Editing app/page.tsx", "Edited app/page.tsx"),
],
},
];
/// A task the agent has started.
#[derive(Clone, Copy)]
struct Progress {
/// Steps finished; the one after them is running.
done: usize,
/// Set once the reader toggles the row; until then it is open only while the task runs.
open: Option<bool>,
}
pub struct TaskPattern {
tasks: Vec<Progress>,
/// Words of the answer shown so far.
words: usize,
busy: bool,
stream: Option<GpuiTask<()>>,
}
impl Default for TaskPattern {
/// Starts on the finished transcript with both tasks closed.
fn default() -> Self {
Self {
tasks: TASKS.iter().map(|task| Progress { done: task.steps.len(), open: None }).collect(),
words: ANSWER.split_inclusive(' ').count(),
busy: false,
stream: None,
}
}
}
impl TaskPattern {
fn replay(&mut self, cx: &mut Context<Self>) {
self.tasks.clear();
self.words = 0;
self.busy = true;
self.stream = Some(cx.spawn(async move |this, cx| {
for (ix, task) in TASKS.iter().enumerate() {
for done in 0..=task.steps.len() {
let updated = this.update(cx, |this, cx| {
match this.tasks.get_mut(ix) {
Some(progress) => progress.done = done,
None => this.tasks.push(Progress { done, open: None }),
}
cx.notify();
});
if updated.is_err() {
return;
}
cx.background_executor().timer(STEP).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 TaskPattern {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect();
let rows = self.tasks.iter().enumerate().map(|(ix, progress)| {
let task = &TASKS[ix];
let running = progress.done < task.steps.len();
let line = if running {
TraceLine::new(("task", ix), task.title.0).icon(LOADER_CIRCLE).spin(true).status(TraceStatus::Running)
} else {
TraceLine::new(("task", ix), task.title.1).icon(CIRCLE_CHECK)
};
// Finished steps, then the running one.
let steps = task.steps.iter().take(progress.done + 1).enumerate().map(|(step, (doing, done))| {
if step < progress.done {
TraceLine::new(("step", step), *done)
} else {
TraceLine::new(("step", step), *doing).status(TraceStatus::Running)
}
});
TraceCollapsible::new(("row", ix), progress.open.unwrap_or(running), line)
.on_open_change(cx.listener(move |this, open: &bool, _, cx| {
if let Some(progress) = this.tasks.get_mut(ix) {
progress.open = Some(*open);
}
cx.notify();
}))
.child(Trace::new().children(steps))
});
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.tasks.is_empty(), |this| {
this.child(
Message::new().child(
div()
.flex()
.flex_col()
.gap_4()
.w_full()
.child(Trace::new().children(rows))
.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 message trace iconsCopy the pattern
Paste the code into
src/ai/task.rsand declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.src/ai/task.rs use std::time::Duration; use gpui::{div, prelude::*, px, relative, Context, Task as GpuiTask, Window}; use crate::icons::{CIRCLE_CHECK, LOADER_CIRCLE}; use crate::theme::ActiveTheme; 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}; /// Each step 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 = "Add Open Graph metadata to the home page."; const ANSWER: &str = "Added Open Graph defaults to app/layout.tsx and a title, description and image for the home page in app/page.tsx."; struct TaskScript { /// The title while running and once finished. title: (&'static str, &'static str), steps: &'static [(&'static str, &'static str)], } const TASKS: [TaskScript; 2] = [ TaskScript { title: ("Finding the project files", "Found the project files"), steps: &[ ("Searching for generateMetadata", "Searched for generateMetadata"), ("Reading app/layout.tsx", "Read app/layout.tsx"), ("Reading app/page.tsx", "Read app/page.tsx"), ], }, TaskScript { title: ("Updating the page metadata", "Updated the page metadata"), steps: &[ ("Editing app/layout.tsx", "Edited app/layout.tsx"), ("Editing app/page.tsx", "Edited app/page.tsx"), ], }, ]; /// A task the agent has started. #[derive(Clone, Copy)] struct Progress { /// Steps finished; the one after them is running. done: usize, /// Set once the reader toggles the row; until then it is open only while the task runs. open: Option<bool>, } pub struct TaskPattern { tasks: Vec<Progress>, /// Words of the answer shown so far. words: usize, busy: bool, stream: Option<GpuiTask<()>>, } impl Default for TaskPattern { /// Starts on the finished transcript with both tasks closed. fn default() -> Self { Self { tasks: TASKS.iter().map(|task| Progress { done: task.steps.len(), open: None }).collect(), words: ANSWER.split_inclusive(' ').count(), busy: false, stream: None, } } } impl TaskPattern { fn replay(&mut self, cx: &mut Context<Self>) { self.tasks.clear(); self.words = 0; self.busy = true; self.stream = Some(cx.spawn(async move |this, cx| { for (ix, task) in TASKS.iter().enumerate() { for done in 0..=task.steps.len() { let updated = this.update(cx, |this, cx| { match this.tasks.get_mut(ix) { Some(progress) => progress.done = done, None => this.tasks.push(Progress { done, open: None }), } cx.notify(); }); if updated.is_err() { return; } cx.background_executor().timer(STEP).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 TaskPattern { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let fg = cx.theme().foreground; let answer: String = ANSWER.split_inclusive(' ').take(self.words).collect(); let rows = self.tasks.iter().enumerate().map(|(ix, progress)| { let task = &TASKS[ix]; let running = progress.done < task.steps.len(); let line = if running { TraceLine::new(("task", ix), task.title.0).icon(LOADER_CIRCLE).spin(true).status(TraceStatus::Running) } else { TraceLine::new(("task", ix), task.title.1).icon(CIRCLE_CHECK) }; // Finished steps, then the running one. let steps = task.steps.iter().take(progress.done + 1).enumerate().map(|(step, (doing, done))| { if step < progress.done { TraceLine::new(("step", step), *done) } else { TraceLine::new(("step", step), *doing).status(TraceStatus::Running) } }); TraceCollapsible::new(("row", ix), progress.open.unwrap_or(running), line) .on_open_change(cx.listener(move |this, open: &bool, _, cx| { if let Some(progress) = this.tasks.get_mut(ix) { progress.open = Some(*open); } cx.notify(); })) .child(Trace::new().children(steps)) }); 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.tasks.is_empty(), |this| { this.child( Message::new().child( div() .flex() .flex_col() .gap_4() .w_full() .child(Trace::new().children(rows)) .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))), ), ) }) } }