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