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