1use std::collections::BTreeMap;
2use std::rc::Rc;
3use std::sync::Arc;
4
5use crate::agent_model_selector::AgentModelSelector;
6use crate::context::{AgentContextKey, ContextCreasesAddon, ContextLoadResult, load_context};
7use crate::tool_compatibility::{IncompatibleToolsState, IncompatibleToolsTooltip};
8use crate::ui::{
9 MaxModeTooltip,
10 preview::{AgentPreview, UsageCallout},
11};
12use agent_settings::{AgentSettings, CompletionMode};
13use assistant_context_editor::language_model_selector::ToggleModelSelector;
14use buffer_diff::BufferDiff;
15use client::UserStore;
16use collections::{HashMap, HashSet};
17use editor::actions::{MoveUp, Paste};
18use editor::{
19 AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorEvent,
20 EditorMode, EditorStyle, MultiBuffer,
21};
22use file_icons::FileIcons;
23use fs::Fs;
24use futures::future::Shared;
25use futures::{FutureExt as _, future};
26use gpui::{
27 Animation, AnimationExt, App, Entity, EventEmitter, Focusable, Subscription, Task, TextStyle,
28 WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
29};
30use language::{Buffer, Language, Point};
31use language_model::{
32 ConfiguredModel, LanguageModelRequestMessage, MessageContent, RequestUsage,
33 ZED_CLOUD_PROVIDER_ID,
34};
35use multi_buffer;
36use project::Project;
37use prompt_store::PromptStore;
38use proto::Plan;
39use settings::Settings;
40use std::time::Duration;
41use theme::ThemeSettings;
42use ui::{
43 Callout, Disclosure, Divider, DividerColor, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*,
44};
45use util::{ResultExt as _, maybe};
46use workspace::{CollaboratorId, Workspace};
47use zed_llm_client::CompletionIntent;
48
49use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider, crease_for_mention};
50use crate::context_store::ContextStore;
51use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
52use crate::profile_selector::ProfileSelector;
53use crate::thread::{MessageCrease, Thread, TokenUsageRatio};
54use crate::thread_store::{TextThreadStore, ThreadStore};
55use crate::{
56 ActiveThread, AgentDiffPane, Chat, ChatWithFollow, ExpandMessageEditor, Follow, KeepAll,
57 ModelUsageContext, NewThread, OpenAgentDiff, RejectAll, RemoveAllContext, ToggleBurnMode,
58 ToggleContextPicker, ToggleProfileSelector, register_agent_preview,
59};
60
61#[derive(RegisterComponent)]
62pub struct MessageEditor {
63 thread: Entity<Thread>,
64 incompatible_tools_state: Entity<IncompatibleToolsState>,
65 editor: Entity<Editor>,
66 workspace: WeakEntity<Workspace>,
67 project: Entity<Project>,
68 user_store: Entity<UserStore>,
69 context_store: Entity<ContextStore>,
70 prompt_store: Option<Entity<PromptStore>>,
71 context_strip: Entity<ContextStrip>,
72 context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
73 model_selector: Entity<AgentModelSelector>,
74 last_loaded_context: Option<ContextLoadResult>,
75 load_context_task: Option<Shared<Task<()>>>,
76 profile_selector: Entity<ProfileSelector>,
77 edits_expanded: bool,
78 editor_is_expanded: bool,
79 last_estimated_token_count: Option<u64>,
80 update_token_count_task: Option<Task<()>>,
81 _subscriptions: Vec<Subscription>,
82}
83
84const MIN_EDITOR_LINES: usize = 4;
85const MAX_EDITOR_LINES: usize = 8;
86
87pub(crate) fn create_editor(
88 workspace: WeakEntity<Workspace>,
89 context_store: WeakEntity<ContextStore>,
90 thread_store: WeakEntity<ThreadStore>,
91 text_thread_store: WeakEntity<TextThreadStore>,
92 window: &mut Window,
93 cx: &mut App,
94) -> Entity<Editor> {
95 let language = Language::new(
96 language::LanguageConfig {
97 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
98 ..Default::default()
99 },
100 None,
101 );
102
103 let editor = cx.new(|cx| {
104 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
105 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
106 let mut editor = Editor::new(
107 editor::EditorMode::AutoHeight {
108 min_lines: MIN_EDITOR_LINES,
109 max_lines: MAX_EDITOR_LINES,
110 },
111 buffer,
112 None,
113 window,
114 cx,
115 );
116 editor.set_placeholder_text("Message the agent – @ to include context", cx);
117 editor.set_show_indent_guides(false, cx);
118 editor.set_soft_wrap();
119 editor.set_use_modal_editing(true);
120 editor.set_context_menu_options(ContextMenuOptions {
121 min_entries_visible: 12,
122 max_entries_visible: 12,
123 placement: Some(ContextMenuPlacement::Above),
124 });
125 editor.register_addon(ContextCreasesAddon::new());
126 editor
127 });
128
129 let editor_entity = editor.downgrade();
130 editor.update(cx, |editor, _| {
131 editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
132 workspace,
133 context_store,
134 Some(thread_store),
135 Some(text_thread_store),
136 editor_entity,
137 None,
138 ))));
139 });
140 editor
141}
142
143impl MessageEditor {
144 pub fn new(
145 fs: Arc<dyn Fs>,
146 workspace: WeakEntity<Workspace>,
147 user_store: Entity<UserStore>,
148 context_store: Entity<ContextStore>,
149 prompt_store: Option<Entity<PromptStore>>,
150 thread_store: WeakEntity<ThreadStore>,
151 text_thread_store: WeakEntity<TextThreadStore>,
152 thread: Entity<Thread>,
153 window: &mut Window,
154 cx: &mut Context<Self>,
155 ) -> Self {
156 let context_picker_menu_handle = PopoverMenuHandle::default();
157 let model_selector_menu_handle = PopoverMenuHandle::default();
158
159 let editor = create_editor(
160 workspace.clone(),
161 context_store.downgrade(),
162 thread_store.clone(),
163 text_thread_store.clone(),
164 window,
165 cx,
166 );
167
168 let context_strip = cx.new(|cx| {
169 ContextStrip::new(
170 context_store.clone(),
171 workspace.clone(),
172 Some(thread_store.clone()),
173 Some(text_thread_store.clone()),
174 context_picker_menu_handle.clone(),
175 SuggestContextKind::File,
176 ModelUsageContext::Thread(thread.clone()),
177 window,
178 cx,
179 )
180 });
181
182 let incompatible_tools = cx.new(|cx| IncompatibleToolsState::new(thread.clone(), cx));
183
184 let subscriptions = vec![
185 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
186 cx.subscribe(&editor, |this, _, event, cx| match event {
187 EditorEvent::BufferEdited => this.handle_message_changed(cx),
188 _ => {}
189 }),
190 cx.observe(&context_store, |this, _, cx| {
191 // When context changes, reload it for token counting.
192 let _ = this.reload_context(cx);
193 }),
194 cx.observe(&thread.read(cx).action_log().clone(), |_, _, cx| {
195 cx.notify()
196 }),
197 ];
198
199 let model_selector = cx.new(|cx| {
200 AgentModelSelector::new(
201 fs.clone(),
202 model_selector_menu_handle,
203 editor.focus_handle(cx),
204 ModelUsageContext::Thread(thread.clone()),
205 window,
206 cx,
207 )
208 });
209
210 let profile_selector =
211 cx.new(|cx| ProfileSelector::new(fs, thread.clone(), editor.focus_handle(cx), cx));
212
213 Self {
214 editor: editor.clone(),
215 project: thread.read(cx).project().clone(),
216 user_store,
217 thread,
218 incompatible_tools_state: incompatible_tools.clone(),
219 workspace,
220 context_store,
221 prompt_store,
222 context_strip,
223 context_picker_menu_handle,
224 load_context_task: None,
225 last_loaded_context: None,
226 model_selector,
227 edits_expanded: false,
228 editor_is_expanded: false,
229 profile_selector,
230 last_estimated_token_count: None,
231 update_token_count_task: None,
232 _subscriptions: subscriptions,
233 }
234 }
235
236 pub fn context_store(&self) -> &Entity<ContextStore> {
237 &self.context_store
238 }
239
240 pub fn expand_message_editor(
241 &mut self,
242 _: &ExpandMessageEditor,
243 _window: &mut Window,
244 cx: &mut Context<Self>,
245 ) {
246 self.set_editor_is_expanded(!self.editor_is_expanded, cx);
247 }
248
249 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
250 self.editor_is_expanded = is_expanded;
251 self.editor.update(cx, |editor, _| {
252 if self.editor_is_expanded {
253 editor.set_mode(EditorMode::Full {
254 scale_ui_elements_with_buffer_font_size: false,
255 show_active_line_background: false,
256 sized_by_content: false,
257 })
258 } else {
259 editor.set_mode(EditorMode::AutoHeight {
260 min_lines: MIN_EDITOR_LINES,
261 max_lines: MAX_EDITOR_LINES,
262 })
263 }
264 });
265 cx.notify();
266 }
267
268 fn toggle_context_picker(
269 &mut self,
270 _: &ToggleContextPicker,
271 window: &mut Window,
272 cx: &mut Context<Self>,
273 ) {
274 self.context_picker_menu_handle.toggle(window, cx);
275 }
276
277 pub fn remove_all_context(
278 &mut self,
279 _: &RemoveAllContext,
280 _window: &mut Window,
281 cx: &mut Context<Self>,
282 ) {
283 self.context_store.update(cx, |store, cx| store.clear(cx));
284 cx.notify();
285 }
286
287 fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
288 if self.is_editor_empty(cx) {
289 return;
290 }
291
292 self.thread.update(cx, |thread, cx| {
293 thread.cancel_editing(cx);
294 });
295
296 if self.thread.read(cx).is_generating() {
297 self.stop_current_and_send_new_message(window, cx);
298 return;
299 }
300
301 self.set_editor_is_expanded(false, cx);
302 self.send_to_model(window, cx);
303
304 cx.emit(MessageEditorEvent::ScrollThreadToBottom);
305 cx.notify();
306 }
307
308 fn chat_with_follow(
309 &mut self,
310 _: &ChatWithFollow,
311 window: &mut Window,
312 cx: &mut Context<Self>,
313 ) {
314 self.workspace
315 .update(cx, |this, cx| {
316 this.follow(CollaboratorId::Agent, window, cx)
317 })
318 .log_err();
319
320 self.chat(&Chat, window, cx);
321 }
322
323 fn is_editor_empty(&self, cx: &App) -> bool {
324 self.editor.read(cx).text(cx).trim().is_empty()
325 }
326
327 pub fn is_editor_fully_empty(&self, cx: &App) -> bool {
328 self.editor.read(cx).is_empty(cx)
329 }
330
331 fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
332 let Some(ConfiguredModel { model, provider }) = self
333 .thread
334 .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
335 else {
336 return;
337 };
338
339 if provider.must_accept_terms(cx) {
340 cx.notify();
341 return;
342 }
343
344 let (user_message, user_message_creases) = self.editor.update(cx, |editor, cx| {
345 let creases = extract_message_creases(editor, cx);
346 let text = editor.text(cx);
347 editor.clear(window, cx);
348 (text, creases)
349 });
350
351 self.last_estimated_token_count.take();
352 cx.emit(MessageEditorEvent::EstimatedTokenCount);
353
354 let thread = self.thread.clone();
355 let git_store = self.project.read(cx).git_store().clone();
356 let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
357 let context_task = self.reload_context(cx);
358 let window_handle = window.window_handle();
359
360 cx.spawn(async move |_this, cx| {
361 let (checkpoint, loaded_context) = future::join(checkpoint, context_task).await;
362 let loaded_context = loaded_context.unwrap_or_default();
363
364 thread
365 .update(cx, |thread, cx| {
366 thread.insert_user_message(
367 user_message,
368 loaded_context,
369 checkpoint.ok(),
370 user_message_creases,
371 cx,
372 );
373 })
374 .log_err();
375
376 thread
377 .update(cx, |thread, cx| {
378 thread.advance_prompt_id();
379 thread.send_to_model(
380 model,
381 CompletionIntent::UserPrompt,
382 Some(window_handle),
383 cx,
384 );
385 })
386 .log_err();
387 })
388 .detach();
389 }
390
391 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
392 self.thread.update(cx, |thread, cx| {
393 thread.cancel_editing(cx);
394 });
395
396 let cancelled = self.thread.update(cx, |thread, cx| {
397 thread.cancel_last_completion(Some(window.window_handle()), cx)
398 });
399
400 if cancelled {
401 self.set_editor_is_expanded(false, cx);
402 self.send_to_model(window, cx);
403 }
404 }
405
406 fn handle_context_strip_event(
407 &mut self,
408 _context_strip: &Entity<ContextStrip>,
409 event: &ContextStripEvent,
410 window: &mut Window,
411 cx: &mut Context<Self>,
412 ) {
413 match event {
414 ContextStripEvent::PickerDismissed
415 | ContextStripEvent::BlurredEmpty
416 | ContextStripEvent::BlurredDown => {
417 let editor_focus_handle = self.editor.focus_handle(cx);
418 window.focus(&editor_focus_handle);
419 }
420 ContextStripEvent::BlurredUp => {}
421 }
422 }
423
424 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
425 if self.context_picker_menu_handle.is_deployed() {
426 cx.propagate();
427 } else if self.context_strip.read(cx).has_context_items(cx) {
428 self.context_strip.focus_handle(cx).focus(window);
429 }
430 }
431
432 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
433 crate::active_thread::attach_pasted_images_as_context(&self.context_store, cx);
434 }
435
436 fn handle_review_click(&mut self, window: &mut Window, cx: &mut Context<Self>) {
437 self.edits_expanded = true;
438 AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
439 cx.notify();
440 }
441
442 fn handle_edit_bar_expand(&mut self, cx: &mut Context<Self>) {
443 self.edits_expanded = !self.edits_expanded;
444 cx.notify();
445 }
446
447 fn handle_file_click(
448 &self,
449 buffer: Entity<Buffer>,
450 window: &mut Window,
451 cx: &mut Context<Self>,
452 ) {
453 if let Ok(diff) =
454 AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
455 {
456 let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
457 diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
458 }
459 }
460
461 pub fn toggle_burn_mode(
462 &mut self,
463 _: &ToggleBurnMode,
464 _window: &mut Window,
465 cx: &mut Context<Self>,
466 ) {
467 self.thread.update(cx, |thread, _cx| {
468 let active_completion_mode = thread.completion_mode();
469
470 thread.set_completion_mode(match active_completion_mode {
471 CompletionMode::Burn => CompletionMode::Normal,
472 CompletionMode::Normal => CompletionMode::Burn,
473 });
474 });
475 }
476
477 fn handle_accept_all(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
478 if self.thread.read(cx).has_pending_edit_tool_uses() {
479 return;
480 }
481
482 self.thread.update(cx, |thread, cx| {
483 thread.keep_all_edits(cx);
484 });
485 cx.notify();
486 }
487
488 fn handle_reject_all(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
489 if self.thread.read(cx).has_pending_edit_tool_uses() {
490 return;
491 }
492
493 // Since there's no reject_all_edits method in the thread API,
494 // we need to iterate through all buffers and reject their edits
495 let action_log = self.thread.read(cx).action_log().clone();
496 let changed_buffers = action_log.read(cx).changed_buffers(cx);
497
498 for (buffer, _) in changed_buffers {
499 self.thread.update(cx, |thread, cx| {
500 let buffer_snapshot = buffer.read(cx);
501 let start = buffer_snapshot.anchor_before(Point::new(0, 0));
502 let end = buffer_snapshot.anchor_after(buffer_snapshot.max_point());
503 thread
504 .reject_edits_in_ranges(buffer, vec![start..end], cx)
505 .detach();
506 });
507 }
508 cx.notify();
509 }
510
511 fn handle_reject_file_changes(
512 &mut self,
513 buffer: Entity<Buffer>,
514 _window: &mut Window,
515 cx: &mut Context<Self>,
516 ) {
517 if self.thread.read(cx).has_pending_edit_tool_uses() {
518 return;
519 }
520
521 self.thread.update(cx, |thread, cx| {
522 let buffer_snapshot = buffer.read(cx);
523 let start = buffer_snapshot.anchor_before(Point::new(0, 0));
524 let end = buffer_snapshot.anchor_after(buffer_snapshot.max_point());
525 thread
526 .reject_edits_in_ranges(buffer, vec![start..end], cx)
527 .detach();
528 });
529 cx.notify();
530 }
531
532 fn handle_accept_file_changes(
533 &mut self,
534 buffer: Entity<Buffer>,
535 _window: &mut Window,
536 cx: &mut Context<Self>,
537 ) {
538 if self.thread.read(cx).has_pending_edit_tool_uses() {
539 return;
540 }
541
542 self.thread.update(cx, |thread, cx| {
543 let buffer_snapshot = buffer.read(cx);
544 let start = buffer_snapshot.anchor_before(Point::new(0, 0));
545 let end = buffer_snapshot.anchor_after(buffer_snapshot.max_point());
546 thread.keep_edits_in_range(buffer, start..end, cx);
547 });
548 cx.notify();
549 }
550
551 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
552 let thread = self.thread.read(cx);
553 let model = thread.configured_model();
554 if !model?.model.supports_max_mode() {
555 return None;
556 }
557
558 let active_completion_mode = thread.completion_mode();
559 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
560 let icon = if burn_mode_enabled {
561 IconName::ZedBurnModeOn
562 } else {
563 IconName::ZedBurnMode
564 };
565
566 Some(
567 IconButton::new("burn-mode", icon)
568 .icon_size(IconSize::Small)
569 .icon_color(Color::Muted)
570 .toggle_state(burn_mode_enabled)
571 .selected_icon_color(Color::Error)
572 .on_click(cx.listener(|this, _event, window, cx| {
573 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
574 }))
575 .tooltip(move |_window, cx| {
576 cx.new(|_| MaxModeTooltip::new().selected(burn_mode_enabled))
577 .into()
578 })
579 .into_any_element(),
580 )
581 }
582
583 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
584 let following = self
585 .workspace
586 .read_with(cx, |workspace, _| {
587 workspace.is_being_followed(CollaboratorId::Agent)
588 })
589 .unwrap_or(false);
590
591 IconButton::new("follow-agent", IconName::Crosshair)
592 .icon_size(IconSize::Small)
593 .icon_color(Color::Muted)
594 .toggle_state(following)
595 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
596 .tooltip(move |window, cx| {
597 if following {
598 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
599 } else {
600 Tooltip::with_meta(
601 "Follow Agent",
602 Some(&Follow),
603 "Track the agent's location as it reads and edits files.",
604 window,
605 cx,
606 )
607 }
608 })
609 .on_click(cx.listener(move |this, _, window, cx| {
610 this.workspace
611 .update(cx, |workspace, cx| {
612 if following {
613 workspace.unfollow(CollaboratorId::Agent, window, cx);
614 } else {
615 workspace.follow(CollaboratorId::Agent, window, cx);
616 }
617 })
618 .ok();
619 }))
620 }
621
622 fn render_editor(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
623 let thread = self.thread.read(cx);
624 let model = thread.configured_model();
625
626 let editor_bg_color = cx.theme().colors().editor_background;
627 let is_generating = thread.is_generating();
628 let focus_handle = self.editor.focus_handle(cx);
629
630 let is_model_selected = model.is_some();
631 let is_editor_empty = self.is_editor_empty(cx);
632
633 let incompatible_tools = model
634 .as_ref()
635 .map(|model| {
636 self.incompatible_tools_state.update(cx, |state, cx| {
637 state
638 .incompatible_tools(&model.model, cx)
639 .iter()
640 .cloned()
641 .collect::<Vec<_>>()
642 })
643 })
644 .unwrap_or_default();
645
646 let is_editor_expanded = self.editor_is_expanded;
647 let expand_icon = if is_editor_expanded {
648 IconName::Minimize
649 } else {
650 IconName::Maximize
651 };
652
653 v_flex()
654 .key_context("MessageEditor")
655 .on_action(cx.listener(Self::chat))
656 .on_action(cx.listener(Self::chat_with_follow))
657 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
658 this.profile_selector
659 .read(cx)
660 .menu_handle()
661 .toggle(window, cx);
662 }))
663 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
664 this.model_selector
665 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
666 }))
667 .on_action(cx.listener(Self::toggle_context_picker))
668 .on_action(cx.listener(Self::remove_all_context))
669 .on_action(cx.listener(Self::move_up))
670 .on_action(cx.listener(Self::expand_message_editor))
671 .on_action(cx.listener(Self::toggle_burn_mode))
672 .on_action(
673 cx.listener(|this, _: &KeepAll, window, cx| this.handle_accept_all(window, cx)),
674 )
675 .on_action(
676 cx.listener(|this, _: &RejectAll, window, cx| this.handle_reject_all(window, cx)),
677 )
678 .capture_action(cx.listener(Self::paste))
679 .gap_2()
680 .p_2()
681 .bg(editor_bg_color)
682 .border_t_1()
683 .border_color(cx.theme().colors().border)
684 .child(
685 h_flex()
686 .justify_between()
687 .child(self.context_strip.clone())
688 .when(focus_handle.is_focused(window), |this| {
689 this.child(
690 IconButton::new("toggle-height", expand_icon)
691 .icon_size(IconSize::XSmall)
692 .icon_color(Color::Muted)
693 .tooltip({
694 let focus_handle = focus_handle.clone();
695 move |window, cx| {
696 let expand_label = if is_editor_expanded {
697 "Minimize Message Editor".to_string()
698 } else {
699 "Expand Message Editor".to_string()
700 };
701
702 Tooltip::for_action_in(
703 expand_label,
704 &ExpandMessageEditor,
705 &focus_handle,
706 window,
707 cx,
708 )
709 }
710 })
711 .on_click(cx.listener(|_, _, window, cx| {
712 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
713 })),
714 )
715 }),
716 )
717 .child(
718 v_flex()
719 .size_full()
720 .gap_1()
721 .when(is_editor_expanded, |this| {
722 this.h(vh(0.8, window)).justify_between()
723 })
724 .child({
725 let settings = ThemeSettings::get_global(cx);
726 let font_size = TextSize::Small
727 .rems(cx)
728 .to_pixels(settings.agent_font_size(cx));
729 let line_height = settings.buffer_line_height.value() * font_size;
730
731 let text_style = TextStyle {
732 color: cx.theme().colors().text,
733 font_family: settings.buffer_font.family.clone(),
734 font_fallbacks: settings.buffer_font.fallbacks.clone(),
735 font_features: settings.buffer_font.features.clone(),
736 font_size: font_size.into(),
737 line_height: line_height.into(),
738 ..Default::default()
739 };
740
741 EditorElement::new(
742 &self.editor,
743 EditorStyle {
744 background: editor_bg_color,
745 local_player: cx.theme().players().local(),
746 text: text_style,
747 syntax: cx.theme().syntax().clone(),
748 ..Default::default()
749 },
750 )
751 .into_any()
752 })
753 .child(
754 h_flex()
755 .flex_none()
756 .flex_wrap()
757 .justify_between()
758 .child(
759 h_flex()
760 .child(self.render_follow_toggle(cx))
761 .children(self.render_burn_mode_toggle(cx)),
762 )
763 .child(
764 h_flex()
765 .gap_1()
766 .flex_wrap()
767 .when(!incompatible_tools.is_empty(), |this| {
768 this.child(
769 IconButton::new(
770 "tools-incompatible-warning",
771 IconName::Warning,
772 )
773 .icon_color(Color::Warning)
774 .icon_size(IconSize::Small)
775 .tooltip({
776 move |_, cx| {
777 cx.new(|_| IncompatibleToolsTooltip {
778 incompatible_tools: incompatible_tools
779 .clone(),
780 })
781 .into()
782 }
783 }),
784 )
785 })
786 .child(self.profile_selector.clone())
787 .child(self.model_selector.clone())
788 .map({
789 let focus_handle = focus_handle.clone();
790 move |parent| {
791 if is_generating {
792 parent
793 .when(is_editor_empty, |parent| {
794 parent.child(
795 IconButton::new(
796 "stop-generation",
797 IconName::StopFilled,
798 )
799 .icon_color(Color::Error)
800 .style(ButtonStyle::Tinted(
801 ui::TintColor::Error,
802 ))
803 .tooltip(move |window, cx| {
804 Tooltip::for_action(
805 "Stop Generation",
806 &editor::actions::Cancel,
807 window,
808 cx,
809 )
810 })
811 .on_click({
812 let focus_handle =
813 focus_handle.clone();
814 move |_event, window, cx| {
815 focus_handle.dispatch_action(
816 &editor::actions::Cancel,
817 window,
818 cx,
819 );
820 }
821 })
822 .with_animation(
823 "pulsating-label",
824 Animation::new(
825 Duration::from_secs(2),
826 )
827 .repeat()
828 .with_easing(pulsating_between(
829 0.4, 1.0,
830 )),
831 |icon_button, delta| {
832 icon_button.alpha(delta)
833 },
834 ),
835 )
836 })
837 .when(!is_editor_empty, |parent| {
838 parent.child(
839 IconButton::new(
840 "send-message",
841 IconName::Send,
842 )
843 .icon_color(Color::Accent)
844 .style(ButtonStyle::Filled)
845 .disabled(!is_model_selected)
846 .on_click({
847 let focus_handle =
848 focus_handle.clone();
849 move |_event, window, cx| {
850 focus_handle.dispatch_action(
851 &Chat, window, cx,
852 );
853 }
854 })
855 .tooltip(move |window, cx| {
856 Tooltip::for_action(
857 "Stop and Send New Message",
858 &Chat,
859 window,
860 cx,
861 )
862 }),
863 )
864 })
865 } else {
866 parent.child(
867 IconButton::new("send-message", IconName::Send)
868 .icon_color(Color::Accent)
869 .style(ButtonStyle::Filled)
870 .disabled(
871 is_editor_empty || !is_model_selected,
872 )
873 .on_click({
874 let focus_handle = focus_handle.clone();
875 move |_event, window, cx| {
876 focus_handle.dispatch_action(
877 &Chat, window, cx,
878 );
879 }
880 })
881 .when(
882 !is_editor_empty && is_model_selected,
883 |button| {
884 button.tooltip(move |window, cx| {
885 Tooltip::for_action(
886 "Send", &Chat, window, cx,
887 )
888 })
889 },
890 )
891 .when(is_editor_empty, |button| {
892 button.tooltip(Tooltip::text(
893 "Type a message to submit",
894 ))
895 })
896 .when(!is_model_selected, |button| {
897 button.tooltip(Tooltip::text(
898 "Select a model to continue",
899 ))
900 }),
901 )
902 }
903 }
904 }),
905 ),
906 ),
907 )
908 }
909
910 fn render_edits_bar(
911 &self,
912 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
913 window: &mut Window,
914 cx: &mut Context<Self>,
915 ) -> Div {
916 let focus_handle = self.editor.focus_handle(cx);
917
918 let editor_bg_color = cx.theme().colors().editor_background;
919 let border_color = cx.theme().colors().border;
920 let active_color = cx.theme().colors().element_selected;
921 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
922
923 let is_edit_changes_expanded = self.edits_expanded;
924 let thread = self.thread.read(cx);
925 let pending_edits = thread.has_pending_edit_tool_uses();
926
927 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
928
929 v_flex()
930 .mt_1()
931 .mx_2()
932 .bg(bg_edit_files_disclosure)
933 .border_1()
934 .border_b_0()
935 .border_color(border_color)
936 .rounded_t_md()
937 .shadow(vec![gpui::BoxShadow {
938 color: gpui::black().opacity(0.15),
939 offset: point(px(1.), px(-1.)),
940 blur_radius: px(3.),
941 spread_radius: px(0.),
942 }])
943 .child(
944 h_flex()
945 .p_1()
946 .justify_between()
947 .when(is_edit_changes_expanded, |this| {
948 this.border_b_1().border_color(border_color)
949 })
950 .child(
951 h_flex()
952 .id("edits-container")
953 .cursor_pointer()
954 .w_full()
955 .gap_1()
956 .child(
957 Disclosure::new("edits-disclosure", is_edit_changes_expanded)
958 .on_click(cx.listener(|this, _, _, cx| {
959 this.handle_edit_bar_expand(cx)
960 })),
961 )
962 .map(|this| {
963 if pending_edits {
964 this.child(
965 Label::new(format!(
966 "Editing {} {}…",
967 changed_buffers.len(),
968 if changed_buffers.len() == 1 {
969 "file"
970 } else {
971 "files"
972 }
973 ))
974 .color(Color::Muted)
975 .size(LabelSize::Small)
976 .with_animation(
977 "edit-label",
978 Animation::new(Duration::from_secs(2))
979 .repeat()
980 .with_easing(pulsating_between(0.3, 0.7)),
981 |label, delta| label.alpha(delta),
982 ),
983 )
984 } else {
985 this.child(
986 Label::new("Edits")
987 .size(LabelSize::Small)
988 .color(Color::Muted),
989 )
990 .child(
991 Label::new("•").size(LabelSize::XSmall).color(Color::Muted),
992 )
993 .child(
994 Label::new(format!(
995 "{} {}",
996 changed_buffers.len(),
997 if changed_buffers.len() == 1 {
998 "file"
999 } else {
1000 "files"
1001 }
1002 ))
1003 .size(LabelSize::Small)
1004 .color(Color::Muted),
1005 )
1006 }
1007 })
1008 .on_click(
1009 cx.listener(|this, _, _, cx| this.handle_edit_bar_expand(cx)),
1010 ),
1011 )
1012 .child(
1013 h_flex()
1014 .gap_1()
1015 .child(
1016 IconButton::new("review-changes", IconName::ListTodo)
1017 .icon_size(IconSize::Small)
1018 .tooltip({
1019 let focus_handle = focus_handle.clone();
1020 move |window, cx| {
1021 Tooltip::for_action_in(
1022 "Review Changes",
1023 &OpenAgentDiff,
1024 &focus_handle,
1025 window,
1026 cx,
1027 )
1028 }
1029 })
1030 .on_click(cx.listener(|this, _, window, cx| {
1031 this.handle_review_click(window, cx)
1032 })),
1033 )
1034 .child(Divider::vertical().color(DividerColor::Border))
1035 .child(
1036 Button::new("reject-all-changes", "Reject All")
1037 .label_size(LabelSize::Small)
1038 .disabled(pending_edits)
1039 .when(pending_edits, |this| {
1040 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1041 })
1042 .key_binding(
1043 KeyBinding::for_action_in(
1044 &RejectAll,
1045 &focus_handle.clone(),
1046 window,
1047 cx,
1048 )
1049 .map(|kb| kb.size(rems_from_px(10.))),
1050 )
1051 .on_click(cx.listener(|this, _, window, cx| {
1052 this.handle_reject_all(window, cx)
1053 })),
1054 )
1055 .child(
1056 Button::new("accept-all-changes", "Accept All")
1057 .label_size(LabelSize::Small)
1058 .disabled(pending_edits)
1059 .when(pending_edits, |this| {
1060 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1061 })
1062 .key_binding(
1063 KeyBinding::for_action_in(
1064 &KeepAll,
1065 &focus_handle,
1066 window,
1067 cx,
1068 )
1069 .map(|kb| kb.size(rems_from_px(10.))),
1070 )
1071 .on_click(cx.listener(|this, _, window, cx| {
1072 this.handle_accept_all(window, cx)
1073 })),
1074 ),
1075 ),
1076 )
1077 .when(is_edit_changes_expanded, |parent| {
1078 parent.child(
1079 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1080 |(index, (buffer, _diff))| {
1081 let file = buffer.read(cx).file()?;
1082 let path = file.path();
1083
1084 let file_path = path.parent().and_then(|parent| {
1085 let parent_str = parent.to_string_lossy();
1086
1087 if parent_str.is_empty() {
1088 None
1089 } else {
1090 Some(
1091 Label::new(format!(
1092 "/{}{}",
1093 parent_str,
1094 std::path::MAIN_SEPARATOR_STR
1095 ))
1096 .color(Color::Muted)
1097 .size(LabelSize::XSmall)
1098 .buffer_font(cx),
1099 )
1100 }
1101 });
1102
1103 let file_name = path.file_name().map(|name| {
1104 Label::new(name.to_string_lossy().to_string())
1105 .size(LabelSize::XSmall)
1106 .buffer_font(cx)
1107 });
1108
1109 let file_icon = FileIcons::get_icon(&path, cx)
1110 .map(Icon::from_path)
1111 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1112 .unwrap_or_else(|| {
1113 Icon::new(IconName::File)
1114 .color(Color::Muted)
1115 .size(IconSize::Small)
1116 });
1117
1118 let overlay_gradient = linear_gradient(
1119 90.,
1120 linear_color_stop(editor_bg_color, 1.),
1121 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1122 );
1123
1124 let element = h_flex()
1125 .group("edited-code")
1126 .id(("file-container", index))
1127 .relative()
1128 .py_1()
1129 .pl_2()
1130 .pr_1()
1131 .gap_2()
1132 .justify_between()
1133 .bg(editor_bg_color)
1134 .when(index < changed_buffers.len() - 1, |parent| {
1135 parent.border_color(border_color).border_b_1()
1136 })
1137 .child(
1138 h_flex()
1139 .id("file-name")
1140 .pr_8()
1141 .gap_1p5()
1142 .max_w_full()
1143 .overflow_x_scroll()
1144 .child(file_icon)
1145 .child(
1146 h_flex()
1147 .gap_0p5()
1148 .children(file_name)
1149 .children(file_path),
1150 ), // TODO: Implement line diff
1151 // .child(Label::new("+").color(Color::Created))
1152 // .child(Label::new("-").color(Color::Deleted)),
1153 )
1154 .child(
1155 h_flex()
1156 .gap_1()
1157 .visible_on_hover("edited-code")
1158 .child(
1159 Button::new("review", "Review")
1160 .label_size(LabelSize::Small)
1161 .on_click({
1162 let buffer = buffer.clone();
1163 cx.listener(move |this, _, window, cx| {
1164 this.handle_file_click(
1165 buffer.clone(),
1166 window,
1167 cx,
1168 );
1169 })
1170 }),
1171 )
1172 .child(
1173 Divider::vertical().color(DividerColor::BorderVariant),
1174 )
1175 .child(
1176 Button::new("reject-file", "Reject")
1177 .label_size(LabelSize::Small)
1178 .disabled(pending_edits)
1179 .on_click({
1180 let buffer = buffer.clone();
1181 cx.listener(move |this, _, window, cx| {
1182 this.handle_reject_file_changes(
1183 buffer.clone(),
1184 window,
1185 cx,
1186 );
1187 })
1188 }),
1189 )
1190 .child(
1191 Button::new("accept-file", "Accept")
1192 .label_size(LabelSize::Small)
1193 .disabled(pending_edits)
1194 .on_click({
1195 let buffer = buffer.clone();
1196 cx.listener(move |this, _, window, cx| {
1197 this.handle_accept_file_changes(
1198 buffer.clone(),
1199 window,
1200 cx,
1201 );
1202 })
1203 }),
1204 ),
1205 )
1206 .child(
1207 div()
1208 .id("gradient-overlay")
1209 .absolute()
1210 .h_full()
1211 .w_12()
1212 .top_0()
1213 .bottom_0()
1214 .right(px(152.))
1215 .bg(overlay_gradient),
1216 );
1217
1218 Some(element)
1219 },
1220 )),
1221 )
1222 })
1223 }
1224
1225 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
1226 let is_using_zed_provider = self
1227 .thread
1228 .read(cx)
1229 .configured_model()
1230 .map_or(false, |model| {
1231 model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
1232 });
1233
1234 if !is_using_zed_provider {
1235 return None;
1236 }
1237
1238 let user_store = self.user_store.read(cx);
1239
1240 let ubb_enable = user_store
1241 .usage_based_billing_enabled()
1242 .map_or(false, |enabled| enabled);
1243
1244 if ubb_enable {
1245 return None;
1246 }
1247
1248 let plan = user_store
1249 .current_plan()
1250 .map(|plan| match plan {
1251 Plan::Free => zed_llm_client::Plan::ZedFree,
1252 Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1253 Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1254 })
1255 .unwrap_or(zed_llm_client::Plan::ZedFree);
1256 let usage = self.thread.read(cx).last_usage().or_else(|| {
1257 maybe!({
1258 let amount = user_store.model_request_usage_amount()?;
1259 let limit = user_store.model_request_usage_limit()?.variant?;
1260
1261 Some(RequestUsage {
1262 amount: amount as i32,
1263 limit: match limit {
1264 proto::usage_limit::Variant::Limited(limited) => {
1265 zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1266 }
1267 proto::usage_limit::Variant::Unlimited(_) => {
1268 zed_llm_client::UsageLimit::Unlimited
1269 }
1270 },
1271 })
1272 })
1273 })?;
1274
1275 Some(
1276 div()
1277 .child(UsageCallout::new(plan, usage))
1278 .line_height(line_height),
1279 )
1280 }
1281
1282 fn render_token_limit_callout(
1283 &self,
1284 line_height: Pixels,
1285 token_usage_ratio: TokenUsageRatio,
1286 cx: &mut Context<Self>,
1287 ) -> Option<Div> {
1288 let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1289 Icon::new(IconName::X)
1290 .color(Color::Error)
1291 .size(IconSize::XSmall)
1292 } else {
1293 Icon::new(IconName::Warning)
1294 .color(Color::Warning)
1295 .size(IconSize::XSmall)
1296 };
1297
1298 let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1299 "Thread reached the token limit"
1300 } else {
1301 "Thread reaching the token limit soon"
1302 };
1303
1304 Some(
1305 div()
1306 .border_t_1()
1307 .border_color(cx.theme().colors().border)
1308 .child(
1309 Callout::new()
1310 .line_height(line_height)
1311 .icon(icon)
1312 .title(title)
1313 .description(
1314 "To continue, start a new thread from a summary or turn burn mode on.",
1315 )
1316 .primary_action(
1317 Button::new("start-new-thread", "Start New Thread")
1318 .label_size(LabelSize::Small)
1319 .on_click(cx.listener(|this, _, window, cx| {
1320 let from_thread_id = Some(this.thread.read(cx).id().clone());
1321 window.dispatch_action(
1322 Box::new(NewThread { from_thread_id }),
1323 cx,
1324 );
1325 })),
1326 )
1327 .secondary_action(
1328 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
1329 .icon_size(IconSize::XSmall)
1330 .on_click(cx.listener(|this, _event, window, cx| {
1331 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
1332 })),
1333 ),
1334 ),
1335 )
1336 }
1337
1338 pub fn last_estimated_token_count(&self) -> Option<u64> {
1339 self.last_estimated_token_count
1340 }
1341
1342 pub fn is_waiting_to_update_token_count(&self) -> bool {
1343 self.update_token_count_task.is_some()
1344 }
1345
1346 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1347 let load_task = cx.spawn(async move |this, cx| {
1348 let Ok(load_task) = this.update(cx, |this, cx| {
1349 let new_context = this
1350 .context_store
1351 .read(cx)
1352 .new_context_for_thread(this.thread.read(cx), None);
1353 load_context(new_context, &this.project, &this.prompt_store, cx)
1354 }) else {
1355 return;
1356 };
1357 let result = load_task.await;
1358 this.update(cx, |this, cx| {
1359 this.last_loaded_context = Some(result);
1360 this.load_context_task = None;
1361 this.message_or_context_changed(false, cx);
1362 })
1363 .ok();
1364 });
1365 // Replace existing load task, if any, causing it to be cancelled.
1366 let load_task = load_task.shared();
1367 self.load_context_task = Some(load_task.clone());
1368 cx.spawn(async move |this, cx| {
1369 load_task.await;
1370 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1371 .ok()
1372 .flatten()
1373 })
1374 }
1375
1376 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1377 self.message_or_context_changed(true, cx);
1378 }
1379
1380 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1381 cx.emit(MessageEditorEvent::Changed);
1382 self.update_token_count_task.take();
1383
1384 let Some(model) = self.thread.read(cx).configured_model() else {
1385 self.last_estimated_token_count.take();
1386 return;
1387 };
1388
1389 let editor = self.editor.clone();
1390
1391 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1392 if debounce {
1393 cx.background_executor()
1394 .timer(Duration::from_millis(200))
1395 .await;
1396 }
1397
1398 let token_count = if let Some(task) = this
1399 .update(cx, |this, cx| {
1400 let loaded_context = this
1401 .last_loaded_context
1402 .as_ref()
1403 .map(|context_load_result| &context_load_result.loaded_context);
1404 let message_text = editor.read(cx).text(cx);
1405
1406 if message_text.is_empty()
1407 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1408 {
1409 return None;
1410 }
1411
1412 let mut request_message = LanguageModelRequestMessage {
1413 role: language_model::Role::User,
1414 content: Vec::new(),
1415 cache: false,
1416 };
1417
1418 if let Some(loaded_context) = loaded_context {
1419 loaded_context.add_to_request_message(&mut request_message);
1420 }
1421
1422 if !message_text.is_empty() {
1423 request_message
1424 .content
1425 .push(MessageContent::Text(message_text));
1426 }
1427
1428 let request = language_model::LanguageModelRequest {
1429 thread_id: None,
1430 prompt_id: None,
1431 intent: None,
1432 mode: None,
1433 messages: vec![request_message],
1434 tools: vec![],
1435 tool_choice: None,
1436 stop: vec![],
1437 temperature: AgentSettings::temperature_for_model(&model.model, cx),
1438 };
1439
1440 Some(model.model.count_tokens(request, cx))
1441 })
1442 .ok()
1443 .flatten()
1444 {
1445 task.await.log_err()
1446 } else {
1447 Some(0)
1448 };
1449
1450 this.update(cx, |this, cx| {
1451 if let Some(token_count) = token_count {
1452 this.last_estimated_token_count = Some(token_count);
1453 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1454 }
1455 this.update_token_count_task.take();
1456 })
1457 .ok();
1458 }));
1459 }
1460}
1461
1462pub fn extract_message_creases(
1463 editor: &mut Editor,
1464 cx: &mut Context<'_, Editor>,
1465) -> Vec<MessageCrease> {
1466 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1467 let mut contexts_by_crease_id = editor
1468 .addon_mut::<ContextCreasesAddon>()
1469 .map(std::mem::take)
1470 .unwrap_or_default()
1471 .into_inner()
1472 .into_iter()
1473 .flat_map(|(key, creases)| {
1474 let context = key.0;
1475 creases
1476 .into_iter()
1477 .map(move |(id, _)| (id, context.clone()))
1478 })
1479 .collect::<HashMap<_, _>>();
1480 // Filter the addon's list of creases based on what the editor reports,
1481 // since the addon might have removed creases in it.
1482 let creases = editor.display_map.update(cx, |display_map, cx| {
1483 display_map
1484 .snapshot(cx)
1485 .crease_snapshot
1486 .creases()
1487 .filter_map(|(id, crease)| {
1488 Some((
1489 id,
1490 (
1491 crease.range().to_offset(&buffer_snapshot),
1492 crease.metadata()?.clone(),
1493 ),
1494 ))
1495 })
1496 .map(|(id, (range, metadata))| {
1497 let context = contexts_by_crease_id.remove(&id);
1498 MessageCrease {
1499 range,
1500 metadata,
1501 context,
1502 }
1503 })
1504 .collect()
1505 });
1506 creases
1507}
1508
1509impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1510
1511pub enum MessageEditorEvent {
1512 EstimatedTokenCount,
1513 Changed,
1514 ScrollThreadToBottom,
1515}
1516
1517impl Focusable for MessageEditor {
1518 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1519 self.editor.focus_handle(cx)
1520 }
1521}
1522
1523impl Render for MessageEditor {
1524 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1525 let thread = self.thread.read(cx);
1526 let token_usage_ratio = thread
1527 .total_token_usage()
1528 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1529 total_token_usage.ratio()
1530 });
1531
1532 let burn_mode_enabled = thread.completion_mode() == CompletionMode::Burn;
1533
1534 let action_log = self.thread.read(cx).action_log();
1535 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1536
1537 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1538
1539 v_flex()
1540 .size_full()
1541 .when(changed_buffers.len() > 0, |parent| {
1542 parent.child(self.render_edits_bar(&changed_buffers, window, cx))
1543 })
1544 .child(self.render_editor(window, cx))
1545 .children({
1546 let usage_callout = self.render_usage_callout(line_height, cx);
1547
1548 if usage_callout.is_some() {
1549 usage_callout
1550 } else if token_usage_ratio != TokenUsageRatio::Normal && !burn_mode_enabled {
1551 self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1552 } else {
1553 None
1554 }
1555 })
1556 }
1557}
1558
1559pub fn insert_message_creases(
1560 editor: &mut Editor,
1561 message_creases: &[MessageCrease],
1562 context_store: &Entity<ContextStore>,
1563 window: &mut Window,
1564 cx: &mut Context<'_, Editor>,
1565) {
1566 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1567 let creases = message_creases
1568 .iter()
1569 .map(|crease| {
1570 let start = buffer_snapshot.anchor_after(crease.range.start);
1571 let end = buffer_snapshot.anchor_before(crease.range.end);
1572 crease_for_mention(
1573 crease.metadata.label.clone(),
1574 crease.metadata.icon_path.clone(),
1575 start..end,
1576 cx.weak_entity(),
1577 )
1578 })
1579 .collect::<Vec<_>>();
1580 let ids = editor.insert_creases(creases.clone(), cx);
1581 editor.fold_creases(creases, false, window, cx);
1582 if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1583 for (crease, id) in message_creases.iter().zip(ids) {
1584 if let Some(context) = crease.context.as_ref() {
1585 let key = AgentContextKey(context.clone());
1586 addon.add_creases(
1587 context_store,
1588 key,
1589 vec![(id, crease.metadata.label.clone())],
1590 cx,
1591 );
1592 }
1593 }
1594 }
1595}
1596impl Component for MessageEditor {
1597 fn scope() -> ComponentScope {
1598 ComponentScope::Agent
1599 }
1600
1601 fn description() -> Option<&'static str> {
1602 Some(
1603 "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1604 )
1605 }
1606}
1607
1608impl AgentPreview for MessageEditor {
1609 fn agent_preview(
1610 workspace: WeakEntity<Workspace>,
1611 active_thread: Entity<ActiveThread>,
1612 window: &mut Window,
1613 cx: &mut App,
1614 ) -> Option<AnyElement> {
1615 if let Some(workspace) = workspace.upgrade() {
1616 let fs = workspace.read(cx).app_state().fs.clone();
1617 let user_store = workspace.read(cx).app_state().user_store.clone();
1618 let project = workspace.read(cx).project().clone();
1619 let weak_project = project.downgrade();
1620 let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1621 let active_thread = active_thread.read(cx);
1622 let thread = active_thread.thread().clone();
1623 let thread_store = active_thread.thread_store().clone();
1624 let text_thread_store = active_thread.text_thread_store().clone();
1625
1626 let default_message_editor = cx.new(|cx| {
1627 MessageEditor::new(
1628 fs,
1629 workspace.downgrade(),
1630 user_store,
1631 context_store,
1632 None,
1633 thread_store.downgrade(),
1634 text_thread_store.downgrade(),
1635 thread,
1636 window,
1637 cx,
1638 )
1639 });
1640
1641 Some(
1642 v_flex()
1643 .gap_4()
1644 .children(vec![single_example(
1645 "Default Message Editor",
1646 div()
1647 .w(px(540.))
1648 .pt_12()
1649 .bg(cx.theme().colors().panel_background)
1650 .border_1()
1651 .border_color(cx.theme().colors().border)
1652 .child(default_message_editor.clone())
1653 .into_any_element(),
1654 )])
1655 .into_any_element(),
1656 )
1657 } else {
1658 None
1659 }
1660 }
1661}
1662
1663register_agent_preview!(MessageEditor);