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
1782 if message.is_hidden {
1783 return Empty.into_any();
1784 }
1785
1786 let message_creases = message.creases.clone();
1787
1788 let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1789 return Empty.into_any();
1790 };
1791
1792 let workspace = self.workspace.clone();
1793 let thread = self.thread.read(cx);
1794
1795 // Get all the data we need from thread before we start using it in closures
1796 let checkpoint = thread.checkpoint_for_message(message_id);
1797 let added_context = thread
1798 .context_for_message(message_id)
1799 .map(|context| AddedContext::new_attached(context, cx))
1800 .collect::<Vec<_>>();
1801
1802 let tool_uses = thread.tool_uses_for_message(message_id, cx);
1803 let has_tool_uses = !tool_uses.is_empty();
1804 let is_generating = thread.is_generating();
1805 let is_generating_stale = thread.is_generation_stale().unwrap_or(false);
1806
1807 let is_first_message = ix == 0;
1808 let is_last_message = ix == self.messages.len() - 1;
1809
1810 let loading_dots = (is_generating_stale && is_last_message)
1811 .then(|| AnimatedLabel::new("").size(LabelSize::Small));
1812
1813 let editing_message_state = self
1814 .editing_message
1815 .as_ref()
1816 .filter(|(id, _)| *id == message_id)
1817 .map(|(_, state)| state);
1818
1819 let colors = cx.theme().colors();
1820 let editor_bg_color = colors.editor_background;
1821
1822 let open_as_markdown = IconButton::new(("open-as-markdown", ix), IconName::DocumentText)
1823 .icon_size(IconSize::XSmall)
1824 .icon_color(Color::Ignored)
1825 .tooltip(Tooltip::text("Open Thread as Markdown"))
1826 .on_click({
1827 let thread = self.thread.clone();
1828 let workspace = self.workspace.clone();
1829 move |_, window, cx| {
1830 if let Some(workspace) = workspace.upgrade() {
1831 open_active_thread_as_markdown(thread.clone(), workspace, window, cx)
1832 .detach_and_log_err(cx);
1833 }
1834 }
1835 });
1836
1837 // For all items that should be aligned with the LLM's response.
1838 const RESPONSE_PADDING_X: Pixels = px(19.);
1839
1840 let show_feedback = thread.is_turn_end(ix);
1841
1842 let feedback_container = h_flex()
1843 .group("feedback_container")
1844 .mt_1()
1845 .py_2()
1846 .px(RESPONSE_PADDING_X)
1847 .mr_1()
1848 .opacity(0.4)
1849 .hover(|style| style.opacity(1.))
1850 .gap_1p5()
1851 .flex_wrap()
1852 .justify_end();
1853 let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1854 Some(feedback) => feedback_container
1855 .child(
1856 div().visible_on_hover("feedback_container").child(
1857 Label::new(match feedback {
1858 ThreadFeedback::Positive => "Thanks for your feedback!",
1859 ThreadFeedback::Negative => {
1860 "We appreciate your feedback and will use it to improve."
1861 }
1862 })
1863 .color(Color::Muted)
1864 .size(LabelSize::XSmall)
1865 .truncate())
1866 )
1867 .child(
1868 h_flex()
1869 .child(
1870 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1871 .icon_size(IconSize::XSmall)
1872 .icon_color(match feedback {
1873 ThreadFeedback::Positive => Color::Accent,
1874 ThreadFeedback::Negative => Color::Ignored,
1875 })
1876 .tooltip(Tooltip::text("Helpful Response"))
1877 .on_click(cx.listener(move |this, _, window, cx| {
1878 this.handle_feedback_click(
1879 message_id,
1880 ThreadFeedback::Positive,
1881 window,
1882 cx,
1883 );
1884 })),
1885 )
1886 .child(
1887 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1888 .icon_size(IconSize::XSmall)
1889 .icon_color(match feedback {
1890 ThreadFeedback::Positive => Color::Ignored,
1891 ThreadFeedback::Negative => Color::Accent,
1892 })
1893 .tooltip(Tooltip::text("Not Helpful"))
1894 .on_click(cx.listener(move |this, _, window, cx| {
1895 this.handle_feedback_click(
1896 message_id,
1897 ThreadFeedback::Negative,
1898 window,
1899 cx,
1900 );
1901 })),
1902 )
1903 .child(open_as_markdown),
1904 )
1905 .into_any_element(),
1906 None if AgentSettings::get_global(cx).enable_feedback =>
1907 feedback_container
1908 .child(
1909 div().visible_on_hover("feedback_container").child(
1910 Label::new(
1911 "Rating the thread sends all of your current conversation to the Zed team.",
1912 )
1913 .color(Color::Muted)
1914 .size(LabelSize::XSmall)
1915 .truncate())
1916 )
1917 .child(
1918 h_flex()
1919 .child(
1920 IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1921 .icon_size(IconSize::XSmall)
1922 .icon_color(Color::Ignored)
1923 .tooltip(Tooltip::text("Helpful Response"))
1924 .on_click(cx.listener(move |this, _, window, cx| {
1925 this.handle_feedback_click(
1926 message_id,
1927 ThreadFeedback::Positive,
1928 window,
1929 cx,
1930 );
1931 })),
1932 )
1933 .child(
1934 IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1935 .icon_size(IconSize::XSmall)
1936 .icon_color(Color::Ignored)
1937 .tooltip(Tooltip::text("Not Helpful"))
1938 .on_click(cx.listener(move |this, _, window, cx| {
1939 this.handle_feedback_click(
1940 message_id,
1941 ThreadFeedback::Negative,
1942 window,
1943 cx,
1944 );
1945 })),
1946 )
1947 .child(open_as_markdown),
1948 )
1949 .into_any_element(),
1950 None => feedback_container
1951 .child(h_flex().child(open_as_markdown))
1952 .into_any_element(),
1953 };
1954
1955 let message_is_empty = message.should_display_content();
1956 let has_content = !message_is_empty || !added_context.is_empty();
1957
1958 let message_content = has_content.then(|| {
1959 if let Some(state) = editing_message_state.as_ref() {
1960 self.render_edit_message_editor(state, window, cx)
1961 .into_any_element()
1962 } else {
1963 v_flex()
1964 .w_full()
1965 .gap_1()
1966 .when(!added_context.is_empty(), |parent| {
1967 parent.child(h_flex().flex_wrap().gap_1().children(
1968 added_context.into_iter().map(|added_context| {
1969 let context = added_context.handle.clone();
1970 ContextPill::added(added_context, false, false, None).on_click(
1971 Rc::new(cx.listener({
1972 let workspace = workspace.clone();
1973 move |_, _, window, cx| {
1974 if let Some(workspace) = workspace.upgrade() {
1975 open_context(&context, workspace, window, cx);
1976 cx.notify();
1977 }
1978 }
1979 })),
1980 )
1981 }),
1982 ))
1983 })
1984 .when(!message_is_empty, |parent| {
1985 parent.child(div().pt_0p5().min_h_6().child(self.render_message_content(
1986 message_id,
1987 rendered_message,
1988 has_tool_uses,
1989 workspace.clone(),
1990 window,
1991 cx,
1992 )))
1993 })
1994 .into_any_element()
1995 }
1996 });
1997
1998 let styled_message = match message.role {
1999 Role::User => v_flex()
2000 .id(("message-container", ix))
2001 .pt_2()
2002 .pl_2()
2003 .pr_2p5()
2004 .pb_4()
2005 .child(
2006 v_flex()
2007 .id(("user-message", ix))
2008 .bg(editor_bg_color)
2009 .rounded_lg()
2010 .shadow_md()
2011 .border_1()
2012 .border_color(colors.border)
2013 .hover(|hover| hover.border_color(colors.text_accent.opacity(0.5)))
2014 .child(
2015 v_flex()
2016 .p_2p5()
2017 .gap_1()
2018 .children(message_content)
2019 .when_some(editing_message_state, |this, state| {
2020 let focus_handle = state.editor.focus_handle(cx).clone();
2021
2022 this.child(
2023 h_flex()
2024 .w_full()
2025 .gap_1()
2026 .justify_between()
2027 .flex_wrap()
2028 .child(
2029 h_flex()
2030 .gap_1p5()
2031 .child(
2032 div()
2033 .opacity(0.8)
2034 .child(
2035 Icon::new(IconName::Warning)
2036 .size(IconSize::Indicator)
2037 .color(Color::Warning)
2038 ),
2039 )
2040 .child(
2041 Label::new("Editing will restart the thread from this point.")
2042 .color(Color::Muted)
2043 .size(LabelSize::XSmall),
2044 ),
2045 )
2046 .child(
2047 h_flex()
2048 .gap_0p5()
2049 .child(
2050 IconButton::new(
2051 "cancel-edit-message",
2052 IconName::Close,
2053 )
2054 .shape(ui::IconButtonShape::Square)
2055 .icon_color(Color::Error)
2056 .icon_size(IconSize::Small)
2057 .tooltip({
2058 let focus_handle = focus_handle.clone();
2059 move |window, cx| {
2060 Tooltip::for_action_in(
2061 "Cancel Edit",
2062 &menu::Cancel,
2063 &focus_handle,
2064 window,
2065 cx,
2066 )
2067 }
2068 })
2069 .on_click(cx.listener(Self::handle_cancel_click)),
2070 )
2071 .child(
2072 IconButton::new(
2073 "confirm-edit-message",
2074 IconName::Return,
2075 )
2076 .disabled(state.editor.read(cx).is_empty(cx))
2077 .shape(ui::IconButtonShape::Square)
2078 .icon_color(Color::Muted)
2079 .icon_size(IconSize::Small)
2080 .tooltip({
2081 let focus_handle = focus_handle.clone();
2082 move |window, cx| {
2083 Tooltip::for_action_in(
2084 "Regenerate",
2085 &menu::Confirm,
2086 &focus_handle,
2087 window,
2088 cx,
2089 )
2090 }
2091 })
2092 .on_click(
2093 cx.listener(Self::handle_regenerate_click),
2094 ),
2095 ),
2096 )
2097 )
2098 }),
2099 )
2100 .on_click(cx.listener({
2101 let message_segments = message.segments.clone();
2102 move |this, _, window, cx| {
2103 this.start_editing_message(
2104 message_id,
2105 &message_segments,
2106 &message_creases,
2107 window,
2108 cx,
2109 );
2110 }
2111 })),
2112 ),
2113 Role::Assistant => v_flex()
2114 .id(("message-container", ix))
2115 .px(RESPONSE_PADDING_X)
2116 .gap_2()
2117 .children(message_content)
2118 .when(has_tool_uses, |parent| {
2119 parent.children(tool_uses.into_iter().map(|tool_use| {
2120 self.render_tool_use(tool_use, window, workspace.clone(), cx)
2121 }))
2122 }),
2123 Role::System => div().id(("message-container", ix)).py_1().px_2().child(
2124 v_flex()
2125 .bg(colors.editor_background)
2126 .rounded_sm()
2127 .child(div().p_4().children(message_content)),
2128 ),
2129 };
2130
2131 let after_editing_message = self
2132 .editing_message
2133 .as_ref()
2134 .map_or(false, |(editing_message_id, _)| {
2135 message_id > *editing_message_id
2136 });
2137
2138 let panel_background = cx.theme().colors().panel_background;
2139
2140 let backdrop = div()
2141 .id("backdrop")
2142 .stop_mouse_events_except_scroll()
2143 .absolute()
2144 .inset_0()
2145 .size_full()
2146 .bg(panel_background)
2147 .opacity(0.8)
2148 .on_click(cx.listener(Self::handle_cancel_click));
2149
2150 v_flex()
2151 .w_full()
2152 .map(|parent| {
2153 if let Some(checkpoint) = checkpoint.filter(|_| !is_generating) {
2154 let mut is_pending = false;
2155 let mut error = None;
2156 if let Some(last_restore_checkpoint) =
2157 self.thread.read(cx).last_restore_checkpoint()
2158 {
2159 if last_restore_checkpoint.message_id() == message_id {
2160 match last_restore_checkpoint {
2161 LastRestoreCheckpoint::Pending { .. } => is_pending = true,
2162 LastRestoreCheckpoint::Error { error: err, .. } => {
2163 error = Some(err.clone());
2164 }
2165 }
2166 }
2167 }
2168
2169 let restore_checkpoint_button =
2170 Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
2171 .icon(if error.is_some() {
2172 IconName::XCircle
2173 } else {
2174 IconName::Undo
2175 })
2176 .icon_size(IconSize::XSmall)
2177 .icon_position(IconPosition::Start)
2178 .icon_color(if error.is_some() {
2179 Some(Color::Error)
2180 } else {
2181 None
2182 })
2183 .label_size(LabelSize::XSmall)
2184 .disabled(is_pending)
2185 .on_click(cx.listener(move |this, _, _window, cx| {
2186 this.thread.update(cx, |thread, cx| {
2187 thread
2188 .restore_checkpoint(checkpoint.clone(), cx)
2189 .detach_and_log_err(cx);
2190 });
2191 }));
2192
2193 let restore_checkpoint_button = if is_pending {
2194 restore_checkpoint_button
2195 .with_animation(
2196 ("pulsating-restore-checkpoint-button", ix),
2197 Animation::new(Duration::from_secs(2))
2198 .repeat()
2199 .with_easing(pulsating_between(0.6, 1.)),
2200 |label, delta| label.alpha(delta),
2201 )
2202 .into_any_element()
2203 } else if let Some(error) = error {
2204 restore_checkpoint_button
2205 .tooltip(Tooltip::text(error.to_string()))
2206 .into_any_element()
2207 } else {
2208 restore_checkpoint_button.into_any_element()
2209 };
2210
2211 parent.child(
2212 h_flex()
2213 .pt_2p5()
2214 .px_2p5()
2215 .w_full()
2216 .gap_1()
2217 .child(ui::Divider::horizontal())
2218 .child(restore_checkpoint_button)
2219 .child(ui::Divider::horizontal()),
2220 )
2221 } else {
2222 parent
2223 }
2224 })
2225 .when(is_first_message, |parent| {
2226 parent.child(self.render_rules_item(cx))
2227 })
2228 .child(styled_message)
2229 .when(is_generating && is_last_message, |this| {
2230 this.child(
2231 h_flex()
2232 .h_8()
2233 .mt_2()
2234 .mb_4()
2235 .ml_4()
2236 .py_1p5()
2237 .when_some(loading_dots, |this, loading_dots| this.child(loading_dots)),
2238 )
2239 })
2240 .when(show_feedback, move |parent| {
2241 parent.child(feedback_items).when_some(
2242 self.open_feedback_editors.get(&message_id),
2243 move |parent, feedback_editor| {
2244 let focus_handle = feedback_editor.focus_handle(cx);
2245 parent.child(
2246 v_flex()
2247 .key_context("AgentFeedbackMessageEditor")
2248 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
2249 this.open_feedback_editors.remove(&message_id);
2250 cx.notify();
2251 }))
2252 .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
2253 this.submit_feedback_message(message_id, cx);
2254 cx.notify();
2255 }))
2256 .on_action(cx.listener(Self::confirm_editing_message))
2257 .mb_2()
2258 .mx_4()
2259 .p_2()
2260 .rounded_md()
2261 .border_1()
2262 .border_color(cx.theme().colors().border)
2263 .bg(cx.theme().colors().editor_background)
2264 .child(feedback_editor.clone())
2265 .child(
2266 h_flex()
2267 .gap_1()
2268 .justify_end()
2269 .child(
2270 Button::new("dismiss-feedback-message", "Cancel")
2271 .label_size(LabelSize::Small)
2272 .key_binding(
2273 KeyBinding::for_action_in(
2274 &menu::Cancel,
2275 &focus_handle,
2276 window,
2277 cx,
2278 )
2279 .map(|kb| kb.size(rems_from_px(10.))),
2280 )
2281 .on_click(cx.listener(
2282 move |this, _, _window, cx| {
2283 this.open_feedback_editors
2284 .remove(&message_id);
2285 cx.notify();
2286 },
2287 )),
2288 )
2289 .child(
2290 Button::new(
2291 "submit-feedback-message",
2292 "Share Feedback",
2293 )
2294 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2295 .label_size(LabelSize::Small)
2296 .key_binding(
2297 KeyBinding::for_action_in(
2298 &menu::Confirm,
2299 &focus_handle,
2300 window,
2301 cx,
2302 )
2303 .map(|kb| kb.size(rems_from_px(10.))),
2304 )
2305 .on_click(
2306 cx.listener(move |this, _, _window, cx| {
2307 this.submit_feedback_message(message_id, cx);
2308 cx.notify()
2309 }),
2310 ),
2311 ),
2312 ),
2313 )
2314 },
2315 )
2316 })
2317 .when(after_editing_message, |parent| {
2318 // Backdrop to dim out the whole thread below the editing user message
2319 parent.relative().child(backdrop)
2320 })
2321 .into_any()
2322 }
2323
2324 fn render_message_content(
2325 &self,
2326 message_id: MessageId,
2327 rendered_message: &RenderedMessage,
2328 has_tool_uses: bool,
2329 workspace: WeakEntity<Workspace>,
2330 window: &Window,
2331 cx: &Context<Self>,
2332 ) -> impl IntoElement {
2333 let is_last_message = self.messages.last() == Some(&message_id);
2334 let is_generating = self.thread.read(cx).is_generating();
2335 let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2336 rendered_message
2337 .segments
2338 .iter()
2339 .enumerate()
2340 .next_back()
2341 .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2342 .map(|(index, _)| index)
2343 } else {
2344 None
2345 };
2346
2347 let message_role = self
2348 .thread
2349 .read(cx)
2350 .message(message_id)
2351 .map(|m| m.role)
2352 .unwrap_or(Role::User);
2353
2354 let is_assistant_message = message_role == Role::Assistant;
2355 let is_user_message = message_role == Role::User;
2356
2357 v_flex()
2358 .text_ui(cx)
2359 .gap_2()
2360 .when(is_user_message, |this| this.text_xs())
2361 .children(
2362 rendered_message.segments.iter().enumerate().map(
2363 |(index, segment)| match segment {
2364 RenderedMessageSegment::Thinking {
2365 content,
2366 scroll_handle,
2367 } => self
2368 .render_message_thinking_segment(
2369 message_id,
2370 index,
2371 content.clone(),
2372 &scroll_handle,
2373 Some(index) == pending_thinking_segment_index,
2374 window,
2375 cx,
2376 )
2377 .into_any_element(),
2378 RenderedMessageSegment::Text(markdown) => {
2379 let markdown_element = MarkdownElement::new(
2380 markdown.clone(),
2381 if is_user_message {
2382 let mut style = default_markdown_style(window, cx);
2383 let mut text_style = window.text_style();
2384 let theme_settings = ThemeSettings::get_global(cx);
2385
2386 let buffer_font = theme_settings.buffer_font.family.clone();
2387 let buffer_font_size = TextSize::Small.rems(cx);
2388
2389 text_style.refine(&TextStyleRefinement {
2390 font_family: Some(buffer_font),
2391 font_size: Some(buffer_font_size.into()),
2392 ..Default::default()
2393 });
2394
2395 style.base_text_style = text_style;
2396 style
2397 } else {
2398 default_markdown_style(window, cx)
2399 },
2400 );
2401
2402 let markdown_element = if is_assistant_message {
2403 markdown_element.code_block_renderer(
2404 markdown::CodeBlockRenderer::Custom {
2405 render: Arc::new({
2406 let workspace = workspace.clone();
2407 let active_thread = cx.entity();
2408 move |kind,
2409 parsed_markdown,
2410 range,
2411 metadata,
2412 window,
2413 cx| {
2414 render_markdown_code_block(
2415 message_id,
2416 range.start,
2417 kind,
2418 parsed_markdown,
2419 metadata,
2420 active_thread.clone(),
2421 workspace.clone(),
2422 window,
2423 cx,
2424 )
2425 }
2426 }),
2427 transform: Some(Arc::new({
2428 let active_thread = cx.entity();
2429
2430 move |element, range, _, _, cx| {
2431 let is_expanded = active_thread
2432 .read(cx)
2433 .is_codeblock_expanded(message_id, range.start);
2434
2435 if is_expanded {
2436 return element;
2437 }
2438
2439 element
2440 }
2441 })),
2442 },
2443 )
2444 } else {
2445 markdown_element.code_block_renderer(
2446 markdown::CodeBlockRenderer::Default {
2447 copy_button: false,
2448 copy_button_on_hover: false,
2449 border: true,
2450 },
2451 )
2452 };
2453
2454 div()
2455 .child(markdown_element.on_url_click({
2456 let workspace = self.workspace.clone();
2457 move |text, window, cx| {
2458 open_markdown_link(text, workspace.clone(), window, cx);
2459 }
2460 }))
2461 .into_any_element()
2462 }
2463 },
2464 ),
2465 )
2466 }
2467
2468 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2469 cx.theme().colors().border.opacity(0.5)
2470 }
2471
2472 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2473 cx.theme()
2474 .colors()
2475 .element_background
2476 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2477 }
2478
2479 fn render_message_thinking_segment(
2480 &self,
2481 message_id: MessageId,
2482 ix: usize,
2483 markdown: Entity<Markdown>,
2484 scroll_handle: &ScrollHandle,
2485 pending: bool,
2486 window: &Window,
2487 cx: &Context<Self>,
2488 ) -> impl IntoElement {
2489 let is_open = self
2490 .expanded_thinking_segments
2491 .get(&(message_id, ix))
2492 .copied()
2493 .unwrap_or_default();
2494
2495 let editor_bg = cx.theme().colors().panel_background;
2496
2497 div().map(|this| {
2498 if pending {
2499 this.v_flex()
2500 .mt_neg_2()
2501 .mb_1p5()
2502 .child(
2503 h_flex()
2504 .group("disclosure-header")
2505 .justify_between()
2506 .child(
2507 h_flex()
2508 .gap_1p5()
2509 .child(
2510 Icon::new(IconName::LightBulb)
2511 .size(IconSize::XSmall)
2512 .color(Color::Muted),
2513 )
2514 .child(AnimatedLabel::new("Thinking").size(LabelSize::Small)),
2515 )
2516 .child(
2517 h_flex()
2518 .gap_1()
2519 .child(
2520 div().visible_on_hover("disclosure-header").child(
2521 Disclosure::new("thinking-disclosure", is_open)
2522 .opened_icon(IconName::ChevronUp)
2523 .closed_icon(IconName::ChevronDown)
2524 .on_click(cx.listener({
2525 move |this, _event, _window, _cx| {
2526 let is_open = this
2527 .expanded_thinking_segments
2528 .entry((message_id, ix))
2529 .or_insert(false);
2530
2531 *is_open = !*is_open;
2532 }
2533 })),
2534 ),
2535 )
2536 .child({
2537 Icon::new(IconName::ArrowCircle)
2538 .color(Color::Accent)
2539 .size(IconSize::Small)
2540 .with_animation(
2541 "arrow-circle",
2542 Animation::new(Duration::from_secs(2)).repeat(),
2543 |icon, delta| {
2544 icon.transform(Transformation::rotate(
2545 percentage(delta),
2546 ))
2547 },
2548 )
2549 }),
2550 ),
2551 )
2552 .when(!is_open, |this| {
2553 let gradient_overlay = div()
2554 .rounded_b_lg()
2555 .h_full()
2556 .absolute()
2557 .w_full()
2558 .bottom_0()
2559 .left_0()
2560 .bg(linear_gradient(
2561 180.,
2562 linear_color_stop(editor_bg, 1.),
2563 linear_color_stop(editor_bg.opacity(0.2), 0.),
2564 ));
2565
2566 this.child(
2567 div()
2568 .relative()
2569 .bg(editor_bg)
2570 .rounded_b_lg()
2571 .mt_2()
2572 .pl_4()
2573 .child(
2574 div()
2575 .id(("thinking-content", ix))
2576 .max_h_20()
2577 .track_scroll(scroll_handle)
2578 .text_ui_sm(cx)
2579 .overflow_hidden()
2580 .child(
2581 MarkdownElement::new(
2582 markdown.clone(),
2583 default_markdown_style(window, cx),
2584 )
2585 .on_url_click({
2586 let workspace = self.workspace.clone();
2587 move |text, window, cx| {
2588 open_markdown_link(
2589 text,
2590 workspace.clone(),
2591 window,
2592 cx,
2593 );
2594 }
2595 }),
2596 ),
2597 )
2598 .child(gradient_overlay),
2599 )
2600 })
2601 .when(is_open, |this| {
2602 this.child(
2603 div()
2604 .id(("thinking-content", ix))
2605 .h_full()
2606 .bg(editor_bg)
2607 .text_ui_sm(cx)
2608 .child(
2609 MarkdownElement::new(
2610 markdown.clone(),
2611 default_markdown_style(window, cx),
2612 )
2613 .on_url_click({
2614 let workspace = self.workspace.clone();
2615 move |text, window, cx| {
2616 open_markdown_link(text, workspace.clone(), window, cx);
2617 }
2618 }),
2619 ),
2620 )
2621 })
2622 } else {
2623 this.v_flex()
2624 .mt_neg_2()
2625 .child(
2626 h_flex()
2627 .group("disclosure-header")
2628 .pr_1()
2629 .justify_between()
2630 .opacity(0.8)
2631 .hover(|style| style.opacity(1.))
2632 .child(
2633 h_flex()
2634 .gap_1p5()
2635 .child(
2636 Icon::new(IconName::LightBulb)
2637 .size(IconSize::XSmall)
2638 .color(Color::Muted),
2639 )
2640 .child(Label::new("Thought Process").size(LabelSize::Small)),
2641 )
2642 .child(
2643 div().visible_on_hover("disclosure-header").child(
2644 Disclosure::new("thinking-disclosure", is_open)
2645 .opened_icon(IconName::ChevronUp)
2646 .closed_icon(IconName::ChevronDown)
2647 .on_click(cx.listener({
2648 move |this, _event, _window, _cx| {
2649 let is_open = this
2650 .expanded_thinking_segments
2651 .entry((message_id, ix))
2652 .or_insert(false);
2653
2654 *is_open = !*is_open;
2655 }
2656 })),
2657 ),
2658 ),
2659 )
2660 .child(
2661 div()
2662 .id(("thinking-content", ix))
2663 .relative()
2664 .mt_1p5()
2665 .ml_1p5()
2666 .pl_2p5()
2667 .border_l_1()
2668 .border_color(cx.theme().colors().border_variant)
2669 .text_ui_sm(cx)
2670 .when(is_open, |this| {
2671 this.child(
2672 MarkdownElement::new(
2673 markdown.clone(),
2674 default_markdown_style(window, cx),
2675 )
2676 .on_url_click({
2677 let workspace = self.workspace.clone();
2678 move |text, window, cx| {
2679 open_markdown_link(text, workspace.clone(), window, cx);
2680 }
2681 }),
2682 )
2683 }),
2684 )
2685 }
2686 })
2687 }
2688
2689 fn render_tool_use(
2690 &self,
2691 tool_use: ToolUse,
2692 window: &mut Window,
2693 workspace: WeakEntity<Workspace>,
2694 cx: &mut Context<Self>,
2695 ) -> impl IntoElement + use<> {
2696 if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2697 return card.render(&tool_use.status, window, workspace, cx);
2698 }
2699
2700 let is_open = self
2701 .expanded_tool_uses
2702 .get(&tool_use.id)
2703 .copied()
2704 .unwrap_or_default();
2705
2706 let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2707
2708 let fs = self
2709 .workspace
2710 .upgrade()
2711 .map(|workspace| workspace.read(cx).app_state().fs.clone());
2712 let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2713 let needs_confirmation_tools = tool_use.needs_confirmation;
2714
2715 let status_icons = div().child(match &tool_use.status {
2716 ToolUseStatus::NeedsConfirmation => {
2717 let icon = Icon::new(IconName::Warning)
2718 .color(Color::Warning)
2719 .size(IconSize::Small);
2720 icon.into_any_element()
2721 }
2722 ToolUseStatus::Pending
2723 | ToolUseStatus::InputStillStreaming
2724 | ToolUseStatus::Running => {
2725 let icon = Icon::new(IconName::ArrowCircle)
2726 .color(Color::Accent)
2727 .size(IconSize::Small);
2728 icon.with_animation(
2729 "arrow-circle",
2730 Animation::new(Duration::from_secs(2)).repeat(),
2731 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2732 )
2733 .into_any_element()
2734 }
2735 ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2736 ToolUseStatus::Error(_) => {
2737 let icon = Icon::new(IconName::Close)
2738 .color(Color::Error)
2739 .size(IconSize::Small);
2740 icon.into_any_element()
2741 }
2742 });
2743
2744 let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2745 let results_content_container = || v_flex().p_2().gap_0p5();
2746
2747 let results_content = v_flex()
2748 .gap_1()
2749 .child(
2750 results_content_container()
2751 .child(
2752 Label::new("Input")
2753 .size(LabelSize::XSmall)
2754 .color(Color::Muted)
2755 .buffer_font(cx),
2756 )
2757 .child(
2758 div()
2759 .w_full()
2760 .text_ui_sm(cx)
2761 .children(rendered_tool_use.as_ref().map(|rendered| {
2762 MarkdownElement::new(
2763 rendered.input.clone(),
2764 tool_use_markdown_style(window, cx),
2765 )
2766 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2767 copy_button: false,
2768 copy_button_on_hover: false,
2769 border: false,
2770 })
2771 .on_url_click({
2772 let workspace = self.workspace.clone();
2773 move |text, window, cx| {
2774 open_markdown_link(text, workspace.clone(), window, cx);
2775 }
2776 })
2777 })),
2778 ),
2779 )
2780 .map(|container| match tool_use.status {
2781 ToolUseStatus::Finished(_) => container.child(
2782 results_content_container()
2783 .border_t_1()
2784 .border_color(self.tool_card_border_color(cx))
2785 .child(
2786 Label::new("Result")
2787 .size(LabelSize::XSmall)
2788 .color(Color::Muted)
2789 .buffer_font(cx),
2790 )
2791 .child(div().w_full().text_ui_sm(cx).children(
2792 rendered_tool_use.as_ref().map(|rendered| {
2793 MarkdownElement::new(
2794 rendered.output.clone(),
2795 tool_use_markdown_style(window, cx),
2796 )
2797 .code_block_renderer(markdown::CodeBlockRenderer::Default {
2798 copy_button: false,
2799 copy_button_on_hover: false,
2800 border: false,
2801 })
2802 .on_url_click({
2803 let workspace = self.workspace.clone();
2804 move |text, window, cx| {
2805 open_markdown_link(text, workspace.clone(), window, cx);
2806 }
2807 })
2808 .into_any_element()
2809 }),
2810 )),
2811 ),
2812 ToolUseStatus::InputStillStreaming | ToolUseStatus::Running => container.child(
2813 results_content_container()
2814 .border_t_1()
2815 .border_color(self.tool_card_border_color(cx))
2816 .child(
2817 h_flex()
2818 .gap_1()
2819 .child(
2820 Icon::new(IconName::ArrowCircle)
2821 .size(IconSize::Small)
2822 .color(Color::Accent)
2823 .with_animation(
2824 "arrow-circle",
2825 Animation::new(Duration::from_secs(2)).repeat(),
2826 |icon, delta| {
2827 icon.transform(Transformation::rotate(percentage(
2828 delta,
2829 )))
2830 },
2831 ),
2832 )
2833 .child(
2834 Label::new("Running…")
2835 .size(LabelSize::XSmall)
2836 .color(Color::Muted)
2837 .buffer_font(cx),
2838 ),
2839 ),
2840 ),
2841 ToolUseStatus::Error(_) => container.child(
2842 results_content_container()
2843 .border_t_1()
2844 .border_color(self.tool_card_border_color(cx))
2845 .child(
2846 Label::new("Error")
2847 .size(LabelSize::XSmall)
2848 .color(Color::Muted)
2849 .buffer_font(cx),
2850 )
2851 .child(
2852 div()
2853 .text_ui_sm(cx)
2854 .children(rendered_tool_use.as_ref().map(|rendered| {
2855 MarkdownElement::new(
2856 rendered.output.clone(),
2857 tool_use_markdown_style(window, cx),
2858 )
2859 .on_url_click({
2860 let workspace = self.workspace.clone();
2861 move |text, window, cx| {
2862 open_markdown_link(text, workspace.clone(), window, cx);
2863 }
2864 })
2865 .into_any_element()
2866 })),
2867 ),
2868 ),
2869 ToolUseStatus::Pending => container,
2870 ToolUseStatus::NeedsConfirmation => container.child(
2871 results_content_container()
2872 .border_t_1()
2873 .border_color(self.tool_card_border_color(cx))
2874 .child(
2875 Label::new("Asking Permission")
2876 .size(LabelSize::Small)
2877 .color(Color::Muted)
2878 .buffer_font(cx),
2879 ),
2880 ),
2881 });
2882
2883 let gradient_overlay = |color: Hsla| {
2884 div()
2885 .h_full()
2886 .absolute()
2887 .w_12()
2888 .bottom_0()
2889 .map(|element| {
2890 if is_status_finished {
2891 element.right_6()
2892 } else {
2893 element.right(px(44.))
2894 }
2895 })
2896 .bg(linear_gradient(
2897 90.,
2898 linear_color_stop(color, 1.),
2899 linear_color_stop(color.opacity(0.2), 0.),
2900 ))
2901 };
2902
2903 v_flex().gap_1().mb_2().map(|element| {
2904 if !needs_confirmation_tools {
2905 element.child(
2906 v_flex()
2907 .child(
2908 h_flex()
2909 .group("disclosure-header")
2910 .relative()
2911 .gap_1p5()
2912 .justify_between()
2913 .opacity(0.8)
2914 .hover(|style| style.opacity(1.))
2915 .when(!is_status_finished, |this| this.pr_2())
2916 .child(
2917 h_flex()
2918 .id("tool-label-container")
2919 .gap_1p5()
2920 .max_w_full()
2921 .overflow_x_scroll()
2922 .child(
2923 Icon::new(tool_use.icon)
2924 .size(IconSize::XSmall)
2925 .color(Color::Muted),
2926 )
2927 .child(
2928 h_flex().pr_8().text_size(rems(0.8125)).children(
2929 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| {
2930 open_markdown_link(text, workspace.clone(), window, cx);
2931 }}))
2932 ),
2933 ),
2934 )
2935 .child(
2936 h_flex()
2937 .gap_1()
2938 .child(
2939 div().visible_on_hover("disclosure-header").child(
2940 Disclosure::new("tool-use-disclosure", is_open)
2941 .opened_icon(IconName::ChevronUp)
2942 .closed_icon(IconName::ChevronDown)
2943 .on_click(cx.listener({
2944 let tool_use_id = tool_use.id.clone();
2945 move |this, _event, _window, _cx| {
2946 let is_open = this
2947 .expanded_tool_uses
2948 .entry(tool_use_id.clone())
2949 .or_insert(false);
2950
2951 *is_open = !*is_open;
2952 }
2953 })),
2954 ),
2955 )
2956 .child(status_icons),
2957 )
2958 .child(gradient_overlay(cx.theme().colors().panel_background)),
2959 )
2960 .map(|parent| {
2961 if !is_open {
2962 return parent;
2963 }
2964
2965 parent.child(
2966 v_flex()
2967 .mt_1()
2968 .border_1()
2969 .border_color(self.tool_card_border_color(cx))
2970 .bg(cx.theme().colors().editor_background)
2971 .rounded_lg()
2972 .child(results_content),
2973 )
2974 }),
2975 )
2976 } else {
2977 v_flex()
2978 .mb_2()
2979 .rounded_lg()
2980 .border_1()
2981 .border_color(self.tool_card_border_color(cx))
2982 .overflow_hidden()
2983 .child(
2984 h_flex()
2985 .group("disclosure-header")
2986 .relative()
2987 .justify_between()
2988 .py_1()
2989 .map(|element| {
2990 if is_status_finished {
2991 element.pl_2().pr_0p5()
2992 } else {
2993 element.px_2()
2994 }
2995 })
2996 .bg(self.tool_card_header_bg(cx))
2997 .map(|element| {
2998 if is_open {
2999 element.border_b_1().rounded_t_md()
3000 } else if needs_confirmation {
3001 element.rounded_t_md()
3002 } else {
3003 element.rounded_md()
3004 }
3005 })
3006 .border_color(self.tool_card_border_color(cx))
3007 .child(
3008 h_flex()
3009 .id("tool-label-container")
3010 .gap_1p5()
3011 .max_w_full()
3012 .overflow_x_scroll()
3013 .child(
3014 Icon::new(tool_use.icon)
3015 .size(IconSize::XSmall)
3016 .color(Color::Muted),
3017 )
3018 .child(
3019 h_flex().pr_8().text_ui_sm(cx).children(
3020 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| {
3021 open_markdown_link(text, workspace.clone(), window, cx);
3022 }}))
3023 ),
3024 ),
3025 )
3026 .child(
3027 h_flex()
3028 .gap_1()
3029 .child(
3030 div().visible_on_hover("disclosure-header").child(
3031 Disclosure::new("tool-use-disclosure", is_open)
3032 .opened_icon(IconName::ChevronUp)
3033 .closed_icon(IconName::ChevronDown)
3034 .on_click(cx.listener({
3035 let tool_use_id = tool_use.id.clone();
3036 move |this, _event, _window, _cx| {
3037 let is_open = this
3038 .expanded_tool_uses
3039 .entry(tool_use_id.clone())
3040 .or_insert(false);
3041
3042 *is_open = !*is_open;
3043 }
3044 })),
3045 ),
3046 )
3047 .child(status_icons),
3048 )
3049 .child(gradient_overlay(self.tool_card_header_bg(cx))),
3050 )
3051 .map(|parent| {
3052 if !is_open {
3053 return parent;
3054 }
3055
3056 parent.child(
3057 v_flex()
3058 .bg(cx.theme().colors().editor_background)
3059 .map(|element| {
3060 if needs_confirmation {
3061 element.rounded_none()
3062 } else {
3063 element.rounded_b_lg()
3064 }
3065 })
3066 .child(results_content),
3067 )
3068 })
3069 .when(needs_confirmation, |this| {
3070 this.child(
3071 h_flex()
3072 .py_1()
3073 .pl_2()
3074 .pr_1()
3075 .gap_1()
3076 .justify_between()
3077 .bg(cx.theme().colors().editor_background)
3078 .border_t_1()
3079 .border_color(self.tool_card_border_color(cx))
3080 .rounded_b_lg()
3081 .child(
3082 AnimatedLabel::new("Waiting for Confirmation").size(LabelSize::Small)
3083 )
3084 .child(
3085 h_flex()
3086 .gap_0p5()
3087 .child({
3088 let tool_id = tool_use.id.clone();
3089 Button::new(
3090 "always-allow-tool-action",
3091 "Always Allow",
3092 )
3093 .label_size(LabelSize::Small)
3094 .icon(IconName::CheckDouble)
3095 .icon_position(IconPosition::Start)
3096 .icon_size(IconSize::Small)
3097 .icon_color(Color::Success)
3098 .tooltip(move |window, cx| {
3099 Tooltip::with_meta(
3100 "Never ask for permission",
3101 None,
3102 "Restore the original behavior in your Agent Panel settings",
3103 window,
3104 cx,
3105 )
3106 })
3107 .on_click(cx.listener(
3108 move |this, event, window, cx| {
3109 if let Some(fs) = fs.clone() {
3110 update_settings_file::<AgentSettings>(
3111 fs.clone(),
3112 cx,
3113 |settings, _| {
3114 settings.set_always_allow_tool_actions(true);
3115 },
3116 );
3117 }
3118 this.handle_allow_tool(
3119 tool_id.clone(),
3120 event,
3121 window,
3122 cx,
3123 )
3124 },
3125 ))
3126 })
3127 .child(ui::Divider::vertical())
3128 .child({
3129 let tool_id = tool_use.id.clone();
3130 Button::new("allow-tool-action", "Allow")
3131 .label_size(LabelSize::Small)
3132 .icon(IconName::Check)
3133 .icon_position(IconPosition::Start)
3134 .icon_size(IconSize::Small)
3135 .icon_color(Color::Success)
3136 .on_click(cx.listener(
3137 move |this, event, window, cx| {
3138 this.handle_allow_tool(
3139 tool_id.clone(),
3140 event,
3141 window,
3142 cx,
3143 )
3144 },
3145 ))
3146 })
3147 .child({
3148 let tool_id = tool_use.id.clone();
3149 let tool_name: Arc<str> = tool_use.name.into();
3150 Button::new("deny-tool", "Deny")
3151 .label_size(LabelSize::Small)
3152 .icon(IconName::Close)
3153 .icon_position(IconPosition::Start)
3154 .icon_size(IconSize::Small)
3155 .icon_color(Color::Error)
3156 .on_click(cx.listener(
3157 move |this, event, window, cx| {
3158 this.handle_deny_tool(
3159 tool_id.clone(),
3160 tool_name.clone(),
3161 event,
3162 window,
3163 cx,
3164 )
3165 },
3166 ))
3167 }),
3168 ),
3169 )
3170 })
3171 }
3172 }).into_any_element()
3173 }
3174
3175 fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
3176 let project_context = self.thread.read(cx).project_context();
3177 let project_context = project_context.borrow();
3178 let Some(project_context) = project_context.as_ref() else {
3179 return div().into_any();
3180 };
3181
3182 let user_rules_text = if project_context.user_rules.is_empty() {
3183 None
3184 } else if project_context.user_rules.len() == 1 {
3185 let user_rules = &project_context.user_rules[0];
3186
3187 match user_rules.title.as_ref() {
3188 Some(title) => Some(format!("Using \"{title}\" user rule")),
3189 None => Some("Using user rule".into()),
3190 }
3191 } else {
3192 Some(format!(
3193 "Using {} user rules",
3194 project_context.user_rules.len()
3195 ))
3196 };
3197
3198 let first_user_rules_id = project_context
3199 .user_rules
3200 .first()
3201 .map(|user_rules| user_rules.uuid.0);
3202
3203 let rules_files = project_context
3204 .worktrees
3205 .iter()
3206 .filter_map(|worktree| worktree.rules_file.as_ref())
3207 .collect::<Vec<_>>();
3208
3209 let rules_file_text = match rules_files.as_slice() {
3210 &[] => None,
3211 &[rules_file] => Some(format!(
3212 "Using project {:?} file",
3213 rules_file.path_in_worktree
3214 )),
3215 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3216 };
3217
3218 if user_rules_text.is_none() && rules_file_text.is_none() {
3219 return div().into_any();
3220 }
3221
3222 v_flex()
3223 .pt_2()
3224 .px_2p5()
3225 .gap_1()
3226 .when_some(user_rules_text, |parent, user_rules_text| {
3227 parent.child(
3228 h_flex()
3229 .w_full()
3230 .child(
3231 Icon::new(RULES_ICON)
3232 .size(IconSize::XSmall)
3233 .color(Color::Disabled),
3234 )
3235 .child(
3236 Label::new(user_rules_text)
3237 .size(LabelSize::XSmall)
3238 .color(Color::Muted)
3239 .truncate()
3240 .buffer_font(cx)
3241 .ml_1p5()
3242 .mr_0p5(),
3243 )
3244 .child(
3245 IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3246 .shape(ui::IconButtonShape::Square)
3247 .icon_size(IconSize::XSmall)
3248 .icon_color(Color::Ignored)
3249 // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary` keybinding
3250 .tooltip(Tooltip::text("View User Rules"))
3251 .on_click(move |_event, window, cx| {
3252 window.dispatch_action(
3253 Box::new(OpenRulesLibrary {
3254 prompt_to_select: first_user_rules_id,
3255 }),
3256 cx,
3257 )
3258 }),
3259 ),
3260 )
3261 })
3262 .when_some(rules_file_text, |parent, rules_file_text| {
3263 parent.child(
3264 h_flex()
3265 .w_full()
3266 .child(
3267 Icon::new(IconName::File)
3268 .size(IconSize::XSmall)
3269 .color(Color::Disabled),
3270 )
3271 .child(
3272 Label::new(rules_file_text)
3273 .size(LabelSize::XSmall)
3274 .color(Color::Muted)
3275 .buffer_font(cx)
3276 .ml_1p5()
3277 .mr_0p5(),
3278 )
3279 .child(
3280 IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3281 .shape(ui::IconButtonShape::Square)
3282 .icon_size(IconSize::XSmall)
3283 .icon_color(Color::Ignored)
3284 .on_click(cx.listener(Self::handle_open_rules))
3285 .tooltip(Tooltip::text("View Rules")),
3286 ),
3287 )
3288 })
3289 .into_any()
3290 }
3291
3292 fn handle_allow_tool(
3293 &mut self,
3294 tool_use_id: LanguageModelToolUseId,
3295 _: &ClickEvent,
3296 window: &mut Window,
3297 cx: &mut Context<Self>,
3298 ) {
3299 if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3300 .thread
3301 .read(cx)
3302 .pending_tool(&tool_use_id)
3303 .map(|tool_use| tool_use.status.clone())
3304 {
3305 self.thread.update(cx, |thread, cx| {
3306 if let Some(configured) = thread.get_or_init_configured_model(cx) {
3307 thread.run_tool(
3308 c.tool_use_id.clone(),
3309 c.ui_text.clone(),
3310 c.input.clone(),
3311 c.request.clone(),
3312 c.tool.clone(),
3313 configured.model,
3314 Some(window.window_handle()),
3315 cx,
3316 );
3317 }
3318 });
3319 }
3320 }
3321
3322 fn handle_deny_tool(
3323 &mut self,
3324 tool_use_id: LanguageModelToolUseId,
3325 tool_name: Arc<str>,
3326 _: &ClickEvent,
3327 window: &mut Window,
3328 cx: &mut Context<Self>,
3329 ) {
3330 let window_handle = window.window_handle();
3331 self.thread.update(cx, |thread, cx| {
3332 thread.deny_tool_use(tool_use_id, tool_name, Some(window_handle), cx);
3333 });
3334 }
3335
3336 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3337 let project_context = self.thread.read(cx).project_context();
3338 let project_context = project_context.borrow();
3339 let Some(project_context) = project_context.as_ref() else {
3340 return;
3341 };
3342
3343 let project_entry_ids = project_context
3344 .worktrees
3345 .iter()
3346 .flat_map(|worktree| worktree.rules_file.as_ref())
3347 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
3348 .collect::<Vec<_>>();
3349
3350 self.workspace
3351 .update(cx, move |workspace, cx| {
3352 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3353 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3354 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3355 let project = workspace.project().read(cx);
3356 let project_paths = project_entry_ids
3357 .into_iter()
3358 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
3359 .collect::<Vec<_>>();
3360 for project_path in project_paths {
3361 workspace
3362 .open_path(project_path, None, true, window, cx)
3363 .detach_and_log_err(cx);
3364 }
3365 })
3366 .ok();
3367 }
3368
3369 fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3370 for window in self.notifications.drain(..) {
3371 window
3372 .update(cx, |_, window, _| {
3373 window.remove_window();
3374 })
3375 .ok();
3376
3377 self.notification_subscriptions.remove(&window);
3378 }
3379 }
3380
3381 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3382 if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3383 return None;
3384 }
3385
3386 Some(
3387 div()
3388 .occlude()
3389 .id("active-thread-scrollbar")
3390 .on_mouse_move(cx.listener(|_, _, _, cx| {
3391 cx.notify();
3392 cx.stop_propagation()
3393 }))
3394 .on_hover(|_, _, cx| {
3395 cx.stop_propagation();
3396 })
3397 .on_any_mouse_down(|_, _, cx| {
3398 cx.stop_propagation();
3399 })
3400 .on_mouse_up(
3401 MouseButton::Left,
3402 cx.listener(|_, _, _, cx| {
3403 cx.stop_propagation();
3404 }),
3405 )
3406 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3407 cx.notify();
3408 }))
3409 .h_full()
3410 .absolute()
3411 .right_1()
3412 .top_1()
3413 .bottom_0()
3414 .w(px(12.))
3415 .cursor_default()
3416 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3417 )
3418 }
3419
3420 fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3421 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3422 self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3423 cx.background_executor()
3424 .timer(SCROLLBAR_SHOW_INTERVAL)
3425 .await;
3426 thread
3427 .update(cx, |thread, cx| {
3428 if !thread.scrollbar_state.is_dragging() {
3429 thread.show_scrollbar = false;
3430 cx.notify();
3431 }
3432 })
3433 .log_err();
3434 }))
3435 }
3436
3437 pub fn is_codeblock_expanded(&self, message_id: MessageId, ix: usize) -> bool {
3438 self.expanded_code_blocks
3439 .get(&(message_id, ix))
3440 .copied()
3441 .unwrap_or(true)
3442 }
3443
3444 pub fn toggle_codeblock_expanded(&mut self, message_id: MessageId, ix: usize) {
3445 let is_expanded = self
3446 .expanded_code_blocks
3447 .entry((message_id, ix))
3448 .or_insert(true);
3449 *is_expanded = !*is_expanded;
3450 }
3451
3452 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3453 self.list_state.reset(self.messages.len());
3454 cx.notify();
3455 }
3456}
3457
3458pub enum ActiveThreadEvent {
3459 EditingMessageTokenCountChanged,
3460}
3461
3462impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3463
3464impl Render for ActiveThread {
3465 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3466 v_flex()
3467 .size_full()
3468 .relative()
3469 .bg(cx.theme().colors().panel_background)
3470 .on_mouse_move(cx.listener(|this, _, _, cx| {
3471 this.show_scrollbar = true;
3472 this.hide_scrollbar_later(cx);
3473 cx.notify();
3474 }))
3475 .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3476 this.show_scrollbar = true;
3477 this.hide_scrollbar_later(cx);
3478 cx.notify();
3479 }))
3480 .on_mouse_up(
3481 MouseButton::Left,
3482 cx.listener(|this, _, _, cx| {
3483 this.hide_scrollbar_later(cx);
3484 }),
3485 )
3486 .child(list(self.list_state.clone()).flex_grow())
3487 .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3488 this.child(scrollbar)
3489 })
3490 }
3491}
3492
3493pub(crate) fn open_active_thread_as_markdown(
3494 thread: Entity<Thread>,
3495 workspace: Entity<Workspace>,
3496 window: &mut Window,
3497 cx: &mut App,
3498) -> Task<anyhow::Result<()>> {
3499 let markdown_language_task = workspace
3500 .read(cx)
3501 .app_state()
3502 .languages
3503 .language_for_name("Markdown");
3504
3505 window.spawn(cx, async move |cx| {
3506 let markdown_language = markdown_language_task.await?;
3507
3508 workspace.update_in(cx, |workspace, window, cx| {
3509 let thread = thread.read(cx);
3510 let markdown = thread.to_markdown(cx)?;
3511 let thread_summary = thread.summary().or_default().to_string();
3512
3513 let project = workspace.project().clone();
3514
3515 if !project.read(cx).is_local() {
3516 anyhow::bail!("failed to open active thread as markdown in remote project");
3517 }
3518
3519 let buffer = project.update(cx, |project, cx| {
3520 project.create_local_buffer(&markdown, Some(markdown_language), cx)
3521 });
3522 let buffer =
3523 cx.new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone()));
3524
3525 workspace.add_item_to_active_pane(
3526 Box::new(cx.new(|cx| {
3527 let mut editor =
3528 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3529 editor.set_breadcrumb_header(thread_summary);
3530 editor
3531 })),
3532 None,
3533 true,
3534 window,
3535 cx,
3536 );
3537
3538 anyhow::Ok(())
3539 })??;
3540 anyhow::Ok(())
3541 })
3542}
3543
3544pub(crate) fn open_context(
3545 context: &AgentContextHandle,
3546 workspace: Entity<Workspace>,
3547 window: &mut Window,
3548 cx: &mut App,
3549) {
3550 match context {
3551 AgentContextHandle::File(file_context) => {
3552 if let Some(project_path) = file_context.project_path(cx) {
3553 workspace.update(cx, |workspace, cx| {
3554 workspace
3555 .open_path(project_path, None, true, window, cx)
3556 .detach_and_log_err(cx);
3557 });
3558 }
3559 }
3560
3561 AgentContextHandle::Directory(directory_context) => {
3562 let entry_id = directory_context.entry_id;
3563 workspace.update(cx, |workspace, cx| {
3564 workspace.project().update(cx, |_project, cx| {
3565 cx.emit(project::Event::RevealInProjectPanel(entry_id));
3566 })
3567 })
3568 }
3569
3570 AgentContextHandle::Symbol(symbol_context) => {
3571 let buffer = symbol_context.buffer.read(cx);
3572 if let Some(project_path) = buffer.project_path(cx) {
3573 let snapshot = buffer.snapshot();
3574 let target_position = symbol_context.range.start.to_point(&snapshot);
3575 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3576 .detach();
3577 }
3578 }
3579
3580 AgentContextHandle::Selection(selection_context) => {
3581 let buffer = selection_context.buffer.read(cx);
3582 if let Some(project_path) = buffer.project_path(cx) {
3583 let snapshot = buffer.snapshot();
3584 let target_position = selection_context.range.start.to_point(&snapshot);
3585
3586 open_editor_at_position(project_path, target_position, &workspace, window, cx)
3587 .detach();
3588 }
3589 }
3590
3591 AgentContextHandle::FetchedUrl(fetched_url_context) => {
3592 cx.open_url(&fetched_url_context.url);
3593 }
3594
3595 AgentContextHandle::Thread(thread_context) => workspace.update(cx, |workspace, cx| {
3596 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3597 panel.update(cx, |panel, cx| {
3598 panel.open_thread(thread_context.thread.clone(), window, cx);
3599 });
3600 }
3601 }),
3602
3603 AgentContextHandle::TextThread(text_thread_context) => {
3604 workspace.update(cx, |workspace, cx| {
3605 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3606 panel.update(cx, |panel, cx| {
3607 panel.open_prompt_editor(text_thread_context.context.clone(), window, cx)
3608 });
3609 }
3610 })
3611 }
3612
3613 AgentContextHandle::Rules(rules_context) => window.dispatch_action(
3614 Box::new(OpenRulesLibrary {
3615 prompt_to_select: Some(rules_context.prompt_id.0),
3616 }),
3617 cx,
3618 ),
3619
3620 AgentContextHandle::Image(_) => {}
3621 }
3622}
3623
3624fn open_editor_at_position(
3625 project_path: project::ProjectPath,
3626 target_position: Point,
3627 workspace: &Entity<Workspace>,
3628 window: &mut Window,
3629 cx: &mut App,
3630) -> Task<()> {
3631 let open_task = workspace.update(cx, |workspace, cx| {
3632 workspace.open_path(project_path, None, true, window, cx)
3633 });
3634 window.spawn(cx, async move |cx| {
3635 if let Some(active_editor) = open_task
3636 .await
3637 .log_err()
3638 .and_then(|item| item.downcast::<Editor>())
3639 {
3640 active_editor
3641 .downgrade()
3642 .update_in(cx, |editor, window, cx| {
3643 editor.go_to_singleton_buffer_point(target_position, window, cx);
3644 })
3645 .log_err();
3646 }
3647 })
3648}
3649
3650#[cfg(test)]
3651mod tests {
3652 use assistant_tool::{ToolRegistry, ToolWorkingSet};
3653 use editor::EditorSettings;
3654 use fs::FakeFs;
3655 use gpui::{AppContext, TestAppContext, VisualTestContext};
3656 use language_model::{LanguageModel, fake_provider::FakeLanguageModel};
3657 use project::Project;
3658 use prompt_store::PromptBuilder;
3659 use serde_json::json;
3660 use settings::SettingsStore;
3661 use util::path;
3662 use workspace::CollaboratorId;
3663
3664 use crate::{ContextLoadResult, thread_store};
3665
3666 use super::*;
3667
3668 #[gpui::test]
3669 async fn test_agent_is_unfollowed_after_cancelling_completion(cx: &mut TestAppContext) {
3670 init_test_settings(cx);
3671
3672 let project = create_test_project(
3673 cx,
3674 json!({"code.rs": "fn main() {\n println!(\"Hello, world!\");\n}"}),
3675 )
3676 .await;
3677
3678 let (cx, _active_thread, workspace, thread, model) =
3679 setup_test_environment(cx, project.clone()).await;
3680
3681 // Insert user message without any context (empty context vector)
3682 thread.update(cx, |thread, cx| {
3683 thread.insert_user_message(
3684 "What is the best way to learn Rust?",
3685 ContextLoadResult::default(),
3686 None,
3687 vec![],
3688 cx,
3689 );
3690 });
3691
3692 // Stream response to user message
3693 thread.update(cx, |thread, cx| {
3694 let request = thread.to_completion_request(model.clone(), cx);
3695 thread.stream_completion(request, model, cx.active_window(), cx)
3696 });
3697 // Follow the agent
3698 cx.update(|window, cx| {
3699 workspace.update(cx, |workspace, cx| {
3700 workspace.follow(CollaboratorId::Agent, window, cx);
3701 })
3702 });
3703 assert!(cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3704
3705 // Cancel the current completion
3706 thread.update(cx, |thread, cx| {
3707 thread.cancel_last_completion(cx.active_window(), cx)
3708 });
3709
3710 cx.executor().run_until_parked();
3711
3712 // No longer following the agent
3713 assert!(!cx.read(|cx| workspace.read(cx).is_being_followed(CollaboratorId::Agent)));
3714 }
3715
3716 fn init_test_settings(cx: &mut TestAppContext) {
3717 cx.update(|cx| {
3718 let settings_store = SettingsStore::test(cx);
3719 cx.set_global(settings_store);
3720 language::init(cx);
3721 Project::init_settings(cx);
3722 AgentSettings::register(cx);
3723 prompt_store::init(cx);
3724 thread_store::init(cx);
3725 workspace::init_settings(cx);
3726 language_model::init_settings(cx);
3727 ThemeSettings::register(cx);
3728 EditorSettings::register(cx);
3729 ToolRegistry::default_global(cx);
3730 });
3731 }
3732
3733 // Helper to create a test project with test files
3734 async fn create_test_project(
3735 cx: &mut TestAppContext,
3736 files: serde_json::Value,
3737 ) -> Entity<Project> {
3738 let fs = FakeFs::new(cx.executor());
3739 fs.insert_tree(path!("/test"), files).await;
3740 Project::test(fs, [path!("/test").as_ref()], cx).await
3741 }
3742
3743 async fn setup_test_environment(
3744 cx: &mut TestAppContext,
3745 project: Entity<Project>,
3746 ) -> (
3747 &mut VisualTestContext,
3748 Entity<ActiveThread>,
3749 Entity<Workspace>,
3750 Entity<Thread>,
3751 Arc<dyn LanguageModel>,
3752 ) {
3753 let (workspace, cx) =
3754 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3755
3756 let thread_store = cx
3757 .update(|_, cx| {
3758 ThreadStore::load(
3759 project.clone(),
3760 cx.new(|_| ToolWorkingSet::default()),
3761 None,
3762 Arc::new(PromptBuilder::new(None).unwrap()),
3763 cx,
3764 )
3765 })
3766 .await
3767 .unwrap();
3768
3769 let text_thread_store = cx
3770 .update(|_, cx| {
3771 TextThreadStore::new(
3772 project.clone(),
3773 Arc::new(PromptBuilder::new(None).unwrap()),
3774 Default::default(),
3775 cx,
3776 )
3777 })
3778 .await
3779 .unwrap();
3780
3781 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
3782 let context_store =
3783 cx.new(|_cx| ContextStore::new(project.downgrade(), Some(thread_store.downgrade())));
3784
3785 let model = FakeLanguageModel::default();
3786 let model: Arc<dyn LanguageModel> = Arc::new(model);
3787
3788 let language_registry = LanguageRegistry::new(cx.executor());
3789 let language_registry = Arc::new(language_registry);
3790
3791 let active_thread = cx.update(|window, cx| {
3792 cx.new(|cx| {
3793 ActiveThread::new(
3794 thread.clone(),
3795 thread_store.clone(),
3796 text_thread_store,
3797 context_store.clone(),
3798 language_registry.clone(),
3799 workspace.downgrade(),
3800 window,
3801 cx,
3802 )
3803 })
3804 });
3805
3806 (cx, active_thread, workspace, thread, model)
3807 }
3808}