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