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(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
261 let context_servers = self.context_server_manager.read(cx).all_servers().clone();
262
263 const SUBHEADING: &str = "Connect to context servers via the Model Context Protocol either via Zed extensions or directly.";
264
265 v_flex()
266 .p(DynamicSpacing::Base16.rems(cx))
267 .pr(DynamicSpacing::Base20.rems(cx))
268 .gap_2()
269 .flex_1()
270 .child(
271 v_flex()
272 .gap_0p5()
273 .child(Headline::new("Model Context Protocol (MCP) Servers"))
274 .child(Label::new(SUBHEADING).color(Color::Muted)),
275 )
276 .children(
277 context_servers
278 .into_iter()
279 .map(|context_server| self.render_context_server(context_server, cx)),
280 )
281 .child(
282 h_flex()
283 .justify_between()
284 .gap_2()
285 .child(
286 h_flex().w_full().child(
287 Button::new("add-context-server", "Add Custom Server")
288 .style(ButtonStyle::Filled)
289 .layer(ElevationIndex::ModalSurface)
290 .full_width()
291 .icon(IconName::Plus)
292 .icon_size(IconSize::Small)
293 .icon_position(IconPosition::Start)
294 .on_click(|_event, window, cx| {
295 window.dispatch_action(AddContextServer.boxed_clone(), cx)
296 }),
297 ),
298 )
299 .child(
300 h_flex().w_full().child(
301 Button::new(
302 "install-context-server-extensions",
303 "Install MCP Extensions",
304 )
305 .style(ButtonStyle::Filled)
306 .layer(ElevationIndex::ModalSurface)
307 .full_width()
308 .icon(IconName::DatabaseZap)
309 .icon_size(IconSize::Small)
310 .icon_position(IconPosition::Start)
311 .on_click(|_event, window, cx| {
312 window.dispatch_action(
313 zed_actions::Extensions {
314 category_filter: Some(
315 ExtensionCategoryFilter::ContextServers,
316 ),
317 }
318 .boxed_clone(),
319 cx,
320 )
321 }),
322 ),
323 ),
324 )
325 }
326
327 fn render_context_server(
328 &self,
329 context_server: Arc<ContextServer>,
330 cx: &mut Context<Self>,
331 ) -> impl use<> + IntoElement {
332 let tools_by_source = self.tools.read(cx).tools_by_source(cx);
333 let server_status = self
334 .context_server_manager
335 .read(cx)
336 .status_for_server(&context_server.id());
337
338 let is_running = matches!(server_status, Some(ContextServerStatus::Running));
339
340 let error = if let Some(ContextServerStatus::Error(error)) = server_status.clone() {
341 Some(error)
342 } else {
343 None
344 };
345
346 let are_tools_expanded = self
347 .expanded_context_server_tools
348 .get(&context_server.id())
349 .copied()
350 .unwrap_or_default();
351
352 let tools = tools_by_source
353 .get(&ToolSource::ContextServer {
354 id: context_server.id().into(),
355 })
356 .map_or([].as_slice(), |tools| tools.as_slice());
357 let tool_count = tools.len();
358
359 v_flex()
360 .id(SharedString::from(context_server.id()))
361 .border_1()
362 .rounded_md()
363 .border_color(cx.theme().colors().border)
364 .bg(cx.theme().colors().background.opacity(0.25))
365 .child(
366 h_flex()
367 .p_1()
368 .justify_between()
369 .when(are_tools_expanded && tool_count > 1, |element| {
370 element
371 .border_b_1()
372 .border_color(cx.theme().colors().border)
373 })
374 .child(
375 h_flex()
376 .gap_2()
377 .child(
378 Disclosure::new(
379 "tool-list-disclosure",
380 are_tools_expanded || error.is_some(),
381 )
382 .disabled(tool_count == 0)
383 .on_click(cx.listener({
384 let context_server_id = context_server.id();
385 move |this, _event, _window, _cx| {
386 let is_open = this
387 .expanded_context_server_tools
388 .entry(context_server_id.clone())
389 .or_insert(false);
390
391 *is_open = !*is_open;
392 }
393 })),
394 )
395 .child(match server_status {
396 Some(ContextServerStatus::Starting) => {
397 let color = Color::Success.color(cx);
398 Indicator::dot()
399 .color(Color::Success)
400 .with_animation(
401 SharedString::from(format!(
402 "{}-starting",
403 context_server.id(),
404 )),
405 Animation::new(Duration::from_secs(2))
406 .repeat()
407 .with_easing(pulsating_between(0.4, 1.)),
408 move |this, delta| {
409 this.color(color.alpha(delta).into())
410 },
411 )
412 .into_any_element()
413 }
414 Some(ContextServerStatus::Running) => {
415 Indicator::dot().color(Color::Success).into_any_element()
416 }
417 Some(ContextServerStatus::Error(_)) => {
418 Indicator::dot().color(Color::Error).into_any_element()
419 }
420 None => Indicator::dot().color(Color::Muted).into_any_element(),
421 })
422 .child(Label::new(context_server.id()))
423 .when(is_running, |this| {
424 this.child(
425 Label::new(if tool_count == 1 {
426 SharedString::from("1 tool")
427 } else {
428 SharedString::from(format!("{} tools", tool_count))
429 })
430 .color(Color::Muted)
431 .size(LabelSize::Small),
432 )
433 }),
434 )
435 .child(
436 Switch::new("context-server-switch", is_running.into())
437 .color(SwitchColor::Accent)
438 .on_click({
439 let context_server_manager = self.context_server_manager.clone();
440 let context_server = context_server.clone();
441 move |state, _window, cx| match state {
442 ToggleState::Unselected | ToggleState::Indeterminate => {
443 context_server_manager.update(cx, |this, cx| {
444 this.stop_server(context_server.clone(), cx).log_err();
445 });
446 }
447 ToggleState::Selected => {
448 cx.spawn({
449 let context_server_manager =
450 context_server_manager.clone();
451 let context_server = context_server.clone();
452 async move |cx| {
453 if let Some(start_server_task) =
454 context_server_manager
455 .update(cx, |this, cx| {
456 this.start_server(context_server, cx)
457 })
458 .log_err()
459 {
460 start_server_task.await.log_err();
461 }
462 }
463 })
464 .detach();
465 }
466 }
467 }),
468 ),
469 )
470 .map(|parent| {
471 if let Some(error) = error {
472 return parent.child(
473 div().py_1p5().px_2().child(
474 Label::new(error)
475 .color(Color::Muted)
476 .buffer_font(cx)
477 .size(LabelSize::Small),
478 ),
479 );
480 }
481
482 if !are_tools_expanded || tools.is_empty() {
483 return parent;
484 }
485
486 parent.child(v_flex().py_1p5().px_1().gap_1().children(
487 tools.into_iter().enumerate().map(|(ix, tool)| {
488 h_flex()
489 .id(("tool-item", ix))
490 .px_1()
491 .gap_2()
492 .justify_between()
493 .hover(|style| style.bg(cx.theme().colors().element_hover))
494 .rounded_sm()
495 .child(
496 Label::new(tool.name())
497 .buffer_font(cx)
498 .size(LabelSize::Small),
499 )
500 .child(
501 Icon::new(IconName::Info)
502 .size(IconSize::Small)
503 .color(Color::Ignored),
504 )
505 .tooltip(Tooltip::text(tool.description()))
506 }),
507 ))
508 })
509 }
510}
511
512impl Render for AssistantConfiguration {
513 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
514 v_flex()
515 .id("assistant-configuration")
516 .key_context("AgentConfiguration")
517 .track_focus(&self.focus_handle(cx))
518 .relative()
519 .size_full()
520 .pb_8()
521 .bg(cx.theme().colors().panel_background)
522 .child(
523 v_flex()
524 .id("assistant-configuration-content")
525 .track_scroll(&self.scroll_handle)
526 .size_full()
527 .overflow_y_scroll()
528 .child(self.render_command_permission(cx))
529 .child(Divider::horizontal().color(DividerColor::Border))
530 .child(self.render_context_servers_section(cx))
531 .child(Divider::horizontal().color(DividerColor::Border))
532 .child(self.render_provider_configuration_section(cx)),
533 )
534 .child(
535 div()
536 .id("assistant-configuration-scrollbar")
537 .occlude()
538 .absolute()
539 .right(px(3.))
540 .top_0()
541 .bottom_0()
542 .pb_6()
543 .w(px(12.))
544 .cursor_default()
545 .on_mouse_move(cx.listener(|_, _, _window, cx| {
546 cx.notify();
547 cx.stop_propagation()
548 }))
549 .on_hover(|_, _window, cx| {
550 cx.stop_propagation();
551 })
552 .on_any_mouse_down(|_, _window, cx| {
553 cx.stop_propagation();
554 })
555 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
556 cx.notify();
557 }))
558 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
559 )
560 }
561}