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 .start_icon(
336 Icon::new(IconName::Thread)
337 .size(IconSize::Small)
338 .color(Color::Muted),
339 )
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 .start_icon(
362 Icon::new(IconName::Trash)
363 .size(IconSize::Small)
364 .color(Color::Muted),
365 )
366 .label_size(LabelSize::Small)
367 .on_click(cx.listener({
368 let provider = provider.clone();
369 move |this, _event, window, cx| {
370 this.delete_provider(provider.clone(), window, cx);
371 }
372 })),
373 )
374 },
375 ),
376 )
377 }
378
379 fn delete_provider(
380 &mut self,
381 provider: Arc<dyn LanguageModelProvider>,
382 window: &mut Window,
383 cx: &mut Context<Self>,
384 ) {
385 let fs = self.fs.clone();
386 let provider_id = provider.id();
387
388 cx.spawn_in(window, async move |_, cx| {
389 cx.update(|_window, cx| {
390 update_settings_file(fs.clone(), cx, {
391 let provider_id = provider_id.clone();
392 move |settings, _| {
393 if let Some(ref mut openai_compatible) = settings
394 .language_models
395 .as_mut()
396 .and_then(|lm| lm.openai_compatible.as_mut())
397 {
398 let key_to_remove: Arc<str> = Arc::from(provider_id.0.as_ref());
399 openai_compatible.remove(&key_to_remove);
400 }
401 }
402 });
403 })
404 .log_err();
405
406 cx.update(|_window, cx| {
407 LanguageModelRegistry::global(cx).update(cx, {
408 let provider_id = provider_id.clone();
409 move |registry, cx| {
410 registry.unregister_provider(provider_id, cx);
411 }
412 })
413 })
414 .log_err();
415
416 anyhow::Ok(())
417 })
418 .detach_and_log_err(cx);
419 }
420
421 fn render_provider_configuration_section(
422 &mut self,
423 cx: &mut Context<Self>,
424 ) -> impl IntoElement {
425 let providers = LanguageModelRegistry::read_global(cx).visible_providers();
426
427 let popover_menu = PopoverMenu::new("add-provider-popover")
428 .trigger(
429 Button::new("add-provider", "Add Provider")
430 .style(ButtonStyle::Outlined)
431 .start_icon(
432 Icon::new(IconName::Plus)
433 .size(IconSize::Small)
434 .color(Color::Muted),
435 )
436 .label_size(LabelSize::Small),
437 )
438 .menu({
439 let workspace = self.workspace.clone();
440 move |window, cx| {
441 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
442 menu.header("Compatible APIs").entry("OpenAI", None, {
443 let workspace = workspace.clone();
444 move |window, cx| {
445 workspace
446 .update(cx, |workspace, cx| {
447 AddLlmProviderModal::toggle(
448 LlmCompatibleProvider::OpenAi,
449 workspace,
450 window,
451 cx,
452 );
453 })
454 .log_err();
455 }
456 })
457 }))
458 }
459 })
460 .anchor(gpui::Corner::TopRight)
461 .offset(gpui::Point {
462 x: px(0.0),
463 y: px(2.0),
464 });
465
466 v_flex()
467 .min_w_0()
468 .w_full()
469 .child(self.render_section_title(
470 "LLM Providers",
471 "Add at least one provider to use AI-powered features with Zed's native agent.",
472 popover_menu.into_any_element(),
473 ))
474 .child(
475 div()
476 .w_full()
477 .pl(DynamicSpacing::Base08.rems(cx))
478 .pr(DynamicSpacing::Base20.rems(cx))
479 .children(
480 providers.into_iter().map(|provider| {
481 self.render_provider_configuration_block(&provider, cx)
482 }),
483 ),
484 )
485 }
486
487 fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
488 if let Some(plan) = plan {
489 let free_chip_bg = cx
490 .theme()
491 .colors()
492 .editor_background
493 .opacity(0.5)
494 .blend(cx.theme().colors().text_accent.opacity(0.05));
495
496 let pro_chip_bg = cx
497 .theme()
498 .colors()
499 .editor_background
500 .opacity(0.5)
501 .blend(cx.theme().colors().text_accent.opacity(0.2));
502
503 let (plan_name, label_color, bg_color) = match plan {
504 Plan::ZedFree => ("Free", Color::Default, free_chip_bg),
505 Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
506 Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
507 Plan::ZedBusiness => ("Business", Color::Accent, pro_chip_bg),
508 Plan::ZedStudent => ("Student", Color::Accent, pro_chip_bg),
509 };
510
511 Chip::new(plan_name.to_string())
512 .bg_color(bg_color)
513 .label_color(label_color)
514 .into_any_element()
515 } else {
516 div().into_any_element()
517 }
518 }
519
520 fn render_context_servers_section(
521 &mut self,
522 window: &mut Window,
523 cx: &mut Context<Self>,
524 ) -> impl IntoElement {
525 let context_server_ids = self.context_server_store.read(cx).server_ids();
526
527 let add_server_popover = PopoverMenu::new("add-server-popover")
528 .trigger(
529 Button::new("add-server", "Add Server")
530 .style(ButtonStyle::Outlined)
531 .start_icon(
532 Icon::new(IconName::Plus)
533 .size(IconSize::Small)
534 .color(Color::Muted),
535 )
536 .label_size(LabelSize::Small),
537 )
538 .menu({
539 move |window, cx| {
540 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
541 menu.entry("Add Custom Server", None, {
542 |window, cx| {
543 window.dispatch_action(crate::AddContextServer.boxed_clone(), cx)
544 }
545 })
546 .entry("Install from Extensions", None, {
547 |window, cx| {
548 window.dispatch_action(
549 zed_actions::Extensions {
550 category_filter: Some(
551 ExtensionCategoryFilter::ContextServers,
552 ),
553 id: None,
554 }
555 .boxed_clone(),
556 cx,
557 )
558 }
559 })
560 }))
561 }
562 })
563 .anchor(gpui::Corner::TopRight)
564 .offset(gpui::Point {
565 x: px(0.0),
566 y: px(2.0),
567 });
568
569 v_flex()
570 .min_w_0()
571 .border_b_1()
572 .border_color(cx.theme().colors().border)
573 .child(self.render_section_title(
574 "Model Context Protocol (MCP) Servers",
575 "All MCP servers connected directly or via a Zed extension.",
576 add_server_popover.into_any_element(),
577 ))
578 .child(
579 v_flex()
580 .pl_4()
581 .pb_4()
582 .pr_5()
583 .w_full()
584 .gap_1()
585 .map(|parent| {
586 if context_server_ids.is_empty() {
587 parent.child(
588 h_flex()
589 .p_4()
590 .justify_center()
591 .border_1()
592 .border_dashed()
593 .border_color(cx.theme().colors().border.opacity(0.6))
594 .rounded_sm()
595 .child(
596 Label::new("No MCP servers added yet.")
597 .color(Color::Muted)
598 .size(LabelSize::Small),
599 ),
600 )
601 } else {
602 parent.children(itertools::intersperse_with(
603 context_server_ids.iter().cloned().map(|context_server_id| {
604 self.render_context_server(context_server_id, window, cx)
605 .into_any_element()
606 }),
607 || {
608 Divider::horizontal()
609 .color(DividerColor::BorderFaded)
610 .into_any_element()
611 },
612 ))
613 }
614 }),
615 )
616 }
617
618 fn render_context_server(
619 &self,
620 context_server_id: ContextServerId,
621 window: &mut Window,
622 cx: &Context<Self>,
623 ) -> impl use<> + IntoElement {
624 let server_status = self
625 .context_server_store
626 .read(cx)
627 .status_for_server(&context_server_id)
628 .unwrap_or(ContextServerStatus::Stopped);
629 let server_configuration = self
630 .context_server_store
631 .read(cx)
632 .configuration_for_server(&context_server_id);
633
634 let is_running = matches!(server_status, ContextServerStatus::Running);
635 let item_id = SharedString::from(context_server_id.0.clone());
636 // Servers without a configuration can only be provided by extensions.
637 let provided_by_extension = server_configuration.as_ref().is_none_or(|config| {
638 matches!(
639 config.as_ref(),
640 ContextServerConfiguration::Extension { .. }
641 )
642 });
643
644 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
645 Some(error)
646 } else {
647 None
648 };
649
650 let tool_count = self
651 .context_server_registry
652 .read(cx)
653 .tools_for_server(&context_server_id)
654 .count();
655
656 let (source_icon, source_tooltip) = if provided_by_extension {
657 (
658 IconName::ZedSrcExtension,
659 "This MCP server was installed from an extension.",
660 )
661 } else {
662 (
663 IconName::ZedSrcCustom,
664 "This custom MCP server was installed directly.",
665 )
666 };
667
668 let (status_indicator, tooltip_text) = match server_status {
669 ContextServerStatus::Starting => (
670 Icon::new(IconName::LoadCircle)
671 .size(IconSize::XSmall)
672 .color(Color::Accent)
673 .with_keyed_rotate_animation(
674 SharedString::from(format!("{}-starting", context_server_id.0)),
675 3,
676 )
677 .into_any_element(),
678 "Server is starting.",
679 ),
680 ContextServerStatus::Running => (
681 Indicator::dot().color(Color::Success).into_any_element(),
682 "Server is active.",
683 ),
684 ContextServerStatus::Error(_) => (
685 Indicator::dot().color(Color::Error).into_any_element(),
686 "Server has an error.",
687 ),
688 ContextServerStatus::Stopped => (
689 Indicator::dot().color(Color::Muted).into_any_element(),
690 "Server is stopped.",
691 ),
692 };
693 let is_remote = server_configuration
694 .as_ref()
695 .map(|config| matches!(config.as_ref(), ContextServerConfiguration::Http { .. }))
696 .unwrap_or(false);
697 let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
698 .trigger_with_tooltip(
699 IconButton::new("context-server-config-menu", IconName::Settings)
700 .icon_color(Color::Muted)
701 .icon_size(IconSize::Small),
702 Tooltip::text("Configure MCP Server"),
703 )
704 .anchor(Corner::TopRight)
705 .menu({
706 let fs = self.fs.clone();
707 let context_server_id = context_server_id.clone();
708 let language_registry = self.language_registry.clone();
709 let workspace = self.workspace.clone();
710 let context_server_registry = self.context_server_registry.clone();
711
712 move |window, cx| {
713 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
714 menu.entry("Configure Server", None, {
715 let context_server_id = context_server_id.clone();
716 let language_registry = language_registry.clone();
717 let workspace = workspace.clone();
718 move |window, cx| {
719 if is_remote {
720 crate::agent_configuration::configure_context_server_modal::ConfigureContextServerModal::show_modal_for_existing_server(
721 context_server_id.clone(),
722 language_registry.clone(),
723 workspace.clone(),
724 window,
725 cx,
726 )
727 .detach();
728 } else {
729 ConfigureContextServerModal::show_modal_for_existing_server(
730 context_server_id.clone(),
731 language_registry.clone(),
732 workspace.clone(),
733 window,
734 cx,
735 )
736 .detach();
737 }
738 }
739 }).when(tool_count > 0, |this| this.entry("View Tools", None, {
740 let context_server_id = context_server_id.clone();
741 let context_server_registry = context_server_registry.clone();
742 let workspace = workspace.clone();
743 move |window, cx| {
744 let context_server_id = context_server_id.clone();
745 workspace.update(cx, |workspace, cx| {
746 ConfigureContextServerToolsModal::toggle(
747 context_server_id,
748 context_server_registry.clone(),
749 workspace,
750 window,
751 cx,
752 );
753 })
754 .ok();
755 }
756 }))
757 .separator()
758 .entry("Uninstall", None, {
759 let fs = fs.clone();
760 let context_server_id = context_server_id.clone();
761 let workspace = workspace.clone();
762 move |_, cx| {
763 let uninstall_extension_task = match (
764 provided_by_extension,
765 resolve_extension_for_context_server(&context_server_id, cx),
766 ) {
767 (true, Some((id, manifest))) => {
768 if extension_only_provides_context_server(manifest.as_ref())
769 {
770 ExtensionStore::global(cx).update(cx, |store, cx| {
771 store.uninstall_extension(id, cx)
772 })
773 } else {
774 workspace.update(cx, |workspace, cx| {
775 show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
776 }).log_err();
777 Task::ready(Ok(()))
778 }
779 }
780 _ => Task::ready(Ok(())),
781 };
782
783 cx.spawn({
784 let fs = fs.clone();
785 let context_server_id = context_server_id.clone();
786 async move |cx| {
787 uninstall_extension_task.await?;
788 cx.update(|cx| {
789 update_settings_file(
790 fs.clone(),
791 cx,
792 {
793 let context_server_id =
794 context_server_id.clone();
795 move |settings, _| {
796 settings.project
797 .context_servers
798 .remove(&context_server_id.0);
799 }
800 },
801 )
802 });
803 anyhow::Ok(())
804 }
805 })
806 .detach_and_log_err(cx);
807 }
808 })
809 }))
810 }
811 });
812
813 v_flex()
814 .min_w_0()
815 .id(item_id.clone())
816 .child(
817 h_flex()
818 .min_w_0()
819 .w_full()
820 .justify_between()
821 .child(
822 h_flex()
823 .flex_1()
824 .min_w_0()
825 .child(
826 h_flex()
827 .id(format!("tooltip-{}", item_id))
828 .h_full()
829 .w_3()
830 .mr_2()
831 .justify_center()
832 .tooltip(Tooltip::text(tooltip_text))
833 .child(status_indicator),
834 )
835 .child(Label::new(item_id).flex_shrink_0().truncate())
836 .child(
837 div()
838 .id("extension-source")
839 .min_w_0()
840 .mt_0p5()
841 .mx_1()
842 .tooltip(Tooltip::text(source_tooltip))
843 .child(
844 Icon::new(source_icon)
845 .size(IconSize::Small)
846 .color(Color::Muted),
847 ),
848 )
849 .when(is_running, |this| {
850 this.child(
851 Label::new(if tool_count == 1 {
852 SharedString::from("1 tool")
853 } else {
854 SharedString::from(format!("{} tools", tool_count))
855 })
856 .color(Color::Muted)
857 .size(LabelSize::Small),
858 )
859 }),
860 )
861 .child(
862 h_flex()
863 .gap_0p5()
864 .flex_none()
865 .child(context_server_configuration_menu)
866 .child(
867 Switch::new("context-server-switch", is_running.into())
868 .on_click({
869 let context_server_manager = self.context_server_store.clone();
870 let fs = self.fs.clone();
871
872 move |state, _window, cx| {
873 let is_enabled = match state {
874 ToggleState::Unselected
875 | ToggleState::Indeterminate => {
876 context_server_manager.update(cx, |this, cx| {
877 this.stop_server(&context_server_id, cx)
878 .log_err();
879 });
880 false
881 }
882 ToggleState::Selected => {
883 context_server_manager.update(cx, |this, cx| {
884 if let Some(server) =
885 this.get_server(&context_server_id)
886 {
887 this.start_server(server, cx);
888 }
889 });
890 true
891 }
892 };
893 update_settings_file(fs.clone(), cx, {
894 let context_server_id = context_server_id.clone();
895
896 move |settings, _| {
897 settings
898 .project
899 .context_servers
900 .entry(context_server_id.0)
901 .or_insert_with(|| {
902 settings::ContextServerSettingsContent::Extension {
903 enabled: is_enabled,
904 remote: false,
905 settings: serde_json::json!({}),
906 }
907 })
908 .set_enabled(is_enabled);
909 }
910 });
911 }
912 }),
913 ),
914 ),
915 )
916 .map(|parent| {
917 if let Some(error) = error {
918 return parent.child(
919 h_flex()
920 .gap_2()
921 .pr_4()
922 .items_start()
923 .child(
924 h_flex()
925 .flex_none()
926 .h(window.line_height() / 1.6_f32)
927 .justify_center()
928 .child(
929 Icon::new(IconName::XCircle)
930 .size(IconSize::XSmall)
931 .color(Color::Error),
932 ),
933 )
934 .child(
935 div().w_full().child(
936 Label::new(error)
937 .buffer_font(cx)
938 .color(Color::Muted)
939 .size(LabelSize::Small),
940 ),
941 ),
942 );
943 }
944 parent
945 })
946 }
947
948 fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
949 let agent_server_store = self.agent_server_store.read(cx);
950
951 let user_defined_agents = agent_server_store
952 .external_agents()
953 .cloned()
954 .collect::<Vec<_>>();
955
956 let user_defined_agents: Vec<_> = user_defined_agents
957 .into_iter()
958 .map(|name| {
959 let icon = if let Some(icon_path) = agent_server_store.agent_icon(&name) {
960 AgentIcon::Path(icon_path)
961 } else {
962 AgentIcon::Name(IconName::Sparkle)
963 };
964 let display_name = agent_server_store
965 .agent_display_name(&name)
966 .unwrap_or_else(|| name.0.clone());
967 let source = agent_server_store.agent_source(&name).unwrap_or_default();
968 (name, icon, display_name, source)
969 })
970 .sorted_unstable_by_key(|(_, _, display_name, _)| display_name.to_lowercase())
971 .collect();
972
973 let add_agent_popover = PopoverMenu::new("add-agent-server-popover")
974 .trigger(
975 Button::new("add-agent", "Add Agent")
976 .style(ButtonStyle::Outlined)
977 .start_icon(
978 Icon::new(IconName::Plus)
979 .size(IconSize::Small)
980 .color(Color::Muted),
981 )
982 .label_size(LabelSize::Small),
983 )
984 .menu({
985 move |window, cx| {
986 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
987 menu.entry("Install from Registry", None, {
988 |window, cx| {
989 window.dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
990 }
991 })
992 .entry("Add Custom Agent", None, {
993 move |window, cx| {
994 if let Some(workspace) = Workspace::for_window(window, cx) {
995 let workspace = workspace.downgrade();
996 window
997 .spawn(cx, async |cx| {
998 open_new_agent_servers_entry_in_settings_editor(
999 workspace, cx,
1000 )
1001 .await
1002 })
1003 .detach_and_log_err(cx);
1004 }
1005 }
1006 })
1007 .separator()
1008 .header("Learn More")
1009 .item(
1010 ContextMenuEntry::new("ACP Docs")
1011 .icon(IconName::ArrowUpRight)
1012 .icon_color(Color::Muted)
1013 .icon_position(IconPosition::End)
1014 .handler({
1015 move |window, cx| {
1016 window.dispatch_action(
1017 Box::new(OpenBrowser {
1018 url: "https://agentclientprotocol.com/".into(),
1019 }),
1020 cx,
1021 );
1022 }
1023 }),
1024 )
1025 }))
1026 }
1027 })
1028 .anchor(gpui::Corner::TopRight)
1029 .offset(gpui::Point {
1030 x: px(0.0),
1031 y: px(2.0),
1032 });
1033
1034 v_flex()
1035 .min_w_0()
1036 .border_b_1()
1037 .border_color(cx.theme().colors().border)
1038 .child(
1039 v_flex()
1040 .child(self.render_section_title(
1041 "External Agents",
1042 "All agents connected through the Agent Client Protocol.",
1043 add_agent_popover.into_any_element(),
1044 ))
1045 .child(v_flex().p_4().pt_0().gap_2().map(|mut parent| {
1046 let mut first = true;
1047 for (name, icon, display_name, source) in user_defined_agents {
1048 if !first {
1049 parent = parent
1050 .child(Divider::horizontal().color(DividerColor::BorderFaded));
1051 }
1052 first = false;
1053 parent = parent.child(self.render_agent_server(
1054 icon,
1055 name,
1056 display_name,
1057 source,
1058 cx,
1059 ));
1060 }
1061 parent
1062 })),
1063 )
1064 }
1065
1066 fn render_agent_server(
1067 &self,
1068 icon: AgentIcon,
1069 id: impl Into<SharedString>,
1070 display_name: impl Into<SharedString>,
1071 source: ExternalAgentSource,
1072 cx: &mut Context<Self>,
1073 ) -> impl IntoElement {
1074 let id = id.into();
1075 let display_name = display_name.into();
1076
1077 let icon = match icon {
1078 AgentIcon::Name(icon_name) => Icon::new(icon_name)
1079 .size(IconSize::Small)
1080 .color(Color::Muted),
1081 AgentIcon::Path(icon_path) => Icon::from_external_svg(icon_path)
1082 .size(IconSize::Small)
1083 .color(Color::Muted),
1084 };
1085
1086 let source_badge = match source {
1087 ExternalAgentSource::Extension => Some((
1088 SharedString::new(format!("agent-source-{}", id)),
1089 SharedString::from(format!(
1090 "The {} agent was installed from an extension.",
1091 display_name
1092 )),
1093 IconName::ZedSrcExtension,
1094 )),
1095 ExternalAgentSource::Registry => Some((
1096 SharedString::new(format!("agent-source-{}", id)),
1097 SharedString::from(format!(
1098 "The {} agent was installed from the ACP registry.",
1099 display_name
1100 )),
1101 IconName::AcpRegistry,
1102 )),
1103 ExternalAgentSource::Custom => None,
1104 };
1105
1106 let agent_server_name = ExternalAgentServerName(id.clone());
1107
1108 let uninstall_button = match source {
1109 ExternalAgentSource::Extension => Some(
1110 IconButton::new(
1111 SharedString::from(format!("uninstall-{}", id)),
1112 IconName::Trash,
1113 )
1114 .icon_color(Color::Muted)
1115 .icon_size(IconSize::Small)
1116 .tooltip(Tooltip::text("Uninstall Agent Extension"))
1117 .on_click(cx.listener(move |this, _, _window, cx| {
1118 let agent_name = agent_server_name.clone();
1119
1120 if let Some(ext_id) = this.agent_server_store.update(cx, |store, _cx| {
1121 store.get_extension_id_for_agent(&agent_name)
1122 }) {
1123 ExtensionStore::global(cx)
1124 .update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
1125 .detach_and_log_err(cx);
1126 }
1127 })),
1128 ),
1129 ExternalAgentSource::Registry => {
1130 let fs = self.fs.clone();
1131 Some(
1132 IconButton::new(
1133 SharedString::from(format!("uninstall-{}", id)),
1134 IconName::Trash,
1135 )
1136 .icon_color(Color::Muted)
1137 .icon_size(IconSize::Small)
1138 .tooltip(Tooltip::text("Remove Registry Agent"))
1139 .on_click(cx.listener(move |_, _, _window, cx| {
1140 let agent_name = agent_server_name.clone();
1141 update_settings_file(fs.clone(), cx, move |settings, _| {
1142 let Some(agent_servers) = settings.agent_servers.as_mut() else {
1143 return;
1144 };
1145 if let Some(entry) = agent_servers.get(agent_name.0.as_ref())
1146 && matches!(
1147 entry,
1148 settings::CustomAgentServerSettings::Registry { .. }
1149 )
1150 {
1151 agent_servers.remove(agent_name.0.as_ref());
1152 }
1153 });
1154 })),
1155 )
1156 }
1157 ExternalAgentSource::Custom => {
1158 let fs = self.fs.clone();
1159 Some(
1160 IconButton::new(
1161 SharedString::from(format!("uninstall-{}", id)),
1162 IconName::Trash,
1163 )
1164 .icon_color(Color::Muted)
1165 .icon_size(IconSize::Small)
1166 .tooltip(Tooltip::text("Remove Custom Agent"))
1167 .on_click(cx.listener(move |_, _, _window, cx| {
1168 let agent_name = agent_server_name.clone();
1169 update_settings_file(fs.clone(), cx, move |settings, _| {
1170 let Some(agent_servers) = settings.agent_servers.as_mut() else {
1171 return;
1172 };
1173 if let Some(entry) = agent_servers.get(agent_name.0.as_ref())
1174 && matches!(
1175 entry,
1176 settings::CustomAgentServerSettings::Custom { .. }
1177 )
1178 {
1179 agent_servers.remove(agent_name.0.as_ref());
1180 }
1181 });
1182 })),
1183 )
1184 }
1185 };
1186
1187 h_flex()
1188 .gap_1()
1189 .justify_between()
1190 .child(
1191 h_flex()
1192 .gap_1p5()
1193 .child(icon)
1194 .child(Label::new(display_name))
1195 .when_some(source_badge, |this, (tooltip_id, tooltip_message, icon)| {
1196 this.child(
1197 div()
1198 .id(tooltip_id)
1199 .flex_none()
1200 .tooltip(Tooltip::text(tooltip_message))
1201 .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted)),
1202 )
1203 })
1204 .child(
1205 Icon::new(IconName::Check)
1206 .color(Color::Success)
1207 .size(IconSize::Small),
1208 ),
1209 )
1210 .when_some(uninstall_button, |this, uninstall_button| {
1211 this.child(uninstall_button)
1212 })
1213 }
1214}
1215
1216impl Render for AgentConfiguration {
1217 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1218 v_flex()
1219 .id("assistant-configuration")
1220 .key_context("AgentConfiguration")
1221 .track_focus(&self.focus_handle(cx))
1222 .relative()
1223 .size_full()
1224 .pb_8()
1225 .bg(cx.theme().colors().panel_background)
1226 .child(
1227 div()
1228 .size_full()
1229 .child(
1230 v_flex()
1231 .id("assistant-configuration-content")
1232 .track_scroll(&self.scroll_handle)
1233 .size_full()
1234 .min_w_0()
1235 .overflow_y_scroll()
1236 .child(self.render_agent_servers_section(cx))
1237 .child(self.render_context_servers_section(window, cx))
1238 .child(self.render_provider_configuration_section(cx)),
1239 )
1240 .vertical_scrollbar_for(&self.scroll_handle, window, cx),
1241 )
1242 }
1243}
1244
1245fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1246 manifest.context_servers.len() == 1
1247 && manifest.themes.is_empty()
1248 && manifest.icon_themes.is_empty()
1249 && manifest.languages.is_empty()
1250 && manifest.grammars.is_empty()
1251 && manifest.language_servers.is_empty()
1252 && manifest.slash_commands.is_empty()
1253 && manifest.snippets.is_none()
1254 && manifest.debug_locators.is_empty()
1255}
1256
1257pub(crate) fn resolve_extension_for_context_server(
1258 id: &ContextServerId,
1259 cx: &App,
1260) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1261 ExtensionStore::global(cx)
1262 .read(cx)
1263 .installed_extensions()
1264 .iter()
1265 .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1266 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1267}
1268
1269// This notification appears when trying to delete
1270// an MCP server extension that not only provides
1271// the server, but other things, too, like language servers and more.
1272fn show_unable_to_uninstall_extension_with_context_server(
1273 workspace: &mut Workspace,
1274 id: ContextServerId,
1275 cx: &mut App,
1276) {
1277 let workspace_handle = workspace.weak_handle();
1278 let context_server_id = id.clone();
1279
1280 let status_toast = StatusToast::new(
1281 format!(
1282 "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1283 id.0
1284 ),
1285 cx,
1286 move |this, _cx| {
1287 let workspace_handle = workspace_handle.clone();
1288
1289 this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1290 .dismiss_button(true)
1291 .action("Uninstall", move |_, _cx| {
1292 if let Some((extension_id, _)) =
1293 resolve_extension_for_context_server(&context_server_id, _cx)
1294 {
1295 ExtensionStore::global(_cx).update(_cx, |store, cx| {
1296 store
1297 .uninstall_extension(extension_id, cx)
1298 .detach_and_log_err(cx);
1299 });
1300
1301 workspace_handle
1302 .update(_cx, |workspace, cx| {
1303 let fs = workspace.app_state().fs.clone();
1304 cx.spawn({
1305 let context_server_id = context_server_id.clone();
1306 async move |_workspace_handle, cx| {
1307 cx.update(|cx| {
1308 update_settings_file(fs, cx, move |settings, _| {
1309 settings
1310 .project
1311 .context_servers
1312 .remove(&context_server_id.0);
1313 });
1314 });
1315 anyhow::Ok(())
1316 }
1317 })
1318 .detach_and_log_err(cx);
1319 })
1320 .log_err();
1321 }
1322 })
1323 },
1324 );
1325
1326 workspace.toggle_status_toast(status_toast, cx);
1327}
1328
1329async fn open_new_agent_servers_entry_in_settings_editor(
1330 workspace: WeakEntity<Workspace>,
1331 cx: &mut AsyncWindowContext,
1332) -> Result<()> {
1333 let settings_editor = workspace
1334 .update_in(cx, |_, window, cx| {
1335 create_and_open_local_file(paths::settings_file(), window, cx, || {
1336 settings::initial_user_settings_content().as_ref().into()
1337 })
1338 })?
1339 .await?
1340 .downcast::<Editor>()
1341 .unwrap();
1342
1343 settings_editor
1344 .downgrade()
1345 .update_in(cx, |item, window, cx| {
1346 let text = item.buffer().read(cx).snapshot(cx).text();
1347
1348 let settings = cx.global::<SettingsStore>();
1349
1350 let mut unique_server_name = None;
1351 let edits = settings.edits_for_update(&text, |settings| {
1352 let server_name: Option<String> = (0..u8::MAX)
1353 .map(|i| {
1354 if i == 0 {
1355 "your_agent".to_string()
1356 } else {
1357 format!("your_agent_{}", i)
1358 }
1359 })
1360 .find(|name| {
1361 !settings
1362 .agent_servers
1363 .as_ref()
1364 .is_some_and(|agent_servers| agent_servers.contains_key(name.as_str()))
1365 });
1366 if let Some(server_name) = server_name {
1367 unique_server_name = Some(SharedString::from(server_name.clone()));
1368 settings.agent_servers.get_or_insert_default().insert(
1369 server_name,
1370 settings::CustomAgentServerSettings::Custom {
1371 path: "path_to_executable".into(),
1372 args: vec![],
1373 env: HashMap::default(),
1374 default_mode: None,
1375 default_model: None,
1376 favorite_models: vec![],
1377 default_config_options: Default::default(),
1378 favorite_config_option_values: Default::default(),
1379 },
1380 );
1381 }
1382 });
1383
1384 if edits.is_empty() {
1385 return;
1386 }
1387
1388 let ranges = edits
1389 .iter()
1390 .map(|(range, _)| range.clone())
1391 .collect::<Vec<_>>();
1392
1393 item.edit(
1394 edits.into_iter().map(|(range, s)| {
1395 (
1396 MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1397 s,
1398 )
1399 }),
1400 cx,
1401 );
1402 if let Some((unique_server_name, buffer)) =
1403 unique_server_name.zip(item.buffer().read(cx).as_singleton())
1404 {
1405 let snapshot = buffer.read(cx).snapshot();
1406 if let Some(range) =
1407 find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1408 {
1409 item.change_selections(
1410 SelectionEffects::scroll(Autoscroll::newest()),
1411 window,
1412 cx,
1413 |selections| {
1414 selections.select_ranges(vec![
1415 MultiBufferOffset(range.start)..MultiBufferOffset(range.end),
1416 ]);
1417 },
1418 );
1419 }
1420 }
1421 })
1422}
1423
1424fn find_text_in_buffer(
1425 text: &str,
1426 start: usize,
1427 snapshot: &language::BufferSnapshot,
1428) -> Option<Range<usize>> {
1429 let chars = text.chars().collect::<Vec<char>>();
1430
1431 let mut offset = start;
1432 let mut char_offset = 0;
1433 for c in snapshot.chars_at(start) {
1434 if char_offset >= chars.len() {
1435 break;
1436 }
1437 offset += 1;
1438
1439 if c == chars[char_offset] {
1440 char_offset += 1;
1441 } else {
1442 char_offset = 0;
1443 }
1444 }
1445
1446 if char_offset == chars.len() {
1447 Some(offset.saturating_sub(chars.len())..offset)
1448 } else {
1449 None
1450 }
1451}
1452
1453// OpenAI-compatible providers are user-configured and can be removed,
1454// whereas built-in providers (like Anthropic, OpenAI, Google, etc.) can't.
1455//
1456// If in the future we have more "API-compatible-type" of providers,
1457// they should be included here as removable providers.
1458fn is_removable_provider(provider_id: &LanguageModelProviderId, cx: &App) -> bool {
1459 AllLanguageModelSettings::get_global(cx)
1460 .openai_compatible
1461 .contains_key(provider_id.0.as_ref())
1462}