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_api_types::Plan;
  13use collections::HashMap;
  14use context_server::ContextServerId;
  15use editor::{Editor, MultiBufferOffset, SelectionEffects, scroll::Autoscroll};
  16use extension::ExtensionManifest;
  17use extension_host::ExtensionStore;
  18use fs::Fs;
  19use gpui::{
  20    Action, AnyView, App, AsyncWindowContext, Corner, Entity, EventEmitter, FocusHandle, Focusable,
  21    ScrollHandle, Subscription, Task, WeakEntity,
  22};
  23use language::LanguageRegistry;
  24use language_model::{
  25    IconOrSvg, LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry,
  26    ZED_CLOUD_PROVIDER_ID,
  27};
  28use language_models::AllLanguageModelSettings;
  29use notifications::status_toast::{StatusToast, ToastIcon};
  30use project::{
  31    agent_server_store::{
  32        AgentServerStore, CLAUDE_CODE_NAME, CODEX_NAME, ExternalAgentServerName,
  33        ExternalAgentSource, GEMINI_NAME,
  34    },
  35    context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
  36};
  37use settings::{Settings, SettingsStore, update_settings_file};
  38use ui::{
  39    ButtonStyle, Chip, CommonAnimationExt, ContextMenu, ContextMenuEntry, Disclosure, Divider,
  40    DividerColor, ElevationIndex, Indicator, LabelSize, PopoverMenu, Switch, Tooltip,
  41    WithScrollbar, prelude::*,
  42};
  43use util::ResultExt as _;
  44use workspace::{Workspace, create_and_open_local_file};
  45use zed_actions::{ExtensionCategoryFilter, OpenBrowser};
  46
  47pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
  48pub(crate) use configure_context_server_tools_modal::ConfigureContextServerToolsModal;
  49pub(crate) use manage_profiles_modal::ManageProfilesModal;
  50
  51use crate::agent_configuration::add_llm_provider_modal::{
  52    AddLlmProviderModal, LlmCompatibleProvider,
  53};
  54
  55pub struct AgentConfiguration {
  56    fs: Arc<dyn Fs>,
  57    language_registry: Arc<LanguageRegistry>,
  58    agent_server_store: Entity<AgentServerStore>,
  59    workspace: WeakEntity<Workspace>,
  60    focus_handle: FocusHandle,
  61    configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
  62    context_server_store: Entity<ContextServerStore>,
  63    expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
  64    context_server_registry: Entity<ContextServerRegistry>,
  65    _registry_subscription: Subscription,
  66    scroll_handle: ScrollHandle,
  67    _check_for_gemini: Task<()>,
  68}
  69
  70impl AgentConfiguration {
  71    pub fn new(
  72        fs: Arc<dyn Fs>,
  73        agent_server_store: Entity<AgentServerStore>,
  74        context_server_store: Entity<ContextServerStore>,
  75        context_server_registry: Entity<ContextServerRegistry>,
  76        language_registry: Arc<LanguageRegistry>,
  77        workspace: WeakEntity<Workspace>,
  78        window: &mut Window,
  79        cx: &mut Context<Self>,
  80    ) -> Self {
  81        let focus_handle = cx.focus_handle();
  82
  83        let registry_subscription = cx.subscribe_in(
  84            &LanguageModelRegistry::global(cx),
  85            window,
  86            |this, _, event: &language_model::Event, window, cx| match event {
  87                language_model::Event::AddedProvider(provider_id) => {
  88                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
  89                    if let Some(provider) = provider {
  90                        this.add_provider_configuration_view(&provider, window, cx);
  91                    }
  92                }
  93                language_model::Event::RemovedProvider(provider_id) => {
  94                    this.remove_provider_configuration_view(provider_id);
  95                }
  96                _ => {}
  97            },
  98        );
  99
 100        cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
 101            .detach();
 102
 103        let mut this = Self {
 104            fs,
 105            language_registry,
 106            workspace,
 107            focus_handle,
 108            configuration_views_by_provider: HashMap::default(),
 109            agent_server_store,
 110            context_server_store,
 111            expanded_provider_configurations: HashMap::default(),
 112            context_server_registry,
 113            _registry_subscription: registry_subscription,
 114            scroll_handle: ScrollHandle::new(),
 115            _check_for_gemini: Task::ready(()),
 116        };
 117        this.build_provider_configuration_views(window, cx);
 118        this
 119    }
 120
 121    fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 122        let providers = LanguageModelRegistry::read_global(cx).visible_providers();
 123        for provider in providers {
 124            self.add_provider_configuration_view(&provider, window, cx);
 125        }
 126    }
 127
 128    fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
 129        self.configuration_views_by_provider.remove(provider_id);
 130        self.expanded_provider_configurations.remove(provider_id);
 131    }
 132
 133    fn add_provider_configuration_view(
 134        &mut self,
 135        provider: &Arc<dyn LanguageModelProvider>,
 136        window: &mut Window,
 137        cx: &mut Context<Self>,
 138    ) {
 139        let configuration_view = provider.configuration_view(
 140            language_model::ConfigurationViewTargetAgent::ZedAgent,
 141            window,
 142            cx,
 143        );
 144        self.configuration_views_by_provider
 145            .insert(provider.id(), configuration_view);
 146    }
 147}
 148
 149impl Focusable for AgentConfiguration {
 150    fn focus_handle(&self, _: &App) -> FocusHandle {
 151        self.focus_handle.clone()
 152    }
 153}
 154
 155pub enum AssistantConfigurationEvent {
 156    NewThread(Arc<dyn LanguageModelProvider>),
 157}
 158
 159impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
 160
 161enum AgentIcon {
 162    Name(IconName),
 163    Path(SharedString),
 164}
 165
 166impl AgentConfiguration {
 167    fn render_section_title(
 168        &mut self,
 169        title: impl Into<SharedString>,
 170        description: impl Into<SharedString>,
 171        menu: AnyElement,
 172    ) -> impl IntoElement {
 173        h_flex()
 174            .p_4()
 175            .pb_0()
 176            .mb_2p5()
 177            .items_start()
 178            .justify_between()
 179            .child(
 180                v_flex()
 181                    .w_full()
 182                    .gap_0p5()
 183                    .child(
 184                        h_flex()
 185                            .pr_1()
 186                            .w_full()
 187                            .gap_2()
 188                            .justify_between()
 189                            .flex_wrap()
 190                            .child(Headline::new(title.into()))
 191                            .child(menu),
 192                    )
 193                    .child(Label::new(description.into()).color(Color::Muted)),
 194            )
 195    }
 196
 197    fn render_provider_configuration_block(
 198        &mut self,
 199        provider: &Arc<dyn LanguageModelProvider>,
 200        cx: &mut Context<Self>,
 201    ) -> impl IntoElement + use<> {
 202        let provider_id = provider.id().0;
 203        let provider_name = provider.name().0;
 204        let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
 205
 206        let configuration_view = self
 207            .configuration_views_by_provider
 208            .get(&provider.id())
 209            .cloned();
 210
 211        let is_expanded = self
 212            .expanded_provider_configurations
 213            .get(&provider.id())
 214            .copied()
 215            .unwrap_or(false);
 216
 217        let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
 218        let current_plan = if is_zed_provider {
 219            self.workspace
 220                .upgrade()
 221                .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
 222        } else {
 223            None
 224        };
 225
 226        let is_signed_in = self
 227            .workspace
 228            .read_with(cx, |workspace, _| {
 229                !workspace.client().status().borrow().is_signed_out()
 230            })
 231            .unwrap_or(false);
 232
 233        v_flex()
 234            .w_full()
 235            .when(is_expanded, |this| this.mb_2())
 236            .child(
 237                div()
 238                    .px_2()
 239                    .child(Divider::horizontal().color(DividerColor::BorderFaded)),
 240            )
 241            .child(
 242                h_flex()
 243                    .map(|this| {
 244                        if is_expanded {
 245                            this.mt_2().mb_1()
 246                        } else {
 247                            this.my_2()
 248                        }
 249                    })
 250                    .w_full()
 251                    .justify_between()
 252                    .child(
 253                        h_flex()
 254                            .id(provider_id_string.clone())
 255                            .px_2()
 256                            .py_0p5()
 257                            .w_full()
 258                            .justify_between()
 259                            .rounded_sm()
 260                            .hover(|hover| hover.bg(cx.theme().colors().element_hover))
 261                            .child(
 262                                h_flex()
 263                                    .w_full()
 264                                    .gap_1p5()
 265                                    .child(
 266                                        match provider.icon() {
 267                                            IconOrSvg::Svg(path) => Icon::from_external_svg(path),
 268                                            IconOrSvg::Icon(name) => Icon::new(name),
 269                                        }
 270                                        .size(IconSize::Small)
 271                                        .color(Color::Muted),
 272                                    )
 273                                    .child(
 274                                        h_flex()
 275                                            .w_full()
 276                                            .gap_1()
 277                                            .child(Label::new(provider_name.clone()))
 278                                            .map(|this| {
 279                                                if is_zed_provider && is_signed_in {
 280                                                    this.child(
 281                                                        self.render_zed_plan_info(current_plan, cx),
 282                                                    )
 283                                                } else {
 284                                                    this.when(
 285                                                        provider.is_authenticated(cx)
 286                                                            && !is_expanded,
 287                                                        |parent| {
 288                                                            parent.child(
 289                                                                Icon::new(IconName::Check)
 290                                                                    .color(Color::Success),
 291                                                            )
 292                                                        },
 293                                                    )
 294                                                }
 295                                            }),
 296                                    ),
 297                            )
 298                            .child(
 299                                Disclosure::new(provider_id_string, is_expanded)
 300                                    .opened_icon(IconName::ChevronUp)
 301                                    .closed_icon(IconName::ChevronDown),
 302                            )
 303                            .on_click(cx.listener({
 304                                let provider_id = provider.id();
 305                                move |this, _event, _window, _cx| {
 306                                    let is_expanded = this
 307                                        .expanded_provider_configurations
 308                                        .entry(provider_id.clone())
 309                                        .or_insert(false);
 310
 311                                    *is_expanded = !*is_expanded;
 312                                }
 313                            })),
 314                    ),
 315            )
 316            .child(
 317                v_flex()
 318                    .w_full()
 319                    .px_2()
 320                    .gap_1()
 321                    .when(is_expanded, |parent| match configuration_view {
 322                        Some(configuration_view) => parent.child(configuration_view),
 323                        None => parent.child(Label::new(format!(
 324                            "No configuration view for {provider_name}",
 325                        ))),
 326                    })
 327                    .when(is_expanded && provider.is_authenticated(cx), |parent| {
 328                        parent.child(
 329                            Button::new(
 330                                SharedString::from(format!("new-thread-{provider_id}")),
 331                                "Start New Thread",
 332                            )
 333                            .full_width()
 334                            .style(ButtonStyle::Outlined)
 335                            .layer(ElevationIndex::ModalSurface)
 336                            .icon_position(IconPosition::Start)
 337                            .icon(IconName::Thread)
 338                            .icon_size(IconSize::Small)
 339                            .icon_color(Color::Muted)
 340                            .label_size(LabelSize::Small)
 341                            .on_click(cx.listener({
 342                                let provider = provider.clone();
 343                                move |_this, _event, _window, cx| {
 344                                    cx.emit(AssistantConfigurationEvent::NewThread(
 345                                        provider.clone(),
 346                                    ))
 347                                }
 348                            })),
 349                        )
 350                    })
 351                    .when(
 352                        is_expanded && is_removable_provider(&provider.id(), cx),
 353                        |this| {
 354                            this.child(
 355                                Button::new(
 356                                    SharedString::from(format!("delete-provider-{provider_id}")),
 357                                    "Remove Provider",
 358                                )
 359                                .full_width()
 360                                .style(ButtonStyle::Outlined)
 361                                .icon_position(IconPosition::Start)
 362                                .icon(IconName::Trash)
 363                                .icon_size(IconSize::Small)
 364                                .icon_color(Color::Muted)
 365                                .label_size(LabelSize::Small)
 366                                .on_click(cx.listener({
 367                                    let provider = provider.clone();
 368                                    move |this, _event, window, cx| {
 369                                        this.delete_provider(provider.clone(), window, cx);
 370                                    }
 371                                })),
 372                            )
 373                        },
 374                    ),
 375            )
 376    }
 377
 378    fn delete_provider(
 379        &mut self,
 380        provider: Arc<dyn LanguageModelProvider>,
 381        window: &mut Window,
 382        cx: &mut Context<Self>,
 383    ) {
 384        let fs = self.fs.clone();
 385        let provider_id = provider.id();
 386
 387        cx.spawn_in(window, async move |_, cx| {
 388            cx.update(|_window, cx| {
 389                update_settings_file(fs.clone(), cx, {
 390                    let provider_id = provider_id.clone();
 391                    move |settings, _| {
 392                        if let Some(ref mut openai_compatible) = settings
 393                            .language_models
 394                            .as_mut()
 395                            .and_then(|lm| lm.openai_compatible.as_mut())
 396                        {
 397                            let key_to_remove: Arc<str> = Arc::from(provider_id.0.as_ref());
 398                            openai_compatible.remove(&key_to_remove);
 399                        }
 400                    }
 401                });
 402            })
 403            .log_err();
 404
 405            cx.update(|_window, cx| {
 406                LanguageModelRegistry::global(cx).update(cx, {
 407                    let provider_id = provider_id.clone();
 408                    move |registry, cx| {
 409                        registry.unregister_provider(provider_id, cx);
 410                    }
 411                })
 412            })
 413            .log_err();
 414
 415            anyhow::Ok(())
 416        })
 417        .detach_and_log_err(cx);
 418    }
 419
 420    fn render_provider_configuration_section(
 421        &mut self,
 422        cx: &mut Context<Self>,
 423    ) -> impl IntoElement {
 424        let providers = LanguageModelRegistry::read_global(cx).visible_providers();
 425
 426        let popover_menu = PopoverMenu::new("add-provider-popover")
 427            .trigger(
 428                Button::new("add-provider", "Add Provider")
 429                    .style(ButtonStyle::Outlined)
 430                    .icon_position(IconPosition::Start)
 431                    .icon(IconName::Plus)
 432                    .icon_size(IconSize::Small)
 433                    .icon_color(Color::Muted)
 434                    .label_size(LabelSize::Small),
 435            )
 436            .menu({
 437                let workspace = self.workspace.clone();
 438                move |window, cx| {
 439                    Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 440                        menu.header("Compatible APIs").entry("OpenAI", None, {
 441                            let workspace = workspace.clone();
 442                            move |window, cx| {
 443                                workspace
 444                                    .update(cx, |workspace, cx| {
 445                                        AddLlmProviderModal::toggle(
 446                                            LlmCompatibleProvider::OpenAi,
 447                                            workspace,
 448                                            window,
 449                                            cx,
 450                                        );
 451                                    })
 452                                    .log_err();
 453                            }
 454                        })
 455                    }))
 456                }
 457            })
 458            .anchor(gpui::Corner::TopRight)
 459            .offset(gpui::Point {
 460                x: px(0.0),
 461                y: px(2.0),
 462            });
 463
 464        v_flex()
 465            .w_full()
 466            .child(self.render_section_title(
 467                "LLM Providers",
 468                "Add at least one provider to use AI-powered features with Zed's native agent.",
 469                popover_menu.into_any_element(),
 470            ))
 471            .child(
 472                div()
 473                    .w_full()
 474                    .pl(DynamicSpacing::Base08.rems(cx))
 475                    .pr(DynamicSpacing::Base20.rems(cx))
 476                    .children(
 477                        providers.into_iter().map(|provider| {
 478                            self.render_provider_configuration_block(&provider, cx)
 479                        }),
 480                    ),
 481            )
 482    }
 483
 484    fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
 485        if let Some(plan) = plan {
 486            let free_chip_bg = cx
 487                .theme()
 488                .colors()
 489                .editor_background
 490                .opacity(0.5)
 491                .blend(cx.theme().colors().text_accent.opacity(0.05));
 492
 493            let pro_chip_bg = cx
 494                .theme()
 495                .colors()
 496                .editor_background
 497                .opacity(0.5)
 498                .blend(cx.theme().colors().text_accent.opacity(0.2));
 499
 500            let (plan_name, label_color, bg_color) = match plan {
 501                Plan::ZedFree => ("Free", Color::Default, free_chip_bg),
 502                Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
 503                Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
 504                Plan::ZedStudent => ("Student", 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, |menu, _window, _cx| {
1003                        menu.entry("Install from Registry", None, {
1004                            |window, cx| {
1005                                window.dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
1006                            }
1007                        })
1008                        .entry("Add Custom Agent", None, {
1009                            move |window, cx| {
1010                                if let Some(workspace) = window.root().flatten() {
1011                                    let workspace = workspace.downgrade();
1012                                    window
1013                                        .spawn(cx, async |cx| {
1014                                            open_new_agent_servers_entry_in_settings_editor(
1015                                                workspace, cx,
1016                                            )
1017                                            .await
1018                                        })
1019                                        .detach_and_log_err(cx);
1020                                }
1021                            }
1022                        })
1023                        .separator()
1024                        .header("Learn More")
1025                        .item(
1026                            ContextMenuEntry::new("Agent Servers Docs")
1027                                .icon(IconName::ArrowUpRight)
1028                                .icon_color(Color::Muted)
1029                                .icon_position(IconPosition::End)
1030                                .handler({
1031                                    move |window, cx| {
1032                                        window.dispatch_action(
1033                                            Box::new(OpenBrowser {
1034                                                url: zed_urls::agent_server_docs(cx),
1035                                            }),
1036                                            cx,
1037                                        );
1038                                    }
1039                                }),
1040                        )
1041                        .item(
1042                            ContextMenuEntry::new("ACP 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: "https://agentclientprotocol.com/".into(),
1051                                            }),
1052                                            cx,
1053                                        );
1054                                    }
1055                                }),
1056                        )
1057                    }))
1058                }
1059            })
1060            .anchor(gpui::Corner::TopRight)
1061            .offset(gpui::Point {
1062                x: px(0.0),
1063                y: px(2.0),
1064            });
1065
1066        v_flex()
1067            .border_b_1()
1068            .border_color(cx.theme().colors().border)
1069            .child(
1070                v_flex()
1071                    .child(self.render_section_title(
1072                        "External Agents",
1073                        "All agents connected through the Agent Client Protocol.",
1074                        add_agent_popover.into_any_element(),
1075                    ))
1076                    .child(
1077                        v_flex()
1078                            .p_4()
1079                            .pt_0()
1080                            .gap_2()
1081                            .child(self.render_agent_server(
1082                                AgentIcon::Name(IconName::AiClaude),
1083                                "Claude Code",
1084                                "Claude Code",
1085                                ExternalAgentSource::Builtin,
1086                                cx,
1087                            ))
1088                            .child(Divider::horizontal().color(DividerColor::BorderFaded))
1089                            .child(self.render_agent_server(
1090                                AgentIcon::Name(IconName::AiOpenAi),
1091                                "Codex CLI",
1092                                "Codex CLI",
1093                                ExternalAgentSource::Builtin,
1094                                cx,
1095                            ))
1096                            .child(Divider::horizontal().color(DividerColor::BorderFaded))
1097                            .child(self.render_agent_server(
1098                                AgentIcon::Name(IconName::AiGemini),
1099                                "Gemini CLI",
1100                                "Gemini CLI",
1101                                ExternalAgentSource::Builtin,
1102                                cx,
1103                            ))
1104                            .map(|mut parent| {
1105                                for (name, icon, display_name, source) in user_defined_agents {
1106                                    parent = parent
1107                                        .child(
1108                                            Divider::horizontal().color(DividerColor::BorderFaded),
1109                                        )
1110                                        .child(self.render_agent_server(
1111                                            icon,
1112                                            name,
1113                                            display_name,
1114                                            source,
1115                                            cx,
1116                                        ));
1117                                }
1118                                parent
1119                            }),
1120                    ),
1121            )
1122    }
1123
1124    fn render_agent_server(
1125        &self,
1126        icon: AgentIcon,
1127        id: impl Into<SharedString>,
1128        display_name: impl Into<SharedString>,
1129        source: ExternalAgentSource,
1130        cx: &mut Context<Self>,
1131    ) -> impl IntoElement {
1132        let id = id.into();
1133        let display_name = display_name.into();
1134
1135        let icon = match icon {
1136            AgentIcon::Name(icon_name) => Icon::new(icon_name)
1137                .size(IconSize::Small)
1138                .color(Color::Muted),
1139            AgentIcon::Path(icon_path) => Icon::from_external_svg(icon_path)
1140                .size(IconSize::Small)
1141                .color(Color::Muted),
1142        };
1143
1144        let source_badge = match source {
1145            ExternalAgentSource::Extension => Some((
1146                SharedString::new(format!("agent-source-{}", id)),
1147                SharedString::from(format!(
1148                    "The {} agent was installed from an extension.",
1149                    display_name
1150                )),
1151                IconName::ZedSrcExtension,
1152            )),
1153            ExternalAgentSource::Registry => Some((
1154                SharedString::new(format!("agent-source-{}", id)),
1155                SharedString::from(format!(
1156                    "The {} agent was installed from the ACP registry.",
1157                    display_name
1158                )),
1159                IconName::AcpRegistry,
1160            )),
1161            ExternalAgentSource::Builtin | ExternalAgentSource::Custom => None,
1162        };
1163
1164        let agent_server_name = ExternalAgentServerName(id.clone());
1165
1166        let uninstall_button = match source {
1167            ExternalAgentSource::Extension => Some(
1168                IconButton::new(
1169                    SharedString::from(format!("uninstall-{}", id)),
1170                    IconName::Trash,
1171                )
1172                .icon_color(Color::Muted)
1173                .icon_size(IconSize::Small)
1174                .tooltip(Tooltip::text("Uninstall Agent Extension"))
1175                .on_click(cx.listener(move |this, _, _window, cx| {
1176                    let agent_name = agent_server_name.clone();
1177
1178                    if let Some(ext_id) = this.agent_server_store.update(cx, |store, _cx| {
1179                        store.get_extension_id_for_agent(&agent_name)
1180                    }) {
1181                        ExtensionStore::global(cx)
1182                            .update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
1183                            .detach_and_log_err(cx);
1184                    }
1185                })),
1186            ),
1187            ExternalAgentSource::Registry => {
1188                let fs = self.fs.clone();
1189                Some(
1190                    IconButton::new(
1191                        SharedString::from(format!("uninstall-{}", id)),
1192                        IconName::Trash,
1193                    )
1194                    .icon_color(Color::Muted)
1195                    .icon_size(IconSize::Small)
1196                    .tooltip(Tooltip::text("Remove Registry Agent"))
1197                    .on_click(cx.listener(move |_, _, _window, cx| {
1198                        let agent_name = agent_server_name.clone();
1199                        update_settings_file(fs.clone(), cx, move |settings, _| {
1200                            let Some(agent_servers) = settings.agent_servers.as_mut() else {
1201                                return;
1202                            };
1203                            if let Some(entry) = agent_servers.custom.get(agent_name.0.as_ref())
1204                                && matches!(
1205                                    entry,
1206                                    settings::CustomAgentServerSettings::Registry { .. }
1207                                )
1208                            {
1209                                agent_servers.custom.remove(agent_name.0.as_ref());
1210                            }
1211                        });
1212                    })),
1213                )
1214            }
1215            ExternalAgentSource::Builtin | ExternalAgentSource::Custom => None,
1216        };
1217
1218        h_flex()
1219            .gap_1()
1220            .justify_between()
1221            .child(
1222                h_flex()
1223                    .gap_1p5()
1224                    .child(icon)
1225                    .child(Label::new(display_name))
1226                    .when_some(source_badge, |this, (tooltip_id, tooltip_message, icon)| {
1227                        this.child(
1228                            div()
1229                                .id(tooltip_id)
1230                                .flex_none()
1231                                .tooltip(Tooltip::text(tooltip_message))
1232                                .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted)),
1233                        )
1234                    })
1235                    .child(
1236                        Icon::new(IconName::Check)
1237                            .color(Color::Success)
1238                            .size(IconSize::Small),
1239                    ),
1240            )
1241            .when_some(uninstall_button, |this, uninstall_button| {
1242                this.child(uninstall_button)
1243            })
1244    }
1245}
1246
1247impl Render for AgentConfiguration {
1248    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1249        v_flex()
1250            .id("assistant-configuration")
1251            .key_context("AgentConfiguration")
1252            .track_focus(&self.focus_handle(cx))
1253            .relative()
1254            .size_full()
1255            .pb_8()
1256            .bg(cx.theme().colors().panel_background)
1257            .child(
1258                div()
1259                    .size_full()
1260                    .child(
1261                        v_flex()
1262                            .id("assistant-configuration-content")
1263                            .track_scroll(&self.scroll_handle)
1264                            .size_full()
1265                            .overflow_y_scroll()
1266                            .child(self.render_agent_servers_section(cx))
1267                            .child(self.render_context_servers_section(window, cx))
1268                            .child(self.render_provider_configuration_section(cx)),
1269                    )
1270                    .vertical_scrollbar_for(&self.scroll_handle, window, cx),
1271            )
1272    }
1273}
1274
1275fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1276    manifest.context_servers.len() == 1
1277        && manifest.themes.is_empty()
1278        && manifest.icon_themes.is_empty()
1279        && manifest.languages.is_empty()
1280        && manifest.grammars.is_empty()
1281        && manifest.language_servers.is_empty()
1282        && manifest.slash_commands.is_empty()
1283        && manifest.snippets.is_none()
1284        && manifest.debug_locators.is_empty()
1285}
1286
1287pub(crate) fn resolve_extension_for_context_server(
1288    id: &ContextServerId,
1289    cx: &App,
1290) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1291    ExtensionStore::global(cx)
1292        .read(cx)
1293        .installed_extensions()
1294        .iter()
1295        .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1296        .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1297}
1298
1299// This notification appears when trying to delete
1300// an MCP server extension that not only provides
1301// the server, but other things, too, like language servers and more.
1302fn show_unable_to_uninstall_extension_with_context_server(
1303    workspace: &mut Workspace,
1304    id: ContextServerId,
1305    cx: &mut App,
1306) {
1307    let workspace_handle = workspace.weak_handle();
1308    let context_server_id = id.clone();
1309
1310    let status_toast = StatusToast::new(
1311        format!(
1312            "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1313            id.0
1314        ),
1315        cx,
1316        move |this, _cx| {
1317            let workspace_handle = workspace_handle.clone();
1318
1319            this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1320                .dismiss_button(true)
1321                .action("Uninstall", move |_, _cx| {
1322                    if let Some((extension_id, _)) =
1323                        resolve_extension_for_context_server(&context_server_id, _cx)
1324                    {
1325                        ExtensionStore::global(_cx).update(_cx, |store, cx| {
1326                            store
1327                                .uninstall_extension(extension_id, cx)
1328                                .detach_and_log_err(cx);
1329                        });
1330
1331                        workspace_handle
1332                            .update(_cx, |workspace, cx| {
1333                                let fs = workspace.app_state().fs.clone();
1334                                cx.spawn({
1335                                    let context_server_id = context_server_id.clone();
1336                                    async move |_workspace_handle, cx| {
1337                                        cx.update(|cx| {
1338                                            update_settings_file(fs, cx, move |settings, _| {
1339                                                settings
1340                                                    .project
1341                                                    .context_servers
1342                                                    .remove(&context_server_id.0);
1343                                            });
1344                                        });
1345                                        anyhow::Ok(())
1346                                    }
1347                                })
1348                                .detach_and_log_err(cx);
1349                            })
1350                            .log_err();
1351                    }
1352                })
1353        },
1354    );
1355
1356    workspace.toggle_status_toast(status_toast, cx);
1357}
1358
1359async fn open_new_agent_servers_entry_in_settings_editor(
1360    workspace: WeakEntity<Workspace>,
1361    cx: &mut AsyncWindowContext,
1362) -> Result<()> {
1363    let settings_editor = workspace
1364        .update_in(cx, |_, window, cx| {
1365            create_and_open_local_file(paths::settings_file(), window, cx, || {
1366                settings::initial_user_settings_content().as_ref().into()
1367            })
1368        })?
1369        .await?
1370        .downcast::<Editor>()
1371        .unwrap();
1372
1373    settings_editor
1374        .downgrade()
1375        .update_in(cx, |item, window, cx| {
1376            let text = item.buffer().read(cx).snapshot(cx).text();
1377
1378            let settings = cx.global::<SettingsStore>();
1379
1380            let mut unique_server_name = None;
1381            let edits = settings.edits_for_update(&text, |settings| {
1382                let server_name: Option<String> = (0..u8::MAX)
1383                    .map(|i| {
1384                        if i == 0 {
1385                            "your_agent".to_string()
1386                        } else {
1387                            format!("your_agent_{}", i)
1388                        }
1389                    })
1390                    .find(|name| {
1391                        !settings
1392                            .agent_servers
1393                            .as_ref()
1394                            .is_some_and(|agent_servers| {
1395                                agent_servers.custom.contains_key(name.as_str())
1396                            })
1397                    });
1398                if let Some(server_name) = server_name {
1399                    unique_server_name = Some(SharedString::from(server_name.clone()));
1400                    settings
1401                        .agent_servers
1402                        .get_or_insert_default()
1403                        .custom
1404                        .insert(
1405                            server_name,
1406                            settings::CustomAgentServerSettings::Custom {
1407                                path: "path_to_executable".into(),
1408                                args: vec![],
1409                                env: HashMap::default(),
1410                                default_mode: None,
1411                                default_model: None,
1412                                favorite_models: vec![],
1413                                default_config_options: Default::default(),
1414                                favorite_config_option_values: Default::default(),
1415                            },
1416                        );
1417                }
1418            });
1419
1420            if edits.is_empty() {
1421                return;
1422            }
1423
1424            let ranges = edits
1425                .iter()
1426                .map(|(range, _)| range.clone())
1427                .collect::<Vec<_>>();
1428
1429            item.edit(
1430                edits.into_iter().map(|(range, s)| {
1431                    (
1432                        MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1433                        s,
1434                    )
1435                }),
1436                cx,
1437            );
1438            if let Some((unique_server_name, buffer)) =
1439                unique_server_name.zip(item.buffer().read(cx).as_singleton())
1440            {
1441                let snapshot = buffer.read(cx).snapshot();
1442                if let Some(range) =
1443                    find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1444                {
1445                    item.change_selections(
1446                        SelectionEffects::scroll(Autoscroll::newest()),
1447                        window,
1448                        cx,
1449                        |selections| {
1450                            selections.select_ranges(vec![
1451                                MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1452                            ]);
1453                        },
1454                    );
1455                }
1456            }
1457        })
1458}
1459
1460fn find_text_in_buffer(
1461    text: &str,
1462    start: usize,
1463    snapshot: &language::BufferSnapshot,
1464) -> Option<Range<usize>> {
1465    let chars = text.chars().collect::<Vec<char>>();
1466
1467    let mut offset = start;
1468    let mut char_offset = 0;
1469    for c in snapshot.chars_at(start) {
1470        if char_offset >= chars.len() {
1471            break;
1472        }
1473        offset += 1;
1474
1475        if c == chars[char_offset] {
1476            char_offset += 1;
1477        } else {
1478            char_offset = 0;
1479        }
1480    }
1481
1482    if char_offset == chars.len() {
1483        Some(offset.saturating_sub(chars.len())..offset)
1484    } else {
1485        None
1486    }
1487}
1488
1489// OpenAI-compatible providers are user-configured and can be removed,
1490// whereas built-in providers (like Anthropic, OpenAI, Google, etc.) can't.
1491//
1492// If in the future we have more "API-compatible-type" of providers,
1493// they should be included here as removable providers.
1494fn is_removable_provider(provider_id: &LanguageModelProviderId, cx: &App) -> bool {
1495    AllLanguageModelSettings::get_global(cx)
1496        .openai_compatible
1497        .contains_key(provider_id.0.as_ref())
1498}