1use 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
25#[serde(tag = "role", rename_all = "snake_case")]
26pub enum ChatMessage {
27 User {
29 text: String,
31 },
32 Agent {
34 text: String,
36 },
37 Tool(ToolCall),
39}
40
41#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
43pub struct ToolCall {
44 pub name: String,
46 #[serde(default)]
48 pub summary: String,
49 #[serde(default)]
51 pub arguments: Value,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub result: Option<Value>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub error: Option<String>,
58}
59
60impl ToolCall {
61 pub fn new(name: impl Into<String>, arguments: Value) -> Self {
63 ToolCall { name: name.into(), arguments, ..Default::default() }
64 }
65
66 pub fn finished(self, result: Value, summary: impl Into<String>) -> Self {
68 ToolCall { result: Some(result), summary: summary.into(), ..self }
69 }
70
71 pub fn is_running(&self) -> bool {
73 self.result.is_none() && self.error.is_none()
74 }
75
76 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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
89pub enum Location {
90 #[default]
92 Local,
93 Remote(String),
95}
96
97#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
99pub struct ChatContext {
100 pub workspace: String,
102 pub location: Location,
104 pub model: String,
106}
107
108#[derive(Clone, Debug, PartialEq, Eq)]
110pub enum ChatEvent {
111 Send(String),
114 Stop,
116}
117
118enum RowView {
120 Text(Entity<TextView>),
121 Tool { open: bool, views: Option<(Entity<CodeView>, Option<Entity<CodeView>>)> },
122}
123
124pub 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 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 pub fn messages(&self) -> &[ChatMessage] {
168 &self.messages
169 }
170
171 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 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 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 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 *views = None;
227 cx.notify();
228 }
229 }
230
231 pub fn is_running(&self) -> bool {
233 self.running
234 }
235
236 pub fn set_running(&mut self, running: bool, cx: &mut Context<Self>) {
238 self.running = running;
239 cx.notify();
240 }
241
242 pub fn set_context(&mut self, context: ChatContext, cx: &mut Context<Self>) {
244 self.context = context;
245 cx.notify();
246 }
247
248 pub fn prompt_text(&self, cx: &App) -> String {
250 self.prompt.read(cx).value().to_string()
251 }
252
253 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 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 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 pub fn stop(&mut self, cx: &mut Context<Self>) {
283 if self.running {
284 cx.emit(ChatEvent::Stop);
285 }
286 }
287
288 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}