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 // Cancel any ongoing streaming when user starts editing a previous message
1286 self.cancel_last_completion(window, cx);
1287
1288 let editor = crate::message_editor::create_editor(
1289 self.workspace.clone(),
1290 self.context_store.downgrade(),
1291 self.thread_store.downgrade(),
1292 self.text_thread_store.downgrade(),
1293 window,
1294 cx,
1295 );
1296 editor.update(cx, |editor, cx| {
1297 editor.set_text(message_text.clone(), window, cx);
1298 editor.focus_handle(cx).focus(window);
1299 editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
1300 });
1301 let buffer_edited_subscription = cx.subscribe(&editor, |this, _, event, cx| match event {
1302 EditorEvent::BufferEdited => {
1303 this.update_editing_message_token_count(true, cx);
1304 }
1305 _ => {}
1306 });
1307
1308 let context_picker_menu_handle = PopoverMenuHandle::default();
1309 let context_strip = cx.new(|cx| {
1310 ContextStrip::new(
1311 self.context_store.clone(),
1312 self.workspace.clone(),
1313 Some(self.thread_store.downgrade()),
1314 Some(self.text_thread_store.downgrade()),
1315 context_picker_menu_handle.clone(),
1316 SuggestContextKind::File,
1317 window,
1318 cx,
1319 )
1320 });
1321
1322 let context_strip_subscription =
1323 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event);
1324
1325 self.editing_message = Some((
1326 message_id,
1327 EditingMessageState {
1328 editor: editor.clone(),
1329 context_strip,
1330 context_picker_menu_handle,
1331 last_estimated_token_count: None,
1332 _subscriptions: [buffer_edited_subscription, context_strip_subscription],
1333 _update_token_count_task: None,
1334 },
1335 ));
1336 self.update_editing_message_token_count(false, cx);
1337 cx.notify();
1338 }
1339
1340 fn handle_context_strip_event(
1341 &mut self,
1342 _context_strip: &Entity<ContextStrip>,
1343 event: &ContextStripEvent,
1344 window: &mut Window,
1345 cx: &mut Context<Self>,
1346 ) {
1347 if let Some((_, state)) = self.editing_message.as_ref() {
1348 match event {
1349 ContextStripEvent::PickerDismissed
1350 | ContextStripEvent::BlurredEmpty
1351 | ContextStripEvent::BlurredDown => {
1352 let editor_focus_handle = state.editor.focus_handle(cx);
1353 window.focus(&editor_focus_handle);
1354 }
1355 ContextStripEvent::BlurredUp => {}
1356 }
1357 }
1358 }
1359
1360 fn update_editing_message_token_count(&mut self, debounce: bool, cx: &mut Context<Self>) {
1361 let Some((message_id, state)) = self.editing_message.as_mut() else {
1362 return;
1363 };
1364
1365 cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1366 state._update_token_count_task.take();
1367
1368 let Some(configured_model) = self.thread.read(cx).configured_model() else {
1369 state.last_estimated_token_count.take();
1370 return;
1371 };
1372
1373 let editor = state.editor.clone();
1374 let thread = self.thread.clone();
1375 let message_id = *message_id;
1376
1377 state._update_token_count_task = Some(cx.spawn(async move |this, cx| {
1378 if debounce {
1379 cx.background_executor()
1380 .timer(Duration::from_millis(200))
1381 .await;
1382 }
1383
1384 let token_count = if let Some(task) = cx
1385 .update(|cx| {
1386 let Some(message) = thread.read(cx).message(message_id) else {
1387 log::error!("Message that was being edited no longer exists");
1388 return None;
1389 };
1390 let message_text = editor.read(cx).text(cx);
1391
1392 if message_text.is_empty() && message.loaded_context.is_empty() {
1393 return None;
1394 }
1395
1396 let mut request_message = LanguageModelRequestMessage {
1397 role: language_model::Role::User,
1398 content: Vec::new(),
1399 cache: false,
1400 };
1401
1402 message
1403 .loaded_context
1404 .add_to_request_message(&mut request_message);
1405
1406 if !message_text.is_empty() {
1407 request_message
1408 .content
1409 .push(MessageContent::Text(message_text));
1410 }
1411
1412 let request = language_model::LanguageModelRequest {
1413 thread_id: None,
1414 prompt_id: None,
1415 mode: None,
1416 messages: vec![request_message],
1417 tools: vec![],
1418 stop: vec![],
1419 temperature: AssistantSettings::temperature_for_model(
1420 &configured_model.model,
1421 cx,
1422 ),
1423 };
1424
1425 Some(configured_model.model.count_tokens(request, cx))
1426 })
1427 .ok()
1428 .flatten()
1429 {
1430 task.await.log_err()
1431 } else {
1432 Some(0)
1433 };
1434
1435 if let Some(token_count) = token_count {
1436 this.update(cx, |this, cx| {
1437 let Some((_message_id, state)) = this.editing_message.as_mut() else {
1438 return;
1439 };
1440
1441 state.last_estimated_token_count = Some(token_count);
1442 cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1443 })
1444 .ok();
1445 };
1446 }));
1447 }
1448
1449 fn toggle_context_picker(
1450 &mut self,
1451 _: &crate::ToggleContextPicker,
1452 window: &mut Window,
1453 cx: &mut Context<Self>,
1454 ) {
1455 if let Some((_, state)) = self.editing_message.as_mut() {
1456 let handle = state.context_picker_menu_handle.clone();
1457 window.defer(cx, move |window, cx| {
1458 handle.toggle(window, cx);
1459 });
1460 }
1461 }
1462
1463 fn remove_all_context(
1464 &mut self,
1465 _: &crate::RemoveAllContext,
1466 _window: &mut Window,
1467 cx: &mut Context<Self>,
1468 ) {
1469 self.context_store.update(cx, |store, _cx| store.clear());
1470 cx.notify();
1471 }
1472
1473 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
1474 if let Some((_, state)) = self.editing_message.as_mut() {
1475 if state.context_picker_menu_handle.is_deployed() {
1476 cx.propagate();
1477 } else {
1478 state.context_strip.focus_handle(cx).focus(window);
1479 }
1480 }
1481 }
1482
1483 fn paste(&mut self, _: &Paste, _window: &mut Window, cx: &mut Context<Self>) {
1484 let images = cx
1485 .read_from_clipboard()
1486 .map(|item| {
1487 item.into_entries()
1488 .filter_map(|entry| {
1489 if let ClipboardEntry::Image(image) = entry {
1490 Some(image)
1491 } else {
1492 None
1493 }
1494 })
1495 .collect::<Vec<_>>()
1496 })
1497 .unwrap_or_default();
1498
1499 if images.is_empty() {
1500 return;
1501 }
1502 cx.stop_propagation();
1503
1504 self.context_store.update(cx, |store, cx| {
1505 for image in images {
1506 store.add_image_instance(Arc::new(image), cx);
1507 }
1508 });
1509 }
1510
1511 fn cancel_editing_message(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
1512 self.editing_message.take();
1513 cx.notify();
1514 }
1515
1516 fn confirm_editing_message(
1517 &mut self,
1518 _: &menu::Confirm,
1519 window: &mut Window,
1520 cx: &mut Context<Self>,
1521 ) {
1522 let Some((message_id, state)) = self.editing_message.take() else {
1523 return;
1524 };
1525
1526 let Some(model) = self
1527 .thread
1528 .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
1529 else {
1530 return;
1531 };
1532
1533 if model.provider.must_accept_terms(cx) {
1534 cx.notify();
1535 return;
1536 }
1537
1538 let edited_text = state.editor.read(cx).text(cx);
1539
1540 let new_context = self
1541 .context_store
1542 .read(cx)
1543 .new_context_for_thread(self.thread.read(cx), Some(message_id));
1544
1545 let project = self.thread.read(cx).project().clone();
1546 let prompt_store = self.thread_store.read(cx).prompt_store().clone();
1547
1548 let load_context_task =
1549 crate::context::load_context(new_context, &project, &prompt_store, cx);
1550 self._load_edited_message_context_task =
1551 Some(cx.spawn_in(window, async move |this, cx| {
1552 let context = load_context_task.await;
1553 let _ = this
1554 .update_in(cx, |this, window, cx| {
1555 this.thread.update(cx, |thread, cx| {
1556 thread.edit_message(
1557 message_id,
1558 Role::User,
1559 vec![MessageSegment::Text(edited_text)],
1560 Some(context.loaded_context),
1561 cx,
1562 );
1563 for message_id in this.messages_after(message_id) {
1564 thread.delete_message(*message_id, cx);
1565 }
1566 });
1567
1568 this.thread.update(cx, |thread, cx| {
1569 thread.advance_prompt_id();
1570 thread.send_to_model(model.model, Some(window.window_handle()), cx);
1571 });
1572 this._load_edited_message_context_task = None;
1573 cx.notify();
1574 })
1575 .log_err();
1576 }));
1577 }
1578
1579 fn messages_after(&self, message_id: MessageId) -> &[MessageId] {
1580 self.messages
1581 .iter()
1582 .position(|id| *id == message_id)
1583 .map(|index| &self.messages[index + 1..])
1584 .unwrap_or(&[])
1585 }
1586
1587 fn handle_cancel_click(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1588 self.cancel_editing_message(&menu::Cancel, window, cx);
1589 }
1590
1591 fn handle_regenerate_click(
1592 &mut self,
1593 _: &ClickEvent,
1594 window: &mut Window,
1595 cx: &mut Context<Self>,
1596 ) {
1597 self.confirm_editing_message(&menu::Confirm, window, cx);
1598 }
1599
1600 fn handle_feedback_click(
1601 &mut self,
1602 message_id: MessageId,
1603 feedback: ThreadFeedback,
1604 window: &mut Window,
1605 cx: &mut Context<Self>,
1606 ) {
1607 let report = self.thread.update(cx, |thread, cx| {
1608 thread.report_message_feedback(message_id, feedback, cx)
1609 });
1610
1611 cx.spawn(async move |this, cx| {
1612 report.await?;
1613 this.update(cx, |_this, cx| cx.notify())
1614 })
1615 .detach_and_log_err(cx);
1616
1617 match feedback {
1618 ThreadFeedback::Positive => {
1619 self.open_feedback_editors.remove(&message_id);
1620 }
1621 ThreadFeedback::Negative => {
1622 self.handle_show_feedback_comments(message_id, window, cx);
1623 }
1624 }
1625 }
1626
1627 fn handle_show_feedback_comments(
1628 &mut self,
1629 message_id: MessageId,
1630 window: &mut Window,
1631 cx: &mut Context<Self>,
1632 ) {
1633 let buffer = cx.new(|cx| {
1634 let empty_string = String::new();
1635 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
1636 });
1637
1638 let editor = cx.new(|cx| {
1639 let mut editor = Editor::new(
1640 editor::EditorMode::AutoHeight { max_lines: 4 },
1641 buffer,
1642 None,
1643 window,
1644 cx,
1645 );
1646 editor.set_placeholder_text(
1647 "What went wrong? Share your feedback so we can improve.",
1648 cx,
1649 );
1650 editor
1651 });
1652
1653 editor.read(cx).focus_handle(cx).focus(window);
1654 self.open_feedback_editors.insert(message_id, editor);
1655 cx.notify();
1656 }
1657
1658 fn submit_feedback_message(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
1659 let Some(editor) = self.open_feedback_editors.get(&message_id) else {
1660 return;
1661 };
1662
1663 let report_task = self.thread.update(cx, |thread, cx| {
1664 thread.report_message_feedback(message_id, ThreadFeedback::Negative, cx)
1665 });
1666
1667 let comments = editor.read(cx).text(cx);
1668 if !comments.is_empty() {
1669 let thread_id = self.thread.read(cx).id().clone();
1670 let comments_value = String::from(comments.as_str());
1671
1672 let message_content = self
1673 .thread
1674 .read(cx)
1675 .message(message_id)
1676 .map(|msg| msg.to_string())
1677 .unwrap_or_default();
1678
1679 telemetry::event!(
1680 "Assistant Thread Feedback Comments",
1681 thread_id,
1682 message_id = message_id.0,
1683 message_content,
1684 comments = comments_value
1685 );
1686
1687 self.open_feedback_editors.remove(&message_id);
1688
1689 cx.spawn(async move |this, cx| {
1690 report_task.await?;
1691 this.update(cx, |_this, cx| cx.notify())
1692 })
1693 .detach_and_log_err(cx);
1694 }
1695 }
1696
1697 fn render_edit_message_editor(
1698 &self,
1699 state: &EditingMessageState,
1700 _window: &mut Window,
1701 cx: &Context<Self>,
1702 ) -> impl IntoElement {
1703 let settings = ThemeSettings::get_global(cx);
1704 let font_size = TextSize::Small
1705 .rems(cx)
1706 .to_pixels(settings.agent_font_size(cx));
1707 let line_height = font_size * 1.75;
1708
1709 let colors = cx.theme().colors();
1710
1711 let text_style = TextStyle {
1712 color: colors.text,
1713 font_family: settings.buffer_font.family.clone(),
1714 font_fallbacks: settings.buffer_font.fallbacks.clone(),
1715 font_features: settings.buffer_font.features.clone(),
1716 font_size: font_size.into(),
1717 line_height: line_height.into(),
1718 ..Default::default()
1719 };
1720
1721 v_flex()
1722 .key_context("EditMessageEditor")
1723 .on_action(cx.listener(Self::toggle_context_picker))
1724 .on_action(cx.listener(Self::remove_all_context))
1725 .on_action(cx.listener(Self::move_up))
1726 .on_action(cx.listener(Self::cancel_editing_message))
1727 .on_action(cx.listener(Self::confirm_editing_message))
1728 .capture_action(cx.listener(Self::paste))
1729 .min_h_6()
1730 .flex_grow()
1731 .w_full()
1732 .gap_2()
1733 .child(EditorElement::new(
1734 &state.editor,
1735 EditorStyle {
1736 background: colors.editor_background,
1737 local_player: cx.theme().players().local(),
1738 text: text_style,
1739 syntax: cx.theme().syntax().clone(),
1740 ..Default::default()
1741 },
1742 ))
1743 .child(state.context_strip.clone())
1744 }
1745
1746 fn render_message(&self, ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1747 let message_id = self.messages[ix];
1748 let Some(message) = self.thread.read(cx).message(message_id) else {
1749 return Empty.into_any();
1750 };
1751
1752 let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1753 return Empty.into_any();
1754 };
1755
1756 let workspace = self.workspace.clone();
1757 let thread = self.thread.read(cx);
1758
1759 // Get all the data we need from thread before we start using it in closures
1760 let checkpoint = thread.checkpoint_for_message(message_id);
1761 let added_context = thread
1762 .context_for_message(message_id)
1763 .map(|context| AddedContext::new_attached(context, cx))
1764 .collect::<Vec<_>>();
1765
1766 let tool_uses = thread.tool_uses_for_message(message_id, cx);
1767 let has_tool_uses = !tool_uses.is_empty();
1768 let is_generating = thread.is_generating();
1769 let is_generating_stale = thread.is_generation_stale().unwrap_or(false);
1770
1771 let is_first_message = ix == 0;
1772 let is_last_message = ix == self.messages.len() - 1;
1773
1774 let loading_dots = (is_generating_stale && is_last_message)
1775 .then(|| AnimatedLabel::new("").size(LabelSize::Small));
1776
1777 let editing_message_state = self
1778 .editing_message
1779 .as_ref()
1780 .filter(|(id, _)| *id == message_id)
1781 .map(|(_, state)| state);
1782
1783 let colors = cx.theme().colors();
1784 let editor_bg_color = colors.editor_background;
1785
1786 let open_as_markdown = IconButton::new(("open-as-markdown", ix), IconName::FileCode)
1787 .shape(ui::IconButtonShape::Square)
1788 .icon_size(IconSize::XSmall)
1789 .icon_color(Color::Ignored)
1790 .tooltip(Tooltip::text("Open Thread as Markdown"))
1791 .on_click({
1792 let thread = self.thread.clone();
1793 let workspace = self.workspace.clone();
1794 move |_, window, cx| {
1795 if let Some(workspace) = workspace.upgrade() {
1796 open_active_thread_as_markdown(thread.clone(), workspace, window, cx)
1797 .detach_and_log_err(cx);
1798 }
1799 }
1800 });
1801
1802 // For all items that should be aligned with the LLM's response.
1803 const RESPONSE_PADDING_X: Pixels = px(19.);
1804
1805 let show_feedback = thread.is_turn_end(ix);
1806
1807 let feedback_container = h_flex()
1808 .group("feedback_container")
1809 .mt_1()
1810 .py_2()
1811 .px(RESPONSE_PADDING_X)
1812 .gap_1()
1813 .flex_wrap()
1814 .justify_end();
1815 let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1816 Some(feedback) => feedback_container
1817 .child(
1818 div().mr_1().visible_on_hover("feedback_container").child(
1819 Label::new(match feedback {
1820 ThreadFeedback::Positive => "Thanks for your feedback!",
1821 ThreadFeedback::Negative => {
1822 "We appreciate your feedback and will use it to improve."
1823 }
1824 })
1825 .color(Color::Muted)
1826 .size(LabelSize::XSmall)
1827 .truncate())
1828 )
1829 .child(
1830 h_flex()
1831 .pr_1()
1832 .gap_1()
1833 .child(
1834 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1835 .shape(ui::IconButtonShape::Square)
1836 .icon_size(IconSize::XSmall)
1837 .icon_color(match feedback {
1838 ThreadFeedback::Positive => Color::Accent,
1839 ThreadFeedback::Negative => Color::Ignored,
1840 })
1841 .tooltip(Tooltip::text("Helpful Response"))
1842 .on_click(cx.listener(move |this, _, window, cx| {
1843 this.handle_feedback_click(
1844 message_id,
1845 ThreadFeedback::Positive,
1846 window,
1847 cx,
1848 );
1849 })),
1850 )
1851 .child(
1852 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1853 .shape(ui::IconButtonShape::Square)
1854 .icon_size(IconSize::XSmall)
1855 .icon_color(match feedback {
1856 ThreadFeedback::Positive => Color::Ignored,
1857 ThreadFeedback::Negative => Color::Accent,
1858 })
1859 .tooltip(Tooltip::text("Not Helpful"))
1860 .on_click(cx.listener(move |this, _, window, cx| {
1861 this.handle_feedback_click(
1862 message_id,
1863 ThreadFeedback::Negative,
1864 window,
1865 cx,
1866 );
1867 })),
1868 )
1869 .child(open_as_markdown),
1870 )
1871 .into_any_element(),
1872 None => feedback_container
1873 .child(
1874 div().mr_1().visible_on_hover("feedback_container").child(
1875 Label::new(
1876 "Rating the thread sends all of your current conversation to the Zed team.",
1877 )
1878 .color(Color::Muted)
1879 .size(LabelSize::XSmall)
1880 .truncate())
1881 )
1882 .child(
1883 h_flex()
1884 .pr_1()
1885 .gap_1()
1886 .child(
1887 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1888 .icon_size(IconSize::XSmall)
1889 .icon_color(Color::Ignored)
1890 .shape(ui::IconButtonShape::Square)
1891 .tooltip(Tooltip::text("Helpful Response"))
1892 .on_click(cx.listener(move |this, _, window, cx| {
1893 this.handle_feedback_click(
1894 message_id,
1895 ThreadFeedback::Positive,
1896 window,
1897 cx,
1898 );
1899 })),
1900 )
1901 .child(
1902 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1903 .icon_size(IconSize::XSmall)
1904 .icon_color(Color::Ignored)
1905 .shape(ui::IconButtonShape::Square)
1906 .tooltip(Tooltip::text("Not Helpful"))
1907 .on_click(cx.listener(move |this, _, window, cx| {
1908 this.handle_feedback_click(
1909 message_id,
1910 ThreadFeedback::Negative,
1911 window,
1912 cx,
1913 );
1914 })),
1915 )
1916 .child(open_as_markdown),
1917 )
1918 .into_any_element(),
1919 };
1920
1921 let message_is_empty = message.should_display_content();
1922 let has_content = !message_is_empty || !added_context.is_empty();
1923
1924 let message_content = has_content.then(|| {
1925 if let Some(state) = editing_message_state.as_ref() {
1926 self.render_edit_message_editor(state, window, cx)
1927 .into_any_element()
1928 } else {
1929 v_flex()
1930 .w_full()
1931 .gap_1()
1932 .when(!message_is_empty, |parent| {
1933 parent.child(div().min_h_6().child(self.render_message_content(
1934 message_id,
1935 rendered_message,
1936 has_tool_uses,
1937 workspace.clone(),
1938 window,
1939 cx,
1940 )))
1941 })
1942 .when(!added_context.is_empty(), |parent| {
1943 parent.child(h_flex().flex_wrap().gap_1().children(
1944 added_context.into_iter().map(|added_context| {
1945 let context = added_context.handle.clone();
1946 ContextPill::added(added_context, false, false, None).on_click(
1947 Rc::new(cx.listener({
1948 let workspace = workspace.clone();
1949 move |_, _, window, cx| {
1950 if let Some(workspace) = workspace.upgrade() {
1951 open_context(&context, workspace, window, cx);
1952 cx.notify();
1953 }
1954 }
1955 })),
1956 )
1957 }),
1958 ))
1959 })
1960 .into_any_element()
1961 }
1962 });
1963
1964 let styled_message = match message.role {
1965 Role::User => v_flex()
1966 .id(("message-container", ix))
1967 .pt_2()
1968 .pl_2()
1969 .pr_2p5()
1970 .pb_4()
1971 .child(
1972 v_flex()
1973 .id(("user-message", ix))
1974 .bg(editor_bg_color)
1975 .rounded_lg()
1976 .shadow_md()
1977 .border_1()
1978 .border_color(colors.border)
1979 .hover(|hover| hover.border_color(colors.text_accent.opacity(0.5)))
1980 .cursor_pointer()
1981 .child(
1982 h_flex()
1983 .p_2p5()
1984 .gap_1()
1985 .children(message_content)
1986 .when_some(editing_message_state, |this, state| {
1987 let focus_handle = state.editor.focus_handle(cx).clone();
1988 this.w_full().justify_between().child(
1989 h_flex()
1990 .gap_0p5()
1991 .child(
1992 IconButton::new(
1993 "cancel-edit-message",
1994 IconName::Close,
1995 )
1996 .shape(ui::IconButtonShape::Square)
1997 .icon_color(Color::Error)
1998 .tooltip({
1999 let focus_handle = focus_handle.clone();
2000 move |window, cx| {
2001 Tooltip::for_action_in(
2002 "Cancel Edit",
2003 &menu::Cancel,
2004 &focus_handle,
2005 window,
2006 cx,
2007 )
2008 }
2009 })
2010 .on_click(cx.listener(Self::handle_cancel_click)),
2011 )
2012 .child(
2013 IconButton::new(
2014 "confirm-edit-message",
2015 IconName::Check,
2016 )
2017 .disabled(state.editor.read(cx).is_empty(cx))
2018 .shape(ui::IconButtonShape::Square)
2019 .icon_color(Color::Success)
2020 .tooltip({
2021 let focus_handle = focus_handle.clone();
2022 move |window, cx| {
2023 Tooltip::for_action_in(
2024 "Regenerate",
2025 &menu::Confirm,
2026 &focus_handle,
2027 window,
2028 cx,
2029 )
2030 }
2031 })
2032 .on_click(
2033 cx.listener(Self::handle_regenerate_click),
2034 ),
2035 ),
2036 )
2037 }),
2038 )
2039 .when(editing_message_state.is_none(), |this| {
2040 this.tooltip(Tooltip::text("Click To Edit"))
2041 })
2042 .on_click(cx.listener({
2043 let message_segments = message.segments.clone();
2044 move |this, _, window, cx| {
2045 this.start_editing_message(
2046 message_id,
2047 &message_segments,
2048 window,
2049 cx,
2050 );
2051 }
2052 })),
2053 ),
2054 Role::Assistant => v_flex()
2055 .id(("message-container", ix))
2056 .px(RESPONSE_PADDING_X)
2057 .gap_2()
2058 .children(message_content)
2059 .when(has_tool_uses, |parent| {
2060 parent.children(tool_uses.into_iter().map(|tool_use| {
2061 self.render_tool_use(tool_use, window, workspace.clone(), cx)
2062 }))
2063 }),
2064 Role::System => div().id(("message-container", ix)).py_1().px_2().child(
2065 v_flex()
2066 .bg(colors.editor_background)
2067 .rounded_sm()
2068 .child(div().p_4().children(message_content)),
2069 ),
2070 };
2071
2072 let after_editing_message = self
2073 .editing_message
2074 .as_ref()
2075 .map_or(false, |(editing_message_id, _)| {
2076 message_id > *editing_message_id
2077 });
2078
2079 let panel_background = cx.theme().colors().panel_background;
2080
2081 v_flex()
2082 .w_full()
2083 .map(|parent| {
2084 if let Some(checkpoint) = checkpoint.filter(|_| !is_generating) {
2085 let mut is_pending = false;
2086 let mut error = None;
2087 if let Some(last_restore_checkpoint) =
2088 self.thread.read(cx).last_restore_checkpoint()
2089 {
2090 if last_restore_checkpoint.message_id() == message_id {
2091 match last_restore_checkpoint {
2092 LastRestoreCheckpoint::Pending { .. } => is_pending = true,
2093 LastRestoreCheckpoint::Error { error: err, .. } => {
2094 error = Some(err.clone());
2095 }
2096 }
2097 }
2098 }
2099
2100 let restore_checkpoint_button =
2101 Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
2102 .icon(if error.is_some() {
2103 IconName::XCircle
2104 } else {
2105 IconName::Undo
2106 })
2107 .icon_size(IconSize::XSmall)
2108 .icon_position(IconPosition::Start)
2109 .icon_color(if error.is_some() {
2110 Some(Color::Error)
2111 } else {
2112 None
2113 })
2114 .label_size(LabelSize::XSmall)
2115 .disabled(is_pending)
2116 .on_click(cx.listener(move |this, _, _window, cx| {
2117 this.thread.update(cx, |thread, cx| {
2118 thread
2119 .restore_checkpoint(checkpoint.clone(), cx)
2120 .detach_and_log_err(cx);
2121 });
2122 }));
2123
2124 let restore_checkpoint_button = if is_pending {
2125 restore_checkpoint_button
2126 .with_animation(
2127 ("pulsating-restore-checkpoint-button", ix),
2128 Animation::new(Duration::from_secs(2))
2129 .repeat()
2130 .with_easing(pulsating_between(0.6, 1.)),
2131 |label, delta| label.alpha(delta),
2132 )
2133 .into_any_element()
2134 } else if let Some(error) = error {
2135 restore_checkpoint_button
2136 .tooltip(Tooltip::text(error.to_string()))
2137 .into_any_element()
2138 } else {
2139 restore_checkpoint_button.into_any_element()
2140 };
2141
2142 parent.child(
2143 h_flex()
2144 .pt_2p5()
2145 .px_2p5()
2146 .w_full()
2147 .gap_1()
2148 .child(ui::Divider::horizontal())
2149 .child(restore_checkpoint_button)
2150 .child(ui::Divider::horizontal()),
2151 )
2152 } else {
2153 parent
2154 }
2155 })
2156 .when(is_first_message, |parent| {
2157 parent.child(self.render_rules_item(cx))
2158 })
2159 .child(styled_message)
2160 .when(is_generating && is_last_message, |this| {
2161 this.child(
2162 h_flex()
2163 .h_8()
2164 .mt_2()
2165 .mb_4()
2166 .ml_4()
2167 .py_1p5()
2168 .when_some(loading_dots, |this, loading_dots| this.child(loading_dots)),
2169 )
2170 })
2171 .when(show_feedback, move |parent| {
2172 parent.child(feedback_items).when_some(
2173 self.open_feedback_editors.get(&message_id),
2174 move |parent, feedback_editor| {
2175 let focus_handle = feedback_editor.focus_handle(cx);
2176 parent.child(
2177 v_flex()
2178 .key_context("AgentFeedbackMessageEditor")
2179 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
2180 this.open_feedback_editors.remove(&message_id);
2181 cx.notify();
2182 }))
2183 .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
2184 this.submit_feedback_message(message_id, cx);
2185 cx.notify();
2186 }))
2187 .on_action(cx.listener(Self::confirm_editing_message))
2188 .mb_2()
2189 .mx_4()
2190 .p_2()
2191 .rounded_md()
2192 .border_1()
2193 .border_color(cx.theme().colors().border)
2194 .bg(cx.theme().colors().editor_background)
2195 .child(feedback_editor.clone())
2196 .child(
2197 h_flex()
2198 .gap_1()
2199 .justify_end()
2200 .child(
2201 Button::new("dismiss-feedback-message", "Cancel")
2202 .label_size(LabelSize::Small)
2203 .key_binding(
2204 KeyBinding::for_action_in(
2205 &menu::Cancel,
2206 &focus_handle,
2207 window,
2208 cx,
2209 )
2210 .map(|kb| kb.size(rems_from_px(10.))),
2211 )
2212 .on_click(cx.listener(
2213 move |this, _, _window, cx| {
2214 this.open_feedback_editors
2215 .remove(&message_id);
2216 cx.notify();
2217 },
2218 )),
2219 )
2220 .child(
2221 Button::new(
2222 "submit-feedback-message",
2223 "Share Feedback",
2224 )
2225 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2226 .label_size(LabelSize::Small)
2227 .key_binding(
2228 KeyBinding::for_action_in(
2229 &menu::Confirm,
2230 &focus_handle,
2231 window,
2232 cx,
2233 )
2234 .map(|kb| kb.size(rems_from_px(10.))),
2235 )
2236 .on_click(
2237 cx.listener(move |this, _, _window, cx| {
2238 this.submit_feedback_message(message_id, cx);
2239 cx.notify()
2240 }),
2241 ),
2242 ),
2243 ),
2244 )
2245 },
2246 )
2247 })
2248 .when(after_editing_message, |parent| {
2249 // Backdrop to dim out the whole thread below the editing user message
2250 parent.relative().child(
2251 div()
2252 .occlude()
2253 .absolute()
2254 .inset_0()
2255 .size_full()
2256 .bg(panel_background)
2257 .opacity(0.8),
2258 )
2259 })
2260 .into_any()
2261 }
2262
2263 fn render_message_content(
2264 &self,
2265 message_id: MessageId,
2266 rendered_message: &RenderedMessage,
2267 has_tool_uses: bool,
2268 workspace: WeakEntity<Workspace>,
2269 window: &Window,
2270 cx: &Context<Self>,
2271 ) -> impl IntoElement {
2272 let is_last_message = self.messages.last() == Some(&message_id);
2273 let is_generating = self.thread.read(cx).is_generating();
2274 let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2275 rendered_message
2276 .segments
2277 .iter()
2278 .enumerate()
2279 .next_back()
2280 .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2281 .map(|(index, _)| index)
2282 } else {
2283 None
2284 };
2285
2286 let message_role = self
2287 .thread
2288 .read(cx)
2289 .message(message_id)
2290 .map(|m| m.role)
2291 .unwrap_or(Role::User);
2292
2293 let is_assistant_message = message_role == Role::Assistant;
2294 let is_user_message = message_role == Role::User;
2295
2296 v_flex()
2297 .text_ui(cx)
2298 .gap_2()
2299 .when(is_user_message, |this| this.text_xs())
2300 .children(
2301 rendered_message.segments.iter().enumerate().map(
2302 |(index, segment)| match segment {
2303 RenderedMessageSegment::Thinking {
2304 content,
2305 scroll_handle,
2306 } => self
2307 .render_message_thinking_segment(
2308 message_id,
2309 index,
2310 content.clone(),
2311 &scroll_handle,
2312 Some(index) == pending_thinking_segment_index,
2313 window,
2314 cx,
2315 )
2316 .into_any_element(),
2317 RenderedMessageSegment::Text(markdown) => {
2318 let markdown_element = MarkdownElement::new(
2319 markdown.clone(),
2320 if is_user_message {
2321 let mut style = default_markdown_style(window, cx);
2322 let mut text_style = window.text_style();
2323 let theme_settings = ThemeSettings::get_global(cx);
2324
2325 let buffer_font = theme_settings.buffer_font.family.clone();
2326 let buffer_font_size = TextSize::Small.rems(cx);
2327
2328 text_style.refine(&TextStyleRefinement {
2329 font_family: Some(buffer_font),
2330 font_size: Some(buffer_font_size.into()),
2331 ..Default::default()
2332 });
2333
2334 style.base_text_style = text_style;
2335 style
2336 } else {
2337 default_markdown_style(window, cx)
2338 },
2339 );
2340
2341 let markdown_element = if is_assistant_message {
2342 markdown_element.code_block_renderer(
2343 markdown::CodeBlockRenderer::Custom {
2344 render: Arc::new({
2345 let workspace = workspace.clone();
2346 let active_thread = cx.entity();
2347 move |kind,
2348 parsed_markdown,
2349 range,
2350 metadata,
2351 window,
2352 cx| {
2353 render_markdown_code_block(
2354 message_id,
2355 range.start,
2356 kind,
2357 parsed_markdown,
2358 metadata,
2359 active_thread.clone(),
2360 workspace.clone(),
2361 window,
2362 cx,
2363 )
2364 }
2365 }),
2366 transform: Some(Arc::new({
2367 let active_thread = cx.entity();
2368 let editor_bg = cx.theme().colors().editor_background;
2369
2370 move |el, range, metadata, _, cx| {
2371 let is_expanded = active_thread
2372 .read(cx)
2373 .expanded_code_blocks
2374 .get(&(message_id, range.start))
2375 .copied()
2376 .unwrap_or(true);
2377
2378 if is_expanded
2379 || metadata.line_count
2380 <= MAX_UNCOLLAPSED_LINES_IN_CODE_BLOCK
2381 {
2382 return el;
2383 }
2384 el.child(
2385 div()
2386 .absolute()
2387 .bottom_0()
2388 .left_0()
2389 .w_full()
2390 .h_1_4()
2391 .rounded_b_lg()
2392 .bg(linear_gradient(
2393 0.,
2394 linear_color_stop(editor_bg, 0.),
2395 linear_color_stop(
2396 editor_bg.opacity(0.),
2397 1.,
2398 ),
2399 )),
2400 )
2401 }
2402 })),
2403 },
2404 )
2405 } else {
2406 markdown_element.code_block_renderer(
2407 markdown::CodeBlockRenderer::Default {
2408 copy_button: false,
2409 border: true,
2410 },
2411 )
2412 };
2413
2414 div()
2415 .child(markdown_element.on_url_click({
2416 let workspace = self.workspace.clone();
2417 move |text, window, cx| {
2418 open_markdown_link(text, workspace.clone(), window, cx);
2419 }
2420 }))
2421 .into_any_element()
2422 }
2423 },
2424 ),
2425 )
2426 }
2427
2428 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2429 cx.theme().colors().border.opacity(0.5)
2430 }
2431
2432 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2433 cx.theme()
2434 .colors()
2435 .element_background
2436 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2437 }
2438
2439 fn render_message_thinking_segment(
2440 &self,
2441 message_id: MessageId,
2442 ix: usize,
2443 markdown: Entity<Markdown>,
2444 scroll_handle: &ScrollHandle,
2445 pending: bool,
2446 window: &Window,
2447 cx: &Context<Self>,
2448 ) -> impl IntoElement {
2449 let is_open = self
2450 .expanded_thinking_segments
2451 .get(&(message_id, ix))
2452 .copied()
2453 .unwrap_or_default();
2454
2455 let editor_bg = cx.theme().colors().panel_background;
2456
2457 div().map(|this| {
2458 if pending {
2459 this.v_flex()
2460 .mt_neg_2()
2461 .mb_1p5()
2462 .child(
2463 h_flex()
2464 .group("disclosure-header")
2465 .justify_between()
2466 .child(
2467 h_flex()
2468 .gap_1p5()
2469 .child(
2470 Icon::new(IconName::LightBulb)
2471 .size(IconSize::XSmall)
2472 .color(Color::Muted),
2473 )
2474 .child(AnimatedLabel::new("Thinking").size(LabelSize::Small)),
2475 )
2476 .child(
2477 h_flex()
2478 .gap_1()
2479 .child(
2480 div().visible_on_hover("disclosure-header").child(
2481 Disclosure::new("thinking-disclosure", is_open)
2482 .opened_icon(IconName::ChevronUp)
2483 .closed_icon(IconName::ChevronDown)
2484 .on_click(cx.listener({
2485 move |this, _event, _window, _cx| {
2486 let is_open = this
2487 .expanded_thinking_segments
2488 .entry((message_id, ix))
2489 .or_insert(false);
2490
2491 *is_open = !*is_open;
2492 }
2493 })),
2494 ),
2495 )
2496 .child({
2497 Icon::new(IconName::ArrowCircle)
2498 .color(Color::Accent)
2499 .size(IconSize::Small)
2500 .with_animation(
2501 "arrow-circle",
2502 Animation::new(Duration::from_secs(2)).repeat(),
2503 |icon, delta| {
2504 icon.transform(Transformation::rotate(
2505 percentage(delta),
2506 ))
2507 },
2508 )
2509 }),
2510 ),
2511 )
2512 .when(!is_open, |this| {
2513 let gradient_overlay = div()
2514 .rounded_b_lg()
2515 .h_full()
2516 .absolute()
2517 .w_full()
2518 .bottom_0()
2519 .left_0()
2520 .bg(linear_gradient(
2521 180.,
2522 linear_color_stop(editor_bg, 1.),
2523 linear_color_stop(editor_bg.opacity(0.2), 0.),
2524 ));
2525
2526 this.child(
2527 div()
2528 .relative()
2529 .bg(editor_bg)
2530 .rounded_b_lg()
2531 .mt_2()
2532 .pl_4()
2533 .child(
2534 div()
2535 .id(("thinking-content", ix))
2536 .max_h_20()
2537 .track_scroll(scroll_handle)
2538 .text_ui_sm(cx)
2539 .overflow_hidden()
2540 .child(
2541 MarkdownElement::new(
2542 markdown.clone(),
2543 default_markdown_style(window, cx),
2544 )
2545 .on_url_click({
2546 let workspace = self.workspace.clone();
2547 move |text, window, cx| {
2548 open_markdown_link(
2549 text,
2550 workspace.clone(),
2551 window,
2552 cx,
2553 );
2554 }
2555 }),
2556 ),
2557 )
2558 .child(gradient_overlay),
2559 )
2560 })
2561 .when(is_open, |this| {
2562 this.child(
2563 div()
2564 .id(("thinking-content", ix))
2565 .h_full()
2566 .bg(editor_bg)
2567 .text_ui_sm(cx)
2568 .child(
2569 MarkdownElement::new(
2570 markdown.clone(),
2571 default_markdown_style(window, cx),
2572 )
2573 .on_url_click({
2574 let workspace = self.workspace.clone();
2575 move |text, window, cx| {
2576 open_markdown_link(text, workspace.clone(), window, cx);
2577 }
2578 }),
2579 ),
2580 )
2581 })
2582 } else {
2583 this.v_flex()
2584 .mt_neg_2()
2585 .child(
2586 h_flex()
2587 .group("disclosure-header")
2588 .pr_1()
2589 .justify_between()
2590 .opacity(0.8)
2591 .hover(|style| style.opacity(1.))
2592 .child(
2593 h_flex()
2594 .gap_1p5()
2595 .child(
2596 Icon::new(IconName::LightBulb)
2597 .size(IconSize::XSmall)
2598 .color(Color::Muted),
2599 )
2600 .child(Label::new("Thought Process").size(LabelSize::Small)),
2601 )
2602 .child(
2603 div().visible_on_hover("disclosure-header").child(
2604 Disclosure::new("thinking-disclosure", is_open)
2605 .opened_icon(IconName::ChevronUp)
2606 .closed_icon(IconName::ChevronDown)
2607 .on_click(cx.listener({
2608 move |this, _event, _window, _cx| {
2609 let is_open = this
2610 .expanded_thinking_segments
2611 .entry((message_id, ix))
2612 .or_insert(false);
2613
2614 *is_open = !*is_open;
2615 }
2616 })),
2617 ),
2618 ),
2619 )
2620 .child(
2621 div()
2622 .id(("thinking-content", ix))
2623 .relative()
2624 .mt_1p5()
2625 .ml_1p5()
2626 .pl_2p5()
2627 .border_l_1()
2628 .border_color(cx.theme().colors().border_variant)
2629 .text_ui_sm(cx)
2630 .when(is_open, |this| {
2631 this.child(
2632 MarkdownElement::new(
2633 markdown.clone(),
2634 default_markdown_style(window, cx),
2635 )
2636 .on_url_click({
2637 let workspace = self.workspace.clone();
2638 move |text, window, cx| {
2639 open_markdown_link(text, workspace.clone(), window, cx);
2640 }
2641 }),
2642 )
2643 }),
2644 )
2645 }
2646 })
2647 }
2648
2649 fn render_tool_use(
2650 &self,
2651 tool_use: ToolUse,
2652 window: &mut Window,
2653 workspace: WeakEntity<Workspace>,
2654 cx: &mut Context<Self>,
2655 ) -> impl IntoElement + use<> {
2656 if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2657 return card.render(&tool_use.status, window, workspace, cx);
2658 }
2659
2660 let is_open = self
2661 .expanded_tool_uses
2662 .get(&tool_use.id)
2663 .copied()
2664 .unwrap_or_default();
2665
2666 let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2667
2668 let fs = self
2669 .workspace
2670 .upgrade()
2671 .map(|workspace| workspace.read(cx).app_state().fs.clone());
2672 let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2673 let needs_confirmation_tools = tool_use.needs_confirmation;
2674
2675 let status_icons = div().child(match &tool_use.status {
2676 ToolUseStatus::NeedsConfirmation => {
2677 let icon = Icon::new(IconName::Warning)
2678 .color(Color::Warning)
2679 .size(IconSize::Small);
2680 icon.into_any_element()
2681 }
2682 ToolUseStatus::Pending
2683 | ToolUseStatus::InputStillStreaming
2684 | ToolUseStatus::Running => {
2685 let icon = Icon::new(IconName::ArrowCircle)
2686 .color(Color::Accent)
2687 .size(IconSize::Small);
2688 icon.with_animation(
2689 "arrow-circle",
2690 Animation::new(Duration::from_secs(2)).repeat(),
2691 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2692 )
2693 .into_any_element()
2694 }
2695 ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2696 ToolUseStatus::Error(_) => {
2697 let icon = Icon::new(IconName::Close)
2698 .color(Color::Error)
2699 .size(IconSize::Small);
2700 icon.into_any_element()
2701 }
2702 });
2703
2704 let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2705 let results_content_container = || v_flex().p_2().gap_0p5();
2706
2707 let results_content = v_flex()
2708 .gap_1()
2709 .child(
2710 results_content_container()
2711 .child(
2712 Label::new("Input")
2713 .size(LabelSize::XSmall)
2714 .color(Color::Muted)
2715 .buffer_font(cx),
2716 )
2717 .child(
2718 div()
2719 .w_full()
2720 .text_ui_sm(cx)
2721 .children(rendered_tool_use.as_ref().map(|rendered| {
2722 MarkdownElement::new(
2723 rendered.input.clone(),
2724 tool_use_markdown_style(window, cx),
2725 )
2726 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2727 copy_button: false,
2728 border: false,
2729 })
2730 .on_url_click({
2731 let workspace = self.workspace.clone();
2732 move |text, window, cx| {
2733 open_markdown_link(text, workspace.clone(), window, cx);
2734 }
2735 })
2736 })),
2737 ),
2738 )
2739 .map(|container| match tool_use.status {
2740 ToolUseStatus::Finished(_) => container.child(
2741 results_content_container()
2742 .border_t_1()
2743 .border_color(self.tool_card_border_color(cx))
2744 .child(
2745 Label::new("Result")
2746 .size(LabelSize::XSmall)
2747 .color(Color::Muted)
2748 .buffer_font(cx),
2749 )
2750 .child(div().w_full().text_ui_sm(cx).children(
2751 rendered_tool_use.as_ref().map(|rendered| {
2752 MarkdownElement::new(
2753 rendered.output.clone(),
2754 tool_use_markdown_style(window, cx),
2755 )
2756 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2757 copy_button: false,
2758 border: false,
2759 })
2760 .on_url_click({
2761 let workspace = self.workspace.clone();
2762 move |text, window, cx| {
2763 open_markdown_link(text, workspace.clone(), window, cx);
2764 }
2765 })
2766 .into_any_element()
2767 }),
2768 )),
2769 ),
2770 ToolUseStatus::InputStillStreaming | ToolUseStatus::Running => container.child(
2771 results_content_container()
2772 .border_t_1()
2773 .border_color(self.tool_card_border_color(cx))
2774 .child(
2775 h_flex()
2776 .gap_1()
2777 .child(
2778 Icon::new(IconName::ArrowCircle)
2779 .size(IconSize::Small)
2780 .color(Color::Accent)
2781 .with_animation(
2782 "arrow-circle",
2783 Animation::new(Duration::from_secs(2)).repeat(),
2784 |icon, delta| {
2785 icon.transform(Transformation::rotate(percentage(
2786 delta,
2787 )))
2788 },
2789 ),
2790 )
2791 .child(
2792 Label::new("Running…")
2793 .size(LabelSize::XSmall)
2794 .color(Color::Muted)
2795 .buffer_font(cx),
2796 ),
2797 ),
2798 ),
2799 ToolUseStatus::Error(_) => container.child(
2800 results_content_container()
2801 .border_t_1()
2802 .border_color(self.tool_card_border_color(cx))
2803 .child(
2804 Label::new("Error")
2805 .size(LabelSize::XSmall)
2806 .color(Color::Muted)
2807 .buffer_font(cx),
2808 )
2809 .child(
2810 div()
2811 .text_ui_sm(cx)
2812 .children(rendered_tool_use.as_ref().map(|rendered| {
2813 MarkdownElement::new(
2814 rendered.output.clone(),
2815 tool_use_markdown_style(window, cx),
2816 )
2817 .on_url_click({
2818 let workspace = self.workspace.clone();
2819 move |text, window, cx| {
2820 open_markdown_link(text, workspace.clone(), window, cx);
2821 }
2822 })
2823 .into_any_element()
2824 })),
2825 ),
2826 ),
2827 ToolUseStatus::Pending => container,
2828 ToolUseStatus::NeedsConfirmation => container.child(
2829 results_content_container()
2830 .border_t_1()
2831 .border_color(self.tool_card_border_color(cx))
2832 .child(
2833 Label::new("Asking Permission")
2834 .size(LabelSize::Small)
2835 .color(Color::Muted)
2836 .buffer_font(cx),
2837 ),
2838 ),
2839 });
2840
2841 let gradient_overlay = |color: Hsla| {
2842 div()
2843 .h_full()
2844 .absolute()
2845 .w_12()
2846 .bottom_0()
2847 .map(|element| {
2848 if is_status_finished {
2849 element.right_6()
2850 } else {
2851 element.right(px(44.))
2852 }
2853 })
2854 .bg(linear_gradient(
2855 90.,
2856 linear_color_stop(color, 1.),
2857 linear_color_stop(color.opacity(0.2), 0.),
2858 ))
2859 };
2860
2861 v_flex().gap_1().mb_2().map(|element| {
2862 if !needs_confirmation_tools {
2863 element.child(
2864 v_flex()
2865 .child(
2866 h_flex()
2867 .group("disclosure-header")
2868 .relative()
2869 .gap_1p5()
2870 .justify_between()
2871 .opacity(0.8)
2872 .hover(|style| style.opacity(1.))
2873 .when(!is_status_finished, |this| this.pr_2())
2874 .child(
2875 h_flex()
2876 .id("tool-label-container")
2877 .gap_1p5()
2878 .max_w_full()
2879 .overflow_x_scroll()
2880 .child(
2881 Icon::new(tool_use.icon)
2882 .size(IconSize::XSmall)
2883 .color(Color::Muted),
2884 )
2885 .child(
2886 h_flex().pr_8().text_size(rems(0.8125)).children(
2887 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| {
2888 open_markdown_link(text, workspace.clone(), window, cx);
2889 }}))
2890 ),
2891 ),
2892 )
2893 .child(
2894 h_flex()
2895 .gap_1()
2896 .child(
2897 div().visible_on_hover("disclosure-header").child(
2898 Disclosure::new("tool-use-disclosure", is_open)
2899 .opened_icon(IconName::ChevronUp)
2900 .closed_icon(IconName::ChevronDown)
2901 .on_click(cx.listener({
2902 let tool_use_id = tool_use.id.clone();
2903 move |this, _event, _window, _cx| {
2904 let is_open = this
2905 .expanded_tool_uses
2906 .entry(tool_use_id.clone())
2907 .or_insert(false);
2908
2909 *is_open = !*is_open;
2910 }
2911 })),
2912 ),
2913 )
2914 .child(status_icons),
2915 )
2916 .child(gradient_overlay(cx.theme().colors().panel_background)),
2917 )
2918 .map(|parent| {
2919 if !is_open {
2920 return parent;
2921 }
2922
2923 parent.child(
2924 v_flex()
2925 .mt_1()
2926 .border_1()
2927 .border_color(self.tool_card_border_color(cx))
2928 .bg(cx.theme().colors().editor_background)
2929 .rounded_lg()
2930 .child(results_content),
2931 )
2932 }),
2933 )
2934 } else {
2935 v_flex()
2936 .mb_2()
2937 .rounded_lg()
2938 .border_1()
2939 .border_color(self.tool_card_border_color(cx))
2940 .overflow_hidden()
2941 .child(
2942 h_flex()
2943 .group("disclosure-header")
2944 .relative()
2945 .justify_between()
2946 .py_1()
2947 .map(|element| {
2948 if is_status_finished {
2949 element.pl_2().pr_0p5()
2950 } else {
2951 element.px_2()
2952 }
2953 })
2954 .bg(self.tool_card_header_bg(cx))
2955 .map(|element| {
2956 if is_open {
2957 element.border_b_1().rounded_t_md()
2958 } else if needs_confirmation {
2959 element.rounded_t_md()
2960 } else {
2961 element.rounded_md()
2962 }
2963 })
2964 .border_color(self.tool_card_border_color(cx))
2965 .child(
2966 h_flex()
2967 .id("tool-label-container")
2968 .gap_1p5()
2969 .max_w_full()
2970 .overflow_x_scroll()
2971 .child(
2972 Icon::new(tool_use.icon)
2973 .size(IconSize::XSmall)
2974 .color(Color::Muted),
2975 )
2976 .child(
2977 h_flex().pr_8().text_ui_sm(cx).children(
2978 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| {
2979 open_markdown_link(text, workspace.clone(), window, cx);
2980 }}))
2981 ),
2982 ),
2983 )
2984 .child(
2985 h_flex()
2986 .gap_1()
2987 .child(
2988 div().visible_on_hover("disclosure-header").child(
2989 Disclosure::new("tool-use-disclosure", is_open)
2990 .opened_icon(IconName::ChevronUp)
2991 .closed_icon(IconName::ChevronDown)
2992 .on_click(cx.listener({
2993 let tool_use_id = tool_use.id.clone();
2994 move |this, _event, _window, _cx| {
2995 let is_open = this
2996 .expanded_tool_uses
2997 .entry(tool_use_id.clone())
2998 .or_insert(false);
2999
3000 *is_open = !*is_open;
3001 }
3002 })),
3003 ),
3004 )
3005 .child(status_icons),
3006 )
3007 .child(gradient_overlay(self.tool_card_header_bg(cx))),
3008 )
3009 .map(|parent| {
3010 if !is_open {
3011 return parent;
3012 }
3013
3014 parent.child(
3015 v_flex()
3016 .bg(cx.theme().colors().editor_background)
3017 .map(|element| {
3018 if needs_confirmation {
3019 element.rounded_none()
3020 } else {
3021 element.rounded_b_lg()
3022 }
3023 })
3024 .child(results_content),
3025 )
3026 })
3027 .when(needs_confirmation, |this| {
3028 this.child(
3029 h_flex()
3030 .py_1()
3031 .pl_2()
3032 .pr_1()
3033 .gap_1()
3034 .justify_between()
3035 .bg(cx.theme().colors().editor_background)
3036 .border_t_1()
3037 .border_color(self.tool_card_border_color(cx))
3038 .rounded_b_lg()
3039 .child(
3040 AnimatedLabel::new("Waiting for Confirmation").size(LabelSize::Small)
3041 )
3042 .child(
3043 h_flex()
3044 .gap_0p5()
3045 .child({
3046 let tool_id = tool_use.id.clone();
3047 Button::new(
3048 "always-allow-tool-action",
3049 "Always Allow",
3050 )
3051 .label_size(LabelSize::Small)
3052 .icon(IconName::CheckDouble)
3053 .icon_position(IconPosition::Start)
3054 .icon_size(IconSize::Small)
3055 .icon_color(Color::Success)
3056 .tooltip(move |window, cx| {
3057 Tooltip::with_meta(
3058 "Never ask for permission",
3059 None,
3060 "Restore the original behavior in your Agent Panel settings",
3061 window,
3062 cx,
3063 )
3064 })
3065 .on_click(cx.listener(
3066 move |this, event, window, cx| {
3067 if let Some(fs) = fs.clone() {
3068 update_settings_file::<AssistantSettings>(
3069 fs.clone(),
3070 cx,
3071 |settings, _| {
3072 settings.set_always_allow_tool_actions(true);
3073 },
3074 );
3075 }
3076 this.handle_allow_tool(
3077 tool_id.clone(),
3078 event,
3079 window,
3080 cx,
3081 )
3082 },
3083 ))
3084 })
3085 .child(ui::Divider::vertical())
3086 .child({
3087 let tool_id = tool_use.id.clone();
3088 Button::new("allow-tool-action", "Allow")
3089 .label_size(LabelSize::Small)
3090 .icon(IconName::Check)
3091 .icon_position(IconPosition::Start)
3092 .icon_size(IconSize::Small)
3093 .icon_color(Color::Success)
3094 .on_click(cx.listener(
3095 move |this, event, window, cx| {
3096 this.handle_allow_tool(
3097 tool_id.clone(),
3098 event,
3099 window,
3100 cx,
3101 )
3102 },
3103 ))
3104 })
3105 .child({
3106 let tool_id = tool_use.id.clone();
3107 let tool_name: Arc<str> = tool_use.name.into();
3108 Button::new("deny-tool", "Deny")
3109 .label_size(LabelSize::Small)
3110 .icon(IconName::Close)
3111 .icon_position(IconPosition::Start)
3112 .icon_size(IconSize::Small)
3113 .icon_color(Color::Error)
3114 .on_click(cx.listener(
3115 move |this, event, window, cx| {
3116 this.handle_deny_tool(
3117 tool_id.clone(),
3118 tool_name.clone(),
3119 event,
3120 window,
3121 cx,
3122 )
3123 },
3124 ))
3125 }),
3126 ),
3127 )
3128 })
3129 }
3130 }).into_any_element()
3131 }
3132
3133 fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
3134 let project_context = self.thread.read(cx).project_context();
3135 let project_context = project_context.borrow();
3136 let Some(project_context) = project_context.as_ref() else {
3137 return div().into_any();
3138 };
3139
3140 let user_rules_text = if project_context.user_rules.is_empty() {
3141 None
3142 } else if project_context.user_rules.len() == 1 {
3143 let user_rules = &project_context.user_rules[0];
3144
3145 match user_rules.title.as_ref() {
3146 Some(title) => Some(format!("Using \"{title}\" user rule")),
3147 None => Some("Using user rule".into()),
3148 }
3149 } else {
3150 Some(format!(
3151 "Using {} user rules",
3152 project_context.user_rules.len()
3153 ))
3154 };
3155
3156 let first_user_rules_id = project_context
3157 .user_rules
3158 .first()
3159 .map(|user_rules| user_rules.uuid.0);
3160
3161 let rules_files = project_context
3162 .worktrees
3163 .iter()
3164 .filter_map(|worktree| worktree.rules_file.as_ref())
3165 .collect::<Vec<_>>();
3166
3167 let rules_file_text = match rules_files.as_slice() {
3168 &[] => None,
3169 &[rules_file] => Some(format!(
3170 "Using project {:?} file",
3171 rules_file.path_in_worktree
3172 )),
3173 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3174 };
3175
3176 if user_rules_text.is_none() && rules_file_text.is_none() {
3177 return div().into_any();
3178 }
3179
3180 v_flex()
3181 .pt_2()
3182 .px_2p5()
3183 .gap_1()
3184 .when_some(user_rules_text, |parent, user_rules_text| {
3185 parent.child(
3186 h_flex()
3187 .w_full()
3188 .child(
3189 Icon::new(RULES_ICON)
3190 .size(IconSize::XSmall)
3191 .color(Color::Disabled),
3192 )
3193 .child(
3194 Label::new(user_rules_text)
3195 .size(LabelSize::XSmall)
3196 .color(Color::Muted)
3197 .truncate()
3198 .buffer_font(cx)
3199 .ml_1p5()
3200 .mr_0p5(),
3201 )
3202 .child(
3203 IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3204 .shape(ui::IconButtonShape::Square)
3205 .icon_size(IconSize::XSmall)
3206 .icon_color(Color::Ignored)
3207 // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary` keybinding
3208 .tooltip(Tooltip::text("View User Rules"))
3209 .on_click(move |_event, window, cx| {
3210 window.dispatch_action(
3211 Box::new(OpenRulesLibrary {
3212 prompt_to_select: first_user_rules_id,
3213 }),
3214 cx,
3215 )
3216 }),
3217 ),
3218 )
3219 })
3220 .when_some(rules_file_text, |parent, rules_file_text| {
3221 parent.child(
3222 h_flex()
3223 .w_full()
3224 .child(
3225 Icon::new(IconName::File)
3226 .size(IconSize::XSmall)
3227 .color(Color::Disabled),
3228 )
3229 .child(
3230 Label::new(rules_file_text)
3231 .size(LabelSize::XSmall)
3232 .color(Color::Muted)
3233 .buffer_font(cx)
3234 .ml_1p5()
3235 .mr_0p5(),
3236 )
3237 .child(
3238 IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3239 .shape(ui::IconButtonShape::Square)
3240 .icon_size(IconSize::XSmall)
3241 .icon_color(Color::Ignored)
3242 .on_click(cx.listener(Self::handle_open_rules))
3243 .tooltip(Tooltip::text("View Rules")),
3244 ),
3245 )
3246 })
3247 .into_any()
3248 }
3249
3250 fn handle_allow_tool(
3251 &mut self,
3252 tool_use_id: LanguageModelToolUseId,
3253 _: &ClickEvent,
3254 window: &mut Window,
3255 cx: &mut Context<Self>,
3256 ) {
3257 if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3258 .thread
3259 .read(cx)
3260 .pending_tool(&tool_use_id)
3261 .map(|tool_use| tool_use.status.clone())
3262 {
3263 self.thread.update(cx, |thread, cx| {
3264 thread.run_tool(
3265 c.tool_use_id.clone(),
3266 c.ui_text.clone(),
3267 c.input.clone(),
3268 &c.messages,
3269 c.tool.clone(),
3270 Some(window.window_handle()),
3271 cx,
3272 );
3273 });
3274 }
3275 }
3276
3277 fn handle_deny_tool(
3278 &mut self,
3279 tool_use_id: LanguageModelToolUseId,
3280 tool_name: Arc<str>,
3281 _: &ClickEvent,
3282 window: &mut Window,
3283 cx: &mut Context<Self>,
3284 ) {
3285 let window_handle = window.window_handle();
3286 self.thread.update(cx, |thread, cx| {
3287 thread.deny_tool_use(tool_use_id, tool_name, Some(window_handle), cx);
3288 });
3289 }
3290
3291 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3292 let project_context = self.thread.read(cx).project_context();
3293 let project_context = project_context.borrow();
3294 let Some(project_context) = project_context.as_ref() else {
3295 return;
3296 };
3297
3298 let project_entry_ids = project_context
3299 .worktrees
3300 .iter()
3301 .flat_map(|worktree| worktree.rules_file.as_ref())
3302 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
3303 .collect::<Vec<_>>();
3304
3305 self.workspace
3306 .update(cx, move |workspace, cx| {
3307 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3308 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3309 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3310 let project = workspace.project().read(cx);
3311 let project_paths = project_entry_ids
3312 .into_iter()
3313 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
3314 .collect::<Vec<_>>();
3315 for project_path in project_paths {
3316 workspace
3317 .open_path(project_path, None, true, window, cx)
3318 .detach_and_log_err(cx);
3319 }
3320 })
3321 .ok();
3322 }
3323
3324 fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3325 for window in self.notifications.drain(..) {
3326 window
3327 .update(cx, |_, window, _| {
3328 window.remove_window();
3329 })
3330 .ok();
3331
3332 self.notification_subscriptions.remove(&window);
3333 }
3334 }
3335
3336 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3337 if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3338 return None;
3339 }
3340
3341 Some(
3342 div()
3343 .occlude()
3344 .id("active-thread-scrollbar")
3345 .on_mouse_move(cx.listener(|_, _, _, cx| {
3346 cx.notify();
3347 cx.stop_propagation()
3348 }))
3349 .on_hover(|_, _, cx| {
3350 cx.stop_propagation();
3351 })
3352 .on_any_mouse_down(|_, _, cx| {
3353 cx.stop_propagation();
3354 })
3355 .on_mouse_up(
3356 MouseButton::Left,
3357 cx.listener(|_, _, _, cx| {
3358 cx.stop_propagation();
3359 }),
3360 )
3361 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3362 cx.notify();
3363 }))
3364 .h_full()
3365 .absolute()
3366 .right_1()
3367 .top_1()
3368 .bottom_0()
3369 .w(px(12.))
3370 .cursor_default()
3371 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3372 )
3373 }
3374
3375 fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3376 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3377 self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3378 cx.background_executor()
3379 .timer(SCROLLBAR_SHOW_INTERVAL)
3380 .await;
3381 thread
3382 .update(cx, |thread, cx| {
3383 if !thread.scrollbar_state.is_dragging() {
3384 thread.show_scrollbar = false;
3385 cx.notify();
3386 }
3387 })
3388 .log_err();
3389 }))
3390 }
3391}
3392
3393pub enum ActiveThreadEvent {
3394 EditingMessageTokenCountChanged,
3395}
3396
3397impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3398
3399impl Render for ActiveThread {
3400 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3401 v_flex()
3402 .size_full()
3403 .relative()
3404 .on_mouse_move(cx.listener(|this, _, _, cx| {
3405 this.show_scrollbar = true;
3406 this.hide_scrollbar_later(cx);
3407 cx.notify();
3408 }))
3409 .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3410 this.show_scrollbar = true;
3411 this.hide_scrollbar_later(cx);
3412 cx.notify();
3413 }))
3414 .on_mouse_up(
3415 MouseButton::Left,
3416 cx.listener(|this, _, _, cx| {
3417 this.hide_scrollbar_later(cx);
3418 }),
3419 )
3420 .child(list(self.list_state.clone()).flex_grow())
3421 .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3422 this.child(scrollbar)
3423 })
3424 }
3425}
3426
3427pub(crate) fn open_active_thread_as_markdown(
3428 thread: Entity<Thread>,
3429 workspace: Entity<Workspace>,
3430 window: &mut Window,
3431 cx: &mut App,
3432) -> Task<anyhow::Result<()>> {
3433 let markdown_language_task = workspace
3434 .read(cx)
3435 .app_state()
3436 .languages
3437 .language_for_name("Markdown");
3438
3439 window.spawn(cx, async move |cx| {
3440 let markdown_language = markdown_language_task.await?;
3441
3442 workspace.update_in(cx, |workspace, window, cx| {
3443 let thread = thread.read(cx);
3444 let markdown = thread.to_markdown(cx)?;
3445 let thread_summary = thread
3446 .summary()
3447 .map(|summary| summary.to_string())
3448 .unwrap_or_else(|| "Thread".to_string());
3449
3450 let project = workspace.project().clone();
3451 let buffer = project.update(cx, |project, cx| {
3452 project.create_local_buffer(&markdown, Some(markdown_language), cx)
3453 });
3454 let buffer =
3455 cx.new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone()));
3456
3457 workspace.add_item_to_active_pane(
3458 Box::new(cx.new(|cx| {
3459 let mut editor =
3460 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3461 editor.set_breadcrumb_header(thread_summary);
3462 editor
3463 })),
3464 None,
3465 true,
3466 window,
3467 cx,
3468 );
3469
3470 anyhow::Ok(())
3471 })??;
3472 anyhow::Ok(())
3473 })
3474}
3475
3476pub(crate) fn open_context(
3477 context: &AgentContextHandle,
3478 workspace: Entity<Workspace>,
3479 window: &mut Window,
3480 cx: &mut App,
3481) {
3482 match context {
3483 AgentContextHandle::File(file_context) => {
3484 if let Some(project_path) = file_context.project_path(cx) {
3485 workspace.update(cx, |workspace, cx| {
3486 workspace
3487 .open_path(project_path, None, true, window, cx)
3488 .detach_and_log_err(cx);
3489 });
3490 }
3491 }
3492
3493 AgentContextHandle::Directory(directory_context) => {
3494 let entry_id = directory_context.entry_id;
3495 workspace.update(cx, |workspace, cx| {
3496 workspace.project().update(cx, |_project, cx| {
3497 cx.emit(project::Event::RevealInProjectPanel(entry_id));
3498 })
3499 })
3500 }
3501
3502 AgentContextHandle::Symbol(symbol_context) => {
3503 let buffer = symbol_context.buffer.read(cx);
3504 if let Some(project_path) = buffer.project_path(cx) {
3505 let snapshot = buffer.snapshot();
3506 let target_position = symbol_context.range.start.to_point(&snapshot);
3507 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3508 .detach();
3509 }
3510 }
3511
3512 AgentContextHandle::Selection(selection_context) => {
3513 let buffer = selection_context.buffer.read(cx);
3514 if let Some(project_path) = buffer.project_path(cx) {
3515 let snapshot = buffer.snapshot();
3516 let target_position = selection_context.range.start.to_point(&snapshot);
3517
3518 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3519 .detach();
3520 }
3521 }
3522
3523 AgentContextHandle::FetchedUrl(fetched_url_context) => {
3524 cx.open_url(&fetched_url_context.url);
3525 }
3526
3527 AgentContextHandle::Thread(thread_context) => workspace.update(cx, |workspace, cx| {
3528 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
3529 panel.update(cx, |panel, cx| {
3530 panel.open_thread(thread_context.thread.clone(), window, cx);
3531 });
3532 }
3533 }),
3534
3535 AgentContextHandle::TextThread(text_thread_context) => {
3536 workspace.update(cx, |workspace, cx| {
3537 if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
3538 panel.update(cx, |panel, cx| {
3539 panel.open_prompt_editor(text_thread_context.context.clone(), window, cx)
3540 });
3541 }
3542 })
3543 }
3544
3545 AgentContextHandle::Rules(rules_context) => window.dispatch_action(
3546 Box::new(OpenRulesLibrary {
3547 prompt_to_select: Some(rules_context.prompt_id.0),
3548 }),
3549 cx,
3550 ),
3551
3552 AgentContextHandle::Image(_) => {}
3553 }
3554}
3555
3556fn open_editor_at_position(
3557 project_path: project::ProjectPath,
3558 target_position: Point,
3559 workspace: &Entity<Workspace>,
3560 window: &mut Window,
3561 cx: &mut App,
3562) -> Task<()> {
3563 let open_task = workspace.update(cx, |workspace, cx| {
3564 workspace.open_path(project_path, None, true, window, cx)
3565 });
3566 window.spawn(cx, async move |cx| {
3567 if let Some(active_editor) = open_task
3568 .await
3569 .log_err()
3570 .and_then(|item| item.downcast::<Editor>())
3571 {
3572 active_editor
3573 .downgrade()
3574 .update_in(cx, |editor, window, cx| {
3575 editor.go_to_singleton_buffer_point(target_position, window, cx);
3576 })
3577 .log_err();
3578 }
3579 })
3580}
3581
3582#[cfg(test)]
3583mod tests {
3584 use assistant_tool::{ToolRegistry, ToolWorkingSet};
3585 use editor::EditorSettings;
3586 use fs::FakeFs;
3587 use gpui::{TestAppContext, VisualTestContext};
3588 use language_model::{LanguageModel, fake_provider::FakeLanguageModel};
3589 use project::Project;
3590 use prompt_store::PromptBuilder;
3591 use serde_json::json;
3592 use settings::SettingsStore;
3593 use util::path;
3594
3595 use crate::{ContextLoadResult, thread_store};
3596
3597 use super::*;
3598
3599 #[gpui::test]
3600 async fn test_current_completion_cancelled_when_message_edited(cx: &mut TestAppContext) {
3601 init_test_settings(cx);
3602
3603 let project = create_test_project(
3604 cx,
3605 json!({"code.rs": "fn main() {\n println!(\"Hello, world!\");\n}"}),
3606 )
3607 .await;
3608
3609 let (cx, active_thread, thread, model) = setup_test_environment(cx, project.clone()).await;
3610
3611 // Insert user message without any context (empty context vector)
3612 let message = thread.update(cx, |thread, cx| {
3613 let message_id = thread.insert_user_message(
3614 "What is the best way to learn Rust?",
3615 ContextLoadResult::default(),
3616 None,
3617 vec![],
3618 cx,
3619 );
3620 thread
3621 .message(message_id)
3622 .expect("message should exist")
3623 .clone()
3624 });
3625
3626 // Stream response to user message
3627 thread.update(cx, |thread, cx| {
3628 let request = thread.to_completion_request(model.clone(), cx);
3629 thread.stream_completion(request, model, cx.active_window(), cx)
3630 });
3631 let generating = thread.update(cx, |thread, _cx| thread.is_generating());
3632 assert!(generating, "There should be one pending completion");
3633
3634 // Edit the previous message
3635 active_thread.update_in(cx, |active_thread, window, cx| {
3636 active_thread.start_editing_message(message.id, &message.segments, window, cx);
3637 });
3638
3639 // Check that the stream was cancelled
3640 let generating = thread.update(cx, |thread, _cx| thread.is_generating());
3641 assert!(!generating, "The completion should have been cancelled");
3642 }
3643
3644 fn init_test_settings(cx: &mut TestAppContext) {
3645 cx.update(|cx| {
3646 let settings_store = SettingsStore::test(cx);
3647 cx.set_global(settings_store);
3648 language::init(cx);
3649 Project::init_settings(cx);
3650 AssistantSettings::register(cx);
3651 prompt_store::init(cx);
3652 thread_store::init(cx);
3653 workspace::init_settings(cx);
3654 language_model::init_settings(cx);
3655 ThemeSettings::register(cx);
3656 EditorSettings::register(cx);
3657 ToolRegistry::default_global(cx);
3658 });
3659 }
3660
3661 // Helper to create a test project with test files
3662 async fn create_test_project(
3663 cx: &mut TestAppContext,
3664 files: serde_json::Value,
3665 ) -> Entity<Project> {
3666 let fs = FakeFs::new(cx.executor());
3667 fs.insert_tree(path!("/test"), files).await;
3668 Project::test(fs, [path!("/test").as_ref()], cx).await
3669 }
3670
3671 async fn setup_test_environment(
3672 cx: &mut TestAppContext,
3673 project: Entity<Project>,
3674 ) -> (
3675 &mut VisualTestContext,
3676 Entity<ActiveThread>,
3677 Entity<Thread>,
3678 Arc<dyn LanguageModel>,
3679 ) {
3680 let (workspace, cx) =
3681 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3682
3683 let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3684 let thread_store = cx
3685 .update(|_, cx| {
3686 ThreadStore::load(
3687 project.clone(),
3688 cx.new(|_| ToolWorkingSet::default()),
3689 None,
3690 prompt_builder.clone(),
3691 cx,
3692 )
3693 })
3694 .await
3695 .unwrap();
3696 let text_thread_store = cx
3697 .update(|_, cx| {
3698 TextThreadStore::new(project.clone(), prompt_builder, Default::default(), cx)
3699 })
3700 .await
3701 .unwrap();
3702
3703 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
3704 let context_store = cx.new(|_cx| ContextStore::new(project.downgrade(), None));
3705
3706 let model = FakeLanguageModel::default();
3707 let model: Arc<dyn LanguageModel> = Arc::new(model);
3708
3709 let language_registry = LanguageRegistry::new(cx.executor());
3710 let language_registry = Arc::new(language_registry);
3711
3712 let active_thread = cx.update(|window, cx| {
3713 cx.new(|cx| {
3714 ActiveThread::new(
3715 thread.clone(),
3716 thread_store.clone(),
3717 text_thread_store.clone(),
3718 context_store.clone(),
3719 language_registry.clone(),
3720 workspace.downgrade(),
3721 window,
3722 cx,
3723 )
3724 })
3725 });
3726
3727 (cx, active_thread, thread, model)
3728 }
3729}