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 editor_bg_color = colors.editor_background;
1542
1543 let open_as_markdown = IconButton::new(("open-as-markdown", ix), IconName::FileCode)
1544 .shape(ui::IconButtonShape::Square)
1545 .icon_size(IconSize::XSmall)
1546 .icon_color(Color::Ignored)
1547 .tooltip(Tooltip::text("Open Thread as Markdown"))
1548 .on_click(|_, window, cx| {
1549 window.dispatch_action(Box::new(OpenActiveThreadAsMarkdown), cx)
1550 });
1551
1552 // For all items that should be aligned with the Assistant's response.
1553 const RESPONSE_PADDING_X: Pixels = px(18.);
1554
1555 let feedback_container = h_flex()
1556 .py_2()
1557 .px(RESPONSE_PADDING_X)
1558 .gap_1()
1559 .justify_between();
1560 let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1561 Some(feedback) => feedback_container
1562 .child(
1563 Label::new(match feedback {
1564 ThreadFeedback::Positive => "Thanks for your feedback!",
1565 ThreadFeedback::Negative => {
1566 "We appreciate your feedback and will use it to improve."
1567 }
1568 })
1569 .color(Color::Muted)
1570 .size(LabelSize::XSmall),
1571 )
1572 .child(
1573 h_flex()
1574 .pr_1()
1575 .gap_1()
1576 .child(
1577 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1578 .shape(ui::IconButtonShape::Square)
1579 .icon_size(IconSize::XSmall)
1580 .icon_color(match feedback {
1581 ThreadFeedback::Positive => Color::Accent,
1582 ThreadFeedback::Negative => Color::Ignored,
1583 })
1584 .tooltip(Tooltip::text("Helpful Response"))
1585 .on_click(cx.listener(move |this, _, window, cx| {
1586 this.handle_feedback_click(
1587 message_id,
1588 ThreadFeedback::Positive,
1589 window,
1590 cx,
1591 );
1592 })),
1593 )
1594 .child(
1595 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1596 .shape(ui::IconButtonShape::Square)
1597 .icon_size(IconSize::XSmall)
1598 .icon_color(match feedback {
1599 ThreadFeedback::Positive => Color::Ignored,
1600 ThreadFeedback::Negative => Color::Accent,
1601 })
1602 .tooltip(Tooltip::text("Not Helpful"))
1603 .on_click(cx.listener(move |this, _, window, cx| {
1604 this.handle_feedback_click(
1605 message_id,
1606 ThreadFeedback::Negative,
1607 window,
1608 cx,
1609 );
1610 })),
1611 )
1612 .child(open_as_markdown),
1613 )
1614 .into_any_element(),
1615 None => feedback_container
1616 .child(
1617 Label::new(
1618 "Rating the thread sends all of your current conversation to the Zed team.",
1619 )
1620 .color(Color::Muted)
1621 .size(LabelSize::XSmall),
1622 )
1623 .child(
1624 h_flex()
1625 .pr_1()
1626 .gap_1()
1627 .child(
1628 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1629 .icon_size(IconSize::XSmall)
1630 .icon_color(Color::Ignored)
1631 .shape(ui::IconButtonShape::Square)
1632 .tooltip(Tooltip::text("Helpful Response"))
1633 .on_click(cx.listener(move |this, _, window, cx| {
1634 this.handle_feedback_click(
1635 message_id,
1636 ThreadFeedback::Positive,
1637 window,
1638 cx,
1639 );
1640 })),
1641 )
1642 .child(
1643 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1644 .icon_size(IconSize::XSmall)
1645 .icon_color(Color::Ignored)
1646 .shape(ui::IconButtonShape::Square)
1647 .tooltip(Tooltip::text("Not Helpful"))
1648 .on_click(cx.listener(move |this, _, window, cx| {
1649 this.handle_feedback_click(
1650 message_id,
1651 ThreadFeedback::Negative,
1652 window,
1653 cx,
1654 );
1655 })),
1656 )
1657 .child(open_as_markdown),
1658 )
1659 .into_any_element(),
1660 };
1661
1662 let message_is_empty = message.should_display_content();
1663 let has_content = !message_is_empty || !context.is_empty();
1664
1665 let message_content =
1666 has_content.then(|| {
1667 v_flex()
1668 .gap_1p5()
1669 .when(!message_is_empty, |parent| {
1670 parent.child(
1671 if let Some(edit_message_editor) = edit_message_editor.clone() {
1672 let settings = ThemeSettings::get_global(cx);
1673 let font_size = TextSize::Small.rems(cx);
1674 let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1675
1676 let text_style = TextStyle {
1677 color: cx.theme().colors().text,
1678 font_family: settings.buffer_font.family.clone(),
1679 font_fallbacks: settings.buffer_font.fallbacks.clone(),
1680 font_features: settings.buffer_font.features.clone(),
1681 font_size: font_size.into(),
1682 line_height: line_height.into(),
1683 ..Default::default()
1684 };
1685
1686 div()
1687 .key_context("EditMessageEditor")
1688 .on_action(cx.listener(Self::cancel_editing_message))
1689 .on_action(cx.listener(Self::confirm_editing_message))
1690 .min_h_6()
1691 .pt_1()
1692 .child(EditorElement::new(
1693 &edit_message_editor,
1694 EditorStyle {
1695 background: colors.editor_background,
1696 local_player: cx.theme().players().local(),
1697 text: text_style,
1698 syntax: cx.theme().syntax().clone(),
1699 ..Default::default()
1700 },
1701 ))
1702 .into_any()
1703 } else {
1704 div()
1705 .min_h_6()
1706 .child(self.render_message_content(
1707 message_id,
1708 rendered_message,
1709 has_tool_uses,
1710 workspace.clone(),
1711 window,
1712 cx,
1713 ))
1714 .into_any()
1715 },
1716 )
1717 })
1718 .when(!context.is_empty(), |parent| {
1719 parent.child(h_flex().flex_wrap().gap_1().children(
1720 context.into_iter().map(|context| {
1721 let context_id = context.id();
1722 ContextPill::added(
1723 AddedContext::new(context, cx),
1724 false,
1725 false,
1726 None,
1727 )
1728 .on_click(Rc::new(cx.listener({
1729 let workspace = workspace.clone();
1730 let context_store = context_store.clone();
1731 move |_, _, window, cx| {
1732 if let Some(workspace) = workspace.upgrade() {
1733 open_context(
1734 context_id,
1735 context_store.clone(),
1736 workspace,
1737 window,
1738 cx,
1739 );
1740 cx.notify();
1741 }
1742 }
1743 })))
1744 }),
1745 ))
1746 })
1747 });
1748
1749 let styled_message = match message.role {
1750 Role::User => v_flex()
1751 .id(("message-container", ix))
1752 .map(|this| {
1753 if is_first_message {
1754 this.pt_2()
1755 } else {
1756 this.pt_4()
1757 }
1758 })
1759 .pl_2()
1760 .pr_2p5()
1761 .pb_4()
1762 .child(
1763 v_flex()
1764 .bg(editor_bg_color)
1765 .rounded_lg()
1766 .border_1()
1767 .border_color(colors.border)
1768 .shadow_md()
1769 .child(div().py_2().px_2p5().children(message_content))
1770 .child(
1771 h_flex()
1772 .p_1()
1773 .border_t_1()
1774 .border_color(colors.border_variant)
1775 .justify_end()
1776 .child(
1777 h_flex()
1778 .gap_1()
1779 .when_some(
1780 edit_message_editor.clone(),
1781 |this, edit_message_editor| {
1782 let focus_handle =
1783 edit_message_editor.focus_handle(cx);
1784 this.child(
1785 Button::new("cancel-edit-message", "Cancel")
1786 .label_size(LabelSize::Small)
1787 .key_binding(
1788 KeyBinding::for_action_in(
1789 &menu::Cancel,
1790 &focus_handle,
1791 window,
1792 cx,
1793 )
1794 .map(|kb| kb.size(rems_from_px(12.))),
1795 )
1796 .on_click(
1797 cx.listener(Self::handle_cancel_click),
1798 ),
1799 )
1800 .child(
1801 Button::new(
1802 "confirm-edit-message",
1803 "Regenerate",
1804 )
1805 .disabled(
1806 edit_message_editor.read(cx).is_empty(cx),
1807 )
1808 .label_size(LabelSize::Small)
1809 .key_binding(
1810 KeyBinding::for_action_in(
1811 &menu::Confirm,
1812 &focus_handle,
1813 window,
1814 cx,
1815 )
1816 .map(|kb| kb.size(rems_from_px(12.))),
1817 )
1818 .on_click(
1819 cx.listener(Self::handle_regenerate_click),
1820 ),
1821 )
1822 },
1823 )
1824 .when(
1825 edit_message_editor.is_none() && allow_editing_message,
1826 |this| {
1827 this.child(
1828 Button::new("edit-message", "Edit Message")
1829 .label_size(LabelSize::Small)
1830 .icon(IconName::Pencil)
1831 .icon_size(IconSize::XSmall)
1832 .icon_color(Color::Muted)
1833 .icon_position(IconPosition::Start)
1834 .on_click(cx.listener({
1835 let message_segments =
1836 message.segments.clone();
1837 move |this, _, window, cx| {
1838 this.start_editing_message(
1839 message_id,
1840 &message_segments,
1841 window,
1842 cx,
1843 );
1844 }
1845 })),
1846 )
1847 },
1848 ),
1849 ),
1850 ),
1851 ),
1852 Role::Assistant => v_flex()
1853 .id(("message-container", ix))
1854 .px(RESPONSE_PADDING_X)
1855 .gap_2()
1856 .children(message_content)
1857 .when(has_tool_uses, |parent| {
1858 parent.children(
1859 tool_uses
1860 .into_iter()
1861 .map(|tool_use| self.render_tool_use(tool_use, window, cx)),
1862 )
1863 }),
1864 Role::System => div().id(("message-container", ix)).py_1().px_2().child(
1865 v_flex()
1866 .bg(colors.editor_background)
1867 .rounded_sm()
1868 .child(div().p_4().children(message_content)),
1869 ),
1870 };
1871
1872 let after_editing_message = self
1873 .editing_message
1874 .as_ref()
1875 .map_or(false, |(editing_message_id, _)| {
1876 message_id > *editing_message_id
1877 });
1878
1879 let panel_background = cx.theme().colors().panel_background;
1880
1881 v_flex()
1882 .w_full()
1883 .when_some(checkpoint, |parent, checkpoint| {
1884 let mut is_pending = false;
1885 let mut error = None;
1886 if let Some(last_restore_checkpoint) =
1887 self.thread.read(cx).last_restore_checkpoint()
1888 {
1889 if last_restore_checkpoint.message_id() == message_id {
1890 match last_restore_checkpoint {
1891 LastRestoreCheckpoint::Pending { .. } => is_pending = true,
1892 LastRestoreCheckpoint::Error { error: err, .. } => {
1893 error = Some(err.clone());
1894 }
1895 }
1896 }
1897 }
1898
1899 let restore_checkpoint_button =
1900 Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
1901 .icon(if error.is_some() {
1902 IconName::XCircle
1903 } else {
1904 IconName::Undo
1905 })
1906 .icon_size(IconSize::XSmall)
1907 .icon_position(IconPosition::Start)
1908 .icon_color(if error.is_some() {
1909 Some(Color::Error)
1910 } else {
1911 None
1912 })
1913 .label_size(LabelSize::XSmall)
1914 .disabled(is_pending)
1915 .on_click(cx.listener(move |this, _, _window, cx| {
1916 this.thread.update(cx, |thread, cx| {
1917 thread
1918 .restore_checkpoint(checkpoint.clone(), cx)
1919 .detach_and_log_err(cx);
1920 });
1921 }));
1922
1923 let restore_checkpoint_button = if is_pending {
1924 restore_checkpoint_button
1925 .with_animation(
1926 ("pulsating-restore-checkpoint-button", ix),
1927 Animation::new(Duration::from_secs(2))
1928 .repeat()
1929 .with_easing(pulsating_between(0.6, 1.)),
1930 |label, delta| label.alpha(delta),
1931 )
1932 .into_any_element()
1933 } else if let Some(error) = error {
1934 restore_checkpoint_button
1935 .tooltip(Tooltip::text(error.to_string()))
1936 .into_any_element()
1937 } else {
1938 restore_checkpoint_button.into_any_element()
1939 };
1940
1941 parent.child(
1942 h_flex()
1943 .pt_2p5()
1944 .px_2p5()
1945 .w_full()
1946 .gap_1()
1947 .child(ui::Divider::horizontal())
1948 .child(restore_checkpoint_button)
1949 .child(ui::Divider::horizontal()),
1950 )
1951 })
1952 .when(is_first_message, |parent| {
1953 parent.child(self.render_rules_item(cx))
1954 })
1955 .child(styled_message)
1956 .when(!needs_confirmation && generating_label.is_some(), |this| {
1957 this.child(
1958 h_flex()
1959 .h_8()
1960 .mt_2()
1961 .mb_4()
1962 .ml_4()
1963 .py_1p5()
1964 .child(generating_label.unwrap()),
1965 )
1966 })
1967 .when(show_feedback, move |parent| {
1968 parent.child(feedback_items).when_some(
1969 self.open_feedback_editors.get(&message_id),
1970 move |parent, feedback_editor| {
1971 let focus_handle = feedback_editor.focus_handle(cx);
1972 parent.child(
1973 v_flex()
1974 .key_context("AgentFeedbackMessageEditor")
1975 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
1976 this.open_feedback_editors.remove(&message_id);
1977 cx.notify();
1978 }))
1979 .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
1980 this.submit_feedback_message(message_id, cx);
1981 cx.notify();
1982 }))
1983 .on_action(cx.listener(Self::confirm_editing_message))
1984 .mb_2()
1985 .mx_4()
1986 .p_2()
1987 .rounded_md()
1988 .border_1()
1989 .border_color(cx.theme().colors().border)
1990 .bg(cx.theme().colors().editor_background)
1991 .child(feedback_editor.clone())
1992 .child(
1993 h_flex()
1994 .gap_1()
1995 .justify_end()
1996 .child(
1997 Button::new("dismiss-feedback-message", "Cancel")
1998 .label_size(LabelSize::Small)
1999 .key_binding(
2000 KeyBinding::for_action_in(
2001 &menu::Cancel,
2002 &focus_handle,
2003 window,
2004 cx,
2005 )
2006 .map(|kb| kb.size(rems_from_px(10.))),
2007 )
2008 .on_click(cx.listener(
2009 move |this, _, _window, cx| {
2010 this.open_feedback_editors
2011 .remove(&message_id);
2012 cx.notify();
2013 },
2014 )),
2015 )
2016 .child(
2017 Button::new(
2018 "submit-feedback-message",
2019 "Share Feedback",
2020 )
2021 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2022 .label_size(LabelSize::Small)
2023 .key_binding(
2024 KeyBinding::for_action_in(
2025 &menu::Confirm,
2026 &focus_handle,
2027 window,
2028 cx,
2029 )
2030 .map(|kb| kb.size(rems_from_px(10.))),
2031 )
2032 .on_click(
2033 cx.listener(move |this, _, _window, cx| {
2034 this.submit_feedback_message(message_id, cx);
2035 cx.notify()
2036 }),
2037 ),
2038 ),
2039 ),
2040 )
2041 },
2042 )
2043 })
2044 .when(after_editing_message, |parent| {
2045 // Backdrop to dim out the whole thread below the editing user message
2046 parent.relative().child(
2047 div()
2048 .occlude()
2049 .absolute()
2050 .inset_0()
2051 .size_full()
2052 .bg(panel_background)
2053 .opacity(0.8),
2054 )
2055 })
2056 .into_any()
2057 }
2058
2059 fn render_message_content(
2060 &self,
2061 message_id: MessageId,
2062 rendered_message: &RenderedMessage,
2063 has_tool_uses: bool,
2064 workspace: WeakEntity<Workspace>,
2065 window: &Window,
2066 cx: &Context<Self>,
2067 ) -> impl IntoElement {
2068 let is_last_message = self.messages.last() == Some(&message_id);
2069 let is_generating = self.thread.read(cx).is_generating();
2070 let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2071 rendered_message
2072 .segments
2073 .iter()
2074 .enumerate()
2075 .next_back()
2076 .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2077 .map(|(index, _)| index)
2078 } else {
2079 None
2080 };
2081
2082 let message_role = self
2083 .thread
2084 .read(cx)
2085 .message(message_id)
2086 .map(|m| m.role)
2087 .unwrap_or(Role::User);
2088
2089 let is_assistant_message = message_role == Role::Assistant;
2090 let is_user_message = message_role == Role::User;
2091
2092 v_flex()
2093 .text_ui(cx)
2094 .gap_2()
2095 .when(is_user_message, |this| this.text_xs())
2096 .children(
2097 rendered_message.segments.iter().enumerate().map(
2098 |(index, segment)| match segment {
2099 RenderedMessageSegment::Thinking {
2100 content,
2101 scroll_handle,
2102 } => self
2103 .render_message_thinking_segment(
2104 message_id,
2105 index,
2106 content.clone(),
2107 &scroll_handle,
2108 Some(index) == pending_thinking_segment_index,
2109 window,
2110 cx,
2111 )
2112 .into_any_element(),
2113 RenderedMessageSegment::Text(markdown) => {
2114 let markdown_element = MarkdownElement::new(
2115 markdown.clone(),
2116 if is_user_message {
2117 let mut style = default_markdown_style(window, cx);
2118 let mut text_style = window.text_style();
2119 let theme_settings = ThemeSettings::get_global(cx);
2120
2121 let buffer_font = theme_settings.buffer_font.family.clone();
2122 let buffer_font_size = TextSize::Small.rems(cx);
2123
2124 text_style.refine(&TextStyleRefinement {
2125 font_family: Some(buffer_font),
2126 font_size: Some(buffer_font_size.into()),
2127 ..Default::default()
2128 });
2129
2130 style.base_text_style = text_style;
2131 style
2132 } else {
2133 default_markdown_style(window, cx)
2134 },
2135 );
2136
2137 let markdown_element = if is_assistant_message {
2138 markdown_element.code_block_renderer(
2139 markdown::CodeBlockRenderer::Custom {
2140 render: Arc::new({
2141 let workspace = workspace.clone();
2142 let active_thread = cx.entity();
2143 move |kind,
2144 parsed_markdown,
2145 range,
2146 metadata,
2147 window,
2148 cx| {
2149 render_markdown_code_block(
2150 message_id,
2151 range.start,
2152 kind,
2153 parsed_markdown,
2154 metadata,
2155 active_thread.clone(),
2156 workspace.clone(),
2157 window,
2158 cx,
2159 )
2160 }
2161 }),
2162 transform: Some(Arc::new({
2163 let active_thread = cx.entity();
2164 move |el, range, metadata, _, cx| {
2165 let is_expanded = active_thread
2166 .read(cx)
2167 .expanded_code_blocks
2168 .get(&(message_id, range.start))
2169 .copied()
2170 .unwrap_or(false);
2171
2172 if is_expanded
2173 || metadata.line_count
2174 <= MAX_UNCOLLAPSED_LINES_IN_CODE_BLOCK
2175 {
2176 return el;
2177 }
2178 el.child(
2179 div()
2180 .absolute()
2181 .bottom_0()
2182 .left_0()
2183 .w_full()
2184 .h_1_4()
2185 .rounded_b_lg()
2186 .bg(gpui::linear_gradient(
2187 0.,
2188 gpui::linear_color_stop(
2189 cx.theme()
2190 .colors()
2191 .editor_background,
2192 0.,
2193 ),
2194 gpui::linear_color_stop(
2195 cx.theme()
2196 .colors()
2197 .editor_background
2198 .opacity(0.),
2199 1.,
2200 ),
2201 )),
2202 )
2203 }
2204 })),
2205 },
2206 )
2207 } else {
2208 markdown_element.code_block_renderer(
2209 markdown::CodeBlockRenderer::Default {
2210 copy_button: false,
2211 border: true,
2212 },
2213 )
2214 };
2215
2216 div()
2217 .child(markdown_element.on_url_click({
2218 let workspace = self.workspace.clone();
2219 move |text, window, cx| {
2220 open_markdown_link(text, workspace.clone(), window, cx);
2221 }
2222 }))
2223 .into_any_element()
2224 }
2225 },
2226 ),
2227 )
2228 }
2229
2230 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2231 cx.theme().colors().border.opacity(0.5)
2232 }
2233
2234 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2235 cx.theme()
2236 .colors()
2237 .element_background
2238 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2239 }
2240
2241 fn render_message_thinking_segment(
2242 &self,
2243 message_id: MessageId,
2244 ix: usize,
2245 markdown: Entity<Markdown>,
2246 scroll_handle: &ScrollHandle,
2247 pending: bool,
2248 window: &Window,
2249 cx: &Context<Self>,
2250 ) -> impl IntoElement {
2251 let is_open = self
2252 .expanded_thinking_segments
2253 .get(&(message_id, ix))
2254 .copied()
2255 .unwrap_or_default();
2256
2257 let editor_bg = cx.theme().colors().panel_background;
2258
2259 div().map(|this| {
2260 if pending {
2261 this.v_flex()
2262 .mt_neg_2()
2263 .mb_1p5()
2264 .child(
2265 h_flex()
2266 .group("disclosure-header")
2267 .justify_between()
2268 .child(
2269 h_flex()
2270 .gap_1p5()
2271 .child(
2272 Icon::new(IconName::LightBulb)
2273 .size(IconSize::XSmall)
2274 .color(Color::Muted),
2275 )
2276 .child({
2277 Label::new("Thinking")
2278 .color(Color::Muted)
2279 .size(LabelSize::Small)
2280 .with_animation(
2281 "generating-label",
2282 Animation::new(Duration::from_secs(1)).repeat(),
2283 |mut label, delta| {
2284 let text = match delta {
2285 d if d < 0.25 => "Thinking",
2286 d if d < 0.5 => "Thinking.",
2287 d if d < 0.75 => "Thinking..",
2288 _ => "Thinking...",
2289 };
2290 label.set_text(text);
2291 label
2292 },
2293 )
2294 .with_animation(
2295 "pulsating-label",
2296 Animation::new(Duration::from_secs(2))
2297 .repeat()
2298 .with_easing(pulsating_between(0.6, 1.)),
2299 |label, delta| {
2300 label.map_element(|label| label.alpha(delta))
2301 },
2302 )
2303 }),
2304 )
2305 .child(
2306 h_flex()
2307 .gap_1()
2308 .child(
2309 div().visible_on_hover("disclosure-header").child(
2310 Disclosure::new("thinking-disclosure", is_open)
2311 .opened_icon(IconName::ChevronUp)
2312 .closed_icon(IconName::ChevronDown)
2313 .on_click(cx.listener({
2314 move |this, _event, _window, _cx| {
2315 let is_open = this
2316 .expanded_thinking_segments
2317 .entry((message_id, ix))
2318 .or_insert(false);
2319
2320 *is_open = !*is_open;
2321 }
2322 })),
2323 ),
2324 )
2325 .child({
2326 Icon::new(IconName::ArrowCircle)
2327 .color(Color::Accent)
2328 .size(IconSize::Small)
2329 .with_animation(
2330 "arrow-circle",
2331 Animation::new(Duration::from_secs(2)).repeat(),
2332 |icon, delta| {
2333 icon.transform(Transformation::rotate(
2334 percentage(delta),
2335 ))
2336 },
2337 )
2338 }),
2339 ),
2340 )
2341 .when(!is_open, |this| {
2342 let gradient_overlay = div()
2343 .rounded_b_lg()
2344 .h_full()
2345 .absolute()
2346 .w_full()
2347 .bottom_0()
2348 .left_0()
2349 .bg(linear_gradient(
2350 180.,
2351 linear_color_stop(editor_bg, 1.),
2352 linear_color_stop(editor_bg.opacity(0.2), 0.),
2353 ));
2354
2355 this.child(
2356 div()
2357 .relative()
2358 .bg(editor_bg)
2359 .rounded_b_lg()
2360 .mt_2()
2361 .pl_4()
2362 .child(
2363 div()
2364 .id(("thinking-content", ix))
2365 .max_h_20()
2366 .track_scroll(scroll_handle)
2367 .text_ui_sm(cx)
2368 .overflow_hidden()
2369 .child(
2370 MarkdownElement::new(
2371 markdown.clone(),
2372 default_markdown_style(window, cx),
2373 )
2374 .on_url_click({
2375 let workspace = self.workspace.clone();
2376 move |text, window, cx| {
2377 open_markdown_link(
2378 text,
2379 workspace.clone(),
2380 window,
2381 cx,
2382 );
2383 }
2384 }),
2385 ),
2386 )
2387 .child(gradient_overlay),
2388 )
2389 })
2390 .when(is_open, |this| {
2391 this.child(
2392 div()
2393 .id(("thinking-content", ix))
2394 .h_full()
2395 .bg(editor_bg)
2396 .text_ui_sm(cx)
2397 .child(
2398 MarkdownElement::new(
2399 markdown.clone(),
2400 default_markdown_style(window, cx),
2401 )
2402 .on_url_click({
2403 let workspace = self.workspace.clone();
2404 move |text, window, cx| {
2405 open_markdown_link(text, workspace.clone(), window, cx);
2406 }
2407 }),
2408 ),
2409 )
2410 })
2411 } else {
2412 this.v_flex()
2413 .mt_neg_2()
2414 .child(
2415 h_flex()
2416 .group("disclosure-header")
2417 .pr_1()
2418 .justify_between()
2419 .opacity(0.8)
2420 .hover(|style| style.opacity(1.))
2421 .child(
2422 h_flex()
2423 .gap_1p5()
2424 .child(
2425 Icon::new(IconName::LightBulb)
2426 .size(IconSize::XSmall)
2427 .color(Color::Muted),
2428 )
2429 .child(Label::new("Thought Process").size(LabelSize::Small)),
2430 )
2431 .child(
2432 div().visible_on_hover("disclosure-header").child(
2433 Disclosure::new("thinking-disclosure", is_open)
2434 .opened_icon(IconName::ChevronUp)
2435 .closed_icon(IconName::ChevronDown)
2436 .on_click(cx.listener({
2437 move |this, _event, _window, _cx| {
2438 let is_open = this
2439 .expanded_thinking_segments
2440 .entry((message_id, ix))
2441 .or_insert(false);
2442
2443 *is_open = !*is_open;
2444 }
2445 })),
2446 ),
2447 ),
2448 )
2449 .child(
2450 div()
2451 .id(("thinking-content", ix))
2452 .relative()
2453 .mt_1p5()
2454 .ml_1p5()
2455 .pl_2p5()
2456 .border_l_1()
2457 .border_color(cx.theme().colors().border_variant)
2458 .text_ui_sm(cx)
2459 .when(is_open, |this| {
2460 this.child(
2461 MarkdownElement::new(
2462 markdown.clone(),
2463 default_markdown_style(window, cx),
2464 )
2465 .on_url_click({
2466 let workspace = self.workspace.clone();
2467 move |text, window, cx| {
2468 open_markdown_link(text, workspace.clone(), window, cx);
2469 }
2470 }),
2471 )
2472 }),
2473 )
2474 }
2475 })
2476 }
2477
2478 fn render_tool_use(
2479 &self,
2480 tool_use: ToolUse,
2481 window: &mut Window,
2482 cx: &mut Context<Self>,
2483 ) -> impl IntoElement + use<> {
2484 if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2485 return card.render(&tool_use.status, window, cx);
2486 }
2487
2488 let is_open = self
2489 .expanded_tool_uses
2490 .get(&tool_use.id)
2491 .copied()
2492 .unwrap_or_default();
2493
2494 let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2495
2496 let fs = self
2497 .workspace
2498 .upgrade()
2499 .map(|workspace| workspace.read(cx).app_state().fs.clone());
2500 let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2501 let edit_tools = tool_use.needs_confirmation;
2502
2503 let status_icons = div().child(match &tool_use.status {
2504 ToolUseStatus::Pending | ToolUseStatus::NeedsConfirmation => {
2505 let icon = Icon::new(IconName::Warning)
2506 .color(Color::Warning)
2507 .size(IconSize::Small);
2508 icon.into_any_element()
2509 }
2510 ToolUseStatus::Running => {
2511 let icon = Icon::new(IconName::ArrowCircle)
2512 .color(Color::Accent)
2513 .size(IconSize::Small);
2514 icon.with_animation(
2515 "arrow-circle",
2516 Animation::new(Duration::from_secs(2)).repeat(),
2517 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2518 )
2519 .into_any_element()
2520 }
2521 ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2522 ToolUseStatus::Error(_) => {
2523 let icon = Icon::new(IconName::Close)
2524 .color(Color::Error)
2525 .size(IconSize::Small);
2526 icon.into_any_element()
2527 }
2528 });
2529
2530 let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2531 let results_content_container = || v_flex().p_2().gap_0p5();
2532
2533 let results_content = v_flex()
2534 .gap_1()
2535 .child(
2536 results_content_container()
2537 .child(
2538 Label::new("Input")
2539 .size(LabelSize::XSmall)
2540 .color(Color::Muted)
2541 .buffer_font(cx),
2542 )
2543 .child(
2544 div()
2545 .w_full()
2546 .text_ui_sm(cx)
2547 .children(rendered_tool_use.as_ref().map(|rendered| {
2548 MarkdownElement::new(
2549 rendered.input.clone(),
2550 tool_use_markdown_style(window, cx),
2551 )
2552 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2553 copy_button: false,
2554 border: false,
2555 })
2556 .on_url_click({
2557 let workspace = self.workspace.clone();
2558 move |text, window, cx| {
2559 open_markdown_link(text, workspace.clone(), window, cx);
2560 }
2561 })
2562 })),
2563 ),
2564 )
2565 .map(|container| match tool_use.status {
2566 ToolUseStatus::Finished(_) => container.child(
2567 results_content_container()
2568 .border_t_1()
2569 .border_color(self.tool_card_border_color(cx))
2570 .child(
2571 Label::new("Result")
2572 .size(LabelSize::XSmall)
2573 .color(Color::Muted)
2574 .buffer_font(cx),
2575 )
2576 .child(div().w_full().text_ui_sm(cx).children(
2577 rendered_tool_use.as_ref().map(|rendered| {
2578 MarkdownElement::new(
2579 rendered.output.clone(),
2580 tool_use_markdown_style(window, cx),
2581 )
2582 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2583 copy_button: false,
2584 border: false,
2585 })
2586 .on_url_click({
2587 let workspace = self.workspace.clone();
2588 move |text, window, cx| {
2589 open_markdown_link(text, workspace.clone(), window, cx);
2590 }
2591 })
2592 .into_any_element()
2593 }),
2594 )),
2595 ),
2596 ToolUseStatus::Running => container.child(
2597 results_content_container().child(
2598 h_flex()
2599 .gap_1()
2600 .pb_1()
2601 .border_t_1()
2602 .border_color(self.tool_card_border_color(cx))
2603 .child(
2604 Icon::new(IconName::ArrowCircle)
2605 .size(IconSize::Small)
2606 .color(Color::Accent)
2607 .with_animation(
2608 "arrow-circle",
2609 Animation::new(Duration::from_secs(2)).repeat(),
2610 |icon, delta| {
2611 icon.transform(Transformation::rotate(percentage(
2612 delta,
2613 )))
2614 },
2615 ),
2616 )
2617 .child(
2618 Label::new("Running…")
2619 .size(LabelSize::XSmall)
2620 .color(Color::Muted)
2621 .buffer_font(cx),
2622 ),
2623 ),
2624 ),
2625 ToolUseStatus::Error(_) => container.child(
2626 results_content_container()
2627 .border_t_1()
2628 .border_color(self.tool_card_border_color(cx))
2629 .child(
2630 Label::new("Error")
2631 .size(LabelSize::XSmall)
2632 .color(Color::Muted)
2633 .buffer_font(cx),
2634 )
2635 .child(
2636 div()
2637 .text_ui_sm(cx)
2638 .children(rendered_tool_use.as_ref().map(|rendered| {
2639 MarkdownElement::new(
2640 rendered.output.clone(),
2641 tool_use_markdown_style(window, cx),
2642 )
2643 .on_url_click({
2644 let workspace = self.workspace.clone();
2645 move |text, window, cx| {
2646 open_markdown_link(text, workspace.clone(), window, cx);
2647 }
2648 })
2649 .into_any_element()
2650 })),
2651 ),
2652 ),
2653 ToolUseStatus::Pending => container,
2654 ToolUseStatus::NeedsConfirmation => container.child(
2655 results_content_container()
2656 .border_t_1()
2657 .border_color(self.tool_card_border_color(cx))
2658 .child(
2659 Label::new("Asking Permission")
2660 .size(LabelSize::Small)
2661 .color(Color::Muted)
2662 .buffer_font(cx),
2663 ),
2664 ),
2665 });
2666
2667 let gradient_overlay = |color: Hsla| {
2668 div()
2669 .h_full()
2670 .absolute()
2671 .w_12()
2672 .bottom_0()
2673 .map(|element| {
2674 if is_status_finished {
2675 element.right_6()
2676 } else {
2677 element.right(px(44.))
2678 }
2679 })
2680 .bg(linear_gradient(
2681 90.,
2682 linear_color_stop(color, 1.),
2683 linear_color_stop(color.opacity(0.2), 0.),
2684 ))
2685 };
2686
2687 v_flex().gap_1().mb_3().map(|element| {
2688 if !edit_tools {
2689 element.child(
2690 v_flex()
2691 .child(
2692 h_flex()
2693 .group("disclosure-header")
2694 .relative()
2695 .gap_1p5()
2696 .justify_between()
2697 .opacity(0.8)
2698 .hover(|style| style.opacity(1.))
2699 .when(!is_status_finished, |this| this.pr_2())
2700 .child(
2701 h_flex()
2702 .id("tool-label-container")
2703 .gap_1p5()
2704 .max_w_full()
2705 .overflow_x_scroll()
2706 .child(
2707 Icon::new(tool_use.icon)
2708 .size(IconSize::XSmall)
2709 .color(Color::Muted),
2710 )
2711 .child(
2712 h_flex().pr_8().text_size(rems(0.8125)).children(
2713 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| {
2714 open_markdown_link(text, workspace.clone(), window, cx);
2715 }}))
2716 ),
2717 ),
2718 )
2719 .child(
2720 h_flex()
2721 .gap_1()
2722 .child(
2723 div().visible_on_hover("disclosure-header").child(
2724 Disclosure::new("tool-use-disclosure", is_open)
2725 .opened_icon(IconName::ChevronUp)
2726 .closed_icon(IconName::ChevronDown)
2727 .on_click(cx.listener({
2728 let tool_use_id = tool_use.id.clone();
2729 move |this, _event, _window, _cx| {
2730 let is_open = this
2731 .expanded_tool_uses
2732 .entry(tool_use_id.clone())
2733 .or_insert(false);
2734
2735 *is_open = !*is_open;
2736 }
2737 })),
2738 ),
2739 )
2740 .child(status_icons),
2741 )
2742 .child(gradient_overlay(cx.theme().colors().panel_background)),
2743 )
2744 .map(|parent| {
2745 if !is_open {
2746 return parent;
2747 }
2748
2749 parent.child(
2750 v_flex()
2751 .mt_1()
2752 .border_1()
2753 .border_color(self.tool_card_border_color(cx))
2754 .bg(cx.theme().colors().editor_background)
2755 .rounded_lg()
2756 .child(results_content),
2757 )
2758 }),
2759 )
2760 } else {
2761 v_flex()
2762 .mb_2()
2763 .rounded_lg()
2764 .border_1()
2765 .border_color(self.tool_card_border_color(cx))
2766 .overflow_hidden()
2767 .child(
2768 h_flex()
2769 .group("disclosure-header")
2770 .relative()
2771 .justify_between()
2772 .py_1()
2773 .map(|element| {
2774 if is_status_finished {
2775 element.pl_2().pr_0p5()
2776 } else {
2777 element.px_2()
2778 }
2779 })
2780 .bg(self.tool_card_header_bg(cx))
2781 .map(|element| {
2782 if is_open {
2783 element.border_b_1().rounded_t_md()
2784 } else if needs_confirmation {
2785 element.rounded_t_md()
2786 } else {
2787 element.rounded_md()
2788 }
2789 })
2790 .border_color(self.tool_card_border_color(cx))
2791 .child(
2792 h_flex()
2793 .id("tool-label-container")
2794 .gap_1p5()
2795 .max_w_full()
2796 .overflow_x_scroll()
2797 .child(
2798 Icon::new(tool_use.icon)
2799 .size(IconSize::XSmall)
2800 .color(Color::Muted),
2801 )
2802 .child(
2803 h_flex().pr_8().text_ui_sm(cx).children(
2804 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| {
2805 open_markdown_link(text, workspace.clone(), window, cx);
2806 }}))
2807 ),
2808 ),
2809 )
2810 .child(
2811 h_flex()
2812 .gap_1()
2813 .child(
2814 div().visible_on_hover("disclosure-header").child(
2815 Disclosure::new("tool-use-disclosure", is_open)
2816 .opened_icon(IconName::ChevronUp)
2817 .closed_icon(IconName::ChevronDown)
2818 .on_click(cx.listener({
2819 let tool_use_id = tool_use.id.clone();
2820 move |this, _event, _window, _cx| {
2821 let is_open = this
2822 .expanded_tool_uses
2823 .entry(tool_use_id.clone())
2824 .or_insert(false);
2825
2826 *is_open = !*is_open;
2827 }
2828 })),
2829 ),
2830 )
2831 .child(status_icons),
2832 )
2833 .child(gradient_overlay(self.tool_card_header_bg(cx))),
2834 )
2835 .map(|parent| {
2836 if !is_open {
2837 return parent;
2838 }
2839
2840 parent.child(
2841 v_flex()
2842 .bg(cx.theme().colors().editor_background)
2843 .map(|element| {
2844 if needs_confirmation {
2845 element.rounded_none()
2846 } else {
2847 element.rounded_b_lg()
2848 }
2849 })
2850 .child(results_content),
2851 )
2852 })
2853 .when(needs_confirmation, |this| {
2854 this.child(
2855 h_flex()
2856 .py_1()
2857 .pl_2()
2858 .pr_1()
2859 .gap_1()
2860 .justify_between()
2861 .bg(cx.theme().colors().editor_background)
2862 .border_t_1()
2863 .border_color(self.tool_card_border_color(cx))
2864 .rounded_b_lg()
2865 .child(
2866 Label::new("Waiting for Confirmation…")
2867 .color(Color::Muted)
2868 .size(LabelSize::Small)
2869 .with_animation(
2870 "generating-label",
2871 Animation::new(Duration::from_secs(1)).repeat(),
2872 |mut label, delta| {
2873 let text = match delta {
2874 d if d < 0.25 => "Waiting for Confirmation",
2875 d if d < 0.5 => "Waiting for Confirmation.",
2876 d if d < 0.75 => "Waiting for Confirmation..",
2877 _ => "Waiting for Confirmation...",
2878 };
2879 label.set_text(text);
2880 label
2881 },
2882 )
2883 .with_animation(
2884 "pulsating-label",
2885 Animation::new(Duration::from_secs(2))
2886 .repeat()
2887 .with_easing(pulsating_between(0.6, 1.)),
2888 |label, delta| label.map_element(|label| label.alpha(delta)),
2889 ),
2890 )
2891 .child(
2892 h_flex()
2893 .gap_0p5()
2894 .child({
2895 let tool_id = tool_use.id.clone();
2896 Button::new(
2897 "always-allow-tool-action",
2898 "Always Allow",
2899 )
2900 .label_size(LabelSize::Small)
2901 .icon(IconName::CheckDouble)
2902 .icon_position(IconPosition::Start)
2903 .icon_size(IconSize::Small)
2904 .icon_color(Color::Success)
2905 .tooltip(move |window, cx| {
2906 Tooltip::with_meta(
2907 "Never ask for permission",
2908 None,
2909 "Restore the original behavior in your Agent Panel settings",
2910 window,
2911 cx,
2912 )
2913 })
2914 .on_click(cx.listener(
2915 move |this, event, window, cx| {
2916 if let Some(fs) = fs.clone() {
2917 update_settings_file::<AssistantSettings>(
2918 fs.clone(),
2919 cx,
2920 |settings, _| {
2921 settings.set_always_allow_tool_actions(true);
2922 },
2923 );
2924 }
2925 this.handle_allow_tool(
2926 tool_id.clone(),
2927 event,
2928 window,
2929 cx,
2930 )
2931 },
2932 ))
2933 })
2934 .child(ui::Divider::vertical())
2935 .child({
2936 let tool_id = tool_use.id.clone();
2937 Button::new("allow-tool-action", "Allow")
2938 .label_size(LabelSize::Small)
2939 .icon(IconName::Check)
2940 .icon_position(IconPosition::Start)
2941 .icon_size(IconSize::Small)
2942 .icon_color(Color::Success)
2943 .on_click(cx.listener(
2944 move |this, event, window, cx| {
2945 this.handle_allow_tool(
2946 tool_id.clone(),
2947 event,
2948 window,
2949 cx,
2950 )
2951 },
2952 ))
2953 })
2954 .child({
2955 let tool_id = tool_use.id.clone();
2956 let tool_name: Arc<str> = tool_use.name.into();
2957 Button::new("deny-tool", "Deny")
2958 .label_size(LabelSize::Small)
2959 .icon(IconName::Close)
2960 .icon_position(IconPosition::Start)
2961 .icon_size(IconSize::Small)
2962 .icon_color(Color::Error)
2963 .on_click(cx.listener(
2964 move |this, event, window, cx| {
2965 this.handle_deny_tool(
2966 tool_id.clone(),
2967 tool_name.clone(),
2968 event,
2969 window,
2970 cx,
2971 )
2972 },
2973 ))
2974 }),
2975 ),
2976 )
2977 })
2978 }
2979 }).into_any_element()
2980 }
2981
2982 fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
2983 let project_context = self.thread.read(cx).project_context();
2984 let project_context = project_context.borrow();
2985 let Some(project_context) = project_context.as_ref() else {
2986 return div().into_any();
2987 };
2988
2989 let user_rules_text = if project_context.user_rules.is_empty() {
2990 None
2991 } else if project_context.user_rules.len() == 1 {
2992 let user_rules = &project_context.user_rules[0];
2993
2994 match user_rules.title.as_ref() {
2995 Some(title) => Some(format!("Using \"{title}\" user rule")),
2996 None => Some("Using user rule".into()),
2997 }
2998 } else {
2999 Some(format!(
3000 "Using {} user rules",
3001 project_context.user_rules.len()
3002 ))
3003 };
3004
3005 let first_user_rules_id = project_context
3006 .user_rules
3007 .first()
3008 .map(|user_rules| user_rules.uuid.0);
3009
3010 let rules_files = project_context
3011 .worktrees
3012 .iter()
3013 .filter_map(|worktree| worktree.rules_file.as_ref())
3014 .collect::<Vec<_>>();
3015
3016 let rules_file_text = match rules_files.as_slice() {
3017 &[] => None,
3018 &[rules_file] => Some(format!(
3019 "Using project {:?} file",
3020 rules_file.path_in_worktree
3021 )),
3022 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3023 };
3024
3025 if user_rules_text.is_none() && rules_file_text.is_none() {
3026 return div().into_any();
3027 }
3028
3029 v_flex()
3030 .pt_2()
3031 .px_2p5()
3032 .gap_1()
3033 .when_some(user_rules_text, |parent, user_rules_text| {
3034 parent.child(
3035 h_flex()
3036 .w_full()
3037 .child(
3038 Icon::new(RULES_ICON)
3039 .size(IconSize::XSmall)
3040 .color(Color::Disabled),
3041 )
3042 .child(
3043 Label::new(user_rules_text)
3044 .size(LabelSize::XSmall)
3045 .color(Color::Muted)
3046 .truncate()
3047 .buffer_font(cx)
3048 .ml_1p5()
3049 .mr_0p5(),
3050 )
3051 .child(
3052 IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3053 .shape(ui::IconButtonShape::Square)
3054 .icon_size(IconSize::XSmall)
3055 .icon_color(Color::Ignored)
3056 // TODO: Figure out a way to pass focus handle here so we can display the `OpenPromptLibrary` keybinding
3057 .tooltip(Tooltip::text("View User Rules"))
3058 .on_click(move |_event, window, cx| {
3059 window.dispatch_action(
3060 Box::new(OpenPromptLibrary {
3061 prompt_to_select: first_user_rules_id,
3062 }),
3063 cx,
3064 )
3065 }),
3066 ),
3067 )
3068 })
3069 .when_some(rules_file_text, |parent, rules_file_text| {
3070 parent.child(
3071 h_flex()
3072 .w_full()
3073 .child(
3074 Icon::new(IconName::File)
3075 .size(IconSize::XSmall)
3076 .color(Color::Disabled),
3077 )
3078 .child(
3079 Label::new(rules_file_text)
3080 .size(LabelSize::XSmall)
3081 .color(Color::Muted)
3082 .buffer_font(cx)
3083 .ml_1p5()
3084 .mr_0p5(),
3085 )
3086 .child(
3087 IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3088 .shape(ui::IconButtonShape::Square)
3089 .icon_size(IconSize::XSmall)
3090 .icon_color(Color::Ignored)
3091 .on_click(cx.listener(Self::handle_open_rules))
3092 .tooltip(Tooltip::text("View Rules")),
3093 ),
3094 )
3095 })
3096 .into_any()
3097 }
3098
3099 fn handle_allow_tool(
3100 &mut self,
3101 tool_use_id: LanguageModelToolUseId,
3102 _: &ClickEvent,
3103 _window: &mut Window,
3104 cx: &mut Context<Self>,
3105 ) {
3106 if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3107 .thread
3108 .read(cx)
3109 .pending_tool(&tool_use_id)
3110 .map(|tool_use| tool_use.status.clone())
3111 {
3112 self.thread.update(cx, |thread, cx| {
3113 thread.run_tool(
3114 c.tool_use_id.clone(),
3115 c.ui_text.clone(),
3116 c.input.clone(),
3117 &c.messages,
3118 c.tool.clone(),
3119 cx,
3120 );
3121 });
3122 }
3123 }
3124
3125 fn handle_deny_tool(
3126 &mut self,
3127 tool_use_id: LanguageModelToolUseId,
3128 tool_name: Arc<str>,
3129 _: &ClickEvent,
3130 _window: &mut Window,
3131 cx: &mut Context<Self>,
3132 ) {
3133 self.thread.update(cx, |thread, cx| {
3134 thread.deny_tool_use(tool_use_id, tool_name, cx);
3135 });
3136 }
3137
3138 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3139 let project_context = self.thread.read(cx).project_context();
3140 let project_context = project_context.borrow();
3141 let Some(project_context) = project_context.as_ref() else {
3142 return;
3143 };
3144
3145 let abs_paths = project_context
3146 .worktrees
3147 .iter()
3148 .flat_map(|worktree| worktree.rules_file.as_ref())
3149 .map(|rules_file| rules_file.abs_path.to_path_buf())
3150 .collect::<Vec<_>>();
3151
3152 if let Ok(task) = self.workspace.update(cx, move |workspace, cx| {
3153 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3154 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3155 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3156 workspace.open_paths(abs_paths, OpenOptions::default(), None, window, cx)
3157 }) {
3158 task.detach();
3159 }
3160 }
3161
3162 fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3163 for window in self.notifications.drain(..) {
3164 window
3165 .update(cx, |_, window, _| {
3166 window.remove_window();
3167 })
3168 .ok();
3169
3170 self.notification_subscriptions.remove(&window);
3171 }
3172 }
3173
3174 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3175 if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3176 return None;
3177 }
3178
3179 Some(
3180 div()
3181 .occlude()
3182 .id("active-thread-scrollbar")
3183 .on_mouse_move(cx.listener(|_, _, _, cx| {
3184 cx.notify();
3185 cx.stop_propagation()
3186 }))
3187 .on_hover(|_, _, cx| {
3188 cx.stop_propagation();
3189 })
3190 .on_any_mouse_down(|_, _, cx| {
3191 cx.stop_propagation();
3192 })
3193 .on_mouse_up(
3194 MouseButton::Left,
3195 cx.listener(|_, _, _, cx| {
3196 cx.stop_propagation();
3197 }),
3198 )
3199 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3200 cx.notify();
3201 }))
3202 .h_full()
3203 .absolute()
3204 .right_1()
3205 .top_1()
3206 .bottom_0()
3207 .w(px(12.))
3208 .cursor_default()
3209 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3210 )
3211 }
3212
3213 fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3214 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3215 self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3216 cx.background_executor()
3217 .timer(SCROLLBAR_SHOW_INTERVAL)
3218 .await;
3219 thread
3220 .update(cx, |thread, cx| {
3221 if !thread.scrollbar_state.is_dragging() {
3222 thread.show_scrollbar = false;
3223 cx.notify();
3224 }
3225 })
3226 .log_err();
3227 }))
3228 }
3229}
3230
3231pub enum ActiveThreadEvent {
3232 EditingMessageTokenCountChanged,
3233}
3234
3235impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3236
3237impl Render for ActiveThread {
3238 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3239 v_flex()
3240 .size_full()
3241 .relative()
3242 .on_mouse_move(cx.listener(|this, _, _, cx| {
3243 this.show_scrollbar = true;
3244 this.hide_scrollbar_later(cx);
3245 cx.notify();
3246 }))
3247 .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3248 this.show_scrollbar = true;
3249 this.hide_scrollbar_later(cx);
3250 cx.notify();
3251 }))
3252 .on_mouse_up(
3253 MouseButton::Left,
3254 cx.listener(|this, _, _, cx| {
3255 this.hide_scrollbar_later(cx);
3256 }),
3257 )
3258 .child(list(self.list_state.clone()).flex_grow())
3259 .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3260 this.child(scrollbar)
3261 })
3262 }
3263}
3264
3265pub(crate) fn open_context(
3266 id: ContextId,
3267 context_store: Entity<ContextStore>,
3268 workspace: Entity<Workspace>,
3269 window: &mut Window,
3270 cx: &mut App,
3271) {
3272 let Some(context) = context_store.read(cx).context_for_id(id) else {
3273 return;
3274 };
3275
3276 match context {
3277 AssistantContext::File(file_context) => {
3278 if let Some(project_path) = file_context.context_buffer.buffer.read(cx).project_path(cx)
3279 {
3280 workspace.update(cx, |workspace, cx| {
3281 workspace
3282 .open_path(project_path, None, true, window, cx)
3283 .detach_and_log_err(cx);
3284 });
3285 }
3286 }
3287 AssistantContext::Directory(directory_context) => {
3288 let entry_id = directory_context.entry_id;
3289 workspace.update(cx, |workspace, cx| {
3290 workspace.project().update(cx, |_project, cx| {
3291 cx.emit(project::Event::RevealInProjectPanel(entry_id));
3292 })
3293 })
3294 }
3295 AssistantContext::Symbol(symbol_context) => {
3296 if let Some(project_path) = symbol_context
3297 .context_symbol
3298 .buffer
3299 .read(cx)
3300 .project_path(cx)
3301 {
3302 let snapshot = symbol_context.context_symbol.buffer.read(cx).snapshot();
3303 let target_position = symbol_context
3304 .context_symbol
3305 .id
3306 .range
3307 .start
3308 .to_point(&snapshot);
3309
3310 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3311 .detach();
3312 }
3313 }
3314 AssistantContext::Selection(selection_context) => {
3315 if let Some(project_path) = selection_context
3316 .context_buffer
3317 .buffer
3318 .read(cx)
3319 .project_path(cx)
3320 {
3321 let snapshot = selection_context.context_buffer.buffer.read(cx).snapshot();
3322 let target_position = selection_context.range.start.to_point(&snapshot);
3323
3324 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3325 .detach();
3326 }
3327 }
3328 AssistantContext::FetchedUrl(fetched_url_context) => {
3329 cx.open_url(&fetched_url_context.url);
3330 }
3331 AssistantContext::Thread(thread_context) => {
3332 let thread_id = thread_context.thread.read(cx).id().clone();
3333 workspace.update(cx, |workspace, cx| {
3334 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
3335 panel.update(cx, |panel, cx| {
3336 panel
3337 .open_thread(&thread_id, window, cx)
3338 .detach_and_log_err(cx)
3339 });
3340 }
3341 })
3342 }
3343 AssistantContext::Rules(rules_context) => window.dispatch_action(
3344 Box::new(OpenPromptLibrary {
3345 prompt_to_select: Some(rules_context.prompt_id.0),
3346 }),
3347 cx,
3348 ),
3349 AssistantContext::Image(_) => {}
3350 }
3351}
3352
3353fn open_editor_at_position(
3354 project_path: project::ProjectPath,
3355 target_position: Point,
3356 workspace: &Entity<Workspace>,
3357 window: &mut Window,
3358 cx: &mut App,
3359) -> Task<()> {
3360 let open_task = workspace.update(cx, |workspace, cx| {
3361 workspace.open_path(project_path, None, true, window, cx)
3362 });
3363 window.spawn(cx, async move |cx| {
3364 if let Some(active_editor) = open_task
3365 .await
3366 .log_err()
3367 .and_then(|item| item.downcast::<Editor>())
3368 {
3369 active_editor
3370 .downgrade()
3371 .update_in(cx, |editor, window, cx| {
3372 editor.go_to_singleton_buffer_point(target_position, window, cx);
3373 })
3374 .log_err();
3375 }
3376 })
3377}