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