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