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