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