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