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