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