agent_configuration.rs

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