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