T23a: AI chat, messages

- messages: yours in a quiet bubble, the assistant's as prose beside its mark,
  system notes, errors; avatars, headers with model and time, footers
- MessageList over gpui's bottom-aligned list: drawn near the view, held at the
  newest, counting arrivals while away; a way back down; day separators
- streaming text and markdown reveal toward the text as it grows, with a caret;
  a blinking cursor before the first words
- CodeBlock with language, copy, run, apply, download and folding;
  MarkdownRenderer::code lets messages draw fences with it
- pictures, grids, files, voice notes, video over host frames, link previews
- quotes, actions, an editor that takes focus, versions, regenerate, stop and
  continue
- errors with retry, a rate limit counting down, feedback, thinking blocks
- gallery: the AI Chat page with scripted states
This commit is contained in:
ZacharyZhang-NY committed 2026-09-26 05:35:09 -04:00
1 parent 03f6ceb583
commit c0afce2507
21 files changed
+3376 -34

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="560" height="160" viewBox="0 0 560 160">
<rect width="560" height="160" rx="10" fill="#FBFAF7"/>
<defs>
<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#8C8A85"/>
</marker>
</defs>
<g font-family="Helvetica, Arial, sans-serif" font-size="14" text-anchor="middle">
<rect x="28" y="54" width="132" height="52" rx="8" fill="#FFFFFF" stroke="#C9C6BF"/>
<text x="94" y="85" fill="#2B2A28">Base color</text>
<rect x="214" y="54" width="132" height="52" rx="8" fill="#FFFFFF" stroke="#C9C6BF"/>
<text x="280" y="78" fill="#2B2A28">Lift</text>
<text x="280" y="96" fill="#8C8A85" font-size="12">t = 0.5 or 0.62</text>
<rect x="400" y="54" width="132" height="52" rx="8" fill="#FFFFFF" stroke="#C9C6BF"/>
<text x="466" y="85" fill="#2B2A28">Theme accent</text>
<line x1="160" y1="80" x2="210" y2="80" stroke="#8C8A85" stroke-width="1.5" marker-end="url(#arrow)"/>
<line x1="346" y1="80" x2="396" y2="80" stroke="#8C8A85" stroke-width="1.5" marker-end="url(#arrow)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+141
View File
@@ -0,0 +1,141 @@
use std::time::Duration;
use ely_gpui_component::{
chat::{
AudioMessage, CodeBlock, FileMessage, ImageGrid, ImageMessage, LinkPreviewCard,
VideoMessage,
},
documents::MarkdownRenderer,
};
use gpui::{App, IntoElement, ParentElement, Styled, Window, div, px};
use crate::ui::{keep, noise, section, set};
macro_rules! asset {
($name:literal) => {
concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/gallery/assets/",
$name
)
};
}
const SHORT: &str = "fn lift(c: f32, t: f32) -> f32 {\n c + t * (1.0 - c)\n}";
const LONG: &str = "/// Every accent in the library, lifted for its theme.\npub struct Accents {\n base: Hsla,\n light: f32,\n dark: f32,\n}\n\nimpl Accents {\n pub fn new(base: Hsla) -> Self {\n Self { base, light: 0.5, dark: 0.62 }\n }\n\n /// The accent as the theme shows it.\n pub fn shown(&self, dark: bool) -> Hsla {\n let t = if dark { self.dark } else { self.light };\n lift(self.base, t)\n }\n\n /// A hover, one step louder.\n pub fn hover(&self, dark: bool) -> Hsla {\n lift(self.shown(dark), 0.08)\n }\n\n /// A press, two steps louder.\n pub fn press(&self, dark: bool) -> Hsla {\n lift(self.shown(dark), 0.16)\n }\n}";
pub fn code(_: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
section(
"CodeBlock",
"Code in a message: its language, copy, and the host's run, apply and download. Long code folds to its first lines until opened.",
cx,
)
.child(
div()
.w(px(620.))
.flex()
.flex_col()
.gap_4()
.child(
CodeBlock::new("chat-code-short", SHORT)
.language("rust")
.on_run(|_, _| log::info!("gallery: run"))
.on_apply(|_, _| log::info!("gallery: apply"))
.on_download(|_, _| log::info!("gallery: download")),
)
.child(CodeBlock::new("chat-code-long", LONG).language("rust")),
)
}
const RICH: &str = "| Theme | Lift | Reads as |\n| --- | ---: | --- |\n| Light | 0.50 | half toward white |\n| Dark | 0.62 | a little louder |\n\n$$c' = c + t\\,(1 - c)$$";
pub fn rich(_: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
section(
"MathBlock / TableBlock / MermaidRenderer",
"Math is typography::Latex and tables are the markdown renderer's, in a message as in a document. A diagram arrives as the picture the host drew from its source.",
cx,
)
.child(
div()
.w(px(620.))
.flex()
.flex_col()
.gap_4()
.child(MarkdownRenderer::new("chat-rich", RICH))
.child(ImageMessage::new("chat-diagram", asset!("flow.svg"), 560.0, 160.0).caption("Drawn by the host from a diagram's source")),
)
}
pub fn media(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let mut wave = noise(7);
let peaks: Vec<f32> = (0..56)
.map(|ix| {
let swell = (ix as f32 / 56.0 * std::f32::consts::PI).sin();
(0.25 + 0.75 * swell * wave() as f32).clamp(0.08, 1.0)
})
.collect();
let playing = keep(
"chat-audio",
|| (Duration::from_secs(12), false),
window,
cx,
);
let (played, on) = *playing.read(cx);
let (toggle, seek) = (playing.clone(), playing);
section(
"ImageMessage / ImageGrid / FileMessage / AudioMessage / VideoMessage / LinkPreviewCard",
"What a message can carry: a picture in its own shape, pictures as a grid, a file, a voice note to play and scrub, a video over the host's frames, and a link unfolded.",
cx,
)
.child(
div()
.flex()
.flex_wrap()
.items_start()
.gap_6()
.child(
div()
.flex()
.flex_col()
.gap_4()
.child(ImageMessage::new("chat-image", asset!("atrium.jpg"), 960.0, 640.0).caption("The atrium at noon"))
.child(FileMessage::new("chat-file", "lift-notes.pdf", 482_000).on_download(|_, _| log::info!("gallery: download file")))
.child(
AudioMessage::new("chat-audio", peaks, Duration::from_secs(42))
.played(played, on)
.on_toggle(move |next, _, cx| {
let at = toggle.read(cx).0;
set(&toggle, (at, next), cx)
})
.on_seek(move |share, _, cx| {
let on = seek.read(cx).1;
set(&seek, (Duration::from_secs_f32(42.0 * share), on), cx)
}),
),
)
.child(
div()
.flex()
.flex_col()
.gap_4()
.child(ImageGrid::new(
"chat-grid",
[
asset!("dunes.jpg"),
asset!("atrium-stair.jpg"),
asset!("dunes-sun.jpg"),
asset!("atrium-olive.jpg"),
asset!("dunes-grass.jpg"),
],
))
.child(VideoMessage::new("chat-video", asset!("dunes.jpg"), 960.0, 640.0, Duration::from_secs(84)).on_toggle(|next, _, _| log::info!("gallery: video playing {next}")))
.child(
LinkPreviewCard::new("chat-link", "example.com", "Color, in light and dark")
.description("How one accent reads the same on paper and on charcoal.")
.picture(asset!("dunes-square.jpg"))
.on_open(|_, _| log::info!("gallery: open link")),
),
),
)
}
+184
View File
@@ -0,0 +1,184 @@
use std::time::{Duration, Instant};
use ely_gpui_component::{
buttons::{Button, ButtonVariant},
chat::{
BranchNavigator, ErrorMessage, FeedbackForm, MessageActions, MessageAvatar, MessageBubble,
MessageEditor, QuoteReply, RateLimitNotice, Role, ThinkingBlock, ThinkingDuration,
ThinkingIndicator, continue_button, regenerate_button, stop_button,
},
forms::TextInput,
primitives::IconName,
};
use gpui::{App, Entity, IntoElement, ParentElement, SharedString, Styled, Window, div, px};
use crate::{
probe::probe,
ui::{keep, section, set},
};
const SENT: &str = "What does a lift do to a color?";
fn field(
key: &'static str,
text: &str,
hint: &str,
window: &mut Window,
cx: &mut App,
) -> Entity<TextInput> {
let (text, hint) = (text.to_string(), hint.to_string());
window.use_keyed_state(key, cx, move |window, cx| {
let mut input = TextInput::new(window, cx)
.multi_line(2, 6)
.placeholder(hint);
input.set_text(text, cx);
input
})
}
pub fn actions(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let rating = keep("chat-rating", || None::<bool>, window, cx);
let now_rating = *rating.read(cx);
let branch = keep("chat-branch", || 1_usize, window, cx);
let now_branch = *branch.read(cx);
let editing = keep("chat-editing", || false, window, cx);
let sent = keep("chat-sent", || SharedString::from(SENT), window, cx);
let now_sent = sent.read(cx).clone();
let draft = field("chat-draft", SENT, "Your message", window, cx);
let open = editing.clone();
let body = if *editing.read(cx) {
let (save, cancel, text) = (editing.clone(), editing.clone(), draft.clone());
MessageEditor::new(
"chat-editor",
&draft,
now_sent,
move |_, cx| {
let next = SharedString::from(text.read(cx).text().trim().to_string());
set(&sent, next, cx);
set(&save, false, cx)
},
move |_, cx| set(&cancel, false, cx),
)
.into_any_element()
} else {
div()
.flex()
.items_center()
.gap_3()
.child(div().child(now_sent))
.child(probe(
"chat-edit-open",
Button::new("chat-edit", "Edit")
.variant(ButtonVariant::Ghost)
.icon(IconName::Pencil)
.on_click(move |_, _, cx| set(&open, true, cx)),
))
.into_any_element()
};
section(
"QuoteReply / MessageActions / MessageEditor / BranchNavigator / RegenerateButton / StopGeneratingButton / ContinueButton",
"A quote to answer, the actions on a message, a sent message opened to change (the submit key saves, Escape cancels), the versions an answer has, and the buttons that regenerate, stop and continue.",
cx,
)
.child(
div()
.w(px(560.))
.flex()
.flex_col()
.gap_4()
.child(QuoteReply::new("chat-quote", "Assistant", "A lift blends a color toward white. Half a lift sits midway between the color and white.").on_remove(|_, _| log::info!("gallery: quote removed")))
.child(body)
.child(
div()
.flex()
.items_center()
.justify_between()
.child(
MessageActions::new("chat-actions", SENT)
.on_edit(|_, _| log::info!("gallery: edit"))
.on_regenerate(|_, _| log::info!("gallery: regenerate"))
.rating(now_rating, move |next, _, cx| set(&rating, next, cx)),
)
.child(BranchNavigator::new("chat-branch", now_branch, 3, move |next, _, cx| set(&branch, next, cx))),
)
.child(
div()
.flex()
.gap_2()
.child(regenerate_button("chat-regenerate").on_click(|_, _, _| log::info!("gallery: regenerate")))
.child(stop_button("chat-stop").on_click(|_, _, _| log::info!("gallery: stop")))
.child(continue_button("chat-continue").on_click(|_, _, _| log::info!("gallery: continue"))),
),
)
}
pub fn status(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let until = *keep(
"chat-limit",
|| Instant::now() + Duration::from_secs(222),
window,
cx,
)
.read(cx);
let picked = keep(
"chat-reasons",
|| vec![SharedString::from("Too long")],
window,
cx,
);
let now_picked = picked.read(cx).clone();
let note = field("chat-note", "", "Anything else? (optional)", window, cx);
section(
"ErrorMessage / RetryMessage / RateLimitNotice / FeedbackForm",
"An answer that failed and a way to try again; a limit reached, counting down to when it lifts; and after a bad mark, what went wrong.",
cx,
)
.child(
div()
.w(px(560.))
.flex()
.flex_col()
.gap_4()
.child(
MessageBubble::new(Role::Error)
.avatar(MessageAvatar::new("chat-error-mark", Role::Error, "Assistant"))
.child(ErrorMessage::new("chat-error", "The answer stopped halfway").detail("The connection closed before the end. Nothing was lost.").on_retry(|_, _| log::info!("gallery: retry"))),
)
.child(RateLimitNotice::new("chat-limit", until).on_upgrade(|_, _| log::info!("gallery: raise limit")))
.child(
FeedbackForm::new(
"chat-feedback",
["Wrong", "Unclear", "Too long", "Missed the point"],
now_picked,
&note,
move |next, _, cx| set(&picked, next.to_vec(), cx),
|_, _| log::info!("gallery: feedback sent"),
)
.on_cancel(|_, _| log::info!("gallery: feedback cancelled")),
),
)
}
const REASONING: &str = "The reader asks what a lift does. Start from the definition: a blend toward white. Then give the two themes, since they lift by different amounts, and say why: a dark ground makes saturated color look louder, so it needs less of it.";
pub fn thinking(_: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
section(
"ThinkingBlock / ReasoningPanel / ThinkingIndicator / ThinkingDuration",
"The reasoning behind an answer, folded under how long it took; open, its steps read in a quiet column. While the assistant works, a word says what it is doing.",
cx,
)
.child(
div()
.w(px(560.))
.flex()
.flex_col()
.gap_4()
.child(probe(
"chat-thinking",
div().w(px(560.)).child(ThinkingBlock::new("chat-thought", REASONING, false, Duration::from_secs(12))),
))
.child(ThinkingBlock::new("chat-thinking-now", "Weighing how dark themes change", true, Duration::from_secs(3)))
.child(ThinkingIndicator::new("chat-searching").label("Searching the web"))
.child(ThinkingDuration::new(Duration::from_secs(75))),
)
}
+45
View File
@@ -0,0 +1,45 @@
mod blocks;
mod controls;
mod talk;
use gpui::{AnyElement, App, IntoElement, ParentElement, Window, div};
use super::Page;
use crate::script::Step;
pub const PAGE: Page = Page {
number: 23,
slug: "chat",
title: "AI Chat",
summary: "A conversation with an assistant: messages that stream in, code and media inside them, and what can be done with each.",
render,
script: SCRIPT,
};
const SCRIPT: &[Step] = &[
Step::DownAt("chat-thinking", 12.0, 10.0),
Step::UpAt("chat-thinking", 12.0, 10.0),
Step::Wait(300),
Step::Shot("reasoning"),
Step::DownAt("chat-thinking", 12.0, 10.0),
Step::UpAt("chat-thinking", 12.0, 10.0),
Step::DownAt("chat-edit-open", 20.0, 12.0),
Step::UpAt("chat-edit-open", 20.0, 12.0),
Step::Wait(300),
Step::Shot("editing"),
Step::Key("escape"),
Step::Wait(200),
];
fn render(window: &mut Window, cx: &mut App) -> AnyElement {
div()
.child(talk::conversation(window, cx))
.child(talk::streaming(window, cx))
.child(blocks::code(window, cx))
.child(blocks::rich(window, cx))
.child(blocks::media(window, cx))
.child(controls::actions(window, cx))
.child(controls::status(window, cx))
.child(controls::thinking(window, cx))
.into_any_element()
}
+224
View File
@@ -0,0 +1,224 @@
use std::time::Duration;
use ely_gpui_component::{
buttons::{Button, ButtonVariant},
chat::{
ChatContainer, DateSeparator, MessageActions, MessageAvatar, MessageBubble, MessageFooter,
MessageHeader, MessageList, Role, StreamingCursor, StreamingMarkdown, stop_button,
},
primitives::IconName,
theme::{ActiveTheme, Radius},
};
use gpui::{App, ElementId, IntoElement, ParentElement, Styled, Task, Window, div, px};
use jiff::{Timestamp, ToSpan, civil::Date, tz::TimeZone};
use crate::{
probe::probe,
ui::{keep, section},
};
/// One row of the demo conversation.
#[derive(Clone)]
enum Row {
Day(Date),
Note(&'static str),
Said {
role: Role,
name: &'static str,
minutes_ago: i64,
text: &'static str,
live: bool,
},
}
const ANSWER: &str = "A **lift** blends a color toward white. Half a lift sits midway between the color and white; a full lift is white itself.\n\n- In light, accents take half a lift.\n- In dark, they take more, so they read with the same weight.";
const LIVE: &str = "The lift $t$ mixes a channel toward one:\n\n$$c' = c + t\\,(1 - c)$$\n\nIn code, for each channel:\n\n```rust\nfn lift(c: f32, t: f32) -> f32 {\n c + t * (1.0 - c)\n}\n```\n\nApplied to every";
fn rows(today: Date) -> Vec<Row> {
let yesterday = today.yesterday().expect("the day before exists");
vec![
Row::Day(yesterday),
Row::Said {
role: Role::User,
name: "Ada Park",
minutes_ago: 1500,
text: "What does a lift do to a color?",
live: false,
},
Row::Said {
role: Role::Assistant,
name: "Assistant",
minutes_ago: 1499,
text: ANSWER,
live: false,
},
Row::Day(today),
Row::Note("Grace Lin joined the conversation"),
Row::Said {
role: Role::User,
name: "Ada Park",
minutes_ago: 2,
text: "Show me the math, and the code.",
live: false,
},
Row::Said {
role: Role::Assistant,
name: "Assistant",
minutes_ago: 1,
text: LIVE,
live: true,
},
]
}
fn row(ix: usize, row: &Row, today: Date, now: Timestamp) -> gpui::AnyElement {
let key = |what: &str| (ElementId::from("chat-row"), format!("{what}-{ix}"));
let body = match row {
Row::Day(day) => return DateSeparator::new(*day, today).into_any_element(),
Row::Note(text) => MessageBubble::new(Role::System).child(*text),
Row::Said {
role,
name,
minutes_ago,
text,
live,
} => {
let header = MessageHeader::new(key("header"), *name).at(now - minutes_ago.minutes());
let header = if *role == Role::Assistant {
header.model("Ely Large")
} else {
header
};
let bubble = MessageBubble::new(*role)
.avatar(MessageAvatar::new(key("avatar"), *role, *name))
.header(header)
.child(StreamingMarkdown::new(key("text"), *text, *live));
match (role, live) {
(Role::Assistant, false) => bubble.footer(
MessageFooter::new().fact("412 tokens").fact("2.1 s").child(
MessageActions::new(key("actions"), *text)
.on_regenerate(|_, _| log::info!("gallery: regenerate"))
.rating(Some(true), |next, _, _| {
log::info!("gallery: rated {next:?}")
}),
),
),
(Role::Assistant, true) => bubble.footer(MessageFooter::new().child(
stop_button(key("stop")).on_click(|_, _, _| log::info!("gallery: stop")),
)),
_ => bubble,
}
}
};
div().px_6().py_3().child(body).into_any_element()
}
pub fn conversation(_: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let today = Timestamp::now().to_zoned(TimeZone::system()).date();
let now = Timestamp::now();
let all = rows(today);
let count = all.len();
let theme = cx.theme();
section(
"ChatContainer / MessageList / MessageBubble / MessageAvatar / MessageHeader / MessageFooter / DateSeparator / ScrollToBottomButton",
"A conversation held at its newest message and drawn only near the view. Yours sit on the right in a quiet bubble; the assistant's read as prose beside its mark. Scroll up and it stays put, with a way back down that counts what arrived.",
cx,
)
.child(probe(
"chat-conversation",
div()
.w(px(760.))
.h(px(600.))
.rounded(theme.radius(Radius::Lg))
.border_1()
.border_color(theme.colors.border)
.overflow_hidden()
.child(ChatContainer::new(MessageList::new("chat-messages", count, move |ix, _, _| {
row(ix, &all[ix], today, now)
}))),
))
}
/// The demo stream: how much of it has arrived, whether more is coming, and the task that feeds it.
struct Stream {
arrived: usize,
live: bool,
_feed: Option<Task<()>>,
}
pub fn streaming(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let stream = keep(
"chat-stream",
|| Stream {
arrived: ANSWER.len(),
live: false,
_feed: None,
},
window,
cx,
);
let (arrived, live) = (stream.read(cx).arrived, stream.read(cx).live);
let text = &ANSWER[..arrived];
let theme = cx.theme();
let replay = stream.clone();
section(
"StreamingText / StreamingMarkdown / StreamingCursor",
"Text as it arrives: what came in shows at a steady pace and catches up when far behind, a caret where more will come; markdown takes shape as its lines land. The cursor alone waits for the first words.",
cx,
)
.child(
div()
.w(px(560.))
.flex()
.flex_col()
.gap_3()
.child(
div()
.p_4()
.rounded(theme.radius(Radius::Lg))
.border_1()
.border_color(theme.colors.border)
.min_h(px(140.))
.child(if arrived == 0 {
StreamingCursor::new("chat-cursor").into_any_element()
} else {
StreamingMarkdown::new("chat-streamed", text.to_string(), live).into_any_element()
}),
)
.child(
div().flex().child(
Button::new("chat-replay", "Replay the stream")
.variant(ButtonVariant::Secondary)
.icon(IconName::RefreshCw)
.on_click(move |_, window, cx| {
let feeder = replay.downgrade();
let feed = window.spawn(cx, async move |cx| {
cx.background_executor().timer(Duration::from_millis(600)).await;
loop {
cx.background_executor().timer(Duration::from_millis(45)).await;
let more = feeder.update(cx, |stream, cx| {
let next = (stream.arrived + 7).min(ANSWER.len());
stream.arrived = (next..=ANSWER.len())
.find(|at| ANSWER.is_char_boundary(*at))
.expect("the text ends on a boundary");
stream.live = stream.arrived < ANSWER.len();
cx.notify();
stream.live
});
if !matches!(more, Ok(true)) {
break;
}
}
});
replay.update(cx, |stream, cx| {
stream.arrived = 0;
stream.live = true;
stream._feed = Some(feed);
cx.notify();
});
}),
),
),
)
}
+2
View File
@@ -1,5 +1,6 @@
mod buttons;
mod charts;
mod chat;
mod collab;
mod data;
mod debug;
@@ -59,6 +60,7 @@ pub const ALL: &[Page] = &[
debug::PAGE,
documents::PAGE,
collab::PAGE,
chat::PAGE,
theme::PAGE,
];