1use crate::AssistantPanel;
2use crate::context::{AssistantContext, ContextId};
3use crate::context_picker::MentionLink;
4use crate::thread::{
5 LastRestoreCheckpoint, MessageId, MessageSegment, RequestKind, Thread, ThreadError,
6 ThreadEvent, ThreadFeedback,
7};
8use crate::thread_store::ThreadStore;
9use crate::tool_use::{PendingToolUseStatus, ToolUse, ToolUseStatus};
10use crate::ui::{AddedContext, AgentNotification, AgentNotificationEvent, ContextPill};
11use anyhow::Context as _;
12use assistant_settings::{AssistantSettings, NotifyWhenAgentWaiting};
13use collections::{HashMap, HashSet};
14use editor::scroll::Autoscroll;
15use editor::{Editor, MultiBuffer};
16use gpui::{
17 AbsoluteLength, Animation, AnimationExt, AnyElement, App, ClickEvent, ClipboardItem,
18 DefiniteLength, EdgesRefinement, Empty, Entity, Focusable, Hsla, ListAlignment, ListState,
19 MouseButton, PlatformDisplay, ScrollHandle, Stateful, StyleRefinement, Subscription, Task,
20 TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity, WindowHandle,
21 linear_color_stop, linear_gradient, list, percentage, pulsating_between,
22};
23use language::{Buffer, LanguageRegistry};
24use language_model::{ConfiguredModel, LanguageModelRegistry, LanguageModelToolUseId, Role};
25use markdown::parser::CodeBlockKind;
26use markdown::{Markdown, MarkdownElement, MarkdownStyle, ParsedMarkdown, without_fences};
27use project::ProjectItem as _;
28use rope::Point;
29use settings::{Settings as _, update_settings_file};
30use std::ops::Range;
31use std::path::Path;
32use std::rc::Rc;
33use std::sync::Arc;
34use std::time::Duration;
35use text::ToPoint;
36use theme::ThemeSettings;
37use ui::{Disclosure, IconButton, KeyBinding, Scrollbar, ScrollbarState, Tooltip, prelude::*};
38use util::ResultExt as _;
39use workspace::{OpenOptions, Workspace};
40
41use crate::context_store::ContextStore;
42
43pub struct ActiveThread {
44 language_registry: Arc<LanguageRegistry>,
45 thread_store: Entity<ThreadStore>,
46 thread: Entity<Thread>,
47 context_store: Entity<ContextStore>,
48 workspace: WeakEntity<Workspace>,
49 save_thread_task: Option<Task<()>>,
50 messages: Vec<MessageId>,
51 list_state: ListState,
52 scrollbar_state: ScrollbarState,
53 show_scrollbar: bool,
54 hide_scrollbar_task: Option<Task<()>>,
55 rendered_messages_by_id: HashMap<MessageId, RenderedMessage>,
56 rendered_tool_uses: HashMap<LanguageModelToolUseId, RenderedToolUse>,
57 editing_message: Option<(MessageId, EditMessageState)>,
58 expanded_tool_uses: HashMap<LanguageModelToolUseId, bool>,
59 expanded_thinking_segments: HashMap<(MessageId, usize), bool>,
60 last_error: Option<ThreadError>,
61 notifications: Vec<WindowHandle<AgentNotification>>,
62 copied_code_block_ids: HashSet<(MessageId, usize)>,
63 _subscriptions: Vec<Subscription>,
64 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
65 feedback_message_editor: Option<Entity<Editor>>,
66}
67
68struct RenderedMessage {
69 language_registry: Arc<LanguageRegistry>,
70 segments: Vec<RenderedMessageSegment>,
71}
72
73#[derive(Clone)]
74struct RenderedToolUse {
75 label: Entity<Markdown>,
76 input: Entity<Markdown>,
77 output: Entity<Markdown>,
78}
79
80impl RenderedMessage {
81 fn from_segments(
82 segments: &[MessageSegment],
83 language_registry: Arc<LanguageRegistry>,
84 cx: &mut App,
85 ) -> Self {
86 let mut this = Self {
87 language_registry,
88 segments: Vec::with_capacity(segments.len()),
89 };
90 for segment in segments {
91 this.push_segment(segment, cx);
92 }
93 this
94 }
95
96 fn append_thinking(&mut self, text: &String, cx: &mut App) {
97 if let Some(RenderedMessageSegment::Thinking {
98 content,
99 scroll_handle,
100 }) = self.segments.last_mut()
101 {
102 content.update(cx, |markdown, cx| {
103 markdown.append(text, cx);
104 });
105 scroll_handle.scroll_to_bottom();
106 } else {
107 self.segments.push(RenderedMessageSegment::Thinking {
108 content: parse_markdown(text.into(), self.language_registry.clone(), cx),
109 scroll_handle: ScrollHandle::default(),
110 });
111 }
112 }
113
114 fn append_text(&mut self, text: &String, cx: &mut App) {
115 if let Some(RenderedMessageSegment::Text(markdown)) = self.segments.last_mut() {
116 markdown.update(cx, |markdown, cx| markdown.append(text, cx));
117 } else {
118 self.segments
119 .push(RenderedMessageSegment::Text(parse_markdown(
120 SharedString::from(text),
121 self.language_registry.clone(),
122 cx,
123 )));
124 }
125 }
126
127 fn push_segment(&mut self, segment: &MessageSegment, cx: &mut App) {
128 let rendered_segment = match segment {
129 MessageSegment::Thinking(text) => RenderedMessageSegment::Thinking {
130 content: parse_markdown(text.into(), self.language_registry.clone(), cx),
131 scroll_handle: ScrollHandle::default(),
132 },
133 MessageSegment::Text(text) => RenderedMessageSegment::Text(parse_markdown(
134 text.into(),
135 self.language_registry.clone(),
136 cx,
137 )),
138 };
139 self.segments.push(rendered_segment);
140 }
141}
142
143enum RenderedMessageSegment {
144 Thinking {
145 content: Entity<Markdown>,
146 scroll_handle: ScrollHandle,
147 },
148 Text(Entity<Markdown>),
149}
150
151fn parse_markdown(
152 text: SharedString,
153 language_registry: Arc<LanguageRegistry>,
154 cx: &mut App,
155) -> Entity<Markdown> {
156 cx.new(|cx| Markdown::new(text, Some(language_registry), None, cx))
157}
158
159fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
160 let theme_settings = ThemeSettings::get_global(cx);
161 let colors = cx.theme().colors();
162 let ui_font_size = TextSize::Default.rems(cx);
163 let buffer_font_size = TextSize::Small.rems(cx);
164 let mut text_style = window.text_style();
165
166 text_style.refine(&TextStyleRefinement {
167 font_family: Some(theme_settings.ui_font.family.clone()),
168 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
169 font_features: Some(theme_settings.ui_font.features.clone()),
170 font_size: Some(ui_font_size.into()),
171 color: Some(cx.theme().colors().text),
172 ..Default::default()
173 });
174
175 MarkdownStyle {
176 base_text_style: text_style,
177 syntax: cx.theme().syntax().clone(),
178 selection_background_color: cx.theme().players().local().selection,
179 code_block_overflow_x_scroll: true,
180 table_overflow_x_scroll: true,
181 code_block: StyleRefinement {
182 padding: EdgesRefinement {
183 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
184 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
185 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
186 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
187 },
188 background: Some(colors.editor_background.into()),
189 text: Some(TextStyleRefinement {
190 font_family: Some(theme_settings.buffer_font.family.clone()),
191 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
192 font_features: Some(theme_settings.buffer_font.features.clone()),
193 font_size: Some(buffer_font_size.into()),
194 ..Default::default()
195 }),
196 ..Default::default()
197 },
198 inline_code: TextStyleRefinement {
199 font_family: Some(theme_settings.buffer_font.family.clone()),
200 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
201 font_features: Some(theme_settings.buffer_font.features.clone()),
202 font_size: Some(buffer_font_size.into()),
203 background_color: Some(colors.editor_foreground.opacity(0.08)),
204 ..Default::default()
205 },
206 link: TextStyleRefinement {
207 background_color: Some(colors.editor_foreground.opacity(0.025)),
208 underline: Some(UnderlineStyle {
209 color: Some(colors.text_accent.opacity(0.5)),
210 thickness: px(1.),
211 ..Default::default()
212 }),
213 ..Default::default()
214 },
215 link_callback: Some(Rc::new(move |url, cx| {
216 if MentionLink::is_valid(url) {
217 let colors = cx.theme().colors();
218 Some(TextStyleRefinement {
219 background_color: Some(colors.element_background),
220 ..Default::default()
221 })
222 } else {
223 None
224 }
225 })),
226 ..Default::default()
227 }
228}
229
230fn render_tool_use_markdown(
231 text: SharedString,
232 language_registry: Arc<LanguageRegistry>,
233 cx: &mut App,
234) -> Entity<Markdown> {
235 cx.new(|cx| Markdown::new(text, Some(language_registry), None, cx))
236}
237
238fn tool_use_markdown_style(window: &Window, cx: &mut App) -> MarkdownStyle {
239 let theme_settings = ThemeSettings::get_global(cx);
240 let colors = cx.theme().colors();
241 let ui_font_size = TextSize::Default.rems(cx);
242 let buffer_font_size = TextSize::Small.rems(cx);
243 let mut text_style = window.text_style();
244
245 text_style.refine(&TextStyleRefinement {
246 font_family: Some(theme_settings.ui_font.family.clone()),
247 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
248 font_features: Some(theme_settings.ui_font.features.clone()),
249 font_size: Some(ui_font_size.into()),
250 color: Some(cx.theme().colors().text),
251 ..Default::default()
252 });
253
254 MarkdownStyle {
255 base_text_style: text_style,
256 syntax: cx.theme().syntax().clone(),
257 selection_background_color: cx.theme().players().local().selection,
258 code_block_overflow_x_scroll: true,
259 code_block: StyleRefinement {
260 margin: EdgesRefinement::default(),
261 padding: EdgesRefinement::default(),
262 background: Some(colors.editor_background.into()),
263 border_color: None,
264 border_widths: EdgesRefinement::default(),
265 text: Some(TextStyleRefinement {
266 font_family: Some(theme_settings.buffer_font.family.clone()),
267 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
268 font_features: Some(theme_settings.buffer_font.features.clone()),
269 font_size: Some(buffer_font_size.into()),
270 ..Default::default()
271 }),
272 ..Default::default()
273 },
274 inline_code: TextStyleRefinement {
275 font_family: Some(theme_settings.buffer_font.family.clone()),
276 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
277 font_features: Some(theme_settings.buffer_font.features.clone()),
278 font_size: Some(TextSize::XSmall.rems(cx).into()),
279 ..Default::default()
280 },
281 heading: StyleRefinement {
282 text: Some(TextStyleRefinement {
283 font_size: Some(ui_font_size.into()),
284 ..Default::default()
285 }),
286 ..Default::default()
287 },
288 ..Default::default()
289 }
290}
291
292fn render_markdown_code_block(
293 message_id: MessageId,
294 ix: usize,
295 kind: &CodeBlockKind,
296 parsed_markdown: &ParsedMarkdown,
297 codeblock_range: Range<usize>,
298 active_thread: Entity<ActiveThread>,
299 workspace: WeakEntity<Workspace>,
300 _window: &mut Window,
301 cx: &App,
302) -> Div {
303 let label = match kind {
304 CodeBlockKind::Indented => None,
305 CodeBlockKind::Fenced => Some(
306 h_flex()
307 .gap_1()
308 .child(
309 Icon::new(IconName::Code)
310 .color(Color::Muted)
311 .size(IconSize::XSmall),
312 )
313 .child(Label::new("untitled").size(LabelSize::Small))
314 .into_any_element(),
315 ),
316 CodeBlockKind::FencedLang(raw_language_name) => Some(
317 h_flex()
318 .gap_1()
319 .children(
320 parsed_markdown
321 .languages_by_name
322 .get(raw_language_name)
323 .and_then(|language| {
324 language
325 .config()
326 .matcher
327 .path_suffixes
328 .iter()
329 .find_map(|extension| {
330 file_icons::FileIcons::get_icon(Path::new(extension), cx)
331 })
332 .map(Icon::from_path)
333 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
334 }),
335 )
336 .child(
337 Label::new(
338 parsed_markdown
339 .languages_by_name
340 .get(raw_language_name)
341 .map(|language| language.name().into())
342 .clone()
343 .unwrap_or_else(|| raw_language_name.clone()),
344 )
345 .size(LabelSize::Small),
346 )
347 .into_any_element(),
348 ),
349 CodeBlockKind::FencedSrc(path_range) => path_range.path.file_name().map(|file_name| {
350 let content = if let Some(parent) = path_range.path.parent() {
351 h_flex()
352 .ml_1()
353 .gap_1()
354 .child(
355 Label::new(file_name.to_string_lossy().to_string()).size(LabelSize::Small),
356 )
357 .child(
358 Label::new(parent.to_string_lossy().to_string())
359 .color(Color::Muted)
360 .size(LabelSize::Small),
361 )
362 .into_any_element()
363 } else {
364 Label::new(path_range.path.to_string_lossy().to_string())
365 .size(LabelSize::Small)
366 .ml_1()
367 .into_any_element()
368 };
369
370 h_flex()
371 .id(("code-block-header-label", ix))
372 .w_full()
373 .max_w_full()
374 .px_1()
375 .gap_0p5()
376 .cursor_pointer()
377 .rounded_sm()
378 .hover(|item| item.bg(cx.theme().colors().element_hover.opacity(0.5)))
379 .tooltip(Tooltip::text("Jump to File"))
380 .children(
381 file_icons::FileIcons::get_icon(&path_range.path, cx)
382 .map(Icon::from_path)
383 .map(|icon| icon.color(Color::Muted).size(IconSize::XSmall)),
384 )
385 .child(content)
386 .child(
387 Icon::new(IconName::ArrowUpRight)
388 .size(IconSize::XSmall)
389 .color(Color::Ignored),
390 )
391 .on_click({
392 let path_range = path_range.clone();
393 move |_, window, cx| {
394 workspace
395 .update(cx, {
396 |workspace, cx| {
397 if let Some(project_path) = workspace
398 .project()
399 .read(cx)
400 .find_project_path(&path_range.path, cx)
401 {
402 let target = path_range.range.as_ref().map(|range| {
403 Point::new(
404 // Line number is 1-based
405 range.start.line.saturating_sub(1),
406 range.start.col.unwrap_or(0),
407 )
408 });
409 let open_task = workspace.open_path(
410 project_path,
411 None,
412 true,
413 window,
414 cx,
415 );
416 window
417 .spawn(cx, async move |cx| {
418 let item = open_task.await?;
419 if let Some(target) = target {
420 if let Some(active_editor) =
421 item.downcast::<Editor>()
422 {
423 active_editor
424 .downgrade()
425 .update_in(cx, |editor, window, cx| {
426 editor
427 .go_to_singleton_buffer_point(
428 target, window, cx,
429 );
430 })
431 .log_err();
432 }
433 }
434 anyhow::Ok(())
435 })
436 .detach_and_log_err(cx);
437 }
438 }
439 })
440 .ok();
441 }
442 })
443 .into_any_element()
444 }),
445 };
446
447 let codeblock_header_bg = cx
448 .theme()
449 .colors()
450 .element_background
451 .blend(cx.theme().colors().editor_foreground.opacity(0.01));
452
453 let codeblock_was_copied = active_thread
454 .read(cx)
455 .copied_code_block_ids
456 .contains(&(message_id, ix));
457
458 let codeblock_header = h_flex()
459 .group("codeblock_header")
460 .p_1()
461 .gap_1()
462 .justify_between()
463 .border_b_1()
464 .border_color(cx.theme().colors().border_variant)
465 .bg(codeblock_header_bg)
466 .rounded_t_md()
467 .children(label)
468 .child(
469 div().visible_on_hover("codeblock_header").child(
470 IconButton::new(
471 ("copy-markdown-code", ix),
472 if codeblock_was_copied {
473 IconName::Check
474 } else {
475 IconName::Copy
476 },
477 )
478 .icon_color(Color::Muted)
479 .shape(ui::IconButtonShape::Square)
480 .tooltip(Tooltip::text("Copy Code"))
481 .on_click({
482 let active_thread = active_thread.clone();
483 let parsed_markdown = parsed_markdown.clone();
484 move |_event, _window, cx| {
485 active_thread.update(cx, |this, cx| {
486 this.copied_code_block_ids.insert((message_id, ix));
487
488 let code =
489 without_fences(&parsed_markdown.source()[codeblock_range.clone()])
490 .to_string();
491
492 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
493
494 cx.spawn(async move |this, cx| {
495 cx.background_executor().timer(Duration::from_secs(2)).await;
496
497 cx.update(|cx| {
498 this.update(cx, |this, cx| {
499 this.copied_code_block_ids.remove(&(message_id, ix));
500 cx.notify();
501 })
502 })
503 .ok();
504 })
505 .detach();
506 });
507 }
508 }),
509 ),
510 );
511
512 v_flex()
513 .mb_2()
514 .relative()
515 .overflow_hidden()
516 .rounded_lg()
517 .border_1()
518 .border_color(cx.theme().colors().border_variant)
519 .child(codeblock_header)
520}
521
522fn open_markdown_link(
523 text: SharedString,
524 workspace: WeakEntity<Workspace>,
525 window: &mut Window,
526 cx: &mut App,
527) {
528 let Some(workspace) = workspace.upgrade() else {
529 cx.open_url(&text);
530 return;
531 };
532
533 match MentionLink::try_parse(&text, &workspace, cx) {
534 Some(MentionLink::File(path, entry)) => workspace.update(cx, |workspace, cx| {
535 if entry.is_dir() {
536 workspace.project().update(cx, |_, cx| {
537 cx.emit(project::Event::RevealInProjectPanel(entry.id));
538 })
539 } else {
540 workspace
541 .open_path(path, None, true, window, cx)
542 .detach_and_log_err(cx);
543 }
544 }),
545 Some(MentionLink::Symbol(path, symbol_name)) => {
546 let open_task = workspace.update(cx, |workspace, cx| {
547 workspace.open_path(path, None, true, window, cx)
548 });
549 window
550 .spawn(cx, async move |cx| {
551 let active_editor = open_task
552 .await?
553 .downcast::<Editor>()
554 .context("Item is not an editor")?;
555 active_editor.update_in(cx, |editor, window, cx| {
556 let symbol_range = editor
557 .buffer()
558 .read(cx)
559 .snapshot(cx)
560 .outline(None)
561 .and_then(|outline| {
562 outline
563 .find_most_similar(&symbol_name)
564 .map(|(_, item)| item.range.clone())
565 })
566 .context("Could not find matching symbol")?;
567
568 editor.change_selections(Some(Autoscroll::center()), window, cx, |s| {
569 s.select_anchor_ranges([symbol_range.start..symbol_range.start])
570 });
571 anyhow::Ok(())
572 })
573 })
574 .detach_and_log_err(cx);
575 }
576 Some(MentionLink::Thread(thread_id)) => workspace.update(cx, |workspace, cx| {
577 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
578 panel.update(cx, |panel, cx| {
579 panel
580 .open_thread(&thread_id, window, cx)
581 .detach_and_log_err(cx)
582 });
583 }
584 }),
585 Some(MentionLink::Fetch(url)) => cx.open_url(&url),
586 None => cx.open_url(&text),
587 }
588}
589
590struct EditMessageState {
591 editor: Entity<Editor>,
592}
593
594impl ActiveThread {
595 pub fn new(
596 thread: Entity<Thread>,
597 thread_store: Entity<ThreadStore>,
598 language_registry: Arc<LanguageRegistry>,
599 context_store: Entity<ContextStore>,
600 workspace: WeakEntity<Workspace>,
601 window: &mut Window,
602 cx: &mut Context<Self>,
603 ) -> Self {
604 let subscriptions = vec![
605 cx.observe(&thread, |_, _, cx| cx.notify()),
606 cx.subscribe_in(&thread, window, Self::handle_thread_event),
607 ];
608
609 let list_state = ListState::new(0, ListAlignment::Bottom, px(2048.), {
610 let this = cx.entity().downgrade();
611 move |ix, window: &mut Window, cx: &mut App| {
612 this.update(cx, |this, cx| this.render_message(ix, window, cx))
613 .unwrap()
614 }
615 });
616
617 let mut this = Self {
618 language_registry,
619 thread_store,
620 thread: thread.clone(),
621 context_store,
622 workspace,
623 save_thread_task: None,
624 messages: Vec::new(),
625 rendered_messages_by_id: HashMap::default(),
626 rendered_tool_uses: HashMap::default(),
627 expanded_tool_uses: HashMap::default(),
628 expanded_thinking_segments: HashMap::default(),
629 list_state: list_state.clone(),
630 scrollbar_state: ScrollbarState::new(list_state),
631 show_scrollbar: false,
632 hide_scrollbar_task: None,
633 editing_message: None,
634 last_error: None,
635 copied_code_block_ids: HashSet::default(),
636 notifications: Vec::new(),
637 _subscriptions: subscriptions,
638 notification_subscriptions: HashMap::default(),
639 feedback_message_editor: None,
640 };
641
642 for message in thread.read(cx).messages().cloned().collect::<Vec<_>>() {
643 this.push_message(&message.id, &message.segments, window, cx);
644
645 for tool_use in thread.read(cx).tool_uses_for_message(message.id, cx) {
646 this.render_tool_use_markdown(
647 tool_use.id.clone(),
648 tool_use.ui_text.clone(),
649 &tool_use.input,
650 tool_use.status.text(),
651 cx,
652 );
653 }
654 }
655
656 this
657 }
658
659 pub fn thread(&self) -> &Entity<Thread> {
660 &self.thread
661 }
662
663 pub fn is_empty(&self) -> bool {
664 self.messages.is_empty()
665 }
666
667 pub fn summary(&self, cx: &App) -> Option<SharedString> {
668 self.thread.read(cx).summary()
669 }
670
671 pub fn summary_or_default(&self, cx: &App) -> SharedString {
672 self.thread.read(cx).summary_or_default()
673 }
674
675 pub fn cancel_last_completion(&mut self, cx: &mut App) -> bool {
676 self.last_error.take();
677 self.thread
678 .update(cx, |thread, cx| thread.cancel_last_completion(cx))
679 }
680
681 pub fn last_error(&self) -> Option<ThreadError> {
682 self.last_error.clone()
683 }
684
685 pub fn clear_last_error(&mut self) {
686 self.last_error.take();
687 }
688
689 fn push_message(
690 &mut self,
691 id: &MessageId,
692 segments: &[MessageSegment],
693 _window: &mut Window,
694 cx: &mut Context<Self>,
695 ) {
696 let old_len = self.messages.len();
697 self.messages.push(*id);
698 self.list_state.splice(old_len..old_len, 1);
699
700 let rendered_message =
701 RenderedMessage::from_segments(segments, self.language_registry.clone(), cx);
702 self.rendered_messages_by_id.insert(*id, rendered_message);
703 }
704
705 fn edited_message(
706 &mut self,
707 id: &MessageId,
708 segments: &[MessageSegment],
709 _window: &mut Window,
710 cx: &mut Context<Self>,
711 ) {
712 let Some(index) = self.messages.iter().position(|message_id| message_id == id) else {
713 return;
714 };
715 self.list_state.splice(index..index + 1, 1);
716 let rendered_message =
717 RenderedMessage::from_segments(segments, self.language_registry.clone(), cx);
718 self.rendered_messages_by_id.insert(*id, rendered_message);
719 }
720
721 fn deleted_message(&mut self, id: &MessageId) {
722 let Some(index) = self.messages.iter().position(|message_id| message_id == id) else {
723 return;
724 };
725 self.messages.remove(index);
726 self.list_state.splice(index..index + 1, 0);
727 self.rendered_messages_by_id.remove(id);
728 }
729
730 fn render_tool_use_markdown(
731 &mut self,
732 tool_use_id: LanguageModelToolUseId,
733 tool_label: impl Into<SharedString>,
734 tool_input: &serde_json::Value,
735 tool_output: SharedString,
736 cx: &mut Context<Self>,
737 ) {
738 let rendered = RenderedToolUse {
739 label: render_tool_use_markdown(tool_label.into(), self.language_registry.clone(), cx),
740 input: render_tool_use_markdown(
741 format!(
742 "```json\n{}\n```",
743 serde_json::to_string_pretty(tool_input).unwrap_or_default()
744 )
745 .into(),
746 self.language_registry.clone(),
747 cx,
748 ),
749 output: render_tool_use_markdown(tool_output, self.language_registry.clone(), cx),
750 };
751 self.rendered_tool_uses
752 .insert(tool_use_id.clone(), rendered);
753 }
754
755 fn handle_thread_event(
756 &mut self,
757 _thread: &Entity<Thread>,
758 event: &ThreadEvent,
759 window: &mut Window,
760 cx: &mut Context<Self>,
761 ) {
762 match event {
763 ThreadEvent::ShowError(error) => {
764 self.last_error = Some(error.clone());
765 }
766 ThreadEvent::StreamedCompletion
767 | ThreadEvent::SummaryGenerated
768 | ThreadEvent::SummaryChanged => {
769 self.save_thread(cx);
770 }
771 ThreadEvent::DoneStreaming => {
772 let thread = self.thread.read(cx);
773
774 if !thread.is_generating() {
775 self.show_notification(
776 if thread.used_tools_since_last_user_message() {
777 "Finished running tools"
778 } else {
779 "New message"
780 },
781 IconName::ZedAssistant,
782 window,
783 cx,
784 );
785 }
786 }
787 ThreadEvent::ToolConfirmationNeeded => {
788 self.show_notification("Waiting for tool confirmation", IconName::Info, window, cx);
789 }
790 ThreadEvent::StreamedAssistantText(message_id, text) => {
791 if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
792 rendered_message.append_text(text, cx);
793 }
794 }
795 ThreadEvent::StreamedAssistantThinking(message_id, text) => {
796 if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
797 rendered_message.append_thinking(text, cx);
798 }
799 }
800 ThreadEvent::MessageAdded(message_id) => {
801 if let Some(message_segments) = self
802 .thread
803 .read(cx)
804 .message(*message_id)
805 .map(|message| message.segments.clone())
806 {
807 self.push_message(message_id, &message_segments, window, cx);
808 }
809
810 self.save_thread(cx);
811 cx.notify();
812 }
813 ThreadEvent::MessageEdited(message_id) => {
814 if let Some(message_segments) = self
815 .thread
816 .read(cx)
817 .message(*message_id)
818 .map(|message| message.segments.clone())
819 {
820 self.edited_message(message_id, &message_segments, window, cx);
821 }
822
823 self.save_thread(cx);
824 cx.notify();
825 }
826 ThreadEvent::MessageDeleted(message_id) => {
827 self.deleted_message(message_id);
828 self.save_thread(cx);
829 cx.notify();
830 }
831 ThreadEvent::UsePendingTools => {
832 let tool_uses = self
833 .thread
834 .update(cx, |thread, cx| thread.use_pending_tools(cx));
835
836 for tool_use in tool_uses {
837 self.render_tool_use_markdown(
838 tool_use.id.clone(),
839 tool_use.ui_text.clone(),
840 &tool_use.input,
841 "".into(),
842 cx,
843 );
844 }
845 }
846 ThreadEvent::ToolFinished {
847 pending_tool_use,
848 canceled,
849 ..
850 } => {
851 let canceled = *canceled;
852 if let Some(tool_use) = pending_tool_use {
853 self.render_tool_use_markdown(
854 tool_use.id.clone(),
855 tool_use.ui_text.clone(),
856 &tool_use.input,
857 self.thread
858 .read(cx)
859 .tool_result(&tool_use.id)
860 .map(|result| result.content.clone().into())
861 .unwrap_or("".into()),
862 cx,
863 );
864 }
865
866 if self.thread.read(cx).all_tools_finished() {
867 let model_registry = LanguageModelRegistry::read_global(cx);
868 if let Some(ConfiguredModel { model, .. }) = model_registry.default_model() {
869 self.thread.update(cx, |thread, cx| {
870 thread.attach_tool_results(cx);
871 if !canceled {
872 thread.send_to_model(model, RequestKind::Chat, cx);
873 }
874 });
875 }
876 }
877 }
878 ThreadEvent::CheckpointChanged => cx.notify(),
879 }
880 }
881
882 fn show_notification(
883 &mut self,
884 caption: impl Into<SharedString>,
885 icon: IconName,
886 window: &mut Window,
887 cx: &mut Context<ActiveThread>,
888 ) {
889 if window.is_window_active() || !self.notifications.is_empty() {
890 return;
891 }
892
893 let title = self
894 .thread
895 .read(cx)
896 .summary()
897 .unwrap_or("Agent Panel".into());
898
899 match AssistantSettings::get_global(cx).notify_when_agent_waiting {
900 NotifyWhenAgentWaiting::PrimaryScreen => {
901 if let Some(primary) = cx.primary_display() {
902 self.pop_up(icon, caption.into(), title.clone(), window, primary, cx);
903 }
904 }
905 NotifyWhenAgentWaiting::AllScreens => {
906 let caption = caption.into();
907 for screen in cx.displays() {
908 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
909 }
910 }
911 NotifyWhenAgentWaiting::Never => {
912 // Don't show anything
913 }
914 }
915 }
916
917 fn pop_up(
918 &mut self,
919 icon: IconName,
920 caption: SharedString,
921 title: SharedString,
922 window: &mut Window,
923 screen: Rc<dyn PlatformDisplay>,
924 cx: &mut Context<'_, ActiveThread>,
925 ) {
926 let options = AgentNotification::window_options(screen, cx);
927
928 if let Some(screen_window) = cx
929 .open_window(options, |_, cx| {
930 cx.new(|_| AgentNotification::new(title.clone(), caption.clone(), icon))
931 })
932 .log_err()
933 {
934 if let Some(pop_up) = screen_window.entity(cx).log_err() {
935 self.notification_subscriptions
936 .entry(screen_window)
937 .or_insert_with(Vec::new)
938 .push(cx.subscribe_in(&pop_up, window, {
939 |this, _, event, window, cx| match event {
940 AgentNotificationEvent::Accepted => {
941 let handle = window.window_handle();
942 cx.activate(true); // Switch back to the Zed application
943
944 let workspace_handle = this.workspace.clone();
945
946 // If there are multiple Zed windows, activate the correct one.
947 cx.defer(move |cx| {
948 handle
949 .update(cx, |_view, window, _cx| {
950 window.activate_window();
951
952 if let Some(workspace) = workspace_handle.upgrade() {
953 workspace.update(_cx, |workspace, cx| {
954 workspace
955 .focus_panel::<AssistantPanel>(window, cx);
956 });
957 }
958 })
959 .log_err();
960 });
961
962 this.dismiss_notifications(cx);
963 }
964 AgentNotificationEvent::Dismissed => {
965 this.dismiss_notifications(cx);
966 }
967 }
968 }));
969
970 self.notifications.push(screen_window);
971
972 // If the user manually refocuses the original window, dismiss the popup.
973 self.notification_subscriptions
974 .entry(screen_window)
975 .or_insert_with(Vec::new)
976 .push({
977 let pop_up_weak = pop_up.downgrade();
978
979 cx.observe_window_activation(window, move |_, window, cx| {
980 if window.is_window_active() {
981 if let Some(pop_up) = pop_up_weak.upgrade() {
982 pop_up.update(cx, |_, cx| {
983 cx.emit(AgentNotificationEvent::Dismissed);
984 });
985 }
986 }
987 })
988 });
989 }
990 }
991 }
992
993 /// Spawns a task to save the active thread.
994 ///
995 /// Only one task to save the thread will be in flight at a time.
996 fn save_thread(&mut self, cx: &mut Context<Self>) {
997 let thread = self.thread.clone();
998 self.save_thread_task = Some(cx.spawn(async move |this, cx| {
999 let task = this
1000 .update(cx, |this, cx| {
1001 this.thread_store
1002 .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
1003 })
1004 .ok();
1005
1006 if let Some(task) = task {
1007 task.await.log_err();
1008 }
1009 }));
1010 }
1011
1012 fn start_editing_message(
1013 &mut self,
1014 message_id: MessageId,
1015 message_segments: &[MessageSegment],
1016 window: &mut Window,
1017 cx: &mut Context<Self>,
1018 ) {
1019 // User message should always consist of a single text segment,
1020 // therefore we can skip returning early if it's not a text segment.
1021 let Some(MessageSegment::Text(message_text)) = message_segments.first() else {
1022 return;
1023 };
1024
1025 let buffer = cx.new(|cx| {
1026 MultiBuffer::singleton(cx.new(|cx| Buffer::local(message_text.clone(), cx)), cx)
1027 });
1028 let editor = cx.new(|cx| {
1029 let mut editor = Editor::new(
1030 editor::EditorMode::AutoHeight { max_lines: 8 },
1031 buffer,
1032 None,
1033 window,
1034 cx,
1035 );
1036 editor.focus_handle(cx).focus(window);
1037 editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
1038 editor
1039 });
1040 self.editing_message = Some((
1041 message_id,
1042 EditMessageState {
1043 editor: editor.clone(),
1044 },
1045 ));
1046 cx.notify();
1047 }
1048
1049 fn cancel_editing_message(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
1050 self.editing_message.take();
1051 cx.notify();
1052 }
1053
1054 fn confirm_editing_message(
1055 &mut self,
1056 _: &menu::Confirm,
1057 _: &mut Window,
1058 cx: &mut Context<Self>,
1059 ) {
1060 let Some((message_id, state)) = self.editing_message.take() else {
1061 return;
1062 };
1063 let edited_text = state.editor.read(cx).text(cx);
1064 self.thread.update(cx, |thread, cx| {
1065 thread.edit_message(
1066 message_id,
1067 Role::User,
1068 vec![MessageSegment::Text(edited_text)],
1069 cx,
1070 );
1071 for message_id in self.messages_after(message_id) {
1072 thread.delete_message(*message_id, cx);
1073 }
1074 });
1075
1076 let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1077 return;
1078 };
1079
1080 if model.provider.must_accept_terms(cx) {
1081 cx.notify();
1082 return;
1083 }
1084
1085 self.thread.update(cx, |thread, cx| {
1086 thread.send_to_model(model.model, RequestKind::Chat, cx)
1087 });
1088 cx.notify();
1089 }
1090
1091 fn messages_after(&self, message_id: MessageId) -> &[MessageId] {
1092 self.messages
1093 .iter()
1094 .position(|id| *id == message_id)
1095 .map(|index| &self.messages[index + 1..])
1096 .unwrap_or(&[])
1097 }
1098
1099 fn handle_cancel_click(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1100 self.cancel_editing_message(&menu::Cancel, window, cx);
1101 }
1102
1103 fn handle_regenerate_click(
1104 &mut self,
1105 _: &ClickEvent,
1106 window: &mut Window,
1107 cx: &mut Context<Self>,
1108 ) {
1109 self.confirm_editing_message(&menu::Confirm, window, cx);
1110 }
1111
1112 fn handle_feedback_click(
1113 &mut self,
1114 feedback: ThreadFeedback,
1115 window: &mut Window,
1116 cx: &mut Context<Self>,
1117 ) {
1118 match feedback {
1119 ThreadFeedback::Positive => {
1120 let report = self
1121 .thread
1122 .update(cx, |thread, cx| thread.report_feedback(feedback, cx));
1123
1124 let this = cx.entity().downgrade();
1125 cx.spawn(async move |_, cx| {
1126 report.await?;
1127 this.update(cx, |_this, cx| cx.notify())
1128 })
1129 .detach_and_log_err(cx);
1130 }
1131 ThreadFeedback::Negative => {
1132 self.handle_show_feedback_comments(window, cx);
1133 }
1134 }
1135 }
1136
1137 fn handle_show_feedback_comments(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1138 if self.feedback_message_editor.is_some() {
1139 return;
1140 }
1141
1142 let buffer = cx.new(|cx| {
1143 let empty_string = String::new();
1144 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
1145 });
1146
1147 let editor = cx.new(|cx| {
1148 let mut editor = Editor::new(
1149 editor::EditorMode::AutoHeight { max_lines: 4 },
1150 buffer,
1151 None,
1152 window,
1153 cx,
1154 );
1155 editor.set_placeholder_text(
1156 "What went wrong? Share your feedback so we can improve.",
1157 cx,
1158 );
1159 editor
1160 });
1161
1162 editor.read(cx).focus_handle(cx).focus(window);
1163 self.feedback_message_editor = Some(editor);
1164 cx.notify();
1165 }
1166
1167 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
1168 let Some(editor) = self.feedback_message_editor.clone() else {
1169 return;
1170 };
1171
1172 let report_task = self.thread.update(cx, |thread, cx| {
1173 thread.report_feedback(ThreadFeedback::Negative, cx)
1174 });
1175
1176 let comments = editor.read(cx).text(cx);
1177 if !comments.is_empty() {
1178 let thread_id = self.thread.read(cx).id().clone();
1179
1180 telemetry::event!("Assistant Thread Feedback Comments", thread_id, comments);
1181 }
1182
1183 self.feedback_message_editor = None;
1184
1185 let this = cx.entity().downgrade();
1186 cx.spawn(async move |_, cx| {
1187 report_task.await?;
1188 this.update(cx, |_this, cx| cx.notify())
1189 })
1190 .detach_and_log_err(cx);
1191 }
1192
1193 fn render_message(&self, ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1194 let message_id = self.messages[ix];
1195 let Some(message) = self.thread.read(cx).message(message_id) else {
1196 return Empty.into_any();
1197 };
1198
1199 let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1200 return Empty.into_any();
1201 };
1202
1203 let context_store = self.context_store.clone();
1204 let workspace = self.workspace.clone();
1205 let thread = self.thread.read(cx);
1206
1207 // Get all the data we need from thread before we start using it in closures
1208 let checkpoint = thread.checkpoint_for_message(message_id);
1209 let context = thread.context_for_message(message_id).collect::<Vec<_>>();
1210
1211 let tool_uses = thread.tool_uses_for_message(message_id, cx);
1212 let has_tool_uses = !tool_uses.is_empty();
1213 let is_generating = thread.is_generating();
1214
1215 let is_first_message = ix == 0;
1216 let is_last_message = ix == self.messages.len() - 1;
1217 let show_feedback = is_last_message && message.role != Role::User;
1218
1219 let needs_confirmation = tool_uses.iter().any(|tool_use| tool_use.needs_confirmation);
1220
1221 let generating_label = (is_generating && is_last_message).then(|| {
1222 Label::new("Generating")
1223 .color(Color::Muted)
1224 .size(LabelSize::Small)
1225 .with_animations(
1226 "generating-label",
1227 vec![
1228 Animation::new(Duration::from_secs(1)),
1229 Animation::new(Duration::from_secs(1)).repeat(),
1230 ],
1231 |mut label, animation_ix, delta| {
1232 match animation_ix {
1233 0 => {
1234 let chars_to_show = (delta * 10.).ceil() as usize;
1235 let text = &"Generating"[0..chars_to_show];
1236 label.set_text(text);
1237 }
1238 1 => {
1239 let text = match delta {
1240 d if d < 0.25 => "Generating",
1241 d if d < 0.5 => "Generating.",
1242 d if d < 0.75 => "Generating..",
1243 _ => "Generating...",
1244 };
1245 label.set_text(text);
1246 }
1247 _ => {}
1248 }
1249 label
1250 },
1251 )
1252 .with_animation(
1253 "pulsating-label",
1254 Animation::new(Duration::from_secs(2))
1255 .repeat()
1256 .with_easing(pulsating_between(0.6, 1.)),
1257 |label, delta| label.map_element(|label| label.alpha(delta)),
1258 )
1259 });
1260
1261 // Don't render user messages that are just there for returning tool results.
1262 if message.role == Role::User && thread.message_has_tool_results(message_id) {
1263 if let Some(generating_label) = generating_label {
1264 return h_flex()
1265 .w_full()
1266 .h_10()
1267 .py_1p5()
1268 .pl_4()
1269 .pb_3()
1270 .child(generating_label)
1271 .into_any_element();
1272 }
1273
1274 return Empty.into_any();
1275 }
1276
1277 let allow_editing_message = message.role == Role::User;
1278
1279 let edit_message_editor = self
1280 .editing_message
1281 .as_ref()
1282 .filter(|(id, _)| *id == message_id)
1283 .map(|(_, state)| state.editor.clone());
1284
1285 let colors = cx.theme().colors();
1286 let active_color = colors.element_active;
1287 let editor_bg_color = colors.editor_background;
1288 let bg_user_message_header = editor_bg_color.blend(active_color.opacity(0.25));
1289
1290 let feedback_container = h_flex().pt_2().pb_4().px_4().gap_1().justify_between();
1291 let feedback_items = match self.thread.read(cx).feedback() {
1292 Some(feedback) => feedback_container
1293 .child(
1294 Label::new(match feedback {
1295 ThreadFeedback::Positive => "Thanks for your feedback!",
1296 ThreadFeedback::Negative => {
1297 "We appreciate your feedback and will use it to improve."
1298 }
1299 })
1300 .color(Color::Muted)
1301 .size(LabelSize::XSmall),
1302 )
1303 .child(
1304 h_flex()
1305 .gap_1()
1306 .child(
1307 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
1308 .icon_size(IconSize::XSmall)
1309 .icon_color(match feedback {
1310 ThreadFeedback::Positive => Color::Accent,
1311 ThreadFeedback::Negative => Color::Ignored,
1312 })
1313 .shape(ui::IconButtonShape::Square)
1314 .tooltip(Tooltip::text("Helpful Response"))
1315 .on_click(cx.listener(move |this, _, window, cx| {
1316 this.handle_feedback_click(
1317 ThreadFeedback::Positive,
1318 window,
1319 cx,
1320 );
1321 })),
1322 )
1323 .child(
1324 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
1325 .icon_size(IconSize::XSmall)
1326 .icon_color(match feedback {
1327 ThreadFeedback::Positive => Color::Ignored,
1328 ThreadFeedback::Negative => Color::Accent,
1329 })
1330 .shape(ui::IconButtonShape::Square)
1331 .tooltip(Tooltip::text("Not Helpful"))
1332 .on_click(cx.listener(move |this, _, window, cx| {
1333 this.handle_feedback_click(
1334 ThreadFeedback::Negative,
1335 window,
1336 cx,
1337 );
1338 })),
1339 ),
1340 )
1341 .into_any_element(),
1342 None => feedback_container
1343 .child(
1344 Label::new(
1345 "Rating the thread sends all of your current conversation to the Zed team.",
1346 )
1347 .color(Color::Muted)
1348 .size(LabelSize::XSmall),
1349 )
1350 .child(
1351 h_flex()
1352 .gap_1()
1353 .child(
1354 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
1355 .icon_size(IconSize::XSmall)
1356 .icon_color(Color::Ignored)
1357 .shape(ui::IconButtonShape::Square)
1358 .tooltip(Tooltip::text("Helpful Response"))
1359 .on_click(cx.listener(move |this, _, window, cx| {
1360 this.handle_feedback_click(
1361 ThreadFeedback::Positive,
1362 window,
1363 cx,
1364 );
1365 })),
1366 )
1367 .child(
1368 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
1369 .icon_size(IconSize::XSmall)
1370 .icon_color(Color::Ignored)
1371 .shape(ui::IconButtonShape::Square)
1372 .tooltip(Tooltip::text("Not Helpful"))
1373 .on_click(cx.listener(move |this, _, window, cx| {
1374 this.handle_feedback_click(
1375 ThreadFeedback::Negative,
1376 window,
1377 cx,
1378 );
1379 })),
1380 ),
1381 )
1382 .into_any_element(),
1383 };
1384
1385 let message_is_empty = message.should_display_content();
1386 let has_content = !message_is_empty || !context.is_empty();
1387
1388 let message_content =
1389 has_content.then(|| {
1390 v_flex()
1391 .gap_1p5()
1392 .when(!message_is_empty, |parent| {
1393 parent.child(
1394 if let Some(edit_message_editor) = edit_message_editor.clone() {
1395 div()
1396 .key_context("EditMessageEditor")
1397 .on_action(cx.listener(Self::cancel_editing_message))
1398 .on_action(cx.listener(Self::confirm_editing_message))
1399 .min_h_6()
1400 .child(edit_message_editor)
1401 .into_any()
1402 } else {
1403 div()
1404 .min_h_6()
1405 .text_ui(cx)
1406 .child(self.render_message_content(
1407 message_id,
1408 rendered_message,
1409 has_tool_uses,
1410 workspace.clone(),
1411 window,
1412 cx,
1413 ))
1414 .into_any()
1415 },
1416 )
1417 })
1418 .when(!context.is_empty(), |parent| {
1419 parent.child(h_flex().flex_wrap().gap_1().children(
1420 context.into_iter().map(|context| {
1421 let context_id = context.id();
1422 ContextPill::added(
1423 AddedContext::new(context, cx),
1424 false,
1425 false,
1426 None,
1427 )
1428 .on_click(Rc::new(cx.listener({
1429 let workspace = workspace.clone();
1430 let context_store = context_store.clone();
1431 move |_, _, window, cx| {
1432 if let Some(workspace) = workspace.upgrade() {
1433 open_context(
1434 context_id,
1435 context_store.clone(),
1436 workspace,
1437 window,
1438 cx,
1439 );
1440 cx.notify();
1441 }
1442 }
1443 })))
1444 }),
1445 ))
1446 })
1447 });
1448
1449 let styled_message = match message.role {
1450 Role::User => v_flex()
1451 .id(("message-container", ix))
1452 .map(|this| {
1453 if is_first_message {
1454 this.pt_2()
1455 } else {
1456 this.pt_4()
1457 }
1458 })
1459 .pb_4()
1460 .pl_2()
1461 .pr_2p5()
1462 .child(
1463 v_flex()
1464 .bg(colors.editor_background)
1465 .rounded_lg()
1466 .border_1()
1467 .border_color(colors.border)
1468 .shadow_md()
1469 .child(
1470 h_flex()
1471 .py_1()
1472 .pl_2()
1473 .pr_1()
1474 .bg(bg_user_message_header)
1475 .border_b_1()
1476 .border_color(colors.border)
1477 .justify_between()
1478 .rounded_t_md()
1479 .child(
1480 h_flex()
1481 .gap_1p5()
1482 .child(
1483 Icon::new(IconName::PersonCircle)
1484 .size(IconSize::XSmall)
1485 .color(Color::Muted),
1486 )
1487 .child(
1488 Label::new("You")
1489 .size(LabelSize::Small)
1490 .color(Color::Muted),
1491 ),
1492 )
1493 .child(
1494 h_flex()
1495 .gap_1()
1496 .when_some(
1497 edit_message_editor.clone(),
1498 |this, edit_message_editor| {
1499 let focus_handle =
1500 edit_message_editor.focus_handle(cx);
1501 this.child(
1502 Button::new("cancel-edit-message", "Cancel")
1503 .label_size(LabelSize::Small)
1504 .key_binding(
1505 KeyBinding::for_action_in(
1506 &menu::Cancel,
1507 &focus_handle,
1508 window,
1509 cx,
1510 )
1511 .map(|kb| kb.size(rems_from_px(12.))),
1512 )
1513 .on_click(
1514 cx.listener(Self::handle_cancel_click),
1515 ),
1516 )
1517 .child(
1518 Button::new(
1519 "confirm-edit-message",
1520 "Regenerate",
1521 )
1522 .label_size(LabelSize::Small)
1523 .key_binding(
1524 KeyBinding::for_action_in(
1525 &menu::Confirm,
1526 &focus_handle,
1527 window,
1528 cx,
1529 )
1530 .map(|kb| kb.size(rems_from_px(12.))),
1531 )
1532 .on_click(
1533 cx.listener(Self::handle_regenerate_click),
1534 ),
1535 )
1536 },
1537 )
1538 .when(
1539 edit_message_editor.is_none() && allow_editing_message,
1540 |this| {
1541 this.child(
1542 Button::new("edit-message", "Edit")
1543 .label_size(LabelSize::Small)
1544 .on_click(cx.listener({
1545 let message_segments =
1546 message.segments.clone();
1547 move |this, _, window, cx| {
1548 this.start_editing_message(
1549 message_id,
1550 &message_segments,
1551 window,
1552 cx,
1553 );
1554 }
1555 })),
1556 )
1557 },
1558 ),
1559 ),
1560 )
1561 .child(div().p_2().children(message_content)),
1562 ),
1563 Role::Assistant => v_flex()
1564 .id(("message-container", ix))
1565 .ml_2()
1566 .pl_2()
1567 .pr_4()
1568 .border_l_1()
1569 .border_color(cx.theme().colors().border_variant)
1570 .children(message_content)
1571 .when(has_tool_uses, |parent| {
1572 parent.children(
1573 tool_uses
1574 .into_iter()
1575 .map(|tool_use| self.render_tool_use(tool_use, window, cx)),
1576 )
1577 }),
1578 Role::System => div().id(("message-container", ix)).py_1().px_2().child(
1579 v_flex()
1580 .bg(colors.editor_background)
1581 .rounded_sm()
1582 .child(div().p_4().children(message_content)),
1583 ),
1584 };
1585
1586 v_flex()
1587 .w_full()
1588 .when_some(checkpoint, |parent, checkpoint| {
1589 let mut is_pending = false;
1590 let mut error = None;
1591 if let Some(last_restore_checkpoint) =
1592 self.thread.read(cx).last_restore_checkpoint()
1593 {
1594 if last_restore_checkpoint.message_id() == message_id {
1595 match last_restore_checkpoint {
1596 LastRestoreCheckpoint::Pending { .. } => is_pending = true,
1597 LastRestoreCheckpoint::Error { error: err, .. } => {
1598 error = Some(err.clone());
1599 }
1600 }
1601 }
1602 }
1603
1604 let restore_checkpoint_button =
1605 Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
1606 .icon(if error.is_some() {
1607 IconName::XCircle
1608 } else {
1609 IconName::Undo
1610 })
1611 .icon_size(IconSize::XSmall)
1612 .icon_position(IconPosition::Start)
1613 .icon_color(if error.is_some() {
1614 Some(Color::Error)
1615 } else {
1616 None
1617 })
1618 .label_size(LabelSize::XSmall)
1619 .disabled(is_pending)
1620 .on_click(cx.listener(move |this, _, _window, cx| {
1621 this.thread.update(cx, |thread, cx| {
1622 thread
1623 .restore_checkpoint(checkpoint.clone(), cx)
1624 .detach_and_log_err(cx);
1625 });
1626 }));
1627
1628 let restore_checkpoint_button = if is_pending {
1629 restore_checkpoint_button
1630 .with_animation(
1631 ("pulsating-restore-checkpoint-button", ix),
1632 Animation::new(Duration::from_secs(2))
1633 .repeat()
1634 .with_easing(pulsating_between(0.6, 1.)),
1635 |label, delta| label.alpha(delta),
1636 )
1637 .into_any_element()
1638 } else if let Some(error) = error {
1639 restore_checkpoint_button
1640 .tooltip(Tooltip::text(error.to_string()))
1641 .into_any_element()
1642 } else {
1643 restore_checkpoint_button.into_any_element()
1644 };
1645
1646 parent.child(
1647 h_flex()
1648 .pt_2p5()
1649 .px_2p5()
1650 .w_full()
1651 .gap_1()
1652 .child(ui::Divider::horizontal())
1653 .child(restore_checkpoint_button)
1654 .child(ui::Divider::horizontal()),
1655 )
1656 })
1657 .when(is_first_message, |parent| {
1658 parent.child(self.render_rules_item(cx))
1659 })
1660 .child(styled_message)
1661 .when(!needs_confirmation && generating_label.is_some(), |this| {
1662 this.child(
1663 h_flex()
1664 .h_8()
1665 .mt_2()
1666 .mb_4()
1667 .ml_4()
1668 .py_1p5()
1669 .child(generating_label.unwrap()),
1670 )
1671 })
1672 .when(show_feedback && !is_generating, |parent| {
1673 parent.child(feedback_items).when_some(
1674 self.feedback_message_editor.clone(),
1675 |parent, feedback_editor| {
1676 let focus_handle = feedback_editor.focus_handle(cx);
1677 parent.child(
1678 v_flex()
1679 .key_context("AgentFeedbackMessageEditor")
1680 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
1681 this.feedback_message_editor = None;
1682 cx.notify();
1683 }))
1684 .on_action(cx.listener(|this, _: &menu::Confirm, _, cx| {
1685 this.submit_feedback_message(cx);
1686 cx.notify();
1687 }))
1688 .on_action(cx.listener(Self::confirm_editing_message))
1689 .my_3()
1690 .mx_4()
1691 .p_2()
1692 .rounded_md()
1693 .border_1()
1694 .border_color(cx.theme().colors().border)
1695 .bg(cx.theme().colors().editor_background)
1696 .child(feedback_editor)
1697 .child(
1698 h_flex()
1699 .gap_1()
1700 .justify_end()
1701 .child(
1702 Button::new("dismiss-feedback-message", "Cancel")
1703 .label_size(LabelSize::Small)
1704 .key_binding(
1705 KeyBinding::for_action_in(
1706 &menu::Cancel,
1707 &focus_handle,
1708 window,
1709 cx,
1710 )
1711 .map(|kb| kb.size(rems_from_px(10.))),
1712 )
1713 .on_click(cx.listener(|this, _, _, cx| {
1714 this.feedback_message_editor = None;
1715 cx.notify();
1716 })),
1717 )
1718 .child(
1719 Button::new(
1720 "submit-feedback-message",
1721 "Share Feedback",
1722 )
1723 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1724 .label_size(LabelSize::Small)
1725 .key_binding(
1726 KeyBinding::for_action_in(
1727 &menu::Confirm,
1728 &focus_handle,
1729 window,
1730 cx,
1731 )
1732 .map(|kb| kb.size(rems_from_px(10.))),
1733 )
1734 .on_click(
1735 cx.listener(|this, _, _, cx| {
1736 this.submit_feedback_message(cx);
1737 cx.notify();
1738 }),
1739 ),
1740 ),
1741 ),
1742 )
1743 },
1744 )
1745 })
1746 .into_any()
1747 }
1748
1749 fn render_message_content(
1750 &self,
1751 message_id: MessageId,
1752 rendered_message: &RenderedMessage,
1753 has_tool_uses: bool,
1754 workspace: WeakEntity<Workspace>,
1755 window: &Window,
1756 cx: &Context<Self>,
1757 ) -> impl IntoElement {
1758 let is_last_message = self.messages.last() == Some(&message_id);
1759 let is_generating = self.thread.read(cx).is_generating();
1760 let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
1761 rendered_message
1762 .segments
1763 .iter()
1764 .enumerate()
1765 .next_back()
1766 .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
1767 .map(|(index, _)| index)
1768 } else {
1769 None
1770 };
1771
1772 v_flex()
1773 .text_ui(cx)
1774 .gap_2()
1775 .children(
1776 rendered_message.segments.iter().enumerate().map(
1777 |(index, segment)| match segment {
1778 RenderedMessageSegment::Thinking {
1779 content,
1780 scroll_handle,
1781 } => self
1782 .render_message_thinking_segment(
1783 message_id,
1784 index,
1785 content.clone(),
1786 &scroll_handle,
1787 Some(index) == pending_thinking_segment_index,
1788 window,
1789 cx,
1790 )
1791 .into_any_element(),
1792 RenderedMessageSegment::Text(markdown) => div()
1793 .child(
1794 MarkdownElement::new(
1795 markdown.clone(),
1796 default_markdown_style(window, cx),
1797 )
1798 .code_block_renderer(markdown::CodeBlockRenderer::Custom {
1799 render: Arc::new({
1800 let workspace = workspace.clone();
1801 let active_thread = cx.entity();
1802 move |id, kind, parsed_markdown, range, window, cx| {
1803 render_markdown_code_block(
1804 message_id,
1805 id,
1806 kind,
1807 parsed_markdown,
1808 range,
1809 active_thread.clone(),
1810 workspace.clone(),
1811 window,
1812 cx,
1813 )
1814 }
1815 }),
1816 })
1817 .on_url_click({
1818 let workspace = self.workspace.clone();
1819 move |text, window, cx| {
1820 open_markdown_link(text, workspace.clone(), window, cx);
1821 }
1822 }),
1823 )
1824 .into_any_element(),
1825 },
1826 ),
1827 )
1828 }
1829
1830 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1831 cx.theme().colors().border.opacity(0.5)
1832 }
1833
1834 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1835 cx.theme()
1836 .colors()
1837 .element_background
1838 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1839 }
1840
1841 fn render_message_thinking_segment(
1842 &self,
1843 message_id: MessageId,
1844 ix: usize,
1845 markdown: Entity<Markdown>,
1846 scroll_handle: &ScrollHandle,
1847 pending: bool,
1848 window: &Window,
1849 cx: &Context<Self>,
1850 ) -> impl IntoElement {
1851 let is_open = self
1852 .expanded_thinking_segments
1853 .get(&(message_id, ix))
1854 .copied()
1855 .unwrap_or_default();
1856
1857 let editor_bg = cx.theme().colors().panel_background;
1858
1859 div().map(|this| {
1860 if pending {
1861 this.v_flex()
1862 .mt_neg_2()
1863 .mb_1p5()
1864 .child(
1865 h_flex()
1866 .group("disclosure-header")
1867 .justify_between()
1868 .child(
1869 h_flex()
1870 .gap_1p5()
1871 .child(
1872 Icon::new(IconName::LightBulb)
1873 .size(IconSize::XSmall)
1874 .color(Color::Muted),
1875 )
1876 .child({
1877 Label::new("Thinking")
1878 .color(Color::Muted)
1879 .size(LabelSize::Small)
1880 .with_animation(
1881 "generating-label",
1882 Animation::new(Duration::from_secs(1)).repeat(),
1883 |mut label, delta| {
1884 let text = match delta {
1885 d if d < 0.25 => "Thinking",
1886 d if d < 0.5 => "Thinking.",
1887 d if d < 0.75 => "Thinking..",
1888 _ => "Thinking...",
1889 };
1890 label.set_text(text);
1891 label
1892 },
1893 )
1894 .with_animation(
1895 "pulsating-label",
1896 Animation::new(Duration::from_secs(2))
1897 .repeat()
1898 .with_easing(pulsating_between(0.6, 1.)),
1899 |label, delta| {
1900 label.map_element(|label| label.alpha(delta))
1901 },
1902 )
1903 }),
1904 )
1905 .child(
1906 h_flex()
1907 .gap_1()
1908 .child(
1909 div().visible_on_hover("disclosure-header").child(
1910 Disclosure::new("thinking-disclosure", is_open)
1911 .opened_icon(IconName::ChevronUp)
1912 .closed_icon(IconName::ChevronDown)
1913 .on_click(cx.listener({
1914 move |this, _event, _window, _cx| {
1915 let is_open = this
1916 .expanded_thinking_segments
1917 .entry((message_id, ix))
1918 .or_insert(false);
1919
1920 *is_open = !*is_open;
1921 }
1922 })),
1923 ),
1924 )
1925 .child({
1926 Icon::new(IconName::ArrowCircle)
1927 .color(Color::Accent)
1928 .size(IconSize::Small)
1929 .with_animation(
1930 "arrow-circle",
1931 Animation::new(Duration::from_secs(2)).repeat(),
1932 |icon, delta| {
1933 icon.transform(Transformation::rotate(
1934 percentage(delta),
1935 ))
1936 },
1937 )
1938 }),
1939 ),
1940 )
1941 .when(!is_open, |this| {
1942 let gradient_overlay = div()
1943 .rounded_b_lg()
1944 .h_full()
1945 .absolute()
1946 .w_full()
1947 .bottom_0()
1948 .left_0()
1949 .bg(linear_gradient(
1950 180.,
1951 linear_color_stop(editor_bg, 1.),
1952 linear_color_stop(editor_bg.opacity(0.2), 0.),
1953 ));
1954
1955 this.child(
1956 div()
1957 .relative()
1958 .bg(editor_bg)
1959 .rounded_b_lg()
1960 .mt_2()
1961 .pl_4()
1962 .child(
1963 div()
1964 .id(("thinking-content", ix))
1965 .max_h_20()
1966 .track_scroll(scroll_handle)
1967 .text_ui_sm(cx)
1968 .overflow_hidden()
1969 .child(
1970 MarkdownElement::new(
1971 markdown.clone(),
1972 default_markdown_style(window, cx),
1973 )
1974 .on_url_click({
1975 let workspace = self.workspace.clone();
1976 move |text, window, cx| {
1977 open_markdown_link(
1978 text,
1979 workspace.clone(),
1980 window,
1981 cx,
1982 );
1983 }
1984 }),
1985 ),
1986 )
1987 .child(gradient_overlay),
1988 )
1989 })
1990 .when(is_open, |this| {
1991 this.child(
1992 div()
1993 .id(("thinking-content", ix))
1994 .h_full()
1995 .bg(editor_bg)
1996 .text_ui_sm(cx)
1997 .child(
1998 MarkdownElement::new(
1999 markdown.clone(),
2000 default_markdown_style(window, cx),
2001 )
2002 .on_url_click({
2003 let workspace = self.workspace.clone();
2004 move |text, window, cx| {
2005 open_markdown_link(text, workspace.clone(), window, cx);
2006 }
2007 }),
2008 ),
2009 )
2010 })
2011 } else {
2012 this.v_flex()
2013 .mt_neg_2()
2014 .child(
2015 h_flex()
2016 .group("disclosure-header")
2017 .pr_1()
2018 .justify_between()
2019 .opacity(0.8)
2020 .hover(|style| style.opacity(1.))
2021 .child(
2022 h_flex()
2023 .gap_1p5()
2024 .child(
2025 Icon::new(IconName::LightBulb)
2026 .size(IconSize::XSmall)
2027 .color(Color::Muted),
2028 )
2029 .child(Label::new("Thought Process").size(LabelSize::Small)),
2030 )
2031 .child(
2032 div().visible_on_hover("disclosure-header").child(
2033 Disclosure::new("thinking-disclosure", is_open)
2034 .opened_icon(IconName::ChevronUp)
2035 .closed_icon(IconName::ChevronDown)
2036 .on_click(cx.listener({
2037 move |this, _event, _window, _cx| {
2038 let is_open = this
2039 .expanded_thinking_segments
2040 .entry((message_id, ix))
2041 .or_insert(false);
2042
2043 *is_open = !*is_open;
2044 }
2045 })),
2046 ),
2047 ),
2048 )
2049 .child(
2050 div()
2051 .id(("thinking-content", ix))
2052 .relative()
2053 .mt_1p5()
2054 .ml_1p5()
2055 .pl_2p5()
2056 .border_l_1()
2057 .border_color(cx.theme().colors().border_variant)
2058 .text_ui_sm(cx)
2059 .when(is_open, |this| {
2060 this.child(
2061 MarkdownElement::new(
2062 markdown.clone(),
2063 default_markdown_style(window, cx),
2064 )
2065 .on_url_click({
2066 let workspace = self.workspace.clone();
2067 move |text, window, cx| {
2068 open_markdown_link(text, workspace.clone(), window, cx);
2069 }
2070 }),
2071 )
2072 }),
2073 )
2074 }
2075 })
2076 }
2077
2078 fn render_tool_use(
2079 &self,
2080 tool_use: ToolUse,
2081 window: &mut Window,
2082 cx: &mut Context<Self>,
2083 ) -> impl IntoElement + use<> {
2084 let is_open = self
2085 .expanded_tool_uses
2086 .get(&tool_use.id)
2087 .copied()
2088 .unwrap_or_default();
2089
2090 let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2091
2092 let fs = self
2093 .workspace
2094 .upgrade()
2095 .map(|workspace| workspace.read(cx).app_state().fs.clone());
2096 let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2097 let edit_tools = tool_use.needs_confirmation;
2098
2099 let status_icons = div().child(match &tool_use.status {
2100 ToolUseStatus::Pending | ToolUseStatus::NeedsConfirmation => {
2101 let icon = Icon::new(IconName::Warning)
2102 .color(Color::Warning)
2103 .size(IconSize::Small);
2104 icon.into_any_element()
2105 }
2106 ToolUseStatus::Running => {
2107 let icon = Icon::new(IconName::ArrowCircle)
2108 .color(Color::Accent)
2109 .size(IconSize::Small);
2110 icon.with_animation(
2111 "arrow-circle",
2112 Animation::new(Duration::from_secs(2)).repeat(),
2113 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2114 )
2115 .into_any_element()
2116 }
2117 ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2118 ToolUseStatus::Error(_) => {
2119 let icon = Icon::new(IconName::Close)
2120 .color(Color::Error)
2121 .size(IconSize::Small);
2122 icon.into_any_element()
2123 }
2124 });
2125
2126 let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2127 let results_content_container = || v_flex().p_2().gap_0p5();
2128
2129 let results_content = v_flex()
2130 .gap_1()
2131 .child(
2132 results_content_container()
2133 .child(
2134 Label::new("Input")
2135 .size(LabelSize::XSmall)
2136 .color(Color::Muted)
2137 .buffer_font(cx),
2138 )
2139 .child(
2140 div()
2141 .w_full()
2142 .text_ui_sm(cx)
2143 .children(rendered_tool_use.as_ref().map(|rendered| {
2144 MarkdownElement::new(
2145 rendered.input.clone(),
2146 tool_use_markdown_style(window, cx),
2147 )
2148 .on_url_click({
2149 let workspace = self.workspace.clone();
2150 move |text, window, cx| {
2151 open_markdown_link(text, workspace.clone(), window, cx);
2152 }
2153 })
2154 })),
2155 ),
2156 )
2157 .map(|container| match tool_use.status {
2158 ToolUseStatus::Finished(_) => container.child(
2159 results_content_container()
2160 .border_t_1()
2161 .border_color(self.tool_card_border_color(cx))
2162 .child(
2163 Label::new("Result")
2164 .size(LabelSize::XSmall)
2165 .color(Color::Muted)
2166 .buffer_font(cx),
2167 )
2168 .child(div().w_full().text_ui_sm(cx).children(
2169 rendered_tool_use.as_ref().map(|rendered| {
2170 MarkdownElement::new(
2171 rendered.output.clone(),
2172 tool_use_markdown_style(window, cx),
2173 )
2174 .on_url_click({
2175 let workspace = self.workspace.clone();
2176 move |text, window, cx| {
2177 open_markdown_link(text, workspace.clone(), window, cx);
2178 }
2179 })
2180 }),
2181 )),
2182 ),
2183 ToolUseStatus::Running => container.child(
2184 results_content_container().child(
2185 h_flex()
2186 .gap_1()
2187 .pb_1()
2188 .border_t_1()
2189 .border_color(self.tool_card_border_color(cx))
2190 .child(
2191 Icon::new(IconName::ArrowCircle)
2192 .size(IconSize::Small)
2193 .color(Color::Accent)
2194 .with_animation(
2195 "arrow-circle",
2196 Animation::new(Duration::from_secs(2)).repeat(),
2197 |icon, delta| {
2198 icon.transform(Transformation::rotate(percentage(
2199 delta,
2200 )))
2201 },
2202 ),
2203 )
2204 .child(
2205 Label::new("Running…")
2206 .size(LabelSize::XSmall)
2207 .color(Color::Muted)
2208 .buffer_font(cx),
2209 ),
2210 ),
2211 ),
2212 ToolUseStatus::Error(_) => container.child(
2213 results_content_container()
2214 .border_t_1()
2215 .border_color(self.tool_card_border_color(cx))
2216 .child(
2217 Label::new("Error")
2218 .size(LabelSize::XSmall)
2219 .color(Color::Muted)
2220 .buffer_font(cx),
2221 )
2222 .child(
2223 div()
2224 .text_ui_sm(cx)
2225 .children(rendered_tool_use.as_ref().map(|rendered| {
2226 MarkdownElement::new(
2227 rendered.output.clone(),
2228 tool_use_markdown_style(window, cx),
2229 )
2230 .on_url_click({
2231 let workspace = self.workspace.clone();
2232 move |text, window, cx| {
2233 open_markdown_link(text, workspace.clone(), window, cx);
2234 }
2235 })
2236 })),
2237 ),
2238 ),
2239 ToolUseStatus::Pending => container,
2240 ToolUseStatus::NeedsConfirmation => container.child(
2241 results_content_container()
2242 .border_t_1()
2243 .border_color(self.tool_card_border_color(cx))
2244 .child(
2245 Label::new("Asking Permission")
2246 .size(LabelSize::Small)
2247 .color(Color::Muted)
2248 .buffer_font(cx),
2249 ),
2250 ),
2251 });
2252
2253 let gradient_overlay = |color: Hsla| {
2254 div()
2255 .h_full()
2256 .absolute()
2257 .w_12()
2258 .bottom_0()
2259 .map(|element| {
2260 if is_status_finished {
2261 element.right_6()
2262 } else {
2263 element.right(px(44.))
2264 }
2265 })
2266 .bg(linear_gradient(
2267 90.,
2268 linear_color_stop(color, 1.),
2269 linear_color_stop(color.opacity(0.2), 0.),
2270 ))
2271 };
2272
2273 div().map(|element| {
2274 if !edit_tools {
2275 element.child(
2276 v_flex()
2277 .my_2()
2278 .child(
2279 h_flex()
2280 .group("disclosure-header")
2281 .relative()
2282 .gap_1p5()
2283 .justify_between()
2284 .opacity(0.8)
2285 .hover(|style| style.opacity(1.))
2286 .when(!is_status_finished, |this| this.pr_2())
2287 .child(
2288 h_flex()
2289 .id("tool-label-container")
2290 .gap_1p5()
2291 .max_w_full()
2292 .overflow_x_scroll()
2293 .child(
2294 Icon::new(tool_use.icon)
2295 .size(IconSize::XSmall)
2296 .color(Color::Muted),
2297 )
2298 .child(
2299 h_flex().pr_8().text_ui_sm(cx).children(
2300 rendered_tool_use.map(|rendered| MarkdownElement::new(rendered.label, tool_use_markdown_style(window, cx)).on_url_click({let workspace = self.workspace.clone(); move |text, window, cx| {
2301 open_markdown_link(text, workspace.clone(), window, cx);
2302 }}))
2303 ),
2304 ),
2305 )
2306 .child(
2307 h_flex()
2308 .gap_1()
2309 .child(
2310 div().visible_on_hover("disclosure-header").child(
2311 Disclosure::new("tool-use-disclosure", is_open)
2312 .opened_icon(IconName::ChevronUp)
2313 .closed_icon(IconName::ChevronDown)
2314 .on_click(cx.listener({
2315 let tool_use_id = tool_use.id.clone();
2316 move |this, _event, _window, _cx| {
2317 let is_open = this
2318 .expanded_tool_uses
2319 .entry(tool_use_id.clone())
2320 .or_insert(false);
2321
2322 *is_open = !*is_open;
2323 }
2324 })),
2325 ),
2326 )
2327 .child(status_icons),
2328 )
2329 .child(gradient_overlay(cx.theme().colors().panel_background)),
2330 )
2331 .map(|parent| {
2332 if !is_open {
2333 return parent;
2334 }
2335
2336 parent.child(
2337 v_flex()
2338 .mt_1()
2339 .border_1()
2340 .border_color(self.tool_card_border_color(cx))
2341 .bg(cx.theme().colors().editor_background)
2342 .rounded_lg()
2343 .child(results_content),
2344 )
2345 }),
2346 )
2347 } else {
2348 v_flex()
2349 .my_3()
2350 .rounded_lg()
2351 .border_1()
2352 .border_color(self.tool_card_border_color(cx))
2353 .overflow_hidden()
2354 .child(
2355 h_flex()
2356 .group("disclosure-header")
2357 .relative()
2358 .justify_between()
2359 .py_1()
2360 .map(|element| {
2361 if is_status_finished {
2362 element.pl_2().pr_0p5()
2363 } else {
2364 element.px_2()
2365 }
2366 })
2367 .bg(self.tool_card_header_bg(cx))
2368 .map(|element| {
2369 if is_open {
2370 element.border_b_1().rounded_t_md()
2371 } else if needs_confirmation {
2372 element.rounded_t_md()
2373 } else {
2374 element.rounded_md()
2375 }
2376 })
2377 .border_color(self.tool_card_border_color(cx))
2378 .child(
2379 h_flex()
2380 .id("tool-label-container")
2381 .gap_1p5()
2382 .max_w_full()
2383 .overflow_x_scroll()
2384 .child(
2385 Icon::new(tool_use.icon)
2386 .size(IconSize::XSmall)
2387 .color(Color::Muted),
2388 )
2389 .child(
2390 h_flex().pr_8().text_ui_sm(cx).children(
2391 rendered_tool_use.map(|rendered| MarkdownElement::new(rendered.label, tool_use_markdown_style(window, cx)).on_url_click({let workspace = self.workspace.clone(); move |text, window, cx| {
2392 open_markdown_link(text, workspace.clone(), window, cx);
2393 }}))
2394 ),
2395 ),
2396 )
2397 .child(
2398 h_flex()
2399 .gap_1()
2400 .child(
2401 div().visible_on_hover("disclosure-header").child(
2402 Disclosure::new("tool-use-disclosure", is_open)
2403 .opened_icon(IconName::ChevronUp)
2404 .closed_icon(IconName::ChevronDown)
2405 .on_click(cx.listener({
2406 let tool_use_id = tool_use.id.clone();
2407 move |this, _event, _window, _cx| {
2408 let is_open = this
2409 .expanded_tool_uses
2410 .entry(tool_use_id.clone())
2411 .or_insert(false);
2412
2413 *is_open = !*is_open;
2414 }
2415 })),
2416 ),
2417 )
2418 .child(status_icons),
2419 )
2420 .child(gradient_overlay(self.tool_card_header_bg(cx))),
2421 )
2422 .map(|parent| {
2423 if !is_open {
2424 return parent;
2425 }
2426
2427 parent.child(
2428 v_flex()
2429 .bg(cx.theme().colors().editor_background)
2430 .map(|element| {
2431 if needs_confirmation {
2432 element.rounded_none()
2433 } else {
2434 element.rounded_b_lg()
2435 }
2436 })
2437 .child(results_content),
2438 )
2439 })
2440 .when(needs_confirmation, |this| {
2441 this.child(
2442 h_flex()
2443 .py_1()
2444 .pl_2()
2445 .pr_1()
2446 .gap_1()
2447 .justify_between()
2448 .bg(cx.theme().colors().editor_background)
2449 .border_t_1()
2450 .border_color(self.tool_card_border_color(cx))
2451 .rounded_b_lg()
2452 .child(
2453 Label::new("Waiting for Confirmation…")
2454 .color(Color::Muted)
2455 .size(LabelSize::Small)
2456 .with_animation(
2457 "generating-label",
2458 Animation::new(Duration::from_secs(1)).repeat(),
2459 |mut label, delta| {
2460 let text = match delta {
2461 d if d < 0.25 => "Waiting for Confirmation",
2462 d if d < 0.5 => "Waiting for Confirmation.",
2463 d if d < 0.75 => "Waiting for Confirmation..",
2464 _ => "Waiting for Confirmation...",
2465 };
2466 label.set_text(text);
2467 label
2468 },
2469 )
2470 .with_animation(
2471 "pulsating-label",
2472 Animation::new(Duration::from_secs(2))
2473 .repeat()
2474 .with_easing(pulsating_between(0.6, 1.)),
2475 |label, delta| label.map_element(|label| label.alpha(delta)),
2476 ),
2477 )
2478 .child(
2479 h_flex()
2480 .gap_0p5()
2481 .child({
2482 let tool_id = tool_use.id.clone();
2483 Button::new(
2484 "always-allow-tool-action",
2485 "Always Allow",
2486 )
2487 .label_size(LabelSize::Small)
2488 .icon(IconName::CheckDouble)
2489 .icon_position(IconPosition::Start)
2490 .icon_size(IconSize::Small)
2491 .icon_color(Color::Success)
2492 .tooltip(move |window, cx| {
2493 Tooltip::with_meta(
2494 "Never ask for permission",
2495 None,
2496 "Restore the original behavior in your Agent Panel settings",
2497 window,
2498 cx,
2499 )
2500 })
2501 .on_click(cx.listener(
2502 move |this, event, window, cx| {
2503 if let Some(fs) = fs.clone() {
2504 update_settings_file::<AssistantSettings>(
2505 fs.clone(),
2506 cx,
2507 |settings, _| {
2508 settings.set_always_allow_tool_actions(true);
2509 },
2510 );
2511 }
2512 this.handle_allow_tool(
2513 tool_id.clone(),
2514 event,
2515 window,
2516 cx,
2517 )
2518 },
2519 ))
2520 })
2521 .child(ui::Divider::vertical())
2522 .child({
2523 let tool_id = tool_use.id.clone();
2524 Button::new("allow-tool-action", "Allow")
2525 .label_size(LabelSize::Small)
2526 .icon(IconName::Check)
2527 .icon_position(IconPosition::Start)
2528 .icon_size(IconSize::Small)
2529 .icon_color(Color::Success)
2530 .on_click(cx.listener(
2531 move |this, event, window, cx| {
2532 this.handle_allow_tool(
2533 tool_id.clone(),
2534 event,
2535 window,
2536 cx,
2537 )
2538 },
2539 ))
2540 })
2541 .child({
2542 let tool_id = tool_use.id.clone();
2543 let tool_name: Arc<str> = tool_use.name.into();
2544 Button::new("deny-tool", "Deny")
2545 .label_size(LabelSize::Small)
2546 .icon(IconName::Close)
2547 .icon_position(IconPosition::Start)
2548 .icon_size(IconSize::Small)
2549 .icon_color(Color::Error)
2550 .on_click(cx.listener(
2551 move |this, event, window, cx| {
2552 this.handle_deny_tool(
2553 tool_id.clone(),
2554 tool_name.clone(),
2555 event,
2556 window,
2557 cx,
2558 )
2559 },
2560 ))
2561 }),
2562 ),
2563 )
2564 })
2565 }
2566 })
2567 }
2568
2569 fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
2570 let Some(system_prompt_context) = self.thread.read(cx).system_prompt_context().as_ref()
2571 else {
2572 return div().into_any();
2573 };
2574
2575 let rules_files = system_prompt_context
2576 .worktrees
2577 .iter()
2578 .filter_map(|worktree| worktree.rules_file.as_ref())
2579 .collect::<Vec<_>>();
2580
2581 let label_text = match rules_files.as_slice() {
2582 &[] => return div().into_any(),
2583 &[rules_file] => {
2584 format!("Using {:?} file", rules_file.path_in_worktree)
2585 }
2586 rules_files => {
2587 format!("Using {} rules files", rules_files.len())
2588 }
2589 };
2590
2591 div()
2592 .pt_2()
2593 .px_2p5()
2594 .child(
2595 h_flex()
2596 .w_full()
2597 .gap_0p5()
2598 .child(
2599 h_flex()
2600 .gap_1p5()
2601 .child(
2602 Icon::new(IconName::File)
2603 .size(IconSize::XSmall)
2604 .color(Color::Disabled),
2605 )
2606 .child(
2607 Label::new(label_text)
2608 .size(LabelSize::XSmall)
2609 .color(Color::Muted)
2610 .buffer_font(cx),
2611 ),
2612 )
2613 .child(
2614 IconButton::new("open-rule", IconName::ArrowUpRightAlt)
2615 .shape(ui::IconButtonShape::Square)
2616 .icon_size(IconSize::XSmall)
2617 .icon_color(Color::Ignored)
2618 .on_click(cx.listener(Self::handle_open_rules))
2619 .tooltip(Tooltip::text("View Rules")),
2620 ),
2621 )
2622 .into_any()
2623 }
2624
2625 fn handle_allow_tool(
2626 &mut self,
2627 tool_use_id: LanguageModelToolUseId,
2628 _: &ClickEvent,
2629 _window: &mut Window,
2630 cx: &mut Context<Self>,
2631 ) {
2632 if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
2633 .thread
2634 .read(cx)
2635 .pending_tool(&tool_use_id)
2636 .map(|tool_use| tool_use.status.clone())
2637 {
2638 self.thread.update(cx, |thread, cx| {
2639 thread.run_tool(
2640 c.tool_use_id.clone(),
2641 c.ui_text.clone(),
2642 c.input.clone(),
2643 &c.messages,
2644 c.tool.clone(),
2645 cx,
2646 );
2647 });
2648 }
2649 }
2650
2651 fn handle_deny_tool(
2652 &mut self,
2653 tool_use_id: LanguageModelToolUseId,
2654 tool_name: Arc<str>,
2655 _: &ClickEvent,
2656 _window: &mut Window,
2657 cx: &mut Context<Self>,
2658 ) {
2659 self.thread.update(cx, |thread, cx| {
2660 thread.deny_tool_use(tool_use_id, tool_name, cx);
2661 });
2662 }
2663
2664 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
2665 let Some(system_prompt_context) = self.thread.read(cx).system_prompt_context().as_ref()
2666 else {
2667 return;
2668 };
2669
2670 let abs_paths = system_prompt_context
2671 .worktrees
2672 .iter()
2673 .flat_map(|worktree| worktree.rules_file.as_ref())
2674 .map(|rules_file| rules_file.abs_path.to_path_buf())
2675 .collect::<Vec<_>>();
2676
2677 if let Ok(task) = self.workspace.update(cx, move |workspace, cx| {
2678 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
2679 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
2680 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
2681 workspace.open_paths(abs_paths, OpenOptions::default(), None, window, cx)
2682 }) {
2683 task.detach();
2684 }
2685 }
2686
2687 fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
2688 for window in self.notifications.drain(..) {
2689 window
2690 .update(cx, |_, window, _| {
2691 window.remove_window();
2692 })
2693 .ok();
2694
2695 self.notification_subscriptions.remove(&window);
2696 }
2697 }
2698
2699 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2700 if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
2701 return None;
2702 }
2703
2704 Some(
2705 div()
2706 .occlude()
2707 .id("active-thread-scrollbar")
2708 .on_mouse_move(cx.listener(|_, _, _, cx| {
2709 cx.notify();
2710 cx.stop_propagation()
2711 }))
2712 .on_hover(|_, _, cx| {
2713 cx.stop_propagation();
2714 })
2715 .on_any_mouse_down(|_, _, cx| {
2716 cx.stop_propagation();
2717 })
2718 .on_mouse_up(
2719 MouseButton::Left,
2720 cx.listener(|_, _, _, cx| {
2721 cx.stop_propagation();
2722 }),
2723 )
2724 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2725 cx.notify();
2726 }))
2727 .h_full()
2728 .absolute()
2729 .right_1()
2730 .top_1()
2731 .bottom_0()
2732 .w(px(12.))
2733 .cursor_default()
2734 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
2735 )
2736 }
2737
2738 fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
2739 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
2740 self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
2741 cx.background_executor()
2742 .timer(SCROLLBAR_SHOW_INTERVAL)
2743 .await;
2744 thread
2745 .update(cx, |thread, cx| {
2746 if !thread.scrollbar_state.is_dragging() {
2747 thread.show_scrollbar = false;
2748 cx.notify();
2749 }
2750 })
2751 .log_err();
2752 }))
2753 }
2754}
2755
2756impl Render for ActiveThread {
2757 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2758 v_flex()
2759 .size_full()
2760 .relative()
2761 .on_mouse_move(cx.listener(|this, _, _, cx| {
2762 this.show_scrollbar = true;
2763 this.hide_scrollbar_later(cx);
2764 cx.notify();
2765 }))
2766 .on_scroll_wheel(cx.listener(|this, _, _, cx| {
2767 this.show_scrollbar = true;
2768 this.hide_scrollbar_later(cx);
2769 cx.notify();
2770 }))
2771 .on_mouse_up(
2772 MouseButton::Left,
2773 cx.listener(|this, _, _, cx| {
2774 this.hide_scrollbar_later(cx);
2775 }),
2776 )
2777 .child(list(self.list_state.clone()).flex_grow())
2778 .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
2779 this.child(scrollbar)
2780 })
2781 }
2782}
2783
2784pub(crate) fn open_context(
2785 id: ContextId,
2786 context_store: Entity<ContextStore>,
2787 workspace: Entity<Workspace>,
2788 window: &mut Window,
2789 cx: &mut App,
2790) {
2791 let Some(context) = context_store.read(cx).context_for_id(id) else {
2792 return;
2793 };
2794
2795 match context {
2796 AssistantContext::File(file_context) => {
2797 if let Some(project_path) = file_context.context_buffer.buffer.read(cx).project_path(cx)
2798 {
2799 workspace.update(cx, |workspace, cx| {
2800 workspace
2801 .open_path(project_path, None, true, window, cx)
2802 .detach_and_log_err(cx);
2803 });
2804 }
2805 }
2806 AssistantContext::Directory(directory_context) => {
2807 let path = directory_context.project_path.clone();
2808 workspace.update(cx, |workspace, cx| {
2809 workspace.project().update(cx, |project, cx| {
2810 if let Some(entry) = project.entry_for_path(&path, cx) {
2811 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2812 }
2813 })
2814 })
2815 }
2816 AssistantContext::Symbol(symbol_context) => {
2817 if let Some(project_path) = symbol_context
2818 .context_symbol
2819 .buffer
2820 .read(cx)
2821 .project_path(cx)
2822 {
2823 let snapshot = symbol_context.context_symbol.buffer.read(cx).snapshot();
2824 let target_position = symbol_context
2825 .context_symbol
2826 .id
2827 .range
2828 .start
2829 .to_point(&snapshot);
2830
2831 let open_task = workspace.update(cx, |workspace, cx| {
2832 workspace.open_path(project_path, None, true, window, cx)
2833 });
2834 window
2835 .spawn(cx, async move |cx| {
2836 if let Some(active_editor) = open_task
2837 .await
2838 .log_err()
2839 .and_then(|item| item.downcast::<Editor>())
2840 {
2841 active_editor
2842 .downgrade()
2843 .update_in(cx, |editor, window, cx| {
2844 editor.go_to_singleton_buffer_point(
2845 target_position,
2846 window,
2847 cx,
2848 );
2849 })
2850 .log_err();
2851 }
2852 })
2853 .detach();
2854 }
2855 }
2856 AssistantContext::FetchedUrl(fetched_url_context) => {
2857 cx.open_url(&fetched_url_context.url);
2858 }
2859 AssistantContext::Thread(thread_context) => {
2860 let thread_id = thread_context.thread.read(cx).id().clone();
2861 workspace.update(cx, |workspace, cx| {
2862 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
2863 panel.update(cx, |panel, cx| {
2864 panel
2865 .open_thread(&thread_id, window, cx)
2866 .detach_and_log_err(cx)
2867 });
2868 }
2869 })
2870 }
2871 }
2872}