File: tab_search_page_handler.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; 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 (1793 lines) | stat: -rw-r--r-- 66,861 bytes parent folder | download | duplicates (2)
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
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/tab_search/tab_search_page_handler.h"

#include <stdint.h>

#include <algorithm>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "base/base64.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "chrome/browser/favicon/favicon_utils.h"
#include "chrome/browser/feedback/show_feedback_page.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/tab_restore_service_factory.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/signin_error_controller_factory.h"
#include "chrome/browser/signin/signin_ui_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_live_tab_context.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/browser_window/public/browser_window_features.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/tabs/alert/tab_alert.h"
#include "chrome/browser/ui/tabs/organization/tab_declutter_controller.h"
#include "chrome/browser/ui/tabs/organization/tab_organization_request.h"
#include "chrome/browser/ui/tabs/organization/tab_organization_service.h"
#include "chrome/browser/ui/tabs/organization/tab_organization_service_factory.h"
#include "chrome/browser/ui/tabs/organization/tab_organization_session.h"
#include "chrome/browser/ui/tabs/organization/tab_organization_utils.h"
#include "chrome/browser/ui/tabs/tab_enums.h"
#include "chrome/browser/ui/tabs/tab_renderer_data.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "chrome/browser/ui/tabs/tab_utils.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/metrics_reporter/metrics_reporter.h"
#include "chrome/browser/ui/webui/tab_search/tab_search_prefs.h"
#include "chrome/browser/ui/webui/util/image_util.h"
#include "chrome/browser/ui/webui/webui_embedding_context.h"
#include "chrome/browser/user_education/tutorial_identifiers.h"
#include "chrome/browser/user_education/user_education_service.h"
#include "chrome/browser/user_education/user_education_service_factory.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "components/optimization_guide/core/optimization_guide_model_executor.h"
#include "components/optimization_guide/proto/model_quality_service.pb.h"
#include "components/signin/public/base/signin_metrics.h"
#include "components/tabs/public/tab_interface.h"
#include "components/user_education/common/tutorial/tutorial_identifier.h"
#include "components/user_education/common/tutorial/tutorial_service.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/time_format.h"
#include "ui/color/color_provider.h"

namespace {
constexpr base::TimeDelta kTabsChangeDelay = base::Milliseconds(50);

std::string GetLastActiveElapsedText(
    const base::TimeTicks& last_active_time_ticks) {
  const base::TimeDelta elapsed =
      base::TimeTicks::Now() - last_active_time_ticks;
  return base::UTF16ToUTF8(ui::TimeFormat::Simple(
      ui::TimeFormat::FORMAT_ELAPSED, ui::TimeFormat::LENGTH_SHORT, elapsed));
}

std::string GetLastActiveElapsedText(const base::Time& last_active_time) {
  const base::TimeDelta elapsed = base::Time::Now() - last_active_time;
  return base::UTF16ToUTF8(ui::TimeFormat::Simple(
      ui::TimeFormat::FORMAT_ELAPSED, ui::TimeFormat::LENGTH_SHORT, elapsed));
}

std::string GetLastActiveElapsedTextForDeclutter(
    const base::Time& last_active_time) {
  const base::TimeDelta elapsed = base::Time::Now() - last_active_time;
  return l10n_util::GetPluralStringFUTF8(IDS_DECLUTTER_TIMESTAMP,
                                         elapsed.InDays());
}

// If Tab Group has no timestamp, we find the tab in the tab group with
// the most recent navigation last active time.
base::Time GetTabGroupTimeStamp(
    const std::vector<std::unique_ptr<sessions::tab_restore::Tab>>& tabs) {
  base::Time last_active_time;
  for (const auto& tab : tabs) {
    const sessions::SerializedNavigationEntry& entry =
        tab->navigations[tab->current_navigation_index];
    if (entry.timestamp() > last_active_time) {
      last_active_time = entry.timestamp();
    }
  }
  return last_active_time;
}

// If a recently closed tab is associated to a group that is no longer
// open we create a TabGroup entry with the required fields to support
// rendering the tab's associated group information in the UI.
void CreateTabGroupIfNotPresent(
    sessions::tab_restore::Tab* tab,
    std::set<tab_groups::TabGroupId>& tab_group_ids,
    std::vector<tab_search::mojom::TabGroupPtr>& tab_groups) {
  if (tab->group.has_value() &&
      !base::Contains(tab_group_ids, tab->group.value())) {
    tab_groups::TabGroupId tab_group_id = tab->group.value();
    const tab_groups::TabGroupVisualData* tab_group_visual_data =
        &tab->group_visual_data.value();
    auto tab_group = tab_search::mojom::TabGroup::New();
    tab_group->id = tab_group_id.token();
    tab_group->color = tab_group_visual_data->color();
    tab_group->title = base::UTF16ToUTF8(tab_group_visual_data->title());

    tab_group_ids.insert(tab_group_id);
    tab_groups.push_back(std::move(tab_group));
  }
}

// Applies theming to favicons where necessary. This is needed to handle favicon
// resources that are rasterized in a theme-unaware way. This is common of
// favicons not sourced directly from the browser.
gfx::ImageSkia ThemeFavicon(const gfx::ImageSkia& source,
                            const ui::ColorProvider& provider) {
  return favicon::ThemeFavicon(
      source, provider.GetColor(kColorTabSearchPrimaryForeground),
      provider.GetColor(kColorTabSearchBackground),
      provider.GetColor(kColorTabSearchBackground));
}

TabOrganization* GetTabOrganization(TabOrganizationService* service,
                                    Browser* browser,
                                    int32_t session_id,
                                    int32_t organization_id) {
  if (!service) {
    return nullptr;
  }

  TabOrganizationSession* session = service->GetSessionForBrowser(browser);
  if (!session || session->session_id() != session_id) {
    return nullptr;
  }

  TabOrganization* matching_organization = nullptr;
  for (const std::unique_ptr<TabOrganization>& organization :
       session->tab_organizations()) {
    if (organization->organization_id() == organization_id) {
      matching_organization = organization.get();
      break;
    }
  }

  return matching_organization;
}

tab_search::mojom::TabOrganizationSessionPtr CreateFailedMojoSession() {
  tab_search::mojom::TabOrganizationSessionPtr mojo_session =
      tab_search::mojom::TabOrganizationSession::New();
  mojo_session->state = tab_search::mojom::TabOrganizationState::kFailure;
  mojo_session->error = tab_search::mojom::TabOrganizationError::kGeneric;

  return mojo_session;
}

tab_search::mojom::TabOrganizationSessionPtr CreateNotStartedMojoSession() {
  tab_search::mojom::TabOrganizationSessionPtr mojo_session =
      tab_search::mojom::TabOrganizationSession::New();
  mojo_session->state = tab_search::mojom::TabOrganizationState::kNotStarted;

  return mojo_session;
}

}  // namespace

DuplicateTabsObserver::DuplicateTabsObserver(
    content::WebContents* web_contents,
    base::RepeatingCallback<void()> on_url_changed_callback)
    : content::WebContentsObserver(web_contents),
      on_url_changed_callback_(std::move(on_url_changed_callback)) {}

DuplicateTabsObserver::~DuplicateTabsObserver() = default;

void DuplicateTabsObserver::PrimaryPageChanged(content::Page& page) {
  if (on_url_changed_callback_) {
    on_url_changed_callback_.Run();
  }
}

TabSearchPageHandler::TabSearchPageHandler(
    mojo::PendingReceiver<tab_search::mojom::PageHandler> receiver,
    mojo::PendingRemote<tab_search::mojom::Page> page,
    content::WebUI* web_ui,
    TopChromeWebUIController* webui_controller,
    MetricsReporter* metrics_reporter)
    : optimization_guide::SettingsEnabledObserver(
          optimization_guide::UserVisibleFeatureKey::kTabOrganization),
      receiver_(this, std::move(receiver)),
      page_(std::move(page)),
      web_ui_(web_ui),
      webui_controller_(webui_controller),
      metrics_reporter_(metrics_reporter),
      debounce_timer_(std::make_unique<base::RetainingOneShotTimer>(
          FROM_HERE,
          kTabsChangeDelay,
          base::BindRepeating(&TabSearchPageHandler::NotifyTabsChanged,
                              base::Unretained(this)))),
      browser_window_changed_subscription_(
          webui::RegisterBrowserWindowInterfaceChanged(
              web_ui->GetWebContents(),
              base::BindRepeating(
                  &TabSearchPageHandler::BrowserWindowInterfaceChanged,
                  base::Unretained(this)))) {
  browser_tab_strip_tracker_.Init();
  Profile* profile = Profile::FromWebUI(web_ui_);
  pref_change_registrar_.Init(profile->GetPrefs());
  pref_change_registrar_.Add(
      tab_search_prefs::kTabSearchTabIndex,
      base::BindRepeating(&TabSearchPageHandler::NotifyTabIndexPrefChanged,
                          base::Unretained(this), profile));
  pref_change_registrar_.Add(
      tab_search_prefs::kTabOrganizationFeature,
      base::BindRepeating(
          &TabSearchPageHandler::NotifyOrganizationFeaturePrefChanged,
          base::Unretained(this), profile));
  pref_change_registrar_.Add(
      tab_search_prefs::kTabOrganizationShowFRE,
      base::BindRepeating(&TabSearchPageHandler::NotifyShowFREPrefChanged,
                          base::Unretained(this), profile));
  organization_service_ = TabOrganizationServiceFactory::GetForProfile(profile);
  if (organization_service_) {
    tab_organization_observation_.Observe(organization_service_);
  }
  optimization_guide_keyed_service_ =
      OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
  if (optimization_guide_keyed_service_) {
    optimization_guide_keyed_service_->AddModelExecutionSettingsEnabledObserver(
        this);
  }
  BrowserWindowInterfaceChanged();
}

TabSearchPageHandler::~TabSearchPageHandler() {
  base::UmaHistogramCounts1000("Tabs.TabSearch.NumTabsClosedPerInstance",
                               num_tabs_closed_);
  base::UmaHistogramEnumeration("Tabs.TabSearch.CloseAction",
                                called_switch_to_tab_
                                    ? TabSearchCloseAction::kTabSwitch
                                    : TabSearchCloseAction::kNoAction);
  for (TabOrganizationSession* session : listened_sessions_) {
    session->RemoveObserver(this);
  }
  if (optimization_guide_keyed_service_) {
    optimization_guide_keyed_service_
        ->RemoveModelExecutionSettingsEnabledObserver(this);
  }
  pref_change_registrar_.Reset();
}

void TabSearchPageHandler::CloseTab(int32_t tab_id) {
  std::optional<TabDetails> details = GetTabDetails(tab_id);
  if (!details) {
    return;
  }

  ++num_tabs_closed_;

  // CloseTab() can target the WebContents hosting Tab Search if the Tab Search
  // WebUI is open in a chrome browser tab rather than its bubble. In this case
  // CloseWebContentsAt() closes the WebContents hosting this
  // TabSearchPageHandler object, causing it to be immediately destroyed. Ensure
  // that no further actions are performed following the call to
  // CloseWebContentsAt(). See (https://crbug.com/1175507).
  TabStripModel* const tab_strip_model =
      details->tab->GetBrowserWindowInterface()->GetTabStripModel();
  CHECK(tab_strip_model);
  const int index = details->GetIndex();
  // Don't dangle a tabs::TabInterface* in `details`.
  details.reset();
  tab_strip_model->CloseWebContentsAt(
      index, TabCloseTypes::CLOSE_CREATE_HISTORICAL_TAB);
  // Do not add code past this point.
}

void TabSearchPageHandler::DeclutterTabs(const std::vector<int32_t>& tab_ids,
                                         const std::vector<GURL>& urls) {
  // TODO(crbug.com/358382903): Add metrics logging.
  // Potentially also invoke IPH pending UX.
  if (!tab_declutter_controller_) {
    return;
  }

  std::vector<tabs::TabInterface*> tabs;

  // Add tabs that are present in the current browser.
  for (const int32_t tab_id : tab_ids) {
    const std::optional<TabDetails> details = GetTabDetails(tab_id);
    if (!details ||
        details->tab->GetBrowserWindowInterface()->GetTabStripModel() !=
            tab_declutter_controller_->tab_strip_model()) {
      continue;
    }

    tabs.push_back(details->tab);
  }
  tab_declutter_controller_->DeclutterTabs(tabs, urls);

  auto embedder = webui_controller_->embedder();
  if (embedder) {
    embedder->CloseUI();
  }
}

void TabSearchPageHandler::AcceptTabOrganization(
    int32_t session_id,
    int32_t organization_id,
    std::vector<tab_search::mojom::TabPtr> tabs) {
  if (!organization_service_) {
    return;
  }

  TabOrganization* organization = GetTabOrganization(
      organization_service_, browser_, session_id, organization_id);
  if (!organization) {
    return;
  }

  std::unordered_set<int> tabs_tab_ids;
  for (tab_search::mojom::TabPtr& tab : tabs) {
    tabs_tab_ids.emplace(tab->tab_id);
  }

  std::vector<TabData::TabID> tab_ids_to_remove;
  for (const auto& tab_data : organization->tab_datas()) {
    if (!tab_data->tab()->GetContents() ||
        !base::Contains(tabs_tab_ids, tab_data->tab_id())) {
      tab_ids_to_remove.emplace_back(tab_data->tab_id());
    }
  }

  for (const auto& tab_id : tab_ids_to_remove) {
    organization->RemoveTabData(tab_id);
  }

  organization_service_->AcceptTabOrganization(browser_, session_id,
                                               organization_id);

  auto embedder = webui_controller_->embedder();
  if (embedder) {
    embedder->CloseUI();
  }
}

void TabSearchPageHandler::RejectTabOrganization(int32_t session_id,
                                                 int32_t organization_id) {
  TabOrganization* organization = GetTabOrganization(
      organization_service_, browser_, session_id, organization_id);
  if (!organization) {
    return;
  }

  organization->Reject();
}

void TabSearchPageHandler::RenameTabOrganization(int32_t session_id,
                                                 int32_t organization_id,
                                                 const std::u16string& name) {
  TabOrganization* organization = GetTabOrganization(
      organization_service_, browser_, session_id, organization_id);
  if (!organization) {
    return;
  }

  organization->SetCurrentName(name);
}

void TabSearchPageHandler::ExcludeFromStaleTabs(int32_t tab_id) {
  if (!tab_declutter_controller_) {
    return;
  }

  std::optional<TabDetails> details = GetTabDetails(tab_id);

  if (!details ||
      details->tab->GetBrowserWindowInterface()->GetTabStripModel() !=
          tab_declutter_controller_->tab_strip_model()) {
    return;
  }

  tab_declutter_controller_->ExcludeFromStaleTabs(details->tab);

  RemoveStaleTab(details->tab);

  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

void TabSearchPageHandler::ExcludeFromDuplicateTabs(const GURL& url) {
  if (!tab_declutter_controller_) {
    return;
  }

  CHECK(duplicate_tabs_.count(url.GetWithoutRef()) > 0);

  tab_declutter_controller_->ExcludeFromDuplicateTabs(url.GetWithoutRef());

  std::vector<tabs::TabInterface*> tabs = duplicate_tabs_[url.GetWithoutRef()];

  for (tabs::TabInterface* tab : tabs) {
    RemoveDuplicateTab(tab);
  }

  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

void TabSearchPageHandler::RegisterInactiveTabDeclutterCallbacks(
    tabs::TabInterface* tab) {
  std::vector<base::CallbackListSubscription> subscriptions;

  subscriptions.push_back(tab->RegisterDidActivate(
      base::BindRepeating(&TabSearchPageHandler::OnStaleTabDidEnterForeground,
                          base::Unretained(this))));

  subscriptions.push_back(tab->RegisterWillDetach(base::BindRepeating(
      [](TabSearchPageHandler* handler, tabs::TabInterface* tab,
         tabs::TabInterface::DetachReason reason) {
        handler->OnUnusedTabWillDetach(tab, reason, UnusedTabType::kInactive);
      },
      base::Unretained(this))));

  subscriptions.push_back(tab->RegisterPinnedStateChanged(base::BindRepeating(
      [](TabSearchPageHandler* handler, tabs::TabInterface* tab,
         bool new_pinned_state) {
        handler->OnUnusedTabPinnedStateChanged(tab, new_pinned_state,
                                               UnusedTabType::kInactive);
      },
      base::Unretained(this))));

  subscriptions.push_back(tab->RegisterGroupChanged(base::BindRepeating(
      [](TabSearchPageHandler* handler, tabs::TabInterface* tab,
         std::optional<tab_groups::TabGroupId> new_group) {
        handler->OnUnusedTabGroupChanged(tab, new_group,
                                         UnusedTabType::kInactive);
      },
      base::Unretained(this))));

  inactive_tab_subscriptions_map_[tab] = std::move(subscriptions);
}

void TabSearchPageHandler::RegisterDuplicateTabDeclutterCallbacks(
    tabs::TabInterface* tab) {
  std::vector<base::CallbackListSubscription> subscriptions;

  subscriptions.push_back(tab->RegisterWillDetach(base::BindRepeating(
      [](TabSearchPageHandler* handler, tabs::TabInterface* tab,
         tabs::TabInterface::DetachReason reason) {
        handler->OnUnusedTabWillDetach(tab, reason, UnusedTabType::kDuplicate);
      },
      base::Unretained(this))));

  subscriptions.push_back(tab->RegisterPinnedStateChanged(base::BindRepeating(
      [](TabSearchPageHandler* handler, tabs::TabInterface* tab,
         bool new_pinned_state) {
        handler->OnUnusedTabPinnedStateChanged(tab, new_pinned_state,
                                               UnusedTabType::kDuplicate);
      },
      base::Unretained(this))));

  subscriptions.push_back(tab->RegisterGroupChanged(base::BindRepeating(
      [](TabSearchPageHandler* handler, tabs::TabInterface* tab,
         std::optional<tab_groups::TabGroupId> new_group) {
        handler->OnUnusedTabGroupChanged(tab, new_group,
                                         UnusedTabType::kDuplicate);
      },
      base::Unretained(this))));

  subscriptions.push_back(tab->RegisterWillDiscardContents(base::BindRepeating(
      &TabSearchPageHandler::OnDuplicateTabWillDiscardWebContents,
      base::Unretained(this))));

  content::WebContents* web_contents = tab->GetContents();
  if (web_contents) {
    auto observer = std::make_unique<DuplicateTabsObserver>(
        web_contents,
        base::BindRepeating(
            [](TabSearchPageHandler* handler, tabs::TabInterface* tab) {
              handler->RemoveDuplicateTab(tab);
              handler->page_->UnusedTabsChanged(handler->GetMojoUnusedTabs());
            },
            base::Unretained(this), tab));

    duplicate_tab_webcontents_observers_[tab] = std::move(observer);
  }

  duplicate_tab_subscriptions_map_[tab] = std::move(subscriptions);
}

void TabSearchPageHandler::UnregisterTabCallbacks() {
  inactive_tab_subscriptions_map_.clear();
  duplicate_tab_subscriptions_map_.clear();
  duplicate_tab_webcontents_observers_.clear();
}

void TabSearchPageHandler::RemoveStaleTab(tabs::TabInterface* tab) {
  CHECK(tab);
  CHECK(std::find(stale_tabs_.begin(), stale_tabs_.end(), tab) !=
        stale_tabs_.end());
  CHECK(inactive_tab_subscriptions_map_.find(tab) !=
        inactive_tab_subscriptions_map_.end());

  // Remove the TabInterface from stale_tabs_
  std::erase(stale_tabs_, tab);

  // Unregister the subscriptions for this TabInterface
  inactive_tab_subscriptions_map_.erase(tab);
}

void TabSearchPageHandler::RemoveDuplicateTab(tabs::TabInterface* tab) {
  CHECK(tab);

  for (auto& [duplicate_url, duplicate_tab_list] : duplicate_tabs_) {
    auto found_it = std::ranges::find(duplicate_tab_list, tab);
    if (found_it != duplicate_tab_list.end()) {
      // Remove the specific tab from `duplicate_tabs_` and subscription maps.
      duplicate_tab_list.erase(found_it);
      duplicate_tab_subscriptions_map_.erase(tab);
      duplicate_tab_webcontents_observers_.erase(tab);

      // If there is only one more element remove it as having one entry is
      // equivalent to having no duplicate items.
      if (duplicate_tab_list.size() == 1) {
        tabs::TabInterface* last_tab = duplicate_tab_list.front();
        duplicate_tab_subscriptions_map_.erase(last_tab);
        duplicate_tab_webcontents_observers_.erase(last_tab);
        duplicate_tab_list.clear();
      }

      // If the list is now empty, remove it from `duplicate_tabs_`.
      if (duplicate_tab_list.empty()) {
        duplicate_tabs_.erase(duplicate_url);
      }

      return;
    }
  }
}

// Tab Search UI can also hosted inside a tab and so we still need to
// be able to handle browser window changes.
void TabSearchPageHandler::BrowserWindowInterfaceChanged() {
  auto* browser_window_interface =
      webui::GetBrowserWindowInterface(web_ui_->GetWebContents());
  browser_ = browser_window_interface
                 ? browser_window_interface->GetBrowserForMigrationOnly()
                 : nullptr;
  SetTabDeclutterController(
      browser_window_interface
          ? browser_window_interface->GetFeatures().tab_declutter_controller()
          : nullptr);
}

std::vector<tabs::TabInterface*>
TabSearchPageHandler::FilterDuplicateTabsFromStaleTabs(
    std::vector<tabs::TabInterface*> stale_tabs,
    std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs) {
  std::vector<tabs::TabInterface*> filtered_stale_tabs;

  for (tabs::TabInterface* stale_tab : stale_tabs) {
    GURL tab_url =
        stale_tab->GetContents()->GetLastCommittedURL().GetWithoutRef();
    if (duplicate_tabs.find(tab_url) == duplicate_tabs.end()) {
      filtered_stale_tabs.push_back(stale_tab);
    }
  }

  return filtered_stale_tabs;
}

void TabSearchPageHandler::OnStaleTabDidEnterForeground(
    tabs::TabInterface* tab) {
  RemoveStaleTab(static_cast<tabs::TabInterface*>(tab));
  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

void TabSearchPageHandler::OnDuplicateTabWillDiscardWebContents(
    tabs::TabInterface* tab,
    content::WebContents* old_content,
    content::WebContents* new_content) {
  RemoveDuplicateTab(tab);
  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

void TabSearchPageHandler::OnUnusedTabWillDetach(
    tabs::TabInterface* tab,
    tabs::TabInterface::DetachReason reason,
    UnusedTabType type) {
  if (type == UnusedTabType::kInactive) {
    RemoveStaleTab(tab);
  } else {
    RemoveDuplicateTab(tab);
  }
  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

void TabSearchPageHandler::OnUnusedTabPinnedStateChanged(
    tabs::TabInterface* tab,
    bool new_pinned_state,
    UnusedTabType type) {
  if (type == UnusedTabType::kInactive) {
    RemoveStaleTab(tab);
  } else {
    RemoveDuplicateTab(tab);
  }

  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

void TabSearchPageHandler::OnUnusedTabGroupChanged(
    tabs::TabInterface* tab,
    std::optional<tab_groups::TabGroupId> new_group,
    UnusedTabType type) {
  if (type == UnusedTabType::kInactive) {
    RemoveStaleTab(tab);
  } else {
    RemoveDuplicateTab(tab);
  }
  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

void TabSearchPageHandler::GetProfileData(GetProfileDataCallback callback) {
  TRACE_EVENT0("browser", "TabSearchPageHandler:GetProfileTabs");
  auto profile_tabs = CreateProfileData();
  // On first run record the number of windows and tabs open for the given
  // profile.
  if (!sent_initial_payload_) {
    sent_initial_payload_ = true;
    int tab_count = 0;
    for (const auto& window : profile_tabs->windows) {
      tab_count += window->tabs.size();
    }
    base::UmaHistogramCounts100("Tabs.TabSearch.NumWindowsOnOpen",
                                profile_tabs->windows.size());
    base::UmaHistogramCounts10000("Tabs.TabSearch.NumTabsOnOpen", tab_count);

    bool expand_preference =
        Profile::FromWebUI(web_ui_)->GetPrefs()->GetBoolean(
            tab_search_prefs::kTabSearchRecentlyClosedSectionExpanded);
    base::UmaHistogramEnumeration(
        "Tabs.TabSearch.RecentlyClosedSectionToggleStateOnOpen",
        expand_preference ? TabSearchRecentlyClosedToggleAction::kExpand
                          : TabSearchRecentlyClosedToggleAction::kCollapse);
  }

  std::move(callback).Run(std::move(profile_tabs));
}

void TabSearchPageHandler::GetUnusedTabs(GetUnusedTabsCallback callback) {
  UpdateUnusedTabs();
  std::move(callback).Run(GetMojoUnusedTabs());
}

void TabSearchPageHandler::GetTabSearchSection(
    GetTabSearchSectionCallback callback) {
  PrefService* prefs = Profile::FromWebUI(web_ui_)->GetPrefs();
  tab_search::mojom::TabSearchSection section =
      tab_search_prefs::GetTabSearchSectionFromInt(
          prefs->GetInteger(tab_search_prefs::kTabSearchTabIndex));
  if (section == tab_search::mojom::TabSearchSection::kNone) {
    section = tab_search::mojom::TabSearchSection::kSearch;
  }
  std::move(callback).Run(section);
}

void TabSearchPageHandler::GetTabOrganizationFeature(
    GetTabOrganizationFeatureCallback callback) {
  PrefService* prefs = Profile::FromWebUI(web_ui_)->GetPrefs();
  const tab_search::mojom::TabOrganizationFeature feature =
      tab_search_prefs::GetTabOrganizationFeatureFromInt(
          prefs->GetInteger(tab_search_prefs::kTabOrganizationFeature));
  std::move(callback).Run(feature);
}

void TabSearchPageHandler::GetTabOrganizationSession(
    GetTabOrganizationSessionCallback callback) {
  if (!browser_ || !browser_->tab_strip_model()->SupportsTabGroups() ||
      !organization_service_) {
    std::move(callback).Run(CreateFailedMojoSession());
    return;
  }

  TabOrganizationSession* session =
      organization_service_->GetSessionForBrowser(browser_);
  if (!session) {
    session = organization_service_->CreateSessionForBrowser(
        browser_, TabOrganizationEntryPoint::kTabSearch);
  }

  if (!base::Contains(listened_sessions_, session)) {
    session->AddObserver(this);
    listened_sessions_.emplace_back(session);
  }

  tab_search::mojom::TabOrganizationSessionPtr mojo_session =
      GetMojoForTabOrganizationSession(session);

  std::move(callback).Run(std::move(mojo_session));
}

std::optional<TabSearchPageHandler::TabDetails>
TabSearchPageHandler::GetTabDetails(int32_t tab_id) {
  const tabs::TabHandle handle = tabs::TabHandle(tab_id);
  tabs::TabInterface* const tab = handle.Get();
  if (!tab) {
    return std::nullopt;
  }
  BrowserWindowInterface* browser = tab->GetBrowserWindowInterface();
  if (!browser || !ShouldTrackBrowser(browser->GetBrowserForMigrationOnly())) {
    return std::nullopt;
  }
  return TabDetails(tab);
}

void TabSearchPageHandler::GetTabOrganizationModelStrategy(
    GetTabOrganizationModelStrategyCallback callback) {
  Profile* profile = Profile::FromWebUI(web_ui_);
  const int32_t strategy_int = profile->GetPrefs()->GetInteger(
      tab_search_prefs::kTabOrganizationModelStrategy);
  const auto strategy =
      static_cast<tab_search::mojom::TabOrganizationModelStrategy>(
          strategy_int);
  std::move(callback).Run(std::move(strategy));
}

void TabSearchPageHandler::GetIsSplit(GetIsSplitCallback callback) {
  bool is_split = false;
  if (base::FeatureList::IsEnabled(features::kSideBySide)) {
    GURL url = web_ui_->GetWebContents()->GetURL();
    if (url.spec() == chrome::kChromeUISplitViewNewTabPageURL) {
      is_split = tabs::TabInterface::GetFromContents(web_ui_->GetWebContents())
                     ->IsSplit();
    }
  }
  std::move(callback).Run(is_split);
}

void TabSearchPageHandler::SwitchToTab(
    tab_search::mojom::SwitchToTabInfoPtr switch_to_tab_info) {
  const std::optional<TabDetails> details =
      GetTabDetails(switch_to_tab_info->tab_id);
  if (!details) {
    return;
  }

  called_switch_to_tab_ = true;

  details->tab->GetBrowserWindowInterface()->GetTabStripModel()->ActivateTabAt(
      details->GetIndex());
  details->tab->GetBrowserWindowInterface()->ActivateWindow();
  metrics_reporter_->Measure(
      "SwitchToTab",
      base::BindOnce(
          [](MetricsReporter* metrics_reporter, base::TimeDelta duration) {
            base::UmaHistogramTimes("Tabs.TabSearch.Mojo.SwitchToTab",
                                    duration);
            metrics_reporter->ClearMark("SwitchToTab");
          },
          metrics_reporter_));
}

void TabSearchPageHandler::OpenRecentlyClosedEntry(int32_t session_id) {
  sessions::TabRestoreService* tab_restore_service =
      TabRestoreServiceFactory::GetForProfile(Profile::FromWebUI(web_ui_));
  if (!tab_restore_service) {
    return;
  }
  tab_restore_service->RestoreEntryById(
      BrowserLiveTabContext::FindContextForWebContents(
          browser_->tab_strip_model()->GetActiveWebContents()),
      SessionID::FromSerializedValue(session_id),
      WindowOpenDisposition::NEW_FOREGROUND_TAB);
}

void TabSearchPageHandler::RequestTabOrganization() {
  if (!organization_service_) {
    return;
  }

  TabOrganizationSession* session =
      organization_service_->GetSessionForBrowser(browser_);
  if (!session) {
    session = organization_service_->CreateSessionForBrowser(
        browser_, TabOrganizationEntryPoint::kTabSearch);
  } else if (session->IsComplete()) {
    session = organization_service_->ResetSessionForBrowser(
        browser_, TabOrganizationEntryPoint::kTabSearch);
  }

  if (!base::Contains(listened_sessions_, session)) {
    session->AddObserver(this);
    listened_sessions_.emplace_back(session);
  }

  browser_->profile()->GetPrefs()->SetBoolean(
      tab_search_prefs::kTabOrganizationShowFRE, false);
  organization_service_->StartRequest(browser_,
                                      TabOrganizationEntryPoint::kTabSearch);
}

void TabSearchPageHandler::RemoveTabFromOrganization(
    int32_t session_id,
    int32_t organization_id,
    tab_search::mojom::TabPtr tab) {
  if (!organization_service_) {
    return;
  }

  TabOrganization* organization = GetTabOrganization(
      organization_service_, browser_, session_id, organization_id);
  if (!organization) {
    return;
  }

  organization->RemoveTabData(tab->tab_id);
}

void TabSearchPageHandler::RejectSession(int32_t session_id) {
  if (!organization_service_) {
    return;
  }

  TabOrganizationSession* session =
      organization_service_->GetSessionForBrowser(browser_);
  if (!session || session->session_id() != session_id) {
    return;
  }

  for (const std::unique_ptr<TabOrganization>& organization :
       session->tab_organizations()) {
    // Organization may have already been rejected, but should not have been
    // accepted.
    CHECK(organization->choice() != TabOrganization::UserChoice::kAccepted);

    if (organization->choice() == TabOrganization::UserChoice::kNoChoice) {
      organization->Reject();
    }
  }

  organization_service_->ResetSessionForBrowser(
      browser_, TabOrganizationEntryPoint::kTabSearch, nullptr);
}

void TabSearchPageHandler::ReplaceActiveSplitTab(int32_t replacement_tab_id) {
  std::optional<split_tabs::SplitTabId> split_id =
      browser_->GetActiveTabInterface()->GetSplit();
  if (split_id.has_value()) {
    const tabs::TabInterface* replacement_tab =
        tabs::TabHandle(replacement_tab_id).Get();
    const int32_t replacement_index =
        browser_->tab_strip_model()->GetIndexOfTab(replacement_tab);
    browser_->tab_strip_model()->UpdateActiveTabInSplit(
        split_id.value(), replacement_index,
        TabStripModel::SplitUpdateType::kReplace);
  }
}

void TabSearchPageHandler::RestartSession() {
  if (!organization_service_) {
    return;
  }

  restarting_ = true;
  TabOrganizationSession* current_session =
      organization_service_->GetSessionForBrowser(browser_);
  const tabs::TabInterface* base_session_tab =
      current_session ? current_session->base_session_tab() : nullptr;
  // Don't notify observers to avoid a repaint
  TabOrganizationSession* session =
      organization_service_->ResetSessionForBrowser(
          browser_, TabOrganizationEntryPoint::kTabSearch, base_session_tab);
  if (!base::Contains(listened_sessions_, session)) {
    session->AddObserver(this);
    listened_sessions_.emplace_back(session);
  }

  organization_service_->StartRequest(browser_,
                                      TabOrganizationEntryPoint::kTabSearch);

  restarting_ = false;

  OnTabOrganizationSessionUpdated(session);
}

void TabSearchPageHandler::SaveRecentlyClosedExpandedPref(bool expanded) {
  Profile::FromWebUI(web_ui_)->GetPrefs()->SetBoolean(
      tab_search_prefs::kTabSearchRecentlyClosedSectionExpanded, expanded);

  base::UmaHistogramEnumeration(
      "Tabs.TabSearch.RecentlyClosedSectionToggleAction",
      expanded ? TabSearchRecentlyClosedToggleAction::kExpand
               : TabSearchRecentlyClosedToggleAction::kCollapse);
}

void TabSearchPageHandler::SetOrganizationFeature(
    tab_search::mojom::TabOrganizationFeature feature) {
  Profile::FromWebUI(web_ui_)->GetPrefs()->SetInteger(
      tab_search_prefs::kTabOrganizationFeature,
      tab_search_prefs::GetIntFromTabOrganizationFeature(feature));
}

void TabSearchPageHandler::StartTabGroupTutorial() {
  // Close the tab search bubble if showing.
  auto embedder = webui_controller_->embedder();
  if (embedder) {
    embedder->CloseUI();
  }

  auto* const user_education_service =
      UserEducationServiceFactory::GetForBrowserContext(browser_->profile());
  user_education::TutorialService* const tutorial_service =
      user_education_service ? &user_education_service->tutorial_service()
                             : nullptr;
  CHECK(tutorial_service);

  const ui::ElementContext context = browser_->window()->GetElementContext();
  CHECK(context);

  user_education::TutorialIdentifier tutorial_id = kTabGroupTutorialId;
  tutorial_service->StartTutorial(tutorial_id, context);
}

void TabSearchPageHandler::TriggerFeedback(int32_t session_id) {
  TabOrganizationSession* session =
      organization_service_->GetSessionForBrowser(browser_);
  const std::u16string feedback_id = session->feedback_id();
  // Bypass feedback flow if there is no feedback id, as in tests.
  if (session->session_id() != session_id || feedback_id.length() == 0) {
    return;
  }
  OptimizationGuideKeyedService* opt_guide_keyed_service =
      OptimizationGuideKeyedServiceFactory::GetForProfile(browser_->profile());
  if (!opt_guide_keyed_service ||
      !opt_guide_keyed_service->ShouldFeatureBeCurrentlyAllowedForFeedback(
          optimization_guide::proto::LogAiDataRequest::kTabOrganization)) {
    return;
  }
  base::Value::Dict feedback_metadata;
  feedback_metadata.Set("log_id", feedback_id);
  chrome::ShowFeedbackPage(
      browser_, feedback::kFeedbackSourceAI,
      /*description_template=*/std::string(),
      /*description_placeholder_text=*/
      l10n_util::GetStringUTF8(IDS_TAB_ORGANIZATION_FEEDBACK_PLACEHOLDER),
      /*category_tag=*/"tab_organization",
      /*extra_diagnostics=*/std::string(),
      /*autofill_metadata=*/base::Value::Dict(), std::move(feedback_metadata));
}

void TabSearchPageHandler::TriggerSignIn() {
  Profile* profile = Profile::FromWebUI(web_ui_);
  const signin::IdentityManager* const identity_manager(
      IdentityManagerFactory::GetInstance()->GetForProfile(profile));
  CoreAccountId primary_account_id =
      identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin);
  if (identity_manager->HasAccountWithRefreshTokenInPersistentErrorState(
          primary_account_id)) {
    signin_ui_util::ShowReauthForPrimaryAccountWithAuthError(
        profile, signin_metrics::AccessPoint::kTabOrganization);
  } else {
    signin_ui_util::ShowSigninPromptFromPromo(
        profile, signin_metrics::AccessPoint::kTabOrganization);
  }
}

void TabSearchPageHandler::OpenHelpPage() {
  GURL help_url(chrome::kTabOrganizationLearnMorePageURL);
  NavigateParams params(browser_->profile(), help_url,
                        ui::PageTransition::PAGE_TRANSITION_LINK);
  params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
  Navigate(&params);
}

void TabSearchPageHandler::SetTabOrganizationModelStrategy(
    tab_search::mojom::TabOrganizationModelStrategy strategy) {
  const auto strategy_int = static_cast<int32_t>(strategy);
  Profile* profile = Profile::FromWebUI(web_ui_);
  profile->GetPrefs()->SetInteger(
      tab_search_prefs::kTabOrganizationModelStrategy, strategy_int);
  page_->TabOrganizationModelStrategyUpdated(std::move(strategy));
}

void TabSearchPageHandler::SetTabOrganizationUserInstruction(
    const std::string& user_instruction) {
  if (base::FeatureList::IsEnabled(features::kTabOrganizationUserInstruction)) {
    TabOrganizationSession* session =
        organization_service_->GetSessionForBrowser(browser_);
    if (!session) {
      return;
    }
    session->SetUserInstruction(user_instruction);
  }
}

void TabSearchPageHandler::SetUserFeedback(
    int32_t session_id,
    tab_search::mojom::UserFeedback feedback) {
  optimization_guide::proto::UserFeedback user_feedback;
  switch (feedback) {
    case tab_search::mojom::UserFeedback::kUserFeedBackPositive:
      user_feedback =
          optimization_guide::proto::UserFeedback::USER_FEEDBACK_THUMBS_UP;
      break;
    case tab_search::mojom::UserFeedback::kUserFeedBackNegative:
      user_feedback =
          optimization_guide::proto::UserFeedback::USER_FEEDBACK_THUMBS_DOWN;
      break;
    case tab_search::mojom::UserFeedback::kUserFeedBackUnspecified:
      user_feedback =
          optimization_guide::proto::UserFeedback::USER_FEEDBACK_UNSPECIFIED;
      break;
  }
  TabOrganizationSession* session =
      organization_service_->GetSessionForBrowser(browser_);
  if (!session) {
    return;
  }
  session->SetFeedback(user_feedback);
}

void TabSearchPageHandler::NotifyOrganizationUIReadyToShow() {
  organization_ready_to_show_ = true;
  MaybeShowUI();
}

void TabSearchPageHandler::NotifySearchUIReadyToShow() {
  search_ready_to_show_ = true;
  MaybeShowUI();
}

void TabSearchPageHandler::MaybeShowUI() {
  Profile* const profile = Profile::FromWebUI(web_ui_);
  bool organization_enabled =
      TabOrganizationUtils::GetInstance()->IsEnabled(profile) &&
      organization_service_;
  if ((organization_enabled && !organization_ready_to_show_) ||
      !search_ready_to_show_) {
    return;
  }
  auto embedder = webui_controller_->embedder();
  if (embedder) {
    embedder->ShowUI();
  }
}

tab_search::mojom::ProfileDataPtr TabSearchPageHandler::CreateProfileData() {
  auto profile_data = tab_search::mojom::ProfileData::New();

  std::set<DedupKey> tab_dedup_keys;
  std::set<tab_groups::TabGroupId> tab_group_ids;
  for (Browser* browser : *BrowserList::GetInstance()) {
    if (!ShouldTrackBrowser(browser)) {
      continue;
    }
    TabStripModel* tab_strip_model = browser->tab_strip_model();

    auto window = tab_search::mojom::Window::New();
    window->active = browser->IsActive();
    window->height = browser->window()->GetContentsSize().height();
    for (int i = 0; i < tab_strip_model->count(); ++i) {
      auto* web_contents = tab_strip_model->GetWebContentsAt(i);
      // A Tab can potentially be in a state where it has no committed entries
      // during loading and thus has no title/URL. Skip any such pending tabs.
      // These tabs will be added to the list later on once loading has
      // finished.
      if (!web_contents->GetController().GetLastCommittedEntry()) {
        continue;
      }
      tab_search::mojom::TabPtr tab = GetTab(tab_strip_model, web_contents, i);
      tab_dedup_keys.insert(DedupKey(tab->url, tab->group_id));
      window->tabs.push_back(std::move(tab));
    }
    profile_data->windows.push_back(std::move(window));

    if (tab_strip_model->group_model()) {
      for (auto tab_group_id :
           tab_strip_model->group_model()->ListTabGroups()) {
        const tab_groups::TabGroupVisualData* tab_group_visual_data =
            tab_strip_model->group_model()
                ->GetTabGroup(tab_group_id)
                ->visual_data();

        auto tab_group = tab_search::mojom::TabGroup::New();
        tab_group->id = tab_group_id.token();
        tab_group->title = base::UTF16ToUTF8(tab_group_visual_data->title());
        tab_group->color = tab_group_visual_data->color();

        tab_group_ids.insert(tab_group_id);
        profile_data->tab_groups.push_back(std::move(tab_group));
      }
    }
  }

  AddRecentlyClosedEntries(profile_data->recently_closed_tabs,
                           profile_data->recently_closed_tab_groups,
                           tab_group_ids, profile_data->tab_groups,
                           tab_dedup_keys);
  profile_data->recently_closed_section_expanded =
      Profile::FromWebUI(web_ui_)->GetPrefs()->GetBoolean(
          tab_search_prefs::kTabSearchRecentlyClosedSectionExpanded);
  return profile_data;
}

void TabSearchPageHandler::UpdateUnusedTabs() {
  stale_tabs_.clear();
  duplicate_tabs_.clear();

  UnregisterTabCallbacks();
  if (!tab_declutter_controller_) {
    return;
  }

  std::vector<tabs::TabInterface*> stale_tabs =
      tab_declutter_controller_->GetStaleTabs();
  std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs;

  if (features::IsTabstripDedupeEnabled()) {
    duplicate_tabs = tab_declutter_controller_->GetDuplicateTabs();
  }

  duplicate_tabs_ = duplicate_tabs;
  stale_tabs_ = FilterDuplicateTabsFromStaleTabs(stale_tabs, duplicate_tabs_);

  for (tabs::TabInterface* tab : stale_tabs_) {
    RegisterInactiveTabDeclutterCallbacks(tab);
  }

  for (auto& [url, tabs] : duplicate_tabs_) {
    for (auto& tab : tabs) {
      RegisterDuplicateTabDeclutterCallbacks(tab);
    }
  }
}

void TabSearchPageHandler::SetTabDeclutterController(
    tabs::TabDeclutterController* tab_declutter_controller) {
  if (tab_declutter_controller == tab_declutter_controller_) {
    return;
  }

  tab_declutter_observation_.Reset();
  tab_declutter_controller_ = tab_declutter_controller;
  if (tab_declutter_controller_) {
    tab_declutter_observation_.Observe(tab_declutter_controller_.get());
    UpdateUnusedTabs();
    page_->UnusedTabsChanged(GetMojoUnusedTabs());
  }
}

void TabSearchPageHandler::OnUnusedTabsProcessed(
    std::vector<tabs::TabInterface*> stale_tabs,
    std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs) {
  stale_tabs_.clear();
  duplicate_tabs_.clear();
  UnregisterTabCallbacks();

  duplicate_tabs_ = duplicate_tabs;
  stale_tabs_ = FilterDuplicateTabsFromStaleTabs(stale_tabs, duplicate_tabs_);

  for (tabs::TabInterface* tab : stale_tabs_) {
    RegisterInactiveTabDeclutterCallbacks(tab);
  }

  for (auto& [url, tabs] : duplicate_tabs_) {
    for (auto& tab : tabs) {
      RegisterDuplicateTabDeclutterCallbacks(tab);
    }
  }

  page_->UnusedTabsChanged(GetMojoUnusedTabs());
}

mojo::StructPtr<tab_search::mojom::UnusedTabInfo>
TabSearchPageHandler::GetMojoUnusedTabs() {
  auto unused_tabs = tab_search::mojom::UnusedTabInfo::New();
  unused_tabs->stale_tabs = GetMojoStaleTabs();
  unused_tabs->duplicate_tabs = GetMojoDuplicateTabs();
  return unused_tabs;
}

std::vector<mojo::StructPtr<tab_search::mojom::Tab>>
TabSearchPageHandler::GetMojoStaleTabs() {
  std::vector<mojo::StructPtr<tab_search::mojom::Tab>> mojo_tabs;
  if (!tab_declutter_controller_) {
    return mojo_tabs;
  }
  TabStripModel* tab_strip_model = tab_declutter_controller_->tab_strip_model();

  for (tabs::TabInterface* tab : stale_tabs_) {
    const int tab_index =
        tab_strip_model->GetIndexOfWebContents(tab->GetContents());
    const std::string last_active_text = GetLastActiveElapsedTextForDeclutter(
        tab->GetContents()->GetLastActiveTime());
    mojo_tabs.push_back(GetTab(tab_strip_model, tab->GetContents(), tab_index,
                               last_active_text));
  }
  return mojo_tabs;
}

base::flat_map<std::string,
               std::vector<mojo::StructPtr<tab_search::mojom::Tab>>>
TabSearchPageHandler::GetMojoDuplicateTabs() {
  base::flat_map<std::string,
                 std::vector<mojo::StructPtr<tab_search::mojom::Tab>>>
      mojo_duplicate_tabs;

  if (!tab_declutter_controller_) {
    return mojo_duplicate_tabs;
  }

  TabStripModel* tab_strip_model = tab_declutter_controller_->tab_strip_model();

  for (const auto& [url, tabs] : duplicate_tabs_) {
    std::vector<mojo::StructPtr<tab_search::mojom::Tab>> mojo_tabs;

    for (tabs::TabInterface* tab : tabs) {
      const int tab_index =
          tab_strip_model->GetIndexOfWebContents(tab->GetContents());
      std::string last_active_text = GetLastActiveElapsedTextForDeclutter(
          tab->GetContents()->GetLastActiveTime());

      mojo_tabs.push_back(GetTab(tab_strip_model, tab->GetContents(), tab_index,
                                 last_active_text));
    }

    mojo_duplicate_tabs.emplace(url.spec(), std::move(mojo_tabs));
  }

  return mojo_duplicate_tabs;
}

void TabSearchPageHandler::AddRecentlyClosedEntries(
    std::vector<tab_search::mojom::RecentlyClosedTabPtr>& recently_closed_tabs,
    std::vector<tab_search::mojom::RecentlyClosedTabGroupPtr>&
        recently_closed_tab_groups,
    std::set<tab_groups::TabGroupId>& tab_group_ids,
    std::vector<tab_search::mojom::TabGroupPtr>& tab_groups,
    std::set<DedupKey>& tab_dedup_keys) {
  sessions::TabRestoreService* tab_restore_service =
      TabRestoreServiceFactory::GetForProfile(Profile::FromWebUI(web_ui_));
  if (!tab_restore_service) {
    return;
  }

  const int kRecentlyClosedTabCountThreshold = 100;
  int recently_closed_tab_count = 0;
  // The minimum number of desired recently closed items (tab or group) to be
  // shown in the 'Recently Closed' section of the UI.
  int recently_closed_item_count = 0;

  // Attempt to add as many recently closed items as necessary to support the
  // default item display count. On reaching this minimum, keep adding
  // items until we have reached or exceeded a tab count threshold value.
  // Ignore any entries that match URLs that are currently open.
  for (auto& entry : tab_restore_service->entries()) {
    if (recently_closed_item_count >= kMinRecentlyClosedItemDisplayCount &&
        recently_closed_tab_count >= kRecentlyClosedTabCountThreshold) {
      return;
    }

    if (entry->type == sessions::tab_restore::Type::WINDOW) {
      sessions::tab_restore::Window* window =
          static_cast<sessions::tab_restore::Window*>(entry.get());

      for (auto& window_tab : window->tabs) {
        sessions::tab_restore::Tab* tab =
            static_cast<sessions::tab_restore::Tab*>(window_tab.get());
        if (AddRecentlyClosedTab(tab, entry->timestamp, recently_closed_tabs,
                                 tab_dedup_keys, tab_group_ids, tab_groups)) {
          recently_closed_tab_count += 1;
          recently_closed_item_count += 1;
        }

        if (recently_closed_item_count >= kMinRecentlyClosedItemDisplayCount &&
            recently_closed_tab_count >= kRecentlyClosedTabCountThreshold) {
          return;
        }
      }
    } else if (entry->type == sessions::tab_restore::Type::TAB) {
      sessions::tab_restore::Tab* tab =
          static_cast<sessions::tab_restore::Tab*>(entry.get());

      if (AddRecentlyClosedTab(tab, entry->timestamp, recently_closed_tabs,
                               tab_dedup_keys, tab_group_ids, tab_groups)) {
        recently_closed_tab_count += 1;
        recently_closed_item_count += 1;
      }
    } else if (entry->type == sessions::tab_restore::Type::GROUP) {
      sessions::tab_restore::Group* group =
          static_cast<sessions::tab_restore::Group*>(entry.get());

      const tab_groups::TabGroupVisualData* tab_group_visual_data =
          &group->visual_data;
      auto recently_closed_tab_group =
          tab_search::mojom::RecentlyClosedTabGroup::New();
      recently_closed_tab_group->session_id = entry->id.id();
      recently_closed_tab_group->id = group->group_id.token();
      recently_closed_tab_group->color = tab_group_visual_data->color();
      recently_closed_tab_group->title =
          base::UTF16ToUTF8(tab_group_visual_data->title());
      recently_closed_tab_group->tab_count = group->tabs.size();
      const base::Time last_active_time =
          (entry->timestamp).is_null() ? GetTabGroupTimeStamp(group->tabs)
                                       : entry->timestamp;
      recently_closed_tab_group->last_active_time = last_active_time;
      recently_closed_tab_group->last_active_elapsed_text =
          GetLastActiveElapsedText(last_active_time);

      for (auto& tab : group->tabs) {
        if (AddRecentlyClosedTab(tab.get(), last_active_time,
                                 recently_closed_tabs, tab_dedup_keys,
                                 tab_group_ids, tab_groups)) {
          recently_closed_tab_count += 1;
        }
      }

      recently_closed_tab_groups.push_back(
          std::move(recently_closed_tab_group));
      // Restored recently closed tab groups map to a single display item.
      recently_closed_item_count += 1;
    }
  }
}

bool TabSearchPageHandler::AddRecentlyClosedTab(
    sessions::tab_restore::Tab* tab,
    const base::Time& close_time,
    std::vector<tab_search::mojom::RecentlyClosedTabPtr>& recently_closed_tabs,
    std::set<DedupKey>& tab_dedup_keys,
    std::set<tab_groups::TabGroupId>& tab_group_ids,
    std::vector<tab_search::mojom::TabGroupPtr>& tab_groups) {
  if (tab->navigations.size() == 0) {
    return false;
  }

  tab_search::mojom::RecentlyClosedTabPtr recently_closed_tab =
      GetRecentlyClosedTab(tab, close_time);

  DedupKey dedup_id(recently_closed_tab->url, recently_closed_tab->group_id);
  // Ignore NTP entries, duplicate entries and tabs with invalid URLs such as
  // empty URLs.
  if (base::Contains(tab_dedup_keys, dedup_id) ||
      recently_closed_tab->url == GURL(chrome::kChromeUINewTabPageURL) ||
      !recently_closed_tab->url.is_valid()) {
    return false;
  }
  tab_dedup_keys.insert(dedup_id);

  if (tab->group.has_value()) {
    recently_closed_tab->group_id = tab->group.value().token();
    CreateTabGroupIfNotPresent(tab, tab_group_ids, tab_groups);
  }

  recently_closed_tabs.push_back(std::move(recently_closed_tab));
  return true;
}

tab_search::mojom::TabPtr TabSearchPageHandler::GetTab(
    const TabStripModel* tab_strip_model,
    content::WebContents* contents,
    int index,
    std::string custom_last_active_text) const {
  auto tab_data = tab_search::mojom::Tab::New();
  const tabs::TabInterface* const tab = tab_strip_model->GetTabAtIndex(index);

  tab_data->active = tab->IsActivated();
  tab_data->visible = tab->IsVisible();
  tab_data->tab_id = tab->GetHandle().raw_value();
  tab_data->index = index;
  const std::optional<tab_groups::TabGroupId> group_id = tab->GetGroup();
  if (group_id.has_value()) {
    tab_data->group_id = group_id.value().token();
  }
  tab_data->pinned = tab->IsPinned();

  TabRendererData tab_renderer_data =
      TabRendererData::FromTabInModel(tab_strip_model, index);
  tab_data->title = base::UTF16ToUTF8(tab_renderer_data.title);
  const auto& last_committed_url = tab_renderer_data.last_committed_url;
  // A visible URL is used when the a new tab is still loading.
  // If it is cancelled during loading the visible URL becomes empty.
  // We will display an empty URL as about:blank in Javascript.
  tab_data->url =
      !last_committed_url.is_valid() || last_committed_url.is_empty()
          ? tab_renderer_data.visible_url
          : last_committed_url;

  if (tab_renderer_data.favicon.IsEmpty()) {
    tab_data->is_default_favicon = true;
  } else {
    const ui::ColorProvider& provider =
        web_ui_->GetWebContents()->GetColorProvider();
    const gfx::ImageSkia default_favicon =
        favicon::GetDefaultFaviconModel().Rasterize(&provider);
    gfx::ImageSkia raster_favicon =
        tab_renderer_data.favicon.Rasterize(&provider);

    if (tab_renderer_data.should_themify_favicon) {
      raster_favicon = ThemeFavicon(raster_favicon, provider);
    }

    tab_data->favicon_url = GURL(webui::EncodePNGAndMakeDataURI(
        raster_favicon, web_ui_->GetDeviceScaleFactor()));
    tab_data->is_default_favicon =
        raster_favicon.BackedBySameObjectAs(default_favicon);
  }

  tab_data->show_icon = tab_renderer_data.show_icon;

  const base::TimeTicks last_active_time_ticks =
      contents->GetLastActiveTimeTicks();
  tab_data->last_active_time_ticks = last_active_time_ticks;

  // last_active_time_for_testing can affect pixel tests depending on when the
  // view pops up. To make it consistent, override the string to something
  // constant.
  tab_data->last_active_elapsed_text =
      disable_last_active_time_for_testing_ ? "0"
      : custom_last_active_text.length() > 0
          ? custom_last_active_text
          : GetLastActiveElapsedText(last_active_time_ticks);

  std::vector<tabs::TabAlert> alert_states =
      GetTabAlertStatesForContents(contents);
  // Currently, we only report media alert states.
  std::ranges::copy_if(alert_states.begin(), alert_states.end(),
                       std::back_inserter(tab_data->alert_states),
                       [](tabs::TabAlert alert) {
                         return alert == tabs::TabAlert::MEDIA_RECORDING ||
                                alert == tabs::TabAlert::AUDIO_RECORDING ||
                                alert == tabs::TabAlert::VIDEO_RECORDING ||
                                alert == tabs::TabAlert::AUDIO_PLAYING ||
                                alert == tabs::TabAlert::AUDIO_MUTING ||
                                alert == tabs::TabAlert::GLIC_ACCESSING;
                       });

  return tab_data;
}

tab_search::mojom::RecentlyClosedTabPtr
TabSearchPageHandler::GetRecentlyClosedTab(sessions::tab_restore::Tab* tab,
                                           const base::Time& close_time) {
  auto recently_closed_tab = tab_search::mojom::RecentlyClosedTab::New();
  DCHECK(tab->navigations.size() > 0);
  sessions::SerializedNavigationEntry& entry =
      tab->navigations[tab->current_navigation_index];
  // N.B. Recently closed tabs use session ids, not TabHandle ids.
  recently_closed_tab->tab_id = tab->id.id();
  recently_closed_tab->url = entry.virtual_url();
  recently_closed_tab->title = entry.title().empty()
                                   ? recently_closed_tab->url.spec()
                                   : base::UTF16ToUTF8(entry.title());
  // Fall back to the navigation last active time if the restore entry has no
  // associated timestamp.
  const base::Time last_active_time =
      close_time.is_null() ? entry.timestamp() : close_time;
  recently_closed_tab->last_active_time = last_active_time;
  recently_closed_tab->last_active_elapsed_text =
      GetLastActiveElapsedText(last_active_time);

  if (tab->group.has_value()) {
    recently_closed_tab->group_id = tab->group.value().token();
  }

  return recently_closed_tab;
}

void TabSearchPageHandler::OnTabStripModelChanged(
    TabStripModel* tab_strip_model,
    const TabStripModelChange& change,
    const TabStripSelectionChange& selection) {
  if (!IsWebContentsVisible() ||
      browser_tab_strip_tracker_.is_processing_initial_browsers()) {
    return;
  }

  if (change.type() == TabStripModelChange::kRemoved) {
    std::vector<int> tab_ids;
    std::set<SessionID> tab_restore_ids;
    for (const auto& removed_tab : change.GetRemove()->contents) {
      tabs::TabInterface* tab = removed_tab.tab;
      tab_ids.push_back(tab->GetHandle().raw_value());

      if (removed_tab.session_id.has_value() &&
          removed_tab.session_id.value().is_valid()) {
        tab_restore_ids.insert(removed_tab.session_id.value());
      }
    }

    auto tabs_removed_info = tab_search::mojom::TabsRemovedInfo::New();
    tabs_removed_info->tab_ids = std::move(tab_ids);

    sessions::TabRestoreService* tab_restore_service =
        TabRestoreServiceFactory::GetForProfile(Profile::FromWebUI(web_ui_));
    if (tab_restore_service) {
      // Loops through at most (TabRestoreServiceHelper) kMaxEntries.
      // Recently closed entries appear first in the list.
      for (auto& entry : tab_restore_service->entries()) {
        if (entry->type == sessions::tab_restore::Type::TAB &&
            base::Contains(tab_restore_ids, entry->id)) {
          // The associated tab group visual data for the recently closed tab is
          // already present at the client side from the initial GetProfileData
          // call.
          sessions::tab_restore::Tab* tab =
              static_cast<sessions::tab_restore::Tab*>(entry.get());
          tab_search::mojom::RecentlyClosedTabPtr recently_closed_tab =
              GetRecentlyClosedTab(tab, entry->timestamp);
          tabs_removed_info->recently_closed_tabs.push_back(
              std::move(recently_closed_tab));
        }
      }
    }

    page_->TabsRemoved(std::move(tabs_removed_info));
    return;
  }
  ScheduleDebounce();
}

void TabSearchPageHandler::TabChangedAt(content::WebContents* contents,
                                        int index,
                                        TabChangeType change_type) {
  if (!IsWebContentsVisible()) {
    return;
  }
  // TODO(crbug.com/40709736): Support more values for TabChangeType and filter
  // out the changes we are not interested in.
  if (change_type != TabChangeType::kAll) {
    return;
  }

  tabs::TabInterface* tab = tabs::TabInterface::GetFromContents(contents);

  TRACE_EVENT0("browser", "TabSearchPageHandler:TabChangedAt");
  const bool is_mark_overlap = metrics_reporter_->HasLocalMark("TabUpdated");
  base::UmaHistogramBoolean("Tabs.TabSearch.Mojo.TabUpdated.IsOverlap",
                            is_mark_overlap);
  if (!is_mark_overlap) {
    metrics_reporter_->Mark("TabUpdated");
  }

  auto tab_update_info = tab_search::mojom::TabUpdateInfo::New();
  BrowserWindowInterface* browser = tab->GetBrowserWindowInterface();
  tab_update_info->in_active_window = browser->IsActive();
  tab_update_info->tab =
      GetTab(browser->GetTabStripModel(), tab->GetContents(), index);
  page_->TabUpdated(std::move(tab_update_info));
}

void TabSearchPageHandler::OnSplitTabChanged(const SplitTabChange& change) {
  if (!base::FeatureList::IsEnabled(features::kSideBySide)) {
    return;
  }
  if (change.type != SplitTabChange::Type::kRemoved) {
    return;
  }
  GURL url = web_ui_->GetWebContents()->GetURL();
  if (url.spec() != chrome::kChromeUISplitViewNewTabPageURL) {
    return;
  }
  if (!tabs::TabInterface::GetFromContents(web_ui_->GetWebContents())
           ->IsSplit()) {
    page_->TabUnsplit();
  }
}

void TabSearchPageHandler::ScheduleDebounce() {
  if (!debounce_timer_->IsRunning()) {
    debounce_timer_->Reset();
  }
}

void TabSearchPageHandler::NotifyTabsChanged() {
  if (!IsWebContentsVisible()) {
    return;
  }
  page_->TabsChanged(CreateProfileData());
  debounce_timer_->Stop();
}

void TabSearchPageHandler::NotifyTabIndexPrefChanged(const Profile* profile) {
  const int32_t section_int =
      profile->GetPrefs()->GetInteger(tab_search_prefs::kTabSearchTabIndex);
  page_->TabSearchSectionChanged(
      tab_search_prefs::GetTabSearchSectionFromInt(section_int));
}

void TabSearchPageHandler::NotifyOrganizationFeaturePrefChanged(
    const Profile* profile) {
  const int32_t feature_int = profile->GetPrefs()->GetInteger(
      tab_search_prefs::kTabOrganizationFeature);
  page_->TabOrganizationFeatureChanged(
      tab_search_prefs::GetTabOrganizationFeatureFromInt(feature_int));
}

void TabSearchPageHandler::NotifyShowFREPrefChanged(const Profile* profile) {
  const bool show_fre = profile->GetPrefs()->GetBoolean(
      tab_search_prefs::kTabOrganizationShowFRE);
  page_->ShowFREChanged(show_fre);
}

bool TabSearchPageHandler::IsWebContentsVisible() {
  auto visibility = web_ui_->GetWebContents()->GetVisibility();
  return visibility == content::Visibility::VISIBLE ||
         visibility == content::Visibility::OCCLUDED;
}

tab_search::mojom::TabPtr TabSearchPageHandler::GetMojoForTabData(
    TabData* tab_data) const {
  return TabSearchPageHandler::GetTab(
      tab_data->original_tab_strip_model(), tab_data->tab()->GetContents(),
      tab_data->original_tab_strip_model()->GetIndexOfWebContents(
          tab_data->tab()->GetContents()));
}

tab_search::mojom::TabOrganizationPtr
TabSearchPageHandler::GetMojoForTabOrganization(
    const TabOrganization* organization) const {
  tab_search::mojom::TabOrganizationPtr mojo_organization =
      tab_search::mojom::TabOrganization::New();

  std::vector<tab_search::mojom::TabPtr> tabs;
  for (const std::unique_ptr<TabData>& tab_data : organization->tab_datas()) {
    if (!tab_data->IsValidForOrganizing(organization->group_id())) {
      continue;
    }

    tabs.emplace_back(GetMojoForTabData(tab_data.get()));
  }

  mojo_organization->organization_id = organization->organization_id();
  mojo_organization->tabs = std::move(tabs);
  mojo_organization->first_new_tab_index = organization->first_new_tab_index();
  mojo_organization->name = organization->GetDisplayName();

  return mojo_organization;
}

tab_search::mojom::TabOrganizationSessionPtr
TabSearchPageHandler::GetMojoForTabOrganizationSession(
    const TabOrganizationSession* session) const {
  tab_search::mojom::TabOrganizationSessionPtr mojo_session =
      tab_search::mojom::TabOrganizationSession::New();

  mojo_session->session_id = session->session_id();
  mojo_session->error = tab_search::mojom::TabOrganizationError::kNone;
  mojo_session->active_tab_id =
      session->base_session_tab()
          ? session->base_session_tab()->GetHandle().raw_value()
          : tabs::TabHandle::NullValue;
  std::vector<tab_search::mojom::TabOrganizationPtr> organizations;

  TabOrganizationRequest::State state = session->request()->state();
  switch (state) {
    case TabOrganizationRequest::State::NOT_STARTED: {
      mojo_session->state =
          tab_search::mojom::TabOrganizationState::kNotStarted;
      break;
    }
    case TabOrganizationRequest::State::STARTED: {
      mojo_session->state =
          tab_search::mojom::TabOrganizationState::kInProgress;
      break;
    }
    case TabOrganizationRequest::State::COMPLETED: {
      if (session->tab_organizations().size() > 0) {
        for (const std::unique_ptr<TabOrganization>& organization :
             session->tab_organizations()) {
          if (!organization->IsValidForOrganizing() ||
              organization->choice() !=
                  TabOrganization::UserChoice::kNoChoice) {
            continue;
          }
          organizations.emplace_back(
              GetMojoForTabOrganization(organization.get()));
        }
        if (organizations.size() > 0) {
          mojo_session->state =
              tab_search::mojom::TabOrganizationState::kSuccess;
        } else {
          mojo_session->state =
              tab_search::mojom::TabOrganizationState::kFailure;
          mojo_session->error =
              tab_search::mojom::TabOrganizationError::kGrouping;
        }
      } else {
        mojo_session->state = tab_search::mojom::TabOrganizationState::kFailure;
        mojo_session->error =
            tab_search::mojom::TabOrganizationError::kGrouping;
      }
      break;
    }
    case TabOrganizationRequest::State::FAILED:
    case TabOrganizationRequest::State::CANCELED: {
      mojo_session->state = tab_search::mojom::TabOrganizationState::kFailure;
      mojo_session->error = tab_search::mojom::TabOrganizationError::kGeneric;
      break;
    }
  }
  mojo_session->organizations = std::move(organizations);

  return mojo_session;
}

void TabSearchPageHandler::OnTabOrganizationSessionUpdated(
    const TabOrganizationSession* session) {
  if (restarting_ || !base::Contains(listened_sessions_, session)) {
    return;
  }

  tab_search::mojom::TabOrganizationSessionPtr mojo_session =
      GetMojoForTabOrganizationSession(session);

  page_->TabOrganizationSessionUpdated(std::move(mojo_session));
}

void TabSearchPageHandler::OnTabOrganizationSessionDestroyed(
    TabOrganizationSession::ID session_id) {
  for (auto session_iter = listened_sessions_.begin();
       session_iter != listened_sessions_.end(); session_iter++) {
    if (session_id == (*session_iter)->session_id()) {
      listened_sessions_.erase(session_iter);
      // Ignore this update when restarting, as it will be replaced by the new
      // session.
      if (!restarting_) {
        page_->TabOrganizationSessionUpdated(CreateNotStartedMojoSession());
      }
      return;
    }
  }
}

void TabSearchPageHandler::OnSessionCreated(const Browser* browser,
                                            TabOrganizationSession* session) {
  Profile* const profile = Profile::FromWebUI(web_ui_);
  if (restarting_ || !browser || browser->profile() != profile) {
    return;
  }

  session->AddObserver(this);
  listened_sessions_.emplace_back(session);

  OnTabOrganizationSessionUpdated(session);
}

void TabSearchPageHandler::OnChangeInFeatureCurrentlyEnabledState(
    bool is_now_enabled) {
  Profile* const profile = Profile::FromWebUI(web_ui_);
  // This logic is slightly more strict than is_now_enabled, may make a
  // difference in some edge cases.
  bool enabled = TabOrganizationUtils::GetInstance()->IsEnabled(profile);
  page_->TabOrganizationEnabledChanged(enabled && organization_service_);
}

void TabSearchPageHandler::SetTabDeclutterControllerForTesting(
    tabs::TabDeclutterController* tab_declutter_controller) {
  SetTabDeclutterController(tab_declutter_controller);
}

bool TabSearchPageHandler::ShouldTrackBrowser(Browser* browser) {
  return browser->profile() == Profile::FromWebUI(web_ui_) &&
         browser->type() == Browser::Type::TYPE_NORMAL;
}

void TabSearchPageHandler::SetTimerForTesting(
    std::unique_ptr<base::RetainingOneShotTimer> timer) {
  debounce_timer_ = std::move(timer);
  debounce_timer_->Start(
      FROM_HERE, kTabsChangeDelay,
      base::BindRepeating(&TabSearchPageHandler::NotifyTabsChanged,
                          base::Unretained(this)));
}