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