agent_configuration.rs

  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, 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 = AssistantSettings::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::<AssistantSettings>(
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 = AssistantSettings::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::<AssistantSettings>(
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_general_settings_section(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
331        v_flex()
332            .p(DynamicSpacing::Base16.rems(cx))
333            .pr(DynamicSpacing::Base20.rems(cx))
334            .gap_2p5()
335            .border_b_1()
336            .border_color(cx.theme().colors().border)
337            .child(Headline::new("General Settings"))
338            .child(self.render_command_permission(cx))
339            .child(self.render_single_file_review(cx))
340    }
341
342    fn render_context_servers_section(
343        &mut self,
344        window: &mut Window,
345        cx: &mut Context<Self>,
346    ) -> impl IntoElement {
347        let context_server_ids = self.context_server_store.read(cx).all_server_ids().clone();
348
349        v_flex()
350            .p(DynamicSpacing::Base16.rems(cx))
351            .pr(DynamicSpacing::Base20.rems(cx))
352            .gap_2()
353            .border_b_1()
354            .border_color(cx.theme().colors().border)
355            .child(
356                v_flex()
357                    .gap_0p5()
358                    .child(Headline::new("Model Context Protocol (MCP) Servers"))
359                    .child(Label::new("Connect to context servers via the Model Context Protocol either via Zed extensions or directly.").color(Color::Muted)),
360            )
361            .children(
362                context_server_ids.into_iter().map(|context_server_id| {
363                    self.render_context_server(context_server_id, window, cx)
364                }),
365            )
366            .child(
367                h_flex()
368                    .justify_between()
369                    .gap_2()
370                    .child(
371                        h_flex().w_full().child(
372                            Button::new("add-context-server", "Add Custom Server")
373                                .style(ButtonStyle::Filled)
374                                .layer(ElevationIndex::ModalSurface)
375                                .full_width()
376                                .icon(IconName::Plus)
377                                .icon_size(IconSize::Small)
378                                .icon_position(IconPosition::Start)
379                                .on_click(|_event, window, cx| {
380                                    window.dispatch_action(AddContextServer.boxed_clone(), cx)
381                                }),
382                        ),
383                    )
384                    .child(
385                        h_flex().w_full().child(
386                            Button::new(
387                                "install-context-server-extensions",
388                                "Install MCP Extensions",
389                            )
390                            .style(ButtonStyle::Filled)
391                            .layer(ElevationIndex::ModalSurface)
392                            .full_width()
393                            .icon(IconName::Hammer)
394                            .icon_size(IconSize::Small)
395                            .icon_position(IconPosition::Start)
396                            .on_click(|_event, window, cx| {
397                                window.dispatch_action(
398                                    zed_actions::Extensions {
399                                        category_filter: Some(
400                                            ExtensionCategoryFilter::ContextServers,
401                                        ),
402                                    }
403                                    .boxed_clone(),
404                                    cx,
405                                )
406                            }),
407                        ),
408                    ),
409            )
410    }
411
412    fn render_context_server(
413        &self,
414        context_server_id: ContextServerId,
415        window: &mut Window,
416        cx: &mut Context<Self>,
417    ) -> impl use<> + IntoElement {
418        let tools_by_source = self.tools.read(cx).tools_by_source(cx);
419        let server_status = self
420            .context_server_store
421            .read(cx)
422            .status_for_server(&context_server_id)
423            .unwrap_or(ContextServerStatus::Stopped);
424
425        let is_running = matches!(server_status, ContextServerStatus::Running);
426        let item_id = SharedString::from(context_server_id.0.clone());
427
428        let error = if let ContextServerStatus::Error(error) = server_status.clone() {
429            Some(error)
430        } else {
431            None
432        };
433
434        let are_tools_expanded = self
435            .expanded_context_server_tools
436            .get(&context_server_id)
437            .copied()
438            .unwrap_or_default();
439
440        let tools = tools_by_source
441            .get(&ToolSource::ContextServer {
442                id: context_server_id.0.clone().into(),
443            })
444            .map_or([].as_slice(), |tools| tools.as_slice());
445        let tool_count = tools.len();
446
447        let border_color = cx.theme().colors().border.opacity(0.6);
448        let success_color = Color::Success.color(cx);
449
450        let (status_indicator, tooltip_text) = match server_status {
451            ContextServerStatus::Starting => (
452                Indicator::dot()
453                    .color(Color::Success)
454                    .with_animation(
455                        SharedString::from(format!("{}-starting", context_server_id.0.clone(),)),
456                        Animation::new(Duration::from_secs(2))
457                            .repeat()
458                            .with_easing(pulsating_between(0.4, 1.)),
459                        move |this, delta| this.color(success_color.alpha(delta).into()),
460                    )
461                    .into_any_element(),
462                "Server is starting.",
463            ),
464            ContextServerStatus::Running => (
465                Indicator::dot().color(Color::Success).into_any_element(),
466                "Server is running.",
467            ),
468            ContextServerStatus::Error(_) => (
469                Indicator::dot().color(Color::Error).into_any_element(),
470                "Server has an error.",
471            ),
472            ContextServerStatus::Stopped => (
473                Indicator::dot().color(Color::Muted).into_any_element(),
474                "Server is stopped.",
475            ),
476        };
477
478        v_flex()
479            .id(item_id.clone())
480            .border_1()
481            .rounded_md()
482            .border_color(border_color)
483            .bg(cx.theme().colors().background.opacity(0.2))
484            .overflow_hidden()
485            .child(
486                h_flex()
487                    .p_1()
488                    .justify_between()
489                    .when(
490                        error.is_some() || are_tools_expanded && tool_count > 1,
491                        |element| element.border_b_1().border_color(border_color),
492                    )
493                    .child(
494                        h_flex()
495                            .gap_1p5()
496                            .child(
497                                Disclosure::new(
498                                    "tool-list-disclosure",
499                                    are_tools_expanded || error.is_some(),
500                                )
501                                .disabled(tool_count == 0)
502                                .on_click(cx.listener({
503                                    let context_server_id = context_server_id.clone();
504                                    move |this, _event, _window, _cx| {
505                                        let is_open = this
506                                            .expanded_context_server_tools
507                                            .entry(context_server_id.clone())
508                                            .or_insert(false);
509
510                                        *is_open = !*is_open;
511                                    }
512                                })),
513                            )
514                            .child(
515                                div()
516                                    .id(item_id.clone())
517                                    .tooltip(Tooltip::text(tooltip_text))
518                                    .child(status_indicator),
519                            )
520                            .child(Label::new(context_server_id.0.clone()).ml_0p5())
521                            .when(is_running, |this| {
522                                this.child(
523                                    Label::new(if tool_count == 1 {
524                                        SharedString::from("1 tool")
525                                    } else {
526                                        SharedString::from(format!("{} tools", tool_count))
527                                    })
528                                    .color(Color::Muted)
529                                    .size(LabelSize::Small),
530                                )
531                            }),
532                    )
533                    .child(
534                        Switch::new("context-server-switch", is_running.into())
535                            .color(SwitchColor::Accent)
536                            .on_click({
537                                let context_server_manager = self.context_server_store.clone();
538                                let context_server_id = context_server_id.clone();
539                                move |state, _window, cx| match state {
540                                    ToggleState::Unselected | ToggleState::Indeterminate => {
541                                        context_server_manager.update(cx, |this, cx| {
542                                            this.stop_server(&context_server_id, cx).log_err();
543                                        });
544                                    }
545                                    ToggleState::Selected => {
546                                        context_server_manager.update(cx, |this, cx| {
547                                            if let Some(server) =
548                                                this.get_server(&context_server_id)
549                                            {
550                                                this.start_server(server, cx).log_err();
551                                            }
552                                        })
553                                    }
554                                }
555                            }),
556                    ),
557            )
558            .map(|parent| {
559                if let Some(error) = error {
560                    return parent.child(
561                        h_flex()
562                            .p_2()
563                            .gap_2()
564                            .items_start()
565                            .child(
566                                h_flex()
567                                    .flex_none()
568                                    .h(window.line_height() / 1.6_f32)
569                                    .justify_center()
570                                    .child(
571                                        Icon::new(IconName::XCircle)
572                                            .size(IconSize::XSmall)
573                                            .color(Color::Error),
574                                    ),
575                            )
576                            .child(
577                                div().w_full().child(
578                                    Label::new(error)
579                                        .buffer_font(cx)
580                                        .color(Color::Muted)
581                                        .size(LabelSize::Small),
582                                ),
583                            ),
584                    );
585                }
586
587                if !are_tools_expanded || tools.is_empty() {
588                    return parent;
589                }
590
591                parent.child(v_flex().py_1p5().px_1().gap_1().children(
592                    tools.into_iter().enumerate().map(|(ix, tool)| {
593                        h_flex()
594                            .id(("tool-item", ix))
595                            .px_1()
596                            .gap_2()
597                            .justify_between()
598                            .hover(|style| style.bg(cx.theme().colors().element_hover))
599                            .rounded_sm()
600                            .child(
601                                Label::new(tool.name())
602                                    .buffer_font(cx)
603                                    .size(LabelSize::Small),
604                            )
605                            .child(
606                                Icon::new(IconName::Info)
607                                    .size(IconSize::Small)
608                                    .color(Color::Ignored),
609                            )
610                            .tooltip(Tooltip::text(tool.description()))
611                    }),
612                ))
613            })
614    }
615}
616
617impl Render for AgentConfiguration {
618    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
619        v_flex()
620            .id("assistant-configuration")
621            .key_context("AgentConfiguration")
622            .track_focus(&self.focus_handle(cx))
623            .relative()
624            .size_full()
625            .pb_8()
626            .bg(cx.theme().colors().panel_background)
627            .child(
628                v_flex()
629                    .id("assistant-configuration-content")
630                    .track_scroll(&self.scroll_handle)
631                    .size_full()
632                    .overflow_y_scroll()
633                    .child(self.render_general_settings_section(cx))
634                    .child(self.render_context_servers_section(window, cx))
635                    .child(self.render_provider_configuration_section(cx)),
636            )
637            .child(
638                div()
639                    .id("assistant-configuration-scrollbar")
640                    .occlude()
641                    .absolute()
642                    .right(px(3.))
643                    .top_0()
644                    .bottom_0()
645                    .pb_6()
646                    .w(px(12.))
647                    .cursor_default()
648                    .on_mouse_move(cx.listener(|_, _, _window, cx| {
649                        cx.notify();
650                        cx.stop_propagation()
651                    }))
652                    .on_hover(|_, _window, cx| {
653                        cx.stop_propagation();
654                    })
655                    .on_any_mouse_down(|_, _window, cx| {
656                        cx.stop_propagation();
657                    })
658                    .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
659                        cx.notify();
660                    }))
661                    .children(Scrollbar::vertical(self.scrollbar_state.clone())),
662            )
663    }
664}