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