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,
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.weak_entity();
383
384 let mut popover_menu = PopoverMenu::new("zeta")
385 .menu(move |window, cx| {
386 this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx))
387 .ok()
388 })
389 .anchor(Corner::BottomRight)
390 .with_handle(self.popover_menu_handle.clone());
391
392 let is_refreshing = self
393 .edit_prediction_provider
394 .as_ref()
395 .is_some_and(|provider| provider.is_refreshing(cx));
396
397 if is_refreshing {
398 popover_menu = popover_menu.trigger(
399 icon_button.with_animation(
400 "pulsating-label",
401 Animation::new(Duration::from_secs(2))
402 .repeat()
403 .with_easing(pulsating_between(0.2, 1.0)),
404 |icon_button, delta| icon_button.alpha(delta),
405 ),
406 );
407 } else {
408 popover_menu = popover_menu.trigger(icon_button);
409 }
410
411 div().child(popover_menu.into_any_element())
412 }
413 }
414 }
415}
416
417impl EditPredictionButton {
418 pub fn new(
419 fs: Arc<dyn Fs>,
420 user_store: Entity<UserStore>,
421 popover_menu_handle: PopoverMenuHandle<ContextMenu>,
422 client: Arc<Client>,
423 cx: &mut Context<Self>,
424 ) -> Self {
425 if let Some(copilot) = Copilot::global(cx) {
426 cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
427 }
428
429 cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
430 .detach();
431
432 CodestralCompletionProvider::ensure_api_key_loaded(client.http_client(), cx);
433
434 Self {
435 editor_subscription: None,
436 editor_enabled: None,
437 editor_show_predictions: true,
438 editor_focus_handle: None,
439 language: None,
440 file: None,
441 edit_prediction_provider: None,
442 user_store,
443 popover_menu_handle,
444 fs,
445 }
446 }
447
448 fn get_available_providers(&self, cx: &App) -> Vec<EditPredictionProvider> {
449 let mut providers = Vec::new();
450
451 providers.push(EditPredictionProvider::Zed);
452
453 if let Some(copilot) = Copilot::global(cx) {
454 if matches!(copilot.read(cx).status(), Status::Authorized) {
455 providers.push(EditPredictionProvider::Copilot);
456 }
457 }
458
459 if let Some(supermaven) = Supermaven::global(cx) {
460 if let Supermaven::Spawned(agent) = supermaven.read(cx) {
461 if matches!(agent.account_status, AccountStatus::Ready) {
462 providers.push(EditPredictionProvider::Supermaven);
463 }
464 }
465 }
466
467 if CodestralCompletionProvider::has_api_key(cx) {
468 providers.push(EditPredictionProvider::Codestral);
469 }
470
471 providers
472 }
473
474 fn add_provider_switching_section(
475 &self,
476 mut menu: ContextMenu,
477 current_provider: EditPredictionProvider,
478 cx: &App,
479 ) -> ContextMenu {
480 let available_providers = self.get_available_providers(cx);
481
482 let other_providers: Vec<_> = available_providers
483 .into_iter()
484 .filter(|p| *p != current_provider && *p != EditPredictionProvider::None)
485 .collect();
486
487 if !other_providers.is_empty() {
488 menu = menu.separator().header("Switch Providers");
489
490 for provider in other_providers {
491 let fs = self.fs.clone();
492
493 menu = match provider {
494 EditPredictionProvider::Zed => menu.item(
495 ContextMenuEntry::new("Zed AI")
496 .documentation_aside(
497 DocumentationSide::Left,
498 DocumentationEdge::Top,
499 |_| {
500 Label::new("Zed's edit prediction is powered by Zeta, an open-source, dataset mode.")
501 .into_any_element()
502 },
503 )
504 .handler(move |_, cx| {
505 set_completion_provider(fs.clone(), cx, provider);
506 }),
507 ),
508 EditPredictionProvider::Copilot => {
509 menu.entry("GitHub Copilot", None, move |_, cx| {
510 set_completion_provider(fs.clone(), cx, provider);
511 })
512 }
513 EditPredictionProvider::Supermaven => {
514 menu.entry("Supermaven", None, move |_, cx| {
515 set_completion_provider(fs.clone(), cx, provider);
516 })
517 }
518 EditPredictionProvider::Codestral => {
519 menu.entry("Codestral", None, move |_, cx| {
520 set_completion_provider(fs.clone(), cx, provider);
521 })
522 }
523 EditPredictionProvider::None => continue,
524 };
525 }
526 }
527
528 menu
529 }
530
531 pub fn build_copilot_start_menu(
532 &mut self,
533 window: &mut Window,
534 cx: &mut Context<Self>,
535 ) -> Entity<ContextMenu> {
536 let fs = self.fs.clone();
537 ContextMenu::build(window, cx, |menu, _, _| {
538 menu.entry("Sign In to Copilot", None, copilot::initiate_sign_in)
539 .entry("Disable Copilot", None, {
540 let fs = fs.clone();
541 move |_window, cx| hide_copilot(fs.clone(), cx)
542 })
543 .separator()
544 .entry("Use Zed AI", None, {
545 let fs = fs.clone();
546 move |_window, cx| {
547 set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
548 }
549 })
550 })
551 }
552
553 pub fn build_language_settings_menu(
554 &self,
555 mut menu: ContextMenu,
556 window: &Window,
557 cx: &mut App,
558 ) -> ContextMenu {
559 let fs = self.fs.clone();
560 let line_height = window.line_height();
561
562 menu = menu.header("Show Edit Predictions For");
563
564 let language_state = self.language.as_ref().map(|language| {
565 (
566 language.clone(),
567 language_settings::language_settings(Some(language.name()), None, cx)
568 .show_edit_predictions,
569 )
570 });
571
572 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
573 let entry = ContextMenuEntry::new("This Buffer")
574 .toggleable(IconPosition::Start, self.editor_show_predictions)
575 .action(Box::new(editor::actions::ToggleEditPrediction))
576 .handler(move |window, cx| {
577 editor_focus_handle.dispatch_action(
578 &editor::actions::ToggleEditPrediction,
579 window,
580 cx,
581 );
582 });
583
584 match language_state.clone() {
585 Some((language, false)) => {
586 menu = menu.item(
587 entry
588 .disabled(true)
589 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_cx| {
590 Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
591 .into_any_element()
592 })
593 );
594 }
595 Some(_) | None => menu = menu.item(entry),
596 }
597 }
598
599 if let Some((language, language_enabled)) = language_state {
600 let fs = fs.clone();
601
602 menu = menu.toggleable_entry(
603 language.name(),
604 language_enabled,
605 IconPosition::Start,
606 None,
607 move |_, cx| {
608 toggle_show_edit_predictions_for_language(language.clone(), fs.clone(), cx)
609 },
610 );
611 }
612
613 let settings = AllLanguageSettings::get_global(cx);
614
615 let globally_enabled = settings.show_edit_predictions(None, cx);
616 let entry = ContextMenuEntry::new("All Files")
617 .toggleable(IconPosition::Start, globally_enabled)
618 .action(workspace::ToggleEditPrediction.boxed_clone())
619 .handler(|window, cx| {
620 window.dispatch_action(workspace::ToggleEditPrediction.boxed_clone(), cx)
621 });
622 menu = menu.item(entry);
623
624 let provider = settings.edit_predictions.provider;
625 let current_mode = settings.edit_predictions_mode();
626 let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
627 let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
628
629 if matches!(
630 provider,
631 EditPredictionProvider::Zed
632 | EditPredictionProvider::Copilot
633 | EditPredictionProvider::Supermaven
634 | EditPredictionProvider::Codestral
635 ) {
636 menu = menu
637 .separator()
638 .header("Display Modes")
639 .item(
640 ContextMenuEntry::new("Eager")
641 .toggleable(IconPosition::Start, eager_mode)
642 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
643 Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
644 })
645 .handler({
646 let fs = fs.clone();
647 move |_, cx| {
648 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
649 }
650 }),
651 )
652 .item(
653 ContextMenuEntry::new("Subtle")
654 .toggleable(IconPosition::Start, subtle_mode)
655 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
656 Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
657 })
658 .handler({
659 let fs = fs.clone();
660 move |_, cx| {
661 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
662 }
663 }),
664 );
665 }
666
667 menu = menu.separator().header("Privacy");
668
669 if let Some(provider) = &self.edit_prediction_provider {
670 let data_collection = provider.data_collection_state(cx);
671
672 if data_collection.is_supported() {
673 let provider = provider.clone();
674 let enabled = data_collection.is_enabled();
675 let is_open_source = data_collection.is_project_open_source();
676 let is_collecting = data_collection.is_enabled();
677 let (icon_name, icon_color) = if is_open_source && is_collecting {
678 (IconName::Check, Color::Success)
679 } else {
680 (IconName::Check, Color::Accent)
681 };
682
683 menu = menu.item(
684 ContextMenuEntry::new("Training Data Collection")
685 .toggleable(IconPosition::Start, data_collection.is_enabled())
686 .icon(icon_name)
687 .icon_color(icon_color)
688 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |cx| {
689 let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
690 (true, true) => (
691 "Project identified as open source, and you're sharing data.",
692 Color::Default,
693 IconName::Check,
694 Color::Success,
695 ),
696 (true, false) => (
697 "Project identified as open source, but you're not sharing data.",
698 Color::Muted,
699 IconName::Close,
700 Color::Muted,
701 ),
702 (false, true) => (
703 "Project not identified as open source. No data captured.",
704 Color::Muted,
705 IconName::Close,
706 Color::Muted,
707 ),
708 (false, false) => (
709 "Project not identified as open source, and setting turned off.",
710 Color::Muted,
711 IconName::Close,
712 Color::Muted,
713 ),
714 };
715 v_flex()
716 .gap_2()
717 .child(
718 Label::new(indoc!{
719 "Help us improve our open dataset model by sharing data from open source repositories. \
720 Zed must detect a license file in your repo for this setting to take effect. \
721 Files with sensitive data and secrets are excluded by default."
722 })
723 )
724 .child(
725 h_flex()
726 .items_start()
727 .pt_2()
728 .pr_1()
729 .flex_1()
730 .gap_1p5()
731 .border_t_1()
732 .border_color(cx.theme().colors().border_variant)
733 .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
734 .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
735 )
736 .into_any_element()
737 })
738 .handler(move |_, cx| {
739 provider.toggle_data_collection(cx);
740
741 if !enabled {
742 telemetry::event!(
743 "Data Collection Enabled",
744 source = "Edit Prediction Status Menu"
745 );
746 } else {
747 telemetry::event!(
748 "Data Collection Disabled",
749 source = "Edit Prediction Status Menu"
750 );
751 }
752 })
753 );
754
755 if is_collecting && !is_open_source {
756 menu = menu.item(
757 ContextMenuEntry::new("No data captured.")
758 .disabled(true)
759 .icon(IconName::Close)
760 .icon_color(Color::Error)
761 .icon_size(IconSize::Small),
762 );
763 }
764 }
765 }
766
767 menu = menu.item(
768 ContextMenuEntry::new("Configure Excluded Files")
769 .icon(IconName::LockOutlined)
770 .icon_color(Color::Muted)
771 .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, |_| {
772 Label::new(indoc!{"
773 Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
774 })
775 .handler(move |window, cx| {
776 if let Some(workspace) = window.root().flatten() {
777 let workspace = workspace.downgrade();
778 window
779 .spawn(cx, async |cx| {
780 open_disabled_globs_setting_in_editor(
781 workspace,
782 cx,
783 ).await
784 })
785 .detach_and_log_err(cx);
786 }
787 }),
788 ).item(
789 ContextMenuEntry::new("View Docs")
790 .icon(IconName::FileGeneric)
791 .icon_color(Color::Muted)
792 .handler(move |_, cx| {
793 cx.open_url(PRIVACY_DOCS);
794 })
795 );
796
797 if !self.editor_enabled.unwrap_or(true) {
798 menu = menu.item(
799 ContextMenuEntry::new("This file is excluded.")
800 .disabled(true)
801 .icon(IconName::ZedPredictDisabled)
802 .icon_size(IconSize::Small),
803 );
804 }
805
806 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
807 menu = menu
808 .separator()
809 .header("Actions")
810 .entry(
811 "Predict Edit at Cursor",
812 Some(Box::new(ShowEditPrediction)),
813 {
814 let editor_focus_handle = editor_focus_handle.clone();
815 move |window, cx| {
816 editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
817 }
818 },
819 )
820 .context(editor_focus_handle)
821 .when(
822 cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
823 |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
824 );
825 }
826
827 menu
828 }
829
830 fn build_copilot_context_menu(
831 &self,
832 window: &mut Window,
833 cx: &mut Context<Self>,
834 ) -> Entity<ContextMenu> {
835 ContextMenu::build(window, cx, |menu, window, cx| {
836 let menu = self.build_language_settings_menu(menu, window, cx);
837 let menu =
838 self.add_provider_switching_section(menu, EditPredictionProvider::Copilot, cx);
839
840 menu.separator()
841 .link(
842 "Go to Copilot Settings",
843 OpenBrowser {
844 url: COPILOT_SETTINGS_URL.to_string(),
845 }
846 .boxed_clone(),
847 )
848 .action("Sign Out", copilot::SignOut.boxed_clone())
849 })
850 }
851
852 fn build_supermaven_context_menu(
853 &self,
854 window: &mut Window,
855 cx: &mut Context<Self>,
856 ) -> Entity<ContextMenu> {
857 ContextMenu::build(window, cx, |menu, window, cx| {
858 let menu = self.build_language_settings_menu(menu, window, cx);
859 let menu =
860 self.add_provider_switching_section(menu, EditPredictionProvider::Supermaven, cx);
861
862 menu.separator()
863 .action("Sign Out", supermaven::SignOut.boxed_clone())
864 })
865 }
866
867 fn build_codestral_context_menu(
868 &self,
869 window: &mut Window,
870 cx: &mut Context<Self>,
871 ) -> Entity<ContextMenu> {
872 ContextMenu::build(window, cx, |menu, window, cx| {
873 let menu = self.build_language_settings_menu(menu, window, cx);
874 let menu =
875 self.add_provider_switching_section(menu, EditPredictionProvider::Codestral, cx);
876
877 menu.separator()
878 .entry("Configure Codestral API Key", None, move |window, cx| {
879 window.dispatch_action(zed_actions::agent::OpenSettings.boxed_clone(), cx);
880 })
881 })
882 }
883
884 fn build_zeta_context_menu(
885 &self,
886 window: &mut Window,
887 cx: &mut Context<Self>,
888 ) -> Entity<ContextMenu> {
889 ContextMenu::build(window, cx, |mut menu, window, cx| {
890 if let Some(usage) = self
891 .edit_prediction_provider
892 .as_ref()
893 .and_then(|provider| provider.usage(cx))
894 {
895 menu = menu.header("Usage");
896 menu = menu
897 .custom_entry(
898 move |_window, cx| {
899 let used_percentage = match usage.limit {
900 UsageLimit::Limited(limit) => {
901 Some((usage.amount as f32 / limit as f32) * 100.)
902 }
903 UsageLimit::Unlimited => None,
904 };
905
906 h_flex()
907 .flex_1()
908 .gap_1p5()
909 .children(
910 used_percentage.map(|percent| {
911 ProgressBar::new("usage", percent, 100., cx)
912 }),
913 )
914 .child(
915 Label::new(match usage.limit {
916 UsageLimit::Limited(limit) => {
917 format!("{} / {limit}", usage.amount)
918 }
919 UsageLimit::Unlimited => format!("{} / ∞", usage.amount),
920 })
921 .size(LabelSize::Small)
922 .color(Color::Muted),
923 )
924 .into_any_element()
925 },
926 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
927 )
928 .when(usage.over_limit(), |menu| -> ContextMenu {
929 menu.entry("Subscribe to increase your limit", None, |_window, cx| {
930 cx.open_url(&zed_urls::account_url(cx))
931 })
932 })
933 .separator();
934 } else if self.user_store.read(cx).account_too_young() {
935 menu = menu
936 .custom_entry(
937 |_window, _cx| {
938 Label::new("Your GitHub account is less than 30 days old.")
939 .size(LabelSize::Small)
940 .color(Color::Warning)
941 .into_any_element()
942 },
943 |_window, cx| cx.open_url(&zed_urls::account_url(cx)),
944 )
945 .entry("Upgrade to Zed Pro or contact us.", None, |_window, cx| {
946 cx.open_url(&zed_urls::account_url(cx))
947 })
948 .separator();
949 } else if self.user_store.read(cx).has_overdue_invoices() {
950 menu = menu
951 .custom_entry(
952 |_window, _cx| {
953 Label::new("You have an outstanding invoice")
954 .size(LabelSize::Small)
955 .color(Color::Warning)
956 .into_any_element()
957 },
958 |_window, cx| {
959 cx.open_url(&zed_urls::account_url(cx))
960 },
961 )
962 .entry(
963 "Check your payment status or contact us at billing-support@zed.dev to continue using this feature.",
964 None,
965 |_window, cx| {
966 cx.open_url(&zed_urls::account_url(cx))
967 },
968 )
969 .separator();
970 }
971
972 let menu = self.build_language_settings_menu(menu, window, cx);
973 let menu = self.add_provider_switching_section(menu, EditPredictionProvider::Zed, cx);
974
975 menu
976 })
977 }
978
979 pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
980 let editor = editor.read(cx);
981 let snapshot = editor.buffer().read(cx).snapshot(cx);
982 let suggestion_anchor = editor.selections.newest_anchor().start;
983 let language = snapshot.language_at(suggestion_anchor);
984 let file = snapshot.file_at(suggestion_anchor).cloned();
985 self.editor_enabled = {
986 let file = file.as_ref();
987 Some(
988 file.map(|file| {
989 all_language_settings(Some(file), cx)
990 .edit_predictions_enabled_for_file(file, cx)
991 })
992 .unwrap_or(true),
993 )
994 };
995 self.editor_show_predictions = editor.edit_predictions_enabled();
996 self.edit_prediction_provider = editor.edit_prediction_provider();
997 self.language = language.cloned();
998 self.file = file;
999 self.editor_focus_handle = Some(editor.focus_handle(cx));
1000
1001 cx.notify();
1002 }
1003}
1004
1005impl StatusItemView for EditPredictionButton {
1006 fn set_active_pane_item(
1007 &mut self,
1008 item: Option<&dyn ItemHandle>,
1009 _: &mut Window,
1010 cx: &mut Context<Self>,
1011 ) {
1012 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
1013 self.editor_subscription = Some((
1014 cx.observe(&editor, Self::update_enabled),
1015 editor.entity_id().as_u64() as usize,
1016 ));
1017 self.update_enabled(editor, cx);
1018 } else {
1019 self.language = None;
1020 self.editor_subscription = None;
1021 self.editor_enabled = None;
1022 }
1023 cx.notify();
1024 }
1025}
1026
1027impl SupermavenButtonStatus {
1028 fn to_icon(&self) -> IconName {
1029 match self {
1030 SupermavenButtonStatus::Ready => IconName::Supermaven,
1031 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
1032 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
1033 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
1034 }
1035 }
1036
1037 fn to_tooltip(&self) -> String {
1038 match self {
1039 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
1040 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
1041 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
1042 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
1043 }
1044 }
1045
1046 fn has_menu(&self) -> bool {
1047 match self {
1048 SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
1049 SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
1050 }
1051 }
1052}
1053
1054async fn open_disabled_globs_setting_in_editor(
1055 workspace: WeakEntity<Workspace>,
1056 cx: &mut AsyncWindowContext,
1057) -> Result<()> {
1058 let settings_editor = workspace
1059 .update_in(cx, |_, window, cx| {
1060 create_and_open_local_file(paths::settings_file(), window, cx, || {
1061 settings::initial_user_settings_content().as_ref().into()
1062 })
1063 })?
1064 .await?
1065 .downcast::<Editor>()
1066 .unwrap();
1067
1068 settings_editor
1069 .downgrade()
1070 .update_in(cx, |item, window, cx| {
1071 let text = item.buffer().read(cx).snapshot(cx).text();
1072
1073 let settings = cx.global::<SettingsStore>();
1074
1075 // Ensure that we always have "edit_predictions { "disabled_globs": [] }"
1076 let edits = settings.edits_for_update(&text, |file| {
1077 file.project
1078 .all_languages
1079 .edit_predictions
1080 .get_or_insert_with(Default::default)
1081 .disabled_globs
1082 .get_or_insert_with(Vec::new);
1083 });
1084
1085 if !edits.is_empty() {
1086 item.edit(edits, cx);
1087 }
1088
1089 let text = item.buffer().read(cx).snapshot(cx).text();
1090
1091 static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
1092 Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
1093 });
1094 // Only capture [...]
1095 let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
1096 captures
1097 .name("content")
1098 .map(|inner_match| inner_match.start()..inner_match.end())
1099 });
1100 if let Some(range) = range {
1101 item.change_selections(
1102 SelectionEffects::scroll(Autoscroll::newest()),
1103 window,
1104 cx,
1105 |selections| {
1106 selections.select_ranges(vec![range]);
1107 },
1108 );
1109 }
1110 })?;
1111
1112 anyhow::Ok(())
1113}
1114
1115fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
1116 update_settings_file(fs, cx, move |settings, _| {
1117 settings
1118 .project
1119 .all_languages
1120 .features
1121 .get_or_insert_default()
1122 .edit_prediction_provider = Some(provider);
1123 });
1124}
1125
1126fn toggle_show_edit_predictions_for_language(
1127 language: Arc<Language>,
1128 fs: Arc<dyn Fs>,
1129 cx: &mut App,
1130) {
1131 let show_edit_predictions =
1132 all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
1133 update_settings_file(fs, cx, move |settings, _| {
1134 settings
1135 .project
1136 .all_languages
1137 .languages
1138 .0
1139 .entry(language.name().0)
1140 .or_default()
1141 .show_edit_predictions = Some(!show_edit_predictions);
1142 });
1143}
1144
1145fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
1146 update_settings_file(fs, cx, move |settings, _| {
1147 settings
1148 .project
1149 .all_languages
1150 .features
1151 .get_or_insert(Default::default())
1152 .edit_prediction_provider = Some(EditPredictionProvider::None);
1153 });
1154}
1155
1156fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
1157 let settings = AllLanguageSettings::get_global(cx);
1158 let current_mode = settings.edit_predictions_mode();
1159
1160 if current_mode != mode {
1161 update_settings_file(fs, cx, move |settings, _cx| {
1162 if let Some(edit_predictions) = settings.project.all_languages.edit_predictions.as_mut()
1163 {
1164 edit_predictions.mode = Some(mode);
1165 } else {
1166 settings.project.all_languages.edit_predictions =
1167 Some(settings::EditPredictionSettingsContent {
1168 mode: Some(mode),
1169 ..Default::default()
1170 });
1171 }
1172 });
1173 }
1174}