1use anyhow::Result;
2use client::UserStore;
3use copilot::{Copilot, Status};
4use editor::{actions::ShowEditPrediction, 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, FocusHandle, Focusable, IntoElement, ParentElement, Render, Subscription,
12 WeakEntity,
13};
14use indoc::indoc;
15use language::{
16 language_settings::{self, all_language_settings, AllLanguageSettings, EditPredictionProvider},
17 File, Language,
18};
19use regex::Regex;
20use settings::{update_settings_file, Settings, SettingsStore};
21use std::{
22 sync::{Arc, LazyLock},
23 time::Duration,
24};
25use supermaven::{AccountStatus, Supermaven};
26use ui::{
27 prelude::*, Clickable, ContextMenu, ContextMenuEntry, IconButton, IconButtonShape, PopoverMenu,
28 PopoverMenuHandle, Tooltip,
29};
30use workspace::{
31 create_and_open_local_file, item::ItemHandle, notifications::NotificationId, StatusItemView,
32 Toast, Workspace,
33};
34use zed_actions::OpenBrowser;
35use zeta::RateCompletionModal;
36
37actions!(zeta, [RateCompletions]);
38actions!(edit_prediction, [ToggleMenu]);
39
40const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
41
42struct CopilotErrorToast;
43
44pub struct InlineCompletionButton {
45 editor_subscription: Option<(Subscription, usize)>,
46 editor_enabled: Option<bool>,
47 editor_focus_handle: Option<FocusHandle>,
48 language: Option<Arc<Language>>,
49 file: Option<Arc<dyn File>>,
50 edit_prediction_provider: Option<Arc<dyn inline_completion::InlineCompletionProviderHandle>>,
51 fs: Arc<dyn Fs>,
52 workspace: WeakEntity<Workspace>,
53 user_store: Entity<UserStore>,
54 popover_menu_handle: PopoverMenuHandle<ContextMenu>,
55}
56
57enum SupermavenButtonStatus {
58 Ready,
59 Errored(String),
60 NeedsActivation(String),
61 Initializing,
62}
63
64impl Render for InlineCompletionButton {
65 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
66 let all_language_settings = all_language_settings(None, cx);
67
68 match all_language_settings.edit_predictions.provider {
69 EditPredictionProvider::None => div(),
70
71 EditPredictionProvider::Copilot => {
72 let Some(copilot) = Copilot::global(cx) else {
73 return div();
74 };
75 let status = copilot.read(cx).status();
76
77 let enabled = self.editor_enabled.unwrap_or(false);
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 EditPredictionProvider::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 EditPredictionProvider::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 EditPredictionProvider::Zed => {
228 if !cx.has_flag::<PredictEditsFeatureFlag>() {
229 return div();
230 }
231
232 let enabled = self.editor_enabled.unwrap_or(false);
233
234 let zeta_icon = if enabled {
235 IconName::ZedPredict
236 } else {
237 IconName::ZedPredictDisabled
238 };
239
240 let current_user_terms_accepted =
241 self.user_store.read(cx).current_user_has_accepted_terms();
242
243 let icon_button = || {
244 let base = IconButton::new("zed-predict-pending-button", zeta_icon)
245 .shape(IconButtonShape::Square);
246
247 match (
248 current_user_terms_accepted,
249 self.popover_menu_handle.is_deployed(),
250 enabled,
251 ) {
252 (Some(false) | None, _, _) => {
253 let signed_in = current_user_terms_accepted.is_some();
254 let tooltip_meta = if signed_in {
255 "Read Terms of Service"
256 } else {
257 "Sign in to use"
258 };
259
260 base.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(
270 move |_, _, window, cx| {
271 telemetry::event!(
272 "Pending ToS Clicked",
273 source = "Edit Prediction Status Button"
274 );
275 window.dispatch_action(
276 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
277 cx,
278 );
279 },
280 ))
281 }
282 (Some(true), true, _) => base,
283 (Some(true), false, true) => base.tooltip(|window, cx| {
284 Tooltip::for_action("Edit Prediction", &ToggleMenu, window, cx)
285 }),
286 (Some(true), false, false) => base.tooltip(|window, cx| {
287 Tooltip::with_meta(
288 "Edit Prediction",
289 Some(&ToggleMenu),
290 "Disabled For This File",
291 window,
292 cx,
293 )
294 }),
295 }
296 };
297
298 let this = cx.entity().clone();
299
300 let mut popover_menu = PopoverMenu::new("zeta")
301 .menu(move |window, cx| {
302 Some(this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx)))
303 })
304 .anchor(Corner::BottomRight)
305 .with_handle(self.popover_menu_handle.clone());
306
307 let is_refreshing = self
308 .edit_prediction_provider
309 .as_ref()
310 .map_or(false, |provider| provider.is_refreshing(cx));
311
312 if is_refreshing {
313 popover_menu = popover_menu.trigger(
314 icon_button().with_animation(
315 "pulsating-label",
316 Animation::new(Duration::from_secs(2))
317 .repeat()
318 .with_easing(pulsating_between(0.2, 1.0)),
319 |icon_button, delta| icon_button.alpha(delta),
320 ),
321 );
322 } else {
323 popover_menu = popover_menu.trigger(icon_button());
324 }
325
326 div().child(popover_menu.into_any_element())
327 }
328 }
329 }
330}
331
332impl InlineCompletionButton {
333 pub fn new(
334 workspace: WeakEntity<Workspace>,
335 fs: Arc<dyn Fs>,
336 user_store: Entity<UserStore>,
337 popover_menu_handle: PopoverMenuHandle<ContextMenu>,
338 cx: &mut Context<Self>,
339 ) -> Self {
340 if let Some(copilot) = Copilot::global(cx) {
341 cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
342 }
343
344 cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
345 .detach();
346
347 Self {
348 editor_subscription: None,
349 editor_enabled: None,
350 editor_focus_handle: None,
351 language: None,
352 file: None,
353 edit_prediction_provider: None,
354 popover_menu_handle,
355 workspace,
356 fs,
357 user_store,
358 }
359 }
360
361 pub fn build_copilot_start_menu(
362 &mut self,
363 window: &mut Window,
364 cx: &mut Context<Self>,
365 ) -> Entity<ContextMenu> {
366 let fs = self.fs.clone();
367 ContextMenu::build(window, cx, |menu, _, _| {
368 menu.entry("Sign In", None, copilot::initiate_sign_in)
369 .entry("Disable Copilot", None, {
370 let fs = fs.clone();
371 move |_window, cx| hide_copilot(fs.clone(), cx)
372 })
373 .entry("Use Supermaven", None, {
374 let fs = fs.clone();
375 move |_window, cx| {
376 set_completion_provider(fs.clone(), cx, EditPredictionProvider::Supermaven)
377 }
378 })
379 })
380 }
381
382 pub fn build_language_settings_menu(&self, mut menu: ContextMenu, cx: &mut App) -> ContextMenu {
383 let fs = self.fs.clone();
384
385 menu = menu.header("Show Edit Predictions For");
386
387 if let Some(language) = self.language.clone() {
388 let fs = fs.clone();
389 let language_enabled =
390 language_settings::language_settings(Some(language.name()), None, cx)
391 .show_edit_predictions;
392
393 menu = menu.toggleable_entry(
394 language.name(),
395 language_enabled,
396 IconPosition::End,
397 None,
398 move |_, cx| {
399 toggle_show_inline_completions_for_language(language.clone(), fs.clone(), cx)
400 },
401 );
402 }
403
404 let settings = AllLanguageSettings::get_global(cx);
405 let globally_enabled = settings.show_inline_completions(None, cx);
406 menu = menu.toggleable_entry(
407 "All Files",
408 globally_enabled,
409 IconPosition::End,
410 None,
411 move |_, cx| toggle_inline_completions_globally(fs.clone(), cx),
412 );
413 menu = menu.separator().header("Privacy Settings");
414
415 if let Some(provider) = &self.edit_prediction_provider {
416 let data_collection = provider.data_collection_state(cx);
417 if data_collection.is_supported() {
418 let provider = provider.clone();
419 let enabled = data_collection.is_enabled();
420
421 menu = menu.item(
422 // TODO: We want to add something later that communicates whether
423 // the current project is open-source.
424 ContextMenuEntry::new("Share Training Data")
425 .toggleable(IconPosition::End, data_collection.is_enabled())
426 .documentation_aside(|_| {
427 Label::new(indoc!{"
428 Help us improve our open model by sharing data from open source repositories. \
429 Zed must detect a license file in your repo for this setting to take effect.\
430 "}).into_any_element()
431 })
432 .handler(move |_, cx| {
433 provider.toggle_data_collection(cx);
434
435 if !enabled {
436 telemetry::event!(
437 "Data Collection Enabled",
438 source = "Edit Prediction Status Menu"
439 );
440 } else {
441 telemetry::event!(
442 "Data Collection Disabled",
443 source = "Edit Prediction Status Menu"
444 );
445 }
446 })
447 )
448 }
449 }
450
451 menu = menu.item(
452 ContextMenuEntry::new("Configure Excluded Files")
453 .documentation_aside(|_| {
454 Label::new(indoc!{"
455 Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
456 })
457 .handler(move |window, cx| {
458 if let Some(workspace) = window.root().flatten() {
459 let workspace = workspace.downgrade();
460 window
461 .spawn(cx, |cx| {
462 open_disabled_globs_setting_in_editor(
463 workspace,
464 cx,
465 )
466 })
467 .detach_and_log_err(cx);
468 }
469 }),
470 );
471
472 if self.file.as_ref().map_or(false, |file| {
473 !all_language_settings(Some(file), cx).inline_completions_enabled_for_path(file.path())
474 }) {
475 menu = menu.item(
476 ContextMenuEntry::new("This file is excluded.")
477 .disabled(true)
478 .icon(IconName::ZedPredictDisabled)
479 .icon_size(IconSize::Small),
480 );
481 }
482
483 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
484 menu = menu
485 .separator()
486 .entry(
487 "Predict Edit at Cursor",
488 Some(Box::new(ShowEditPrediction)),
489 {
490 let editor_focus_handle = editor_focus_handle.clone();
491
492 move |window, cx| {
493 editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
494 }
495 },
496 )
497 .context(editor_focus_handle);
498 }
499
500 menu
501 }
502
503 fn build_copilot_context_menu(
504 &self,
505 window: &mut Window,
506 cx: &mut Context<Self>,
507 ) -> Entity<ContextMenu> {
508 ContextMenu::build(window, cx, |menu, _, cx| {
509 self.build_language_settings_menu(menu, cx)
510 .separator()
511 .link(
512 "Go to Copilot Settings",
513 OpenBrowser {
514 url: COPILOT_SETTINGS_URL.to_string(),
515 }
516 .boxed_clone(),
517 )
518 .action("Sign Out", copilot::SignOut.boxed_clone())
519 })
520 }
521
522 fn build_supermaven_context_menu(
523 &self,
524 window: &mut Window,
525 cx: &mut Context<Self>,
526 ) -> Entity<ContextMenu> {
527 ContextMenu::build(window, cx, |menu, _, cx| {
528 self.build_language_settings_menu(menu, cx)
529 .separator()
530 .action("Sign Out", supermaven::SignOut.boxed_clone())
531 })
532 }
533
534 fn build_zeta_context_menu(
535 &self,
536 window: &mut Window,
537 cx: &mut Context<Self>,
538 ) -> Entity<ContextMenu> {
539 let workspace = self.workspace.clone();
540 ContextMenu::build(window, cx, |menu, _window, cx| {
541 self.build_language_settings_menu(menu, cx).when(
542 cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
543 |this| {
544 this.entry(
545 "Rate Completions",
546 Some(RateCompletions.boxed_clone()),
547 move |window, cx| {
548 workspace
549 .update(cx, |workspace, cx| {
550 RateCompletionModal::toggle(workspace, window, cx)
551 })
552 .ok();
553 },
554 )
555 },
556 )
557 })
558 }
559
560 pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
561 let editor = editor.read(cx);
562 let snapshot = editor.buffer().read(cx).snapshot(cx);
563 let suggestion_anchor = editor.selections.newest_anchor().start;
564 let language = snapshot.language_at(suggestion_anchor);
565 let file = snapshot.file_at(suggestion_anchor).cloned();
566 self.editor_enabled = {
567 let file = file.as_ref();
568 Some(
569 file.map(|file| {
570 all_language_settings(Some(file), cx)
571 .inline_completions_enabled_for_path(file.path())
572 })
573 .unwrap_or(true),
574 )
575 };
576 self.edit_prediction_provider = editor.edit_prediction_provider();
577 self.language = language.cloned();
578 self.file = file;
579 self.editor_focus_handle = Some(editor.focus_handle(cx));
580
581 cx.notify();
582 }
583
584 pub fn toggle_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
585 self.popover_menu_handle.toggle(window, cx);
586 }
587}
588
589impl StatusItemView for InlineCompletionButton {
590 fn set_active_pane_item(
591 &mut self,
592 item: Option<&dyn ItemHandle>,
593 _: &mut Window,
594 cx: &mut Context<Self>,
595 ) {
596 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
597 self.editor_subscription = Some((
598 cx.observe(&editor, Self::update_enabled),
599 editor.entity_id().as_u64() as usize,
600 ));
601 self.update_enabled(editor, cx);
602 } else {
603 self.language = None;
604 self.editor_subscription = None;
605 self.editor_enabled = None;
606 }
607 cx.notify();
608 }
609}
610
611impl SupermavenButtonStatus {
612 fn to_icon(&self) -> IconName {
613 match self {
614 SupermavenButtonStatus::Ready => IconName::Supermaven,
615 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
616 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
617 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
618 }
619 }
620
621 fn to_tooltip(&self) -> String {
622 match self {
623 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
624 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
625 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
626 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
627 }
628 }
629
630 fn has_menu(&self) -> bool {
631 match self {
632 SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
633 SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
634 }
635 }
636}
637
638async fn open_disabled_globs_setting_in_editor(
639 workspace: WeakEntity<Workspace>,
640 mut cx: AsyncWindowContext,
641) -> Result<()> {
642 let settings_editor = workspace
643 .update_in(&mut cx, |_, window, cx| {
644 create_and_open_local_file(paths::settings_file(), window, cx, || {
645 settings::initial_user_settings_content().as_ref().into()
646 })
647 })?
648 .await?
649 .downcast::<Editor>()
650 .unwrap();
651
652 settings_editor
653 .downgrade()
654 .update_in(&mut cx, |item, window, cx| {
655 let text = item.buffer().read(cx).snapshot(cx).text();
656
657 let settings = cx.global::<SettingsStore>();
658
659 // Ensure that we always have "inline_completions { "disabled_globs": [] }"
660 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
661 file.edit_predictions
662 .get_or_insert_with(Default::default)
663 .disabled_globs
664 .get_or_insert_with(Vec::new);
665 });
666
667 if !edits.is_empty() {
668 item.edit(edits.iter().cloned(), cx);
669 }
670
671 let text = item.buffer().read(cx).snapshot(cx).text();
672
673 static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
674 Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
675 });
676 // Only capture [...]
677 let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
678 captures
679 .name("content")
680 .map(|inner_match| inner_match.start()..inner_match.end())
681 });
682 if let Some(range) = range {
683 item.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
684 selections.select_ranges(vec![range]);
685 });
686 }
687 })?;
688
689 anyhow::Ok(())
690}
691
692fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut App) {
693 let show_edit_predictions = all_language_settings(None, cx).show_inline_completions(None, cx);
694 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
695 file.defaults.show_edit_predictions = Some(!show_edit_predictions)
696 });
697}
698
699fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
700 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
701 file.features
702 .get_or_insert(Default::default())
703 .edit_prediction_provider = Some(provider);
704 });
705}
706
707fn toggle_show_inline_completions_for_language(
708 language: Arc<Language>,
709 fs: Arc<dyn Fs>,
710 cx: &mut App,
711) {
712 let show_edit_predictions =
713 all_language_settings(None, cx).show_inline_completions(Some(&language), cx);
714 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
715 file.languages
716 .entry(language.name())
717 .or_default()
718 .show_edit_predictions = Some(!show_edit_predictions);
719 });
720}
721
722fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
723 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
724 file.features
725 .get_or_insert(Default::default())
726 .edit_prediction_provider = Some(EditPredictionProvider::None);
727 });
728}