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