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