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