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