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