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