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