1mod add_llm_provider_modal;
2mod configure_context_server_modal;
3mod manage_profiles_modal;
4mod tool_picker;
5
6use std::{sync::Arc, time::Duration};
7
8use agent_settings::AgentSettings;
9use assistant_tool::{ToolSource, ToolWorkingSet};
10use cloud_llm_client::Plan;
11use collections::HashMap;
12use context_server::ContextServerId;
13use extension::ExtensionManifest;
14use extension_host::ExtensionStore;
15use fs::Fs;
16use gpui::{
17 Action, Animation, AnimationExt as _, AnyView, App, Corner, Entity, EventEmitter, FocusHandle,
18 Focusable, ScrollHandle, Subscription, Task, Transformation, WeakEntity, percentage,
19};
20use language::LanguageRegistry;
21use language_model::{
22 LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID,
23};
24use notifications::status_toast::{StatusToast, ToastIcon};
25use project::{
26 context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
27 project_settings::{ContextServerSettings, ProjectSettings},
28};
29use settings::{Settings, update_settings_file};
30use ui::{
31 Chip, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex, Indicator, PopoverMenu,
32 Scrollbar, ScrollbarState, Switch, SwitchColor, SwitchField, Tooltip, prelude::*,
33};
34use util::ResultExt as _;
35use workspace::Workspace;
36use zed_actions::ExtensionCategoryFilter;
37
38pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
39pub(crate) use manage_profiles_modal::ManageProfilesModal;
40
41use crate::{
42 AddContextServer,
43 agent_configuration::add_llm_provider_modal::{AddLlmProviderModal, LlmCompatibleProvider},
44};
45
46pub struct AgentConfiguration {
47 fs: Arc<dyn Fs>,
48 language_registry: Arc<LanguageRegistry>,
49 workspace: WeakEntity<Workspace>,
50 focus_handle: FocusHandle,
51 configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
52 context_server_store: Entity<ContextServerStore>,
53 expanded_context_server_tools: HashMap<ContextServerId, bool>,
54 expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
55 tools: Entity<ToolWorkingSet>,
56 _registry_subscription: Subscription,
57 scroll_handle: ScrollHandle,
58 scrollbar_state: ScrollbarState,
59}
60
61impl AgentConfiguration {
62 pub fn new(
63 fs: Arc<dyn Fs>,
64 context_server_store: Entity<ContextServerStore>,
65 tools: Entity<ToolWorkingSet>,
66 language_registry: Arc<LanguageRegistry>,
67 workspace: WeakEntity<Workspace>,
68 window: &mut Window,
69 cx: &mut Context<Self>,
70 ) -> Self {
71 let focus_handle = cx.focus_handle();
72
73 let registry_subscription = cx.subscribe_in(
74 &LanguageModelRegistry::global(cx),
75 window,
76 |this, _, event: &language_model::Event, window, cx| match event {
77 language_model::Event::AddedProvider(provider_id) => {
78 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
79 if let Some(provider) = provider {
80 this.add_provider_configuration_view(&provider, window, cx);
81 }
82 }
83 language_model::Event::RemovedProvider(provider_id) => {
84 this.remove_provider_configuration_view(provider_id);
85 }
86 _ => {}
87 },
88 );
89
90 cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
91 .detach();
92
93 let scroll_handle = ScrollHandle::new();
94 let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
95
96 let mut expanded_provider_configurations = HashMap::default();
97 if LanguageModelRegistry::read_global(cx)
98 .provider(&ZED_CLOUD_PROVIDER_ID)
99 .map_or(false, |cloud_provider| cloud_provider.must_accept_terms(cx))
100 {
101 expanded_provider_configurations.insert(ZED_CLOUD_PROVIDER_ID, true);
102 }
103
104 let mut this = Self {
105 fs,
106 language_registry,
107 workspace,
108 focus_handle,
109 configuration_views_by_provider: HashMap::default(),
110 context_server_store,
111 expanded_context_server_tools: HashMap::default(),
112 expanded_provider_configurations,
113 tools,
114 _registry_subscription: registry_subscription,
115 scroll_handle,
116 scrollbar_state,
117 };
118 this.build_provider_configuration_views(window, cx);
119 this
120 }
121
122 fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
123 let providers = LanguageModelRegistry::read_global(cx).providers();
124 for provider in providers {
125 self.add_provider_configuration_view(&provider, window, cx);
126 }
127 }
128
129 fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
130 self.configuration_views_by_provider.remove(provider_id);
131 self.expanded_provider_configurations.remove(provider_id);
132 }
133
134 fn add_provider_configuration_view(
135 &mut self,
136 provider: &Arc<dyn LanguageModelProvider>,
137 window: &mut Window,
138 cx: &mut Context<Self>,
139 ) {
140 let configuration_view = provider.configuration_view(window, cx);
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
158impl AgentConfiguration {
159 fn render_provider_configuration_block(
160 &mut self,
161 provider: &Arc<dyn LanguageModelProvider>,
162 cx: &mut Context<Self>,
163 ) -> impl IntoElement + use<> {
164 let provider_id = provider.id().0.clone();
165 let provider_name = provider.name().0.clone();
166 let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
167
168 let configuration_view = self
169 .configuration_views_by_provider
170 .get(&provider.id())
171 .cloned();
172
173 let is_expanded = self
174 .expanded_provider_configurations
175 .get(&provider.id())
176 .copied()
177 .unwrap_or(false);
178
179 let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
180 let current_plan = if is_zed_provider {
181 self.workspace
182 .upgrade()
183 .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
184 } else {
185 None
186 };
187
188 let is_signed_in = self
189 .workspace
190 .read_with(cx, |workspace, _| {
191 workspace.client().status().borrow().is_connected()
192 })
193 .unwrap_or(false);
194
195 v_flex()
196 .w_full()
197 .when(is_expanded, |this| this.mb_2())
198 .child(
199 div()
200 .opacity(0.6)
201 .px_2()
202 .child(Divider::horizontal().color(DividerColor::Border)),
203 )
204 .child(
205 h_flex()
206 .map(|this| {
207 if is_expanded {
208 this.mt_2().mb_1()
209 } else {
210 this.my_2()
211 }
212 })
213 .w_full()
214 .justify_between()
215 .child(
216 h_flex()
217 .id(provider_id_string.clone())
218 .cursor_pointer()
219 .px_2()
220 .py_0p5()
221 .w_full()
222 .justify_between()
223 .rounded_sm()
224 .hover(|hover| hover.bg(cx.theme().colors().element_hover))
225 .child(
226 h_flex()
227 .w_full()
228 .gap_2()
229 .child(
230 Icon::new(provider.icon())
231 .size(IconSize::Small)
232 .color(Color::Muted),
233 )
234 .child(
235 h_flex()
236 .w_full()
237 .gap_1()
238 .child(
239 Label::new(provider_name.clone())
240 .size(LabelSize::Large),
241 )
242 .map(|this| {
243 if is_zed_provider && is_signed_in {
244 this.child(
245 self.render_zed_plan_info(current_plan, cx),
246 )
247 } else {
248 this.when(
249 provider.is_authenticated(cx)
250 && !is_expanded,
251 |parent| {
252 parent.child(
253 Icon::new(IconName::Check)
254 .color(Color::Success),
255 )
256 },
257 )
258 }
259 }),
260 ),
261 )
262 .child(
263 Disclosure::new(provider_id_string, is_expanded)
264 .opened_icon(IconName::ChevronUp)
265 .closed_icon(IconName::ChevronDown),
266 )
267 .on_click(cx.listener({
268 let provider_id = provider.id().clone();
269 move |this, _event, _window, _cx| {
270 let is_expanded = this
271 .expanded_provider_configurations
272 .entry(provider_id.clone())
273 .or_insert(false);
274
275 *is_expanded = !*is_expanded;
276 }
277 })),
278 )
279 .when(provider.is_authenticated(cx), |parent| {
280 parent.child(
281 Button::new(
282 SharedString::from(format!("new-thread-{provider_id}")),
283 "Start New Thread",
284 cx,
285 )
286 .icon_position(IconPosition::Start)
287 .icon(IconName::Plus)
288 .icon_size(IconSize::Small)
289 .icon_color(Color::Muted)
290 .label_size(LabelSize::Small)
291 .on_click(cx.listener({
292 let provider = provider.clone();
293 move |_this, _event, _window, cx| {
294 cx.emit(AssistantConfigurationEvent::NewThread(
295 provider.clone(),
296 ))
297 }
298 })),
299 )
300 }),
301 )
302 .child(
303 div()
304 .px_2()
305 .when(is_expanded, |parent| match configuration_view {
306 Some(configuration_view) => parent.child(configuration_view),
307 None => parent.child(Label::new(format!(
308 "No configuration view for {provider_name}",
309 ))),
310 }),
311 )
312 }
313
314 fn render_provider_configuration_section(
315 &mut self,
316 cx: &mut Context<Self>,
317 ) -> impl IntoElement {
318 let providers = LanguageModelRegistry::read_global(cx).providers();
319
320 v_flex()
321 .w_full()
322 .child(
323 h_flex()
324 .p(DynamicSpacing::Base16.rems(cx))
325 .pr(DynamicSpacing::Base20.rems(cx))
326 .pb_0()
327 .mb_2p5()
328 .items_start()
329 .justify_between()
330 .child(
331 v_flex()
332 .w_full()
333 .gap_0p5()
334 .child(
335 h_flex()
336 .w_full()
337 .gap_2()
338 .justify_between()
339 .child(Headline::new("LLM Providers"))
340 .child(
341 PopoverMenu::new("add-provider-popover")
342 .trigger(
343 Button::new("add-provider", "Add Provider", cx)
344 .icon_position(IconPosition::Start)
345 .icon(IconName::Plus)
346 .icon_size(IconSize::Small)
347 .icon_color(Color::Muted)
348 .label_size(LabelSize::Small),
349 )
350 .anchor(gpui::Corner::TopRight)
351 .menu({
352 let workspace = self.workspace.clone();
353 move |window, cx| {
354 Some(ContextMenu::build(
355 window,
356 cx,
357 |menu, _window, _cx| {
358 menu.header("Compatible APIs").entry(
359 "OpenAI",
360 None,
361 {
362 let workspace =
363 workspace.clone();
364 move |window, cx| {
365 workspace
366 .update(cx, |workspace, cx| {
367 AddLlmProviderModal::toggle(
368 LlmCompatibleProvider::OpenAi,
369 workspace,
370 window,
371 cx,
372 );
373 })
374 .log_err();
375 }
376 },
377 )
378 },
379 ))
380 }
381 }),
382 ),
383 )
384 .child(
385 Label::new("Add at least one provider to use AI-powered features.")
386 .color(Color::Muted),
387 ),
388 ),
389 )
390 .child(
391 div()
392 .w_full()
393 .pl(DynamicSpacing::Base08.rems(cx))
394 .pr(DynamicSpacing::Base20.rems(cx))
395 .children(
396 providers.into_iter().map(|provider| {
397 self.render_provider_configuration_block(&provider, cx)
398 }),
399 ),
400 )
401 }
402
403 fn render_command_permission(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
404 let always_allow_tool_actions = AgentSettings::get_global(cx).always_allow_tool_actions;
405 let fs = self.fs.clone();
406
407 SwitchField::new(
408 "always-allow-tool-actions-switch",
409 "Allow running commands without asking for confirmation",
410 Some(
411 "The agent can perform potentially destructive actions without asking for your confirmation.".into(),
412 ),
413 always_allow_tool_actions,
414 move |state, _window, cx| {
415 let allow = state == &ToggleState::Selected;
416 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
417 settings.set_always_allow_tool_actions(allow);
418 });
419 },
420 )
421 }
422
423 fn render_single_file_review(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
424 let single_file_review = AgentSettings::get_global(cx).single_file_review;
425 let fs = self.fs.clone();
426
427 SwitchField::new(
428 "single-file-review",
429 "Enable single-file agent reviews",
430 Some("Agent edits are also displayed in single-file editors for review.".into()),
431 single_file_review,
432 move |state, _window, cx| {
433 let allow = state == &ToggleState::Selected;
434 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
435 settings.set_single_file_review(allow);
436 });
437 },
438 )
439 }
440
441 fn render_sound_notification(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
442 let play_sound_when_agent_done = AgentSettings::get_global(cx).play_sound_when_agent_done;
443 let fs = self.fs.clone();
444
445 SwitchField::new(
446 "sound-notification",
447 "Play sound when finished generating",
448 Some(
449 "Hear a notification sound when the agent is done generating changes or needs your input.".into(),
450 ),
451 play_sound_when_agent_done,
452 move |state, _window, cx| {
453 let allow = state == &ToggleState::Selected;
454 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
455 settings.set_play_sound_when_agent_done(allow);
456 });
457 },
458 )
459 }
460
461 fn render_modifier_to_send(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
462 let use_modifier_to_send = AgentSettings::get_global(cx).use_modifier_to_send;
463 let fs = self.fs.clone();
464
465 SwitchField::new(
466 "modifier-send",
467 "Use modifier to submit a message",
468 Some(
469 "Make a modifier (cmd-enter on macOS, ctrl-enter on Linux) required to send messages.".into(),
470 ),
471 use_modifier_to_send,
472 move |state, _window, cx| {
473 let allow = state == &ToggleState::Selected;
474 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
475 settings.set_use_modifier_to_send(allow);
476 });
477 },
478 )
479 }
480
481 fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
482 v_flex()
483 .p(DynamicSpacing::Base16.rems(cx))
484 .pr(DynamicSpacing::Base20.rems(cx))
485 .gap_2p5()
486 .border_b_1()
487 .border_color(cx.theme().colors().border)
488 .child(Headline::new("General Settings"))
489 .child(self.render_command_permission(cx))
490 .child(self.render_single_file_review(cx))
491 .child(self.render_sound_notification(cx))
492 .child(self.render_modifier_to_send(cx))
493 }
494
495 fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
496 if let Some(plan) = plan {
497 let free_chip_bg = cx
498 .theme()
499 .colors()
500 .editor_background
501 .opacity(0.5)
502 .blend(cx.theme().colors().text_accent.opacity(0.05));
503
504 let pro_chip_bg = cx
505 .theme()
506 .colors()
507 .editor_background
508 .opacity(0.5)
509 .blend(cx.theme().colors().text_accent.opacity(0.2));
510
511 let (plan_name, label_color, bg_color) = match plan {
512 Plan::ZedFree => ("Free", Color::Default, free_chip_bg),
513 Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
514 Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
515 };
516
517 Chip::new(plan_name.to_string())
518 .bg_color(bg_color)
519 .label_color(label_color)
520 .into_any_element()
521 } else {
522 div().into_any_element()
523 }
524 }
525
526 fn render_context_servers_section(
527 &mut self,
528 window: &mut Window,
529 cx: &mut Context<Self>,
530 ) -> impl IntoElement {
531 let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
532
533 v_flex()
534 .p(DynamicSpacing::Base16.rems(cx))
535 .pr(DynamicSpacing::Base20.rems(cx))
536 .gap_2()
537 .border_b_1()
538 .border_color(cx.theme().colors().border)
539 .child(
540 v_flex()
541 .gap_0p5()
542 .child(Headline::new("Model Context Protocol (MCP) Servers"))
543 .child(Label::new("Connect to context servers through the Model Context Protocol, either using Zed extensions or directly.").color(Color::Muted)),
544 )
545 .children(
546 context_server_ids.into_iter().map(|context_server_id| {
547 self.render_context_server(context_server_id, window, cx)
548 }),
549 )
550 .child(
551 h_flex()
552 .justify_between()
553 .gap_2()
554 .child(
555 h_flex().w_full().child(
556 Button::new("add-context-server", "Add Custom Server", cx)
557 .style(ButtonStyle::Filled)
558 .layer(ElevationIndex::ModalSurface)
559 .full_width()
560 .icon(IconName::Plus)
561 .icon_size(IconSize::Small)
562 .icon_position(IconPosition::Start)
563 .on_click(|_event, window, cx| {
564 window.dispatch_action(AddContextServer.boxed_clone(), cx)
565 }),
566 ),
567 )
568 .child(
569 h_flex().w_full().child(
570 Button::new(
571 "install-context-server-extensions",
572 "Install MCP Extensions",
573 cx,
574 )
575 .style(ButtonStyle::Filled)
576 .layer(ElevationIndex::ModalSurface)
577 .full_width()
578 .icon(IconName::ToolHammer)
579 .icon_size(IconSize::Small)
580 .icon_position(IconPosition::Start)
581 .on_click(|_event, window, cx| {
582 window.dispatch_action(
583 zed_actions::Extensions {
584 category_filter: Some(
585 ExtensionCategoryFilter::ContextServers,
586 ),
587 id: None,
588 }
589 .boxed_clone(),
590 cx,
591 )
592 }),
593 ),
594 ),
595 )
596 }
597
598 fn render_context_server(
599 &self,
600 context_server_id: ContextServerId,
601 window: &mut Window,
602 cx: &mut Context<Self>,
603 ) -> impl use<> + IntoElement {
604 let tools_by_source = self.tools.read(cx).tools_by_source(cx);
605 let server_status = self
606 .context_server_store
607 .read(cx)
608 .status_for_server(&context_server_id)
609 .unwrap_or(ContextServerStatus::Stopped);
610 let server_configuration = self
611 .context_server_store
612 .read(cx)
613 .configuration_for_server(&context_server_id);
614
615 let is_running = matches!(server_status, ContextServerStatus::Running);
616 let item_id = SharedString::from(context_server_id.0.clone());
617 let is_from_extension = server_configuration
618 .as_ref()
619 .map(|config| {
620 matches!(
621 config.as_ref(),
622 ContextServerConfiguration::Extension { .. }
623 )
624 })
625 .unwrap_or(false);
626
627 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
628 Some(error)
629 } else {
630 None
631 };
632
633 let are_tools_expanded = self
634 .expanded_context_server_tools
635 .get(&context_server_id)
636 .copied()
637 .unwrap_or_default();
638 let tools = tools_by_source
639 .get(&ToolSource::ContextServer {
640 id: context_server_id.0.clone().into(),
641 })
642 .map_or([].as_slice(), |tools| tools.as_slice());
643 let tool_count = tools.len();
644
645 let border_color = cx.theme().colors().border.opacity(0.6);
646
647 let (source_icon, source_tooltip) = if is_from_extension {
648 (
649 IconName::ZedMcpExtension,
650 "This MCP server was installed from an extension.",
651 )
652 } else {
653 (
654 IconName::ZedMcpCustom,
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_animation(
665 SharedString::from(format!("{}-starting", context_server_id.0.clone(),)),
666 Animation::new(Duration::from_secs(3)).repeat(),
667 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
668 )
669 .into_any_element(),
670 "Server is starting.",
671 ),
672 ContextServerStatus::Running => (
673 Indicator::dot().color(Color::Success).into_any_element(),
674 "Server is active.",
675 ),
676 ContextServerStatus::Error(_) => (
677 Indicator::dot().color(Color::Error).into_any_element(),
678 "Server has an error.",
679 ),
680 ContextServerStatus::Stopped => (
681 Indicator::dot().color(Color::Muted).into_any_element(),
682 "Server is stopped.",
683 ),
684 };
685
686 let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
687 .trigger_with_tooltip(
688 IconButton::new("context-server-config-menu", IconName::Settings)
689 .icon_color(Color::Muted)
690 .icon_size(IconSize::Small),
691 Tooltip::text("Open MCP server options"),
692 )
693 .anchor(Corner::TopRight)
694 .menu({
695 let fs = self.fs.clone();
696 let context_server_id = context_server_id.clone();
697 let language_registry = self.language_registry.clone();
698 let context_server_store = self.context_server_store.clone();
699 let workspace = self.workspace.clone();
700 move |window, cx| {
701 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
702 menu.entry("Configure Server", None, {
703 let context_server_id = context_server_id.clone();
704 let language_registry = language_registry.clone();
705 let workspace = workspace.clone();
706 move |window, cx| {
707 ConfigureContextServerModal::show_modal_for_existing_server(
708 context_server_id.clone(),
709 language_registry.clone(),
710 workspace.clone(),
711 window,
712 cx,
713 )
714 .detach_and_log_err(cx);
715 }
716 })
717 .separator()
718 .entry("Uninstall", None, {
719 let fs = fs.clone();
720 let context_server_id = context_server_id.clone();
721 let context_server_store = context_server_store.clone();
722 let workspace = workspace.clone();
723 move |_, cx| {
724 let is_provided_by_extension = context_server_store
725 .read(cx)
726 .configuration_for_server(&context_server_id)
727 .as_ref()
728 .map(|config| {
729 matches!(
730 config.as_ref(),
731 ContextServerConfiguration::Extension { .. }
732 )
733 })
734 .unwrap_or(false);
735
736 let uninstall_extension_task = match (
737 is_provided_by_extension,
738 resolve_extension_for_context_server(&context_server_id, cx),
739 ) {
740 (true, Some((id, manifest))) => {
741 if extension_only_provides_context_server(manifest.as_ref())
742 {
743 ExtensionStore::global(cx).update(cx, |store, cx| {
744 store.uninstall_extension(id, cx)
745 })
746 } else {
747 workspace.update(cx, |workspace, cx| {
748 show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
749 }).log_err();
750 Task::ready(Ok(()))
751 }
752 }
753 _ => Task::ready(Ok(())),
754 };
755
756 cx.spawn({
757 let fs = fs.clone();
758 let context_server_id = context_server_id.clone();
759 async move |cx| {
760 uninstall_extension_task.await?;
761 cx.update(|cx| {
762 update_settings_file::<ProjectSettings>(
763 fs.clone(),
764 cx,
765 {
766 let context_server_id =
767 context_server_id.clone();
768 move |settings, _| {
769 settings
770 .context_servers
771 .remove(&context_server_id.0);
772 }
773 },
774 )
775 })
776 }
777 })
778 .detach_and_log_err(cx);
779 }
780 })
781 }))
782 }
783 });
784
785 v_flex()
786 .id(item_id.clone())
787 .border_1()
788 .rounded_md()
789 .border_color(border_color)
790 .bg(cx.theme().colors().background.opacity(0.2))
791 .overflow_hidden()
792 .child(
793 h_flex()
794 .p_1()
795 .justify_between()
796 .when(
797 error.is_some() || are_tools_expanded && tool_count >= 1,
798 |element| element.border_b_1().border_color(border_color),
799 )
800 .child(
801 h_flex()
802 .child(
803 Disclosure::new(
804 "tool-list-disclosure",
805 are_tools_expanded || error.is_some(),
806 )
807 .disabled(tool_count == 0)
808 .on_click(cx.listener({
809 let context_server_id = context_server_id.clone();
810 move |this, _event, _window, _cx| {
811 let is_open = this
812 .expanded_context_server_tools
813 .entry(context_server_id.clone())
814 .or_insert(false);
815
816 *is_open = !*is_open;
817 }
818 })),
819 )
820 .child(
821 h_flex()
822 .id(SharedString::from(format!("tooltip-{}", item_id)))
823 .h_full()
824 .w_3()
825 .mx_1()
826 .justify_center()
827 .tooltip(Tooltip::text(tooltip_text))
828 .child(status_indicator),
829 )
830 .child(Label::new(item_id).ml_0p5())
831 .child(
832 div()
833 .id("extension-source")
834 .mt_0p5()
835 .mx_1()
836 .tooltip(Tooltip::text(source_tooltip))
837 .child(
838 Icon::new(source_icon)
839 .size(IconSize::Small)
840 .color(Color::Muted),
841 ),
842 )
843 .when(is_running, |this| {
844 this.child(
845 Label::new(if tool_count == 1 {
846 SharedString::from("1 tool")
847 } else {
848 SharedString::from(format!("{} tools", tool_count))
849 })
850 .color(Color::Muted)
851 .size(LabelSize::Small),
852 )
853 }),
854 )
855 .child(
856 h_flex()
857 .gap_1()
858 .child(context_server_configuration_menu)
859 .child(
860 Switch::new("context-server-switch", is_running.into())
861 .color(SwitchColor::Accent)
862 .on_click({
863 let context_server_manager =
864 self.context_server_store.clone();
865 let context_server_id = context_server_id.clone();
866 let fs = self.fs.clone();
867
868 move |state, _window, cx| {
869 let is_enabled = match state {
870 ToggleState::Unselected
871 | ToggleState::Indeterminate => {
872 context_server_manager.update(
873 cx,
874 |this, cx| {
875 this.stop_server(
876 &context_server_id,
877 cx,
878 )
879 .log_err();
880 },
881 );
882 false
883 }
884 ToggleState::Selected => {
885 context_server_manager.update(
886 cx,
887 |this, cx| {
888 if let Some(server) =
889 this.get_server(&context_server_id)
890 {
891 this.start_server(server, cx);
892 }
893 },
894 );
895 true
896 }
897 };
898 update_settings_file::<ProjectSettings>(
899 fs.clone(),
900 cx,
901 {
902 let context_server_id =
903 context_server_id.clone();
904
905 move |settings, _| {
906 settings
907 .context_servers
908 .entry(context_server_id.0)
909 .or_insert_with(|| {
910 ContextServerSettings::Extension {
911 enabled: is_enabled,
912 settings: serde_json::json!({}),
913 }
914 })
915 .set_enabled(is_enabled);
916 }
917 },
918 );
919 }
920 }),
921 ),
922 ),
923 )
924 .map(|parent| {
925 if let Some(error) = error {
926 return parent.child(
927 h_flex()
928 .p_2()
929 .gap_2()
930 .items_start()
931 .child(
932 h_flex()
933 .flex_none()
934 .h(window.line_height() / 1.6_f32)
935 .justify_center()
936 .child(
937 Icon::new(IconName::XCircle)
938 .size(IconSize::XSmall)
939 .color(Color::Error),
940 ),
941 )
942 .child(
943 div().w_full().child(
944 Label::new(error)
945 .buffer_font(cx)
946 .color(Color::Muted)
947 .size(LabelSize::Small),
948 ),
949 ),
950 );
951 }
952
953 if !are_tools_expanded || tools.is_empty() {
954 return parent;
955 }
956
957 parent.child(v_flex().py_1p5().px_1().gap_1().children(
958 tools.into_iter().enumerate().map(|(ix, tool)| {
959 h_flex()
960 .id(("tool-item", ix))
961 .px_1()
962 .gap_2()
963 .justify_between()
964 .hover(|style| style.bg(cx.theme().colors().element_hover))
965 .rounded_sm()
966 .child(
967 Label::new(tool.name())
968 .buffer_font(cx)
969 .size(LabelSize::Small),
970 )
971 .child(
972 Icon::new(IconName::Info)
973 .size(IconSize::Small)
974 .color(Color::Ignored),
975 )
976 .tooltip(Tooltip::text(tool.description()))
977 }),
978 ))
979 })
980 }
981}
982
983impl Render for AgentConfiguration {
984 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
985 v_flex()
986 .id("assistant-configuration")
987 .key_context("AgentConfiguration")
988 .track_focus(&self.focus_handle(cx))
989 .relative()
990 .size_full()
991 .pb_8()
992 .bg(cx.theme().colors().panel_background)
993 .child(
994 v_flex()
995 .id("assistant-configuration-content")
996 .track_scroll(&self.scroll_handle)
997 .size_full()
998 .overflow_y_scroll()
999 .child(self.render_general_settings_section(cx))
1000 .child(self.render_context_servers_section(window, cx))
1001 .child(self.render_provider_configuration_section(cx)),
1002 )
1003 .child(
1004 div()
1005 .id("assistant-configuration-scrollbar")
1006 .occlude()
1007 .absolute()
1008 .right(px(3.))
1009 .top_0()
1010 .bottom_0()
1011 .pb_6()
1012 .w(px(12.))
1013 .cursor_default()
1014 .on_mouse_move(cx.listener(|_, _, _window, cx| {
1015 cx.notify();
1016 cx.stop_propagation()
1017 }))
1018 .on_hover(|_, _window, cx| {
1019 cx.stop_propagation();
1020 })
1021 .on_any_mouse_down(|_, _window, cx| {
1022 cx.stop_propagation();
1023 })
1024 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
1025 cx.notify();
1026 }))
1027 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1028 )
1029 }
1030}
1031
1032fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1033 manifest.context_servers.len() == 1
1034 && manifest.themes.is_empty()
1035 && manifest.icon_themes.is_empty()
1036 && manifest.languages.is_empty()
1037 && manifest.grammars.is_empty()
1038 && manifest.language_servers.is_empty()
1039 && manifest.slash_commands.is_empty()
1040 && manifest.indexed_docs_providers.is_empty()
1041 && manifest.snippets.is_none()
1042 && manifest.debug_locators.is_empty()
1043}
1044
1045pub(crate) fn resolve_extension_for_context_server(
1046 id: &ContextServerId,
1047 cx: &App,
1048) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1049 ExtensionStore::global(cx)
1050 .read(cx)
1051 .installed_extensions()
1052 .iter()
1053 .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1054 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1055}
1056
1057// This notification appears when trying to delete
1058// an MCP server extension that not only provides
1059// the server, but other things, too, like language servers and more.
1060fn show_unable_to_uninstall_extension_with_context_server(
1061 workspace: &mut Workspace,
1062 id: ContextServerId,
1063 cx: &mut App,
1064) {
1065 let workspace_handle = workspace.weak_handle();
1066 let context_server_id = id.clone();
1067
1068 let status_toast = StatusToast::new(
1069 format!(
1070 "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1071 id.0
1072 ),
1073 cx,
1074 move |this, _cx| {
1075 let workspace_handle = workspace_handle.clone();
1076 let context_server_id = context_server_id.clone();
1077
1078 this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1079 .dismiss_button(true)
1080 .action("Uninstall", move |_, _cx| {
1081 if let Some((extension_id, _)) =
1082 resolve_extension_for_context_server(&context_server_id, _cx)
1083 {
1084 ExtensionStore::global(_cx).update(_cx, |store, cx| {
1085 store
1086 .uninstall_extension(extension_id, cx)
1087 .detach_and_log_err(cx);
1088 });
1089
1090 workspace_handle
1091 .update(_cx, |workspace, cx| {
1092 let fs = workspace.app_state().fs.clone();
1093 cx.spawn({
1094 let context_server_id = context_server_id.clone();
1095 async move |_workspace_handle, cx| {
1096 cx.update(|cx| {
1097 update_settings_file::<ProjectSettings>(
1098 fs,
1099 cx,
1100 move |settings, _| {
1101 settings
1102 .context_servers
1103 .remove(&context_server_id.0);
1104 },
1105 );
1106 })?;
1107 anyhow::Ok(())
1108 }
1109 })
1110 .detach_and_log_err(cx);
1111 })
1112 .log_err();
1113 }
1114 })
1115 },
1116 );
1117
1118 workspace.toggle_status_toast(status_toast, cx);
1119}