edit_prediction_button.rs

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