agent_configuration.rs

   1mod add_llm_provider_modal;
   2pub mod configure_context_server_modal;
   3mod configure_context_server_tools_modal;
   4mod manage_profiles_modal;
   5mod tool_picker;
   6
   7use std::{ops::Range, sync::Arc};
   8
   9use agent::ContextServerRegistry;
  10use anyhow::Result;
  11use client::zed_urls;
  12use cloud_llm_client::{Plan, PlanV2};
  13use collections::HashMap;
  14use context_server::ContextServerId;
  15use editor::{Editor, MultiBufferOffset, SelectionEffects, scroll::Autoscroll};
  16use extension::ExtensionManifest;
  17use extension_host::ExtensionStore;
  18use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};
  19use fs::Fs;
  20use gpui::{
  21    Action, AnyView, App, AsyncWindowContext, Corner, Entity, EventEmitter, FocusHandle, Focusable,
  22    ScrollHandle, Subscription, Task, WeakEntity,
  23};
  24use language::LanguageRegistry;
  25use language_model::{
  26    IconOrSvg, LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry,
  27    ZED_CLOUD_PROVIDER_ID,
  28};
  29use language_models::AllLanguageModelSettings;
  30use notifications::status_toast::{StatusToast, ToastIcon};
  31use project::{
  32    agent_server_store::{
  33        AgentServerStore, CLAUDE_CODE_NAME, CODEX_NAME, ExternalAgentServerName,
  34        ExternalAgentSource, GEMINI_NAME,
  35    },
  36    context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
  37};
  38use settings::{Settings, SettingsStore, update_settings_file};
  39use ui::{
  40    ButtonStyle, Chip, CommonAnimationExt, ContextMenu, ContextMenuEntry, Disclosure, Divider,
  41    DividerColor, ElevationIndex, Indicator, LabelSize, PopoverMenu, Switch, Tooltip,
  42    WithScrollbar, prelude::*,
  43};
  44use util::ResultExt as _;
  45use workspace::{Workspace, create_and_open_local_file};
  46use zed_actions::{ExtensionCategoryFilter, OpenBrowser};
  47
  48pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
  49pub(crate) use configure_context_server_tools_modal::ConfigureContextServerToolsModal;
  50pub(crate) use manage_profiles_modal::ManageProfilesModal;
  51
  52use crate::agent_configuration::add_llm_provider_modal::{
  53    AddLlmProviderModal, LlmCompatibleProvider,
  54};
  55
  56pub struct AgentConfiguration {
  57    fs: Arc<dyn Fs>,
  58    language_registry: Arc<LanguageRegistry>,
  59    agent_server_store: Entity<AgentServerStore>,
  60    workspace: WeakEntity<Workspace>,
  61    focus_handle: FocusHandle,
  62    configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
  63    context_server_store: Entity<ContextServerStore>,
  64    expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
  65    context_server_registry: Entity<ContextServerRegistry>,
  66    _registry_subscription: Subscription,
  67    scroll_handle: ScrollHandle,
  68    _check_for_gemini: Task<()>,
  69}
  70
  71impl AgentConfiguration {
  72    pub fn new(
  73        fs: Arc<dyn Fs>,
  74        agent_server_store: Entity<AgentServerStore>,
  75        context_server_store: Entity<ContextServerStore>,
  76        context_server_registry: Entity<ContextServerRegistry>,
  77        language_registry: Arc<LanguageRegistry>,
  78        workspace: WeakEntity<Workspace>,
  79        window: &mut Window,
  80        cx: &mut Context<Self>,
  81    ) -> Self {
  82        let focus_handle = cx.focus_handle();
  83
  84        let registry_subscription = cx.subscribe_in(
  85            &LanguageModelRegistry::global(cx),
  86            window,
  87            |this, _, event: &language_model::Event, window, cx| match event {
  88                language_model::Event::AddedProvider(provider_id) => {
  89                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
  90                    if let Some(provider) = provider {
  91                        this.add_provider_configuration_view(&provider, window, cx);
  92                    }
  93                }
  94                language_model::Event::RemovedProvider(provider_id) => {
  95                    this.remove_provider_configuration_view(provider_id);
  96                }
  97                _ => {}
  98            },
  99        );
 100
 101        cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
 102            .detach();
 103
 104        let mut this = Self {
 105            fs,
 106            language_registry,
 107            workspace,
 108            focus_handle,
 109            configuration_views_by_provider: HashMap::default(),
 110            agent_server_store,
 111            context_server_store,
 112            expanded_provider_configurations: HashMap::default(),
 113            context_server_registry,
 114            _registry_subscription: registry_subscription,
 115            scroll_handle: ScrollHandle::new(),
 116            _check_for_gemini: Task::ready(()),
 117        };
 118        this.build_provider_configuration_views(window, cx);
 119        this
 120    }
 121
 122    fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 123        let providers = LanguageModelRegistry::read_global(cx).visible_providers();
 124        for provider in providers {
 125            self.add_provider_configuration_view(&provider, window, cx);
 126        }
 127    }
 128
 129    fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
 130        self.configuration_views_by_provider.remove(provider_id);
 131        self.expanded_provider_configurations.remove(provider_id);
 132    }
 133
 134    fn add_provider_configuration_view(
 135        &mut self,
 136        provider: &Arc<dyn LanguageModelProvider>,
 137        window: &mut Window,
 138        cx: &mut Context<Self>,
 139    ) {
 140        let configuration_view = provider.configuration_view(
 141            language_model::ConfigurationViewTargetAgent::ZedAgent,
 142            window,
 143            cx,
 144        );
 145        self.configuration_views_by_provider
 146            .insert(provider.id(), configuration_view);
 147    }
 148}
 149
 150impl Focusable for AgentConfiguration {
 151    fn focus_handle(&self, _: &App) -> FocusHandle {
 152        self.focus_handle.clone()
 153    }
 154}
 155
 156pub enum AssistantConfigurationEvent {
 157    NewThread(Arc<dyn LanguageModelProvider>),
 158}
 159
 160impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
 161
 162enum AgentIcon {
 163    Name(IconName),
 164    Path(SharedString),
 165}
 166
 167impl AgentConfiguration {
 168    fn render_section_title(
 169        &mut self,
 170        title: impl Into<SharedString>,
 171        description: impl Into<SharedString>,
 172        menu: AnyElement,
 173    ) -> impl IntoElement {
 174        h_flex()
 175            .p_4()
 176            .pb_0()
 177            .mb_2p5()
 178            .items_start()
 179            .justify_between()
 180            .child(
 181                v_flex()
 182                    .w_full()
 183                    .gap_0p5()
 184                    .child(
 185                        h_flex()
 186                            .pr_1()
 187                            .w_full()
 188                            .gap_2()
 189                            .justify_between()
 190                            .flex_wrap()
 191                            .child(Headline::new(title.into()))
 192                            .child(menu),
 193                    )
 194                    .child(Label::new(description.into()).color(Color::Muted)),
 195            )
 196    }
 197
 198    fn render_provider_configuration_block(
 199        &mut self,
 200        provider: &Arc<dyn LanguageModelProvider>,
 201        cx: &mut Context<Self>,
 202    ) -> impl IntoElement + use<> {
 203        let provider_id = provider.id().0;
 204        let provider_name = provider.name().0;
 205        let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
 206
 207        let configuration_view = self
 208            .configuration_views_by_provider
 209            .get(&provider.id())
 210            .cloned();
 211
 212        let is_expanded = self
 213            .expanded_provider_configurations
 214            .get(&provider.id())
 215            .copied()
 216            .unwrap_or(false);
 217
 218        let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
 219        let current_plan = if is_zed_provider {
 220            self.workspace
 221                .upgrade()
 222                .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
 223        } else {
 224            None
 225        };
 226
 227        let is_signed_in = self
 228            .workspace
 229            .read_with(cx, |workspace, _| {
 230                !workspace.client().status().borrow().is_signed_out()
 231            })
 232            .unwrap_or(false);
 233
 234        v_flex()
 235            .w_full()
 236            .when(is_expanded, |this| this.mb_2())
 237            .child(
 238                div()
 239                    .px_2()
 240                    .child(Divider::horizontal().color(DividerColor::BorderFaded)),
 241            )
 242            .child(
 243                h_flex()
 244                    .map(|this| {
 245                        if is_expanded {
 246                            this.mt_2().mb_1()
 247                        } else {
 248                            this.my_2()
 249                        }
 250                    })
 251                    .w_full()
 252                    .justify_between()
 253                    .child(
 254                        h_flex()
 255                            .id(provider_id_string.clone())
 256                            .px_2()
 257                            .py_0p5()
 258                            .w_full()
 259                            .justify_between()
 260                            .rounded_sm()
 261                            .hover(|hover| hover.bg(cx.theme().colors().element_hover))
 262                            .child(
 263                                h_flex()
 264                                    .w_full()
 265                                    .gap_1p5()
 266                                    .child(
 267                                        match provider.icon() {
 268                                            IconOrSvg::Svg(path) => Icon::from_external_svg(path),
 269                                            IconOrSvg::Icon(name) => Icon::new(name),
 270                                        }
 271                                        .size(IconSize::Small)
 272                                        .color(Color::Muted),
 273                                    )
 274                                    .child(
 275                                        h_flex()
 276                                            .w_full()
 277                                            .gap_1()
 278                                            .child(Label::new(provider_name.clone()))
 279                                            .map(|this| {
 280                                                if is_zed_provider && is_signed_in {
 281                                                    this.child(
 282                                                        self.render_zed_plan_info(current_plan, cx),
 283                                                    )
 284                                                } else {
 285                                                    this.when(
 286                                                        provider.is_authenticated(cx)
 287                                                            && !is_expanded,
 288                                                        |parent| {
 289                                                            parent.child(
 290                                                                Icon::new(IconName::Check)
 291                                                                    .color(Color::Success),
 292                                                            )
 293                                                        },
 294                                                    )
 295                                                }
 296                                            }),
 297                                    ),
 298                            )
 299                            .child(
 300                                Disclosure::new(provider_id_string, is_expanded)
 301                                    .opened_icon(IconName::ChevronUp)
 302                                    .closed_icon(IconName::ChevronDown),
 303                            )
 304                            .on_click(cx.listener({
 305                                let provider_id = provider.id();
 306                                move |this, _event, _window, _cx| {
 307                                    let is_expanded = this
 308                                        .expanded_provider_configurations
 309                                        .entry(provider_id.clone())
 310                                        .or_insert(false);
 311
 312                                    *is_expanded = !*is_expanded;
 313                                }
 314                            })),
 315                    ),
 316            )
 317            .child(
 318                v_flex()
 319                    .w_full()
 320                    .px_2()
 321                    .gap_1()
 322                    .when(is_expanded, |parent| match configuration_view {
 323                        Some(configuration_view) => parent.child(configuration_view),
 324                        None => parent.child(Label::new(format!(
 325                            "No configuration view for {provider_name}",
 326                        ))),
 327                    })
 328                    .when(is_expanded && provider.is_authenticated(cx), |parent| {
 329                        parent.child(
 330                            Button::new(
 331                                SharedString::from(format!("new-thread-{provider_id}")),
 332                                "Start New Thread",
 333                            )
 334                            .full_width()
 335                            .style(ButtonStyle::Outlined)
 336                            .layer(ElevationIndex::ModalSurface)
 337                            .icon_position(IconPosition::Start)
 338                            .icon(IconName::Thread)
 339                            .icon_size(IconSize::Small)
 340                            .icon_color(Color::Muted)
 341                            .label_size(LabelSize::Small)
 342                            .on_click(cx.listener({
 343                                let provider = provider.clone();
 344                                move |_this, _event, _window, cx| {
 345                                    cx.emit(AssistantConfigurationEvent::NewThread(
 346                                        provider.clone(),
 347                                    ))
 348                                }
 349                            })),
 350                        )
 351                    })
 352                    .when(
 353                        is_expanded && is_removable_provider(&provider.id(), cx),
 354                        |this| {
 355                            this.child(
 356                                Button::new(
 357                                    SharedString::from(format!("delete-provider-{provider_id}")),
 358                                    "Remove Provider",
 359                                )
 360                                .full_width()
 361                                .style(ButtonStyle::Outlined)
 362                                .icon_position(IconPosition::Start)
 363                                .icon(IconName::Trash)
 364                                .icon_size(IconSize::Small)
 365                                .icon_color(Color::Muted)
 366                                .label_size(LabelSize::Small)
 367                                .on_click(cx.listener({
 368                                    let provider = provider.clone();
 369                                    move |this, _event, window, cx| {
 370                                        this.delete_provider(provider.clone(), window, cx);
 371                                    }
 372                                })),
 373                            )
 374                        },
 375                    ),
 376            )
 377    }
 378
 379    fn delete_provider(
 380        &mut self,
 381        provider: Arc<dyn LanguageModelProvider>,
 382        window: &mut Window,
 383        cx: &mut Context<Self>,
 384    ) {
 385        let fs = self.fs.clone();
 386        let provider_id = provider.id();
 387
 388        cx.spawn_in(window, async move |_, cx| {
 389            cx.update(|_window, cx| {
 390                update_settings_file(fs.clone(), cx, {
 391                    let provider_id = provider_id.clone();
 392                    move |settings, _| {
 393                        if let Some(ref mut openai_compatible) = settings
 394                            .language_models
 395                            .as_mut()
 396                            .and_then(|lm| lm.openai_compatible.as_mut())
 397                        {
 398                            let key_to_remove: Arc<str> = Arc::from(provider_id.0.as_ref());
 399                            openai_compatible.remove(&key_to_remove);
 400                        }
 401                    }
 402                });
 403            })
 404            .log_err();
 405
 406            cx.update(|_window, cx| {
 407                LanguageModelRegistry::global(cx).update(cx, {
 408                    let provider_id = provider_id.clone();
 409                    move |registry, cx| {
 410                        registry.unregister_provider(provider_id, cx);
 411                    }
 412                })
 413            })
 414            .log_err();
 415
 416            anyhow::Ok(())
 417        })
 418        .detach_and_log_err(cx);
 419    }
 420
 421    fn render_provider_configuration_section(
 422        &mut self,
 423        cx: &mut Context<Self>,
 424    ) -> impl IntoElement {
 425        let providers = LanguageModelRegistry::read_global(cx).visible_providers();
 426
 427        let popover_menu = PopoverMenu::new("add-provider-popover")
 428            .trigger(
 429                Button::new("add-provider", "Add Provider")
 430                    .style(ButtonStyle::Outlined)
 431                    .icon_position(IconPosition::Start)
 432                    .icon(IconName::Plus)
 433                    .icon_size(IconSize::Small)
 434                    .icon_color(Color::Muted)
 435                    .label_size(LabelSize::Small),
 436            )
 437            .menu({
 438                let workspace = self.workspace.clone();
 439                move |window, cx| {
 440                    Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 441                        menu.header("Compatible APIs").entry("OpenAI", None, {
 442                            let workspace = workspace.clone();
 443                            move |window, cx| {
 444                                workspace
 445                                    .update(cx, |workspace, cx| {
 446                                        AddLlmProviderModal::toggle(
 447                                            LlmCompatibleProvider::OpenAi,
 448                                            workspace,
 449                                            window,
 450                                            cx,
 451                                        );
 452                                    })
 453                                    .log_err();
 454                            }
 455                        })
 456                    }))
 457                }
 458            })
 459            .anchor(gpui::Corner::TopRight)
 460            .offset(gpui::Point {
 461                x: px(0.0),
 462                y: px(2.0),
 463            });
 464
 465        v_flex()
 466            .w_full()
 467            .child(self.render_section_title(
 468                "LLM Providers",
 469                "Add at least one provider to use AI-powered features with Zed's native agent.",
 470                popover_menu.into_any_element(),
 471            ))
 472            .child(
 473                div()
 474                    .w_full()
 475                    .pl(DynamicSpacing::Base08.rems(cx))
 476                    .pr(DynamicSpacing::Base20.rems(cx))
 477                    .children(
 478                        providers.into_iter().map(|provider| {
 479                            self.render_provider_configuration_block(&provider, cx)
 480                        }),
 481                    ),
 482            )
 483    }
 484
 485    fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
 486        if let Some(plan) = plan {
 487            let free_chip_bg = cx
 488                .theme()
 489                .colors()
 490                .editor_background
 491                .opacity(0.5)
 492                .blend(cx.theme().colors().text_accent.opacity(0.05));
 493
 494            let pro_chip_bg = cx
 495                .theme()
 496                .colors()
 497                .editor_background
 498                .opacity(0.5)
 499                .blend(cx.theme().colors().text_accent.opacity(0.2));
 500
 501            let (plan_name, label_color, bg_color) = match plan {
 502                Plan::V2(PlanV2::ZedFree) => ("Free", Color::Default, free_chip_bg),
 503                Plan::V2(PlanV2::ZedProTrial) => ("Pro Trial", Color::Accent, pro_chip_bg),
 504                Plan::V2(PlanV2::ZedPro) => ("Pro", Color::Accent, pro_chip_bg),
 505            };
 506
 507            Chip::new(plan_name.to_string())
 508                .bg_color(bg_color)
 509                .label_color(label_color)
 510                .into_any_element()
 511        } else {
 512            div().into_any_element()
 513        }
 514    }
 515
 516    fn render_context_servers_section(
 517        &mut self,
 518        window: &mut Window,
 519        cx: &mut Context<Self>,
 520    ) -> impl IntoElement {
 521        let mut context_server_ids = self
 522            .context_server_store
 523            .read(cx)
 524            .server_ids(cx)
 525            .into_iter()
 526            .collect::<Vec<_>>();
 527
 528        // Sort context servers: ones without mcp-server- prefix first, then prefixed ones
 529        context_server_ids.sort_by(|a, b| {
 530            const MCP_PREFIX: &str = "mcp-server-";
 531            match (a.0.strip_prefix(MCP_PREFIX), b.0.strip_prefix(MCP_PREFIX)) {
 532                // If one has mcp-server- prefix and other doesn't, non-mcp comes first
 533                (Some(_), None) => std::cmp::Ordering::Greater,
 534                (None, Some(_)) => std::cmp::Ordering::Less,
 535                // If both have same prefix status, sort by appropriate key
 536                (Some(a), Some(b)) => a.cmp(b),
 537                (None, None) => a.0.cmp(&b.0),
 538            }
 539        });
 540
 541        let add_server_popover = PopoverMenu::new("add-server-popover")
 542            .trigger(
 543                Button::new("add-server", "Add Server")
 544                    .style(ButtonStyle::Outlined)
 545                    .icon_position(IconPosition::Start)
 546                    .icon(IconName::Plus)
 547                    .icon_size(IconSize::Small)
 548                    .icon_color(Color::Muted)
 549                    .label_size(LabelSize::Small),
 550            )
 551            .menu({
 552                move |window, cx| {
 553                    Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 554                        menu.entry("Add Custom Server", None, {
 555                            |window, cx| {
 556                                window.dispatch_action(crate::AddContextServer.boxed_clone(), cx)
 557                            }
 558                        })
 559                        .entry("Install from Extensions", None, {
 560                            |window, cx| {
 561                                window.dispatch_action(
 562                                    zed_actions::Extensions {
 563                                        category_filter: Some(
 564                                            ExtensionCategoryFilter::ContextServers,
 565                                        ),
 566                                        id: None,
 567                                    }
 568                                    .boxed_clone(),
 569                                    cx,
 570                                )
 571                            }
 572                        })
 573                    }))
 574                }
 575            })
 576            .anchor(gpui::Corner::TopRight)
 577            .offset(gpui::Point {
 578                x: px(0.0),
 579                y: px(2.0),
 580            });
 581
 582        v_flex()
 583            .border_b_1()
 584            .border_color(cx.theme().colors().border)
 585            .child(self.render_section_title(
 586                "Model Context Protocol (MCP) Servers",
 587                "All MCP servers connected directly or via a Zed extension.",
 588                add_server_popover.into_any_element(),
 589            ))
 590            .child(
 591                v_flex()
 592                    .pl_4()
 593                    .pb_4()
 594                    .pr_5()
 595                    .w_full()
 596                    .gap_1()
 597                    .map(|mut parent| {
 598                        if context_server_ids.is_empty() {
 599                            parent.child(
 600                                h_flex()
 601                                    .p_4()
 602                                    .justify_center()
 603                                    .border_1()
 604                                    .border_dashed()
 605                                    .border_color(cx.theme().colors().border.opacity(0.6))
 606                                    .rounded_sm()
 607                                    .child(
 608                                        Label::new("No MCP servers added yet.")
 609                                            .color(Color::Muted)
 610                                            .size(LabelSize::Small),
 611                                    ),
 612                            )
 613                        } else {
 614                            for (index, context_server_id) in
 615                                context_server_ids.into_iter().enumerate()
 616                            {
 617                                if index > 0 {
 618                                    parent = parent.child(
 619                                        Divider::horizontal()
 620                                            .color(DividerColor::BorderFaded)
 621                                            .into_any_element(),
 622                                    );
 623                                }
 624                                parent = parent.child(self.render_context_server(
 625                                    context_server_id,
 626                                    window,
 627                                    cx,
 628                                ));
 629                            }
 630                            parent
 631                        }
 632                    }),
 633            )
 634    }
 635
 636    fn render_context_server(
 637        &self,
 638        context_server_id: ContextServerId,
 639        window: &mut Window,
 640        cx: &mut Context<Self>,
 641    ) -> impl use<> + IntoElement {
 642        let server_status = self
 643            .context_server_store
 644            .read(cx)
 645            .status_for_server(&context_server_id)
 646            .unwrap_or(ContextServerStatus::Stopped);
 647        let server_configuration = self
 648            .context_server_store
 649            .read(cx)
 650            .configuration_for_server(&context_server_id);
 651
 652        let is_running = matches!(server_status, ContextServerStatus::Running);
 653        let item_id = SharedString::from(context_server_id.0.clone());
 654        // Servers without a configuration can only be provided by extensions.
 655        let provided_by_extension = server_configuration.as_ref().is_none_or(|config| {
 656            matches!(
 657                config.as_ref(),
 658                ContextServerConfiguration::Extension { .. }
 659            )
 660        });
 661
 662        let error = if let ContextServerStatus::Error(error) = server_status.clone() {
 663            Some(error)
 664        } else {
 665            None
 666        };
 667
 668        let tool_count = self
 669            .context_server_registry
 670            .read(cx)
 671            .tools_for_server(&context_server_id)
 672            .count();
 673
 674        let (source_icon, source_tooltip) = if provided_by_extension {
 675            (
 676                IconName::ZedSrcExtension,
 677                "This MCP server was installed from an extension.",
 678            )
 679        } else {
 680            (
 681                IconName::ZedSrcCustom,
 682                "This custom MCP server was installed directly.",
 683            )
 684        };
 685
 686        let (status_indicator, tooltip_text) = match server_status {
 687            ContextServerStatus::Starting => (
 688                Icon::new(IconName::LoadCircle)
 689                    .size(IconSize::XSmall)
 690                    .color(Color::Accent)
 691                    .with_keyed_rotate_animation(
 692                        SharedString::from(format!("{}-starting", context_server_id.0)),
 693                        3,
 694                    )
 695                    .into_any_element(),
 696                "Server is starting.",
 697            ),
 698            ContextServerStatus::Running => (
 699                Indicator::dot().color(Color::Success).into_any_element(),
 700                "Server is active.",
 701            ),
 702            ContextServerStatus::Error(_) => (
 703                Indicator::dot().color(Color::Error).into_any_element(),
 704                "Server has an error.",
 705            ),
 706            ContextServerStatus::Stopped => (
 707                Indicator::dot().color(Color::Muted).into_any_element(),
 708                "Server is stopped.",
 709            ),
 710        };
 711        let is_remote = server_configuration
 712            .as_ref()
 713            .map(|config| matches!(config.as_ref(), ContextServerConfiguration::Http { .. }))
 714            .unwrap_or(false);
 715        let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
 716            .trigger_with_tooltip(
 717                IconButton::new("context-server-config-menu", IconName::Settings)
 718                    .icon_color(Color::Muted)
 719                    .icon_size(IconSize::Small),
 720                Tooltip::text("Configure MCP Server"),
 721            )
 722            .anchor(Corner::TopRight)
 723            .menu({
 724                let fs = self.fs.clone();
 725                let context_server_id = context_server_id.clone();
 726                let language_registry = self.language_registry.clone();
 727                let workspace = self.workspace.clone();
 728                let context_server_registry = self.context_server_registry.clone();
 729
 730                move |window, cx| {
 731                    Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 732                        menu.entry("Configure Server", None, {
 733                            let context_server_id = context_server_id.clone();
 734                            let language_registry = language_registry.clone();
 735                            let workspace = workspace.clone();
 736                            move |window, cx| {
 737                                if is_remote {
 738                                    crate::agent_configuration::configure_context_server_modal::ConfigureContextServerModal::show_modal_for_existing_server(
 739                                        context_server_id.clone(),
 740                                        language_registry.clone(),
 741                                        workspace.clone(),
 742                                        window,
 743                                        cx,
 744                                    )
 745                                    .detach();
 746                                } else {
 747                                    ConfigureContextServerModal::show_modal_for_existing_server(
 748                                        context_server_id.clone(),
 749                                        language_registry.clone(),
 750                                        workspace.clone(),
 751                                        window,
 752                                        cx,
 753                                    )
 754                                    .detach();
 755                                }
 756                            }
 757                        }).when(tool_count > 0, |this| this.entry("View Tools", None, {
 758                            let context_server_id = context_server_id.clone();
 759                            let context_server_registry = context_server_registry.clone();
 760                            let workspace = workspace.clone();
 761                            move |window, cx| {
 762                                let context_server_id = context_server_id.clone();
 763                                workspace.update(cx, |workspace, cx| {
 764                                    ConfigureContextServerToolsModal::toggle(
 765                                        context_server_id,
 766                                        context_server_registry.clone(),
 767                                        workspace,
 768                                        window,
 769                                        cx,
 770                                    );
 771                                })
 772                                .ok();
 773                            }
 774                        }))
 775                        .separator()
 776                        .entry("Uninstall", None, {
 777                            let fs = fs.clone();
 778                            let context_server_id = context_server_id.clone();
 779                            let workspace = workspace.clone();
 780                            move |_, cx| {
 781                                let uninstall_extension_task = match (
 782                                    provided_by_extension,
 783                                    resolve_extension_for_context_server(&context_server_id, cx),
 784                                ) {
 785                                    (true, Some((id, manifest))) => {
 786                                        if extension_only_provides_context_server(manifest.as_ref())
 787                                        {
 788                                            ExtensionStore::global(cx).update(cx, |store, cx| {
 789                                                store.uninstall_extension(id, cx)
 790                                            })
 791                                        } else {
 792                                            workspace.update(cx, |workspace, cx| {
 793                                                show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
 794                                            }).log_err();
 795                                            Task::ready(Ok(()))
 796                                        }
 797                                    }
 798                                    _ => Task::ready(Ok(())),
 799                                };
 800
 801                                cx.spawn({
 802                                    let fs = fs.clone();
 803                                    let context_server_id = context_server_id.clone();
 804                                    async move |cx| {
 805                                        uninstall_extension_task.await?;
 806                                        cx.update(|cx| {
 807                                            update_settings_file(
 808                                                fs.clone(),
 809                                                cx,
 810                                                {
 811                                                    let context_server_id =
 812                                                        context_server_id.clone();
 813                                                    move |settings, _| {
 814                                                        settings.project
 815                                                            .context_servers
 816                                                            .remove(&context_server_id.0);
 817                                                    }
 818                                                },
 819                                            )
 820                                        });
 821                                        anyhow::Ok(())
 822                                    }
 823                                })
 824                                .detach_and_log_err(cx);
 825                            }
 826                        })
 827                    }))
 828                }
 829            });
 830
 831        v_flex()
 832            .id(item_id.clone())
 833            .child(
 834                h_flex()
 835                    .justify_between()
 836                    .child(
 837                        h_flex()
 838                            .flex_1()
 839                            .min_w_0()
 840                            .child(
 841                                h_flex()
 842                                    .id(format!("tooltip-{}", item_id))
 843                                    .h_full()
 844                                    .w_3()
 845                                    .mr_2()
 846                                    .justify_center()
 847                                    .tooltip(Tooltip::text(tooltip_text))
 848                                    .child(status_indicator),
 849                            )
 850                            .child(Label::new(item_id).truncate())
 851                            .child(
 852                                div()
 853                                    .id("extension-source")
 854                                    .mt_0p5()
 855                                    .mx_1()
 856                                    .flex_none()
 857                                    .tooltip(Tooltip::text(source_tooltip))
 858                                    .child(
 859                                        Icon::new(source_icon)
 860                                            .size(IconSize::Small)
 861                                            .color(Color::Muted),
 862                                    ),
 863                            )
 864                            .when(is_running, |this| {
 865                                this.child(
 866                                    Label::new(if tool_count == 1 {
 867                                        SharedString::from("1 tool")
 868                                    } else {
 869                                        SharedString::from(format!("{} tools", tool_count))
 870                                    })
 871                                    .color(Color::Muted)
 872                                    .size(LabelSize::Small),
 873                                )
 874                            }),
 875                    )
 876                    .child(
 877                        h_flex()
 878                            .gap_0p5()
 879                            .flex_none()
 880                            .child(context_server_configuration_menu)
 881                            .child(
 882                            Switch::new("context-server-switch", is_running.into())
 883                                .on_click({
 884                                    let context_server_manager = self.context_server_store.clone();
 885                                    let fs = self.fs.clone();
 886
 887                                    move |state, _window, cx| {
 888                                        let is_enabled = match state {
 889                                            ToggleState::Unselected
 890                                            | ToggleState::Indeterminate => {
 891                                                context_server_manager.update(cx, |this, cx| {
 892                                                    this.stop_server(&context_server_id, cx)
 893                                                        .log_err();
 894                                                });
 895                                                false
 896                                            }
 897                                            ToggleState::Selected => {
 898                                                context_server_manager.update(cx, |this, cx| {
 899                                                    if let Some(server) =
 900                                                        this.get_server(&context_server_id)
 901                                                    {
 902                                                        this.start_server(server, cx);
 903                                                    }
 904                                                });
 905                                                true
 906                                            }
 907                                        };
 908                                        update_settings_file(fs.clone(), cx, {
 909                                            let context_server_id = context_server_id.clone();
 910
 911                                            move |settings, _| {
 912                                                settings
 913                                                    .project
 914                                                    .context_servers
 915                                                    .entry(context_server_id.0)
 916                                                    .or_insert_with(|| {
 917                                                        settings::ContextServerSettingsContent::Extension {
 918                                                            enabled: is_enabled,
 919                                                            remote: false,
 920                                                            settings: serde_json::json!({}),
 921                                                        }
 922                                                    })
 923                                                    .set_enabled(is_enabled);
 924                                            }
 925                                        });
 926                                    }
 927                                }),
 928                        ),
 929                    ),
 930            )
 931            .map(|parent| {
 932                if let Some(error) = error {
 933                    return parent.child(
 934                        h_flex()
 935                            .gap_2()
 936                            .pr_4()
 937                            .items_start()
 938                            .child(
 939                                h_flex()
 940                                    .flex_none()
 941                                    .h(window.line_height() / 1.6_f32)
 942                                    .justify_center()
 943                                    .child(
 944                                        Icon::new(IconName::XCircle)
 945                                            .size(IconSize::XSmall)
 946                                            .color(Color::Error),
 947                                    ),
 948                            )
 949                            .child(
 950                                div().w_full().child(
 951                                    Label::new(error)
 952                                        .buffer_font(cx)
 953                                        .color(Color::Muted)
 954                                        .size(LabelSize::Small),
 955                                ),
 956                            ),
 957                    );
 958                }
 959                parent
 960            })
 961    }
 962
 963    fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 964        let agent_server_store = self.agent_server_store.read(cx);
 965
 966        let user_defined_agents = agent_server_store
 967            .external_agents()
 968            .filter(|name| {
 969                name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME && name.0 != CODEX_NAME
 970            })
 971            .cloned()
 972            .collect::<Vec<_>>();
 973
 974        let user_defined_agents: Vec<_> = user_defined_agents
 975            .into_iter()
 976            .map(|name| {
 977                let icon = if let Some(icon_path) = agent_server_store.agent_icon(&name) {
 978                    AgentIcon::Path(icon_path)
 979                } else {
 980                    AgentIcon::Name(IconName::Sparkle)
 981                };
 982                let display_name = agent_server_store
 983                    .agent_display_name(&name)
 984                    .unwrap_or_else(|| name.0.clone());
 985                let source = agent_server_store.agent_source(&name).unwrap_or_default();
 986                (name, icon, display_name, source)
 987            })
 988            .collect();
 989
 990        let add_agent_popover = PopoverMenu::new("add-agent-server-popover")
 991            .trigger(
 992                Button::new("add-agent", "Add Agent")
 993                    .style(ButtonStyle::Outlined)
 994                    .icon_position(IconPosition::Start)
 995                    .icon(IconName::Plus)
 996                    .icon_size(IconSize::Small)
 997                    .icon_color(Color::Muted)
 998                    .label_size(LabelSize::Small),
 999            )
1000            .menu({
1001                move |window, cx| {
1002                    Some(ContextMenu::build(window, cx, |mut menu, _window, _cx| {
1003                        if _cx.has_flag::<AcpBetaFeatureFlag>() {
1004                            menu = menu.entry("Install from Registry", None, {
1005                                |window, cx| {
1006                                    window.dispatch_action(Box::new(zed_actions::AgentRegistry), cx)
1007                                }
1008                            });
1009                        }
1010                        menu.entry("Install from Extensions", None, {
1011                            |window, cx| {
1012                                window.dispatch_action(
1013                                    zed_actions::Extensions {
1014                                        category_filter: Some(
1015                                            ExtensionCategoryFilter::AgentServers,
1016                                        ),
1017                                        id: None,
1018                                    }
1019                                    .boxed_clone(),
1020                                    cx,
1021                                )
1022                            }
1023                        })
1024                        .entry("Add Custom Agent", None, {
1025                            move |window, cx| {
1026                                if let Some(workspace) = window.root().flatten() {
1027                                    let workspace = workspace.downgrade();
1028                                    window
1029                                        .spawn(cx, async |cx| {
1030                                            open_new_agent_servers_entry_in_settings_editor(
1031                                                workspace, cx,
1032                                            )
1033                                            .await
1034                                        })
1035                                        .detach_and_log_err(cx);
1036                                }
1037                            }
1038                        })
1039                        .separator()
1040                        .header("Learn More")
1041                        .item(
1042                            ContextMenuEntry::new("Agent Servers Docs")
1043                                .icon(IconName::ArrowUpRight)
1044                                .icon_color(Color::Muted)
1045                                .icon_position(IconPosition::End)
1046                                .handler({
1047                                    move |window, cx| {
1048                                        window.dispatch_action(
1049                                            Box::new(OpenBrowser {
1050                                                url: zed_urls::agent_server_docs(cx),
1051                                            }),
1052                                            cx,
1053                                        );
1054                                    }
1055                                }),
1056                        )
1057                        .item(
1058                            ContextMenuEntry::new("ACP Docs")
1059                                .icon(IconName::ArrowUpRight)
1060                                .icon_color(Color::Muted)
1061                                .icon_position(IconPosition::End)
1062                                .handler({
1063                                    move |window, cx| {
1064                                        window.dispatch_action(
1065                                            Box::new(OpenBrowser {
1066                                                url: "https://agentclientprotocol.com/".into(),
1067                                            }),
1068                                            cx,
1069                                        );
1070                                    }
1071                                }),
1072                        )
1073                    }))
1074                }
1075            })
1076            .anchor(gpui::Corner::TopRight)
1077            .offset(gpui::Point {
1078                x: px(0.0),
1079                y: px(2.0),
1080            });
1081
1082        v_flex()
1083            .border_b_1()
1084            .border_color(cx.theme().colors().border)
1085            .child(
1086                v_flex()
1087                    .child(self.render_section_title(
1088                        "External Agents",
1089                        "All agents connected through the Agent Client Protocol.",
1090                        add_agent_popover.into_any_element(),
1091                    ))
1092                    .child(
1093                        v_flex()
1094                            .p_4()
1095                            .pt_0()
1096                            .gap_2()
1097                            .child(self.render_agent_server(
1098                                AgentIcon::Name(IconName::AiClaude),
1099                                "Claude Code",
1100                                "Claude Code",
1101                                ExternalAgentSource::Builtin,
1102                                cx,
1103                            ))
1104                            .child(Divider::horizontal().color(DividerColor::BorderFaded))
1105                            .child(self.render_agent_server(
1106                                AgentIcon::Name(IconName::AiOpenAi),
1107                                "Codex CLI",
1108                                "Codex CLI",
1109                                ExternalAgentSource::Builtin,
1110                                cx,
1111                            ))
1112                            .child(Divider::horizontal().color(DividerColor::BorderFaded))
1113                            .child(self.render_agent_server(
1114                                AgentIcon::Name(IconName::AiGemini),
1115                                "Gemini CLI",
1116                                "Gemini CLI",
1117                                ExternalAgentSource::Builtin,
1118                                cx,
1119                            ))
1120                            .map(|mut parent| {
1121                                for (name, icon, display_name, source) in user_defined_agents {
1122                                    parent = parent
1123                                        .child(
1124                                            Divider::horizontal().color(DividerColor::BorderFaded),
1125                                        )
1126                                        .child(self.render_agent_server(
1127                                            icon,
1128                                            name,
1129                                            display_name,
1130                                            source,
1131                                            cx,
1132                                        ));
1133                                }
1134                                parent
1135                            }),
1136                    ),
1137            )
1138    }
1139
1140    fn render_agent_server(
1141        &self,
1142        icon: AgentIcon,
1143        id: impl Into<SharedString>,
1144        display_name: impl Into<SharedString>,
1145        source: ExternalAgentSource,
1146        cx: &mut Context<Self>,
1147    ) -> impl IntoElement {
1148        let id = id.into();
1149        let display_name = display_name.into();
1150
1151        let icon = match icon {
1152            AgentIcon::Name(icon_name) => Icon::new(icon_name)
1153                .size(IconSize::Small)
1154                .color(Color::Muted),
1155            AgentIcon::Path(icon_path) => Icon::from_external_svg(icon_path)
1156                .size(IconSize::Small)
1157                .color(Color::Muted),
1158        };
1159
1160        let source_badge = match source {
1161            ExternalAgentSource::Extension => Some((
1162                SharedString::new(format!("agent-source-{}", id)),
1163                SharedString::from(format!(
1164                    "The {} agent was installed from an extension.",
1165                    display_name
1166                )),
1167                IconName::ZedSrcExtension,
1168            )),
1169            ExternalAgentSource::Registry => Some((
1170                SharedString::new(format!("agent-source-{}", id)),
1171                SharedString::from(format!(
1172                    "The {} agent was installed from the ACP registry.",
1173                    display_name
1174                )),
1175                IconName::AcpRegistry,
1176            )),
1177            ExternalAgentSource::Builtin | ExternalAgentSource::Custom => None,
1178        };
1179
1180        let agent_server_name = ExternalAgentServerName(id.clone());
1181
1182        let uninstall_button = match source {
1183            ExternalAgentSource::Extension => Some(
1184                IconButton::new(
1185                    SharedString::from(format!("uninstall-{}", id)),
1186                    IconName::Trash,
1187                )
1188                .icon_color(Color::Muted)
1189                .icon_size(IconSize::Small)
1190                .tooltip(Tooltip::text("Uninstall Agent Extension"))
1191                .on_click(cx.listener(move |this, _, _window, cx| {
1192                    let agent_name = agent_server_name.clone();
1193
1194                    if let Some(ext_id) = this.agent_server_store.update(cx, |store, _cx| {
1195                        store.get_extension_id_for_agent(&agent_name)
1196                    }) {
1197                        ExtensionStore::global(cx)
1198                            .update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
1199                            .detach_and_log_err(cx);
1200                    }
1201                })),
1202            ),
1203            ExternalAgentSource::Registry => {
1204                let fs = self.fs.clone();
1205                Some(
1206                    IconButton::new(
1207                        SharedString::from(format!("uninstall-{}", id)),
1208                        IconName::Trash,
1209                    )
1210                    .icon_color(Color::Muted)
1211                    .icon_size(IconSize::Small)
1212                    .tooltip(Tooltip::text("Remove Registry Agent"))
1213                    .on_click(cx.listener(move |_, _, _window, cx| {
1214                        let agent_name = agent_server_name.clone();
1215                        update_settings_file(fs.clone(), cx, move |settings, _| {
1216                            let Some(agent_servers) = settings.agent_servers.as_mut() else {
1217                                return;
1218                            };
1219                            if let Some(entry) = agent_servers.custom.get(agent_name.0.as_ref())
1220                                && matches!(
1221                                    entry,
1222                                    settings::CustomAgentServerSettings::Registry { .. }
1223                                )
1224                            {
1225                                agent_servers.custom.remove(agent_name.0.as_ref());
1226                            }
1227                        });
1228                    })),
1229                )
1230            }
1231            ExternalAgentSource::Builtin | ExternalAgentSource::Custom => None,
1232        };
1233
1234        h_flex()
1235            .gap_1()
1236            .justify_between()
1237            .child(
1238                h_flex()
1239                    .gap_1p5()
1240                    .child(icon)
1241                    .child(Label::new(display_name))
1242                    .when_some(source_badge, |this, (tooltip_id, tooltip_message, icon)| {
1243                        this.child(
1244                            div()
1245                                .id(tooltip_id)
1246                                .flex_none()
1247                                .tooltip(Tooltip::text(tooltip_message))
1248                                .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted)),
1249                        )
1250                    })
1251                    .child(
1252                        Icon::new(IconName::Check)
1253                            .color(Color::Success)
1254                            .size(IconSize::Small),
1255                    ),
1256            )
1257            .when_some(uninstall_button, |this, uninstall_button| {
1258                this.child(uninstall_button)
1259            })
1260    }
1261}
1262
1263impl Render for AgentConfiguration {
1264    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1265        v_flex()
1266            .id("assistant-configuration")
1267            .key_context("AgentConfiguration")
1268            .track_focus(&self.focus_handle(cx))
1269            .relative()
1270            .size_full()
1271            .pb_8()
1272            .bg(cx.theme().colors().panel_background)
1273            .child(
1274                div()
1275                    .size_full()
1276                    .child(
1277                        v_flex()
1278                            .id("assistant-configuration-content")
1279                            .track_scroll(&self.scroll_handle)
1280                            .size_full()
1281                            .overflow_y_scroll()
1282                            .child(self.render_agent_servers_section(cx))
1283                            .child(self.render_context_servers_section(window, cx))
1284                            .child(self.render_provider_configuration_section(cx)),
1285                    )
1286                    .vertical_scrollbar_for(&self.scroll_handle, window, cx),
1287            )
1288    }
1289}
1290
1291fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1292    manifest.context_servers.len() == 1
1293        && manifest.themes.is_empty()
1294        && manifest.icon_themes.is_empty()
1295        && manifest.languages.is_empty()
1296        && manifest.grammars.is_empty()
1297        && manifest.language_servers.is_empty()
1298        && manifest.slash_commands.is_empty()
1299        && manifest.snippets.is_none()
1300        && manifest.debug_locators.is_empty()
1301}
1302
1303pub(crate) fn resolve_extension_for_context_server(
1304    id: &ContextServerId,
1305    cx: &App,
1306) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1307    ExtensionStore::global(cx)
1308        .read(cx)
1309        .installed_extensions()
1310        .iter()
1311        .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1312        .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1313}
1314
1315// This notification appears when trying to delete
1316// an MCP server extension that not only provides
1317// the server, but other things, too, like language servers and more.
1318fn show_unable_to_uninstall_extension_with_context_server(
1319    workspace: &mut Workspace,
1320    id: ContextServerId,
1321    cx: &mut App,
1322) {
1323    let workspace_handle = workspace.weak_handle();
1324    let context_server_id = id.clone();
1325
1326    let status_toast = StatusToast::new(
1327        format!(
1328            "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1329            id.0
1330        ),
1331        cx,
1332        move |this, _cx| {
1333            let workspace_handle = workspace_handle.clone();
1334
1335            this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1336                .dismiss_button(true)
1337                .action("Uninstall", move |_, _cx| {
1338                    if let Some((extension_id, _)) =
1339                        resolve_extension_for_context_server(&context_server_id, _cx)
1340                    {
1341                        ExtensionStore::global(_cx).update(_cx, |store, cx| {
1342                            store
1343                                .uninstall_extension(extension_id, cx)
1344                                .detach_and_log_err(cx);
1345                        });
1346
1347                        workspace_handle
1348                            .update(_cx, |workspace, cx| {
1349                                let fs = workspace.app_state().fs.clone();
1350                                cx.spawn({
1351                                    let context_server_id = context_server_id.clone();
1352                                    async move |_workspace_handle, cx| {
1353                                        cx.update(|cx| {
1354                                            update_settings_file(fs, cx, move |settings, _| {
1355                                                settings
1356                                                    .project
1357                                                    .context_servers
1358                                                    .remove(&context_server_id.0);
1359                                            });
1360                                        });
1361                                        anyhow::Ok(())
1362                                    }
1363                                })
1364                                .detach_and_log_err(cx);
1365                            })
1366                            .log_err();
1367                    }
1368                })
1369        },
1370    );
1371
1372    workspace.toggle_status_toast(status_toast, cx);
1373}
1374
1375async fn open_new_agent_servers_entry_in_settings_editor(
1376    workspace: WeakEntity<Workspace>,
1377    cx: &mut AsyncWindowContext,
1378) -> Result<()> {
1379    let settings_editor = workspace
1380        .update_in(cx, |_, window, cx| {
1381            create_and_open_local_file(paths::settings_file(), window, cx, || {
1382                settings::initial_user_settings_content().as_ref().into()
1383            })
1384        })?
1385        .await?
1386        .downcast::<Editor>()
1387        .unwrap();
1388
1389    settings_editor
1390        .downgrade()
1391        .update_in(cx, |item, window, cx| {
1392            let text = item.buffer().read(cx).snapshot(cx).text();
1393
1394            let settings = cx.global::<SettingsStore>();
1395
1396            let mut unique_server_name = None;
1397            let edits = settings.edits_for_update(&text, |settings| {
1398                let server_name: Option<String> = (0..u8::MAX)
1399                    .map(|i| {
1400                        if i == 0 {
1401                            "your_agent".to_string()
1402                        } else {
1403                            format!("your_agent_{}", i)
1404                        }
1405                    })
1406                    .find(|name| {
1407                        !settings
1408                            .agent_servers
1409                            .as_ref()
1410                            .is_some_and(|agent_servers| {
1411                                agent_servers.custom.contains_key(name.as_str())
1412                            })
1413                    });
1414                if let Some(server_name) = server_name {
1415                    unique_server_name = Some(SharedString::from(server_name.clone()));
1416                    settings
1417                        .agent_servers
1418                        .get_or_insert_default()
1419                        .custom
1420                        .insert(
1421                            server_name,
1422                            settings::CustomAgentServerSettings::Custom {
1423                                path: "path_to_executable".into(),
1424                                args: vec![],
1425                                env: HashMap::default(),
1426                                default_mode: None,
1427                                default_model: None,
1428                                favorite_models: vec![],
1429                                default_config_options: Default::default(),
1430                                favorite_config_option_values: Default::default(),
1431                            },
1432                        );
1433                }
1434            });
1435
1436            if edits.is_empty() {
1437                return;
1438            }
1439
1440            let ranges = edits
1441                .iter()
1442                .map(|(range, _)| range.clone())
1443                .collect::<Vec<_>>();
1444
1445            item.edit(
1446                edits.into_iter().map(|(range, s)| {
1447                    (
1448                        MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1449                        s,
1450                    )
1451                }),
1452                cx,
1453            );
1454            if let Some((unique_server_name, buffer)) =
1455                unique_server_name.zip(item.buffer().read(cx).as_singleton())
1456            {
1457                let snapshot = buffer.read(cx).snapshot();
1458                if let Some(range) =
1459                    find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1460                {
1461                    item.change_selections(
1462                        SelectionEffects::scroll(Autoscroll::newest()),
1463                        window,
1464                        cx,
1465                        |selections| {
1466                            selections.select_ranges(vec![
1467                                MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1468                            ]);
1469                        },
1470                    );
1471                }
1472            }
1473        })
1474}
1475
1476fn find_text_in_buffer(
1477    text: &str,
1478    start: usize,
1479    snapshot: &language::BufferSnapshot,
1480) -> Option<Range<usize>> {
1481    let chars = text.chars().collect::<Vec<char>>();
1482
1483    let mut offset = start;
1484    let mut char_offset = 0;
1485    for c in snapshot.chars_at(start) {
1486        if char_offset >= chars.len() {
1487            break;
1488        }
1489        offset += 1;
1490
1491        if c == chars[char_offset] {
1492            char_offset += 1;
1493        } else {
1494            char_offset = 0;
1495        }
1496    }
1497
1498    if char_offset == chars.len() {
1499        Some(offset.saturating_sub(chars.len())..offset)
1500    } else {
1501        None
1502    }
1503}
1504
1505// OpenAI-compatible providers are user-configured and can be removed,
1506// whereas built-in providers (like Anthropic, OpenAI, Google, etc.) can't.
1507//
1508// If in the future we have more "API-compatible-type" of providers,
1509// they should be included here as removable providers.
1510fn is_removable_provider(provider_id: &LanguageModelProviderId, cx: &App) -> bool {
1511    AllLanguageModelSettings::get_global(cx)
1512        .openai_compatible
1513        .contains_key(provider_id.0.as_ref())
1514}