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