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, time::Duration};
   7
   8use agent_servers::{AgentServerCommand, AllAgentServersSettings, CustomAgentServerSettings};
   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, Animation, AnimationExt as _, AnyView, App, AsyncWindowContext, Corner, Entity,
  21    EventEmitter, FocusHandle, Focusable, Hsla, ScrollHandle, Subscription, Task, Transformation,
  22    WeakEntity, percentage,
  23};
  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, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex, Indicator, PopoverMenu,
  36    Scrollbar, ScrollbarState, Switch, SwitchColor, SwitchField, Tooltip, prelude::*,
  37};
  38use util::ResultExt as _;
  39use workspace::{Workspace, create_and_open_local_file};
  40use zed_actions::ExtensionCategoryFilter;
  41
  42pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
  43pub(crate) use manage_profiles_modal::ManageProfilesModal;
  44
  45use crate::{
  46    AddContextServer, ExternalAgent, NewExternalAgentThread,
  47    agent_configuration::add_llm_provider_modal::{AddLlmProviderModal, LlmCompatibleProvider},
  48};
  49
  50pub struct AgentConfiguration {
  51    fs: Arc<dyn Fs>,
  52    language_registry: Arc<LanguageRegistry>,
  53    workspace: WeakEntity<Workspace>,
  54    focus_handle: FocusHandle,
  55    configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
  56    context_server_store: Entity<ContextServerStore>,
  57    expanded_context_server_tools: HashMap<ContextServerId, bool>,
  58    expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
  59    tools: Entity<ToolWorkingSet>,
  60    _registry_subscription: Subscription,
  61    scroll_handle: ScrollHandle,
  62    scrollbar_state: ScrollbarState,
  63    _check_for_gemini: Task<()>,
  64}
  65
  66impl AgentConfiguration {
  67    pub fn new(
  68        fs: Arc<dyn Fs>,
  69        context_server_store: Entity<ContextServerStore>,
  70        tools: Entity<ToolWorkingSet>,
  71        language_registry: Arc<LanguageRegistry>,
  72        workspace: WeakEntity<Workspace>,
  73        window: &mut Window,
  74        cx: &mut Context<Self>,
  75    ) -> Self {
  76        let focus_handle = cx.focus_handle();
  77
  78        let registry_subscription = cx.subscribe_in(
  79            &LanguageModelRegistry::global(cx),
  80            window,
  81            |this, _, event: &language_model::Event, window, cx| match event {
  82                language_model::Event::AddedProvider(provider_id) => {
  83                    let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
  84                    if let Some(provider) = provider {
  85                        this.add_provider_configuration_view(&provider, window, cx);
  86                    }
  87                }
  88                language_model::Event::RemovedProvider(provider_id) => {
  89                    this.remove_provider_configuration_view(provider_id);
  90                }
  91                _ => {}
  92            },
  93        );
  94
  95        cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
  96            .detach();
  97
  98        let scroll_handle = ScrollHandle::new();
  99        let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
 100
 101        let mut this = Self {
 102            fs,
 103            language_registry,
 104            workspace,
 105            focus_handle,
 106            configuration_views_by_provider: HashMap::default(),
 107            context_server_store,
 108            expanded_context_server_tools: HashMap::default(),
 109            expanded_provider_configurations: HashMap::default(),
 110            tools,
 111            _registry_subscription: registry_subscription,
 112            scroll_handle,
 113            scrollbar_state,
 114            _check_for_gemini: Task::ready(()),
 115        };
 116        this.build_provider_configuration_views(window, cx);
 117        this
 118    }
 119
 120    fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 121        let providers = LanguageModelRegistry::read_global(cx).providers();
 122        for provider in providers {
 123            self.add_provider_configuration_view(&provider, window, cx);
 124        }
 125    }
 126
 127    fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
 128        self.configuration_views_by_provider.remove(provider_id);
 129        self.expanded_provider_configurations.remove(provider_id);
 130    }
 131
 132    fn add_provider_configuration_view(
 133        &mut self,
 134        provider: &Arc<dyn LanguageModelProvider>,
 135        window: &mut Window,
 136        cx: &mut Context<Self>,
 137    ) {
 138        let configuration_view = provider.configuration_view(
 139            language_model::ConfigurationViewTargetAgent::ZedAgent,
 140            window,
 141            cx,
 142        );
 143        self.configuration_views_by_provider
 144            .insert(provider.id(), configuration_view);
 145    }
 146}
 147
 148impl Focusable for AgentConfiguration {
 149    fn focus_handle(&self, _: &App) -> FocusHandle {
 150        self.focus_handle.clone()
 151    }
 152}
 153
 154pub enum AssistantConfigurationEvent {
 155    NewThread(Arc<dyn LanguageModelProvider>),
 156}
 157
 158impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
 159
 160impl AgentConfiguration {
 161    fn render_provider_configuration_block(
 162        &mut self,
 163        provider: &Arc<dyn LanguageModelProvider>,
 164        cx: &mut Context<Self>,
 165    ) -> impl IntoElement + use<> {
 166        let provider_id = provider.id().0;
 167        let provider_name = provider.name().0;
 168        let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
 169
 170        let configuration_view = self
 171            .configuration_views_by_provider
 172            .get(&provider.id())
 173            .cloned();
 174
 175        let is_expanded = self
 176            .expanded_provider_configurations
 177            .get(&provider.id())
 178            .copied()
 179            .unwrap_or(false);
 180
 181        let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
 182        let current_plan = if is_zed_provider {
 183            self.workspace
 184                .upgrade()
 185                .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
 186        } else {
 187            None
 188        };
 189
 190        let is_signed_in = self
 191            .workspace
 192            .read_with(cx, |workspace, _| {
 193                !workspace.client().status().borrow().is_signed_out()
 194            })
 195            .unwrap_or(false);
 196
 197        v_flex()
 198            .w_full()
 199            .when(is_expanded, |this| this.mb_2())
 200            .child(
 201                div()
 202                    .opacity(0.6)
 203                    .px_2()
 204                    .child(Divider::horizontal().color(DividerColor::Border)),
 205            )
 206            .child(
 207                h_flex()
 208                    .map(|this| {
 209                        if is_expanded {
 210                            this.mt_2().mb_1()
 211                        } else {
 212                            this.my_2()
 213                        }
 214                    })
 215                    .w_full()
 216                    .justify_between()
 217                    .child(
 218                        h_flex()
 219                            .id(provider_id_string.clone())
 220                            .px_2()
 221                            .py_0p5()
 222                            .w_full()
 223                            .justify_between()
 224                            .rounded_sm()
 225                            .hover(|hover| hover.bg(cx.theme().colors().element_hover))
 226                            .child(
 227                                h_flex()
 228                                    .w_full()
 229                                    .gap_2()
 230                                    .child(
 231                                        Icon::new(provider.icon())
 232                                            .size(IconSize::Small)
 233                                            .color(Color::Muted),
 234                                    )
 235                                    .child(
 236                                        h_flex()
 237                                            .w_full()
 238                                            .gap_1()
 239                                            .child(Label::new(provider_name.clone()))
 240                                            .map(|this| {
 241                                                if is_zed_provider && is_signed_in {
 242                                                    this.child(
 243                                                        self.render_zed_plan_info(current_plan, cx),
 244                                                    )
 245                                                } else {
 246                                                    this.when(
 247                                                        provider.is_authenticated(cx)
 248                                                            && !is_expanded,
 249                                                        |parent| {
 250                                                            parent.child(
 251                                                                Icon::new(IconName::Check)
 252                                                                    .color(Color::Success),
 253                                                            )
 254                                                        },
 255                                                    )
 256                                                }
 257                                            }),
 258                                    ),
 259                            )
 260                            .child(
 261                                Disclosure::new(provider_id_string, is_expanded)
 262                                    .opened_icon(IconName::ChevronUp)
 263                                    .closed_icon(IconName::ChevronDown),
 264                            )
 265                            .on_click(cx.listener({
 266                                let provider_id = provider.id();
 267                                move |this, _event, _window, _cx| {
 268                                    let is_expanded = this
 269                                        .expanded_provider_configurations
 270                                        .entry(provider_id.clone())
 271                                        .or_insert(false);
 272
 273                                    *is_expanded = !*is_expanded;
 274                                }
 275                            })),
 276                    )
 277                    .when(provider.is_authenticated(cx), |parent| {
 278                        parent.child(
 279                            Button::new(
 280                                SharedString::from(format!("new-thread-{provider_id}")),
 281                                "Start New Thread",
 282                            )
 283                            .icon_position(IconPosition::Start)
 284                            .icon(IconName::Thread)
 285                            .icon_size(IconSize::Small)
 286                            .icon_color(Color::Muted)
 287                            .label_size(LabelSize::Small)
 288                            .on_click(cx.listener({
 289                                let provider = provider.clone();
 290                                move |_this, _event, _window, cx| {
 291                                    cx.emit(AssistantConfigurationEvent::NewThread(
 292                                        provider.clone(),
 293                                    ))
 294                                }
 295                            })),
 296                        )
 297                    }),
 298            )
 299            .child(
 300                div()
 301                    .w_full()
 302                    .px_2()
 303                    .when(is_expanded, |parent| match configuration_view {
 304                        Some(configuration_view) => parent.child(configuration_view),
 305                        None => parent.child(Label::new(format!(
 306                            "No configuration view for {provider_name}",
 307                        ))),
 308                    }),
 309            )
 310    }
 311
 312    fn render_provider_configuration_section(
 313        &mut self,
 314        cx: &mut Context<Self>,
 315    ) -> impl IntoElement {
 316        let providers = LanguageModelRegistry::read_global(cx).providers();
 317
 318        v_flex()
 319            .w_full()
 320            .child(
 321                h_flex()
 322                    .p(DynamicSpacing::Base16.rems(cx))
 323                    .pr(DynamicSpacing::Base20.rems(cx))
 324                    .pb_0()
 325                    .mb_2p5()
 326                    .items_start()
 327                    .justify_between()
 328                    .child(
 329                        v_flex()
 330                            .w_full()
 331                            .gap_0p5()
 332                            .child(
 333                                h_flex()
 334                                    .pr_1()
 335                                    .w_full()
 336                                    .gap_2()
 337                                    .justify_between()
 338                                    .child(Headline::new("LLM Providers"))
 339                                    .child(
 340                                        PopoverMenu::new("add-provider-popover")
 341                                            .trigger(
 342                                                Button::new("add-provider", "Add Provider")
 343                                                    .icon_position(IconPosition::Start)
 344                                                    .icon(IconName::Plus)
 345                                                    .icon_size(IconSize::Small)
 346                                                    .icon_color(Color::Muted)
 347                                                    .label_size(LabelSize::Small),
 348                                            )
 349                                            .anchor(gpui::Corner::TopRight)
 350                                            .menu({
 351                                                let workspace = self.workspace.clone();
 352                                                move |window, cx| {
 353                                                    Some(ContextMenu::build(
 354                                                        window,
 355                                                        cx,
 356                                                        |menu, _window, _cx| {
 357                                                            menu.header("Compatible APIs").entry(
 358                                                                "OpenAI",
 359                                                                None,
 360                                                                {
 361                                                                    let workspace =
 362                                                                        workspace.clone();
 363                                                                    move |window, cx| {
 364                                                                        workspace
 365                                                        .update(cx, |workspace, cx| {
 366                                                            AddLlmProviderModal::toggle(
 367                                                                LlmCompatibleProvider::OpenAi,
 368                                                                workspace,
 369                                                                window,
 370                                                                cx,
 371                                                            );
 372                                                        })
 373                                                        .log_err();
 374                                                                    }
 375                                                                },
 376                                                            )
 377                                                        },
 378                                                    ))
 379                                                }
 380                                            }),
 381                                    ),
 382                            )
 383                            .child(
 384                                Label::new("Add at least one provider to use AI-powered features with Zed's native agent.")
 385                                    .color(Color::Muted),
 386                            ),
 387                    ),
 388            )
 389            .child(
 390                div()
 391                    .w_full()
 392                    .pl(DynamicSpacing::Base08.rems(cx))
 393                    .pr(DynamicSpacing::Base20.rems(cx))
 394                    .children(
 395                        providers.into_iter().map(|provider| {
 396                            self.render_provider_configuration_block(&provider, cx)
 397                        }),
 398                    ),
 399            )
 400    }
 401
 402    fn render_command_permission(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 403        let always_allow_tool_actions = AgentSettings::get_global(cx).always_allow_tool_actions;
 404        let fs = self.fs.clone();
 405
 406        SwitchField::new(
 407            "always-allow-tool-actions-switch",
 408            "Allow running commands without asking for confirmation",
 409            Some(
 410                "The agent can perform potentially destructive actions without asking for your confirmation.".into(),
 411            ),
 412            always_allow_tool_actions,
 413            move |state, _window, cx| {
 414                let allow = state == &ToggleState::Selected;
 415                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 416                    settings.set_always_allow_tool_actions(allow);
 417                });
 418            },
 419        )
 420    }
 421
 422    fn render_single_file_review(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 423        let single_file_review = AgentSettings::get_global(cx).single_file_review;
 424        let fs = self.fs.clone();
 425
 426        SwitchField::new(
 427            "single-file-review",
 428            "Enable single-file agent reviews",
 429            Some("Agent edits are also displayed in single-file editors for review.".into()),
 430            single_file_review,
 431            move |state, _window, cx| {
 432                let allow = state == &ToggleState::Selected;
 433                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 434                    settings.set_single_file_review(allow);
 435                });
 436            },
 437        )
 438    }
 439
 440    fn render_sound_notification(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 441        let play_sound_when_agent_done = AgentSettings::get_global(cx).play_sound_when_agent_done;
 442        let fs = self.fs.clone();
 443
 444        SwitchField::new(
 445            "sound-notification",
 446            "Play sound when finished generating",
 447            Some(
 448                "Hear a notification sound when the agent is done generating changes or needs your input.".into(),
 449            ),
 450            play_sound_when_agent_done,
 451            move |state, _window, cx| {
 452                let allow = state == &ToggleState::Selected;
 453                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 454                    settings.set_play_sound_when_agent_done(allow);
 455                });
 456            },
 457        )
 458    }
 459
 460    fn render_modifier_to_send(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 461        let use_modifier_to_send = AgentSettings::get_global(cx).use_modifier_to_send;
 462        let fs = self.fs.clone();
 463
 464        SwitchField::new(
 465            "modifier-send",
 466            "Use modifier to submit a message",
 467            Some(
 468                "Make a modifier (cmd-enter on macOS, ctrl-enter on Linux or Windows) required to send messages.".into(),
 469            ),
 470            use_modifier_to_send,
 471            move |state, _window, cx| {
 472                let allow = state == &ToggleState::Selected;
 473                update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
 474                    settings.set_use_modifier_to_send(allow);
 475                });
 476            },
 477        )
 478    }
 479
 480    fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
 481        v_flex()
 482            .p(DynamicSpacing::Base16.rems(cx))
 483            .pr(DynamicSpacing::Base20.rems(cx))
 484            .gap_2p5()
 485            .border_b_1()
 486            .border_color(cx.theme().colors().border)
 487            .child(Headline::new("General Settings"))
 488            .child(self.render_command_permission(cx))
 489            .child(self.render_single_file_review(cx))
 490            .child(self.render_sound_notification(cx))
 491            .child(self.render_modifier_to_send(cx))
 492    }
 493
 494    fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
 495        if let Some(plan) = plan {
 496            let free_chip_bg = cx
 497                .theme()
 498                .colors()
 499                .editor_background
 500                .opacity(0.5)
 501                .blend(cx.theme().colors().text_accent.opacity(0.05));
 502
 503            let pro_chip_bg = cx
 504                .theme()
 505                .colors()
 506                .editor_background
 507                .opacity(0.5)
 508                .blend(cx.theme().colors().text_accent.opacity(0.2));
 509
 510            let (plan_name, label_color, bg_color) = match plan {
 511                Plan::ZedFree => ("Free", Color::Default, free_chip_bg),
 512                Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
 513                Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
 514            };
 515
 516            Chip::new(plan_name.to_string())
 517                .bg_color(bg_color)
 518                .label_color(label_color)
 519                .into_any_element()
 520        } else {
 521            div().into_any_element()
 522        }
 523    }
 524
 525    fn card_item_bg_color(&self, cx: &mut Context<Self>) -> Hsla {
 526        cx.theme().colors().background.opacity(0.25)
 527    }
 528
 529    fn card_item_border_color(&self, cx: &mut Context<Self>) -> Hsla {
 530        cx.theme().colors().border.opacity(0.6)
 531    }
 532
 533    fn render_context_servers_section(
 534        &mut self,
 535        window: &mut Window,
 536        cx: &mut Context<Self>,
 537    ) -> impl IntoElement {
 538        let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
 539
 540        v_flex()
 541            .p(DynamicSpacing::Base16.rems(cx))
 542            .pr(DynamicSpacing::Base20.rems(cx))
 543            .gap_2()
 544            .border_b_1()
 545            .border_color(cx.theme().colors().border)
 546            .child(
 547                v_flex()
 548                    .gap_0p5()
 549                    .child(Headline::new("Model Context Protocol (MCP) Servers"))
 550                    .child(
 551                        Label::new(
 552                            "All context servers connected through the Model Context Protocol.",
 553                        )
 554                        .color(Color::Muted),
 555                    ),
 556            )
 557            .children(
 558                context_server_ids.into_iter().map(|context_server_id| {
 559                    self.render_context_server(context_server_id, window, cx)
 560                }),
 561            )
 562            .child(
 563                h_flex()
 564                    .justify_between()
 565                    .gap_1p5()
 566                    .child(
 567                        h_flex().w_full().child(
 568                            Button::new("add-context-server", "Add Custom Server")
 569                                .style(ButtonStyle::Filled)
 570                                .layer(ElevationIndex::ModalSurface)
 571                                .full_width()
 572                                .icon(IconName::Plus)
 573                                .icon_size(IconSize::Small)
 574                                .icon_position(IconPosition::Start)
 575                                .on_click(|_event, window, cx| {
 576                                    window.dispatch_action(AddContextServer.boxed_clone(), cx)
 577                                }),
 578                        ),
 579                    )
 580                    .child(
 581                        h_flex().w_full().child(
 582                            Button::new(
 583                                "install-context-server-extensions",
 584                                "Install MCP Extensions",
 585                            )
 586                            .style(ButtonStyle::Filled)
 587                            .layer(ElevationIndex::ModalSurface)
 588                            .full_width()
 589                            .icon(IconName::ToolHammer)
 590                            .icon_size(IconSize::Small)
 591                            .icon_position(IconPosition::Start)
 592                            .on_click(|_event, window, cx| {
 593                                window.dispatch_action(
 594                                    zed_actions::Extensions {
 595                                        category_filter: Some(
 596                                            ExtensionCategoryFilter::ContextServers,
 597                                        ),
 598                                        id: None,
 599                                    }
 600                                    .boxed_clone(),
 601                                    cx,
 602                                )
 603                            }),
 604                        ),
 605                    ),
 606            )
 607    }
 608
 609    fn render_context_server(
 610        &self,
 611        context_server_id: ContextServerId,
 612        window: &mut Window,
 613        cx: &mut Context<Self>,
 614    ) -> impl use<> + IntoElement {
 615        let tools_by_source = self.tools.read(cx).tools_by_source(cx);
 616        let server_status = self
 617            .context_server_store
 618            .read(cx)
 619            .status_for_server(&context_server_id)
 620            .unwrap_or(ContextServerStatus::Stopped);
 621        let server_configuration = self
 622            .context_server_store
 623            .read(cx)
 624            .configuration_for_server(&context_server_id);
 625
 626        let is_running = matches!(server_status, ContextServerStatus::Running);
 627        let item_id = SharedString::from(context_server_id.0.clone());
 628        let is_from_extension = server_configuration
 629            .as_ref()
 630            .map(|config| {
 631                matches!(
 632                    config.as_ref(),
 633                    ContextServerConfiguration::Extension { .. }
 634                )
 635            })
 636            .unwrap_or(false);
 637
 638        let error = if let ContextServerStatus::Error(error) = server_status.clone() {
 639            Some(error)
 640        } else {
 641            None
 642        };
 643
 644        let are_tools_expanded = self
 645            .expanded_context_server_tools
 646            .get(&context_server_id)
 647            .copied()
 648            .unwrap_or_default();
 649        let tools = tools_by_source
 650            .get(&ToolSource::ContextServer {
 651                id: context_server_id.0.clone().into(),
 652            })
 653            .map_or([].as_slice(), |tools| tools.as_slice());
 654        let tool_count = tools.len();
 655
 656        let (source_icon, source_tooltip) = if is_from_extension {
 657            (
 658                IconName::ZedMcpExtension,
 659                "This MCP server was installed from an extension.",
 660            )
 661        } else {
 662            (
 663                IconName::ZedMcpCustom,
 664                "This custom MCP server was installed directly.",
 665            )
 666        };
 667
 668        let (status_indicator, tooltip_text) = match server_status {
 669            ContextServerStatus::Starting => (
 670                Icon::new(IconName::LoadCircle)
 671                    .size(IconSize::XSmall)
 672                    .color(Color::Accent)
 673                    .with_animation(
 674                        SharedString::from(format!("{}-starting", context_server_id.0,)),
 675                        Animation::new(Duration::from_secs(3)).repeat(),
 676                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
 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            .custom
 998            .iter()
 999            .map(|(name, settings)| {
1000                self.render_agent_server(
1001                    IconName::Ai,
1002                    name.clone(),
1003                    ExternalAgent::Custom {
1004                        name: name.clone(),
1005                        command: settings.command.clone(),
1006                    },
1007                    cx,
1008                )
1009                .into_any_element()
1010            })
1011            .collect::<Vec<_>>();
1012
1013        v_flex()
1014            .border_b_1()
1015            .border_color(cx.theme().colors().border)
1016            .child(
1017                v_flex()
1018                    .p(DynamicSpacing::Base16.rems(cx))
1019                    .pr(DynamicSpacing::Base20.rems(cx))
1020                    .gap_2()
1021                    .child(
1022                        v_flex()
1023                            .gap_0p5()
1024                            .child(
1025                                h_flex()
1026                                    .pr_1()
1027                                    .w_full()
1028                                    .gap_2()
1029                                    .justify_between()
1030                                    .child(Headline::new("External Agents"))
1031                                    .child(
1032                                        Button::new("add-agent", "Add Agent")
1033                                            .icon_position(IconPosition::Start)
1034                                            .icon(IconName::Plus)
1035                                            .icon_size(IconSize::Small)
1036                                            .icon_color(Color::Muted)
1037                                            .label_size(LabelSize::Small)
1038                                            .on_click(
1039                                                move |_, window, cx| {
1040                                                    if let Some(workspace) = window.root().flatten() {
1041                                                        let workspace = workspace.downgrade();
1042                                                        window
1043                                                            .spawn(cx, async |cx| {
1044                                                                open_new_agent_servers_entry_in_settings_editor(
1045                                                                    workspace,
1046                                                                    cx,
1047                                                                ).await
1048                                                            })
1049                                                            .detach_and_log_err(cx);
1050                                                    }
1051                                                }
1052                                            ),
1053                                    )
1054                            )
1055                            .child(
1056                                Label::new(
1057                                    "All agents connected through the Agent Client Protocol.",
1058                                )
1059                                .color(Color::Muted),
1060                            ),
1061                    )
1062                    .child(self.render_agent_server(
1063                        IconName::AiGemini,
1064                        "Gemini CLI",
1065                        ExternalAgent::Gemini,
1066                        cx,
1067                    ))
1068                    .child(self.render_agent_server(
1069                        IconName::AiClaude,
1070                        "Claude Code",
1071                        ExternalAgent::ClaudeCode,
1072                        cx,
1073                    ))
1074                    .children(user_defined_agents),
1075            )
1076    }
1077
1078    fn render_agent_server(
1079        &self,
1080        icon: IconName,
1081        name: impl Into<SharedString>,
1082        agent: ExternalAgent,
1083        cx: &mut Context<Self>,
1084    ) -> impl IntoElement {
1085        let name = name.into();
1086        h_flex()
1087            .p_1()
1088            .pl_2()
1089            .gap_1p5()
1090            .justify_between()
1091            .border_1()
1092            .rounded_md()
1093            .border_color(self.card_item_border_color(cx))
1094            .bg(self.card_item_bg_color(cx))
1095            .overflow_hidden()
1096            .child(
1097                h_flex()
1098                    .gap_1p5()
1099                    .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1100                    .child(Label::new(name.clone())),
1101            )
1102            .child(
1103                Button::new(
1104                    SharedString::from(format!("start_acp_thread-{name}")),
1105                    "Start New Thread",
1106                )
1107                .label_size(LabelSize::Small)
1108                .icon(IconName::Thread)
1109                .icon_position(IconPosition::Start)
1110                .icon_size(IconSize::XSmall)
1111                .icon_color(Color::Muted)
1112                .on_click(move |_, window, cx| {
1113                    window.dispatch_action(
1114                        NewExternalAgentThread {
1115                            agent: Some(agent.clone()),
1116                        }
1117                        .boxed_clone(),
1118                        cx,
1119                    );
1120                }),
1121            )
1122    }
1123}
1124
1125impl Render for AgentConfiguration {
1126    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1127        v_flex()
1128            .id("assistant-configuration")
1129            .key_context("AgentConfiguration")
1130            .track_focus(&self.focus_handle(cx))
1131            .relative()
1132            .size_full()
1133            .pb_8()
1134            .bg(cx.theme().colors().panel_background)
1135            .child(
1136                v_flex()
1137                    .id("assistant-configuration-content")
1138                    .track_scroll(&self.scroll_handle)
1139                    .size_full()
1140                    .overflow_y_scroll()
1141                    .child(self.render_general_settings_section(cx))
1142                    .child(self.render_agent_servers_section(cx))
1143                    .child(self.render_context_servers_section(window, cx))
1144                    .child(self.render_provider_configuration_section(cx)),
1145            )
1146            .child(
1147                div()
1148                    .id("assistant-configuration-scrollbar")
1149                    .occlude()
1150                    .absolute()
1151                    .right(px(3.))
1152                    .top_0()
1153                    .bottom_0()
1154                    .pb_6()
1155                    .w(px(12.))
1156                    .cursor_default()
1157                    .on_mouse_move(cx.listener(|_, _, _window, cx| {
1158                        cx.notify();
1159                        cx.stop_propagation()
1160                    }))
1161                    .on_hover(|_, _window, cx| {
1162                        cx.stop_propagation();
1163                    })
1164                    .on_any_mouse_down(|_, _window, cx| {
1165                        cx.stop_propagation();
1166                    })
1167                    .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
1168                        cx.notify();
1169                    }))
1170                    .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1171            )
1172    }
1173}
1174
1175fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1176    manifest.context_servers.len() == 1
1177        && manifest.themes.is_empty()
1178        && manifest.icon_themes.is_empty()
1179        && manifest.languages.is_empty()
1180        && manifest.grammars.is_empty()
1181        && manifest.language_servers.is_empty()
1182        && manifest.slash_commands.is_empty()
1183        && manifest.snippets.is_none()
1184        && manifest.debug_locators.is_empty()
1185}
1186
1187pub(crate) fn resolve_extension_for_context_server(
1188    id: &ContextServerId,
1189    cx: &App,
1190) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1191    ExtensionStore::global(cx)
1192        .read(cx)
1193        .installed_extensions()
1194        .iter()
1195        .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1196        .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1197}
1198
1199// This notification appears when trying to delete
1200// an MCP server extension that not only provides
1201// the server, but other things, too, like language servers and more.
1202fn show_unable_to_uninstall_extension_with_context_server(
1203    workspace: &mut Workspace,
1204    id: ContextServerId,
1205    cx: &mut App,
1206) {
1207    let workspace_handle = workspace.weak_handle();
1208    let context_server_id = id.clone();
1209
1210    let status_toast = StatusToast::new(
1211        format!(
1212            "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1213            id.0
1214        ),
1215        cx,
1216        move |this, _cx| {
1217            let workspace_handle = workspace_handle.clone();
1218
1219            this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1220                .dismiss_button(true)
1221                .action("Uninstall", move |_, _cx| {
1222                    if let Some((extension_id, _)) =
1223                        resolve_extension_for_context_server(&context_server_id, _cx)
1224                    {
1225                        ExtensionStore::global(_cx).update(_cx, |store, cx| {
1226                            store
1227                                .uninstall_extension(extension_id, cx)
1228                                .detach_and_log_err(cx);
1229                        });
1230
1231                        workspace_handle
1232                            .update(_cx, |workspace, cx| {
1233                                let fs = workspace.app_state().fs.clone();
1234                                cx.spawn({
1235                                    let context_server_id = context_server_id.clone();
1236                                    async move |_workspace_handle, cx| {
1237                                        cx.update(|cx| {
1238                                            update_settings_file::<ProjectSettings>(
1239                                                fs,
1240                                                cx,
1241                                                move |settings, _| {
1242                                                    settings
1243                                                        .context_servers
1244                                                        .remove(&context_server_id.0);
1245                                                },
1246                                            );
1247                                        })?;
1248                                        anyhow::Ok(())
1249                                    }
1250                                })
1251                                .detach_and_log_err(cx);
1252                            })
1253                            .log_err();
1254                    }
1255                })
1256        },
1257    );
1258
1259    workspace.toggle_status_toast(status_toast, cx);
1260}
1261
1262async fn open_new_agent_servers_entry_in_settings_editor(
1263    workspace: WeakEntity<Workspace>,
1264    cx: &mut AsyncWindowContext,
1265) -> Result<()> {
1266    let settings_editor = workspace
1267        .update_in(cx, |_, window, cx| {
1268            create_and_open_local_file(paths::settings_file(), window, cx, || {
1269                settings::initial_user_settings_content().as_ref().into()
1270            })
1271        })?
1272        .await?
1273        .downcast::<Editor>()
1274        .unwrap();
1275
1276    settings_editor
1277        .downgrade()
1278        .update_in(cx, |item, window, cx| {
1279            let text = item.buffer().read(cx).snapshot(cx).text();
1280
1281            let settings = cx.global::<SettingsStore>();
1282
1283            let mut unique_server_name = None;
1284            let edits = settings.edits_for_update::<AllAgentServersSettings>(&text, |file| {
1285                let server_name: Option<SharedString> = (0..u8::MAX)
1286                    .map(|i| {
1287                        if i == 0 {
1288                            "your_agent".into()
1289                        } else {
1290                            format!("your_agent_{}", i).into()
1291                        }
1292                    })
1293                    .find(|name| !file.custom.contains_key(name));
1294                if let Some(server_name) = server_name {
1295                    unique_server_name = Some(server_name.clone());
1296                    file.custom.insert(
1297                        server_name,
1298                        CustomAgentServerSettings {
1299                            command: AgentServerCommand {
1300                                path: "path_to_executable".into(),
1301                                args: vec![],
1302                                env: Some(HashMap::default()),
1303                            },
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}