1mod add_llm_provider_modal;
2mod configure_context_server_modal;
3mod manage_profiles_modal;
4mod tool_picker;
5
6use std::{ops::Range, sync::Arc};
7
8use agent_servers::{AgentServerCommand, AllAgentServersSettings, CustomAgentServerSettings};
9use agent_settings::AgentSettings;
10use anyhow::Result;
11use assistant_tool::{ToolSource, ToolWorkingSet};
12use cloud_llm_client::Plan;
13use collections::HashMap;
14use context_server::ContextServerId;
15use editor::{Editor, SelectionEffects, scroll::Autoscroll};
16use extension::ExtensionManifest;
17use extension_host::ExtensionStore;
18use fs::Fs;
19use gpui::{
20 Action, AnyView, App, AsyncWindowContext, Corner, Entity, EventEmitter, FocusHandle, Focusable,
21 Hsla, ScrollHandle, Subscription, Task, WeakEntity,
22};
23use language::LanguageRegistry;
24use language_model::{
25 LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID,
26};
27use notifications::status_toast::{StatusToast, ToastIcon};
28use project::{
29 context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
30 project_settings::{ContextServerSettings, ProjectSettings},
31};
32use settings::{Settings, SettingsStore, update_settings_file};
33use ui::{
34 Chip, CommonAnimationExt, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex,
35 Indicator, PopoverMenu, Scrollbar, ScrollbarState, Switch, SwitchColor, SwitchField, Tooltip,
36 prelude::*,
37};
38use util::ResultExt as _;
39use workspace::{Workspace, create_and_open_local_file};
40use zed_actions::ExtensionCategoryFilter;
41
42pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
43pub(crate) use manage_profiles_modal::ManageProfilesModal;
44
45use crate::{
46 AddContextServer, ExternalAgent, NewExternalAgentThread,
47 agent_configuration::add_llm_provider_modal::{AddLlmProviderModal, LlmCompatibleProvider},
48};
49
50pub struct AgentConfiguration {
51 fs: Arc<dyn Fs>,
52 language_registry: Arc<LanguageRegistry>,
53 workspace: WeakEntity<Workspace>,
54 focus_handle: FocusHandle,
55 configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
56 context_server_store: Entity<ContextServerStore>,
57 expanded_context_server_tools: HashMap<ContextServerId, bool>,
58 expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
59 tools: Entity<ToolWorkingSet>,
60 _registry_subscription: Subscription,
61 scroll_handle: ScrollHandle,
62 scrollbar_state: ScrollbarState,
63 _check_for_gemini: Task<()>,
64}
65
66impl AgentConfiguration {
67 pub fn new(
68 fs: Arc<dyn Fs>,
69 context_server_store: Entity<ContextServerStore>,
70 tools: Entity<ToolWorkingSet>,
71 language_registry: Arc<LanguageRegistry>,
72 workspace: WeakEntity<Workspace>,
73 window: &mut Window,
74 cx: &mut Context<Self>,
75 ) -> Self {
76 let focus_handle = cx.focus_handle();
77
78 let registry_subscription = cx.subscribe_in(
79 &LanguageModelRegistry::global(cx),
80 window,
81 |this, _, event: &language_model::Event, window, cx| match event {
82 language_model::Event::AddedProvider(provider_id) => {
83 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
84 if let Some(provider) = provider {
85 this.add_provider_configuration_view(&provider, window, cx);
86 }
87 }
88 language_model::Event::RemovedProvider(provider_id) => {
89 this.remove_provider_configuration_view(provider_id);
90 }
91 _ => {}
92 },
93 );
94
95 cx.subscribe(&context_server_store, |_, _, _, cx| cx.notify())
96 .detach();
97
98 let scroll_handle = ScrollHandle::new();
99 let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
100
101 let mut this = Self {
102 fs,
103 language_registry,
104 workspace,
105 focus_handle,
106 configuration_views_by_provider: HashMap::default(),
107 context_server_store,
108 expanded_context_server_tools: HashMap::default(),
109 expanded_provider_configurations: HashMap::default(),
110 tools,
111 _registry_subscription: registry_subscription,
112 scroll_handle,
113 scrollbar_state,
114 _check_for_gemini: Task::ready(()),
115 };
116 this.build_provider_configuration_views(window, cx);
117 this
118 }
119
120 fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
121 let providers = LanguageModelRegistry::read_global(cx).providers();
122 for provider in providers {
123 self.add_provider_configuration_view(&provider, window, cx);
124 }
125 }
126
127 fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
128 self.configuration_views_by_provider.remove(provider_id);
129 self.expanded_provider_configurations.remove(provider_id);
130 }
131
132 fn add_provider_configuration_view(
133 &mut self,
134 provider: &Arc<dyn LanguageModelProvider>,
135 window: &mut Window,
136 cx: &mut Context<Self>,
137 ) {
138 let configuration_view = provider.configuration_view(
139 language_model::ConfigurationViewTargetAgent::ZedAgent,
140 window,
141 cx,
142 );
143 self.configuration_views_by_provider
144 .insert(provider.id(), configuration_view);
145 }
146}
147
148impl Focusable for AgentConfiguration {
149 fn focus_handle(&self, _: &App) -> FocusHandle {
150 self.focus_handle.clone()
151 }
152}
153
154pub enum AssistantConfigurationEvent {
155 NewThread(Arc<dyn LanguageModelProvider>),
156}
157
158impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
159
160impl AgentConfiguration {
161 fn render_provider_configuration_block(
162 &mut self,
163 provider: &Arc<dyn LanguageModelProvider>,
164 cx: &mut Context<Self>,
165 ) -> impl IntoElement + use<> {
166 let provider_id = provider.id().0;
167 let provider_name = provider.name().0;
168 let provider_id_string = SharedString::from(format!("provider-disclosure-{provider_id}"));
169
170 let configuration_view = self
171 .configuration_views_by_provider
172 .get(&provider.id())
173 .cloned();
174
175 let is_expanded = self
176 .expanded_provider_configurations
177 .get(&provider.id())
178 .copied()
179 .unwrap_or(false);
180
181 let is_zed_provider = provider.id() == ZED_CLOUD_PROVIDER_ID;
182 let current_plan = if is_zed_provider {
183 self.workspace
184 .upgrade()
185 .and_then(|workspace| workspace.read(cx).user_store().read(cx).plan())
186 } else {
187 None
188 };
189
190 let is_signed_in = self
191 .workspace
192 .read_with(cx, |workspace, _| {
193 !workspace.client().status().borrow().is_signed_out()
194 })
195 .unwrap_or(false);
196
197 v_flex()
198 .w_full()
199 .when(is_expanded, |this| this.mb_2())
200 .child(
201 div()
202 .opacity(0.6)
203 .px_2()
204 .child(Divider::horizontal().color(DividerColor::Border)),
205 )
206 .child(
207 h_flex()
208 .map(|this| {
209 if is_expanded {
210 this.mt_2().mb_1()
211 } else {
212 this.my_2()
213 }
214 })
215 .w_full()
216 .justify_between()
217 .child(
218 h_flex()
219 .id(provider_id_string.clone())
220 .px_2()
221 .py_0p5()
222 .w_full()
223 .justify_between()
224 .rounded_sm()
225 .hover(|hover| hover.bg(cx.theme().colors().element_hover))
226 .child(
227 h_flex()
228 .w_full()
229 .gap_2()
230 .child(
231 Icon::new(provider.icon())
232 .size(IconSize::Small)
233 .color(Color::Muted),
234 )
235 .child(
236 h_flex()
237 .w_full()
238 .gap_1()
239 .child(Label::new(provider_name.clone()))
240 .map(|this| {
241 if is_zed_provider && is_signed_in {
242 this.child(
243 self.render_zed_plan_info(current_plan, cx),
244 )
245 } else {
246 this.when(
247 provider.is_authenticated(cx)
248 && !is_expanded,
249 |parent| {
250 parent.child(
251 Icon::new(IconName::Check)
252 .color(Color::Success),
253 )
254 },
255 )
256 }
257 }),
258 ),
259 )
260 .child(
261 Disclosure::new(provider_id_string, is_expanded)
262 .opened_icon(IconName::ChevronUp)
263 .closed_icon(IconName::ChevronDown),
264 )
265 .on_click(cx.listener({
266 let provider_id = provider.id();
267 move |this, _event, _window, _cx| {
268 let is_expanded = this
269 .expanded_provider_configurations
270 .entry(provider_id.clone())
271 .or_insert(false);
272
273 *is_expanded = !*is_expanded;
274 }
275 })),
276 )
277 .when(provider.is_authenticated(cx), |parent| {
278 parent.child(
279 Button::new(
280 SharedString::from(format!("new-thread-{provider_id}")),
281 "Start New Thread",
282 )
283 .icon_position(IconPosition::Start)
284 .icon(IconName::Thread)
285 .icon_size(IconSize::Small)
286 .icon_color(Color::Muted)
287 .label_size(LabelSize::Small)
288 .on_click(cx.listener({
289 let provider = provider.clone();
290 move |_this, _event, _window, cx| {
291 cx.emit(AssistantConfigurationEvent::NewThread(
292 provider.clone(),
293 ))
294 }
295 })),
296 )
297 }),
298 )
299 .child(
300 div()
301 .w_full()
302 .px_2()
303 .when(is_expanded, |parent| match configuration_view {
304 Some(configuration_view) => parent.child(configuration_view),
305 None => parent.child(Label::new(format!(
306 "No configuration view for {provider_name}",
307 ))),
308 }),
309 )
310 }
311
312 fn render_provider_configuration_section(
313 &mut self,
314 cx: &mut Context<Self>,
315 ) -> impl IntoElement {
316 let providers = LanguageModelRegistry::read_global(cx).providers();
317
318 v_flex()
319 .w_full()
320 .child(
321 h_flex()
322 .p(DynamicSpacing::Base16.rems(cx))
323 .pr(DynamicSpacing::Base20.rems(cx))
324 .pb_0()
325 .mb_2p5()
326 .items_start()
327 .justify_between()
328 .child(
329 v_flex()
330 .w_full()
331 .gap_0p5()
332 .child(
333 h_flex()
334 .pr_1()
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 with Zed's native agent.")
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 Some(
410 "The agent can perform potentially destructive actions without asking for your confirmation.".into(),
411 ),
412 always_allow_tool_actions,
413 move |state, _window, cx| {
414 let allow = state == &ToggleState::Selected;
415 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
416 settings.set_always_allow_tool_actions(allow);
417 });
418 },
419 )
420 }
421
422 fn render_single_file_review(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
423 let single_file_review = AgentSettings::get_global(cx).single_file_review;
424 let fs = self.fs.clone();
425
426 SwitchField::new(
427 "single-file-review",
428 "Enable single-file agent reviews",
429 Some("Agent edits are also displayed in single-file editors for review.".into()),
430 single_file_review,
431 move |state, _window, cx| {
432 let allow = state == &ToggleState::Selected;
433 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
434 settings.set_single_file_review(allow);
435 });
436 },
437 )
438 }
439
440 fn render_sound_notification(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
441 let play_sound_when_agent_done = AgentSettings::get_global(cx).play_sound_when_agent_done;
442 let fs = self.fs.clone();
443
444 SwitchField::new(
445 "sound-notification",
446 "Play sound when finished generating",
447 Some(
448 "Hear a notification sound when the agent is done generating changes or needs your input.".into(),
449 ),
450 play_sound_when_agent_done,
451 move |state, _window, cx| {
452 let allow = state == &ToggleState::Selected;
453 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
454 settings.set_play_sound_when_agent_done(allow);
455 });
456 },
457 )
458 }
459
460 fn render_modifier_to_send(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
461 let use_modifier_to_send = AgentSettings::get_global(cx).use_modifier_to_send;
462 let fs = self.fs.clone();
463
464 SwitchField::new(
465 "modifier-send",
466 "Use modifier to submit a message",
467 Some(
468 "Make a modifier (cmd-enter on macOS, ctrl-enter on Linux or Windows) required to send messages.".into(),
469 ),
470 use_modifier_to_send,
471 move |state, _window, cx| {
472 let allow = state == &ToggleState::Selected;
473 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
474 settings.set_use_modifier_to_send(allow);
475 });
476 },
477 )
478 }
479
480 fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
481 v_flex()
482 .p(DynamicSpacing::Base16.rems(cx))
483 .pr(DynamicSpacing::Base20.rems(cx))
484 .gap_2p5()
485 .border_b_1()
486 .border_color(cx.theme().colors().border)
487 .child(Headline::new("General Settings"))
488 .child(self.render_command_permission(cx))
489 .child(self.render_single_file_review(cx))
490 .child(self.render_sound_notification(cx))
491 .child(self.render_modifier_to_send(cx))
492 }
493
494 fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
495 if let Some(plan) = plan {
496 let free_chip_bg = cx
497 .theme()
498 .colors()
499 .editor_background
500 .opacity(0.5)
501 .blend(cx.theme().colors().text_accent.opacity(0.05));
502
503 let pro_chip_bg = cx
504 .theme()
505 .colors()
506 .editor_background
507 .opacity(0.5)
508 .blend(cx.theme().colors().text_accent.opacity(0.2));
509
510 let (plan_name, label_color, bg_color) = match plan {
511 Plan::ZedFree => ("Free", Color::Default, free_chip_bg),
512 Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
513 Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
514 };
515
516 Chip::new(plan_name.to_string())
517 .bg_color(bg_color)
518 .label_color(label_color)
519 .into_any_element()
520 } else {
521 div().into_any_element()
522 }
523 }
524
525 fn card_item_bg_color(&self, cx: &mut Context<Self>) -> Hsla {
526 cx.theme().colors().background.opacity(0.25)
527 }
528
529 fn card_item_border_color(&self, cx: &mut Context<Self>) -> Hsla {
530 cx.theme().colors().border.opacity(0.6)
531 }
532
533 fn render_context_servers_section(
534 &mut self,
535 window: &mut Window,
536 cx: &mut Context<Self>,
537 ) -> impl IntoElement {
538 let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
539
540 v_flex()
541 .p(DynamicSpacing::Base16.rems(cx))
542 .pr(DynamicSpacing::Base20.rems(cx))
543 .gap_2()
544 .border_b_1()
545 .border_color(cx.theme().colors().border)
546 .child(
547 v_flex()
548 .gap_0p5()
549 .child(Headline::new("Model Context Protocol (MCP) Servers"))
550 .child(
551 Label::new(
552 "All context servers connected through the Model Context Protocol.",
553 )
554 .color(Color::Muted),
555 ),
556 )
557 .children(
558 context_server_ids.into_iter().map(|context_server_id| {
559 self.render_context_server(context_server_id, window, cx)
560 }),
561 )
562 .child(
563 h_flex()
564 .justify_between()
565 .gap_1p5()
566 .child(
567 h_flex().w_full().child(
568 Button::new("add-context-server", "Add Custom Server")
569 .style(ButtonStyle::Filled)
570 .layer(ElevationIndex::ModalSurface)
571 .full_width()
572 .icon(IconName::Plus)
573 .icon_size(IconSize::Small)
574 .icon_position(IconPosition::Start)
575 .on_click(|_event, window, cx| {
576 window.dispatch_action(AddContextServer.boxed_clone(), cx)
577 }),
578 ),
579 )
580 .child(
581 h_flex().w_full().child(
582 Button::new(
583 "install-context-server-extensions",
584 "Install MCP Extensions",
585 )
586 .style(ButtonStyle::Filled)
587 .layer(ElevationIndex::ModalSurface)
588 .full_width()
589 .icon(IconName::ToolHammer)
590 .icon_size(IconSize::Small)
591 .icon_position(IconPosition::Start)
592 .on_click(|_event, window, cx| {
593 window.dispatch_action(
594 zed_actions::Extensions {
595 category_filter: Some(
596 ExtensionCategoryFilter::ContextServers,
597 ),
598 id: None,
599 }
600 .boxed_clone(),
601 cx,
602 )
603 }),
604 ),
605 ),
606 )
607 }
608
609 fn render_context_server(
610 &self,
611 context_server_id: ContextServerId,
612 window: &mut Window,
613 cx: &mut Context<Self>,
614 ) -> impl use<> + IntoElement {
615 let tools_by_source = self.tools.read(cx).tools_by_source(cx);
616 let server_status = self
617 .context_server_store
618 .read(cx)
619 .status_for_server(&context_server_id)
620 .unwrap_or(ContextServerStatus::Stopped);
621 let server_configuration = self
622 .context_server_store
623 .read(cx)
624 .configuration_for_server(&context_server_id);
625
626 let is_running = matches!(server_status, ContextServerStatus::Running);
627 let item_id = SharedString::from(context_server_id.0.clone());
628 let is_from_extension = server_configuration
629 .as_ref()
630 .map(|config| {
631 matches!(
632 config.as_ref(),
633 ContextServerConfiguration::Extension { .. }
634 )
635 })
636 .unwrap_or(false);
637
638 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
639 Some(error)
640 } else {
641 None
642 };
643
644 let are_tools_expanded = self
645 .expanded_context_server_tools
646 .get(&context_server_id)
647 .copied()
648 .unwrap_or_default();
649 let tools = tools_by_source
650 .get(&ToolSource::ContextServer {
651 id: context_server_id.0.clone().into(),
652 })
653 .map_or([].as_slice(), |tools| tools.as_slice());
654 let tool_count = tools.len();
655
656 let (source_icon, source_tooltip) = if is_from_extension {
657 (
658 IconName::ZedMcpExtension,
659 "This MCP server was installed from an extension.",
660 )
661 } else {
662 (
663 IconName::ZedMcpCustom,
664 "This custom MCP server was installed directly.",
665 )
666 };
667
668 let (status_indicator, tooltip_text) = match server_status {
669 ContextServerStatus::Starting => (
670 Icon::new(IconName::LoadCircle)
671 .size(IconSize::XSmall)
672 .color(Color::Accent)
673 .with_keyed_rotate_animation(
674 SharedString::from(format!("{}-starting", context_server_id.0)),
675 3,
676 )
677 .into_any_element(),
678 "Server is starting.",
679 ),
680 ContextServerStatus::Running => (
681 Indicator::dot().color(Color::Success).into_any_element(),
682 "Server is active.",
683 ),
684 ContextServerStatus::Error(_) => (
685 Indicator::dot().color(Color::Error).into_any_element(),
686 "Server has an error.",
687 ),
688 ContextServerStatus::Stopped => (
689 Indicator::dot().color(Color::Muted).into_any_element(),
690 "Server is stopped.",
691 ),
692 };
693
694 let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
695 .trigger_with_tooltip(
696 IconButton::new("context-server-config-menu", IconName::Settings)
697 .icon_color(Color::Muted)
698 .icon_size(IconSize::Small),
699 Tooltip::text("Open MCP server options"),
700 )
701 .anchor(Corner::TopRight)
702 .menu({
703 let fs = self.fs.clone();
704 let context_server_id = context_server_id.clone();
705 let language_registry = self.language_registry.clone();
706 let context_server_store = self.context_server_store.clone();
707 let workspace = self.workspace.clone();
708 move |window, cx| {
709 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
710 menu.entry("Configure Server", None, {
711 let context_server_id = context_server_id.clone();
712 let language_registry = language_registry.clone();
713 let workspace = workspace.clone();
714 move |window, cx| {
715 ConfigureContextServerModal::show_modal_for_existing_server(
716 context_server_id.clone(),
717 language_registry.clone(),
718 workspace.clone(),
719 window,
720 cx,
721 )
722 .detach_and_log_err(cx);
723 }
724 })
725 .separator()
726 .entry("Uninstall", None, {
727 let fs = fs.clone();
728 let context_server_id = context_server_id.clone();
729 let context_server_store = context_server_store.clone();
730 let workspace = workspace.clone();
731 move |_, cx| {
732 let is_provided_by_extension = context_server_store
733 .read(cx)
734 .configuration_for_server(&context_server_id)
735 .as_ref()
736 .map(|config| {
737 matches!(
738 config.as_ref(),
739 ContextServerConfiguration::Extension { .. }
740 )
741 })
742 .unwrap_or(false);
743
744 let uninstall_extension_task = match (
745 is_provided_by_extension,
746 resolve_extension_for_context_server(&context_server_id, cx),
747 ) {
748 (true, Some((id, manifest))) => {
749 if extension_only_provides_context_server(manifest.as_ref())
750 {
751 ExtensionStore::global(cx).update(cx, |store, cx| {
752 store.uninstall_extension(id, cx)
753 })
754 } else {
755 workspace.update(cx, |workspace, cx| {
756 show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
757 }).log_err();
758 Task::ready(Ok(()))
759 }
760 }
761 _ => Task::ready(Ok(())),
762 };
763
764 cx.spawn({
765 let fs = fs.clone();
766 let context_server_id = context_server_id.clone();
767 async move |cx| {
768 uninstall_extension_task.await?;
769 cx.update(|cx| {
770 update_settings_file::<ProjectSettings>(
771 fs.clone(),
772 cx,
773 {
774 let context_server_id =
775 context_server_id.clone();
776 move |settings, _| {
777 settings
778 .context_servers
779 .remove(&context_server_id.0);
780 }
781 },
782 )
783 })
784 }
785 })
786 .detach_and_log_err(cx);
787 }
788 })
789 }))
790 }
791 });
792
793 v_flex()
794 .id(item_id.clone())
795 .border_1()
796 .rounded_md()
797 .border_color(self.card_item_border_color(cx))
798 .bg(self.card_item_bg_color(cx))
799 .overflow_hidden()
800 .child(
801 h_flex()
802 .p_1()
803 .justify_between()
804 .when(
805 error.is_some() || are_tools_expanded && tool_count >= 1,
806 |element| {
807 element
808 .border_b_1()
809 .border_color(self.card_item_border_color(cx))
810 },
811 )
812 .child(
813 h_flex()
814 .child(
815 Disclosure::new(
816 "tool-list-disclosure",
817 are_tools_expanded || error.is_some(),
818 )
819 .disabled(tool_count == 0)
820 .on_click(cx.listener({
821 let context_server_id = context_server_id.clone();
822 move |this, _event, _window, _cx| {
823 let is_open = this
824 .expanded_context_server_tools
825 .entry(context_server_id.clone())
826 .or_insert(false);
827
828 *is_open = !*is_open;
829 }
830 })),
831 )
832 .child(
833 h_flex()
834 .id(SharedString::from(format!("tooltip-{}", item_id)))
835 .h_full()
836 .w_3()
837 .mx_1()
838 .justify_center()
839 .tooltip(Tooltip::text(tooltip_text))
840 .child(status_indicator),
841 )
842 .child(Label::new(item_id).ml_0p5())
843 .child(
844 div()
845 .id("extension-source")
846 .mt_0p5()
847 .mx_1()
848 .tooltip(Tooltip::text(source_tooltip))
849 .child(
850 Icon::new(source_icon)
851 .size(IconSize::Small)
852 .color(Color::Muted),
853 ),
854 )
855 .when(is_running, |this| {
856 this.child(
857 Label::new(if tool_count == 1 {
858 SharedString::from("1 tool")
859 } else {
860 SharedString::from(format!("{} tools", tool_count))
861 })
862 .color(Color::Muted)
863 .size(LabelSize::Small),
864 )
865 }),
866 )
867 .child(
868 h_flex()
869 .gap_1()
870 .child(context_server_configuration_menu)
871 .child(
872 Switch::new("context-server-switch", is_running.into())
873 .color(SwitchColor::Accent)
874 .on_click({
875 let context_server_manager =
876 self.context_server_store.clone();
877 let fs = self.fs.clone();
878
879 move |state, _window, cx| {
880 let is_enabled = match state {
881 ToggleState::Unselected
882 | ToggleState::Indeterminate => {
883 context_server_manager.update(
884 cx,
885 |this, cx| {
886 this.stop_server(
887 &context_server_id,
888 cx,
889 )
890 .log_err();
891 },
892 );
893 false
894 }
895 ToggleState::Selected => {
896 context_server_manager.update(
897 cx,
898 |this, cx| {
899 if let Some(server) =
900 this.get_server(&context_server_id)
901 {
902 this.start_server(server, cx);
903 }
904 },
905 );
906 true
907 }
908 };
909 update_settings_file::<ProjectSettings>(
910 fs.clone(),
911 cx,
912 {
913 let context_server_id =
914 context_server_id.clone();
915
916 move |settings, _| {
917 settings
918 .context_servers
919 .entry(context_server_id.0)
920 .or_insert_with(|| {
921 ContextServerSettings::Extension {
922 enabled: is_enabled,
923 settings: serde_json::json!({}),
924 }
925 })
926 .set_enabled(is_enabled);
927 }
928 },
929 );
930 }
931 }),
932 ),
933 ),
934 )
935 .map(|parent| {
936 if let Some(error) = error {
937 return parent.child(
938 h_flex()
939 .p_2()
940 .gap_2()
941 .items_start()
942 .child(
943 h_flex()
944 .flex_none()
945 .h(window.line_height() / 1.6_f32)
946 .justify_center()
947 .child(
948 Icon::new(IconName::XCircle)
949 .size(IconSize::XSmall)
950 .color(Color::Error),
951 ),
952 )
953 .child(
954 div().w_full().child(
955 Label::new(error)
956 .buffer_font(cx)
957 .color(Color::Muted)
958 .size(LabelSize::Small),
959 ),
960 ),
961 );
962 }
963
964 if !are_tools_expanded || tools.is_empty() {
965 return parent;
966 }
967
968 parent.child(v_flex().py_1p5().px_1().gap_1().children(
969 tools.iter().enumerate().map(|(ix, tool)| {
970 h_flex()
971 .id(("tool-item", ix))
972 .px_1()
973 .gap_2()
974 .justify_between()
975 .hover(|style| style.bg(cx.theme().colors().element_hover))
976 .rounded_sm()
977 .child(
978 Label::new(tool.name())
979 .buffer_font(cx)
980 .size(LabelSize::Small),
981 )
982 .child(
983 Icon::new(IconName::Info)
984 .size(IconSize::Small)
985 .color(Color::Ignored),
986 )
987 .tooltip(Tooltip::text(tool.description()))
988 }),
989 ))
990 })
991 }
992
993 fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
994 let settings = AllAgentServersSettings::get_global(cx).clone();
995 let user_defined_agents = settings
996 .custom
997 .iter()
998 .map(|(name, settings)| {
999 self.render_agent_server(
1000 IconName::Ai,
1001 name.clone(),
1002 ExternalAgent::Custom {
1003 name: name.clone(),
1004 command: settings.command.clone(),
1005 },
1006 cx,
1007 )
1008 .into_any_element()
1009 })
1010 .collect::<Vec<_>>();
1011
1012 v_flex()
1013 .border_b_1()
1014 .border_color(cx.theme().colors().border)
1015 .child(
1016 v_flex()
1017 .p(DynamicSpacing::Base16.rems(cx))
1018 .pr(DynamicSpacing::Base20.rems(cx))
1019 .gap_2()
1020 .child(
1021 v_flex()
1022 .gap_0p5()
1023 .child(
1024 h_flex()
1025 .pr_1()
1026 .w_full()
1027 .gap_2()
1028 .justify_between()
1029 .child(Headline::new("External Agents"))
1030 .child(
1031 Button::new("add-agent", "Add Agent")
1032 .icon_position(IconPosition::Start)
1033 .icon(IconName::Plus)
1034 .icon_size(IconSize::Small)
1035 .icon_color(Color::Muted)
1036 .label_size(LabelSize::Small)
1037 .on_click(
1038 move |_, window, cx| {
1039 if let Some(workspace) = window.root().flatten() {
1040 let workspace = workspace.downgrade();
1041 window
1042 .spawn(cx, async |cx| {
1043 open_new_agent_servers_entry_in_settings_editor(
1044 workspace,
1045 cx,
1046 ).await
1047 })
1048 .detach_and_log_err(cx);
1049 }
1050 }
1051 ),
1052 )
1053 )
1054 .child(
1055 Label::new(
1056 "All agents connected through the Agent Client Protocol.",
1057 )
1058 .color(Color::Muted),
1059 ),
1060 )
1061 .child(self.render_agent_server(
1062 IconName::AiGemini,
1063 "Gemini CLI",
1064 ExternalAgent::Gemini,
1065 cx,
1066 ))
1067 .child(self.render_agent_server(
1068 IconName::AiClaude,
1069 "Claude Code",
1070 ExternalAgent::ClaudeCode,
1071 cx,
1072 ))
1073 .children(user_defined_agents),
1074 )
1075 }
1076
1077 fn render_agent_server(
1078 &self,
1079 icon: IconName,
1080 name: impl Into<SharedString>,
1081 agent: ExternalAgent,
1082 cx: &mut Context<Self>,
1083 ) -> impl IntoElement {
1084 let name = name.into();
1085 h_flex()
1086 .p_1()
1087 .pl_2()
1088 .gap_1p5()
1089 .justify_between()
1090 .border_1()
1091 .rounded_md()
1092 .border_color(self.card_item_border_color(cx))
1093 .bg(self.card_item_bg_color(cx))
1094 .overflow_hidden()
1095 .child(
1096 h_flex()
1097 .gap_1p5()
1098 .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1099 .child(Label::new(name.clone())),
1100 )
1101 .child(
1102 Button::new(
1103 SharedString::from(format!("start_acp_thread-{name}")),
1104 "Start New Thread",
1105 )
1106 .label_size(LabelSize::Small)
1107 .icon(IconName::Thread)
1108 .icon_position(IconPosition::Start)
1109 .icon_size(IconSize::XSmall)
1110 .icon_color(Color::Muted)
1111 .on_click(move |_, window, cx| {
1112 window.dispatch_action(
1113 NewExternalAgentThread {
1114 agent: Some(agent.clone()),
1115 }
1116 .boxed_clone(),
1117 cx,
1118 );
1119 }),
1120 )
1121 }
1122}
1123
1124impl Render for AgentConfiguration {
1125 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1126 v_flex()
1127 .id("assistant-configuration")
1128 .key_context("AgentConfiguration")
1129 .track_focus(&self.focus_handle(cx))
1130 .relative()
1131 .size_full()
1132 .pb_8()
1133 .bg(cx.theme().colors().panel_background)
1134 .child(
1135 v_flex()
1136 .id("assistant-configuration-content")
1137 .track_scroll(&self.scroll_handle)
1138 .size_full()
1139 .overflow_y_scroll()
1140 .child(self.render_general_settings_section(cx))
1141 .child(self.render_agent_servers_section(cx))
1142 .child(self.render_context_servers_section(window, cx))
1143 .child(self.render_provider_configuration_section(cx)),
1144 )
1145 .child(
1146 div()
1147 .id("assistant-configuration-scrollbar")
1148 .occlude()
1149 .absolute()
1150 .right(px(3.))
1151 .top_0()
1152 .bottom_0()
1153 .pb_6()
1154 .w(px(12.))
1155 .cursor_default()
1156 .on_mouse_move(cx.listener(|_, _, _window, cx| {
1157 cx.notify();
1158 cx.stop_propagation()
1159 }))
1160 .on_hover(|_, _window, cx| {
1161 cx.stop_propagation();
1162 })
1163 .on_any_mouse_down(|_, _window, cx| {
1164 cx.stop_propagation();
1165 })
1166 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
1167 cx.notify();
1168 }))
1169 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1170 )
1171 }
1172}
1173
1174fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1175 manifest.context_servers.len() == 1
1176 && manifest.themes.is_empty()
1177 && manifest.icon_themes.is_empty()
1178 && manifest.languages.is_empty()
1179 && manifest.grammars.is_empty()
1180 && manifest.language_servers.is_empty()
1181 && manifest.slash_commands.is_empty()
1182 && manifest.snippets.is_none()
1183 && manifest.debug_locators.is_empty()
1184}
1185
1186pub(crate) fn resolve_extension_for_context_server(
1187 id: &ContextServerId,
1188 cx: &App,
1189) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1190 ExtensionStore::global(cx)
1191 .read(cx)
1192 .installed_extensions()
1193 .iter()
1194 .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1195 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1196}
1197
1198// This notification appears when trying to delete
1199// an MCP server extension that not only provides
1200// the server, but other things, too, like language servers and more.
1201fn show_unable_to_uninstall_extension_with_context_server(
1202 workspace: &mut Workspace,
1203 id: ContextServerId,
1204 cx: &mut App,
1205) {
1206 let workspace_handle = workspace.weak_handle();
1207 let context_server_id = id.clone();
1208
1209 let status_toast = StatusToast::new(
1210 format!(
1211 "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1212 id.0
1213 ),
1214 cx,
1215 move |this, _cx| {
1216 let workspace_handle = workspace_handle.clone();
1217
1218 this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1219 .dismiss_button(true)
1220 .action("Uninstall", move |_, _cx| {
1221 if let Some((extension_id, _)) =
1222 resolve_extension_for_context_server(&context_server_id, _cx)
1223 {
1224 ExtensionStore::global(_cx).update(_cx, |store, cx| {
1225 store
1226 .uninstall_extension(extension_id, cx)
1227 .detach_and_log_err(cx);
1228 });
1229
1230 workspace_handle
1231 .update(_cx, |workspace, cx| {
1232 let fs = workspace.app_state().fs.clone();
1233 cx.spawn({
1234 let context_server_id = context_server_id.clone();
1235 async move |_workspace_handle, cx| {
1236 cx.update(|cx| {
1237 update_settings_file::<ProjectSettings>(
1238 fs,
1239 cx,
1240 move |settings, _| {
1241 settings
1242 .context_servers
1243 .remove(&context_server_id.0);
1244 },
1245 );
1246 })?;
1247 anyhow::Ok(())
1248 }
1249 })
1250 .detach_and_log_err(cx);
1251 })
1252 .log_err();
1253 }
1254 })
1255 },
1256 );
1257
1258 workspace.toggle_status_toast(status_toast, cx);
1259}
1260
1261async fn open_new_agent_servers_entry_in_settings_editor(
1262 workspace: WeakEntity<Workspace>,
1263 cx: &mut AsyncWindowContext,
1264) -> Result<()> {
1265 let settings_editor = workspace
1266 .update_in(cx, |_, window, cx| {
1267 create_and_open_local_file(paths::settings_file(), window, cx, || {
1268 settings::initial_user_settings_content().as_ref().into()
1269 })
1270 })?
1271 .await?
1272 .downcast::<Editor>()
1273 .unwrap();
1274
1275 settings_editor
1276 .downgrade()
1277 .update_in(cx, |item, window, cx| {
1278 let text = item.buffer().read(cx).snapshot(cx).text();
1279
1280 let settings = cx.global::<SettingsStore>();
1281
1282 let mut unique_server_name = None;
1283 let edits = settings.edits_for_update::<AllAgentServersSettings>(&text, |file| {
1284 let server_name: Option<SharedString> = (0..u8::MAX)
1285 .map(|i| {
1286 if i == 0 {
1287 "your_agent".into()
1288 } else {
1289 format!("your_agent_{}", i).into()
1290 }
1291 })
1292 .find(|name| !file.custom.contains_key(name));
1293 if let Some(server_name) = server_name {
1294 unique_server_name = Some(server_name.clone());
1295 file.custom.insert(
1296 server_name,
1297 CustomAgentServerSettings {
1298 command: AgentServerCommand {
1299 path: "path_to_executable".into(),
1300 args: vec![],
1301 env: Some(HashMap::default()),
1302 },
1303 },
1304 );
1305 }
1306 });
1307
1308 if edits.is_empty() {
1309 return;
1310 }
1311
1312 let ranges = edits
1313 .iter()
1314 .map(|(range, _)| range.clone())
1315 .collect::<Vec<_>>();
1316
1317 item.edit(edits, cx);
1318 if let Some((unique_server_name, buffer)) =
1319 unique_server_name.zip(item.buffer().read(cx).as_singleton())
1320 {
1321 let snapshot = buffer.read(cx).snapshot();
1322 if let Some(range) =
1323 find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1324 {
1325 item.change_selections(
1326 SelectionEffects::scroll(Autoscroll::newest()),
1327 window,
1328 cx,
1329 |selections| {
1330 selections.select_ranges(vec![range]);
1331 },
1332 );
1333 }
1334 }
1335 })
1336}
1337
1338fn find_text_in_buffer(
1339 text: &str,
1340 start: usize,
1341 snapshot: &language::BufferSnapshot,
1342) -> Option<Range<usize>> {
1343 let chars = text.chars().collect::<Vec<char>>();
1344
1345 let mut offset = start;
1346 let mut char_offset = 0;
1347 for c in snapshot.chars_at(start) {
1348 if char_offset >= chars.len() {
1349 break;
1350 }
1351 offset += 1;
1352
1353 if c == chars[char_offset] {
1354 char_offset += 1;
1355 } else {
1356 char_offset = 0;
1357 }
1358 }
1359
1360 if char_offset == chars.len() {
1361 Some(offset.saturating_sub(chars.len())..offset)
1362 } else {
1363 None
1364 }
1365}