1mod add_llm_provider_modal;
2mod configure_context_server_modal;
3mod manage_profiles_modal;
4mod tool_picker;
5
6use std::{ops::Range, sync::Arc, time::Duration};
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, Animation, AnimationExt as _, AnyView, App, AsyncWindowContext, Corner, Entity,
21 EventEmitter, FocusHandle, Focusable, Hsla, ScrollHandle, Subscription, Task, Transformation,
22 WeakEntity, percentage,
23};
24use language::LanguageRegistry;
25use language_model::{
26 LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID,
27};
28use notifications::status_toast::{StatusToast, ToastIcon};
29use project::{
30 context_server_store::{ContextServerConfiguration, ContextServerStatus, ContextServerStore},
31 project_settings::{ContextServerSettings, ProjectSettings},
32};
33use settings::{Settings, SettingsStore, update_settings_file};
34use ui::{
35 Chip, ContextMenu, Disclosure, Divider, DividerColor, ElevationIndex, Indicator, PopoverMenu,
36 Scrollbar, ScrollbarState, Switch, SwitchColor, SwitchField, Tooltip, 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 .w_full()
335 .gap_2()
336 .justify_between()
337 .child(Headline::new("LLM Providers"))
338 .child(
339 PopoverMenu::new("add-provider-popover")
340 .trigger(
341 Button::new("add-provider", "Add Provider")
342 .icon_position(IconPosition::Start)
343 .icon(IconName::Plus)
344 .icon_size(IconSize::Small)
345 .icon_color(Color::Muted)
346 .label_size(LabelSize::Small),
347 )
348 .anchor(gpui::Corner::TopRight)
349 .menu({
350 let workspace = self.workspace.clone();
351 move |window, cx| {
352 Some(ContextMenu::build(
353 window,
354 cx,
355 |menu, _window, _cx| {
356 menu.header("Compatible APIs").entry(
357 "OpenAI",
358 None,
359 {
360 let workspace =
361 workspace.clone();
362 move |window, cx| {
363 workspace
364 .update(cx, |workspace, cx| {
365 AddLlmProviderModal::toggle(
366 LlmCompatibleProvider::OpenAi,
367 workspace,
368 window,
369 cx,
370 );
371 })
372 .log_err();
373 }
374 },
375 )
376 },
377 ))
378 }
379 }),
380 ),
381 )
382 .child(
383 Label::new("Add at least one provider to use AI-powered features with Zed's native agent.")
384 .color(Color::Muted),
385 ),
386 ),
387 )
388 .child(
389 div()
390 .w_full()
391 .pl(DynamicSpacing::Base08.rems(cx))
392 .pr(DynamicSpacing::Base20.rems(cx))
393 .children(
394 providers.into_iter().map(|provider| {
395 self.render_provider_configuration_block(&provider, cx)
396 }),
397 ),
398 )
399 }
400
401 fn render_command_permission(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
402 let always_allow_tool_actions = AgentSettings::get_global(cx).always_allow_tool_actions;
403 let fs = self.fs.clone();
404
405 SwitchField::new(
406 "always-allow-tool-actions-switch",
407 "Allow running commands without asking for confirmation",
408 Some(
409 "The agent can perform potentially destructive actions without asking for your confirmation.".into(),
410 ),
411 always_allow_tool_actions,
412 move |state, _window, cx| {
413 let allow = state == &ToggleState::Selected;
414 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
415 settings.set_always_allow_tool_actions(allow);
416 });
417 },
418 )
419 }
420
421 fn render_single_file_review(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
422 let single_file_review = AgentSettings::get_global(cx).single_file_review;
423 let fs = self.fs.clone();
424
425 SwitchField::new(
426 "single-file-review",
427 "Enable single-file agent reviews",
428 Some("Agent edits are also displayed in single-file editors for review.".into()),
429 single_file_review,
430 move |state, _window, cx| {
431 let allow = state == &ToggleState::Selected;
432 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
433 settings.set_single_file_review(allow);
434 });
435 },
436 )
437 }
438
439 fn render_sound_notification(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
440 let play_sound_when_agent_done = AgentSettings::get_global(cx).play_sound_when_agent_done;
441 let fs = self.fs.clone();
442
443 SwitchField::new(
444 "sound-notification",
445 "Play sound when finished generating",
446 Some(
447 "Hear a notification sound when the agent is done generating changes or needs your input.".into(),
448 ),
449 play_sound_when_agent_done,
450 move |state, _window, cx| {
451 let allow = state == &ToggleState::Selected;
452 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
453 settings.set_play_sound_when_agent_done(allow);
454 });
455 },
456 )
457 }
458
459 fn render_modifier_to_send(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
460 let use_modifier_to_send = AgentSettings::get_global(cx).use_modifier_to_send;
461 let fs = self.fs.clone();
462
463 SwitchField::new(
464 "modifier-send",
465 "Use modifier to submit a message",
466 Some(
467 "Make a modifier (cmd-enter on macOS, ctrl-enter on Linux or Windows) required to send messages.".into(),
468 ),
469 use_modifier_to_send,
470 move |state, _window, cx| {
471 let allow = state == &ToggleState::Selected;
472 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
473 settings.set_use_modifier_to_send(allow);
474 });
475 },
476 )
477 }
478
479 fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
480 v_flex()
481 .p(DynamicSpacing::Base16.rems(cx))
482 .pr(DynamicSpacing::Base20.rems(cx))
483 .gap_2p5()
484 .border_b_1()
485 .border_color(cx.theme().colors().border)
486 .child(Headline::new("General Settings"))
487 .child(self.render_command_permission(cx))
488 .child(self.render_single_file_review(cx))
489 .child(self.render_sound_notification(cx))
490 .child(self.render_modifier_to_send(cx))
491 }
492
493 fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
494 if let Some(plan) = plan {
495 let free_chip_bg = cx
496 .theme()
497 .colors()
498 .editor_background
499 .opacity(0.5)
500 .blend(cx.theme().colors().text_accent.opacity(0.05));
501
502 let pro_chip_bg = cx
503 .theme()
504 .colors()
505 .editor_background
506 .opacity(0.5)
507 .blend(cx.theme().colors().text_accent.opacity(0.2));
508
509 let (plan_name, label_color, bg_color) = match plan {
510 Plan::ZedFree => ("Free", Color::Default, free_chip_bg),
511 Plan::ZedProTrial => ("Pro Trial", Color::Accent, pro_chip_bg),
512 Plan::ZedPro => ("Pro", Color::Accent, pro_chip_bg),
513 };
514
515 Chip::new(plan_name.to_string())
516 .bg_color(bg_color)
517 .label_color(label_color)
518 .into_any_element()
519 } else {
520 div().into_any_element()
521 }
522 }
523
524 fn card_item_bg_color(&self, cx: &mut Context<Self>) -> Hsla {
525 cx.theme().colors().background.opacity(0.25)
526 }
527
528 fn card_item_border_color(&self, cx: &mut Context<Self>) -> Hsla {
529 cx.theme().colors().border.opacity(0.6)
530 }
531
532 fn render_context_servers_section(
533 &mut self,
534 window: &mut Window,
535 cx: &mut Context<Self>,
536 ) -> impl IntoElement {
537 let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
538
539 v_flex()
540 .p(DynamicSpacing::Base16.rems(cx))
541 .pr(DynamicSpacing::Base20.rems(cx))
542 .gap_2()
543 .border_b_1()
544 .border_color(cx.theme().colors().border)
545 .child(
546 v_flex()
547 .gap_0p5()
548 .child(Headline::new("Model Context Protocol (MCP) Servers"))
549 .child(
550 Label::new(
551 "All context servers connected through the Model Context Protocol.",
552 )
553 .color(Color::Muted),
554 ),
555 )
556 .children(
557 context_server_ids.into_iter().map(|context_server_id| {
558 self.render_context_server(context_server_id, window, cx)
559 }),
560 )
561 .child(
562 h_flex()
563 .justify_between()
564 .gap_1p5()
565 .child(
566 h_flex().w_full().child(
567 Button::new("add-context-server", "Add Custom Server")
568 .style(ButtonStyle::Filled)
569 .layer(ElevationIndex::ModalSurface)
570 .full_width()
571 .icon(IconName::Plus)
572 .icon_size(IconSize::Small)
573 .icon_position(IconPosition::Start)
574 .on_click(|_event, window, cx| {
575 window.dispatch_action(AddContextServer.boxed_clone(), cx)
576 }),
577 ),
578 )
579 .child(
580 h_flex().w_full().child(
581 Button::new(
582 "install-context-server-extensions",
583 "Install MCP Extensions",
584 )
585 .style(ButtonStyle::Filled)
586 .layer(ElevationIndex::ModalSurface)
587 .full_width()
588 .icon(IconName::ToolHammer)
589 .icon_size(IconSize::Small)
590 .icon_position(IconPosition::Start)
591 .on_click(|_event, window, cx| {
592 window.dispatch_action(
593 zed_actions::Extensions {
594 category_filter: Some(
595 ExtensionCategoryFilter::ContextServers,
596 ),
597 id: None,
598 }
599 .boxed_clone(),
600 cx,
601 )
602 }),
603 ),
604 ),
605 )
606 }
607
608 fn render_context_server(
609 &self,
610 context_server_id: ContextServerId,
611 window: &mut Window,
612 cx: &mut Context<Self>,
613 ) -> impl use<> + IntoElement {
614 let tools_by_source = self.tools.read(cx).tools_by_source(cx);
615 let server_status = self
616 .context_server_store
617 .read(cx)
618 .status_for_server(&context_server_id)
619 .unwrap_or(ContextServerStatus::Stopped);
620 let server_configuration = self
621 .context_server_store
622 .read(cx)
623 .configuration_for_server(&context_server_id);
624
625 let is_running = matches!(server_status, ContextServerStatus::Running);
626 let item_id = SharedString::from(context_server_id.0.clone());
627 let is_from_extension = server_configuration
628 .as_ref()
629 .map(|config| {
630 matches!(
631 config.as_ref(),
632 ContextServerConfiguration::Extension { .. }
633 )
634 })
635 .unwrap_or(false);
636
637 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
638 Some(error)
639 } else {
640 None
641 };
642
643 let are_tools_expanded = self
644 .expanded_context_server_tools
645 .get(&context_server_id)
646 .copied()
647 .unwrap_or_default();
648 let tools = tools_by_source
649 .get(&ToolSource::ContextServer {
650 id: context_server_id.0.clone().into(),
651 })
652 .map_or([].as_slice(), |tools| tools.as_slice());
653 let tool_count = tools.len();
654
655 let (source_icon, source_tooltip) = if is_from_extension {
656 (
657 IconName::ZedMcpExtension,
658 "This MCP server was installed from an extension.",
659 )
660 } else {
661 (
662 IconName::ZedMcpCustom,
663 "This custom MCP server was installed directly.",
664 )
665 };
666
667 let (status_indicator, tooltip_text) = match server_status {
668 ContextServerStatus::Starting => (
669 Icon::new(IconName::LoadCircle)
670 .size(IconSize::XSmall)
671 .color(Color::Accent)
672 .with_animation(
673 SharedString::from(format!("{}-starting", context_server_id.0,)),
674 Animation::new(Duration::from_secs(3)).repeat(),
675 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
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 .w_full()
1026 .gap_2()
1027 .justify_between()
1028 .child(Headline::new("External Agents"))
1029 .child(
1030 Button::new("add-agent", "Add Agent")
1031 .icon_position(IconPosition::Start)
1032 .icon(IconName::Plus)
1033 .icon_size(IconSize::Small)
1034 .icon_color(Color::Muted)
1035 .label_size(LabelSize::Small)
1036 .on_click(
1037 move |_, window, cx| {
1038 if let Some(workspace) = window.root().flatten() {
1039 let workspace = workspace.downgrade();
1040 window
1041 .spawn(cx, async |cx| {
1042 open_new_agent_servers_entry_in_settings_editor(
1043 workspace,
1044 cx,
1045 ).await
1046 })
1047 .detach_and_log_err(cx);
1048 }
1049 }
1050 ),
1051 )
1052 )
1053 .child(
1054 Label::new(
1055 "Bring the agent of your choice to Zed via our new Agent Client Protocol.",
1056 )
1057 .color(Color::Muted),
1058 ),
1059 )
1060 .child(self.render_agent_server(
1061 IconName::AiGemini,
1062 "Gemini CLI",
1063 ExternalAgent::Gemini,
1064 cx,
1065 ))
1066 // TODO add CC
1067 .children(user_defined_agents),
1068 )
1069 }
1070
1071 fn render_agent_server(
1072 &self,
1073 icon: IconName,
1074 name: impl Into<SharedString>,
1075 agent: ExternalAgent,
1076 cx: &mut Context<Self>,
1077 ) -> impl IntoElement {
1078 let name = name.into();
1079 h_flex()
1080 .p_1()
1081 .pl_2()
1082 .gap_1p5()
1083 .justify_between()
1084 .border_1()
1085 .rounded_md()
1086 .border_color(self.card_item_border_color(cx))
1087 .bg(self.card_item_bg_color(cx))
1088 .overflow_hidden()
1089 .child(
1090 h_flex()
1091 .gap_1p5()
1092 .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1093 .child(Label::new(name.clone())),
1094 )
1095 .child(
1096 h_flex().gap_1().child(
1097 Button::new(
1098 SharedString::from(format!("start_acp_thread-{name}")),
1099 "Start New Thread",
1100 )
1101 .label_size(LabelSize::Small)
1102 .icon(IconName::Thread)
1103 .icon_position(IconPosition::Start)
1104 .icon_size(IconSize::XSmall)
1105 .icon_color(Color::Muted)
1106 .on_click(move |_, window, cx| {
1107 window.dispatch_action(
1108 NewExternalAgentThread {
1109 agent: Some(agent.clone()),
1110 }
1111 .boxed_clone(),
1112 cx,
1113 );
1114 }),
1115 ),
1116 )
1117 }
1118}
1119
1120impl Render for AgentConfiguration {
1121 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1122 v_flex()
1123 .id("assistant-configuration")
1124 .key_context("AgentConfiguration")
1125 .track_focus(&self.focus_handle(cx))
1126 .relative()
1127 .size_full()
1128 .pb_8()
1129 .bg(cx.theme().colors().panel_background)
1130 .child(
1131 v_flex()
1132 .id("assistant-configuration-content")
1133 .track_scroll(&self.scroll_handle)
1134 .size_full()
1135 .overflow_y_scroll()
1136 .child(self.render_general_settings_section(cx))
1137 .child(self.render_agent_servers_section(cx))
1138 .child(self.render_context_servers_section(window, cx))
1139 .child(self.render_provider_configuration_section(cx)),
1140 )
1141 .child(
1142 div()
1143 .id("assistant-configuration-scrollbar")
1144 .occlude()
1145 .absolute()
1146 .right(px(3.))
1147 .top_0()
1148 .bottom_0()
1149 .pb_6()
1150 .w(px(12.))
1151 .cursor_default()
1152 .on_mouse_move(cx.listener(|_, _, _window, cx| {
1153 cx.notify();
1154 cx.stop_propagation()
1155 }))
1156 .on_hover(|_, _window, cx| {
1157 cx.stop_propagation();
1158 })
1159 .on_any_mouse_down(|_, _window, cx| {
1160 cx.stop_propagation();
1161 })
1162 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
1163 cx.notify();
1164 }))
1165 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
1166 )
1167 }
1168}
1169
1170fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1171 manifest.context_servers.len() == 1
1172 && manifest.themes.is_empty()
1173 && manifest.icon_themes.is_empty()
1174 && manifest.languages.is_empty()
1175 && manifest.grammars.is_empty()
1176 && manifest.language_servers.is_empty()
1177 && manifest.slash_commands.is_empty()
1178 && manifest.snippets.is_none()
1179 && manifest.debug_locators.is_empty()
1180}
1181
1182pub(crate) fn resolve_extension_for_context_server(
1183 id: &ContextServerId,
1184 cx: &App,
1185) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1186 ExtensionStore::global(cx)
1187 .read(cx)
1188 .installed_extensions()
1189 .iter()
1190 .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1191 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1192}
1193
1194// This notification appears when trying to delete
1195// an MCP server extension that not only provides
1196// the server, but other things, too, like language servers and more.
1197fn show_unable_to_uninstall_extension_with_context_server(
1198 workspace: &mut Workspace,
1199 id: ContextServerId,
1200 cx: &mut App,
1201) {
1202 let workspace_handle = workspace.weak_handle();
1203 let context_server_id = id.clone();
1204
1205 let status_toast = StatusToast::new(
1206 format!(
1207 "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1208 id.0
1209 ),
1210 cx,
1211 move |this, _cx| {
1212 let workspace_handle = workspace_handle.clone();
1213
1214 this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1215 .dismiss_button(true)
1216 .action("Uninstall", move |_, _cx| {
1217 if let Some((extension_id, _)) =
1218 resolve_extension_for_context_server(&context_server_id, _cx)
1219 {
1220 ExtensionStore::global(_cx).update(_cx, |store, cx| {
1221 store
1222 .uninstall_extension(extension_id, cx)
1223 .detach_and_log_err(cx);
1224 });
1225
1226 workspace_handle
1227 .update(_cx, |workspace, cx| {
1228 let fs = workspace.app_state().fs.clone();
1229 cx.spawn({
1230 let context_server_id = context_server_id.clone();
1231 async move |_workspace_handle, cx| {
1232 cx.update(|cx| {
1233 update_settings_file::<ProjectSettings>(
1234 fs,
1235 cx,
1236 move |settings, _| {
1237 settings
1238 .context_servers
1239 .remove(&context_server_id.0);
1240 },
1241 );
1242 })?;
1243 anyhow::Ok(())
1244 }
1245 })
1246 .detach_and_log_err(cx);
1247 })
1248 .log_err();
1249 }
1250 })
1251 },
1252 );
1253
1254 workspace.toggle_status_toast(status_toast, cx);
1255}
1256
1257async fn open_new_agent_servers_entry_in_settings_editor(
1258 workspace: WeakEntity<Workspace>,
1259 cx: &mut AsyncWindowContext,
1260) -> Result<()> {
1261 let settings_editor = workspace
1262 .update_in(cx, |_, window, cx| {
1263 create_and_open_local_file(paths::settings_file(), window, cx, || {
1264 settings::initial_user_settings_content().as_ref().into()
1265 })
1266 })?
1267 .await?
1268 .downcast::<Editor>()
1269 .unwrap();
1270
1271 settings_editor
1272 .downgrade()
1273 .update_in(cx, |item, window, cx| {
1274 let text = item.buffer().read(cx).snapshot(cx).text();
1275
1276 let settings = cx.global::<SettingsStore>();
1277
1278 let mut unique_server_name = None;
1279 let edits = settings.edits_for_update::<AllAgentServersSettings>(&text, |file| {
1280 let server_name: Option<SharedString> = (0..u8::MAX)
1281 .map(|i| {
1282 if i == 0 {
1283 "your_agent".into()
1284 } else {
1285 format!("your_agent_{}", i).into()
1286 }
1287 })
1288 .find(|name| !file.custom.contains_key(name));
1289 if let Some(server_name) = server_name {
1290 unique_server_name = Some(server_name.clone());
1291 file.custom.insert(
1292 server_name,
1293 CustomAgentServerSettings {
1294 command: AgentServerCommand {
1295 path: "path_to_executable".into(),
1296 args: vec![],
1297 env: Some(HashMap::default()),
1298 },
1299 },
1300 );
1301 }
1302 });
1303
1304 if edits.is_empty() {
1305 return;
1306 }
1307
1308 let ranges = edits
1309 .iter()
1310 .map(|(range, _)| range.clone())
1311 .collect::<Vec<_>>();
1312
1313 item.edit(edits, cx);
1314 if let Some((unique_server_name, buffer)) =
1315 unique_server_name.zip(item.buffer().read(cx).as_singleton())
1316 {
1317 let snapshot = buffer.read(cx).snapshot();
1318 if let Some(range) =
1319 find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1320 {
1321 item.change_selections(
1322 SelectionEffects::scroll(Autoscroll::newest()),
1323 window,
1324 cx,
1325 |selections| {
1326 selections.select_ranges(vec![range]);
1327 },
1328 );
1329 }
1330 }
1331 })
1332}
1333
1334fn find_text_in_buffer(
1335 text: &str,
1336 start: usize,
1337 snapshot: &language::BufferSnapshot,
1338) -> Option<Range<usize>> {
1339 let chars = text.chars().collect::<Vec<char>>();
1340
1341 let mut offset = start;
1342 let mut char_offset = 0;
1343 for c in snapshot.chars_at(start) {
1344 if char_offset >= chars.len() {
1345 break;
1346 }
1347 offset += 1;
1348
1349 if c == chars[char_offset] {
1350 char_offset += 1;
1351 } else {
1352 char_offset = 0;
1353 }
1354 }
1355
1356 if char_offset == chars.len() {
1357 Some(offset.saturating_sub(chars.len())..offset)
1358 } else {
1359 None
1360 }
1361}