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, Indicator,
28 PopoverMenu, 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(true);
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 if !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 "Read Terms of Service"
247 } else {
248 "Sign in to use"
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::Error))
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 icon_button = IconButton::new("zed-predict-pending-button", zeta_icon)
279 .shape(IconButtonShape::Square)
280 .when(!self.popover_menu_handle.is_deployed(), |element| {
281 if enabled {
282 element.tooltip(|window, cx| {
283 Tooltip::for_action("Edit Prediction", &ToggleMenu, window, cx)
284 })
285 } else {
286 element.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.editor_enabled.unwrap_or(true) {
473 menu = menu.item(
474 ContextMenuEntry::new("This file is excluded.")
475 .disabled(true)
476 .icon(IconName::ZedPredictDisabled)
477 .icon_size(IconSize::Small),
478 );
479 }
480
481 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
482 menu = menu
483 .separator()
484 .entry(
485 "Predict Edit at Cursor",
486 Some(Box::new(ShowEditPrediction)),
487 {
488 let editor_focus_handle = editor_focus_handle.clone();
489
490 move |window, cx| {
491 editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
492 }
493 },
494 )
495 .context(editor_focus_handle);
496 }
497
498 menu
499 }
500
501 fn build_copilot_context_menu(
502 &self,
503 window: &mut Window,
504 cx: &mut Context<Self>,
505 ) -> Entity<ContextMenu> {
506 ContextMenu::build(window, cx, |menu, _, cx| {
507 self.build_language_settings_menu(menu, cx)
508 .separator()
509 .link(
510 "Go to Copilot Settings",
511 OpenBrowser {
512 url: COPILOT_SETTINGS_URL.to_string(),
513 }
514 .boxed_clone(),
515 )
516 .action("Sign Out", copilot::SignOut.boxed_clone())
517 })
518 }
519
520 fn build_supermaven_context_menu(
521 &self,
522 window: &mut Window,
523 cx: &mut Context<Self>,
524 ) -> Entity<ContextMenu> {
525 ContextMenu::build(window, cx, |menu, _, cx| {
526 self.build_language_settings_menu(menu, cx)
527 .separator()
528 .action("Sign Out", supermaven::SignOut.boxed_clone())
529 })
530 }
531
532 fn build_zeta_context_menu(
533 &self,
534 window: &mut Window,
535 cx: &mut Context<Self>,
536 ) -> Entity<ContextMenu> {
537 let workspace = self.workspace.clone();
538 ContextMenu::build(window, cx, |menu, _window, cx| {
539 self.build_language_settings_menu(menu, cx).when(
540 cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
541 |this| {
542 this.entry(
543 "Rate Completions",
544 Some(RateCompletions.boxed_clone()),
545 move |window, cx| {
546 workspace
547 .update(cx, |workspace, cx| {
548 RateCompletionModal::toggle(workspace, window, cx)
549 })
550 .ok();
551 },
552 )
553 },
554 )
555 })
556 }
557
558 pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
559 let editor = editor.read(cx);
560 let snapshot = editor.buffer().read(cx).snapshot(cx);
561 let suggestion_anchor = editor.selections.newest_anchor().start;
562 let language = snapshot.language_at(suggestion_anchor);
563 let file = snapshot.file_at(suggestion_anchor).cloned();
564 self.editor_enabled = {
565 let file = file.as_ref();
566 Some(
567 file.map(|file| {
568 all_language_settings(Some(file), cx)
569 .inline_completions_enabled_for_path(file.path())
570 })
571 .unwrap_or(true),
572 )
573 };
574 self.edit_prediction_provider = editor.edit_prediction_provider();
575 self.language = language.cloned();
576 self.file = file;
577 self.editor_focus_handle = Some(editor.focus_handle(cx));
578
579 cx.notify();
580 }
581
582 pub fn toggle_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
583 self.popover_menu_handle.toggle(window, cx);
584 }
585}
586
587impl StatusItemView for InlineCompletionButton {
588 fn set_active_pane_item(
589 &mut self,
590 item: Option<&dyn ItemHandle>,
591 _: &mut Window,
592 cx: &mut Context<Self>,
593 ) {
594 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
595 self.editor_subscription = Some((
596 cx.observe(&editor, Self::update_enabled),
597 editor.entity_id().as_u64() as usize,
598 ));
599 self.update_enabled(editor, cx);
600 } else {
601 self.language = None;
602 self.editor_subscription = None;
603 self.editor_enabled = None;
604 }
605 cx.notify();
606 }
607}
608
609impl SupermavenButtonStatus {
610 fn to_icon(&self) -> IconName {
611 match self {
612 SupermavenButtonStatus::Ready => IconName::Supermaven,
613 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
614 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
615 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
616 }
617 }
618
619 fn to_tooltip(&self) -> String {
620 match self {
621 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
622 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
623 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
624 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
625 }
626 }
627
628 fn has_menu(&self) -> bool {
629 match self {
630 SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
631 SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
632 }
633 }
634}
635
636async fn open_disabled_globs_setting_in_editor(
637 workspace: WeakEntity<Workspace>,
638 mut cx: AsyncWindowContext,
639) -> Result<()> {
640 let settings_editor = workspace
641 .update_in(&mut cx, |_, window, cx| {
642 create_and_open_local_file(paths::settings_file(), window, cx, || {
643 settings::initial_user_settings_content().as_ref().into()
644 })
645 })?
646 .await?
647 .downcast::<Editor>()
648 .unwrap();
649
650 settings_editor
651 .downgrade()
652 .update_in(&mut cx, |item, window, cx| {
653 let text = item.buffer().read(cx).snapshot(cx).text();
654
655 let settings = cx.global::<SettingsStore>();
656
657 // Ensure that we always have "inline_completions { "disabled_globs": [] }"
658 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
659 file.edit_predictions
660 .get_or_insert_with(Default::default)
661 .disabled_globs
662 .get_or_insert_with(Vec::new);
663 });
664
665 if !edits.is_empty() {
666 item.edit(edits.iter().cloned(), cx);
667 }
668
669 let text = item.buffer().read(cx).snapshot(cx).text();
670
671 static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
672 Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
673 });
674 // Only capture [...]
675 let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
676 captures
677 .name("content")
678 .map(|inner_match| inner_match.start()..inner_match.end())
679 });
680 if let Some(range) = range {
681 item.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
682 selections.select_ranges(vec![range]);
683 });
684 }
685 })?;
686
687 anyhow::Ok(())
688}
689
690fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut App) {
691 let show_edit_predictions = all_language_settings(None, cx).show_inline_completions(None, cx);
692 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
693 file.defaults.show_edit_predictions = Some(!show_edit_predictions)
694 });
695}
696
697fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
698 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
699 file.features
700 .get_or_insert(Default::default())
701 .edit_prediction_provider = Some(provider);
702 });
703}
704
705fn toggle_show_inline_completions_for_language(
706 language: Arc<Language>,
707 fs: Arc<dyn Fs>,
708 cx: &mut App,
709) {
710 let show_edit_predictions =
711 all_language_settings(None, cx).show_inline_completions(Some(&language), cx);
712 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
713 file.languages
714 .entry(language.name())
715 .or_default()
716 .show_edit_predictions = Some(!show_edit_predictions);
717 });
718}
719
720fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
721 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
722 file.features
723 .get_or_insert(Default::default())
724 .edit_prediction_provider = Some(EditPredictionProvider::None);
725 });
726}