edit_prediction_button.rs

   1use anyhow::Result;
   2use client::{Client, UserStore, zed_urls};
   3use cloud_llm_client::UsageLimit;
   4use codestral::CodestralEditPredictionDelegate;
   5use copilot::Status;
   6use edit_prediction::{
   7    EditPredictionStore, MercuryFeatureFlag, SweepFeatureFlag, Zeta2FeatureFlag,
   8};
   9use edit_prediction_types::EditPredictionDelegateHandle;
  10use editor::{
  11    Editor, MultiBufferOffset, SelectionEffects, actions::ShowEditPrediction, scroll::Autoscroll,
  12};
  13use feature_flags::FeatureFlagAppExt;
  14use fs::Fs;
  15use gpui::{
  16    Action, Animation, AnimationExt, App, AsyncWindowContext, Corner, Entity, FocusHandle,
  17    Focusable, IntoElement, ParentElement, Render, Subscription, WeakEntity, actions, div,
  18    ease_in_out, pulsating_between,
  19};
  20use indoc::indoc;
  21use language::{
  22    EditPredictionsMode, File, Language,
  23    language_settings::{self, AllLanguageSettings, EditPredictionProvider, all_language_settings},
  24};
  25use project::{DisableAiSettings, Project};
  26use regex::Regex;
  27use settings::{
  28    EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
  29    EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
  30    EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME, Settings, SettingsStore,
  31    update_settings_file,
  32};
  33use std::{
  34    sync::{Arc, LazyLock},
  35    time::Duration,
  36};
  37use supermaven::{AccountStatus, Supermaven};
  38use ui::{
  39    Clickable, ContextMenu, ContextMenuEntry, DocumentationSide, IconButton, IconButtonShape,
  40    Indicator, PopoverMenu, PopoverMenuHandle, ProgressBar, Tooltip, prelude::*,
  41};
  42use util::ResultExt as _;
  43use workspace::{
  44    StatusItemView, Toast, Workspace, create_and_open_local_file, item::ItemHandle,
  45    notifications::NotificationId,
  46};
  47use zed_actions::{OpenBrowser, OpenSettingsAt};
  48
  49use crate::{
  50    CaptureExample, RatePredictions, rate_prediction_modal::PredictEditsRatePredictionsFeatureFlag,
  51};
  52
  53actions!(
  54    edit_prediction,
  55    [
  56        /// Toggles the edit prediction menu.
  57        ToggleMenu
  58    ]
  59);
  60
  61const COPILOT_SETTINGS_PATH: &str = "/settings/copilot";
  62const COPILOT_SETTINGS_URL: &str = concat!("https://github.com", "/settings/copilot");
  63const PRIVACY_DOCS: &str = "https://zed.dev/docs/ai/privacy-and-security";
  64
  65struct CopilotErrorToast;
  66
  67pub struct EditPredictionButton {
  68    editor_subscription: Option<(Subscription, usize)>,
  69    editor_enabled: Option<bool>,
  70    editor_show_predictions: bool,
  71    editor_focus_handle: Option<FocusHandle>,
  72    language: Option<Arc<Language>>,
  73    file: Option<Arc<dyn File>>,
  74    edit_prediction_provider: Option<Arc<dyn EditPredictionDelegateHandle>>,
  75    fs: Arc<dyn Fs>,
  76    user_store: Entity<UserStore>,
  77    popover_menu_handle: PopoverMenuHandle<ContextMenu>,
  78    project: WeakEntity<Project>,
  79}
  80
  81enum SupermavenButtonStatus {
  82    Ready,
  83    Errored(String),
  84    NeedsActivation(String),
  85    Initializing,
  86}
  87
  88impl Render for EditPredictionButton {
  89    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
  90        // Return empty div if AI is disabled
  91        if DisableAiSettings::get_global(cx).disable_ai {
  92            return div().hidden();
  93        }
  94
  95        let all_language_settings = all_language_settings(None, cx);
  96
  97        match all_language_settings.edit_predictions.provider {
  98            EditPredictionProvider::Copilot => {
  99                let Some(copilot) = EditPredictionStore::try_global(cx)
 100                    .and_then(|store| store.read(cx).copilot_for_project(&self.project.upgrade()?))
 101                else {
 102                    return div().hidden();
 103                };
 104                let status = copilot.read(cx).status();
 105
 106                let enabled = self.editor_enabled.unwrap_or(false);
 107
 108                let icon = match status {
 109                    Status::Error(_) => IconName::CopilotError,
 110                    Status::Authorized => {
 111                        if enabled {
 112                            IconName::Copilot
 113                        } else {
 114                            IconName::CopilotDisabled
 115                        }
 116                    }
 117                    _ => IconName::CopilotInit,
 118                };
 119
 120                if let Status::Error(e) = status {
 121                    return div().child(
 122                        IconButton::new("copilot-error", icon)
 123                            .icon_size(IconSize::Small)
 124                            .on_click(cx.listener(move |_, _, window, cx| {
 125                                if let Some(workspace) = window.root::<Workspace>().flatten() {
 126                                    workspace.update(cx, |workspace, cx| {
 127                                        let copilot = copilot.clone();
 128                                        workspace.show_toast(
 129                                            Toast::new(
 130                                                NotificationId::unique::<CopilotErrorToast>(),
 131                                                format!("Copilot can't be started: {}", e),
 132                                            )
 133                                            .on_click(
 134                                                "Reinstall Copilot",
 135                                                move |window, cx| {
 136                                                    copilot_ui::reinstall_and_sign_in(
 137                                                        copilot.clone(),
 138                                                        window,
 139                                                        cx,
 140                                                    )
 141                                                },
 142                                            ),
 143                                            cx,
 144                                        );
 145                                    });
 146                                }
 147                            }))
 148                            .tooltip(|_window, cx| {
 149                                Tooltip::for_action("GitHub Copilot", &ToggleMenu, cx)
 150                            }),
 151                    );
 152                }
 153                let this = cx.weak_entity();
 154                let project = self.project.clone();
 155                div().child(
 156                    PopoverMenu::new("copilot")
 157                        .menu(move |window, cx| {
 158                            let current_status = EditPredictionStore::try_global(cx)
 159                                .and_then(|store| {
 160                                    store.read(cx).copilot_for_project(&project.upgrade()?)
 161                                })?
 162                                .read(cx)
 163                                .status();
 164                            match current_status {
 165                                Status::Authorized => this.update(cx, |this, cx| {
 166                                    this.build_copilot_context_menu(window, cx)
 167                                }),
 168                                _ => this.update(cx, |this, cx| {
 169                                    this.build_copilot_start_menu(window, cx)
 170                                }),
 171                            }
 172                            .ok()
 173                        })
 174                        .anchor(Corner::BottomRight)
 175                        .trigger_with_tooltip(
 176                            IconButton::new("copilot-icon", icon),
 177                            |_window, cx| Tooltip::for_action("GitHub Copilot", &ToggleMenu, cx),
 178                        )
 179                        .with_handle(self.popover_menu_handle.clone()),
 180                )
 181            }
 182
 183            EditPredictionProvider::Supermaven => {
 184                let Some(supermaven) = Supermaven::global(cx) else {
 185                    return div();
 186                };
 187
 188                let supermaven = supermaven.read(cx);
 189
 190                let status = match supermaven {
 191                    Supermaven::Starting => SupermavenButtonStatus::Initializing,
 192                    Supermaven::FailedDownload { error } => {
 193                        SupermavenButtonStatus::Errored(error.to_string())
 194                    }
 195                    Supermaven::Spawned(agent) => {
 196                        let account_status = agent.account_status.clone();
 197                        match account_status {
 198                            AccountStatus::NeedsActivation { activate_url } => {
 199                                SupermavenButtonStatus::NeedsActivation(activate_url)
 200                            }
 201                            AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
 202                            AccountStatus::Ready => SupermavenButtonStatus::Ready,
 203                        }
 204                    }
 205                    Supermaven::Error { error } => {
 206                        SupermavenButtonStatus::Errored(error.to_string())
 207                    }
 208                };
 209
 210                let icon = status.to_icon();
 211                let tooltip_text = status.to_tooltip();
 212                let has_menu = status.has_menu();
 213                let this = cx.weak_entity();
 214                let fs = self.fs.clone();
 215
 216                div().child(
 217                    PopoverMenu::new("supermaven")
 218                        .menu(move |window, cx| match &status {
 219                            SupermavenButtonStatus::NeedsActivation(activate_url) => {
 220                                Some(ContextMenu::build(window, cx, |menu, _, _| {
 221                                    let fs = fs.clone();
 222                                    let activate_url = activate_url.clone();
 223
 224                                    menu.entry("Sign In", None, move |_, cx| {
 225                                        cx.open_url(activate_url.as_str())
 226                                    })
 227                                    .entry(
 228                                        "Use Zed AI",
 229                                        None,
 230                                        move |_, cx| {
 231                                            set_completion_provider(
 232                                                fs.clone(),
 233                                                cx,
 234                                                EditPredictionProvider::Zed,
 235                                            )
 236                                        },
 237                                    )
 238                                }))
 239                            }
 240                            SupermavenButtonStatus::Ready => this
 241                                .update(cx, |this, cx| {
 242                                    this.build_supermaven_context_menu(window, cx)
 243                                })
 244                                .ok(),
 245                            _ => None,
 246                        })
 247                        .anchor(Corner::BottomRight)
 248                        .trigger_with_tooltip(
 249                            IconButton::new("supermaven-icon", icon),
 250                            move |window, cx| {
 251                                if has_menu {
 252                                    Tooltip::for_action(tooltip_text.clone(), &ToggleMenu, cx)
 253                                } else {
 254                                    Tooltip::text(tooltip_text.clone())(window, cx)
 255                                }
 256                            },
 257                        )
 258                        .with_handle(self.popover_menu_handle.clone()),
 259                )
 260            }
 261
 262            EditPredictionProvider::Codestral => {
 263                let enabled = self.editor_enabled.unwrap_or(true);
 264                let has_api_key = CodestralEditPredictionDelegate::has_api_key(cx);
 265                let this = cx.weak_entity();
 266
 267                let tooltip_meta = if has_api_key {
 268                    "Powered by Codestral"
 269                } else {
 270                    "Missing API key for Codestral"
 271                };
 272
 273                div().child(
 274                    PopoverMenu::new("codestral")
 275                        .menu(move |window, cx| {
 276                            this.update(cx, |this, cx| {
 277                                this.build_codestral_context_menu(window, cx)
 278                            })
 279                            .ok()
 280                        })
 281                        .anchor(Corner::BottomRight)
 282                        .trigger_with_tooltip(
 283                            IconButton::new("codestral-icon", IconName::AiMistral)
 284                                .shape(IconButtonShape::Square)
 285                                .when(!has_api_key, |this| {
 286                                    this.indicator(Indicator::dot().color(Color::Error))
 287                                        .indicator_border_color(Some(
 288                                            cx.theme().colors().status_bar_background,
 289                                        ))
 290                                })
 291                                .when(has_api_key && !enabled, |this| {
 292                                    this.indicator(Indicator::dot().color(Color::Ignored))
 293                                        .indicator_border_color(Some(
 294                                            cx.theme().colors().status_bar_background,
 295                                        ))
 296                                }),
 297                            move |_window, cx| {
 298                                Tooltip::with_meta(
 299                                    "Edit Prediction",
 300                                    Some(&ToggleMenu),
 301                                    tooltip_meta,
 302                                    cx,
 303                                )
 304                            },
 305                        )
 306                        .with_handle(self.popover_menu_handle.clone()),
 307                )
 308            }
 309            provider @ (EditPredictionProvider::Experimental(_) | EditPredictionProvider::Zed) => {
 310                let enabled = self.editor_enabled.unwrap_or(true);
 311
 312                let ep_icon;
 313                let tooltip_meta;
 314                let mut missing_token = false;
 315
 316                match provider {
 317                    EditPredictionProvider::Experimental(
 318                        EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
 319                    ) => {
 320                        ep_icon = IconName::SweepAi;
 321                        tooltip_meta = if missing_token {
 322                            "Missing API key for Sweep"
 323                        } else {
 324                            "Powered by Sweep"
 325                        };
 326                        missing_token = edit_prediction::EditPredictionStore::try_global(cx)
 327                            .is_some_and(|ep_store| !ep_store.read(cx).has_sweep_api_token(cx));
 328                    }
 329                    EditPredictionProvider::Experimental(
 330                        EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
 331                    ) => {
 332                        ep_icon = IconName::Inception;
 333                        missing_token = edit_prediction::EditPredictionStore::try_global(cx)
 334                            .is_some_and(|ep_store| !ep_store.read(cx).has_mercury_api_token(cx));
 335                        tooltip_meta = if missing_token {
 336                            "Missing API key for Mercury"
 337                        } else {
 338                            "Powered by Mercury"
 339                        };
 340                    }
 341                    _ => {
 342                        ep_icon = if enabled {
 343                            IconName::ZedPredict
 344                        } else {
 345                            IconName::ZedPredictDisabled
 346                        };
 347                        tooltip_meta = "Powered by Zeta"
 348                    }
 349                };
 350
 351                if edit_prediction::should_show_upsell_modal() {
 352                    let tooltip_meta = if self.user_store.read(cx).current_user().is_some() {
 353                        "Choose a Plan"
 354                    } else {
 355                        "Sign In To Use"
 356                    };
 357
 358                    return div().child(
 359                        IconButton::new("zed-predict-pending-button", ep_icon)
 360                            .shape(IconButtonShape::Square)
 361                            .indicator(Indicator::dot().color(Color::Muted))
 362                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
 363                            .tooltip(move |_window, cx| {
 364                                Tooltip::with_meta("Edit Predictions", None, tooltip_meta, cx)
 365                            })
 366                            .on_click(cx.listener(move |_, _, window, cx| {
 367                                telemetry::event!(
 368                                    "Pending ToS Clicked",
 369                                    source = "Edit Prediction Status Button"
 370                                );
 371                                window.dispatch_action(
 372                                    zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 373                                    cx,
 374                                );
 375                            })),
 376                    );
 377                }
 378
 379                let mut over_limit = false;
 380
 381                if let Some(usage) = self
 382                    .edit_prediction_provider
 383                    .as_ref()
 384                    .and_then(|provider| provider.usage(cx))
 385                {
 386                    over_limit = usage.over_limit()
 387                }
 388
 389                let show_editor_predictions = self.editor_show_predictions;
 390                let user = self.user_store.read(cx).current_user();
 391
 392                let indicator_color = if missing_token {
 393                    Some(Color::Error)
 394                } else if enabled && (!show_editor_predictions || over_limit) {
 395                    Some(if over_limit {
 396                        Color::Error
 397                    } else {
 398                        Color::Muted
 399                    })
 400                } else {
 401                    None
 402                };
 403
 404                let icon_button = IconButton::new("zed-predict-pending-button", ep_icon)
 405                    .shape(IconButtonShape::Square)
 406                    .when_some(indicator_color, |this, color| {
 407                        this.indicator(Indicator::dot().color(color))
 408                            .indicator_border_color(Some(cx.theme().colors().status_bar_background))
 409                    })
 410                    .when(!self.popover_menu_handle.is_deployed(), |element| {
 411                        let user = user.clone();
 412
 413                        element.tooltip(move |_window, cx| {
 414                            let description = if enabled {
 415                                if show_editor_predictions {
 416                                    tooltip_meta
 417                                } else if user.is_none() {
 418                                    "Sign In To Use"
 419                                } else {
 420                                    "Hidden For This File"
 421                                }
 422                            } else {
 423                                "Disabled For This File"
 424                            };
 425
 426                            Tooltip::with_meta(
 427                                "Edit Prediction",
 428                                Some(&ToggleMenu),
 429                                description,
 430                                cx,
 431                            )
 432                        })
 433                    });
 434
 435                let this = cx.weak_entity();
 436
 437                let mut popover_menu = PopoverMenu::new("edit-prediction")
 438                    .when(user.is_some(), |popover_menu| {
 439                        let this = this.clone();
 440
 441                        popover_menu.menu(move |window, cx| {
 442                            this.update(cx, |this, cx| {
 443                                this.build_edit_prediction_context_menu(provider, window, cx)
 444                            })
 445                            .ok()
 446                        })
 447                    })
 448                    .when(user.is_none(), |popover_menu| {
 449                        let this = this.clone();
 450
 451                        popover_menu.menu(move |window, cx| {
 452                            this.update(cx, |this, cx| {
 453                                this.build_zeta_upsell_context_menu(window, cx)
 454                            })
 455                            .ok()
 456                        })
 457                    })
 458                    .anchor(Corner::BottomRight)
 459                    .with_handle(self.popover_menu_handle.clone());
 460
 461                let is_refreshing = self
 462                    .edit_prediction_provider
 463                    .as_ref()
 464                    .is_some_and(|provider| provider.is_refreshing(cx));
 465
 466                if is_refreshing {
 467                    popover_menu = popover_menu.trigger(
 468                        icon_button.with_animation(
 469                            "pulsating-label",
 470                            Animation::new(Duration::from_secs(2))
 471                                .repeat()
 472                                .with_easing(pulsating_between(0.2, 1.0)),
 473                            |icon_button, delta| icon_button.alpha(delta),
 474                        ),
 475                    );
 476                } else {
 477                    popover_menu = popover_menu.trigger(icon_button);
 478                }
 479
 480                div().child(popover_menu.into_any_element())
 481            }
 482
 483            EditPredictionProvider::None => div().hidden(),
 484        }
 485    }
 486}
 487
 488impl EditPredictionButton {
 489    pub fn new(
 490        fs: Arc<dyn Fs>,
 491        user_store: Entity<UserStore>,
 492        popover_menu_handle: PopoverMenuHandle<ContextMenu>,
 493        client: Arc<Client>,
 494        project: Entity<Project>,
 495        cx: &mut Context<Self>,
 496    ) -> Self {
 497        let copilot = EditPredictionStore::try_global(cx).and_then(|store| {
 498            store.update(cx, |this, cx| this.start_copilot_for_project(&project, cx))
 499        });
 500        if let Some(copilot) = copilot {
 501            cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
 502        }
 503
 504        cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
 505            .detach();
 506
 507        cx.observe_global::<EditPredictionStore>(move |_, cx| cx.notify())
 508            .detach();
 509
 510        let sweep_api_token_task = edit_prediction::sweep_ai::load_sweep_api_token(cx);
 511        let mercury_api_token_task = edit_prediction::mercury::load_mercury_api_token(cx);
 512
 513        cx.spawn(async move |this, cx| {
 514            _ = futures::join!(sweep_api_token_task, mercury_api_token_task);
 515            this.update(cx, |_, cx| {
 516                cx.notify();
 517            })
 518            .ok();
 519        })
 520        .detach();
 521
 522        CodestralEditPredictionDelegate::ensure_api_key_loaded(client.http_client(), cx);
 523
 524        Self {
 525            editor_subscription: None,
 526            editor_enabled: None,
 527            editor_show_predictions: true,
 528            editor_focus_handle: None,
 529            language: None,
 530            file: None,
 531            edit_prediction_provider: None,
 532            user_store,
 533            popover_menu_handle,
 534            project: project.downgrade(),
 535            fs,
 536        }
 537    }
 538
 539    fn add_provider_switching_section(
 540        &self,
 541        mut menu: ContextMenu,
 542        current_provider: EditPredictionProvider,
 543        cx: &mut App,
 544    ) -> ContextMenu {
 545        let available_providers = get_available_providers(cx);
 546
 547        let providers: Vec<_> = available_providers
 548            .into_iter()
 549            .filter(|p| *p != EditPredictionProvider::None)
 550            .collect();
 551
 552        if !providers.is_empty() {
 553            menu = menu.separator().header("Providers");
 554
 555            for provider in providers {
 556                let Some(name) = provider.display_name() else {
 557                    continue;
 558                };
 559                let is_current = provider == current_provider;
 560                let fs = self.fs.clone();
 561
 562                menu = menu.item(
 563                    ContextMenuEntry::new(name)
 564                        .toggleable(IconPosition::Start, is_current)
 565                        .handler(move |_, cx| {
 566                            set_completion_provider(fs.clone(), cx, provider);
 567                        }),
 568                )
 569            }
 570        }
 571
 572        menu
 573    }
 574
 575    pub fn build_copilot_start_menu(
 576        &mut self,
 577        window: &mut Window,
 578        cx: &mut Context<Self>,
 579    ) -> Entity<ContextMenu> {
 580        let fs = self.fs.clone();
 581        let project = self.project.clone();
 582        ContextMenu::build(window, cx, |menu, _, _| {
 583            menu.entry("Sign In to Copilot", None, move |window, cx| {
 584                if let Some(copilot) = EditPredictionStore::try_global(cx).and_then(|store| {
 585                    store.update(cx, |this, cx| {
 586                        this.start_copilot_for_project(&project.upgrade()?, cx)
 587                    })
 588                }) {
 589                    copilot_ui::initiate_sign_in(copilot, window, cx);
 590                }
 591            })
 592            .entry("Disable Copilot", None, {
 593                let fs = fs.clone();
 594                move |_window, cx| hide_copilot(fs.clone(), cx)
 595            })
 596            .separator()
 597            .entry("Use Zed AI", None, {
 598                let fs = fs.clone();
 599                move |_window, cx| {
 600                    set_completion_provider(fs.clone(), cx, EditPredictionProvider::Zed)
 601                }
 602            })
 603        })
 604    }
 605
 606    pub fn build_language_settings_menu(
 607        &self,
 608        mut menu: ContextMenu,
 609        window: &Window,
 610        cx: &mut App,
 611    ) -> ContextMenu {
 612        let fs = self.fs.clone();
 613        let line_height = window.line_height();
 614
 615        menu = menu.header("Show Edit Predictions For");
 616
 617        let language_state = self.language.as_ref().map(|language| {
 618            (
 619                language.clone(),
 620                language_settings::language_settings(Some(language.name()), None, cx)
 621                    .show_edit_predictions,
 622            )
 623        });
 624
 625        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
 626            let entry = ContextMenuEntry::new("This Buffer")
 627                .toggleable(IconPosition::Start, self.editor_show_predictions)
 628                .action(Box::new(editor::actions::ToggleEditPrediction))
 629                .handler(move |window, cx| {
 630                    editor_focus_handle.dispatch_action(
 631                        &editor::actions::ToggleEditPrediction,
 632                        window,
 633                        cx,
 634                    );
 635                });
 636
 637            match language_state.clone() {
 638                Some((language, false)) => {
 639                    menu = menu.item(
 640                        entry
 641                            .disabled(true)
 642                            .documentation_aside(DocumentationSide::Left, move |_cx| {
 643                                Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
 644                                    .into_any_element()
 645                            })
 646                    );
 647                }
 648                Some(_) | None => menu = menu.item(entry),
 649            }
 650        }
 651
 652        if let Some((language, language_enabled)) = language_state {
 653            let fs = fs.clone();
 654
 655            menu = menu.toggleable_entry(
 656                language.name(),
 657                language_enabled,
 658                IconPosition::Start,
 659                None,
 660                move |_, cx| {
 661                    toggle_show_edit_predictions_for_language(language.clone(), fs.clone(), cx)
 662                },
 663            );
 664        }
 665
 666        let settings = AllLanguageSettings::get_global(cx);
 667
 668        let globally_enabled = settings.show_edit_predictions(None, cx);
 669        let entry = ContextMenuEntry::new("All Files")
 670            .toggleable(IconPosition::Start, globally_enabled)
 671            .action(workspace::ToggleEditPrediction.boxed_clone())
 672            .handler(|window, cx| {
 673                window.dispatch_action(workspace::ToggleEditPrediction.boxed_clone(), cx)
 674            });
 675        menu = menu.item(entry);
 676
 677        let provider = settings.edit_predictions.provider;
 678        let current_mode = settings.edit_predictions_mode();
 679        let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
 680        let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
 681
 682        menu = menu
 683                .separator()
 684                .header("Display Modes")
 685                .item(
 686                    ContextMenuEntry::new("Eager")
 687                        .toggleable(IconPosition::Start, eager_mode)
 688                        .documentation_aside(DocumentationSide::Left, move |_| {
 689                            Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
 690                        })
 691                        .handler({
 692                            let fs = fs.clone();
 693                            move |_, cx| {
 694                                toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
 695                            }
 696                        }),
 697                )
 698                .item(
 699                    ContextMenuEntry::new("Subtle")
 700                        .toggleable(IconPosition::Start, subtle_mode)
 701                        .documentation_aside(DocumentationSide::Left, move |_| {
 702                            Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
 703                        })
 704                        .handler({
 705                            let fs = fs.clone();
 706                            move |_, cx| {
 707                                toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
 708                            }
 709                        }),
 710                );
 711
 712        menu = menu.separator().header("Privacy");
 713
 714        if matches!(
 715            provider,
 716            EditPredictionProvider::Zed
 717                | EditPredictionProvider::Experimental(
 718                    EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
 719                )
 720        ) {
 721            if let Some(provider) = &self.edit_prediction_provider {
 722                let data_collection = provider.data_collection_state(cx);
 723
 724                if data_collection.is_supported() {
 725                    let provider = provider.clone();
 726                    let enabled = data_collection.is_enabled();
 727                    let is_open_source = data_collection.is_project_open_source();
 728                    let is_collecting = data_collection.is_enabled();
 729                    let (icon_name, icon_color) = if is_open_source && is_collecting {
 730                        (IconName::Check, Color::Success)
 731                    } else {
 732                        (IconName::Check, Color::Accent)
 733                    };
 734
 735                    menu = menu.item(
 736                        ContextMenuEntry::new("Training Data Collection")
 737                            .toggleable(IconPosition::Start, data_collection.is_enabled())
 738                            .icon(icon_name)
 739                            .icon_color(icon_color)
 740                            .disabled(cx.is_staff())
 741                            .documentation_aside(DocumentationSide::Left, move |cx| {
 742                                let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
 743                                    (true, true) => (
 744                                        "Project identified as open source, and you're sharing data.",
 745                                        Color::Default,
 746                                        IconName::Check,
 747                                        Color::Success,
 748                                    ),
 749                                    (true, false) => (
 750                                        "Project identified as open source, but you're not sharing data.",
 751                                        Color::Muted,
 752                                        IconName::Close,
 753                                        Color::Muted,
 754                                    ),
 755                                    (false, true) => (
 756                                        "Project not identified as open source. No data captured.",
 757                                        Color::Muted,
 758                                        IconName::Close,
 759                                        Color::Muted,
 760                                    ),
 761                                    (false, false) => (
 762                                        "Project not identified as open source, and setting turned off.",
 763                                        Color::Muted,
 764                                        IconName::Close,
 765                                        Color::Muted,
 766                                    ),
 767                                };
 768                                v_flex()
 769                                    .gap_2()
 770                                    .child(
 771                                        Label::new(indoc!{
 772                                            "Help us improve our open dataset model by sharing data from open source repositories. \
 773                                            Zed must detect a license file in your repo for this setting to take effect. \
 774                                            Files with sensitive data and secrets are excluded by default."
 775                                        })
 776                                    )
 777                                    .child(
 778                                        h_flex()
 779                                            .items_start()
 780                                            .pt_2()
 781                                            .pr_1()
 782                                            .flex_1()
 783                                            .gap_1p5()
 784                                            .border_t_1()
 785                                            .border_color(cx.theme().colors().border_variant)
 786                                            .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
 787                                            .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
 788                                    )
 789                                    .into_any_element()
 790                            })
 791                            .handler(move |_, cx| {
 792                                provider.toggle_data_collection(cx);
 793
 794                                if !enabled {
 795                                    telemetry::event!(
 796                                        "Data Collection Enabled",
 797                                        source = "Edit Prediction Status Menu"
 798                                    );
 799                                } else {
 800                                    telemetry::event!(
 801                                        "Data Collection Disabled",
 802                                        source = "Edit Prediction Status Menu"
 803                                    );
 804                                }
 805                            })
 806                    );
 807
 808                    if is_collecting && !is_open_source {
 809                        menu = menu.item(
 810                            ContextMenuEntry::new("No data captured.")
 811                                .disabled(true)
 812                                .icon(IconName::Close)
 813                                .icon_color(Color::Error)
 814                                .icon_size(IconSize::Small),
 815                        );
 816                    }
 817                }
 818            }
 819        }
 820
 821        menu = menu.item(
 822            ContextMenuEntry::new("Configure Excluded Files")
 823                .icon(IconName::LockOutlined)
 824                .icon_color(Color::Muted)
 825                .documentation_aside(DocumentationSide::Left, |_| {
 826                    Label::new(indoc!{"
 827                        Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
 828                })
 829                .handler(move |window, cx| {
 830                    if let Some(workspace) = window.root().flatten() {
 831                        let workspace = workspace.downgrade();
 832                        window
 833                            .spawn(cx, async |cx| {
 834                                open_disabled_globs_setting_in_editor(
 835                                    workspace,
 836                                    cx,
 837                                ).await
 838                            })
 839                            .detach_and_log_err(cx);
 840                    }
 841                }),
 842        ).item(
 843            ContextMenuEntry::new("View Docs")
 844                .icon(IconName::FileGeneric)
 845                .icon_color(Color::Muted)
 846                .handler(move |_, cx| {
 847                    cx.open_url(PRIVACY_DOCS);
 848                })
 849        );
 850
 851        if !self.editor_enabled.unwrap_or(true) {
 852            menu = menu.item(
 853                ContextMenuEntry::new("This file is excluded.")
 854                    .disabled(true)
 855                    .icon(IconName::ZedPredictDisabled)
 856                    .icon_size(IconSize::Small),
 857            );
 858        }
 859
 860        if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
 861            menu = menu
 862                .separator()
 863                .header("Actions")
 864                .entry(
 865                    "Predict Edit at Cursor",
 866                    Some(Box::new(ShowEditPrediction)),
 867                    {
 868                        let editor_focus_handle = editor_focus_handle.clone();
 869                        move |window, cx| {
 870                            editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
 871                        }
 872                    },
 873                )
 874                .context(editor_focus_handle)
 875                .when(
 876                    cx.has_flag::<PredictEditsRatePredictionsFeatureFlag>(),
 877                    |this| {
 878                        this.action("Capture Prediction Example", CaptureExample.boxed_clone())
 879                            .action("Rate Predictions", RatePredictions.boxed_clone())
 880                    },
 881                );
 882        }
 883
 884        menu
 885    }
 886
 887    fn build_copilot_context_menu(
 888        &self,
 889        window: &mut Window,
 890        cx: &mut Context<Self>,
 891    ) -> Entity<ContextMenu> {
 892        let all_language_settings = all_language_settings(None, cx);
 893        let next_edit_suggestions = all_language_settings
 894            .edit_predictions
 895            .copilot
 896            .enable_next_edit_suggestions
 897            .unwrap_or(true);
 898        let copilot_config = copilot_chat::CopilotChatConfiguration {
 899            enterprise_uri: all_language_settings
 900                .edit_predictions
 901                .copilot
 902                .enterprise_uri
 903                .clone(),
 904        };
 905        let settings_url = copilot_settings_url(copilot_config.enterprise_uri.as_deref());
 906
 907        ContextMenu::build(window, cx, |menu, window, cx| {
 908            let menu = self.build_language_settings_menu(menu, window, cx);
 909            let menu =
 910                self.add_provider_switching_section(menu, EditPredictionProvider::Copilot, cx);
 911
 912            menu.separator()
 913                .item(
 914                    ContextMenuEntry::new("Copilot: Next Edit Suggestions")
 915                        .toggleable(IconPosition::Start, next_edit_suggestions)
 916                        .handler({
 917                            let fs = self.fs.clone();
 918                            move |_, cx| {
 919                                update_settings_file(fs.clone(), cx, move |settings, _| {
 920                                    settings
 921                                        .project
 922                                        .all_languages
 923                                        .edit_predictions
 924                                        .get_or_insert_default()
 925                                        .copilot
 926                                        .get_or_insert_default()
 927                                        .enable_next_edit_suggestions =
 928                                        Some(!next_edit_suggestions);
 929                                });
 930                            }
 931                        }),
 932                )
 933                .separator()
 934                .link(
 935                    "Go to Copilot Settings",
 936                    OpenBrowser { url: settings_url }.boxed_clone(),
 937                )
 938                .action("Sign Out", copilot::SignOut.boxed_clone())
 939        })
 940    }
 941
 942    fn build_supermaven_context_menu(
 943        &self,
 944        window: &mut Window,
 945        cx: &mut Context<Self>,
 946    ) -> Entity<ContextMenu> {
 947        ContextMenu::build(window, cx, |menu, window, cx| {
 948            let menu = self.build_language_settings_menu(menu, window, cx);
 949            let menu =
 950                self.add_provider_switching_section(menu, EditPredictionProvider::Supermaven, cx);
 951
 952            menu.separator()
 953                .action("Sign Out", supermaven::SignOut.boxed_clone())
 954        })
 955    }
 956
 957    fn build_codestral_context_menu(
 958        &self,
 959        window: &mut Window,
 960        cx: &mut Context<Self>,
 961    ) -> Entity<ContextMenu> {
 962        ContextMenu::build(window, cx, |menu, window, cx| {
 963            let menu = self.build_language_settings_menu(menu, window, cx);
 964            let menu =
 965                self.add_provider_switching_section(menu, EditPredictionProvider::Codestral, cx);
 966
 967            menu
 968        })
 969    }
 970
 971    fn build_edit_prediction_context_menu(
 972        &self,
 973        provider: EditPredictionProvider,
 974        window: &mut Window,
 975        cx: &mut Context<Self>,
 976    ) -> Entity<ContextMenu> {
 977        ContextMenu::build(window, cx, |mut menu, window, cx| {
 978            if let Some(usage) = self
 979                .edit_prediction_provider
 980                .as_ref()
 981                .and_then(|provider| provider.usage(cx))
 982            {
 983                menu = menu.header("Usage");
 984                menu = menu
 985                    .custom_entry(
 986                        move |_window, cx| {
 987                            let used_percentage = match usage.limit {
 988                                UsageLimit::Limited(limit) => {
 989                                    Some((usage.amount as f32 / limit as f32) * 100.)
 990                                }
 991                                UsageLimit::Unlimited => None,
 992                            };
 993
 994                            h_flex()
 995                                .flex_1()
 996                                .gap_1p5()
 997                                .children(
 998                                    used_percentage.map(|percent| {
 999                                        ProgressBar::new("usage", percent, 100., cx)
1000                                    }),
1001                                )
1002                                .child(
1003                                    Label::new(match usage.limit {
1004                                        UsageLimit::Limited(limit) => {
1005                                            format!("{} / {limit}", usage.amount)
1006                                        }
1007                                        UsageLimit::Unlimited => format!("{} / ∞", usage.amount),
1008                                    })
1009                                    .size(LabelSize::Small)
1010                                    .color(Color::Muted),
1011                                )
1012                                .into_any_element()
1013                        },
1014                        move |_, cx| cx.open_url(&zed_urls::account_url(cx)),
1015                    )
1016                    .when(usage.over_limit(), |menu| -> ContextMenu {
1017                        menu.entry("Subscribe to increase your limit", None, |_window, cx| {
1018                            cx.open_url(&zed_urls::account_url(cx))
1019                        })
1020                    })
1021                    .separator();
1022            } else if self.user_store.read(cx).account_too_young() {
1023                menu = menu
1024                    .custom_entry(
1025                        |_window, _cx| {
1026                            Label::new("Your GitHub account is less than 30 days old.")
1027                                .size(LabelSize::Small)
1028                                .color(Color::Warning)
1029                                .into_any_element()
1030                        },
1031                        |_window, cx| cx.open_url(&zed_urls::account_url(cx)),
1032                    )
1033                    .entry("Upgrade to Zed Pro or contact us.", None, |_window, cx| {
1034                        cx.open_url(&zed_urls::account_url(cx))
1035                    })
1036                    .separator();
1037            } else if self.user_store.read(cx).has_overdue_invoices() {
1038                menu = menu
1039                    .custom_entry(
1040                        |_window, _cx| {
1041                            Label::new("You have an outstanding invoice")
1042                                .size(LabelSize::Small)
1043                                .color(Color::Warning)
1044                                .into_any_element()
1045                        },
1046                        |_window, cx| {
1047                            cx.open_url(&zed_urls::account_url(cx))
1048                        },
1049                    )
1050                    .entry(
1051                        "Check your payment status or contact us at billing-support@zed.dev to continue using this feature.",
1052                        None,
1053                        |_window, cx| {
1054                            cx.open_url(&zed_urls::account_url(cx))
1055                        },
1056                    )
1057                    .separator();
1058            }
1059
1060            menu = self.build_language_settings_menu(menu, window, cx);
1061
1062            menu = self.add_provider_switching_section(menu, provider, cx);
1063            menu = menu.separator().item(
1064                ContextMenuEntry::new("Configure Providers")
1065                    .icon(IconName::Settings)
1066                    .icon_position(IconPosition::Start)
1067                    .icon_color(Color::Muted)
1068                    .handler(move |window, cx| {
1069                        window.dispatch_action(
1070                            OpenSettingsAt {
1071                                path: "edit_predictions.providers".to_string(),
1072                            }
1073                            .boxed_clone(),
1074                            cx,
1075                        );
1076                    }),
1077            );
1078
1079            menu
1080        })
1081    }
1082
1083    fn build_zeta_upsell_context_menu(
1084        &self,
1085        window: &mut Window,
1086        cx: &mut Context<Self>,
1087    ) -> Entity<ContextMenu> {
1088        ContextMenu::build(window, cx, |mut menu, _window, cx| {
1089            menu = menu
1090                .custom_row(move |_window, cx| {
1091                    let description = indoc! {
1092                        "You get 2,000 accepted suggestions at every keystroke for free, \
1093                        powered by Zeta, our open-source, open-data model"
1094                    };
1095
1096                    v_flex()
1097                        .max_w_64()
1098                        .h(rems_from_px(148.))
1099                        .child(render_zeta_tab_animation(cx))
1100                        .child(Label::new("Edit Prediction"))
1101                        .child(
1102                            Label::new(description)
1103                                .color(Color::Muted)
1104                                .size(LabelSize::Small),
1105                        )
1106                        .into_any_element()
1107                })
1108                .separator()
1109                .entry("Sign In & Start Using", None, |window, cx| {
1110                    let client = Client::global(cx);
1111                    window
1112                        .spawn(cx, async move |cx| {
1113                            client
1114                                .sign_in_with_optional_connect(true, &cx)
1115                                .await
1116                                .log_err();
1117                        })
1118                        .detach();
1119                })
1120                .link(
1121                    "Learn More",
1122                    OpenBrowser {
1123                        url: zed_urls::edit_prediction_docs(cx),
1124                    }
1125                    .boxed_clone(),
1126                );
1127
1128            menu
1129        })
1130    }
1131
1132    pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
1133        let editor = editor.read(cx);
1134        let snapshot = editor.buffer().read(cx).snapshot(cx);
1135        let suggestion_anchor = editor.selections.newest_anchor().start;
1136        let language = snapshot.language_at(suggestion_anchor);
1137        let file = snapshot.file_at(suggestion_anchor).cloned();
1138        self.editor_enabled = {
1139            let file = file.as_ref();
1140            Some(
1141                file.map(|file| {
1142                    all_language_settings(Some(file), cx)
1143                        .edit_predictions_enabled_for_file(file, cx)
1144                })
1145                .unwrap_or(true),
1146            )
1147        };
1148        self.editor_show_predictions = editor.edit_predictions_enabled();
1149        self.edit_prediction_provider = editor.edit_prediction_provider();
1150        self.language = language.cloned();
1151        self.file = file;
1152        self.editor_focus_handle = Some(editor.focus_handle(cx));
1153
1154        cx.notify();
1155    }
1156}
1157
1158impl StatusItemView for EditPredictionButton {
1159    fn set_active_pane_item(
1160        &mut self,
1161        item: Option<&dyn ItemHandle>,
1162        _: &mut Window,
1163        cx: &mut Context<Self>,
1164    ) {
1165        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
1166            self.editor_subscription = Some((
1167                cx.observe(&editor, Self::update_enabled),
1168                editor.entity_id().as_u64() as usize,
1169            ));
1170            self.update_enabled(editor, cx);
1171        } else {
1172            self.language = None;
1173            self.editor_subscription = None;
1174            self.editor_enabled = None;
1175        }
1176        cx.notify();
1177    }
1178}
1179
1180impl SupermavenButtonStatus {
1181    fn to_icon(&self) -> IconName {
1182        match self {
1183            SupermavenButtonStatus::Ready => IconName::Supermaven,
1184            SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
1185            SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
1186            SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
1187        }
1188    }
1189
1190    fn to_tooltip(&self) -> String {
1191        match self {
1192            SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
1193            SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
1194            SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
1195            SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
1196        }
1197    }
1198
1199    fn has_menu(&self) -> bool {
1200        match self {
1201            SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
1202            SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
1203        }
1204    }
1205}
1206
1207async fn open_disabled_globs_setting_in_editor(
1208    workspace: WeakEntity<Workspace>,
1209    cx: &mut AsyncWindowContext,
1210) -> Result<()> {
1211    let settings_editor = workspace
1212        .update_in(cx, |_, window, cx| {
1213            create_and_open_local_file(paths::settings_file(), window, cx, || {
1214                settings::initial_user_settings_content().as_ref().into()
1215            })
1216        })?
1217        .await?
1218        .downcast::<Editor>()
1219        .unwrap();
1220
1221    settings_editor
1222        .downgrade()
1223        .update_in(cx, |item, window, cx| {
1224            let text = item.buffer().read(cx).snapshot(cx).text();
1225
1226            let settings = cx.global::<SettingsStore>();
1227
1228            // Ensure that we always have "edit_predictions { "disabled_globs": [] }"
1229            let edits = settings.edits_for_update(&text, |file| {
1230                file.project
1231                    .all_languages
1232                    .edit_predictions
1233                    .get_or_insert_with(Default::default)
1234                    .disabled_globs
1235                    .get_or_insert_with(Vec::new);
1236            });
1237
1238            if !edits.is_empty() {
1239                item.edit(
1240                    edits
1241                        .into_iter()
1242                        .map(|(r, s)| (MultiBufferOffset(r.start)..MultiBufferOffset(r.end), s)),
1243                    cx,
1244                );
1245            }
1246
1247            let text = item.buffer().read(cx).snapshot(cx).text();
1248
1249            static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
1250                Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
1251            });
1252            // Only capture [...]
1253            let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
1254                captures
1255                    .name("content")
1256                    .map(|inner_match| inner_match.start()..inner_match.end())
1257            });
1258            if let Some(range) = range {
1259                let range = MultiBufferOffset(range.start)..MultiBufferOffset(range.end);
1260                item.change_selections(
1261                    SelectionEffects::scroll(Autoscroll::newest()),
1262                    window,
1263                    cx,
1264                    |selections| {
1265                        selections.select_ranges(vec![range]);
1266                    },
1267                );
1268            }
1269        })?;
1270
1271    anyhow::Ok(())
1272}
1273
1274pub fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
1275    update_settings_file(fs, cx, move |settings, _| {
1276        settings
1277            .project
1278            .all_languages
1279            .features
1280            .get_or_insert_default()
1281            .edit_prediction_provider = Some(provider);
1282    });
1283}
1284
1285pub fn get_available_providers(cx: &mut App) -> Vec<EditPredictionProvider> {
1286    let mut providers = Vec::new();
1287
1288    providers.push(EditPredictionProvider::Zed);
1289
1290    if cx.has_flag::<Zeta2FeatureFlag>() {
1291        providers.push(EditPredictionProvider::Experimental(
1292            EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
1293        ));
1294    }
1295
1296    if let Some(app_state) = workspace::AppState::global(cx).upgrade()
1297        && copilot::GlobalCopilotAuth::get_or_init(app_state, cx)
1298            .0
1299            .read(cx)
1300            .is_authenticated()
1301    {
1302        providers.push(EditPredictionProvider::Copilot);
1303    };
1304
1305    if let Some(supermaven) = Supermaven::global(cx) {
1306        if let Supermaven::Spawned(agent) = supermaven.read(cx) {
1307            if matches!(agent.account_status, AccountStatus::Ready) {
1308                providers.push(EditPredictionProvider::Supermaven);
1309            }
1310        }
1311    }
1312
1313    if CodestralEditPredictionDelegate::has_api_key(cx) {
1314        providers.push(EditPredictionProvider::Codestral);
1315    }
1316
1317    if cx.has_flag::<SweepFeatureFlag>()
1318        && edit_prediction::sweep_ai::sweep_api_token(cx)
1319            .read(cx)
1320            .has_key()
1321    {
1322        providers.push(EditPredictionProvider::Experimental(
1323            EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
1324        ));
1325    }
1326
1327    if cx.has_flag::<MercuryFeatureFlag>()
1328        && edit_prediction::mercury::mercury_api_token(cx)
1329            .read(cx)
1330            .has_key()
1331    {
1332        providers.push(EditPredictionProvider::Experimental(
1333            EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
1334        ));
1335    }
1336
1337    providers
1338}
1339
1340fn toggle_show_edit_predictions_for_language(
1341    language: Arc<Language>,
1342    fs: Arc<dyn Fs>,
1343    cx: &mut App,
1344) {
1345    let show_edit_predictions =
1346        all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
1347    update_settings_file(fs, cx, move |settings, _| {
1348        settings
1349            .project
1350            .all_languages
1351            .languages
1352            .0
1353            .entry(language.name().0.to_string())
1354            .or_default()
1355            .show_edit_predictions = Some(!show_edit_predictions);
1356    });
1357}
1358
1359fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
1360    update_settings_file(fs, cx, move |settings, _| {
1361        settings
1362            .project
1363            .all_languages
1364            .features
1365            .get_or_insert(Default::default())
1366            .edit_prediction_provider = Some(EditPredictionProvider::None);
1367    });
1368}
1369
1370fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
1371    let settings = AllLanguageSettings::get_global(cx);
1372    let current_mode = settings.edit_predictions_mode();
1373
1374    if current_mode != mode {
1375        update_settings_file(fs, cx, move |settings, _cx| {
1376            if let Some(edit_predictions) = settings.project.all_languages.edit_predictions.as_mut()
1377            {
1378                edit_predictions.mode = Some(mode);
1379            } else {
1380                settings.project.all_languages.edit_predictions =
1381                    Some(settings::EditPredictionSettingsContent {
1382                        mode: Some(mode),
1383                        ..Default::default()
1384                    });
1385            }
1386        });
1387    }
1388}
1389
1390fn render_zeta_tab_animation(cx: &App) -> impl IntoElement {
1391    let tab = |n: u64, inverted: bool| {
1392        let text_color = cx.theme().colors().text;
1393
1394        h_flex().child(
1395            h_flex()
1396                .text_size(TextSize::XSmall.rems(cx))
1397                .text_color(text_color)
1398                .child("tab")
1399                .with_animation(
1400                    ElementId::Integer(n),
1401                    Animation::new(Duration::from_secs(3)).repeat(),
1402                    move |tab, delta| {
1403                        let n_f32 = n as f32;
1404
1405                        let offset = if inverted {
1406                            0.2 * (4.0 - n_f32)
1407                        } else {
1408                            0.2 * n_f32
1409                        };
1410
1411                        let phase = (delta - offset + 1.0) % 1.0;
1412                        let pulse = if phase < 0.6 {
1413                            let t = phase / 0.6;
1414                            1.0 - (0.5 - t).abs() * 2.0
1415                        } else {
1416                            0.0
1417                        };
1418
1419                        let eased = ease_in_out(pulse);
1420                        let opacity = 0.1 + 0.5 * eased;
1421
1422                        tab.text_color(text_color.opacity(opacity))
1423                    },
1424                ),
1425        )
1426    };
1427
1428    let tab_sequence = |inverted: bool| {
1429        h_flex()
1430            .gap_1()
1431            .child(tab(0, inverted))
1432            .child(tab(1, inverted))
1433            .child(tab(2, inverted))
1434            .child(tab(3, inverted))
1435            .child(tab(4, inverted))
1436    };
1437
1438    h_flex()
1439        .my_1p5()
1440        .p_4()
1441        .justify_center()
1442        .gap_2()
1443        .rounded_xs()
1444        .border_1()
1445        .border_dashed()
1446        .border_color(cx.theme().colors().border)
1447        .bg(gpui::pattern_slash(
1448            cx.theme().colors().border.opacity(0.5),
1449            1.,
1450            8.,
1451        ))
1452        .child(tab_sequence(true))
1453        .child(Icon::new(IconName::ZedPredict))
1454        .child(tab_sequence(false))
1455}
1456
1457fn copilot_settings_url(enterprise_uri: Option<&str>) -> String {
1458    match enterprise_uri {
1459        Some(uri) => {
1460            format!("{}{}", uri.trim_end_matches('/'), COPILOT_SETTINGS_PATH)
1461        }
1462        None => COPILOT_SETTINGS_URL.to_string(),
1463    }
1464}
1465
1466#[cfg(test)]
1467mod tests {
1468    use super::*;
1469    use gpui::TestAppContext;
1470
1471    #[gpui::test]
1472    async fn test_copilot_settings_url_with_enterprise_uri(cx: &mut TestAppContext) {
1473        cx.update(|cx| {
1474            let settings_store = SettingsStore::test(cx);
1475            cx.set_global(settings_store);
1476        });
1477
1478        cx.update_global(|settings_store: &mut SettingsStore, cx| {
1479            settings_store
1480                .set_user_settings(
1481                    r#"{"edit_predictions":{"copilot":{"enterprise_uri":"https://my-company.ghe.com"}}}"#,
1482                    cx,
1483                )
1484                .unwrap();
1485        });
1486
1487        let url = cx.update(|cx| {
1488            let all_language_settings = all_language_settings(None, cx);
1489            copilot_settings_url(
1490                all_language_settings
1491                    .edit_predictions
1492                    .copilot
1493                    .enterprise_uri
1494                    .as_deref(),
1495            )
1496        });
1497
1498        assert_eq!(url, "https://my-company.ghe.com/settings/copilot");
1499    }
1500
1501    #[gpui::test]
1502    async fn test_copilot_settings_url_with_enterprise_uri_trailing_slash(cx: &mut TestAppContext) {
1503        cx.update(|cx| {
1504            let settings_store = SettingsStore::test(cx);
1505            cx.set_global(settings_store);
1506        });
1507
1508        cx.update_global(|settings_store: &mut SettingsStore, cx| {
1509            settings_store
1510                .set_user_settings(
1511                    r#"{"edit_predictions":{"copilot":{"enterprise_uri":"https://my-company.ghe.com/"}}}"#,
1512                    cx,
1513                )
1514                .unwrap();
1515        });
1516
1517        let url = cx.update(|cx| {
1518            let all_language_settings = all_language_settings(None, cx);
1519            copilot_settings_url(
1520                all_language_settings
1521                    .edit_predictions
1522                    .copilot
1523                    .enterprise_uri
1524                    .as_deref(),
1525            )
1526        });
1527
1528        assert_eq!(url, "https://my-company.ghe.com/settings/copilot");
1529    }
1530
1531    #[gpui::test]
1532    async fn test_copilot_settings_url_without_enterprise_uri(cx: &mut TestAppContext) {
1533        cx.update(|cx| {
1534            let settings_store = SettingsStore::test(cx);
1535            cx.set_global(settings_store);
1536        });
1537
1538        let url = cx.update(|cx| {
1539            let all_language_settings = all_language_settings(None, cx);
1540            copilot_settings_url(
1541                all_language_settings
1542                    .edit_predictions
1543                    .copilot
1544                    .enterprise_uri
1545                    .as_deref(),
1546            )
1547        });
1548
1549        assert_eq!(url, "https://github.com/settings/copilot");
1550    }
1551}