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