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 assistant_settings::AssistantSettings;
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, Divider, DividerColor, ElevationIndex, Indicator, Scrollbar, ScrollbarState,
22 Switch, SwitchColor, Tooltip, 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(true);
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_open = this
205 .expanded_provider_configurations
206 .entry(provider_id.clone())
207 .or_insert(true);
208
209 *is_open = !*is_open;
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(div().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 .flex_1()
234 .child(
235 v_flex()
236 .gap_0p5()
237 .child(Headline::new("LLM Providers"))
238 .child(
239 Label::new("Add at least one provider to use AI-powered features.")
240 .color(Color::Muted),
241 ),
242 )
243 .children(
244 providers
245 .into_iter()
246 .map(|provider| self.render_provider_configuration_block(&provider, cx)),
247 )
248 }
249
250 fn render_command_permission(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
251 let always_allow_tool_actions = AssistantSettings::get_global(cx).always_allow_tool_actions;
252
253 h_flex()
254 .gap_4()
255 .justify_between()
256 .flex_wrap()
257 .child(
258 v_flex()
259 .gap_0p5()
260 .max_w_5_6()
261 .child(Label::new("Allow running editing tools without asking for confirmation"))
262 .child(
263 Label::new(
264 "The agent can perform potentially destructive actions without asking for your confirmation.",
265 )
266 .color(Color::Muted),
267 ),
268 )
269 .child(
270 Switch::new(
271 "always-allow-tool-actions-switch",
272 always_allow_tool_actions.into(),
273 )
274 .color(SwitchColor::Accent)
275 .on_click({
276 let fs = self.fs.clone();
277 move |state, _window, cx| {
278 let allow = state == &ToggleState::Selected;
279 update_settings_file::<AssistantSettings>(
280 fs.clone(),
281 cx,
282 move |settings, _| {
283 settings.set_always_allow_tool_actions(allow);
284 },
285 );
286 }
287 }),
288 )
289 }
290
291 fn render_single_file_review(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
292 let single_file_review = AssistantSettings::get_global(cx).single_file_review;
293
294 h_flex()
295 .gap_4()
296 .justify_between()
297 .flex_wrap()
298 .child(
299 v_flex()
300 .gap_0p5()
301 .max_w_5_6()
302 .child(Label::new("Enable single-file agent reviews"))
303 .child(
304 Label::new(
305 "Agent edits are also displayed in single-file editors for review.",
306 )
307 .color(Color::Muted),
308 ),
309 )
310 .child(
311 Switch::new("single-file-review-switch", single_file_review.into())
312 .color(SwitchColor::Accent)
313 .on_click({
314 let fs = self.fs.clone();
315 move |state, _window, cx| {
316 let allow = state == &ToggleState::Selected;
317 update_settings_file::<AssistantSettings>(
318 fs.clone(),
319 cx,
320 move |settings, _| {
321 settings.set_single_file_review(allow);
322 },
323 );
324 }
325 }),
326 )
327 }
328
329 fn render_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
330 v_flex()
331 .p(DynamicSpacing::Base16.rems(cx))
332 .pr(DynamicSpacing::Base20.rems(cx))
333 .gap_2p5()
334 .flex_1()
335 .child(Headline::new("General Settings"))
336 .child(self.render_command_permission(cx))
337 .child(self.render_single_file_review(cx))
338 }
339
340 fn render_context_servers_section(
341 &mut self,
342 window: &mut Window,
343 cx: &mut Context<Self>,
344 ) -> impl IntoElement {
345 let context_server_ids = self.context_server_store.read(cx).all_server_ids().clone();
346
347 const SUBHEADING: &str = "Connect to context servers via the Model Context Protocol either via Zed extensions or directly.";
348
349 v_flex()
350 .p(DynamicSpacing::Base16.rems(cx))
351 .pr(DynamicSpacing::Base20.rems(cx))
352 .gap_2()
353 .flex_1()
354 .child(
355 v_flex()
356 .gap_0p5()
357 .child(Headline::new("Model Context Protocol (MCP) Servers"))
358 .child(Label::new(SUBHEADING).color(Color::Muted)),
359 )
360 .children(
361 context_server_ids.into_iter().map(|context_server_id| {
362 self.render_context_server(context_server_id, window, cx)
363 }),
364 )
365 .child(
366 h_flex()
367 .justify_between()
368 .gap_2()
369 .child(
370 h_flex().w_full().child(
371 Button::new("add-context-server", "Add Custom Server")
372 .style(ButtonStyle::Filled)
373 .layer(ElevationIndex::ModalSurface)
374 .full_width()
375 .icon(IconName::Plus)
376 .icon_size(IconSize::Small)
377 .icon_position(IconPosition::Start)
378 .on_click(|_event, window, cx| {
379 window.dispatch_action(AddContextServer.boxed_clone(), cx)
380 }),
381 ),
382 )
383 .child(
384 h_flex().w_full().child(
385 Button::new(
386 "install-context-server-extensions",
387 "Install MCP Extensions",
388 )
389 .style(ButtonStyle::Filled)
390 .layer(ElevationIndex::ModalSurface)
391 .full_width()
392 .icon(IconName::Hammer)
393 .icon_size(IconSize::Small)
394 .icon_position(IconPosition::Start)
395 .on_click(|_event, window, cx| {
396 window.dispatch_action(
397 zed_actions::Extensions {
398 category_filter: Some(
399 ExtensionCategoryFilter::ContextServers,
400 ),
401 }
402 .boxed_clone(),
403 cx,
404 )
405 }),
406 ),
407 ),
408 )
409 }
410
411 fn render_context_server(
412 &self,
413 context_server_id: ContextServerId,
414 window: &mut Window,
415 cx: &mut Context<Self>,
416 ) -> impl use<> + IntoElement {
417 let tools_by_source = self.tools.read(cx).tools_by_source(cx);
418 let server_status = self
419 .context_server_store
420 .read(cx)
421 .status_for_server(&context_server_id)
422 .unwrap_or(ContextServerStatus::Stopped);
423
424 let is_running = matches!(server_status, ContextServerStatus::Running);
425 let item_id = SharedString::from(context_server_id.0.clone());
426
427 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
428 Some(error)
429 } else {
430 None
431 };
432
433 let are_tools_expanded = self
434 .expanded_context_server_tools
435 .get(&context_server_id)
436 .copied()
437 .unwrap_or_default();
438
439 let tools = tools_by_source
440 .get(&ToolSource::ContextServer {
441 id: context_server_id.0.clone().into(),
442 })
443 .map_or([].as_slice(), |tools| tools.as_slice());
444 let tool_count = tools.len();
445
446 let border_color = cx.theme().colors().border.opacity(0.6);
447 let success_color = Color::Success.color(cx);
448
449 let (status_indicator, tooltip_text) = match server_status {
450 ContextServerStatus::Starting => (
451 Indicator::dot()
452 .color(Color::Success)
453 .with_animation(
454 SharedString::from(format!("{}-starting", context_server_id.0.clone(),)),
455 Animation::new(Duration::from_secs(2))
456 .repeat()
457 .with_easing(pulsating_between(0.4, 1.)),
458 move |this, delta| this.color(success_color.alpha(delta).into()),
459 )
460 .into_any_element(),
461 "Server is starting.",
462 ),
463 ContextServerStatus::Running => (
464 Indicator::dot().color(Color::Success).into_any_element(),
465 "Server is running.",
466 ),
467 ContextServerStatus::Error(_) => (
468 Indicator::dot().color(Color::Error).into_any_element(),
469 "Server has an error.",
470 ),
471 ContextServerStatus::Stopped => (
472 Indicator::dot().color(Color::Muted).into_any_element(),
473 "Server is stopped.",
474 ),
475 };
476
477 v_flex()
478 .id(item_id.clone())
479 .border_1()
480 .rounded_md()
481 .border_color(border_color)
482 .bg(cx.theme().colors().background.opacity(0.2))
483 .overflow_hidden()
484 .child(
485 h_flex()
486 .p_1()
487 .justify_between()
488 .when(
489 error.is_some() || are_tools_expanded && tool_count > 1,
490 |element| element.border_b_1().border_color(border_color),
491 )
492 .child(
493 h_flex()
494 .gap_1p5()
495 .child(
496 Disclosure::new(
497 "tool-list-disclosure",
498 are_tools_expanded || error.is_some(),
499 )
500 .disabled(tool_count == 0)
501 .on_click(cx.listener({
502 let context_server_id = context_server_id.clone();
503 move |this, _event, _window, _cx| {
504 let is_open = this
505 .expanded_context_server_tools
506 .entry(context_server_id.clone())
507 .or_insert(false);
508
509 *is_open = !*is_open;
510 }
511 })),
512 )
513 .child(
514 div()
515 .id(item_id.clone())
516 .tooltip(Tooltip::text(tooltip_text))
517 .child(status_indicator),
518 )
519 .child(Label::new(context_server_id.0.clone()).ml_0p5())
520 .when(is_running, |this| {
521 this.child(
522 Label::new(if tool_count == 1 {
523 SharedString::from("1 tool")
524 } else {
525 SharedString::from(format!("{} tools", tool_count))
526 })
527 .color(Color::Muted)
528 .size(LabelSize::Small),
529 )
530 }),
531 )
532 .child(
533 Switch::new("context-server-switch", is_running.into())
534 .color(SwitchColor::Accent)
535 .on_click({
536 let context_server_manager = self.context_server_store.clone();
537 let context_server_id = context_server_id.clone();
538 move |state, _window, cx| match state {
539 ToggleState::Unselected | ToggleState::Indeterminate => {
540 context_server_manager.update(cx, |this, cx| {
541 this.stop_server(&context_server_id, cx).log_err();
542 });
543 }
544 ToggleState::Selected => {
545 context_server_manager.update(cx, |this, cx| {
546 if let Some(server) =
547 this.get_server(&context_server_id)
548 {
549 this.start_server(server, cx).log_err();
550 }
551 })
552 }
553 }
554 }),
555 ),
556 )
557 .map(|parent| {
558 if let Some(error) = error {
559 return parent.child(
560 h_flex()
561 .p_2()
562 .gap_2()
563 .items_start()
564 .child(
565 h_flex()
566 .flex_none()
567 .h(window.line_height() / 1.6_f32)
568 .justify_center()
569 .child(
570 Icon::new(IconName::XCircle)
571 .size(IconSize::XSmall)
572 .color(Color::Error),
573 ),
574 )
575 .child(
576 div().w_full().child(
577 Label::new(error)
578 .buffer_font(cx)
579 .color(Color::Muted)
580 .size(LabelSize::Small),
581 ),
582 ),
583 );
584 }
585
586 if !are_tools_expanded || tools.is_empty() {
587 return parent;
588 }
589
590 parent.child(v_flex().py_1p5().px_1().gap_1().children(
591 tools.into_iter().enumerate().map(|(ix, tool)| {
592 h_flex()
593 .id(("tool-item", ix))
594 .px_1()
595 .gap_2()
596 .justify_between()
597 .hover(|style| style.bg(cx.theme().colors().element_hover))
598 .rounded_sm()
599 .child(
600 Label::new(tool.name())
601 .buffer_font(cx)
602 .size(LabelSize::Small),
603 )
604 .child(
605 Icon::new(IconName::Info)
606 .size(IconSize::Small)
607 .color(Color::Ignored),
608 )
609 .tooltip(Tooltip::text(tool.description()))
610 }),
611 ))
612 })
613 }
614}
615
616impl Render for AgentConfiguration {
617 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
618 v_flex()
619 .id("assistant-configuration")
620 .key_context("AgentConfiguration")
621 .track_focus(&self.focus_handle(cx))
622 .relative()
623 .size_full()
624 .pb_8()
625 .bg(cx.theme().colors().panel_background)
626 .child(
627 v_flex()
628 .id("assistant-configuration-content")
629 .track_scroll(&self.scroll_handle)
630 .size_full()
631 .overflow_y_scroll()
632 .child(self.render_general_settings_section(cx))
633 .child(Divider::horizontal().color(DividerColor::Border))
634 .child(self.render_context_servers_section(window, cx))
635 .child(Divider::horizontal().color(DividerColor::Border))
636 .child(self.render_provider_configuration_section(cx)),
637 )
638 .child(
639 div()
640 .id("assistant-configuration-scrollbar")
641 .occlude()
642 .absolute()
643 .right(px(3.))
644 .top_0()
645 .bottom_0()
646 .pb_6()
647 .w(px(12.))
648 .cursor_default()
649 .on_mouse_move(cx.listener(|_, _, _window, cx| {
650 cx.notify();
651 cx.stop_propagation()
652 }))
653 .on_hover(|_, _window, cx| {
654 cx.stop_propagation();
655 })
656 .on_any_mouse_down(|_, _window, cx| {
657 cx.stop_propagation();
658 })
659 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
660 cx.notify();
661 }))
662 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
663 )
664 }
665}