inline_completion_button.rs

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