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