ai_setup_page.rs

  1use std::sync::Arc;
  2
  3use ai_onboarding::AiUpsellCard;
  4use client::{Client, UserStore, zed_urls};
  5use fs::Fs;
  6use gpui::{
  7    Action, AnyView, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, WeakEntity,
  8    Window, prelude::*,
  9};
 10use itertools;
 11use language_model::{LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry};
 12use project::DisableAiSettings;
 13use settings::{Settings, update_settings_file};
 14use ui::{
 15    Badge, ButtonLike, Divider, KeyBinding, Modal, ModalFooter, ModalHeader, Section, SwitchField,
 16    ToggleState, prelude::*, tooltip_container,
 17};
 18use util::ResultExt;
 19use workspace::{ModalView, Workspace};
 20use zed_actions::agent::OpenSettings;
 21
 22const FEATURED_PROVIDERS: [&'static str; 4] = ["anthropic", "google", "openai", "ollama"];
 23
 24fn render_llm_provider_section(
 25    tab_index: &mut isize,
 26    workspace: WeakEntity<Workspace>,
 27    disabled: bool,
 28    window: &mut Window,
 29    cx: &mut App,
 30) -> impl IntoElement {
 31    v_flex()
 32        .gap_4()
 33        .child(
 34            v_flex()
 35                .child(Label::new("Or use other LLM providers").size(LabelSize::Large))
 36                .child(
 37                    Label::new("Bring your API keys to use the available providers with Zed's UI for free.")
 38                        .color(Color::Muted),
 39                ),
 40        )
 41        .child(render_llm_provider_card(tab_index, workspace, disabled, window, cx))
 42}
 43
 44fn render_privacy_card(tab_index: &mut isize, disabled: bool, cx: &mut App) -> impl IntoElement {
 45    let (title, description) = if disabled {
 46        (
 47            "AI is disabled across Zed",
 48            "Re-enable it any time in Settings.",
 49        )
 50    } else {
 51        (
 52            "Privacy is the default for Zed",
 53            "Any use or storage of your data is with your explicit, single-use, opt-in consent.",
 54        )
 55    };
 56
 57    v_flex()
 58        .relative()
 59        .pt_2()
 60        .pb_2p5()
 61        .pl_3()
 62        .pr_2()
 63        .border_1()
 64        .border_dashed()
 65        .border_color(cx.theme().colors().border.opacity(0.5))
 66        .bg(cx.theme().colors().surface_background.opacity(0.3))
 67        .rounded_lg()
 68        .overflow_hidden()
 69        .child(
 70            h_flex()
 71                .gap_2()
 72                .justify_between()
 73                .child(Label::new(title))
 74                .child(
 75                    h_flex()
 76                        .gap_1()
 77                        .child(
 78                            Badge::new("Privacy")
 79                                .icon(IconName::ShieldCheck)
 80                                .tooltip(move |_, cx| cx.new(|_| AiPrivacyTooltip::new()).into()),
 81                        )
 82                        .child(
 83                            Button::new("learn_more", "Learn More")
 84                                .style(ButtonStyle::Outlined)
 85                                .label_size(LabelSize::Small)
 86                                .icon(IconName::ArrowUpRight)
 87                                .icon_size(IconSize::XSmall)
 88                                .icon_color(Color::Muted)
 89                                .on_click(|_, _, cx| {
 90                                    cx.open_url(&zed_urls::ai_privacy_and_security(cx))
 91                                })
 92                                .tab_index({
 93                                    *tab_index += 1;
 94                                    *tab_index - 1
 95                                }),
 96                        ),
 97                ),
 98        )
 99        .child(
100            Label::new(description)
101                .size(LabelSize::Small)
102                .color(Color::Muted),
103        )
104}
105
106fn render_llm_provider_card(
107    tab_index: &mut isize,
108    workspace: WeakEntity<Workspace>,
109    disabled: bool,
110    _: &mut Window,
111    cx: &mut App,
112) -> impl IntoElement {
113    let registry = LanguageModelRegistry::read_global(cx);
114
115    v_flex()
116        .border_1()
117        .border_color(cx.theme().colors().border)
118        .bg(cx.theme().colors().surface_background.opacity(0.5))
119        .rounded_lg()
120        .overflow_hidden()
121        .children(itertools::intersperse_with(
122            FEATURED_PROVIDERS
123                .into_iter()
124                .flat_map(|provider_name| {
125                    registry.provider(&LanguageModelProviderId::new(provider_name))
126                })
127                .enumerate()
128                .map(|(index, provider)| {
129                    let group_name = SharedString::new(format!("onboarding-hover-group-{}", index));
130                    let is_authenticated = provider.is_authenticated(cx);
131
132                    ButtonLike::new(("onboarding-ai-setup-buttons", index))
133                        .size(ButtonSize::Large)
134                        .tab_index({
135                            *tab_index += 1;
136                            *tab_index - 1
137                        })
138                        .child(
139                            h_flex()
140                                .group(&group_name)
141                                .px_0p5()
142                                .w_full()
143                                .gap_2()
144                                .justify_between()
145                                .child(
146                                    h_flex()
147                                        .gap_1()
148                                        .child(
149                                            Icon::new(provider.icon())
150                                                .color(Color::Muted)
151                                                .size(IconSize::XSmall),
152                                        )
153                                        .child(Label::new(provider.name().0)),
154                                )
155                                .child(
156                                    h_flex()
157                                        .gap_1()
158                                        .when(!is_authenticated, |el| {
159                                            el.visible_on_hover(group_name.clone())
160                                                .child(
161                                                    Icon::new(IconName::Settings)
162                                                        .color(Color::Muted)
163                                                        .size(IconSize::XSmall),
164                                                )
165                                                .child(
166                                                    Label::new("Configure")
167                                                        .color(Color::Muted)
168                                                        .size(LabelSize::Small),
169                                                )
170                                        })
171                                        .when(is_authenticated && !disabled, |el| {
172                                            el.child(
173                                                Icon::new(IconName::Check)
174                                                    .color(Color::Success)
175                                                    .size(IconSize::XSmall),
176                                            )
177                                            .child(
178                                                Label::new("Configured")
179                                                    .color(Color::Muted)
180                                                    .size(LabelSize::Small),
181                                            )
182                                        }),
183                                ),
184                        )
185                        .on_click({
186                            let workspace = workspace.clone();
187                            move |_, window, cx| {
188                                workspace
189                                    .update(cx, |workspace, cx| {
190                                        workspace.toggle_modal(window, cx, |window, cx| {
191                                            let modal = AiConfigurationModal::new(
192                                                provider.clone(),
193                                                window,
194                                                cx,
195                                            );
196                                            window.focus(&modal.focus_handle(cx));
197                                            modal
198                                        });
199                                    })
200                                    .log_err();
201                            }
202                        })
203                        .into_any_element()
204                }),
205            || Divider::horizontal().into_any_element(),
206        ))
207        .child(Divider::horizontal())
208        .child(
209            Button::new("agent_settings", "Add Many Others")
210                .size(ButtonSize::Large)
211                .icon(IconName::Plus)
212                .icon_position(IconPosition::Start)
213                .icon_color(Color::Muted)
214                .icon_size(IconSize::XSmall)
215                .on_click(|_event, window, cx| {
216                    window.dispatch_action(OpenSettings.boxed_clone(), cx)
217                })
218                .tab_index({
219                    *tab_index += 1;
220                    *tab_index - 1
221                }),
222        )
223}
224
225pub(crate) fn render_ai_setup_page(
226    workspace: WeakEntity<Workspace>,
227    user_store: Entity<UserStore>,
228    client: Arc<Client>,
229    window: &mut Window,
230    cx: &mut App,
231) -> impl IntoElement {
232    let mut tab_index = 0;
233    let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
234
235    v_flex()
236        .gap_2()
237        .child(
238            SwitchField::new(
239                "enable_ai",
240                "Enable AI features",
241                None,
242                if is_ai_disabled {
243                    ToggleState::Unselected
244                } else {
245                    ToggleState::Selected
246                },
247                |&toggle_state, _, cx| {
248                    let fs = <dyn Fs>::global(cx);
249                    update_settings_file::<DisableAiSettings>(
250                        fs,
251                        cx,
252                        move |ai_settings: &mut Option<bool>, _| {
253                            *ai_settings = match toggle_state {
254                                ToggleState::Indeterminate => None,
255                                ToggleState::Unselected => Some(true),
256                                ToggleState::Selected => Some(false),
257                            };
258                        },
259                    );
260                },
261            )
262            .tab_index({
263                tab_index += 1;
264                tab_index - 1
265            }),
266        )
267        .child(render_privacy_card(&mut tab_index, is_ai_disabled, cx))
268        .child(
269            v_flex()
270                .mt_2()
271                .gap_6()
272                .child({
273                    let mut ai_upsell_card =
274                        AiUpsellCard::new(client, &user_store, user_store.read(cx).plan(), cx);
275
276                    ai_upsell_card.tab_index = Some({
277                        tab_index += 1;
278                        tab_index - 1
279                    });
280
281                    ai_upsell_card
282                })
283                .child(render_llm_provider_section(
284                    &mut tab_index,
285                    workspace,
286                    is_ai_disabled,
287                    window,
288                    cx,
289                ))
290                .when(is_ai_disabled, |this| {
291                    this.child(
292                        div()
293                            .id("backdrop")
294                            .size_full()
295                            .absolute()
296                            .inset_0()
297                            .bg(cx.theme().colors().editor_background)
298                            .opacity(0.8)
299                            .block_mouse_except_scroll(),
300                    )
301                }),
302        )
303}
304
305struct AiConfigurationModal {
306    focus_handle: FocusHandle,
307    selected_provider: Arc<dyn LanguageModelProvider>,
308    configuration_view: AnyView,
309}
310
311impl AiConfigurationModal {
312    fn new(
313        selected_provider: Arc<dyn LanguageModelProvider>,
314        window: &mut Window,
315        cx: &mut Context<Self>,
316    ) -> Self {
317        let focus_handle = cx.focus_handle();
318        let configuration_view = selected_provider.configuration_view(window, cx);
319
320        Self {
321            focus_handle,
322            configuration_view,
323            selected_provider,
324        }
325    }
326
327    fn cancel(&mut self, _: &menu::Cancel, cx: &mut Context<Self>) {
328        cx.emit(DismissEvent);
329    }
330}
331
332impl ModalView for AiConfigurationModal {}
333
334impl EventEmitter<DismissEvent> for AiConfigurationModal {}
335
336impl Focusable for AiConfigurationModal {
337    fn focus_handle(&self, _cx: &App) -> FocusHandle {
338        self.focus_handle.clone()
339    }
340}
341
342impl Render for AiConfigurationModal {
343    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
344        v_flex()
345            .key_context("OnboardingAiConfigurationModal")
346            .w(rems(34.))
347            .elevation_3(cx)
348            .track_focus(&self.focus_handle)
349            .on_action(
350                cx.listener(|this, _: &menu::Cancel, _window, cx| this.cancel(&menu::Cancel, cx)),
351            )
352            .child(
353                Modal::new("onboarding-ai-setup-modal", None)
354                    .header(
355                        ModalHeader::new()
356                            .icon(
357                                Icon::new(self.selected_provider.icon())
358                                    .color(Color::Muted)
359                                    .size(IconSize::Small),
360                            )
361                            .headline(self.selected_provider.name().0),
362                    )
363                    .section(Section::new().child(self.configuration_view.clone()))
364                    .footer(
365                        ModalFooter::new().end_slot(
366                            Button::new("ai-onb-modal-Done", "Done")
367                                .key_binding(
368                                    KeyBinding::for_action_in(
369                                        &menu::Cancel,
370                                        &self.focus_handle.clone(),
371                                        window,
372                                        cx,
373                                    )
374                                    .map(|kb| kb.size(rems_from_px(12.))),
375                                )
376                                .on_click(cx.listener(|this, _event, _window, cx| {
377                                    this.cancel(&menu::Cancel, cx)
378                                })),
379                        ),
380                    ),
381            )
382    }
383}
384
385pub struct AiPrivacyTooltip {}
386
387impl AiPrivacyTooltip {
388    pub fn new() -> Self {
389        Self {}
390    }
391}
392
393impl Render for AiPrivacyTooltip {
394    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
395        const DESCRIPTION: &'static str = "We believe in opt-in data sharing as the default for building AI products, rather than opt-out. We'll only use or store your data if you affirmatively send it to us. ";
396
397        tooltip_container(window, cx, move |this, _, _| {
398            this.child(
399                h_flex()
400                    .gap_1()
401                    .child(
402                        Icon::new(IconName::ShieldCheck)
403                            .size(IconSize::Small)
404                            .color(Color::Muted),
405                    )
406                    .child(Label::new("Privacy First")),
407            )
408            .child(
409                div().max_w_64().child(
410                    Label::new(DESCRIPTION)
411                        .size(LabelSize::Small)
412                        .color(Color::Muted),
413                ),
414            )
415        })
416    }
417}