Displays a model's reasoning. The row streams the thinking open while the model thinks, then folds it away behind how long it took.
Loading GPUI…
use std::time::Duration;
use gpui::{div, prelude::*, px, relative, Context, Task, Window};
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};
/// The mock transport's pace: reasoning streams a word every 40ms, the answer a word every 20ms,
/// with a 400ms pause between them.
const REASONING_CHUNK: Duration = Duration::from_millis(40);
const CHUNK: Duration = Duration::from_millis(20);
const PAUSE: Duration = Duration::from_millis(400);
const QUESTION: &str = "Why is the checkout deploy so slow?";
const REASONING: &str = "The deploy log has three phases. Install takes 38s and next build takes 52s, both normal for this repo.\n\nImage optimization takes 3m 50s. It reruns on every deploy because its cache key includes the commit hash, so the cache never hits.";
const ANSWER: &str = "Image optimization is the bottleneck. Key its cache on the lockfile and the image directory instead of the commit hash, and the deploy should take under two minutes.";
/// Splits text the way the mock transport does: each word with the whitespace after it.
fn words(text: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut start = 0;
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
i += 1;
}
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
out.push(&text[start..i]);
start = i;
}
out
}
pub struct ReasoningPattern {
/// Words of the reasoning and of the answer shown so far.
reasoning_words: usize,
answer_words: usize,
thinking: bool,
/// The reader's choice. `None` follows the stream: open while thinking, closed after.
open: Option<bool>,
busy: bool,
stream: Option<Task<()>>,
}
impl Default for ReasoningPattern {
/// Starts on the finished transcript with the reasoning open, as shadcn's `defaultOpen` does
/// when the page loads; a replayed row closes once the thinking ends.
fn default() -> Self {
Self {
reasoning_words: words(REASONING).len(),
answer_words: words(ANSWER).len(),
thinking: false,
open: Some(true),
busy: false,
stream: None,
}
}
}
impl ReasoningPattern {
fn replay(&mut self, cx: &mut Context<Self>) {
self.reasoning_words = 0;
self.answer_words = 0;
self.thinking = true;
self.open = None;
self.busy = true;
self.stream = Some(cx.spawn(async move |this, cx| {
for _ in 0..words(REASONING).len() {
cx.background_executor().timer(REASONING_CHUNK).await;
if this.update(cx, |this, cx| { this.reasoning_words += 1; cx.notify(); }).is_err() {
return;
}
}
let _ = this.update(cx, |this, cx| { this.thinking = false; cx.notify(); });
cx.background_executor().timer(PAUSE).await;
for _ in 0..words(ANSWER).len() {
cx.background_executor().timer(CHUNK).await;
if this.update(cx, |this, cx| { this.answer_words += 1; cx.notify(); }).is_err() {
return;
}
}
let _ = this.update(cx, |this, cx| { this.busy = false; cx.notify(); });
}));
cx.notify();
}
}
impl Render for ReasoningPattern {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
let reasoning: String = words(REASONING)[..self.reasoning_words].concat();
let answer: String = words(ANSWER)[..self.answer_words].concat();
let line = if self.thinking {
TraceLine::new("reasoning", "Thinking").status(TraceStatus::Running)
} else {
TraceLine::new("reasoning", "Thought for 5s")
};
// Until the first word arrives there is nothing to open, so the row has no chevron.
let row = if reasoning.is_empty() {
line.into_any_element()
} else {
TraceCollapsible::new("row", self.open.unwrap_or(self.thinking), line)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = Some(*open);
cx.notify();
}))
// `whitespace-pre-wrap`: each line of the reasoning is its own block, a blank line
// keeps its height, and a trailing newline adds no line, as in CSS.
.children(reasoning.lines().map(|line| div().min_h(px(22.75)).child(line.to_string())))
.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 message traceCopy the pattern
Paste the code into
src/ai/reasoning.rsand declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.src/ai/reasoning.rs use std::time::Duration; use gpui::{div, prelude::*, px, relative, Context, Task, Window}; 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}; /// The mock transport's pace: reasoning streams a word every 40ms, the answer a word every 20ms, /// with a 400ms pause between them. const REASONING_CHUNK: Duration = Duration::from_millis(40); const CHUNK: Duration = Duration::from_millis(20); const PAUSE: Duration = Duration::from_millis(400); const QUESTION: &str = "Why is the checkout deploy so slow?"; const REASONING: &str = "The deploy log has three phases. Install takes 38s and next build takes 52s, both normal for this repo.\n\nImage optimization takes 3m 50s. It reruns on every deploy because its cache key includes the commit hash, so the cache never hits."; const ANSWER: &str = "Image optimization is the bottleneck. Key its cache on the lockfile and the image directory instead of the commit hash, and the deploy should take under two minutes."; /// Splits text the way the mock transport does: each word with the whitespace after it. fn words(text: &str) -> Vec<&str> { let mut out = Vec::new(); let mut start = 0; let bytes = text.as_bytes(); let mut i = 0; while i < bytes.len() { while i < bytes.len() && !bytes[i].is_ascii_whitespace() { i += 1; } while i < bytes.len() && bytes[i].is_ascii_whitespace() { i += 1; } out.push(&text[start..i]); start = i; } out } pub struct ReasoningPattern { /// Words of the reasoning and of the answer shown so far. reasoning_words: usize, answer_words: usize, thinking: bool, /// The reader's choice. `None` follows the stream: open while thinking, closed after. open: Option<bool>, busy: bool, stream: Option<Task<()>>, } impl Default for ReasoningPattern { /// Starts on the finished transcript with the reasoning open, as shadcn's `defaultOpen` does /// when the page loads; a replayed row closes once the thinking ends. fn default() -> Self { Self { reasoning_words: words(REASONING).len(), answer_words: words(ANSWER).len(), thinking: false, open: Some(true), busy: false, stream: None, } } } impl ReasoningPattern { fn replay(&mut self, cx: &mut Context<Self>) { self.reasoning_words = 0; self.answer_words = 0; self.thinking = true; self.open = None; self.busy = true; self.stream = Some(cx.spawn(async move |this, cx| { for _ in 0..words(REASONING).len() { cx.background_executor().timer(REASONING_CHUNK).await; if this.update(cx, |this, cx| { this.reasoning_words += 1; cx.notify(); }).is_err() { return; } } let _ = this.update(cx, |this, cx| { this.thinking = false; cx.notify(); }); cx.background_executor().timer(PAUSE).await; for _ in 0..words(ANSWER).len() { cx.background_executor().timer(CHUNK).await; if this.update(cx, |this, cx| { this.answer_words += 1; cx.notify(); }).is_err() { return; } } let _ = this.update(cx, |this, cx| { this.busy = false; cx.notify(); }); })); cx.notify(); } } impl Render for ReasoningPattern { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let fg = cx.theme().foreground; let reasoning: String = words(REASONING)[..self.reasoning_words].concat(); let answer: String = words(ANSWER)[..self.answer_words].concat(); let line = if self.thinking { TraceLine::new("reasoning", "Thinking").status(TraceStatus::Running) } else { TraceLine::new("reasoning", "Thought for 5s") }; // Until the first word arrives there is nothing to open, so the row has no chevron. let row = if reasoning.is_empty() { line.into_any_element() } else { TraceCollapsible::new("row", self.open.unwrap_or(self.thinking), line) .on_open_change(cx.listener(|this, open: &bool, _, cx| { this.open = Some(*open); cx.notify(); })) // `whitespace-pre-wrap`: each line of the reasoning is its own block, a blank line // keeps its height, and a trailing newline adds no line, as in CSS. .children(reasoning.lines().map(|line| div().min_h(px(22.75)).child(line.to_string()))) .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))), ), ) }) } }