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