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