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