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