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 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::{AgentServerStore, ExternalAgentServerName, ExternalAgentSource},
32 context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
33};
34use settings::{Settings, SettingsStore, update_settings_file};
35use ui::{
36 ButtonStyle, Chip, CommonAnimationExt, ContextMenu, ContextMenuEntry, Disclosure, Divider,
37 DividerColor, ElevationIndex, Indicator, LabelSize, PopoverMenu, Switch, Tooltip,
38 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::agent_configuration::add_llm_provider_modal::{
49 AddLlmProviderModal, LlmCompatibleProvider,
50};
51
52pub struct AgentConfiguration {
53 fs: Arc<dyn Fs>,
54 language_registry: Arc<LanguageRegistry>,
55 agent_server_store: Entity<AgentServerStore>,
56 workspace: WeakEntity<Workspace>,
57 focus_handle: FocusHandle,
58 configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
59 context_server_store: Entity<ContextServerStore>,
60 expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
61 context_server_registry: Entity<ContextServerRegistry>,
62 _registry_subscription: Subscription,
63 scroll_handle: ScrollHandle,
64 _check_for_gemini: Task<()>,
65}
66
67impl AgentConfiguration {
68 pub fn new(
69 fs: Arc<dyn Fs>,
70 agent_server_store: Entity<AgentServerStore>,
71 context_server_store: Entity<ContextServerStore>,
72 context_server_registry: Entity<ContextServerRegistry>,
73 language_registry: Arc<LanguageRegistry>,
74 workspace: WeakEntity<Workspace>,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) -> Self {
78 let focus_handle = cx.focus_handle();
79
80 let registry_subscription = cx.subscribe_in(
81 &LanguageModelRegistry::global(cx),
82 window,
83 |this, _, event: &language_model::Event, window, cx| match event {
84 language_model::Event::AddedProvider(provider_id) => {
85 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
86 if let Some(provider) = provider {
87 this.add_provider_configuration_view(&provider, window, cx);
88 }
89 }
90 language_model::Event::RemovedProvider(provider_id) => {
91 this.remove_provider_configuration_view(provider_id);
92 }
93 _ => {}
94 },
95 );
96
97 cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
98 .detach();
99
100 let mut this = Self {
101 fs,
102 language_registry,
103 workspace,
104 focus_handle,
105 configuration_views_by_provider: HashMap::default(),
106 agent_server_store,
107 context_server_store,
108 expanded_provider_configurations: HashMap::default(),
109 context_server_registry,
110 _registry_subscription: registry_subscription,
111 scroll_handle: ScrollHandle::new(),
112 _check_for_gemini: Task::ready(()),
113 };
114 this.build_provider_configuration_views(window, cx);
115 this
116 }
117
118 fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
119 let providers = LanguageModelRegistry::read_global(cx).visible_providers();
120 for provider in providers {
121 self.add_provider_configuration_view(&provider, window, cx);
122 }
123 }
124
125 fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
126 self.configuration_views_by_provider.remove(provider_id);
127 self.expanded_provider_configurations.remove(provider_id);
128 }
129
130 fn add_provider_configuration_view(
131 &mut self,
132 provider: &Arc<dyn LanguageModelProvider>,
133 window: &mut Window,
134 cx: &mut Context<Self>,
135 ) {
136 let configuration_view = provider.configuration_view(
137 language_model::ConfigurationViewTargetAgent::ZedAgent,
138 window,
139 cx,
140 );
141 self.configuration_views_by_provider
142 .insert(provider.id(), configuration_view);
143 }
144}
145
146impl Focusable for AgentConfiguration {
147 fn focus_handle(&self, _: &App) -> FocusHandle {
148 self.focus_handle.clone()
149 }
150}
151
152pub enum AssistantConfigurationEvent {
153 NewThread(Arc<dyn LanguageModelProvider>),
154}
155
156impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
157
158enum AgentIcon {
159 Name(IconName),
160 Path(SharedString),
161}
162
163impl AgentConfiguration {
164 fn render_section_title(
165 &mut self,
166 title: impl Into<SharedString>,
167 description: impl Into<SharedString>,
168 menu: AnyElement,
169 ) -> impl IntoElement {
170 h_flex()
171 .p_4()
172 .pb_0()
173 .mb_2p5()
174 .items_start()
175 .justify_between()
176 .child(
177 v_flex()
178 .w_full()
179 .gap_0p5()
180 .child(
181 h_flex()
182 .pr_1()
183 .w_full()
184 .gap_2()
185 .justify_between()
186 .flex_wrap()
187 .child(Headline::new(title.into()))
188 .child(menu),
189 )
190 .child(Label::new(description.into()).color(Color::Muted)),
191 )
192 }
193
194 fn render_provider_configuration_block(
195 &mut self,
196 provider: &Arc<dyn LanguageModelProvider>,
197 cx: &mut Context<Self>,
198 ) -> impl IntoElement + use<> {
199 let provider_id = provider.id().0;
200 let provider_name = provider.name().0;
201 let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
202
203 let configuration_view = self
204 .configuration_views_by_provider
205 .get(&provider.id())
206 .cloned();
207
208 let is_expanded = self
209 .expanded_provider_configurations
210 .get(&provider.id())
211 .copied()
212 .unwrap_or(false);
213
214 let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
215 let current_plan = if is_zed_provider {
216 self.workspace
217 .upgrade()
218 .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
219 } else {
220 None
221 };
222
223 let is_signed_in = self
224 .workspace
225 .read_with(cx, |workspace, _| {
226 !workspace.client().status().borrow().is_signed_out()
227 })
228 .unwrap_or(false);
229
230 v_flex()
231 .min_w_0()
232 .w_full()
233 .when(is_expanded, |this| this.mb_2())
234 .child(
235 div()
236 .px_2()
237 .child(Divider::horizontal().color(DividerColor::BorderFaded)),
238 )
239 .child(
240 h_flex()
241 .map(|this| {
242 if is_expanded {
243 this.mt_2().mb_1()
244 } else {
245 this.my_2()
246 }
247 })
248 .w_full()
249 .justify_between()
250 .child(
251 h_flex()
252 .id(provider_id_string.clone())
253 .px_2()
254 .py_0p5()
255 .w_full()
256 .justify_between()
257 .rounded_sm()
258 .hover(|hover| hover.bg(cx.theme().colors().element_hover))
259 .child(
260 h_flex()
261 .w_full()
262 .gap_1p5()
263 .child(
264 match provider.icon() {
265 IconOrSvg::Svg(path) => Icon::from_external_svg(path),
266 IconOrSvg::Icon(name) => Icon::new(name),
267 }
268 .size(IconSize::Small)
269 .color(Color::Muted),
270 )
271 .child(
272 h_flex()
273 .w_full()
274 .gap_1()
275 .child(Label::new(provider_name.clone()))
276 .map(|this| {
277 if is_zed_provider && is_signed_in {
278 this.child(
279 self.render_zed_plan_info(current_plan, cx),
280 )
281 } else {
282 this.when(
283 provider.is_authenticated(cx)
284 && !is_expanded,
285 |parent| {
286 parent.child(
287 Icon::new(IconName::Check)
288 .color(Color::Success),
289 )
290 },
291 )
292 }
293 }),
294 ),
295 )
296 .child(
297 Disclosure::new(provider_id_string, is_expanded)
298 .opened_icon(IconName::ChevronUp)
299 .closed_icon(IconName::ChevronDown),
300 )
301 .on_click(cx.listener({
302 let provider_id = provider.id();
303 move |this, _event, _window, _cx| {
304 let is_expanded = this
305 .expanded_provider_configurations
306 .entry(provider_id.clone())
307 .or_insert(false);
308
309 *is_expanded = !*is_expanded;
310 }
311 })),
312 ),
313 )
314 .child(
315 v_flex()
316 .min_w_0()
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 .min_w_0()
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::ZedBusiness => ("Business", Color::Accent, pro_chip_bg),
505 Plan::ZedStudent => ("Student", Color::Accent, pro_chip_bg),
506 };
507
508 Chip::new(plan_name.to_string())
509 .bg_color(bg_color)
510 .label_color(label_color)
511 .into_any_element()
512 } else {
513 div().into_any_element()
514 }
515 }
516
517 fn render_context_servers_section(
518 &mut self,
519 window: &mut Window,
520 cx: &mut Context<Self>,
521 ) -> impl IntoElement {
522 let context_server_ids = self.context_server_store.read(cx).server_ids();
523
524 let add_server_popover = PopoverMenu::new("add-server-popover")
525 .trigger(
526 Button::new("add-server", "Add Server")
527 .style(ButtonStyle::Outlined)
528 .icon_position(IconPosition::Start)
529 .icon(IconName::Plus)
530 .icon_size(IconSize::Small)
531 .icon_color(Color::Muted)
532 .label_size(LabelSize::Small),
533 )
534 .menu({
535 move |window, cx| {
536 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
537 menu.entry("Add Custom Server", None, {
538 |window, cx| {
539 window.dispatch_action(crate::AddContextServer.boxed_clone(), cx)
540 }
541 })
542 .entry("Install from Extensions", None, {
543 |window, cx| {
544 window.dispatch_action(
545 zed_actions::Extensions {
546 category_filter: Some(
547 ExtensionCategoryFilter::ContextServers,
548 ),
549 id: None,
550 }
551 .boxed_clone(),
552 cx,
553 )
554 }
555 })
556 }))
557 }
558 })
559 .anchor(gpui::Corner::TopRight)
560 .offset(gpui::Point {
561 x: px(0.0),
562 y: px(2.0),
563 });
564
565 v_flex()
566 .min_w_0()
567 .border_b_1()
568 .border_color(cx.theme().colors().border)
569 .child(self.render_section_title(
570 "Model Context Protocol (MCP) Servers",
571 "All MCP servers connected directly or via a Zed extension.",
572 add_server_popover.into_any_element(),
573 ))
574 .child(
575 v_flex()
576 .pl_4()
577 .pb_4()
578 .pr_5()
579 .w_full()
580 .gap_1()
581 .map(|parent| {
582 if context_server_ids.is_empty() {
583 parent.child(
584 h_flex()
585 .p_4()
586 .justify_center()
587 .border_1()
588 .border_dashed()
589 .border_color(cx.theme().colors().border.opacity(0.6))
590 .rounded_sm()
591 .child(
592 Label::new("No MCP servers added yet.")
593 .color(Color::Muted)
594 .size(LabelSize::Small),
595 ),
596 )
597 } else {
598 parent.children(itertools::intersperse_with(
599 context_server_ids.iter().cloned().map(|context_server_id| {
600 self.render_context_server(context_server_id, window, cx)
601 .into_any_element()
602 }),
603 || {
604 Divider::horizontal()
605 .color(DividerColor::BorderFaded)
606 .into_any_element()
607 },
608 ))
609 }
610 }),
611 )
612 }
613
614 fn render_context_server(
615 &self,
616 context_server_id: ContextServerId,
617 window: &mut Window,
618 cx: &Context<Self>,
619 ) -> impl use<> + IntoElement {
620 let server_status = self
621 .context_server_store
622 .read(cx)
623 .status_for_server(&context_server_id)
624 .unwrap_or(ContextServerStatus::Stopped);
625 let server_configuration = self
626 .context_server_store
627 .read(cx)
628 .configuration_for_server(&context_server_id);
629
630 let is_running = matches!(server_status, ContextServerStatus::Running);
631 let item_id = SharedString::from(context_server_id.0.clone());
632 // Servers without a configuration can only be provided by extensions.
633 let provided_by_extension = server_configuration.as_ref().is_none_or(|config| {
634 matches!(
635 config.as_ref(),
636 ContextServerConfiguration::Extension { .. }
637 )
638 });
639
640 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
641 Some(error)
642 } else {
643 None
644 };
645
646 let tool_count = self
647 .context_server_registry
648 .read(cx)
649 .tools_for_server(&context_server_id)
650 .count();
651
652 let (source_icon, source_tooltip) = if provided_by_extension {
653 (
654 IconName::ZedSrcExtension,
655 "This MCP server was installed from an extension.",
656 )
657 } else {
658 (
659 IconName::ZedSrcCustom,
660 "This custom MCP server was installed directly.",
661 )
662 };
663
664 let (status_indicator, tooltip_text) = match server_status {
665 ContextServerStatus::Starting => (
666 Icon::new(IconName::LoadCircle)
667 .size(IconSize::XSmall)
668 .color(Color::Accent)
669 .with_keyed_rotate_animation(
670 SharedString::from(format!("{}-starting", context_server_id.0)),
671 3,
672 )
673 .into_any_element(),
674 "Server is starting.",
675 ),
676 ContextServerStatus::Running => (
677 Indicator::dot().color(Color::Success).into_any_element(),
678 "Server is active.",
679 ),
680 ContextServerStatus::Error(_) => (
681 Indicator::dot().color(Color::Error).into_any_element(),
682 "Server has an error.",
683 ),
684 ContextServerStatus::Stopped => (
685 Indicator::dot().color(Color::Muted).into_any_element(),
686 "Server is stopped.",
687 ),
688 };
689 let is_remote = server_configuration
690 .as_ref()
691 .map(|config| matches!(config.as_ref(), ContextServerConfiguration::Http { .. }))
692 .unwrap_or(false);
693 let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
694 .trigger_with_tooltip(
695 IconButton::new("context-server-config-menu", IconName::Settings)
696 .icon_color(Color::Muted)
697 .icon_size(IconSize::Small),
698 Tooltip::text("Configure MCP Server"),
699 )
700 .anchor(Corner::TopRight)
701 .menu({
702 let fs = self.fs.clone();
703 let context_server_id = context_server_id.clone();
704 let language_registry = self.language_registry.clone();
705 let workspace = self.workspace.clone();
706 let context_server_registry = self.context_server_registry.clone();
707
708 move |window, cx| {
709 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
710 menu.entry("Configure Server", None, {
711 let context_server_id = context_server_id.clone();
712 let language_registry = language_registry.clone();
713 let workspace = workspace.clone();
714 move |window, cx| {
715 if is_remote {
716 crate::agent_configuration::configure_context_server_modal::ConfigureContextServerModal::show_modal_for_existing_server(
717 context_server_id.clone(),
718 language_registry.clone(),
719 workspace.clone(),
720 window,
721 cx,
722 )
723 .detach();
724 } else {
725 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 }
734 }
735 }).when(tool_count > 0, |this| this.entry("View Tools", None, {
736 let context_server_id = context_server_id.clone();
737 let context_server_registry = context_server_registry.clone();
738 let workspace = workspace.clone();
739 move |window, cx| {
740 let context_server_id = context_server_id.clone();
741 workspace.update(cx, |workspace, cx| {
742 ConfigureContextServerToolsModal::toggle(
743 context_server_id,
744 context_server_registry.clone(),
745 workspace,
746 window,
747 cx,
748 );
749 })
750 .ok();
751 }
752 }))
753 .separator()
754 .entry("Uninstall", None, {
755 let fs = fs.clone();
756 let context_server_id = context_server_id.clone();
757 let workspace = workspace.clone();
758 move |_, cx| {
759 let uninstall_extension_task = match (
760 provided_by_extension,
761 resolve_extension_for_context_server(&context_server_id, cx),
762 ) {
763 (true, Some((id, manifest))) => {
764 if extension_only_provides_context_server(manifest.as_ref())
765 {
766 ExtensionStore::global(cx).update(cx, |store, cx| {
767 store.uninstall_extension(id, cx)
768 })
769 } else {
770 workspace.update(cx, |workspace, cx| {
771 show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
772 }).log_err();
773 Task::ready(Ok(()))
774 }
775 }
776 _ => Task::ready(Ok(())),
777 };
778
779 cx.spawn({
780 let fs = fs.clone();
781 let context_server_id = context_server_id.clone();
782 async move |cx| {
783 uninstall_extension_task.await?;
784 cx.update(|cx| {
785 update_settings_file(
786 fs.clone(),
787 cx,
788 {
789 let context_server_id =
790 context_server_id.clone();
791 move |settings, _| {
792 settings.project
793 .context_servers
794 .remove(&context_server_id.0);
795 }
796 },
797 )
798 });
799 anyhow::Ok(())
800 }
801 })
802 .detach_and_log_err(cx);
803 }
804 })
805 }))
806 }
807 });
808
809 v_flex()
810 .min_w_0()
811 .id(item_id.clone())
812 .child(
813 h_flex()
814 .min_w_0()
815 .w_full()
816 .justify_between()
817 .child(
818 h_flex()
819 .flex_1()
820 .min_w_0()
821 .child(
822 h_flex()
823 .id(format!("tooltip-{}", item_id))
824 .h_full()
825 .w_3()
826 .mr_2()
827 .justify_center()
828 .tooltip(Tooltip::text(tooltip_text))
829 .child(status_indicator),
830 )
831 .child(Label::new(item_id).flex_shrink_0().truncate())
832 .child(
833 div()
834 .id("extension-source")
835 .min_w_0()
836 .mt_0p5()
837 .mx_1()
838 .tooltip(Tooltip::text(source_tooltip))
839 .child(
840 Icon::new(source_icon)
841 .size(IconSize::Small)
842 .color(Color::Muted),
843 ),
844 )
845 .when(is_running, |this| {
846 this.child(
847 Label::new(if tool_count == 1 {
848 SharedString::from("1 tool")
849 } else {
850 SharedString::from(format!("{} tools", tool_count))
851 })
852 .color(Color::Muted)
853 .size(LabelSize::Small),
854 )
855 }),
856 )
857 .child(
858 h_flex()
859 .gap_0p5()
860 .flex_none()
861 .child(context_server_configuration_menu)
862 .child(
863 Switch::new("context-server-switch", is_running.into())
864 .on_click({
865 let context_server_manager = self.context_server_store.clone();
866 let fs = self.fs.clone();
867
868 move |state, _window, cx| {
869 let is_enabled = match state {
870 ToggleState::Unselected
871 | ToggleState::Indeterminate => {
872 context_server_manager.update(cx, |this, cx| {
873 this.stop_server(&context_server_id, cx)
874 .log_err();
875 });
876 false
877 }
878 ToggleState::Selected => {
879 context_server_manager.update(cx, |this, cx| {
880 if let Some(server) =
881 this.get_server(&context_server_id)
882 {
883 this.start_server(server, cx);
884 }
885 });
886 true
887 }
888 };
889 update_settings_file(fs.clone(), cx, {
890 let context_server_id = context_server_id.clone();
891
892 move |settings, _| {
893 settings
894 .project
895 .context_servers
896 .entry(context_server_id.0)
897 .or_insert_with(|| {
898 settings::ContextServerSettingsContent::Extension {
899 enabled: is_enabled,
900 remote: false,
901 settings: serde_json::json!({}),
902 }
903 })
904 .set_enabled(is_enabled);
905 }
906 });
907 }
908 }),
909 ),
910 ),
911 )
912 .map(|parent| {
913 if let Some(error) = error {
914 return parent.child(
915 h_flex()
916 .gap_2()
917 .pr_4()
918 .items_start()
919 .child(
920 h_flex()
921 .flex_none()
922 .h(window.line_height() / 1.6_f32)
923 .justify_center()
924 .child(
925 Icon::new(IconName::XCircle)
926 .size(IconSize::XSmall)
927 .color(Color::Error),
928 ),
929 )
930 .child(
931 div().w_full().child(
932 Label::new(error)
933 .buffer_font(cx)
934 .color(Color::Muted)
935 .size(LabelSize::Small),
936 ),
937 ),
938 );
939 }
940 parent
941 })
942 }
943
944 fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
945 let agent_server_store = self.agent_server_store.read(cx);
946
947 let user_defined_agents = agent_server_store
948 .external_agents()
949 .cloned()
950 .collect::<Vec<_>>();
951
952 let user_defined_agents: Vec<_> = user_defined_agents
953 .into_iter()
954 .map(|name| {
955 let icon = if let Some(icon_path) = agent_server_store.agent_icon(&name) {
956 AgentIcon::Path(icon_path)
957 } else {
958 AgentIcon::Name(IconName::Sparkle)
959 };
960 let display_name = agent_server_store
961 .agent_display_name(&name)
962 .unwrap_or_else(|| name.0.clone());
963 let source = agent_server_store.agent_source(&name).unwrap_or_default();
964 (name, icon, display_name, source)
965 })
966 .sorted_unstable_by_key(|(_, _, display_name, _)| display_name.to_lowercase())
967 .collect();
968
969 let add_agent_popover = PopoverMenu::new("add-agent-server-popover")
970 .trigger(
971 Button::new("add-agent", "Add Agent")
972 .style(ButtonStyle::Outlined)
973 .icon_position(IconPosition::Start)
974 .icon(IconName::Plus)
975 .icon_size(IconSize::Small)
976 .icon_color(Color::Muted)
977 .label_size(LabelSize::Small),
978 )
979 .menu({
980 move |window, cx| {
981 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
982 menu.entry("Install from Registry", None, {
983 |window, cx| {
984 window.dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
985 }
986 })
987 .entry("Add Custom Agent", None, {
988 move |window, cx| {
989 if let Some(workspace) = Workspace::for_window(window, cx) {
990 let workspace = workspace.downgrade();
991 window
992 .spawn(cx, async |cx| {
993 open_new_agent_servers_entry_in_settings_editor(
994 workspace, cx,
995 )
996 .await
997 })
998 .detach_and_log_err(cx);
999 }
1000 }
1001 })
1002 .separator()
1003 .header("Learn More")
1004 .item(
1005 ContextMenuEntry::new("ACP Docs")
1006 .icon(IconName::ArrowUpRight)
1007 .icon_color(Color::Muted)
1008 .icon_position(IconPosition::End)
1009 .handler({
1010 move |window, cx| {
1011 window.dispatch_action(
1012 Box::new(OpenBrowser {
1013 url: "https://agentclientprotocol.com/".into(),
1014 }),
1015 cx,
1016 );
1017 }
1018 }),
1019 )
1020 }))
1021 }
1022 })
1023 .anchor(gpui::Corner::TopRight)
1024 .offset(gpui::Point {
1025 x: px(0.0),
1026 y: px(2.0),
1027 });
1028
1029 v_flex()
1030 .min_w_0()
1031 .border_b_1()
1032 .border_color(cx.theme().colors().border)
1033 .child(
1034 v_flex()
1035 .child(self.render_section_title(
1036 "External Agents",
1037 "All agents connected through the Agent Client Protocol.",
1038 add_agent_popover.into_any_element(),
1039 ))
1040 .child(v_flex().p_4().pt_0().gap_2().map(|mut parent| {
1041 let mut first = true;
1042 for (name, icon, display_name, source) in user_defined_agents {
1043 if !first {
1044 parent = parent
1045 .child(Divider::horizontal().color(DividerColor::BorderFaded));
1046 }
1047 first = false;
1048 parent = parent.child(self.render_agent_server(
1049 icon,
1050 name,
1051 display_name,
1052 source,
1053 cx,
1054 ));
1055 }
1056 parent
1057 })),
1058 )
1059 }
1060
1061 fn render_agent_server(
1062 &self,
1063 icon: AgentIcon,
1064 id: impl Into<SharedString>,
1065 display_name: impl Into<SharedString>,
1066 source: ExternalAgentSource,
1067 cx: &mut Context<Self>,
1068 ) -> impl IntoElement {
1069 let id = id.into();
1070 let display_name = display_name.into();
1071
1072 let icon = match icon {
1073 AgentIcon::Name(icon_name) => Icon::new(icon_name)
1074 .size(IconSize::Small)
1075 .color(Color::Muted),
1076 AgentIcon::Path(icon_path) => Icon::from_external_svg(icon_path)
1077 .size(IconSize::Small)
1078 .color(Color::Muted),
1079 };
1080
1081 let source_badge = match source {
1082 ExternalAgentSource::Extension => Some((
1083 SharedString::new(format!("agent-source-{}", id)),
1084 SharedString::from(format!(
1085 "The {} agent was installed from an extension.",
1086 display_name
1087 )),
1088 IconName::ZedSrcExtension,
1089 )),
1090 ExternalAgentSource::Registry => Some((
1091 SharedString::new(format!("agent-source-{}", id)),
1092 SharedString::from(format!(
1093 "The {} agent was installed from the ACP registry.",
1094 display_name
1095 )),
1096 IconName::AcpRegistry,
1097 )),
1098 ExternalAgentSource::Custom => None,
1099 };
1100
1101 let agent_server_name = ExternalAgentServerName(id.clone());
1102
1103 let uninstall_button = match source {
1104 ExternalAgentSource::Extension => Some(
1105 IconButton::new(
1106 SharedString::from(format!("uninstall-{}", id)),
1107 IconName::Trash,
1108 )
1109 .icon_color(Color::Muted)
1110 .icon_size(IconSize::Small)
1111 .tooltip(Tooltip::text("Uninstall Agent Extension"))
1112 .on_click(cx.listener(move |this, _, _window, cx| {
1113 let agent_name = agent_server_name.clone();
1114
1115 if let Some(ext_id) = this.agent_server_store.update(cx, |store, _cx| {
1116 store.get_extension_id_for_agent(&agent_name)
1117 }) {
1118 ExtensionStore::global(cx)
1119 .update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
1120 .detach_and_log_err(cx);
1121 }
1122 })),
1123 ),
1124 ExternalAgentSource::Registry => {
1125 let fs = self.fs.clone();
1126 Some(
1127 IconButton::new(
1128 SharedString::from(format!("uninstall-{}", id)),
1129 IconName::Trash,
1130 )
1131 .icon_color(Color::Muted)
1132 .icon_size(IconSize::Small)
1133 .tooltip(Tooltip::text("Remove Registry Agent"))
1134 .on_click(cx.listener(move |_, _, _window, cx| {
1135 let agent_name = agent_server_name.clone();
1136 update_settings_file(fs.clone(), cx, move |settings, _| {
1137 let Some(agent_servers) = settings.agent_servers.as_mut() else {
1138 return;
1139 };
1140 if let Some(entry) = agent_servers.get(agent_name.0.as_ref())
1141 && matches!(
1142 entry,
1143 settings::CustomAgentServerSettings::Registry { .. }
1144 )
1145 {
1146 agent_servers.remove(agent_name.0.as_ref());
1147 }
1148 });
1149 })),
1150 )
1151 }
1152 ExternalAgentSource::Custom => {
1153 let fs = self.fs.clone();
1154 Some(
1155 IconButton::new(
1156 SharedString::from(format!("uninstall-{}", id)),
1157 IconName::Trash,
1158 )
1159 .icon_color(Color::Muted)
1160 .icon_size(IconSize::Small)
1161 .tooltip(Tooltip::text("Remove Custom Agent"))
1162 .on_click(cx.listener(move |_, _, _window, cx| {
1163 let agent_name = agent_server_name.clone();
1164 update_settings_file(fs.clone(), cx, move |settings, _| {
1165 let Some(agent_servers) = settings.agent_servers.as_mut() else {
1166 return;
1167 };
1168 if let Some(entry) = agent_servers.get(agent_name.0.as_ref())
1169 && matches!(
1170 entry,
1171 settings::CustomAgentServerSettings::Custom { .. }
1172 )
1173 {
1174 agent_servers.remove(agent_name.0.as_ref());
1175 }
1176 });
1177 })),
1178 )
1179 }
1180 };
1181
1182 h_flex()
1183 .gap_1()
1184 .justify_between()
1185 .child(
1186 h_flex()
1187 .gap_1p5()
1188 .child(icon)
1189 .child(Label::new(display_name))
1190 .when_some(source_badge, |this, (tooltip_id, tooltip_message, icon)| {
1191 this.child(
1192 div()
1193 .id(tooltip_id)
1194 .flex_none()
1195 .tooltip(Tooltip::text(tooltip_message))
1196 .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted)),
1197 )
1198 })
1199 .child(
1200 Icon::new(IconName::Check)
1201 .color(Color::Success)
1202 .size(IconSize::Small),
1203 ),
1204 )
1205 .when_some(uninstall_button, |this, uninstall_button| {
1206 this.child(uninstall_button)
1207 })
1208 }
1209}
1210
1211impl Render for AgentConfiguration {
1212 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1213 v_flex()
1214 .id("assistant-configuration")
1215 .key_context("AgentConfiguration")
1216 .track_focus(&self.focus_handle(cx))
1217 .relative()
1218 .size_full()
1219 .pb_8()
1220 .bg(cx.theme().colors().panel_background)
1221 .child(
1222 div()
1223 .size_full()
1224 .child(
1225 v_flex()
1226 .id("assistant-configuration-content")
1227 .track_scroll(&self.scroll_handle)
1228 .size_full()
1229 .min_w_0()
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<String> = (0..u8::MAX)
1348 .map(|i| {
1349 if i == 0 {
1350 "your_agent".to_string()
1351 } else {
1352 format!("your_agent_{}", i)
1353 }
1354 })
1355 .find(|name| {
1356 !settings
1357 .agent_servers
1358 .as_ref()
1359 .is_some_and(|agent_servers| agent_servers.contains_key(name.as_str()))
1360 });
1361 if let Some(server_name) = server_name {
1362 unique_server_name = Some(SharedString::from(server_name.clone()));
1363 settings.agent_servers.get_or_insert_default().insert(
1364 server_name,
1365 settings::CustomAgentServerSettings::Custom {
1366 path: "path_to_executable".into(),
1367 args: vec![],
1368 env: HashMap::default(),
1369 default_mode: None,
1370 default_model: None,
1371 favorite_models: vec![],
1372 default_config_options: Default::default(),
1373 favorite_config_option_values: Default::default(),
1374 },
1375 );
1376 }
1377 });
1378
1379 if edits.is_empty() {
1380 return;
1381 }
1382
1383 let ranges = edits
1384 .iter()
1385 .map(|(range, _)| range.clone())
1386 .collect::<Vec<_>>();
1387
1388 item.edit(
1389 edits.into_iter().map(|(range, s)| {
1390 (
1391 MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1392 s,
1393 )
1394 }),
1395 cx,
1396 );
1397 if let Some((unique_server_name, buffer)) =
1398 unique_server_name.zip(item.buffer().read(cx).as_singleton())
1399 {
1400 let snapshot = buffer.read(cx).snapshot();
1401 if let Some(range) =
1402 find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1403 {
1404 item.change_selections(
1405 SelectionEffects::scroll(Autoscroll::newest()),
1406 window,
1407 cx,
1408 |selections| {
1409 selections.select_ranges(vec![
1410 MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1411 ]);
1412 },
1413 );
1414 }
1415 }
1416 })
1417}
1418
1419fn find_text_in_buffer(
1420 text: &str,
1421 start: usize,
1422 snapshot: &language::BufferSnapshot,
1423) -> Option<Range<usize>> {
1424 let chars = text.chars().collect::<Vec<char>>();
1425
1426 let mut offset = start;
1427 let mut char_offset = 0;
1428 for c in snapshot.chars_at(start) {
1429 if char_offset >= chars.len() {
1430 break;
1431 }
1432 offset += 1;
1433
1434 if c == chars[char_offset] {
1435 char_offset += 1;
1436 } else {
1437 char_offset = 0;
1438 }
1439 }
1440
1441 if char_offset == chars.len() {
1442 Some(offset.saturating_sub(chars.len())..offset)
1443 } else {
1444 None
1445 }
1446}
1447
1448// OpenAI-compatible providers are user-configured and can be removed,
1449// whereas built-in providers (like Anthropic, OpenAI, Google, etc.) can't.
1450//
1451// If in the future we have more "API-compatible-type" of providers,
1452// they should be included here as removable providers.
1453fn is_removable_provider(provider_id: &LanguageModelProviderId, cx: &App) -> bool {
1454 AllLanguageModelSettings::get_global(cx)
1455 .openai_compatible
1456 .contains_key(provider_id.0.as_ref())
1457}