File: preinstalled_web_app_manager.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; 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 (1167 lines) | stat: -rw-r--r-- 46,436 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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
// Copyright 2018 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/web_applications/preinstalled_web_app_manager.h"

#include <iterator>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <variant>
#include <vector>

#include "base/auto_reset.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/concurrent_closures.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_reader.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/observer_list.h"
#include "base/scoped_observation.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "build/build_config.h"
// TODO(crbug.com/40251079): Remove or at least isolate circular dependencies on
// app service by moving this code to //c/b/web_applications/adjustments, or
// flip entire dependency so web_applications depends on app_service.
#include "chrome/browser/apps/app_service/app_service_proxy.h"  // nogncheck
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"  // nogncheck
#include "chrome/browser/apps/user_type_filter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/web_applications/callback_utils.h"
#include "chrome/browser/web_applications/extension_status_utils.h"
#include "chrome/browser/web_applications/externally_managed_app_manager.h"
#include "chrome/browser/web_applications/file_utils_wrapper.h"
#include "chrome/browser/web_applications/preinstalled_app_install_features.h"
#include "chrome/browser/web_applications/preinstalled_web_app_config_utils.h"
#include "chrome/browser/web_applications/preinstalled_web_app_utils.h"
#include "chrome/browser/web_applications/preinstalled_web_apps/preinstalled_web_apps.h"
#include "chrome/browser/web_applications/user_uninstalled_preinstalled_web_app_prefs.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/browser/web_applications/web_app_install_utils.h"
#include "chrome/browser/web_applications/web_app_management_type.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_ui_manager.h"
#include "chrome/browser/web_applications/web_app_utils.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "components/ntp_tiles/most_visited_sites.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "components/services/app_service/public/cpp/types_util.h"
#include "components/version_info/version_info.h"
#include "components/webapps/browser/install_result_code.h"
#include "components/webapps/common/constants.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/common/constants.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/events/devices/input_device_event_observer.h"
#include "ui/events/devices/touchscreen_device.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_CHROMEOS)
// TODO(http://b/333583704): Revert CL which added this include after migration.
#include "ash/constants/ash_switches.h"
#include "ash/constants/web_app_id_constants.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chromeos/ash/components/report/utils/time_utils.h"
#include "chromeos/ash/experiences/arc/arc_util.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

namespace web_app {

namespace {

bool g_skip_startup_for_testing_ = false;
bool g_bypass_awaiting_dependencies_for_testing_ = false;
bool g_bypass_offline_manifest_requirement_for_testing_ = false;
bool g_override_previous_user_uninstall_for_testing_ = false;
const base::Value::List* g_configs_for_testing = nullptr;
FileUtilsWrapper* g_file_utils_for_testing = nullptr;

const char kHistogramMigrationDisabledReason[] =
    "WebApp.Preinstalled.DisabledReason";

// These values are reported to UMA, do not modify them.
enum class DisabledReason {
  kNotDisabled = 0,
  kUninstallPreinstalledAppsNotEnabled = 1,
  kUninstallUserTypeNotAllowed = 2,
  kUninstallGatedFeatureNotEnabled = 3,
  kIgnoreGatedFeatureNotEnabled = 4,
  kIgnoreArcAvailable = 5,
  kIgnoreTabletFormFactor = 6,
  kIgnoreNotNewUser = 7,
  kIgnoreNotPreviouslyPreinstalled = 8,
  kUninstallReplacingAppBlockedByPolicy = 9,
  kUninstallReplacingAppForceInstalled = 10,
  kInstallReplacingAppStillInstalled = 11,
  kUninstallDefaultAppAndAppsToReplaceUninstalled = 12,
  kIgnoreReplacingAppUninstalledByUser = 13,
  kIgnoreStylusRequired = 14,
  kInstallOverridePreviousUserUninstall = 15,
  kIgnoreStylusRequiredNoDeviceData = 16,
  kIgnorePreviouslyUninstalledByUser = 17,
  kMaxValue = kIgnorePreviouslyUninstalledByUser
};

struct LoadedConfig {
  base::Value contents;
  base::FilePath file;
};

struct LoadedConfigs {
  std::vector<LoadedConfig> configs;
  std::vector<std::string> errors;
};

std::optional<bool> HasStylusEnabledTouchscreen() {
  return DeviceHasStylusEnabledTouchscreen();
}

LoadedConfigs LoadConfigsBlocking(
    const std::vector<base::FilePath>& config_dirs) {
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);

  LoadedConfigs result;
  base::FilePath::StringType extension(FILE_PATH_LITERAL(".json"));

  for (const auto& config_dir : config_dirs) {
    base::FileEnumerator json_files(config_dir,
                                    false,  // Recursive.
                                    base::FileEnumerator::FILES);
    for (base::FilePath file = json_files.Next(); !file.empty();
         file = json_files.Next()) {
      if (!file.MatchesExtension(extension)) {
        continue;
      }

      JSONFileValueDeserializer deserializer(file);
      std::string error_msg;
      std::unique_ptr<base::Value> app_config =
          deserializer.Deserialize(nullptr, &error_msg);
      if (!app_config) {
        result.errors.push_back(base::StrCat(
            {file.AsUTF8Unsafe(), " was not valid JSON: ", error_msg}));
        VLOG(1) << result.errors.back();
        continue;
      }
      result.configs.push_back(
          {.contents = std::move(*app_config), .file = file});
    }
  }
  return result;
}

struct ParsedConfigs {
  std::vector<ExternalInstallOptions> options_list;
  std::vector<std::string> errors;
};

ParsedConfigs ParseConfigsBlocking(LoadedConfigs loaded_configs) {
  ParsedConfigs result;
  result.errors = std::move(loaded_configs.errors);

  scoped_refptr<FileUtilsWrapper> file_utils =
      g_file_utils_for_testing ? base::WrapRefCounted(g_file_utils_for_testing)
                               : base::MakeRefCounted<FileUtilsWrapper>();

  for (const LoadedConfig& loaded_config : loaded_configs.configs) {
    OptionsOrError parse_result =
        ParseConfig(*file_utils, loaded_config.file.DirName(),
                    loaded_config.file, loaded_config.contents);
    if (ExternalInstallOptions* options =
            std::get_if<ExternalInstallOptions>(&parse_result)) {
      result.options_list.push_back(std::move(*options));
    } else {
      result.errors.push_back(std::move(std::get<std::string>(parse_result)));
      VLOG(1) << result.errors.back();
    }
  }

  return result;
}

struct SynchronizeDecision {
  enum {
    // Ensures the web app preinstall gets removed.
    kUninstall,

    // Ensures the web app gets preinstalled.
    kInstall,

    // Leaves the web app preinstall state alone.
    // Prefer kIgnore over kUninstall in most cases of disabling a config as
    // uninstalling can have permanent consequences for users when bugs are hit.
    // See crbug.com/1393284 and crbug.com/1363004 for past incidents.
    kIgnore,
  } type;
  // TODO(crbug.com/40253925): Rename DisabledReason to
  // SynchronizeDecisionReason since it applies to every install decision.
  DisabledReason reason;
  std::string log;
};

SynchronizeDecision GetSynchronizeDecision(
    const ExternalInstallOptions& options,
    Profile* profile,
    WebAppRegistrar* registrar,
    bool preinstalled_apps_enabled_in_prefs,
    bool is_new_user,
    const std::string& user_type,
    size_t& corrupt_user_uninstall_prefs_count) {
  DCHECK(registrar);

  // This function encodes the exceptions to the standard preinstalled web app
  // configs; situations in which the preinstall should be removed, added or be
  // left untouched.
  //
  // The priority of these decisions is ordered:
  // kUninstall > kInstall > kIgnore > kInstall (default).

  /////////////////////////
  // kUninstall conditions.
  /////////////////////////

  if (!preinstalled_apps_enabled_in_prefs) {
    return {
        .type = SynchronizeDecision::kUninstall,
        .reason = DisabledReason::kUninstallPreinstalledAppsNotEnabled,
        .log = base::StrCat({options.install_url.spec(),
                             " uninstall by preinstalled_apps pref setting."})};
  }

  // Remove if not applicable to current user type.
  DCHECK_GT(options.user_type_allowlist.size(), 0u);
  if (!base::Contains(options.user_type_allowlist, user_type)) {
    return {.type = SynchronizeDecision::kUninstall,
            .reason = DisabledReason::kUninstallUserTypeNotAllowed,
            .log = base::StrCat({options.install_url.spec(),
                                 " uninstall for user type: ", user_type})};
  }

  // Remove if gated on a disabled feature.
  if (options.gate_on_feature &&
      !IsPreinstalledAppInstallFeatureEnabled(*options.gate_on_feature)) {
    return {.type = SynchronizeDecision::kUninstall,
            .reason = DisabledReason::kUninstallGatedFeatureNotEnabled,
            .log = base::StrCat({options.install_url.spec(),
                                 " uninstall because feature is disabled: ",
                                 *options.gate_on_feature})};
  }

  // Remove if any apps to replace are blocked or force installed by admin
  // policy.
  for (const webapps::AppId& app_id : options.uninstall_and_replace) {
    if (extensions::IsExtensionBlockedByPolicy(profile, app_id)) {
      return {.type = SynchronizeDecision::kUninstall,
              .reason = DisabledReason::kUninstallReplacingAppBlockedByPolicy,
              .log = base::StrCat({options.install_url.spec(),
                                   " uninstall due to admin policy blocking "
                                   "replacement Extension."})};
    }
    std::u16string reason;
    if (extensions::IsExtensionForceInstalled(profile, app_id, &reason)) {
      return {
          .type = SynchronizeDecision::kUninstall,
          .reason = DisabledReason::kUninstallReplacingAppForceInstalled,
          .log = base::StrCat(
              {options.install_url.spec(),
               " uninstall due to admin policy force installing replacement "
               "Extension: ",
               base::UTF16ToUTF8(reason)})};
    }
  }
#if !BUILDFLAG(IS_CHROMEOS)
  // Remove if it's a default app and the apps to replace are not installed and
  // default extension apps are not performing new installation.
  if (options.gate_on_feature && !options.uninstall_and_replace.empty() &&
      !extensions::DidPreinstalledAppsPerformNewInstallation(profile)) {
    for (const webapps::AppId& app_id : options.uninstall_and_replace) {
      // First time migration and the app to replace is uninstalled as it passed
      // the last code block. Save the information that the app was
      // uninstalled by user.
      if (!WasMigrationRun(profile, *options.gate_on_feature)) {
        if (extensions::IsPreinstalledAppId(app_id)) {
          MarkPreinstalledAppAsUninstalled(profile, app_id);
          return {.type = SynchronizeDecision::kUninstall,
                  .reason = DisabledReason::
                      kUninstallDefaultAppAndAppsToReplaceUninstalled,
                  .log = base::StrCat(
                      {options.install_url.spec(),
                       "uninstall because its default app and apps to replace ",
                       "were uninstalled."})};
        }
      } else {
        // Not first time migration, can't determine if the app to replace is
        // uninstalled by user as the migration is already run, use the pref
        // saved in first migration.
        if (WasPreinstalledAppUninstalled(profile, app_id)) {
          return {.type = SynchronizeDecision::kUninstall,
                  .reason = DisabledReason::
                      kUninstallDefaultAppAndAppsToReplaceUninstalled,
                  .log = base::StrCat(
                      {options.install_url.spec(),
                       "uninstall because its default app and apps to replace "
                       "were uninstalled."})};
        }
      }
    }
  }
#endif  // !BUILDFLAG(IS_CHROMEOS)

  ///////////////////////
  // kInstall conditions.
  ///////////////////////

  bool was_previously_uninstalled_by_user =
      UserUninstalledPreinstalledWebAppPrefs(profile->GetPrefs())
          .LookUpAppIdByInstallUrl(options.install_url)
          .has_value();
  if (options.override_previous_user_uninstall &&
      was_previously_uninstalled_by_user) {
    return {
        .type = SynchronizeDecision::kInstall,
        .reason = DisabledReason::kInstallOverridePreviousUserUninstall,
        .log = base::StrCat({options.install_url.spec(),
                             " install overrides previous user uninstall."})};
  }

  // Ensure install if any apps to replace are installed as installation
  // includes uninstall_and_replace-ing the specified apps.
  for (const webapps::AppId& app_id : options.uninstall_and_replace) {
    if (extensions::IsExtensionInstalled(profile, app_id)) {
      return {
          .type = SynchronizeDecision::kInstall,
          .reason = DisabledReason::kInstallReplacingAppStillInstalled,
          .log = base::StrCat({options.install_url.spec(),
                               " install to replace existing Chrome app."})};
    }
  }

  //////////////////////
  // kIgnore conditions.
  //////////////////////

  if (was_previously_uninstalled_by_user) {
    return {.type = SynchronizeDecision::kIgnore,
            .reason = DisabledReason::kIgnorePreviouslyUninstalledByUser,
            .log = base::StrCat(
                {options.install_url.spec(),
                 " ignore because previously uninstalled by user"})};
  }

  // This option means to ignore if the feature flag is not enabled and leave
  // any existing installations alone.
  if (options.gate_on_feature_or_installed &&
      !IsPreinstalledAppInstallFeatureEnabled(
          *options.gate_on_feature_or_installed)) {
    return {.type = SynchronizeDecision::kIgnore,
            .reason = DisabledReason::kIgnoreGatedFeatureNotEnabled,
            .log = base::StrCat(
                {options.install_url.spec(), " ignore because the feature ",
                 *options.gate_on_feature_or_installed, " is disabled"})};
  }

#if BUILDFLAG(IS_CHROMEOS)
  if (options.disable_if_arc_supported && arc::IsArcAvailable()) {
    return {.type = SynchronizeDecision::kIgnore,
            .reason = DisabledReason::kIgnoreArcAvailable,
            .log = base::StrCat({options.install_url.spec(),
                                 " ignore because ARC is available."})};
  }

  if (options.disable_if_tablet_form_factor &&
      ash::switches::IsTabletFormFactor()) {
    return {.type = SynchronizeDecision::kIgnore,
            .reason = DisabledReason::kIgnoreTabletFormFactor,
            .log = base::StrCat({options.install_url.spec(),
                                 " ignore because device is tablet."})};
  }
#endif  // BUILDFLAG(IS_CHROMEOS)

  if (options.only_for_new_users && !is_new_user) {
    return {.type = SynchronizeDecision::kIgnore,
            .reason = DisabledReason::kIgnoreNotNewUser,
            .log = base::StrCat({options.install_url.spec(),
                                 " ignore because user is not new."})};
  }

  // This option means to ignore installations of the config, it came from a
  // time before SynchronizeDecision::kIgnore was added and so is worded
  // differently.
  if (options.only_if_previously_preinstalled) {
    return {.type = SynchronizeDecision::kIgnore,
            .reason = DisabledReason::kIgnoreNotPreviouslyPreinstalled,
            .log = base::StrCat(
                {options.install_url.spec(),
                 " ignore by config (only_if_previously_preinstalled)."})};
  }

  // Ignore if any apps to replace were previously uninstalled.
  for (const webapps::AppId& app_id : options.uninstall_and_replace) {
    if (extensions::IsExternalExtensionUninstalled(profile, app_id)) {
      return {.type = SynchronizeDecision::kIgnore,
              .reason = DisabledReason::kIgnoreReplacingAppUninstalledByUser,
              .log = base::StrCat(
                  {options.install_url.spec(),
                   " ignore because apps to replace were uninstalled."})};
    }
  }

  // Only install if device has a built-in touch screen with stylus support.
  if (options.disable_if_touchscreen_with_stylus_not_supported) {
    std::optional<bool> has_stylus = HasStylusEnabledTouchscreen();

    if (!has_stylus.has_value()) {
      return {.type = SynchronizeDecision::kIgnore,
              .reason = DisabledReason::kIgnoreStylusRequiredNoDeviceData,
              .log = base::StrCat(
                  {options.install_url.spec(),
                   " ignore because touchscreen device information is "
                   "unavailable"})};
    }

    if (!has_stylus.value()) {
      return {.type = SynchronizeDecision::kIgnore,
              .reason = DisabledReason::kIgnoreStylusRequired,
              .log = base::StrCat(
                  {options.install_url.spec(),
                   " ignore because the device does not have a built-in "
                   "touchscreen with stylus support."})};
    }
  }

  ////////////////////
  // Default scenario.
  ////////////////////

  return {
      .type = SynchronizeDecision::kInstall,
      .reason = DisabledReason::kNotDisabled,
      .log = base::StrCat({options.install_url.spec(), " regular install"})};
}

bool IsReinstallPastMilestoneNeededSinceLastSync(
    const PrefService& prefs,
    int force_reinstall_for_milestone) {
  std::string last_preinstall_synchronize_milestone =
      prefs.GetString(prefs::kWebAppsLastPreinstallSynchronizeVersion);

  return IsReinstallPastMilestoneNeeded(last_preinstall_synchronize_milestone,
                                        version_info::GetMajorVersionNumber(),
                                        force_reinstall_for_milestone);
}

bool ShouldForceReinstall(const ExternalInstallOptions& options,
                          const PrefService& prefs,
                          const WebAppRegistrar& registrar) {
  if (options.force_reinstall_for_milestone &&
      IsReinstallPastMilestoneNeededSinceLastSync(
          prefs, options.force_reinstall_for_milestone.value())) {
    return true;
  }

  // TODO(crbug.com/40261748): Add metrics for this event.
  const WebApp* app = registrar.LookUpAppByInstallSourceInstallUrl(
      WebAppManagement::Type::kDefault, options.install_url);
  if (app && LooksLikePlaceholder(*app)) {
    return true;
  }

  return false;
}

#if BUILDFLAG(IS_CHROMEOS)
// Modifies ExternalInstallOptions to be force_reinstall = true if they are
// already installed but their uninstall_and_replace apps are also installed,
// this is to re-trigger the migration logic that happens at the end of
// installation. May not do anything depending on feature flags and platform.
void MaybeForceInstallForRemigration(
    std::vector<ExternalInstallOptions>* options_list,
    Profile* profile,
    const WebAppRegistrar& registrar) {
  bool always_migrate_calculator = base::FeatureList::IsEnabled(
      features::kPreinstalledWebAppAlwaysMigrateCalculator);
  bool always_migrate =
      base::FeatureList::IsEnabled(features::kPreinstalledWebAppAlwaysMigrate);
  if (!always_migrate_calculator && !always_migrate) {
    return;
  }

  // Record Calculator remigration metrics.
  bool calculator_web_app_installed =
      registrar.IsInstalledByDefaultManagement(ash::kCalculatorAppId);
  bool calculator_chrome_app_installed = extensions::IsExtensionInstalled(
      profile, extension_misc::kCalculatorAppId);
  base::UmaHistogramBoolean(
      "WebApp.Preinstalled.CalculatorForceMigration.WebAppInstalled",
      calculator_web_app_installed);
  base::UmaHistogramBoolean(
      "WebApp.Preinstalled.CalculatorForceMigration."
      "ChromeAppAndWebAppInstalled",
      calculator_chrome_app_installed && calculator_web_app_installed);
  base::UmaHistogramBoolean(
      "WebApp.Preinstalled.CalculatorForceMigration.ChromeAppNoWebAppInstalled",
      calculator_chrome_app_installed && !calculator_web_app_installed);

  bool any_migration_needed = false;
  bool calculator_migration_needed = false;
  for (ExternalInstallOptions& options : *options_list) {
    // Ignore preinstalled apps that aren't currently installed.
    if (!registrar.LookUpAppByInstallSourceInstallUrl(
            WebAppManagement::Type::kDefault, options.install_url)) {
      continue;
    }

    // Force migration if corresponding Chrome app is installed, according to
    // feature flags.
    for (const std::string& app_id : options.uninstall_and_replace) {
      bool migration_needed = false;
      if (extensions::IsExtensionInstalled(profile, app_id)) {
        if (always_migrate_calculator &&
            app_id == extension_misc::kCalculatorAppId) {
          calculator_migration_needed = true;
          migration_needed = true;
        }

        if (always_migrate) {
          migration_needed = true;
        }
      }

      if (migration_needed) {
        any_migration_needed = true;
        options.force_reinstall = true;
        break;
      }
    }
  }

  base::UmaHistogramBoolean("WebApp.Preinstalled.ChromeAppMigrationNeeded",
                            any_migration_needed);
  base::UmaHistogramBoolean(
      "WebApp.Preinstalled.CalculatorForceMigration.MigrationTriggered",
      calculator_migration_needed);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

}  // namespace

class PreinstalledWebAppManager::DeviceDataInitializedEvent
    : public ui::InputDeviceEventObserver {
 public:
  DeviceDataInitializedEvent() = default;
  DeviceDataInitializedEvent(const DeviceDataInitializedEvent&) = delete;
  DeviceDataInitializedEvent& operator=(const DeviceDataInitializedEvent&) =
      delete;

  // Posts a `task` to be run once ui::DeviceDataManager has complete device
  // lists. If device lists are already complete, or DeviceDataManager is not
  // available, the task will be posted immediately.
  void Post(base::OnceClosure task);

 private:
  // ui::InputDeviceEventObserver:
  void OnDeviceListsComplete() override;

  // Task to run once ui::DeviceDataManager initialization is complete.
  base::OnceClosure initialized_task_;

  base::ScopedObservation<ui::DeviceDataManager, ui::InputDeviceEventObserver>
      device_data_observation_{this};
};

void PreinstalledWebAppManager::DeviceDataInitializedEvent::Post(
    base::OnceClosure task) {
  // DeviceDataManager does not exist on all platforms, but on platforms where
  // it exists, it's always created early in startup, so HasInstance() is a
  // reliable indicator of availability. However, loading device information is
  // asynchronous and may not have completed by this point.
  if (!ui::DeviceDataManager::HasInstance() ||
      ui::DeviceDataManager::GetInstance()->AreDeviceListsComplete()) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,
                                                             std::move(task));
  } else {
    DCHECK(!device_data_observation_.IsObserving());
    device_data_observation_.Observe(ui::DeviceDataManager::GetInstance());
    initialized_task_ = std::move(task);
  }
}

void PreinstalledWebAppManager::DeviceDataInitializedEvent::
    OnDeviceListsComplete() {
  std::move(initialized_task_).Run();
  device_data_observation_.Reset();
}

const char* PreinstalledWebAppManager::kHistogramEnabledCount =
    "WebApp.Preinstalled.EnabledCount";
const char* PreinstalledWebAppManager::kHistogramDisabledCount =
    "WebApp.Preinstalled.DisabledCount";
const char* PreinstalledWebAppManager::kHistogramConfigErrorCount =
    "WebApp.Preinstalled.ConfigErrorCount";
const char*
    PreinstalledWebAppManager::kHistogramCorruptUserUninstallPrefsCount =
        "WebApp.Preinstalled.CorruptUserUninstallPrefsCount";
const char* PreinstalledWebAppManager::kHistogramInstallResult =
    "Webapp.InstallResult.Default";
const char* PreinstalledWebAppManager::kHistogramInstallCount =
    "WebApp.Preinstalled.InstallCount";
const char* PreinstalledWebAppManager::kHistogramUninstallTotalCount =
    "WebApp.Preinstalled.UninstallTotalCount";
const char* PreinstalledWebAppManager::kHistogramUninstallSourceRemovedCount =
    "WebApp.Preinstalled.UninstallSourceRemovedCount";
const char* PreinstalledWebAppManager::kHistogramUninstallAppRemovedCount =
    "WebApp.Preinstalled.UninstallAppRemovedCount";
const char* PreinstalledWebAppManager::kHistogramUninstallAndReplaceCount =
    "WebApp.Preinstalled.UninstallAndReplaceCount";
const char*
    PreinstalledWebAppManager::kHistogramAppToReplaceStillInstalledCount =
        "WebApp.Preinstalled.AppToReplaceStillInstalledCount";
const char* PreinstalledWebAppManager::
    kHistogramAppToReplaceStillDefaultInstalledCount =
        "WebApp.Preinstalled.AppToReplaceStillDefaultInstalledCount";
const char* PreinstalledWebAppManager::
    kHistogramAppToReplaceStillInstalledInShelfCount =
        "WebApp.Preinstalled.AppToReplaceStillInstalledInShelfCount";

void PreinstalledWebAppManager::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterStringPref(prefs::kWebAppsLastPreinstallSynchronizeVersion,
                               "");
  registry->RegisterListPref(webapps::kWebAppsMigratedPreinstalledApps);
  registry->RegisterListPref(prefs::kWebAppsDidMigrateDefaultChromeApps);
  registry->RegisterListPref(prefs::kWebAppsUninstalledDefaultChromeApps);
}

// static
base::AutoReset<bool> PreinstalledWebAppManager::SkipStartupForTesting() {
  return {&g_skip_startup_for_testing_, true};
}

// static
base::AutoReset<bool>
PreinstalledWebAppManager::BypassAwaitingDependenciesForTesting() {
  return {&g_bypass_awaiting_dependencies_for_testing_, true};
}

// static
base::AutoReset<bool>
PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting() {
  return {&g_bypass_offline_manifest_requirement_for_testing_, true};
}

// static
base::AutoReset<bool>
PreinstalledWebAppManager::OverridePreviousUserUninstallConfigForTesting() {
  return {&g_override_previous_user_uninstall_for_testing_, true};
}

// static
base::AutoReset<const base::Value::List*>
PreinstalledWebAppManager::SetConfigsForTesting(
    const base::Value::List* configs) {
  return {&g_configs_for_testing, configs, nullptr};
}

// static
base::AutoReset<FileUtilsWrapper*>
PreinstalledWebAppManager::SetFileUtilsForTesting(
    FileUtilsWrapper* file_utils) {
  return {&g_file_utils_for_testing, file_utils, nullptr};
}

PreinstalledWebAppManager::PreinstalledWebAppManager(Profile* profile)
    : profile_(profile),
      device_data_initialized_event_(
          std::make_unique<DeviceDataInitializedEvent>()) {
  if (base::FeatureList::IsEnabled(features::kRecordWebAppDebugInfo)) {
    debug_info_ = std::make_unique<DebugInfo>();
  }
}

PreinstalledWebAppManager::~PreinstalledWebAppManager() {
  for (auto& observer : observers_) {
    observer.OnDestroyed();
  }
}

void PreinstalledWebAppManager::SetProvider(base::PassKey<WebAppProvider>,
                                            WebAppProvider& provider) {
  provider_ = &provider;
}

void PreinstalledWebAppManager::Start(base::OnceClosure on_done) {
  DCHECK(provider_);
  if (g_skip_startup_for_testing_ || skip_startup_for_testing_) {  // IN-TEST
    std::move(on_done).Run();                                      // IN-TEST
    return;                                                        // IN-TEST
  }

  LoadAndSynchronize(
      base::BindOnce(&PreinstalledWebAppManager::OnStartUpTaskCompleted,
                     weak_ptr_factory_.GetWeakPtr())
          .Then(std::move(on_done)));
}

void PreinstalledWebAppManager::LoadForTesting(ConsumeInstallOptions callback) {
  Load(std::move(callback));
}

void PreinstalledWebAppManager::AddObserver(
    PreinstalledWebAppManager::Observer* observer) {
  observers_.AddObserver(observer);
}

void PreinstalledWebAppManager::RemoveObserver(
    PreinstalledWebAppManager::Observer* observer) {
  observers_.RemoveObserver(observer);
}

void PreinstalledWebAppManager::SetSkipStartupSynchronizeForTesting(  // IN-TEST
    bool skip_startup) {
  skip_startup_for_testing_ = skip_startup;  // IN-TEST
}

void PreinstalledWebAppManager::LoadAndSynchronizeForTesting(
    SynchronizeCallback callback) {
  LoadAndSynchronize(std::move(callback));
}

void PreinstalledWebAppManager::LoadAndSynchronize(
    SynchronizeCallback callback) {
  base::OnceClosure load_and_synchronize = base::BindOnce(
      &PreinstalledWebAppManager::Load, weak_ptr_factory_.GetWeakPtr(),
      base::BindOnce(&PreinstalledWebAppManager::Synchronize,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));

  if (g_bypass_awaiting_dependencies_for_testing_) {
    std::move(load_and_synchronize).Run();
    return;
  }

  base::ConcurrentClosures concurrent;
  device_data_initialized_event_->Post(concurrent.CreateClosure());
  // Make sure ExtensionSystem is ready to know if default apps new installation
  // will be performed.
  extensions::OnExtensionSystemReady(profile_, concurrent.CreateClosure());
  std::move(concurrent).Done(std::move(load_and_synchronize));
}

void PreinstalledWebAppManager::Load(ConsumeInstallOptions callback) {
  bool preinstalling_enabled =
      base::FeatureList::IsEnabled(features::kPreinstalledWebAppInstallation);

  if (!preinstalling_enabled) {
    std::move(callback).Run({});
    return;
  }

  auto weak_ptr = weak_ptr_factory_.GetWeakPtr();
  RunChainedCallbacks(
      base::BindOnce(&PreinstalledWebAppManager::LoadDeviceInfo, weak_ptr),
      base::BindOnce(&PreinstalledWebAppManager::CacheDeviceInfo, weak_ptr),
      base::BindOnce(&PreinstalledWebAppManager::LoadConfigs, weak_ptr),
      base::BindOnce(&PreinstalledWebAppManager::ParseConfigs, weak_ptr),
      base::BindOnce(&PreinstalledWebAppManager::PostProcessConfigs, weak_ptr),
      std::move(callback));
}

// TODO(http://b/333583704): Revert CL which added this method after migration.
void PreinstalledWebAppManager::LoadDeviceInfo(ConsumeDeviceInfo callback) {
#if BUILDFLAG(IS_CHROMEOS)
  // This needs to be consistent with echo_private_api to avoid inconsistency
  // between promo offering and eligibility.
  DeviceInfo device_info;
  device_info.oobe_timestamp = ash::report::utils::GetFirstActiveWeek();
  std::move(callback).Run(device_info);
#else  // BUILDFLAG(IS_CHROMEOS)
  std::move(callback).Run(DeviceInfo());
#endif
}

// TODO(http://b/333583704): Revert CL which added this method after migration.
void PreinstalledWebAppManager::CacheDeviceInfo(
    CacheDeviceInfoCallback callback,
    DeviceInfo device_info) {
  device_info_ = std::move(device_info);
  std::move(callback).Run();
}

void PreinstalledWebAppManager::LoadConfigs(ConsumeLoadedConfigs callback) {
  if (g_configs_for_testing) {
    LoadedConfigs loaded_configs;
    for (const base::Value& config : *g_configs_for_testing) {
      auto file = base::FilePath(FILE_PATH_LITERAL("test.json"));
      if (test::GetPreinstalledWebAppConfigDirForTesting()) {  //  IN-TEST
        file = test::GetPreinstalledWebAppConfigDirForTesting()->Append(
            file);  // IN-TEST
      }

      loaded_configs.configs.push_back(
          {.contents = config.Clone(), .file = file});
    }
    std::move(callback).Run(std::move(loaded_configs));
    return;
  }

  if (PreinstalledWebAppsDisabled()) {
    std::move(callback).Run({});
    return;
  }

  base::FilePath config_dir = GetPreinstalledWebAppConfigDir(profile_);
  if (config_dir.empty()) {
    std::move(callback).Run({});
    return;
  }

  std::vector<base::FilePath> config_dirs = {config_dir};
  base::FilePath extra_config_dir =
      GetPreinstalledWebAppExtraConfigDir(profile_);
  if (!extra_config_dir.empty()) {
    config_dirs.push_back(extra_config_dir);
  }

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&LoadConfigsBlocking, std::move(config_dirs)),
      std::move(callback));
}

void PreinstalledWebAppManager::ParseConfigs(ConsumeParsedConfigs callback,
                                             LoadedConfigs loaded_configs) {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&ParseConfigsBlocking, std::move(loaded_configs)),
      std::move(callback));
}

void PreinstalledWebAppManager::PostProcessConfigs(
    ConsumeInstallOptions callback,
    ParsedConfigs parsed_configs) {
  // Add hard coded configs.
  for (ExternalInstallOptions& options :
       GetPreinstalledWebApps(*profile_, device_info_)) {
    parsed_configs.options_list.push_back(std::move(options));
  }

  // Allow tests to bypass kDisableDefaultApps with an allow list.
  if (GetPreinstallUrlAllowListForTesting().has_value()) {
    std::erase_if(
        parsed_configs.options_list, [](const ExternalInstallOptions& options) {
          return !GetPreinstallUrlAllowListForTesting().value().contains(
              options.install_url);
        });
  }

  // Set common install options.
  for (ExternalInstallOptions& options : parsed_configs.options_list) {
    DCHECK_EQ(options.install_source, ExternalInstallSource::kExternalDefault);

    options.require_manifest = true;

#if BUILDFLAG(IS_CHROMEOS)
    // On Chrome OS the "quick launch bar" is the shelf pinned apps.
    // This is configured in `GetDefaultPinnedAppsForFormFactor()` instead of
    // here to ensure a specific order is deployed.
    options.add_to_quick_launch_bar = false;
#else   // BUILDFLAG(IS_CHROMEOS)
    if (!g_bypass_offline_manifest_requirement_for_testing_) {
      // Non-Chrome OS platforms are not permitted to fetch the web app install
      // URLs during start up.
      DCHECK(options.app_info_factory);
      options.only_use_app_info_factory = true;
    }

    // Preinstalled web apps should not have OS shortcuts of any kind outside of
    // Chrome OS.
    options.add_to_applications_menu = false;
    options.add_to_search = false;
    options.add_to_management = false;
    options.add_to_desktop = false;
    options.add_to_quick_launch_bar = false;
    options.install_without_os_integration = true;
#endif  // BUILDFLAG(IS_CHROMEOS)

    if (g_override_previous_user_uninstall_for_testing_) {
      options.override_previous_user_uninstall = true;
    }
  }

  // TODO(crbug.com/40747215): Move this constant into some shared constants.h
  // file.
  bool preinstalled_apps_enabled_in_prefs =
      profile_->GetPrefs()->GetString(prefs::kPreinstalledApps) == "install";
  bool is_new_user = IsNewUser();
  std::string user_type = apps::DetermineUserType(profile_);
  size_t disabled_count = 0;
  size_t corrupt_user_uninstall_prefs_count = 0;
  std::erase_if(
      parsed_configs.options_list, [&](const ExternalInstallOptions& options) {
        SynchronizeDecision install_decision = GetSynchronizeDecision(
            options, profile_, &provider_->registrar_unsafe(),
            preinstalled_apps_enabled_in_prefs, is_new_user, user_type,
            corrupt_user_uninstall_prefs_count);
        base::UmaHistogramEnumeration(kHistogramMigrationDisabledReason,
                                      install_decision.reason);

        switch (install_decision.type) {
          case SynchronizeDecision::kUninstall:
            VLOG(1) << install_decision.log;
            ++disabled_count;
            if (debug_info_) {
              debug_info_->uninstall_configs.emplace_back(
                  options, std::move(install_decision.log));
            }
            return true;

          case SynchronizeDecision::kInstall:
            if (debug_info_) {
              debug_info_->install_configs.emplace_back(
                  options, std::move(install_decision.log));
            }
            return false;

          case SynchronizeDecision::kIgnore:
            if (debug_info_) {
              debug_info_->ignore_configs.emplace_back(
                  options, std::move(install_decision.log));
            }
            // These configs get passed to SynchronizeInstalledApps() which has
            // no concept of kIgnore, only ensuring installation or
            // uninstallation based on presence/absence of the config. In order
            // for the config to be ignored (as in no installation or
            // uninstallation taking place) the config presence needs to match
            // whether the install_source + install_url is already present in
            // the installed web apps.
            return !provider_->registrar_unsafe()
                        .LookUpAppByInstallSourceInstallUrl(
                            WebAppManagement::Type::kDefault,
                            options.install_url);
        }
      });

  if (debug_info_) {
    debug_info_->parse_errors = parsed_configs.errors;
  }

  for (ExternalInstallOptions& options : parsed_configs.options_list) {
    if (ShouldForceReinstall(options, *profile_->GetPrefs(),
                             provider_->registrar_unsafe())) {
      options.force_reinstall = true;
    }
  }

#if BUILDFLAG(IS_CHROMEOS)
  MaybeForceInstallForRemigration(&parsed_configs.options_list, profile_.get(),
                                  provider_->registrar_unsafe());
#endif

  base::UmaHistogramCounts100(kHistogramEnabledCount,
                              parsed_configs.options_list.size());
  base::UmaHistogramCounts100(kHistogramDisabledCount, disabled_count);
  base::UmaHistogramCounts100(kHistogramConfigErrorCount,
                              parsed_configs.errors.size());
  base::UmaHistogramCounts100(kHistogramCorruptUserUninstallPrefsCount,
                              corrupt_user_uninstall_prefs_count);

  std::move(callback).Run(parsed_configs.options_list);
}

void PreinstalledWebAppManager::Synchronize(
    ExternallyManagedAppManager::SynchronizeCallback callback,
    std::vector<ExternalInstallOptions> desired_apps_install_options) {
  DCHECK(provider_);

  std::set<InstallUrl> desired_preferred_apps_for_supported_links;
  std::map<InstallUrl, std::vector<webapps::AppId>> desired_uninstalls;
  for (const auto& entry : desired_apps_install_options) {
    if (entry.is_preferred_app_for_supported_links) {
      desired_preferred_apps_for_supported_links.insert(entry.install_url);
    }
    if (!entry.uninstall_and_replace.empty()) {
      desired_uninstalls.emplace(entry.install_url,
                                 entry.uninstall_and_replace);
    }
  }

  provider_->externally_managed_app_manager().SynchronizeInstalledApps(
      std::move(desired_apps_install_options),
      ExternalInstallSource::kExternalDefault,
      base::BindOnce(&PreinstalledWebAppManager::OnExternalWebAppsSynchronized,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(desired_preferred_apps_for_supported_links),
                     std::move(desired_uninstalls)));
}

void PreinstalledWebAppManager::OnExternalWebAppsSynchronized(
    ExternallyManagedAppManager::SynchronizeCallback callback,
    std::set<InstallUrl> desired_preferred_apps_for_supported_links,
    std::map<InstallUrl, std::vector<webapps::AppId>> desired_uninstalls,
    std::map<InstallUrl, ExternallyManagedAppManager::InstallResult>
        install_results,
    std::map<InstallUrl, webapps::UninstallResultCode> uninstall_results) {
  // Note that we are storing the Chrome version (milestone number) instead of a
  // "has synchronised" bool in order to do version update specific logic.
  profile_->GetPrefs()->SetString(
      prefs::kWebAppsLastPreinstallSynchronizeVersion,
      version_info::GetMajorVersionNumber());

  DCHECK(
      apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile_));
  auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile_);

  size_t uninstall_and_replace_count = 0;
  size_t app_to_replace_still_installed_count = 0;
  size_t app_to_replace_still_default_installed_count = 0;
  size_t app_to_replace_still_installed_in_shelf_count = 0;

  for (const auto& [url, result] : install_results) {
    base::UmaHistogramEnumeration(kHistogramInstallResult, result.code);
    if (result.did_uninstall_and_replace) {
      ++uninstall_and_replace_count;
    }

    if (!IsSuccess(result.code)) {
      continue;
    }

    DCHECK(result.app_id.has_value());

    // Do not set as the preferred app for supported links if the app is
    // already installed as the user may have already updated their preference.
    if (result.code != webapps::InstallResultCode::kSuccessAlreadyInstalled &&
        desired_preferred_apps_for_supported_links.contains(url)) {
      proxy->SetSupportedLinksPreference(*result.app_id);
    }

    auto iter = desired_uninstalls.find(url);
    if (iter == desired_uninstalls.end()) {
      continue;
    }

    for (const webapps::AppId& replace_id : iter->second) {
      // We mark the app as migrated to a web app as long as the
      // installation was successful, even if the previous app was not
      // installed. This ensures we properly re-install apps if the
      // migration feature is rolled back.
      MarkAppAsMigratedToWebApp(profile_, replace_id, /*was_migrated=*/true);

      // Track whether the app to replace is still present. This is
      // possibly due to getting reinstalled by the user or by Chrome app
      // sync. See https://crbug.com/1266234 for context.
      if (proxy &&
          result.code == webapps::InstallResultCode::kSuccessAlreadyInstalled) {
        bool is_installed = false;
        proxy->AppRegistryCache().ForOneApp(
            replace_id, [&is_installed](const apps::AppUpdate& app) {
              is_installed = apps_util::IsInstalled(app.Readiness());
            });

        if (!is_installed) {
          continue;
        }

        ++app_to_replace_still_installed_count;

        if (extensions::IsExtensionDefaultInstalled(profile_, replace_id)) {
          ++app_to_replace_still_default_installed_count;
        }

        if (provider_->ui_manager().CanAddAppToQuickLaunchBar()) {
          if (provider_->ui_manager().IsAppInQuickLaunchBar(
                  result.app_id.value())) {
            ++app_to_replace_still_installed_in_shelf_count;
          }
        }
      }
    }
  }

  size_t uninstall_source_removed_count = 0;
  size_t uninstall_app_removed_count = 0;

  for (const auto& [url, result] : uninstall_results) {
    if (result == webapps::UninstallResultCode::kInstallSourceRemoved) {
      ++uninstall_source_removed_count;
    } else if (result == webapps::UninstallResultCode::kAppRemoved) {
      ++uninstall_app_removed_count;
    }
  }

  base::UmaHistogramCounts100(kHistogramInstallCount, install_results.size());
  base::UmaHistogramCounts100(kHistogramUninstallTotalCount,
                              uninstall_results.size());
  base::UmaHistogramCounts100(kHistogramUninstallSourceRemovedCount,
                              uninstall_source_removed_count);
  base::UmaHistogramCounts100(kHistogramUninstallAppRemovedCount,
                              uninstall_app_removed_count);
  base::UmaHistogramCounts100(kHistogramUninstallAndReplaceCount,
                              uninstall_and_replace_count);

  base::UmaHistogramCounts100(kHistogramAppToReplaceStillInstalledCount,
                              app_to_replace_still_installed_count);
  base::UmaHistogramCounts100(kHistogramAppToReplaceStillDefaultInstalledCount,
                              app_to_replace_still_default_installed_count);
  base::UmaHistogramCounts100(kHistogramAppToReplaceStillInstalledInShelfCount,
                              app_to_replace_still_installed_in_shelf_count);

  SetMigrationRun(profile_, "MigrateDefaultChromeAppToWebAppsGSuite", true);
  SetMigrationRun(profile_, "MigrateDefaultChromeAppToWebAppsNonGSuite", true);
  if (uninstall_and_replace_count > 0) {
    for (auto& observer : observers_) {
      observer.OnMigrationRun();
    }
  }

  if (callback) {
    std::move(callback).Run(std::move(install_results),
                            std::move(uninstall_results));
  }
}

void PreinstalledWebAppManager::OnStartUpTaskCompleted(
    std::map<InstallUrl, ExternallyManagedAppManager::InstallResult>
        install_results,
    std::map<InstallUrl, webapps::UninstallResultCode> uninstall_results) {
  if (debug_info_) {
    debug_info_->is_start_up_task_complete = true;
    debug_info_->install_results = std::move(install_results);
    debug_info_->uninstall_results = std::move(uninstall_results);
  }
}

bool PreinstalledWebAppManager::IsNewUser() {
  PrefService* prefs = profile_->GetPrefs();
  return prefs->GetString(prefs::kWebAppsLastPreinstallSynchronizeVersion)
      .empty();
}

PreinstalledWebAppManager::DebugInfo::DebugInfo() = default;

PreinstalledWebAppManager::DebugInfo::~DebugInfo() = default;

}  //  namespace web_app