agent_configuration.rs

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