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