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