1mod add_context_server_modal;
2mod configure_context_server_modal;
3mod manage_profiles_modal;
4mod tool_picker;
5
6use std::{sync::Arc, time::Duration};
7
8use agent_settings::AgentSettings;
9use assistant_tool::{ToolSource, ToolWorkingSet};
10use collections::HashMap;
11use context_server::ContextServerId;
12use fs::Fs;
13use gpui::{
14 Action, Animation, AnimationExt as _, AnyView, App, Entity, EventEmitter, FocusHandle,
15 Focusable, ScrollHandle, Subscription, pulsating_between,
16};
17use language_model::{LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry};
18use project::context_server_store::{ContextServerStatus, ContextServerStore};
19use settings::{Settings, update_settings_file};
20use ui::{
21 Disclosure, ElevationIndex, Indicator, Scrollbar, ScrollbarState, Switch, SwitchColor, Tooltip,
22 prelude::*,
23};
24use util::ResultExt as _;
25use zed_actions::ExtensionCategoryFilter;
26
27pub(crate) use add_context_server_modal::AddContextServerModal;
28pub(crate) use configure_context_server_modal::ConfigureContextServerModal;
29pub(crate) use manage_profiles_modal::ManageProfilesModal;
30
31use crate::AddContextServer;
32
33pub struct AgentConfiguration {
34 fs: Arc<dyn Fs>,
35 focus_handle: FocusHandle,
36 configuration_views_by_provider: HashMap<LanguageModelProviderId, AnyView>,
37 context_server_store: Entity<ContextServerStore>,
38 expanded_context_server_tools: HashMap<ContextServerId, bool>,
39 expanded_provider_configurations: HashMap<LanguageModelProviderId, bool>,
40 tools: Entity<ToolWorkingSet>,
41 _registry_subscription: Subscription,
42 scroll_handle: ScrollHandle,
43 scrollbar_state: ScrollbarState,
44}
45
46impl AgentConfiguration {
47 pub fn new(
48 fs: Arc<dyn Fs>,
49 context_server_store: Entity<ContextServerStore>,
50 tools: Entity<ToolWorkingSet>,
51 window: &mut Window,
52 cx: &mut Context<Self>,
53 ) -> Self {
54 let focus_handle = cx.focus_handle();
55
56 let registry_subscription = cx.subscribe_in(
57 &LanguageModelRegistry::global(cx),
58 window,
59 |this, _, event: &language_model::Event, window, cx| match event {
60 language_model::Event::AddedProvider(provider_id) => {
61 let provider = LanguageModelRegistry::read_global(cx).provider(provider_id);
62 if let Some(provider) = provider {
63 this.add_provider_configuration_view(&provider, window, cx);
64 }
65 }
66 language_model::Event::RemovedProvider(provider_id) => {
67 this.remove_provider_configuration_view(provider_id);
68 }
69 _ => {}
70 },
71 );
72
73 let scroll_handle = ScrollHandle::new();
74 let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
75
76 let mut this = Self {
77 fs,
78 focus_handle,
79 configuration_views_by_provider: HashMap::default(),
80 context_server_store,
81 expanded_context_server_tools: HashMap::default(),
82 expanded_provider_configurations: HashMap::default(),
83 tools,
84 _registry_subscription: registry_subscription,
85 scroll_handle,
86 scrollbar_state,
87 };
88 this.build_provider_configuration_views(window, cx);
89 this
90 }
91
92 fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
93 let providers = LanguageModelRegistry::read_global(cx).providers();
94 for provider in providers {
95 self.add_provider_configuration_view(&provider, window, cx);
96 }
97 }
98
99 fn remove_provider_configuration_view(&mut self, provider_id: &LanguageModelProviderId) {
100 self.configuration_views_by_provider.remove(provider_id);
101 self.expanded_provider_configurations.remove(provider_id);
102 }
103
104 fn add_provider_configuration_view(
105 &mut self,
106 provider: &Arc<dyn LanguageModelProvider>,
107 window: &mut Window,
108 cx: &mut Context<Self>,
109 ) {
110 let configuration_view = provider.configuration_view(window, cx);
111 self.configuration_views_by_provider
112 .insert(provider.id(), configuration_view);
113 }
114}
115
116impl Focusable for AgentConfiguration {
117 fn focus_handle(&self, _: &App) -> FocusHandle {
118 self.focus_handle.clone()
119 }
120}
121
122pub enum AssistantConfigurationEvent {
123 NewThread(Arc<dyn LanguageModelProvider>),
124}
125
126impl EventEmitter<AssistantConfigurationEvent> for AgentConfiguration {}
127
128impl AgentConfiguration {
129 fn render_provider_configuration_block(
130 &mut self,
131 provider: &Arc<dyn LanguageModelProvider>,
132 cx: &mut Context<Self>,
133 ) -> impl IntoElement + use<> {
134 let provider_id = provider.id().0.clone();
135 let provider_name = provider.name().0.clone();
136 let configuration_view = self
137 .configuration_views_by_provider
138 .get(&provider.id())
139 .cloned();
140
141 let is_expanded = self
142 .expanded_provider_configurations
143 .get(&provider.id())
144 .copied()
145 .unwrap_or(false);
146
147 v_flex()
148 .pt_3()
149 .gap_1p5()
150 .border_t_1()
151 .border_color(cx.theme().colors().border.opacity(0.6))
152 .child(
153 h_flex()
154 .justify_between()
155 .child(
156 h_flex()
157 .gap_2()
158 .child(
159 Icon::new(provider.icon())
160 .size(IconSize::Small)
161 .color(Color::Muted),
162 )
163 .child(Label::new(provider_name.clone()).size(LabelSize::Large))
164 .when(provider.is_authenticated(cx) && !is_expanded, |parent| {
165 parent.child(Icon::new(IconName::Check).color(Color::Success))
166 }),
167 )
168 .child(
169 h_flex()
170 .gap_1()
171 .when(provider.is_authenticated(cx), |parent| {
172 parent.child(
173 Button::new(
174 SharedString::from(format!("new-thread-{provider_id}")),
175 "Start New Thread",
176 )
177 .icon_position(IconPosition::Start)
178 .icon(IconName::Plus)
179 .icon_size(IconSize::Small)
180 .layer(ElevationIndex::ModalSurface)
181 .label_size(LabelSize::Small)
182 .on_click(cx.listener({
183 let provider = provider.clone();
184 move |_this, _event, _window, cx| {
185 cx.emit(AssistantConfigurationEvent::NewThread(
186 provider.clone(),
187 ))
188 }
189 })),
190 )
191 })
192 .child(
193 Disclosure::new(
194 SharedString::from(format!(
195 "provider-disclosure-{provider_id}"
196 )),
197 is_expanded,
198 )
199 .opened_icon(IconName::ChevronUp)
200 .closed_icon(IconName::ChevronDown)
201 .on_click(cx.listener({
202 let provider_id = provider.id().clone();
203 move |this, _event, _window, _cx| {
204 let is_expanded = this
205 .expanded_provider_configurations
206 .entry(provider_id.clone())
207 .or_insert(false);
208
209 *is_expanded = !*is_expanded;
210 }
211 })),
212 ),
213 ),
214 )
215 .when(is_expanded, |parent| match configuration_view {
216 Some(configuration_view) => parent.child(configuration_view),
217 None => parent.child(Label::new(format!(
218 "No configuration view for {provider_name}",
219 ))),
220 })
221 }
222
223 fn render_provider_configuration_section(
224 &mut self,
225 cx: &mut Context<Self>,
226 ) -> impl IntoElement {
227 let providers = LanguageModelRegistry::read_global(cx).providers();
228
229 v_flex()
230 .p(DynamicSpacing::Base16.rems(cx))
231 .pr(DynamicSpacing::Base20.rems(cx))
232 .gap_4()
233 .border_b_1()
234 .border_color(cx.theme().colors().border)
235 .child(
236 v_flex()
237 .gap_0p5()
238 .child(Headline::new("LLM Providers"))
239 .child(
240 Label::new("Add at least one provider to use AI-powered features.")
241 .color(Color::Muted),
242 ),
243 )
244 .children(
245 providers
246 .into_iter()
247 .map(|provider| self.render_provider_configuration_block(&provider, cx)),
248 )
249 }
250
251 fn render_command_permission(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
252 let always_allow_tool_actions = AgentSettings::get_global(cx).always_allow_tool_actions;
253
254 h_flex()
255 .gap_4()
256 .justify_between()
257 .flex_wrap()
258 .child(
259 v_flex()
260 .gap_0p5()
261 .max_w_5_6()
262 .child(Label::new("Allow running editing tools without asking for confirmation"))
263 .child(
264 Label::new(
265 "The agent can perform potentially destructive actions without asking for your confirmation.",
266 )
267 .color(Color::Muted),
268 ),
269 )
270 .child(
271 Switch::new(
272 "always-allow-tool-actions-switch",
273 always_allow_tool_actions.into(),
274 )
275 .color(SwitchColor::Accent)
276 .on_click({
277 let fs = self.fs.clone();
278 move |state, _window, cx| {
279 let allow = state == &ToggleState::Selected;
280 update_settings_file::<AgentSettings>(
281 fs.clone(),
282 cx,
283 move |settings, _| {
284 settings.set_always_allow_tool_actions(allow);
285 },
286 );
287 }
288 }),
289 )
290 }
291
292 fn render_single_file_review(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
293 let single_file_review = AgentSettings::get_global(cx).single_file_review;
294
295 h_flex()
296 .gap_4()
297 .justify_between()
298 .flex_wrap()
299 .child(
300 v_flex()
301 .gap_0p5()
302 .max_w_5_6()
303 .child(Label::new("Enable single-file agent reviews"))
304 .child(
305 Label::new(
306 "Agent edits are also displayed in single-file editors for review.",
307 )
308 .color(Color::Muted),
309 ),
310 )
311 .child(
312 Switch::new("single-file-review-switch", single_file_review.into())
313 .color(SwitchColor::Accent)
314 .on_click({
315 let fs = self.fs.clone();
316 move |state, _window, cx| {
317 let allow = state == &ToggleState::Selected;
318 update_settings_file::<AgentSettings>(
319 fs.clone(),
320 cx,
321 move |settings, _| {
322 settings.set_single_file_review(allow);
323 },
324 );
325 }
326 }),
327 )
328 }
329
330 fn render_sound_notification(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
331 let play_sound_when_agent_done = AgentSettings::get_global(cx).play_sound_when_agent_done;
332
333 h_flex()
334 .gap_4()
335 .justify_between()
336 .flex_wrap()
337 .child(
338 v_flex()
339 .gap_0p5()
340 .max_w_5_6()
341 .child(Label::new("Play sound when finished generating"))
342 .child(
343 Label::new(
344 "Hear a notification sound when the agent is done generating changes or needs your input.",
345 )
346 .color(Color::Muted),
347 ),
348 )
349 .child(
350 Switch::new("play-sound-notification-switch", play_sound_when_agent_done.into())
351 .color(SwitchColor::Accent)
352 .on_click({
353 let fs = self.fs.clone();
354 move |state, _window, cx| {
355 let allow = state == &ToggleState::Selected;
356 update_settings_file::<AgentSettings>(
357 fs.clone(),
358 cx,
359 move |settings, _| {
360 settings.set_play_sound_when_agent_done(allow);
361 },
362 );
363 }
364 }),
365 )
366 }
367
368 fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
369 v_flex()
370 .p(DynamicSpacing::Base16.rems(cx))
371 .pr(DynamicSpacing::Base20.rems(cx))
372 .gap_2p5()
373 .border_b_1()
374 .border_color(cx.theme().colors().border)
375 .child(Headline::new("General Settings"))
376 .child(self.render_command_permission(cx))
377 .child(self.render_single_file_review(cx))
378 .child(self.render_sound_notification(cx))
379 }
380
381 fn render_context_servers_section(
382 &mut self,
383 window: &mut Window,
384 cx: &mut Context<Self>,
385 ) -> impl IntoElement {
386 let context_server_ids = self.context_server_store.read(cx).all_server_ids().clone();
387
388 v_flex()
389 .p(DynamicSpacing::Base16.rems(cx))
390 .pr(DynamicSpacing::Base20.rems(cx))
391 .gap_2()
392 .border_b_1()
393 .border_color(cx.theme().colors().border)
394 .child(
395 v_flex()
396 .gap_0p5()
397 .child(Headline::new("Model Context Protocol (MCP) Servers"))
398 .child(Label::new("Connect to context servers via the Model Context Protocol either via Zed extensions or directly.").color(Color::Muted)),
399 )
400 .children(
401 context_server_ids.into_iter().map(|context_server_id| {
402 self.render_context_server(context_server_id, window, cx)
403 }),
404 )
405 .child(
406 h_flex()
407 .justify_between()
408 .gap_2()
409 .child(
410 h_flex().w_full().child(
411 Button::new("add-context-server", "Add Custom Server")
412 .style(ButtonStyle::Filled)
413 .layer(ElevationIndex::ModalSurface)
414 .full_width()
415 .icon(IconName::Plus)
416 .icon_size(IconSize::Small)
417 .icon_position(IconPosition::Start)
418 .on_click(|_event, window, cx| {
419 window.dispatch_action(AddContextServer.boxed_clone(), cx)
420 }),
421 ),
422 )
423 .child(
424 h_flex().w_full().child(
425 Button::new(
426 "install-context-server-extensions",
427 "Install MCP Extensions",
428 )
429 .style(ButtonStyle::Filled)
430 .layer(ElevationIndex::ModalSurface)
431 .full_width()
432 .icon(IconName::Hammer)
433 .icon_size(IconSize::Small)
434 .icon_position(IconPosition::Start)
435 .on_click(|_event, window, cx| {
436 window.dispatch_action(
437 zed_actions::Extensions {
438 category_filter: Some(
439 ExtensionCategoryFilter::ContextServers,
440 ),
441 }
442 .boxed_clone(),
443 cx,
444 )
445 }),
446 ),
447 ),
448 )
449 }
450
451 fn render_context_server(
452 &self,
453 context_server_id: ContextServerId,
454 window: &mut Window,
455 cx: &mut Context<Self>,
456 ) -> impl use<> + IntoElement {
457 let tools_by_source = self.tools.read(cx).tools_by_source(cx);
458 let server_status = self
459 .context_server_store
460 .read(cx)
461 .status_for_server(&context_server_id)
462 .unwrap_or(ContextServerStatus::Stopped);
463
464 let is_running = matches!(server_status, ContextServerStatus::Running);
465 let item_id = SharedString::from(context_server_id.0.clone());
466
467 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
468 Some(error)
469 } else {
470 None
471 };
472
473 let are_tools_expanded = self
474 .expanded_context_server_tools
475 .get(&context_server_id)
476 .copied()
477 .unwrap_or_default();
478
479 let tools = tools_by_source
480 .get(&ToolSource::ContextServer {
481 id: context_server_id.0.clone().into(),
482 })
483 .map_or([].as_slice(), |tools| tools.as_slice());
484 let tool_count = tools.len();
485
486 let border_color = cx.theme().colors().border.opacity(0.6);
487 let success_color = Color::Success.color(cx);
488
489 let (status_indicator, tooltip_text) = match server_status {
490 ContextServerStatus::Starting => (
491 Indicator::dot()
492 .color(Color::Success)
493 .with_animation(
494 SharedString::from(format!("{}-starting", context_server_id.0.clone(),)),
495 Animation::new(Duration::from_secs(2))
496 .repeat()
497 .with_easing(pulsating_between(0.4, 1.)),
498 move |this, delta| this.color(success_color.alpha(delta).into()),
499 )
500 .into_any_element(),
501 "Server is starting.",
502 ),
503 ContextServerStatus::Running => (
504 Indicator::dot().color(Color::Success).into_any_element(),
505 "Server is running.",
506 ),
507 ContextServerStatus::Error(_) => (
508 Indicator::dot().color(Color::Error).into_any_element(),
509 "Server has an error.",
510 ),
511 ContextServerStatus::Stopped => (
512 Indicator::dot().color(Color::Muted).into_any_element(),
513 "Server is stopped.",
514 ),
515 };
516
517 v_flex()
518 .id(item_id.clone())
519 .border_1()
520 .rounded_md()
521 .border_color(border_color)
522 .bg(cx.theme().colors().background.opacity(0.2))
523 .overflow_hidden()
524 .child(
525 h_flex()
526 .p_1()
527 .justify_between()
528 .when(
529 error.is_some() || are_tools_expanded && tool_count > 1,
530 |element| element.border_b_1().border_color(border_color),
531 )
532 .child(
533 h_flex()
534 .gap_1p5()
535 .child(
536 Disclosure::new(
537 "tool-list-disclosure",
538 are_tools_expanded || error.is_some(),
539 )
540 .disabled(tool_count == 0)
541 .on_click(cx.listener({
542 let context_server_id = context_server_id.clone();
543 move |this, _event, _window, _cx| {
544 let is_open = this
545 .expanded_context_server_tools
546 .entry(context_server_id.clone())
547 .or_insert(false);
548
549 *is_open = !*is_open;
550 }
551 })),
552 )
553 .child(
554 div()
555 .id(item_id.clone())
556 .tooltip(Tooltip::text(tooltip_text))
557 .child(status_indicator),
558 )
559 .child(Label::new(context_server_id.0.clone()).ml_0p5())
560 .when(is_running, |this| {
561 this.child(
562 Label::new(if tool_count == 1 {
563 SharedString::from("1 tool")
564 } else {
565 SharedString::from(format!("{} tools", tool_count))
566 })
567 .color(Color::Muted)
568 .size(LabelSize::Small),
569 )
570 }),
571 )
572 .child(
573 Switch::new("context-server-switch", is_running.into())
574 .color(SwitchColor::Accent)
575 .on_click({
576 let context_server_manager = self.context_server_store.clone();
577 let context_server_id = context_server_id.clone();
578 move |state, _window, cx| match state {
579 ToggleState::Unselected | ToggleState::Indeterminate => {
580 context_server_manager.update(cx, |this, cx| {
581 this.stop_server(&context_server_id, cx).log_err();
582 });
583 }
584 ToggleState::Selected => {
585 context_server_manager.update(cx, |this, cx| {
586 if let Some(server) =
587 this.get_server(&context_server_id)
588 {
589 this.start_server(server, cx).log_err();
590 }
591 })
592 }
593 }
594 }),
595 ),
596 )
597 .map(|parent| {
598 if let Some(error) = error {
599 return parent.child(
600 h_flex()
601 .p_2()
602 .gap_2()
603 .items_start()
604 .child(
605 h_flex()
606 .flex_none()
607 .h(window.line_height() / 1.6_f32)
608 .justify_center()
609 .child(
610 Icon::new(IconName::XCircle)
611 .size(IconSize::XSmall)
612 .color(Color::Error),
613 ),
614 )
615 .child(
616 div().w_full().child(
617 Label::new(error)
618 .buffer_font(cx)
619 .color(Color::Muted)
620 .size(LabelSize::Small),
621 ),
622 ),
623 );
624 }
625
626 if !are_tools_expanded || tools.is_empty() {
627 return parent;
628 }
629
630 parent.child(v_flex().py_1p5().px_1().gap_1().children(
631 tools.into_iter().enumerate().map(|(ix, tool)| {
632 h_flex()
633 .id(("tool-item", ix))
634 .px_1()
635 .gap_2()
636 .justify_between()
637 .hover(|style| style.bg(cx.theme().colors().element_hover))
638 .rounded_sm()
639 .child(
640 Label::new(tool.name())
641 .buffer_font(cx)
642 .size(LabelSize::Small),
643 )
644 .child(
645 Icon::new(IconName::Info)
646 .size(IconSize::Small)
647 .color(Color::Ignored),
648 )
649 .tooltip(Tooltip::text(tool.description()))
650 }),
651 ))
652 })
653 }
654}
655
656impl Render for AgentConfiguration {
657 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
658 v_flex()
659 .id("assistant-configuration")
660 .key_context("AgentConfiguration")
661 .track_focus(&self.focus_handle(cx))
662 .relative()
663 .size_full()
664 .pb_8()
665 .bg(cx.theme().colors().panel_background)
666 .child(
667 v_flex()
668 .id("assistant-configuration-content")
669 .track_scroll(&self.scroll_handle)
670 .size_full()
671 .overflow_y_scroll()
672 .child(self.render_general_settings_section(cx))
673 .child(self.render_context_servers_section(window, cx))
674 .child(self.render_provider_configuration_section(cx)),
675 )
676 .child(
677 div()
678 .id("assistant-configuration-scrollbar")
679 .occlude()
680 .absolute()
681 .right(px(3.))
682 .top_0()
683 .bottom_0()
684 .pb_6()
685 .w(px(12.))
686 .cursor_default()
687 .on_mouse_move(cx.listener(|_, _, _window, cx| {
688 cx.notify();
689 cx.stop_propagation()
690 }))
691 .on_hover(|_, _window, cx| {
692 cx.stop_propagation();
693 })
694 .on_any_mouse_down(|_, _window, cx| {
695 cx.stop_propagation();
696 })
697 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
698 cx.notify();
699 }))
700 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
701 )
702 }
703}