agent_configuration.rs

   1mod add_llm_provider_modal;
   2mod configure_context_server_modal;
   3mod manage_profiles_modal;
   4mod tool_picker;
   5
   6use std::{ops::Range, sync::Arc};
   7
   8use agent_servers::{AgentServerCommand, AllAgentServersSettings};
   9use agent_settings::AgentSettings;
  10use anyhow::Result;
  11use assistant_tool::{ToolSource, ToolWorkingSet};
  12use cloud_llm_client::Plan;
  13use collections::HashMap;
  14use context_server::ContextServerId;
  15use editor::{Editor, SelectionEffects, scroll::Autoscroll};
  16use extension::ExtensionManifest;
  17use extension_host::ExtensionStore;
  18use fs::Fs;
  19use gpui::{
  20    Action, AnyView, App, AsyncWindowContext, Corner, Entity, EventEmitter, FocusHandle, Focusable,
  21    Hsla, ScrollHandle, Subscription, Task, WeakEntity,
  22};
  23use itertools::Itertools as _;
  24use language::LanguageRegistry;
  25use language_model::{
  26    LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID,
  27};
  28use notifications::status_toast::{StatusToast, ToastIcon};
  29use project::{
  30    context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
  31    project_settings::{ContextServerSettings, ProjectSettings},
  32};
  33use settings::{Settings, SettingsStore, update_settings_file};
  34use ui::{
  35    Chip, CommonAnimationExt, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex,
  36    Indicator, PopoverMenu, Scrollbar, ScrollbarState, Switch, SwitchColor, SwitchField, Tooltip,
  37    prelude::*,
  38};
  39use util::ResultExt as _;
  40use workspace::{Workspace, create_and_open_local_file};
  41use zed_actions::ExtensionCategoryFilter;
  42
  43pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
  44pub(crate) use manage_profiles_modal::ManageProfilesModal;
  45
  46use crate::{
  47    AddContextServer, ExternalAgent, NewExternalAgentThread,
  48    agent_configuration::add_llm_provider_modal::{AddLlmProviderModal, LlmCompatibleProvider},
  49};
  50
  51pub struct AgentConfiguration {
  52    fs: Arc<dyn Fs>,
  53    language_registry: Arc<LanguageRegistry>,
  54    workspace: WeakEntity<Workspace>,
  55    focus_handle: FocusHandle,
  56    configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
  57    context_server_store: Entity<ContextServerStore>,
  58    expanded_context_server_tools: HashMap<ContextServerId, bool>,
  59    expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
  60    tools: Entity<ToolWorkingSet>,
  61    _registry_subscription: Subscription,
  62    scroll_handle: ScrollHandle,
  63    scrollbar_state: ScrollbarState,
  64    _check_for_gemini: Task<()>,
  65}
  66
  67impl AgentConfiguration {
  68    pub fn new(
  69        fs: Arc<dyn Fs>,
  70        context_server_store: Entity<ContextServerStore>,
  71        tools: Entity<ToolWorkingSet>,
  72        language_registry: Arc<LanguageRegistry>,
  73        workspace: WeakEntity<Workspace>,
  74        window: &mut Window,
  75        cx: &mut Context<Self>,
  76    ) -> Self {
  77        let focus_handle = cx.focus_handle();
  78
  79        let registry_subscription = cx.subscribe_in(
  80            &LanguageModelRegistry::global(cx),
  81            window,
  82            |this, _, event: &language_model::Event, window, cx| match event {
  83                language_model::Event::AddedProvider(provider_id) => {
  84                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
  85                    if let Some(provider) = provider {
  86                        this.add_provider_configuration_view(&provider, window, cx);
  87                    }
  88                }
  89                language_model::Event::RemovedProvider(provider_id) => {
  90                    this.remove_provider_configuration_view(provider_id);
  91                }
  92                _ => {}
  93            },
  94        );
  95
  96        cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
  97            .detach();
  98
  99        let scroll_handle = ScrollHandle::new();
 100        let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
 101
 102        let mut this = Self {
 103            fs,
 104            language_registry,
 105            workspace,
 106            focus_handle,
 107            configuration_views_by_provider: HashMap::default(),
 108            context_server_store,
 109            expanded_context_server_tools: HashMap::default(),
 110            expanded_provider_configurations: HashMap::default(),
 111            tools,
 112            _registry_subscription: registry_subscription,
 113            scroll_handle,
 114            scrollbar_state,
 115            _check_for_gemini: Task::ready(()),
 116        };
 117        this.build_provider_configuration_views(window, cx);
 118        this
 119    }
 120
 121    fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 122        let providers = LanguageModelRegistry::read_global(cx).providers();
 123        for provider in providers {
 124            self.add_provider_configuration_view(&provider, window, cx);
 125        }
 126    }
 127
 128    fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
 129        self.configuration_views_by_provider.remove(provider_id);
 130        self.expanded_provider_configurations.remove(provider_id);
 131    }
 132
 133    fn add_provider_configuration_view(
 134        &mut self,
 135        provider: &Arc<dyn LanguageModelProvider>,
 136        window: &mut Window,
 137        cx: &mut Context<Self>,
 138    ) {
 139        let configuration_view = provider.configuration_view(
 140            language_model::ConfigurationViewTargetAgent::ZedAgent,
 141            window,
 142            cx,
 143        );
 144        self.configuration_views_by_provider
 145            .insert(provider.id(), configuration_view);
 146    }
 147}
 148
 149impl Focusable for AgentConfiguration {
 150    fn focus_handle(&self, _: &App) -> FocusHandle {
 151        self.focus_handle.clone()
 152    }
 153}
 154
 155pub enum AssistantConfigurationEvent {
 156    NewThread(Arc<dyn LanguageModelProvider>),
 157}
 158
 159impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
 160
 161impl AgentConfiguration {
 162    fn render_provider_configuration_block(
 163        &mut self,
 164        provider: &Arc<dyn LanguageModelProvider>,
 165        cx: &mut Context<Self>,
 166    ) -> impl IntoElement + use<> {
 167        let provider_id = provider.id().0;
 168        let provider_name = provider.name().0;
 169        let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
 170
 171        let configuration_view = self
 172            .configuration_views_by_provider
 173            .get(&provider.id())
 174            .cloned();
 175
 176        let is_expanded = self
 177            .expanded_provider_configurations
 178            .get(&provider.id())
 179            .copied()
 180            .unwrap_or(false);
 181
 182        let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
 183        let current_plan = if is_zed_provider {
 184            self.workspace
 185                .upgrade()
 186                .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
 187        } else {
 188            None
 189        };
 190
 191        let is_signed_in = self
 192            .workspace
 193            .read_with(cx, |workspace, _| {
 194                !workspace.client().status().borrow().is_signed_out()
 195            })
 196            .unwrap_or(false);
 197
 198        v_flex()
 199            .w_full()
 200            .when(is_expanded, |this| this.mb_2())
 201            .child(
 202                div()
 203                    .opacity(0.6)
 204                    .px_2()
 205                    .child(Divider::horizontal().color(DividerColor::Border)),
 206            )
 207            .child(
 208                h_flex()
 209                    .map(|this| {
 210                        if is_expanded {
 211                            this.mt_2().mb_1()
 212                        } else {
 213                            this.my_2()
 214                        }
 215                    })
 216                    .w_full()
 217                    .justify_between()
 218                    .child(
 219                        h_flex()
 220                            .id(provider_id_string.clone())
 221                            .px_2()
 222                            .py_0p5()
 223                            .w_full()
 224                            .justify_between()
 225                            .rounded_sm()
 226                            .hover(|hover| hover.bg(cx.theme().colors().element_hover))
 227                            .child(
 228                                h_flex()
 229                                    .w_full()
 230                                    .gap_2()
 231                                    .child(
 232                                        Icon::new(provider.icon())
 233                                            .size(IconSize::Small)
 234                                            .color(Color::Muted),
 235                                    )
 236                                    .child(
 237                                        h_flex()
 238                                            .w_full()
 239                                            .gap_1()
 240                                            .child(Label::new(provider_name.clone()))
 241                                            .map(|this| {
 242                                                if is_zed_provider && is_signed_in {
 243                                                    this.child(
 244                                                        self.render_zed_plan_info(current_plan, cx),
 245                                                    )
 246                                                } else {
 247                                                    this.when(
 248                                                        provider.is_authenticated(cx)
 249                                                            && !is_expanded,
 250                                                        |parent| {
 251                                                            parent.child(
 252                                                                Icon::new(IconName::Check)
 253                                                                    .color(Color::Success),
 254                                                            )
 255                                                        },
 256                                                    )
 257                                                }
 258                                            }),
 259                                    ),
 260                            )
 261                            .child(
 262                                Disclosure::new(provider_id_string, is_expanded)
 263                                    .opened_icon(IconName::ChevronUp)
 264                                    .closed_icon(IconName::ChevronDown),
 265                            )
 266                            .on_click(cx.listener({
 267                                let provider_id = provider.id();
 268                                move |this, _event, _window, _cx| {
 269                                    let is_expanded = this
 270                                        .expanded_provider_configurations
 271                                        .entry(provider_id.clone())
 272                                        .or_insert(false);
 273
 274                                    *is_expanded = !*is_expanded;
 275                                }
 276                            })),
 277                    )
 278                    .when(provider.is_authenticated(cx), |parent| {
 279                        parent.child(
 280                            Button::new(
 281                                SharedString::from(format!("new-thread-{provider_id}")),
 282                                "Start New Thread",
 283                            )
 284                            .icon_position(IconPosition::Start)
 285                            .icon(IconName::Thread)
 286                            .icon_size(IconSize::Small)
 287                            .icon_color(Color::Muted)
 288                            .label_size(LabelSize::Small)
 289                            .on_click(cx.listener({
 290                                let provider = provider.clone();
 291                                move |_this, _event, _window, cx| {
 292                                    cx.emit(AssistantConfigurationEvent::NewThread(
 293                                        provider.clone(),
 294                                    ))
 295                                }
 296                            })),
 297                        )
 298                    }),
 299            )
 300            .child(
 301                div()
 302                    .w_full()
 303                    .px_2()
 304                    .when(is_expanded, |parent| match configuration_view {
 305                        Some(configuration_view) => parent.child(configuration_view),
 306                        None => parent.child(Label::new(format!(
 307                            "No configuration view for {provider_name}",
 308                        ))),
 309                    }),
 310            )
 311    }
 312
 313    fn render_provider_configuration_section(
 314        &mut self,
 315        cx: &mut Context<Self>,
 316    ) -> impl IntoElement {
 317        let providers = LanguageModelRegistry::read_global(cx).providers();
 318
 319        v_flex()
 320            .w_full()
 321            .child(
 322                h_flex()
 323                    .p(DynamicSpacing::Base16.rems(cx))
 324                    .pr(DynamicSpacing::Base20.rems(cx))
 325                    .pb_0()
 326                    .mb_2p5()
 327                    .items_start()
 328                    .justify_between()
 329                    .child(
 330                        v_flex()
 331                            .w_full()
 332                            .gap_0p5()
 333                            .child(
 334                                h_flex()
 335                                    .pr_1()
 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 with Zed's native agent.")
 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 card_item_bg_color(&self, cx: &mut Context<Self>) -> Hsla {
 527        cx.theme().colors().background.opacity(0.25)
 528    }
 529
 530    fn card_item_border_color(&self, cx: &mut Context<Self>) -> Hsla {
 531        cx.theme().colors().border.opacity(0.6)
 532    }
 533
 534    fn render_context_servers_section(
 535        &mut self,
 536        window: &mut Window,
 537        cx: &mut Context<Self>,
 538    ) -> impl IntoElement {
 539        let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
 540
 541        v_flex()
 542            .p(DynamicSpacing::Base16.rems(cx))
 543            .pr(DynamicSpacing::Base20.rems(cx))
 544            .gap_2()
 545            .border_b_1()
 546            .border_color(cx.theme().colors().border)
 547            .child(
 548                v_flex()
 549                    .gap_0p5()
 550                    .child(Headline::new("Model Context Protocol (MCP) Servers"))
 551                    .child(
 552                        Label::new(
 553                            "All context servers connected through the Model Context Protocol.",
 554                        )
 555                        .color(Color::Muted),
 556                    ),
 557            )
 558            .children(
 559                context_server_ids.into_iter().map(|context_server_id| {
 560                    self.render_context_server(context_server_id, window, cx)
 561                }),
 562            )
 563            .child(
 564                h_flex()
 565                    .justify_between()
 566                    .gap_1p5()
 567                    .child(
 568                        h_flex().w_full().child(
 569                            Button::new("add-context-server", "Add Custom Server")
 570                                .style(ButtonStyle::Filled)
 571                                .layer(ElevationIndex::ModalSurface)
 572                                .full_width()
 573                                .icon(IconName::Plus)
 574                                .icon_size(IconSize::Small)
 575                                .icon_position(IconPosition::Start)
 576                                .on_click(|_event, window, cx| {
 577                                    window.dispatch_action(AddContextServer.boxed_clone(), cx)
 578                                }),
 579                        ),
 580                    )
 581                    .child(
 582                        h_flex().w_full().child(
 583                            Button::new(
 584                                "install-context-server-extensions",
 585                                "Install MCP Extensions",
 586                            )
 587                            .style(ButtonStyle::Filled)
 588                            .layer(ElevationIndex::ModalSurface)
 589                            .full_width()
 590                            .icon(IconName::ToolHammer)
 591                            .icon_size(IconSize::Small)
 592                            .icon_position(IconPosition::Start)
 593                            .on_click(|_event, window, cx| {
 594                                window.dispatch_action(
 595                                    zed_actions::Extensions {
 596                                        category_filter: Some(
 597                                            ExtensionCategoryFilter::ContextServers,
 598                                        ),
 599                                        id: None,
 600                                    }
 601                                    .boxed_clone(),
 602                                    cx,
 603                                )
 604                            }),
 605                        ),
 606                    ),
 607            )
 608    }
 609
 610    fn render_context_server(
 611        &self,
 612        context_server_id: ContextServerId,
 613        window: &mut Window,
 614        cx: &mut Context<Self>,
 615    ) -> impl use<> + IntoElement {
 616        let tools_by_source = self.tools.read(cx).tools_by_source(cx);
 617        let server_status = self
 618            .context_server_store
 619            .read(cx)
 620            .status_for_server(&context_server_id)
 621            .unwrap_or(ContextServerStatus::Stopped);
 622        let server_configuration = self
 623            .context_server_store
 624            .read(cx)
 625            .configuration_for_server(&context_server_id);
 626
 627        let is_running = matches!(server_status, ContextServerStatus::Running);
 628        let item_id = SharedString::from(context_server_id.0.clone());
 629        let is_from_extension = server_configuration
 630            .as_ref()
 631            .map(|config| {
 632                matches!(
 633                    config.as_ref(),
 634                    ContextServerConfiguration::Extension { .. }
 635                )
 636            })
 637            .unwrap_or(false);
 638
 639        let error = if let ContextServerStatus::Error(error) = server_status.clone() {
 640            Some(error)
 641        } else {
 642            None
 643        };
 644
 645        let are_tools_expanded = self
 646            .expanded_context_server_tools
 647            .get(&context_server_id)
 648            .copied()
 649            .unwrap_or_default();
 650        let tools = tools_by_source
 651            .get(&ToolSource::ContextServer {
 652                id: context_server_id.0.clone().into(),
 653            })
 654            .map_or([].as_slice(), |tools| tools.as_slice());
 655        let tool_count = tools.len();
 656
 657        let (source_icon, source_tooltip) = if is_from_extension {
 658            (
 659                IconName::ZedMcpExtension,
 660                "This MCP server was installed from an extension.",
 661            )
 662        } else {
 663            (
 664                IconName::ZedMcpCustom,
 665                "This custom MCP server was installed directly.",
 666            )
 667        };
 668
 669        let (status_indicator, tooltip_text) = match server_status {
 670            ContextServerStatus::Starting => (
 671                Icon::new(IconName::LoadCircle)
 672                    .size(IconSize::XSmall)
 673                    .color(Color::Accent)
 674                    .with_keyed_rotate_animation(
 675                        SharedString::from(format!("{}-starting", context_server_id.0)),
 676                        3,
 677                    )
 678                    .into_any_element(),
 679                "Server is starting.",
 680            ),
 681            ContextServerStatus::Running => (
 682                Indicator::dot().color(Color::Success).into_any_element(),
 683                "Server is active.",
 684            ),
 685            ContextServerStatus::Error(_) => (
 686                Indicator::dot().color(Color::Error).into_any_element(),
 687                "Server has an error.",
 688            ),
 689            ContextServerStatus::Stopped => (
 690                Indicator::dot().color(Color::Muted).into_any_element(),
 691                "Server is stopped.",
 692            ),
 693        };
 694
 695        let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
 696            .trigger_with_tooltip(
 697                IconButton::new("context-server-config-menu", IconName::Settings)
 698                    .icon_color(Color::Muted)
 699                    .icon_size(IconSize::Small),
 700                Tooltip::text("Open MCP server options"),
 701            )
 702            .anchor(Corner::TopRight)
 703            .menu({
 704                let fs = self.fs.clone();
 705                let context_server_id = context_server_id.clone();
 706                let language_registry = self.language_registry.clone();
 707                let context_server_store = self.context_server_store.clone();
 708                let workspace = self.workspace.clone();
 709                move |window, cx| {
 710                    Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 711                        menu.entry("Configure Server", None, {
 712                            let context_server_id = context_server_id.clone();
 713                            let language_registry = language_registry.clone();
 714                            let workspace = workspace.clone();
 715                            move |window, cx| {
 716                                ConfigureContextServerModal::show_modal_for_existing_server(
 717                                    context_server_id.clone(),
 718                                    language_registry.clone(),
 719                                    workspace.clone(),
 720                                    window,
 721                                    cx,
 722                                )
 723                                .detach_and_log_err(cx);
 724                            }
 725                        })
 726                        .separator()
 727                        .entry("Uninstall", None, {
 728                            let fs = fs.clone();
 729                            let context_server_id = context_server_id.clone();
 730                            let context_server_store = context_server_store.clone();
 731                            let workspace = workspace.clone();
 732                            move |_, cx| {
 733                                let is_provided_by_extension = context_server_store
 734                                    .read(cx)
 735                                    .configuration_for_server(&context_server_id)
 736                                    .as_ref()
 737                                    .map(|config| {
 738                                        matches!(
 739                                            config.as_ref(),
 740                                            ContextServerConfiguration::Extension { .. }
 741                                        )
 742                                    })
 743                                    .unwrap_or(false);
 744
 745                                let uninstall_extension_task = match (
 746                                    is_provided_by_extension,
 747                                    resolve_extension_for_context_server(&context_server_id, cx),
 748                                ) {
 749                                    (true, Some((id, manifest))) => {
 750                                        if extension_only_provides_context_server(manifest.as_ref())
 751                                        {
 752                                            ExtensionStore::global(cx).update(cx, |store, cx| {
 753                                                store.uninstall_extension(id, cx)
 754                                            })
 755                                        } else {
 756                                            workspace.update(cx, |workspace, cx| {
 757                                                show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
 758                                            }).log_err();
 759                                            Task::ready(Ok(()))
 760                                        }
 761                                    }
 762                                    _ => Task::ready(Ok(())),
 763                                };
 764
 765                                cx.spawn({
 766                                    let fs = fs.clone();
 767                                    let context_server_id = context_server_id.clone();
 768                                    async move |cx| {
 769                                        uninstall_extension_task.await?;
 770                                        cx.update(|cx| {
 771                                            update_settings_file::<ProjectSettings>(
 772                                                fs.clone(),
 773                                                cx,
 774                                                {
 775                                                    let context_server_id =
 776                                                        context_server_id.clone();
 777                                                    move |settings, _| {
 778                                                        settings
 779                                                            .context_servers
 780                                                            .remove(&context_server_id.0);
 781                                                    }
 782                                                },
 783                                            )
 784                                        })
 785                                    }
 786                                })
 787                                .detach_and_log_err(cx);
 788                            }
 789                        })
 790                    }))
 791                }
 792            });
 793
 794        v_flex()
 795            .id(item_id.clone())
 796            .border_1()
 797            .rounded_md()
 798            .border_color(self.card_item_border_color(cx))
 799            .bg(self.card_item_bg_color(cx))
 800            .overflow_hidden()
 801            .child(
 802                h_flex()
 803                    .p_1()
 804                    .justify_between()
 805                    .when(
 806                        error.is_some() || are_tools_expanded && tool_count >= 1,
 807                        |element| {
 808                            element
 809                                .border_b_1()
 810                                .border_color(self.card_item_border_color(cx))
 811                        },
 812                    )
 813                    .child(
 814                        h_flex()
 815                            .child(
 816                                Disclosure::new(
 817                                    "tool-list-disclosure",
 818                                    are_tools_expanded || error.is_some(),
 819                                )
 820                                .disabled(tool_count == 0)
 821                                .on_click(cx.listener({
 822                                    let context_server_id = context_server_id.clone();
 823                                    move |this, _event, _window, _cx| {
 824                                        let is_open = this
 825                                            .expanded_context_server_tools
 826                                            .entry(context_server_id.clone())
 827                                            .or_insert(false);
 828
 829                                        *is_open = !*is_open;
 830                                    }
 831                                })),
 832                            )
 833                            .child(
 834                                h_flex()
 835                                    .id(SharedString::from(format!("tooltip-{}", item_id)))
 836                                    .h_full()
 837                                    .w_3()
 838                                    .mx_1()
 839                                    .justify_center()
 840                                    .tooltip(Tooltip::text(tooltip_text))
 841                                    .child(status_indicator),
 842                            )
 843                            .child(Label::new(item_id).ml_0p5())
 844                            .child(
 845                                div()
 846                                    .id("extension-source")
 847                                    .mt_0p5()
 848                                    .mx_1()
 849                                    .tooltip(Tooltip::text(source_tooltip))
 850                                    .child(
 851                                        Icon::new(source_icon)
 852                                            .size(IconSize::Small)
 853                                            .color(Color::Muted),
 854                                    ),
 855                            )
 856                            .when(is_running, |this| {
 857                                this.child(
 858                                    Label::new(if tool_count == 1 {
 859                                        SharedString::from("1 tool")
 860                                    } else {
 861                                        SharedString::from(format!("{} tools", tool_count))
 862                                    })
 863                                    .color(Color::Muted)
 864                                    .size(LabelSize::Small),
 865                                )
 866                            }),
 867                    )
 868                    .child(
 869                        h_flex()
 870                            .gap_1()
 871                            .child(context_server_configuration_menu)
 872                            .child(
 873                                Switch::new("context-server-switch", is_running.into())
 874                                    .color(SwitchColor::Accent)
 875                                    .on_click({
 876                                        let context_server_manager =
 877                                            self.context_server_store.clone();
 878                                        let fs = self.fs.clone();
 879
 880                                        move |state, _window, cx| {
 881                                            let is_enabled = match state {
 882                                                ToggleState::Unselected
 883                                                | ToggleState::Indeterminate => {
 884                                                    context_server_manager.update(
 885                                                        cx,
 886                                                        |this, cx| {
 887                                                            this.stop_server(
 888                                                                &context_server_id,
 889                                                                cx,
 890                                                            )
 891                                                            .log_err();
 892                                                        },
 893                                                    );
 894                                                    false
 895                                                }
 896                                                ToggleState::Selected => {
 897                                                    context_server_manager.update(
 898                                                        cx,
 899                                                        |this, cx| {
 900                                                            if let Some(server) =
 901                                                                this.get_server(&context_server_id)
 902                                                            {
 903                                                                this.start_server(server, cx);
 904                                                            }
 905                                                        },
 906                                                    );
 907                                                    true
 908                                                }
 909                                            };
 910                                            update_settings_file::<ProjectSettings>(
 911                                                fs.clone(),
 912                                                cx,
 913                                                {
 914                                                    let context_server_id =
 915                                                        context_server_id.clone();
 916
 917                                                    move |settings, _| {
 918                                                        settings
 919                                                            .context_servers
 920                                                            .entry(context_server_id.0)
 921                                                            .or_insert_with(|| {
 922                                                                ContextServerSettings::Extension {
 923                                                                    enabled: is_enabled,
 924                                                                    settings: serde_json::json!({}),
 925                                                                }
 926                                                            })
 927                                                            .set_enabled(is_enabled);
 928                                                    }
 929                                                },
 930                                            );
 931                                        }
 932                                    }),
 933                            ),
 934                    ),
 935            )
 936            .map(|parent| {
 937                if let Some(error) = error {
 938                    return parent.child(
 939                        h_flex()
 940                            .p_2()
 941                            .gap_2()
 942                            .items_start()
 943                            .child(
 944                                h_flex()
 945                                    .flex_none()
 946                                    .h(window.line_height() / 1.6_f32)
 947                                    .justify_center()
 948                                    .child(
 949                                        Icon::new(IconName::XCircle)
 950                                            .size(IconSize::XSmall)
 951                                            .color(Color::Error),
 952                                    ),
 953                            )
 954                            .child(
 955                                div().w_full().child(
 956                                    Label::new(error)
 957                                        .buffer_font(cx)
 958                                        .color(Color::Muted)
 959                                        .size(LabelSize::Small),
 960                                ),
 961                            ),
 962                    );
 963                }
 964
 965                if !are_tools_expanded || tools.is_empty() {
 966                    return parent;
 967                }
 968
 969                parent.child(v_flex().py_1p5().px_1().gap_1().children(
 970                    tools.iter().enumerate().map(|(ix, tool)| {
 971                        h_flex()
 972                            .id(("tool-item", ix))
 973                            .px_1()
 974                            .gap_2()
 975                            .justify_between()
 976                            .hover(|style| style.bg(cx.theme().colors().element_hover))
 977                            .rounded_sm()
 978                            .child(
 979                                Label::new(tool.name())
 980                                    .buffer_font(cx)
 981                                    .size(LabelSize::Small),
 982                            )
 983                            .child(
 984                                Icon::new(IconName::Info)
 985                                    .size(IconSize::Small)
 986                                    .color(Color::Ignored),
 987                            )
 988                            .tooltip(Tooltip::text(tool.description()))
 989                    }),
 990                ))
 991            })
 992    }
 993
 994    fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 995        let settings = AllAgentServersSettings::get_global(cx).clone();
 996        let user_defined_agents = settings
 997            .iter()
 998            .filter(|(name, _)| *name != "gemini" && *name != "claude")
 999            .sorted_by(|(l, _), (r, _)| l.cmp(r))
1000            .map(|(name, command)| {
1001                self.render_agent_server(
1002                    IconName::Ai,
1003                    name.clone(),
1004                    ExternalAgent::Custom {
1005                        name: name.clone(),
1006                        command: command.clone(),
1007                    },
1008                    cx,
1009                )
1010                .into_any_element()
1011            })
1012            .collect::<Vec<_>>();
1013
1014        v_flex()
1015            .border_b_1()
1016            .border_color(cx.theme().colors().border)
1017            .child(
1018                v_flex()
1019                    .p(DynamicSpacing::Base16.rems(cx))
1020                    .pr(DynamicSpacing::Base20.rems(cx))
1021                    .gap_2()
1022                    .child(
1023                        v_flex()
1024                            .gap_0p5()
1025                            .child(
1026                                h_flex()
1027                                    .pr_1()
1028                                    .w_full()
1029                                    .gap_2()
1030                                    .justify_between()
1031                                    .child(Headline::new("External Agents"))
1032                                    .child(
1033                                        Button::new("add-agent", "Add Agent")
1034                                            .icon_position(IconPosition::Start)
1035                                            .icon(IconName::Plus)
1036                                            .icon_size(IconSize::Small)
1037                                            .icon_color(Color::Muted)
1038                                            .label_size(LabelSize::Small)
1039                                            .on_click(
1040                                                move |_, window, cx| {
1041                                                    if let Some(workspace) = window.root().flatten() {
1042                                                        let workspace = workspace.downgrade();
1043                                                        window
1044                                                            .spawn(cx, async |cx| {
1045                                                                open_new_agent_servers_entry_in_settings_editor(
1046                                                                    workspace,
1047                                                                    cx,
1048                                                                ).await
1049                                                            })
1050                                                            .detach_and_log_err(cx);
1051                                                    }
1052                                                }
1053                                            ),
1054                                    )
1055                            )
1056                            .child(
1057                                Label::new(
1058                                    "All agents connected through the Agent Client Protocol.",
1059                                )
1060                                .color(Color::Muted),
1061                            ),
1062                    )
1063                    .child(self.render_agent_server(
1064                        IconName::AiGemini,
1065                        "Gemini CLI",
1066                        ExternalAgent::Gemini,
1067                        cx,
1068                    ))
1069                    .child(self.render_agent_server(
1070                        IconName::AiClaude,
1071                        "Claude Code",
1072                        ExternalAgent::ClaudeCode,
1073                        cx,
1074                    ))
1075                    .children(user_defined_agents),
1076            )
1077    }
1078
1079    fn render_agent_server(
1080        &self,
1081        icon: IconName,
1082        name: impl Into<SharedString>,
1083        agent: ExternalAgent,
1084        cx: &mut Context<Self>,
1085    ) -> impl IntoElement {
1086        let name = name.into();
1087        h_flex()
1088            .p_1()
1089            .pl_2()
1090            .gap_1p5()
1091            .justify_between()
1092            .border_1()
1093            .rounded_md()
1094            .border_color(self.card_item_border_color(cx))
1095            .bg(self.card_item_bg_color(cx))
1096            .overflow_hidden()
1097            .child(
1098                h_flex()
1099                    .gap_1p5()
1100                    .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1101                    .child(Label::new(name.clone())),
1102            )
1103            .child(
1104                Button::new(
1105                    SharedString::from(format!("start_acp_thread-{name}")),
1106                    "Start New Thread",
1107                )
1108                .label_size(LabelSize::Small)
1109                .icon(IconName::Thread)
1110                .icon_position(IconPosition::Start)
1111                .icon_size(IconSize::XSmall)
1112                .icon_color(Color::Muted)
1113                .on_click(move |_, window, cx| {
1114                    window.dispatch_action(
1115                        NewExternalAgentThread {
1116                            agent: Some(agent.clone()),
1117                        }
1118                        .boxed_clone(),
1119                        cx,
1120                    );
1121                }),
1122            )
1123    }
1124}
1125
1126impl Render for AgentConfiguration {
1127    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1128        v_flex()
1129            .id("assistant-configuration")
1130            .key_context("AgentConfiguration")
1131            .track_focus(&self.focus_handle(cx))
1132            .relative()
1133            .size_full()
1134            .pb_8()
1135            .bg(cx.theme().colors().panel_background)
1136            .child(
1137                v_flex()
1138                    .id("assistant-configuration-content")
1139                    .track_scroll(&self.scroll_handle)
1140                    .size_full()
1141                    .overflow_y_scroll()
1142                    .child(self.render_general_settings_section(cx))
1143                    .child(self.render_agent_servers_section(cx))
1144                    .child(self.render_context_servers_section(window, cx))
1145                    .child(self.render_provider_configuration_section(cx)),
1146            )
1147            .child(
1148                div()
1149                    .id("assistant-configuration-scrollbar")
1150                    .occlude()
1151                    .absolute()
1152                    .right(px(3.))
1153                    .top_0()
1154                    .bottom_0()
1155                    .pb_6()
1156                    .w(px(12.))
1157                    .cursor_default()
1158                    .on_mouse_move(cx.listener(|_, _, _window, cx| {
1159                        cx.notify();
1160                        cx.stop_propagation()
1161                    }))
1162                    .on_hover(|_, _window, cx| {
1163                        cx.stop_propagation();
1164                    })
1165                    .on_any_mouse_down(|_, _window, cx| {
1166                        cx.stop_propagation();
1167                    })
1168                    .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
1169                        cx.notify();
1170                    }))
1171                    .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1172            )
1173    }
1174}
1175
1176fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1177    manifest.context_servers.len() == 1
1178        && manifest.themes.is_empty()
1179        && manifest.icon_themes.is_empty()
1180        && manifest.languages.is_empty()
1181        && manifest.grammars.is_empty()
1182        && manifest.language_servers.is_empty()
1183        && manifest.slash_commands.is_empty()
1184        && manifest.snippets.is_none()
1185        && manifest.debug_locators.is_empty()
1186}
1187
1188pub(crate) fn resolve_extension_for_context_server(
1189    id: &ContextServerId,
1190    cx: &App,
1191) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1192    ExtensionStore::global(cx)
1193        .read(cx)
1194        .installed_extensions()
1195        .iter()
1196        .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1197        .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1198}
1199
1200// This notification appears when trying to delete
1201// an MCP server extension that not only provides
1202// the server, but other things, too, like language servers and more.
1203fn show_unable_to_uninstall_extension_with_context_server(
1204    workspace: &mut Workspace,
1205    id: ContextServerId,
1206    cx: &mut App,
1207) {
1208    let workspace_handle = workspace.weak_handle();
1209    let context_server_id = id.clone();
1210
1211    let status_toast = StatusToast::new(
1212        format!(
1213            "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1214            id.0
1215        ),
1216        cx,
1217        move |this, _cx| {
1218            let workspace_handle = workspace_handle.clone();
1219
1220            this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1221                .dismiss_button(true)
1222                .action("Uninstall", move |_, _cx| {
1223                    if let Some((extension_id, _)) =
1224                        resolve_extension_for_context_server(&context_server_id, _cx)
1225                    {
1226                        ExtensionStore::global(_cx).update(_cx, |store, cx| {
1227                            store
1228                                .uninstall_extension(extension_id, cx)
1229                                .detach_and_log_err(cx);
1230                        });
1231
1232                        workspace_handle
1233                            .update(_cx, |workspace, cx| {
1234                                let fs = workspace.app_state().fs.clone();
1235                                cx.spawn({
1236                                    let context_server_id = context_server_id.clone();
1237                                    async move |_workspace_handle, cx| {
1238                                        cx.update(|cx| {
1239                                            update_settings_file::<ProjectSettings>(
1240                                                fs,
1241                                                cx,
1242                                                move |settings, _| {
1243                                                    settings
1244                                                        .context_servers
1245                                                        .remove(&context_server_id.0);
1246                                                },
1247                                            );
1248                                        })?;
1249                                        anyhow::Ok(())
1250                                    }
1251                                })
1252                                .detach_and_log_err(cx);
1253                            })
1254                            .log_err();
1255                    }
1256                })
1257        },
1258    );
1259
1260    workspace.toggle_status_toast(status_toast, cx);
1261}
1262
1263async fn open_new_agent_servers_entry_in_settings_editor(
1264    workspace: WeakEntity<Workspace>,
1265    cx: &mut AsyncWindowContext,
1266) -> Result<()> {
1267    let settings_editor = workspace
1268        .update_in(cx, |_, window, cx| {
1269            create_and_open_local_file(paths::settings_file(), window, cx, || {
1270                settings::initial_user_settings_content().as_ref().into()
1271            })
1272        })?
1273        .await?
1274        .downcast::<Editor>()
1275        .unwrap();
1276
1277    settings_editor
1278        .downgrade()
1279        .update_in(cx, |item, window, cx| {
1280            let text = item.buffer().read(cx).snapshot(cx).text();
1281
1282            let settings = cx.global::<SettingsStore>();
1283
1284            let mut unique_server_name = None;
1285            // FIXME test that this still works
1286            let edits = settings.edits_for_update::<AllAgentServersSettings>(&text, |file| {
1287                let server_name: Option<SharedString> = (0..u8::MAX)
1288                    .map(|i| {
1289                        if i == 0 {
1290                            "your_agent".into()
1291                        } else {
1292                            format!("your_agent_{}", i).into()
1293                        }
1294                    })
1295                    .find(|name| !file.custom.contains_key(name));
1296                if let Some(server_name) = server_name {
1297                    unique_server_name = Some(server_name.clone());
1298                    file.custom.insert(
1299                        server_name,
1300                        AgentServerCommand {
1301                            path: "path_to_executable".into(),
1302                            args: vec![],
1303                            env: Some(HashMap::default()),
1304                        },
1305                    );
1306                }
1307            });
1308
1309            if edits.is_empty() {
1310                return;
1311            }
1312
1313            let ranges = edits
1314                .iter()
1315                .map(|(range, _)| range.clone())
1316                .collect::<Vec<_>>();
1317
1318            item.edit(edits, cx);
1319            if let Some((unique_server_name, buffer)) =
1320                unique_server_name.zip(item.buffer().read(cx).as_singleton())
1321            {
1322                let snapshot = buffer.read(cx).snapshot();
1323                if let Some(range) =
1324                    find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1325                {
1326                    item.change_selections(
1327                        SelectionEffects::scroll(Autoscroll::newest()),
1328                        window,
1329                        cx,
1330                        |selections| {
1331                            selections.select_ranges(vec![range]);
1332                        },
1333                    );
1334                }
1335            }
1336        })
1337}
1338
1339fn find_text_in_buffer(
1340    text: &str,
1341    start: usize,
1342    snapshot: &language::BufferSnapshot,
1343) -> Option<Range<usize>> {
1344    let chars = text.chars().collect::<Vec<char>>();
1345
1346    let mut offset = start;
1347    let mut char_offset = 0;
1348    for c in snapshot.chars_at(start) {
1349        if char_offset >= chars.len() {
1350            break;
1351        }
1352        offset += 1;
1353
1354        if c == chars[char_offset] {
1355            char_offset += 1;
1356        } else {
1357            char_offset = 0;
1358        }
1359    }
1360
1361    if char_offset == chars.len() {
1362        Some(offset.saturating_sub(chars.len())..offset)
1363    } else {
1364        None
1365    }
1366}