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