The thread. Message Scroller keeps your place while the reply streams.
Loading GPUI…
use std::{sync::Arc, time::Duration};
use gpui::{
div, linear_color_stop, linear_gradient, prelude::*, px, AnyElement, App,
Animation, AnimationExt, ClipboardItem, Context, ElementId, Entity, Font, FontWeight, Hsla,
KeyDownEvent, Pixels, ScrollHandle, SharedString, Subscription, Task, TextRun, Window,
};
use crate::icons::{
icon, ARROW_UP, CHECK, CIRCLE_CHECK, COPY, GLOBE, LOADER_CIRCLE, MESSAGE_CIRCLE_DASHED,
PAPERCLIP, PLUS, ROTATE_CW, TELESCOPE, TERMINAL,
};
use crate::theme::{ActiveTheme, Theme};
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::input::{InputEvent, TextInput};
use crate::ui::message::{Message, MessageAlign};
use crate::ui::message_scroller::MessageScroller;
use crate::ui::popover::{Align, Side};
use crate::ui::textarea::Textarea;
use crate::ui::tooltip::Tooltip;
use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus};
const MONO: &str = "Geist Mono";
/// The mock transport's pace: every chunk of text waits 16ms.
const CHUNK: Duration = Duration::from_millis(16);
/// `.sleep(600)`: the beat between a sent message and the agent starting.
const START: Duration = Duration::from_millis(600);
/// `writer.sleep(400)` after the reasoning, `writer.sleep(500)` after a command.
const AFTER_REASONING: Duration = Duration::from_millis(400);
const AFTER_COMMAND: Duration = Duration::from_millis(500);
/// shadcn's "slide-up" message animation: a sent message rises 10px into place as it fades in,
/// over 260ms on `cubic-bezier(0.16, 1, 0.3, 1)`.
const SLIDE_UP: Duration = Duration::from_millis(260);
const SLIDE_UP_RISE: f32 = 10.0;
/// The chat demo runs in shadcn's `theme-blue`: Tailwind blue-700 with blue-50 text.
const BLUE: u32 = 0x1447e6;
const BLUE_FOREGROUND: u32 = 0xeff6ff;
const FALLBACK: &str = "This demo only knows the scripted turns. Press reset to start over.";
/// A CSS cubic-bézier timing function: solves x for `t` by Newton's method and returns y.
fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 {
move |t| {
let at = |a: f32, b: f32, s: f32| 3.0 * a * s * (1.0 - s).powi(2) + 3.0 * b * s * s * (1.0 - s) + s.powi(3);
let slope = |a: f32, b: f32, s: f32| 3.0 * a * (1.0 - s).powi(2) + 6.0 * (b - a) * s * (1.0 - s) + 3.0 * (1.0 - b) * s * s;
let mut s = t.clamp(0.0, 1.0);
for _ in 0..8 {
let dx = slope(x1, x2, s);
if dx.abs() < 1e-6 {
break;
}
s = (s - (at(x1, x2, s) - t) / dx).clamp(0.0, 1.0);
}
at(y1, y2, s)
}
}
/// One thing the agent does before it answers.
#[derive(Clone, Copy)]
enum Step {
Reasoning(&'static str),
/// A command, how long it runs, and what it prints.
Command(&'static str, Duration, &'static str),
}
struct Turn {
ask: &'static str,
steps: &'static [Step],
reply: &'static str,
}
const SCRIPT: [Turn; 3] = [
Turn {
ask: "Add a dark mode toggle to the settings page.",
steps: &[
Step::Reasoning(
"I need to know how themes are set up before I add a toggle. If next-themes is already in the layout, the toggle only has to call setTheme.",
),
Step::Command("rg -l ThemeProvider app", Duration::from_millis(800), "app/layout.tsx"),
],
reply: "next-themes is already set up in `app/layout.tsx`, so the toggle only has to call `setTheme`.
**Changes**
- Added `components/mode-toggle.tsx` with a Light and Dark option.
- Put `<ModeToggle />` next to the Appearance heading in `app/settings/page.tsx`.
```tsx
const { setTheme } = useTheme()
```
",
},
Turn {
ask: "Make it follow the system setting by default.",
steps: &[
Step::Reasoning("The default theme lives on the ThemeProvider. I should check what it is set to now."),
Step::Command(
"rg -n defaultTheme app/layout.tsx",
Duration::from_millis(800),
"12: <ThemeProvider attribute=\"class\" defaultTheme=\"light\">",
),
],
reply: "It was set to `light`. I updated the `ThemeProvider` in `app/layout.tsx`:
```tsx
<ThemeProvider attribute=\"class\" defaultTheme=\"system\" enableSystem>
```
New visitors now get the theme from their OS. The toggle also has a **System** option, so anyone who picked Light or Dark can switch back.
",
},
Turn {
ask: "Run the build before I ship it.",
steps: &[Step::Command(
"pnpm build",
Duration::from_millis(1600),
"▲ Next.js 16.0.0\n\n✓ Compiled successfully in 4.2s\n✓ Linting and checking validity of types\n✓ Generating static pages (12/12)",
)],
reply: "The build passes, so it is ready to ship.
- Compiled in **4.2s**.
- No lint or type errors.
- Generated all **12** static pages.
",
},
];
/// shiki's tsx tokens for each scripted code line, so a partly streamed line keeps its colors.
#[derive(Clone, Copy)]
enum Token {
Plain,
Keyword,
Constant,
Function,
String,
}
const CODE_LINES: [&[(&str, Token)]; 2] = [
&[
("const", Token::Keyword),
(" { ", Token::Plain),
("setTheme", Token::Constant),
(" } ", Token::Plain),
("=", Token::Keyword),
(" ", Token::Plain),
("useTheme", Token::Function),
("()", Token::Plain),
],
&[
("<", Token::Plain),
("ThemeProvider", Token::Constant),
(" ", Token::Plain),
("attribute", Token::Function),
("=", Token::Keyword),
("\"class\"", Token::String),
(" ", Token::Plain),
("defaultTheme", Token::Function),
("=", Token::Keyword),
("\"system\"", Token::String),
(" ", Token::Plain),
("enableSystem", Token::Function),
(">", Token::Plain),
],
];
fn token_color(token: Token, theme: &Theme) -> Hsla {
let dark = theme.background.l < 0.5;
let hex = match (token, dark) {
(Token::Plain, false) => 0x24292e,
(Token::Keyword, false) => 0xd73a49,
(Token::Constant, false) => 0x005cc5,
(Token::Function, false) => 0x6f42c1,
(Token::String, false) => 0x032f62,
(Token::Plain, true) => 0xe1e4e8,
(Token::Keyword, true) => 0xf97583,
(Token::Constant, true) => 0x79b8ff,
(Token::Function, true) => 0xb392f0,
(Token::String, true) => 0x9ecbff,
};
gpui::rgb(hex).into()
}
/// Colors a code line, which may be a prefix of a scripted one while it streams.
fn code_tokens(line: &str) -> Vec<(String, Token)> {
for tokens in CODE_LINES {
let full: String = tokens.iter().map(|(text, _)| *text).collect();
if full.starts_with(line) {
let mut left = line.len();
let mut out = Vec::new();
for (text, token) in tokens {
if left == 0 {
break;
}
let take = text.len().min(left);
out.push((text[..take].to_string(), *token));
left -= take;
}
return out;
}
}
vec![(line.to_string(), Token::Plain)]
}
/// Splits like the mock transport, `/\S+\s*/g`: each chunk is a word and the whitespace after it.
fn chunks(text: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut start = None;
let mut in_space = false;
for (ix, ch) in text.char_indices() {
let space = ch.is_whitespace();
match start {
None if !space => {
start = Some(ix);
in_space = false;
}
Some(from) if !space && in_space => {
out.push(&text[from..ix]);
start = Some(ix);
in_space = false;
}
Some(_) if space => in_space = true,
_ => {}
}
}
if let Some(from) = start {
out.push(&text[from..]);
}
out
}
fn streamed(text: &str, count: usize) -> String {
chunks(text).into_iter().take(count).collect()
}
/// A step the agent has started.
struct StepState {
step: Step,
/// Reasoning chunks shown so far.
words: usize,
done: bool,
/// Set once the reader opens or closes the row; until then a reasoning row is open while it
/// runs, and a command's output starts closed.
open: Option<bool>,
}
/// One exchange: the sent message and, once the agent starts, its reply.
struct Exchange {
ask: String,
/// `None` for a message the script doesn't know; it gets the fallback reply.
script: Option<usize>,
started: bool,
steps: Vec<StepState>,
/// Reply chunks shown so far.
words: usize,
}
impl Exchange {
fn reply(&self) -> &'static str {
self.script.map_or(FALLBACK, |ix| SCRIPT[ix].reply)
}
}
#[derive(Default)]
pub struct ChatPattern {
composer: Option<Entity<TextInput>>,
_change: Option<Subscription>,
/// What the reader typed, if it differs from the next scripted message.
draft: Option<String>,
exchanges: Vec<Exchange>,
stream: Option<Task<()>>,
/// Bumped on reset so the slide-up animations of a new thread start fresh.
generation: usize,
menu_open: bool,
copied: Option<(usize, usize)>,
copy_reset: Option<Task<()>>,
}
impl ChatPattern {
fn busy(&self) -> bool {
self.stream.is_some()
}
/// The next scripted message after the thread so far.
fn next_scripted(&self) -> Option<usize> {
let sent = self.exchanges.iter().filter_map(|exchange| exchange.script).max();
let next = sent.map_or(0, |ix| ix + 1);
(next < SCRIPT.len()).then_some(next)
}
/// What the composer shows: the reader's draft, else the next scripted message.
fn composer_text(&self) -> String {
self.draft
.clone()
.unwrap_or_else(|| self.next_scripted().map_or(String::new(), |ix| SCRIPT[ix].ask.to_string()))
}
fn sync_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let text = self.composer_text();
if let Some(composer) = self.composer.clone() {
if composer.read(cx).text().as_ref() != text {
composer.update(cx, |input, cx| input.set_text(text, window, cx));
}
}
}
fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.stream = None;
self.exchanges.clear();
self.draft = None;
self.generation += 1;
self.sync_composer(window, cx);
cx.notify();
}
fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let text = self.composer_text();
if self.busy() || text.trim().is_empty() {
return;
}
let script = match &self.draft {
None => self.next_scripted(),
// A typed message only follows the script if it is the scripted one.
Some(draft) => self.next_scripted().filter(|&ix| SCRIPT[ix].ask == draft.trim()),
};
self.exchanges.push(Exchange {
ask: text.trim().to_string(),
script,
started: false,
steps: Vec::new(),
words: 0,
});
let ix = self.exchanges.len() - 1;
self.draft = None;
self.sync_composer(window, cx);
self.stream = Some(cx.spawn(async move |this, cx| {
let update = |cx: &mut gpui::AsyncApp, f: &dyn Fn(&mut Exchange)| {
this.update(cx, |this, cx| {
if let Some(exchange) = this.exchanges.get_mut(ix) {
f(exchange);
}
cx.notify();
})
.is_ok()
};
let steps: &[Step] = script.map_or(&[], |ix| SCRIPT[ix].steps);
if script.is_some() {
cx.background_executor().timer(START).await;
}
if !update(cx, &|exchange| exchange.started = true) {
return;
}
for (step_ix, step) in steps.iter().enumerate() {
let push = |exchange: &mut Exchange| {
exchange.steps.push(StepState { step: *step, words: 0, done: false, open: None })
};
if !update(cx, &push) {
return;
}
match *step {
Step::Reasoning(text) => {
for _ in chunks(text) {
cx.background_executor().timer(CHUNK).await;
if !update(cx, &|exchange| exchange.steps[step_ix].words += 1) {
return;
}
}
if !update(cx, &|exchange| exchange.steps[step_ix].done = true) {
return;
}
cx.background_executor().timer(AFTER_REASONING).await;
}
Step::Command(_, runs, _) => {
cx.background_executor().timer(runs).await;
if !update(cx, &|exchange| exchange.steps[step_ix].done = true) {
return;
}
cx.background_executor().timer(AFTER_COMMAND).await;
}
}
}
let reply = script.map_or(FALLBACK, |ix| SCRIPT[ix].reply);
for _ in chunks(reply) {
cx.background_executor().timer(CHUNK).await;
if !update(cx, &|exchange| exchange.words += 1) {
return;
}
}
this.update(cx, |this, cx| {
this.stream = None;
cx.notify();
})
.ok();
}));
cx.notify();
}
fn copy(&mut self, key: (usize, usize), code: String, cx: &mut Context<Self>) {
cx.write_to_clipboard(ClipboardItem::new_string(code));
self.copied = Some(key);
self.copy_reset = Some(cx.spawn(async move |this, cx| {
cx.background_executor().timer(Duration::from_secs(2)).await;
this.update(cx, |this, cx| {
this.copied = None;
cx.notify();
})
.ok();
}));
cx.notify();
}
}
impl Render for ChatPattern {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if self.composer.is_none() {
let composer = cx.new(|cx| Textarea::new(cx).multi_line(1).placeholder("Ask the agent...").bare());
self._change = Some(cx.subscribe(&composer, |this: &mut Self, composer, _: &InputEvent, cx| {
let text = composer.read(cx).text().to_string();
let scripted = this.next_scripted().map(|ix| SCRIPT[ix].ask);
this.draft = (scripted != Some(text.as_str())).then_some(text);
cx.notify();
}));
self.composer = Some(composer);
self.sync_composer(window, cx);
}
let Some(composer) = self.composer.clone() else {
return div();
};
let theme = cx.theme();
let (fg, muted_fg, muted, border, bg, input) =
(theme.foreground, theme.muted_foreground, theme.muted, theme.border, theme.background, theme.input);
let busy = self.busy();
let can_send = !busy && !self.composer_text().trim().is_empty();
let header = div()
.flex()
.items_start()
.justify_between()
.gap_4()
.p_8()
.pb_4()
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_size(px(15.0))
.line_height(px(26.25))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.child("New Thread"),
)
.child(div().text_sm().text_color(muted_fg).child("Ask the agent to change your code.")),
)
.child(
Tooltip::new("reset-tip", "Reset").trigger(
Button::new("reset", "")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.icon_only()
.rounded_full()
.disabled(busy)
.leading(icon(ROTATE_CW).size(px(16.0)).text_color(fg))
.on_click(cx.listener(|this, _, window, cx| this.reset(window, cx))),
),
);
let body = if self.exchanges.is_empty() {
// shadcn's `Empty` with an icon tile, centered in the thread's space.
div()
.size_full()
.flex()
.items_center()
.justify_center()
.p_12()
.child(
div()
.max_w(px(384.0))
.flex()
.flex_col()
.items_center()
.gap_2()
.child(
div()
.mb_2()
.flex()
.items_center()
.justify_center()
.size(px(40.0))
.rounded(px(14.0))
.bg(muted)
.child(icon(MESSAGE_CIRCLE_DASHED).size(px(20.0)).text_color(fg)),
)
.child(
div()
.text_size(px(18.0))
.line_height(px(28.0))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.child("What should we build?"),
)
.child(
// shadcn balances the description's lines (`text-balance`); this
// width breaks it in the same place.
div()
.max_w(px(305.0))
.text_sm()
.line_height(px(22.75))
.text_center()
.text_color(muted_fg)
.child("The agent can read your code, run commands and make changes. Press send to start."),
),
)
.into_any_element()
} else {
let mut items: Vec<AnyElement> = Vec::new();
let mut anchor = None;
let last = self.exchanges.len() - 1;
for (ix, exchange) in self.exchanges.iter().enumerate() {
// The reader's messages are `scrollAnchor` items: each one sent is placed near
// the top while its reply streams in below.
anchor = Some(items.len());
items.push(self.user_message(ix, exchange).into_any_element());
if exchange.started {
items.push(self.assistant_message(ix, exchange, busy && ix == last, window, cx));
}
}
MessageScroller::new(("thread", self.generation))
.size_full()
.auto_scroll(false)
.scroll_anchor(anchor)
.jump_label("")
.content_gap(px(24.0))
.content_padding(px(32.0), px(0.0))
.children(items)
.into_any_element()
};
let blue: Hsla = gpui::rgb(BLUE).into();
let menu = DropdownMenu::new("context-menu", self.menu_open)
.side(Side::Top)
.align(Align::Start)
.width(px(176.0))
.trigger(
div()
.id("add-context")
.flex()
.items_center()
.justify_center()
.size(px(32.0))
.rounded_full()
.border_1()
.border_color(border)
.bg(if self.menu_open { muted } else { bg })
.cursor_pointer()
.hover(move |style| style.bg(muted))
.child(icon(PLUS).size(px(16.0)).text_color(if self.menu_open { fg } else { muted_fg })),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.menu_open = *open;
cx.notify();
}))
.item(MenuItem::new("Add Photos & Files").icon(icon(PAPERCLIP).size(px(16.0)).text_color(muted_fg)))
.separator()
.item(MenuItem::new("Deep Research").icon(icon(TELESCOPE).size(px(16.0)).text_color(muted_fg)))
.item(MenuItem::new("Web Search").icon(icon(GLOBE).size(px(16.0)).text_color(muted_fg)));
let send = div()
.id("send")
.flex()
.items_center()
.justify_center()
.size(px(32.0))
.rounded_full()
.bg(blue)
.child(icon(ARROW_UP).size(px(16.0)).text_color(gpui::rgb(BLUE_FOREGROUND)))
.map(|this| {
if can_send {
this.cursor_pointer()
.hover(move |style| style.bg(blue.opacity(0.8)))
.active(|style| style.top(px(1.0)))
.on_click(cx.listener(|this, _, window, cx| this.submit(window, cx)))
} else {
this.opacity(0.5).cursor_not_allowed()
}
});
let composer_box = div()
.w_full()
.flex()
.flex_col()
.rounded(px(18.0))
.border_1()
.border_color(gpui::transparent_black())
.bg(input.opacity(0.5))
// Enter sends and Shift+Enter breaks the line, like the form's `onKeyDown`.
.capture_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
let keystroke = &event.keystroke;
if keystroke.key == "enter" && !keystroke.modifiers.shift {
cx.stop_propagation();
this.submit(window, cx);
}
}))
.child(div().min_h(px(56.0)).py_2().px(px(10.0)).child(composer))
.child(
div()
.flex()
.items_center()
.gap_2()
.px(px(10.0))
.pt_1()
.pb_2()
.child(menu)
.child(div().flex_1())
.child(send),
);
// Fills the preview frame edge to edge, like the demo's `p-0!` on shadcn's preview.
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.flex()
.flex_col()
.gap_4()
.bg(bg)
.text_color(fg)
// shadcn's text-sm: 14px on a 20px line.
.text_sm()
.line_height(px(20.0))
.child(header)
.child(div().flex_1().min_h_0().child(body))
.child(div().px_8().pb_8().child(composer_box))
}
}
impl ChatPattern {
fn user_message(&self, ix: usize, exchange: &Exchange) -> impl IntoElement {
let enter = ElementId::NamedChild(Arc::new(ElementId::from(("enter", self.generation))), ix.to_string().into());
// The rise moves an inner box, so the item's own bounds, which the scroller anchors
// to, hold still while it animates.
div().flex_none().child(
div()
.relative()
.child(
Message::new().align(MessageAlign::End).child(
Bubble::new(("ask", ix))
.align(BubbleAlign::End)
.variant(BubbleVariant::Muted)
.child(exchange.ask.clone()),
),
)
.with_animation(enter, Animation::new(SLIDE_UP).with_easing(cubic_bezier(0.16, 1.0, 0.3, 1.0)), |this, t| {
this.opacity(t).top(px(SLIDE_UP_RISE * (1.0 - t)))
}),
)
}
fn assistant_message(
&self,
ix: usize,
exchange: &Exchange,
streaming: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> AnyElement {
let fg = cx.theme().foreground;
let rows = exchange.steps.iter().enumerate().map(|(step_ix, state)| {
let id = ElementId::from(("step", ix * 16 + step_ix));
let toggle = cx.listener(move |this, open: &bool, _, cx| {
if let Some(step) = this.exchanges.get_mut(ix).and_then(|exchange| exchange.steps.get_mut(step_ix)) {
step.open = Some(*open);
}
cx.notify();
});
match state.step {
Step::Reasoning(text) => {
let running = !state.done;
let line = TraceLine::new(("reasoning-line", ix * 16 + step_ix), if running { "Thinking" } else { "Thought" })
.icon(if running { LOADER_CIRCLE } else { CIRCLE_CHECK })
.spin(running)
.status(if running { TraceStatus::Running } else { TraceStatus::Done });
TraceCollapsible::new(id, state.open.unwrap_or(running), line)
.on_open_change(toggle)
.child(div().whitespace_normal().child(streamed(text, state.words)))
.into_any_element()
}
Step::Command(command, _, output) if state.done => {
let line = TraceLine::new(("command-line", ix * 16 + step_ix), format!("Ran {command}")).icon(TERMINAL);
TraceCollapsible::new(id, state.open.unwrap_or(false), line)
.on_open_change(toggle)
.child(small_code_block(output, cx))
.into_any_element()
}
Step::Command(command, _, _) => TraceLine::new(id, format!("Running {command}"))
.icon(TERMINAL)
.status(if streaming { TraceStatus::Running } else { TraceStatus::Error })
.into_any_element(),
}
});
let rows: Vec<AnyElement> = rows.collect();
let has_steps = !exchange.steps.is_empty();
let reply = streamed(exchange.reply(), exchange.words);
let blocks = markdown(&reply);
let count = blocks.len();
let mut code_ix = 0;
let rendered: Vec<AnyElement> = blocks
.into_iter()
.enumerate()
.map(|(block_ix, block)| {
let last = block_ix + 1 == count;
let element = match block {
Block::Paragraph(text) => paragraph(&text, window, cx),
Block::List(items) => div()
.flex()
.flex_col()
.children(items.into_iter().map(|item| {
div()
.flex()
.py_1()
.child(
div()
.w(px(20.0))
.flex_none()
.h(px(20.0))
.flex()
.items_center()
.child(div().size(px(5.0)).rounded_full().bg(fg)),
)
.child(div().flex_1().min_w_0().child(paragraph(&item, window, cx)))
}))
.into_any_element(),
Block::Code(language, code) => {
let key = (ix, code_ix);
code_ix += 1;
self.code_block(key, &language, &code, window, cx)
}
};
div().when(!last, |this| this.mb_4()).child(element).into_any_element()
})
.collect();
Message::new()
.gap(px(12.0))
.when(has_steps, |this| this.child(Trace::new().children(rows)))
.when(!rendered.is_empty(), |this| this.child(div().w_full().flex().flex_col().children(rendered)))
.into_any_element()
}
/// shadcn's markdown code block: muted panel, the language and a copy button, then numbered
/// lines in 14px Geist Mono that scroll sideways when too wide.
fn code_block(
&self,
key: (usize, usize),
language: &str,
code: &str,
window: &mut Window,
cx: &mut Context<Self>,
) -> AnyElement {
// Kept across renders so the edge fades follow the block's sideways scroll.
let scroll_id = ElementId::from(("code-scroll", (self.generation * 1024 + key.0 * 16 + key.1)));
let handle = window.use_keyed_state(scroll_id, cx, |_, _| ScrollHandle::new()).read(cx).clone();
let theme = cx.theme();
let (fg, muted_fg, muted) = (theme.foreground, theme.muted_foreground, theme.muted);
let copied = self.copied == Some(key);
let lines: Vec<&str> = if code.is_empty() { vec![""] } else { code.lines().collect() };
let offset = -handle.offset().x;
let overflow = handle.max_offset().x;
let source = code.to_string();
let numbers = div()
.flex()
.flex_col()
.flex_none()
.w(px(24.0))
.items_end()
.text_color(muted_fg)
.children((1..=lines.len()).map(|number| div().h(px(22.75)).child(number.to_string())));
let text = div().flex().flex_col().flex_none().children(lines.iter().map(|line| {
div().h(px(22.75)).flex().children(
code_tokens(line)
.into_iter()
.map(|(text, token)| div().whitespace_nowrap().text_color(token_color(token, theme)).child(text)),
)
}));
let fade = |angle: f32| {
div()
.absolute()
.top_0()
.bottom_0()
.w(px(40.0))
.bg(linear_gradient(angle, linear_color_stop(muted.opacity(0.0), 0.0), linear_color_stop(muted, 1.0)))
};
let body = div()
.relative()
.child(
div()
.id(("code", key.0 * 16 + key.1))
.track_scroll(&handle)
.overflow_x_scroll()
.on_scroll(cx.listener(|_, _, _, cx| cx.notify()))
.flex()
.gap_3()
.pt_2()
.pb(px(15.0))
.px(px(15.0))
.font_family(MONO)
.text_sm()
.line_height(px(22.75))
.child(numbers)
.child(text),
)
.when(offset > px(0.5), |this| this.child(fade(270.0).left_0()))
.when(offset < overflow - px(0.5), |this| this.child(fade(90.0).right_0()));
div()
.w_full()
.flex()
.flex_col()
.rounded(px(18.0))
.bg(muted)
// shadcn draws a 1px ring of foreground at 5%.
.border_1()
.border_color(fg.opacity(0.05))
.overflow_hidden()
.child(
div()
.flex()
.items_center()
.gap_2()
.pt(px(15.0))
.px(px(15.0))
.child(div().flex_1().text_sm().font_weight(FontWeight::MEDIUM).text_color(fg).child(language.to_string()))
.child(
div()
.id(("code-copy", key.0 * 16 + key.1))
.flex()
.items_center()
.justify_center()
.size(px(24.0))
.mr(px(-6.0))
// Like shadcn's `-my-1`, the button doesn't make the header taller.
.my(px(-4.0))
.rounded_full()
.cursor_pointer()
.hover(move |style| style.bg(fg.opacity(0.05)))
.on_click(cx.listener(move |this, _, _, cx| this.copy(key, source.clone(), cx)))
.child(icon(if copied { CHECK } else { COPY }).size(px(12.0)).text_color(muted_fg)),
),
)
.child(body)
.into_any_element()
}
}
/// shadcn's small code block for command output: muted panel, 12px mono text that wraps.
fn small_code_block(output: &'static str, cx: &App) -> impl IntoElement {
let theme = cx.theme();
let fg = theme.foreground;
div()
.max_h(px(256.0))
.overflow_hidden()
.p_3()
.rounded(px(14.0))
.bg(theme.muted)
.font_family(MONO)
.text_xs()
.line_height(px(19.5))
.text_color(fg)
.whitespace_normal()
.children(output.lines().map(move |line| match line.split_once('✓') {
// Geist Mono has no check mark, so draw the tick as an icon in its character cell.
Some((lead, rest)) => div()
.flex()
.items_center()
.min_h(px(19.5))
.child(lead.to_string())
.child(div().w(px(7.2)).flex().justify_center().child(icon(CHECK).size(px(10.0)).text_color(fg)))
.child(rest.to_string()),
None => div().min_h(px(19.5)).child(line.to_string()),
}))
}
/// A block of the reply's markdown.
enum Block {
Paragraph(String),
List(Vec<String>),
/// The language and the code so far.
Code(String, String),
}
/// Parses the subset of markdown the script uses. It runs on partly streamed text, so an open
/// code fence is a code block that is still growing.
fn markdown(source: &str) -> Vec<Block> {
let mut blocks = Vec::new();
let mut lines = source.lines().peekable();
while let Some(line) = lines.next() {
if let Some(language) = line.strip_prefix("```") {
let mut code = Vec::new();
for line in lines.by_ref() {
if line.starts_with("```") {
break;
}
code.push(line);
}
blocks.push(Block::Code(language.to_string(), code.join("\n")));
} else if let Some(item) = line.strip_prefix("- ").or_else(|| (line == "-").then_some("")) {
let mut items = vec![item.to_string()];
while let Some(next) = lines.peek().and_then(|line| line.strip_prefix("- ")) {
items.push(next.to_string());
lines.next();
}
blocks.push(Block::List(items));
} else if !line.trim().is_empty() {
blocks.push(Block::Paragraph(line.trim_end().to_string()));
}
}
blocks
}
/// The inline styles a paragraph can mix.
#[derive(Clone, Copy, PartialEq)]
enum Style {
Plain,
Bold,
Code,
}
/// Lays out one line of markdown (`code` and **bold** only) like a browser paragraph: words
/// wrap as units, and inline code is a padded chip that doesn't grow the line. An unclosed
/// marker styles the rest of the line, as the streaming renderer does.
fn paragraph(source: &str, window: &Window, cx: &App) -> AnyElement {
let theme = cx.theme();
let (fg, muted) = (theme.foreground, theme.muted);
// GPUI rounds each text element's width up to a whole pixel, so a line of one-word
// elements drifts wider than the browser's and wraps early. Each unit gets its exact
// shaped width instead.
let base = window.text_style().font();
let measure = |text: &str, style: Style| -> Pixels {
let (font, size) = match style {
Style::Plain => (base.clone(), px(14.0)),
Style::Bold => (Font { weight: FontWeight::SEMIBOLD, ..base.clone() }, px(14.0)),
Style::Code => (gpui::font(MONO), px(12.6)),
};
let run = TextRun { len: text.len(), font, color: fg, background_color: None, underline: None, strikethrough: None };
let width = window.text_system().shape_line(SharedString::from(text.to_string()), size, &[run], None).width;
if style == Style::Code { width + px(8.0) } else { width }
};
// Split into styled runs, then into words that keep their trailing space.
let mut atoms: Vec<(Style, String)> = Vec::new();
let mut style = Style::Plain;
let mut rest = source;
while !rest.is_empty() {
let next = [rest.find('`'), rest.find("**")].into_iter().flatten().min();
let end = next.unwrap_or(rest.len());
let run = &rest[..end];
if style == Style::Code {
if !run.is_empty() {
atoms.push((Style::Code, run.to_string()));
}
} else {
atoms.extend(run.split_inclusive(' ').map(|word| (style, word.to_string())));
}
rest = &rest[end..];
if let Some(stripped) = rest.strip_prefix('`') {
style = if style == Style::Code { Style::Plain } else { Style::Code };
rest = stripped;
} else if let Some(stripped) = rest.strip_prefix("**") {
if style != Style::Code {
style = if style == Style::Bold { Style::Plain } else { Style::Bold };
}
rest = stripped;
}
}
// A word only starts a new unit after whitespace, so `code` and the comma after it wrap
// together.
let mut units: Vec<Vec<(Style, String)>> = Vec::new();
for atom in atoms {
let after_space = units
.last()
.and_then(|unit| unit.last())
.is_none_or(|(_, text)| text.ends_with(' '));
if atom.1.trim().is_empty() {
match units.last_mut() {
Some(unit) => unit.push(atom),
None => units.push(vec![atom]),
}
} else if after_space {
units.push(vec![atom]);
} else if let Some(unit) = units.last_mut() {
unit.push(atom);
}
}
div()
.flex()
.flex_wrap()
.w_full()
.line_height(px(20.0))
.text_color(fg)
.children(units.into_iter().map(|unit| {
let width: Pixels = unit.iter().map(|(style, text)| measure(text, *style)).fold(px(0.0), |sum, w| sum + w);
div().flex().flex_none().w(width).children(unit.into_iter().map(|(style, text)| match style {
// shadcn's inline code: 12.6px mono, 2px/4px padding, 6px corners. Its 21px box
// hangs below the 20px line rather than growing it.
Style::Code => div()
.relative()
.h(px(20.0))
.px(px(4.0))
.flex()
.items_center()
.font_family(MONO)
.text_size(px(12.6))
.child(div().absolute().top_0().left_0().right_0().h(px(21.0)).rounded(px(6.0)).bg(muted))
.child(div().relative().whitespace_nowrap().child(text))
.into_any_element(),
Style::Bold => div()
.whitespace_nowrap()
.font_weight(FontWeight::SEMIBOLD)
.child(text)
.into_any_element(),
Style::Plain => div().whitespace_nowrap().child(text).into_any_element(),
}))
}))
.into_any_element()
}Installation
Add the components
$ cargo hyuskui add bubble button dropdown-menu input message message-scroller popover textarea tooltip trace iconsUses Bubble, Button, Dropdown Menu, Input, Message, Message Scroller, Popover, Textarea, Tooltip and Trace.
Copy the pattern
Paste the code into
src/ai/chat.rsand declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.src/ai/chat.rs use std::{sync::Arc, time::Duration}; use gpui::{ div, linear_color_stop, linear_gradient, prelude::*, px, AnyElement, App, Animation, AnimationExt, ClipboardItem, Context, ElementId, Entity, Font, FontWeight, Hsla, KeyDownEvent, Pixels, ScrollHandle, SharedString, Subscription, Task, TextRun, Window, }; use crate::icons::{ icon, ARROW_UP, CHECK, CIRCLE_CHECK, COPY, GLOBE, LOADER_CIRCLE, MESSAGE_CIRCLE_DASHED, PAPERCLIP, PLUS, ROTATE_CW, TELESCOPE, TERMINAL, }; use crate::theme::{ActiveTheme, Theme}; use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant}; use crate::ui::button::{Button, ButtonSize, ButtonVariant}; use crate::ui::dropdown_menu::{DropdownMenu, MenuItem}; use crate::ui::input::{InputEvent, TextInput}; use crate::ui::message::{Message, MessageAlign}; use crate::ui::message_scroller::MessageScroller; use crate::ui::popover::{Align, Side}; use crate::ui::textarea::Textarea; use crate::ui::tooltip::Tooltip; use crate::ui::trace::{Trace, TraceCollapsible, TraceLine, TraceStatus}; const MONO: &str = "Geist Mono"; /// The mock transport's pace: every chunk of text waits 16ms. const CHUNK: Duration = Duration::from_millis(16); /// `.sleep(600)`: the beat between a sent message and the agent starting. const START: Duration = Duration::from_millis(600); /// `writer.sleep(400)` after the reasoning, `writer.sleep(500)` after a command. const AFTER_REASONING: Duration = Duration::from_millis(400); const AFTER_COMMAND: Duration = Duration::from_millis(500); /// shadcn's "slide-up" message animation: a sent message rises 10px into place as it fades in, /// over 260ms on `cubic-bezier(0.16, 1, 0.3, 1)`. const SLIDE_UP: Duration = Duration::from_millis(260); const SLIDE_UP_RISE: f32 = 10.0; /// The chat demo runs in shadcn's `theme-blue`: Tailwind blue-700 with blue-50 text. const BLUE: u32 = 0x1447e6; const BLUE_FOREGROUND: u32 = 0xeff6ff; const FALLBACK: &str = "This demo only knows the scripted turns. Press reset to start over."; /// A CSS cubic-bézier timing function: solves x for `t` by Newton's method and returns y. fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 { move |t| { let at = |a: f32, b: f32, s: f32| 3.0 * a * s * (1.0 - s).powi(2) + 3.0 * b * s * s * (1.0 - s) + s.powi(3); let slope = |a: f32, b: f32, s: f32| 3.0 * a * (1.0 - s).powi(2) + 6.0 * (b - a) * s * (1.0 - s) + 3.0 * (1.0 - b) * s * s; let mut s = t.clamp(0.0, 1.0); for _ in 0..8 { let dx = slope(x1, x2, s); if dx.abs() < 1e-6 { break; } s = (s - (at(x1, x2, s) - t) / dx).clamp(0.0, 1.0); } at(y1, y2, s) } } /// One thing the agent does before it answers. #[derive(Clone, Copy)] enum Step { Reasoning(&'static str), /// A command, how long it runs, and what it prints. Command(&'static str, Duration, &'static str), } struct Turn { ask: &'static str, steps: &'static [Step], reply: &'static str, } const SCRIPT: [Turn; 3] = [ Turn { ask: "Add a dark mode toggle to the settings page.", steps: &[ Step::Reasoning( "I need to know how themes are set up before I add a toggle. If next-themes is already in the layout, the toggle only has to call setTheme.", ), Step::Command("rg -l ThemeProvider app", Duration::from_millis(800), "app/layout.tsx"), ], reply: "next-themes is already set up in `app/layout.tsx`, so the toggle only has to call `setTheme`. **Changes** - Added `components/mode-toggle.tsx` with a Light and Dark option. - Put `<ModeToggle />` next to the Appearance heading in `app/settings/page.tsx`. ```tsx const { setTheme } = useTheme() ``` ", }, Turn { ask: "Make it follow the system setting by default.", steps: &[ Step::Reasoning("The default theme lives on the ThemeProvider. I should check what it is set to now."), Step::Command( "rg -n defaultTheme app/layout.tsx", Duration::from_millis(800), "12: <ThemeProvider attribute=\"class\" defaultTheme=\"light\">", ), ], reply: "It was set to `light`. I updated the `ThemeProvider` in `app/layout.tsx`: ```tsx <ThemeProvider attribute=\"class\" defaultTheme=\"system\" enableSystem> ``` New visitors now get the theme from their OS. The toggle also has a **System** option, so anyone who picked Light or Dark can switch back. ", }, Turn { ask: "Run the build before I ship it.", steps: &[Step::Command( "pnpm build", Duration::from_millis(1600), "▲ Next.js 16.0.0\n\n✓ Compiled successfully in 4.2s\n✓ Linting and checking validity of types\n✓ Generating static pages (12/12)", )], reply: "The build passes, so it is ready to ship. - Compiled in **4.2s**. - No lint or type errors. - Generated all **12** static pages. ", }, ]; /// shiki's tsx tokens for each scripted code line, so a partly streamed line keeps its colors. #[derive(Clone, Copy)] enum Token { Plain, Keyword, Constant, Function, String, } const CODE_LINES: [&[(&str, Token)]; 2] = [ &[ ("const", Token::Keyword), (" { ", Token::Plain), ("setTheme", Token::Constant), (" } ", Token::Plain), ("=", Token::Keyword), (" ", Token::Plain), ("useTheme", Token::Function), ("()", Token::Plain), ], &[ ("<", Token::Plain), ("ThemeProvider", Token::Constant), (" ", Token::Plain), ("attribute", Token::Function), ("=", Token::Keyword), ("\"class\"", Token::String), (" ", Token::Plain), ("defaultTheme", Token::Function), ("=", Token::Keyword), ("\"system\"", Token::String), (" ", Token::Plain), ("enableSystem", Token::Function), (">", Token::Plain), ], ]; fn token_color(token: Token, theme: &Theme) -> Hsla { let dark = theme.background.l < 0.5; let hex = match (token, dark) { (Token::Plain, false) => 0x24292e, (Token::Keyword, false) => 0xd73a49, (Token::Constant, false) => 0x005cc5, (Token::Function, false) => 0x6f42c1, (Token::String, false) => 0x032f62, (Token::Plain, true) => 0xe1e4e8, (Token::Keyword, true) => 0xf97583, (Token::Constant, true) => 0x79b8ff, (Token::Function, true) => 0xb392f0, (Token::String, true) => 0x9ecbff, }; gpui::rgb(hex).into() } /// Colors a code line, which may be a prefix of a scripted one while it streams. fn code_tokens(line: &str) -> Vec<(String, Token)> { for tokens in CODE_LINES { let full: String = tokens.iter().map(|(text, _)| *text).collect(); if full.starts_with(line) { let mut left = line.len(); let mut out = Vec::new(); for (text, token) in tokens { if left == 0 { break; } let take = text.len().min(left); out.push((text[..take].to_string(), *token)); left -= take; } return out; } } vec![(line.to_string(), Token::Plain)] } /// Splits like the mock transport, `/\S+\s*/g`: each chunk is a word and the whitespace after it. fn chunks(text: &str) -> Vec<&str> { let mut out = Vec::new(); let mut start = None; let mut in_space = false; for (ix, ch) in text.char_indices() { let space = ch.is_whitespace(); match start { None if !space => { start = Some(ix); in_space = false; } Some(from) if !space && in_space => { out.push(&text[from..ix]); start = Some(ix); in_space = false; } Some(_) if space => in_space = true, _ => {} } } if let Some(from) = start { out.push(&text[from..]); } out } fn streamed(text: &str, count: usize) -> String { chunks(text).into_iter().take(count).collect() } /// A step the agent has started. struct StepState { step: Step, /// Reasoning chunks shown so far. words: usize, done: bool, /// Set once the reader opens or closes the row; until then a reasoning row is open while it /// runs, and a command's output starts closed. open: Option<bool>, } /// One exchange: the sent message and, once the agent starts, its reply. struct Exchange { ask: String, /// `None` for a message the script doesn't know; it gets the fallback reply. script: Option<usize>, started: bool, steps: Vec<StepState>, /// Reply chunks shown so far. words: usize, } impl Exchange { fn reply(&self) -> &'static str { self.script.map_or(FALLBACK, |ix| SCRIPT[ix].reply) } } #[derive(Default)] pub struct ChatPattern { composer: Option<Entity<TextInput>>, _change: Option<Subscription>, /// What the reader typed, if it differs from the next scripted message. draft: Option<String>, exchanges: Vec<Exchange>, stream: Option<Task<()>>, /// Bumped on reset so the slide-up animations of a new thread start fresh. generation: usize, menu_open: bool, copied: Option<(usize, usize)>, copy_reset: Option<Task<()>>, } impl ChatPattern { fn busy(&self) -> bool { self.stream.is_some() } /// The next scripted message after the thread so far. fn next_scripted(&self) -> Option<usize> { let sent = self.exchanges.iter().filter_map(|exchange| exchange.script).max(); let next = sent.map_or(0, |ix| ix + 1); (next < SCRIPT.len()).then_some(next) } /// What the composer shows: the reader's draft, else the next scripted message. fn composer_text(&self) -> String { self.draft .clone() .unwrap_or_else(|| self.next_scripted().map_or(String::new(), |ix| SCRIPT[ix].ask.to_string())) } fn sync_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) { let text = self.composer_text(); if let Some(composer) = self.composer.clone() { if composer.read(cx).text().as_ref() != text { composer.update(cx, |input, cx| input.set_text(text, window, cx)); } } } fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) { self.stream = None; self.exchanges.clear(); self.draft = None; self.generation += 1; self.sync_composer(window, cx); cx.notify(); } fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) { let text = self.composer_text(); if self.busy() || text.trim().is_empty() { return; } let script = match &self.draft { None => self.next_scripted(), // A typed message only follows the script if it is the scripted one. Some(draft) => self.next_scripted().filter(|&ix| SCRIPT[ix].ask == draft.trim()), }; self.exchanges.push(Exchange { ask: text.trim().to_string(), script, started: false, steps: Vec::new(), words: 0, }); let ix = self.exchanges.len() - 1; self.draft = None; self.sync_composer(window, cx); self.stream = Some(cx.spawn(async move |this, cx| { let update = |cx: &mut gpui::AsyncApp, f: &dyn Fn(&mut Exchange)| { this.update(cx, |this, cx| { if let Some(exchange) = this.exchanges.get_mut(ix) { f(exchange); } cx.notify(); }) .is_ok() }; let steps: &[Step] = script.map_or(&[], |ix| SCRIPT[ix].steps); if script.is_some() { cx.background_executor().timer(START).await; } if !update(cx, &|exchange| exchange.started = true) { return; } for (step_ix, step) in steps.iter().enumerate() { let push = |exchange: &mut Exchange| { exchange.steps.push(StepState { step: *step, words: 0, done: false, open: None }) }; if !update(cx, &push) { return; } match *step { Step::Reasoning(text) => { for _ in chunks(text) { cx.background_executor().timer(CHUNK).await; if !update(cx, &|exchange| exchange.steps[step_ix].words += 1) { return; } } if !update(cx, &|exchange| exchange.steps[step_ix].done = true) { return; } cx.background_executor().timer(AFTER_REASONING).await; } Step::Command(_, runs, _) => { cx.background_executor().timer(runs).await; if !update(cx, &|exchange| exchange.steps[step_ix].done = true) { return; } cx.background_executor().timer(AFTER_COMMAND).await; } } } let reply = script.map_or(FALLBACK, |ix| SCRIPT[ix].reply); for _ in chunks(reply) { cx.background_executor().timer(CHUNK).await; if !update(cx, &|exchange| exchange.words += 1) { return; } } this.update(cx, |this, cx| { this.stream = None; cx.notify(); }) .ok(); })); cx.notify(); } fn copy(&mut self, key: (usize, usize), code: String, cx: &mut Context<Self>) { cx.write_to_clipboard(ClipboardItem::new_string(code)); self.copied = Some(key); self.copy_reset = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(Duration::from_secs(2)).await; this.update(cx, |this, cx| { this.copied = None; cx.notify(); }) .ok(); })); cx.notify(); } } impl Render for ChatPattern { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { if self.composer.is_none() { let composer = cx.new(|cx| Textarea::new(cx).multi_line(1).placeholder("Ask the agent...").bare()); self._change = Some(cx.subscribe(&composer, |this: &mut Self, composer, _: &InputEvent, cx| { let text = composer.read(cx).text().to_string(); let scripted = this.next_scripted().map(|ix| SCRIPT[ix].ask); this.draft = (scripted != Some(text.as_str())).then_some(text); cx.notify(); })); self.composer = Some(composer); self.sync_composer(window, cx); } let Some(composer) = self.composer.clone() else { return div(); }; let theme = cx.theme(); let (fg, muted_fg, muted, border, bg, input) = (theme.foreground, theme.muted_foreground, theme.muted, theme.border, theme.background, theme.input); let busy = self.busy(); let can_send = !busy && !self.composer_text().trim().is_empty(); let header = div() .flex() .items_start() .justify_between() .gap_4() .p_8() .pb_4() .child( div() .flex() .flex_col() .gap_1() .child( div() .text_size(px(15.0)) .line_height(px(26.25)) .font_weight(FontWeight::MEDIUM) .text_color(fg) .child("New Thread"), ) .child(div().text_sm().text_color(muted_fg).child("Ask the agent to change your code.")), ) .child( Tooltip::new("reset-tip", "Reset").trigger( Button::new("reset", "") .variant(ButtonVariant::Outline) .size(ButtonSize::Sm) .icon_only() .rounded_full() .disabled(busy) .leading(icon(ROTATE_CW).size(px(16.0)).text_color(fg)) .on_click(cx.listener(|this, _, window, cx| this.reset(window, cx))), ), ); let body = if self.exchanges.is_empty() { // shadcn's `Empty` with an icon tile, centered in the thread's space. div() .size_full() .flex() .items_center() .justify_center() .p_12() .child( div() .max_w(px(384.0)) .flex() .flex_col() .items_center() .gap_2() .child( div() .mb_2() .flex() .items_center() .justify_center() .size(px(40.0)) .rounded(px(14.0)) .bg(muted) .child(icon(MESSAGE_CIRCLE_DASHED).size(px(20.0)).text_color(fg)), ) .child( div() .text_size(px(18.0)) .line_height(px(28.0)) .font_weight(FontWeight::MEDIUM) .text_color(fg) .child("What should we build?"), ) .child( // shadcn balances the description's lines (`text-balance`); this // width breaks it in the same place. div() .max_w(px(305.0)) .text_sm() .line_height(px(22.75)) .text_center() .text_color(muted_fg) .child("The agent can read your code, run commands and make changes. Press send to start."), ), ) .into_any_element() } else { let mut items: Vec<AnyElement> = Vec::new(); let mut anchor = None; let last = self.exchanges.len() - 1; for (ix, exchange) in self.exchanges.iter().enumerate() { // The reader's messages are `scrollAnchor` items: each one sent is placed near // the top while its reply streams in below. anchor = Some(items.len()); items.push(self.user_message(ix, exchange).into_any_element()); if exchange.started { items.push(self.assistant_message(ix, exchange, busy && ix == last, window, cx)); } } MessageScroller::new(("thread", self.generation)) .size_full() .auto_scroll(false) .scroll_anchor(anchor) .jump_label("") .content_gap(px(24.0)) .content_padding(px(32.0), px(0.0)) .children(items) .into_any_element() }; let blue: Hsla = gpui::rgb(BLUE).into(); let menu = DropdownMenu::new("context-menu", self.menu_open) .side(Side::Top) .align(Align::Start) .width(px(176.0)) .trigger( div() .id("add-context") .flex() .items_center() .justify_center() .size(px(32.0)) .rounded_full() .border_1() .border_color(border) .bg(if self.menu_open { muted } else { bg }) .cursor_pointer() .hover(move |style| style.bg(muted)) .child(icon(PLUS).size(px(16.0)).text_color(if self.menu_open { fg } else { muted_fg })), ) .on_open_change(cx.listener(|this, open: &bool, _, cx| { this.menu_open = *open; cx.notify(); })) .item(MenuItem::new("Add Photos & Files").icon(icon(PAPERCLIP).size(px(16.0)).text_color(muted_fg))) .separator() .item(MenuItem::new("Deep Research").icon(icon(TELESCOPE).size(px(16.0)).text_color(muted_fg))) .item(MenuItem::new("Web Search").icon(icon(GLOBE).size(px(16.0)).text_color(muted_fg))); let send = div() .id("send") .flex() .items_center() .justify_center() .size(px(32.0)) .rounded_full() .bg(blue) .child(icon(ARROW_UP).size(px(16.0)).text_color(gpui::rgb(BLUE_FOREGROUND))) .map(|this| { if can_send { this.cursor_pointer() .hover(move |style| style.bg(blue.opacity(0.8))) .active(|style| style.top(px(1.0))) .on_click(cx.listener(|this, _, window, cx| this.submit(window, cx))) } else { this.opacity(0.5).cursor_not_allowed() } }); let composer_box = div() .w_full() .flex() .flex_col() .rounded(px(18.0)) .border_1() .border_color(gpui::transparent_black()) .bg(input.opacity(0.5)) // Enter sends and Shift+Enter breaks the line, like the form's `onKeyDown`. .capture_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { let keystroke = &event.keystroke; if keystroke.key == "enter" && !keystroke.modifiers.shift { cx.stop_propagation(); this.submit(window, cx); } })) .child(div().min_h(px(56.0)).py_2().px(px(10.0)).child(composer)) .child( div() .flex() .items_center() .gap_2() .px(px(10.0)) .pt_1() .pb_2() .child(menu) .child(div().flex_1()) .child(send), ); // Fills the preview frame edge to edge, like the demo's `p-0!` on shadcn's preview. div() .absolute() .top_0() .left_0() .right_0() .bottom_0() .flex() .flex_col() .gap_4() .bg(bg) .text_color(fg) // shadcn's text-sm: 14px on a 20px line. .text_sm() .line_height(px(20.0)) .child(header) .child(div().flex_1().min_h_0().child(body)) .child(div().px_8().pb_8().child(composer_box)) } } impl ChatPattern { fn user_message(&self, ix: usize, exchange: &Exchange) -> impl IntoElement { let enter = ElementId::NamedChild(Arc::new(ElementId::from(("enter", self.generation))), ix.to_string().into()); // The rise moves an inner box, so the item's own bounds, which the scroller anchors // to, hold still while it animates. div().flex_none().child( div() .relative() .child( Message::new().align(MessageAlign::End).child( Bubble::new(("ask", ix)) .align(BubbleAlign::End) .variant(BubbleVariant::Muted) .child(exchange.ask.clone()), ), ) .with_animation(enter, Animation::new(SLIDE_UP).with_easing(cubic_bezier(0.16, 1.0, 0.3, 1.0)), |this, t| { this.opacity(t).top(px(SLIDE_UP_RISE * (1.0 - t))) }), ) } fn assistant_message( &self, ix: usize, exchange: &Exchange, streaming: bool, window: &mut Window, cx: &mut Context<Self>, ) -> AnyElement { let fg = cx.theme().foreground; let rows = exchange.steps.iter().enumerate().map(|(step_ix, state)| { let id = ElementId::from(("step", ix * 16 + step_ix)); let toggle = cx.listener(move |this, open: &bool, _, cx| { if let Some(step) = this.exchanges.get_mut(ix).and_then(|exchange| exchange.steps.get_mut(step_ix)) { step.open = Some(*open); } cx.notify(); }); match state.step { Step::Reasoning(text) => { let running = !state.done; let line = TraceLine::new(("reasoning-line", ix * 16 + step_ix), if running { "Thinking" } else { "Thought" }) .icon(if running { LOADER_CIRCLE } else { CIRCLE_CHECK }) .spin(running) .status(if running { TraceStatus::Running } else { TraceStatus::Done }); TraceCollapsible::new(id, state.open.unwrap_or(running), line) .on_open_change(toggle) .child(div().whitespace_normal().child(streamed(text, state.words))) .into_any_element() } Step::Command(command, _, output) if state.done => { let line = TraceLine::new(("command-line", ix * 16 + step_ix), format!("Ran {command}")).icon(TERMINAL); TraceCollapsible::new(id, state.open.unwrap_or(false), line) .on_open_change(toggle) .child(small_code_block(output, cx)) .into_any_element() } Step::Command(command, _, _) => TraceLine::new(id, format!("Running {command}")) .icon(TERMINAL) .status(if streaming { TraceStatus::Running } else { TraceStatus::Error }) .into_any_element(), } }); let rows: Vec<AnyElement> = rows.collect(); let has_steps = !exchange.steps.is_empty(); let reply = streamed(exchange.reply(), exchange.words); let blocks = markdown(&reply); let count = blocks.len(); let mut code_ix = 0; let rendered: Vec<AnyElement> = blocks .into_iter() .enumerate() .map(|(block_ix, block)| { let last = block_ix + 1 == count; let element = match block { Block::Paragraph(text) => paragraph(&text, window, cx), Block::List(items) => div() .flex() .flex_col() .children(items.into_iter().map(|item| { div() .flex() .py_1() .child( div() .w(px(20.0)) .flex_none() .h(px(20.0)) .flex() .items_center() .child(div().size(px(5.0)).rounded_full().bg(fg)), ) .child(div().flex_1().min_w_0().child(paragraph(&item, window, cx))) })) .into_any_element(), Block::Code(language, code) => { let key = (ix, code_ix); code_ix += 1; self.code_block(key, &language, &code, window, cx) } }; div().when(!last, |this| this.mb_4()).child(element).into_any_element() }) .collect(); Message::new() .gap(px(12.0)) .when(has_steps, |this| this.child(Trace::new().children(rows))) .when(!rendered.is_empty(), |this| this.child(div().w_full().flex().flex_col().children(rendered))) .into_any_element() } /// shadcn's markdown code block: muted panel, the language and a copy button, then numbered /// lines in 14px Geist Mono that scroll sideways when too wide. fn code_block( &self, key: (usize, usize), language: &str, code: &str, window: &mut Window, cx: &mut Context<Self>, ) -> AnyElement { // Kept across renders so the edge fades follow the block's sideways scroll. let scroll_id = ElementId::from(("code-scroll", (self.generation * 1024 + key.0 * 16 + key.1))); let handle = window.use_keyed_state(scroll_id, cx, |_, _| ScrollHandle::new()).read(cx).clone(); let theme = cx.theme(); let (fg, muted_fg, muted) = (theme.foreground, theme.muted_foreground, theme.muted); let copied = self.copied == Some(key); let lines: Vec<&str> = if code.is_empty() { vec![""] } else { code.lines().collect() }; let offset = -handle.offset().x; let overflow = handle.max_offset().x; let source = code.to_string(); let numbers = div() .flex() .flex_col() .flex_none() .w(px(24.0)) .items_end() .text_color(muted_fg) .children((1..=lines.len()).map(|number| div().h(px(22.75)).child(number.to_string()))); let text = div().flex().flex_col().flex_none().children(lines.iter().map(|line| { div().h(px(22.75)).flex().children( code_tokens(line) .into_iter() .map(|(text, token)| div().whitespace_nowrap().text_color(token_color(token, theme)).child(text)), ) })); let fade = |angle: f32| { div() .absolute() .top_0() .bottom_0() .w(px(40.0)) .bg(linear_gradient(angle, linear_color_stop(muted.opacity(0.0), 0.0), linear_color_stop(muted, 1.0))) }; let body = div() .relative() .child( div() .id(("code", key.0 * 16 + key.1)) .track_scroll(&handle) .overflow_x_scroll() .on_scroll(cx.listener(|_, _, _, cx| cx.notify())) .flex() .gap_3() .pt_2() .pb(px(15.0)) .px(px(15.0)) .font_family(MONO) .text_sm() .line_height(px(22.75)) .child(numbers) .child(text), ) .when(offset > px(0.5), |this| this.child(fade(270.0).left_0())) .when(offset < overflow - px(0.5), |this| this.child(fade(90.0).right_0())); div() .w_full() .flex() .flex_col() .rounded(px(18.0)) .bg(muted) // shadcn draws a 1px ring of foreground at 5%. .border_1() .border_color(fg.opacity(0.05)) .overflow_hidden() .child( div() .flex() .items_center() .gap_2() .pt(px(15.0)) .px(px(15.0)) .child(div().flex_1().text_sm().font_weight(FontWeight::MEDIUM).text_color(fg).child(language.to_string())) .child( div() .id(("code-copy", key.0 * 16 + key.1)) .flex() .items_center() .justify_center() .size(px(24.0)) .mr(px(-6.0)) // Like shadcn's `-my-1`, the button doesn't make the header taller. .my(px(-4.0)) .rounded_full() .cursor_pointer() .hover(move |style| style.bg(fg.opacity(0.05))) .on_click(cx.listener(move |this, _, _, cx| this.copy(key, source.clone(), cx))) .child(icon(if copied { CHECK } else { COPY }).size(px(12.0)).text_color(muted_fg)), ), ) .child(body) .into_any_element() } } /// shadcn's small code block for command output: muted panel, 12px mono text that wraps. fn small_code_block(output: &'static str, cx: &App) -> impl IntoElement { let theme = cx.theme(); let fg = theme.foreground; div() .max_h(px(256.0)) .overflow_hidden() .p_3() .rounded(px(14.0)) .bg(theme.muted) .font_family(MONO) .text_xs() .line_height(px(19.5)) .text_color(fg) .whitespace_normal() .children(output.lines().map(move |line| match line.split_once('✓') { // Geist Mono has no check mark, so draw the tick as an icon in its character cell. Some((lead, rest)) => div() .flex() .items_center() .min_h(px(19.5)) .child(lead.to_string()) .child(div().w(px(7.2)).flex().justify_center().child(icon(CHECK).size(px(10.0)).text_color(fg))) .child(rest.to_string()), None => div().min_h(px(19.5)).child(line.to_string()), })) } /// A block of the reply's markdown. enum Block { Paragraph(String), List(Vec<String>), /// The language and the code so far. Code(String, String), } /// Parses the subset of markdown the script uses. It runs on partly streamed text, so an open /// code fence is a code block that is still growing. fn markdown(source: &str) -> Vec<Block> { let mut blocks = Vec::new(); let mut lines = source.lines().peekable(); while let Some(line) = lines.next() { if let Some(language) = line.strip_prefix("```") { let mut code = Vec::new(); for line in lines.by_ref() { if line.starts_with("```") { break; } code.push(line); } blocks.push(Block::Code(language.to_string(), code.join("\n"))); } else if let Some(item) = line.strip_prefix("- ").or_else(|| (line == "-").then_some("")) { let mut items = vec![item.to_string()]; while let Some(next) = lines.peek().and_then(|line| line.strip_prefix("- ")) { items.push(next.to_string()); lines.next(); } blocks.push(Block::List(items)); } else if !line.trim().is_empty() { blocks.push(Block::Paragraph(line.trim_end().to_string())); } } blocks } /// The inline styles a paragraph can mix. #[derive(Clone, Copy, PartialEq)] enum Style { Plain, Bold, Code, } /// Lays out one line of markdown (`code` and **bold** only) like a browser paragraph: words /// wrap as units, and inline code is a padded chip that doesn't grow the line. An unclosed /// marker styles the rest of the line, as the streaming renderer does. fn paragraph(source: &str, window: &Window, cx: &App) -> AnyElement { let theme = cx.theme(); let (fg, muted) = (theme.foreground, theme.muted); // GPUI rounds each text element's width up to a whole pixel, so a line of one-word // elements drifts wider than the browser's and wraps early. Each unit gets its exact // shaped width instead. let base = window.text_style().font(); let measure = |text: &str, style: Style| -> Pixels { let (font, size) = match style { Style::Plain => (base.clone(), px(14.0)), Style::Bold => (Font { weight: FontWeight::SEMIBOLD, ..base.clone() }, px(14.0)), Style::Code => (gpui::font(MONO), px(12.6)), }; let run = TextRun { len: text.len(), font, color: fg, background_color: None, underline: None, strikethrough: None }; let width = window.text_system().shape_line(SharedString::from(text.to_string()), size, &[run], None).width; if style == Style::Code { width + px(8.0) } else { width } }; // Split into styled runs, then into words that keep their trailing space. let mut atoms: Vec<(Style, String)> = Vec::new(); let mut style = Style::Plain; let mut rest = source; while !rest.is_empty() { let next = [rest.find('`'), rest.find("**")].into_iter().flatten().min(); let end = next.unwrap_or(rest.len()); let run = &rest[..end]; if style == Style::Code { if !run.is_empty() { atoms.push((Style::Code, run.to_string())); } } else { atoms.extend(run.split_inclusive(' ').map(|word| (style, word.to_string()))); } rest = &rest[end..]; if let Some(stripped) = rest.strip_prefix('`') { style = if style == Style::Code { Style::Plain } else { Style::Code }; rest = stripped; } else if let Some(stripped) = rest.strip_prefix("**") { if style != Style::Code { style = if style == Style::Bold { Style::Plain } else { Style::Bold }; } rest = stripped; } } // A word only starts a new unit after whitespace, so `code` and the comma after it wrap // together. let mut units: Vec<Vec<(Style, String)>> = Vec::new(); for atom in atoms { let after_space = units .last() .and_then(|unit| unit.last()) .is_none_or(|(_, text)| text.ends_with(' ')); if atom.1.trim().is_empty() { match units.last_mut() { Some(unit) => unit.push(atom), None => units.push(vec![atom]), } } else if after_space { units.push(vec![atom]); } else if let Some(unit) = units.last_mut() { unit.push(atom); } } div() .flex() .flex_wrap() .w_full() .line_height(px(20.0)) .text_color(fg) .children(units.into_iter().map(|unit| { let width: Pixels = unit.iter().map(|(style, text)| measure(text, *style)).fold(px(0.0), |sum, w| sum + w); div().flex().flex_none().w(width).children(unit.into_iter().map(|(style, text)| match style { // shadcn's inline code: 12.6px mono, 2px/4px padding, 6px corners. Its 21px box // hangs below the 20px line rather than growing it. Style::Code => div() .relative() .h(px(20.0)) .px(px(4.0)) .flex() .items_center() .font_family(MONO) .text_size(px(12.6)) .child(div().absolute().top_0().left_0().right_0().h(px(21.0)).rounded(px(6.0)).bg(muted)) .child(div().relative().whitespace_nowrap().child(text)) .into_any_element(), Style::Bold => div() .whitespace_nowrap() .font_weight(FontWeight::SEMIBOLD) .child(text) .into_any_element(), Style::Plain => div().whitespace_nowrap().child(text).into_any_element(), })) })) .into_any_element() }