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