1use anyhow::Result;
2use client::{Client, UserStore, zed_urls};
3use cloud_llm_client::UsageLimit;
4use codestral::CodestralCompletionProvider;
5use copilot::{Copilot, Status};
6use editor::{
7 Editor, MultiBufferOffset, SelectionEffects, actions::ShowEditPrediction, scroll::Autoscroll,
8};
9use feature_flags::{FeatureFlagAppExt, PredictEditsRateCompletionsFeatureFlag};
10use fs::Fs;
11use gpui::{
12 Action, Animation, AnimationExt, App, AsyncWindowContext, Corner, Entity, FocusHandle,
13 Focusable, IntoElement, ParentElement, Render, Subscription, WeakEntity, actions, div,
14 pulsating_between,
15};
16use indoc::indoc;
17use language::{
18 EditPredictionsMode, File, Language,
19 language_settings::{self, AllLanguageSettings, EditPredictionProvider, all_language_settings},
20};
21use project::DisableAiSettings;
22use regex::Regex;
23use settings::{
24 EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME, Settings, SettingsStore, update_settings_file,
25};
26use std::{
27 sync::{Arc, LazyLock},
28 time::Duration,
29};
30use supermaven::{AccountStatus, Supermaven};
31use ui::{
32 Clickable, ContextMenu, ContextMenuEntry, DocumentationEdge, DocumentationSide, IconButton,
33 IconButtonShape, Indicator, PopoverMenu, PopoverMenuHandle, ProgressBar, Tooltip, prelude::*,
34};
35use workspace::{
36 StatusItemView, Toast, Workspace, create_and_open_local_file, item::ItemHandle,
37 notifications::NotificationId,
38};
39use zed_actions::OpenBrowser;
40use zeta::RateCompletions;
41use zeta2::SweepFeatureFlag;
42
43actions!(
44 edit_prediction,
45 [
46 /// Toggles the edit prediction menu.
47 ToggleMenu
48 ]
49);
50
51const COPILOT_SETTINGS_PATH: &str = "/settings/copilot";
52const COPILOT_SETTINGS_URL: &str = concat!("https://github.com", "/settings/copilot");
53const PRIVACY_DOCS: &str = "https://zed.dev/docs/ai/privacy-and-security";
54
55struct CopilotErrorToast;
56
57pub struct EditPredictionButton {
58 editor_subscription: Option<(Subscription, usize)>,
59 editor_enabled: Option<bool>,
60 editor_show_predictions: bool,
61 editor_focus_handle: Option<FocusHandle>,
62 language: Option<Arc<Language>>,
63 file: Option<Arc<dyn File>>,
64 edit_prediction_provider: Option<Arc<dyn edit_prediction::EditPredictionProviderHandle>>,
65 fs: Arc<dyn Fs>,
66 user_store: Entity<UserStore>,
67 popover_menu_handle: PopoverMenuHandle<ContextMenu>,
68}
69
70enum SupermavenButtonStatus {
71 Ready,
72 Errored(String),
73 NeedsActivation(String),
74 Initializing,
75}
76
77impl Render for EditPredictionButton {
78 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
79 // Return empty div if AI is disabled
80 if DisableAiSettings::get_global(cx).disable_ai {
81 return div().hidden();
82 }
83
84 let all_language_settings = all_language_settings(None, cx);
85
86 match &all_language_settings.edit_predictions.provider {
87 EditPredictionProvider::None => div().hidden(),
88
89 EditPredictionProvider::Copilot => {
90 let Some(copilot) = Copilot::global(cx) else {
91 return div().hidden();
92 };
93 let status = copilot.read(cx).status();
94
95 let enabled = self.editor_enabled.unwrap_or(false);
96
97 let icon = match status {
98 Status::Error(_) => IconName::CopilotError,
99 Status::Authorized => {
100 if enabled {
101 IconName::Copilot
102 } else {
103 IconName::CopilotDisabled
104 }
105 }
106 _ => IconName::CopilotInit,
107 };
108
109 if let Status::Error(e) = status {
110 return div().child(
111 IconButton::new("copilot-error", icon)
112 .icon_size(IconSize::Small)
113 .on_click(cx.listener(move |_, _, window, cx| {
114 if let Some(workspace) = window.root::<Workspace>().flatten() {
115 workspace.update(cx, |workspace, cx| {
116 workspace.show_toast(
117 Toast::new(
118 NotificationId::unique::<CopilotErrorToast>(),
119 format!("Copilot can't be started: {}", e),
120 )
121 .on_click(
122 "Reinstall Copilot",
123 |window, cx| {
124 copilot::reinstall_and_sign_in(window, cx)
125 },
126 ),
127 cx,
128 );
129 });
130 }
131 }))
132 .tooltip(|_window, cx| {
133 Tooltip::for_action("GitHub Copilot", &ToggleMenu, cx)
134 }),
135 );
136 }
137 let this = cx.weak_entity();
138
139 div().child(
140 PopoverMenu::new("copilot")
141 .menu(move |window, cx| {
142 let current_status = Copilot::global(cx)?.read(cx).status();
143 match current_status {
144 Status::Authorized => this.update(cx, |this, cx| {
145 this.build_copilot_context_menu(window, cx)
146 }),
147 _ => this.update(cx, |this, cx| {
148 this.build_copilot_start_menu(window, cx)
149 }),
150 }
151 .ok()
152 })
153 .anchor(Corner::BottomRight)
154 .trigger_with_tooltip(
155 IconButton::new("copilot-icon", icon),
156 |_window, cx| Tooltip::for_action("GitHub Copilot", &ToggleMenu, cx),
157 )
158 .with_handle(self.popover_menu_handle.clone()),
159 )
160 }
161
162 EditPredictionProvider::Supermaven => {
163 let Some(supermaven) = Supermaven::global(cx) else {
164 return div();
165 };
166
167 let supermaven = supermaven.read(cx);
168
169 let status = match supermaven {
170 Supermaven::Starting => SupermavenButtonStatus::Initializing,
171 Supermaven::FailedDownload { error } => {
172 SupermavenButtonStatus::Errored(error.to_string())
173 }
174 Supermaven::Spawned(agent) => {
175 let account_status = agent.account_status.clone();
176 match account_status {
177 AccountStatus::NeedsActivation { activate_url } => {
178 SupermavenButtonStatus::NeedsActivation(activate_url)
179 }
180 AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
181 AccountStatus::Ready => SupermavenButtonStatus::Ready,
182 }
183 }
184 Supermaven::Error { error } => {
185 SupermavenButtonStatus::Errored(error.to_string())
186 }
187 };
188
189 let icon = status.to_icon();
190 let tooltip_text = status.to_tooltip();
191 let has_menu = status.has_menu();
192 let this = cx.weak_entity();
193 let fs = self.fs.clone();
194
195 div().child(
196 PopoverMenu::new("supermaven")
197 .menu(move |window, cx| match &status {
198 SupermavenButtonStatus::NeedsActivation(activate_url) => {
199 Some(ContextMenu::build(window, cx, |menu, _, _| {
200 let fs = fs.clone();
201 let activate_url = activate_url.clone();
202
203 menu.entry("Sign In", None, move |_, cx| {
204 cx.open_url(activate_url.as_str())
205 })
206 .entry(
207 "Use Zed AI",
208 None,
209 move |_, cx| {
210 set_completion_provider(
211 fs.clone(),
212 cx,
213 EditPredictionProvider::Zed,
214 )
215 },
216 )
217 }))
218 }
219 SupermavenButtonStatus::Ready => this
220 .update(cx, |this, cx| {
221 this.build_supermaven_context_menu(window, cx)
222 })
223 .ok(),
224 _ => None,
225 })
226 .anchor(Corner::BottomRight)
227 .trigger_with_tooltip(
228 IconButton::new("supermaven-icon", icon),
229 move |window, cx| {
230 if has_menu {
231 Tooltip::for_action(tooltip_text.clone(), &ToggleMenu, cx)
232 } else {
233 Tooltip::text(tooltip_text.clone())(window, cx)
234 }
235 },
236 )
237 .with_handle(self.popover_menu_handle.clone()),
238 )
239 }
240
241 EditPredictionProvider::Codestral => {
242 let enabled = self.editor_enabled.unwrap_or(true);
243 let has_api_key = CodestralCompletionProvider::has_api_key(cx);
244 let fs = self.fs.clone();
245 let this = cx.weak_entity();
246
247 div().child(
248 PopoverMenu::new("codestral")
249 .menu(move |window, cx| {
250 if has_api_key {
251 this.update(cx, |this, cx| {
252 this.build_codestral_context_menu(window, cx)
253 })
254 .ok()
255 } else {
256 Some(ContextMenu::build(window, cx, |menu, _, _| {
257 let fs = fs.clone();
258
259 menu.entry(
260 "Configure Codestral API Key",
261 None,
262 move |window, cx| {
263 window.dispatch_action(
264 zed_actions::agent::OpenSettings.boxed_clone(),
265 cx,
266 );
267 },
268 )
269 .separator()
270 .entry(
271 "Use Zed AI instead",
272 None,
273 move |_, cx| {
274 set_completion_provider(
275 fs.clone(),
276 cx,
277 EditPredictionProvider::Zed,
278 )
279 },
280 )
281 }))
282 }
283 })
284 .anchor(Corner::BottomRight)
285 .trigger_with_tooltip(
286 IconButton::new("codestral-icon", IconName::AiMistral)
287 .shape(IconButtonShape::Square)
288 .when(!has_api_key, |this| {
289 this.indicator(Indicator::dot().color(Color::Error))
290 .indicator_border_color(Some(
291 cx.theme().colors().status_bar_background,
292 ))
293 })
294 .when(has_api_key && !enabled, |this| {
295 this.indicator(Indicator::dot().color(Color::Ignored))
296 .indicator_border_color(Some(
297 cx.theme().colors().status_bar_background,
298 ))
299 }),
300 move |_window, cx| Tooltip::for_action("Codestral", &ToggleMenu, cx),
301 )
302 .with_handle(self.popover_menu_handle.clone()),
303 )
304 }
305 EditPredictionProvider::Experimental(provider_name) => {
306 if *provider_name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME
307 && cx.has_flag::<SweepFeatureFlag>()
308 {
309 div().child(Icon::new(IconName::SweepAi))
310 } else {
311 div()
312 }
313 }
314
315 EditPredictionProvider::Zed => {
316 let enabled = self.editor_enabled.unwrap_or(true);
317
318 let zeta_icon = if enabled {
319 IconName::ZedPredict
320 } else {
321 IconName::ZedPredictDisabled
322 };
323
324 if zeta::should_show_upsell_modal() {
325 let tooltip_meta = if self.user_store.read(cx).current_user().is_some() {
326 "Choose a Plan"
327 } else {
328 "Sign In"
329 };
330
331 return div().child(
332 IconButton::new("zed-predict-pending-button", zeta_icon)
333 .shape(IconButtonShape::Square)
334 .indicator(Indicator::dot().color(Color::Muted))
335 .indicator_border_color(Some(cx.theme().colors().status_bar_background))
336 .tooltip(move |_window, cx| {
337 Tooltip::with_meta("Edit Predictions", None, tooltip_meta, cx)
338 })
339 .on_click(cx.listener(move |_, _, window, cx| {
340 telemetry::event!(
341 "Pending ToS Clicked",
342 source = "Edit Prediction Status Button"
343 );
344 window.dispatch_action(
345 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
346 cx,
347 );
348 })),
349 );
350 }
351
352 let mut over_limit = false;
353
354 if let Some(usage) = self
355 .edit_prediction_provider
356 .as_ref()
357 .and_then(|provider| provider.usage(cx))
358 {
359 over_limit = usage.over_limit()
360 }
361
362 let show_editor_predictions = self.editor_show_predictions;
363
364 let icon_button = IconButton::new("zed-predict-pending-button", zeta_icon)
365 .shape(IconButtonShape::Square)
366 .when(
367 enabled && (!show_editor_predictions || over_limit),
368 |this| {
369 this.indicator(Indicator::dot().when_else(
370 over_limit,
371 |dot| dot.color(Color::Error),
372 |dot| dot.color(Color::Muted),
373 ))
374 .indicator_border_color(Some(cx.theme().colors().status_bar_background))
375 },
376 )
377 .when(!self.popover_menu_handle.is_deployed(), |element| {
378 element.tooltip(move |_window, cx| {
379 if enabled {
380 if show_editor_predictions {
381 Tooltip::for_action("Edit Prediction", &ToggleMenu, cx)
382 } else {
383 Tooltip::with_meta(
384 "Edit Prediction",
385 Some(&ToggleMenu),
386 "Hidden For This File",
387 cx,
388 )
389 }
390 } else {
391 Tooltip::with_meta(
392 "Edit Prediction",
393 Some(&ToggleMenu),
394 "Disabled For This File",
395 cx,
396 )
397 }
398 })
399 });
400
401 let this = cx.weak_entity();
402
403 let mut popover_menu = PopoverMenu::new("zeta")
404 .menu(move |window, cx| {
405 this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx))
406 .ok()
407 })
408 .anchor(Corner::BottomRight)
409 .with_handle(self.popover_menu_handle.clone());
410
411 let is_refreshing = self
412 .edit_prediction_provider
413 .as_ref()
414 .is_some_and(|provider| provider.is_refreshing(cx));
415
416 if is_refreshing {
417 popover_menu = popover_menu.trigger(
418 icon_button.with_animation(
419 "pulsating-label",
420 Animation::new(Duration::from_secs(2))
421 .repeat()
422 .with_easing(pulsating_between(0.2, 1.0)),
423 |icon_button, delta| icon_button.alpha(delta),
424 ),
425 );
426 } else {
427 popover_menu = popover_menu.trigger(icon_button);
428 }
429
430 div().child(popover_menu.into_any_element())
431 }
432 }
433 }
434}
435
436impl EditPredictionButton {
437 pub fn new(
438 fs: Arc<dyn Fs>,
439 user_store: Entity<UserStore>,
440 popover_menu_handle: PopoverMenuHandle<ContextMenu>,
441 client: Arc<Client>,
442 cx: &mut Context<Self>,
443 ) -> Self {
444 if let Some(copilot) = Copilot::global(cx) {
445 cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
446 }
447
448 cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
449 .detach();
450
451 CodestralCompletionProvider::ensure_api_key_loaded(client.http_client(), cx);
452
453 Self {
454 editor_subscription: None,
455 editor_enabled: None,
456 editor_show_predictions: true,
457 editor_focus_handle: None,
458 language: None,
459 file: None,
460 edit_prediction_provider: None,
461 user_store,
462 popover_menu_handle,
463 fs,
464 }
465 }
466
467 fn get_available_providers(&self, cx: &App) -> Vec<EditPredictionProvider> {
468 let mut providers = Vec::new();
469
470 providers.push(EditPredictionProvider::Zed);
471
472 if let Some(copilot) = Copilot::global(cx) {
473 if matches!(copilot.read(cx).status(), Status::Authorized) {
474 providers.push(EditPredictionProvider::Copilot);
475 }
476 }
477
478 if let Some(supermaven) = Supermaven::global(cx) {
479 if let Supermaven::Spawned(agent) = supermaven.read(cx) {
480 if matches!(agent.account_status, AccountStatus::Ready) {
481 providers.push(EditPredictionProvider::Supermaven);
482 }
483 }
484 }
485
486 if CodestralCompletionProvider::has_api_key(cx) {
487 providers.push(EditPredictionProvider::Codestral);
488 }
489
490 providers
491 }
492
493 fn add_provider_switching_section(
494 &self,
495 mut menu: ContextMenu,
496 current_provider: EditPredictionProvider,
497 cx: &App,
498 ) -> ContextMenu {
499 let available_providers = self.get_available_providers(cx);
500
501 let other_providers: Vec<_> = available_providers
502 .into_iter()
503 .filter(|p| *p != current_provider && *p != EditPredictionProvider::None)
504 .collect();
505
506 if !other_providers.is_empty() {
507 menu = menu.separator().header("Switch Providers");
508
509 for provider in other_providers {
510 let fs = self.fs.clone();
511
512 menu = match provider {
513 EditPredictionProvider::Zed => menu.item(
514 ContextMenuEntry::new("Zed AI")
515 .documentation_aside(
516 DocumentationSide::Left,
517 DocumentationEdge::Top,
518 |_| {
519 Label::new("Zed's edit prediction is powered by Zeta, an open-source, dataset mode.")
520 .into_any_element()
521 },
522 )
523 .handler(move |_, cx| {
524 set_completion_provider(fs.clone(), cx, provider);
525 }),
526 ),
527 EditPredictionProvider::Copilot => {
528 menu.entry("GitHub Copilot", None, move |_, cx| {
529 set_completion_provider(fs.clone(), cx, provider);
530 })
531 }
532 EditPredictionProvider::Supermaven => {
533 menu.entry("Supermaven", None, move |_, cx| {
534 set_completion_provider(fs.clone(), cx, provider);
535 })
536 }
537 EditPredictionProvider::Codestral => {
538 menu.entry("Codestral", None, move |_, cx| {
539 set_completion_provider(fs.clone(), cx, provider);
540 })
541 }
542 EditPredictionProvider::None | EditPredictionProvider::Experimental(_) => continue,
543 };
544 }
545 }
546
547 menu
548 }
549
550 pub fn build_copilot_start_menu(
551 &mut self,
552 window: &mut Window,
553 cx: &mut Context<Self>,
554 ) -> Entity<ContextMenu> {
555 let fs = self.fs.clone();
556 ContextMenu::build(window, cx, |menu, _, _| {
557 menu.entry("Sign In to Copilot", None, copilot::initiate_sign_in)
558 .entry("Disable Copilot", None, {
559 let fs = fs.clone();
560 move |_window, cx| hide_copilot(fs.clone(), cx)
561 })
562 .separator()
563 .entry("Use Zed AI", None, {
564 let fs = fs.clone();
565 move |_window, cx| {
566 set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
567 }
568 })
569 })
570 }
571
572 pub fn build_language_settings_menu(
573 &self,
574 mut menu: ContextMenu,
575 window: &Window,
576 cx: &mut App,
577 ) -> ContextMenu {
578 let fs = self.fs.clone();
579 let line_height = window.line_height();
580
581 menu = menu.header("Show Edit Predictions For");
582
583 let language_state = self.language.as_ref().map(|language| {
584 (
585 language.clone(),
586 language_settings::language_settings(Some(language.name()), None, cx)
587 .show_edit_predictions,
588 )
589 });
590
591 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
592 let entry = ContextMenuEntry::new("This Buffer")
593 .toggleable(IconPosition::Start, self.editor_show_predictions)
594 .action(Box::new(editor::actions::ToggleEditPrediction))
595 .handler(move |window, cx| {
596 editor_focus_handle.dispatch_action(
597 &editor::actions::ToggleEditPrediction,
598 window,
599 cx,
600 );
601 });
602
603 match language_state.clone() {
604 Some((language, false)) => {
605 menu = menu.item(
606 entry
607 .disabled(true)
608 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_cx| {
609 Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
610 .into_any_element()
611 })
612 );
613 }
614 Some(_) | None => menu = menu.item(entry),
615 }
616 }
617
618 if let Some((language, language_enabled)) = language_state {
619 let fs = fs.clone();
620
621 menu = menu.toggleable_entry(
622 language.name(),
623 language_enabled,
624 IconPosition::Start,
625 None,
626 move |_, cx| {
627 toggle_show_edit_predictions_for_language(language.clone(), fs.clone(), cx)
628 },
629 );
630 }
631
632 let settings = AllLanguageSettings::get_global(cx);
633
634 let globally_enabled = settings.show_edit_predictions(None, cx);
635 let entry = ContextMenuEntry::new("All Files")
636 .toggleable(IconPosition::Start, globally_enabled)
637 .action(workspace::ToggleEditPrediction.boxed_clone())
638 .handler(|window, cx| {
639 window.dispatch_action(workspace::ToggleEditPrediction.boxed_clone(), cx)
640 });
641 menu = menu.item(entry);
642
643 let provider = settings.edit_predictions.provider;
644 let current_mode = settings.edit_predictions_mode();
645 let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
646 let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
647
648 if matches!(
649 provider,
650 EditPredictionProvider::Zed
651 | EditPredictionProvider::Copilot
652 | EditPredictionProvider::Supermaven
653 | EditPredictionProvider::Codestral
654 ) {
655 menu = menu
656 .separator()
657 .header("Display Modes")
658 .item(
659 ContextMenuEntry::new("Eager")
660 .toggleable(IconPosition::Start, eager_mode)
661 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
662 Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
663 })
664 .handler({
665 let fs = fs.clone();
666 move |_, cx| {
667 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
668 }
669 }),
670 )
671 .item(
672 ContextMenuEntry::new("Subtle")
673 .toggleable(IconPosition::Start, subtle_mode)
674 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
675 Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
676 })
677 .handler({
678 let fs = fs.clone();
679 move |_, cx| {
680 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
681 }
682 }),
683 );
684 }
685
686 menu = menu.separator().header("Privacy");
687
688 if let Some(provider) = &self.edit_prediction_provider {
689 let data_collection = provider.data_collection_state(cx);
690
691 if data_collection.is_supported() {
692 let provider = provider.clone();
693 let enabled = data_collection.is_enabled();
694 let is_open_source = data_collection.is_project_open_source();
695 let is_collecting = data_collection.is_enabled();
696 let (icon_name, icon_color) = if is_open_source && is_collecting {
697 (IconName::Check, Color::Success)
698 } else {
699 (IconName::Check, Color::Accent)
700 };
701
702 menu = menu.item(
703 ContextMenuEntry::new("Training Data Collection")
704 .toggleable(IconPosition::Start, data_collection.is_enabled())
705 .icon(icon_name)
706 .icon_color(icon_color)
707 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |cx| {
708 let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
709 (true, true) => (
710 "Project identified as open source, and you're sharing data.",
711 Color::Default,
712 IconName::Check,
713 Color::Success,
714 ),
715 (true, false) => (
716 "Project identified as open source, but you're not sharing data.",
717 Color::Muted,
718 IconName::Close,
719 Color::Muted,
720 ),
721 (false, true) => (
722 "Project not identified as open source. No data captured.",
723 Color::Muted,
724 IconName::Close,
725 Color::Muted,
726 ),
727 (false, false) => (
728 "Project not identified as open source, and setting turned off.",
729 Color::Muted,
730 IconName::Close,
731 Color::Muted,
732 ),
733 };
734 v_flex()
735 .gap_2()
736 .child(
737 Label::new(indoc!{
738 "Help us improve our open dataset model by sharing data from open source repositories. \
739 Zed must detect a license file in your repo for this setting to take effect. \
740 Files with sensitive data and secrets are excluded by default."
741 })
742 )
743 .child(
744 h_flex()
745 .items_start()
746 .pt_2()
747 .pr_1()
748 .flex_1()
749 .gap_1p5()
750 .border_t_1()
751 .border_color(cx.theme().colors().border_variant)
752 .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
753 .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
754 )
755 .into_any_element()
756 })
757 .handler(move |_, cx| {
758 provider.toggle_data_collection(cx);
759
760 if !enabled {
761 telemetry::event!(
762 "Data Collection Enabled",
763 source = "Edit Prediction Status Menu"
764 );
765 } else {
766 telemetry::event!(
767 "Data Collection Disabled",
768 source = "Edit Prediction Status Menu"
769 );
770 }
771 })
772 );
773
774 if is_collecting && !is_open_source {
775 menu = menu.item(
776 ContextMenuEntry::new("No data captured.")
777 .disabled(true)
778 .icon(IconName::Close)
779 .icon_color(Color::Error)
780 .icon_size(IconSize::Small),
781 );
782 }
783 }
784 }
785
786 menu = menu.item(
787 ContextMenuEntry::new("Configure Excluded Files")
788 .icon(IconName::LockOutlined)
789 .icon_color(Color::Muted)
790 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, |_| {
791 Label::new(indoc!{"
792 Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
793 })
794 .handler(move |window, cx| {
795 if let Some(workspace) = window.root().flatten() {
796 let workspace = workspace.downgrade();
797 window
798 .spawn(cx, async |cx| {
799 open_disabled_globs_setting_in_editor(
800 workspace,
801 cx,
802 ).await
803 })
804 .detach_and_log_err(cx);
805 }
806 }),
807 ).item(
808 ContextMenuEntry::new("View Docs")
809 .icon(IconName::FileGeneric)
810 .icon_color(Color::Muted)
811 .handler(move |_, cx| {
812 cx.open_url(PRIVACY_DOCS);
813 })
814 );
815
816 if !self.editor_enabled.unwrap_or(true) {
817 menu = menu.item(
818 ContextMenuEntry::new("This file is excluded.")
819 .disabled(true)
820 .icon(IconName::ZedPredictDisabled)
821 .icon_size(IconSize::Small),
822 );
823 }
824
825 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
826 menu = menu
827 .separator()
828 .header("Actions")
829 .entry(
830 "Predict Edit at Cursor",
831 Some(Box::new(ShowEditPrediction)),
832 {
833 let editor_focus_handle = editor_focus_handle.clone();
834 move |window, cx| {
835 editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
836 }
837 },
838 )
839 .context(editor_focus_handle)
840 .when(
841 cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
842 |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
843 );
844 }
845
846 menu
847 }
848
849 fn build_copilot_context_menu(
850 &self,
851 window: &mut Window,
852 cx: &mut Context<Self>,
853 ) -> Entity<ContextMenu> {
854 let all_language_settings = all_language_settings(None, cx);
855 let copilot_config = copilot::copilot_chat::CopilotChatConfiguration {
856 enterprise_uri: all_language_settings
857 .edit_predictions
858 .copilot
859 .enterprise_uri
860 .clone(),
861 };
862 let settings_url = copilot_settings_url(copilot_config.enterprise_uri.as_deref());
863
864 ContextMenu::build(window, cx, |menu, window, cx| {
865 let menu = self.build_language_settings_menu(menu, window, cx);
866 let menu =
867 self.add_provider_switching_section(menu, EditPredictionProvider::Copilot, cx);
868
869 menu.separator()
870 .link(
871 "Go to Copilot Settings",
872 OpenBrowser { url: settings_url }.boxed_clone(),
873 )
874 .action("Sign Out", copilot::SignOut.boxed_clone())
875 })
876 }
877
878 fn build_supermaven_context_menu(
879 &self,
880 window: &mut Window,
881 cx: &mut Context<Self>,
882 ) -> Entity<ContextMenu> {
883 ContextMenu::build(window, cx, |menu, window, cx| {
884 let menu = self.build_language_settings_menu(menu, window, cx);
885 let menu =
886 self.add_provider_switching_section(menu, EditPredictionProvider::Supermaven, cx);
887
888 menu.separator()
889 .action("Sign Out", supermaven::SignOut.boxed_clone())
890 })
891 }
892
893 fn build_codestral_context_menu(
894 &self,
895 window: &mut Window,
896 cx: &mut Context<Self>,
897 ) -> Entity<ContextMenu> {
898 ContextMenu::build(window, cx, |menu, window, cx| {
899 let menu = self.build_language_settings_menu(menu, window, cx);
900 let menu =
901 self.add_provider_switching_section(menu, EditPredictionProvider::Codestral, cx);
902
903 menu.separator()
904 .entry("Configure Codestral API Key", None, move |window, cx| {
905 window.dispatch_action(zed_actions::agent::OpenSettings.boxed_clone(), cx);
906 })
907 })
908 }
909
910 fn build_zeta_context_menu(
911 &self,
912 window: &mut Window,
913 cx: &mut Context<Self>,
914 ) -> Entity<ContextMenu> {
915 ContextMenu::build(window, cx, |mut menu, window, cx| {
916 if let Some(usage) = self
917 .edit_prediction_provider
918 .as_ref()
919 .and_then(|provider| provider.usage(cx))
920 {
921 menu = menu.header("Usage");
922 menu = menu
923 .custom_entry(
924 move |_window, cx| {
925 let used_percentage = match usage.limit {
926 UsageLimit::Limited(limit) => {
927 Some((usage.amount as f32 / limit as f32) * 100.)
928 }
929 UsageLimit::Unlimited => None,
930 };
931
932 h_flex()
933 .flex_1()
934 .gap_1p5()
935 .children(
936 used_percentage.map(|percent| {
937 ProgressBar::new("usage", percent, 100., cx)
938 }),
939 )
940 .child(
941 Label::new(match usage.limit {
942 UsageLimit::Limited(limit) => {
943 format!("{} / {limit}", usage.amount)
944 }
945 UsageLimit::Unlimited => format!("{} / ∞", usage.amount),
946 })
947 .size(LabelSize::Small)
948 .color(Color::Muted),
949 )
950 .into_any_element()
951 },
952 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
953 )
954 .when(usage.over_limit(), |menu| -> ContextMenu {
955 menu.entry("Subscribe to increase your limit", None, |_window, cx| {
956 cx.open_url(&zed_urls::account_url(cx))
957 })
958 })
959 .separator();
960 } else if self.user_store.read(cx).account_too_young() {
961 menu = menu
962 .custom_entry(
963 |_window, _cx| {
964 Label::new("Your GitHub account is less than 30 days old.")
965 .size(LabelSize::Small)
966 .color(Color::Warning)
967 .into_any_element()
968 },
969 |_window, cx| cx.open_url(&zed_urls::account_url(cx)),
970 )
971 .entry("Upgrade to Zed Pro or contact us.", None, |_window, cx| {
972 cx.open_url(&zed_urls::account_url(cx))
973 })
974 .separator();
975 } else if self.user_store.read(cx).has_overdue_invoices() {
976 menu = menu
977 .custom_entry(
978 |_window, _cx| {
979 Label::new("You have an outstanding invoice")
980 .size(LabelSize::Small)
981 .color(Color::Warning)
982 .into_any_element()
983 },
984 |_window, cx| {
985 cx.open_url(&zed_urls::account_url(cx))
986 },
987 )
988 .entry(
989 "Check your payment status or contact us at billing-support@zed.dev to continue using this feature.",
990 None,
991 |_window, cx| {
992 cx.open_url(&zed_urls::account_url(cx))
993 },
994 )
995 .separator();
996 }
997
998 let menu = self.build_language_settings_menu(menu, window, cx);
999 let menu = self.add_provider_switching_section(menu, EditPredictionProvider::Zed, cx);
1000
1001 menu
1002 })
1003 }
1004
1005 pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
1006 let editor = editor.read(cx);
1007 let snapshot = editor.buffer().read(cx).snapshot(cx);
1008 let suggestion_anchor = editor.selections.newest_anchor().start;
1009 let language = snapshot.language_at(suggestion_anchor);
1010 let file = snapshot.file_at(suggestion_anchor).cloned();
1011 self.editor_enabled = {
1012 let file = file.as_ref();
1013 Some(
1014 file.map(|file| {
1015 all_language_settings(Some(file), cx)
1016 .edit_predictions_enabled_for_file(file, cx)
1017 })
1018 .unwrap_or(true),
1019 )
1020 };
1021 self.editor_show_predictions = editor.edit_predictions_enabled();
1022 self.edit_prediction_provider = editor.edit_prediction_provider();
1023 self.language = language.cloned();
1024 self.file = file;
1025 self.editor_focus_handle = Some(editor.focus_handle(cx));
1026
1027 cx.notify();
1028 }
1029}
1030
1031impl StatusItemView for EditPredictionButton {
1032 fn set_active_pane_item(
1033 &mut self,
1034 item: Option<&dyn ItemHandle>,
1035 _: &mut Window,
1036 cx: &mut Context<Self>,
1037 ) {
1038 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
1039 self.editor_subscription = Some((
1040 cx.observe(&editor, Self::update_enabled),
1041 editor.entity_id().as_u64() as usize,
1042 ));
1043 self.update_enabled(editor, cx);
1044 } else {
1045 self.language = None;
1046 self.editor_subscription = None;
1047 self.editor_enabled = None;
1048 }
1049 cx.notify();
1050 }
1051}
1052
1053impl SupermavenButtonStatus {
1054 fn to_icon(&self) -> IconName {
1055 match self {
1056 SupermavenButtonStatus::Ready => IconName::Supermaven,
1057 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
1058 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
1059 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
1060 }
1061 }
1062
1063 fn to_tooltip(&self) -> String {
1064 match self {
1065 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
1066 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
1067 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
1068 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
1069 }
1070 }
1071
1072 fn has_menu(&self) -> bool {
1073 match self {
1074 SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
1075 SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
1076 }
1077 }
1078}
1079
1080async fn open_disabled_globs_setting_in_editor(
1081 workspace: WeakEntity<Workspace>,
1082 cx: &mut AsyncWindowContext,
1083) -> Result<()> {
1084 let settings_editor = workspace
1085 .update_in(cx, |_, window, cx| {
1086 create_and_open_local_file(paths::settings_file(), window, cx, || {
1087 settings::initial_user_settings_content().as_ref().into()
1088 })
1089 })?
1090 .await?
1091 .downcast::<Editor>()
1092 .unwrap();
1093
1094 settings_editor
1095 .downgrade()
1096 .update_in(cx, |item, window, cx| {
1097 let text = item.buffer().read(cx).snapshot(cx).text();
1098
1099 let settings = cx.global::<SettingsStore>();
1100
1101 // Ensure that we always have "edit_predictions { "disabled_globs": [] }"
1102 let edits = settings.edits_for_update(&text, |file| {
1103 file.project
1104 .all_languages
1105 .edit_predictions
1106 .get_or_insert_with(Default::default)
1107 .disabled_globs
1108 .get_or_insert_with(Vec::new);
1109 });
1110
1111 if !edits.is_empty() {
1112 item.edit(
1113 edits
1114 .into_iter()
1115 .map(|(r, s)| (MultiBufferOffset(r.start)..MultiBufferOffset(r.end), s)),
1116 cx,
1117 );
1118 }
1119
1120 let text = item.buffer().read(cx).snapshot(cx).text();
1121
1122 static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
1123 Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
1124 });
1125 // Only capture [...]
1126 let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
1127 captures
1128 .name("content")
1129 .map(|inner_match| inner_match.start()..inner_match.end())
1130 });
1131 if let Some(range) = range {
1132 let range = MultiBufferOffset(range.start)..MultiBufferOffset(range.end);
1133 item.change_selections(
1134 SelectionEffects::scroll(Autoscroll::newest()),
1135 window,
1136 cx,
1137 |selections| {
1138 selections.select_ranges(vec![range]);
1139 },
1140 );
1141 }
1142 })?;
1143
1144 anyhow::Ok(())
1145}
1146
1147fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
1148 update_settings_file(fs, cx, move |settings, _| {
1149 settings
1150 .project
1151 .all_languages
1152 .features
1153 .get_or_insert_default()
1154 .edit_prediction_provider = Some(provider);
1155 });
1156}
1157
1158fn toggle_show_edit_predictions_for_language(
1159 language: Arc<Language>,
1160 fs: Arc<dyn Fs>,
1161 cx: &mut App,
1162) {
1163 let show_edit_predictions =
1164 all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
1165 update_settings_file(fs, cx, move |settings, _| {
1166 settings
1167 .project
1168 .all_languages
1169 .languages
1170 .0
1171 .entry(language.name().0)
1172 .or_default()
1173 .show_edit_predictions = Some(!show_edit_predictions);
1174 });
1175}
1176
1177fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
1178 update_settings_file(fs, cx, move |settings, _| {
1179 settings
1180 .project
1181 .all_languages
1182 .features
1183 .get_or_insert(Default::default())
1184 .edit_prediction_provider = Some(EditPredictionProvider::None);
1185 });
1186}
1187
1188fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
1189 let settings = AllLanguageSettings::get_global(cx);
1190 let current_mode = settings.edit_predictions_mode();
1191
1192 if current_mode != mode {
1193 update_settings_file(fs, cx, move |settings, _cx| {
1194 if let Some(edit_predictions) = settings.project.all_languages.edit_predictions.as_mut()
1195 {
1196 edit_predictions.mode = Some(mode);
1197 } else {
1198 settings.project.all_languages.edit_predictions =
1199 Some(settings::EditPredictionSettingsContent {
1200 mode: Some(mode),
1201 ..Default::default()
1202 });
1203 }
1204 });
1205 }
1206}
1207
1208fn copilot_settings_url(enterprise_uri: Option<&str>) -> String {
1209 match enterprise_uri {
1210 Some(uri) => {
1211 format!("{}{}", uri.trim_end_matches('/'), COPILOT_SETTINGS_PATH)
1212 }
1213 None => COPILOT_SETTINGS_URL.to_string(),
1214 }
1215}
1216
1217#[cfg(test)]
1218mod tests {
1219 use super::*;
1220 use gpui::TestAppContext;
1221
1222 #[gpui::test]
1223 async fn test_copilot_settings_url_with_enterprise_uri(cx: &mut TestAppContext) {
1224 cx.update(|cx| {
1225 let settings_store = SettingsStore::test(cx);
1226 cx.set_global(settings_store);
1227 });
1228
1229 cx.update_global(|settings_store: &mut SettingsStore, cx| {
1230 settings_store
1231 .set_user_settings(
1232 r#"{"edit_predictions":{"copilot":{"enterprise_uri":"https://my-company.ghe.com"}}}"#,
1233 cx,
1234 )
1235 .unwrap();
1236 });
1237
1238 let url = cx.update(|cx| {
1239 let all_language_settings = all_language_settings(None, cx);
1240 copilot_settings_url(
1241 all_language_settings
1242 .edit_predictions
1243 .copilot
1244 .enterprise_uri
1245 .as_deref(),
1246 )
1247 });
1248
1249 assert_eq!(url, "https://my-company.ghe.com/settings/copilot");
1250 }
1251
1252 #[gpui::test]
1253 async fn test_copilot_settings_url_with_enterprise_uri_trailing_slash(cx: &mut TestAppContext) {
1254 cx.update(|cx| {
1255 let settings_store = SettingsStore::test(cx);
1256 cx.set_global(settings_store);
1257 });
1258
1259 cx.update_global(|settings_store: &mut SettingsStore, cx| {
1260 settings_store
1261 .set_user_settings(
1262 r#"{"edit_predictions":{"copilot":{"enterprise_uri":"https://my-company.ghe.com/"}}}"#,
1263 cx,
1264 )
1265 .unwrap();
1266 });
1267
1268 let url = cx.update(|cx| {
1269 let all_language_settings = all_language_settings(None, cx);
1270 copilot_settings_url(
1271 all_language_settings
1272 .edit_predictions
1273 .copilot
1274 .enterprise_uri
1275 .as_deref(),
1276 )
1277 });
1278
1279 assert_eq!(url, "https://my-company.ghe.com/settings/copilot");
1280 }
1281
1282 #[gpui::test]
1283 async fn test_copilot_settings_url_without_enterprise_uri(cx: &mut TestAppContext) {
1284 cx.update(|cx| {
1285 let settings_store = SettingsStore::test(cx);
1286 cx.set_global(settings_store);
1287 });
1288
1289 let url = cx.update(|cx| {
1290 let all_language_settings = all_language_settings(None, cx);
1291 copilot_settings_url(
1292 all_language_settings
1293 .edit_predictions
1294 .copilot
1295 .enterprise_uri
1296 .as_deref(),
1297 )
1298 });
1299
1300 assert_eq!(url, "https://github.com/settings/copilot");
1301 }
1302}