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