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