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_1p5()
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 .pt_1()
1723 .child(EditorElement::new(
1724 &edit_message_editor,
1725 EditorStyle {
1726 background: colors.editor_background,
1727 local_player: cx.theme().players().local(),
1728 text: text_style,
1729 syntax: cx.theme().syntax().clone(),
1730 ..Default::default()
1731 },
1732 ))
1733 .into_any()
1734 } else {
1735 div()
1736 .min_h_6()
1737 .child(self.render_message_content(
1738 message_id,
1739 rendered_message,
1740 has_tool_uses,
1741 workspace.clone(),
1742 window,
1743 cx,
1744 ))
1745 .into_any()
1746 },
1747 )
1748 })
1749 .when(!context.is_empty(), |parent| {
1750 parent.child(h_flex().flex_wrap().gap_1().children(
1751 context.into_iter().map(|context| {
1752 let context_id = context.id();
1753 ContextPill::added(
1754 AddedContext::new(context, cx),
1755 false,
1756 false,
1757 None,
1758 )
1759 .on_click(Rc::new(cx.listener({
1760 let workspace = workspace.clone();
1761 let context_store = context_store.clone();
1762 move |_, _, window, cx| {
1763 if let Some(workspace) = workspace.upgrade() {
1764 open_context(
1765 context_id,
1766 context_store.clone(),
1767 workspace,
1768 window,
1769 cx,
1770 );
1771 cx.notify();
1772 }
1773 }
1774 })))
1775 }),
1776 ))
1777 })
1778 });
1779
1780 let styled_message = match message.role {
1781 Role::User => v_flex()
1782 .id(("message-container", ix))
1783 .map(|this| {
1784 if is_first_message {
1785 this.pt_2()
1786 } else {
1787 this.pt_4()
1788 }
1789 })
1790 .pl_2()
1791 .pr_2p5()
1792 .pb_4()
1793 .child(
1794 v_flex()
1795 .bg(editor_bg_color)
1796 .rounded_lg()
1797 .border_1()
1798 .border_color(colors.border)
1799 .shadow_md()
1800 .child(div().py_2().px_2p5().children(message_content))
1801 .child(
1802 h_flex()
1803 .p_1()
1804 .border_t_1()
1805 .border_color(colors.border_variant)
1806 .justify_end()
1807 .child(
1808 h_flex()
1809 .gap_1()
1810 .when_some(
1811 edit_message_editor.clone(),
1812 |this, edit_message_editor| {
1813 let focus_handle =
1814 edit_message_editor.focus_handle(cx);
1815 this.child(
1816 Button::new("cancel-edit-message", "Cancel")
1817 .label_size(LabelSize::Small)
1818 .key_binding(
1819 KeyBinding::for_action_in(
1820 &menu::Cancel,
1821 &focus_handle,
1822 window,
1823 cx,
1824 )
1825 .map(|kb| kb.size(rems_from_px(12.))),
1826 )
1827 .on_click(
1828 cx.listener(Self::handle_cancel_click),
1829 ),
1830 )
1831 .child(
1832 Button::new(
1833 "confirm-edit-message",
1834 "Regenerate",
1835 )
1836 .disabled(
1837 edit_message_editor.read(cx).is_empty(cx),
1838 )
1839 .label_size(LabelSize::Small)
1840 .key_binding(
1841 KeyBinding::for_action_in(
1842 &menu::Confirm,
1843 &focus_handle,
1844 window,
1845 cx,
1846 )
1847 .map(|kb| kb.size(rems_from_px(12.))),
1848 )
1849 .on_click(
1850 cx.listener(Self::handle_regenerate_click),
1851 ),
1852 )
1853 },
1854 )
1855 .when(
1856 edit_message_editor.is_none() && allow_editing_message,
1857 |this| {
1858 this.child(
1859 Button::new("edit-message", "Edit Message")
1860 .label_size(LabelSize::Small)
1861 .icon(IconName::Pencil)
1862 .icon_size(IconSize::XSmall)
1863 .icon_color(Color::Muted)
1864 .icon_position(IconPosition::Start)
1865 .on_click(cx.listener({
1866 let message_segments =
1867 message.segments.clone();
1868 move |this, _, window, cx| {
1869 this.start_editing_message(
1870 message_id,
1871 &message_segments,
1872 window,
1873 cx,
1874 );
1875 }
1876 })),
1877 )
1878 },
1879 ),
1880 ),
1881 ),
1882 ),
1883 Role::Assistant => v_flex()
1884 .id(("message-container", ix))
1885 .px(RESPONSE_PADDING_X)
1886 .gap_2()
1887 .children(message_content)
1888 .when(has_tool_uses, |parent| {
1889 parent.children(
1890 tool_uses
1891 .into_iter()
1892 .map(|tool_use| self.render_tool_use(tool_use, window, cx)),
1893 )
1894 }),
1895 Role::System => div().id(("message-container", ix)).py_1().px_2().child(
1896 v_flex()
1897 .bg(colors.editor_background)
1898 .rounded_sm()
1899 .child(div().p_4().children(message_content)),
1900 ),
1901 };
1902
1903 let after_editing_message = self
1904 .editing_message
1905 .as_ref()
1906 .map_or(false, |(editing_message_id, _)| {
1907 message_id > *editing_message_id
1908 });
1909
1910 let panel_background = cx.theme().colors().panel_background;
1911
1912 v_flex()
1913 .w_full()
1914 .when_some(checkpoint, |parent, checkpoint| {
1915 let mut is_pending = false;
1916 let mut error = None;
1917 if let Some(last_restore_checkpoint) =
1918 self.thread.read(cx).last_restore_checkpoint()
1919 {
1920 if last_restore_checkpoint.message_id() == message_id {
1921 match last_restore_checkpoint {
1922 LastRestoreCheckpoint::Pending { .. } => is_pending = true,
1923 LastRestoreCheckpoint::Error { error: err, .. } => {
1924 error = Some(err.clone());
1925 }
1926 }
1927 }
1928 }
1929
1930 let restore_checkpoint_button =
1931 Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
1932 .icon(if error.is_some() {
1933 IconName::XCircle
1934 } else {
1935 IconName::Undo
1936 })
1937 .icon_size(IconSize::XSmall)
1938 .icon_position(IconPosition::Start)
1939 .icon_color(if error.is_some() {
1940 Some(Color::Error)
1941 } else {
1942 None
1943 })
1944 .label_size(LabelSize::XSmall)
1945 .disabled(is_pending)
1946 .on_click(cx.listener(move |this, _, _window, cx| {
1947 this.thread.update(cx, |thread, cx| {
1948 thread
1949 .restore_checkpoint(checkpoint.clone(), cx)
1950 .detach_and_log_err(cx);
1951 });
1952 }));
1953
1954 let restore_checkpoint_button = if is_pending {
1955 restore_checkpoint_button
1956 .with_animation(
1957 ("pulsating-restore-checkpoint-button", ix),
1958 Animation::new(Duration::from_secs(2))
1959 .repeat()
1960 .with_easing(pulsating_between(0.6, 1.)),
1961 |label, delta| label.alpha(delta),
1962 )
1963 .into_any_element()
1964 } else if let Some(error) = error {
1965 restore_checkpoint_button
1966 .tooltip(Tooltip::text(error.to_string()))
1967 .into_any_element()
1968 } else {
1969 restore_checkpoint_button.into_any_element()
1970 };
1971
1972 parent.child(
1973 h_flex()
1974 .pt_2p5()
1975 .px_2p5()
1976 .w_full()
1977 .gap_1()
1978 .child(ui::Divider::horizontal())
1979 .child(restore_checkpoint_button)
1980 .child(ui::Divider::horizontal()),
1981 )
1982 })
1983 .when(is_first_message, |parent| {
1984 parent.child(self.render_rules_item(cx))
1985 })
1986 .child(styled_message)
1987 .when(!needs_confirmation && generating_label.is_some(), |this| {
1988 this.child(
1989 h_flex()
1990 .h_8()
1991 .mt_2()
1992 .mb_4()
1993 .ml_4()
1994 .py_1p5()
1995 .child(generating_label.unwrap()),
1996 )
1997 })
1998 .when(show_feedback, move |parent| {
1999 parent.child(feedback_items).when_some(
2000 self.open_feedback_editors.get(&message_id),
2001 move |parent, feedback_editor| {
2002 let focus_handle = feedback_editor.focus_handle(cx);
2003 parent.child(
2004 v_flex()
2005 .key_context("AgentFeedbackMessageEditor")
2006 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
2007 this.open_feedback_editors.remove(&message_id);
2008 cx.notify();
2009 }))
2010 .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
2011 this.submit_feedback_message(message_id, cx);
2012 cx.notify();
2013 }))
2014 .on_action(cx.listener(Self::confirm_editing_message))
2015 .mb_2()
2016 .mx_4()
2017 .p_2()
2018 .rounded_md()
2019 .border_1()
2020 .border_color(cx.theme().colors().border)
2021 .bg(cx.theme().colors().editor_background)
2022 .child(feedback_editor.clone())
2023 .child(
2024 h_flex()
2025 .gap_1()
2026 .justify_end()
2027 .child(
2028 Button::new("dismiss-feedback-message", "Cancel")
2029 .label_size(LabelSize::Small)
2030 .key_binding(
2031 KeyBinding::for_action_in(
2032 &menu::Cancel,
2033 &focus_handle,
2034 window,
2035 cx,
2036 )
2037 .map(|kb| kb.size(rems_from_px(10.))),
2038 )
2039 .on_click(cx.listener(
2040 move |this, _, _window, cx| {
2041 this.open_feedback_editors
2042 .remove(&message_id);
2043 cx.notify();
2044 },
2045 )),
2046 )
2047 .child(
2048 Button::new(
2049 "submit-feedback-message",
2050 "Share Feedback",
2051 )
2052 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2053 .label_size(LabelSize::Small)
2054 .key_binding(
2055 KeyBinding::for_action_in(
2056 &menu::Confirm,
2057 &focus_handle,
2058 window,
2059 cx,
2060 )
2061 .map(|kb| kb.size(rems_from_px(10.))),
2062 )
2063 .on_click(
2064 cx.listener(move |this, _, _window, cx| {
2065 this.submit_feedback_message(message_id, cx);
2066 cx.notify()
2067 }),
2068 ),
2069 ),
2070 ),
2071 )
2072 },
2073 )
2074 })
2075 .when(after_editing_message, |parent| {
2076 // Backdrop to dim out the whole thread below the editing user message
2077 parent.relative().child(
2078 div()
2079 .occlude()
2080 .absolute()
2081 .inset_0()
2082 .size_full()
2083 .bg(panel_background)
2084 .opacity(0.8),
2085 )
2086 })
2087 .into_any()
2088 }
2089
2090 fn render_message_content(
2091 &self,
2092 message_id: MessageId,
2093 rendered_message: &RenderedMessage,
2094 has_tool_uses: bool,
2095 workspace: WeakEntity<Workspace>,
2096 window: &Window,
2097 cx: &Context<Self>,
2098 ) -> impl IntoElement {
2099 let is_last_message = self.messages.last() == Some(&message_id);
2100 let is_generating = self.thread.read(cx).is_generating();
2101 let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2102 rendered_message
2103 .segments
2104 .iter()
2105 .enumerate()
2106 .next_back()
2107 .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2108 .map(|(index, _)| index)
2109 } else {
2110 None
2111 };
2112
2113 let message_role = self
2114 .thread
2115 .read(cx)
2116 .message(message_id)
2117 .map(|m| m.role)
2118 .unwrap_or(Role::User);
2119
2120 let is_assistant_message = message_role == Role::Assistant;
2121 let is_user_message = message_role == Role::User;
2122
2123 v_flex()
2124 .text_ui(cx)
2125 .gap_2()
2126 .when(is_user_message, |this| this.text_xs())
2127 .children(
2128 rendered_message.segments.iter().enumerate().map(
2129 |(index, segment)| match segment {
2130 RenderedMessageSegment::Thinking {
2131 content,
2132 scroll_handle,
2133 } => self
2134 .render_message_thinking_segment(
2135 message_id,
2136 index,
2137 content.clone(),
2138 &scroll_handle,
2139 Some(index) == pending_thinking_segment_index,
2140 window,
2141 cx,
2142 )
2143 .into_any_element(),
2144 RenderedMessageSegment::Text(markdown) => {
2145 let markdown_element = MarkdownElement::new(
2146 markdown.clone(),
2147 if is_user_message {
2148 let mut style = default_markdown_style(window, cx);
2149 let mut text_style = window.text_style();
2150 let theme_settings = ThemeSettings::get_global(cx);
2151
2152 let buffer_font = theme_settings.buffer_font.family.clone();
2153 let buffer_font_size = TextSize::Small.rems(cx);
2154
2155 text_style.refine(&TextStyleRefinement {
2156 font_family: Some(buffer_font),
2157 font_size: Some(buffer_font_size.into()),
2158 ..Default::default()
2159 });
2160
2161 style.base_text_style = text_style;
2162 style
2163 } else {
2164 default_markdown_style(window, cx)
2165 },
2166 );
2167
2168 let markdown_element = if is_assistant_message {
2169 markdown_element.code_block_renderer(
2170 markdown::CodeBlockRenderer::Custom {
2171 render: Arc::new({
2172 let workspace = workspace.clone();
2173 let active_thread = cx.entity();
2174 move |kind,
2175 parsed_markdown,
2176 range,
2177 metadata,
2178 window,
2179 cx| {
2180 render_markdown_code_block(
2181 message_id,
2182 range.start,
2183 kind,
2184 parsed_markdown,
2185 metadata,
2186 active_thread.clone(),
2187 workspace.clone(),
2188 window,
2189 cx,
2190 )
2191 }
2192 }),
2193 transform: Some(Arc::new({
2194 let active_thread = cx.entity();
2195 move |el, range, metadata, _, cx| {
2196 let is_expanded = active_thread
2197 .read(cx)
2198 .expanded_code_blocks
2199 .get(&(message_id, range.start))
2200 .copied()
2201 .unwrap_or(false);
2202
2203 if is_expanded
2204 || metadata.line_count
2205 <= MAX_UNCOLLAPSED_LINES_IN_CODE_BLOCK
2206 {
2207 return el;
2208 }
2209 el.child(
2210 div()
2211 .absolute()
2212 .bottom_0()
2213 .left_0()
2214 .w_full()
2215 .h_1_4()
2216 .rounded_b_lg()
2217 .bg(gpui::linear_gradient(
2218 0.,
2219 gpui::linear_color_stop(
2220 cx.theme()
2221 .colors()
2222 .editor_background,
2223 0.,
2224 ),
2225 gpui::linear_color_stop(
2226 cx.theme()
2227 .colors()
2228 .editor_background
2229 .opacity(0.),
2230 1.,
2231 ),
2232 )),
2233 )
2234 }
2235 })),
2236 },
2237 )
2238 } else {
2239 markdown_element.code_block_renderer(
2240 markdown::CodeBlockRenderer::Default {
2241 copy_button: false,
2242 border: true,
2243 },
2244 )
2245 };
2246
2247 div()
2248 .child(markdown_element.on_url_click({
2249 let workspace = self.workspace.clone();
2250 move |text, window, cx| {
2251 open_markdown_link(text, workspace.clone(), window, cx);
2252 }
2253 }))
2254 .into_any_element()
2255 }
2256 },
2257 ),
2258 )
2259 }
2260
2261 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2262 cx.theme().colors().border.opacity(0.5)
2263 }
2264
2265 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2266 cx.theme()
2267 .colors()
2268 .element_background
2269 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2270 }
2271
2272 fn render_message_thinking_segment(
2273 &self,
2274 message_id: MessageId,
2275 ix: usize,
2276 markdown: Entity<Markdown>,
2277 scroll_handle: &ScrollHandle,
2278 pending: bool,
2279 window: &Window,
2280 cx: &Context<Self>,
2281 ) -> impl IntoElement {
2282 let is_open = self
2283 .expanded_thinking_segments
2284 .get(&(message_id, ix))
2285 .copied()
2286 .unwrap_or_default();
2287
2288 let editor_bg = cx.theme().colors().panel_background;
2289
2290 div().map(|this| {
2291 if pending {
2292 this.v_flex()
2293 .mt_neg_2()
2294 .mb_1p5()
2295 .child(
2296 h_flex()
2297 .group("disclosure-header")
2298 .justify_between()
2299 .child(
2300 h_flex()
2301 .gap_1p5()
2302 .child(
2303 Icon::new(IconName::LightBulb)
2304 .size(IconSize::XSmall)
2305 .color(Color::Muted),
2306 )
2307 .child({
2308 Label::new("Thinking")
2309 .color(Color::Muted)
2310 .size(LabelSize::Small)
2311 .with_animation(
2312 "generating-label",
2313 Animation::new(Duration::from_secs(1)).repeat(),
2314 |mut label, delta| {
2315 let text = match delta {
2316 d if d < 0.25 => "Thinking",
2317 d if d < 0.5 => "Thinking.",
2318 d if d < 0.75 => "Thinking..",
2319 _ => "Thinking...",
2320 };
2321 label.set_text(text);
2322 label
2323 },
2324 )
2325 .with_animation(
2326 "pulsating-label",
2327 Animation::new(Duration::from_secs(2))
2328 .repeat()
2329 .with_easing(pulsating_between(0.6, 1.)),
2330 |label, delta| {
2331 label.map_element(|label| label.alpha(delta))
2332 },
2333 )
2334 }),
2335 )
2336 .child(
2337 h_flex()
2338 .gap_1()
2339 .child(
2340 div().visible_on_hover("disclosure-header").child(
2341 Disclosure::new("thinking-disclosure", is_open)
2342 .opened_icon(IconName::ChevronUp)
2343 .closed_icon(IconName::ChevronDown)
2344 .on_click(cx.listener({
2345 move |this, _event, _window, _cx| {
2346 let is_open = this
2347 .expanded_thinking_segments
2348 .entry((message_id, ix))
2349 .or_insert(false);
2350
2351 *is_open = !*is_open;
2352 }
2353 })),
2354 ),
2355 )
2356 .child({
2357 Icon::new(IconName::ArrowCircle)
2358 .color(Color::Accent)
2359 .size(IconSize::Small)
2360 .with_animation(
2361 "arrow-circle",
2362 Animation::new(Duration::from_secs(2)).repeat(),
2363 |icon, delta| {
2364 icon.transform(Transformation::rotate(
2365 percentage(delta),
2366 ))
2367 },
2368 )
2369 }),
2370 ),
2371 )
2372 .when(!is_open, |this| {
2373 let gradient_overlay = div()
2374 .rounded_b_lg()
2375 .h_full()
2376 .absolute()
2377 .w_full()
2378 .bottom_0()
2379 .left_0()
2380 .bg(linear_gradient(
2381 180.,
2382 linear_color_stop(editor_bg, 1.),
2383 linear_color_stop(editor_bg.opacity(0.2), 0.),
2384 ));
2385
2386 this.child(
2387 div()
2388 .relative()
2389 .bg(editor_bg)
2390 .rounded_b_lg()
2391 .mt_2()
2392 .pl_4()
2393 .child(
2394 div()
2395 .id(("thinking-content", ix))
2396 .max_h_20()
2397 .track_scroll(scroll_handle)
2398 .text_ui_sm(cx)
2399 .overflow_hidden()
2400 .child(
2401 MarkdownElement::new(
2402 markdown.clone(),
2403 default_markdown_style(window, cx),
2404 )
2405 .on_url_click({
2406 let workspace = self.workspace.clone();
2407 move |text, window, cx| {
2408 open_markdown_link(
2409 text,
2410 workspace.clone(),
2411 window,
2412 cx,
2413 );
2414 }
2415 }),
2416 ),
2417 )
2418 .child(gradient_overlay),
2419 )
2420 })
2421 .when(is_open, |this| {
2422 this.child(
2423 div()
2424 .id(("thinking-content", ix))
2425 .h_full()
2426 .bg(editor_bg)
2427 .text_ui_sm(cx)
2428 .child(
2429 MarkdownElement::new(
2430 markdown.clone(),
2431 default_markdown_style(window, cx),
2432 )
2433 .on_url_click({
2434 let workspace = self.workspace.clone();
2435 move |text, window, cx| {
2436 open_markdown_link(text, workspace.clone(), window, cx);
2437 }
2438 }),
2439 ),
2440 )
2441 })
2442 } else {
2443 this.v_flex()
2444 .mt_neg_2()
2445 .child(
2446 h_flex()
2447 .group("disclosure-header")
2448 .pr_1()
2449 .justify_between()
2450 .opacity(0.8)
2451 .hover(|style| style.opacity(1.))
2452 .child(
2453 h_flex()
2454 .gap_1p5()
2455 .child(
2456 Icon::new(IconName::LightBulb)
2457 .size(IconSize::XSmall)
2458 .color(Color::Muted),
2459 )
2460 .child(Label::new("Thought Process").size(LabelSize::Small)),
2461 )
2462 .child(
2463 div().visible_on_hover("disclosure-header").child(
2464 Disclosure::new("thinking-disclosure", is_open)
2465 .opened_icon(IconName::ChevronUp)
2466 .closed_icon(IconName::ChevronDown)
2467 .on_click(cx.listener({
2468 move |this, _event, _window, _cx| {
2469 let is_open = this
2470 .expanded_thinking_segments
2471 .entry((message_id, ix))
2472 .or_insert(false);
2473
2474 *is_open = !*is_open;
2475 }
2476 })),
2477 ),
2478 ),
2479 )
2480 .child(
2481 div()
2482 .id(("thinking-content", ix))
2483 .relative()
2484 .mt_1p5()
2485 .ml_1p5()
2486 .pl_2p5()
2487 .border_l_1()
2488 .border_color(cx.theme().colors().border_variant)
2489 .text_ui_sm(cx)
2490 .when(is_open, |this| {
2491 this.child(
2492 MarkdownElement::new(
2493 markdown.clone(),
2494 default_markdown_style(window, cx),
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 }
2506 })
2507 }
2508
2509 fn render_tool_use(
2510 &self,
2511 tool_use: ToolUse,
2512 window: &mut Window,
2513 cx: &mut Context<Self>,
2514 ) -> impl IntoElement + use<> {
2515 if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2516 return card.render(&tool_use.status, window, cx);
2517 }
2518
2519 let is_open = self
2520 .expanded_tool_uses
2521 .get(&tool_use.id)
2522 .copied()
2523 .unwrap_or_default();
2524
2525 let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2526
2527 let fs = self
2528 .workspace
2529 .upgrade()
2530 .map(|workspace| workspace.read(cx).app_state().fs.clone());
2531 let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2532 let edit_tools = tool_use.needs_confirmation;
2533
2534 let status_icons = div().child(match &tool_use.status {
2535 ToolUseStatus::NeedsConfirmation => {
2536 let icon = Icon::new(IconName::Warning)
2537 .color(Color::Warning)
2538 .size(IconSize::Small);
2539 icon.into_any_element()
2540 }
2541 ToolUseStatus::Pending
2542 | ToolUseStatus::InputStillStreaming
2543 | ToolUseStatus::Running => {
2544 let icon = Icon::new(IconName::ArrowCircle)
2545 .color(Color::Accent)
2546 .size(IconSize::Small);
2547 icon.with_animation(
2548 "arrow-circle",
2549 Animation::new(Duration::from_secs(2)).repeat(),
2550 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2551 )
2552 .into_any_element()
2553 }
2554 ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2555 ToolUseStatus::Error(_) => {
2556 let icon = Icon::new(IconName::Close)
2557 .color(Color::Error)
2558 .size(IconSize::Small);
2559 icon.into_any_element()
2560 }
2561 });
2562
2563 let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2564 let results_content_container = || v_flex().p_2().gap_0p5();
2565
2566 let results_content = v_flex()
2567 .gap_1()
2568 .child(
2569 results_content_container()
2570 .child(
2571 Label::new("Input")
2572 .size(LabelSize::XSmall)
2573 .color(Color::Muted)
2574 .buffer_font(cx),
2575 )
2576 .child(
2577 div()
2578 .w_full()
2579 .text_ui_sm(cx)
2580 .children(rendered_tool_use.as_ref().map(|rendered| {
2581 MarkdownElement::new(
2582 rendered.input.clone(),
2583 tool_use_markdown_style(window, cx),
2584 )
2585 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2586 copy_button: false,
2587 border: false,
2588 })
2589 .on_url_click({
2590 let workspace = self.workspace.clone();
2591 move |text, window, cx| {
2592 open_markdown_link(text, workspace.clone(), window, cx);
2593 }
2594 })
2595 })),
2596 ),
2597 )
2598 .map(|container| match tool_use.status {
2599 ToolUseStatus::Finished(_) => container.child(
2600 results_content_container()
2601 .border_t_1()
2602 .border_color(self.tool_card_border_color(cx))
2603 .child(
2604 Label::new("Result")
2605 .size(LabelSize::XSmall)
2606 .color(Color::Muted)
2607 .buffer_font(cx),
2608 )
2609 .child(div().w_full().text_ui_sm(cx).children(
2610 rendered_tool_use.as_ref().map(|rendered| {
2611 MarkdownElement::new(
2612 rendered.output.clone(),
2613 tool_use_markdown_style(window, cx),
2614 )
2615 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2616 copy_button: false,
2617 border: false,
2618 })
2619 .on_url_click({
2620 let workspace = self.workspace.clone();
2621 move |text, window, cx| {
2622 open_markdown_link(text, workspace.clone(), window, cx);
2623 }
2624 })
2625 .into_any_element()
2626 }),
2627 )),
2628 ),
2629 ToolUseStatus::InputStillStreaming | ToolUseStatus::Running => container.child(
2630 results_content_container().child(
2631 h_flex()
2632 .gap_1()
2633 .pb_1()
2634 .border_t_1()
2635 .border_color(self.tool_card_border_color(cx))
2636 .child(
2637 Icon::new(IconName::ArrowCircle)
2638 .size(IconSize::Small)
2639 .color(Color::Accent)
2640 .with_animation(
2641 "arrow-circle",
2642 Animation::new(Duration::from_secs(2)).repeat(),
2643 |icon, delta| {
2644 icon.transform(Transformation::rotate(percentage(
2645 delta,
2646 )))
2647 },
2648 ),
2649 )
2650 .child(
2651 Label::new("Running…")
2652 .size(LabelSize::XSmall)
2653 .color(Color::Muted)
2654 .buffer_font(cx),
2655 ),
2656 ),
2657 ),
2658 ToolUseStatus::Error(_) => container.child(
2659 results_content_container()
2660 .border_t_1()
2661 .border_color(self.tool_card_border_color(cx))
2662 .child(
2663 Label::new("Error")
2664 .size(LabelSize::XSmall)
2665 .color(Color::Muted)
2666 .buffer_font(cx),
2667 )
2668 .child(
2669 div()
2670 .text_ui_sm(cx)
2671 .children(rendered_tool_use.as_ref().map(|rendered| {
2672 MarkdownElement::new(
2673 rendered.output.clone(),
2674 tool_use_markdown_style(window, cx),
2675 )
2676 .on_url_click({
2677 let workspace = self.workspace.clone();
2678 move |text, window, cx| {
2679 open_markdown_link(text, workspace.clone(), window, cx);
2680 }
2681 })
2682 .into_any_element()
2683 })),
2684 ),
2685 ),
2686 ToolUseStatus::Pending => container,
2687 ToolUseStatus::NeedsConfirmation => container.child(
2688 results_content_container()
2689 .border_t_1()
2690 .border_color(self.tool_card_border_color(cx))
2691 .child(
2692 Label::new("Asking Permission")
2693 .size(LabelSize::Small)
2694 .color(Color::Muted)
2695 .buffer_font(cx),
2696 ),
2697 ),
2698 });
2699
2700 let gradient_overlay = |color: Hsla| {
2701 div()
2702 .h_full()
2703 .absolute()
2704 .w_12()
2705 .bottom_0()
2706 .map(|element| {
2707 if is_status_finished {
2708 element.right_6()
2709 } else {
2710 element.right(px(44.))
2711 }
2712 })
2713 .bg(linear_gradient(
2714 90.,
2715 linear_color_stop(color, 1.),
2716 linear_color_stop(color.opacity(0.2), 0.),
2717 ))
2718 };
2719
2720 v_flex().gap_1().mb_3().map(|element| {
2721 if !edit_tools {
2722 element.child(
2723 v_flex()
2724 .child(
2725 h_flex()
2726 .group("disclosure-header")
2727 .relative()
2728 .gap_1p5()
2729 .justify_between()
2730 .opacity(0.8)
2731 .hover(|style| style.opacity(1.))
2732 .when(!is_status_finished, |this| this.pr_2())
2733 .child(
2734 h_flex()
2735 .id("tool-label-container")
2736 .gap_1p5()
2737 .max_w_full()
2738 .overflow_x_scroll()
2739 .child(
2740 Icon::new(tool_use.icon)
2741 .size(IconSize::XSmall)
2742 .color(Color::Muted),
2743 )
2744 .child(
2745 h_flex().pr_8().text_size(rems(0.8125)).children(
2746 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| {
2747 open_markdown_link(text, workspace.clone(), window, cx);
2748 }}))
2749 ),
2750 ),
2751 )
2752 .child(
2753 h_flex()
2754 .gap_1()
2755 .child(
2756 div().visible_on_hover("disclosure-header").child(
2757 Disclosure::new("tool-use-disclosure", is_open)
2758 .opened_icon(IconName::ChevronUp)
2759 .closed_icon(IconName::ChevronDown)
2760 .on_click(cx.listener({
2761 let tool_use_id = tool_use.id.clone();
2762 move |this, _event, _window, _cx| {
2763 let is_open = this
2764 .expanded_tool_uses
2765 .entry(tool_use_id.clone())
2766 .or_insert(false);
2767
2768 *is_open = !*is_open;
2769 }
2770 })),
2771 ),
2772 )
2773 .child(status_icons),
2774 )
2775 .child(gradient_overlay(cx.theme().colors().panel_background)),
2776 )
2777 .map(|parent| {
2778 if !is_open {
2779 return parent;
2780 }
2781
2782 parent.child(
2783 v_flex()
2784 .mt_1()
2785 .border_1()
2786 .border_color(self.tool_card_border_color(cx))
2787 .bg(cx.theme().colors().editor_background)
2788 .rounded_lg()
2789 .child(results_content),
2790 )
2791 }),
2792 )
2793 } else {
2794 v_flex()
2795 .mb_2()
2796 .rounded_lg()
2797 .border_1()
2798 .border_color(self.tool_card_border_color(cx))
2799 .overflow_hidden()
2800 .child(
2801 h_flex()
2802 .group("disclosure-header")
2803 .relative()
2804 .justify_between()
2805 .py_1()
2806 .map(|element| {
2807 if is_status_finished {
2808 element.pl_2().pr_0p5()
2809 } else {
2810 element.px_2()
2811 }
2812 })
2813 .bg(self.tool_card_header_bg(cx))
2814 .map(|element| {
2815 if is_open {
2816 element.border_b_1().rounded_t_md()
2817 } else if needs_confirmation {
2818 element.rounded_t_md()
2819 } else {
2820 element.rounded_md()
2821 }
2822 })
2823 .border_color(self.tool_card_border_color(cx))
2824 .child(
2825 h_flex()
2826 .id("tool-label-container")
2827 .gap_1p5()
2828 .max_w_full()
2829 .overflow_x_scroll()
2830 .child(
2831 Icon::new(tool_use.icon)
2832 .size(IconSize::XSmall)
2833 .color(Color::Muted),
2834 )
2835 .child(
2836 h_flex().pr_8().text_ui_sm(cx).children(
2837 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| {
2838 open_markdown_link(text, workspace.clone(), window, cx);
2839 }}))
2840 ),
2841 ),
2842 )
2843 .child(
2844 h_flex()
2845 .gap_1()
2846 .child(
2847 div().visible_on_hover("disclosure-header").child(
2848 Disclosure::new("tool-use-disclosure", is_open)
2849 .opened_icon(IconName::ChevronUp)
2850 .closed_icon(IconName::ChevronDown)
2851 .on_click(cx.listener({
2852 let tool_use_id = tool_use.id.clone();
2853 move |this, _event, _window, _cx| {
2854 let is_open = this
2855 .expanded_tool_uses
2856 .entry(tool_use_id.clone())
2857 .or_insert(false);
2858
2859 *is_open = !*is_open;
2860 }
2861 })),
2862 ),
2863 )
2864 .child(status_icons),
2865 )
2866 .child(gradient_overlay(self.tool_card_header_bg(cx))),
2867 )
2868 .map(|parent| {
2869 if !is_open {
2870 return parent;
2871 }
2872
2873 parent.child(
2874 v_flex()
2875 .bg(cx.theme().colors().editor_background)
2876 .map(|element| {
2877 if needs_confirmation {
2878 element.rounded_none()
2879 } else {
2880 element.rounded_b_lg()
2881 }
2882 })
2883 .child(results_content),
2884 )
2885 })
2886 .when(needs_confirmation, |this| {
2887 this.child(
2888 h_flex()
2889 .py_1()
2890 .pl_2()
2891 .pr_1()
2892 .gap_1()
2893 .justify_between()
2894 .bg(cx.theme().colors().editor_background)
2895 .border_t_1()
2896 .border_color(self.tool_card_border_color(cx))
2897 .rounded_b_lg()
2898 .child(
2899 Label::new("Waiting for Confirmation…")
2900 .color(Color::Muted)
2901 .size(LabelSize::Small)
2902 .with_animation(
2903 "generating-label",
2904 Animation::new(Duration::from_secs(1)).repeat(),
2905 |mut label, delta| {
2906 let text = match delta {
2907 d if d < 0.25 => "Waiting for Confirmation",
2908 d if d < 0.5 => "Waiting for Confirmation.",
2909 d if d < 0.75 => "Waiting for Confirmation..",
2910 _ => "Waiting for Confirmation...",
2911 };
2912 label.set_text(text);
2913 label
2914 },
2915 )
2916 .with_animation(
2917 "pulsating-label",
2918 Animation::new(Duration::from_secs(2))
2919 .repeat()
2920 .with_easing(pulsating_between(0.6, 1.)),
2921 |label, delta| label.map_element(|label| label.alpha(delta)),
2922 ),
2923 )
2924 .child(
2925 h_flex()
2926 .gap_0p5()
2927 .child({
2928 let tool_id = tool_use.id.clone();
2929 Button::new(
2930 "always-allow-tool-action",
2931 "Always Allow",
2932 )
2933 .label_size(LabelSize::Small)
2934 .icon(IconName::CheckDouble)
2935 .icon_position(IconPosition::Start)
2936 .icon_size(IconSize::Small)
2937 .icon_color(Color::Success)
2938 .tooltip(move |window, cx| {
2939 Tooltip::with_meta(
2940 "Never ask for permission",
2941 None,
2942 "Restore the original behavior in your Agent Panel settings",
2943 window,
2944 cx,
2945 )
2946 })
2947 .on_click(cx.listener(
2948 move |this, event, window, cx| {
2949 if let Some(fs) = fs.clone() {
2950 update_settings_file::<AssistantSettings>(
2951 fs.clone(),
2952 cx,
2953 |settings, _| {
2954 settings.set_always_allow_tool_actions(true);
2955 },
2956 );
2957 }
2958 this.handle_allow_tool(
2959 tool_id.clone(),
2960 event,
2961 window,
2962 cx,
2963 )
2964 },
2965 ))
2966 })
2967 .child(ui::Divider::vertical())
2968 .child({
2969 let tool_id = tool_use.id.clone();
2970 Button::new("allow-tool-action", "Allow")
2971 .label_size(LabelSize::Small)
2972 .icon(IconName::Check)
2973 .icon_position(IconPosition::Start)
2974 .icon_size(IconSize::Small)
2975 .icon_color(Color::Success)
2976 .on_click(cx.listener(
2977 move |this, event, window, cx| {
2978 this.handle_allow_tool(
2979 tool_id.clone(),
2980 event,
2981 window,
2982 cx,
2983 )
2984 },
2985 ))
2986 })
2987 .child({
2988 let tool_id = tool_use.id.clone();
2989 let tool_name: Arc<str> = tool_use.name.into();
2990 Button::new("deny-tool", "Deny")
2991 .label_size(LabelSize::Small)
2992 .icon(IconName::Close)
2993 .icon_position(IconPosition::Start)
2994 .icon_size(IconSize::Small)
2995 .icon_color(Color::Error)
2996 .on_click(cx.listener(
2997 move |this, event, window, cx| {
2998 this.handle_deny_tool(
2999 tool_id.clone(),
3000 tool_name.clone(),
3001 event,
3002 window,
3003 cx,
3004 )
3005 },
3006 ))
3007 }),
3008 ),
3009 )
3010 })
3011 }
3012 }).into_any_element()
3013 }
3014
3015 fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
3016 let project_context = self.thread.read(cx).project_context();
3017 let project_context = project_context.borrow();
3018 let Some(project_context) = project_context.as_ref() else {
3019 return div().into_any();
3020 };
3021
3022 let user_rules_text = if project_context.user_rules.is_empty() {
3023 None
3024 } else if project_context.user_rules.len() == 1 {
3025 let user_rules = &project_context.user_rules[0];
3026
3027 match user_rules.title.as_ref() {
3028 Some(title) => Some(format!("Using \"{title}\" user rule")),
3029 None => Some("Using user rule".into()),
3030 }
3031 } else {
3032 Some(format!(
3033 "Using {} user rules",
3034 project_context.user_rules.len()
3035 ))
3036 };
3037
3038 let first_user_rules_id = project_context
3039 .user_rules
3040 .first()
3041 .map(|user_rules| user_rules.uuid.0);
3042
3043 let rules_files = project_context
3044 .worktrees
3045 .iter()
3046 .filter_map(|worktree| worktree.rules_file.as_ref())
3047 .collect::<Vec<_>>();
3048
3049 let rules_file_text = match rules_files.as_slice() {
3050 &[] => None,
3051 &[rules_file] => Some(format!(
3052 "Using project {:?} file",
3053 rules_file.path_in_worktree
3054 )),
3055 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3056 };
3057
3058 if user_rules_text.is_none() && rules_file_text.is_none() {
3059 return div().into_any();
3060 }
3061
3062 v_flex()
3063 .pt_2()
3064 .px_2p5()
3065 .gap_1()
3066 .when_some(user_rules_text, |parent, user_rules_text| {
3067 parent.child(
3068 h_flex()
3069 .w_full()
3070 .child(
3071 Icon::new(RULES_ICON)
3072 .size(IconSize::XSmall)
3073 .color(Color::Disabled),
3074 )
3075 .child(
3076 Label::new(user_rules_text)
3077 .size(LabelSize::XSmall)
3078 .color(Color::Muted)
3079 .truncate()
3080 .buffer_font(cx)
3081 .ml_1p5()
3082 .mr_0p5(),
3083 )
3084 .child(
3085 IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3086 .shape(ui::IconButtonShape::Square)
3087 .icon_size(IconSize::XSmall)
3088 .icon_color(Color::Ignored)
3089 // TODO: Figure out a way to pass focus handle here so we can display the `OpenPromptLibrary` keybinding
3090 .tooltip(Tooltip::text("View User Rules"))
3091 .on_click(move |_event, window, cx| {
3092 window.dispatch_action(
3093 Box::new(OpenPromptLibrary {
3094 prompt_to_select: first_user_rules_id,
3095 }),
3096 cx,
3097 )
3098 }),
3099 ),
3100 )
3101 })
3102 .when_some(rules_file_text, |parent, rules_file_text| {
3103 parent.child(
3104 h_flex()
3105 .w_full()
3106 .child(
3107 Icon::new(IconName::File)
3108 .size(IconSize::XSmall)
3109 .color(Color::Disabled),
3110 )
3111 .child(
3112 Label::new(rules_file_text)
3113 .size(LabelSize::XSmall)
3114 .color(Color::Muted)
3115 .buffer_font(cx)
3116 .ml_1p5()
3117 .mr_0p5(),
3118 )
3119 .child(
3120 IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3121 .shape(ui::IconButtonShape::Square)
3122 .icon_size(IconSize::XSmall)
3123 .icon_color(Color::Ignored)
3124 .on_click(cx.listener(Self::handle_open_rules))
3125 .tooltip(Tooltip::text("View Rules")),
3126 ),
3127 )
3128 })
3129 .into_any()
3130 }
3131
3132 fn handle_allow_tool(
3133 &mut self,
3134 tool_use_id: LanguageModelToolUseId,
3135 _: &ClickEvent,
3136 _window: &mut Window,
3137 cx: &mut Context<Self>,
3138 ) {
3139 if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3140 .thread
3141 .read(cx)
3142 .pending_tool(&tool_use_id)
3143 .map(|tool_use| tool_use.status.clone())
3144 {
3145 self.thread.update(cx, |thread, cx| {
3146 thread.run_tool(
3147 c.tool_use_id.clone(),
3148 c.ui_text.clone(),
3149 c.input.clone(),
3150 &c.messages,
3151 c.tool.clone(),
3152 cx,
3153 );
3154 });
3155 }
3156 }
3157
3158 fn handle_deny_tool(
3159 &mut self,
3160 tool_use_id: LanguageModelToolUseId,
3161 tool_name: Arc<str>,
3162 _: &ClickEvent,
3163 _window: &mut Window,
3164 cx: &mut Context<Self>,
3165 ) {
3166 self.thread.update(cx, |thread, cx| {
3167 thread.deny_tool_use(tool_use_id, tool_name, cx);
3168 });
3169 }
3170
3171 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3172 let project_context = self.thread.read(cx).project_context();
3173 let project_context = project_context.borrow();
3174 let Some(project_context) = project_context.as_ref() else {
3175 return;
3176 };
3177
3178 let abs_paths = project_context
3179 .worktrees
3180 .iter()
3181 .flat_map(|worktree| worktree.rules_file.as_ref())
3182 .map(|rules_file| rules_file.abs_path.to_path_buf())
3183 .collect::<Vec<_>>();
3184
3185 if let Ok(task) = self.workspace.update(cx, move |workspace, cx| {
3186 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3187 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3188 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3189 workspace.open_paths(abs_paths, OpenOptions::default(), None, window, cx)
3190 }) {
3191 task.detach();
3192 }
3193 }
3194
3195 fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3196 for window in self.notifications.drain(..) {
3197 window
3198 .update(cx, |_, window, _| {
3199 window.remove_window();
3200 })
3201 .ok();
3202
3203 self.notification_subscriptions.remove(&window);
3204 }
3205 }
3206
3207 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3208 if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3209 return None;
3210 }
3211
3212 Some(
3213 div()
3214 .occlude()
3215 .id("active-thread-scrollbar")
3216 .on_mouse_move(cx.listener(|_, _, _, cx| {
3217 cx.notify();
3218 cx.stop_propagation()
3219 }))
3220 .on_hover(|_, _, cx| {
3221 cx.stop_propagation();
3222 })
3223 .on_any_mouse_down(|_, _, cx| {
3224 cx.stop_propagation();
3225 })
3226 .on_mouse_up(
3227 MouseButton::Left,
3228 cx.listener(|_, _, _, cx| {
3229 cx.stop_propagation();
3230 }),
3231 )
3232 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3233 cx.notify();
3234 }))
3235 .h_full()
3236 .absolute()
3237 .right_1()
3238 .top_1()
3239 .bottom_0()
3240 .w(px(12.))
3241 .cursor_default()
3242 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3243 )
3244 }
3245
3246 fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3247 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3248 self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3249 cx.background_executor()
3250 .timer(SCROLLBAR_SHOW_INTERVAL)
3251 .await;
3252 thread
3253 .update(cx, |thread, cx| {
3254 if !thread.scrollbar_state.is_dragging() {
3255 thread.show_scrollbar = false;
3256 cx.notify();
3257 }
3258 })
3259 .log_err();
3260 }))
3261 }
3262}
3263
3264pub enum ActiveThreadEvent {
3265 EditingMessageTokenCountChanged,
3266}
3267
3268impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3269
3270impl Render for ActiveThread {
3271 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3272 v_flex()
3273 .size_full()
3274 .relative()
3275 .on_mouse_move(cx.listener(|this, _, _, cx| {
3276 this.show_scrollbar = true;
3277 this.hide_scrollbar_later(cx);
3278 cx.notify();
3279 }))
3280 .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3281 this.show_scrollbar = true;
3282 this.hide_scrollbar_later(cx);
3283 cx.notify();
3284 }))
3285 .on_mouse_up(
3286 MouseButton::Left,
3287 cx.listener(|this, _, _, cx| {
3288 this.hide_scrollbar_later(cx);
3289 }),
3290 )
3291 .child(list(self.list_state.clone()).flex_grow())
3292 .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3293 this.child(scrollbar)
3294 })
3295 }
3296}
3297
3298pub(crate) fn open_context(
3299 id: ContextId,
3300 context_store: Entity<ContextStore>,
3301 workspace: Entity<Workspace>,
3302 window: &mut Window,
3303 cx: &mut App,
3304) {
3305 let Some(context) = context_store.read(cx).context_for_id(id) else {
3306 return;
3307 };
3308
3309 match context {
3310 AssistantContext::File(file_context) => {
3311 if let Some(project_path) = file_context.context_buffer.buffer.read(cx).project_path(cx)
3312 {
3313 workspace.update(cx, |workspace, cx| {
3314 workspace
3315 .open_path(project_path, None, true, window, cx)
3316 .detach_and_log_err(cx);
3317 });
3318 }
3319 }
3320 AssistantContext::Directory(directory_context) => {
3321 let entry_id = directory_context.entry_id;
3322 workspace.update(cx, |workspace, cx| {
3323 workspace.project().update(cx, |_project, cx| {
3324 cx.emit(project::Event::RevealInProjectPanel(entry_id));
3325 })
3326 })
3327 }
3328 AssistantContext::Symbol(symbol_context) => {
3329 if let Some(project_path) = symbol_context
3330 .context_symbol
3331 .buffer
3332 .read(cx)
3333 .project_path(cx)
3334 {
3335 let snapshot = symbol_context.context_symbol.buffer.read(cx).snapshot();
3336 let target_position = symbol_context
3337 .context_symbol
3338 .id
3339 .range
3340 .start
3341 .to_point(&snapshot);
3342
3343 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3344 .detach();
3345 }
3346 }
3347 AssistantContext::Selection(selection_context) => {
3348 if let Some(project_path) = selection_context
3349 .context_buffer
3350 .buffer
3351 .read(cx)
3352 .project_path(cx)
3353 {
3354 let snapshot = selection_context.context_buffer.buffer.read(cx).snapshot();
3355 let target_position = selection_context.range.start.to_point(&snapshot);
3356
3357 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3358 .detach();
3359 }
3360 }
3361 AssistantContext::FetchedUrl(fetched_url_context) => {
3362 cx.open_url(&fetched_url_context.url);
3363 }
3364 AssistantContext::Thread(thread_context) => {
3365 let thread_id = thread_context.thread.read(cx).id().clone();
3366 workspace.update(cx, |workspace, cx| {
3367 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
3368 panel.update(cx, |panel, cx| {
3369 panel
3370 .open_thread(&thread_id, window, cx)
3371 .detach_and_log_err(cx)
3372 });
3373 }
3374 })
3375 }
3376 AssistantContext::Rules(rules_context) => window.dispatch_action(
3377 Box::new(OpenPromptLibrary {
3378 prompt_to_select: Some(rules_context.prompt_id.0),
3379 }),
3380 cx,
3381 ),
3382 AssistantContext::Image(_) => {}
3383 }
3384}
3385
3386fn open_editor_at_position(
3387 project_path: project::ProjectPath,
3388 target_position: Point,
3389 workspace: &Entity<Workspace>,
3390 window: &mut Window,
3391 cx: &mut App,
3392) -> Task<()> {
3393 let open_task = workspace.update(cx, |workspace, cx| {
3394 workspace.open_path(project_path, None, true, window, cx)
3395 });
3396 window.spawn(cx, async move |cx| {
3397 if let Some(active_editor) = open_task
3398 .await
3399 .log_err()
3400 .and_then(|item| item.downcast::<Editor>())
3401 {
3402 active_editor
3403 .downgrade()
3404 .update_in(cx, |editor, window, cx| {
3405 editor.go_to_singleton_buffer_point(target_position, window, cx);
3406 })
3407 .log_err();
3408 }
3409 })
3410}