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