File: coral_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; 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 (866 lines) | stat: -rw-r--r-- 35,312 bytes parent folder | download | duplicates (7)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/birch/birch_coral_provider.h"
#include "ash/birch/birch_item.h"
#include "ash/birch/birch_model.h"
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "ash/public/cpp/coral_delegate.h"
#include "ash/public/cpp/window_properties.h"
#include "ash/shell.h"
#include "ash/test/ash_test_util.h"
#include "ash/webui/system_apps/public/system_web_app_type.h"
#include "ash/wm/coral/coral_test_util.h"
#include "ash/wm/desks/desks_controller.h"
#include "ash/wm/desks/desks_test_util.h"
#include "ash/wm/mru_window_tracker.h"
#include "ash/wm/overview/birch/birch_chip_button.h"
#include "ash/wm/overview/birch/birch_chip_button_base.h"
#include "ash/wm/overview/birch/coral_chip_button.h"
#include "ash/wm/overview/overview_test_util.h"
#include "base/command_line.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/ash/app_restore/app_restore_test_util.h"
#include "chrome/browser/ash/app_restore/full_restore_app_launch_handler.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/ash/birch/birch_test_util.h"
#include "chrome/browser/ui/ash/system_web_apps/system_web_app_ui_utils.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/test/base/ash/util/ash_test_util.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chromeos/ash/services/coral/public/mojom/coral_service.mojom.h"
#include "components/app_restore/restore_data.h"
#include "content/public/test/browser_test.h"
#include "gmock/gmock.h"

namespace ash {
namespace {

// Collects the tab URLs from the given window list.
std::vector<GURL> CollectTabURLsFromWindows(
    const MruWindowTracker::WindowList& windows) {
  std::vector<GURL> tab_urls;
  for (aura::Window* window : windows) {
    Browser* browser =
        BrowserView::GetBrowserViewForNativeWindow(window)->browser();

    if (!browser) {
      continue;
    }

    TabStripModel* tab_strip_model = browser->tab_strip_model();
    for (int idx = 0; idx < tab_strip_model->count(); idx++) {
      tab_urls.push_back(
          tab_strip_model->GetWebContentsAt(idx)->GetVisibleURL());
    }
  }
  return tab_urls;
}

// Collects the app IDs from the given window list.
std::vector<std::string> CollectAppIDsFromWindows(
    const MruWindowTracker::WindowList& windows) {
  std::vector<std::string> app_ids;
  for (aura::Window* window : windows) {
    if (auto* app_id = window->GetProperty(kAppIDKey)) {
      app_ids.emplace_back(*app_id);
    }
  }
  return app_ids;
}

// Returns the native window associated with `swa_type`, if it exists.
aura::Window* GetNativeWindowForSwa(SystemWebAppType swa_type) {
  BrowserList* browsers = BrowserList::GetInstance();
  auto it = std::ranges::find_if(*browsers, [swa_type](Browser* browser) {
    return IsBrowserForSystemWebApp(browser, swa_type);
  });
  return it == browsers->end() ? nullptr : (*it)->window()->GetNativeWindow();
}

}  // namespace

class CoralBrowserTest : public InProcessBrowserTest {
 public:
  CoralBrowserTest() { set_launch_browser_for_testing(nullptr); }
  CoralBrowserTest(const CoralBrowserTest&) = delete;
  CoralBrowserTest& operator=(const CoralBrowserTest&) = delete;
  ~CoralBrowserTest() override = default;

  // InProcessBrowserTest:
  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();

    // Disable the prefs for data providers other than coral. This ensures
    // the data is fresh once the last active provider replies.
    DisableAllDataTypePrefsExcept({prefs::kBirchUseCoral});

    // Ensure the item remover is initialized, otherwise data fetches won't
    // complete.
    EnsureItemRemoverInitialized();
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    InProcessBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kForceBirchFakeCoralGroup);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_{features::kCoralFeature};
};

IN_PROC_BROWSER_TEST_F(CoralBrowserTest, PRE_PostLoginLaunch) {
  Profile* profile = ProfileManager::GetActiveUserProfile();
  test::InstallSystemAppsForTesting(profile);

  // Launch some SWA's. We will confirm their window bounds and state in the
  // real test. This will also ensure that post login overview shows up by
  // having at least one app open.
  test::CreateSystemWebApp(profile, SystemWebAppType::FILE_MANAGER);
  test::CreateSystemWebApp(profile, SystemWebAppType::SETTINGS);

  aura::Window* files_window =
      GetNativeWindowForSwa(SystemWebAppType::FILE_MANAGER);
  ASSERT_TRUE(files_window);
  files_window->SetBounds(gfx::Rect(600, 600));
  aura::Window* settings_window =
      GetNativeWindowForSwa(SystemWebAppType::SETTINGS);
  ASSERT_TRUE(settings_window);
  WindowState::Get(settings_window)->Maximize();

  test::InstallAndLaunchPWA(profile, GURL("https://www.nba.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"NBA");

  // Immediate save to full restore file to bypass the 2.5 second throttle.
  AppLaunchInfoSaveWaiter::Wait();
}

// Launches a browser with the expected tabs when the post login coral chip is
// clicked.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, PostLoginLaunch) {
  ASSERT_TRUE(BrowserList::GetInstance()->empty());

  Profile* profile = ProfileManager::GetActiveUserProfile();

  test::InstallSystemAppsForTesting(profile);

  // Wait until the chip is visible, it may not be visible while data fetch is
  // underway or the overview animation is still running.
  EXPECT_TRUE(base::test::RunUntil([]() {
    BirchChipButtonBase* coral_chip = GetBirchChipButton();
    return !!coral_chip;
  }));

  BirchChipButtonBase* coral_chip = GetBirchChipButton();
  ASSERT_EQ(coral_chip->GetItem()->GetType(), BirchItemType::kCoral);

  test::BrowsersWaiter waiter(/*expected_count=*/4);
  test::Click(coral_chip);
  waiter.Wait();

  // TODO(zxdan): These tabs and apps are currently hardcoded in ash for
  // `switches::kForceBirchFakeCoral`. Update to use a test coral provider
  // instead.
  BrowserList* browsers = BrowserList::GetInstance();
  ASSERT_EQ(browsers->size(), 4u);
  // Verify the chrome browser.
  EXPECT_TRUE(std::ranges::any_of(*browsers, [](Browser* browser) {
    TabStripModel* tab_strip_model = browser->tab_strip_model();
    return tab_strip_model->count() == 3 &&
           tab_strip_model->GetWebContentsAt(0)->GetVisibleURL() ==
               GURL("https://www.reddit.com/") &&
           tab_strip_model->GetWebContentsAt(1)->GetVisibleURL() ==
               GURL("https://www.figma.com/") &&
           tab_strip_model->GetWebContentsAt(2)->GetVisibleURL() ==
               GURL("https://www.notion.so/");
  }));

  // Verify the PWA.
  EXPECT_TRUE(std::ranges::any_of(*browsers, [](Browser* browser) {
    if (browser->type() != Browser::TYPE_APP) {
      return false;
    }
    TabStripModel* tab_strip_model = browser->tab_strip_model();
    return tab_strip_model->count() == 1 &&
           tab_strip_model->GetWebContentsAt(0)->GetVisibleURL() ==
               GURL("https://www.nba.com/");
  }));

  // Tests that the files and settings SWAs are launched and have their previous
  // session window bounds.
  aura::Window* files_window =
      GetNativeWindowForSwa(SystemWebAppType::FILE_MANAGER);
  ASSERT_TRUE(files_window);
  EXPECT_EQ(files_window->GetBoundsInScreen(), gfx::Rect(600, 600));

  aura::Window* settings_window =
      GetNativeWindowForSwa(SystemWebAppType::SETTINGS);
  ASSERT_TRUE(settings_window);
  EXPECT_TRUE(WindowState::Get(settings_window)->IsMaximized());
}

// Tests that the Coral Delegate could create a new browser on the new desk by
// moving indicated tabs from the browser on the active desk.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, MoveTabsToNewDesk) {
  // Create two browsers with different tabs and urls.
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();
  test::CreateAndShowBrowser(primary_profile, {GURL("https://youtube.com"),
                                               GURL("https://google.com")});
  test::CreateAndShowBrowser(
      primary_profile,
      {GURL("https://maps.google.com"), GURL("https://mail.google.com")});

  // Cache the windows on current desk.
  const auto windows_on_last_active_desk =
      Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk);

  // Create a fake coral group which contains two tabs that are selected from
  // each of the two browsers created above.
  std::vector<coral::mojom::GroupPtr> fake_groups;
  fake_groups.push_back(
      CreateTestGroup({{"Youtube", GURL("https://youtube.com")},
                       {"Google Maps", GURL("https://maps.google.com")}},
                      "Coral desk"));
  OverrideTestResponse(std::move(fake_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  BirchChipButton* coral_chip = GetFirstCoralButton();
  ASSERT_TRUE(coral_chip);
  test::Click(coral_chip);

  // We should have two desks and the new active desk has the coral title.
  DesksController* desks_controller = DesksController::Get();
  EXPECT_EQ(desks_controller->desks().size(), 2u);
  EXPECT_EQ(desks_controller->GetActiveDeskIndex(), 1);
  EXPECT_EQ(
      desks_controller->GetDeskName(desks_controller->GetActiveDeskIndex()),
      u"Coral desk");

  // The active desk should have a browser window which has the two tabs in the
  // fake group.
  std::vector<GURL> tab_urls_on_active_desk = CollectTabURLsFromWindows(
      Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk));
  EXPECT_THAT(tab_urls_on_active_desk,
              testing::UnorderedElementsAre(GURL("https://youtube.com"),
                                            GURL("https://maps.google.com")));

  // The last active desk should not have the moved tabs.
  std::vector<GURL> tab_urls_on_last_active_desk =
      CollectTabURLsFromWindows(windows_on_last_active_desk);
  EXPECT_THAT(tab_urls_on_last_active_desk,
              testing::UnorderedElementsAre(GURL("https://google.com"),
                                            GURL("https://mail.google.com")));
}

// Tests that the Coral controller could create a new desk and move the apps in
// the group to the new desk.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, MoveAppsToNewDesk) {
  // Create two browsers with different tabs and urls.
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();

  test::InstallSystemAppsForTesting(primary_profile);

  // Open some SWA windows.
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::FILE_MANAGER);
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::SETTINGS);
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::HELP);

  // Create a browser window.
  CreateBrowser(primary_profile);

  // Open some PWA windows.
  test::InstallAndLaunchPWA(primary_profile, GURL("https://www.youtube.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"YouTube");
  test::InstallAndLaunchPWA(primary_profile, GURL("https://www.gmail.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"Gmail");

  // Create a fake coral group which contains four apps except the Files app and
  // the browser.
  std::vector<coral::mojom::GroupPtr> fake_groups;
  fake_groups.push_back(
      CreateTestGroup({{"Youtube", "adnlfjpnmidfimlkaohpidplnoimahfh"},
                       {"Gmail", "gdkbjbkdgeggmfkjbfohmimchmkikbid"},
                       {"Explore", "nbljnnecbjbmifnoehiemkgefbnpoeak"},
                       {"Settings", "odknhmnlageboeamepcngndbggdpaobj"}},
                      "Coral desk"));
  OverrideTestResponse(std::move(fake_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  BirchChipButton* coral_chip = GetFirstCoralButton();
  ASSERT_TRUE(coral_chip);
  test::Click(coral_chip);

  // We should have two desks and the new active desk has the coral title.
  DesksController* desks_controller = DesksController::Get();
  EXPECT_EQ(desks_controller->desks().size(), 2u);
  EXPECT_EQ(desks_controller->GetActiveDeskIndex(), 1);
  EXPECT_EQ(
      desks_controller->GetDeskName(desks_controller->GetActiveDeskIndex()),
      u"Coral desk");

  // The active desk should have the four apps in the group.
  std::vector<std::string> app_ids_on_active_desk = CollectAppIDsFromWindows(
      Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk));
  EXPECT_THAT(app_ids_on_active_desk, testing::UnorderedElementsAre(
                                          "adnlfjpnmidfimlkaohpidplnoimahfh",
                                          "gdkbjbkdgeggmfkjbfohmimchmkikbid",
                                          "nbljnnecbjbmifnoehiemkgefbnpoeak",
                                          "odknhmnlageboeamepcngndbggdpaobj"));
}

// Tests that the chip will get updated when the title is loaded by the backend.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, AsyncGroupTitle) {
  // Create a test coral group with a pending title.
  std::vector<coral::mojom::GroupPtr> test_groups;
  test_groups.push_back(
      CreateTestGroup({{"example", GURL("www.example.com")}}));
  OverrideTestResponse(std::move(test_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // The birch bar is created with a single chip.
  CoralChipButton* coral_chip =
      views::AsViewClass<CoralChipButton>(GetBirchChipButton());
  ASSERT_TRUE(coral_chip);

  // The chip should hide title with title pending.
  ASSERT_EQ(coral_chip->GetItem()->GetType(), BirchItemType::kCoral);
  ASSERT_FALSE(coral_chip->title()->GetVisible());

  // When the group title gets updated, the chip title will be shown with
  // updated title.
  BirchCoralProvider::Get()->TitleUpdated(base::Token(), "Updated Title");
  ASSERT_TRUE(coral_chip->title()->GetVisible());
  EXPECT_EQ(coral_chip->title()->GetText(), u"Updated Title");
  EXPECT_EQ(coral_chip->GetAccessibleName(),
            u"Updated Title Organize in a new desk");
}

// Tests that the chip will show placeholder title when corresponding group
// title loading fails.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, GroupTitleLoadingFail) {
  // Create a test coral group with a pending title.
  std::vector<coral::mojom::GroupPtr> test_groups;
  test_groups.push_back(
      CreateTestGroup({{"example", GURL("www.example.com")}}));
  OverrideTestResponse(std::move(test_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // The birch bar is created with a single chip.
  CoralChipButton* coral_chip =
      views::AsViewClass<CoralChipButton>(GetBirchChipButton());
  ASSERT_TRUE(coral_chip);

  // The chip should show placeholder title when receiving an empty title.
  ASSERT_EQ(coral_chip->GetItem()->GetType(), BirchItemType::kCoral);
  ASSERT_FALSE(coral_chip->title()->GetVisible());

  // When the group title gets updated, the chip title will be shown with
  // updated title.
  BirchCoralProvider::Get()->TitleUpdated(base::Token(), "");
  ASSERT_TRUE(coral_chip->title()->GetVisible());
  EXPECT_EQ(coral_chip->title()->GetText(), u"Suggested group");
  EXPECT_EQ(coral_chip->GetAccessibleName(),
            u"Suggested group Organize in a new desk");
}

// Tests that the coral chip gets updated while corresponding tab/app items are
// closed.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, CloseTabAppUpdateChip) {
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();

  // Create two browsers. A url appears in both browsers.
  test::CreateAndShowBrowser(primary_profile, {GURL("https://youtube.com")});
  test::CreateAndShowBrowser(primary_profile, {GURL("https://youtube.com"),
                                               GURL("https://google.com")});

  test::InstallSystemAppsForTesting(primary_profile);

  // Open two File windows and two PWA windows.
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::FILE_MANAGER);
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::FILE_MANAGER);
  test::InstallAndLaunchPWA(primary_profile, GURL("https://www.youtube.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"YouTube");
  test::InstallAndLaunchPWA(primary_profile, GURL("https://www.gmail.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"Gmail");

  // Create a fake coral group which contains non-duplicated tabs and apps.
  std::vector<coral::mojom::GroupPtr> test_groups;
  test_groups.push_back(
      CreateTestGroup({{"google.com", GURL("https://google.com/")},
                       {"youtube.com", GURL("https://youtube.com/")},
                       {"YouTube", "adnlfjpnmidfimlkaohpidplnoimahfh"},
                       {"Files", "fkiggjmkendpmbegkagpmagjepfkpmeb"}},
                      "Coral desk"));

  OverrideTestResponse(std::move(test_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // The birch bar is created with a coral chip.
  ASSERT_TRUE(GetBirchChipButton());

  const auto& group = BirchCoralProvider::Get()->GetGroupById(base::Token());

  EXPECT_EQ(group->entities.size(), 4u);

  // Closing the first browser with the duplicated tab (https://youtube.com)
  // will not change the group.
  SelectFirstBrowser();
  CloseBrowserSynchronously(browser());
  EXPECT_EQ(group->entities.size(), 4u);

  // Closing the next browser will decrease the items in the group.
  SelectFirstBrowser();
  CloseBrowserSynchronously(browser());
  EXPECT_EQ(group->entities.size(), 2u);

  // Closing a duplicated window (file manager) will not change the group.
  SelectFirstBrowser();
  EXPECT_TRUE(
      browser()->window()->GetNativeWindow()->GetTitle().starts_with(u"Files"));
  CloseBrowserSynchronously(browser());
  EXPECT_EQ(group->entities.size(), 2u);

  // Closing a non-duplicated window will decrease the items in the group.
  SelectFirstBrowser();
  EXPECT_TRUE(
      browser()->window()->GetNativeWindow()->GetTitle().starts_with(u"Files"));
  CloseBrowserSynchronously(browser());
  EXPECT_EQ(group->entities.size(), 1u);

  // Closing the last app window in group will remove the chip.
  SelectFirstBrowser();
  EXPECT_TRUE(browser()->window()->GetNativeWindow()->GetTitle().starts_with(
      u"YouTube"));
  CloseBrowserSynchronously(browser());

  EXPECT_FALSE(GetBirchChipButton());
}

// Tests that closing a window which contains all the items in two groups would
// remove corresponding coral chips.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, CloseWindowRemoveTwoChips) {
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();

  // Create a browser containing 8 tabs.
  test::CreateAndShowBrowser(
      primary_profile,
      {GURL("https://mail.google.com"), GURL("https://youtube.com"),
       GURL("https://google.com"), GURL("https://earth.google.com"),
       GURL("https://maps.google.com"), GURL("https://docs.google.com"),
       GURL("https://calendar.google.com"), GURL("https://chat.google.com")});
  // Create another browser to keep staying in Overview after removing the first
  // one.
  test::CreateAndShowBrowser(primary_profile,
                             {GURL("https://meet.google.com")});

  // Create a fake coral group which contains non-duplicated tabs and apps.
  std::vector<coral::mojom::GroupPtr> test_groups;
  test_groups.push_back(
      CreateTestGroup({{"mail.google.com", GURL("https://mail.google.com")},
                       {"youtube.com", GURL("https://youtube.com")},
                       {"google.com", GURL("https://google.com")},
                       {"earth.google.com", GURL("https://earth.google.com")}},
                      "Coral desk 1", /*id=*/base::Token(1, 2)));
  test_groups.push_back(CreateTestGroup(
      {{"maps.google.com", GURL("https://maps.google.com")},
       {"docs.google.com", GURL("https://docs.google.com")},
       {"calendar.google.com", GURL("https://calendar.google.com")},
       {"chat.google.com", GURL("https://chat.google.com")}},
      "Coral desk 2", /*id=*/base::Token(2, 3)));

  OverrideTestResponse(std::move(test_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // The birch bar is created with two coral chips.
  ASSERT_EQ(GetBirchChipsNum(), 2u);

  // Closing the first browser with all items in groups.
  SelectFirstBrowser();
  EXPECT_EQ(8, browser()->tab_strip_model()->GetTabCount());
  CloseBrowserSynchronously(browser());

  // Two chips are removed.
  EXPECT_EQ(0u, GetBirchChipsNum());
}

// Tests that closing a desk removes all coral chips.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, CloseDeskRemoveAllChips) {
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();

  // Create a browser containing 8 tabs.
  test::CreateAndShowBrowser(
      primary_profile,
      {GURL("https://mail.google.com"), GURL("https://youtube.com"),
       GURL("https://google.com"), GURL("https://earth.google.com"),
       GURL("https://maps.google.com"), GURL("https://docs.google.com"),
       GURL("https://calendar.google.com"), GURL("https://chat.google.com")});

  test::InstallSystemAppsForTesting(primary_profile);

  // Open a File window and a PWA window.
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::FILE_MANAGER);
  test::InstallAndLaunchPWA(primary_profile, GURL("https://www.youtube.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"YouTube");

  // Create two fake coral groups.
  std::vector<coral::mojom::GroupPtr> test_groups;
  test_groups.push_back(
      CreateTestGroup({{"mail.google.com", GURL("https://mail.google.com")},
                       {"youtube.com", GURL("https://youtube.com")},
                       {"google.com", GURL("https://google.com")},
                       {"YouTube", "adnlfjpnmidfimlkaohpidplnoimahfh"}},
                      "Coral desk 1", /*id=*/base::Token(1, 2)));
  test_groups.push_back(CreateTestGroup(
      {{"maps.google.com", GURL("https://maps.google.com")},
       {"docs.google.com", GURL("https://docs.google.com")},
       {"calendar.google.com", GURL("https://calendar.google.com")},
       {"Files", "fkiggjmkendpmbegkagpmagjepfkpmeb"}},
      "Coral desk 2", /*id=*/base::Token(2, 3)));

  OverrideTestResponse(std::move(test_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  NewDesk();

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // The birch bar is created with two coral chips.
  ASSERT_EQ(GetBirchChipsNum(), 2u);

  // Closing the active desk removes all chips.
  RemoveDesk(GetActiveDesk(), DeskCloseType::kCloseAllWindows);
  SimulateWaitForCloseAll();

  // Two chips are removed.
  EXPECT_EQ(0u, GetBirchChipsNum());
}

// Tests that merging a desk removes all coral chips.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, MergeDeskRemoveAllChips) {
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();

  // Create a browser containing 8 tabs.
  test::CreateAndShowBrowser(
      primary_profile,
      {GURL("https://mail.google.com"), GURL("https://youtube.com"),
       GURL("https://google.com"), GURL("https://earth.google.com"),
       GURL("https://maps.google.com"), GURL("https://docs.google.com"),
       GURL("https://calendar.google.com"), GURL("https://chat.google.com")});

  test::InstallSystemAppsForTesting(primary_profile);

  // Open a File window and a PWA window.
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::FILE_MANAGER);
  test::InstallAndLaunchPWA(primary_profile, GURL("https://www.youtube.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"YouTube");

  // Create two fake coral groups.
  std::vector<coral::mojom::GroupPtr> test_groups;
  test_groups.push_back(
      CreateTestGroup({{"mail.google.com", GURL("https://mail.google.com")},
                       {"youtube.com", GURL("https://youtube.com")},
                       {"google.com", GURL("https://google.com")},
                       {"YouTube", "adnlfjpnmidfimlkaohpidplnoimahfh"}},
                      "Coral desk 1", /*id=*/base::Token(1, 2)));
  test_groups.push_back(CreateTestGroup(
      {{"maps.google.com", GURL("https://maps.google.com")},
       {"docs.google.com", GURL("https://docs.google.com")},
       {"calendar.google.com", GURL("https://calendar.google.com")},
       {"Files", "fkiggjmkendpmbegkagpmagjepfkpmeb"}},
      "Coral desk 2", /*id=*/base::Token(2, 3)));

  OverrideTestResponse(std::move(test_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  // Create a new desk to merge the active desk.
  NewDesk();

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // The birch bar is created with two coral chips.
  ASSERT_EQ(GetBirchChipsNum(), 2u);

  // There are two desks before removing.
  auto* desks_controller = DesksController::Get();
  ASSERT_EQ(desks_controller->GetNumberOfDesks(), 2);

  // Merging the active desk removes all chips.
  RemoveDesk(GetActiveDesk(), DeskCloseType::kCombineDesks);
  // There should be only one desk after merging.
  ASSERT_EQ(desks_controller->GetNumberOfDesks(), 1);

  // Two chips are removed.
  EXPECT_EQ(0u, GetBirchChipsNum());
}

// Tests that moving a window to another desk would update the groups and chips.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, MoveWindowToOtherDeskUpdateChip) {
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();

  // TODO(crbug.com/378159705): move this to a test helper.
  // Create a browser containing 8 tabs.
  test::CreateAndShowBrowser(
      primary_profile,
      {GURL("https://mail.google.com"), GURL("https://youtube.com"),
       GURL("https://google.com"), GURL("https://earth.google.com"),
       GURL("https://maps.google.com"), GURL("https://docs.google.com"),
       GURL("https://calendar.google.com"), GURL("https://chat.google.com")});

  test::InstallSystemAppsForTesting(primary_profile);

  // Open a File window and a PWA window.
  test::CreateSystemWebApp(primary_profile, SystemWebAppType::FILE_MANAGER);
  test::InstallAndLaunchPWA(primary_profile, GURL("https://www.youtube.com/"),
                            /*launch_in_browser=*/false,
                            /*app_title=*/u"YouTube");

  // Create two fake coral groups.
  std::vector<coral::mojom::GroupPtr> test_groups;
  test_groups.push_back(
      CreateTestGroup({{"mail.google.com", GURL("https://mail.google.com")},
                       {"youtube.com", GURL("https://youtube.com")},
                       {"google.com", GURL("https://google.com")},
                       {"YouTube", "adnlfjpnmidfimlkaohpidplnoimahfh"}},
                      "Coral desk 1", /*id=*/base::Token(1, 2)));
  test_groups.push_back(CreateTestGroup(
      {{"maps.google.com", GURL("https://maps.google.com")},
       {"docs.google.com", GURL("https://docs.google.com")},
       {"calendar.google.com", GURL("https://calendar.google.com")},
       {"Files", "fkiggjmkendpmbegkagpmagjepfkpmeb"}},
      "Coral desk 2", /*id=*/base::Token(2, 3)));

  OverrideTestResponse(std::move(test_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  // Create another desk.
  NewDesk();

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // The birch bar is created with two coral chips.
  ASSERT_EQ(GetBirchChipsNum(), 2u);

  // Both groups initially have 4 entities.
  const auto& group_1 =
      BirchCoralProvider::Get()->GetGroupById(base::Token(1, 2));
  EXPECT_EQ(group_1->entities.size(), 4u);

  const auto& group_2 =
      BirchCoralProvider::Get()->GetGroupById(base::Token(2, 3));
  EXPECT_EQ(group_2->entities.size(), 4u);

  auto* browser_list = BrowserList::GetInstance();

  auto* desks_controller = DesksController::Get();

  auto* new_desk = desks_controller->GetDeskAtIndex(1);

  // Move the browser window to another desk.
  ASSERT_EQ(8, browser_list->get(0)->tab_strip_model()->GetTabCount());
  auto* browser_window = browser_list->get(0)->window()->GetNativeWindow();
  desks_controller->MoveWindowFromActiveDeskTo(
      browser_window, new_desk, browser_window->GetRootWindow(),
      DesksMoveWindowFromActiveDeskSource::kSendToDesk);
  EXPECT_FALSE(desks_controller->BelongsToActiveDesk(browser_window));

  // Both groups are reduced to 1 entity.
  EXPECT_EQ(group_1->entities.size(), 1u);
  EXPECT_EQ(group_2->entities.size(), 1u);

  // Move the Files app to another desk.
  auto* file_window = browser_list->get(1)->window()->GetNativeWindow();
  ASSERT_EQ(file_window->GetTitle(), u"Files");
  desks_controller->MoveWindowFromActiveDeskTo(
      file_window, new_desk, file_window->GetRootWindow(),
      DesksMoveWindowFromActiveDeskSource::kSendToDesk);
  EXPECT_FALSE(desks_controller->BelongsToActiveDesk(file_window));

  // The first chip is removed.
  EXPECT_EQ(GetBirchChipsNum(), 1u);
}

// Tests that consecutively launching groups to new desks works.
IN_PROC_BROWSER_TEST_F(CoralBrowserTest, ConsecutiveLaunchGroups) {
  // Create two browsers with different tabs and urls.
  Profile* primary_profile = ProfileManager::GetPrimaryUserProfile();
  test::CreateAndShowBrowser(
      primary_profile,
      {GURL("https://youtube.com"), GURL("https://google.com"),
       GURL("https://docs.google.com"), GURL("https://drive.google.com")});
  test::CreateAndShowBrowser(
      primary_profile,
      {GURL("https://maps.google.com"), GURL("https://mail.google.com"),
       GURL("https://calendar.google.com"), GURL("https://meet.google.com")});

  // Create two fake coral groups which contains tabs that are selected from
  // each of the two browsers created above.
  std::vector<coral::mojom::GroupPtr> fake_groups;
  fake_groups.push_back(
      CreateTestGroup({{"Youtube", GURL("https://youtube.com")},
                       {"Docs", GURL("https://docs.google.com")},
                       {"Google Maps", GURL("https://maps.google.com")},
                       {"Calendar", GURL("https://calendar.google.com")}},
                      "Coral 1"));
  fake_groups.push_back(
      CreateTestGroup({{"Google", GURL("https://google.com")},
                       {"Drive", GURL("https://drive.google.com")},
                       {"Gmail", GURL("https://mail.google.com")},
                       {"Meet", GURL("https://meet.google.com")}},
                      "Coral 2"));
  OverrideTestResponse(std::move(fake_groups));

  // Set up a callback for a birch data fetch.
  base::RunLoop birch_data_fetch_waiter;
  Shell::Get()->birch_model()->SetDataFetchCallbackForTest(
      birch_data_fetch_waiter.QuitClosure());

  ToggleOverview();
  WaitForOverviewEntered();

  // Wait for fetch callback to complete.
  birch_data_fetch_waiter.Run();

  // There should be two chips on the bar.
  ASSERT_EQ(GetBirchChipsNum(), 2u);

  // Launch the first group.
  test::Click(GetFirstCoralButton());

  // We should have two desks and the new active desk is the second one.
  DesksController* desks_controller = DesksController::Get();
  EXPECT_EQ(desks_controller->desks().size(), 2u);
  EXPECT_EQ(desks_controller->GetActiveDeskIndex(), 1);
  EXPECT_EQ(
      desks_controller->GetDeskName(desks_controller->GetActiveDeskIndex()),
      u"Coral 1");

  // The active desk should have a browser window which has the tabs in the
  // first group.
  std::vector<GURL> tab_urls_on_active_desk = CollectTabURLsFromWindows(
      Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk));
  EXPECT_THAT(tab_urls_on_active_desk,
              testing::UnorderedElementsAre(
                  GURL("https://youtube.com"), GURL("https://docs.google.com"),
                  GURL("https://maps.google.com"),
                  GURL("https://calendar.google.com")));

  // Launch the second group.
  ASSERT_EQ(GetBirchChipsNum(), 1u);
  test::Click(GetFirstCoralButton());

  // We should have three desks and the new active desk is the third one.
  EXPECT_EQ(desks_controller->desks().size(), 3u);
  EXPECT_EQ(desks_controller->GetActiveDeskIndex(), 2);
  EXPECT_EQ(
      desks_controller->GetDeskName(desks_controller->GetActiveDeskIndex()),
      u"Coral 2");

  // The active desk should have a browser window which has the tabs in the
  // second group.
  tab_urls_on_active_desk = CollectTabURLsFromWindows(
      Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk));
  EXPECT_THAT(tab_urls_on_active_desk,
              testing::UnorderedElementsAre(GURL("https://google.com"),
                                            GURL("https://drive.google.com"),
                                            GURL("https://mail.google.com"),
                                            GURL("https://meet.google.com")));
}

}  // namespace ash