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