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(fs.clone(), cx, move |settings, _| {
417 settings.agent.get_or_insert_default.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(fs.clone(), cx, move |settings, _| {
435 settings
436 .agent
437 .get_or_insert_default()
438 .set_single_file_review(allow);
439 });
440 },
441 )
442 }
443
444 fn render_sound_notification(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
445 let play_sound_when_agent_done = AgentSettings::get_global(cx).play_sound_when_agent_done;
446 let fs = self.fs.clone();
447
448 SwitchField::new(
449 "sound-notification",
450 "Play sound when finished generating",
451 Some(
452 "Hear a notification sound when the agent is done generating changes or needs your input.".into(),
453 ),
454 play_sound_when_agent_done,
455 move |state, _window, cx| {
456 let allow = state == &ToggleState::Selected;
457 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
458 settings.set_play_sound_when_agent_done(allow);
459 });
460 },
461 )
462 }
463
464 fn render_modifier_to_send(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
465 let use_modifier_to_send = AgentSettings::get_global(cx).use_modifier_to_send;
466 let fs = self.fs.clone();
467
468 SwitchField::new(
469 "modifier-send",
470 "Use modifier to submit a message",
471 Some(
472 "Make a modifier (cmd-enter on macOS, ctrl-enter on Linux or Windows) required to send messages.".into(),
473 ),
474 use_modifier_to_send,
475 move |state, _window, cx| {
476 let allow = state == &ToggleState::Selected;
477 update_settings_file::<AgentSettings>(fs.clone(), cx, move |settings, _| {
478 settings.set_use_modifier_to_send(allow);
479 });
480 },
481 )
482 }
483
484 fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
485 v_flex()
486 .p(DynamicSpacing::Base16.rems(cx))
487 .pr(DynamicSpacing::Base20.rems(cx))
488 .gap_2p5()
489 .border_b_1()
490 .border_color(cx.theme().colors().border)
491 .child(Headline::new("General Settings"))
492 .child(self.render_command_permission(cx))
493 .child(self.render_single_file_review(cx))
494 .child(self.render_sound_notification(cx))
495 .child(self.render_modifier_to_send(cx))
496 }
497
498 fn render_zed_plan_info(&self, plan: Option<Plan>, cx: &mut Context<Self>) -> impl IntoElement {
499 if let Some(plan) = plan {
500 let free_chip_bg = cx
501 .theme()
502 .colors()
503 .editor_background
504 .opacity(0.5)
505 .blend(cx.theme().colors().text_accent.opacity(0.05));
506
507 let pro_chip_bg = cx
508 .theme()
509 .colors()
510 .editor_background
511 .opacity(0.5)
512 .blend(cx.theme().colors().text_accent.opacity(0.2));
513
514 let (plan_name, label_color, bg_color) = match plan {
515 Plan::V1(PlanV1::ZedFree) | Plan::V2(PlanV2::ZedFree) => {
516 ("Free", Color::Default, free_chip_bg)
517 }
518 Plan::V1(PlanV1::ZedProTrial) | Plan::V2(PlanV2::ZedProTrial) => {
519 ("Pro Trial", Color::Accent, pro_chip_bg)
520 }
521 Plan::V1(PlanV1::ZedPro) | Plan::V2(PlanV2::ZedPro) => {
522 ("Pro", Color::Accent, pro_chip_bg)
523 }
524 };
525
526 Chip::new(plan_name.to_string())
527 .bg_color(bg_color)
528 .label_color(label_color)
529 .into_any_element()
530 } else {
531 div().into_any_element()
532 }
533 }
534
535 fn card_item_bg_color(&self, cx: &mut Context<Self>) -> Hsla {
536 cx.theme().colors().background.opacity(0.25)
537 }
538
539 fn card_item_border_color(&self, cx: &mut Context<Self>) -> Hsla {
540 cx.theme().colors().border.opacity(0.6)
541 }
542
543 fn render_context_servers_section(
544 &mut self,
545 window: &mut Window,
546 cx: &mut Context<Self>,
547 ) -> impl IntoElement {
548 let context_server_ids = self.context_server_store.read(cx).configured_server_ids();
549
550 v_flex()
551 .p(DynamicSpacing::Base16.rems(cx))
552 .pr(DynamicSpacing::Base20.rems(cx))
553 .gap_2()
554 .border_b_1()
555 .border_color(cx.theme().colors().border)
556 .child(
557 v_flex()
558 .gap_0p5()
559 .child(Headline::new("Model Context Protocol (MCP) Servers"))
560 .child(
561 Label::new(
562 "All context servers connected through the Model Context Protocol.",
563 )
564 .color(Color::Muted),
565 ),
566 )
567 .children(
568 context_server_ids.into_iter().map(|context_server_id| {
569 self.render_context_server(context_server_id, window, cx)
570 }),
571 )
572 .child(
573 h_flex()
574 .justify_between()
575 .gap_1p5()
576 .child(
577 h_flex().w_full().child(
578 Button::new("add-context-server", "Add Custom Server")
579 .style(ButtonStyle::Filled)
580 .layer(ElevationIndex::ModalSurface)
581 .full_width()
582 .icon(IconName::Plus)
583 .icon_size(IconSize::Small)
584 .icon_position(IconPosition::Start)
585 .on_click(|_event, window, cx| {
586 window.dispatch_action(AddContextServer.boxed_clone(), cx)
587 }),
588 ),
589 )
590 .child(
591 h_flex().w_full().child(
592 Button::new(
593 "install-context-server-extensions",
594 "Install MCP Extensions",
595 )
596 .style(ButtonStyle::Filled)
597 .layer(ElevationIndex::ModalSurface)
598 .full_width()
599 .icon(IconName::ToolHammer)
600 .icon_size(IconSize::Small)
601 .icon_position(IconPosition::Start)
602 .on_click(|_event, window, cx| {
603 window.dispatch_action(
604 zed_actions::Extensions {
605 category_filter: Some(
606 ExtensionCategoryFilter::ContextServers,
607 ),
608 id: None,
609 }
610 .boxed_clone(),
611 cx,
612 )
613 }),
614 ),
615 ),
616 )
617 }
618
619 fn render_context_server(
620 &self,
621 context_server_id: ContextServerId,
622 window: &mut Window,
623 cx: &mut Context<Self>,
624 ) -> impl use<> + IntoElement {
625 let tools_by_source = self.tools.read(cx).tools_by_source(cx);
626 let server_status = self
627 .context_server_store
628 .read(cx)
629 .status_for_server(&context_server_id)
630 .unwrap_or(ContextServerStatus::Stopped);
631 let server_configuration = self
632 .context_server_store
633 .read(cx)
634 .configuration_for_server(&context_server_id);
635
636 let is_running = matches!(server_status, ContextServerStatus::Running);
637 let item_id = SharedString::from(context_server_id.0.clone());
638 let is_from_extension = server_configuration
639 .as_ref()
640 .map(|config| {
641 matches!(
642 config.as_ref(),
643 ContextServerConfiguration::Extension { .. }
644 )
645 })
646 .unwrap_or(false);
647
648 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
649 Some(error)
650 } else {
651 None
652 };
653
654 let are_tools_expanded = self
655 .expanded_context_server_tools
656 .get(&context_server_id)
657 .copied()
658 .unwrap_or_default();
659 let tools = tools_by_source
660 .get(&ToolSource::ContextServer {
661 id: context_server_id.0.clone().into(),
662 })
663 .map_or([].as_slice(), |tools| tools.as_slice());
664 let tool_count = tools.len();
665
666 let (source_icon, source_tooltip) = if is_from_extension {
667 (
668 IconName::ZedMcpExtension,
669 "This MCP server was installed from an extension.",
670 )
671 } else {
672 (
673 IconName::ZedMcpCustom,
674 "This custom MCP server was installed directly.",
675 )
676 };
677
678 let (status_indicator, tooltip_text) = match server_status {
679 ContextServerStatus::Starting => (
680 Icon::new(IconName::LoadCircle)
681 .size(IconSize::XSmall)
682 .color(Color::Accent)
683 .with_keyed_rotate_animation(
684 SharedString::from(format!("{}-starting", context_server_id.0)),
685 3,
686 )
687 .into_any_element(),
688 "Server is starting.",
689 ),
690 ContextServerStatus::Running => (
691 Indicator::dot().color(Color::Success).into_any_element(),
692 "Server is active.",
693 ),
694 ContextServerStatus::Error(_) => (
695 Indicator::dot().color(Color::Error).into_any_element(),
696 "Server has an error.",
697 ),
698 ContextServerStatus::Stopped => (
699 Indicator::dot().color(Color::Muted).into_any_element(),
700 "Server is stopped.",
701 ),
702 };
703
704 let context_server_configuration_menu = PopoverMenu::new("context-server-config-menu")
705 .trigger_with_tooltip(
706 IconButton::new("context-server-config-menu", IconName::Settings)
707 .icon_color(Color::Muted)
708 .icon_size(IconSize::Small),
709 Tooltip::text("Open MCP server options"),
710 )
711 .anchor(Corner::TopRight)
712 .menu({
713 let fs = self.fs.clone();
714 let context_server_id = context_server_id.clone();
715 let language_registry = self.language_registry.clone();
716 let context_server_store = self.context_server_store.clone();
717 let workspace = self.workspace.clone();
718 move |window, cx| {
719 Some(ContextMenu::build(window, cx, |menu, _window, _cx| {
720 menu.entry("Configure Server", None, {
721 let context_server_id = context_server_id.clone();
722 let language_registry = language_registry.clone();
723 let workspace = workspace.clone();
724 move |window, cx| {
725 ConfigureContextServerModal::show_modal_for_existing_server(
726 context_server_id.clone(),
727 language_registry.clone(),
728 workspace.clone(),
729 window,
730 cx,
731 )
732 .detach_and_log_err(cx);
733 }
734 })
735 .separator()
736 .entry("Uninstall", None, {
737 let fs = fs.clone();
738 let context_server_id = context_server_id.clone();
739 let context_server_store = context_server_store.clone();
740 let workspace = workspace.clone();
741 move |_, cx| {
742 let is_provided_by_extension = context_server_store
743 .read(cx)
744 .configuration_for_server(&context_server_id)
745 .as_ref()
746 .map(|config| {
747 matches!(
748 config.as_ref(),
749 ContextServerConfiguration::Extension { .. }
750 )
751 })
752 .unwrap_or(false);
753
754 let uninstall_extension_task = match (
755 is_provided_by_extension,
756 resolve_extension_for_context_server(&context_server_id, cx),
757 ) {
758 (true, Some((id, manifest))) => {
759 if extension_only_provides_context_server(manifest.as_ref())
760 {
761 ExtensionStore::global(cx).update(cx, |store, cx| {
762 store.uninstall_extension(id, cx)
763 })
764 } else {
765 workspace.update(cx, |workspace, cx| {
766 show_unable_to_uninstall_extension_with_context_server(workspace, context_server_id.clone(), cx);
767 }).log_err();
768 Task::ready(Ok(()))
769 }
770 }
771 _ => Task::ready(Ok(())),
772 };
773
774 cx.spawn({
775 let fs = fs.clone();
776 let context_server_id = context_server_id.clone();
777 async move |cx| {
778 uninstall_extension_task.await?;
779 cx.update(|cx| {
780 update_settings_file::<ProjectSettings>(
781 fs.clone(),
782 cx,
783 {
784 let context_server_id =
785 context_server_id.clone();
786 move |settings, _| {
787 settings
788 .context_servers
789 .remove(&context_server_id.0);
790 }
791 },
792 )
793 })
794 }
795 })
796 .detach_and_log_err(cx);
797 }
798 })
799 }))
800 }
801 });
802
803 v_flex()
804 .id(item_id.clone())
805 .border_1()
806 .rounded_md()
807 .border_color(self.card_item_border_color(cx))
808 .bg(self.card_item_bg_color(cx))
809 .overflow_hidden()
810 .child(
811 h_flex()
812 .p_1()
813 .justify_between()
814 .when(
815 error.is_some() || are_tools_expanded && tool_count >= 1,
816 |element| {
817 element
818 .border_b_1()
819 .border_color(self.card_item_border_color(cx))
820 },
821 )
822 .child(
823 h_flex()
824 .child(
825 Disclosure::new(
826 "tool-list-disclosure",
827 are_tools_expanded || error.is_some(),
828 )
829 .disabled(tool_count == 0)
830 .on_click(cx.listener({
831 let context_server_id = context_server_id.clone();
832 move |this, _event, _window, _cx| {
833 let is_open = this
834 .expanded_context_server_tools
835 .entry(context_server_id.clone())
836 .or_insert(false);
837
838 *is_open = !*is_open;
839 }
840 })),
841 )
842 .child(
843 h_flex()
844 .id(SharedString::from(format!("tooltip-{}", item_id)))
845 .h_full()
846 .w_3()
847 .mx_1()
848 .justify_center()
849 .tooltip(Tooltip::text(tooltip_text))
850 .child(status_indicator),
851 )
852 .child(Label::new(item_id).ml_0p5())
853 .child(
854 div()
855 .id("extension-source")
856 .mt_0p5()
857 .mx_1()
858 .tooltip(Tooltip::text(source_tooltip))
859 .child(
860 Icon::new(source_icon)
861 .size(IconSize::Small)
862 .color(Color::Muted),
863 ),
864 )
865 .when(is_running, |this| {
866 this.child(
867 Label::new(if tool_count == 1 {
868 SharedString::from("1 tool")
869 } else {
870 SharedString::from(format!("{} tools", tool_count))
871 })
872 .color(Color::Muted)
873 .size(LabelSize::Small),
874 )
875 }),
876 )
877 .child(
878 h_flex()
879 .gap_1()
880 .child(context_server_configuration_menu)
881 .child(
882 Switch::new("context-server-switch", is_running.into())
883 .color(SwitchColor::Accent)
884 .on_click({
885 let context_server_manager =
886 self.context_server_store.clone();
887 let fs = self.fs.clone();
888
889 move |state, _window, cx| {
890 let is_enabled = match state {
891 ToggleState::Unselected
892 | ToggleState::Indeterminate => {
893 context_server_manager.update(
894 cx,
895 |this, cx| {
896 this.stop_server(
897 &context_server_id,
898 cx,
899 )
900 .log_err();
901 },
902 );
903 false
904 }
905 ToggleState::Selected => {
906 context_server_manager.update(
907 cx,
908 |this, cx| {
909 if let Some(server) =
910 this.get_server(&context_server_id)
911 {
912 this.start_server(server, cx);
913 }
914 },
915 );
916 true
917 }
918 };
919 update_settings_file::<ProjectSettings>(
920 fs.clone(),
921 cx,
922 {
923 let context_server_id =
924 context_server_id.clone();
925
926 move |settings, _| {
927 settings
928 .context_servers
929 .entry(context_server_id.0)
930 .or_insert_with(|| {
931 ContextServerSettings::Extension {
932 enabled: is_enabled,
933 settings: serde_json::json!({}),
934 }
935 })
936 .set_enabled(is_enabled);
937 }
938 },
939 );
940 }
941 }),
942 ),
943 ),
944 )
945 .map(|parent| {
946 if let Some(error) = error {
947 return parent.child(
948 h_flex()
949 .p_2()
950 .gap_2()
951 .items_start()
952 .child(
953 h_flex()
954 .flex_none()
955 .h(window.line_height() / 1.6_f32)
956 .justify_center()
957 .child(
958 Icon::new(IconName::XCircle)
959 .size(IconSize::XSmall)
960 .color(Color::Error),
961 ),
962 )
963 .child(
964 div().w_full().child(
965 Label::new(error)
966 .buffer_font(cx)
967 .color(Color::Muted)
968 .size(LabelSize::Small),
969 ),
970 ),
971 );
972 }
973
974 if !are_tools_expanded || tools.is_empty() {
975 return parent;
976 }
977
978 parent.child(v_flex().py_1p5().px_1().gap_1().children(
979 tools.iter().enumerate().map(|(ix, tool)| {
980 h_flex()
981 .id(("tool-item", ix))
982 .px_1()
983 .gap_2()
984 .justify_between()
985 .hover(|style| style.bg(cx.theme().colors().element_hover))
986 .rounded_sm()
987 .child(
988 Label::new(tool.name())
989 .buffer_font(cx)
990 .size(LabelSize::Small),
991 )
992 .child(
993 Icon::new(IconName::Info)
994 .size(IconSize::Small)
995 .color(Color::Ignored),
996 )
997 .tooltip(Tooltip::text(tool.description()))
998 }),
999 ))
1000 })
1001 }
1002
1003 fn render_agent_servers_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
1004 let custom_settings = cx
1005 .global::<SettingsStore>()
1006 .get::<AllAgentServersSettings>(None)
1007 .custom
1008 .clone();
1009 let user_defined_agents = self
1010 .agent_server_store
1011 .read(cx)
1012 .external_agents()
1013 .filter(|name| name.0 != GEMINI_NAME && name.0 != CLAUDE_CODE_NAME)
1014 .cloned()
1015 .collect::<Vec<_>>();
1016 let user_defined_agents = user_defined_agents
1017 .into_iter()
1018 .map(|name| {
1019 self.render_agent_server(
1020 IconName::Ai,
1021 name.clone(),
1022 ExternalAgent::Custom {
1023 name: name.clone().into(),
1024 command: custom_settings
1025 .get(&name.0)
1026 .map(|settings| settings.command.clone())
1027 .unwrap_or(placeholder_command()),
1028 },
1029 cx,
1030 )
1031 .into_any_element()
1032 })
1033 .collect::<Vec<_>>();
1034
1035 v_flex()
1036 .border_b_1()
1037 .border_color(cx.theme().colors().border)
1038 .child(
1039 v_flex()
1040 .p(DynamicSpacing::Base16.rems(cx))
1041 .pr(DynamicSpacing::Base20.rems(cx))
1042 .gap_2()
1043 .child(
1044 v_flex()
1045 .gap_0p5()
1046 .child(
1047 h_flex()
1048 .pr_1()
1049 .w_full()
1050 .gap_2()
1051 .justify_between()
1052 .child(Headline::new("External Agents"))
1053 .child(
1054 Button::new("add-agent", "Add Agent")
1055 .icon_position(IconPosition::Start)
1056 .icon(IconName::Plus)
1057 .icon_size(IconSize::Small)
1058 .icon_color(Color::Muted)
1059 .label_size(LabelSize::Small)
1060 .on_click(
1061 move |_, window, cx| {
1062 if let Some(workspace) = window.root().flatten() {
1063 let workspace = workspace.downgrade();
1064 window
1065 .spawn(cx, async |cx| {
1066 open_new_agent_servers_entry_in_settings_editor(
1067 workspace,
1068 cx,
1069 ).await
1070 })
1071 .detach_and_log_err(cx);
1072 }
1073 }
1074 ),
1075 )
1076 )
1077 .child(
1078 Label::new(
1079 "All agents connected through the Agent Client Protocol.",
1080 )
1081 .color(Color::Muted),
1082 ),
1083 )
1084 .child(self.render_agent_server(
1085 IconName::AiGemini,
1086 "Gemini CLI",
1087 ExternalAgent::Gemini,
1088 cx,
1089 ))
1090 .child(self.render_agent_server(
1091 IconName::AiClaude,
1092 "Claude Code",
1093 ExternalAgent::ClaudeCode,
1094 cx,
1095 ))
1096 .children(user_defined_agents),
1097 )
1098 }
1099
1100 fn render_agent_server(
1101 &self,
1102 icon: IconName,
1103 name: impl Into<SharedString>,
1104 agent: ExternalAgent,
1105 cx: &mut Context<Self>,
1106 ) -> impl IntoElement {
1107 let name = name.into();
1108 h_flex()
1109 .p_1()
1110 .pl_2()
1111 .gap_1p5()
1112 .justify_between()
1113 .border_1()
1114 .rounded_md()
1115 .border_color(self.card_item_border_color(cx))
1116 .bg(self.card_item_bg_color(cx))
1117 .overflow_hidden()
1118 .child(
1119 h_flex()
1120 .gap_1p5()
1121 .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))
1122 .child(Label::new(name.clone())),
1123 )
1124 .child(
1125 Button::new(
1126 SharedString::from(format!("start_acp_thread-{name}")),
1127 "Start New Thread",
1128 )
1129 .label_size(LabelSize::Small)
1130 .icon(IconName::Thread)
1131 .icon_position(IconPosition::Start)
1132 .icon_size(IconSize::XSmall)
1133 .icon_color(Color::Muted)
1134 .on_click(move |_, window, cx| {
1135 window.dispatch_action(
1136 NewExternalAgentThread {
1137 agent: Some(agent.clone()),
1138 }
1139 .boxed_clone(),
1140 cx,
1141 );
1142 }),
1143 )
1144 }
1145}
1146
1147impl Render for AgentConfiguration {
1148 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1149 v_flex()
1150 .id("assistant-configuration")
1151 .key_context("AgentConfiguration")
1152 .track_focus(&self.focus_handle(cx))
1153 .relative()
1154 .size_full()
1155 .pb_8()
1156 .bg(cx.theme().colors().panel_background)
1157 .child(
1158 div()
1159 .size_full()
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 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx),
1172 )
1173 }
1174}
1175
1176fn extension_only_provides_context_server(manifest: &ExtensionManifest) -> bool {
1177 manifest.context_servers.len() == 1
1178 && manifest.themes.is_empty()
1179 && manifest.icon_themes.is_empty()
1180 && manifest.languages.is_empty()
1181 && manifest.grammars.is_empty()
1182 && manifest.language_servers.is_empty()
1183 && manifest.slash_commands.is_empty()
1184 && manifest.snippets.is_none()
1185 && manifest.debug_locators.is_empty()
1186}
1187
1188pub(crate) fn resolve_extension_for_context_server(
1189 id: &ContextServerId,
1190 cx: &App,
1191) -> Option<(Arc<str>, Arc<ExtensionManifest>)> {
1192 ExtensionStore::global(cx)
1193 .read(cx)
1194 .installed_extensions()
1195 .iter()
1196 .find(|(_, entry)| entry.manifest.context_servers.contains_key(&id.0))
1197 .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
1198}
1199
1200// This notification appears when trying to delete
1201// an MCP server extension that not only provides
1202// the server, but other things, too, like language servers and more.
1203fn show_unable_to_uninstall_extension_with_context_server(
1204 workspace: &mut Workspace,
1205 id: ContextServerId,
1206 cx: &mut App,
1207) {
1208 let workspace_handle = workspace.weak_handle();
1209 let context_server_id = id.clone();
1210
1211 let status_toast = StatusToast::new(
1212 format!(
1213 "The {} extension provides more than just the MCP server. Proceed to uninstall anyway?",
1214 id.0
1215 ),
1216 cx,
1217 move |this, _cx| {
1218 let workspace_handle = workspace_handle.clone();
1219
1220 this.icon(ToastIcon::new(IconName::Warning).color(Color::Warning))
1221 .dismiss_button(true)
1222 .action("Uninstall", move |_, _cx| {
1223 if let Some((extension_id, _)) =
1224 resolve_extension_for_context_server(&context_server_id, _cx)
1225 {
1226 ExtensionStore::global(_cx).update(_cx, |store, cx| {
1227 store
1228 .uninstall_extension(extension_id, cx)
1229 .detach_and_log_err(cx);
1230 });
1231
1232 workspace_handle
1233 .update(_cx, |workspace, cx| {
1234 let fs = workspace.app_state().fs.clone();
1235 cx.spawn({
1236 let context_server_id = context_server_id.clone();
1237 async move |_workspace_handle, cx| {
1238 cx.update(|cx| {
1239 update_settings_file::<ProjectSettings>(
1240 fs,
1241 cx,
1242 move |settings, _| {
1243 settings
1244 .context_servers
1245 .remove(&context_server_id.0);
1246 },
1247 );
1248 })?;
1249 anyhow::Ok(())
1250 }
1251 })
1252 .detach_and_log_err(cx);
1253 })
1254 .log_err();
1255 }
1256 })
1257 },
1258 );
1259
1260 workspace.toggle_status_toast(status_toast, cx);
1261}
1262
1263async fn open_new_agent_servers_entry_in_settings_editor(
1264 workspace: WeakEntity<Workspace>,
1265 cx: &mut AsyncWindowContext,
1266) -> Result<()> {
1267 let settings_editor = workspace
1268 .update_in(cx, |_, window, cx| {
1269 create_and_open_local_file(paths::settings_file(), window, cx, || {
1270 settings::initial_user_settings_content().as_ref().into()
1271 })
1272 })?
1273 .await?
1274 .downcast::<Editor>()
1275 .unwrap();
1276
1277 settings_editor
1278 .downgrade()
1279 .update_in(cx, |item, window, cx| {
1280 let text = item.buffer().read(cx).snapshot(cx).text();
1281
1282 let settings = cx.global::<SettingsStore>();
1283
1284 let mut unique_server_name = None;
1285 let edits = settings.edits_for_update(&text, |settings| {
1286 let server_name: Option<SharedString> = (0..u8::MAX)
1287 .map(|i| {
1288 if i == 0 {
1289 "your_agent".into()
1290 } else {
1291 format!("your_agent_{}", i).into()
1292 }
1293 })
1294 .find(|name| {
1295 !settings
1296 .agent_servers
1297 .is_some_and(|agent_servers| agent_servers.custom.contains_key(name))
1298 });
1299 if let Some(server_name) = server_name {
1300 unique_server_name = Some(server_name.clone());
1301 settings
1302 .agent_servers
1303 .get_or_insert_default()
1304 .custom
1305 .insert(
1306 server_name,
1307 settings::CustomAgentServerSettings {
1308 path: "path_to_executable".into(),
1309 args: vec![],
1310 env: Some(HashMap::default()),
1311 default_mode: None,
1312 },
1313 );
1314 }
1315 });
1316
1317 if edits.is_empty() {
1318 return;
1319 }
1320
1321 let ranges = edits
1322 .iter()
1323 .map(|(range, _)| range.clone())
1324 .collect::<Vec<_>>();
1325
1326 item.edit(edits, cx);
1327 if let Some((unique_server_name, buffer)) =
1328 unique_server_name.zip(item.buffer().read(cx).as_singleton())
1329 {
1330 let snapshot = buffer.read(cx).snapshot();
1331 if let Some(range) =
1332 find_text_in_buffer(&unique_server_name, ranges[0].start, &snapshot)
1333 {
1334 item.change_selections(
1335 SelectionEffects::scroll(Autoscroll::newest()),
1336 window,
1337 cx,
1338 |selections| {
1339 selections.select_ranges(vec![range]);
1340 },
1341 );
1342 }
1343 }
1344 })
1345}
1346
1347fn find_text_in_buffer(
1348 text: &str,
1349 start: usize,
1350 snapshot: &language::BufferSnapshot,
1351) -> Option<Range<usize>> {
1352 let chars = text.chars().collect::<Vec<char>>();
1353
1354 let mut offset = start;
1355 let mut char_offset = 0;
1356 for c in snapshot.chars_at(start) {
1357 if char_offset >= chars.len() {
1358 break;
1359 }
1360 offset += 1;
1361
1362 if c == chars[char_offset] {
1363 char_offset += 1;
1364 } else {
1365 char_offset = 0;
1366 }
1367 }
1368
1369 if char_offset == chars.len() {
1370 Some(offset.saturating_sub(chars.len())..offset)
1371 } else {
1372 None
1373 }
1374}