edit_prediction_button.rs

   1use anyhow::Result;
   2use client::{UserStore, zed_urls};
   3use cloud_llm_client::UsageLimit;
   4use copilot::{Copilot, Status};
   5use editor::{Editor, SelectionEffects, actions::ShowEditPrediction, scroll::Autoscroll};
   6use feature_flags::{FeatureFlagAppExt, PredictEditsRateCompletionsFeatureFlag};
   7use fs::Fs;
   8use gpui::{
   9    Action, Animation, AnimationExt, App, AsyncWindowContext, Corner, Entity, FocusHandle,
  10    Focusable, IntoElement, ParentElement, Render, Subscription, WeakEntity, actions, div,
  11    pulsating_between,
  12};
  13use indoc::indoc;
  14use language::{
  15    EditPredictionsMode, File, Language,
  16    language_settings::{self, AllLanguageSettings, EditPredictionProvider, all_language_settings},
  17};
  18use project::DisableAiSettings;
  19use regex::Regex;
  20use settings::{Settings, SettingsStore, update_settings_file};
  21use std::{
  22    sync::{Arc, LazyLock},
  23    time::Duration,
  24};
  25use supermaven::{AccountStatus, Supermaven};
  26use ui::{
  27    Clickable, ContextMenu, ContextMenuEntry, DocumentationEdge, DocumentationSide, IconButton,
  28    IconButtonShape, Indicator, PopoverMenu, PopoverMenuHandle, ProgressBar, Tooltip, prelude::*,
  29};
  30use workspace::{
  31    StatusItemView, Toast, Workspace, create_and_open_local_file, item::ItemHandle,
  32    notifications::NotificationId,
  33};
  34use zed_actions::OpenBrowser;
  35use zeta::RateCompletions;
  36
  37actions!(
  38    edit_prediction,
  39    [
  40        /// Toggles the edit prediction menu.
  41        ToggleMenu
  42    ]
  43);
  44
  45const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
  46const PRIVACY_DOCS: &str = "https://zed.dev/docs/ai/privacy-and-security";
  47
  48struct CopilotErrorToast;
  49
  50pub struct EditPredictionButton {
  51    editor_subscription: Option<(Subscription, usize)>,
  52    editor_enabled: Option<bool>,
  53    editor_show_predictions: bool,
  54    editor_focus_handle: Option<FocusHandle>,
  55    language: Option<Arc<Language>>,
  56    file: Option<Arc<dyn File>>,
  57    edit_prediction_provider: Option<Arc<dyn edit_prediction::EditPredictionProviderHandle>>,
  58    fs: Arc<dyn Fs>,
  59    user_store: Entity<UserStore>,
  60    popover_menu_handle: PopoverMenuHandle<ContextMenu>,
  61}
  62
  63enum SupermavenButtonStatus {
  64    Ready,
  65    Errored(String),
  66    NeedsActivation(String),
  67    Initializing,
  68}
  69
  70impl Render for EditPredictionButton {
  71    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
  72        // Return empty div if AI is disabled
  73        if DisableAiSettings::get_global(cx).disable_ai {
  74            return div();
  75        }
  76
  77        let all_language_settings = all_language_settings(None, cx);
  78
  79        match all_language_settings.edit_predictions.provider {
  80            EditPredictionProvider::None => div(),
  81
  82            EditPredictionProvider::Copilot => {
  83                let Some(copilot) = Copilot::global(cx) else {
  84                    return div();
  85                };
  86                let status = copilot.read(cx).status();
  87
  88                let enabled = self.editor_enabled.unwrap_or(false);
  89
  90                let icon = match status {
  91                    Status::Error(_) => IconName::CopilotError,
  92                    Status::Authorized => {
  93                        if enabled {
  94                            IconName::Copilot
  95                        } else {
  96                            IconName::CopilotDisabled
  97                        }
  98                    }
  99                    _ => IconName::CopilotInit,
 100                };
 101
 102                if let Status::Error(e) = status {
 103                    return div().child(
 104                        IconButton::new("copilot-error", icon)
 105                            .icon_size(IconSize::Small)
 106                            .on_click(cx.listener(move |_, _, window, cx| {
 107                                if let Some(workspace) = window.root::<Workspace>().flatten() {
 108                                    workspace.update(cx, |workspace, cx| {
 109                                        workspace.show_toast(
 110                                            Toast::new(
 111                                                NotificationId::unique::<CopilotErrorToast>(),
 112                                                format!("Copilot can't be started: {}", e),
 113                                            )
 114                                            .on_click(
 115                                                "Reinstall Copilot",
 116                                                |window, cx| {
 117                                                    copilot::reinstall_and_sign_in(window, cx)
 118                                                },
 119                                            ),
 120                                            cx,
 121                                        );
 122                                    });
 123                                }
 124                            }))
 125                            .tooltip(|window, cx| {
 126                                Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
 127                            }),
 128                    );
 129                }
 130                let this = cx.entity();
 131
 132                div().child(
 133                    PopoverMenu::new("copilot")
 134                        .menu(move |window, cx| {
 135                            let current_status = Copilot::global(cx)?.read(cx).status();
 136                            Some(match current_status {
 137                                Status::Authorized => this.update(cx, |this, cx| {
 138                                    this.build_copilot_context_menu(window, cx)
 139                                }),
 140                                _ => this.update(cx, |this, cx| {
 141                                    this.build_copilot_start_menu(window, cx)
 142                                }),
 143                            })
 144                        })
 145                        .anchor(Corner::BottomRight)
 146                        .trigger_with_tooltip(
 147                            IconButton::new("copilot-icon", icon),
 148                            |window, cx| {
 149                                Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
 150                            },
 151                        )
 152                        .with_handle(self.popover_menu_handle.clone()),
 153                )
 154            }
 155
 156            EditPredictionProvider::Supermaven => {
 157                let Some(supermaven) = Supermaven::global(cx) else {
 158                    return div();
 159                };
 160
 161                let supermaven = supermaven.read(cx);
 162
 163                let status = match supermaven {
 164                    Supermaven::Starting => SupermavenButtonStatus::Initializing,
 165                    Supermaven::FailedDownload { error } => {
 166                        SupermavenButtonStatus::Errored(error.to_string())
 167                    }
 168                    Supermaven::Spawned(agent) => {
 169                        let account_status = agent.account_status.clone();
 170                        match account_status {
 171                            AccountStatus::NeedsActivation { activate_url } => {
 172                                SupermavenButtonStatus::NeedsActivation(activate_url)
 173                            }
 174                            AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
 175                            AccountStatus::Ready => SupermavenButtonStatus::Ready,
 176                        }
 177                    }
 178                    Supermaven::Error { error } => {
 179                        SupermavenButtonStatus::Errored(error.to_string())
 180                    }
 181                };
 182
 183                let icon = status.to_icon();
 184                let tooltip_text = status.to_tooltip();
 185                let has_menu = status.has_menu();
 186                let this = cx.entity();
 187                let fs = self.fs.clone();
 188
 189                div().child(
 190                    PopoverMenu::new("supermaven")
 191                        .menu(move |window, cx| match &status {
 192                            SupermavenButtonStatus::NeedsActivation(activate_url) => {
 193                                Some(ContextMenu::build(window, cx, |menu, _, _| {
 194                                    let fs = fs.clone();
 195                                    let activate_url = activate_url.clone();
 196                                    menu.entry("Sign In", None, move |_, cx| {
 197                                        cx.open_url(activate_url.as_str())
 198                                    })
 199                                    .entry(
 200                                        "Use Zed AI",
 201                                        None,
 202                                        move |_, cx| {
 203                                            set_completion_provider(
 204                                                fs.clone(),
 205                                                cx,
 206                                                EditPredictionProvider::Zed,
 207                                            )
 208                                        },
 209                                    )
 210                                }))
 211                            }
 212                            SupermavenButtonStatus::Ready => Some(this.update(cx, |this, cx| {
 213                                this.build_supermaven_context_menu(window, cx)
 214                            })),
 215                            _ => None,
 216                        })
 217                        .anchor(Corner::BottomRight)
 218                        .trigger_with_tooltip(
 219                            IconButton::new("supermaven-icon", icon),
 220                            move |window, cx| {
 221                                if has_menu {
 222                                    Tooltip::for_action(
 223                                        tooltip_text.clone(),
 224                                        &ToggleMenu,
 225                                        window,
 226                                        cx,
 227                                    )
 228                                } else {
 229                                    Tooltip::text(tooltip_text.clone())(window, cx)
 230                                }
 231                            },
 232                        )
 233                        .with_handle(self.popover_menu_handle.clone()),
 234                )
 235            }
 236
 237            EditPredictionProvider::Zed => {
 238                let enabled = self.editor_enabled.unwrap_or(true);
 239
 240                let zeta_icon = if enabled {
 241                    IconName::ZedPredict
 242                } else {
 243                    IconName::ZedPredictDisabled
 244                };
 245
 246                if zeta::should_show_upsell_modal() {
 247                    let tooltip_meta = if self.user_store.read(cx).current_user().is_some() {
 248                        "Choose a Plan"
 249                    } else {
 250                        "Sign In"
 251                    };
 252
 253                    return div().child(
 254                        IconButton::new("zed-predict-pending-button", zeta_icon)
 255                            .shape(IconButtonShape::Square)
 256                            .indicator(Indicator::dot().color(Color::Muted))
 257                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
 258                            .tooltip(move |window, cx| {
 259                                Tooltip::with_meta(
 260                                    "Edit Predictions",
 261                                    None,
 262                                    tooltip_meta,
 263                                    window,
 264                                    cx,
 265                                )
 266                            })
 267                            .on_click(cx.listener(move |_, _, window, cx| {
 268                                telemetry::event!(
 269                                    "Pending ToS Clicked",
 270                                    source = "Edit Prediction Status Button"
 271                                );
 272                                window.dispatch_action(
 273                                    zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 274                                    cx,
 275                                );
 276                            })),
 277                    );
 278                }
 279
 280                let mut over_limit = false;
 281
 282                if let Some(usage) = self
 283                    .edit_prediction_provider
 284                    .as_ref()
 285                    .and_then(|provider| provider.usage(cx))
 286                {
 287                    over_limit = usage.over_limit()
 288                }
 289
 290                let show_editor_predictions = self.editor_show_predictions;
 291
 292                let icon_button = IconButton::new("zed-predict-pending-button", zeta_icon)
 293                    .shape(IconButtonShape::Square)
 294                    .when(
 295                        enabled && (!show_editor_predictions || over_limit),
 296                        |this| {
 297                            this.indicator(Indicator::dot().when_else(
 298                                over_limit,
 299                                |dot| dot.color(Color::Error),
 300                                |dot| dot.color(Color::Muted),
 301                            ))
 302                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
 303                        },
 304                    )
 305                    .when(!self.popover_menu_handle.is_deployed(), |element| {
 306                        element.tooltip(move |window, cx| {
 307                            if enabled {
 308                                if show_editor_predictions {
 309                                    Tooltip::for_action("Edit Prediction", &ToggleMenu, window, cx)
 310                                } else {
 311                                    Tooltip::with_meta(
 312                                        "Edit Prediction",
 313                                        Some(&ToggleMenu),
 314                                        "Hidden For This File",
 315                                        window,
 316                                        cx,
 317                                    )
 318                                }
 319                            } else {
 320                                Tooltip::with_meta(
 321                                    "Edit Prediction",
 322                                    Some(&ToggleMenu),
 323                                    "Disabled For This File",
 324                                    window,
 325                                    cx,
 326                                )
 327                            }
 328                        })
 329                    });
 330
 331                let this = cx.entity();
 332
 333                let mut popover_menu = PopoverMenu::new("zeta")
 334                    .menu(move |window, cx| {
 335                        Some(this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx)))
 336                    })
 337                    .anchor(Corner::BottomRight)
 338                    .with_handle(self.popover_menu_handle.clone());
 339
 340                let is_refreshing = self
 341                    .edit_prediction_provider
 342                    .as_ref()
 343                    .is_some_and(|provider| provider.is_refreshing(cx));
 344
 345                if is_refreshing {
 346                    popover_menu = popover_menu.trigger(
 347                        icon_button.with_animation(
 348                            "pulsating-label",
 349                            Animation::new(Duration::from_secs(2))
 350                                .repeat()
 351                                .with_easing(pulsating_between(0.2, 1.0)),
 352                            |icon_button, delta| icon_button.alpha(delta),
 353                        ),
 354                    );
 355                } else {
 356                    popover_menu = popover_menu.trigger(icon_button);
 357                }
 358
 359                div().child(popover_menu.into_any_element())
 360            }
 361        }
 362    }
 363}
 364
 365impl EditPredictionButton {
 366    pub fn new(
 367        fs: Arc<dyn Fs>,
 368        user_store: Entity<UserStore>,
 369        popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 370        cx: &mut Context<Self>,
 371    ) -> Self {
 372        if let Some(copilot) = Copilot::global(cx) {
 373            cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
 374        }
 375
 376        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
 377            .detach();
 378
 379        Self {
 380            editor_subscription: None,
 381            editor_enabled: None,
 382            editor_show_predictions: true,
 383            editor_focus_handle: None,
 384            language: None,
 385            file: None,
 386            edit_prediction_provider: None,
 387            user_store,
 388            popover_menu_handle,
 389            fs,
 390        }
 391    }
 392
 393    pub fn build_copilot_start_menu(
 394        &mut self,
 395        window: &mut Window,
 396        cx: &mut Context<Self>,
 397    ) -> Entity<ContextMenu> {
 398        let fs = self.fs.clone();
 399        ContextMenu::build(window, cx, |menu, _, _| {
 400            menu.entry("Sign In to Copilot", None, copilot::initiate_sign_in)
 401                .entry("Disable Copilot", None, {
 402                    let fs = fs.clone();
 403                    move |_window, cx| hide_copilot(fs.clone(), cx)
 404                })
 405                .separator()
 406                .entry("Use Zed AI", None, {
 407                    let fs = fs.clone();
 408                    move |_window, cx| {
 409                        set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
 410                    }
 411                })
 412        })
 413    }
 414
 415    pub fn build_language_settings_menu(
 416        &self,
 417        mut menu: ContextMenu,
 418        window: &Window,
 419        cx: &mut App,
 420    ) -> ContextMenu {
 421        let fs = self.fs.clone();
 422        let line_height = window.line_height();
 423
 424        menu = menu.header("Show Edit Predictions For");
 425
 426        let language_state = self.language.as_ref().map(|language| {
 427            (
 428                language.clone(),
 429                language_settings::language_settings(Some(language.name()), None, cx)
 430                    .show_edit_predictions,
 431            )
 432        });
 433
 434        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
 435            let entry = ContextMenuEntry::new("This Buffer")
 436                .toggleable(IconPosition::Start, self.editor_show_predictions)
 437                .action(Box::new(editor::actions::ToggleEditPrediction))
 438                .handler(move |window, cx| {
 439                    editor_focus_handle.dispatch_action(
 440                        &editor::actions::ToggleEditPrediction,
 441                        window,
 442                        cx,
 443                    );
 444                });
 445
 446            match language_state.clone() {
 447                Some((language, false)) => {
 448                    menu = menu.item(
 449                        entry
 450                            .disabled(true)
 451                            .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_cx| {
 452                                Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
 453                                    .into_any_element()
 454                            })
 455                    );
 456                }
 457                Some(_) | None => menu = menu.item(entry),
 458            }
 459        }
 460
 461        if let Some((language, language_enabled)) = language_state {
 462            let fs = fs.clone();
 463
 464            menu = menu.toggleable_entry(
 465                language.name(),
 466                language_enabled,
 467                IconPosition::Start,
 468                None,
 469                move |_, cx| {
 470                    toggle_show_edit_predictions_for_language(language.clone(), fs.clone(), cx)
 471                },
 472            );
 473        }
 474
 475        let settings = AllLanguageSettings::get_global(cx);
 476
 477        let globally_enabled = settings.show_edit_predictions(None, cx);
 478        let entry = ContextMenuEntry::new("All Files")
 479            .toggleable(IconPosition::Start, globally_enabled)
 480            .action(workspace::ToggleEditPrediction.boxed_clone())
 481            .handler(|window, cx| {
 482                window.dispatch_action(workspace::ToggleEditPrediction.boxed_clone(), cx)
 483            });
 484        menu = menu.item(entry);
 485
 486        let provider = settings.edit_predictions.provider;
 487        let current_mode = settings.edit_predictions_mode();
 488        let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
 489        let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
 490
 491        if matches!(
 492            provider,
 493            EditPredictionProvider::Zed
 494                | EditPredictionProvider::Copilot
 495                | EditPredictionProvider::Supermaven
 496        ) {
 497            menu = menu
 498                .separator()
 499                .header("Display Modes")
 500                .item(
 501                    ContextMenuEntry::new("Eager")
 502                        .toggleable(IconPosition::Start, eager_mode)
 503                        .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
 504                            Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
 505                        })
 506                        .handler({
 507                            let fs = fs.clone();
 508                            move |_, cx| {
 509                                toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
 510                            }
 511                        }),
 512                )
 513                .item(
 514                    ContextMenuEntry::new("Subtle")
 515                        .toggleable(IconPosition::Start, subtle_mode)
 516                        .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
 517                            Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
 518                        })
 519                        .handler({
 520                            let fs = fs.clone();
 521                            move |_, cx| {
 522                                toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
 523                            }
 524                        }),
 525                );
 526        }
 527
 528        menu = menu.separator().header("Privacy");
 529        if let Some(provider) = &self.edit_prediction_provider {
 530            let data_collection = provider.data_collection_state(cx);
 531            if data_collection.is_supported() {
 532                let provider = provider.clone();
 533                let enabled = data_collection.is_enabled();
 534                let is_open_source = data_collection.is_project_open_source();
 535                let is_collecting = data_collection.is_enabled();
 536                let (icon_name, icon_color) = if is_open_source && is_collecting {
 537                    (IconName::Check, Color::Success)
 538                } else {
 539                    (IconName::Check, Color::Accent)
 540                };
 541
 542                menu = menu.item(
 543                    ContextMenuEntry::new("Training Data Collection")
 544                        .toggleable(IconPosition::Start, data_collection.is_enabled())
 545                        .icon(icon_name)
 546                        .icon_color(icon_color)
 547                        .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |cx| {
 548                            let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
 549                                (true, true) => (
 550                                    "Project identified as open source, and you're sharing data.",
 551                                    Color::Default,
 552                                    IconName::Check,
 553                                    Color::Success,
 554                                ),
 555                                (true, false) => (
 556                                    "Project identified as open source, but you're not sharing data.",
 557                                    Color::Muted,
 558                                    IconName::Close,
 559                                    Color::Muted,
 560                                ),
 561                                (false, true) => (
 562                                    "Project not identified as open source. No data captured.",
 563                                    Color::Muted,
 564                                    IconName::Close,
 565                                    Color::Muted,
 566                                ),
 567                                (false, false) => (
 568                                    "Project not identified as open source, and setting turned off.",
 569                                    Color::Muted,
 570                                    IconName::Close,
 571                                    Color::Muted,
 572                                ),
 573                            };
 574                            v_flex()
 575                                .gap_2()
 576                                .child(
 577                                    Label::new(indoc!{
 578                                        "Help us improve our open dataset model by sharing data from open source repositories. \
 579                                        Zed must detect a license file in your repo for this setting to take effect. \
 580                                        Files with sensitive data and secrets are excluded by default."
 581                                    })
 582                                )
 583                                .child(
 584                                    h_flex()
 585                                        .items_start()
 586                                        .pt_2()
 587                                        .pr_1()
 588                                        .flex_1()
 589                                        .gap_1p5()
 590                                        .border_t_1()
 591                                        .border_color(cx.theme().colors().border_variant)
 592                                        .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
 593                                        .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
 594                                )
 595                                .into_any_element()
 596                        })
 597                        .handler(move |_, cx| {
 598                            provider.toggle_data_collection(cx);
 599
 600                            if !enabled {
 601                                telemetry::event!(
 602                                    "Data Collection Enabled",
 603                                    source = "Edit Prediction Status Menu"
 604                                );
 605                            } else {
 606                                telemetry::event!(
 607                                    "Data Collection Disabled",
 608                                    source = "Edit Prediction Status Menu"
 609                                );
 610                            }
 611                        })
 612                );
 613
 614                if is_collecting && !is_open_source {
 615                    menu = menu.item(
 616                        ContextMenuEntry::new("No data captured.")
 617                            .disabled(true)
 618                            .icon(IconName::Close)
 619                            .icon_color(Color::Error)
 620                            .icon_size(IconSize::Small),
 621                    );
 622                }
 623            }
 624        }
 625
 626        menu = menu.item(
 627            ContextMenuEntry::new("Configure Excluded Files")
 628                .icon(IconName::LockOutlined)
 629                .icon_color(Color::Muted)
 630                .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, |_| {
 631                    Label::new(indoc!{"
 632                        Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
 633                })
 634                .handler(move |window, cx| {
 635                    if let Some(workspace) = window.root().flatten() {
 636                        let workspace = workspace.downgrade();
 637                        window
 638                            .spawn(cx, async |cx| {
 639                                open_disabled_globs_setting_in_editor(
 640                                    workspace,
 641                                    cx,
 642                                ).await
 643                            })
 644                            .detach_and_log_err(cx);
 645                    }
 646                }),
 647        ).item(
 648            ContextMenuEntry::new("View Documentation")
 649                .icon(IconName::FileGeneric)
 650                .icon_color(Color::Muted)
 651                .handler(move |_, cx| {
 652                    cx.open_url(PRIVACY_DOCS);
 653                })
 654        );
 655
 656        if !self.editor_enabled.unwrap_or(true) {
 657            menu = menu.item(
 658                ContextMenuEntry::new("This file is excluded.")
 659                    .disabled(true)
 660                    .icon(IconName::ZedPredictDisabled)
 661                    .icon_size(IconSize::Small),
 662            );
 663        }
 664
 665        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
 666            menu = menu
 667                .separator()
 668                .entry(
 669                    "Predict Edit at Cursor",
 670                    Some(Box::new(ShowEditPrediction)),
 671                    {
 672                        let editor_focus_handle = editor_focus_handle.clone();
 673                        move |window, cx| {
 674                            editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
 675                        }
 676                    },
 677                )
 678                .context(editor_focus_handle);
 679        }
 680
 681        menu
 682    }
 683
 684    fn build_copilot_context_menu(
 685        &self,
 686        window: &mut Window,
 687        cx: &mut Context<Self>,
 688    ) -> Entity<ContextMenu> {
 689        ContextMenu::build(window, cx, |menu, window, cx| {
 690            self.build_language_settings_menu(menu, window, cx)
 691                .separator()
 692                .entry("Use Zed AI instead", None, {
 693                    let fs = self.fs.clone();
 694                    move |_window, cx| {
 695                        set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
 696                    }
 697                })
 698                .separator()
 699                .link(
 700                    "Go to Copilot Settings",
 701                    OpenBrowser {
 702                        url: COPILOT_SETTINGS_URL.to_string(),
 703                    }
 704                    .boxed_clone(),
 705                )
 706                .action("Sign Out", copilot::SignOut.boxed_clone())
 707        })
 708    }
 709
 710    fn build_supermaven_context_menu(
 711        &self,
 712        window: &mut Window,
 713        cx: &mut Context<Self>,
 714    ) -> Entity<ContextMenu> {
 715        ContextMenu::build(window, cx, |menu, window, cx| {
 716            self.build_language_settings_menu(menu, window, cx)
 717                .separator()
 718                .action("Sign Out", supermaven::SignOut.boxed_clone())
 719        })
 720    }
 721
 722    fn build_zeta_context_menu(
 723        &self,
 724        window: &mut Window,
 725        cx: &mut Context<Self>,
 726    ) -> Entity<ContextMenu> {
 727        ContextMenu::build(window, cx, |mut menu, window, cx| {
 728            if let Some(usage) = self
 729                .edit_prediction_provider
 730                .as_ref()
 731                .and_then(|provider| provider.usage(cx))
 732            {
 733                menu = menu.header("Usage");
 734                menu = menu
 735                    .custom_entry(
 736                        move |_window, cx| {
 737                            let used_percentage = match usage.limit {
 738                                UsageLimit::Limited(limit) => {
 739                                    Some((usage.amount as f32 / limit as f32) * 100.)
 740                                }
 741                                UsageLimit::Unlimited => None,
 742                            };
 743
 744                            h_flex()
 745                                .flex_1()
 746                                .gap_1p5()
 747                                .children(
 748                                    used_percentage.map(|percent| {
 749                                        ProgressBar::new("usage", percent, 100., cx)
 750                                    }),
 751                                )
 752                                .child(
 753                                    Label::new(match usage.limit {
 754                                        UsageLimit::Limited(limit) => {
 755                                            format!("{} / {limit}", usage.amount)
 756                                        }
 757                                        UsageLimit::Unlimited => format!("{} / ∞", usage.amount),
 758                                    })
 759                                    .size(LabelSize::Small)
 760                                    .color(Color::Muted),
 761                                )
 762                                .into_any_element()
 763                        },
 764                        move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
 765                    )
 766                    .when(usage.over_limit(), |menu| -> ContextMenu {
 767                        menu.entry("Subscribe to increase your limit", None, |_window, cx| {
 768                            cx.open_url(&zed_urls::account_url(cx))
 769                        })
 770                    })
 771                    .separator();
 772            } else if self.user_store.read(cx).account_too_young() {
 773                menu = menu
 774                    .custom_entry(
 775                        |_window, _cx| {
 776                            Label::new("Your GitHub account is less than 30 days old.")
 777                                .size(LabelSize::Small)
 778                                .color(Color::Warning)
 779                                .into_any_element()
 780                        },
 781                        |_window, cx| cx.open_url(&zed_urls::account_url(cx)),
 782                    )
 783                    .entry("Upgrade to Zed Pro or contact us.", None, |_window, cx| {
 784                        cx.open_url(&zed_urls::account_url(cx))
 785                    })
 786                    .separator();
 787            } else if self.user_store.read(cx).has_overdue_invoices() {
 788                menu = menu
 789                    .custom_entry(
 790                        |_window, _cx| {
 791                            Label::new("You have an outstanding invoice")
 792                                .size(LabelSize::Small)
 793                                .color(Color::Warning)
 794                                .into_any_element()
 795                        },
 796                        |_window, cx| {
 797                            cx.open_url(&zed_urls::account_url(cx))
 798                        },
 799                    )
 800                    .entry(
 801                        "Check your payment status or contact us at billing-support@zed.dev to continue using this feature.",
 802                        None,
 803                        |_window, cx| {
 804                            cx.open_url(&zed_urls::account_url(cx))
 805                        },
 806                    )
 807                    .separator();
 808            }
 809
 810            self.build_language_settings_menu(menu, window, cx).when(
 811                cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
 812                |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
 813            )
 814        })
 815    }
 816
 817    pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
 818        let editor = editor.read(cx);
 819        let snapshot = editor.buffer().read(cx).snapshot(cx);
 820        let suggestion_anchor = editor.selections.newest_anchor().start;
 821        let language = snapshot.language_at(suggestion_anchor);
 822        let file = snapshot.file_at(suggestion_anchor).cloned();
 823        self.editor_enabled = {
 824            let file = file.as_ref();
 825            Some(
 826                file.map(|file| {
 827                    all_language_settings(Some(file), cx)
 828                        .edit_predictions_enabled_for_file(file, cx)
 829                })
 830                .unwrap_or(true),
 831            )
 832        };
 833        self.editor_show_predictions = editor.edit_predictions_enabled();
 834        self.edit_prediction_provider = editor.edit_prediction_provider();
 835        self.language = language.cloned();
 836        self.file = file;
 837        self.editor_focus_handle = Some(editor.focus_handle(cx));
 838
 839        cx.notify();
 840    }
 841}
 842
 843impl StatusItemView for EditPredictionButton {
 844    fn set_active_pane_item(
 845        &mut self,
 846        item: Option<&dyn ItemHandle>,
 847        _: &mut Window,
 848        cx: &mut Context<Self>,
 849    ) {
 850        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
 851            self.editor_subscription = Some((
 852                cx.observe(&editor, Self::update_enabled),
 853                editor.entity_id().as_u64() as usize,
 854            ));
 855            self.update_enabled(editor, cx);
 856        } else {
 857            self.language = None;
 858            self.editor_subscription = None;
 859            self.editor_enabled = None;
 860        }
 861        cx.notify();
 862    }
 863}
 864
 865impl SupermavenButtonStatus {
 866    fn to_icon(&self) -> IconName {
 867        match self {
 868            SupermavenButtonStatus::Ready => IconName::Supermaven,
 869            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
 870            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
 871            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
 872        }
 873    }
 874
 875    fn to_tooltip(&self) -> String {
 876        match self {
 877            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
 878            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
 879            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
 880            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
 881        }
 882    }
 883
 884    fn has_menu(&self) -> bool {
 885        match self {
 886            SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
 887            SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
 888        }
 889    }
 890}
 891
 892async fn open_disabled_globs_setting_in_editor(
 893    workspace: WeakEntity<Workspace>,
 894    cx: &mut AsyncWindowContext,
 895) -> Result<()> {
 896    let settings_editor = workspace
 897        .update_in(cx, |_, window, cx| {
 898            create_and_open_local_file(paths::settings_file(), window, cx, || {
 899                settings::initial_user_settings_content().as_ref().into()
 900            })
 901        })?
 902        .await?
 903        .downcast::<Editor>()
 904        .unwrap();
 905
 906    settings_editor
 907        .downgrade()
 908        .update_in(cx, |item, window, cx| {
 909            let text = item.buffer().read(cx).snapshot(cx).text();
 910
 911            let settings = cx.global::<SettingsStore>();
 912
 913            // Ensure that we always have "edit_predictions { "disabled_globs": [] }"
 914            let edits = settings.edits_for_update(&text, |file| {
 915                file.project
 916                    .all_languages
 917                    .edit_predictions
 918                    .get_or_insert_with(Default::default)
 919                    .disabled_globs
 920                    .get_or_insert_with(Vec::new);
 921            });
 922
 923            if !edits.is_empty() {
 924                item.edit(edits, cx);
 925            }
 926
 927            let text = item.buffer().read(cx).snapshot(cx).text();
 928
 929            static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
 930                Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
 931            });
 932            // Only capture [...]
 933            let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
 934                captures
 935                    .name("content")
 936                    .map(|inner_match| inner_match.start()..inner_match.end())
 937            });
 938            if let Some(range) = range {
 939                item.change_selections(
 940                    SelectionEffects::scroll(Autoscroll::newest()),
 941                    window,
 942                    cx,
 943                    |selections| {
 944                        selections.select_ranges(vec![range]);
 945                    },
 946                );
 947            }
 948        })?;
 949
 950    anyhow::Ok(())
 951}
 952
 953fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
 954    update_settings_file(fs, cx, move |settings, _| {
 955        settings
 956            .project
 957            .all_languages
 958            .features
 959            .get_or_insert_default()
 960            .edit_prediction_provider = Some(provider);
 961    });
 962}
 963
 964fn toggle_show_edit_predictions_for_language(
 965    language: Arc<Language>,
 966    fs: Arc<dyn Fs>,
 967    cx: &mut App,
 968) {
 969    let show_edit_predictions =
 970        all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
 971    update_settings_file(fs, cx, move |settings, _| {
 972        settings
 973            .project
 974            .all_languages
 975            .languages
 976            .0
 977            .entry(language.name().0)
 978            .or_default()
 979            .show_edit_predictions = Some(!show_edit_predictions);
 980    });
 981}
 982
 983fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
 984    update_settings_file(fs, cx, move |settings, _| {
 985        settings
 986            .project
 987            .all_languages
 988            .features
 989            .get_or_insert(Default::default())
 990            .edit_prediction_provider = Some(EditPredictionProvider::None);
 991    });
 992}
 993
 994fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
 995    let settings = AllLanguageSettings::get_global(cx);
 996    let current_mode = settings.edit_predictions_mode();
 997
 998    if current_mode != mode {
 999        update_settings_file(fs, cx, move |settings, _cx| {
1000            if let Some(edit_predictions) = settings.project.all_languages.edit_predictions.as_mut()
1001            {
1002                edit_predictions.mode = Some(mode);
1003            } else {
1004                settings.project.all_languages.edit_predictions =
1005                    Some(settings::EditPredictionSettingsContent {
1006                        mode: Some(mode),
1007                        ..Default::default()
1008                    });
1009            }
1010        });
1011    }
1012}