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