onboarding_modal.rs

  1use std::{sync::Arc, time::Duration};
  2
  3use crate::{ZED_PREDICT_DATA_COLLECTION_CHOICE, onboarding_event};
  4use anyhow::Context as _;
  5use client::{Client, UserStore};
  6use db::kvp::KEY_VALUE_STORE;
  7use fs::Fs;
  8use gpui::{
  9    Animation, AnimationExt as _, ClickEvent, DismissEvent, Entity, EventEmitter, FocusHandle,
 10    Focusable, MouseDownEvent, Render, ease_in_out, svg,
 11};
 12use language::language_settings::{AllLanguageSettings, EditPredictionProvider};
 13use settings::{Settings, update_settings_file};
 14use ui::{Checkbox, TintColor, prelude::*};
 15use util::ResultExt;
 16use workspace::{ModalView, Workspace, notifications::NotifyTaskExt};
 17
 18/// Introduces user to Zed's Edit Prediction feature and terms of service
 19pub struct ZedPredictModal {
 20    user_store: Entity<UserStore>,
 21    client: Arc<Client>,
 22    fs: Arc<dyn Fs>,
 23    focus_handle: FocusHandle,
 24    sign_in_status: SignInStatus,
 25    terms_of_service: bool,
 26    data_collection_expanded: bool,
 27    data_collection_opted_in: bool,
 28}
 29
 30#[derive(PartialEq, Eq)]
 31enum SignInStatus {
 32    /// Signed out or signed in but not from this modal
 33    Idle,
 34    /// Authentication triggered from this modal
 35    Waiting,
 36    /// Signed in after authentication from this modal
 37    SignedIn,
 38}
 39
 40impl ZedPredictModal {
 41    pub fn toggle(
 42        workspace: &mut Workspace,
 43        user_store: Entity<UserStore>,
 44        client: Arc<Client>,
 45        fs: Arc<dyn Fs>,
 46        window: &mut Window,
 47        cx: &mut Context<Workspace>,
 48    ) {
 49        workspace.toggle_modal(window, cx, |_window, cx| Self {
 50            user_store,
 51            client,
 52            fs,
 53            focus_handle: cx.focus_handle(),
 54            sign_in_status: SignInStatus::Idle,
 55            terms_of_service: false,
 56            data_collection_expanded: false,
 57            data_collection_opted_in: false,
 58        });
 59    }
 60
 61    fn view_terms(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
 62        cx.open_url("https://zed.dev/terms-of-service");
 63        cx.notify();
 64
 65        onboarding_event!("ToS Link Clicked");
 66    }
 67
 68    fn view_blog(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
 69        cx.open_url("https://zed.dev/blog/edit-prediction");
 70        cx.notify();
 71
 72        onboarding_event!("Blog Link clicked");
 73    }
 74
 75    fn inline_completions_doc(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
 76        cx.open_url("https://zed.dev/docs/configuring-zed#disabled-globs");
 77        cx.notify();
 78
 79        onboarding_event!("Docs Link Clicked");
 80    }
 81
 82    fn accept_and_enable(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
 83        let task = self
 84            .user_store
 85            .update(cx, |this, cx| this.accept_terms_of_service(cx));
 86        let fs = self.fs.clone();
 87
 88        cx.spawn(async move |this, cx| {
 89            task.await?;
 90
 91            let mut data_collection_opted_in = false;
 92            this.update(cx, |this, _cx| {
 93                data_collection_opted_in = this.data_collection_opted_in;
 94            })
 95            .ok();
 96
 97            KEY_VALUE_STORE
 98                .write_kvp(
 99                    ZED_PREDICT_DATA_COLLECTION_CHOICE.into(),
100                    data_collection_opted_in.to_string(),
101                )
102                .await
103                .log_err();
104
105            // Make sure edit prediction provider setting is using the new key
106            let settings_path = paths::settings_file().as_path();
107            let settings_path = fs.canonicalize(settings_path).await.with_context(|| {
108                format!("Failed to canonicalize settings path {:?}", settings_path)
109            })?;
110
111            if let Some(settings) = fs.load(&settings_path).await.log_err() {
112                if let Some(new_settings) =
113                    migrator::migrate_edit_prediction_provider_settings(&settings)?
114                {
115                    fs.atomic_write(settings_path, new_settings).await?;
116                }
117            }
118
119            this.update(cx, |this, cx| {
120                update_settings_file::<AllLanguageSettings>(this.fs.clone(), cx, move |file, _| {
121                    file.features
122                        .get_or_insert(Default::default())
123                        .edit_prediction_provider = Some(EditPredictionProvider::Zed);
124                });
125
126                cx.emit(DismissEvent);
127            })
128        })
129        .detach_and_notify_err(window, cx);
130
131        onboarding_event!(
132            "Enable Clicked",
133            data_collection_opted_in = self.data_collection_opted_in,
134        );
135    }
136
137    fn sign_in(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
138        let client = self.client.clone();
139        self.sign_in_status = SignInStatus::Waiting;
140
141        cx.spawn(async move |this, cx| {
142            let result = client
143                .authenticate_and_connect(true, &cx)
144                .await
145                .into_response();
146
147            let status = match result {
148                Ok(_) => SignInStatus::SignedIn,
149                Err(_) => SignInStatus::Idle,
150            };
151
152            this.update(cx, |this, cx| {
153                this.sign_in_status = status;
154                onboarding_event!("Signed In");
155                cx.notify()
156            })?;
157
158            result
159        })
160        .detach_and_notify_err(window, cx);
161
162        onboarding_event!("Sign In Clicked");
163    }
164
165    fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
166        cx.emit(DismissEvent);
167    }
168}
169
170impl EventEmitter<DismissEvent> for ZedPredictModal {}
171
172impl Focusable for ZedPredictModal {
173    fn focus_handle(&self, _cx: &App) -> FocusHandle {
174        self.focus_handle.clone()
175    }
176}
177
178impl ModalView for ZedPredictModal {}
179
180impl ZedPredictModal {
181    fn render_data_collection_explanation(&self, cx: &Context<Self>) -> impl IntoElement {
182        fn label_item(label_text: impl Into<SharedString>) -> impl Element {
183            Label::new(label_text).color(Color::Muted).into_element()
184        }
185
186        fn info_item(label_text: impl Into<SharedString>) -> impl Element {
187            h_flex()
188                .items_start()
189                .gap_2()
190                .child(
191                    div()
192                        .mt_1p5()
193                        .child(Icon::new(IconName::Check).size(IconSize::XSmall)),
194                )
195                .child(div().w_full().child(label_item(label_text)))
196        }
197
198        fn multiline_info_item<E1: Into<SharedString>, E2: IntoElement>(
199            first_line: E1,
200            second_line: E2,
201        ) -> impl Element {
202            v_flex()
203                .child(info_item(first_line))
204                .child(div().pl_5().child(second_line))
205        }
206
207        v_flex()
208            .mt_2()
209            .p_2()
210            .rounded_sm()
211            .bg(cx.theme().colors().editor_background.opacity(0.5))
212            .border_1()
213            .border_color(cx.theme().colors().border_variant)
214            .child(
215                div().child(
216                    Label::new("To improve edit predictions, please consider contributing to our open dataset based on your interactions within open source repositories.")
217                        .mb_1()
218                )
219            )
220            .child(info_item(
221                "We collect data exclusively from open source projects.",
222            ))
223            .child(info_item(
224                "Zed automatically detects if your project is open source.",
225            ))
226            .child(info_item("Toggle participation at any time via the status bar menu."))
227            .child(multiline_info_item(
228                "If turned on, this setting applies for all open source repositories",
229                label_item("you open in Zed.")
230            ))
231            .child(multiline_info_item(
232                "Files with sensitive data, like `.env`, are excluded by default",
233                h_flex()
234                    .w_full()
235                    .flex_wrap()
236                    .child(label_item("via the"))
237                    .child(
238                        Button::new("doc-link", "disabled_globs").on_click(
239                            cx.listener(Self::inline_completions_doc),
240                        ),
241                    )
242                    .child(label_item("setting.")),
243            ))
244    }
245}
246
247impl Render for ZedPredictModal {
248    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
249        let window_height = window.viewport_size().height;
250        let max_height = window_height - px(200.);
251
252        let has_subscription_period = self.user_store.read(cx).subscription_period().is_some();
253        let plan = self.user_store.read(cx).current_plan().filter(|_| {
254            // Since the user might be on the legacy free plan we filter based on whether we have a subscription period.
255            has_subscription_period
256        });
257
258        let base = v_flex()
259            .id("edit-prediction-onboarding")
260            .key_context("ZedPredictModal")
261            .relative()
262            .w(px(550.))
263            .h_full()
264            .max_h(max_height)
265            .p_4()
266            .gap_2()
267            .when(self.data_collection_expanded, |element| {
268                element.overflow_y_scroll()
269            })
270            .when(!self.data_collection_expanded, |element| {
271                element.overflow_hidden()
272            })
273            .elevation_3(cx)
274            .track_focus(&self.focus_handle(cx))
275            .on_action(cx.listener(Self::cancel))
276            .on_action(cx.listener(|_, _: &menu::Cancel, _window, cx| {
277                onboarding_event!("Cancelled", trigger = "Action");
278                cx.emit(DismissEvent);
279            }))
280            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
281                this.focus_handle.focus(window);
282            }))
283            .child(
284                div()
285                    .p_1p5()
286                    .absolute()
287                    .top_1()
288                    .left_1()
289                    .right_0()
290                    .h(px(200.))
291                    .child(
292                        svg()
293                            .path("icons/zed_predict_bg.svg")
294                            .text_color(cx.theme().colors().icon_disabled)
295                            .w(px(530.))
296                            .h(px(128.))
297                            .overflow_hidden(),
298                    ),
299            )
300            .child(
301                h_flex()
302                    .w_full()
303                    .mb_2()
304                    .justify_between()
305                    .child(
306                        v_flex()
307                            .gap_1()
308                            .child(
309                                Label::new("Introducing Zed AI's")
310                                    .size(LabelSize::Small)
311                                    .color(Color::Muted),
312                            )
313                            .child(Headline::new("Edit Prediction").size(HeadlineSize::Large)),
314                    )
315                    .child({
316                        let tab = |n: usize| {
317                            let text_color = cx.theme().colors().text;
318                            let border_color = cx.theme().colors().text_accent.opacity(0.4);
319
320                            h_flex().child(
321                                h_flex()
322                                    .px_4()
323                                    .py_0p5()
324                                    .bg(cx.theme().colors().editor_background)
325                                    .border_1()
326                                    .border_color(border_color)
327                                    .rounded_sm()
328                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
329                                    .text_size(TextSize::XSmall.rems(cx))
330                                    .text_color(text_color)
331                                    .child("tab")
332                                    .with_animation(
333                                        n,
334                                        Animation::new(Duration::from_secs(2)).repeat(),
335                                        move |tab, delta| {
336                                            let delta = (delta - 0.15 * n as f32) / 0.7;
337                                            let delta = 1.0 - (0.5 - delta).abs() * 2.;
338                                            let delta = ease_in_out(delta.clamp(0., 1.));
339                                            let delta = 0.1 + 0.9 * delta;
340
341                                            tab.border_color(border_color.opacity(delta))
342                                                .text_color(text_color.opacity(delta))
343                                        },
344                                    ),
345                            )
346                        };
347
348                        v_flex()
349                            .gap_2()
350                            .items_center()
351                            .pr_2p5()
352                            .child(tab(0).ml_neg_20())
353                            .child(tab(1))
354                            .child(tab(2).ml_20())
355                    }),
356            )
357            .child(h_flex().absolute().top_2().right_2().child(
358                IconButton::new("cancel", IconName::X).on_click(cx.listener(
359                    |_, _: &ClickEvent, _window, cx| {
360                        onboarding_event!("Cancelled", trigger = "X click");
361                        cx.emit(DismissEvent);
362                    },
363                )),
364            ));
365
366        let blog_post_button = Button::new("view-blog", "Read the Blog Post")
367            .full_width()
368            .icon(IconName::ArrowUpRight)
369            .icon_size(IconSize::Indicator)
370            .icon_color(Color::Muted)
371            .on_click(cx.listener(Self::view_blog));
372
373        if self.user_store.read(cx).current_user().is_some() {
374            let copy = match self.sign_in_status {
375                SignInStatus::Idle => {
376                    "Zed can now predict your next edit on every keystroke. Powered by Zeta, our open-source, open-dataset language model."
377                }
378                SignInStatus::SignedIn => "Almost there! Ensure you:",
379                SignInStatus::Waiting => unreachable!(),
380            };
381
382            let accordion_icons = if self.data_collection_expanded {
383                (IconName::ChevronUp, IconName::ChevronDown)
384            } else {
385                (IconName::ChevronDown, IconName::ChevronUp)
386            };
387            let plan = plan.unwrap_or(proto::Plan::Free);
388
389            base.child(Label::new(copy).color(Color::Muted))
390                .child(
391                    h_flex().child(
392                        Checkbox::new("plan", ToggleState::Selected)
393                            .fill()
394                            .disabled(true)
395                            .label(format!(
396                                "You get {} edit predictions through your {}.",
397                                if plan == proto::Plan::Free {
398                                    "2,000"
399                                } else {
400                                    "unlimited"
401                                },
402                                match plan {
403                                    proto::Plan::Free => "Zed Free plan",
404                                    proto::Plan::ZedPro => "Zed Pro plan",
405                                    proto::Plan::ZedProTrial => "Zed Pro trial",
406                                }
407                            )),
408                    ),
409                )
410                .child(
411                    h_flex()
412                        .child(
413                            Checkbox::new("tos-checkbox", self.terms_of_service.into())
414                                .fill()
415                                .label("I have read and accept the")
416                                .on_click(cx.listener(move |this, state, _window, cx| {
417                                    this.terms_of_service = *state == ToggleState::Selected;
418                                    cx.notify();
419                                })),
420                        )
421                        .child(
422                            Button::new("view-tos", "Terms of Service")
423                                .icon(IconName::ArrowUpRight)
424                                .icon_size(IconSize::Indicator)
425                                .icon_color(Color::Muted)
426                                .on_click(cx.listener(Self::view_terms)),
427                        ),
428                )
429                .child(
430                    v_flex()
431                        .child(
432                            h_flex()
433                                .flex_wrap()
434                                .child(
435                                    Checkbox::new(
436                                        "training-data-checkbox",
437                                        self.data_collection_opted_in.into(),
438                                    )
439                                    .label(
440                                        "Contribute to the open dataset when editing open source.",
441                                    )
442                                    .fill()
443                                    .on_click(cx.listener(
444                                        move |this, state, _window, cx| {
445                                            this.data_collection_opted_in =
446                                                *state == ToggleState::Selected;
447                                            cx.notify()
448                                        },
449                                    )),
450                                )
451                                .child(
452                                    Button::new("learn-more", "Learn More")
453                                        .icon(accordion_icons.0)
454                                        .icon_size(IconSize::Indicator)
455                                        .icon_color(Color::Muted)
456                                        .on_click(cx.listener(|this, _, _, cx| {
457                                            this.data_collection_expanded =
458                                                !this.data_collection_expanded;
459                                            cx.notify();
460
461                                            if this.data_collection_expanded {
462                                                onboarding_event!(
463                                                    "Data Collection Learn More Clicked"
464                                                );
465                                            }
466                                        })),
467                                ),
468                        )
469                        .when(self.data_collection_expanded, |element| {
470                            element.child(self.render_data_collection_explanation(cx))
471                        }),
472                )
473                .child(
474                    v_flex()
475                        .mt_2()
476                        .gap_2()
477                        .w_full()
478                        .child(
479                            Button::new("accept-tos", "Enable Edit Prediction")
480                                .disabled(!self.terms_of_service)
481                                .style(ButtonStyle::Tinted(TintColor::Accent))
482                                .full_width()
483                                .on_click(cx.listener(Self::accept_and_enable)),
484                        )
485                        .child(blog_post_button),
486                )
487        } else {
488            base.child(
489                Label::new("To set Zed as your edit prediction provider, please sign in.")
490                    .color(Color::Muted),
491            )
492            .child(
493                v_flex()
494                    .mt_2()
495                    .gap_2()
496                    .w_full()
497                    .child(
498                        Button::new("accept-tos", "Sign in with GitHub")
499                            .disabled(self.sign_in_status == SignInStatus::Waiting)
500                            .style(ButtonStyle::Tinted(TintColor::Accent))
501                            .full_width()
502                            .on_click(cx.listener(Self::sign_in)),
503                    )
504                    .child(blog_post_button),
505            )
506        }
507    }
508}