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