File: download_bubble_update_service.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1416 lines) | stat: -rw-r--r-- 52,195 bytes parent folder | download | duplicates (3)
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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
// Copyright 2023 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/download/bubble/download_bubble_update_service.h"

#include <iterator>
#include <optional>
#include <tuple>

#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/content_index/content_index_provider_impl.h"
#include "chrome/browser/download/bubble/download_bubble_ui_controller.h"
#include "chrome/browser/download/bubble/download_bubble_update_service_factory.h"
#include "chrome/browser/download/bubble/download_bubble_utils.h"
#include "chrome/browser/download/bubble/download_display_controller.h"
#include "chrome/browser/download/download_core_service.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/download/download_crx_util.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_item_web_app_data.h"
#include "chrome/browser/download/download_ui_model.h"
#include "chrome/browser/download/offline_item_model_manager.h"
#include "chrome/browser/download/offline_item_model_manager_factory.h"
#include "chrome/browser/download/offline_item_utils.h"
#include "chrome/browser/offline_items_collection/offline_content_aggregator_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "components/download/content/public/all_download_item_notifier.h"
#include "components/download/public/common/download_item.h"
#include "components/offline_items_collection/core/offline_content_provider.h"
#include "components/offline_items_collection/core/offline_item.h"
#include "content/public/browser/download_manager.h"

namespace {

using ::offline_items_collection::ContentId;
using ::offline_items_collection::OfflineContentProvider;
using ::offline_items_collection::OfflineItem;
using ::offline_items_collection::OfflineItemState;
using DownloadState = download::DownloadItem::DownloadState;
using DownloadUIModelPtr = DownloadUIModel::DownloadUIModelPtr;
using ItemSortKey = DownloadBubbleUpdateService::ItemSortKey;
template <typename Id, typename Item>
using IterMap = DownloadBubbleUpdateService::IterMap<Id, Item>;
using ProgressInfo = DownloadDisplay::ProgressInfo;
template <typename Item>
using SortedItems = DownloadBubbleUpdateService::SortedItems<Item>;

// Show up to 30 items in total by default.
constexpr size_t kDefaultMaxNumItemsToShow = 30u;
// Cache a few more items of each type than we will return from
// GetAllModelsToDisplay. This gives us some wiggle room and makes it more
// likely that we'll return enough items before backfilling.
constexpr size_t kDefaultExtraItemsToCache = 30u;
// Amount of time to show an item in the bubble. Items older than this duration
// ago will be pruned.
constexpr base::TimeDelta kShowItemInBubbleDuration = base::Hours(24);
// Don't send the "download started" notification for an extension or theme
// (crx) download until 2 seconds after it has begun. If it is a small download
// that finishes in under 2 seconds, the download UI does not show at all. If it
// is a large download that takes longer than 2 seconds, show the UI so that the
// user knows Chrome is working on it.
constexpr base::TimeDelta kCrxShowNewItemDelay = base::Seconds(2);
// Limit the size of the |delayed_crx_guids_| set so it doesn't grow
// unboundedly. It is unlikely that the user would have 20 active crx downloads
// simultaneously.
constexpr int kMaxDelayedCrxGuids = 20;

template <typename Item>
ItemSortKey::State GetState(const Item& item) {
  if (IsItemInProgress(item)) {
    return IsItemPaused(item) ? ItemSortKey::kInProgressPaused
                              : ItemSortKey::kInProgressActive;
  }
  return ItemSortKey::kNotInProgress;
}

template <typename Item>
ItemSortKey GetSortKey(const Item& item) {
  return ItemSortKey{GetState(item), GetItemStartTime(item)};
}

// Helper to get an iterator to the last element in the cache. The cache
// must not be empty.
template <typename Item>
SortedItems<Item>::const_iterator GetLastIter(const SortedItems<Item>& cache) {
  CHECK(!cache.empty());
  auto it = cache.end();
  return std::prev(it);
}

// Returns the earliest creation time for which we will show items in the
// bubble.
base::Time GetCutoffTime() {
  return base::Time::Now() - kShowItemInBubbleDuration;
}

// Updates the count of received vs total bytes. Returns whether progress is
// certain.
bool AddItemProgress(int64_t item_received_bytes,
                     int64_t item_total_bytes,
                     int& in_progress_items,
                     int64_t& received_bytes,
                     int64_t& total_bytes) {
  ++in_progress_items;
  if (item_total_bytes <= 0) {
    // Progress is uncertain: there may or may not be more data coming down this
    // pipe.
    return false;
  }
  received_bytes += item_received_bytes;
  total_bytes += item_total_bytes;
  return true;
}

bool ShouldIncludeModel(const DownloadUIModel* model, base::Time cutoff_time) {
  return DownloadUIModelIsRecent(model, cutoff_time) &&
         model->ShouldShowInBubble();
}

// Returns whether |model| was eligible to be added to |models|, regardless of
// whether it was actually added.
bool MaybeAddModel(DownloadUIModelPtr model,
                   base::Time cutoff_time,
                   size_t max_num_models,
                   std::vector<DownloadUIModelPtr>& models) {
  if (!ShouldIncludeModel(model.get(), cutoff_time)) {
    model->SetActionedOn(true);
    return false;
  }
  if (models.size() < max_num_models) {
    models.push_back(std::move(model));
  }
  return true;
}

// For GetAllModelsToDisplay()'s iteration over the merged caches, don't stop
// until all models have been processed.
bool NeverStop() {
  return false;
}

// `update_is_for_model` is whether the current call to this function was
// triggered on behalf of `model`.
void UpdateInfoForModel(const DownloadUIModel& model,
                        bool update_is_for_model,
                        base::Time cutoff_time,
                        DownloadBubbleDisplayInfo& info) {
  if (!ShouldIncludeModel(&model, cutoff_time)) {
    return;
  }
  ++info.all_models_size;
  if (model.GetDangerType() == download::DOWNLOAD_DANGER_TYPE_ASYNC_SCANNING &&
      model.GetState() != download::DownloadItem::CANCELLED) {
    info.has_deep_scanning = true;
  }
  if (!model.WasActionedOn()) {
    info.has_unactioned = true;
  }
  if (IsModelInProgress(&model)) {
    ++info.in_progress_count;
    if (model.IsPaused()) {
      ++info.paused_count;
    }
  } else {
    base::Time cur_completed_time = model.GetEndTime();
    if (cur_completed_time.is_null() && update_is_for_model &&
        model.GetState() != download::DownloadItem::CANCELLED) {
      // Given that we consider dangerous/insecure downloads to be complete, the
      // completion time should reflect the time they were marked as
      // dangerous/insecure. Since download is still technically IN_PROGRESS in
      // this scenario and thus has a null end time, we just use the current
      // time based on the assumption that a download in a dangerous/insecure
      // state does not receive further updates besides cancellation.
      cur_completed_time = base::Time::Now();
    }
    info.last_completed_time =
        std::max(info.last_completed_time, cur_completed_time);
  }
}

bool BrowserMatchesWebAppData(const Browser* browser,
                              const DownloadItemWebAppData* data) {
  return data != nullptr
             ? web_app::AppBrowserController::IsForWebApp(browser, data->id())
             : !web_app::AppBrowserController::IsWebApp(browser);
}

}  // namespace

bool DownloadBubbleUpdateService::ItemSortKey::operator<(
    const DownloadBubbleUpdateService::ItemSortKey& other) const {
  if (state < other.state) {
    return true;
  } else if (state > other.state) {
    return false;
  }
  return start_time > other.start_time;
}

bool DownloadBubbleUpdateService::ItemSortKey::operator>(
    const DownloadBubbleUpdateService::ItemSortKey& other) const {
  return !(*this == other || *this < other);
}

// static
DownloadBubbleUpdateService::ItemSortKey
DownloadBubbleUpdateService::ItemSortKey::Min() {
  return ItemSortKey{kInProgressActive, base::Time::Max()};
}

DownloadBubbleUpdateService::CacheManager::CacheManager(
    DownloadBubbleUpdateService* update_service)
    : update_service_(update_service) {
  CHECK(update_service);
}

DownloadBubbleUpdateService::CacheManager::~CacheManager() = default;

DownloadBubbleUpdateService::DownloadBubbleUpdateService(Profile* profile)
    : profile_(profile),
      original_profile_(IsProfileOtr() ? profile_->GetOriginalProfile()
                                       : nullptr),
      main_cache_(this) {
  offline_content_provider_observation_.Observe(
      OfflineContentAggregatorFactory::GetForKey(profile_->GetProfileKey()));
}

DownloadBubbleUpdateService::~DownloadBubbleUpdateService() = default;

void DownloadBubbleUpdateService::Shutdown() {
  offline_content_provider_observation_.Reset();
  is_shut_down_ = true;
}

bool DownloadBubbleUpdateService::IsShutDown() const {
  return is_shut_down_;
}

bool DownloadBubbleUpdateService::IsProfileOtr() const {
  return profile_->IsOffTheRecord();
}

size_t DownloadBubbleUpdateService::GetMaxNumItemsToShow() const {
  size_t max =
      max_num_items_to_show_for_testing_.value_or(kDefaultMaxNumItemsToShow);
  CHECK_GE(max, 2u);
  return max;
}

size_t DownloadBubbleUpdateService::GetNumItemsToCache() const {
  return GetMaxNumItemsToShow() +
         extra_items_to_cache_for_testing_.value_or(kDefaultExtraItemsToCache);
}

size_t DownloadBubbleUpdateService::CacheManager::GetMaxNumItemsToShow() const {
  return update_service_->GetMaxNumItemsToShow();
}

size_t DownloadBubbleUpdateService::CacheManager::GetNumItemsToCache() const {
  return update_service_->GetNumItemsToCache();
}

bool DownloadBubbleUpdateService::CacheManager::IsDownloadItemCacheAtMax()
    const {
  CHECK(download_items_.size() <= GetNumItemsToCache());
  return download_items_.size() == GetNumItemsToCache();
}

bool DownloadBubbleUpdateService::CacheManager::IsOfflineItemCacheAtMax()
    const {
  CHECK(offline_items_.size() <= GetNumItemsToCache());
  return offline_items_.size() == GetNumItemsToCache();
}

DownloadBubbleUpdateService::CacheManager&
DownloadBubbleUpdateService::GetCacheForWebApp(const webapps::AppId& app_id) {
  auto it = web_app_caches_.find(app_id);
  if (it == web_app_caches_.end()) {
    // Create a new CacheManager for this |app_id|.
    it = web_app_caches_.emplace(app_id, this).first;
  }
  return it->second;
}

const DownloadBubbleUpdateService::CacheManager*
DownloadBubbleUpdateService::GetExistingCacheForWebApp(
    const webapps::AppId& app_id) const {
  if (auto it = web_app_caches_.find(app_id); it != web_app_caches_.end()) {
    return &it->second;
  }
  return nullptr;
}

DownloadBubbleUpdateService::CacheManager*
DownloadBubbleUpdateService::GetExistingCacheForWebApp(
    const webapps::AppId& app_id) {
  return const_cast<CacheManager*>(
      std::as_const(*this).GetExistingCacheForWebApp(app_id));
}

DownloadBubbleUpdateService::CacheManager&
DownloadBubbleUpdateService::GetCacheForItem(download::DownloadItem* item) {
  auto* web_app_data = DownloadItemWebAppData::Get(item);
  if (web_app_data == nullptr) {
    return main_cache_;
  }
  return GetCacheForWebApp(web_app_data->id());
}

std::vector<DownloadBubbleUpdateService::CacheManager*>
DownloadBubbleUpdateService::GetAllCacheManagers() {
  std::vector<CacheManager*> cache_managers;
  cache_managers.push_back(&main_cache_);
  for (auto& [web_app_id, cache_manager] : web_app_caches_) {
    cache_managers.push_back(&cache_manager);
  }
  return cache_managers;
}

void DownloadBubbleUpdateService::ObserveDownloadHistory() {
  // If OTR, this is the original profile. Otherwise, this is just the profile
  // itself.
  Profile* profile = profile_->GetOriginalProfile();
  if (DownloadCoreService* dcs =
          DownloadCoreServiceFactory::GetForBrowserContext(profile);
      dcs && dcs->GetDownloadHistory()) {
    download_history_observation_.Observe(dcs->GetDownloadHistory());
  }
}

void DownloadBubbleUpdateService::Initialize(
    content::DownloadManager* manager) {
  CHECK(manager);
  CHECK(!download_item_notifier_);

  // This is safe to do here because we know the DownloadManager has been
  // created by now. If we did this earlier, then it might trigger early
  // initialization of the DownloadManager and ChromeDownloadManagerDelegate.
  ObserveDownloadHistory();

  // Assume we have an original profile and it has an OTR profile.
  // If the original profile's DownloadBubbleUpdateService is Initialize()'d
  // already when this function is invoked on the OTR profile's
  // DownloadBubbleUpdateService, we set the OTR profile's
  // DownloadBubbleUpdateService's |original_download_item_notifier_| in the
  // 'if' block below. If the original profile's DownloadBubbleUpdateService is
  // not yet initialized when this function is invoked on the OTR profile's
  // DownloadBubbleUpdateService, we will set the OTR profile's
  // DownloadBubbleUpdateService's |original_download_item_notifier_| when the
  // original profile's DownloadBubbleUpdateService does become Initialize()'d,
  // in the 'else' block below (which will trigger re-intialization of the
  // download item cache).
  if (profile_->IsOffTheRecord()) {
    DownloadBubbleUpdateService* original_update_service =
        DownloadBubbleUpdateServiceFactory::GetForProfile(original_profile_);
    content::DownloadManager* original_download_manager =
        original_update_service ? original_update_service->GetDownloadManager()
                                : nullptr;
    if (original_download_manager) {
      InitializeOriginalNotifier(original_download_manager);
    }
  } else {
    for (Profile* otr_profile : profile_->GetAllOffTheRecordProfiles()) {
      DownloadBubbleUpdateServiceFactory::GetForProfile(otr_profile)
          ->InitializeOriginalNotifier(manager);
    }
  }
  download_item_notifier_ =
      std::make_unique<download::AllDownloadItemNotifier>(manager, this);
  // As long as we have a notifier for this profile, we can initialize the cache
  // with the current profile's downloads. If we get an original manager in the
  // future, we will initialize from scratch at that time.
  InitializeDownloadItemsCache();
  StartInitializeOfflineItemsCache();
}

void DownloadBubbleUpdateService::InitializeOriginalNotifier(
    content::DownloadManager* manager) {
  CHECK(profile_->IsOffTheRecord());
  CHECK(manager);
  if (original_download_item_notifier_) {
    return;
  }
  original_download_item_notifier_ =
      std::make_unique<download::AllDownloadItemNotifier>(manager, this);
  // Reset the download items cache, now that we have an original
  // DownloadManager to pull from.
  if (download_item_notifier_) {
    InitializeDownloadItemsCache();
  }
}

content::DownloadManager* DownloadBubbleUpdateService::GetDownloadManager() {
  return download_item_notifier_ ? download_item_notifier_->GetManager()
                                 : nullptr;
}

bool DownloadBubbleUpdateService::IsInitialized() const {
  return download_item_notifier_ && offline_items_initialized_;
}

bool DownloadBubbleUpdateService::CacheManager::GetAllModelsToDisplay(
    std::vector<DownloadUIModelPtr>& models,
    bool force_backfill_download_items) {
#if DCHECK_IS_ON()
  ConsistencyCheckCaches();
#endif  // DCHECK_IS_ON()

  base::Time cutoff_time = GetCutoffTime();
  models.clear();
  // If the caches are at max capacity, and we prune some items that are too
  // old, we may need to backfill items.
  bool download_items_cache_was_at_max = IsDownloadItemCacheAtMax();
  bool offline_items_cache_was_at_max = IsOfflineItemCacheAtMax();
  bool download_item_pruned = false;
  bool offline_item_pruned = false;

  // Merge the two sorted lists, while pruning the expired items. Since the
  // criteria for pruning requires the model, to avoid unnecessary creation and
  // destruction of models, we collect the models to return and prune items in
  // the same loop iteration.
  IterateOverMergedCaches(
      base::BindRepeating(&DownloadBubbleUpdateService::CacheManager::
                              GetDownloadItemModelToDisplayOrPrune,
                          base::Unretained(this), cutoff_time, std::ref(models),
                          std::ref(download_item_pruned)),
      base::BindRepeating(&DownloadBubbleUpdateService::CacheManager::
                              GetOfflineItemModelToDisplayOrPrune,
                          base::Unretained(this), cutoff_time, std::ref(models),
                          std::ref(offline_item_pruned)),
      base::BindRepeating(&NeverStop));

  CHECK_LE(models.size(), GetMaxNumItemsToShow());

  bool download_items_need_backfill =
      download_item_pruned && download_items_cache_was_at_max;
  bool offline_items_need_backfill =
      offline_item_pruned && offline_items_cache_was_at_max;

  if (download_items_need_backfill) {
    // A key that will sort before any other key.
    ItemSortKey last_download_item_key = ItemSortKey::Min();
    if (!download_items_.empty()) {
      last_download_item_key = GetLastIter(download_items_)->first;
    }
    if (force_backfill_download_items) {
      // Get more items synchronously.
      update_service_->BackfillDownloadItems(last_download_item_key);
      AppendBackfilledDownloadItems(last_download_item_key, cutoff_time,
                                    models);
      download_items_need_backfill = false;
    } else {
      update_service_->StartBackfillDownloadItems(last_download_item_key);
    }
  }

  if (offline_items_need_backfill) {
    // A key that will sort before any other key.
    ItemSortKey last_offline_item_key = ItemSortKey::Min();
    if (!offline_items_.empty()) {
      last_offline_item_key = GetLastIter(offline_items_)->first;
    }
    update_service_->StartBackfillOfflineItems(last_offline_item_key);
  }

#if DCHECK_IS_ON()
  ConsistencyCheckCaches();
#endif  // DCHECK_IS_ON()
  return models.size() == GetMaxNumItemsToShow() ||
         !(download_items_need_backfill || offline_items_need_backfill);
}

void DownloadBubbleUpdateService::CacheManager::
    GetDownloadItemModelToDisplayOrPrune(
        base::Time cutoff_time,
        std::vector<DownloadUIModel::DownloadUIModelPtr>& models,
        bool& download_item_pruned,
        SortedDownloadItems::iterator& download_item_it) {
  if (!MaybeAddDownloadItemModel(download_item_it->second, cutoff_time,
                                 models)) {
    download_item_it = RemoveItemFromCacheByIter(
        download_item_it, download_items_, download_items_iter_map_);
    download_item_pruned = true;
  } else {
    ++download_item_it;
  }
}

void DownloadBubbleUpdateService::CacheManager::
    GetOfflineItemModelToDisplayOrPrune(
        base::Time cutoff_time,
        std::vector<DownloadUIModel::DownloadUIModelPtr>& models,
        bool& offline_item_pruned,
        SortedOfflineItems::iterator& offline_item_it) {
  if (!MaybeAddOfflineItemModel(offline_item_it->second, cutoff_time, models)) {
    offline_item_it = RemoveItemFromCacheByIter(offline_item_it, offline_items_,
                                                offline_items_iter_map_);
    offline_item_pruned = true;
  } else {
    ++offline_item_it;
  }
}

bool DownloadBubbleUpdateService::GetAllModelsToDisplay(
    std::vector<DownloadUIModelPtr>& models,
    const webapps::AppId* web_app_id,
    bool force_backfill_download_items) {
  if (web_app_id == nullptr) {
    return main_cache_.GetAllModelsToDisplay(models,
                                             force_backfill_download_items);
  }
  return GetCacheForWebApp(*web_app_id)
      .GetAllModelsToDisplay(models, force_backfill_download_items);
}

const DownloadBubbleDisplayInfo&
DownloadBubbleUpdateService::CacheManager::GetDisplayInfo() const {
  return display_info_;
}

const DownloadBubbleDisplayInfo& DownloadBubbleUpdateService::GetDisplayInfo(
    const webapps::AppId* web_app_id) {
  if (web_app_id == nullptr) {
    return main_cache_.GetDisplayInfo();
  }
  if (const CacheManager* cache = GetExistingCacheForWebApp(*web_app_id);
      cache != nullptr) {
    return cache->GetDisplayInfo();
  }
  return DownloadBubbleDisplayInfo::EmptyInfo();
}

void DownloadBubbleUpdateService::CacheManager::UpdateDisplayInfo(
    const std::string& updating_for_item) {
#if DCHECK_IS_ON()
  ConsistencyCheckCaches();
#endif  // DCHECK_IS_ON()

  // A new info is constructed from scratch based on the current cache contents.
  DownloadBubbleDisplayInfo info;
  base::Time cutoff_time = GetCutoffTime();

  // Iterate over the two sorted caches (download items and offline items) in
  // combined/merged sorted order. This is done in the same way as in
  // GetAllItemsToDisplay() to ensure that the info most accurately represents
  // the list of items that would be returned from that method.
  IterateOverMergedCaches(
      base::BindRepeating(
          &DownloadBubbleUpdateService::CacheManager::
              UpdateDisplayInfoForDownloadItem,
          base::Unretained(this),
          base::optional_ref<const std::string>(updating_for_item), cutoff_time,
          std::ref(info)),
      base::BindRepeating(&DownloadBubbleUpdateService::CacheManager::
                              UpdateDisplayInfoForOfflineItem,
                          base::Unretained(this), std::nullopt, cutoff_time,
                          std::ref(info)),
      base::BindRepeating(&DownloadBubbleUpdateService::CacheManager::
                              ShouldStopUpdatingDisplayInfo,
                          base::Unretained(this), std::ref(info)));

  display_info_ = info;
}

void DownloadBubbleUpdateService::CacheManager::UpdateDisplayInfo(
    const ContentId& updating_for_item) {
#if DCHECK_IS_ON()
  ConsistencyCheckCaches();
#endif  // DCHECK_IS_ON()

  // A new info is constructed from scratch based on the current cache contents.
  DownloadBubbleDisplayInfo info;
  base::Time cutoff_time = GetCutoffTime();

  // Iterate over the two sorted caches (download items and offline items) in
  // combined/merged sorted order. This is done in the same way as in
  // GetAllItemsToDisplay() to ensure that the info most accurately represents
  // the list of items that would be returned from that method.
  IterateOverMergedCaches(
      base::BindRepeating(&DownloadBubbleUpdateService::CacheManager::
                              UpdateDisplayInfoForDownloadItem,
                          base::Unretained(this), std::nullopt, cutoff_time,
                          std::ref(info)),
      base::BindRepeating(
          &DownloadBubbleUpdateService::CacheManager::
              UpdateDisplayInfoForOfflineItem,
          base::Unretained(this),
          base::optional_ref<const ContentId>(updating_for_item), cutoff_time,
          std::ref(info)),
      base::BindRepeating(&DownloadBubbleUpdateService::CacheManager::
                              ShouldStopUpdatingDisplayInfo,
                          base::Unretained(this), std::ref(info)));

  display_info_ = info;
}

void DownloadBubbleUpdateService::CacheManager::
    UpdateDisplayInfoForDownloadItem(
        base::optional_ref<const std::string> updating_for_item,
        base::Time cutoff_time,
        DownloadBubbleDisplayInfo& info,
        SortedDownloadItems::iterator& download_item_it) {
  DownloadItemModel model(
      download_item_it->second,
      std::make_unique<DownloadUIModel::BubbleStatusTextBuilder>());
  bool update_is_for_model =
      updating_for_item.has_value() &&
      *updating_for_item == GetItemId(download_item_it->second);
  UpdateInfoForModel(model, update_is_for_model, cutoff_time, info);
  ++download_item_it;
}

void DownloadBubbleUpdateService::CacheManager::UpdateDisplayInfoForOfflineItem(
    base::optional_ref<const ContentId> updating_for_item,
    base::Time cutoff_time,
    DownloadBubbleDisplayInfo& info,
    SortedOfflineItems::iterator& offline_item_it) {
  OfflineItemModel model(
      update_service_->GetOfflineManager(), offline_item_it->second,
      std::make_unique<DownloadUIModel::BubbleStatusTextBuilder>());
  bool update_is_for_model =
      updating_for_item.has_value() &&
      *updating_for_item == GetItemId(offline_item_it->second);
  UpdateInfoForModel(model, update_is_for_model, cutoff_time, info);
  ++offline_item_it;
}

bool DownloadBubbleUpdateService::CacheManager::ShouldStopUpdatingDisplayInfo(
    const DownloadBubbleDisplayInfo& info) {
  return info.all_models_size >= GetMaxNumItemsToShow();
}

void DownloadBubbleUpdateService::CacheManager::IterateOverMergedCaches(
    base::RepeatingCallback<void(SortedDownloadItems::iterator&)>
        download_item_action,
    base::RepeatingCallback<void(SortedOfflineItems::iterator&)>
        offline_item_action,
    base::RepeatingCallback<bool()> should_stop) {
  auto download_item_it = download_items_.begin();
  auto offline_item_it = offline_items_.begin();
  while (download_item_it != download_items_.end() ||
         offline_item_it != offline_items_.end()) {
    // If the current download item sorts before the current offline item (or we
    // are out of offline items), take the download item.
    if (download_item_it != download_items_.end() &&
        (offline_item_it == offline_items_.end() ||
         download_item_it->first < offline_item_it->first)) {
      download_item_action.Run(download_item_it);
    } else {
      // Else, the current offline item sorts before the current download item
      // (or we are out of download items), so take the offline item.
      offline_item_action.Run(offline_item_it);
    }
    if (should_stop.Run()) {
      break;
    }
  }
}

ProgressInfo DownloadBubbleUpdateService::CacheManager::GetProgressInfo()
    const {
#if DCHECK_IS_ON()
  ConsistencyCheckCaches();
#endif  // DCHECK_IS_ON()

  ProgressInfo info;
  int in_progress_items = 0;
  int64_t received_bytes = 0;
  int64_t total_bytes = 0;

  base::Time cutoff_time = GetCutoffTime();

  for (const auto& [key, item] : download_items_) {
    if (key.state == ItemSortKey::kNotInProgress) {
      break;
    }
    if (GetItemStartTime(item) < cutoff_time) {
      continue;
    }
    // Note that operator&= does not short-circuit.
    info.progress_certain &=
        AddItemProgress(item->GetReceivedBytes(), item->GetTotalBytes(),
                        in_progress_items, received_bytes, total_bytes);
  }

  for (const auto& [key, item] : offline_items_) {
    if (key.state == ItemSortKey::kNotInProgress) {
      break;
    }
    if (GetItemStartTime(item) < cutoff_time) {
      continue;
    }
    // Note that operator&= does not short-circuit.
    info.progress_certain &=
        AddItemProgress(item.received_bytes, item.total_size_bytes,
                        in_progress_items, received_bytes, total_bytes);
  }

  info.download_count = in_progress_items;
  if (total_bytes > 0) {
    info.progress_percentage =
        base::ClampFloor(received_bytes * 100.0 / total_bytes);
  }
  return info;
}

ProgressInfo DownloadBubbleUpdateService::GetProgressInfo(
    const webapps::AppId* web_app_id) const {
  if (web_app_id == nullptr) {
    return main_cache_.GetProgressInfo();
  }
  if (const CacheManager* cache = GetExistingCacheForWebApp(*web_app_id);
      cache != nullptr) {
    return cache->GetProgressInfo();
  }
  return ProgressInfo{};
}

std::vector<std::u16string> DownloadBubbleUpdateService::CacheManager::
    TakeAccessibleAlertsForAnnouncement() {
  std::vector<std::u16string> to_announce =
      accessible_alerts_.TakeAlertsForAnnouncement();
  accessible_alerts_.GarbageCollect();
  return to_announce;
}

std::vector<std::u16string>
DownloadBubbleUpdateService::TakeAccessibleAlertsForAnnouncement(
    const webapps::AppId* web_app_id) {
  if (web_app_id == nullptr) {
    return main_cache_.TakeAccessibleAlertsForAnnouncement();
  }
  if (CacheManager* cache = GetExistingCacheForWebApp(*web_app_id);
      cache != nullptr) {
    return cache->TakeAccessibleAlertsForAnnouncement();
  }
  return std::vector<std::u16string>();
}

void DownloadBubbleUpdateService::OnDownloadCreated(
    content::DownloadManager* manager,
    download::DownloadItem* item) {
  if (IsShutDown()) {
    return;
  }
  CHECK(download_item_notifier_ || original_download_item_notifier_);
  if (!download_item_notifier_) {
    return;
  }
  if (download_crx_util::IsExtensionDownload(*item) &&
      delayed_crx_guids_.size() < kMaxDelayedCrxGuids) {
    const std::string& guid = item->GetGuid();
    CHECK(!delayed_crx_guids_.contains(guid));
    delayed_crx_guids_.insert(guid);
    base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(
            &DownloadBubbleUpdateService::OnDelayedCrxDownloadCreated,
            weak_factory_.GetWeakPtr(), guid),
        kCrxShowNewItemDelay);
    return;
  }
  GetCacheForItem(item).MaybeAddDownloadItemToCache(
      item, /*is_new=*/true,
      /*maybe_add_alert=*/download_history_loaded_);
  // NotifyWindowsOfDownloadItemAdded() is called from
  // DownloadBubbleUIControllerDelegate for new non-crx downloads.
}

void DownloadBubbleUpdateService::OnDelayedCrxDownloadCreated(
    const std::string& guid) {
  if (IsShutDown()) {
    return;
  }
  CHECK(download_item_notifier_ || original_download_item_notifier_);
  if (!download_item_notifier_) {
    return;
  }
  // This assumes that for extension/theme downloads, the DownloadItem is
  // removed from the DownloadManager upon completion.
  download::DownloadItem* item =
      download_item_notifier_->GetManager()->GetDownloadByGuid(guid);
  if (item && !item->IsDone()) {
    GetCacheForItem(item).MaybeAddDownloadItemToCache(
        item, /*is_new=*/true,
        /*maybe_add_alert=*/download_history_loaded_);
    NotifyWindowsOfDownloadItemAdded(item);
  }
  size_t erased = delayed_crx_guids_.erase(guid);
  CHECK_EQ(erased, 1u);
}

void DownloadBubbleUpdateService::NotifyWindowsOfDownloadItemAdded(
    download::DownloadItem* item) {
  Browser* browser_to_show_animation =
      FindBrowserToShowAnimation(item, profile_);
  auto* web_app_data = DownloadItemWebAppData::Get(item);
  for (Browser* browser : chrome::FindAllBrowsersWithProfile(profile_)) {
    if (browser->window() &&
        browser->window()->GetDownloadBubbleUIController() &&
        BrowserMatchesWebAppData(browser, web_app_data)) {
      browser->window()->GetDownloadBubbleUIController()->OnDownloadItemAdded(
          item, /*may_show_animation=*/browser == browser_to_show_animation);
    }
  }
}

void DownloadBubbleUpdateService::OnDownloadUpdated(
    content::DownloadManager* manager,
    download::DownloadItem* item) {
  if (IsShutDown()) {
    return;
  }
  CHECK(download_item_notifier_ || original_download_item_notifier_);
  if (!download_item_notifier_) {
    return;
  }
  // If the item is an extension or theme download waiting out its 2-second
  // delay, don't show a UI update for it.
  if (delayed_crx_guids_.contains(item->GetGuid())) {
    return;
  }
  CacheManager& cache = GetCacheForItem(item);
  // When persisted web app download items are restored from the history
  // database, we first get a OnDownloadCreated() notification about the item
  // without its DownloadItemWebAppData, causing the item to go into the main
  // cache, followed by an OnDownloadUpdated() notification after the
  // DownloadItemWebAppData is added. In order to keep the item in the
  // appropriate cache for the web app, and NOT in the main cache, we must
  // remove it from the main cache explicitly here. Note this assumes that an
  // item's associated web app id never changes once it is tagged.
  if (!IsMainCache(cache)) {
    main_cache_.OnDownloadItemRemoved(item);
  }
  cache.OnDownloadItemUpdated(item);

  auto* web_app_data = DownloadItemWebAppData::Get(item);
  for (Browser* browser : chrome::FindAllBrowsersWithProfile(profile_)) {
    if (browser->window() &&
        browser->window()->GetDownloadBubbleUIController() &&
        BrowserMatchesWebAppData(browser, web_app_data)) {
      browser->window()->GetDownloadBubbleUIController()->OnDownloadItemUpdated(
          item);
    }
  }
}

void DownloadBubbleUpdateService::CacheManager::OnDownloadItemUpdated(
    download::DownloadItem* item) {
  bool cache_was_at_max = IsDownloadItemCacheAtMax();
  bool removed_item = RemoveDownloadItemFromCache(item);
  bool added_back_at_end = MaybeAddDownloadItemToCache(
      item, /*is_new=*/false,
      /*maybe_add_alert=*/update_service_->download_history_loaded());
  if (cache_was_at_max && removed_item && added_back_at_end) {
    CHECK_EQ(download_items_.size(), GetNumItemsToCache());
    const ItemSortKey& last_key =
        std::prev(GetLastIter(download_items_))->first;
    update_service_->StartBackfillDownloadItems(last_key);
  }
}

void DownloadBubbleUpdateService::OnDownloadRemoved(
    content::DownloadManager* manager,
    download::DownloadItem* item) {
  if (IsShutDown()) {
    return;
  }
  CHECK(download_item_notifier_ || original_download_item_notifier_);
  if (!download_item_notifier_) {
    return;
  }
  GetCacheForItem(item).OnDownloadItemRemoved(item);

  auto* web_app_data = DownloadItemWebAppData::Get(item);
  for (Browser* browser : chrome::FindAllBrowsersWithProfile(profile_)) {
    if (browser->window() &&
        browser->window()->GetDownloadBubbleUIController() &&
        BrowserMatchesWebAppData(browser, web_app_data)) {
      browser->window()->GetDownloadBubbleUIController()->OnDownloadItemRemoved(
          item);
    }
  }
}

void DownloadBubbleUpdateService::CacheManager::OnDownloadItemRemoved(
    download::DownloadItem* item) {
  bool cache_was_at_max = IsDownloadItemCacheAtMax();
  if (RemoveDownloadItemFromCache(item) && cache_was_at_max) {
    CHECK_EQ(download_items_.size(), GetNumItemsToCache() - 1);
    const ItemSortKey& last_key = GetLastIter(download_items_)->first;
    update_service_->StartBackfillDownloadItems(last_key);
  }
}

void DownloadBubbleUpdateService::OnManagerGoingDown(
    content::DownloadManager* manager) {
  CHECK(download_item_notifier_ || original_download_item_notifier_);
  // Assume that the original manager (if this is an OTR profile) may or may not
  // have shut down, but we still want to cease all operations when this
  // profile's manager shuts down.
  if (download_item_notifier_ &&
      (manager == download_item_notifier_->GetManager())) {
    is_shut_down_ = true;
    download_item_notifier_.reset();
    for (CacheManager* cache : GetAllCacheManagers()) {
      cache->DropAllDownloadItems();
    }
  }
}

void DownloadBubbleUpdateService::OnItemsAdded(
    const OfflineContentProvider::OfflineItemList& items) {
  if (IsShutDown()) {
    return;
  }
  if (!offline_items_initialized_) {
    offline_item_callbacks_.push_back(
        base::BindOnce(&DownloadBubbleUpdateService::OnItemsAdded,
                       weak_factory_.GetWeakPtr(), items));
    return;
  }
  for (const OfflineItem& item : items) {
    main_cache_.MaybeAddOfflineItemToCache(item, /*is_new=*/true,
                                           /*maybe_add_alert=*/true);
  }

  for (Browser* browser : chrome::FindAllBrowsersWithProfile(profile_)) {
    if (browser->window() &&
        browser->window()->GetDownloadBubbleUIController() &&
        !web_app::AppBrowserController::IsWebApp(browser)) {
      browser->window()->GetDownloadBubbleUIController()->OnOfflineItemsAdded(
          items);
    }
  }
}

void DownloadBubbleUpdateService::OnItemRemoved(const ContentId& id) {
  if (IsShutDown()) {
    return;
  }
  if (!offline_items_initialized_) {
    offline_item_callbacks_.push_back(
        base::BindOnce(&DownloadBubbleUpdateService::OnItemRemoved,
                       weak_factory_.GetWeakPtr(), id));
    return;
  }
  main_cache_.OnOfflineItemRemoved(id);

  for (Browser* browser : chrome::FindAllBrowsersWithProfile(profile_)) {
    if (browser->window() &&
        browser->window()->GetDownloadBubbleUIController() &&
        !web_app::AppBrowserController::IsWebApp(browser)) {
      browser->window()->GetDownloadBubbleUIController()->OnOfflineItemRemoved(
          id);
    }
  }
}

void DownloadBubbleUpdateService::CacheManager::OnOfflineItemRemoved(
    const ContentId& id) {
  bool cache_was_at_max = IsOfflineItemCacheAtMax();
  if (RemoveOfflineItemFromCache(id) && cache_was_at_max) {
    CHECK_EQ(offline_items_.size(), GetNumItemsToCache() - 1);
    const ItemSortKey& last_key = GetLastIter(offline_items_)->first;
    update_service_->StartBackfillOfflineItems(last_key);
  }
}

void DownloadBubbleUpdateService::OnItemUpdated(
    const OfflineItem& item,
    const std::optional<offline_items_collection::UpdateDelta>& update_delta) {
  if (IsShutDown()) {
    return;
  }
  if (!offline_items_initialized_) {
    offline_item_callbacks_.push_back(
        base::BindOnce(&DownloadBubbleUpdateService::OnItemUpdated,
                       weak_factory_.GetWeakPtr(), item, update_delta));
    return;
  }
  main_cache_.OnOfflineItemUpdated(item);

  for (Browser* browser : chrome::FindAllBrowsersWithProfile(profile_)) {
    if (browser->window() &&
        browser->window()->GetDownloadBubbleUIController() &&
        !web_app::AppBrowserController::IsWebApp(browser)) {
      browser->window()->GetDownloadBubbleUIController()->OnOfflineItemUpdated(
          item);
    }
  }
}

void DownloadBubbleUpdateService::CacheManager::OnOfflineItemUpdated(
    const OfflineItem& item) {
  bool cache_was_at_max = IsOfflineItemCacheAtMax();
  bool removed_item = RemoveOfflineItemFromCache(GetItemId(item));
  bool added_back_to_end = MaybeAddOfflineItemToCache(item, /*is_new=*/false,
                                                      /*maybe_add_alert=*/true);
  if (cache_was_at_max && removed_item && added_back_to_end) {
    CHECK_EQ(offline_items_.size(), GetNumItemsToCache());
    const ItemSortKey& last_key = std::prev(GetLastIter(offline_items_))->first;
    update_service_->StartBackfillOfflineItems(last_key);
  }
}

void DownloadBubbleUpdateService::OnContentProviderGoingDown() {
  is_shut_down_ = true;
  main_cache_.DropAllOfflineItems();
}

void DownloadBubbleUpdateService::OnHistoryQueryComplete() {
  download_history_loaded_ = true;
}

void DownloadBubbleUpdateService::OnDownloadHistoryDestroyed() {
  download_history_observation_.Reset();
}

bool DownloadBubbleUpdateService::CacheManager::MaybeAddDownloadItemToCache(
    download::DownloadItem* item,
    bool is_new,
    bool maybe_add_alert) {
  DownloadItemModel model(
      item, std::make_unique<DownloadUIModel::BubbleStatusTextBuilder>());
  if (!ShouldIncludeModel(&model, GetCutoffTime())) {
    return false;
  }
  if (is_new && model.ShouldNotifyUI()) {
    model.SetActionedOn(false);
  }
  if (maybe_add_alert) {
    // Garbage collect accessible alerts before we add another item because this
    // can be called after a long time since the last alert activity.
    accessible_alerts_.GarbageCollect();
    accessible_alerts_.MaybeAddAccessibleAlert(
        model.GetContentId(), GetAccessibleAlertForModel(model));
  }
  return AddItemToCacheImpl(item, download_items_, download_items_iter_map_);
}

bool DownloadBubbleUpdateService::CacheManager::MaybeAddOfflineItemToCache(
    const OfflineItem& item,
    bool is_new,
    bool maybe_add_alert) {
  CHECK(update_service_->IsMainCache(*this));
  if (update_service_->IsProfileOtr() != item.is_off_the_record) {
    return false;
  }
  if (OfflineItemUtils::IsDownload(item.id)) {
    return false;
  }
  if (item.state == offline_items_collection::OfflineItemState::CANCELLED) {
    return false;
  }
  if (item.id.name_space == ContentIndexProviderImpl::kProviderNamespace) {
    return false;
  }

  OfflineItemModel model(
      update_service_->GetOfflineManager(), item,
      std::make_unique<DownloadUIModel::BubbleStatusTextBuilder>());
  if (!ShouldIncludeModel(&model, GetCutoffTime())) {
    return false;
  }
  if (is_new && model.ShouldNotifyUI()) {
    model.SetActionedOn(false);
  }
  if (maybe_add_alert) {
    // Garbage collect accessible alerts before we add another item because this
    // can be called after a long time since the last alert activity.
    accessible_alerts_.GarbageCollect();
    accessible_alerts_.MaybeAddAccessibleAlert(
        model.GetContentId(), GetAccessibleAlertForModel(model));
  }

  return AddItemToCacheImpl(item, offline_items_, offline_items_iter_map_);
}

template <typename Id, typename Item>
bool DownloadBubbleUpdateService::CacheManager::AddItemToCacheImpl(
    Item item,
    SortedItems<Item>& cache,
    IterMap<Id, Item>& iter_map) {
  // This check duplicates part of the ShouldIncludeModel() check, but is still
  // needed because we don't always call that before this function.
  if (GetItemStartTime(item) < GetCutoffTime()) {
    return false;
  }
  Id id = GetItemId(item);
  if (iter_map.contains(id)) {
    return false;
  }
  ItemSortKey key = GetSortKey(item);

  if (cache.size() >= GetNumItemsToCache()) {
    CHECK_EQ(cache.size(), GetNumItemsToCache());
    if (key > GetLastIter(cache)->first) {
      return false;
    }
  }

  auto it = cache.insert(std::make_pair(std::move(key), item));
  iter_map.insert(std::make_pair(id, it));

  while (cache.size() > GetNumItemsToCache()) {
    CHECK(!cache.empty());
    CHECK_EQ(cache.size(), 1 + GetNumItemsToCache());
    auto to_remove = GetLastIter(cache);
    const Id& id_to_remove = GetItemId(to_remove->second);
    iter_map.erase(id_to_remove);
    cache.erase(to_remove);
  }

  UpdateDisplayInfo(id);

  CHECK(!cache.empty());
  auto last_it = GetLastIter(cache);
  return GetItemId(last_it->second) == id;
}

bool DownloadBubbleUpdateService::CacheManager::RemoveDownloadItemFromCache(
    download::DownloadItem* item) {
  return RemoveItemFromCacheImpl(GetItemId(item), download_items_,
                                 download_items_iter_map_);
}

bool DownloadBubbleUpdateService::CacheManager::RemoveOfflineItemFromCache(
    const ContentId& id) {
  CHECK(update_service_->IsMainCache(*this));
  return RemoveItemFromCacheImpl(id, offline_items_, offline_items_iter_map_);
}

template <typename Id, typename Item>
bool DownloadBubbleUpdateService::CacheManager::RemoveItemFromCacheImpl(
    const Id& id,
    SortedItems<Item>& cache,
    IterMap<Id, Item>& iter_map) {
  auto iter_map_it = iter_map.find(id);
  if (iter_map_it == iter_map.end()) {
    return false;
  }

  cache.erase(iter_map_it->second);
  iter_map.erase(iter_map_it);

  UpdateDisplayInfo(id);

  CHECK(cache.size() < GetNumItemsToCache());
  return true;
}

template <typename Id, typename Item>
SortedItems<Item>::iterator
DownloadBubbleUpdateService::CacheManager::RemoveItemFromCacheByIter(
    SortedItems<Item>::iterator iter,
    SortedItems<Item>& cache,
    IterMap<Id, Item>& iter_map) {
  CHECK(iter != cache.end());
  auto next_iter = std::next(iter);
  Id id = GetItemId(iter->second);
  iter_map.erase(id);
  cache.erase(iter);

  UpdateDisplayInfo(id);

  return next_iter;
}

void DownloadBubbleUpdateService::StartBackfillDownloadItems(
    const ItemSortKey& last_key) {
  if (IsShutDown()) {
    return;
  }
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&DownloadBubbleUpdateService::BackfillDownloadItems,
                     weak_factory_.GetWeakPtr(), last_key));
}

void DownloadBubbleUpdateService::BackfillDownloadItems(
    const ItemSortKey& last_key) {
  if (IsShutDown()) {
    return;
  }
  for (download::DownloadItem* item : GetAllDownloadItems()) {
    if (GetSortKey(item) < last_key) {
      continue;
    }
    GetCacheForItem(item).MaybeAddDownloadItemToCache(
        item, /*is_new=*/false, /*maybe_add_alert=*/false);
  }
}

void DownloadBubbleUpdateService::StartBackfillOfflineItems(
    const ItemSortKey& last_key) {
  if (IsShutDown()) {
    return;
  }
  offline_items_collection::OfflineContentProvider* provider =
      OfflineContentAggregatorFactory::GetForKey(profile_->GetProfileKey());
  provider->GetAllItems(
      base::BindOnce(&DownloadBubbleUpdateService::BackfillOfflineItems,
                     weak_factory_.GetWeakPtr(), last_key));
}

void DownloadBubbleUpdateService::BackfillOfflineItems(
    const ItemSortKey& last_key,
    const std::vector<OfflineItem>& all_items) {
  if (IsShutDown()) {
    return;
  }
  for (const OfflineItem& item : all_items) {
    if (GetSortKey(item) < last_key) {
      continue;
    }
    main_cache_.MaybeAddOfflineItemToCache(item, /*is_new=*/false,
                                           /*maybe_add_alert=*/false);
  }
}

void DownloadBubbleUpdateService::CacheManager::DropAllDownloadItems() {
  download_items_.clear();
  download_items_iter_map_.clear();
}

void DownloadBubbleUpdateService::InitializeDownloadItemsCache() {
  CHECK(download_item_notifier_);
  for (CacheManager* cache : GetAllCacheManagers()) {
    cache->DropAllDownloadItems();
  }
  for (download::DownloadItem* item : GetAllDownloadItems()) {
    GetCacheForItem(item).MaybeAddDownloadItemToCache(
        item, /*is_new=*/false, /*maybe_add_alert=*/false);
  }
}

void DownloadBubbleUpdateService::CacheManager::DropAllOfflineItems() {
  CHECK(update_service_->IsMainCache(*this));
  offline_items_.clear();
  offline_items_iter_map_.clear();
}

void DownloadBubbleUpdateService::StartInitializeOfflineItemsCache() {
  if (IsShutDown()) {
    return;
  }
  if (offline_items_initialized_) {
    return;
  }
  offline_items_collection::OfflineContentProvider* provider =
      OfflineContentAggregatorFactory::GetForKey(profile_->GetProfileKey());
  provider->GetAllItems(
      base::BindOnce(&DownloadBubbleUpdateService::InitializeOfflineItemsCache,
                     weak_factory_.GetWeakPtr()));
}

void DownloadBubbleUpdateService::InitializeOfflineItemsCache(
    const std::vector<OfflineItem>& all_items) {
  main_cache_.DropAllOfflineItems();
  for (const OfflineItem& item : all_items) {
    main_cache_.MaybeAddOfflineItemToCache(item, /*is_new=*/false,
                                           /*maybe_add_alert=*/false);
  }
  offline_items_initialized_ = true;
  for (auto& callback : offline_item_callbacks_) {
    std::move(callback).Run();
  }
  offline_item_callbacks_.clear();
}

std::vector<raw_ptr<download::DownloadItem, VectorExperimental>>
DownloadBubbleUpdateService::GetAllDownloadItems() {
  std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> all_items;
  if (download_item_notifier_) {
    download_item_notifier_->GetManager()->GetAllDownloads(&all_items);
  }
  if (original_download_item_notifier_) {
    original_download_item_notifier_->GetManager()->GetAllDownloads(&all_items);
  }
  return all_items;
}

OfflineItemModelManager* DownloadBubbleUpdateService::GetOfflineManager()
    const {
  return OfflineItemModelManagerFactory::GetForBrowserContext(profile_);
}

bool DownloadBubbleUpdateService::CacheManager::MaybeAddDownloadItemModel(
    download::DownloadItem* item,
    base::Time cutoff_time,
    std::vector<DownloadUIModelPtr>& models) {
  DownloadUIModelPtr model = DownloadItemModel::Wrap(
      item, std::make_unique<DownloadUIModel::BubbleStatusTextBuilder>());
  return MaybeAddModel(std::move(model), cutoff_time, GetMaxNumItemsToShow(),
                       models);
}

bool DownloadBubbleUpdateService::CacheManager::MaybeAddOfflineItemModel(
    const offline_items_collection::OfflineItem& item,
    base::Time cutoff_time,
    std::vector<DownloadUIModelPtr>& models) {
  DownloadUIModelPtr model = OfflineItemModel::Wrap(
      update_service_->GetOfflineManager(), item,
      std::make_unique<DownloadUIModel::BubbleStatusTextBuilder>());
  return MaybeAddModel(std::move(model), cutoff_time, GetMaxNumItemsToShow(),
                       models);
}

void DownloadBubbleUpdateService::CacheManager::AppendBackfilledDownloadItems(
    const ItemSortKey& last_key,
    base::Time cutoff_time,
    std::vector<DownloadUIModelPtr>& models) {
  // This is not quite right because there might be a newly backfilled item
  // whose key is equal to |last_key| that this would then skip
  // over (and we would not be able to detect/fix the omission, unless the item
  // received an update later), but this should happen rarely enough (requires
  // two download items with the exact same creation time) that we will not
  // handle this case.
  auto it = download_items_.upper_bound(last_key);

  while (it != download_items_.end()) {
    if (!MaybeAddDownloadItemModel(it->second, cutoff_time, models)) {
      it = RemoveItemFromCacheByIter(it, download_items_,
                                     download_items_iter_map_);
    } else {
      ++it;
    }
  }
}

bool DownloadBubbleUpdateService::IsMainCache(
    const DownloadBubbleUpdateService::CacheManager& cache) const {
  return &cache == &main_cache_;
}

void DownloadBubbleUpdateService::OnEphemeralWarningExpired(
    const std::string& guid) {
  if (IsShutDown()) {
    return;
  }
  CHECK(download_item_notifier_ || original_download_item_notifier_);
  if (!download_item_notifier_) {
    return;
  }
  content::DownloadManager* download_manager = GetDownloadManager();
  if (!download_manager) {
    return;
  }

  download::DownloadItem* item = download_manager->GetDownloadByGuid(guid);
  // The item might be from the original profile.
  if (!item && original_download_item_notifier_ &&
      original_download_item_notifier_->GetManager()) {
    item =
        original_download_item_notifier_->GetManager()->GetDownloadByGuid(guid);
  }
  if (!item) {
    return;
  }

  GetCacheForItem(item).UpdateDisplayInfo(guid);

  auto* web_app_data = DownloadItemWebAppData::Get(item);
  for (Browser* browser : chrome::FindAllBrowsersWithProfile(profile_)) {
    if (browser->window() &&
        browser->window()->GetDownloadBubbleUIController() &&
        BrowserMatchesWebAppData(browser, web_app_data)) {
      browser->window()->GetDownloadBubbleUIController()->OnDownloadItemRemoved(
          item);
    }
  }
}

#if DCHECK_IS_ON()
void DownloadBubbleUpdateService::CacheManager::ConsistencyCheckCaches() const {
  ConsistencyCheckImpl(download_items_, download_items_iter_map_);
  ConsistencyCheckImpl(offline_items_, offline_items_iter_map_);
}

template <typename Id, typename Item>
void DownloadBubbleUpdateService::CacheManager::ConsistencyCheckImpl(
    const SortedItems<Item>& cache,
    const IterMap<Id, Item>& iter_map) const {
  DCHECK_EQ(cache.size(), iter_map.size())
      << "Cache size " << cache.size() << " does not match index size "
      << iter_map.size() << ".";
  DCHECK_LE(cache.size(), GetNumItemsToCache())
      << "Cache size " << cache.size() << " exceeds max size "
      << GetNumItemsToCache() << ".";
  for (auto it = cache.begin(); it != cache.end(); ++it) {
    const ItemSortKey& key = it->first;
    const Item& item = it->second;
    // The state of the stored key and the current state of the item may not
    // always match, if we haven't received the update notification yet.
    DCHECK_EQ(key.start_time, GetSortKey(item).start_time)
        << "Start time in key does not match item.";
    const Id& id = GetItemId(item);
    auto iter_map_it = iter_map.find(id);
    DCHECK(iter_map_it != iter_map.end()) << "Item id not in index.";
    DCHECK(iter_map_it->second == it) << "Index inconsistent.";
  }
}
#endif  // DCHECK_IS_ON()