agent_configuration.rs

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