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