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