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