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