agent_configuration.rs

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