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::history_store::HistoryStore;
13use agent::{
14 context::{AgentContextKey, ContextLoadResult, load_context},
15 context_store::ContextStoreEvent,
16};
17use agent_settings::{AgentSettings, CompletionMode};
18use ai_onboarding::ApiKeysWithProviders;
19use buffer_diff::BufferDiff;
20use cloud_llm_client::CompletionIntent;
21use collections::{HashMap, HashSet};
22use editor::actions::{MoveUp, Paste};
23use editor::display_map::CreaseId;
24use editor::{
25 Addon, AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement,
26 EditorEvent, EditorMode, EditorStyle, MultiBuffer,
27};
28use file_icons::FileIcons;
29use fs::Fs;
30use futures::future::Shared;
31use futures::{FutureExt as _, future};
32use gpui::{
33 Animation, AnimationExt, App, Entity, EventEmitter, Focusable, IntoElement, KeyContext,
34 Subscription, Task, TextStyle, WeakEntity, linear_color_stop, linear_gradient, point,
35 pulsating_between,
36};
37use language::{Buffer, Language, Point};
38use language_model::{
39 ConfiguredModel, LanguageModelRegistry, LanguageModelRequestMessage, MessageContent,
40 ZED_CLOUD_PROVIDER_ID,
41};
42use multi_buffer;
43use project::Project;
44use prompt_store::PromptStore;
45use settings::Settings;
46use std::time::Duration;
47use theme::ThemeSettings;
48use ui::{
49 Callout, Disclosure, Divider, DividerColor, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*,
50};
51use util::ResultExt as _;
52use workspace::{CollaboratorId, Workspace};
53use zed_actions::agent::Chat;
54use zed_actions::agent::ToggleModelSelector;
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 context_store: Entity<ContextStore>,
81 prompt_store: Option<Entity<PromptStore>>,
82 history_store: Option<WeakEntity<HistoryStore>>,
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 context_store: Entity<ContextStore>,
160 prompt_store: Option<Entity<PromptStore>>,
161 thread_store: WeakEntity<ThreadStore>,
162 text_thread_store: WeakEntity<TextThreadStore>,
163 history_store: Option<WeakEntity<HistoryStore>>,
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 thread,
231 incompatible_tools_state: incompatible_tools.clone(),
232 workspace,
233 context_store,
234 prompt_store,
235 history_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::Small)
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::Stop,
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.project.read(cx).user_store().read(cx);
1286 if user_store.is_usage_based_billing_enabled() {
1287 return None;
1288 }
1289
1290 let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
1291
1292 let usage = user_store.model_request_usage()?;
1293
1294 Some(
1295 div()
1296 .child(UsageCallout::new(plan, usage))
1297 .line_height(line_height),
1298 )
1299 }
1300
1301 fn render_token_limit_callout(
1302 &self,
1303 line_height: Pixels,
1304 token_usage_ratio: TokenUsageRatio,
1305 cx: &mut Context<Self>,
1306 ) -> Option<Div> {
1307 let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1308 Icon::new(IconName::Close)
1309 .color(Color::Error)
1310 .size(IconSize::XSmall)
1311 } else {
1312 Icon::new(IconName::Warning)
1313 .color(Color::Warning)
1314 .size(IconSize::XSmall)
1315 };
1316
1317 let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1318 "Thread reached the token limit"
1319 } else {
1320 "Thread reaching the token limit soon"
1321 };
1322
1323 let description = if self.is_using_zed_provider(cx) {
1324 "To continue, start a new thread from a summary or turn burn mode on."
1325 } else {
1326 "To continue, start a new thread from a summary."
1327 };
1328
1329 let mut callout = Callout::new()
1330 .line_height(line_height)
1331 .icon(icon)
1332 .title(title)
1333 .description(description)
1334 .primary_action(
1335 Button::new("start-new-thread", "Start New Thread")
1336 .label_size(LabelSize::Small)
1337 .on_click(cx.listener(|this, _, window, cx| {
1338 let from_thread_id = Some(this.thread.read(cx).id().clone());
1339 window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1340 })),
1341 );
1342
1343 if self.is_using_zed_provider(cx) {
1344 callout = callout.secondary_action(
1345 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
1346 .icon_size(IconSize::XSmall)
1347 .on_click(cx.listener(|this, _event, window, cx| {
1348 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
1349 })),
1350 );
1351 }
1352
1353 Some(
1354 div()
1355 .border_t_1()
1356 .border_color(cx.theme().colors().border)
1357 .child(callout),
1358 )
1359 }
1360
1361 pub fn last_estimated_token_count(&self) -> Option<u64> {
1362 self.last_estimated_token_count
1363 }
1364
1365 pub fn is_waiting_to_update_token_count(&self) -> bool {
1366 self.update_token_count_task.is_some()
1367 }
1368
1369 fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1370 let load_task = cx.spawn(async move |this, cx| {
1371 let Ok(load_task) = this.update(cx, |this, cx| {
1372 let new_context = this
1373 .context_store
1374 .read(cx)
1375 .new_context_for_thread(this.thread.read(cx), None);
1376 load_context(new_context, &this.project, &this.prompt_store, cx)
1377 }) else {
1378 return;
1379 };
1380 let result = load_task.await;
1381 this.update(cx, |this, cx| {
1382 this.last_loaded_context = Some(result);
1383 this.load_context_task = None;
1384 this.message_or_context_changed(false, cx);
1385 })
1386 .ok();
1387 });
1388 // Replace existing load task, if any, causing it to be cancelled.
1389 let load_task = load_task.shared();
1390 self.load_context_task = Some(load_task.clone());
1391 cx.spawn(async move |this, cx| {
1392 load_task.await;
1393 this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1394 .ok()
1395 .flatten()
1396 })
1397 }
1398
1399 fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1400 self.message_or_context_changed(true, cx);
1401 }
1402
1403 fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1404 cx.emit(MessageEditorEvent::Changed);
1405 self.update_token_count_task.take();
1406
1407 let Some(model) = self.thread.read(cx).configured_model() else {
1408 self.last_estimated_token_count.take();
1409 return;
1410 };
1411
1412 let editor = self.editor.clone();
1413
1414 self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1415 if debounce {
1416 cx.background_executor()
1417 .timer(Duration::from_millis(200))
1418 .await;
1419 }
1420
1421 let token_count = if let Some(task) = this
1422 .update(cx, |this, cx| {
1423 let loaded_context = this
1424 .last_loaded_context
1425 .as_ref()
1426 .map(|context_load_result| &context_load_result.loaded_context);
1427 let message_text = editor.read(cx).text(cx);
1428
1429 if message_text.is_empty()
1430 && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1431 {
1432 return None;
1433 }
1434
1435 let mut request_message = LanguageModelRequestMessage {
1436 role: language_model::Role::User,
1437 content: Vec::new(),
1438 cache: false,
1439 };
1440
1441 if let Some(loaded_context) = loaded_context {
1442 loaded_context.add_to_request_message(&mut request_message);
1443 }
1444
1445 if !message_text.is_empty() {
1446 request_message
1447 .content
1448 .push(MessageContent::Text(message_text));
1449 }
1450
1451 let request = language_model::LanguageModelRequest {
1452 thread_id: None,
1453 prompt_id: None,
1454 intent: None,
1455 mode: None,
1456 messages: vec![request_message],
1457 tools: vec![],
1458 tool_choice: None,
1459 stop: vec![],
1460 temperature: AgentSettings::temperature_for_model(&model.model, cx),
1461 thinking_allowed: true,
1462 };
1463
1464 Some(model.model.count_tokens(request, cx))
1465 })
1466 .ok()
1467 .flatten()
1468 {
1469 task.await.log_err()
1470 } else {
1471 Some(0)
1472 };
1473
1474 this.update(cx, |this, cx| {
1475 if let Some(token_count) = token_count {
1476 this.last_estimated_token_count = Some(token_count);
1477 cx.emit(MessageEditorEvent::EstimatedTokenCount);
1478 }
1479 this.update_token_count_task.take();
1480 })
1481 .ok();
1482 }));
1483 }
1484}
1485
1486#[derive(Default)]
1487pub struct ContextCreasesAddon {
1488 creases: HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>>,
1489 _subscription: Option<Subscription>,
1490}
1491
1492pub struct MessageEditorAddon {}
1493
1494impl MessageEditorAddon {
1495 pub fn new() -> Self {
1496 Self {}
1497 }
1498}
1499
1500impl Addon for MessageEditorAddon {
1501 fn to_any(&self) -> &dyn std::any::Any {
1502 self
1503 }
1504
1505 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1506 Some(self)
1507 }
1508
1509 fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
1510 let settings = agent_settings::AgentSettings::get_global(cx);
1511 if settings.use_modifier_to_send {
1512 key_context.add("use_modifier_to_send");
1513 }
1514 }
1515}
1516
1517impl Addon for ContextCreasesAddon {
1518 fn to_any(&self) -> &dyn std::any::Any {
1519 self
1520 }
1521
1522 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1523 Some(self)
1524 }
1525}
1526
1527impl ContextCreasesAddon {
1528 pub fn new() -> Self {
1529 Self {
1530 creases: HashMap::default(),
1531 _subscription: None,
1532 }
1533 }
1534
1535 pub fn add_creases(
1536 &mut self,
1537 context_store: &Entity<ContextStore>,
1538 key: AgentContextKey,
1539 creases: impl IntoIterator<Item = (CreaseId, SharedString)>,
1540 cx: &mut Context<Editor>,
1541 ) {
1542 self.creases.entry(key).or_default().extend(creases);
1543 self._subscription = Some(cx.subscribe(
1544 &context_store,
1545 |editor, _, event, cx| match event {
1546 ContextStoreEvent::ContextRemoved(key) => {
1547 let Some(this) = editor.addon_mut::<Self>() else {
1548 return;
1549 };
1550 let (crease_ids, replacement_texts): (Vec<_>, Vec<_>) = this
1551 .creases
1552 .remove(key)
1553 .unwrap_or_default()
1554 .into_iter()
1555 .unzip();
1556 let ranges = editor
1557 .remove_creases(crease_ids, cx)
1558 .into_iter()
1559 .map(|(_, range)| range)
1560 .collect::<Vec<_>>();
1561 editor.unfold_ranges(&ranges, false, false, cx);
1562 editor.edit(ranges.into_iter().zip(replacement_texts), cx);
1563 cx.notify();
1564 }
1565 },
1566 ))
1567 }
1568
1569 pub fn into_inner(self) -> HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>> {
1570 self.creases
1571 }
1572}
1573
1574pub fn extract_message_creases(
1575 editor: &mut Editor,
1576 cx: &mut Context<'_, Editor>,
1577) -> Vec<MessageCrease> {
1578 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1579 let mut contexts_by_crease_id = editor
1580 .addon_mut::<ContextCreasesAddon>()
1581 .map(std::mem::take)
1582 .unwrap_or_default()
1583 .into_inner()
1584 .into_iter()
1585 .flat_map(|(key, creases)| {
1586 let context = key.0;
1587 creases
1588 .into_iter()
1589 .map(move |(id, _)| (id, context.clone()))
1590 })
1591 .collect::<HashMap<_, _>>();
1592 // Filter the addon's list of creases based on what the editor reports,
1593 // since the addon might have removed creases in it.
1594 let creases = editor.display_map.update(cx, |display_map, cx| {
1595 display_map
1596 .snapshot(cx)
1597 .crease_snapshot
1598 .creases()
1599 .filter_map(|(id, crease)| {
1600 Some((
1601 id,
1602 (
1603 crease.range().to_offset(&buffer_snapshot),
1604 crease.metadata()?.clone(),
1605 ),
1606 ))
1607 })
1608 .map(|(id, (range, metadata))| {
1609 let context = contexts_by_crease_id.remove(&id);
1610 MessageCrease {
1611 range,
1612 context,
1613 label: metadata.label,
1614 icon_path: metadata.icon_path,
1615 }
1616 })
1617 .collect()
1618 });
1619 creases
1620}
1621
1622impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1623
1624pub enum MessageEditorEvent {
1625 EstimatedTokenCount,
1626 Changed,
1627 ScrollThreadToBottom,
1628}
1629
1630impl Focusable for MessageEditor {
1631 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1632 self.editor.focus_handle(cx)
1633 }
1634}
1635
1636impl Render for MessageEditor {
1637 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1638 let thread = self.thread.read(cx);
1639 let token_usage_ratio = thread
1640 .total_token_usage()
1641 .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1642 total_token_usage.ratio()
1643 });
1644
1645 let burn_mode_enabled = thread.completion_mode() == CompletionMode::Burn;
1646
1647 let action_log = self.thread.read(cx).action_log();
1648 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1649
1650 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1651
1652 let has_configured_providers = LanguageModelRegistry::read_global(cx)
1653 .providers()
1654 .iter()
1655 .filter(|provider| {
1656 provider.is_authenticated(cx) && provider.id() != ZED_CLOUD_PROVIDER_ID
1657 })
1658 .count()
1659 > 0;
1660
1661 let is_signed_out = self
1662 .workspace
1663 .read_with(cx, |workspace, _| {
1664 workspace.client().status().borrow().is_signed_out()
1665 })
1666 .unwrap_or(true);
1667
1668 let has_history = self
1669 .history_store
1670 .as_ref()
1671 .and_then(|hs| hs.update(cx, |hs, cx| hs.entries(cx).len() > 0).ok())
1672 .unwrap_or(false)
1673 || self
1674 .thread
1675 .read_with(cx, |thread, _| thread.messages().len() > 0);
1676
1677 v_flex()
1678 .size_full()
1679 .bg(cx.theme().colors().panel_background)
1680 .when(
1681 !has_history && is_signed_out && has_configured_providers,
1682 |this| this.child(cx.new(ApiKeysWithProviders::new)),
1683 )
1684 .when(changed_buffers.len() > 0, |parent| {
1685 parent.child(self.render_edits_bar(&changed_buffers, window, cx))
1686 })
1687 .child(self.render_editor(window, cx))
1688 .children({
1689 let usage_callout = self.render_usage_callout(line_height, cx);
1690
1691 if usage_callout.is_some() {
1692 usage_callout
1693 } else if token_usage_ratio != TokenUsageRatio::Normal && !burn_mode_enabled {
1694 self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1695 } else {
1696 None
1697 }
1698 })
1699 }
1700}
1701
1702pub fn insert_message_creases(
1703 editor: &mut Editor,
1704 message_creases: &[MessageCrease],
1705 context_store: &Entity<ContextStore>,
1706 window: &mut Window,
1707 cx: &mut Context<'_, Editor>,
1708) {
1709 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1710 let creases = message_creases
1711 .iter()
1712 .map(|crease| {
1713 let start = buffer_snapshot.anchor_after(crease.range.start);
1714 let end = buffer_snapshot.anchor_before(crease.range.end);
1715 crease_for_mention(
1716 crease.label.clone(),
1717 crease.icon_path.clone(),
1718 start..end,
1719 cx.weak_entity(),
1720 )
1721 })
1722 .collect::<Vec<_>>();
1723 let ids = editor.insert_creases(creases.clone(), cx);
1724 editor.fold_creases(creases, false, window, cx);
1725 if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1726 for (crease, id) in message_creases.iter().zip(ids) {
1727 if let Some(context) = crease.context.as_ref() {
1728 let key = AgentContextKey(context.clone());
1729 addon.add_creases(context_store, key, vec![(id, crease.label.clone())], cx);
1730 }
1731 }
1732 }
1733}
1734impl Component for MessageEditor {
1735 fn scope() -> ComponentScope {
1736 ComponentScope::Agent
1737 }
1738
1739 fn description() -> Option<&'static str> {
1740 Some(
1741 "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1742 )
1743 }
1744}
1745
1746impl AgentPreview for MessageEditor {
1747 fn agent_preview(
1748 workspace: WeakEntity<Workspace>,
1749 active_thread: Entity<ActiveThread>,
1750 window: &mut Window,
1751 cx: &mut App,
1752 ) -> Option<AnyElement> {
1753 if let Some(workspace) = workspace.upgrade() {
1754 let fs = workspace.read(cx).app_state().fs.clone();
1755 let project = workspace.read(cx).project().clone();
1756 let weak_project = project.downgrade();
1757 let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1758 let active_thread = active_thread.read(cx);
1759 let thread = active_thread.thread().clone();
1760 let thread_store = active_thread.thread_store().clone();
1761 let text_thread_store = active_thread.text_thread_store().clone();
1762
1763 let default_message_editor = cx.new(|cx| {
1764 MessageEditor::new(
1765 fs,
1766 workspace.downgrade(),
1767 context_store,
1768 None,
1769 thread_store.downgrade(),
1770 text_thread_store.downgrade(),
1771 None,
1772 thread,
1773 window,
1774 cx,
1775 )
1776 });
1777
1778 Some(
1779 v_flex()
1780 .gap_4()
1781 .children(vec![single_example(
1782 "Default Message Editor",
1783 div()
1784 .w(px(540.))
1785 .pt_12()
1786 .bg(cx.theme().colors().panel_background)
1787 .border_1()
1788 .border_color(cx.theme().colors().border)
1789 .child(default_message_editor.clone())
1790 .into_any_element(),
1791 )])
1792 .into_any_element(),
1793 )
1794 } else {
1795 None
1796 }
1797 }
1798}
1799
1800register_agent_preview!(MessageEditor);