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 focus_handle.dispatch_action(
914 &Chat, window, cx,
915 );
916 }
917 })
918 .when(
919 !is_editor_empty && is_model_selected,
920 |button| {
921 button.tooltip(move |window, cx| {
922 Tooltip::for_action(
923 "Send", &Chat, window, cx,
924 )
925 })
926 },
927 )
928 .when(is_editor_empty, |button| {
929 button.tooltip(Tooltip::text(
930 "Type a message to submit",
931 ))
932 })
933 .when(!is_model_selected, |button| {
934 button.tooltip(Tooltip::text(
935 "Select a model to continue",
936 ))
937 }),
938 )
939 }
940 }
941 }),
942 ),
943 ),
944 )
945 }
946
947 fn render_edits_bar(
948 &self,
949 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
950 window: &mut Window,
951 cx: &mut Context<Self>,
952 ) -> Div {
953 let focus_handle = self.editor.focus_handle(cx);
954
955 let editor_bg_color = cx.theme().colors().editor_background;
956 let border_color = cx.theme().colors().border;
957 let active_color = cx.theme().colors().element_selected;
958 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
959
960 let is_edit_changes_expanded = self.edits_expanded;
961 let thread = self.thread.read(cx);
962 let pending_edits = thread.has_pending_edit_tool_uses();
963
964 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
965
966 v_flex()
967 .mt_1()
968 .mx_2()
969 .bg(bg_edit_files_disclosure)
970 .border_1()
971 .border_b_0()
972 .border_color(border_color)
973 .rounded_t_md()
974 .shadow(vec![gpui::BoxShadow {
975 color: gpui::black().opacity(0.15),
976 offset: point(px(1.), px(-1.)),
977 blur_radius: px(3.),
978 spread_radius: px(0.),
979 }])
980 .child(
981 h_flex()
982 .p_1()
983 .justify_between()
984 .when(is_edit_changes_expanded, |this| {
985 this.border_b_1().border_color(border_color)
986 })
987 .child(
988 h_flex()
989 .id("edits-container")
990 .cursor_pointer()
991 .w_full()
992 .gap_1()
993 .child(
994 Disclosure::new("edits-disclosure", is_edit_changes_expanded)
995 .on_click(cx.listener(|this, _, _, cx| {
996 this.handle_edit_bar_expand(cx)
997 })),
998 )
999 .map(|this| {
1000 if pending_edits {
1001 this.child(
1002 Label::new(format!(
1003 "Editing {} {}…",
1004 changed_buffers.len(),
1005 if changed_buffers.len() == 1 {
1006 "file"
1007 } else {
1008 "files"
1009 }
1010 ))
1011 .color(Color::Muted)
1012 .size(LabelSize::Small)
1013 .with_animation(
1014 "edit-label",
1015 Animation::new(Duration::from_secs(2))
1016 .repeat()
1017 .with_easing(pulsating_between(0.3, 0.7)),
1018 |label, delta| label.alpha(delta),
1019 ),
1020 )
1021 } else {
1022 this.child(
1023 Label::new("Edits")
1024 .size(LabelSize::Small)
1025 .color(Color::Muted),
1026 )
1027 .child(
1028 Label::new("•").size(LabelSize::XSmall).color(Color::Muted),
1029 )
1030 .child(
1031 Label::new(format!(
1032 "{} {}",
1033 changed_buffers.len(),
1034 if changed_buffers.len() == 1 {
1035 "file"
1036 } else {
1037 "files"
1038 }
1039 ))
1040 .size(LabelSize::Small)
1041 .color(Color::Muted),
1042 )
1043 }
1044 })
1045 .on_click(
1046 cx.listener(|this, _, _, cx| this.handle_edit_bar_expand(cx)),
1047 ),
1048 )
1049 .child(
1050 h_flex()
1051 .gap_1()
1052 .child(
1053 IconButton::new("review-changes", IconName::ListTodo)
1054 .icon_size(IconSize::Small)
1055 .tooltip({
1056 let focus_handle = focus_handle.clone();
1057 move |window, cx| {
1058 Tooltip::for_action_in(
1059 "Review Changes",
1060 &OpenAgentDiff,
1061 &focus_handle,
1062 window,
1063 cx,
1064 )
1065 }
1066 })
1067 .on_click(cx.listener(|this, _, window, cx| {
1068 this.handle_review_click(window, cx)
1069 })),
1070 )
1071 .child(Divider::vertical().color(DividerColor::Border))
1072 .child(
1073 Button::new("reject-all-changes", "Reject All")
1074 .label_size(LabelSize::Small)
1075 .disabled(pending_edits)
1076 .when(pending_edits, |this| {
1077 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1078 })
1079 .key_binding(
1080 KeyBinding::for_action_in(
1081 &RejectAll,
1082 &focus_handle.clone(),
1083 window,
1084 cx,
1085 )
1086 .map(|kb| kb.size(rems_from_px(10.))),
1087 )
1088 .on_click(cx.listener(|this, _, window, cx| {
1089 this.handle_reject_all(window, cx)
1090 })),
1091 )
1092 .child(
1093 Button::new("accept-all-changes", "Accept All")
1094 .label_size(LabelSize::Small)
1095 .disabled(pending_edits)
1096 .when(pending_edits, |this| {
1097 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1098 })
1099 .key_binding(
1100 KeyBinding::for_action_in(
1101 &KeepAll,
1102 &focus_handle,
1103 window,
1104 cx,
1105 )
1106 .map(|kb| kb.size(rems_from_px(10.))),
1107 )
1108 .on_click(cx.listener(|this, _, window, cx| {
1109 this.handle_accept_all(window, cx)
1110 })),
1111 ),
1112 ),
1113 )
1114 .when(is_edit_changes_expanded, |parent| {
1115 parent.child(
1116 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1117 |(index, (buffer, _diff))| {
1118 let file = buffer.read(cx).file()?;
1119 let path = file.path();
1120
1121 let file_path = path.parent().and_then(|parent| {
1122 let parent_str = parent.to_string_lossy();
1123
1124 if parent_str.is_empty() {
1125 None
1126 } else {
1127 Some(
1128 Label::new(format!(
1129 "/{}{}",
1130 parent_str,
1131 std::path::MAIN_SEPARATOR_STR
1132 ))
1133 .color(Color::Muted)
1134 .size(LabelSize::XSmall)
1135 .buffer_font(cx),
1136 )
1137 }
1138 });
1139
1140 let file_name = path.file_name().map(|name| {
1141 Label::new(name.to_string_lossy().to_string())
1142 .size(LabelSize::XSmall)
1143 .buffer_font(cx)
1144 });
1145
1146 let file_icon = FileIcons::get_icon(&path, cx)
1147 .map(Icon::from_path)
1148 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1149 .unwrap_or_else(|| {
1150 Icon::new(IconName::File)
1151 .color(Color::Muted)
1152 .size(IconSize::Small)
1153 });
1154
1155 let overlay_gradient = linear_gradient(
1156 90.,
1157 linear_color_stop(editor_bg_color, 1.),
1158 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1159 );
1160
1161 let element = h_flex()
1162 .group("edited-code")
1163 .id(("file-container", index))
1164 .relative()
1165 .py_1()
1166 .pl_2()
1167 .pr_1()
1168 .gap_2()
1169 .justify_between()
1170 .bg(editor_bg_color)
1171 .when(index < changed_buffers.len() - 1, |parent| {
1172 parent.border_color(border_color).border_b_1()
1173 })
1174 .child(
1175 h_flex()
1176 .id(("file-name", index))
1177 .pr_8()
1178 .gap_1p5()
1179 .max_w_full()
1180 .overflow_x_scroll()
1181 .child(file_icon)
1182 .child(
1183 h_flex()
1184 .gap_0p5()
1185 .children(file_name)
1186 .children(file_path),
1187 )
1188 .on_click({
1189 let buffer = buffer.clone();
1190 cx.listener(move |this, _, window, cx| {
1191 this.handle_file_click(buffer.clone(), window, cx);
1192 })
1193 }), // TODO: Implement line diff
1194 // .child(Label::new("+").color(Color::Created))
1195 // .child(Label::new("-").color(Color::Deleted)),
1196 //
1197 )
1198 .child(
1199 h_flex()
1200 .gap_1()
1201 .visible_on_hover("edited-code")
1202 .child(
1203 Button::new("review", "Review")
1204 .label_size(LabelSize::Small)
1205 .on_click({
1206 let buffer = buffer.clone();
1207 cx.listener(move |this, _, window, cx| {
1208 this.handle_file_click(
1209 buffer.clone(),
1210 window,
1211 cx,
1212 );
1213 })
1214 }),
1215 )
1216 .child(
1217 Divider::vertical().color(DividerColor::BorderVariant),
1218 )
1219 .child(
1220 Button::new("reject-file", "Reject")
1221 .label_size(LabelSize::Small)
1222 .disabled(pending_edits)
1223 .on_click({
1224 let buffer = buffer.clone();
1225 cx.listener(move |this, _, window, cx| {
1226 this.handle_reject_file_changes(
1227 buffer.clone(),
1228 window,
1229 cx,
1230 );
1231 })
1232 }),
1233 )
1234 .child(
1235 Button::new("accept-file", "Accept")
1236 .label_size(LabelSize::Small)
1237 .disabled(pending_edits)
1238 .on_click({
1239 let buffer = buffer.clone();
1240 cx.listener(move |this, _, window, cx| {
1241 this.handle_accept_file_changes(
1242 buffer.clone(),
1243 window,
1244 cx,
1245 );
1246 })
1247 }),
1248 ),
1249 )
1250 .child(
1251 div()
1252 .id("gradient-overlay")
1253 .absolute()
1254 .h_full()
1255 .w_12()
1256 .top_0()
1257 .bottom_0()
1258 .right(px(152.))
1259 .bg(overlay_gradient),
1260 );
1261
1262 Some(element)
1263 },
1264 )),
1265 )
1266 })
1267 }
1268
1269 fn is_using_zed_provider(&self, cx: &App) -> bool {
1270 self.thread
1271 .read(cx)
1272 .configured_model()
1273 .map_or(false, |model| model.provider.id() == ZED_CLOUD_PROVIDER_ID)
1274 }
1275
1276 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
1277 if !self.is_using_zed_provider(cx) {
1278 return None;
1279 }
1280
1281 let user_store = self.user_store.read(cx);
1282
1283 let ubb_enable = user_store
1284 .usage_based_billing_enabled()
1285 .map_or(false, |enabled| enabled);
1286
1287 if ubb_enable {
1288 return None;
1289 }
1290
1291 let plan = user_store
1292 .current_plan()
1293 .map(|plan| match plan {
1294 Plan::Free => zed_llm_client::Plan::ZedFree,
1295 Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1296 Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1297 })
1298 .unwrap_or(zed_llm_client::Plan::ZedFree);
1299
1300 let usage = user_store.model_request_usage()?;
1301
1302 Some(
1303 div()
1304 .child(UsageCallout::new(plan, usage))
1305 .line_height(line_height),
1306 )
1307 }
1308
1309 fn render_token_limit_callout(
1310 &self,
1311 line_height: Pixels,
1312 token_usage_ratio: TokenUsageRatio,
1313 cx: &mut Context<Self>,
1314 ) -> Option<Div> {
1315 let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1316 Icon::new(IconName::X)
1317 .color(Color::Error)
1318 .size(IconSize::XSmall)
1319 } else {
1320 Icon::new(IconName::Warning)
1321 .color(Color::Warning)
1322 .size(IconSize::XSmall)
1323 };
1324
1325 let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1326 "Thread reached the token limit"
1327 } else {
1328 "Thread reaching the token limit soon"
1329 };
1330
1331 let description = if self.is_using_zed_provider(cx) {
1332 "To continue, start a new thread from a summary or turn burn mode on."
1333 } else {
1334 "To continue, start a new thread from a summary."
1335 };
1336
1337 let mut callout = Callout::new()
1338 .line_height(line_height)
1339 .icon(icon)
1340 .title(title)
1341 .description(description)
1342 .primary_action(
1343 Button::new("start-new-thread", "Start New Thread")
1344 .label_size(LabelSize::Small)
1345 .on_click(cx.listener(|this, _, window, cx| {
1346 let from_thread_id = Some(this.thread.read(cx).id().clone());
1347 window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1348 })),
1349 );
1350
1351 if self.is_using_zed_provider(cx) {
1352 callout = callout.secondary_action(
1353 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
1354 .icon_size(IconSize::XSmall)
1355 .on_click(cx.listener(|this, _event, window, cx| {
1356 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
1357 })),
1358 );
1359 }
1360
1361 Some(
1362 div()
1363 .border_t_1()
1364 .border_color(cx.theme().colors().border)
1365 .child(callout),
1366 )
1367 }
1368
1369 pub fn last_estimated_token_count(&self) -> Option<u64> {
1370 self.last_estimated_token_count
1371 }
1372
1373 pub fn is_waiting_to_update_token_count(&self) -> bool {
1374 self.update_token_count_task.is_some()
1375 }
1376
1377 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1378 let load_task = cx.spawn(async move |this, cx| {
1379 let Ok(load_task) = this.update(cx, |this, cx| {
1380 let new_context = this
1381 .context_store
1382 .read(cx)
1383 .new_context_for_thread(this.thread.read(cx), None);
1384 load_context(new_context, &this.project, &this.prompt_store, cx)
1385 }) else {
1386 return;
1387 };
1388 let result = load_task.await;
1389 this.update(cx, |this, cx| {
1390 this.last_loaded_context = Some(result);
1391 this.load_context_task = None;
1392 this.message_or_context_changed(false, cx);
1393 })
1394 .ok();
1395 });
1396 // Replace existing load task, if any, causing it to be cancelled.
1397 let load_task = load_task.shared();
1398 self.load_context_task = Some(load_task.clone());
1399 cx.spawn(async move |this, cx| {
1400 load_task.await;
1401 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1402 .ok()
1403 .flatten()
1404 })
1405 }
1406
1407 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1408 self.message_or_context_changed(true, cx);
1409 }
1410
1411 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1412 cx.emit(MessageEditorEvent::Changed);
1413 self.update_token_count_task.take();
1414
1415 let Some(model) = self.thread.read(cx).configured_model() else {
1416 self.last_estimated_token_count.take();
1417 return;
1418 };
1419
1420 let editor = self.editor.clone();
1421
1422 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1423 if debounce {
1424 cx.background_executor()
1425 .timer(Duration::from_millis(200))
1426 .await;
1427 }
1428
1429 let token_count = if let Some(task) = this
1430 .update(cx, |this, cx| {
1431 let loaded_context = this
1432 .last_loaded_context
1433 .as_ref()
1434 .map(|context_load_result| &context_load_result.loaded_context);
1435 let message_text = editor.read(cx).text(cx);
1436
1437 if message_text.is_empty()
1438 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1439 {
1440 return None;
1441 }
1442
1443 let mut request_message = LanguageModelRequestMessage {
1444 role: language_model::Role::User,
1445 content: Vec::new(),
1446 cache: false,
1447 };
1448
1449 if let Some(loaded_context) = loaded_context {
1450 loaded_context.add_to_request_message(&mut request_message);
1451 }
1452
1453 if !message_text.is_empty() {
1454 request_message
1455 .content
1456 .push(MessageContent::Text(message_text));
1457 }
1458
1459 let request = language_model::LanguageModelRequest {
1460 thread_id: None,
1461 prompt_id: None,
1462 intent: None,
1463 mode: None,
1464 messages: vec![request_message],
1465 tools: vec![],
1466 tool_choice: None,
1467 stop: vec![],
1468 temperature: AgentSettings::temperature_for_model(&model.model, cx),
1469 thinking_allowed: true,
1470 };
1471
1472 Some(model.model.count_tokens(request, cx))
1473 })
1474 .ok()
1475 .flatten()
1476 {
1477 task.await.log_err()
1478 } else {
1479 Some(0)
1480 };
1481
1482 this.update(cx, |this, cx| {
1483 if let Some(token_count) = token_count {
1484 this.last_estimated_token_count = Some(token_count);
1485 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1486 }
1487 this.update_token_count_task.take();
1488 })
1489 .ok();
1490 }));
1491 }
1492}
1493
1494#[derive(Default)]
1495pub struct ContextCreasesAddon {
1496 creases: HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>>,
1497 _subscription: Option<Subscription>,
1498}
1499
1500pub struct MessageEditorAddon {}
1501
1502impl MessageEditorAddon {
1503 pub fn new() -> Self {
1504 Self {}
1505 }
1506}
1507
1508impl Addon for MessageEditorAddon {
1509 fn to_any(&self) -> &dyn std::any::Any {
1510 self
1511 }
1512
1513 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1514 Some(self)
1515 }
1516
1517 fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
1518 let settings = agent_settings::AgentSettings::get_global(cx);
1519 if settings.use_modifier_to_send {
1520 key_context.add("use_modifier_to_send");
1521 }
1522 }
1523}
1524
1525impl Addon for ContextCreasesAddon {
1526 fn to_any(&self) -> &dyn std::any::Any {
1527 self
1528 }
1529
1530 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1531 Some(self)
1532 }
1533}
1534
1535impl ContextCreasesAddon {
1536 pub fn new() -> Self {
1537 Self {
1538 creases: HashMap::default(),
1539 _subscription: None,
1540 }
1541 }
1542
1543 pub fn add_creases(
1544 &mut self,
1545 context_store: &Entity<ContextStore>,
1546 key: AgentContextKey,
1547 creases: impl IntoIterator<Item = (CreaseId, SharedString)>,
1548 cx: &mut Context<Editor>,
1549 ) {
1550 self.creases.entry(key).or_default().extend(creases);
1551 self._subscription = Some(cx.subscribe(
1552 &context_store,
1553 |editor, _, event, cx| match event {
1554 ContextStoreEvent::ContextRemoved(key) => {
1555 let Some(this) = editor.addon_mut::<Self>() else {
1556 return;
1557 };
1558 let (crease_ids, replacement_texts): (Vec<_>, Vec<_>) = this
1559 .creases
1560 .remove(key)
1561 .unwrap_or_default()
1562 .into_iter()
1563 .unzip();
1564 let ranges = editor
1565 .remove_creases(crease_ids, cx)
1566 .into_iter()
1567 .map(|(_, range)| range)
1568 .collect::<Vec<_>>();
1569 editor.unfold_ranges(&ranges, false, false, cx);
1570 editor.edit(ranges.into_iter().zip(replacement_texts), cx);
1571 cx.notify();
1572 }
1573 },
1574 ))
1575 }
1576
1577 pub fn into_inner(self) -> HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>> {
1578 self.creases
1579 }
1580}
1581
1582pub fn extract_message_creases(
1583 editor: &mut Editor,
1584 cx: &mut Context<'_, Editor>,
1585) -> Vec<MessageCrease> {
1586 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1587 let mut contexts_by_crease_id = editor
1588 .addon_mut::<ContextCreasesAddon>()
1589 .map(std::mem::take)
1590 .unwrap_or_default()
1591 .into_inner()
1592 .into_iter()
1593 .flat_map(|(key, creases)| {
1594 let context = key.0;
1595 creases
1596 .into_iter()
1597 .map(move |(id, _)| (id, context.clone()))
1598 })
1599 .collect::<HashMap<_, _>>();
1600 // Filter the addon's list of creases based on what the editor reports,
1601 // since the addon might have removed creases in it.
1602 let creases = editor.display_map.update(cx, |display_map, cx| {
1603 display_map
1604 .snapshot(cx)
1605 .crease_snapshot
1606 .creases()
1607 .filter_map(|(id, crease)| {
1608 Some((
1609 id,
1610 (
1611 crease.range().to_offset(&buffer_snapshot),
1612 crease.metadata()?.clone(),
1613 ),
1614 ))
1615 })
1616 .map(|(id, (range, metadata))| {
1617 let context = contexts_by_crease_id.remove(&id);
1618 MessageCrease {
1619 range,
1620 context,
1621 label: metadata.label,
1622 icon_path: metadata.icon_path,
1623 }
1624 })
1625 .collect()
1626 });
1627 creases
1628}
1629
1630impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1631
1632pub enum MessageEditorEvent {
1633 EstimatedTokenCount,
1634 Changed,
1635 ScrollThreadToBottom,
1636}
1637
1638impl Focusable for MessageEditor {
1639 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1640 self.editor.focus_handle(cx)
1641 }
1642}
1643
1644impl Render for MessageEditor {
1645 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1646 let thread = self.thread.read(cx);
1647 let token_usage_ratio = thread
1648 .total_token_usage()
1649 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1650 total_token_usage.ratio()
1651 });
1652
1653 let burn_mode_enabled = thread.completion_mode() == CompletionMode::Burn;
1654
1655 let action_log = self.thread.read(cx).action_log();
1656 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1657
1658 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1659
1660 let in_pro_trial = matches!(
1661 self.user_store.read(cx).current_plan(),
1662 Some(proto::Plan::ZedProTrial)
1663 );
1664
1665 let pro_user = matches!(
1666 self.user_store.read(cx).current_plan(),
1667 Some(proto::Plan::ZedPro)
1668 );
1669
1670 let configured_providers: Vec<(IconName, SharedString)> =
1671 LanguageModelRegistry::read_global(cx)
1672 .providers()
1673 .iter()
1674 .filter(|provider| {
1675 provider.is_authenticated(cx) && provider.id() != ZED_CLOUD_PROVIDER_ID
1676 })
1677 .map(|provider| (provider.icon(), provider.name().0.clone()))
1678 .collect();
1679 let has_existing_providers = configured_providers.len() > 0;
1680
1681 v_flex()
1682 .size_full()
1683 .bg(cx.theme().colors().panel_background)
1684 .when(
1685 has_existing_providers && !in_pro_trial && !pro_user,
1686 |this| this.child(cx.new(ApiKeysWithProviders::new)),
1687 )
1688 .when(changed_buffers.len() > 0, |parent| {
1689 parent.child(self.render_edits_bar(&changed_buffers, window, cx))
1690 })
1691 .child(self.render_editor(window, cx))
1692 .children({
1693 let usage_callout = self.render_usage_callout(line_height, cx);
1694
1695 if usage_callout.is_some() {
1696 usage_callout
1697 } else if token_usage_ratio != TokenUsageRatio::Normal && !burn_mode_enabled {
1698 self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1699 } else {
1700 None
1701 }
1702 })
1703 }
1704}
1705
1706pub fn insert_message_creases(
1707 editor: &mut Editor,
1708 message_creases: &[MessageCrease],
1709 context_store: &Entity<ContextStore>,
1710 window: &mut Window,
1711 cx: &mut Context<'_, Editor>,
1712) {
1713 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1714 let creases = message_creases
1715 .iter()
1716 .map(|crease| {
1717 let start = buffer_snapshot.anchor_after(crease.range.start);
1718 let end = buffer_snapshot.anchor_before(crease.range.end);
1719 crease_for_mention(
1720 crease.label.clone(),
1721 crease.icon_path.clone(),
1722 start..end,
1723 cx.weak_entity(),
1724 )
1725 })
1726 .collect::<Vec<_>>();
1727 let ids = editor.insert_creases(creases.clone(), cx);
1728 editor.fold_creases(creases, false, window, cx);
1729 if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1730 for (crease, id) in message_creases.iter().zip(ids) {
1731 if let Some(context) = crease.context.as_ref() {
1732 let key = AgentContextKey(context.clone());
1733 addon.add_creases(context_store, key, vec![(id, crease.label.clone())], cx);
1734 }
1735 }
1736 }
1737}
1738impl Component for MessageEditor {
1739 fn scope() -> ComponentScope {
1740 ComponentScope::Agent
1741 }
1742
1743 fn description() -> Option<&'static str> {
1744 Some(
1745 "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1746 )
1747 }
1748}
1749
1750impl AgentPreview for MessageEditor {
1751 fn agent_preview(
1752 workspace: WeakEntity<Workspace>,
1753 active_thread: Entity<ActiveThread>,
1754 window: &mut Window,
1755 cx: &mut App,
1756 ) -> Option<AnyElement> {
1757 if let Some(workspace) = workspace.upgrade() {
1758 let fs = workspace.read(cx).app_state().fs.clone();
1759 let user_store = workspace.read(cx).app_state().user_store.clone();
1760 let project = workspace.read(cx).project().clone();
1761 let weak_project = project.downgrade();
1762 let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1763 let active_thread = active_thread.read(cx);
1764 let thread = active_thread.thread().clone();
1765 let thread_store = active_thread.thread_store().clone();
1766 let text_thread_store = active_thread.text_thread_store().clone();
1767
1768 let default_message_editor = cx.new(|cx| {
1769 MessageEditor::new(
1770 fs,
1771 workspace.downgrade(),
1772 user_store,
1773 context_store,
1774 None,
1775 thread_store.downgrade(),
1776 text_thread_store.downgrade(),
1777 thread,
1778 window,
1779 cx,
1780 )
1781 });
1782
1783 Some(
1784 v_flex()
1785 .gap_4()
1786 .children(vec![single_example(
1787 "Default Message Editor",
1788 div()
1789 .w(px(540.))
1790 .pt_12()
1791 .bg(cx.theme().colors().panel_background)
1792 .border_1()
1793 .border_color(cx.theme().colors().border)
1794 .child(default_message_editor.clone())
1795 .into_any_element(),
1796 )])
1797 .into_any_element(),
1798 )
1799 } else {
1800 None
1801 }
1802 }
1803}
1804
1805register_agent_preview!(MessageEditor);