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