agent_configuration.rs

   1mod add_llm_provider_modal;
   2mod configure_context_server_modal;
   3mod manage_profiles_modal;
   4mod tool_picker;
   5
   6use std::{sync::Arc, time::Duration};
   7
   8use agent_settings::AgentSettings;
   9use assistant_tool::{ToolSource, ToolWorkingSet};
  10use collections::HashMap;
  11use context_server::ContextServerId;
  12use extension::ExtensionManifest;
  13use extension_host::ExtensionStore;
  14use fs::Fs;
  15use gpui::{
  16    Action, Animation, AnimationExt as _, AnyView, App, Corner, Entity, EventEmitter, FocusHandle,
  17    Focusable, ScrollHandle, Subscription, Task, Transformation, WeakEntity, percentage,
  18};
  19use language::LanguageRegistry;
  20use language_model::{
  21    LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID,
  22};
  23use notifications::status_toast::{StatusToast, ToastIcon};
  24use project::{
  25    context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
  26    project_settings::{ContextServerSettings, ProjectSettings},
  27};
  28use proto::Plan;
  29use settings::{Settings, update_settings_file};
  30use ui::{
  31    Chip, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex, Indicator, PopoverMenu,
  32    Scrollbar, ScrollbarState, Switch, SwitchColor, SwitchField, Tooltip, prelude::*,
  33};
  34use util::ResultExt as _;
  35use workspace::Workspace;
  36use zed_actions::ExtensionCategoryFilter;
  37
  38pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
  39pub(crate) use manage_profiles_modal::ManageProfilesModal;
  40
  41use crate::{
  42    AddContextServer,
  43    agent_configuration::add_llm_provider_modal::{AddLlmProviderModal, LlmCompatibleProvider},
  44};
  45
  46pub struct AgentConfiguration {
  47    fs: Arc<dyn Fs>,
  48    language_registry: Arc<LanguageRegistry>,
  49    workspace: WeakEntity<Workspace>,
  50    focus_handle: FocusHandle,
  51    configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
  52    context_server_store: Entity<ContextServerStore>,
  53    expanded_context_server_tools: HashMap<ContextServerId, bool>,
  54    expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
  55    tools: Entity<ToolWorkingSet>,
  56    _registry_subscription: Subscription,
  57    scroll_handle: ScrollHandle,
  58    scrollbar_state: ScrollbarState,
  59}
  60
  61impl AgentConfiguration {
  62    pub fn new(
  63        fs: Arc<dyn Fs>,
  64        context_server_store: Entity<ContextServerStore>,
  65        tools: Entity<ToolWorkingSet>,
  66        language_registry: Arc<LanguageRegistry>,
  67        workspace: WeakEntity<Workspace>,
  68        window: &mut Window,
  69        cx: &mut Context<Self>,
  70    ) -> Self {
  71        let focus_handle = cx.focus_handle();
  72
  73        let registry_subscription = cx.subscribe_in(
  74            &LanguageModelRegistry::global(cx),
  75            window,
  76            |this, _, event: &language_model::Event, window, cx| match event {
  77                language_model::Event::AddedProvider(provider_id) => {
  78                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
  79                    if let Some(provider) = provider {
  80                        this.add_provider_configuration_view(&provider, window, cx);
  81                    }
  82                }
  83                language_model::Event::RemovedProvider(provider_id) => {
  84                    this.remove_provider_configuration_view(provider_id);
  85                }
  86                _ => {}
  87            },
  88        );
  89
  90        cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
  91            .detach();
  92
  93        let scroll_handle = ScrollHandle::new();
  94        let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
  95
  96        let mut expanded_provider_configurations = HashMap::default();
  97        if LanguageModelRegistry::read_global(cx)
  98            .provider(&ZED_CLOUD_PROVIDER_ID)
  99            .map_or(false, |cloud_provider| cloud_provider.must_accept_terms(cx))
 100        {
 101            expanded_provider_configurations.insert(ZED_CLOUD_PROVIDER_ID, true);
 102        }
 103
 104        let mut this = Self {
 105            fs,
 106            language_registry,
 107            workspace,
 108            focus_handle,
 109            configuration_views_by_provider: HashMap::default(),
 110            context_server_store,
 111            expanded_context_server_tools: HashMap::default(),
 112            expanded_provider_configurations,
 113            tools,
 114            _registry_subscription: registry_subscription,
 115            scroll_handle,
 116            scrollbar_state,
 117        };
 118        this.build_provider_configuration_views(window, cx);
 119        this
 120    }
 121
 122    fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 123        let providers = LanguageModelRegistry::read_global(cx).providers();
 124        for provider in providers {
 125            self.add_provider_configuration_view(&provider, window, cx);
 126        }
 127    }
 128
 129    fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
 130        self.configuration_views_by_provider.remove(provider_id);
 131        self.expanded_provider_configurations.remove(provider_id);
 132    }
 133
 134    fn add_provider_configuration_view(
 135        &mut self,
 136        provider: &Arc<dyn LanguageModelProvider>,
 137        window: &mut Window,
 138        cx: &mut Context<Self>,
 139    ) {
 140        let configuration_view = provider.configuration_view(window, cx);
 141        self.configuration_views_by_provider
 142            .insert(provider.id(), configuration_view);
 143    }
 144}
 145
 146impl Focusable for AgentConfiguration {
 147    fn focus_handle(&self, _: &App) -> FocusHandle {
 148        self.focus_handle.clone()
 149    }
 150}
 151
 152pub enum AssistantConfigurationEvent {
 153    NewThread(Arc<dyn LanguageModelProvider>),
 154}
 155
 156impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
 157
 158impl AgentConfiguration {
 159    fn render_provider_configuration_block(
 160        &mut self,
 161        provider: &Arc<dyn LanguageModelProvider>,
 162        cx: &mut Context<Self>,
 163    ) -> impl IntoElement + use<> {
 164        let provider_id = provider.id().0.clone();
 165        let provider_name = provider.name().0.clone();
 166        let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
 167
 168        let configuration_view = self
 169            .configuration_views_by_provider
 170            .get(&provider.id())
 171            .cloned();
 172
 173        let is_expanded = self
 174            .expanded_provider_configurations
 175            .get(&provider.id())
 176            .copied()
 177            .unwrap_or(false);
 178
 179        let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
 180        let current_plan = if is_zed_provider {
 181            self.workspace
 182                .upgrade()
 183                .and_then(|workspace| workspace.read(cx).user_store().read(cx).current_plan())
 184        } else {
 185            None
 186        };
 187
 188        v_flex()
 189            .w_full()
 190            .when(is_expanded, |this| this.mb_2())
 191            .child(
 192                div()
 193                    .opacity(0.6)
 194                    .px_2()
 195                    .child(Divider::horizontal().color(DividerColor::Border)),
 196            )
 197            .child(
 198                h_flex()
 199                    .map(|this| {
 200                        if is_expanded {
 201                            this.mt_2().mb_1()
 202                        } else {
 203                            this.my_2()
 204                        }
 205                    })
 206                    .w_full()
 207                    .justify_between()
 208                    .child(
 209                        h_flex()
 210                            .id(provider_id_string.clone())
 211                            .cursor_pointer()
 212                            .px_2()
 213                            .py_0p5()
 214                            .w_full()
 215                            .justify_between()
 216                            .rounded_sm()
 217                            .hover(|hover| hover.bg(cx.theme().colors().element_hover))
 218                            .child(
 219                                h_flex()
 220                                    .w_full()
 221                                    .gap_2()
 222                                    .child(
 223                                        Icon::new(provider.icon())
 224                                            .size(IconSize::Small)
 225                                            .color(Color::Muted),
 226                                    )
 227                                    .child(
 228                                        h_flex()
 229                                            .w_full()
 230                                            .gap_1()
 231                                            .child(
 232                                                Label::new(provider_name.clone())
 233                                                    .size(LabelSize::Large),
 234                                            )
 235                                            .map(|this| {
 236                                                if is_zed_provider {
 237                                                    this.gap_2().child(
 238                                                        self.render_zed_plan_info(current_plan, cx),
 239                                                    )
 240                                                } else {
 241                                                    this.when(
 242                                                        provider.is_authenticated(cx)
 243                                                            && !is_expanded,
 244                                                        |parent| {
 245                                                            parent.child(
 246                                                                Icon::new(IconName::Check)
 247                                                                    .color(Color::Success),
 248                                                            )
 249                                                        },
 250                                                    )
 251                                                }
 252                                            }),
 253                                    ),
 254                            )
 255                            .child(
 256                                Disclosure::new(provider_id_string, is_expanded)
 257                                    .opened_icon(IconName::ChevronUp)
 258                                    .closed_icon(IconName::ChevronDown),
 259                            )
 260                            .on_click(cx.listener({
 261                                let provider_id = provider.id().clone();
 262                                move |this, _event, _window, _cx| {
 263                                    let is_expanded = this
 264                                        .expanded_provider_configurations
 265                                        .entry(provider_id.clone())
 266                                        .or_insert(false);
 267
 268                                    *is_expanded = !*is_expanded;
 269                                }
 270                            })),
 271                    )
 272                    .when(provider.is_authenticated(cx), |parent| {
 273                        parent.child(
 274                            Button::new(
 275                                SharedString::from(format!("new-thread-{provider_id}")),
 276                                "Start New Thread",
 277                            )
 278                            .icon_position(IconPosition::Start)
 279                            .icon(IconName::Plus)
 280                            .icon_size(IconSize::Small)
 281                            .icon_color(Color::Muted)
 282                            .label_size(LabelSize::Small)
 283                            .on_click(cx.listener({
 284                                let provider = provider.clone();
 285                                move |_this, _event, _window, cx| {
 286                                    cx.emit(AssistantConfigurationEvent::NewThread(
 287                                        provider.clone(),
 288                                    ))
 289                                }
 290                            })),
 291                        )
 292                    }),
 293            )
 294            .child(
 295                div()
 296                    .px_2()
 297                    .when(is_expanded, |parent| match configuration_view {
 298                        Some(configuration_view) => parent.child(configuration_view),
 299                        None => parent.child(Label::new(format!(
 300                            "No configuration view for {provider_name}",
 301                        ))),
 302                    }),
 303            )
 304    }
 305
 306    fn render_provider_configuration_section(
 307        &mut self,
 308        cx: &mut Context<Self>,
 309    ) -> impl IntoElement {
 310        let providers = LanguageModelRegistry::read_global(cx).providers();
 311
 312        v_flex()
 313            .w_full()
 314            .child(
 315                h_flex()
 316                    .p(DynamicSpacing::Base16.rems(cx))
 317                    .pr(DynamicSpacing::Base20.rems(cx))
 318                    .pb_0()
 319                    .mb_2p5()
 320                    .items_start()
 321                    .justify_between()
 322                    .child(
 323                        v_flex()
 324                            .w_full()
 325                            .gap_0p5()
 326                            .child(
 327                                h_flex()
 328                                    .w_full()
 329                                    .gap_2()
 330                                    .justify_between()
 331                                    .child(Headline::new("LLM Providers"))
 332                                    .child(
 333                                        PopoverMenu::new("add-provider-popover")
 334                                            .trigger(
 335                                                Button::new("add-provider", "Add Provider")
 336                                                    .icon_position(IconPosition::Start)
 337                                                    .icon(IconName::Plus)
 338                                                    .icon_size(IconSize::Small)
 339                                                    .icon_color(Color::Muted)
 340                                                    .label_size(LabelSize::Small),
 341                                            )
 342                                            .anchor(gpui::Corner::TopRight)
 343                                            .menu({
 344                                                let workspace = self.workspace.clone();
 345                                                move |window, cx| {
 346                                                    Some(ContextMenu::build(
 347                                                        window,
 348                                                        cx,
 349                                                        |menu, _window, _cx| {
 350                                                            menu.header("Compatible APIs").entry(
 351                                                                "OpenAI",
 352                                                                None,
 353                                                                {
 354                                                                    let workspace =
 355                                                                        workspace.clone();
 356                                                                    move |window, cx| {
 357                                                                        workspace
 358                                                        .update(cx, |workspace, cx| {
 359                                                            AddLlmProviderModal::toggle(
 360                                                                LlmCompatibleProvider::OpenAi,
 361                                                                workspace,
 362                                                                window,
 363                                                                cx,
 364                                                            );
 365                                                        })
 366                                                        .log_err();
 367                                                                    }
 368                                                                },
 369                                                            )
 370                                                        },
 371                                                    ))
 372                                                }
 373                                            }),
 374                                    ),
 375                            )
 376                            .child(
 377                                Label::new("Add at least one provider to use AI-powered features.")
 378                                    .color(Color::Muted),
 379                            ),
 380                    ),
 381            )
 382            .child(
 383                div()
 384                    .w_full()
 385                    .pl(DynamicSpacing::Base08.rems(cx))
 386                    .pr(DynamicSpacing::Base20.rems(cx))
 387                    .children(
 388                        providers.into_iter().map(|provider| {
 389                            self.render_provider_configuration_block(&provider, cx)
 390                        }),
 391                    ),
 392            )
 393    }
 394
 395    fn render_command_permission(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 396        let always_allow_tool_actions = AgentSettings::get_global(cx).always_allow_tool_actions;
 397        let fs = self.fs.clone();
 398
 399        SwitchField::new(
 400            "single-file-review",
 401            "Enable single-file agent reviews",
 402            "Agent edits are also displayed in single-file editors for review.",
 403            always_allow_tool_actions,
 404            move |state, _window, cx| {
 405                let allow = state == &ToggleState::Selected;
 406                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 407                    settings.set_always_allow_tool_actions(allow);
 408                });
 409            },
 410        )
 411    }
 412
 413    fn render_single_file_review(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 414        let single_file_review = AgentSettings::get_global(cx).single_file_review;
 415        let fs = self.fs.clone();
 416
 417        SwitchField::new(
 418            "single-file-review",
 419            "Enable single-file agent reviews",
 420            "Agent edits are also displayed in single-file editors for review.",
 421            single_file_review,
 422            move |state, _window, cx| {
 423                let allow = state == &ToggleState::Selected;
 424                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 425                    settings.set_single_file_review(allow);
 426                });
 427            },
 428        )
 429    }
 430
 431    fn render_sound_notification(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 432        let play_sound_when_agent_done = AgentSettings::get_global(cx).play_sound_when_agent_done;
 433        let fs = self.fs.clone();
 434
 435        SwitchField::new(
 436            "sound-notification",
 437            "Play sound when finished generating",
 438            "Hear a notification sound when the agent is done generating changes or needs your input.",
 439            play_sound_when_agent_done,
 440            move |state, _window, cx| {
 441                let allow = state == &ToggleState::Selected;
 442                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 443                    settings.set_play_sound_when_agent_done(allow);
 444                });
 445            },
 446        )
 447    }
 448
 449    fn render_modifier_to_send(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 450        let use_modifier_to_send = AgentSettings::get_global(cx).use_modifier_to_send;
 451        let fs = self.fs.clone();
 452
 453        SwitchField::new(
 454            "modifier-send",
 455            "Use modifier to submit a message",
 456            "Make a modifier (cmd-enter on macOS, ctrl-enter on Linux) required to send messages.",
 457            use_modifier_to_send,
 458            move |state, _window, cx| {
 459                let allow = state == &ToggleState::Selected;
 460                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 461                    settings.set_use_modifier_to_send(allow);
 462                });
 463            },
 464        )
 465    }
 466
 467    fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 468        v_flex()
 469            .p(DynamicSpacing::Base16.rems(cx))
 470            .pr(DynamicSpacing::Base20.rems(cx))
 471            .gap_2p5()
 472            .border_b_1()
 473            .border_color(cx.theme().colors().border)
 474            .child(Headline::new("General Settings"))
 475            .child(self.render_command_permission(cx))
 476            .child(self.render_single_file_review(cx))
 477            .child(self.render_sound_notification(cx))
 478            .child(self.render_modifier_to_send(cx))
 479    }
 480
 481    fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
 482        if let Some(plan) = plan {
 483            let free_chip_bg = cx
 484                .theme()
 485                .colors()
 486                .editor_background
 487                .opacity(0.5)
 488                .blend(cx.theme().colors().text_accent.opacity(0.05));
 489
 490            let pro_chip_bg = cx
 491                .theme()
 492                .colors()
 493                .editor_background
 494                .opacity(0.5)
 495                .blend(cx.theme().colors().text_accent.opacity(0.2));
 496
 497            let (plan_name, label_color, bg_color) = match plan {
 498                Plan::Free => ("Free", Color::Default, free_chip_bg),
 499                Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
 500                Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
 501            };
 502
 503            Chip::new(plan_name.to_string())
 504                .bg_color(bg_color)
 505                .label_color(label_color)
 506                .into_any_element()
 507        } else {
 508            div().into_any_element()
 509        }
 510    }
 511
 512    fn render_context_servers_section(
 513        &mut self,
 514        window: &mut Window,
 515        cx: &mut Context<Self>,
 516    ) -> impl IntoElement {
 517        let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
 518
 519        v_flex()
 520            .p(DynamicSpacing::Base16.rems(cx))
 521            .pr(DynamicSpacing::Base20.rems(cx))
 522            .gap_2()
 523            .border_b_1()
 524            .border_color(cx.theme().colors().border)
 525            .child(
 526                v_flex()
 527                    .gap_0p5()
 528                    .child(Headline::new("Model Context Protocol (MCP) Servers"))
 529                    .child(Label::new("Connect to context servers via the Model Context Protocol either via Zed extensions or directly.").color(Color::Muted)),
 530            )
 531            .children(
 532                context_server_ids.into_iter().map(|context_server_id| {
 533                    self.render_context_server(context_server_id, window, cx)
 534                }),
 535            )
 536            .child(
 537                h_flex()
 538                    .justify_between()
 539                    .gap_2()
 540                    .child(
 541                        h_flex().w_full().child(
 542                            Button::new("add-context-server", "Add Custom Server")
 543                                .style(ButtonStyle::Filled)
 544                                .layer(ElevationIndex::ModalSurface)
 545                                .full_width()
 546                                .icon(IconName::Plus)
 547                                .icon_size(IconSize::Small)
 548                                .icon_position(IconPosition::Start)
 549                                .on_click(|_event, window, cx| {
 550                                    window.dispatch_action(AddContextServer.boxed_clone(), cx)
 551                                }),
 552                        ),
 553                    )
 554                    .child(
 555                        h_flex().w_full().child(
 556                            Button::new(
 557                                "install-context-server-extensions",
 558                                "Install MCP Extensions",
 559                            )
 560                            .style(ButtonStyle::Filled)
 561                            .layer(ElevationIndex::ModalSurface)
 562                            .full_width()
 563                            .icon(IconName::Hammer)
 564                            .icon_size(IconSize::Small)
 565                            .icon_position(IconPosition::Start)
 566                            .on_click(|_event, window, cx| {
 567                                window.dispatch_action(
 568                                    zed_actions::Extensions {
 569                                        category_filter: Some(
 570                                            ExtensionCategoryFilter::ContextServers,
 571                                        ),
 572                                        id: None,
 573                                    }
 574                                    .boxed_clone(),
 575                                    cx,
 576                                )
 577                            }),
 578                        ),
 579                    ),
 580            )
 581    }
 582
 583    fn render_context_server(
 584        &self,
 585        context_server_id: ContextServerId,
 586        window: &mut Window,
 587        cx: &mut Context<Self>,
 588    ) -> impl use<> + IntoElement {
 589        let tools_by_source = self.tools.read(cx).tools_by_source(cx);
 590        let server_status = self
 591            .context_server_store
 592            .read(cx)
 593            .status_for_server(&context_server_id)
 594            .unwrap_or(ContextServerStatus::Stopped);
 595        let server_configuration = self
 596            .context_server_store
 597            .read(cx)
 598            .configuration_for_server(&context_server_id);
 599
 600        let is_running = matches!(server_status, ContextServerStatus::Running);
 601        let item_id = SharedString::from(context_server_id.0.clone());
 602        let is_from_extension = server_configuration
 603            .as_ref()
 604            .map(|config| {
 605                matches!(
 606                    config.as_ref(),
 607                    ContextServerConfiguration::Extension { .. }
 608                )
 609            })
 610            .unwrap_or(false);
 611
 612        let error = if let ContextServerStatus::Error(error) = server_status.clone() {
 613            Some(error)
 614        } else {
 615            None
 616        };
 617
 618        let are_tools_expanded = self
 619            .expanded_context_server_tools
 620            .get(&context_server_id)
 621            .copied()
 622            .unwrap_or_default();
 623        let tools = tools_by_source
 624            .get(&ToolSource::ContextServer {
 625                id: context_server_id.0.clone().into(),
 626            })
 627            .map_or([].as_slice(), |tools| tools.as_slice());
 628        let tool_count = tools.len();
 629
 630        let border_color = cx.theme().colors().border.opacity(0.6);
 631
 632        let (source_icon, source_tooltip) = if is_from_extension {
 633            (
 634                IconName::ZedMcpExtension,
 635                "This MCP server was installed from an extension.",
 636            )
 637        } else {
 638            (
 639                IconName::ZedMcpCustom,
 640                "This custom MCP server was installed directly.",
 641            )
 642        };
 643
 644        let (status_indicator, tooltip_text) = match server_status {
 645            ContextServerStatus::Starting => (
 646                Icon::new(IconName::LoadCircle)
 647                    .size(IconSize::XSmall)
 648                    .color(Color::Accent)
 649                    .with_animation(
 650                        SharedString::from(format!("{}-starting", context_server_id.0.clone(),)),
 651                        Animation::new(Duration::from_secs(3)).repeat(),
 652                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
 653                    )
 654                    .into_any_element(),
 655                "Server is starting.",
 656            ),
 657            ContextServerStatus::Running => (
 658                Indicator::dot().color(Color::Success).into_any_element(),
 659                "Server is active.",
 660            ),
 661            ContextServerStatus::Error(_) => (
 662                Indicator::dot().color(Color::Error).into_any_element(),
 663                "Server has an error.",
 664            ),
 665            ContextServerStatus::Stopped => (
 666                Indicator::dot().color(Color::Muted).into_any_element(),
 667                "Server is stopped.",
 668            ),
 669        };
 670
 671        let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
 672            .trigger_with_tooltip(
 673                IconButton::new("context-server-config-menu", IconName::Settings)
 674                    .icon_color(Color::Muted)
 675                    .icon_size(IconSize::Small),
 676                Tooltip::text("Open MCP server options"),
 677            )
 678            .anchor(Corner::TopRight)
 679            .menu({
 680                let fs = self.fs.clone();
 681                let context_server_id = context_server_id.clone();
 682                let language_registry = self.language_registry.clone();
 683                let context_server_store = self.context_server_store.clone();
 684                let workspace = self.workspace.clone();
 685                move |window, cx| {
 686                    Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 687                        menu.entry("Configure Server", None, {
 688                            let context_server_id = context_server_id.clone();
 689                            let language_registry = language_registry.clone();
 690                            let workspace = workspace.clone();
 691                            move |window, cx| {
 692                                ConfigureContextServerModal::show_modal_for_existing_server(
 693                                    context_server_id.clone(),
 694                                    language_registry.clone(),
 695                                    workspace.clone(),
 696                                    window,
 697                                    cx,
 698                                )
 699                                .detach_and_log_err(cx);
 700                            }
 701                        })
 702                        .separator()
 703                        .entry("Uninstall", None, {
 704                            let fs = fs.clone();
 705                            let context_server_id = context_server_id.clone();
 706                            let context_server_store = context_server_store.clone();
 707                            let workspace = workspace.clone();
 708                            move |_, cx| {
 709                                let is_provided_by_extension = context_server_store
 710                                    .read(cx)
 711                                    .configuration_for_server(&context_server_id)
 712                                    .as_ref()
 713                                    .map(|config| {
 714                                        matches!(
 715                                            config.as_ref(),
 716                                            ContextServerConfiguration::Extension { .. }
 717                                        )
 718                                    })
 719                                    .unwrap_or(false);
 720
 721                                let uninstall_extension_task = match (
 722                                    is_provided_by_extension,
 723                                    resolve_extension_for_context_server(&context_server_id, cx),
 724                                ) {
 725                                    (true, Some((id, manifest))) => {
 726                                        if extension_only_provides_context_server(manifest.as_ref())
 727                                        {
 728                                            ExtensionStore::global(cx).update(cx, |store, cx| {
 729                                                store.uninstall_extension(id, cx)
 730                                            })
 731                                        } else {
 732                                            workspace.update(cx, |workspace, cx| {
 733                                                show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
 734                                            }).log_err();
 735                                            Task::ready(Ok(()))
 736                                        }
 737                                    }
 738                                    _ => Task::ready(Ok(())),
 739                                };
 740
 741                                cx.spawn({
 742                                    let fs = fs.clone();
 743                                    let context_server_id = context_server_id.clone();
 744                                    async move |cx| {
 745                                        uninstall_extension_task.await?;
 746                                        cx.update(|cx| {
 747                                            update_settings_file::<ProjectSettings>(
 748                                                fs.clone(),
 749                                                cx,
 750                                                {
 751                                                    let context_server_id =
 752                                                        context_server_id.clone();
 753                                                    move |settings, _| {
 754                                                        settings
 755                                                            .context_servers
 756                                                            .remove(&context_server_id.0);
 757                                                    }
 758                                                },
 759                                            )
 760                                        })
 761                                    }
 762                                })
 763                                .detach_and_log_err(cx);
 764                            }
 765                        })
 766                    }))
 767                }
 768            });
 769
 770        v_flex()
 771            .id(item_id.clone())
 772            .border_1()
 773            .rounded_md()
 774            .border_color(border_color)
 775            .bg(cx.theme().colors().background.opacity(0.2))
 776            .overflow_hidden()
 777            .child(
 778                h_flex()
 779                    .p_1()
 780                    .justify_between()
 781                    .when(
 782                        error.is_some() || are_tools_expanded && tool_count >= 1,
 783                        |element| element.border_b_1().border_color(border_color),
 784                    )
 785                    .child(
 786                        h_flex()
 787                            .child(
 788                                Disclosure::new(
 789                                    "tool-list-disclosure",
 790                                    are_tools_expanded || error.is_some(),
 791                                )
 792                                .disabled(tool_count == 0)
 793                                .on_click(cx.listener({
 794                                    let context_server_id = context_server_id.clone();
 795                                    move |this, _event, _window, _cx| {
 796                                        let is_open = this
 797                                            .expanded_context_server_tools
 798                                            .entry(context_server_id.clone())
 799                                            .or_insert(false);
 800
 801                                        *is_open = !*is_open;
 802                                    }
 803                                })),
 804                            )
 805                            .child(
 806                                h_flex()
 807                                    .id(SharedString::from(format!("tooltip-{}", item_id)))
 808                                    .h_full()
 809                                    .w_3()
 810                                    .mx_1()
 811                                    .justify_center()
 812                                    .tooltip(Tooltip::text(tooltip_text))
 813                                    .child(status_indicator),
 814                            )
 815                            .child(Label::new(item_id).ml_0p5())
 816                            .child(
 817                                div()
 818                                    .id("extension-source")
 819                                    .mt_0p5()
 820                                    .mx_1()
 821                                    .tooltip(Tooltip::text(source_tooltip))
 822                                    .child(
 823                                        Icon::new(source_icon)
 824                                            .size(IconSize::Small)
 825                                            .color(Color::Muted),
 826                                    ),
 827                            )
 828                            .when(is_running, |this| {
 829                                this.child(
 830                                    Label::new(if tool_count == 1 {
 831                                        SharedString::from("1 tool")
 832                                    } else {
 833                                        SharedString::from(format!("{} tools", tool_count))
 834                                    })
 835                                    .color(Color::Muted)
 836                                    .size(LabelSize::Small),
 837                                )
 838                            }),
 839                    )
 840                    .child(
 841                        h_flex()
 842                            .gap_1()
 843                            .child(context_server_configuration_menu)
 844                            .child(
 845                                Switch::new("context-server-switch", is_running.into())
 846                                    .color(SwitchColor::Accent)
 847                                    .on_click({
 848                                        let context_server_manager =
 849                                            self.context_server_store.clone();
 850                                        let context_server_id = context_server_id.clone();
 851                                        let fs = self.fs.clone();
 852
 853                                        move |state, _window, cx| {
 854                                            let is_enabled = match state {
 855                                                ToggleState::Unselected
 856                                                | ToggleState::Indeterminate => {
 857                                                    context_server_manager.update(
 858                                                        cx,
 859                                                        |this, cx| {
 860                                                            this.stop_server(
 861                                                                &context_server_id,
 862                                                                cx,
 863                                                            )
 864                                                            .log_err();
 865                                                        },
 866                                                    );
 867                                                    false
 868                                                }
 869                                                ToggleState::Selected => {
 870                                                    context_server_manager.update(
 871                                                        cx,
 872                                                        |this, cx| {
 873                                                            if let Some(server) =
 874                                                                this.get_server(&context_server_id)
 875                                                            {
 876                                                                this.start_server(server, cx);
 877                                                            }
 878                                                        },
 879                                                    );
 880                                                    true
 881                                                }
 882                                            };
 883                                            update_settings_file::<ProjectSettings>(
 884                                                fs.clone(),
 885                                                cx,
 886                                                {
 887                                                    let context_server_id =
 888                                                        context_server_id.clone();
 889
 890                                                    move |settings, _| {
 891                                                        settings
 892                                                            .context_servers
 893                                                            .entry(context_server_id.0)
 894                                                            .or_insert_with(|| {
 895                                                                ContextServerSettings::Extension {
 896                                                                    enabled: is_enabled,
 897                                                                    settings: serde_json::json!({}),
 898                                                                }
 899                                                            })
 900                                                            .set_enabled(is_enabled);
 901                                                    }
 902                                                },
 903                                            );
 904                                        }
 905                                    }),
 906                            ),
 907                    ),
 908            )
 909            .map(|parent| {
 910                if let Some(error) = error {
 911                    return parent.child(
 912                        h_flex()
 913                            .p_2()
 914                            .gap_2()
 915                            .items_start()
 916                            .child(
 917                                h_flex()
 918                                    .flex_none()
 919                                    .h(window.line_height() / 1.6_f32)
 920                                    .justify_center()
 921                                    .child(
 922                                        Icon::new(IconName::XCircle)
 923                                            .size(IconSize::XSmall)
 924                                            .color(Color::Error),
 925                                    ),
 926                            )
 927                            .child(
 928                                div().w_full().child(
 929                                    Label::new(error)
 930                                        .buffer_font(cx)
 931                                        .color(Color::Muted)
 932                                        .size(LabelSize::Small),
 933                                ),
 934                            ),
 935                    );
 936                }
 937
 938                if !are_tools_expanded || tools.is_empty() {
 939                    return parent;
 940                }
 941
 942                parent.child(v_flex().py_1p5().px_1().gap_1().children(
 943                    tools.into_iter().enumerate().map(|(ix, tool)| {
 944                        h_flex()
 945                            .id(("tool-item", ix))
 946                            .px_1()
 947                            .gap_2()
 948                            .justify_between()
 949                            .hover(|style| style.bg(cx.theme().colors().element_hover))
 950                            .rounded_sm()
 951                            .child(
 952                                Label::new(tool.name())
 953                                    .buffer_font(cx)
 954                                    .size(LabelSize::Small),
 955                            )
 956                            .child(
 957                                Icon::new(IconName::Info)
 958                                    .size(IconSize::Small)
 959                                    .color(Color::Ignored),
 960                            )
 961                            .tooltip(Tooltip::text(tool.description()))
 962                    }),
 963                ))
 964            })
 965    }
 966}
 967
 968impl Render for AgentConfiguration {
 969    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 970        v_flex()
 971            .id("assistant-configuration")
 972            .key_context("AgentConfiguration")
 973            .track_focus(&self.focus_handle(cx))
 974            .relative()
 975            .size_full()
 976            .pb_8()
 977            .bg(cx.theme().colors().panel_background)
 978            .child(
 979                v_flex()
 980                    .id("assistant-configuration-content")
 981                    .track_scroll(&self.scroll_handle)
 982                    .size_full()
 983                    .overflow_y_scroll()
 984                    .child(self.render_general_settings_section(cx))
 985                    .child(self.render_context_servers_section(window, cx))
 986                    .child(self.render_provider_configuration_section(cx)),
 987            )
 988            .child(
 989                div()
 990                    .id("assistant-configuration-scrollbar")
 991                    .occlude()
 992                    .absolute()
 993                    .right(px(3.))
 994                    .top_0()
 995                    .bottom_0()
 996                    .pb_6()
 997                    .w(px(12.))
 998                    .cursor_default()
 999                    .on_mouse_move(cx.listener(|_, _, _window, cx| {
1000                        cx.notify();
1001                        cx.stop_propagation()
1002                    }))
1003                    .on_hover(|_, _window, cx| {
1004                        cx.stop_propagation();
1005                    })
1006                    .on_any_mouse_down(|_, _window, cx| {
1007                        cx.stop_propagation();
1008                    })
1009                    .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
1010                        cx.notify();
1011                    }))
1012                    .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1013            )
1014    }
1015}
1016
1017fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1018    manifest.context_servers.len() == 1
1019        && manifest.themes.is_empty()
1020        && manifest.icon_themes.is_empty()
1021        && manifest.languages.is_empty()
1022        && manifest.grammars.is_empty()
1023        && manifest.language_servers.is_empty()
1024        && manifest.slash_commands.is_empty()
1025        && manifest.indexed_docs_providers.is_empty()
1026        && manifest.snippets.is_none()
1027        && manifest.debug_locators.is_empty()
1028}
1029
1030pub(crate) fn resolve_extension_for_context_server(
1031    id: &ContextServerId,
1032    cx: &App,
1033) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1034    ExtensionStore::global(cx)
1035        .read(cx)
1036        .installed_extensions()
1037        .iter()
1038        .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1039        .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1040}
1041
1042// This notification appears when trying to delete
1043// an MCP server extension that not only provides
1044// the server, but other things, too, like language servers and more.
1045fn show_unable_to_uninstall_extension_with_context_server(
1046    workspace: &mut Workspace,
1047    id: ContextServerId,
1048    cx: &mut App,
1049) {
1050    let workspace_handle = workspace.weak_handle();
1051    let context_server_id = id.clone();
1052
1053    let status_toast = StatusToast::new(
1054        format!(
1055            "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1056            id.0
1057        ),
1058        cx,
1059        move |this, _cx| {
1060            let workspace_handle = workspace_handle.clone();
1061            let context_server_id = context_server_id.clone();
1062
1063            this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1064                .dismiss_button(true)
1065                .action("Uninstall", move |_, _cx| {
1066                    if let Some((extension_id, _)) =
1067                        resolve_extension_for_context_server(&context_server_id, _cx)
1068                    {
1069                        ExtensionStore::global(_cx).update(_cx, |store, cx| {
1070                            store
1071                                .uninstall_extension(extension_id, cx)
1072                                .detach_and_log_err(cx);
1073                        });
1074
1075                        workspace_handle
1076                            .update(_cx, |workspace, cx| {
1077                                let fs = workspace.app_state().fs.clone();
1078                                cx.spawn({
1079                                    let context_server_id = context_server_id.clone();
1080                                    async move |_workspace_handle, cx| {
1081                                        cx.update(|cx| {
1082                                            update_settings_file::<ProjectSettings>(
1083                                                fs,
1084                                                cx,
1085                                                move |settings, _| {
1086                                                    settings
1087                                                        .context_servers
1088                                                        .remove(&context_server_id.0);
1089                                                },
1090                                            );
1091                                        })?;
1092                                        anyhow::Ok(())
1093                                    }
1094                                })
1095                                .detach_and_log_err(cx);
1096                            })
1097                            .log_err();
1098                    }
1099                })
1100        },
1101    );
1102
1103    workspace.toggle_status_toast(status_toast, cx);
1104}