agent_configuration.rs

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