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