File: tab_manager_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1108 lines) | stat: -rw-r--r-- 45,095 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
// Copyright 2012 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/resource_coordinator/tab_manager.h"

#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/test/simple_test_tick_clock.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/devtools/devtools_window_testing.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/media_stream_capture_indicator.h"
#include "chrome/browser/resource_coordinator/lifecycle_unit_observer.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_source.h"
#include "chrome/browser/resource_coordinator/tab_load_tracker.h"
#include "chrome/browser/resource_coordinator/tab_manager_features.h"
#include "chrome/browser/resource_coordinator/time.h"
#include "chrome/browser/resource_coordinator/utils.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/browser_window/public/browser_window_features.h"
#include "chrome/browser/ui/find_bar/find_bar_controller.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/memory_pressure/fake_memory_pressure_monitor.h"
#include "components/performance_manager/public/features.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_creation_observer.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#include "url/gurl.h"

using content::OpenURLParams;

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \
    BUILDFLAG(IS_CHROMEOS)

namespace resource_coordinator {

namespace {

constexpr base::TimeDelta kShortDelay = base::Seconds(1);

bool IsTabDiscarded(content::WebContents* web_contents) {
  return TabLifecycleUnitExternal::FromWebContents(web_contents)
             ->GetTabState() == ::mojom::LifecycleUnitState::DISCARDED;
}

class ExpectStateTransitionObserver : public LifecycleUnitObserver {
 public:
  ExpectStateTransitionObserver(LifecycleUnit* lifecyle_unit,
                                LifecycleUnitState expected_state)
      : lifecycle_unit_(lifecyle_unit), expected_state_(expected_state) {
    lifecycle_unit_->AddObserver(this);
  }

  ExpectStateTransitionObserver(const ExpectStateTransitionObserver&) = delete;
  ExpectStateTransitionObserver& operator=(
      const ExpectStateTransitionObserver&) = delete;

  ~ExpectStateTransitionObserver() override {
    lifecycle_unit_->RemoveObserver(this);
  }

  void AllowState(LifecycleUnitState allowed_state) {
    allowed_states_.insert(allowed_state);
  }

  void Wait() {
    EXPECT_NE(expected_state_, lifecycle_unit_->GetState());
    run_loop_.Run();
    EXPECT_EQ(expected_state_, lifecycle_unit_->GetState());
  }

 private:
  // LifecycleUnitObserver:
  void OnLifecycleUnitStateChanged(
      LifecycleUnit* lifecycle_unit,
      LifecycleUnitState last_state,
      LifecycleUnitStateChangeReason reason) override {
    EXPECT_EQ(lifecycle_unit, lifecycle_unit_);
    if (lifecycle_unit_->GetState() == expected_state_) {
      run_loop_.Quit();
    } else {
      LOG(ERROR) << "transition to state "
                 << static_cast<int>(lifecycle_unit_->GetState());
      EXPECT_TRUE(base::Contains(allowed_states_, lifecycle_unit_->GetState()));
    }
  }

  const raw_ptr<LifecycleUnit> lifecycle_unit_;
  const LifecycleUnitState expected_state_;
  std::set<LifecycleUnitState> allowed_states_;
  base::RunLoop run_loop_;
};

class DiscardWaiter : public LifecycleUnitObserver {
 public:
  DiscardWaiter() { GetTabLifecycleUnitSource()->AddLifecycleObserver(this); }

  ~DiscardWaiter() override {
    GetTabLifecycleUnitSource()->RemoveLifecycleObserver(this);
  }

  void Wait() { run_loop_.Run(); }

 private:
  void OnLifecycleUnitStateChanged(
      LifecycleUnit* lifecycle_unit,
      LifecycleUnitState last_state,
      LifecycleUnitStateChangeReason reason) override {
    if (lifecycle_unit->GetState() == mojom::LifecycleUnitState::DISCARDED) {
      run_loop_.Quit();
    }
  }

  base::RunLoop run_loop_;
};

// Allows tests to wait for a renderer process host to exit.
class WindowedRenderProcessHostExitObserver
    : public content::RenderProcessHostObserver {
 public:
  WindowedRenderProcessHostExitObserver() {
    for (auto it = content::RenderProcessHost::AllHostsIterator();
         !it.IsAtEnd(); it.Advance()) {
      host_observation_.AddObservation(it.GetCurrentValue());
    }
  }

  void Wait() {
    if (!seen_) {
      run_loop_.Run();
    }
    EXPECT_TRUE(seen_);
  }

  // content::RenderProcessHostObserver:
  void RenderProcessExited(
      content::RenderProcessHost* host,
      const content::ChildProcessTerminationInfo& info) override {
    seen_ = true;
    host_observation_.RemoveObservation(host);
  }

 private:
  base::ScopedMultiSourceObservation<content::RenderProcessHost,
                                     content::RenderProcessHostObserver>
      host_observation_{this};

  base::RunLoop run_loop_;
  bool seen_ = false;
};

}  // namespace

class TabManagerTest : public InProcessBrowserTest,
                       public ::testing::WithParamInterface<bool> {
 public:
  TabManagerTest()
      : scoped_set_clocks_for_testing_(&test_clock_, &test_tick_clock_) {
    scoped_feature_list_.InitWithFeatureState(features::kWebContentsDiscard,
                                              GetParam());
    // Start with a non-null TimeTicks, as there is no discard protection for
    // a tab with a null focused timestamp.
    test_tick_clock_.Advance(kShortDelay);
  }

  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();
    host_resolver()->AddRule("*", "127.0.0.1");

    // To avoid flakes when focus changes, set the active tab strip model
    // explicitly.
    GetTabLifecycleUnitSource()->SetFocusedTabStripModelForTesting(tsm());
  }

  void TearDownOnMainThread() override {
    // Clear the fakely-focused model before browsers are destroyed.
    GetTabLifecycleUnitSource()->SetFocusedTabStripModelForTesting(nullptr);
    InProcessBrowserTest::TearDownOnMainThread();
  }

  void OpenTwoTabs(const GURL& first_url, const GURL& second_url) {
    // Open two tabs. Wait for both of them to load.
    content::TestNavigationObserver load1(tsm()->GetActiveWebContents(), 1);
    OpenURLParams open1(first_url, content::Referrer(),
                        WindowOpenDisposition::CURRENT_TAB,
                        ui::PAGE_TRANSITION_TYPED, false);
    browser()->OpenURL(open1, /*navigation_handle_callback=*/{});
    load1.Wait();

    OpenURLParams open2(second_url, content::Referrer(),
                        WindowOpenDisposition::NEW_BACKGROUND_TAB,
                        ui::PAGE_TRANSITION_TYPED, false);
    auto* tab2 = browser()->OpenURL(open2, /*navigation_handle_callback=*/{});
    content::WaitForLoadStop(tab2);

    ASSERT_EQ(2, tsm()->count());
  }

  TabManager* tab_manager() { return g_browser_process->GetTabManager(); }
  TabStripModel* tsm() { return browser()->tab_strip_model(); }

  content::WebContents* GetWebContentsAt(int index) {
    return tsm()->GetWebContentsAt(index);
  }

  LifecycleUnit* GetLifecycleUnitAt(int index) {
    return GetTabLifecycleUnitSource()->GetTabLifecycleUnit(
        GetWebContentsAt(index));
  }

  memory_pressure::test::FakeMemoryPressureMonitor
      fake_memory_pressure_monitor_;

  base::SimpleTestClock test_clock_;
  base::SimpleTestTickClock test_tick_clock_;
  ScopedSetClocksForTesting scoped_set_clocks_for_testing_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

class TabManagerTestWithTwoTabs : public TabManagerTest {
 public:
  TabManagerTestWithTwoTabs() {
    // Tests using two tabs assume that each tab has a dedicated process.
    feature_list_.InitAndEnableFeature(features::kDisableProcessReuse);
  }

  TabManagerTestWithTwoTabs(const TabManagerTestWithTwoTabs&) = delete;
  TabManagerTestWithTwoTabs& operator=(const TabManagerTestWithTwoTabs&) =
      delete;

  void SetUpOnMainThread() override {
    TabManagerTest::SetUpOnMainThread();

    ASSERT_TRUE(embedded_test_server()->Start());

    // Open 2 tabs with default URLs in a focused tab strip.
    OpenTwoTabs(embedded_test_server()->GetURL("/title2.html"),
                embedded_test_server()->GetURL("/title3.html"));
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_P(TabManagerTest, TabManagerBasics) {
  ASSERT_TRUE(embedded_test_server()->Start());
  const GURL url1 = embedded_test_server()->GetURL("a.com", "/title1.html");
  const GURL url2 = embedded_test_server()->GetURL("a.com", "/title2.html");
  const GURL url3 = embedded_test_server()->GetURL("a.com", "/title3.html");

  // Get three tabs open.

  test_tick_clock_.Advance(kShortDelay);
  NavigateToURLWithDisposition(browser(), url1,
                               WindowOpenDisposition::CURRENT_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  test_tick_clock_.Advance(kShortDelay);
  NavigateToURLWithDisposition(browser(), url1,
                               WindowOpenDisposition::NEW_FOREGROUND_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  test_tick_clock_.Advance(kShortDelay);
  NavigateToURLWithDisposition(browser(), url1,
                               WindowOpenDisposition::NEW_FOREGROUND_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  EXPECT_EQ(3, tsm()->count());

  // Navigate the current (third) tab to a different URL, so we can test
  // back/forward later.
  NavigateToURLWithDisposition(browser(), url2,
                               WindowOpenDisposition::CURRENT_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  // Navigate the third tab again, such that we have three navigation entries.
  NavigateToURLWithDisposition(browser(), url3,
                               WindowOpenDisposition::CURRENT_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  EXPECT_EQ(3, tsm()->count());

  // Advance time so everything is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  // Discard a tab.
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));
  EXPECT_EQ(3, tsm()->count());

  // The first tab should be killed since it was the oldest and was not
  // selected.
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(0)));
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(1)));

  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(2)));

  // Run discard again. Both unselected tabs should now be killed.
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));
  EXPECT_EQ(3, tsm()->count());
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(0)));
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(1)));
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(2)));

  // Run discard again. It should not kill the last tab, since it is active.
  EXPECT_FALSE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(0)));
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(1)));
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(2)));

  // Kill the third tab after making second tab active.
  tsm()->ActivateTabAt(1, TabStripUserGestureDetails(
                              TabStripUserGestureDetails::GestureType::kOther));

  // Advance time so everything is urgent discardable again.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  EXPECT_EQ(1, tsm()->active_index());
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(1)));
  tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT);
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(2)));

  // Force creation of the FindBarController.
  browser()->GetFeatures().GetFindBarController();

  // Select the first tab.  It should reload.
  chrome::SelectNumberedTab(browser(), 0);
  content::WaitForLoadStop(
      browser()->tab_strip_model()->GetActiveWebContents());
  // Make sure the FindBarController gets the right WebContents.
  EXPECT_EQ(browser()->GetFeatures().GetFindBarController()->web_contents(),
            tsm()->GetActiveWebContents());
  EXPECT_EQ(0, tsm()->active_index());
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(0)));
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(1)));
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(2)));

  // Select the third tab. It should reload.
  chrome::SelectNumberedTab(browser(), 2);
  content::WaitForLoadStop(
      browser()->tab_strip_model()->GetActiveWebContents());
  EXPECT_EQ(2, tsm()->active_index());
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(0)));
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(1)));
  EXPECT_FALSE(IsTabDiscarded(GetWebContentsAt(2)));

  // Navigate the third tab back twice.  We used to crash here due to
  // crbug.com/121373.
  EXPECT_TRUE(chrome::CanGoBack(browser()));
  EXPECT_FALSE(chrome::CanGoForward(browser()));
  chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
  content::WaitForLoadStop(
      browser()->tab_strip_model()->GetActiveWebContents());
  EXPECT_TRUE(chrome::CanGoBack(browser()));
  EXPECT_TRUE(chrome::CanGoForward(browser()));
  chrome::GoBack(browser(), WindowOpenDisposition::CURRENT_TAB);
  content::WaitForLoadStop(
      browser()->tab_strip_model()->GetActiveWebContents());
  EXPECT_FALSE(chrome::CanGoBack(browser()));
  EXPECT_TRUE(chrome::CanGoForward(browser()));
}

// Verify that a discarded tab is considered unloaded by `TabLoadTracker`.
IN_PROC_BROWSER_TEST_P(TabManagerTest, DiscardedTabIsUnloaded) {
  // Setup a browser with one background and one foreground tab.
  ASSERT_TRUE(embedded_test_server()->Start());
  const GURL kURL = embedded_test_server()->GetURL("a.com", "/title1.html");
  NavigateToURLWithDisposition(browser(), kURL,
                               WindowOpenDisposition::CURRENT_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  NavigateToURLWithDisposition(browser(), kURL,
                               WindowOpenDisposition::NEW_FOREGROUND_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  // Discard the background tab.
  auto* lifecycle_unit_to_discard = GetLifecycleUnitAt(0);
  auto* web_contents = GetWebContentsAt(0);
  ASSERT_EQ(web_contents->GetVisibility(), content::Visibility::HIDDEN);
  lifecycle_unit_to_discard->Discard(LifecycleUnitDiscardReason::URGENT,
                                     /* resident_set_size_estimate=*/0);

  // Get the WebContents at index 0 again. This is necessary because discarding
  // the tab via LifecycleUnit might replace the original WebContents object at
  // that index with a new, empty WebContents. We need to obtain a reference to
  // this newly created WebContents to correctly verify its unloaded state.
  auto* discarded_contents = GetWebContentsAt(0);
  // Verify that it is considered unloaded by `TabLoadTracker`.
  ASSERT_TRUE(discarded_contents->WasDiscarded());
  EXPECT_EQ(TabLoadTracker::Get()->GetLoadingState(discarded_contents),
            TabLoadTracker::LoadingState::UNLOADED);
}

IN_PROC_BROWSER_TEST_P(TabManagerTest, InvalidOrEmptyURL) {
  // Open two tabs. Wait for the foreground one to load but do not wait for the
  // background one.
  NavigateToURLWithDisposition(browser(), GURL(chrome::kChromeUIAboutURL),
                               WindowOpenDisposition::CURRENT_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  NavigateToURLWithDisposition(browser(), GURL(chrome::kChromeUICreditsURL),
                               WindowOpenDisposition::NEW_BACKGROUND_TAB,
                               ui_test_utils::BROWSER_TEST_NO_WAIT);

  ASSERT_EQ(2, tsm()->count());

  // This shouldn't be able to discard a tab as the background tab has not yet
  // started loading (its URL is not committed).
  EXPECT_FALSE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));

  // Wait for the background tab to load which then allows it to be discarded.
  content::WaitForLoadStop(browser()->tab_strip_model()->GetWebContentsAt(1));
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));
}

// Makes sure that the TabDiscardDoneCB callback is called after
// DiscardTabImpl() returns.
IN_PROC_BROWSER_TEST_P(TabManagerTest, TabDiscardDoneCallback) {
  // Open two tabs.
  NavigateToURLWithDisposition(browser(), GURL(chrome::kChromeUIAboutURL),
                               WindowOpenDisposition::CURRENT_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  NavigateToURLWithDisposition(browser(), GURL(chrome::kChromeUICreditsURL),
                               WindowOpenDisposition::NEW_BACKGROUND_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  ASSERT_EQ(2, tsm()->count());

  struct CallbackState {
    bool called_ = false;
    void Run() { called_ = true; }
  } callback_state;

  TabManager::TabDiscardDoneCB callback{
      base::BindOnce(&CallbackState::Run, base::Unretained(&callback_state))};
  EXPECT_TRUE(tab_manager()->DiscardTabImpl(
      LifecycleUnitDiscardReason::EXTERNAL, std::move(callback)));
  EXPECT_TRUE(callback_state.called_);
}

// Makes sure that PDF pages are protected.
IN_PROC_BROWSER_TEST_P(TabManagerTest, ProtectPDFPages) {
  // Start the embedded test server so we can get served the required PDF page.
  ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
  embedded_test_server()->StartAcceptingConnections();

  // Get two tabs open, the first one being a PDF page and the second one being
  // the foreground tab.
  GURL url1 = embedded_test_server()->GetURL("/pdf/test.pdf");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url1));

  GURL url2(chrome::kChromeUIAboutURL);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), url2, WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  // No discarding should be possible as the only background tab is displaying a
  // PDF page, hence protected.
  EXPECT_FALSE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));
}

#if !BUILDFLAG(IS_CHROMEOS)
// Makes sure that recently opened or used tabs are protected.
// These protections only apply on non-Ash desktop platforms. Check
// TabLifecycleUnit::CanDiscard for more details.
IN_PROC_BROWSER_TEST_P(TabManagerTest,
                       ProtectRecentlyUsedTabsFromUrgentDiscarding) {
  TabManager* tab_manager = g_browser_process->GetTabManager();

  auto* tsm = browser()->tab_strip_model();

  // Open 2 tabs, the second one being in the background.
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL)));
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUIAboutURL),
      WindowOpenDisposition::NEW_BACKGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  EXPECT_EQ(2, tsm->count());

  // Advance the clock for less than the protection time.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime / 2);

  // Should not be able to discard a tab.
  ASSERT_FALSE(tab_manager->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));

  // Advance the clock for more than the protection time.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime / 2 +
                           base::Seconds(1));

  // Should be able to discard the background tab now.
  EXPECT_TRUE(tab_manager->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));

  // Activate the 2nd tab.
  tsm->ActivateTabAt(1, TabStripUserGestureDetails(
                            TabStripUserGestureDetails::GestureType::kOther));
  EXPECT_EQ(1, tsm->active_index());

  // Advance the clock for less than the protection time.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime / 2);

  // Should not be able to urgent discard the tab.
  ASSERT_FALSE(tab_manager->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));

  // But should be able to externally discard the tab.
  EXPECT_TRUE(
      tab_manager->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));

  // This is necessary otherwise the test crashes in
  // WebContentsData::WebContentsDestroyed.
  tsm->CloseAllTabs();
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

// Makes sure that tabs using media devices are protected.
IN_PROC_BROWSER_TEST_P(TabManagerTest, ProtectVideoTabs) {
  // Open 2 tabs, the second one being in the background.
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL)));
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUIAboutURL),
      WindowOpenDisposition::NEW_BACKGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  auto* tab = GetWebContentsAt(1);

  // Simulate that a video stream is now being captured.
  blink::mojom::StreamDevices devices;
  blink::MediaStreamDevice video_device = blink::MediaStreamDevice(
      blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, "fake_media_device",
      "fake_media_device");
  devices.video_device = video_device;
  MediaCaptureDevicesDispatcher* dispatcher =
      MediaCaptureDevicesDispatcher::GetInstance();
  dispatcher->SetTestVideoCaptureDevices({video_device});
  std::unique_ptr<content::MediaStreamUI> video_stream_ui =
      dispatcher->GetMediaStreamCaptureIndicator()->RegisterMediaStream(
          tab, devices);
  video_stream_ui->OnStarted(base::RepeatingClosure(),
                             content::MediaStreamUI::SourceCallback(),
                             /*label=*/std::string(), /*screen_capture_ids=*/{},
                             content::MediaStreamUI::StateChangeCallback());

  // Should not be able to discard a tab.
  ASSERT_FALSE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));

  // Remove the video stream.
  video_stream_ui.reset();

  // Should be able to discard the background tab now.
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));
}

// Makes sure that tabs using DevTools are protected from discarding.
// TODO(crbug.com/40913262): Flaky on debug Linux.
#if BUILDFLAG(IS_LINUX) && !defined(NDEBUG)
#define MAYBE_ProtectDevToolsTabsFromDiscarding \
  DISABLED_ProtectDevToolsTabsFromDiscarding
#else
#define MAYBE_ProtectDevToolsTabsFromDiscarding \
  ProtectDevToolsTabsFromDiscarding
#endif
IN_PROC_BROWSER_TEST_P(TabManagerTest,
                       MAYBE_ProtectDevToolsTabsFromDiscarding) {
  // Get two tabs open, the second one being the foreground tab.
  GURL test_page(ui_test_utils::GetTestUrl(
      base::FilePath(), base::FilePath(FILE_PATH_LITERAL("simple.html"))));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page));
  // Open a DevTools window for the first.
  DevToolsWindow* devtool = DevToolsWindowTesting::OpenDevToolsWindowSync(
      GetWebContentsAt(0), true /* is_docked */);
  EXPECT_TRUE(devtool);

  GURL url2(chrome::kChromeUIAboutURL);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUIAboutURL),
      WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  // No discarding should be possible as the only background tab is currently
  // using DevTools.
  EXPECT_FALSE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));

  // Close the DevTools window and repeat the test, this time use a non-docked
  // window.
  DevToolsWindowTesting::CloseDevToolsWindowSync(devtool);
  devtool = DevToolsWindowTesting::OpenDevToolsWindowSync(
      GetWebContentsAt(0), false /* is_docked */);
  EXPECT_TRUE(devtool);
  EXPECT_FALSE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));

  // Close the DevTools window, ensure that the tab can be discarded.
  DevToolsWindowTesting::CloseDevToolsWindowSync(devtool);
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));
}

IN_PROC_BROWSER_TEST_P(TabManagerTest, AutoDiscardable) {
  // Get two tabs open.
  NavigateToURLWithDisposition(browser(), GURL(chrome::kChromeUIAboutURL),
                               WindowOpenDisposition::CURRENT_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);

  NavigateToURLWithDisposition(browser(), GURL(chrome::kChromeUICreditsURL),
                               WindowOpenDisposition::NEW_FOREGROUND_TAB,
                               ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  ASSERT_EQ(2, tsm()->count());

  // Set the auto-discardable state of the first tab to false.
  TabLifecycleUnitExternal::FromWebContents(GetWebContentsAt(0))
      ->SetAutoDiscardable(false);

  // Shouldn't discard the tab, since auto-discardable is deactivated.
  EXPECT_FALSE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));

  // Reset auto-discardable state to true.
  TabLifecycleUnitExternal::FromWebContents(GetWebContentsAt(0))
      ->SetAutoDiscardable(true);

  // Now it should be able to discard the tab.
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::EXTERNAL));
  EXPECT_TRUE(IsTabDiscarded(GetWebContentsAt(0)));
}

IN_PROC_BROWSER_TEST_P(TabManagerTestWithTwoTabs,
                       UrgentFastShutdownSingleTabProcess) {
  // The Tab Manager should be able to fast-kill a process for the discarded tab
  // on all platforms, as each tab will be running in a separate process by
  // itself regardless of the discard reason.
  WindowedRenderProcessHostExitObserver observer;
  // Advance time so everything is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));
  observer.Wait();
}

IN_PROC_BROWSER_TEST_P(TabManagerTest, UrgentFastShutdownSharedTabProcess) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Set max renderers to 1 before opening tabs to force running out of
  // processes and for both these tabs to share a renderer.
  content::RenderProcessHost::SetMaxRendererProcessCount(1);
  OpenTwoTabs(embedded_test_server()->GetURL("a.com", "/title1.html"),
              embedded_test_server()->GetURL("a.com", "/title2.html"));
  EXPECT_EQ(tsm()->GetWebContentsAt(0)->GetPrimaryMainFrame()->GetProcess(),
            tsm()->GetWebContentsAt(1)->GetPrimaryMainFrame()->GetProcess());

  // Advance time so everything is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  // The Tab Manager will not be able to fast-kill either of the tabs since they
  // share the same process regardless of the discard reason. An unsafe attempt
  // will be made on some platforms.
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));
}

IN_PROC_BROWSER_TEST_P(TabManagerTest, UrgentFastShutdownWithUnloadHandler) {
  ASSERT_TRUE(embedded_test_server()->Start());
  // Disable the protection of recent tabs.
  OpenTwoTabs(embedded_test_server()->GetURL("a.com", "/title1.html"),
              embedded_test_server()->GetURL("/unload.html"));

  // Advance time so everything is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  // The Tab Manager will not be able to safely fast-kill either of the tabs as
  // one of them is current, and the other has an unload handler. An unsafe
  // attempt will be made on some platforms.
#if BUILDFLAG(IS_CHROMEOS)
  // The unsafe attempt for ChromeOS should succeed as ChromeOS ignores unload
  // handlers when in critical condition.
  WindowedRenderProcessHostExitObserver observer;
#endif  // BUILDFLAG(IS_CHROMEOS)
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));
#if BUILDFLAG(IS_CHROMEOS)
  observer.Wait();
#endif  // BUILDFLAG(IS_CHROMEOS)
}

IN_PROC_BROWSER_TEST_P(TabManagerTest,
                       UrgentFastShutdownWithBeforeunloadHandler) {
  ASSERT_TRUE(embedded_test_server()->Start());
  // Disable the protection of recent tabs.
  OpenTwoTabs(embedded_test_server()->GetURL("a.com", "/title1.html"),
              embedded_test_server()->GetURL("/beforeunload.html"));

  // Advance time so everything is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  // The Tab Manager will not be able to safely fast-kill either of the tabs as
  // one of them is current, and the other has a beforeunload handler. An unsafe
  // attempt will be made on some platforms.
  EXPECT_TRUE(
      tab_manager()->DiscardTabImpl(LifecycleUnitDiscardReason::URGENT));
}

// Verifies the following state transitions for a tab:
// - Initial state: ACTIVE
// - Discard(kUrgent): ACTIVE->DISCARDED
// - Navigate: DISCARDED->ACTIVE
//             window.document.wasDiscarded is true
IN_PROC_BROWSER_TEST_P(TabManagerTestWithTwoTabs, TabUrgentDiscardAndNavigate) {
  const char kDiscardedStateJS[] = "window.document.wasDiscarded;";

  GURL test_page(ui_test_utils::GetTestUrl(
      base::FilePath(), base::FilePath(FILE_PATH_LITERAL("simple.html"))));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page));

  // document.wasDiscarded is false initially.
  EXPECT_EQ(false, content::EvalJs(GetWebContentsAt(0), kDiscardedStateJS));

  // Discard the tab.
  EXPECT_EQ(LifecycleUnitState::ACTIVE, GetLifecycleUnitAt(0)->GetState());
  EXPECT_TRUE(
      GetLifecycleUnitAt(0)->Discard(LifecycleUnitDiscardReason::EXTERNAL));
  EXPECT_EQ(LifecycleUnitState::DISCARDED, GetLifecycleUnitAt(0)->GetState());

  // Here we simulate re-focussing the tab causing reload with navigation,
  // the navigation will reload the tab.
  // TODO(fdoray): Figure out why the test fails if a reload is done instead of
  // a navigation.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page));
  EXPECT_EQ(LifecycleUnitState::ACTIVE, GetLifecycleUnitAt(0)->GetState());

  // document.wasDiscarded is true on navigate after discard.
  EXPECT_EQ(true, content::EvalJs(GetWebContentsAt(0), kDiscardedStateJS));
}

IN_PROC_BROWSER_TEST_P(TabManagerTest, DiscardedTabHasNoProcess) {
  GURL test_page(ui_test_utils::GetTestUrl(
      base::FilePath(), base::FilePath(FILE_PATH_LITERAL("simple.html"))));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page));
  content::WebContents* web_contents = tsm()->GetActiveWebContents();

  // The renderer process should be alive at this point.
  content::RenderProcessHost* process =
      web_contents->GetPrimaryMainFrame()->GetProcess();
  ASSERT_TRUE(process);
  EXPECT_TRUE(process->IsInitializedAndNotDead());
  EXPECT_NE(base::kNullProcessHandle, process->GetProcess().Handle());
  const int initial_renderer_id = process->GetDeprecatedID();

  // Discard the tab. This simulates a tab discard.
  TabLifecycleUnitExternal::FromWebContents(web_contents)
      ->DiscardTab(LifecycleUnitDiscardReason::URGENT);

  // Replacing the WebContents for the discard operation should result in
  // assignment of a new RenderProcessHost.
  if (!base::FeatureList::IsEnabled(features::kWebContentsDiscard)) {
    content::WebContents* new_web_contents = tsm()->GetActiveWebContents();
    EXPECT_NE(new_web_contents, web_contents);
    web_contents = new_web_contents;
    content::RenderProcessHost* new_process =
        web_contents->GetPrimaryMainFrame()->GetProcess();
    EXPECT_NE(new_process, process);
    EXPECT_NE(new_process->GetDeprecatedID(), initial_renderer_id);
    process = new_process;
  }

  // The renderer process should be dead after a discard.
  EXPECT_EQ(process, web_contents->GetPrimaryMainFrame()->GetProcess());
  EXPECT_FALSE(process->IsInitializedAndNotDead());
  EXPECT_EQ(base::kNullProcessHandle, process->GetProcess().Handle());

  // Here we simulate re-focussing the tab causing reload with navigation,
  // the navigation will reload the tab.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page));

  // Reload should mean that the renderer process is alive now.
  EXPECT_EQ(process, web_contents->GetPrimaryMainFrame()->GetProcess());
  EXPECT_TRUE(process->IsInitializedAndNotDead());
  EXPECT_NE(base::kNullProcessHandle, process->GetProcess().Handle());
}

IN_PROC_BROWSER_TEST_P(TabManagerTest,
                       TabManagerWasDiscardedCrossSiteSubFrame) {
  const char kDiscardedStateJS[] = "window.document.wasDiscarded;";
  // Navigate to a page with a cross-site frame.
  content::SetupCrossSiteRedirector(embedded_test_server());
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL main_url(
      embedded_test_server()->GetURL("a.com", "/iframe_cross_site.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));

  // Grab the original frames.
  content::WebContents* contents = tsm()->GetActiveWebContents();
  content::RenderFrameHost* main_frame = contents->GetPrimaryMainFrame();
  content::RenderFrameHost* child_frame = ChildFrameAt(main_frame, 0);
  ASSERT_TRUE(child_frame);

  // Sanity check that in this test page the main frame and the
  // subframe are cross-site.
  EXPECT_NE(main_frame->GetLastCommittedURL().DeprecatedGetOriginAsURL(),
            child_frame->GetLastCommittedURL().DeprecatedGetOriginAsURL());
  if (content::AreAllSitesIsolatedForTesting()) {
    EXPECT_NE(main_frame->GetSiteInstance(), child_frame->GetSiteInstance());
    EXPECT_NE(main_frame->GetProcess()->GetDeprecatedID(),
              child_frame->GetProcess()->GetDeprecatedID());
  }

  // document.wasDiscarded is false before discard, on main frame and child
  // frame.
  EXPECT_EQ(false, content::EvalJs(main_frame, kDiscardedStateJS));

  EXPECT_EQ(false, content::EvalJs(child_frame, kDiscardedStateJS));

  // Discard the tab. This simulates a tab discard.
  TabLifecycleUnitExternal::FromWebContents(contents)->DiscardTab(
      LifecycleUnitDiscardReason::URGENT);

  // Here we simulate re-focussing the tab causing reload with navigation,
  // the navigation will reload the tab.
  // TODO(panicker): Consider adding a test hook on LifecycleUnit when ready.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));

  // Re-assign pointers after discarding, as they've changed.
  contents = tsm()->GetActiveWebContents();
  main_frame = contents->GetPrimaryMainFrame();
  child_frame = ChildFrameAt(main_frame, 0);
  ASSERT_TRUE(child_frame);

  // document.wasDiscarded is true after discard, on mainframe and childframe.
  EXPECT_EQ(true, content::EvalJs(main_frame, kDiscardedStateJS));

  EXPECT_EQ(true, content::EvalJs(child_frame, kDiscardedStateJS));

  // Navigate the child frame, wasDiscarded is not set anymore.
  GURL childframe_url(embedded_test_server()->GetURL("b.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(contents, "frame1", childframe_url));
  EXPECT_EQ(false,
            content::EvalJs(ChildFrameAt(contents, 0), kDiscardedStateJS));

  // Navigate second child frame cross site.
  GURL second_childframe_url(
      embedded_test_server()->GetURL("d.com", "/title1.html"));
  EXPECT_TRUE(NavigateIframeToURL(contents, "frame2", second_childframe_url));
  EXPECT_EQ(false,
            content::EvalJs(ChildFrameAt(contents, 1), kDiscardedStateJS));

  // Navigate the main frame (same site) again, wasDiscarded is not set anymore.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));
  main_frame = contents->GetPrimaryMainFrame();
  EXPECT_EQ(false, content::EvalJs(main_frame, kDiscardedStateJS));

  // Go back in history and ensure wasDiscarded is still false.
  content::TestNavigationObserver observer(contents);
  contents->GetController().GoBack();
  observer.Wait();
  main_frame = contents->GetPrimaryMainFrame();
  EXPECT_EQ(false, content::EvalJs(main_frame, kDiscardedStateJS));
}

class TabManagerFencedFrameTest : public TabManagerTest {
 public:
  TabManagerFencedFrameTest()
      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
    https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
    https_server_.AddDefaultHandlers(GetChromeTestDataDir());
  }
  ~TabManagerFencedFrameTest() override = default;

 protected:
  net::EmbeddedTestServer& https_server() { return https_server_; }
  content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
    return fenced_frame_test_helper_;
  }

 private:
  net::EmbeddedTestServer https_server_;
  content::test::FencedFrameTestHelper fenced_frame_test_helper_;
};

// Tests that `window.document.wasDiscarded` is updated for a fenced frame.
IN_PROC_BROWSER_TEST_P(TabManagerFencedFrameTest, TabManagerWasDiscarded) {
  const char kDiscardedStateJS[] = "window.document.wasDiscarded;";

  // Navigate to a page with a fenced frame.
  ASSERT_TRUE(https_server().Start());
  GURL main_url(
      https_server().GetURL("c.test", "/fenced_frames/basic_title.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));

  // Grab the original frames.
  content::WebContents* contents = tsm()->GetActiveWebContents();
  content::RenderFrameHost* primary_main_frame =
      contents->GetPrimaryMainFrame();

  content::RenderFrameHost* fenced_frame =
      fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
          primary_main_frame);
  ASSERT_TRUE(fenced_frame);

  // document.wasDiscarded is false before discard, on a main frame and fenced
  // frame.
  EXPECT_EQ(false, content::EvalJs(primary_main_frame, kDiscardedStateJS));

  EXPECT_EQ(false, content::EvalJs(fenced_frame, kDiscardedStateJS));

  // Discard the tab. This simulates a tab discard.
  TabLifecycleUnitExternal::FromWebContents(contents)->DiscardTab(
      LifecycleUnitDiscardReason::URGENT);

  // Here we simulate re-focussing the tab causing reload with navigation,
  // the navigation will reload the tab.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url));

  // Re-assign pointers after discarding, as they've changed.
  contents = tsm()->GetActiveWebContents();
  primary_main_frame = contents->GetPrimaryMainFrame();
  fenced_frame = fenced_frame_test_helper().GetMostRecentlyAddedFencedFrame(
      primary_main_frame);
  ASSERT_TRUE(fenced_frame);

  // document.wasDiscarded is true after discard, on a main frame and fenced
  // frame.
  EXPECT_EQ(true, content::EvalJs(primary_main_frame, kDiscardedStateJS));

  EXPECT_EQ(true, content::EvalJs(fenced_frame, kDiscardedStateJS));
}

namespace {

// Ensures that |browser| has |num_tabs| open tabs.
void EnsureTabsInBrowser(Browser* browser, int num_tabs) {
  for (int i = 0; i < num_tabs; ++i) {
    ui_test_utils::NavigateToURLWithDisposition(
        browser, GURL(chrome::kChromeUICreditsURL),
        i == 0 ? WindowOpenDisposition::CURRENT_TAB
               : WindowOpenDisposition::NEW_BACKGROUND_TAB,
        ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  }

  EXPECT_EQ(num_tabs, browser->tab_strip_model()->count());
}

// Creates a browser with |num_tabs| tabs.
Browser* CreateBrowserWithTabs(int num_tabs) {
  Browser* current_browser = BrowserList::GetInstance()->GetLastActive();
  ui_test_utils::BrowserChangeObserver new_browser_observer(
      nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded);
  chrome::NewWindow(current_browser);
  ui_test_utils::WaitForBrowserSetLastActive(new_browser_observer.Wait());
  Browser* new_browser = BrowserList::GetInstance()->GetLastActive();
  EXPECT_NE(new_browser, current_browser);

  // To avoid flakes when focus changes, set the active tab strip model
  // explicitly.
  GetTabLifecycleUnitSource()->SetFocusedTabStripModelForTesting(
      new_browser->tab_strip_model());

  EnsureTabsInBrowser(new_browser, num_tabs);
  return new_browser;
}

}  // namespace

// Do not run in debug or ASAN builds to avoid timeouts due to multiple
// navigations. https://crbug.com/1106485
#if !defined(NDEBUG) || defined(ADDRESS_SANITIZER)
#define MAYBE_DiscardTabsWithMinimizedWindow \
  DISABLED_DiscardTabsWithMinimizedWindow
#else
#define MAYBE_DiscardTabsWithMinimizedWindow DiscardTabsWithMinimizedWindow
#endif
IN_PROC_BROWSER_TEST_P(TabManagerTest, MAYBE_DiscardTabsWithMinimizedWindow) {
  // Do not override the focused TabStripModel.
  GetTabLifecycleUnitSource()->SetFocusedTabStripModelForTesting(nullptr);

  // Minimized browser.
  EnsureTabsInBrowser(browser(), 2);
  browser()->window()->Minimize();

  // Advance time so everything is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  for (int i = 0; i < 8; ++i) {
    tab_manager()->DiscardTabByExtension(nullptr);
  }

  base::RunLoop().RunUntilIdle();

// On ChromeOS, active tabs are discarded if their window is non-visible. On
// other platforms, they are never discarded.
#if BUILDFLAG(IS_CHROMEOS)
  EXPECT_TRUE(
      IsTabDiscarded(browser()->tab_strip_model()->GetWebContentsAt(0)));
#else
  EXPECT_FALSE(
      IsTabDiscarded(browser()->tab_strip_model()->GetWebContentsAt(0)));
#endif

  // Non-active tabs can be discarded on all platforms.
  EXPECT_TRUE(
      IsTabDiscarded(browser()->tab_strip_model()->GetWebContentsAt(1)));

  // Showing the browser again should reload the active tab.
  browser()->window()->Show();
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(
      IsTabDiscarded(browser()->tab_strip_model()->GetWebContentsAt(0)));
}

// Do not run in debug or ASAN builds to avoid timeouts due to multiple
// navigations. https://crbug.com/1106485
#if !defined(NDEBUG) || defined(ADDRESS_SANITIZER)
#define MAYBE_DiscardTabsWithOccludedWindow \
  DISABLED_DiscardTabsWithOccludedWindow
#else
#define MAYBE_DiscardTabsWithOccludedWindow DiscardTabsWithOccludedWindow
#endif
IN_PROC_BROWSER_TEST_P(TabManagerTest, MAYBE_DiscardTabsWithOccludedWindow) {
  // Occluded browser.
  EnsureTabsInBrowser(browser(), 2);
  browser()->window()->SetBounds(gfx::Rect(10, 10, 10, 10));
  // Other browser that covers the occluded browser.
  Browser* other_browser = CreateBrowserWithTabs(1);
  EXPECT_NE(other_browser, browser());
  other_browser->window()->SetBounds(gfx::Rect(0, 0, 100, 100));

  // Advance time so everything is urgent discardable.
  test_tick_clock_.Advance(kBackgroundUrgentProtectionTime);

  for (int i = 0; i < 3; ++i)
    tab_manager()->DiscardTabByExtension(nullptr);

  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(
      IsTabDiscarded(browser()->tab_strip_model()->GetWebContentsAt(0)));

  // Non-active tabs can be discarded on all platforms.
  EXPECT_TRUE(
      IsTabDiscarded(browser()->tab_strip_model()->GetWebContentsAt(1)));
}

INSTANTIATE_TEST_SUITE_P(
    ,
    TabManagerTest,
    ::testing::Values(false, true),
    [](const ::testing::TestParamInfo<TabManagerTest::ParamType>& info) {
      return info.param ? "RetainedWebContents" : "UnretainedWebContents";
    });

INSTANTIATE_TEST_SUITE_P(
    ,
    TabManagerTestWithTwoTabs,
    ::testing::Values(false, true),
    [](const ::testing::TestParamInfo<TabManagerTestWithTwoTabs::ParamType>&
           info) {
      return info.param ? "RetainedWebContents" : "UnretainedWebContents";
    });

INSTANTIATE_TEST_SUITE_P(
    ,
    TabManagerFencedFrameTest,
    ::testing::Values(false, true),
    [](const ::testing::TestParamInfo<TabManagerFencedFrameTest::ParamType>&
           info) {
      return info.param ? "RetainedWebContents" : "UnretainedWebContents";
    });

}  // namespace resource_coordinator

#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) ||
        // BUILDFLAG(IS_CHROMEOS)