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    IconButtonShape, 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().hidden();
  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().hidden(),
  82
  83            EditPredictionProvider::Copilot => {
  84                let Some(copilot) = Copilot::global(cx) else {
  85                    return div().hidden();
  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                            .shape(IconButtonShape::Square)
 318                            .indicator(Indicator::dot().color(Color::Muted))
 319                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
 320                            .tooltip(move |window, cx| {
 321                                Tooltip::with_meta(
 322                                    "Edit Predictions",
 323                                    None,
 324                                    tooltip_meta,
 325                                    window,
 326                                    cx,
 327                                )
 328                            })
 329                            .on_click(cx.listener(move |_, _, window, cx| {
 330                                telemetry::event!(
 331                                    "Pending ToS Clicked",
 332                                    source = "Edit Prediction Status Button"
 333                                );
 334                                window.dispatch_action(
 335                                    zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 336                                    cx,
 337                                );
 338                            })),
 339                    );
 340                }
 341
 342                let mut over_limit = false;
 343
 344                if let Some(usage) = self
 345                    .edit_prediction_provider
 346                    .as_ref()
 347                    .and_then(|provider| provider.usage(cx))
 348                {
 349                    over_limit = usage.over_limit()
 350                }
 351
 352                let show_editor_predictions = self.editor_show_predictions;
 353
 354                let icon_button = IconButton::new("zed-predict-pending-button", zeta_icon)
 355                    .shape(IconButtonShape::Square)
 356                    .when(
 357                        enabled && (!show_editor_predictions || over_limit),
 358                        |this| {
 359                            this.indicator(Indicator::dot().when_else(
 360                                over_limit,
 361                                |dot| dot.color(Color::Error),
 362                                |dot| dot.color(Color::Muted),
 363                            ))
 364                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
 365                        },
 366                    )
 367                    .when(!self.popover_menu_handle.is_deployed(), |element| {
 368                        element.tooltip(move |window, cx| {
 369                            if enabled {
 370                                if show_editor_predictions {
 371                                    Tooltip::for_action("Edit Prediction", &ToggleMenu, window, cx)
 372                                } else {
 373                                    Tooltip::with_meta(
 374                                        "Edit Prediction",
 375                                        Some(&ToggleMenu),
 376                                        "Hidden For This File",
 377                                        window,
 378                                        cx,
 379                                    )
 380                                }
 381                            } else {
 382                                Tooltip::with_meta(
 383                                    "Edit Prediction",
 384                                    Some(&ToggleMenu),
 385                                    "Disabled For This File",
 386                                    window,
 387                                    cx,
 388                                )
 389                            }
 390                        })
 391                    });
 392
 393                let this = cx.entity();
 394
 395                let mut popover_menu = PopoverMenu::new("zeta")
 396                    .menu(move |window, cx| {
 397                        Some(this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx)))
 398                    })
 399                    .anchor(Corner::BottomRight)
 400                    .with_handle(self.popover_menu_handle.clone());
 401
 402                let is_refreshing = self
 403                    .edit_prediction_provider
 404                    .as_ref()
 405                    .is_some_and(|provider| provider.is_refreshing(cx));
 406
 407                if is_refreshing {
 408                    popover_menu = popover_menu.trigger(
 409                        icon_button.with_animation(
 410                            "pulsating-label",
 411                            Animation::new(Duration::from_secs(2))
 412                                .repeat()
 413                                .with_easing(pulsating_between(0.2, 1.0)),
 414                            |icon_button, delta| icon_button.alpha(delta),
 415                        ),
 416                    );
 417                } else {
 418                    popover_menu = popover_menu.trigger(icon_button);
 419                }
 420
 421                div().child(popover_menu.into_any_element())
 422            }
 423        }
 424    }
 425}
 426
 427impl EditPredictionButton {
 428    pub fn new(
 429        fs: Arc<dyn Fs>,
 430        user_store: Entity<UserStore>,
 431        popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 432        cx: &mut Context<Self>,
 433    ) -> Self {
 434        if let Some(copilot) = Copilot::global(cx) {
 435            cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
 436        }
 437
 438        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
 439            .detach();
 440
 441        Self {
 442            editor_subscription: None,
 443            editor_enabled: None,
 444            editor_show_predictions: true,
 445            editor_focus_handle: None,
 446            language: None,
 447            file: None,
 448            edit_prediction_provider: None,
 449            user_store,
 450            popover_menu_handle,
 451            fs,
 452        }
 453    }
 454
 455    pub fn build_copilot_start_menu(
 456        &mut self,
 457        window: &mut Window,
 458        cx: &mut Context<Self>,
 459    ) -> Entity<ContextMenu> {
 460        let fs = self.fs.clone();
 461        ContextMenu::build(window, cx, |menu, _, _| {
 462            menu.entry("Sign In to Copilot", None, copilot::initiate_sign_in)
 463                .entry("Disable Copilot", None, {
 464                    let fs = fs.clone();
 465                    move |_window, cx| hide_copilot(fs.clone(), cx)
 466                })
 467                .separator()
 468                .entry("Use Zed AI", None, {
 469                    let fs = fs.clone();
 470                    move |_window, cx| {
 471                        set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
 472                    }
 473                })
 474        })
 475    }
 476
 477    pub fn build_language_settings_menu(
 478        &self,
 479        mut menu: ContextMenu,
 480        window: &Window,
 481        cx: &mut App,
 482    ) -> ContextMenu {
 483        let fs = self.fs.clone();
 484        let line_height = window.line_height();
 485
 486        menu = menu.header("Show Edit Predictions For");
 487
 488        let language_state = self.language.as_ref().map(|language| {
 489            (
 490                language.clone(),
 491                language_settings::language_settings(Some(language.name()), None, cx)
 492                    .show_edit_predictions,
 493            )
 494        });
 495
 496        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
 497            let entry = ContextMenuEntry::new("This Buffer")
 498                .toggleable(IconPosition::Start, self.editor_show_predictions)
 499                .action(Box::new(editor::actions::ToggleEditPrediction))
 500                .handler(move |window, cx| {
 501                    editor_focus_handle.dispatch_action(
 502                        &editor::actions::ToggleEditPrediction,
 503                        window,
 504                        cx,
 505                    );
 506                });
 507
 508            match language_state.clone() {
 509                Some((language, false)) => {
 510                    menu = menu.item(
 511                        entry
 512                            .disabled(true)
 513                            .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_cx| {
 514                                Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
 515                                    .into_any_element()
 516                            })
 517                    );
 518                }
 519                Some(_) | None => menu = menu.item(entry),
 520            }
 521        }
 522
 523        if let Some((language, language_enabled)) = language_state {
 524            let fs = fs.clone();
 525
 526            menu = menu.toggleable_entry(
 527                language.name(),
 528                language_enabled,
 529                IconPosition::Start,
 530                None,
 531                move |_, cx| {
 532                    toggle_show_edit_predictions_for_language(language.clone(), fs.clone(), cx)
 533                },
 534            );
 535        }
 536
 537        let settings = AllLanguageSettings::get_global(cx);
 538
 539        let globally_enabled = settings.show_edit_predictions(None, cx);
 540        let entry = ContextMenuEntry::new("All Files")
 541            .toggleable(IconPosition::Start, globally_enabled)
 542            .action(workspace::ToggleEditPrediction.boxed_clone())
 543            .handler(|window, cx| {
 544                window.dispatch_action(workspace::ToggleEditPrediction.boxed_clone(), cx)
 545            });
 546        menu = menu.item(entry);
 547
 548        let provider = settings.edit_predictions.provider;
 549        let current_mode = settings.edit_predictions_mode();
 550        let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
 551        let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
 552
 553        if matches!(
 554            provider,
 555            EditPredictionProvider::Zed
 556                | EditPredictionProvider::Copilot
 557                | EditPredictionProvider::Supermaven
 558                | EditPredictionProvider::Codestral
 559        ) {
 560            menu = menu
 561                .separator()
 562                .header("Display Modes")
 563                .item(
 564                    ContextMenuEntry::new("Eager")
 565                        .toggleable(IconPosition::Start, eager_mode)
 566                        .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
 567                            Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
 568                        })
 569                        .handler({
 570                            let fs = fs.clone();
 571                            move |_, cx| {
 572                                toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
 573                            }
 574                        }),
 575                )
 576                .item(
 577                    ContextMenuEntry::new("Subtle")
 578                        .toggleable(IconPosition::Start, subtle_mode)
 579                        .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |_| {
 580                            Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
 581                        })
 582                        .handler({
 583                            let fs = fs.clone();
 584                            move |_, cx| {
 585                                toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
 586                            }
 587                        }),
 588                );
 589        }
 590
 591        menu = menu.separator().header("Privacy");
 592        if let Some(provider) = &self.edit_prediction_provider {
 593            let data_collection = provider.data_collection_state(cx);
 594            if data_collection.is_supported() {
 595                let provider = provider.clone();
 596                let enabled = data_collection.is_enabled();
 597                let is_open_source = data_collection.is_project_open_source();
 598                let is_collecting = data_collection.is_enabled();
 599                let (icon_name, icon_color) = if is_open_source && is_collecting {
 600                    (IconName::Check, Color::Success)
 601                } else {
 602                    (IconName::Check, Color::Accent)
 603                };
 604
 605                menu = menu.item(
 606                    ContextMenuEntry::new("Training Data Collection")
 607                        .toggleable(IconPosition::Start, data_collection.is_enabled())
 608                        .icon(icon_name)
 609                        .icon_color(icon_color)
 610                        .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |cx| {
 611                            let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
 612                                (true, true) => (
 613                                    "Project identified as open source, and you're sharing data.",
 614                                    Color::Default,
 615                                    IconName::Check,
 616                                    Color::Success,
 617                                ),
 618                                (true, false) => (
 619                                    "Project identified as open source, but you're not sharing data.",
 620                                    Color::Muted,
 621                                    IconName::Close,
 622                                    Color::Muted,
 623                                ),
 624                                (false, true) => (
 625                                    "Project not identified as open source. No data captured.",
 626                                    Color::Muted,
 627                                    IconName::Close,
 628                                    Color::Muted,
 629                                ),
 630                                (false, false) => (
 631                                    "Project not identified as open source, and setting turned off.",
 632                                    Color::Muted,
 633                                    IconName::Close,
 634                                    Color::Muted,
 635                                ),
 636                            };
 637                            v_flex()
 638                                .gap_2()
 639                                .child(
 640                                    Label::new(indoc!{
 641                                        "Help us improve our open dataset model by sharing data from open source repositories. \
 642                                        Zed must detect a license file in your repo for this setting to take effect. \
 643                                        Files with sensitive data and secrets are excluded by default."
 644                                    })
 645                                )
 646                                .child(
 647                                    h_flex()
 648                                        .items_start()
 649                                        .pt_2()
 650                                        .pr_1()
 651                                        .flex_1()
 652                                        .gap_1p5()
 653                                        .border_t_1()
 654                                        .border_color(cx.theme().colors().border_variant)
 655                                        .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
 656                                        .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
 657                                )
 658                                .into_any_element()
 659                        })
 660                        .handler(move |_, cx| {
 661                            provider.toggle_data_collection(cx);
 662
 663                            if !enabled {
 664                                telemetry::event!(
 665                                    "Data Collection Enabled",
 666                                    source = "Edit Prediction Status Menu"
 667                                );
 668                            } else {
 669                                telemetry::event!(
 670                                    "Data Collection Disabled",
 671                                    source = "Edit Prediction Status Menu"
 672                                );
 673                            }
 674                        })
 675                );
 676
 677                if is_collecting && !is_open_source {
 678                    menu = menu.item(
 679                        ContextMenuEntry::new("No data captured.")
 680                            .disabled(true)
 681                            .icon(IconName::Close)
 682                            .icon_color(Color::Error)
 683                            .icon_size(IconSize::Small),
 684                    );
 685                }
 686            }
 687        }
 688
 689        menu = menu.item(
 690            ContextMenuEntry::new("Configure Excluded Files")
 691                .icon(IconName::LockOutlined)
 692                .icon_color(Color::Muted)
 693                .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, |_| {
 694                    Label::new(indoc!{"
 695                        Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
 696                })
 697                .handler(move |window, cx| {
 698                    if let Some(workspace) = window.root().flatten() {
 699                        let workspace = workspace.downgrade();
 700                        window
 701                            .spawn(cx, async |cx| {
 702                                open_disabled_globs_setting_in_editor(
 703                                    workspace,
 704                                    cx,
 705                                ).await
 706                            })
 707                            .detach_and_log_err(cx);
 708                    }
 709                }),
 710        ).item(
 711            ContextMenuEntry::new("View Documentation")
 712                .icon(IconName::FileGeneric)
 713                .icon_color(Color::Muted)
 714                .handler(move |_, cx| {
 715                    cx.open_url(PRIVACY_DOCS);
 716                })
 717        );
 718
 719        if !self.editor_enabled.unwrap_or(true) {
 720            menu = menu.item(
 721                ContextMenuEntry::new("This file is excluded.")
 722                    .disabled(true)
 723                    .icon(IconName::ZedPredictDisabled)
 724                    .icon_size(IconSize::Small),
 725            );
 726        }
 727
 728        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
 729            menu = menu
 730                .separator()
 731                .entry(
 732                    "Predict Edit at Cursor",
 733                    Some(Box::new(ShowEditPrediction)),
 734                    {
 735                        let editor_focus_handle = editor_focus_handle.clone();
 736                        move |window, cx| {
 737                            editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
 738                        }
 739                    },
 740                )
 741                .context(editor_focus_handle);
 742        }
 743
 744        menu
 745    }
 746
 747    fn build_copilot_context_menu(
 748        &self,
 749        window: &mut Window,
 750        cx: &mut Context<Self>,
 751    ) -> Entity<ContextMenu> {
 752        ContextMenu::build(window, cx, |menu, window, cx| {
 753            self.build_language_settings_menu(menu, window, cx)
 754                .separator()
 755                .entry("Use Zed AI instead", None, {
 756                    let fs = self.fs.clone();
 757                    move |_window, cx| {
 758                        set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
 759                    }
 760                })
 761                .separator()
 762                .link(
 763                    "Go to Copilot Settings",
 764                    OpenBrowser {
 765                        url: COPILOT_SETTINGS_URL.to_string(),
 766                    }
 767                    .boxed_clone(),
 768                )
 769                .action("Sign Out", copilot::SignOut.boxed_clone())
 770        })
 771    }
 772
 773    fn build_supermaven_context_menu(
 774        &self,
 775        window: &mut Window,
 776        cx: &mut Context<Self>,
 777    ) -> Entity<ContextMenu> {
 778        ContextMenu::build(window, cx, |menu, window, cx| {
 779            self.build_language_settings_menu(menu, window, cx)
 780                .separator()
 781                .action("Sign Out", supermaven::SignOut.boxed_clone())
 782        })
 783    }
 784
 785    fn build_codestral_context_menu(
 786        &self,
 787        window: &mut Window,
 788        cx: &mut Context<Self>,
 789    ) -> Entity<ContextMenu> {
 790        let fs = self.fs.clone();
 791        ContextMenu::build(window, cx, |menu, window, cx| {
 792            self.build_language_settings_menu(menu, window, cx)
 793                .separator()
 794                .entry("Use Zed AI instead", None, move |_, cx| {
 795                    set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
 796                })
 797                .separator()
 798                .entry("Configure Codestral API Key", None, move |window, cx| {
 799                    window.dispatch_action(zed_actions::agent::OpenSettings.boxed_clone(), cx);
 800                })
 801        })
 802    }
 803
 804    fn build_zeta_context_menu(
 805        &self,
 806        window: &mut Window,
 807        cx: &mut Context<Self>,
 808    ) -> Entity<ContextMenu> {
 809        ContextMenu::build(window, cx, |mut menu, window, cx| {
 810            if let Some(usage) = self
 811                .edit_prediction_provider
 812                .as_ref()
 813                .and_then(|provider| provider.usage(cx))
 814            {
 815                menu = menu.header("Usage");
 816                menu = menu
 817                    .custom_entry(
 818                        move |_window, cx| {
 819                            let used_percentage = match usage.limit {
 820                                UsageLimit::Limited(limit) => {
 821                                    Some((usage.amount as f32 / limit as f32) * 100.)
 822                                }
 823                                UsageLimit::Unlimited => None,
 824                            };
 825
 826                            h_flex()
 827                                .flex_1()
 828                                .gap_1p5()
 829                                .children(
 830                                    used_percentage.map(|percent| {
 831                                        ProgressBar::new("usage", percent, 100., cx)
 832                                    }),
 833                                )
 834                                .child(
 835                                    Label::new(match usage.limit {
 836                                        UsageLimit::Limited(limit) => {
 837                                            format!("{} / {limit}", usage.amount)
 838                                        }
 839                                        UsageLimit::Unlimited => format!("{} / ∞", usage.amount),
 840                                    })
 841                                    .size(LabelSize::Small)
 842                                    .color(Color::Muted),
 843                                )
 844                                .into_any_element()
 845                        },
 846                        move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
 847                    )
 848                    .when(usage.over_limit(), |menu| -> ContextMenu {
 849                        menu.entry("Subscribe to increase your limit", None, |_window, cx| {
 850                            cx.open_url(&zed_urls::account_url(cx))
 851                        })
 852                    })
 853                    .separator();
 854            } else if self.user_store.read(cx).account_too_young() {
 855                menu = menu
 856                    .custom_entry(
 857                        |_window, _cx| {
 858                            Label::new("Your GitHub account is less than 30 days old.")
 859                                .size(LabelSize::Small)
 860                                .color(Color::Warning)
 861                                .into_any_element()
 862                        },
 863                        |_window, cx| cx.open_url(&zed_urls::account_url(cx)),
 864                    )
 865                    .entry("Upgrade to Zed Pro or contact us.", None, |_window, cx| {
 866                        cx.open_url(&zed_urls::account_url(cx))
 867                    })
 868                    .separator();
 869            } else if self.user_store.read(cx).has_overdue_invoices() {
 870                menu = menu
 871                    .custom_entry(
 872                        |_window, _cx| {
 873                            Label::new("You have an outstanding invoice")
 874                                .size(LabelSize::Small)
 875                                .color(Color::Warning)
 876                                .into_any_element()
 877                        },
 878                        |_window, cx| {
 879                            cx.open_url(&zed_urls::account_url(cx))
 880                        },
 881                    )
 882                    .entry(
 883                        "Check your payment status or contact us at billing-support@zed.dev to continue using this feature.",
 884                        None,
 885                        |_window, cx| {
 886                            cx.open_url(&zed_urls::account_url(cx))
 887                        },
 888                    )
 889                    .separator();
 890            }
 891
 892            self.build_language_settings_menu(menu, window, cx).when(
 893                cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
 894                |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
 895            )
 896        })
 897    }
 898
 899    pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
 900        let editor = editor.read(cx);
 901        let snapshot = editor.buffer().read(cx).snapshot(cx);
 902        let suggestion_anchor = editor.selections.newest_anchor().start;
 903        let language = snapshot.language_at(suggestion_anchor);
 904        let file = snapshot.file_at(suggestion_anchor).cloned();
 905        self.editor_enabled = {
 906            let file = file.as_ref();
 907            Some(
 908                file.map(|file| {
 909                    all_language_settings(Some(file), cx)
 910                        .edit_predictions_enabled_for_file(file, cx)
 911                })
 912                .unwrap_or(true),
 913            )
 914        };
 915        self.editor_show_predictions = editor.edit_predictions_enabled();
 916        self.edit_prediction_provider = editor.edit_prediction_provider();
 917        self.language = language.cloned();
 918        self.file = file;
 919        self.editor_focus_handle = Some(editor.focus_handle(cx));
 920
 921        cx.notify();
 922    }
 923}
 924
 925impl StatusItemView for EditPredictionButton {
 926    fn set_active_pane_item(
 927        &mut self,
 928        item: Option<&dyn ItemHandle>,
 929        _: &mut Window,
 930        cx: &mut Context<Self>,
 931    ) {
 932        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
 933            self.editor_subscription = Some((
 934                cx.observe(&editor, Self::update_enabled),
 935                editor.entity_id().as_u64() as usize,
 936            ));
 937            self.update_enabled(editor, cx);
 938        } else {
 939            self.language = None;
 940            self.editor_subscription = None;
 941            self.editor_enabled = None;
 942        }
 943        cx.notify();
 944    }
 945}
 946
 947impl SupermavenButtonStatus {
 948    fn to_icon(&self) -> IconName {
 949        match self {
 950            SupermavenButtonStatus::Ready => IconName::Supermaven,
 951            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
 952            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
 953            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
 954        }
 955    }
 956
 957    fn to_tooltip(&self) -> String {
 958        match self {
 959            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
 960            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
 961            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
 962            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
 963        }
 964    }
 965
 966    fn has_menu(&self) -> bool {
 967        match self {
 968            SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
 969            SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
 970        }
 971    }
 972}
 973
 974async fn open_disabled_globs_setting_in_editor(
 975    workspace: WeakEntity<Workspace>,
 976    cx: &mut AsyncWindowContext,
 977) -> Result<()> {
 978    let settings_editor = workspace
 979        .update_in(cx, |_, window, cx| {
 980            create_and_open_local_file(paths::settings_file(), window, cx, || {
 981                settings::initial_user_settings_content().as_ref().into()
 982            })
 983        })?
 984        .await?
 985        .downcast::<Editor>()
 986        .unwrap();
 987
 988    settings_editor
 989        .downgrade()
 990        .update_in(cx, |item, window, cx| {
 991            let text = item.buffer().read(cx).snapshot(cx).text();
 992
 993            let settings = cx.global::<SettingsStore>();
 994
 995            // Ensure that we always have "edit_predictions { "disabled_globs": [] }"
 996            let edits = settings.edits_for_update(&text, |file| {
 997                file.project
 998                    .all_languages
 999                    .edit_predictions
1000                    .get_or_insert_with(Default::default)
1001                    .disabled_globs
1002                    .get_or_insert_with(Vec::new);
1003            });
1004
1005            if !edits.is_empty() {
1006                item.edit(edits, cx);
1007            }
1008
1009            let text = item.buffer().read(cx).snapshot(cx).text();
1010
1011            static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
1012                Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
1013            });
1014            // Only capture [...]
1015            let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
1016                captures
1017                    .name("content")
1018                    .map(|inner_match| inner_match.start()..inner_match.end())
1019            });
1020            if let Some(range) = range {
1021                item.change_selections(
1022                    SelectionEffects::scroll(Autoscroll::newest()),
1023                    window,
1024                    cx,
1025                    |selections| {
1026                        selections.select_ranges(vec![range]);
1027                    },
1028                );
1029            }
1030        })?;
1031
1032    anyhow::Ok(())
1033}
1034
1035fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
1036    update_settings_file(fs, cx, move |settings, _| {
1037        settings
1038            .project
1039            .all_languages
1040            .features
1041            .get_or_insert_default()
1042            .edit_prediction_provider = Some(provider);
1043    });
1044}
1045
1046fn toggle_show_edit_predictions_for_language(
1047    language: Arc<Language>,
1048    fs: Arc<dyn Fs>,
1049    cx: &mut App,
1050) {
1051    let show_edit_predictions =
1052        all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
1053    update_settings_file(fs, cx, move |settings, _| {
1054        settings
1055            .project
1056            .all_languages
1057            .languages
1058            .0
1059            .entry(language.name().0)
1060            .or_default()
1061            .show_edit_predictions = Some(!show_edit_predictions);
1062    });
1063}
1064
1065fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
1066    update_settings_file(fs, cx, move |settings, _| {
1067        settings
1068            .project
1069            .all_languages
1070            .features
1071            .get_or_insert(Default::default())
1072            .edit_prediction_provider = Some(EditPredictionProvider::None);
1073    });
1074}
1075
1076fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
1077    let settings = AllLanguageSettings::get_global(cx);
1078    let current_mode = settings.edit_predictions_mode();
1079
1080    if current_mode != mode {
1081        update_settings_file(fs, cx, move |settings, _cx| {
1082            if let Some(edit_predictions) = settings.project.all_languages.edit_predictions.as_mut()
1083            {
1084                edit_predictions.mode = Some(mode);
1085            } else {
1086                settings.project.all_languages.edit_predictions =
1087                    Some(settings::EditPredictionSettingsContent {
1088                        mode: Some(mode),
1089                        ..Default::default()
1090                    });
1091            }
1092        });
1093    }
1094}