agent_configuration.rs

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