inline_completion_button.rs

  1use anyhow::Result;
  2use client::UserStore;
  3use copilot::{Copilot, Status};
  4use editor::{scroll::Autoscroll, Editor};
  5use feature_flags::{
  6    FeatureFlagAppExt, PredictEditsFeatureFlag, PredictEditsRateCompletionsFeatureFlag,
  7};
  8use fs::Fs;
  9use gpui::{
 10    actions, div, pulsating_between, Action, Animation, AnimationExt, App, AsyncWindowContext,
 11    Corner, Entity, IntoElement, ParentElement, Render, Subscription, WeakEntity,
 12};
 13use language::{
 14    language_settings::{
 15        self, all_language_settings, AllLanguageSettings, InlineCompletionProvider,
 16    },
 17    File, Language,
 18};
 19use settings::{update_settings_file, Settings, SettingsStore};
 20use std::{path::Path, sync::Arc, time::Duration};
 21use supermaven::{AccountStatus, Supermaven};
 22use ui::{prelude::*, ButtonLike, Color, Icon, IconWithIndicator, Indicator, PopoverMenuHandle};
 23use workspace::{
 24    create_and_open_local_file,
 25    item::ItemHandle,
 26    notifications::NotificationId,
 27    ui::{
 28        ButtonCommon, Clickable, ContextMenu, IconButton, IconName, IconSize, PopoverMenu, Tooltip,
 29    },
 30    StatusItemView, Toast, Workspace,
 31};
 32use zed_actions::OpenBrowser;
 33use zed_predict_tos::ZedPredictTos;
 34use zeta::RateCompletionModal;
 35
 36actions!(zeta, [RateCompletions]);
 37actions!(inline_completion, [ToggleMenu]);
 38
 39const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
 40
 41struct CopilotErrorToast;
 42
 43pub struct InlineCompletionButton {
 44    editor_subscription: Option<(Subscription, usize)>,
 45    editor_enabled: Option<bool>,
 46    language: Option<Arc<Language>>,
 47    file: Option<Arc<dyn File>>,
 48    inline_completion_provider: Option<Arc<dyn inline_completion::InlineCompletionProviderHandle>>,
 49    fs: Arc<dyn Fs>,
 50    workspace: WeakEntity<Workspace>,
 51    user_store: Entity<UserStore>,
 52    popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 53}
 54
 55enum SupermavenButtonStatus {
 56    Ready,
 57    Errored(String),
 58    NeedsActivation(String),
 59    Initializing,
 60}
 61
 62impl Render for InlineCompletionButton {
 63    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 64        let all_language_settings = all_language_settings(None, cx);
 65
 66        match all_language_settings.inline_completions.provider {
 67            InlineCompletionProvider::None => div(),
 68
 69            InlineCompletionProvider::Copilot => {
 70                let Some(copilot) = Copilot::global(cx) else {
 71                    return div();
 72                };
 73                let status = copilot.read(cx).status();
 74
 75                let enabled = self.editor_enabled.unwrap_or_else(|| {
 76                    all_language_settings.inline_completions_enabled(None, None, cx)
 77                });
 78
 79                let icon = match status {
 80                    Status::Error(_) => IconName::CopilotError,
 81                    Status::Authorized => {
 82                        if enabled {
 83                            IconName::Copilot
 84                        } else {
 85                            IconName::CopilotDisabled
 86                        }
 87                    }
 88                    _ => IconName::CopilotInit,
 89                };
 90
 91                if let Status::Error(e) = status {
 92                    return div().child(
 93                        IconButton::new("copilot-error", icon)
 94                            .icon_size(IconSize::Small)
 95                            .on_click(cx.listener(move |_, _, window, cx| {
 96                                if let Some(workspace) = window.root::<Workspace>().flatten() {
 97                                    workspace.update(cx, |workspace, cx| {
 98                                        workspace.show_toast(
 99                                            Toast::new(
100                                                NotificationId::unique::<CopilotErrorToast>(),
101                                                format!("Copilot can't be started: {}", e),
102                                            )
103                                            .on_click(
104                                                "Reinstall Copilot",
105                                                |_, cx| {
106                                                    if let Some(copilot) = Copilot::global(cx) {
107                                                        copilot
108                                                            .update(cx, |copilot, cx| {
109                                                                copilot.reinstall(cx)
110                                                            })
111                                                            .detach();
112                                                    }
113                                                },
114                                            ),
115                                            cx,
116                                        );
117                                    });
118                                }
119                            }))
120                            .tooltip(|window, cx| {
121                                Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
122                            }),
123                    );
124                }
125                let this = cx.entity().clone();
126
127                div().child(
128                    PopoverMenu::new("copilot")
129                        .menu(move |window, cx| {
130                            Some(match status {
131                                Status::Authorized => this.update(cx, |this, cx| {
132                                    this.build_copilot_context_menu(window, cx)
133                                }),
134                                _ => this.update(cx, |this, cx| {
135                                    this.build_copilot_start_menu(window, cx)
136                                }),
137                            })
138                        })
139                        .anchor(Corner::BottomRight)
140                        .trigger(IconButton::new("copilot-icon", icon).tooltip(|window, cx| {
141                            Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
142                        }))
143                        .with_handle(self.popover_menu_handle.clone()),
144                )
145            }
146
147            InlineCompletionProvider::Supermaven => {
148                let Some(supermaven) = Supermaven::global(cx) else {
149                    return div();
150                };
151
152                let supermaven = supermaven.read(cx);
153
154                let status = match supermaven {
155                    Supermaven::Starting => SupermavenButtonStatus::Initializing,
156                    Supermaven::FailedDownload { error } => {
157                        SupermavenButtonStatus::Errored(error.to_string())
158                    }
159                    Supermaven::Spawned(agent) => {
160                        let account_status = agent.account_status.clone();
161                        match account_status {
162                            AccountStatus::NeedsActivation { activate_url } => {
163                                SupermavenButtonStatus::NeedsActivation(activate_url.clone())
164                            }
165                            AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
166                            AccountStatus::Ready => SupermavenButtonStatus::Ready,
167                        }
168                    }
169                    Supermaven::Error { error } => {
170                        SupermavenButtonStatus::Errored(error.to_string())
171                    }
172                };
173
174                let icon = status.to_icon();
175                let tooltip_text = status.to_tooltip();
176                let has_menu = status.has_menu();
177                let this = cx.entity().clone();
178                let fs = self.fs.clone();
179
180                return div().child(
181                    PopoverMenu::new("supermaven")
182                        .menu(move |window, cx| match &status {
183                            SupermavenButtonStatus::NeedsActivation(activate_url) => {
184                                Some(ContextMenu::build(window, cx, |menu, _, _| {
185                                    let fs = fs.clone();
186                                    let activate_url = activate_url.clone();
187                                    menu.entry("Sign In", None, move |_, cx| {
188                                        cx.open_url(activate_url.as_str())
189                                    })
190                                    .entry(
191                                        "Use Copilot",
192                                        None,
193                                        move |_, cx| {
194                                            set_completion_provider(
195                                                fs.clone(),
196                                                cx,
197                                                InlineCompletionProvider::Copilot,
198                                            )
199                                        },
200                                    )
201                                }))
202                            }
203                            SupermavenButtonStatus::Ready => Some(this.update(cx, |this, cx| {
204                                this.build_supermaven_context_menu(window, cx)
205                            })),
206                            _ => None,
207                        })
208                        .anchor(Corner::BottomRight)
209                        .trigger(IconButton::new("supermaven-icon", icon).tooltip(
210                            move |window, cx| {
211                                if has_menu {
212                                    Tooltip::for_action(
213                                        tooltip_text.clone(),
214                                        &ToggleMenu,
215                                        window,
216                                        cx,
217                                    )
218                                } else {
219                                    Tooltip::text(tooltip_text.clone())(window, cx)
220                                }
221                            },
222                        ))
223                        .with_handle(self.popover_menu_handle.clone()),
224                );
225            }
226
227            InlineCompletionProvider::Zed => {
228                if !cx.has_flag::<PredictEditsFeatureFlag>() {
229                    return div();
230                }
231
232                if !self
233                    .user_store
234                    .read(cx)
235                    .current_user_has_accepted_terms()
236                    .unwrap_or(false)
237                {
238                    let workspace = self.workspace.clone();
239                    let user_store = self.user_store.clone();
240
241                    return div().child(
242                        ButtonLike::new("zeta-pending-tos-icon")
243                            .child(
244                                IconWithIndicator::new(
245                                    Icon::new(IconName::ZedPredict),
246                                    Some(Indicator::dot().color(Color::Error)),
247                                )
248                                .indicator_border_color(Some(
249                                    cx.theme().colors().status_bar_background,
250                                ))
251                                .into_any_element(),
252                            )
253                            .tooltip(|window, cx| {
254                                Tooltip::with_meta(
255                                    "Edit Predictions",
256                                    None,
257                                    "Read Terms of Service",
258                                    window,
259                                    cx,
260                                )
261                            })
262                            .on_click(cx.listener(move |_, _, window, cx| {
263                                let user_store = user_store.clone();
264
265                                if let Some(workspace) = workspace.upgrade() {
266                                    ZedPredictTos::toggle(workspace, user_store, window, cx);
267                                }
268                            })),
269                    );
270                }
271
272                let this = cx.entity().clone();
273                let button = IconButton::new("zeta", IconName::ZedPredict).when(
274                    !self.popover_menu_handle.is_deployed(),
275                    |button| {
276                        button.tooltip(|window, cx| {
277                            Tooltip::for_action("Edit Prediction", &ToggleMenu, window, cx)
278                        })
279                    },
280                );
281
282                let is_refreshing = self
283                    .inline_completion_provider
284                    .as_ref()
285                    .map_or(false, |provider| provider.is_refreshing(cx));
286
287                let mut popover_menu = PopoverMenu::new("zeta")
288                    .menu(move |window, cx| {
289                        Some(this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx)))
290                    })
291                    .anchor(Corner::BottomRight)
292                    .with_handle(self.popover_menu_handle.clone());
293
294                if is_refreshing {
295                    popover_menu = popover_menu.trigger(
296                        button.with_animation(
297                            "pulsating-label",
298                            Animation::new(Duration::from_secs(2))
299                                .repeat()
300                                .with_easing(pulsating_between(0.2, 1.0)),
301                            |icon_button, delta| icon_button.alpha(delta),
302                        ),
303                    );
304                } else {
305                    popover_menu = popover_menu.trigger(button);
306                }
307
308                div().child(popover_menu.into_any_element())
309            }
310        }
311    }
312}
313
314impl InlineCompletionButton {
315    pub fn new(
316        workspace: WeakEntity<Workspace>,
317        fs: Arc<dyn Fs>,
318        user_store: Entity<UserStore>,
319        popover_menu_handle: PopoverMenuHandle<ContextMenu>,
320        cx: &mut Context<Self>,
321    ) -> Self {
322        if let Some(copilot) = Copilot::global(cx) {
323            cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
324        }
325
326        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
327            .detach();
328
329        Self {
330            editor_subscription: None,
331            editor_enabled: None,
332            language: None,
333            file: None,
334            inline_completion_provider: None,
335            popover_menu_handle,
336            workspace,
337            fs,
338            user_store,
339        }
340    }
341
342    pub fn build_copilot_start_menu(
343        &mut self,
344        window: &mut Window,
345        cx: &mut Context<Self>,
346    ) -> Entity<ContextMenu> {
347        let fs = self.fs.clone();
348        ContextMenu::build(window, cx, |menu, _, _| {
349            menu.entry("Sign In", None, copilot::initiate_sign_in)
350                .entry("Disable Copilot", None, {
351                    let fs = fs.clone();
352                    move |_window, cx| hide_copilot(fs.clone(), cx)
353                })
354                .entry("Use Supermaven", None, {
355                    let fs = fs.clone();
356                    move |_window, cx| {
357                        set_completion_provider(
358                            fs.clone(),
359                            cx,
360                            InlineCompletionProvider::Supermaven,
361                        )
362                    }
363                })
364        })
365    }
366
367    pub fn build_language_settings_menu(&self, mut menu: ContextMenu, cx: &mut App) -> ContextMenu {
368        let fs = self.fs.clone();
369
370        if let Some(language) = self.language.clone() {
371            let fs = fs.clone();
372            let language_enabled =
373                language_settings::language_settings(Some(language.name()), None, cx)
374                    .show_inline_completions;
375
376            menu = menu.entry(
377                format!(
378                    "{} Inline Completions for {}",
379                    if language_enabled { "Hide" } else { "Show" },
380                    language.name()
381                ),
382                None,
383                move |_, cx| {
384                    toggle_inline_completions_for_language(language.clone(), fs.clone(), cx)
385                },
386            );
387        }
388
389        let settings = AllLanguageSettings::get_global(cx);
390
391        if let Some(file) = &self.file {
392            let path = file.path().clone();
393            let path_enabled = settings.inline_completions_enabled_for_path(&path);
394
395            menu = menu.entry(
396                format!(
397                    "{} Inline Completions for This Path",
398                    if path_enabled { "Hide" } else { "Show" }
399                ),
400                None,
401                move |window, cx| {
402                    if let Some(workspace) = window.root().flatten() {
403                        let workspace = workspace.downgrade();
404                        window
405                            .spawn(cx, |cx| {
406                                configure_disabled_globs(
407                                    workspace,
408                                    path_enabled.then_some(path.clone()),
409                                    cx,
410                                )
411                            })
412                            .detach_and_log_err(cx);
413                    }
414                },
415            );
416        }
417
418        let globally_enabled = settings.inline_completions_enabled(None, None, cx);
419        menu.entry(
420            if globally_enabled {
421                "Hide Inline Completions for All Files"
422            } else {
423                "Show Inline Completions for All Files"
424            },
425            None,
426            move |_, cx| toggle_inline_completions_globally(fs.clone(), cx),
427        )
428    }
429
430    fn build_copilot_context_menu(
431        &self,
432        window: &mut Window,
433        cx: &mut Context<Self>,
434    ) -> Entity<ContextMenu> {
435        ContextMenu::build(window, cx, |menu, _, cx| {
436            self.build_language_settings_menu(menu, cx)
437                .separator()
438                .link(
439                    "Go to Copilot Settings",
440                    OpenBrowser {
441                        url: COPILOT_SETTINGS_URL.to_string(),
442                    }
443                    .boxed_clone(),
444                )
445                .action("Sign Out", copilot::SignOut.boxed_clone())
446        })
447    }
448
449    fn build_supermaven_context_menu(
450        &self,
451        window: &mut Window,
452        cx: &mut Context<Self>,
453    ) -> Entity<ContextMenu> {
454        ContextMenu::build(window, cx, |menu, _, cx| {
455            self.build_language_settings_menu(menu, cx)
456                .separator()
457                .action("Sign Out", supermaven::SignOut.boxed_clone())
458        })
459    }
460
461    fn build_zeta_context_menu(
462        &self,
463        window: &mut Window,
464        cx: &mut Context<Self>,
465    ) -> Entity<ContextMenu> {
466        let workspace = self.workspace.clone();
467        ContextMenu::build(window, cx, |menu, _window, cx| {
468            self.build_language_settings_menu(menu, cx).when(
469                cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
470                |this| {
471                    this.separator().entry(
472                        "Rate Completions",
473                        Some(RateCompletions.boxed_clone()),
474                        move |window, cx| {
475                            workspace
476                                .update(cx, |workspace, cx| {
477                                    RateCompletionModal::toggle(workspace, window, cx)
478                                })
479                                .ok();
480                        },
481                    )
482                },
483            )
484        })
485    }
486
487    pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
488        let editor = editor.read(cx);
489        let snapshot = editor.buffer().read(cx).snapshot(cx);
490        let suggestion_anchor = editor.selections.newest_anchor().start;
491        let language = snapshot.language_at(suggestion_anchor);
492        let file = snapshot.file_at(suggestion_anchor).cloned();
493        self.editor_enabled = {
494            let file = file.as_ref();
495            Some(
496                file.map(|file| !file.is_private()).unwrap_or(true)
497                    && all_language_settings(file, cx).inline_completions_enabled(
498                        language,
499                        file.map(|file| file.path().as_ref()),
500                        cx,
501                    ),
502            )
503        };
504        self.inline_completion_provider = editor.inline_completion_provider();
505        self.language = language.cloned();
506        self.file = file;
507
508        cx.notify();
509    }
510
511    pub fn toggle_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
512        self.popover_menu_handle.toggle(window, cx);
513    }
514}
515
516impl StatusItemView for InlineCompletionButton {
517    fn set_active_pane_item(
518        &mut self,
519        item: Option<&dyn ItemHandle>,
520        _: &mut Window,
521        cx: &mut Context<Self>,
522    ) {
523        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
524            self.editor_subscription = Some((
525                cx.observe(&editor, Self::update_enabled),
526                editor.entity_id().as_u64() as usize,
527            ));
528            self.update_enabled(editor, cx);
529        } else {
530            self.language = None;
531            self.editor_subscription = None;
532            self.editor_enabled = None;
533        }
534        cx.notify();
535    }
536}
537
538impl SupermavenButtonStatus {
539    fn to_icon(&self) -> IconName {
540        match self {
541            SupermavenButtonStatus::Ready => IconName::Supermaven,
542            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
543            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
544            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
545        }
546    }
547
548    fn to_tooltip(&self) -> String {
549        match self {
550            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
551            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
552            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
553            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
554        }
555    }
556
557    fn has_menu(&self) -> bool {
558        match self {
559            SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
560            SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
561        }
562    }
563}
564
565async fn configure_disabled_globs(
566    workspace: WeakEntity<Workspace>,
567    path_to_disable: Option<Arc<Path>>,
568    mut cx: AsyncWindowContext,
569) -> Result<()> {
570    let settings_editor = workspace
571        .update_in(&mut cx, |_, window, cx| {
572            create_and_open_local_file(paths::settings_file(), window, cx, || {
573                settings::initial_user_settings_content().as_ref().into()
574            })
575        })?
576        .await?
577        .downcast::<Editor>()
578        .unwrap();
579
580    settings_editor
581        .downgrade()
582        .update_in(&mut cx, |item, window, cx| {
583            let text = item.buffer().read(cx).snapshot(cx).text();
584
585            let settings = cx.global::<SettingsStore>();
586            let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
587                let copilot = file.inline_completions.get_or_insert_with(Default::default);
588                let globs = copilot.disabled_globs.get_or_insert_with(|| {
589                    settings
590                        .get::<AllLanguageSettings>(None)
591                        .inline_completions
592                        .disabled_globs
593                        .iter()
594                        .map(|glob| glob.glob().to_string())
595                        .collect()
596                });
597
598                if let Some(path_to_disable) = &path_to_disable {
599                    globs.push(path_to_disable.to_string_lossy().into_owned());
600                } else {
601                    globs.clear();
602                }
603            });
604
605            if !edits.is_empty() {
606                item.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
607                    selections.select_ranges(edits.iter().map(|e| e.0.clone()));
608                });
609
610                // When *enabling* a path, don't actually perform an edit, just select the range.
611                if path_to_disable.is_some() {
612                    item.edit(edits.iter().cloned(), cx);
613                }
614            }
615        })?;
616
617    anyhow::Ok(())
618}
619
620fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut App) {
621    let show_inline_completions =
622        all_language_settings(None, cx).inline_completions_enabled(None, None, cx);
623    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
624        file.defaults.show_inline_completions = Some(!show_inline_completions)
625    });
626}
627
628fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: InlineCompletionProvider) {
629    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
630        file.features
631            .get_or_insert(Default::default())
632            .inline_completion_provider = Some(provider);
633    });
634}
635
636fn toggle_inline_completions_for_language(language: Arc<Language>, fs: Arc<dyn Fs>, cx: &mut App) {
637    let show_inline_completions =
638        all_language_settings(None, cx).inline_completions_enabled(Some(&language), None, cx);
639    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
640        file.languages
641            .entry(language.name())
642            .or_default()
643            .show_inline_completions = Some(!show_inline_completions);
644    });
645}
646
647fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
648    update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
649        file.features
650            .get_or_insert(Default::default())
651            .inline_completion_provider = Some(InlineCompletionProvider::None);
652    });
653}