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 open_feedback_editors: HashMap<MessageId, 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 open_feedback_editors: HashMap::default(),
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);
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 message_id: MessageId,
1115 feedback: ThreadFeedback,
1116 window: &mut Window,
1117 cx: &mut Context<Self>,
1118 ) {
1119 let report = self.thread.update(cx, |thread, cx| {
1120 thread.report_message_feedback(message_id, feedback, cx)
1121 });
1122
1123 cx.spawn(async move |this, cx| {
1124 report.await?;
1125 this.update(cx, |_this, cx| cx.notify())
1126 })
1127 .detach_and_log_err(cx);
1128
1129 match feedback {
1130 ThreadFeedback::Positive => {
1131 self.open_feedback_editors.remove(&message_id);
1132 }
1133 ThreadFeedback::Negative => {
1134 self.handle_show_feedback_comments(message_id, window, cx);
1135 }
1136 }
1137 }
1138
1139 fn handle_show_feedback_comments(
1140 &mut self,
1141 message_id: MessageId,
1142 window: &mut Window,
1143 cx: &mut Context<Self>,
1144 ) {
1145 let buffer = cx.new(|cx| {
1146 let empty_string = String::new();
1147 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
1148 });
1149
1150 let editor = cx.new(|cx| {
1151 let mut editor = Editor::new(
1152 editor::EditorMode::AutoHeight { max_lines: 4 },
1153 buffer,
1154 None,
1155 window,
1156 cx,
1157 );
1158 editor.set_placeholder_text(
1159 "What went wrong? Share your feedback so we can improve.",
1160 cx,
1161 );
1162 editor
1163 });
1164
1165 editor.read(cx).focus_handle(cx).focus(window);
1166 self.open_feedback_editors.insert(message_id, editor);
1167 cx.notify();
1168 }
1169
1170 fn submit_feedback_message(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
1171 let Some(editor) = self.open_feedback_editors.get(&message_id) else {
1172 return;
1173 };
1174
1175 let report_task = self.thread.update(cx, |thread, cx| {
1176 thread.report_message_feedback(message_id, ThreadFeedback::Negative, cx)
1177 });
1178
1179 let comments = editor.read(cx).text(cx);
1180 if !comments.is_empty() {
1181 let thread_id = self.thread.read(cx).id().clone();
1182 let comments_value = String::from(comments.as_str());
1183
1184 let message_content = self
1185 .thread
1186 .read(cx)
1187 .message(message_id)
1188 .map(|msg| msg.to_string())
1189 .unwrap_or_default();
1190
1191 telemetry::event!(
1192 "Assistant Thread Feedback Comments",
1193 thread_id,
1194 message_id = message_id.0,
1195 message_content,
1196 comments = comments_value
1197 );
1198
1199 self.open_feedback_editors.remove(&message_id);
1200
1201 cx.spawn(async move |this, cx| {
1202 report_task.await?;
1203 this.update(cx, |_this, cx| cx.notify())
1204 })
1205 .detach_and_log_err(cx);
1206 }
1207 }
1208
1209 fn render_message(&self, ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1210 let message_id = self.messages[ix];
1211 let Some(message) = self.thread.read(cx).message(message_id) else {
1212 return Empty.into_any();
1213 };
1214
1215 let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1216 return Empty.into_any();
1217 };
1218
1219 let context_store = self.context_store.clone();
1220 let workspace = self.workspace.clone();
1221 let thread = self.thread.read(cx);
1222
1223 // Get all the data we need from thread before we start using it in closures
1224 let checkpoint = thread.checkpoint_for_message(message_id);
1225 let context = thread.context_for_message(message_id).collect::<Vec<_>>();
1226
1227 let tool_uses = thread.tool_uses_for_message(message_id, cx);
1228 let has_tool_uses = !tool_uses.is_empty();
1229 let is_generating = thread.is_generating();
1230
1231 let is_first_message = ix == 0;
1232 let is_last_message = ix == self.messages.len() - 1;
1233
1234 let show_feedback = (!is_generating && is_last_message && message.role != Role::User)
1235 || self.messages.get(ix + 1).map_or(false, |next_id| {
1236 self.thread
1237 .read(cx)
1238 .message(*next_id)
1239 .map_or(false, |next_message| {
1240 next_message.role == Role::User
1241 && thread.tool_uses_for_message(*next_id, cx).is_empty()
1242 && thread.tool_results_for_message(*next_id).is_empty()
1243 })
1244 });
1245
1246 let needs_confirmation = tool_uses.iter().any(|tool_use| tool_use.needs_confirmation);
1247
1248 let generating_label = (is_generating && is_last_message).then(|| {
1249 Label::new("Generating")
1250 .color(Color::Muted)
1251 .size(LabelSize::Small)
1252 .with_animations(
1253 "generating-label",
1254 vec![
1255 Animation::new(Duration::from_secs(1)),
1256 Animation::new(Duration::from_secs(1)).repeat(),
1257 ],
1258 |mut label, animation_ix, delta| {
1259 match animation_ix {
1260 0 => {
1261 let chars_to_show = (delta * 10.).ceil() as usize;
1262 let text = &"Generating"[0..chars_to_show];
1263 label.set_text(text);
1264 }
1265 1 => {
1266 let text = match delta {
1267 d if d < 0.25 => "Generating",
1268 d if d < 0.5 => "Generating.",
1269 d if d < 0.75 => "Generating..",
1270 _ => "Generating...",
1271 };
1272 label.set_text(text);
1273 }
1274 _ => {}
1275 }
1276 label
1277 },
1278 )
1279 .with_animation(
1280 "pulsating-label",
1281 Animation::new(Duration::from_secs(2))
1282 .repeat()
1283 .with_easing(pulsating_between(0.6, 1.)),
1284 |label, delta| label.map_element(|label| label.alpha(delta)),
1285 )
1286 });
1287
1288 // Don't render user messages that are just there for returning tool results.
1289 if message.role == Role::User && thread.message_has_tool_results(message_id) {
1290 if let Some(generating_label) = generating_label {
1291 return h_flex()
1292 .w_full()
1293 .h_10()
1294 .py_1p5()
1295 .pl_4()
1296 .pb_3()
1297 .child(generating_label)
1298 .into_any_element();
1299 }
1300
1301 return Empty.into_any();
1302 }
1303
1304 let allow_editing_message = message.role == Role::User;
1305
1306 let edit_message_editor = self
1307 .editing_message
1308 .as_ref()
1309 .filter(|(id, _)| *id == message_id)
1310 .map(|(_, state)| state.editor.clone());
1311
1312 let colors = cx.theme().colors();
1313 let active_color = colors.element_active;
1314 let editor_bg_color = colors.editor_background;
1315 let bg_user_message_header = editor_bg_color.blend(active_color.opacity(0.25));
1316
1317 let feedback_container = h_flex().py_2().px_4().gap_1().justify_between();
1318
1319 let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1320 Some(feedback) => feedback_container
1321 .child(
1322 Label::new(match feedback {
1323 ThreadFeedback::Positive => "Thanks for your feedback!",
1324 ThreadFeedback::Negative => {
1325 "We appreciate your feedback and will use it to improve."
1326 }
1327 })
1328 .color(Color::Muted)
1329 .size(LabelSize::XSmall),
1330 )
1331 .child(
1332 h_flex()
1333 .pr_1()
1334 .gap_1()
1335 .child(
1336 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1337 .shape(ui::IconButtonShape::Square)
1338 .icon_size(IconSize::XSmall)
1339 .icon_color(match feedback {
1340 ThreadFeedback::Positive => Color::Accent,
1341 ThreadFeedback::Negative => Color::Ignored,
1342 })
1343 .tooltip(Tooltip::text("Helpful Response"))
1344 .on_click(cx.listener(move |this, _, window, cx| {
1345 this.handle_feedback_click(
1346 message_id,
1347 ThreadFeedback::Positive,
1348 window,
1349 cx,
1350 );
1351 })),
1352 )
1353 .child(
1354 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1355 .shape(ui::IconButtonShape::Square)
1356 .icon_size(IconSize::XSmall)
1357 .icon_color(match feedback {
1358 ThreadFeedback::Positive => Color::Ignored,
1359 ThreadFeedback::Negative => Color::Accent,
1360 })
1361 .tooltip(Tooltip::text("Not Helpful"))
1362 .on_click(cx.listener(move |this, _, window, cx| {
1363 this.handle_feedback_click(
1364 message_id,
1365 ThreadFeedback::Negative,
1366 window,
1367 cx,
1368 );
1369 })),
1370 ),
1371 )
1372 .into_any_element(),
1373 None => feedback_container
1374 .child(
1375 Label::new(
1376 "Rating the thread sends all of your current conversation to the Zed team.",
1377 )
1378 .color(Color::Muted)
1379 .size(LabelSize::XSmall),
1380 )
1381 .child(
1382 h_flex()
1383 .gap_1()
1384 .child(
1385 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1386 .icon_size(IconSize::XSmall)
1387 .icon_color(Color::Ignored)
1388 .shape(ui::IconButtonShape::Square)
1389 .tooltip(Tooltip::text("Helpful Response"))
1390 .on_click(cx.listener(move |this, _, window, cx| {
1391 this.handle_feedback_click(
1392 message_id,
1393 ThreadFeedback::Positive,
1394 window,
1395 cx,
1396 );
1397 })),
1398 )
1399 .child(
1400 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1401 .icon_size(IconSize::XSmall)
1402 .icon_color(Color::Ignored)
1403 .shape(ui::IconButtonShape::Square)
1404 .tooltip(Tooltip::text("Not Helpful"))
1405 .on_click(cx.listener(move |this, _, window, cx| {
1406 this.handle_feedback_click(
1407 message_id,
1408 ThreadFeedback::Negative,
1409 window,
1410 cx,
1411 );
1412 })),
1413 ),
1414 )
1415 .into_any_element(),
1416 };
1417
1418 let message_is_empty = message.should_display_content();
1419 let has_content = !message_is_empty || !context.is_empty();
1420
1421 let message_content =
1422 has_content.then(|| {
1423 v_flex()
1424 .gap_1p5()
1425 .when(!message_is_empty, |parent| {
1426 parent.child(
1427 if let Some(edit_message_editor) = edit_message_editor.clone() {
1428 div()
1429 .key_context("EditMessageEditor")
1430 .on_action(cx.listener(Self::cancel_editing_message))
1431 .on_action(cx.listener(Self::confirm_editing_message))
1432 .min_h_6()
1433 .child(edit_message_editor)
1434 .into_any()
1435 } else {
1436 div()
1437 .min_h_6()
1438 .text_ui(cx)
1439 .child(self.render_message_content(
1440 message_id,
1441 rendered_message,
1442 has_tool_uses,
1443 workspace.clone(),
1444 window,
1445 cx,
1446 ))
1447 .into_any()
1448 },
1449 )
1450 })
1451 .when(!context.is_empty(), |parent| {
1452 parent.child(h_flex().flex_wrap().gap_1().children(
1453 context.into_iter().map(|context| {
1454 let context_id = context.id();
1455 ContextPill::added(
1456 AddedContext::new(context, cx),
1457 false,
1458 false,
1459 None,
1460 )
1461 .on_click(Rc::new(cx.listener({
1462 let workspace = workspace.clone();
1463 let context_store = context_store.clone();
1464 move |_, _, window, cx| {
1465 if let Some(workspace) = workspace.upgrade() {
1466 open_context(
1467 context_id,
1468 context_store.clone(),
1469 workspace,
1470 window,
1471 cx,
1472 );
1473 cx.notify();
1474 }
1475 }
1476 })))
1477 }),
1478 ))
1479 })
1480 });
1481
1482 let styled_message = match message.role {
1483 Role::User => v_flex()
1484 .id(("message-container", ix))
1485 .map(|this| {
1486 if is_first_message {
1487 this.pt_2()
1488 } else {
1489 this.pt_4()
1490 }
1491 })
1492 .pb_4()
1493 .pl_2()
1494 .pr_2p5()
1495 .child(
1496 v_flex()
1497 .bg(colors.editor_background)
1498 .rounded_lg()
1499 .border_1()
1500 .border_color(colors.border)
1501 .shadow_md()
1502 .child(
1503 h_flex()
1504 .py_1()
1505 .pl_2()
1506 .pr_1()
1507 .bg(bg_user_message_header)
1508 .border_b_1()
1509 .border_color(colors.border)
1510 .justify_between()
1511 .rounded_t_md()
1512 .child(
1513 h_flex()
1514 .gap_1p5()
1515 .child(
1516 Icon::new(IconName::PersonCircle)
1517 .size(IconSize::XSmall)
1518 .color(Color::Muted),
1519 )
1520 .child(
1521 Label::new("You")
1522 .size(LabelSize::Small)
1523 .color(Color::Muted),
1524 ),
1525 )
1526 .child(
1527 h_flex()
1528 .gap_1()
1529 .when_some(
1530 edit_message_editor.clone(),
1531 |this, edit_message_editor| {
1532 let focus_handle =
1533 edit_message_editor.focus_handle(cx);
1534 this.child(
1535 Button::new("cancel-edit-message", "Cancel")
1536 .label_size(LabelSize::Small)
1537 .key_binding(
1538 KeyBinding::for_action_in(
1539 &menu::Cancel,
1540 &focus_handle,
1541 window,
1542 cx,
1543 )
1544 .map(|kb| kb.size(rems_from_px(12.))),
1545 )
1546 .on_click(
1547 cx.listener(Self::handle_cancel_click),
1548 ),
1549 )
1550 .child(
1551 Button::new(
1552 "confirm-edit-message",
1553 "Regenerate",
1554 )
1555 .label_size(LabelSize::Small)
1556 .key_binding(
1557 KeyBinding::for_action_in(
1558 &menu::Confirm,
1559 &focus_handle,
1560 window,
1561 cx,
1562 )
1563 .map(|kb| kb.size(rems_from_px(12.))),
1564 )
1565 .on_click(
1566 cx.listener(Self::handle_regenerate_click),
1567 ),
1568 )
1569 },
1570 )
1571 .when(
1572 edit_message_editor.is_none() && allow_editing_message,
1573 |this| {
1574 this.child(
1575 Button::new("edit-message", "Edit")
1576 .label_size(LabelSize::Small)
1577 .on_click(cx.listener({
1578 let message_segments =
1579 message.segments.clone();
1580 move |this, _, window, cx| {
1581 this.start_editing_message(
1582 message_id,
1583 &message_segments,
1584 window,
1585 cx,
1586 );
1587 }
1588 })),
1589 )
1590 },
1591 ),
1592 ),
1593 )
1594 .child(div().p_2().children(message_content)),
1595 ),
1596 Role::Assistant => v_flex()
1597 .id(("message-container", ix))
1598 .ml_2()
1599 .pl_2()
1600 .pr_4()
1601 .border_l_1()
1602 .border_color(cx.theme().colors().border_variant)
1603 .children(message_content)
1604 .when(has_tool_uses, |parent| {
1605 parent.children(
1606 tool_uses
1607 .into_iter()
1608 .map(|tool_use| self.render_tool_use(tool_use, window, cx)),
1609 )
1610 }),
1611 Role::System => div().id(("message-container", ix)).py_1().px_2().child(
1612 v_flex()
1613 .bg(colors.editor_background)
1614 .rounded_sm()
1615 .child(div().p_4().children(message_content)),
1616 ),
1617 };
1618
1619 v_flex()
1620 .w_full()
1621 .when_some(checkpoint, |parent, checkpoint| {
1622 let mut is_pending = false;
1623 let mut error = None;
1624 if let Some(last_restore_checkpoint) =
1625 self.thread.read(cx).last_restore_checkpoint()
1626 {
1627 if last_restore_checkpoint.message_id() == message_id {
1628 match last_restore_checkpoint {
1629 LastRestoreCheckpoint::Pending { .. } => is_pending = true,
1630 LastRestoreCheckpoint::Error { error: err, .. } => {
1631 error = Some(err.clone());
1632 }
1633 }
1634 }
1635 }
1636
1637 let restore_checkpoint_button =
1638 Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
1639 .icon(if error.is_some() {
1640 IconName::XCircle
1641 } else {
1642 IconName::Undo
1643 })
1644 .icon_size(IconSize::XSmall)
1645 .icon_position(IconPosition::Start)
1646 .icon_color(if error.is_some() {
1647 Some(Color::Error)
1648 } else {
1649 None
1650 })
1651 .label_size(LabelSize::XSmall)
1652 .disabled(is_pending)
1653 .on_click(cx.listener(move |this, _, _window, cx| {
1654 this.thread.update(cx, |thread, cx| {
1655 thread
1656 .restore_checkpoint(checkpoint.clone(), cx)
1657 .detach_and_log_err(cx);
1658 });
1659 }));
1660
1661 let restore_checkpoint_button = if is_pending {
1662 restore_checkpoint_button
1663 .with_animation(
1664 ("pulsating-restore-checkpoint-button", ix),
1665 Animation::new(Duration::from_secs(2))
1666 .repeat()
1667 .with_easing(pulsating_between(0.6, 1.)),
1668 |label, delta| label.alpha(delta),
1669 )
1670 .into_any_element()
1671 } else if let Some(error) = error {
1672 restore_checkpoint_button
1673 .tooltip(Tooltip::text(error.to_string()))
1674 .into_any_element()
1675 } else {
1676 restore_checkpoint_button.into_any_element()
1677 };
1678
1679 parent.child(
1680 h_flex()
1681 .pt_2p5()
1682 .px_2p5()
1683 .w_full()
1684 .gap_1()
1685 .child(ui::Divider::horizontal())
1686 .child(restore_checkpoint_button)
1687 .child(ui::Divider::horizontal()),
1688 )
1689 })
1690 .when(is_first_message, |parent| {
1691 parent.child(self.render_rules_item(cx))
1692 })
1693 .child(styled_message)
1694 .when(!needs_confirmation && generating_label.is_some(), |this| {
1695 this.child(
1696 h_flex()
1697 .h_8()
1698 .mt_2()
1699 .mb_4()
1700 .ml_4()
1701 .py_1p5()
1702 .child(generating_label.unwrap()),
1703 )
1704 })
1705 .when(show_feedback, move |parent| {
1706 parent.child(feedback_items).when_some(
1707 self.open_feedback_editors.get(&message_id),
1708 move |parent, feedback_editor| {
1709 let focus_handle = feedback_editor.focus_handle(cx);
1710 parent.child(
1711 v_flex()
1712 .key_context("AgentFeedbackMessageEditor")
1713 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
1714 this.open_feedback_editors.remove(&message_id);
1715 cx.notify();
1716 }))
1717 .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
1718 this.submit_feedback_message(message_id, cx);
1719 cx.notify();
1720 }))
1721 .on_action(cx.listener(Self::confirm_editing_message))
1722 .mb_2()
1723 .mx_4()
1724 .p_2()
1725 .rounded_md()
1726 .border_1()
1727 .border_color(cx.theme().colors().border)
1728 .bg(cx.theme().colors().editor_background)
1729 .child(feedback_editor.clone())
1730 .child(
1731 h_flex()
1732 .gap_1()
1733 .justify_end()
1734 .child(
1735 Button::new("dismiss-feedback-message", "Cancel")
1736 .label_size(LabelSize::Small)
1737 .key_binding(
1738 KeyBinding::for_action_in(
1739 &menu::Cancel,
1740 &focus_handle,
1741 window,
1742 cx,
1743 )
1744 .map(|kb| kb.size(rems_from_px(10.))),
1745 )
1746 .on_click(cx.listener(
1747 move |this, _, _window, cx| {
1748 this.open_feedback_editors
1749 .remove(&message_id);
1750 cx.notify();
1751 },
1752 )),
1753 )
1754 .child(
1755 Button::new(
1756 "submit-feedback-message",
1757 "Share Feedback",
1758 )
1759 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1760 .label_size(LabelSize::Small)
1761 .key_binding(
1762 KeyBinding::for_action_in(
1763 &menu::Confirm,
1764 &focus_handle,
1765 window,
1766 cx,
1767 )
1768 .map(|kb| kb.size(rems_from_px(10.))),
1769 )
1770 .on_click(
1771 cx.listener(move |this, _, _window, cx| {
1772 this.submit_feedback_message(message_id, cx);
1773 cx.notify()
1774 }),
1775 ),
1776 ),
1777 ),
1778 )
1779 },
1780 )
1781 })
1782 .into_any()
1783 }
1784
1785 fn render_message_content(
1786 &self,
1787 message_id: MessageId,
1788 rendered_message: &RenderedMessage,
1789 has_tool_uses: bool,
1790 workspace: WeakEntity<Workspace>,
1791 window: &Window,
1792 cx: &Context<Self>,
1793 ) -> impl IntoElement {
1794 let is_last_message = self.messages.last() == Some(&message_id);
1795 let is_generating = self.thread.read(cx).is_generating();
1796 let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
1797 rendered_message
1798 .segments
1799 .iter()
1800 .enumerate()
1801 .next_back()
1802 .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
1803 .map(|(index, _)| index)
1804 } else {
1805 None
1806 };
1807
1808 v_flex()
1809 .text_ui(cx)
1810 .gap_2()
1811 .children(
1812 rendered_message.segments.iter().enumerate().map(
1813 |(index, segment)| match segment {
1814 RenderedMessageSegment::Thinking {
1815 content,
1816 scroll_handle,
1817 } => self
1818 .render_message_thinking_segment(
1819 message_id,
1820 index,
1821 content.clone(),
1822 &scroll_handle,
1823 Some(index) == pending_thinking_segment_index,
1824 window,
1825 cx,
1826 )
1827 .into_any_element(),
1828 RenderedMessageSegment::Text(markdown) => div()
1829 .child(
1830 MarkdownElement::new(
1831 markdown.clone(),
1832 default_markdown_style(window, cx),
1833 )
1834 .code_block_renderer(markdown::CodeBlockRenderer::Custom {
1835 render: Arc::new({
1836 let workspace = workspace.clone();
1837 let active_thread = cx.entity();
1838 move |id, kind, parsed_markdown, range, window, cx| {
1839 render_markdown_code_block(
1840 message_id,
1841 id,
1842 kind,
1843 parsed_markdown,
1844 range,
1845 active_thread.clone(),
1846 workspace.clone(),
1847 window,
1848 cx,
1849 )
1850 }
1851 }),
1852 })
1853 .on_url_click({
1854 let workspace = self.workspace.clone();
1855 move |text, window, cx| {
1856 open_markdown_link(text, workspace.clone(), window, cx);
1857 }
1858 }),
1859 )
1860 .into_any_element(),
1861 },
1862 ),
1863 )
1864 }
1865
1866 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1867 cx.theme().colors().border.opacity(0.5)
1868 }
1869
1870 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1871 cx.theme()
1872 .colors()
1873 .element_background
1874 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1875 }
1876
1877 fn render_message_thinking_segment(
1878 &self,
1879 message_id: MessageId,
1880 ix: usize,
1881 markdown: Entity<Markdown>,
1882 scroll_handle: &ScrollHandle,
1883 pending: bool,
1884 window: &Window,
1885 cx: &Context<Self>,
1886 ) -> impl IntoElement {
1887 let is_open = self
1888 .expanded_thinking_segments
1889 .get(&(message_id, ix))
1890 .copied()
1891 .unwrap_or_default();
1892
1893 let editor_bg = cx.theme().colors().panel_background;
1894
1895 div().map(|this| {
1896 if pending {
1897 this.v_flex()
1898 .mt_neg_2()
1899 .mb_1p5()
1900 .child(
1901 h_flex()
1902 .group("disclosure-header")
1903 .justify_between()
1904 .child(
1905 h_flex()
1906 .gap_1p5()
1907 .child(
1908 Icon::new(IconName::LightBulb)
1909 .size(IconSize::XSmall)
1910 .color(Color::Muted),
1911 )
1912 .child({
1913 Label::new("Thinking")
1914 .color(Color::Muted)
1915 .size(LabelSize::Small)
1916 .with_animation(
1917 "generating-label",
1918 Animation::new(Duration::from_secs(1)).repeat(),
1919 |mut label, delta| {
1920 let text = match delta {
1921 d if d < 0.25 => "Thinking",
1922 d if d < 0.5 => "Thinking.",
1923 d if d < 0.75 => "Thinking..",
1924 _ => "Thinking...",
1925 };
1926 label.set_text(text);
1927 label
1928 },
1929 )
1930 .with_animation(
1931 "pulsating-label",
1932 Animation::new(Duration::from_secs(2))
1933 .repeat()
1934 .with_easing(pulsating_between(0.6, 1.)),
1935 |label, delta| {
1936 label.map_element(|label| label.alpha(delta))
1937 },
1938 )
1939 }),
1940 )
1941 .child(
1942 h_flex()
1943 .gap_1()
1944 .child(
1945 div().visible_on_hover("disclosure-header").child(
1946 Disclosure::new("thinking-disclosure", is_open)
1947 .opened_icon(IconName::ChevronUp)
1948 .closed_icon(IconName::ChevronDown)
1949 .on_click(cx.listener({
1950 move |this, _event, _window, _cx| {
1951 let is_open = this
1952 .expanded_thinking_segments
1953 .entry((message_id, ix))
1954 .or_insert(false);
1955
1956 *is_open = !*is_open;
1957 }
1958 })),
1959 ),
1960 )
1961 .child({
1962 Icon::new(IconName::ArrowCircle)
1963 .color(Color::Accent)
1964 .size(IconSize::Small)
1965 .with_animation(
1966 "arrow-circle",
1967 Animation::new(Duration::from_secs(2)).repeat(),
1968 |icon, delta| {
1969 icon.transform(Transformation::rotate(
1970 percentage(delta),
1971 ))
1972 },
1973 )
1974 }),
1975 ),
1976 )
1977 .when(!is_open, |this| {
1978 let gradient_overlay = div()
1979 .rounded_b_lg()
1980 .h_full()
1981 .absolute()
1982 .w_full()
1983 .bottom_0()
1984 .left_0()
1985 .bg(linear_gradient(
1986 180.,
1987 linear_color_stop(editor_bg, 1.),
1988 linear_color_stop(editor_bg.opacity(0.2), 0.),
1989 ));
1990
1991 this.child(
1992 div()
1993 .relative()
1994 .bg(editor_bg)
1995 .rounded_b_lg()
1996 .mt_2()
1997 .pl_4()
1998 .child(
1999 div()
2000 .id(("thinking-content", ix))
2001 .max_h_20()
2002 .track_scroll(scroll_handle)
2003 .text_ui_sm(cx)
2004 .overflow_hidden()
2005 .child(
2006 MarkdownElement::new(
2007 markdown.clone(),
2008 default_markdown_style(window, cx),
2009 )
2010 .on_url_click({
2011 let workspace = self.workspace.clone();
2012 move |text, window, cx| {
2013 open_markdown_link(
2014 text,
2015 workspace.clone(),
2016 window,
2017 cx,
2018 );
2019 }
2020 }),
2021 ),
2022 )
2023 .child(gradient_overlay),
2024 )
2025 })
2026 .when(is_open, |this| {
2027 this.child(
2028 div()
2029 .id(("thinking-content", ix))
2030 .h_full()
2031 .bg(editor_bg)
2032 .text_ui_sm(cx)
2033 .child(
2034 MarkdownElement::new(
2035 markdown.clone(),
2036 default_markdown_style(window, cx),
2037 )
2038 .on_url_click({
2039 let workspace = self.workspace.clone();
2040 move |text, window, cx| {
2041 open_markdown_link(text, workspace.clone(), window, cx);
2042 }
2043 }),
2044 ),
2045 )
2046 })
2047 } else {
2048 this.v_flex()
2049 .mt_neg_2()
2050 .child(
2051 h_flex()
2052 .group("disclosure-header")
2053 .pr_1()
2054 .justify_between()
2055 .opacity(0.8)
2056 .hover(|style| style.opacity(1.))
2057 .child(
2058 h_flex()
2059 .gap_1p5()
2060 .child(
2061 Icon::new(IconName::LightBulb)
2062 .size(IconSize::XSmall)
2063 .color(Color::Muted),
2064 )
2065 .child(Label::new("Thought Process").size(LabelSize::Small)),
2066 )
2067 .child(
2068 div().visible_on_hover("disclosure-header").child(
2069 Disclosure::new("thinking-disclosure", is_open)
2070 .opened_icon(IconName::ChevronUp)
2071 .closed_icon(IconName::ChevronDown)
2072 .on_click(cx.listener({
2073 move |this, _event, _window, _cx| {
2074 let is_open = this
2075 .expanded_thinking_segments
2076 .entry((message_id, ix))
2077 .or_insert(false);
2078
2079 *is_open = !*is_open;
2080 }
2081 })),
2082 ),
2083 ),
2084 )
2085 .child(
2086 div()
2087 .id(("thinking-content", ix))
2088 .relative()
2089 .mt_1p5()
2090 .ml_1p5()
2091 .pl_2p5()
2092 .border_l_1()
2093 .border_color(cx.theme().colors().border_variant)
2094 .text_ui_sm(cx)
2095 .when(is_open, |this| {
2096 this.child(
2097 MarkdownElement::new(
2098 markdown.clone(),
2099 default_markdown_style(window, cx),
2100 )
2101 .on_url_click({
2102 let workspace = self.workspace.clone();
2103 move |text, window, cx| {
2104 open_markdown_link(text, workspace.clone(), window, cx);
2105 }
2106 }),
2107 )
2108 }),
2109 )
2110 }
2111 })
2112 }
2113
2114 fn render_tool_use(
2115 &self,
2116 tool_use: ToolUse,
2117 window: &mut Window,
2118 cx: &mut Context<Self>,
2119 ) -> impl IntoElement + use<> {
2120 let is_open = self
2121 .expanded_tool_uses
2122 .get(&tool_use.id)
2123 .copied()
2124 .unwrap_or_default();
2125
2126 let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2127
2128 let fs = self
2129 .workspace
2130 .upgrade()
2131 .map(|workspace| workspace.read(cx).app_state().fs.clone());
2132 let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2133 let edit_tools = tool_use.needs_confirmation;
2134
2135 let status_icons = div().child(match &tool_use.status {
2136 ToolUseStatus::Pending | ToolUseStatus::NeedsConfirmation => {
2137 let icon = Icon::new(IconName::Warning)
2138 .color(Color::Warning)
2139 .size(IconSize::Small);
2140 icon.into_any_element()
2141 }
2142 ToolUseStatus::Running => {
2143 let icon = Icon::new(IconName::ArrowCircle)
2144 .color(Color::Accent)
2145 .size(IconSize::Small);
2146 icon.with_animation(
2147 "arrow-circle",
2148 Animation::new(Duration::from_secs(2)).repeat(),
2149 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2150 )
2151 .into_any_element()
2152 }
2153 ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2154 ToolUseStatus::Error(_) => {
2155 let icon = Icon::new(IconName::Close)
2156 .color(Color::Error)
2157 .size(IconSize::Small);
2158 icon.into_any_element()
2159 }
2160 });
2161
2162 let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2163 let results_content_container = || v_flex().p_2().gap_0p5();
2164
2165 let results_content = v_flex()
2166 .gap_1()
2167 .child(
2168 results_content_container()
2169 .child(
2170 Label::new("Input")
2171 .size(LabelSize::XSmall)
2172 .color(Color::Muted)
2173 .buffer_font(cx),
2174 )
2175 .child(
2176 div()
2177 .w_full()
2178 .text_ui_sm(cx)
2179 .children(rendered_tool_use.as_ref().map(|rendered| {
2180 MarkdownElement::new(
2181 rendered.input.clone(),
2182 tool_use_markdown_style(window, cx),
2183 )
2184 .on_url_click({
2185 let workspace = self.workspace.clone();
2186 move |text, window, cx| {
2187 open_markdown_link(text, workspace.clone(), window, cx);
2188 }
2189 })
2190 })),
2191 ),
2192 )
2193 .map(|container| match tool_use.status {
2194 ToolUseStatus::Finished(_) => container.child(
2195 results_content_container()
2196 .border_t_1()
2197 .border_color(self.tool_card_border_color(cx))
2198 .child(
2199 Label::new("Result")
2200 .size(LabelSize::XSmall)
2201 .color(Color::Muted)
2202 .buffer_font(cx),
2203 )
2204 .child(div().w_full().text_ui_sm(cx).children(
2205 rendered_tool_use.as_ref().map(|rendered| {
2206 MarkdownElement::new(
2207 rendered.output.clone(),
2208 tool_use_markdown_style(window, cx),
2209 )
2210 .on_url_click({
2211 let workspace = self.workspace.clone();
2212 move |text, window, cx| {
2213 open_markdown_link(text, workspace.clone(), window, cx);
2214 }
2215 })
2216 }),
2217 )),
2218 ),
2219 ToolUseStatus::Running => container.child(
2220 results_content_container().child(
2221 h_flex()
2222 .gap_1()
2223 .pb_1()
2224 .border_t_1()
2225 .border_color(self.tool_card_border_color(cx))
2226 .child(
2227 Icon::new(IconName::ArrowCircle)
2228 .size(IconSize::Small)
2229 .color(Color::Accent)
2230 .with_animation(
2231 "arrow-circle",
2232 Animation::new(Duration::from_secs(2)).repeat(),
2233 |icon, delta| {
2234 icon.transform(Transformation::rotate(percentage(
2235 delta,
2236 )))
2237 },
2238 ),
2239 )
2240 .child(
2241 Label::new("Running…")
2242 .size(LabelSize::XSmall)
2243 .color(Color::Muted)
2244 .buffer_font(cx),
2245 ),
2246 ),
2247 ),
2248 ToolUseStatus::Error(_) => container.child(
2249 results_content_container()
2250 .border_t_1()
2251 .border_color(self.tool_card_border_color(cx))
2252 .child(
2253 Label::new("Error")
2254 .size(LabelSize::XSmall)
2255 .color(Color::Muted)
2256 .buffer_font(cx),
2257 )
2258 .child(
2259 div()
2260 .text_ui_sm(cx)
2261 .children(rendered_tool_use.as_ref().map(|rendered| {
2262 MarkdownElement::new(
2263 rendered.output.clone(),
2264 tool_use_markdown_style(window, cx),
2265 )
2266 .on_url_click({
2267 let workspace = self.workspace.clone();
2268 move |text, window, cx| {
2269 open_markdown_link(text, workspace.clone(), window, cx);
2270 }
2271 })
2272 })),
2273 ),
2274 ),
2275 ToolUseStatus::Pending => container,
2276 ToolUseStatus::NeedsConfirmation => container.child(
2277 results_content_container()
2278 .border_t_1()
2279 .border_color(self.tool_card_border_color(cx))
2280 .child(
2281 Label::new("Asking Permission")
2282 .size(LabelSize::Small)
2283 .color(Color::Muted)
2284 .buffer_font(cx),
2285 ),
2286 ),
2287 });
2288
2289 let gradient_overlay = |color: Hsla| {
2290 div()
2291 .h_full()
2292 .absolute()
2293 .w_12()
2294 .bottom_0()
2295 .map(|element| {
2296 if is_status_finished {
2297 element.right_6()
2298 } else {
2299 element.right(px(44.))
2300 }
2301 })
2302 .bg(linear_gradient(
2303 90.,
2304 linear_color_stop(color, 1.),
2305 linear_color_stop(color.opacity(0.2), 0.),
2306 ))
2307 };
2308
2309 div().map(|element| {
2310 if !edit_tools {
2311 element.child(
2312 v_flex()
2313 .my_2()
2314 .child(
2315 h_flex()
2316 .group("disclosure-header")
2317 .relative()
2318 .gap_1p5()
2319 .justify_between()
2320 .opacity(0.8)
2321 .hover(|style| style.opacity(1.))
2322 .when(!is_status_finished, |this| this.pr_2())
2323 .child(
2324 h_flex()
2325 .id("tool-label-container")
2326 .gap_1p5()
2327 .max_w_full()
2328 .overflow_x_scroll()
2329 .child(
2330 Icon::new(tool_use.icon)
2331 .size(IconSize::XSmall)
2332 .color(Color::Muted),
2333 )
2334 .child(
2335 h_flex().pr_8().text_ui_sm(cx).children(
2336 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| {
2337 open_markdown_link(text, workspace.clone(), window, cx);
2338 }}))
2339 ),
2340 ),
2341 )
2342 .child(
2343 h_flex()
2344 .gap_1()
2345 .child(
2346 div().visible_on_hover("disclosure-header").child(
2347 Disclosure::new("tool-use-disclosure", is_open)
2348 .opened_icon(IconName::ChevronUp)
2349 .closed_icon(IconName::ChevronDown)
2350 .on_click(cx.listener({
2351 let tool_use_id = tool_use.id.clone();
2352 move |this, _event, _window, _cx| {
2353 let is_open = this
2354 .expanded_tool_uses
2355 .entry(tool_use_id.clone())
2356 .or_insert(false);
2357
2358 *is_open = !*is_open;
2359 }
2360 })),
2361 ),
2362 )
2363 .child(status_icons),
2364 )
2365 .child(gradient_overlay(cx.theme().colors().panel_background)),
2366 )
2367 .map(|parent| {
2368 if !is_open {
2369 return parent;
2370 }
2371
2372 parent.child(
2373 v_flex()
2374 .mt_1()
2375 .border_1()
2376 .border_color(self.tool_card_border_color(cx))
2377 .bg(cx.theme().colors().editor_background)
2378 .rounded_lg()
2379 .child(results_content),
2380 )
2381 }),
2382 )
2383 } else {
2384 v_flex()
2385 .my_3()
2386 .rounded_lg()
2387 .border_1()
2388 .border_color(self.tool_card_border_color(cx))
2389 .overflow_hidden()
2390 .child(
2391 h_flex()
2392 .group("disclosure-header")
2393 .relative()
2394 .justify_between()
2395 .py_1()
2396 .map(|element| {
2397 if is_status_finished {
2398 element.pl_2().pr_0p5()
2399 } else {
2400 element.px_2()
2401 }
2402 })
2403 .bg(self.tool_card_header_bg(cx))
2404 .map(|element| {
2405 if is_open {
2406 element.border_b_1().rounded_t_md()
2407 } else if needs_confirmation {
2408 element.rounded_t_md()
2409 } else {
2410 element.rounded_md()
2411 }
2412 })
2413 .border_color(self.tool_card_border_color(cx))
2414 .child(
2415 h_flex()
2416 .id("tool-label-container")
2417 .gap_1p5()
2418 .max_w_full()
2419 .overflow_x_scroll()
2420 .child(
2421 Icon::new(tool_use.icon)
2422 .size(IconSize::XSmall)
2423 .color(Color::Muted),
2424 )
2425 .child(
2426 h_flex().pr_8().text_ui_sm(cx).children(
2427 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| {
2428 open_markdown_link(text, workspace.clone(), window, cx);
2429 }}))
2430 ),
2431 ),
2432 )
2433 .child(
2434 h_flex()
2435 .gap_1()
2436 .child(
2437 div().visible_on_hover("disclosure-header").child(
2438 Disclosure::new("tool-use-disclosure", is_open)
2439 .opened_icon(IconName::ChevronUp)
2440 .closed_icon(IconName::ChevronDown)
2441 .on_click(cx.listener({
2442 let tool_use_id = tool_use.id.clone();
2443 move |this, _event, _window, _cx| {
2444 let is_open = this
2445 .expanded_tool_uses
2446 .entry(tool_use_id.clone())
2447 .or_insert(false);
2448
2449 *is_open = !*is_open;
2450 }
2451 })),
2452 ),
2453 )
2454 .child(status_icons),
2455 )
2456 .child(gradient_overlay(self.tool_card_header_bg(cx))),
2457 )
2458 .map(|parent| {
2459 if !is_open {
2460 return parent;
2461 }
2462
2463 parent.child(
2464 v_flex()
2465 .bg(cx.theme().colors().editor_background)
2466 .map(|element| {
2467 if needs_confirmation {
2468 element.rounded_none()
2469 } else {
2470 element.rounded_b_lg()
2471 }
2472 })
2473 .child(results_content),
2474 )
2475 })
2476 .when(needs_confirmation, |this| {
2477 this.child(
2478 h_flex()
2479 .py_1()
2480 .pl_2()
2481 .pr_1()
2482 .gap_1()
2483 .justify_between()
2484 .bg(cx.theme().colors().editor_background)
2485 .border_t_1()
2486 .border_color(self.tool_card_border_color(cx))
2487 .rounded_b_lg()
2488 .child(
2489 Label::new("Waiting for Confirmation…")
2490 .color(Color::Muted)
2491 .size(LabelSize::Small)
2492 .with_animation(
2493 "generating-label",
2494 Animation::new(Duration::from_secs(1)).repeat(),
2495 |mut label, delta| {
2496 let text = match delta {
2497 d if d < 0.25 => "Waiting for Confirmation",
2498 d if d < 0.5 => "Waiting for Confirmation.",
2499 d if d < 0.75 => "Waiting for Confirmation..",
2500 _ => "Waiting for Confirmation...",
2501 };
2502 label.set_text(text);
2503 label
2504 },
2505 )
2506 .with_animation(
2507 "pulsating-label",
2508 Animation::new(Duration::from_secs(2))
2509 .repeat()
2510 .with_easing(pulsating_between(0.6, 1.)),
2511 |label, delta| label.map_element(|label| label.alpha(delta)),
2512 ),
2513 )
2514 .child(
2515 h_flex()
2516 .gap_0p5()
2517 .child({
2518 let tool_id = tool_use.id.clone();
2519 Button::new(
2520 "always-allow-tool-action",
2521 "Always Allow",
2522 )
2523 .label_size(LabelSize::Small)
2524 .icon(IconName::CheckDouble)
2525 .icon_position(IconPosition::Start)
2526 .icon_size(IconSize::Small)
2527 .icon_color(Color::Success)
2528 .tooltip(move |window, cx| {
2529 Tooltip::with_meta(
2530 "Never ask for permission",
2531 None,
2532 "Restore the original behavior in your Agent Panel settings",
2533 window,
2534 cx,
2535 )
2536 })
2537 .on_click(cx.listener(
2538 move |this, event, window, cx| {
2539 if let Some(fs) = fs.clone() {
2540 update_settings_file::<AssistantSettings>(
2541 fs.clone(),
2542 cx,
2543 |settings, _| {
2544 settings.set_always_allow_tool_actions(true);
2545 },
2546 );
2547 }
2548 this.handle_allow_tool(
2549 tool_id.clone(),
2550 event,
2551 window,
2552 cx,
2553 )
2554 },
2555 ))
2556 })
2557 .child(ui::Divider::vertical())
2558 .child({
2559 let tool_id = tool_use.id.clone();
2560 Button::new("allow-tool-action", "Allow")
2561 .label_size(LabelSize::Small)
2562 .icon(IconName::Check)
2563 .icon_position(IconPosition::Start)
2564 .icon_size(IconSize::Small)
2565 .icon_color(Color::Success)
2566 .on_click(cx.listener(
2567 move |this, event, window, cx| {
2568 this.handle_allow_tool(
2569 tool_id.clone(),
2570 event,
2571 window,
2572 cx,
2573 )
2574 },
2575 ))
2576 })
2577 .child({
2578 let tool_id = tool_use.id.clone();
2579 let tool_name: Arc<str> = tool_use.name.into();
2580 Button::new("deny-tool", "Deny")
2581 .label_size(LabelSize::Small)
2582 .icon(IconName::Close)
2583 .icon_position(IconPosition::Start)
2584 .icon_size(IconSize::Small)
2585 .icon_color(Color::Error)
2586 .on_click(cx.listener(
2587 move |this, event, window, cx| {
2588 this.handle_deny_tool(
2589 tool_id.clone(),
2590 tool_name.clone(),
2591 event,
2592 window,
2593 cx,
2594 )
2595 },
2596 ))
2597 }),
2598 ),
2599 )
2600 })
2601 }
2602 })
2603 }
2604
2605 fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
2606 let Some(system_prompt_context) = self.thread.read(cx).system_prompt_context().as_ref()
2607 else {
2608 return div().into_any();
2609 };
2610
2611 let rules_files = system_prompt_context
2612 .worktrees
2613 .iter()
2614 .filter_map(|worktree| worktree.rules_file.as_ref())
2615 .collect::<Vec<_>>();
2616
2617 let label_text = match rules_files.as_slice() {
2618 &[] => return div().into_any(),
2619 &[rules_file] => {
2620 format!("Using {:?} file", rules_file.path_in_worktree)
2621 }
2622 rules_files => {
2623 format!("Using {} rules files", rules_files.len())
2624 }
2625 };
2626
2627 div()
2628 .pt_2()
2629 .px_2p5()
2630 .child(
2631 h_flex()
2632 .w_full()
2633 .gap_0p5()
2634 .child(
2635 h_flex()
2636 .gap_1p5()
2637 .child(
2638 Icon::new(IconName::File)
2639 .size(IconSize::XSmall)
2640 .color(Color::Disabled),
2641 )
2642 .child(
2643 Label::new(label_text)
2644 .size(LabelSize::XSmall)
2645 .color(Color::Muted)
2646 .buffer_font(cx),
2647 ),
2648 )
2649 .child(
2650 IconButton::new("open-rule", IconName::ArrowUpRightAlt)
2651 .shape(ui::IconButtonShape::Square)
2652 .icon_size(IconSize::XSmall)
2653 .icon_color(Color::Ignored)
2654 .on_click(cx.listener(Self::handle_open_rules))
2655 .tooltip(Tooltip::text("View Rules")),
2656 ),
2657 )
2658 .into_any()
2659 }
2660
2661 fn handle_allow_tool(
2662 &mut self,
2663 tool_use_id: LanguageModelToolUseId,
2664 _: &ClickEvent,
2665 _window: &mut Window,
2666 cx: &mut Context<Self>,
2667 ) {
2668 if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
2669 .thread
2670 .read(cx)
2671 .pending_tool(&tool_use_id)
2672 .map(|tool_use| tool_use.status.clone())
2673 {
2674 self.thread.update(cx, |thread, cx| {
2675 thread.run_tool(
2676 c.tool_use_id.clone(),
2677 c.ui_text.clone(),
2678 c.input.clone(),
2679 &c.messages,
2680 c.tool.clone(),
2681 cx,
2682 );
2683 });
2684 }
2685 }
2686
2687 fn handle_deny_tool(
2688 &mut self,
2689 tool_use_id: LanguageModelToolUseId,
2690 tool_name: Arc<str>,
2691 _: &ClickEvent,
2692 _window: &mut Window,
2693 cx: &mut Context<Self>,
2694 ) {
2695 self.thread.update(cx, |thread, cx| {
2696 thread.deny_tool_use(tool_use_id, tool_name, cx);
2697 });
2698 }
2699
2700 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
2701 let Some(system_prompt_context) = self.thread.read(cx).system_prompt_context().as_ref()
2702 else {
2703 return;
2704 };
2705
2706 let abs_paths = system_prompt_context
2707 .worktrees
2708 .iter()
2709 .flat_map(|worktree| worktree.rules_file.as_ref())
2710 .map(|rules_file| rules_file.abs_path.to_path_buf())
2711 .collect::<Vec<_>>();
2712
2713 if let Ok(task) = self.workspace.update(cx, move |workspace, cx| {
2714 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
2715 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
2716 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
2717 workspace.open_paths(abs_paths, OpenOptions::default(), None, window, cx)
2718 }) {
2719 task.detach();
2720 }
2721 }
2722
2723 fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
2724 for window in self.notifications.drain(..) {
2725 window
2726 .update(cx, |_, window, _| {
2727 window.remove_window();
2728 })
2729 .ok();
2730
2731 self.notification_subscriptions.remove(&window);
2732 }
2733 }
2734
2735 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2736 if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
2737 return None;
2738 }
2739
2740 Some(
2741 div()
2742 .occlude()
2743 .id("active-thread-scrollbar")
2744 .on_mouse_move(cx.listener(|_, _, _, cx| {
2745 cx.notify();
2746 cx.stop_propagation()
2747 }))
2748 .on_hover(|_, _, cx| {
2749 cx.stop_propagation();
2750 })
2751 .on_any_mouse_down(|_, _, cx| {
2752 cx.stop_propagation();
2753 })
2754 .on_mouse_up(
2755 MouseButton::Left,
2756 cx.listener(|_, _, _, cx| {
2757 cx.stop_propagation();
2758 }),
2759 )
2760 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2761 cx.notify();
2762 }))
2763 .h_full()
2764 .absolute()
2765 .right_1()
2766 .top_1()
2767 .bottom_0()
2768 .w(px(12.))
2769 .cursor_default()
2770 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
2771 )
2772 }
2773
2774 fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
2775 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
2776 self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
2777 cx.background_executor()
2778 .timer(SCROLLBAR_SHOW_INTERVAL)
2779 .await;
2780 thread
2781 .update(cx, |thread, cx| {
2782 if !thread.scrollbar_state.is_dragging() {
2783 thread.show_scrollbar = false;
2784 cx.notify();
2785 }
2786 })
2787 .log_err();
2788 }))
2789 }
2790}
2791
2792impl Render for ActiveThread {
2793 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2794 v_flex()
2795 .size_full()
2796 .relative()
2797 .on_mouse_move(cx.listener(|this, _, _, cx| {
2798 this.show_scrollbar = true;
2799 this.hide_scrollbar_later(cx);
2800 cx.notify();
2801 }))
2802 .on_scroll_wheel(cx.listener(|this, _, _, cx| {
2803 this.show_scrollbar = true;
2804 this.hide_scrollbar_later(cx);
2805 cx.notify();
2806 }))
2807 .on_mouse_up(
2808 MouseButton::Left,
2809 cx.listener(|this, _, _, cx| {
2810 this.hide_scrollbar_later(cx);
2811 }),
2812 )
2813 .child(list(self.list_state.clone()).flex_grow())
2814 .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
2815 this.child(scrollbar)
2816 })
2817 }
2818}
2819
2820pub(crate) fn open_context(
2821 id: ContextId,
2822 context_store: Entity<ContextStore>,
2823 workspace: Entity<Workspace>,
2824 window: &mut Window,
2825 cx: &mut App,
2826) {
2827 let Some(context) = context_store.read(cx).context_for_id(id) else {
2828 return;
2829 };
2830
2831 match context {
2832 AssistantContext::File(file_context) => {
2833 if let Some(project_path) = file_context.context_buffer.buffer.read(cx).project_path(cx)
2834 {
2835 workspace.update(cx, |workspace, cx| {
2836 workspace
2837 .open_path(project_path, None, true, window, cx)
2838 .detach_and_log_err(cx);
2839 });
2840 }
2841 }
2842 AssistantContext::Directory(directory_context) => {
2843 let path = directory_context.project_path.clone();
2844 workspace.update(cx, |workspace, cx| {
2845 workspace.project().update(cx, |project, cx| {
2846 if let Some(entry) = project.entry_for_path(&path, cx) {
2847 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2848 }
2849 })
2850 })
2851 }
2852 AssistantContext::Symbol(symbol_context) => {
2853 if let Some(project_path) = symbol_context
2854 .context_symbol
2855 .buffer
2856 .read(cx)
2857 .project_path(cx)
2858 {
2859 let snapshot = symbol_context.context_symbol.buffer.read(cx).snapshot();
2860 let target_position = symbol_context
2861 .context_symbol
2862 .id
2863 .range
2864 .start
2865 .to_point(&snapshot);
2866
2867 let open_task = workspace.update(cx, |workspace, cx| {
2868 workspace.open_path(project_path, None, true, window, cx)
2869 });
2870 window
2871 .spawn(cx, async move |cx| {
2872 if let Some(active_editor) = open_task
2873 .await
2874 .log_err()
2875 .and_then(|item| item.downcast::<Editor>())
2876 {
2877 active_editor
2878 .downgrade()
2879 .update_in(cx, |editor, window, cx| {
2880 editor.go_to_singleton_buffer_point(
2881 target_position,
2882 window,
2883 cx,
2884 );
2885 })
2886 .log_err();
2887 }
2888 })
2889 .detach();
2890 }
2891 }
2892 AssistantContext::FetchedUrl(fetched_url_context) => {
2893 cx.open_url(&fetched_url_context.url);
2894 }
2895 AssistantContext::Thread(thread_context) => {
2896 let thread_id = thread_context.thread.read(cx).id().clone();
2897 workspace.update(cx, |workspace, cx| {
2898 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
2899 panel.update(cx, |panel, cx| {
2900 panel
2901 .open_thread(&thread_id, window, cx)
2902 .detach_and_log_err(cx)
2903 });
2904 }
2905 })
2906 }
2907 }
2908}