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