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