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 | Plan::ZedFreeV2 => ("Free", Color::Default, free_chip_bg),
 519                Plan::ZedProTrial | Plan::ZedProTrialV2 => {
 520                    ("Pro Trial", Color::Accent, pro_chip_bg)
 521                }
 522                Plan::ZedPro | Plan::ZedProV2 => ("Pro", Color::Accent, pro_chip_bg),
 523            };
 524
 525            Chip::new(plan_name.to_string())
 526                .bg_color(bg_color)
 527                .label_color(label_color)
 528                .into_any_element()
 529        } else {
 530            div().into_any_element()
 531        }
 532    }
 533
 534    fn card_item_bg_color(&self, cx: &mut Context<Self>) -> Hsla {
 535        cx.theme().colors().background.opacity(0.25)
 536    }
 537
 538    fn card_item_border_color(&self, cx: &mut Context<Self>) -> Hsla {
 539        cx.theme().colors().border.opacity(0.6)
 540    }
 541
 542    fn render_context_servers_section(
 543        &mut self,
 544        window: &mut Window,
 545        cx: &mut Context<Self>,
 546    ) -> impl IntoElement {
 547        let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
 548
 549        v_flex()
 550            .p(DynamicSpacing::Base16.rems(cx))
 551            .pr(DynamicSpacing::Base20.rems(cx))
 552            .gap_2()
 553            .border_b_1()
 554            .border_color(cx.theme().colors().border)
 555            .child(
 556                v_flex()
 557                    .gap_0p5()
 558                    .child(Headline::new("Model Context Protocol (MCP) Servers"))
 559                    .child(
 560                        Label::new(
 561                            "All context servers connected through the Model Context Protocol.",
 562                        )
 563                        .color(Color::Muted),
 564                    ),
 565            )
 566            .children(
 567                context_server_ids.into_iter().map(|context_server_id| {
 568                    self.render_context_server(context_server_id, window, cx)
 569                }),
 570            )
 571            .child(
 572                h_flex()
 573                    .justify_between()
 574                    .gap_1p5()
 575                    .child(
 576                        h_flex().w_full().child(
 577                            Button::new("add-context-server", "Add Custom Server")
 578                                .style(ButtonStyle::Filled)
 579                                .layer(ElevationIndex::ModalSurface)
 580                                .full_width()
 581                                .icon(IconName::Plus)
 582                                .icon_size(IconSize::Small)
 583                                .icon_position(IconPosition::Start)
 584                                .on_click(|_event, window, cx| {
 585                                    window.dispatch_action(AddContextServer.boxed_clone(), cx)
 586                                }),
 587                        ),
 588                    )
 589                    .child(
 590                        h_flex().w_full().child(
 591                            Button::new(
 592                                "install-context-server-extensions",
 593                                "Install MCP Extensions",
 594                            )
 595                            .style(ButtonStyle::Filled)
 596                            .layer(ElevationIndex::ModalSurface)
 597                            .full_width()
 598                            .icon(IconName::ToolHammer)
 599                            .icon_size(IconSize::Small)
 600                            .icon_position(IconPosition::Start)
 601                            .on_click(|_event, window, cx| {
 602                                window.dispatch_action(
 603                                    zed_actions::Extensions {
 604                                        category_filter: Some(
 605                                            ExtensionCategoryFilter::ContextServers,
 606                                        ),
 607                                        id: None,
 608                                    }
 609                                    .boxed_clone(),
 610                                    cx,
 611                                )
 612                            }),
 613                        ),
 614                    ),
 615            )
 616    }
 617
 618    fn render_context_server(
 619        &self,
 620        context_server_id: ContextServerId,
 621        window: &mut Window,
 622        cx: &mut Context<Self>,
 623    ) -> impl use<> + IntoElement {
 624        let tools_by_source = self.tools.read(cx).tools_by_source(cx);
 625        let server_status = self
 626            .context_server_store
 627            .read(cx)
 628            .status_for_server(&context_server_id)
 629            .unwrap_or(ContextServerStatus::Stopped);
 630        let server_configuration = self
 631            .context_server_store
 632            .read(cx)
 633            .configuration_for_server(&context_server_id);
 634
 635        let is_running = matches!(server_status, ContextServerStatus::Running);
 636        let item_id = SharedString::from(context_server_id.0.clone());
 637        let is_from_extension = server_configuration
 638            .as_ref()
 639            .map(|config| {
 640                matches!(
 641                    config.as_ref(),
 642                    ContextServerConfiguration::Extension { .. }
 643                )
 644            })
 645            .unwrap_or(false);
 646
 647        let error = if let ContextServerStatus::Error(error) = server_status.clone() {
 648            Some(error)
 649        } else {
 650            None
 651        };
 652
 653        let are_tools_expanded = self
 654            .expanded_context_server_tools
 655            .get(&context_server_id)
 656            .copied()
 657            .unwrap_or_default();
 658        let tools = tools_by_source
 659            .get(&ToolSource::ContextServer {
 660                id: context_server_id.0.clone().into(),
 661            })
 662            .map_or([].as_slice(), |tools| tools.as_slice());
 663        let tool_count = tools.len();
 664
 665        let (source_icon, source_tooltip) = if is_from_extension {
 666            (
 667                IconName::ZedMcpExtension,
 668                "This MCP server was installed from an extension.",
 669            )
 670        } else {
 671            (
 672                IconName::ZedMcpCustom,
 673                "This custom MCP server was installed directly.",
 674            )
 675        };
 676
 677        let (status_indicator, tooltip_text) = match server_status {
 678            ContextServerStatus::Starting => (
 679                Icon::new(IconName::LoadCircle)
 680                    .size(IconSize::XSmall)
 681                    .color(Color::Accent)
 682                    .with_keyed_rotate_animation(
 683                        SharedString::from(format!("{}-starting", context_server_id.0)),
 684                        3,
 685                    )
 686                    .into_any_element(),
 687                "Server is starting.",
 688            ),
 689            ContextServerStatus::Running => (
 690                Indicator::dot().color(Color::Success).into_any_element(),
 691                "Server is active.",
 692            ),
 693            ContextServerStatus::Error(_) => (
 694                Indicator::dot().color(Color::Error).into_any_element(),
 695                "Server has an error.",
 696            ),
 697            ContextServerStatus::Stopped => (
 698                Indicator::dot().color(Color::Muted).into_any_element(),
 699                "Server is stopped.",
 700            ),
 701        };
 702
 703        let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
 704            .trigger_with_tooltip(
 705                IconButton::new("context-server-config-menu", IconName::Settings)
 706                    .icon_color(Color::Muted)
 707                    .icon_size(IconSize::Small),
 708                Tooltip::text("Open MCP server options"),
 709            )
 710            .anchor(Corner::TopRight)
 711            .menu({
 712                let fs = self.fs.clone();
 713                let context_server_id = context_server_id.clone();
 714                let language_registry = self.language_registry.clone();
 715                let context_server_store = self.context_server_store.clone();
 716                let workspace = self.workspace.clone();
 717                move |window, cx| {
 718                    Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
 719                        menu.entry("Configure Server", None, {
 720                            let context_server_id = context_server_id.clone();
 721                            let language_registry = language_registry.clone();
 722                            let workspace = workspace.clone();
 723                            move |window, cx| {
 724                                ConfigureContextServerModal::show_modal_for_existing_server(
 725                                    context_server_id.clone(),
 726                                    language_registry.clone(),
 727                                    workspace.clone(),
 728                                    window,
 729                                    cx,
 730                                )
 731                                .detach_and_log_err(cx);
 732                            }
 733                        })
 734                        .separator()
 735                        .entry("Uninstall", None, {
 736                            let fs = fs.clone();
 737                            let context_server_id = context_server_id.clone();
 738                            let context_server_store = context_server_store.clone();
 739                            let workspace = workspace.clone();
 740                            move |_, cx| {
 741                                let is_provided_by_extension = context_server_store
 742                                    .read(cx)
 743                                    .configuration_for_server(&context_server_id)
 744                                    .as_ref()
 745                                    .map(|config| {
 746                                        matches!(
 747                                            config.as_ref(),
 748                                            ContextServerConfiguration::Extension { .. }
 749                                        )
 750                                    })
 751                                    .unwrap_or(false);
 752
 753                                let uninstall_extension_task = match (
 754                                    is_provided_by_extension,
 755                                    resolve_extension_for_context_server(&context_server_id, cx),
 756                                ) {
 757                                    (true, Some((id, manifest))) => {
 758                                        if extension_only_provides_context_server(manifest.as_ref())
 759                                        {
 760                                            ExtensionStore::global(cx).update(cx, |store, cx| {
 761                                                store.uninstall_extension(id, cx)
 762                                            })
 763                                        } else {
 764                                            workspace.update(cx, |workspace, cx| {
 765                                                show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
 766                                            }).log_err();
 767                                            Task::ready(Ok(()))
 768                                        }
 769                                    }
 770                                    _ => Task::ready(Ok(())),
 771                                };
 772
 773                                cx.spawn({
 774                                    let fs = fs.clone();
 775                                    let context_server_id = context_server_id.clone();
 776                                    async move |cx| {
 777                                        uninstall_extension_task.await?;
 778                                        cx.update(|cx| {
 779                                            update_settings_file::<ProjectSettings>(
 780                                                fs.clone(),
 781                                                cx,
 782                                                {
 783                                                    let context_server_id =
 784                                                        context_server_id.clone();
 785                                                    move |settings, _| {
 786                                                        settings
 787                                                            .context_servers
 788                                                            .remove(&context_server_id.0);
 789                                                    }
 790                                                },
 791                                            )
 792                                        })
 793                                    }
 794                                })
 795                                .detach_and_log_err(cx);
 796                            }
 797                        })
 798                    }))
 799                }
 800            });
 801
 802        v_flex()
 803            .id(item_id.clone())
 804            .border_1()
 805            .rounded_md()
 806            .border_color(self.card_item_border_color(cx))
 807            .bg(self.card_item_bg_color(cx))
 808            .overflow_hidden()
 809            .child(
 810                h_flex()
 811                    .p_1()
 812                    .justify_between()
 813                    .when(
 814                        error.is_some() || are_tools_expanded && tool_count >= 1,
 815                        |element| {
 816                            element
 817                                .border_b_1()
 818                                .border_color(self.card_item_border_color(cx))
 819                        },
 820                    )
 821                    .child(
 822                        h_flex()
 823                            .child(
 824                                Disclosure::new(
 825                                    "tool-list-disclosure",
 826                                    are_tools_expanded || error.is_some(),
 827                                )
 828                                .disabled(tool_count == 0)
 829                                .on_click(cx.listener({
 830                                    let context_server_id = context_server_id.clone();
 831                                    move |this, _event, _window, _cx| {
 832                                        let is_open = this
 833                                            .expanded_context_server_tools
 834                                            .entry(context_server_id.clone())
 835                                            .or_insert(false);
 836
 837                                        *is_open = !*is_open;
 838                                    }
 839                                })),
 840                            )
 841                            .child(
 842                                h_flex()
 843                                    .id(SharedString::from(format!("tooltip-{}", item_id)))
 844                                    .h_full()
 845                                    .w_3()
 846                                    .mx_1()
 847                                    .justify_center()
 848                                    .tooltip(Tooltip::text(tooltip_text))
 849                                    .child(status_indicator),
 850                            )
 851                            .child(Label::new(item_id).ml_0p5())
 852                            .child(
 853                                div()
 854                                    .id("extension-source")
 855                                    .mt_0p5()
 856                                    .mx_1()
 857                                    .tooltip(Tooltip::text(source_tooltip))
 858                                    .child(
 859                                        Icon::new(source_icon)
 860                                            .size(IconSize::Small)
 861                                            .color(Color::Muted),
 862                                    ),
 863                            )
 864                            .when(is_running, |this| {
 865                                this.child(
 866                                    Label::new(if tool_count == 1 {
 867                                        SharedString::from("1 tool")
 868                                    } else {
 869                                        SharedString::from(format!("{} tools", tool_count))
 870                                    })
 871                                    .color(Color::Muted)
 872                                    .size(LabelSize::Small),
 873                                )
 874                            }),
 875                    )
 876                    .child(
 877                        h_flex()
 878                            .gap_1()
 879                            .child(context_server_configuration_menu)
 880                            .child(
 881                                Switch::new("context-server-switch", is_running.into())
 882                                    .color(SwitchColor::Accent)
 883                                    .on_click({
 884                                        let context_server_manager =
 885                                            self.context_server_store.clone();
 886                                        let fs = self.fs.clone();
 887
 888                                        move |state, _window, cx| {
 889                                            let is_enabled = match state {
 890                                                ToggleState::Unselected
 891                                                | ToggleState::Indeterminate => {
 892                                                    context_server_manager.update(
 893                                                        cx,
 894                                                        |this, cx| {
 895                                                            this.stop_server(
 896                                                                &context_server_id,
 897                                                                cx,
 898                                                            )
 899                                                            .log_err();
 900                                                        },
 901                                                    );
 902                                                    false
 903                                                }
 904                                                ToggleState::Selected => {
 905                                                    context_server_manager.update(
 906                                                        cx,
 907                                                        |this, cx| {
 908                                                            if let Some(server) =
 909                                                                this.get_server(&context_server_id)
 910                                                            {
 911                                                                this.start_server(server, cx);
 912                                                            }
 913                                                        },
 914                                                    );
 915                                                    true
 916                                                }
 917                                            };
 918                                            update_settings_file::<ProjectSettings>(
 919                                                fs.clone(),
 920                                                cx,
 921                                                {
 922                                                    let context_server_id =
 923                                                        context_server_id.clone();
 924
 925                                                    move |settings, _| {
 926                                                        settings
 927                                                            .context_servers
 928                                                            .entry(context_server_id.0)
 929                                                            .or_insert_with(|| {
 930                                                                ContextServerSettings::Extension {
 931                                                                    enabled: is_enabled,
 932                                                                    settings: serde_json::json!({}),
 933                                                                }
 934                                                            })
 935                                                            .set_enabled(is_enabled);
 936                                                    }
 937                                                },
 938                                            );
 939                                        }
 940                                    }),
 941                            ),
 942                    ),
 943            )
 944            .map(|parent| {
 945                if let Some(error) = error {
 946                    return parent.child(
 947                        h_flex()
 948                            .p_2()
 949                            .gap_2()
 950                            .items_start()
 951                            .child(
 952                                h_flex()
 953                                    .flex_none()
 954                                    .h(window.line_height() / 1.6_f32)
 955                                    .justify_center()
 956                                    .child(
 957                                        Icon::new(IconName::XCircle)
 958                                            .size(IconSize::XSmall)
 959                                            .color(Color::Error),
 960                                    ),
 961                            )
 962                            .child(
 963                                div().w_full().child(
 964                                    Label::new(error)
 965                                        .buffer_font(cx)
 966                                        .color(Color::Muted)
 967                                        .size(LabelSize::Small),
 968                                ),
 969                            ),
 970                    );
 971                }
 972
 973                if !are_tools_expanded || tools.is_empty() {
 974                    return parent;
 975                }
 976
 977                parent.child(v_flex().py_1p5().px_1().gap_1().children(
 978                    tools.iter().enumerate().map(|(ix, tool)| {
 979                        h_flex()
 980                            .id(("tool-item", ix))
 981                            .px_1()
 982                            .gap_2()
 983                            .justify_between()
 984                            .hover(|style| style.bg(cx.theme().colors().element_hover))
 985                            .rounded_sm()
 986                            .child(
 987                                Label::new(tool.name())
 988                                    .buffer_font(cx)
 989                                    .size(LabelSize::Small),
 990                            )
 991                            .child(
 992                                Icon::new(IconName::Info)
 993                                    .size(IconSize::Small)
 994                                    .color(Color::Ignored),
 995                            )
 996                            .tooltip(Tooltip::text(tool.description()))
 997                    }),
 998                ))
 999            })
1000    }
1001
1002    fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
1003        let custom_settings = cx
1004            .global::<SettingsStore>()
1005            .get::<AllAgentServersSettings>(None)
1006            .custom
1007            .clone();
1008        let user_defined_agents = self
1009            .agent_server_store
1010            .read(cx)
1011            .external_agents()
1012            .filter(|name| name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME)
1013            .cloned()
1014            .collect::<Vec<_>>();
1015        let user_defined_agents = user_defined_agents
1016            .into_iter()
1017            .map(|name| {
1018                self.render_agent_server(
1019                    IconName::Ai,
1020                    name.clone(),
1021                    ExternalAgent::Custom {
1022                        name: name.clone().into(),
1023                        command: custom_settings
1024                            .get(&name.0)
1025                            .map(|settings| settings.command.clone())
1026                            .unwrap_or(placeholder_command()),
1027                    },
1028                    cx,
1029                )
1030                .into_any_element()
1031            })
1032            .collect::<Vec<_>>();
1033
1034        v_flex()
1035            .border_b_1()
1036            .border_color(cx.theme().colors().border)
1037            .child(
1038                v_flex()
1039                    .p(DynamicSpacing::Base16.rems(cx))
1040                    .pr(DynamicSpacing::Base20.rems(cx))
1041                    .gap_2()
1042                    .child(
1043                        v_flex()
1044                            .gap_0p5()
1045                            .child(
1046                                h_flex()
1047                                    .pr_1()
1048                                    .w_full()
1049                                    .gap_2()
1050                                    .justify_between()
1051                                    .child(Headline::new("External Agents"))
1052                                    .child(
1053                                        Button::new("add-agent", "Add Agent")
1054                                            .icon_position(IconPosition::Start)
1055                                            .icon(IconName::Plus)
1056                                            .icon_size(IconSize::Small)
1057                                            .icon_color(Color::Muted)
1058                                            .label_size(LabelSize::Small)
1059                                            .on_click(
1060                                                move |_, window, cx| {
1061                                                    if let Some(workspace) = window.root().flatten() {
1062                                                        let workspace = workspace.downgrade();
1063                                                        window
1064                                                            .spawn(cx, async |cx| {
1065                                                                open_new_agent_servers_entry_in_settings_editor(
1066                                                                    workspace,
1067                                                                    cx,
1068                                                                ).await
1069                                                            })
1070                                                            .detach_and_log_err(cx);
1071                                                    }
1072                                                }
1073                                            ),
1074                                    )
1075                            )
1076                            .child(
1077                                Label::new(
1078                                    "All agents connected through the Agent Client Protocol.",
1079                                )
1080                                .color(Color::Muted),
1081                            ),
1082                    )
1083                    .child(self.render_agent_server(
1084                        IconName::AiGemini,
1085                        "Gemini CLI",
1086                        ExternalAgent::Gemini,
1087                        cx,
1088                    ))
1089                    .child(self.render_agent_server(
1090                        IconName::AiClaude,
1091                        "Claude Code",
1092                        ExternalAgent::ClaudeCode,
1093                        cx,
1094                    ))
1095                    .children(user_defined_agents),
1096            )
1097    }
1098
1099    fn render_agent_server(
1100        &self,
1101        icon: IconName,
1102        name: impl Into<SharedString>,
1103        agent: ExternalAgent,
1104        cx: &mut Context<Self>,
1105    ) -> impl IntoElement {
1106        let name = name.into();
1107        h_flex()
1108            .p_1()
1109            .pl_2()
1110            .gap_1p5()
1111            .justify_between()
1112            .border_1()
1113            .rounded_md()
1114            .border_color(self.card_item_border_color(cx))
1115            .bg(self.card_item_bg_color(cx))
1116            .overflow_hidden()
1117            .child(
1118                h_flex()
1119                    .gap_1p5()
1120                    .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1121                    .child(Label::new(name.clone())),
1122            )
1123            .child(
1124                Button::new(
1125                    SharedString::from(format!("start_acp_thread-{name}")),
1126                    "Start New Thread",
1127                )
1128                .label_size(LabelSize::Small)
1129                .icon(IconName::Thread)
1130                .icon_position(IconPosition::Start)
1131                .icon_size(IconSize::XSmall)
1132                .icon_color(Color::Muted)
1133                .on_click(move |_, window, cx| {
1134                    window.dispatch_action(
1135                        NewExternalAgentThread {
1136                            agent: Some(agent.clone()),
1137                        }
1138                        .boxed_clone(),
1139                        cx,
1140                    );
1141                }),
1142            )
1143    }
1144}
1145
1146impl Render for AgentConfiguration {
1147    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1148        v_flex()
1149            .id("assistant-configuration")
1150            .key_context("AgentConfiguration")
1151            .track_focus(&self.focus_handle(cx))
1152            .relative()
1153            .size_full()
1154            .pb_8()
1155            .bg(cx.theme().colors().panel_background)
1156            .child(
1157                v_flex()
1158                    .id("assistant-configuration-content")
1159                    .track_scroll(&self.scroll_handle)
1160                    .size_full()
1161                    .overflow_y_scroll()
1162                    .child(self.render_general_settings_section(cx))
1163                    .child(self.render_agent_servers_section(cx))
1164                    .child(self.render_context_servers_section(window, cx))
1165                    .child(self.render_provider_configuration_section(cx)),
1166            )
1167            .child(
1168                div()
1169                    .id("assistant-configuration-scrollbar")
1170                    .occlude()
1171                    .absolute()
1172                    .right(px(3.))
1173                    .top_0()
1174                    .bottom_0()
1175                    .pb_6()
1176                    .w(px(12.))
1177                    .cursor_default()
1178                    .on_mouse_move(cx.listener(|_, _, _window, cx| {
1179                        cx.notify();
1180                        cx.stop_propagation()
1181                    }))
1182                    .on_hover(|_, _window, cx| {
1183                        cx.stop_propagation();
1184                    })
1185                    .on_any_mouse_down(|_, _window, cx| {
1186                        cx.stop_propagation();
1187                    })
1188                    .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
1189                        cx.notify();
1190                    }))
1191                    .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1192            )
1193    }
1194}
1195
1196fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1197    manifest.context_servers.len() == 1
1198        && manifest.themes.is_empty()
1199        && manifest.icon_themes.is_empty()
1200        && manifest.languages.is_empty()
1201        && manifest.grammars.is_empty()
1202        && manifest.language_servers.is_empty()
1203        && manifest.slash_commands.is_empty()
1204        && manifest.snippets.is_none()
1205        && manifest.debug_locators.is_empty()
1206}
1207
1208pub(crate) fn resolve_extension_for_context_server(
1209    id: &ContextServerId,
1210    cx: &App,
1211) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1212    ExtensionStore::global(cx)
1213        .read(cx)
1214        .installed_extensions()
1215        .iter()
1216        .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1217        .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1218}
1219
1220// This notification appears when trying to delete
1221// an MCP server extension that not only provides
1222// the server, but other things, too, like language servers and more.
1223fn show_unable_to_uninstall_extension_with_context_server(
1224    workspace: &mut Workspace,
1225    id: ContextServerId,
1226    cx: &mut App,
1227) {
1228    let workspace_handle = workspace.weak_handle();
1229    let context_server_id = id.clone();
1230
1231    let status_toast = StatusToast::new(
1232        format!(
1233            "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1234            id.0
1235        ),
1236        cx,
1237        move |this, _cx| {
1238            let workspace_handle = workspace_handle.clone();
1239
1240            this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1241                .dismiss_button(true)
1242                .action("Uninstall", move |_, _cx| {
1243                    if let Some((extension_id, _)) =
1244                        resolve_extension_for_context_server(&context_server_id, _cx)
1245                    {
1246                        ExtensionStore::global(_cx).update(_cx, |store, cx| {
1247                            store
1248                                .uninstall_extension(extension_id, cx)
1249                                .detach_and_log_err(cx);
1250                        });
1251
1252                        workspace_handle
1253                            .update(_cx, |workspace, cx| {
1254                                let fs = workspace.app_state().fs.clone();
1255                                cx.spawn({
1256                                    let context_server_id = context_server_id.clone();
1257                                    async move |_workspace_handle, cx| {
1258                                        cx.update(|cx| {
1259                                            update_settings_file::<ProjectSettings>(
1260                                                fs,
1261                                                cx,
1262                                                move |settings, _| {
1263                                                    settings
1264                                                        .context_servers
1265                                                        .remove(&context_server_id.0);
1266                                                },
1267                                            );
1268                                        })?;
1269                                        anyhow::Ok(())
1270                                    }
1271                                })
1272                                .detach_and_log_err(cx);
1273                            })
1274                            .log_err();
1275                    }
1276                })
1277        },
1278    );
1279
1280    workspace.toggle_status_toast(status_toast, cx);
1281}
1282
1283async fn open_new_agent_servers_entry_in_settings_editor(
1284    workspace: WeakEntity<Workspace>,
1285    cx: &mut AsyncWindowContext,
1286) -> Result<()> {
1287    let settings_editor = workspace
1288        .update_in(cx, |_, window, cx| {
1289            create_and_open_local_file(paths::settings_file(), window, cx, || {
1290                settings::initial_user_settings_content().as_ref().into()
1291            })
1292        })?
1293        .await?
1294        .downcast::<Editor>()
1295        .unwrap();
1296
1297    settings_editor
1298        .downgrade()
1299        .update_in(cx, |item, window, cx| {
1300            let text = item.buffer().read(cx).snapshot(cx).text();
1301
1302            let settings = cx.global::<SettingsStore>();
1303
1304            let mut unique_server_name = None;
1305            let edits = settings.edits_for_update::<AllAgentServersSettings>(&text, |file| {
1306                let server_name: Option<SharedString> = (0..u8::MAX)
1307                    .map(|i| {
1308                        if i == 0 {
1309                            "your_agent".into()
1310                        } else {
1311                            format!("your_agent_{}", i).into()
1312                        }
1313                    })
1314                    .find(|name| !file.custom.contains_key(name));
1315                if let Some(server_name) = server_name {
1316                    unique_server_name = Some(server_name.clone());
1317                    file.custom.insert(
1318                        server_name,
1319                        CustomAgentServerSettings {
1320                            command: AgentServerCommand {
1321                                path: "path_to_executable".into(),
1322                                args: vec![],
1323                                env: Some(HashMap::default()),
1324                            },
1325                            default_mode: None,
1326                        },
1327                    );
1328                }
1329            });
1330
1331            if edits.is_empty() {
1332                return;
1333            }
1334
1335            let ranges = edits
1336                .iter()
1337                .map(|(range, _)| range.clone())
1338                .collect::<Vec<_>>();
1339
1340            item.edit(edits, cx);
1341            if let Some((unique_server_name, buffer)) =
1342                unique_server_name.zip(item.buffer().read(cx).as_singleton())
1343            {
1344                let snapshot = buffer.read(cx).snapshot();
1345                if let Some(range) =
1346                    find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1347                {
1348                    item.change_selections(
1349                        SelectionEffects::scroll(Autoscroll::newest()),
1350                        window,
1351                        cx,
1352                        |selections| {
1353                            selections.select_ranges(vec![range]);
1354                        },
1355                    );
1356                }
1357            }
1358        })
1359}
1360
1361fn find_text_in_buffer(
1362    text: &str,
1363    start: usize,
1364    snapshot: &language::BufferSnapshot,
1365) -> Option<Range<usize>> {
1366    let chars = text.chars().collect::<Vec<char>>();
1367
1368    let mut offset = start;
1369    let mut char_offset = 0;
1370    for c in snapshot.chars_at(start) {
1371        if char_offset >= chars.len() {
1372            break;
1373        }
1374        offset += 1;
1375
1376        if c == chars[char_offset] {
1377            char_offset += 1;
1378        } else {
1379            char_offset = 0;
1380        }
1381    }
1382
1383    if char_offset == chars.len() {
1384        Some(offset.saturating_sub(chars.len())..offset)
1385    } else {
1386        None
1387    }
1388}