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 .flex_1()
822 .min_w_0()
823 .child(
824 Disclosure::new(
825 "tool-list-disclosure",
826 are_tools_expanded || error.is_some(),
827 )
828 .disabled(tool_count == 0)
829 .on_click(cx.listener({
830 let context_server_id = context_server_id.clone();
831 move |this, _event, _window, _cx| {
832 let is_open = this
833 .expanded_context_server_tools
834 .entry(context_server_id.clone())
835 .or_insert(false);
836
837 *is_open = !*is_open;
838 }
839 })),
840 )
841 .child(
842 h_flex()
843 .id(SharedString::from(format!("tooltip-{}", item_id)))
844 .h_full()
845 .w_3()
846 .ml_1()
847 .mr_1p5()
848 .justify_center()
849 .tooltip(Tooltip::text(tooltip_text))
850 .child(status_indicator),
851 )
852 .child(Label::new(item_id).truncate())
853 .child(
854 div()
855 .id("extension-source")
856 .mt_0p5()
857 .mx_1()
858 .flex_none()
859 .tooltip(Tooltip::text(source_tooltip))
860 .child(
861 Icon::new(source_icon)
862 .size(IconSize::Small)
863 .color(Color::Muted),
864 ),
865 )
866 .when(is_running, |this| {
867 this.child(
868 Label::new(if tool_count == 1 {
869 SharedString::from("1 tool")
870 } else {
871 SharedString::from(format!("{} tools", tool_count))
872 })
873 .color(Color::Muted)
874 .size(LabelSize::Small),
875 )
876 }),
877 )
878 .child(
879 h_flex()
880 .gap_0p5()
881 .flex_none()
882 .child(context_server_configuration_menu)
883 .child(
884 Switch::new("context-server-switch", is_running.into())
885 .color(SwitchColor::Accent)
886 .on_click({
887 let context_server_manager =
888 self.context_server_store.clone();
889 let fs = self.fs.clone();
890
891 move |state, _window, cx| {
892 let is_enabled = match state {
893 ToggleState::Unselected
894 | ToggleState::Indeterminate => {
895 context_server_manager.update(
896 cx,
897 |this, cx| {
898 this.stop_server(
899 &context_server_id,
900 cx,
901 )
902 .log_err();
903 },
904 );
905 false
906 }
907 ToggleState::Selected => {
908 context_server_manager.update(
909 cx,
910 |this, cx| {
911 if let Some(server) =
912 this.get_server(&context_server_id)
913 {
914 this.start_server(server, cx);
915 }
916 },
917 );
918 true
919 }
920 };
921 update_settings_file::<ProjectSettings>(
922 fs.clone(),
923 cx,
924 {
925 let context_server_id =
926 context_server_id.clone();
927
928 move |settings, _| {
929 settings
930 .context_servers
931 .entry(context_server_id.0)
932 .or_insert_with(|| {
933 ContextServerSettings::Extension {
934 enabled: is_enabled,
935 settings: serde_json::json!({}),
936 }
937 })
938 .set_enabled(is_enabled);
939 }
940 },
941 );
942 }
943 }),
944 ),
945 ),
946 )
947 .map(|parent| {
948 if let Some(error) = error {
949 return parent.child(
950 h_flex()
951 .p_2()
952 .gap_2()
953 .items_start()
954 .child(
955 h_flex()
956 .flex_none()
957 .h(window.line_height() / 1.6_f32)
958 .justify_center()
959 .child(
960 Icon::new(IconName::XCircle)
961 .size(IconSize::XSmall)
962 .color(Color::Error),
963 ),
964 )
965 .child(
966 div().w_full().child(
967 Label::new(error)
968 .buffer_font(cx)
969 .color(Color::Muted)
970 .size(LabelSize::Small),
971 ),
972 ),
973 );
974 }
975
976 if !are_tools_expanded || tools.is_empty() {
977 return parent;
978 }
979
980 parent.child(v_flex().py_1p5().px_1().gap_1().children(
981 tools.iter().enumerate().map(|(ix, tool)| {
982 h_flex()
983 .id(("tool-item", ix))
984 .px_1()
985 .gap_2()
986 .justify_between()
987 .hover(|style| style.bg(cx.theme().colors().element_hover))
988 .rounded_sm()
989 .child(
990 Label::new(tool.name())
991 .buffer_font(cx)
992 .size(LabelSize::Small),
993 )
994 .child(
995 Icon::new(IconName::Info)
996 .size(IconSize::Small)
997 .color(Color::Ignored),
998 )
999 .tooltip(Tooltip::text(tool.description()))
1000 }),
1001 ))
1002 })
1003 }
1004
1005 fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
1006 let custom_settings = cx
1007 .global::<SettingsStore>()
1008 .get::<AllAgentServersSettings>(None)
1009 .custom
1010 .clone();
1011 let user_defined_agents = self
1012 .agent_server_store
1013 .read(cx)
1014 .external_agents()
1015 .filter(|name| name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME)
1016 .cloned()
1017 .collect::<Vec<_>>();
1018 let user_defined_agents = user_defined_agents
1019 .into_iter()
1020 .map(|name| {
1021 self.render_agent_server(
1022 IconName::Ai,
1023 name.clone(),
1024 ExternalAgent::Custom {
1025 name: name.clone().into(),
1026 command: custom_settings
1027 .get(&name.0)
1028 .map(|settings| settings.command.clone())
1029 .unwrap_or(placeholder_command()),
1030 },
1031 cx,
1032 )
1033 .into_any_element()
1034 })
1035 .collect::<Vec<_>>();
1036
1037 v_flex()
1038 .border_b_1()
1039 .border_color(cx.theme().colors().border)
1040 .child(
1041 v_flex()
1042 .p(DynamicSpacing::Base16.rems(cx))
1043 .pr(DynamicSpacing::Base20.rems(cx))
1044 .gap_2()
1045 .child(
1046 v_flex()
1047 .gap_0p5()
1048 .child(
1049 h_flex()
1050 .pr_1()
1051 .w_full()
1052 .gap_2()
1053 .justify_between()
1054 .child(Headline::new("External Agents"))
1055 .child(
1056 Button::new("add-agent", "Add Agent")
1057 .icon_position(IconPosition::Start)
1058 .icon(IconName::Plus)
1059 .icon_size(IconSize::Small)
1060 .icon_color(Color::Muted)
1061 .label_size(LabelSize::Small)
1062 .on_click(
1063 move |_, window, cx| {
1064 if let Some(workspace) = window.root().flatten() {
1065 let workspace = workspace.downgrade();
1066 window
1067 .spawn(cx, async |cx| {
1068 open_new_agent_servers_entry_in_settings_editor(
1069 workspace,
1070 cx,
1071 ).await
1072 })
1073 .detach_and_log_err(cx);
1074 }
1075 }
1076 ),
1077 )
1078 )
1079 .child(
1080 Label::new(
1081 "All agents connected through the Agent Client Protocol.",
1082 )
1083 .color(Color::Muted),
1084 ),
1085 )
1086 .child(self.render_agent_server(
1087 IconName::AiGemini,
1088 "Gemini CLI",
1089 ExternalAgent::Gemini,
1090 cx,
1091 ))
1092 .child(self.render_agent_server(
1093 IconName::AiClaude,
1094 "Claude Code",
1095 ExternalAgent::ClaudeCode,
1096 cx,
1097 ))
1098 .children(user_defined_agents),
1099 )
1100 }
1101
1102 fn render_agent_server(
1103 &self,
1104 icon: IconName,
1105 name: impl Into<SharedString>,
1106 agent: ExternalAgent,
1107 cx: &mut Context<Self>,
1108 ) -> impl IntoElement {
1109 let name = name.into();
1110 h_flex()
1111 .p_1()
1112 .pl_2()
1113 .gap_1p5()
1114 .justify_between()
1115 .border_1()
1116 .rounded_md()
1117 .border_color(self.card_item_border_color(cx))
1118 .bg(self.card_item_bg_color(cx))
1119 .overflow_hidden()
1120 .child(
1121 h_flex()
1122 .gap_1p5()
1123 .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1124 .child(Label::new(name.clone())),
1125 )
1126 .child(
1127 Button::new(
1128 SharedString::from(format!("start_acp_thread-{name}")),
1129 "Start New Thread",
1130 )
1131 .label_size(LabelSize::Small)
1132 .icon(IconName::Thread)
1133 .icon_position(IconPosition::Start)
1134 .icon_size(IconSize::XSmall)
1135 .icon_color(Color::Muted)
1136 .on_click(move |_, window, cx| {
1137 window.dispatch_action(
1138 NewExternalAgentThread {
1139 agent: Some(agent.clone()),
1140 }
1141 .boxed_clone(),
1142 cx,
1143 );
1144 }),
1145 )
1146 }
1147}
1148
1149impl Render for AgentConfiguration {
1150 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1151 v_flex()
1152 .id("assistant-configuration")
1153 .key_context("AgentConfiguration")
1154 .track_focus(&self.focus_handle(cx))
1155 .relative()
1156 .size_full()
1157 .pb_8()
1158 .bg(cx.theme().colors().panel_background)
1159 .child(
1160 div()
1161 .size_full()
1162 .child(
1163 v_flex()
1164 .id("assistant-configuration-content")
1165 .track_scroll(&self.scroll_handle)
1166 .size_full()
1167 .overflow_y_scroll()
1168 .child(self.render_general_settings_section(cx))
1169 .child(self.render_agent_servers_section(cx))
1170 .child(self.render_context_servers_section(window, cx))
1171 .child(self.render_provider_configuration_section(cx)),
1172 )
1173 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx),
1174 )
1175 }
1176}
1177
1178fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1179 manifest.context_servers.len() == 1
1180 && manifest.themes.is_empty()
1181 && manifest.icon_themes.is_empty()
1182 && manifest.languages.is_empty()
1183 && manifest.grammars.is_empty()
1184 && manifest.language_servers.is_empty()
1185 && manifest.slash_commands.is_empty()
1186 && manifest.snippets.is_none()
1187 && manifest.debug_locators.is_empty()
1188}
1189
1190pub(crate) fn resolve_extension_for_context_server(
1191 id: &ContextServerId,
1192 cx: &App,
1193) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1194 ExtensionStore::global(cx)
1195 .read(cx)
1196 .installed_extensions()
1197 .iter()
1198 .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1199 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1200}
1201
1202// This notification appears when trying to delete
1203// an MCP server extension that not only provides
1204// the server, but other things, too, like language servers and more.
1205fn show_unable_to_uninstall_extension_with_context_server(
1206 workspace: &mut Workspace,
1207 id: ContextServerId,
1208 cx: &mut App,
1209) {
1210 let workspace_handle = workspace.weak_handle();
1211 let context_server_id = id.clone();
1212
1213 let status_toast = StatusToast::new(
1214 format!(
1215 "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1216 id.0
1217 ),
1218 cx,
1219 move |this, _cx| {
1220 let workspace_handle = workspace_handle.clone();
1221
1222 this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1223 .dismiss_button(true)
1224 .action("Uninstall", move |_, _cx| {
1225 if let Some((extension_id, _)) =
1226 resolve_extension_for_context_server(&context_server_id, _cx)
1227 {
1228 ExtensionStore::global(_cx).update(_cx, |store, cx| {
1229 store
1230 .uninstall_extension(extension_id, cx)
1231 .detach_and_log_err(cx);
1232 });
1233
1234 workspace_handle
1235 .update(_cx, |workspace, cx| {
1236 let fs = workspace.app_state().fs.clone();
1237 cx.spawn({
1238 let context_server_id = context_server_id.clone();
1239 async move |_workspace_handle, cx| {
1240 cx.update(|cx| {
1241 update_settings_file::<ProjectSettings>(
1242 fs,
1243 cx,
1244 move |settings, _| {
1245 settings
1246 .context_servers
1247 .remove(&context_server_id.0);
1248 },
1249 );
1250 })?;
1251 anyhow::Ok(())
1252 }
1253 })
1254 .detach_and_log_err(cx);
1255 })
1256 .log_err();
1257 }
1258 })
1259 },
1260 );
1261
1262 workspace.toggle_status_toast(status_toast, cx);
1263}
1264
1265async fn open_new_agent_servers_entry_in_settings_editor(
1266 workspace: WeakEntity<Workspace>,
1267 cx: &mut AsyncWindowContext,
1268) -> Result<()> {
1269 let settings_editor = workspace
1270 .update_in(cx, |_, window, cx| {
1271 create_and_open_local_file(paths::settings_file(), window, cx, || {
1272 settings::initial_user_settings_content().as_ref().into()
1273 })
1274 })?
1275 .await?
1276 .downcast::<Editor>()
1277 .unwrap();
1278
1279 settings_editor
1280 .downgrade()
1281 .update_in(cx, |item, window, cx| {
1282 let text = item.buffer().read(cx).snapshot(cx).text();
1283
1284 let settings = cx.global::<SettingsStore>();
1285
1286 let mut unique_server_name = None;
1287 let edits = settings.edits_for_update::<AllAgentServersSettings>(&text, |file| {
1288 let server_name: Option<SharedString> = (0..u8::MAX)
1289 .map(|i| {
1290 if i == 0 {
1291 "your_agent".into()
1292 } else {
1293 format!("your_agent_{}", i).into()
1294 }
1295 })
1296 .find(|name| !file.custom.contains_key(name));
1297 if let Some(server_name) = server_name {
1298 unique_server_name = Some(server_name.clone());
1299 file.custom.insert(
1300 server_name,
1301 CustomAgentServerSettings {
1302 command: AgentServerCommand {
1303 path: "path_to_executable".into(),
1304 args: vec![],
1305 env: Some(HashMap::default()),
1306 },
1307 default_mode: None,
1308 },
1309 );
1310 }
1311 });
1312
1313 if edits.is_empty() {
1314 return;
1315 }
1316
1317 let ranges = edits
1318 .iter()
1319 .map(|(range, _)| range.clone())
1320 .collect::<Vec<_>>();
1321
1322 item.edit(edits, cx);
1323 if let Some((unique_server_name, buffer)) =
1324 unique_server_name.zip(item.buffer().read(cx).as_singleton())
1325 {
1326 let snapshot = buffer.read(cx).snapshot();
1327 if let Some(range) =
1328 find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1329 {
1330 item.change_selections(
1331 SelectionEffects::scroll(Autoscroll::newest()),
1332 window,
1333 cx,
1334 |selections| {
1335 selections.select_ranges(vec![range]);
1336 },
1337 );
1338 }
1339 }
1340 })
1341}
1342
1343fn find_text_in_buffer(
1344 text: &str,
1345 start: usize,
1346 snapshot: &language::BufferSnapshot,
1347) -> Option<Range<usize>> {
1348 let chars = text.chars().collect::<Vec<char>>();
1349
1350 let mut offset = start;
1351 let mut char_offset = 0;
1352 for c in snapshot.chars_at(start) {
1353 if char_offset >= chars.len() {
1354 break;
1355 }
1356 offset += 1;
1357
1358 if c == chars[char_offset] {
1359 char_offset += 1;
1360 } else {
1361 char_offset = 0;
1362 }
1363 }
1364
1365 if char_offset == chars.len() {
1366 Some(offset.saturating_sub(chars.len())..offset)
1367 } else {
1368 None
1369 }
1370}