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