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().clone();
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().clone();
186 let fs = self.fs.clone();
187
188 return 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().clone();
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 .map_or(false, |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!(provider, EditPredictionProvider::Zed) {
495 menu = menu
496 .separator()
497 .header("Display Modes")
498 .item(
499 ContextMenuEntry::new("Eager")
500 .toggleable(IconPosition::Start, eager_mode)
501 .documentation_aside(DocumentationSide::Left, move |_| {
502 Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
503 })
504 .handler({
505 let fs = fs.clone();
506 move |_, cx| {
507 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
508 }
509 }),
510 )
511 .item(
512 ContextMenuEntry::new("Subtle")
513 .toggleable(IconPosition::Start, subtle_mode)
514 .documentation_aside(DocumentationSide::Left, move |_| {
515 Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
516 })
517 .handler({
518 let fs = fs.clone();
519 move |_, cx| {
520 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
521 }
522 }),
523 );
524 }
525
526 menu = menu.separator().header("Privacy");
527 if let Some(provider) = &self.edit_prediction_provider {
528 let data_collection = provider.data_collection_state(cx);
529 if data_collection.is_supported() {
530 let provider = provider.clone();
531 let enabled = data_collection.is_enabled();
532 let is_open_source = data_collection.is_project_open_source();
533 let is_collecting = data_collection.is_enabled();
534 let (icon_name, icon_color) = if is_open_source && is_collecting {
535 (IconName::Check, Color::Success)
536 } else {
537 (IconName::Check, Color::Accent)
538 };
539
540 menu = menu.item(
541 ContextMenuEntry::new("Training Data Collection")
542 .toggleable(IconPosition::Start, data_collection.is_enabled())
543 .icon(icon_name)
544 .icon_color(icon_color)
545 .documentation_aside(DocumentationSide::Left, move |cx| {
546 let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
547 (true, true) => (
548 "Project identified as open source, and you're sharing data.",
549 Color::Default,
550 IconName::Check,
551 Color::Success,
552 ),
553 (true, false) => (
554 "Project identified as open source, but you're not sharing data.",
555 Color::Muted,
556 IconName::Close,
557 Color::Muted,
558 ),
559 (false, true) => (
560 "Project not identified as open source. No data captured.",
561 Color::Muted,
562 IconName::Close,
563 Color::Muted,
564 ),
565 (false, false) => (
566 "Project not identified as open source, and setting turned off.",
567 Color::Muted,
568 IconName::Close,
569 Color::Muted,
570 ),
571 };
572 v_flex()
573 .gap_2()
574 .child(
575 Label::new(indoc!{
576 "Help us improve our open dataset model by sharing data from open source repositories. \
577 Zed must detect a license file in your repo for this setting to take effect. \
578 Files with sensitive data and secrets are excluded by default."
579 })
580 )
581 .child(
582 h_flex()
583 .items_start()
584 .pt_2()
585 .pr_1()
586 .flex_1()
587 .gap_1p5()
588 .border_t_1()
589 .border_color(cx.theme().colors().border_variant)
590 .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
591 .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
592 )
593 .into_any_element()
594 })
595 .handler(move |_, cx| {
596 provider.toggle_data_collection(cx);
597
598 if !enabled {
599 telemetry::event!(
600 "Data Collection Enabled",
601 source = "Edit Prediction Status Menu"
602 );
603 } else {
604 telemetry::event!(
605 "Data Collection Disabled",
606 source = "Edit Prediction Status Menu"
607 );
608 }
609 })
610 );
611
612 if is_collecting && !is_open_source {
613 menu = menu.item(
614 ContextMenuEntry::new("No data captured.")
615 .disabled(true)
616 .icon(IconName::Close)
617 .icon_color(Color::Error)
618 .icon_size(IconSize::Small),
619 );
620 }
621 }
622 }
623
624 menu = menu.item(
625 ContextMenuEntry::new("Configure Excluded Files")
626 .icon(IconName::LockOutlined)
627 .icon_color(Color::Muted)
628 .documentation_aside(DocumentationSide::Left, |_| {
629 Label::new(indoc!{"
630 Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
631 })
632 .handler(move |window, cx| {
633 if let Some(workspace) = window.root().flatten() {
634 let workspace = workspace.downgrade();
635 window
636 .spawn(cx, async |cx| {
637 open_disabled_globs_setting_in_editor(
638 workspace,
639 cx,
640 ).await
641 })
642 .detach_and_log_err(cx);
643 }
644 }),
645 ).item(
646 ContextMenuEntry::new("View Documentation")
647 .icon(IconName::FileGeneric)
648 .icon_color(Color::Muted)
649 .handler(move |_, cx| {
650 cx.open_url(PRIVACY_DOCS);
651 })
652 );
653
654 if !self.editor_enabled.unwrap_or(true) {
655 menu = menu.item(
656 ContextMenuEntry::new("This file is excluded.")
657 .disabled(true)
658 .icon(IconName::ZedPredictDisabled)
659 .icon_size(IconSize::Small),
660 );
661 }
662
663 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
664 menu = menu
665 .separator()
666 .entry(
667 "Predict Edit at Cursor",
668 Some(Box::new(ShowEditPrediction)),
669 {
670 let editor_focus_handle = editor_focus_handle.clone();
671 move |window, cx| {
672 editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
673 }
674 },
675 )
676 .context(editor_focus_handle);
677 }
678
679 menu
680 }
681
682 fn build_copilot_context_menu(
683 &self,
684 window: &mut Window,
685 cx: &mut Context<Self>,
686 ) -> Entity<ContextMenu> {
687 ContextMenu::build(window, cx, |menu, window, cx| {
688 self.build_language_settings_menu(menu, window, cx)
689 .separator()
690 .entry("Use Zed AI instead", None, {
691 let fs = self.fs.clone();
692 move |_window, cx| {
693 set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
694 }
695 })
696 .separator()
697 .link(
698 "Go to Copilot Settings",
699 OpenBrowser {
700 url: COPILOT_SETTINGS_URL.to_string(),
701 }
702 .boxed_clone(),
703 )
704 .action("Sign Out", copilot::SignOut.boxed_clone())
705 })
706 }
707
708 fn build_supermaven_context_menu(
709 &self,
710 window: &mut Window,
711 cx: &mut Context<Self>,
712 ) -> Entity<ContextMenu> {
713 ContextMenu::build(window, cx, |menu, window, cx| {
714 self.build_language_settings_menu(menu, window, cx)
715 .separator()
716 .action("Sign Out", supermaven::SignOut.boxed_clone())
717 })
718 }
719
720 fn build_zeta_context_menu(
721 &self,
722 window: &mut Window,
723 cx: &mut Context<Self>,
724 ) -> Entity<ContextMenu> {
725 ContextMenu::build(window, cx, |mut menu, window, cx| {
726 if let Some(usage) = self
727 .edit_prediction_provider
728 .as_ref()
729 .and_then(|provider| provider.usage(cx))
730 {
731 menu = menu.header("Usage");
732 menu = menu
733 .custom_entry(
734 move |_window, cx| {
735 let used_percentage = match usage.limit {
736 UsageLimit::Limited(limit) => {
737 Some((usage.amount as f32 / limit as f32) * 100.)
738 }
739 UsageLimit::Unlimited => None,
740 };
741
742 h_flex()
743 .flex_1()
744 .gap_1p5()
745 .children(
746 used_percentage.map(|percent| {
747 ProgressBar::new("usage", percent, 100., cx)
748 }),
749 )
750 .child(
751 Label::new(match usage.limit {
752 UsageLimit::Limited(limit) => {
753 format!("{} / {limit}", usage.amount)
754 }
755 UsageLimit::Unlimited => format!("{} / ∞", usage.amount),
756 })
757 .size(LabelSize::Small)
758 .color(Color::Muted),
759 )
760 .into_any_element()
761 },
762 move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
763 )
764 .when(usage.over_limit(), |menu| -> ContextMenu {
765 menu.entry("Subscribe to increase your limit", None, |_window, cx| {
766 cx.open_url(&zed_urls::account_url(cx))
767 })
768 })
769 .separator();
770 } else if self.user_store.read(cx).account_too_young() {
771 menu = menu
772 .custom_entry(
773 |_window, _cx| {
774 Label::new("Your GitHub account is less than 30 days old.")
775 .size(LabelSize::Small)
776 .color(Color::Warning)
777 .into_any_element()
778 },
779 |_window, cx| cx.open_url(&zed_urls::account_url(cx)),
780 )
781 .entry("Upgrade to Zed Pro or contact us.", None, |_window, cx| {
782 cx.open_url(&zed_urls::account_url(cx))
783 })
784 .separator();
785 } else if self.user_store.read(cx).has_overdue_invoices() {
786 menu = menu
787 .custom_entry(
788 |_window, _cx| {
789 Label::new("You have an outstanding invoice")
790 .size(LabelSize::Small)
791 .color(Color::Warning)
792 .into_any_element()
793 },
794 |_window, cx| {
795 cx.open_url(&zed_urls::account_url(cx))
796 },
797 )
798 .entry(
799 "Check your payment status or contact us at billing-support@zed.dev to continue using this feature.",
800 None,
801 |_window, cx| {
802 cx.open_url(&zed_urls::account_url(cx))
803 },
804 )
805 .separator();
806 }
807
808 self.build_language_settings_menu(menu, window, cx).when(
809 cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
810 |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
811 )
812 })
813 }
814
815 pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
816 let editor = editor.read(cx);
817 let snapshot = editor.buffer().read(cx).snapshot(cx);
818 let suggestion_anchor = editor.selections.newest_anchor().start;
819 let language = snapshot.language_at(suggestion_anchor);
820 let file = snapshot.file_at(suggestion_anchor).cloned();
821 self.editor_enabled = {
822 let file = file.as_ref();
823 Some(
824 file.map(|file| {
825 all_language_settings(Some(file), cx)
826 .edit_predictions_enabled_for_file(file, cx)
827 })
828 .unwrap_or(true),
829 )
830 };
831 self.editor_show_predictions = editor.edit_predictions_enabled();
832 self.edit_prediction_provider = editor.edit_prediction_provider();
833 self.language = language.cloned();
834 self.file = file;
835 self.editor_focus_handle = Some(editor.focus_handle(cx));
836
837 cx.notify();
838 }
839}
840
841impl StatusItemView for EditPredictionButton {
842 fn set_active_pane_item(
843 &mut self,
844 item: Option<&dyn ItemHandle>,
845 _: &mut Window,
846 cx: &mut Context<Self>,
847 ) {
848 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
849 self.editor_subscription = Some((
850 cx.observe(&editor, Self::update_enabled),
851 editor.entity_id().as_u64() as usize,
852 ));
853 self.update_enabled(editor, cx);
854 } else {
855 self.language = None;
856 self.editor_subscription = None;
857 self.editor_enabled = None;
858 }
859 cx.notify();
860 }
861}
862
863impl SupermavenButtonStatus {
864 fn to_icon(&self) -> IconName {
865 match self {
866 SupermavenButtonStatus::Ready => IconName::Supermaven,
867 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
868 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
869 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
870 }
871 }
872
873 fn to_tooltip(&self) -> String {
874 match self {
875 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
876 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
877 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
878 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
879 }
880 }
881
882 fn has_menu(&self) -> bool {
883 match self {
884 SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
885 SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
886 }
887 }
888}
889
890async fn open_disabled_globs_setting_in_editor(
891 workspace: WeakEntity<Workspace>,
892 cx: &mut AsyncWindowContext,
893) -> Result<()> {
894 let settings_editor = workspace
895 .update_in(cx, |_, window, cx| {
896 create_and_open_local_file(paths::settings_file(), window, cx, || {
897 settings::initial_user_settings_content().as_ref().into()
898 })
899 })?
900 .await?
901 .downcast::<Editor>()
902 .unwrap();
903
904 settings_editor
905 .downgrade()
906 .update_in(cx, |item, window, cx| {
907 let text = item.buffer().read(cx).snapshot(cx).text();
908
909 let settings = cx.global::<SettingsStore>();
910
911 // Ensure that we always have "edit_predictions { "disabled_globs": [] }"
912 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
913 file.edit_predictions
914 .get_or_insert_with(Default::default)
915 .disabled_globs
916 .get_or_insert_with(Vec::new);
917 });
918
919 if !edits.is_empty() {
920 item.edit(edits, cx);
921 }
922
923 let text = item.buffer().read(cx).snapshot(cx).text();
924
925 static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
926 Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
927 });
928 // Only capture [...]
929 let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
930 captures
931 .name("content")
932 .map(|inner_match| inner_match.start()..inner_match.end())
933 });
934 if let Some(range) = range {
935 item.change_selections(
936 SelectionEffects::scroll(Autoscroll::newest()),
937 window,
938 cx,
939 |selections| {
940 selections.select_ranges(vec![range]);
941 },
942 );
943 }
944 })?;
945
946 anyhow::Ok(())
947}
948
949fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
950 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
951 file.features
952 .get_or_insert(Default::default())
953 .edit_prediction_provider = Some(provider);
954 });
955}
956
957fn toggle_show_edit_predictions_for_language(
958 language: Arc<Language>,
959 fs: Arc<dyn Fs>,
960 cx: &mut App,
961) {
962 let show_edit_predictions =
963 all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
964 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
965 file.languages
966 .0
967 .entry(language.name())
968 .or_default()
969 .show_edit_predictions = Some(!show_edit_predictions);
970 });
971}
972
973fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
974 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
975 file.features
976 .get_or_insert(Default::default())
977 .edit_prediction_provider = Some(EditPredictionProvider::None);
978 });
979}
980
981fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
982 let settings = AllLanguageSettings::get_global(cx);
983 let current_mode = settings.edit_predictions_mode();
984
985 if current_mode != mode {
986 update_settings_file::<AllLanguageSettings>(fs, cx, move |settings, _cx| {
987 if let Some(edit_predictions) = settings.edit_predictions.as_mut() {
988 edit_predictions.mode = mode;
989 } else {
990 settings.edit_predictions =
991 Some(language_settings::EditPredictionSettingsContent {
992 mode,
993 ..Default::default()
994 });
995 }
996 });
997 }
998}