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