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