Skip to main content

kitchen_ui/
chat.rs

1//! The agent chat as a view an app can dock: the conversation (the user's prompts, the agent's
2//! replies, its tool calls) and a prompt box. No network or model code: the pane emits
3//! [`ChatEvent`]s and the app pushes messages in. The conversation is plain data
4//! ([`ChatMessage`], serializable) so an app can record it (a session file) and restore it.
5
6use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::input::{InputEvent, Textarea, TextareaState};
9use gpui_kit::component::tooltip::Tooltip;
10use gpui_kit::component::{Icon, Sizable as _, h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::{
13    AnyElement, App, AppContext as _, Context, Entity, EventEmitter, FontWeight, InteractiveElement as _, IntoElement,
14    ParentElement as _, Render, ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription,
15    TestSupportExt as _, Window, div, px,
16};
17use serde::{Deserialize, Serialize};
18use serde_json::Value;
19
20use crate::theme::{self, color};
21use crate::widgets::{CodeLanguage, CodeView, EmptyState, TextView};
22
23/// One message of the conversation.
24#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
25#[serde(tag = "role", rename_all = "snake_case")]
26pub enum ChatMessage {
27    /// What the user asked.
28    User {
29        /// Plain text (shown as markdown).
30        text: String,
31    },
32    /// What the agent answered (markdown).
33    Agent {
34        /// Markdown.
35        text: String,
36    },
37    /// A command the agent ran.
38    Tool(ToolCall),
39}
40
41/// A command the agent ran: its name, arguments, result and a one-line summary.
42#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
43pub struct ToolCall {
44    /// The command id (`hist.find_cells`).
45    pub name: String,
46    /// What it did, shortly (`2,539 cells`); shown after the name.
47    #[serde(default)]
48    pub summary: String,
49    /// Its arguments.
50    #[serde(default)]
51    pub arguments: Value,
52    /// Its result, once it finished.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub result: Option<Value>,
55    /// Why it failed, if it did.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub error: Option<String>,
58}
59
60impl ToolCall {
61    /// A call of `name` with `arguments`, still running.
62    pub fn new(name: impl Into<String>, arguments: Value) -> Self {
63        ToolCall { name: name.into(), arguments, ..Default::default() }
64    }
65
66    /// The same call, finished with `result` and `summary`.
67    pub fn finished(self, result: Value, summary: impl Into<String>) -> Self {
68        ToolCall { result: Some(result), summary: summary.into(), ..self }
69    }
70
71    /// Whether it is still running (no result, no error).
72    pub fn is_running(&self) -> bool {
73        self.result.is_none() && self.error.is_none()
74    }
75
76    /// The collapsed line: "Ran hist.find_cells · 2,539 cells", "Running …", "Failed …".
77    pub fn line(&self) -> String {
78        let tail = |s: &str| if s.is_empty() { String::new() } else { format!(" · {s}") };
79        match (&self.result, &self.error) {
80            (_, Some(e)) => format!("Failed {}{}", self.name, tail(e)),
81            (Some(_), None) => format!("Ran {}{}", self.name, tail(&self.summary)),
82            (None, None) => format!("Running {}…", self.name),
83        }
84    }
85}
86
87/// Where the agent works.
88#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
89pub enum Location {
90    /// This computer.
91    #[default]
92    Local,
93    /// A remote machine (its name).
94    Remote(String),
95}
96
97/// What the chips above the prompt show: the workspace, where the agent runs, the model.
98#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
99pub struct ChatContext {
100    /// The workspace or project (empty: no chip).
101    pub workspace: String,
102    /// This computer or a remote one.
103    pub location: Location,
104    /// The model (empty: no chip).
105    pub model: String,
106}
107
108/// What the pane asks of the app.
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub enum ChatEvent {
111    /// The user sent this prompt (already added to the conversation as a user message, and the
112    /// pane shows the agent as running until [`ChatPane::set_running`]`(false)`).
113    Send(String),
114    /// The user asked the running agent to stop.
115    Stop,
116}
117
118/// What a message shows with: its text view, or a tool call's open state and code views.
119enum RowView {
120    Text(Entity<TextView>),
121    Tool { open: bool, views: Option<(Entity<CodeView>, Option<Entity<CodeView>>)> },
122}
123
124/// The agent chat: a scrolling conversation (user, agent and tool-call rows) above a prompt box
125/// with context chips. A tool call is one line ("Ran hist.find_cells · 2,539 cells") that opens
126/// to its JSON arguments and result. Agent text streams in with [`ChatPane::append_agent`].
127///
128/// The prompt: Enter sends, Shift+Enter is a newline; the Send button becomes Stop while the agent
129/// runs. The pane emits [`ChatEvent`]; the app pushes the agent's messages in
130/// ([`ChatPane::push`], [`ChatPane::append_agent`], [`ChatPane::set_tool_result`]) and says when
131/// it is done ([`ChatPane::set_running`]). [`ChatPane::messages`] is the whole conversation.
132pub struct ChatPane {
133    messages: Vec<ChatMessage>,
134    rows: Vec<RowView>,
135    context: ChatContext,
136    running: bool,
137    prompt: Entity<TextareaState>,
138    scroll: ScrollHandle,
139    _subs: Vec<Subscription>,
140}
141
142impl EventEmitter<ChatEvent> for ChatPane {}
143
144impl ChatPane {
145    /// An empty conversation.
146    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
147        let prompt = cx.new(|cx| {
148            TextareaState::new(window, cx).auto_grow(1, 8).submit_on_enter(true).placeholder("Ask the agent…")
149        });
150        let sub = cx.subscribe_in(&prompt, window, |this, _, e: &InputEvent, window, cx| {
151            if let InputEvent::PressEnter { shift: false, .. } = e {
152                this.send(window, cx);
153            }
154        });
155        Self {
156            messages: Vec::new(),
157            rows: Vec::new(),
158            context: ChatContext::default(),
159            running: false,
160            prompt,
161            scroll: ScrollHandle::new(),
162            _subs: vec![sub],
163        }
164    }
165
166    /// The conversation.
167    pub fn messages(&self) -> &[ChatMessage] {
168        &self.messages
169    }
170
171    /// Replaces the conversation (a restored session).
172    pub fn set_messages(&mut self, messages: Vec<ChatMessage>, cx: &mut Context<Self>) {
173        self.messages.clear();
174        self.rows.clear();
175        for m in messages {
176            self.push(m, cx);
177        }
178    }
179
180    /// Adds a message; returns its index.
181    pub fn push(&mut self, message: ChatMessage, cx: &mut Context<Self>) -> usize {
182        let row = match &message {
183            ChatMessage::User { text } | ChatMessage::Agent { text } => {
184                let text = text.clone();
185                RowView::Text(cx.new(|cx| TextView::new(text, cx)))
186            }
187            ChatMessage::Tool(_) => RowView::Tool { open: false, views: None },
188        };
189        self.messages.push(message);
190        self.rows.push(row);
191        self.scroll.scroll_to_bottom();
192        cx.notify();
193        self.messages.len() - 1
194    }
195
196    /// Appends streamed agent text: to the last message when it is the agent's, else as a new
197    /// agent message.
198    pub fn append_agent(&mut self, text: &str, cx: &mut Context<Self>) {
199        let last = self.messages.len().checked_sub(1);
200        if let Some(i) = last
201            && let (ChatMessage::Agent { text: t }, RowView::Text(view)) = (&mut self.messages[i], &self.rows[i])
202        {
203            t.push_str(text);
204            view.update(cx, |v, cx| v.push_str(text, cx));
205            self.scroll.scroll_to_bottom();
206            cx.notify();
207            return;
208        }
209        self.push(ChatMessage::Agent { text: text.to_string() }, cx);
210    }
211
212    /// Finishes the tool call at `index`: its result and summary, or why it failed.
213    pub fn set_tool_result(&mut self, index: usize, result: Result<(Value, String), String>, cx: &mut Context<Self>) {
214        if let (Some(ChatMessage::Tool(call)), Some(RowView::Tool { views, .. })) =
215            (self.messages.get_mut(index), self.rows.get_mut(index))
216        {
217            match result {
218                Ok((value, summary)) => {
219                    call.result = Some(value);
220                    call.summary = summary;
221                    call.error = None;
222                }
223                Err(e) => call.error = Some(e),
224            }
225            // Built again with the result on the next draw
226            *views = None;
227            cx.notify();
228        }
229    }
230
231    /// Whether the agent is running (the Send button shows Stop).
232    pub fn is_running(&self) -> bool {
233        self.running
234    }
235
236    /// Says whether the agent is running.
237    pub fn set_running(&mut self, running: bool, cx: &mut Context<Self>) {
238        self.running = running;
239        cx.notify();
240    }
241
242    /// The chips above the prompt.
243    pub fn set_context(&mut self, context: ChatContext, cx: &mut Context<Self>) {
244        self.context = context;
245        cx.notify();
246    }
247
248    /// The prompt's text.
249    pub fn prompt_text(&self, cx: &App) -> String {
250        self.prompt.read(cx).value().to_string()
251    }
252
253    /// Puts `text` in the prompt.
254    pub fn set_prompt(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
255        let text = text.to_string();
256        self.prompt.update(cx, |p, cx| p.set_value(text, window, cx));
257    }
258
259    /// Focuses the prompt.
260    pub fn focus_prompt(&self, window: &mut Window, cx: &mut Context<Self>) {
261        self.prompt.update(cx, |p, cx| p.focus(window, cx));
262    }
263
264    /// Sends the prompt (as Enter and the Send button do): adds it as a user message, clears the
265    /// box, shows the agent as running and emits [`ChatEvent::Send`]. Nothing while the agent
266    /// runs or when the prompt is blank.
267    pub fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
268        let text = self.prompt_text(cx);
269        let text = text.trim();
270        if self.running || text.is_empty() {
271            return;
272        }
273        let text = text.to_string();
274        self.prompt.update(cx, |p, cx| p.set_value("", window, cx));
275        self.push(ChatMessage::User { text: text.clone() }, cx);
276        self.running = true;
277        cx.emit(ChatEvent::Send(text));
278        cx.notify();
279    }
280
281    /// Asks the running agent to stop (emits [`ChatEvent::Stop`]; the app says when it stopped).
282    pub fn stop(&mut self, cx: &mut Context<Self>) {
283        if self.running {
284            cx.emit(ChatEvent::Stop);
285        }
286    }
287
288    /// Opens or closes the tool call at `index`.
289    pub fn toggle_tool(&mut self, index: usize, cx: &mut Context<Self>) {
290        if let Some(RowView::Tool { open, .. }) = self.rows.get_mut(index) {
291            *open = !*open;
292            cx.notify();
293        }
294    }
295
296    fn message_row(&mut self, i: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
297        let caption = |icon: IconName, who: &'static str| {
298            h_flex()
299                .gap(px(theme::XS))
300                .text_xs()
301                .font_weight(FontWeight::SEMIBOLD)
302                .text_color(color::text_muted())
303                .child(Icon::new(icon).size(px(12.)))
304                .child(who)
305        };
306        match (&self.messages[i], &mut self.rows[i]) {
307            (ChatMessage::User { .. }, RowView::Text(view)) => v_flex()
308                .w_full()
309                .gap(px(theme::XS))
310                .child(caption(IconName::User, "You"))
311                .child(
312                    div()
313                        .w_full()
314                        .px(px(theme::MD))
315                        .py(px(theme::SM))
316                        .rounded(px(theme::RADIUS_LG))
317                        .bg(color::raised())
318                        .child(view.clone()),
319                )
320                .into_any_element(),
321            (ChatMessage::Agent { .. }, RowView::Text(view)) => v_flex()
322                .w_full()
323                .gap(px(theme::XS))
324                .child(caption(IconName::Bot, "Agent"))
325                .child(view.clone())
326                .into_any_element(),
327            (ChatMessage::Tool(call), RowView::Tool { open, views }) => {
328                let (icon, icon_color) = match (&call.result, &call.error) {
329                    (_, Some(_)) => (IconName::CircleX, color::danger()),
330                    (Some(_), None) => (IconName::SquareTerminal, color::text_muted()),
331                    (None, None) => (IconName::LoaderCircle, color::accent_mark()),
332                };
333                let line = h_flex()
334                    .id(SharedString::from(format!("chat-tool-{i}")))
335                    .w_full()
336                    .min_h(px(theme::TARGET_MIN))
337                    .px(px(theme::XS))
338                    .gap(px(theme::SM))
339                    .rounded(px(theme::RADIUS))
340                    .cursor_pointer()
341                    .hover(|d| d.bg(color::hover()))
342                    .child(
343                        Icon::new(if *open { IconName::ChevronDown } else { IconName::ChevronRight })
344                            .size(px(14.))
345                            .text_color(color::text_muted()),
346                    )
347                    .child(Icon::new(icon).size(px(14.)).text_color(icon_color))
348                    .child(
349                        div()
350                            .flex_1()
351                            .min_w_0()
352                            .truncate()
353                            .text_sm()
354                            .text_color(color::text_muted())
355                            .child(call.line()),
356                    )
357                    .on_click(cx.listener(move |this, _, _, cx| this.toggle_tool(i, cx)))
358                    .test_support();
359                if !*open {
360                    return line.into_any_element();
361                }
362                if views.is_none() {
363                    let pretty = |v: &Value| serde_json::to_string_pretty(v).unwrap_or_default();
364                    let args = pretty(&call.arguments);
365                    let result = call.result.as_ref().map(pretty);
366                    let a = cx.new(|cx| CodeView::new(CodeLanguage::Json, args, window, cx).max_lines(12));
367                    let r = result.map(|r| cx.new(|cx| CodeView::new(CodeLanguage::Json, r, window, cx).max_lines(12)));
368                    *views = Some((a, r));
369                }
370                let Some((a, r)) = views.clone() else { return line.into_any_element() };
371                let label = |s: &'static str| {
372                    div()
373                        .text_xs()
374                        .font_weight(FontWeight::SEMIBOLD)
375                        .text_color(color::text_muted())
376                        .child(s.to_uppercase())
377                };
378                let error = call.error.clone();
379                v_flex()
380                    .w_full()
381                    .gap(px(theme::XS))
382                    .child(line)
383                    .child(
384                        v_flex()
385                            .w_full()
386                            .pl(px(theme::XL))
387                            .gap(px(theme::XS))
388                            .child(label("Arguments"))
389                            .child(a)
390                            .when_some(r, |d, r| d.child(label("Result")).child(r))
391                            .when_some(error, |d, e| {
392                                d.child(label("Error")).child(div().text_sm().text_color(color::danger()).child(e))
393                            }),
394                    )
395                    .into_any_element()
396            }
397            _ => div().into_any_element(),
398        }
399    }
400
401    fn chips(&self) -> Option<impl IntoElement> {
402        let c = &self.context;
403        let chip = |id: &'static str, icon: IconName, text: String, tip: &'static str| {
404            h_flex()
405                .id(id)
406                .flex_none()
407                .min_h(px(theme::TARGET_MIN))
408                .px(px(theme::SM))
409                .gap(px(theme::XS))
410                .rounded(px(theme::RADIUS_SM))
411                .bg(color::control())
412                .text_xs()
413                .text_color(color::text())
414                .child(Icon::new(icon).size(px(12.)).text_color(color::text_muted()))
415                .child(div().max_w(px(180.)).truncate().child(text))
416                .tooltip(move |window, cx| Tooltip::new(tip).build(window, cx))
417                .into_any_element()
418        };
419        let mut out: Vec<AnyElement> = Vec::new();
420        if !c.workspace.is_empty() {
421            out.push(chip("chat-chip-workspace", IconName::Folder, c.workspace.clone(), "Workspace"));
422        }
423        out.push(match &c.location {
424            Location::Local => chip(
425                "chat-chip-location",
426                IconName::HardDrive,
427                "This computer".into(),
428                "The agent runs on this computer",
429            ),
430            Location::Remote(host) => {
431                chip("chat-chip-location", IconName::Globe, host.clone(), "The agent runs on a remote machine")
432            }
433        });
434        if !c.model.is_empty() {
435            out.push(chip("chat-chip-model", IconName::Cpu, c.model.clone(), "Model"));
436        }
437        Some(h_flex().w_full().flex_wrap().gap(px(theme::XS)).children(out))
438    }
439}
440
441impl Render for ChatPane {
442    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
443        let list: Vec<AnyElement> = (0..self.messages.len()).map(|i| self.message_row(i, window, cx)).collect();
444        let body = if list.is_empty() {
445            div()
446                .flex_1()
447                .min_h_0()
448                .child(EmptyState::new(IconName::Bot, "Ask the agent", "Say what you want done with this workspace. Each command the agent runs shows here, with its arguments and result."))
449                .into_any_element()
450        } else {
451            v_flex()
452                .id("chat-messages")
453                .flex_1()
454                .min_h_0()
455                .w_full()
456                .overflow_y_scroll()
457                .track_scroll(&self.scroll)
458                .p(px(theme::MD))
459                .gap(px(theme::LG))
460                .children(list)
461                .into_any_element()
462        };
463        let action = if self.running {
464            Button::new("chat-stop")
465                .small()
466                .icon(IconName::Square)
467                .label("Stop")
468                .tooltip("Stop the agent")
469                .on_click(cx.listener(|this, _, _, cx| this.stop(cx)))
470        } else {
471            Button::new("chat-send")
472                .small()
473                .primary()
474                .icon(IconName::ArrowUp)
475                .label("Send")
476                .tooltip("Send (Enter; Shift+Enter for a new line)")
477                .on_click(cx.listener(|this, _, window, cx| this.send(window, cx)))
478        };
479        let footer = v_flex()
480            .flex_none()
481            .w_full()
482            .p(px(theme::SM))
483            .gap(px(theme::SM))
484            .border_t_1()
485            .border_color(color::border())
486            .children(self.chips())
487            .child(
488                v_flex().w_full().gap(px(theme::XS)).child(Textarea::new(&self.prompt).w_full()).child(
489                    h_flex()
490                        .w_full()
491                        .gap(px(theme::SM))
492                        .child(div().flex_1().min_w_0().truncate().text_xs().text_color(color::text_muted()).child(
493                            if self.running {
494                                "The agent is working…"
495                            } else {
496                                "Enter sends · Shift+Enter for a new line"
497                            },
498                        ))
499                        .child(action),
500                ),
501            );
502        v_flex()
503            .id("chat-pane")
504            .size_full()
505            .bg(color::panel())
506            .rounded(px(theme::RADIUS_LG))
507            .overflow_hidden()
508            .child(body)
509            .child(footer)
510    }
511}