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
426 let error = if let ContextServerStatus::Error(error) = server_status.clone() {
427 Some(error)
428 } else {
429 None
430 };
431
432 let are_tools_expanded = self
433 .expanded_context_server_tools
434 .get(&context_server_id)
435 .copied()
436 .unwrap_or_default();
437
438 let tools = tools_by_source
439 .get(&ToolSource::ContextServer {
440 id: context_server_id.0.clone().into(),
441 })
442 .map_or([].as_slice(), |tools| tools.as_slice());
443 let tool_count = tools.len();
444
445 let border_color = cx.theme().colors().border.opacity(0.6);
446
447 v_flex()
448 .id(SharedString::from(context_server_id.0.clone()))
449 .border_1()
450 .rounded_md()
451 .border_color(border_color)
452 .bg(cx.theme().colors().background.opacity(0.2))
453 .overflow_hidden()
454 .child(
455 h_flex()
456 .p_1()
457 .justify_between()
458 .when(
459 error.is_some() || are_tools_expanded && tool_count > 1,
460 |element| element.border_b_1().border_color(border_color),
461 )
462 .child(
463 h_flex()
464 .gap_1p5()
465 .child(
466 Disclosure::new(
467 "tool-list-disclosure",
468 are_tools_expanded || error.is_some(),
469 )
470 .disabled(tool_count == 0)
471 .on_click(cx.listener({
472 let context_server_id = context_server_id.clone();
473 move |this, _event, _window, _cx| {
474 let is_open = this
475 .expanded_context_server_tools
476 .entry(context_server_id.clone())
477 .or_insert(false);
478
479 *is_open = !*is_open;
480 }
481 })),
482 )
483 .child(match server_status {
484 ContextServerStatus::Starting => {
485 let color = Color::Success.color(cx);
486 Indicator::dot()
487 .color(Color::Success)
488 .with_animation(
489 SharedString::from(format!(
490 "{}-starting",
491 context_server_id.0.clone(),
492 )),
493 Animation::new(Duration::from_secs(2))
494 .repeat()
495 .with_easing(pulsating_between(0.4, 1.)),
496 move |this, delta| {
497 this.color(color.alpha(delta).into())
498 },
499 )
500 .into_any_element()
501 }
502 ContextServerStatus::Running => {
503 Indicator::dot().color(Color::Success).into_any_element()
504 }
505 ContextServerStatus::Error(_) => {
506 Indicator::dot().color(Color::Error).into_any_element()
507 }
508 ContextServerStatus::Stopped => {
509 Indicator::dot().color(Color::Muted).into_any_element()
510 }
511 })
512 .child(Label::new(context_server_id.0.clone()).ml_0p5())
513 .when(is_running, |this| {
514 this.child(
515 Label::new(if tool_count == 1 {
516 SharedString::from("1 tool")
517 } else {
518 SharedString::from(format!("{} tools", tool_count))
519 })
520 .color(Color::Muted)
521 .size(LabelSize::Small),
522 )
523 }),
524 )
525 .child(
526 Switch::new("context-server-switch", is_running.into())
527 .color(SwitchColor::Accent)
528 .on_click({
529 let context_server_manager = self.context_server_store.clone();
530 let context_server_id = context_server_id.clone();
531 move |state, _window, cx| match state {
532 ToggleState::Unselected | ToggleState::Indeterminate => {
533 context_server_manager.update(cx, |this, cx| {
534 this.stop_server(&context_server_id, cx).log_err();
535 });
536 }
537 ToggleState::Selected => {
538 context_server_manager.update(cx, |this, cx| {
539 if let Some(server) =
540 this.get_server(&context_server_id)
541 {
542 this.start_server(server, cx).log_err();
543 }
544 })
545 }
546 }
547 }),
548 ),
549 )
550 .map(|parent| {
551 if let Some(error) = error {
552 return parent.child(
553 h_flex()
554 .p_2()
555 .gap_2()
556 .items_start()
557 .child(
558 h_flex()
559 .flex_none()
560 .h(window.line_height() / 1.6_f32)
561 .justify_center()
562 .child(
563 Icon::new(IconName::XCircle)
564 .size(IconSize::XSmall)
565 .color(Color::Error),
566 ),
567 )
568 .child(
569 div().w_full().child(
570 Label::new(error)
571 .buffer_font(cx)
572 .color(Color::Muted)
573 .size(LabelSize::Small),
574 ),
575 ),
576 );
577 }
578
579 if !are_tools_expanded || tools.is_empty() {
580 return parent;
581 }
582
583 parent.child(v_flex().py_1p5().px_1().gap_1().children(
584 tools.into_iter().enumerate().map(|(ix, tool)| {
585 h_flex()
586 .id(("tool-item", ix))
587 .px_1()
588 .gap_2()
589 .justify_between()
590 .hover(|style| style.bg(cx.theme().colors().element_hover))
591 .rounded_sm()
592 .child(
593 Label::new(tool.name())
594 .buffer_font(cx)
595 .size(LabelSize::Small),
596 )
597 .child(
598 Icon::new(IconName::Info)
599 .size(IconSize::Small)
600 .color(Color::Ignored),
601 )
602 .tooltip(Tooltip::text(tool.description()))
603 }),
604 ))
605 })
606 }
607}
608
609impl Render for AgentConfiguration {
610 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
611 v_flex()
612 .id("assistant-configuration")
613 .key_context("AgentConfiguration")
614 .track_focus(&self.focus_handle(cx))
615 .relative()
616 .size_full()
617 .pb_8()
618 .bg(cx.theme().colors().panel_background)
619 .child(
620 v_flex()
621 .id("assistant-configuration-content")
622 .track_scroll(&self.scroll_handle)
623 .size_full()
624 .overflow_y_scroll()
625 .child(self.render_general_settings_section(cx))
626 .child(Divider::horizontal().color(DividerColor::Border))
627 .child(self.render_context_servers_section(window, cx))
628 .child(Divider::horizontal().color(DividerColor::Border))
629 .child(self.render_provider_configuration_section(cx)),
630 )
631 .child(
632 div()
633 .id("assistant-configuration-scrollbar")
634 .occlude()
635 .absolute()
636 .right(px(3.))
637 .top_0()
638 .bottom_0()
639 .pb_6()
640 .w(px(12.))
641 .cursor_default()
642 .on_mouse_move(cx.listener(|_, _, _window, cx| {
643 cx.notify();
644 cx.stop_propagation()
645 }))
646 .on_hover(|_, _window, cx| {
647 cx.stop_propagation();
648 })
649 .on_any_mouse_down(|_, _window, cx| {
650 cx.stop_propagation();
651 })
652 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
653 cx.notify();
654 }))
655 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
656 )
657 }
658}