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