File: first_run_flow_controller_dice.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (638 lines) | stat: -rw-r--r-- 25,549 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/profiles/first_run_flow_controller_dice.h"

#include <memory>
#include <utility>

#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_forward.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/enterprise/util/managed_browser_utils.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engine_choice/search_engine_choice_dialog_service.h"
#include "chrome/browser/search_engine_choice/search_engine_choice_dialog_service_factory.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/profiles/profile_management_flow_controller.h"
#include "chrome/browser/ui/views/profiles/profile_management_flow_controller_impl.h"
#include "chrome/browser/ui/views/profiles/profile_management_step_controller.h"
#include "chrome/browser/ui/views/profiles/profile_management_types.h"
#include "chrome/browser/ui/views/profiles/profile_picker_signed_in_flow_controller.h"
#include "chrome/browser/ui/views/profiles/profile_picker_web_contents_host.h"
#include "chrome/browser/ui/webui/intro/intro_ui.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/base/signin_metrics.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "content/public/browser/web_ui.h"
#include "google_apis/gaia/core_account_id.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_WIN)
#include "chrome/browser/win/taskbar_manager.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/shell_util.h"
#endif

namespace {

constexpr base::TimeDelta kDefaultBrowserCheckTimeout = base::Seconds(2);

const signin_metrics::AccessPoint kAccessPoint =
    signin_metrics::AccessPoint::kForYouFre;

enum class ShowDefaultBrowserStep {
  // The default browser step should be shown as appropriate.
  kYes,
  // The default browser step should be skipped.
  kNo,
  // The default browser step should be shown even if we normally should skip
  // it, example because of policies or the current default state.
  kForce
};

bool IsDefaultBrowserDisabledByPolicy() {
  const PrefService::Preference* pref =
      g_browser_process->local_state()->FindPreference(
          prefs::kDefaultBrowserSettingEnabled);
  CHECK(pref);
  DCHECK(pref->GetValue()->is_bool());
  return pref->IsManaged() && !pref->GetValue()->GetBool();
}

void MaybeLogSetAsDefaultSuccess(
    shell_integration::DefaultWebClientState state) {
  if (state == shell_integration::IS_DEFAULT) {
    base::UmaHistogramEnumeration(
        "ProfilePicker.FirstRun.DefaultBrowser",
        DefaultBrowserChoice::kSuccessfullySetAsDefault);
  }
}

bool IsPostIdentityStep(ProfileManagementFlowController::Step step) {
  switch (step) {
    case ProfileManagementFlowController::Step::kUnknown:
    case ProfileManagementFlowController::Step::kFinishFlow:
    case ProfileManagementFlowController::Step::kFinishSamlSignin:
    case ProfileManagementFlowController::Step::kPostSignInFlow:
    case ProfileManagementFlowController::Step::kProfilePicker:
    case ProfileManagementFlowController::Step::kAccountSelection:
    case ProfileManagementFlowController::Step::kIntro:
    case ProfileManagementFlowController::Step::kReauth:
      return false;
    case ProfileManagementFlowController::Step::kDefaultBrowser:
    case ProfileManagementFlowController::Step::kSearchEngineChoice:
      return true;
  }
}

#if BUILDFLAG(IS_WIN)
void PinToTaskbarResult(bool result) {
  base::UmaHistogramBoolean("Windows.TaskbarPinFromFRESucceeded", result);
}
#endif  // BUILDFLAG(IS_WIN)

class IntroStepController : public ProfileManagementStepController {
 public:
  explicit IntroStepController(
      ProfilePickerWebContentsHost* host,
      base::RepeatingCallback<void(IntroChoice)> choice_callback,
      bool enable_animations)
      : ProfileManagementStepController(host),
        intro_url_(BuildIntroURL(enable_animations)),
        choice_callback_(std::move(choice_callback)) {}

  ~IntroStepController() override = default;

  void Show(StepSwitchFinishedCallback step_shown_callback,
            bool reset_state) override {
    if (reset_state) {
      // Reload the WebUI in the picker contents.
      host()->ShowScreenInPickerContents(
          intro_url_, base::BindOnce(&IntroStepController::OnIntroLoaded,
                                     weak_ptr_factory_.GetWeakPtr(),
                                     std::move(step_shown_callback)));
    } else {
      // Just switch to the picker contents, which should be showing this step.
      DCHECK_EQ(intro_url_, host()->GetPickerContents()->GetURL());
      host()->ShowScreenInPickerContents(
          GURL(), base::BindOnce(std::move(step_shown_callback.value()), true));
      ExpectSigninChoiceOnce();
    }
  }

  void OnNavigateBackRequested() override {
    NavigateBackInternal(host()->GetPickerContents());
  }

  void OnIntroLoaded(StepSwitchFinishedCallback step_shown_callback) {
    std::move(step_shown_callback.value()).Run(/*success=*/true);

    ExpectSigninChoiceOnce();
  }

 private:
  GURL BuildIntroURL(bool enable_animations) {
    std::string url_string = chrome::kChromeUIIntroURL;
    if (!enable_animations) {
      url_string += "?noAnimations";
    }
    return GURL(url_string);
  }

  void ExpectSigninChoiceOnce() {
    auto* intro_ui = host()
                         ->GetPickerContents()
                         ->GetWebUI()
                         ->GetController()
                         ->GetAs<IntroUI>();
    DCHECK(intro_ui);
    intro_ui->SetSigninChoiceCallback(
        IntroSigninChoiceCallback(choice_callback_));
  }

  const GURL intro_url_;

  // `choice_callback_` is a `Repeating` one to be able to advance the flow more
  // than once in case we navigate back to this step.
  const base::RepeatingCallback<void(IntroChoice)> choice_callback_;

  base::WeakPtrFactory<IntroStepController> weak_ptr_factory_{this};
};

class DefaultBrowserStepController : public ProfileManagementStepController {
 public:
  explicit DefaultBrowserStepController(
      ProfilePickerWebContentsHost* host,
      base::OnceClosure step_completed_callback)
      : ProfileManagementStepController(host),
        step_completed_callback_(std::move(step_completed_callback)) {}

  ~DefaultBrowserStepController() override {
    if (step_completed_callback_) {
      base::UmaHistogramEnumeration("ProfilePicker.FirstRun.DefaultBrowser",
                                    DefaultBrowserChoice::kQuit);
    }
  }

  void Show(StepSwitchFinishedCallback step_shown_callback,
            bool reset_state) override {
    CHECK(!step_shown_callback->is_null());
    CHECK(reset_state);
    const ShowDefaultBrowserStep show_screen = ShouldShowScreen();

    if (show_screen == ShowDefaultBrowserStep::kNo) {
      // Mark that this step was skipped and proceed with the next one.
      std::move(step_shown_callback.value()).Run(false);
      std::move(step_completed_callback_).Run();
      return;
    }

    step_shown_callback_ = std::move(step_shown_callback);
    navigation_finished_closure_ = base::BindOnce(
        &DefaultBrowserStepController::OnLoadFinished, base::Unretained(this));

    show_default_browser_screen_callback_ =
        base::BindOnce(&DefaultBrowserStepController::ShowDefaultBrowserScreen,
                       weak_ptr_factory_.GetWeakPtr());

    // If the feature is set to forced, show the step even if it's already
    // the default browser.
    if (show_screen == ShowDefaultBrowserStep::kForce) {
      std::move(show_default_browser_screen_callback_).Run();
      return;
    }

    // Set up the timeout closure, in case checking if the browser is already
    // set as default isn't completed before the timeout.
    default_browser_check_timeout_closure_.Reset(base::BindOnce(
        &DefaultBrowserStepController::OnDefaultBrowserCheckTimeout,
        weak_ptr_factory_.GetWeakPtr()));
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE, default_browser_check_timeout_closure_.callback(),
        kDefaultBrowserCheckTimeout);

    // Check if browser is already set as default. If it isn't, show default
    // browser step.
    base::MakeRefCounted<shell_integration::DefaultBrowserWorker>()
        ->StartCheckIsDefault(base::BindOnce(
            &DefaultBrowserStepController::OnDefaultBrowserCheckFinished,
            weak_ptr_factory_.GetWeakPtr()));
  }

  void OnNavigateBackRequested() override {
    // Do nothing, navigating back is not allowed.
  }

 private:
  void OnLoadFinished() {
    auto* intro_ui = host()
                         ->GetPickerContents()
                         ->GetWebUI()
                         ->GetController()
                         ->GetAs<IntroUI>();
    CHECK(intro_ui);
    if (can_pin_) {
      intro_ui->SetCanPinToTaskbar(can_pin_);
    }
    intro_ui->SetDefaultBrowserCallback(DefaultBrowserCallback(
        base::BindOnce(&DefaultBrowserStepController::OnStepCompleted,
                       // WeakPtr: The callback is given to the WebUIController,
                       // owned by the webcontents, which lifecycle is not
                       // bounded by a single step.
                       weak_ptr_factory_.GetWeakPtr())));
  }

  void OnCanPinToTaskbarResult(bool can_pin) {
    can_pin_ = can_pin;
    std::move(show_default_browser_screen_callback_).Run();
  }

  void OnStepCompleted(DefaultBrowserChoice choice) {
    if (choice == DefaultBrowserChoice::kClickSetAsDefault) {
      CHECK(!IsDefaultBrowserDisabledByPolicy());
      // The worker pointer is reference counted. While it is running, sequence
      // it runs on will hold references to it and it will be automatically
      // freed once all its tasks have finished.
      base::MakeRefCounted<shell_integration::DefaultBrowserWorker>()
          ->StartSetAsDefault(base::BindOnce(&MaybeLogSetAsDefaultSuccess));
#if BUILDFLAG(IS_WIN)
      if (can_pin_) {
        browser_util::PinAppToTaskbar(
            ShellUtil::GetBrowserModelId(InstallUtil::IsPerUserInstall()),
            base::BindOnce(&PinToTaskbarResult));
      }
#endif  // BUILDFLAG(IS_WIN)
    }
    base::UmaHistogramEnumeration("ProfilePicker.FirstRun.DefaultBrowser",
                                  choice);
    CHECK(step_completed_callback_);
    std::move(step_completed_callback_).Run();
  }

  void OnDefaultBrowserCheckFinished(
      shell_integration::DefaultWebClientState state) {
    if (!show_default_browser_screen_callback_) {
      return;
    }

    // Cancel timeout.
    default_browser_check_timeout_closure_.Cancel();

    bool should_show_default_browser_step =
        state == shell_integration::NOT_DEFAULT ||
        state == shell_integration::OTHER_MODE_IS_DEFAULT;

    if (should_show_default_browser_step) {
#if BUILDFLAG(IS_WIN)
      // Check if Chrome can pin to the taskbar, which is an async call. When it
      // finishes, the result will be recorded and
      // `show_default_browser_screen_callback_` will be run.
      if (base::FeatureList::IsEnabled(
              features::kOfferPinToTaskbarInFirstRunExperience)) {
        browser_util::ShouldOfferToPin(
            ShellUtil::GetBrowserModelId(InstallUtil::IsPerUserInstall()),
            base::BindOnce(
                &DefaultBrowserStepController::OnCanPinToTaskbarResult,
                weak_ptr_factory_.GetWeakPtr()));
        return;
      }
#endif  // BUILDFLAG(IS_WIN)
      std::move(show_default_browser_screen_callback_).Run();
    } else {
      // Mark that this step was skipped and proceed with the next one.
      std::move(step_shown_callback_.value()).Run(false);
      std::move(step_completed_callback_).Run();
    }
  }

  void OnDefaultBrowserCheckTimeout() {
    if (!step_completed_callback_) {
      return;
    }

    base::UmaHistogramEnumeration("ProfilePicker.FirstRun.DefaultBrowser",
                                  DefaultBrowserChoice::kNotShownOnTimeout);
    // Mark that this step was skipped and proceed with the next one.
    std::move(step_shown_callback_.value()).Run(false);
    std::move(step_completed_callback_).Run();
  }

  void ShowDefaultBrowserScreen() {
    if (navigation_finished_closure_) {
      if (!step_shown_callback_->is_null()) {
        // Notify the previous step before executing this step's initialization
        // callback.
        navigation_finished_closure_ =
            base::BindOnce(std::move(step_shown_callback_.value()), true)
                .Then(std::move(navigation_finished_closure_));
      }

      host()->ShowScreenInPickerContents(
          GURL(chrome::kChromeUIIntroDefaultBrowserURL),
          std::move(navigation_finished_closure_));
    }
  }

  ShowDefaultBrowserStep ShouldShowScreen() const {
    bool should_show_default_browser_step =
        // Check for policies.
        !IsDefaultBrowserDisabledByPolicy() &&
        // Some releases cannot be set as default browser.
        shell_integration::CanSetAsDefaultBrowser();

    if (!should_show_default_browser_step) {
      return ShowDefaultBrowserStep::kNo;
    }

    // The default browser step should be shown only on Windows. We only show it
    // on Windows because we display a dialog before the FRE on MacOS and Linux
    // to ask the user about the default browser. If it's forced, it should be
    // shown on the other platforms for testing.
#if BUILDFLAG(IS_WIN)
    return ShowDefaultBrowserStep::kYes;
#else
    // Non-Windows platforms should not show this unless forced (e.g.
    // command line)
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    return command_line->HasSwitch(switches::kForceFreDefaultBrowserStep)
               ? ShowDefaultBrowserStep::kForce
               : ShowDefaultBrowserStep::kNo;
#endif  // BUILDFLAG(IS_WIN)
  }

  // Callback to be executed when the step is completed.
  base::OnceClosure step_completed_callback_;
  StepSwitchFinishedCallback step_shown_callback_;

  // Whether or not Chrome be pinned to the taskbar.
  bool can_pin_ = false;

  base::OnceClosure navigation_finished_closure_;
  base::CancelableOnceClosure default_browser_check_timeout_closure_;
  base::OnceClosure show_default_browser_screen_callback_;
  base::WeakPtrFactory<DefaultBrowserStepController> weak_ptr_factory_{this};
};

using IdentityStepsCompletedCallback =
    base::OnceCallback<void(PostHostClearedCallback post_host_cleared_callback,
                            bool is_continue_callback)>;

// Instance allowing `TurnSyncOnHelper` to drive the interface in the
// `kPostSignIn` step.
//
// Not following the `*SignedInFlowController` naming pattern to avoid confusion
// with `*StepController` and `*FlowController` that we also have here.
// `ProfilePickerSignedInFlowController` should eventually be renamed.
class FirstRunPostSignInAdapter : public ProfilePickerSignedInFlowController {
 public:
  FirstRunPostSignInAdapter(
      ProfilePickerWebContentsHost* host,
      Profile* profile,
      const CoreAccountInfo& account_info,
      std::unique_ptr<content::WebContents> contents,
      IdentityStepsCompletedCallback step_completed_callback)
      : ProfilePickerSignedInFlowController(host,
                                            profile,
                                            account_info,
                                            std::move(contents),
                                            kAccessPoint,
                                            /*profile_color=*/std::nullopt),
        step_completed_callback_(std::move(step_completed_callback)) {
    DCHECK(step_completed_callback_);
  }

  void Init(StepSwitchFinishedCallback step_switch_callback) override {
    // Stop with the sign-in navigation and show a spinner instead. The spinner
    // will be shown until TurnSyncOnHelper figures out whether it's a
    // managed account and whether sync is disabled by policies (which in some
    // cases involves fetching policies and can take a couple of seconds).
    host()->ShowScreen(contents(), GetSyncConfirmationURL(/*loading=*/true),
                       /*navigation_finished_closure=*/base::OnceClosure());

    ProfilePickerSignedInFlowController::Init(std::move(step_switch_callback));
  }

  PostHostClearedCallback CreateSupervisedUserIphCallback() {
    return PostHostClearedCallback(base::BindOnce([](Browser* browser) {
      CHECK(browser);
      BrowserView* browser_view =
          BrowserView::GetBrowserViewForBrowser(browser);
      if (!browser_view) {
        return;
      }
      browser_view->MaybeShowSupervisedUserProfileSignInIPH();
    }));
  }

  void FinishAndOpenBrowserInternal(
      PostHostClearedCallback post_host_cleared_callback,
      bool is_continue_callback) override {
    // Do nothing if this has already been called. Note that this can get called
    // first time from a special case handling (such as the Settings link) and
    // than second time when the TurnSyncOnHelper finishes.
    if (!step_completed_callback_) {
      return;
    }
    // The supervised user IPH should be called after the present
    // post_host_cleared_callback which finishes the browser creation.
    auto combined_callback =
        CombineCallbacks<PostHostClearedCallback, Browser*>(
            std::move(post_host_cleared_callback),
            CreateSupervisedUserIphCallback());
    std::move(step_completed_callback_)
        .Run(std::move(combined_callback), is_continue_callback);
  }

 private:
  IdentityStepsCompletedCallback step_completed_callback_;
};

}  // namespace

std::unique_ptr<ProfileManagementStepController> CreateIntroStep(
    ProfilePickerWebContentsHost* host,
    base::RepeatingCallback<void(IntroChoice)> choice_callback,
    bool enable_animations) {
  return std::make_unique<IntroStepController>(host, std::move(choice_callback),
                                               enable_animations);
}

FirstRunFlowControllerDice::FirstRunFlowControllerDice(
    ProfilePickerWebContentsHost* host,
    ClearHostClosure clear_host_callback,
    Profile* profile,
    ProfilePicker::FirstRunExitedCallback first_run_exited_callback)
    : ProfileManagementFlowControllerImpl(host,
                                          std::move(clear_host_callback),
                                          /*flow_type_string=*/"FREFlow"),
      profile_(profile),
      first_run_exited_callback_(std::move(first_run_exited_callback)) {
  DCHECK(profile_);
  DCHECK(first_run_exited_callback_);
}

FirstRunFlowControllerDice::~FirstRunFlowControllerDice() {
  if (!first_run_exited_callback_) {
    // As the callback gets executed by `PreFinishWithBrowser()`,
    // this indicates that `FinishFlowAndRunInBrowser()` has already run.
    return;
  }

  // The core of the flow stops at the sync opt in step. Considering the flow
  // completed means among other things that we would always proceed to the
  // browser when closing the host view.
  bool is_core_flow_completed = IsPostIdentityStep(current_step());

  if (is_core_flow_completed) {
    RunFinishFlowCallback();
  } else {
    // TODO(crbug.com/40276516): Revisit the enum value name for kQuitAtEnd.
    std::move(first_run_exited_callback_)
        .Run(ProfilePicker::FirstRunExitStatus::kQuitAtEnd);
  }
}

void FirstRunFlowControllerDice::Init() {
  RegisterStep(
      Step::kIntro,
      CreateIntroStep(host(),
                      base::BindRepeating(
                          &FirstRunFlowControllerDice::HandleIntroSigninChoice,
                          weak_ptr_factory_.GetWeakPtr()),
                      /*enable_animations=*/true));
  SwitchToStep(Step::kIntro, /*reset_state=*/true);

  signin_metrics::LogSignInOffered(
      kAccessPoint, signin_metrics::PromoAction::
                        PROMO_ACTION_NEW_ACCOUNT_NO_EXISTING_ACCOUNT);
}

void FirstRunFlowControllerDice::CancelPostSignInFlow() {
  // Called when the user declines enterprise management. Unfortunately, for
  // some technical and historical reasons, management is already marked as
  // accepted before we show the prompt. So here we need to revert it.
  // Currently we remove the account to match the behaviour from the profile
  // creation flow.
  // TODO(crbug.com/40067597): Look into letting the user keep their account.
  signin::ClearProfileWithManagedAccounts(profile_);

  HandleIdentityStepsCompleted(profile_, PostHostClearedCallback(),
                               /*is_continue_callback=*/false);
}

void FirstRunFlowControllerDice::PickProfile(
    const base::FilePath& profile_path,
    ProfilePicker::ProfilePickingArgs args,
    base::OnceCallback<void(bool)> pick_profile_complete_callback) {
  NOTREACHED() << "FRE is not expected to handle this flow";
}

bool FirstRunFlowControllerDice::PreFinishWithBrowser() {
  DCHECK(first_run_exited_callback_);
  std::move(first_run_exited_callback_)
      .Run(ProfilePicker::FirstRunExitStatus::kCompleted);
  return true;
}

void FirstRunFlowControllerDice::HandleIntroSigninChoice(IntroChoice choice) {
  if (choice == IntroChoice::kQuit) {
    // The view is getting destroyed. The class destructor will handle the rest.
    return;
  }

  if (choice == IntroChoice::kContinueWithoutAccount) {
    HandleIdentityStepsCompleted(profile_, PostHostClearedCallback(),
                                 /*is_continue_callback=*/false);
    return;
  }

  SwitchToIdentityStepsFromAccountSelection(
      /*step_switch_finished_callback=*/StepSwitchFinishedCallback(),
      kAccessPoint, profile_->GetPath());
}

std::unique_ptr<ProfilePickerSignedInFlowController>
FirstRunFlowControllerDice::CreateSignedInFlowController(
    Profile* signed_in_profile,
    const CoreAccountInfo& account_info,
    std::unique_ptr<content::WebContents> contents) {
  DCHECK_EQ(profile_, signed_in_profile);
  return std::make_unique<FirstRunPostSignInAdapter>(
      host(), signed_in_profile, account_info, std::move(contents),
      base::BindOnce(&FirstRunFlowControllerDice::HandleIdentityStepsCompleted,
                     // Unretained ok: the callback is passed to a step that
                     // the `this` will own and outlive.
                     base::Unretained(this), base::Unretained(profile_)));
}

void FirstRunFlowControllerDice::RunFinishFlowCallback() {
  if (finish_flow_callback_) {
    std::move(finish_flow_callback_).Run();
  }
}

base::queue<ProfileManagementFlowController::Step>
FirstRunFlowControllerDice::RegisterPostIdentitySteps(
    PostHostClearedCallback post_host_cleared_callback) {
  base::queue<ProfileManagementFlowController::Step> post_identity_steps;

  finish_flow_callback_ = base::BindOnce(
      &FirstRunFlowControllerDice::FinishFlowAndRunInBrowser,
      base::Unretained(this),
      // Unretained ok: the steps register a profile keep-alive and
      // will be alive until this callback runs.
      base::Unretained(profile_), std::move(post_host_cleared_callback));

  auto search_engine_choice_step_completed =
      base::BindOnce(&FirstRunFlowControllerDice::AdvanceToNextPostIdentityStep,
                     base::Unretained(this));
  SearchEngineChoiceDialogService* search_engine_choice_dialog_service =
      SearchEngineChoiceDialogServiceFactory::GetForProfile(profile_);
  RegisterStep(
      Step::kSearchEngineChoice,
      ProfileManagementStepController::CreateForSearchEngineChoice(
          host(), search_engine_choice_dialog_service,
          host()->GetPickerContents(),
          SearchEngineChoiceDialogService::EntryPoint::kFirstRunExperience,
          std::move(search_engine_choice_step_completed)));
  post_identity_steps.emplace(
      ProfileManagementFlowController::Step::kSearchEngineChoice);

  auto default_browser_promo_step_completed =
      base::BindOnce(&FirstRunFlowControllerDice::AdvanceToNextPostIdentityStep,
                     base::Unretained(this));
  RegisterStep(Step::kDefaultBrowser,
               std::make_unique<DefaultBrowserStepController>(
                   host(), std::move(default_browser_promo_step_completed)));
  post_identity_steps.emplace(
      ProfileManagementFlowController::Step::kDefaultBrowser);

  RegisterStep(
      Step::kFinishFlow,
      ProfileManagementStepController::CreateForFinishFlowAndRunInBrowser(
          host(),
          base::BindOnce(&FirstRunFlowControllerDice::RunFinishFlowCallback,
                         base::Unretained(this))));
  post_identity_steps.emplace(
      ProfileManagementFlowController::Step::kFinishFlow);
  return post_identity_steps;
}