assistant_configuration.rs

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