inline_completion_button.rs

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