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