File: saved_tab_group_model.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 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 (1064 lines) | stat: -rw-r--r-- 34,838 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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/saved_tab_groups/internal/saved_tab_group_model.h"

#include <algorithm>
#include <cstddef>
#include <memory>
#include <optional>
#include <vector>

#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/observer_list.h"
#include "base/strings/utf_string_conversions.h"
#include "base/uuid.h"
#include "components/saved_tab_groups/internal/saved_tab_group_model_observer.h"
#include "components/saved_tab_groups/internal/stats.h"
#include "components/saved_tab_groups/public/features.h"
#include "components/saved_tab_groups/public/saved_tab_group.h"
#include "components/saved_tab_groups/public/saved_tab_group_tab.h"
#include "components/saved_tab_groups/public/types.h"
#include "components/sync/protocol/saved_tab_group_specifics.pb.h"
#include "components/tab_groups/tab_group_color.h"
#include "components/tab_groups/tab_group_id.h"
#include "components/tab_groups/tab_group_visual_data.h"
#include "google_apis/gaia/gaia_id.h"

namespace tab_groups {
namespace {

void RecordGroupDeletedMetric(const SavedTabGroup& removed_group) {
  const base::TimeDelta duration_saved =
      base::Time::Now() - removed_group.creation_time();

  base::UmaHistogramCounts1M("TabGroups.SavedTabGroupLifespan",
                             duration_saved.InMinutes());

  base::RecordAction(
      base::UserMetricsAction("TabGroups_SavedTabGroups_Deleted"));

  if (removed_group.is_shared_tab_group()) {
    base::UmaHistogramBoolean("TabGroups.Shared.GroupDeleted", true);
  }
}

// Compare function for 2 SavedTabGroup.
// SaveTabGroup with position set is always placed before the one without
// position set. If both have position set, the one with lower position number
// should place before. If both positions are the same or both are not set, the
// one with more recent update time should place before.
bool ShouldPlaceBefore(const SavedTabGroup& group1,
                       const SavedTabGroup& group2) {
  std::optional<size_t> position1 = group1.position();
  std::optional<size_t> position2 = group2.position();
  if (position1.has_value() && position2.has_value()) {
    if (position1.value() != position2.value()) {
      return position1.value() < position2.value();
    } else {
      return group1.update_time() >= group2.update_time();
    }
  } else if (position1.has_value() && !position2.has_value()) {
    return true;
  } else if (!position1.has_value() && position2.has_value()) {
    return false;
  } else {
    return group1.update_time() >= group2.update_time();
  }
}

// URL and title used for pending NTP.
const char kPendingNtpURL[] = "chrome://newtab/";
const char16_t kPendingNtpTitle[] = u"New tab";

}  // anonymous namespace

SavedTabGroupModel::SavedTabGroupModel() = default;
SavedTabGroupModel::~SavedTabGroupModel() = default;

std::vector<const SavedTabGroup*> SavedTabGroupModel::GetSavedTabGroupsOnly()
    const {
  std::vector<const SavedTabGroup*> saved_tab_groups;
  for (const SavedTabGroup& group : saved_tab_groups_) {
    if (!group.is_shared_tab_group()) {
      saved_tab_groups.push_back(&group);
    }
  }
  return saved_tab_groups;
}

std::vector<const SavedTabGroup*> SavedTabGroupModel::GetSharedTabGroupsOnly()
    const {
  std::vector<const SavedTabGroup*> shared_tab_groups;
  for (const SavedTabGroup& group : saved_tab_groups_) {
    if (group.is_shared_tab_group()) {
      shared_tab_groups.push_back(&group);
    }
  }
  return shared_tab_groups;
}

std::optional<int> SavedTabGroupModel::GetIndexOf(
    LocalTabGroupID tab_group_id) const {
  for (size_t i = 0; i < saved_tab_groups_.size(); i++) {
    if (saved_tab_groups_[i].local_group_id() == tab_group_id) {
      return i;
    }
  }

  return std::nullopt;
}

std::optional<int> SavedTabGroupModel::GetIndexOf(const base::Uuid& id) const {
  for (size_t i = 0; i < saved_tab_groups_.size(); i++) {
    if (saved_tab_groups_[i].saved_guid() == id) {
      return i;
    }
  }

  return std::nullopt;
}

std::optional<bool> SavedTabGroupModel::IsGroupPinned(
    const base::Uuid& id) const {
  std::optional<int> index = GetIndexOf(id);
  if (index.has_value()) {
    return saved_tab_groups_[index.value()].is_pinned();
  } else {
    return std::nullopt;
  }
}

const SavedTabGroup* SavedTabGroupModel::Get(const base::Uuid& id) const {
  std::optional<int> index = GetIndexOf(id);
  if (!index.has_value()) {
    return nullptr;
  }

  return &saved_tab_groups_[index.value()];
}

const SavedTabGroup* SavedTabGroupModel::Get(
    const LocalTabGroupID local_group_id) const {
  std::optional<int> index = GetIndexOf(local_group_id);
  if (!index.has_value()) {
    return nullptr;
  }

  return &saved_tab_groups_[index.value()];
}

void SavedTabGroupModel::AddedLocally(SavedTabGroup saved_group) {
  base::Uuid group_guid = saved_group.saved_guid();
  CHECK(!Contains(group_guid));

  InsertGroupImpl(std::move(saved_group));

  for (auto& observer : observers_) {
    observer.SavedTabGroupAddedLocally(group_guid);
  }
}

void SavedTabGroupModel::RemovedLocally(const LocalTabGroupID tab_group_id) {
  if (!Contains(tab_group_id)) {
    return;
  }

  const int index = GetIndexOf(tab_group_id).value();
  SavedTabGroup removed_group = RemoveImpl(index);

  UpdateGroupPositionsImpl();
  for (auto& observer : observers_) {
    observer.SavedTabGroupRemovedLocally(removed_group);
  }

  RecordGroupDeletedMetric(removed_group);
}

void SavedTabGroupModel::RemovedLocally(const base::Uuid& id) {
  if (!Contains(id)) {
    return;
  }

  const int index = GetIndexOf(id).value();
  SavedTabGroup removed_group = RemoveImpl(index);

  UpdateGroupPositionsImpl();
  for (auto& observer : observers_) {
    observer.SavedTabGroupRemovedLocally(removed_group);
  }

  RecordGroupDeletedMetric(removed_group);
}

void SavedTabGroupModel::UpdateVisualDataLocally(
    LocalTabGroupID tab_group_id,
    const tab_groups::TabGroupVisualData* visual_data) {
  if (!Contains(tab_group_id)) {
    return;
  }

  const std::optional<int> index = GetIndexOf(tab_group_id);
  UpdateVisualDataImpl(index.value(), visual_data);
  base::Uuid updated_guid = Get(tab_group_id)->saved_guid();
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(updated_guid,
                                         /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::MakeTabGroupSharedForTesting(
    const LocalTabGroupID& local_group_id,
    CollaborationId collaboration_id) {
  SavedTabGroup* const group = GetMutableGroup(local_group_id);
  group->SetCollaborationId(std::move(collaboration_id));
}

void SavedTabGroupModel::SetIsTransitioningToSaved(
    const LocalTabGroupID& local_group_id,
    bool is_transitioning_to_saved) {
  SavedTabGroup* const group = GetMutableGroup(local_group_id);
  group->SetIsTransitioningToSaved(is_transitioning_to_saved);
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(group->saved_guid(),
                                         /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::AddedFromSync(SavedTabGroup saved_group) {
  base::Uuid group_guid = saved_group.saved_guid();
  if (Contains(group_guid)) {
    return;
  }

  stats::RecordEmptyGroupsMetricsOnGroupAddedFromSync(saved_group, is_loaded_);

  InsertGroupImpl(std::move(saved_group));

  // TODO(crbug.com/375636822): Doing this before `is_loaded_ == true` is
  // problematic.
  for (auto& observer : observers_) {
    observer.SavedTabGroupAddedFromSync(Get(group_guid)->saved_guid());
  }
}

void SavedTabGroupModel::RemovedFromSync(const LocalTabGroupID tab_group_id) {
  if (!Contains(tab_group_id)) {
    return;
  }

  const std::optional<int> index = GetIndexOf(tab_group_id);
  HandleTabGroupRemovedFromSync(index.value());
}

void SavedTabGroupModel::RemovedFromSync(const base::Uuid& id) {
  if (!Contains(id)) {
    return;
  }

  const std::optional<int> index = GetIndexOf(id);
  HandleTabGroupRemovedFromSync(index.value());
}

void SavedTabGroupModel::UpdatedVisualDataFromSync(
    LocalTabGroupID tab_group_id,
    const tab_groups::TabGroupVisualData* visual_data) {
  if (!Contains(tab_group_id)) {
    return;
  }

  const std::optional<int> index = GetIndexOf(tab_group_id);
  UpdateVisualDataImpl(index.value(), visual_data);
  base::Uuid updated_guid = Get(tab_group_id)->saved_guid();
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(updated_guid,
                                          /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::UpdatedVisualDataFromSync(
    const base::Uuid& id,
    const tab_groups::TabGroupVisualData* visual_data) {
  if (!Contains(id)) {
    return;
  }

  const std::optional<int> index = GetIndexOf(id);
  UpdateVisualDataImpl(index.value(), visual_data);
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(id, /*tab_guid=*/std::nullopt);
  }
}

const SavedTabGroup* SavedTabGroupModel::GetGroupContainingTab(
    const base::Uuid& saved_tab_guid) const {
  for (auto& saved_group : saved_tab_groups_) {
    if (saved_group.ContainsTab(saved_tab_guid)) {
      return &saved_group;
    }
  }

  return nullptr;
}

const SavedTabGroup* SavedTabGroupModel::GetGroupContainingTab(
    const LocalTabID& local_tab_id) const {
  for (auto& saved_group : saved_tab_groups_) {
    if (saved_group.ContainsTab(local_tab_id)) {
      return &saved_group;
    }
  }

  return nullptr;
}

void SavedTabGroupModel::AddTabToGroupLocally(const base::Uuid& group_id,
                                              SavedTabGroupTab tab) {
  if (!Contains(group_id)) {
    return;
  }

  const base::Uuid tab_id = tab.saved_tab_guid();
  SavedTabGroup& group = saved_tab_groups_[GetIndexOf(group_id).value()];

  stats::RecordEmptyGroupsMetricsOnTabAddedLocally(group, tab, is_loaded_);

  group.AddTabLocally(std::move(tab));

  // When adding a tab locally, we should also check for any pending NTP
  // and start syncing them.
  StartSyncingPendingNtpIfAny(group);

  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(group_id, tab_id);
  }

  base::RecordAction(
      base::UserMetricsAction("TabGroups_SavedTabGroups_TabAdded"));
}

void SavedTabGroupModel::AddTabToGroupFromSync(const base::Uuid& group_id,
                                               SavedTabGroupTab tab) {
  if (!Contains(group_id)) {
    return;
  }

  const base::Uuid tab_id = tab.saved_tab_guid();
  SavedTabGroup& group = saved_tab_groups_[GetIndexOf(group_id).value()];

  if (group.ContainsTab(tab_id)) {
    // This can happen when an out of sync SavedTabGroup sends a tab update.
    group.ReplaceTabAt(tab_id, std::move(tab));
  } else {
    stats::RecordEmptyGroupsMetricsOnTabAddedFromSync(group, tab, is_loaded_);

    group.AddTabFromSync(std::move(tab));

    // If there is a pending NTP in this group, merge it with the incoming tab.
    MergePendingNtpWithIncomingTabIfAny(group, tab_id);
  }

  // TODO(crbug.com/375636822): Doing this before `is_loaded_ == true` is
  // problematic.
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(group_id, tab_id);
  }
}

void SavedTabGroupModel::UpdateTabInGroup(const base::Uuid& group_id,
                                          SavedTabGroupTab tab,
                                          bool notify_observers) {
  SavedTabGroup* group = GetMutableGroup(group_id);
  CHECK(group);

  if (group->GetTab(tab.saved_tab_guid())->url() != tab.url()) {
    base::RecordAction(
        base::UserMetricsAction("TabGroups_SavedTabGroups_TabNavigated"));
  }

  // Make a copy before moving the `tab`.
  const base::Uuid tab_guid_copy = tab.saved_tab_guid();
  group->UpdateTab(std::move(tab));

  if (!notify_observers) {
    return;
  }

  // This is a locally generated navigation event. Update the navigation
  // timestamp of the SavedTabGroupTab since we will not get the tab
  // modification time back from sync in the standard way due to reflection
  // blocking.
  tab.SetNavigationTime(base::Time::Now());

  // Since the group has at least one synced tab now, start syncing any pending
  // NTP.
  StartSyncingPendingNtpIfAny(*group);

  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(group_id, tab_guid_copy);
  }
}

void SavedTabGroupModel::UpdateLocalTabId(const base::Uuid& group_id,
                                          SavedTabGroupTab tab,
                                          std::optional<LocalTabID> local_id) {
  std::optional<int> group_index = GetIndexOf(group_id);
  CHECK(group_index.has_value());
  tab.SetLocalTabID(local_id);
  saved_tab_groups_[group_index.value()].UpdateTab(tab);
}

void SavedTabGroupModel::RemoveTabFromGroupLocally(
    const base::Uuid& group_id,
    const base::Uuid& tab_id,
    std::optional<GaiaId> local_gaia_id) {
  if (!Contains(group_id)) {
    return;
  }

  std::optional<int> index = GetIndexOf(group_id);
  const SavedTabGroup& group = saved_tab_groups_[index.value()];

  if (!group.ContainsTab(tab_id)) {
    return;
  }

  // Remove the group from the model if the last tab will be removed from it.
  if (group.saved_tabs().size() == 1) {
    if (group.is_shared_tab_group()) {
      base::UmaHistogramBoolean("TabGroups.Shared.LastTabClosed2", true);
    }
    RemovedLocally(group_id);
    return;
  }

  // TODO(crbug.com/40062298): Convert all methods to pass ids by value to
  // prevent UAFs. Also removes the need for a separate copy variable.
  const base::Uuid copy_tab_id = tab_id;
  saved_tab_groups_[index.value()].RemoveTabLocally(tab_id,
                                                    std::move(local_gaia_id));

  // TODO(dljames): Update to use SavedTabGroupRemoveLocally and update the API
  // to pass a group_id and an optional tab_id.
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(group_id, copy_tab_id);
  }

  base::RecordAction(
      base::UserMetricsAction("TabGroups_SavedTabGroups_TabRemoved"));
}

void SavedTabGroupModel::RemoveTabFromGroupFromSync(
    const base::Uuid& group_id,
    const base::Uuid& tab_id,
    GaiaId removed_by,
    bool prevent_group_destruction_for_testing) {
  std::optional<int> index = GetIndexOf(group_id);
  CHECK(index.has_value());
  SavedTabGroup& group = saved_tab_groups_[index.value()];

  if (!group.ContainsTab(tab_id)) {
    return;
  }

  const base::Uuid copy_tab_id = tab_id;
  saved_tab_groups_[index.value()].RemoveTabFromSync(
      tab_id, std::move(removed_by), prevent_group_destruction_for_testing);

  // The group became empty because of last tab deletion from sync. It could be
  // a transient state. Create a pending NTP since UI can't handle empty
  // groups. Any subsequent navigation or tab addition from locally or from
  // sync will commit this pending NTP.
  if (group.saved_tabs().empty()) {
    CreatePendingNtp(group);
    // Update local observers so that the pending NTP is written to storage.
    SavedTabGroupTab* pending_ntp = FindPendingNtpInGroup(group);
    for (SavedTabGroupModelObserver& observer : observers_) {
      observer.SavedTabGroupUpdatedLocally(group_id,
                                           pending_ntp->saved_tab_guid());
    }
  }

  // TODO(dljames): Update to use SavedTabGroupRemoveFromSync and update the API
  // to pass a group_id and an optional tab_id.
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(group_id, copy_tab_id);
  }
}

void SavedTabGroupModel::MoveTabInGroupTo(const base::Uuid& group_id,
                                          const base::Uuid& tab_id,
                                          int new_index) {
  if (!Contains(group_id)) {
    return;
  }

  // Copy `tab_id` to prevent uaf when ungrouping a saved tab: crbug/1401965.
  const base::Uuid copy_tab_id = tab_id;
  std::optional<int> index = GetIndexOf(group_id);
  saved_tab_groups_[index.value()].MoveTabLocally(tab_id, new_index);

  for (SavedTabGroupModelObserver& observer : observers_) {
    // TODO(crbug.com/40919583): Consider further optimizations.
    observer.SavedTabGroupTabMovedLocally(group_id, copy_tab_id);
  }
}

void SavedTabGroupModel::UpdateLastUserInteractionTimeLocally(
    const LocalTabGroupID& local_group_id) {
  SavedTabGroup* group = GetMutableGroup(local_group_id);
  CHECK(group);

  group->SetLastUserInteractionTime(base::Time::Now());

  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.SavedTabGroupLastUserInteractionTimeUpdated(group->saved_guid());
  }
}

void SavedTabGroupModel::UpdateTabLastSeenTime(const base::Uuid& group_id,
                                               const base::Uuid& tab_id,
                                               base::Time time,
                                               TriggerSource source) {
  SavedTabGroup* group = GetMutableGroup(group_id);
  CHECK(group);

  if (!group->is_shared_tab_group()) {
    return;
  }

  SavedTabGroupTab* tab = group->GetTab(tab_id);
  CHECK(tab);

  // If the new time is not more recent than the one in the model,
  // ignore it. This data is managed by the account data sync bridge,
  // which always prefers the more recent time.
  const std::optional<base::Time>& current_model_time = tab->last_seen_time();
  if (current_model_time.has_value() && current_model_time.value() >= time) {
    return;
  }

  // Optimization: If the tab is already seen, we don't need to update the
  // timestamp again (e.g. due to a tab selection event locally) which will save
  // a redundant update to sync.
  if (source == TriggerSource::LOCAL && tab->last_seen_time().has_value() &&
      tab->last_seen_time() >= tab->navigation_time()) {
    return;
  }

  tab->SetLastSeenTime(time);

  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.SavedTabGroupTabLastSeenTimeUpdated(tab_id, source);
  }
}

void SavedTabGroupModel::UpdatePositionForSharedGroupFromSync(
    const base::Uuid& group_id,
    std::optional<size_t> position) {
  const SavedTabGroup* group = Get(group_id);
  if (!group || !group->is_shared_tab_group() ||
      group->position() == position) {
    return;
  }

  // Remove the tab group, set position and reinsert.
  const int index = GetIndexOf(group_id).value();
  SavedTabGroup saved_group = RemoveImpl(index);
  if (position.has_value()) {
    saved_group.SetPosition(position.value());
  } else {
    saved_group.SetPinned(false);
  }
  InsertGroupImpl(std::move(saved_group));

  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(group_id, /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::UpdateLastUpdaterCacheGuidForGroup(
    const std::optional<std::string>& cache_guid,
    const LocalTabGroupID& group_id,
    const std::optional<LocalTabID>& tab_id) {
  const std::optional<int> index = GetIndexOf(group_id);
  if (!index.has_value()) {
    return;
  }

  SavedTabGroup& group = saved_tab_groups_[index.value()];
  group.SetLastUpdaterCacheGuid(cache_guid);

  if (!tab_id.has_value()) {
    return;
  }

  auto* tab = group.GetTab(tab_id.value());
  if (tab) {
    tab->SetLastUpdaterCacheGuid(cache_guid);
  }
}

void SavedTabGroupModel::UpdateSharedAttribution(
    const LocalTabGroupID& group_id,
    const std::optional<LocalTabID>& tab_id,
    GaiaId updated_by) {
  SavedTabGroup* group = GetMutableGroup(group_id);
  CHECK(group);
  if (!tab_id.has_value()) {
    group->SetUpdatedByAttribution(std::move(updated_by));
    return;
  }

  SavedTabGroupTab* tab = group->GetTab(tab_id.value());
  if (tab) {
    tab->SetUpdatedByAttribution(std::move(updated_by));
  }

  // Do not notify observers to avoid having too many updates because this
  // method is called quite extensively and in most cases duplicates the other
  // updates.
}

const SavedTabGroup* SavedTabGroupModel::MergeRemoteGroupMetadata(
    const base::Uuid& guid,
    const std::u16string& title,
    TabGroupColorId color,
    std::optional<size_t> position,
    std::optional<std::string> creator_cache_guid,
    std::optional<std::string> last_updater_cache_guid,
    base::Time update_time,
    const GaiaId& updated_by) {
  CHECK(Contains(guid));

  // For unpinned groups, `pinned_index` should be std::nullopt since its
  // position doesn't matter.
  const int index = GetIndexOf(guid).value();
  const std::optional<size_t> pinned_index =
      saved_tab_groups_[index].is_pinned() ? std::optional<size_t>(index)
                                           : std::nullopt;

  // Merge group and get `preferred_pinned_index`.
  saved_tab_groups_[index].MergeRemoteGroupMetadata(
      title, color, position, creator_cache_guid, last_updater_cache_guid,
      update_time);
  if (saved_tab_groups_[index].is_shared_tab_group()) {
    saved_tab_groups_[index].SetUpdatedByAttribution(updated_by);
  }
  std::optional<size_t> preferred_pinned_index =
      saved_tab_groups_[index].position();

  if (pinned_index != preferred_pinned_index) {
    int new_index = 0;
    if (preferred_pinned_index.has_value()) {
      // If the group is pinned, find the pinned position to insert.
      new_index = preferred_pinned_index.value();
    } else {
      // If the group is unpinned, find the first unpinned group index to
      // insert.
      for (const SavedTabGroup& group : saved_tab_groups_) {
        if (group.is_pinned()) {
          ++new_index;
        }
      }
    }

    ReorderGroupFromSync(guid, std::min(std::max(new_index, 0), Count() - 1));
  }

  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(guid, /*tab_guid=*/std::nullopt);
  }

  // Note that `index` can't be used anymore because groups could be re-ordered.
  return Get(guid);
}

const SavedTabGroupTab* SavedTabGroupModel::MergeRemoteTab(
    const SavedTabGroupTab& remote_tab) {
  const base::Uuid& group_guid = remote_tab.saved_group_guid();
  const base::Uuid& tab_guid = remote_tab.saved_tab_guid();
  SavedTabGroup* const group = MutableGroupContainingTab(tab_guid);
  CHECK(group);
  CHECK_EQ(group->saved_guid(), group_guid);

  const std::optional<int> index = group->GetIndexOfTab(tab_guid);

  // TODO(crbug.com/370714643): check that remote tab always contains position.
  const int preferred_index = remote_tab.position().value_or(0);

  group->GetTab(tab_guid)->MergeRemoteTab(remote_tab);

  if (index != preferred_index) {
    const int num_tabs = group->saved_tabs().size();
    const int new_index =
        preferred_index < num_tabs ? preferred_index : num_tabs - 1;
    group->MoveTabFromSync(tab_guid, std::max(new_index, 0));
  }

  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(group_guid, tab_guid);
  }

  return group->GetTab(tab_guid);
}

void SavedTabGroupModel::ReorderGroupLocally(const base::Uuid& id,
                                             int new_index) {
  ReorderGroupImpl(id, new_index);
  UpdateGroupPositionsImpl();
  for (auto& observer : observers_) {
    observer.SavedTabGroupReorderedLocally();
  }
}

void SavedTabGroupModel::ReorderGroupFromSync(const base::Uuid& id,
                                              int new_index) {
  ReorderGroupImpl(id, new_index);
  for (auto& observer : observers_) {
    observer.SavedTabGroupReorderedFromSync();
  }
}

std::pair<std::set<base::Uuid>, std::set<base::Uuid>>
SavedTabGroupModel::UpdateLocalCacheGuid(
    std::optional<std::string> old_cache_guid,
    std::optional<std::string> new_cache_guid) {
  std::set<base::Uuid> updated_group_ids;
  std::set<base::Uuid> updated_tab_ids;
  // Update the group cache guids.
  for (SavedTabGroup& saved_group : saved_tab_groups_) {
    // Only saved tab groups use creator cache GUID.
    if (saved_group.is_shared_tab_group() ||
        saved_group.creator_cache_guid() != old_cache_guid) {
      continue;
    }

    saved_group.SetCreatorCacheGuid(new_cache_guid);
    updated_group_ids.insert(saved_group.saved_guid());
  }

  for (SavedTabGroup& saved_group : saved_tab_groups_) {
    // Only saved tab groups use creator cache GUID.
    if (saved_group.is_shared_tab_group()) {
      continue;
    }

    // Update the tabs in the group with the new cache guid.
    for (SavedTabGroupTab& saved_tab : saved_group.saved_tabs()) {
      if (saved_tab.creator_cache_guid() != old_cache_guid) {
        continue;
      }

      saved_tab.SetCreatorCacheGuid(new_cache_guid);
      updated_tab_ids.insert(saved_tab.saved_tab_guid());
    }
  }

  return std::make_pair(std::move(updated_group_ids),
                        std::move(updated_tab_ids));
}

void SavedTabGroupModel::CreatePendingNtp(SavedTabGroup& group) {
  CHECK(group.saved_tabs().empty());

  SavedTabGroupTab pending_ntp(GURL(kPendingNtpURL), kPendingNtpTitle,
                               group.saved_guid(), /*position=*/std::nullopt);
  pending_ntp.SetIsPendingNtp(true);
  group.AddTabLocally(std::move(pending_ntp));
}

void SavedTabGroupModel::StartSyncingPendingNtpIfAny(SavedTabGroup& group) {
  SavedTabGroupTab* pending_ntp = FindPendingNtpInGroup(group);
  if (pending_ntp) {
    pending_ntp->SetIsPendingNtp(false);
  }
}

void SavedTabGroupModel::MergePendingNtpWithIncomingTabIfAny(
    SavedTabGroup& group,
    const base::Uuid& tab_id) {
  SavedTabGroupTab* tab = group.GetTab(tab_id);
  CHECK(tab);

  SavedTabGroupTab* pending_ntp = FindPendingNtpInGroup(group);
  if (!pending_ntp) {
    return;
  }

  // Copy over local tab ID of the pending NTP to the incoming sync tab and then
  // delete it from the group.
  tab->SetLocalTabID(pending_ntp->local_tab_id());
  group.RemoveTabFromSync(pending_ntp->saved_tab_guid(),
                          /*removed_by=*/GaiaId());
}

SavedTabGroupTab* SavedTabGroupModel::FindPendingNtpInGroup(
    SavedTabGroup& group) {
  SavedTabGroupTab* pending_ntp = nullptr;
  size_t pending_ntp_count = 0;
  for (SavedTabGroupTab& saved_tab : group.saved_tabs()) {
    if (saved_tab.is_pending_ntp()) {
      pending_ntp = &saved_tab;
      pending_ntp_count++;
    }
  }

  // There should never be more than one pending NTP in a group.
  CHECK_LE(pending_ntp_count, 1u);
  return pending_ntp;
}

void SavedTabGroupModel::LoadStoredEntries(std::vector<SavedTabGroup> groups,
                                           std::vector<SavedTabGroupTab> tabs) {
  // `entries` is not ordered such that groups are guaranteed to be
  // at the front of the vector. As such, we can run into the case where we
  // try to add a tab to a group that does not exist for us yet.
  for (SavedTabGroup& group : groups) {
    // TODO(crbug.com/375636822): AddedLocally doesn't make sense here. This
    // should probably use a separate path that doesn't notify observers.
    AddedLocally(std::move(group));
  }
  UpdateGroupPositionsImpl();

  for (SavedTabGroupTab& tab : tabs) {
    base::Uuid group_id = tab.saved_group_guid();
    // The caller must guarantee that all `tabs` have a corresponding group.
    CHECK(Contains(group_id));
    AddTabToGroupFromSync(group_id, std::move(tab));
  }

  is_loaded_ = true;

  for (auto& observer : observers_) {
    observer.SavedTabGroupModelLoaded();
  }
}

void SavedTabGroupModel::OnGroupClosedInTabStrip(
    const LocalTabGroupID& tab_group_id) {
  const std::optional<int> index = GetIndexOf(tab_group_id);
  if (!index.has_value()) {
    return;
  }

  SavedTabGroup& saved_group = saved_tab_groups_[index.value()];
  saved_group.SetLocalGroupId(std::nullopt);

  // Remove the ID mappings from the tabs as well, since the group is closed.
  for (SavedTabGroupTab& saved_tab : saved_group.saved_tabs()) {
    saved_tab.SetLocalTabID(std::nullopt);
  }

  for (auto& observer : observers_) {
    observer.SavedTabGroupLocalIdChanged(saved_group.saved_guid());
  }

  base::RecordAction(
      base::UserMetricsAction("TabGroups_SavedTabGroups_Closed"));
}

void SavedTabGroupModel::OnGroupOpenedInTabStrip(
    const base::Uuid& id,
    const LocalTabGroupID& tab_group_id) {
  const std::optional<int> index = GetIndexOf(id);
  CHECK(index.has_value());
  CHECK_GE(index.value(), 0);

  SavedTabGroup& saved_group = saved_tab_groups_[index.value()];
  saved_group.SetLocalGroupId(tab_group_id);

  for (auto& observer : observers_) {
    observer.SavedTabGroupLocalIdChanged(saved_group.saved_guid());
  }
}

void SavedTabGroupModel::AddObserver(SavedTabGroupModelObserver* observer) {
  observers_.AddObserver(observer);
}

void SavedTabGroupModel::RemoveObserver(SavedTabGroupModelObserver* observer) {
  observers_.RemoveObserver(observer);
}

void SavedTabGroupModel::MigrateTabGroupSavesUIUpdate() {
  constexpr size_t kMaxNumberOfGroupToPin = 4;
  // Pin the first 4 saved tab groups from V1.
  for (size_t i = 0;
       i < std::min(saved_tab_groups_.size(), kMaxNumberOfGroupToPin); ++i) {
    saved_tab_groups_[i].SetPosition(i);
    for (auto& observer : observers_) {
      observer.SavedTabGroupUpdatedLocally(saved_tab_groups_[i].saved_guid(),
                                           /*tab_guid=*/std::nullopt);
    }
  }
}

void SavedTabGroupModel::MarkTransitionedToShared(
    const base::Uuid& shared_group_id) {
  SavedTabGroup* group = GetMutableGroup(shared_group_id);
  CHECK(group);
  group->MarkTransitionedToShared();
  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(group->saved_guid(),
                                         /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::SetGroupHidden(
    const base::Uuid& originating_group_id) {
  SavedTabGroup* group = GetMutableGroup(originating_group_id);
  CHECK(group);
  group->SetIsHidden(true);
  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(group->saved_guid(),
                                         /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::RestoreHiddenGroupFromSync(
    const base::Uuid& group_id) {
  SavedTabGroup* group = GetMutableGroup(group_id);
  CHECK(group);
  group->SetIsHidden(false);
  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.SavedTabGroupUpdatedFromSync(group->saved_guid(),
                                          /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::OnSyncBridgeUpdateTypeChanged(
    SyncBridgeUpdateType sync_bridge_update_type) {
  for (SavedTabGroupModelObserver& observer : observers_) {
    observer.OnSyncBridgeUpdateTypeChanged(sync_bridge_update_type);
  }
}

SavedTabGroup* SavedTabGroupModel::MutableGroupContainingTab(
    const base::Uuid& saved_tab_guid) {
  return const_cast<SavedTabGroup*>(GetGroupContainingTab(saved_tab_guid));
}

SavedTabGroup* SavedTabGroupModel::GetMutableGroup(
    const LocalTabGroupID& local_group_id) {
  return const_cast<SavedTabGroup*>(Get(local_group_id));
}

SavedTabGroup* SavedTabGroupModel::GetMutableGroup(const base::Uuid& id) {
  return const_cast<SavedTabGroup*>(Get(id));
}

void SavedTabGroupModel::ReorderGroupImpl(const base::Uuid& id, int new_index) {
  CHECK_GE(new_index, 0);
  CHECK_LT(new_index, Count());

  std::optional<int> index = GetIndexOf(id);
  CHECK(index.has_value());
  CHECK_GE(index.value(), 0);

  SavedTabGroup group = std::move(saved_tab_groups_[index.value()]);

  saved_tab_groups_.erase(saved_tab_groups_.begin() + index.value());
  saved_tab_groups_.emplace(saved_tab_groups_.begin() + new_index,
                            std::move(group));
}

void SavedTabGroupModel::UpdateGroupPositionsImpl() {
  for (size_t i = 0; i < saved_tab_groups_.size(); ++i) {
    //  Only update position for tab groups for which position is set.
    if (saved_tab_groups_[i].position().has_value()) {
      saved_tab_groups_[i].SetPosition(i);
    }
  }
}

void SavedTabGroupModel::InsertGroupImpl(SavedTabGroup group) {
  size_t index;
  for (index = 0; index < saved_tab_groups_.size(); ++index) {
    const SavedTabGroup& curr_group = saved_tab_groups_[index];

    if (ShouldPlaceBefore(group, curr_group)) {
      break;
    }
  }
  saved_tab_groups_.insert(saved_tab_groups_.begin() + index, std::move(group));
}

SavedTabGroup SavedTabGroupModel::RemoveImpl(size_t index) {
  CHECK_LT(index, saved_tab_groups_.size());
  SavedTabGroup removed_group = std::move(saved_tab_groups_[index]);
  saved_tab_groups_.erase(saved_tab_groups_.begin() + index);
  return removed_group;
}

void SavedTabGroupModel::UpdateVisualDataImpl(
    int index,
    const tab_groups::TabGroupVisualData* visual_data) {
  SavedTabGroup& saved_group = saved_tab_groups_[index];
  if (saved_group.title() == visual_data->title() &&
      saved_group.color() == visual_data->color()) {
    return;
  }

  saved_group.SetTitle(visual_data->title());
  saved_group.SetColor(visual_data->color());
}

void SavedTabGroupModel::TogglePinState(base::Uuid id) {
  if (!Contains(id)) {
    return;
  }
  const int index = GetIndexOf(id).value();
  SavedTabGroup saved_group = RemoveImpl(index);
  bool was_pinned = saved_group.is_pinned();
  saved_group.SetPinned(!saved_group.is_pinned());
  InsertGroupImpl(std::move(saved_group));
  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(id, /*tab_guid=*/std::nullopt);
  }

  if (was_pinned) {
    base::RecordAction(
        base::UserMetricsAction("TabGroups_SavedTabGroups_Unpinned"));
  } else {
    base::RecordAction(
        base::UserMetricsAction("TabGroups_SavedTabGroups_Pinned"));
  }
}

void SavedTabGroupModel::UpdateArchivalStatus(const base::Uuid& id,
                                              bool archival_status) {
  SavedTabGroup* const group = GetMutableGroup(id);
  CHECK(group);
  std::optional<base::Time> archival_time;
  if (archival_status) {
    archival_time = base::Time::Now();
  }
  group->SetArchivalTime(archival_time);

  for (auto& observer : observers_) {
    observer.SavedTabGroupUpdatedLocally(id, /*tab_guid=*/std::nullopt);
  }
}

void SavedTabGroupModel::HandleTabGroupRemovedFromSync(int index) {
  // If this is a shared group that is transitioning to saved, make the
  // transition complete and that will delete the shared group during the
  // process.
  SavedTabGroup* group = &saved_tab_groups_[index];
  if (group->is_shared_tab_group() && group->is_transitioning_to_saved()) {
    for (auto& observer : observers_) {
      observer.TabGroupTransitioningToSavedRemovedFromSync(group->saved_guid());
    }
    return;
  }
  SavedTabGroup removed_group = RemoveImpl(index);
  for (auto& observer : observers_) {
    observer.SavedTabGroupRemovedFromSync(removed_group);
  }
}
}  // namespace tab_groups