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

#include "ash/app_list/views/app_list_bubble_apps_page.h"
#include "ash/app_list/views/app_list_item_view.h"
#include "ash/app_list/views/apps_grid_view.h"
#include "ash/ash_element_identifiers.h"
#include "ash/constants/web_app_id_constants.h"
#include "ash/public/cpp/app_menu_constants.h"
#include "ash/public/cpp/shelf_item.h"
#include "ash/public/cpp/shelf_model.h"
#include "ash/root_window_controller.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_app_button.h"
#include "ash/shelf/shelf_view.h"
#include "ash/shell.h"
#include "ash/system/status_area_widget.h"
#include "ash/webui/settings/public/constants/routes.mojom.h"
#include "base/base64.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/types/expected.h"
#include "chrome/browser/ash/app_list/app_list_client_impl.h"
#include "chrome/browser/ash/app_restore/full_restore_app_launch_handler.h"
#include "chrome/browser/ash/login/test/guest_session_mixin.h"
#include "chrome/browser/ash/login/test/logged_in_user_mixin.h"
#include "chrome/browser/ash/system_web_apps/system_web_app_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_element_identifiers.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/browser/web_applications/preinstalled_web_apps/gemini.h"
#include "chrome/browser/web_applications/preinstalled_web_apps/gmail.h"
#include "chrome/browser/web_applications/preinstalled_web_apps/preinstalled_web_apps.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#include "chrome/test/interaction/interactive_browser_test.h"
#include "chromeos/ash/components/file_manager/app_id.h"
#include "chromeos/ash/components/report/utils/time_utils.h"
#include "chromeos/constants/chromeos_features.h"
#include "components/app_constants/constants.h"
#include "components/session_manager/session_manager_types.h"
#include "components/sync/base/command_line_switches.h"
#include "components/webapps/common/web_app_id.h"
#include "content/public/test/browser_test.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/widget/widget.h"

namespace {

// Aliases.
using ::testing::AllOf;
using ::testing::Bool;
using ::testing::Conditional;
using ::testing::Contains;
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Not;
using ::testing::Pointer;
using ::testing::PrintToStringParamName;
using ::testing::Property;
using ::testing::ValuesIn;
using ::testing::WithParamInterface;

// Elements --------------------------------------------------------------------

// Identifiers.
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kBrowserWebContentsElementId);
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kGeminiAppWebContentsElementId);
DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kSettingsAppWebContentsElementId);

// Names.
inline char kAppsGridViewElementName[] = "AppsGridView";
inline char kAppListBubbleAppsPageElementName[] = "AppListBubbleAppsPage";
inline char kChromeAppElementName[] = "ChromeApp";
inline char kFilesAppElementName[] = "FilesApp";
inline char kGeminiAppElementName[] = "GeminiApp";
inline char kGmailAppElementName[] = "GmailApp";
inline char kShowAppInfoMenuItemElementName[] = "ShowAppInfoMenuItem";

// Returns all `descendants` of the specified `parent` matching the given class.
template <typename ViewClass>
void FindDescendantsOfClass(views::View* parent,
                            std::vector<raw_ptr<ViewClass>>& descendants) {
  for (views::View* child : parent->children()) {
    if (views::IsViewClass<ViewClass>(child)) {
      descendants.emplace_back(views::AsViewClass<ViewClass>(child));
    }
    FindDescendantsOfClass(child, descendants);
  }
}

// Returns the index of `value` in the specified `range`.
template <typename Range, typename Value>
std::optional<size_t> FindIndex(const Range& range, const Value* value) {
  auto it = std::ranges::find(range, value);
  return it != range.end()
             ? std::make_optional<size_t>(std::distance(range.begin(), it))
             : std::make_optional<size_t>();
}

// Returns the `views::MenuItemView`s for the currently showing menu.
std::vector<raw_ptr<views::MenuItemView>> FindMenuItemViews() {
  if (auto* menu_controller = views::MenuController::GetActiveInstance()) {
    if (auto* menu_item_view = menu_controller->GetSelectedMenuItem()) {
      std::vector<raw_ptr<views::MenuItemView>> items;
      FindDescendantsOfClass(menu_item_view->parent(), items);
      return items;
    }
  }
  return {};
}

// Returns the `views::MenuItemView` for the currently showing menu associated
// with the specified command `id`.
views::MenuItemView* FindMenuItemViewForCommand(int id) {
  std::vector<raw_ptr<views::MenuItemView>> views = FindMenuItemViews();
  auto it = std::ranges::find(views, id, &views::MenuItemView::GetCommand);
  return it != views.end() ? *it : nullptr;
}

// Returns the `ash::ShelfItem` for the given web app `id`.
const ash::ShelfItem* FindShelfItemForWebApp(std::string_view id) {
  const ash::ShelfItems& items = ash::ShelfModel::Get()->items();
  auto it = std::ranges::find_if(
      items, [id](const ash::ShelfItem& item) { return item.id.app_id == id; });
  return it != items.end() ? &*it : nullptr;
}

// Returns if `view` is the `ash::AppListItemView` for the given web app `id`.
bool IsAppListItemViewForWebApp(std::string_view id, const views::View* view) {
  return views::IsViewClass<ash::AppListItemView>(view) &&
         views::AsViewClass<ash::AppListItemView>(view)->item()->id() == id;
}

// Returns if `browser` is the `Browser` for the given web app `id`.
bool IsBrowserForWebApp(const webapps::AppId& id, const Browser* browser) {
  return web_app::AppBrowserController::IsForWebApp(browser, id);
}

// Returns if the menu is currently showing.
bool IsMenuShowing() {
  auto* menu_controller = views::MenuController::GetActiveInstance();
  return menu_controller && menu_controller->GetSelectedMenuItem();
}

// Returns if `view` is the `ash::ShelfAppButton` for the given web app `id`.
bool IsShelfAppButtonForWebApp(
    std::reference_wrapper<const raw_ptr<ash::ShelfView>> shelf,
    std::string_view id,
    const views::View* view) {
  const ash::ShelfItem* const item = FindShelfItemForWebApp(id);
  return views::IsViewClass<ash::ShelfAppButton>(view) && item &&
         shelf.get()->GetShelfAppButton(item->id) == view;
}

// Waiters ---------------------------------------------------------------------

// Class which waits for `BrowserListObserver::OnBrowserSetLastActive()` events.
class OnBrowserSetLastActiveWaiter : public BrowserListObserver {
 public:
  void Wait() {
    CHECK(!run_loop_);

    base::ScopedObservation<BrowserList, BrowserListObserver> observer(this);
    observer.Observe(BrowserList::GetInstance());

    run_loop_ = std::make_unique<base::RunLoop>(
        base::RunLoop::Type::kNestableTasksAllowed);

    run_loop_->Run();
    run_loop_.reset();
  }

 private:
  // BrowserListObserver:
  void OnBrowserSetLastActive(Browser* browser) override {
    CHECK(run_loop_);
    run_loop_->Quit();
  }

  // Used to wait for `OnBrowserSetLastActive()` events.
  std::unique_ptr<base::RunLoop> run_loop_;
};

}  // namespace

// GeminiAppInteractiveUiTestBase ----------------------------------------------

// Base class for interactive UI tests of the Gemini app.
class GeminiAppInteractiveUiTestBase
    : public InteractiveBrowserTestT<MixinBasedInProcessBrowserTest> {
 public:
  GeminiAppInteractiveUiTestBase(
      std::optional<ash::LoggedInUserMixin::LogInType> login_type)
      : user_session_mixin_(CreateUserSessionMixin(login_type)),
        scoped_preinstall_url_allow_list_(
            web_app::SetPreinstallUrlAllowListForTesting(
                {{web_app::GetConfigForGemini(/*device_info=*/std::nullopt)
                      .install_url,
                  web_app::GetConfigForGmail().install_url}})) {
    // Enable Gemini app preinstallation.
    scoped_feature_list_.InitAndEnableFeature(
        chromeos::features::kGeminiAppPreinstall);

    // Use a consistent context for element tracking. Otherwise each widget has
    // its own context, greatly increasing the complexity of tracking
    // cross-widget CUJs as is the case in this test suite.
    views::ElementTrackerViews::SetContextOverrideCallback(
        base::BindRepeating([](views::Widget* widget) {
          return ui::ElementContext(ash::Shell::GetPrimaryRootWindow());
        }));
  }

  // Returns a builder for a step which assigns the last active browser to the
  // specified `ptr_ref`.
  [[nodiscard]] auto AssignLastActiveBrowser(
      std::reference_wrapper<Browser*> ptr_ref) {
    return Do([ptr_ref]() {
      ptr_ref.get() = BrowserList::GetInstance()->GetLastActive();
    });
  }

  // Returns a builder for a step which assigns the view associated with the
  // given `element_specifier` to the given `ptr`.
  template <typename ViewClass>
  [[nodiscard]] static auto AssignView(
      ElementSpecifier element_specifier,
      std::reference_wrapper<raw_ptr<ViewClass>> ptr) {
    return WithView(element_specifier,
                    [ptr](ViewClass* view) { ptr.get() = view; });
  }

  // Returns the expected launch URL for the Gemini app.
  GURL GetGeminiAppLaunchUrl() const {
    GURL::Replacements components;
    components.SetQueryStr(*gemini_app_install_info_->launch_query_params);
    return gemini_app_install_info_->start_url().ReplaceComponents(components);
  }

  // Returns the expected title for the Gemini app.
  const std::u16string& GetGeminiAppTitle() const {
    return gemini_app_install_info_->title;
  }

  // Returns a builder for a step which presses and releases the given `key`.
  [[nodiscard]] static auto PressAndReleaseKey(ui::KeyboardCode key) {
    return Do([key]() {
      ui::test::EventGenerator(ash::Shell::GetPrimaryRootWindow())
          .PressAndReleaseKeyAndModifierKeys(key, ui::EF_NONE);
    });
  }

  // Returns a builder for a step which resets the specified `ptr`.
  template <typename T>
  [[nodiscard]] static auto Reset(std::reference_wrapper<raw_ptr<T>> ptr) {
    return Do([ptr]() { ptr.get() = nullptr; });
  }

  // Returns a builder for a step which waits for a
  // `BrowserList::OnBrowserSetLastActive()` event.
  [[nodiscard]] auto WaitForOnBrowserSetLastActive() {
    return Do([]() { OnBrowserSetLastActiveWaiter().Wait(); });
  }

 protected:
  // InteractiveBrowserTestT<MixinBasedInProcessBrowserTest>:
  void SetUpDefaultCommandLine(base::CommandLine* command_line) override {
    InteractiveBrowserTestT<
        MixinBasedInProcessBrowserTest>::SetUpDefaultCommandLine(command_line);

    // Disable sync as it would otherwise block updating of shelf pins.
    command_line->AppendSwitch(syncer::kDisableSync);
  }

  void SetUpOnMainThread() override {
    // There's nothing to do if not logging in the user.
    if (!ShouldLogInUser()) {
      InteractiveBrowserTestT<
          MixinBasedInProcessBrowserTest>::SetUpOnMainThread();
      return;
    }

    // For logged-in user sessions, perform login prior to
    // `InteractiveBrowserTestT<>::SetUpOnMainThread()` so that the interactive
    // browser test base class will successfully set the context widget for the
    // test sequence. The context widget will be associated with the browser.
    if (std::holds_alternative<ash::LoggedInUserMixin>(user_session_mixin_)) {
      std::get<ash::LoggedInUserMixin>(user_session_mixin_).LogInUser();
    }

    InteractiveBrowserTestT<
        MixinBasedInProcessBrowserTest>::SetUpOnMainThread();

    // Wait for installation of both system and external web apps. The Gemini
    // app is an external app and this test suite will verify its adjacency to
    // system web apps.
    Profile* const profile = browser()->profile();
    ash::SystemWebAppManager::GetForTest(profile)
        ->InstallSystemAppsForTesting();
    web_app::test::WaitUntilWebAppProviderAndSubsystemsReady(
        web_app::WebAppProvider::GetForTest(profile));
    AppListClientImpl::GetInstance()->UpdateProfile();

    // Fetch `device_info` from echo.
    std::optional<base::Time> oobe_timestamp =
        ash::report::utils::GetFirstActiveWeek();
    ASSERT_TRUE(oobe_timestamp.has_value());
    web_app::DeviceInfo device_info;
    device_info.oobe_timestamp = oobe_timestamp.value();

    // Cache install info for the Gemini app.
    gemini_app_install_info_ =
        web_app::GetConfigForGemini(device_info).app_info_factory.Run();
  }

 private:
  // Creates the appropriate guest or logged-in user session mixin based on
  // the presence of `login_type`.
  std::variant<ash::GuestSessionMixin, ash::LoggedInUserMixin>
  CreateUserSessionMixin(
      std::optional<ash::LoggedInUserMixin::LogInType> login_type) {
    if (!login_type) {
      return std::variant<ash::GuestSessionMixin, ash::LoggedInUserMixin>(
          std::in_place_type_t<ash::GuestSessionMixin>(), &mixin_host_);
    }

    return std::variant<ash::GuestSessionMixin, ash::LoggedInUserMixin>(
        std::in_place_type_t<ash::LoggedInUserMixin>(), &mixin_host_,
        /*test_base=*/this, embedded_test_server(), login_type.value());
  }

  // Returns whether the user should be logged in as part of test setup.
  virtual bool ShouldLogInUser() const { return true; }

  // Used to manage either a guest or logged-in user session based on test
  // parameterization.
  std::variant<ash::GuestSessionMixin, ash::LoggedInUserMixin>
      user_session_mixin_;

  // Used to enable the Gemini app preinstallation.
  base::test::ScopedFeatureList scoped_feature_list_;

  // Used to retrieve expected title/URL for the Gemini app.
  std::unique_ptr<web_app::WebAppInstallInfo> gemini_app_install_info_;

  // Allowlists the specific apps to be preinstalled.
  web_app::ScopedPreinstallUrlAllowList scoped_preinstall_url_allow_list_;
};

// GeminiAppInteractiveUiTest --------------------------------------------------

// Base class for interactive UI tests of the Gemini app, parameterized by
// whether the logged-in user is new or existing. Tests include a PRE_ session,
// where user state is initialized, followed by a subsequent session containing
// test logic. Chrome is restarted between sessions.
class GeminiAppInteractiveUiTest
    : public GeminiAppInteractiveUiTestBase,
      public WithParamInterface</*existing_user=*/bool> {
 public:
  GeminiAppInteractiveUiTest()
      : GeminiAppInteractiveUiTestBase(
            ash::LoggedInUserMixin::LogInType::kConsumer) {
    // Disable the Gemini app during the PRE_ session so that the subsequent
    // session containing test logic is when the app preinstallation occurs.
    if (IsPreSession()) {
      scoped_feature_list_.InitAndDisableFeature(
          chromeos::features::kGeminiAppPreinstall);
    }
  }

 protected:
  // GeminiAppInteractiveUiTestBase:
  void SetUpOnMainThread() override {
    GeminiAppInteractiveUiTestBase::SetUpOnMainThread();

    // Check that session state is as expected.
    const auto* session_controller = ash::Shell::Get()->session_controller();
    EXPECT_THAT(session_controller->GetSessionState(),
                Conditional(ShouldLogInUser(),
                            Eq(session_manager::SessionState::ACTIVE),
                            Eq(session_manager::SessionState::LOGIN_PRIMARY)));

    // Check that login state is as expected.
    EXPECT_THAT(
        session_controller->IsUserFirstLogin(),
        Conditional(IsPreSession(), IsExistingUser(), Not(IsExistingUser())));
  }

  bool ShouldLogInUser() const override {
    // Existing users should be logged in for both the PRE_ session and the
    // subsequent session containing test logic. New users should only be logged
    // in for the subsequent session.
    return IsExistingUser() || !IsPreSession();
  }

  // Returns whether the logged-in user is existing given test parameterization.
  bool IsExistingUser() const { return GetParam(); }

  // Returns whether the current session is the PRE_ session. The PRE_ session
  // is the session before the subsequent session containing test logic.
  bool IsPreSession() const {
    return base::StartsWith(
        testing::UnitTest::GetInstance()->current_test_info()->name(), "PRE_");
  }

 private:
  // Used to disable Gemini app preinstallation for the PRE_ session.
  base::test::ScopedFeatureList scoped_feature_list_;
};

INSTANTIATE_TEST_SUITE_P(
    All,
    GeminiAppInteractiveUiTest,
    /*existing_user=*/Bool(),
    [](const testing::TestParamInfo</*existing_user=*/bool>& info) {
      return info.param ? "ExistingUser" : "NewUser";
    });

// Tests -----------------------------------------------------------------------

// Initializes user state and restarts Chrome before `LaunchFromAppList`.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, PRE_LaunchFromAppList) {}

// Verifies that the Gemini app can be launched from the app list.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, LaunchFromAppList) {
  // Views.
  raw_ptr<ash::AppsGridView> apps_grid_view = nullptr;
  raw_ptr<ash::AppListItemView> files_app = nullptr;
  raw_ptr<ash::AppListItemView> gemini_app = nullptr;
  raw_ptr<ash::AppListItemView> gmail_app = nullptr;

  // Test.
  RunTestSequence(
      // Launch app list.
      DoDefaultAction(ash::kHomeButtonElementId),
      WaitForShow(ash::kAppListBubbleViewElementId),

      // Find apps page.
      NameDescendantViewByType<ash::AppListBubbleAppsPage>(
          ash::kAppListBubbleViewElementId, kAppListBubbleAppsPageElementName),

      // Find apps grid.
      NameDescendantViewByType<ash::AppsGridView>(
          kAppListBubbleAppsPageElementName, kAppsGridViewElementName),

      // Cache apps grid.
      AssignView(kAppsGridViewElementName, std::ref(apps_grid_view)),

      // Find Gemini app.
      NameDescendantView(
          kAppsGridViewElementName, kGeminiAppElementName,
          base::BindRepeating(&IsAppListItemViewForWebApp, ash::kGeminiAppId)),

      // Cache Gemini app.
      AssignView(kGeminiAppElementName, std::ref(gemini_app)),

      // Find Files app.
      NameDescendantView(
          kAppsGridViewElementName, kFilesAppElementName,
          base::BindRepeating(&IsAppListItemViewForWebApp,
                              file_manager::kFileManagerSwaAppId)),

      // Cache Files app.
      AssignView(kFilesAppElementName, std::ref(files_app)),

      // Find Gmail app.
      NameDescendantView(
          kAppsGridViewElementName, kGmailAppElementName,
          base::BindRepeating(&IsAppListItemViewForWebApp, ash::kGmailAppId)),

      // Cache Gmail app.
      AssignView(kGmailAppElementName, std::ref(gmail_app)),

      // Check Gemini app title.
      CheckView(
          kGeminiAppElementName,
          [](ash::AppListItemView* item) { return item->title(); },
          Property(&views::Label::GetText, Eq(GetGeminiAppTitle()))),

      // Check Gemini app position.
      Check([&]() {
        std::vector<raw_ptr<ash::AppListItemView>> apps;
        FindDescendantsOfClass(apps_grid_view, apps);
        const auto gemini_app_index = FindIndex(apps, gemini_app.get());
        if (IsExistingUser()) {
          return gemini_app_index == 0u;
        }
        const auto files_app_index = FindIndex(apps, files_app.get());
        const auto gmail_app_index = FindIndex(apps, gmail_app.get());
        return (files_app_index == gemini_app_index.value() - 1u) &&
               (gmail_app_index == gemini_app_index.value() + 1u);
      }),

      // Reset cached pointers which might dangle when the app list closes.
      Reset(std::ref(apps_grid_view)), Reset(std::ref(gemini_app)),
      Reset(std::ref(files_app)), Reset(std::ref(gmail_app)),

      // Launch Gemini app.
      InstrumentNextTab(kGeminiAppWebContentsElementId, AnyBrowser()),
      DoDefaultAction(kGeminiAppElementName),

      // Check Gemini app browser.
      CheckElement(
          kGeminiAppWebContentsElementId,
          base::BindOnce(&AsInstrumentedWebContents)
              .Then(
                  base::BindOnce(&WebContentsInteractionTestUtil::web_contents))
              .Then(base::BindOnce(&chrome::FindBrowserWithTab))
              .Then(base::BindOnce(&IsBrowserForWebApp, ash::kGeminiAppId))),

      // Check Gemini app launch URL.
      WaitForWebContentsReady(kGeminiAppWebContentsElementId,
                              GetGeminiAppLaunchUrl()));
}

// Initializes user state and restarts Chrome before `LaunchFromShelf`.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, PRE_LaunchFromShelf) {}

// Verifies that the Gemini app can be launched from the shelf.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, LaunchFromShelf) {
  // Views.
  raw_ptr<ash::ShelfAppButton> chrome_app = nullptr;
  raw_ptr<ash::ShelfAppButton> gemini_app = nullptr;
  raw_ptr<ash::ShelfView> shelf = nullptr;

  // Test.
  RunTestSequence(
      // Cache shelf.
      AssignView(ash::kShelfViewElementId, std::ref(shelf)),

      // Find Gemini app.
      NameDescendantView(
          ash::kShelfViewElementId, kGeminiAppElementName,
          base::BindRepeating(&IsShelfAppButtonForWebApp, std::cref(shelf),
                              ash::kGeminiAppId)),

      // Cache Gemini app.
      AssignView(kGeminiAppElementName, std::ref(gemini_app)),

      // Find Chrome app.
      NameDescendantView(
          ash::kShelfViewElementId, kChromeAppElementName,
          base::BindRepeating(&IsShelfAppButtonForWebApp, std::cref(shelf),
                              app_constants::kChromeAppId)),

      // Cache Chrome app.
      AssignView(kChromeAppElementName, std::ref(chrome_app)),

      // Check Gemini app position.
      Check(
          [&]() {
            std::vector<raw_ptr<ash::ShelfAppButton>> apps;
            FindDescendantsOfClass(shelf, apps);
            const auto gemini_app_index = FindIndex(apps, gemini_app.get());
            if (IsExistingUser()) {
              return gemini_app_index == 0u;
            }
            const auto chrome_app_index = FindIndex(apps, chrome_app.get());
            return chrome_app_index == 0u && gemini_app_index == 1u;
          },
          "Gemini app is positioned correctly"),

      // Launch Gemini app.
      InstrumentNextTab(kGeminiAppWebContentsElementId, AnyBrowser()),
      DoDefaultAction(kGeminiAppElementName),

      // Check Gemini app browser.
      CheckElement(
          kGeminiAppWebContentsElementId,
          base::BindOnce(&AsInstrumentedWebContents)
              .Then(
                  base::BindOnce(&WebContentsInteractionTestUtil::web_contents))
              .Then(base::BindOnce(&chrome::FindBrowserWithTab))
              .Then(base::BindOnce(&IsBrowserForWebApp, ash::kGeminiAppId))),

      // Check Gemini app launch URL.
      WaitForWebContentsReady(kGeminiAppWebContentsElementId,
                              GetGeminiAppLaunchUrl()));
}

// Initializes user state and restarts Chrome before
// `PreferredAppForSupportedLinks`.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest,
                       PRE_PreferredAppForSupportedLinks) {}

// Verifies that the Gemini app is the preferred app for supported links.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest,
                       PreferredAppForSupportedLinks) {
  // Browser.
  Browser* gemini_app_browser = nullptr;

  // Test.
  RunTestSequence(
      // Navigate browser to page with supported link.
      AddInstrumentedTab(
          kBrowserWebContentsElementId,
          GURL(base::StrCat({"data:text/html;base64,",
                             base::Base64Encode(base::ReplaceStringPlaceholders(
                                 R"(<DOCTYPE html>
                                    <html>
                                      <head>
                                        <style>
                                          html, body, a {
                                            display: block;
                                            height: 100%;
                                            width: 100%;
                                          }
                                        </style>
                                      </head>
                                      <body>
                                        <a href="$1" target="_blank"></a>
                                      </body>
                                    </html>)",
                                 /*subst=*/{GetGeminiAppLaunchUrl().spec()},
                                 /*offsets=*/nullptr))}))),

      // Launch Gemini app via supported link.
      MoveMouseTo(kBrowserViewElementId), ClickMouse(),

      // Instrument Gemini app browser.
      WaitForOnBrowserSetLastActive(),
      AssignLastActiveBrowser(std::ref(gemini_app_browser)),
      InstrumentTab(kGeminiAppWebContentsElementId,
                    /*tab_index=*/std::nullopt, std::ref(gemini_app_browser)),

      // Check Gemini app browser.
      CheckElement(
          kGeminiAppWebContentsElementId,
          base::BindOnce(&AsInstrumentedWebContents)
              .Then(
                  base::BindOnce(&WebContentsInteractionTestUtil::web_contents))
              .Then(base::BindOnce(&chrome::FindBrowserWithTab))
              .Then(base::BindOnce(&IsBrowserForWebApp, ash::kGeminiAppId))),

      // Check Gemini app launch URL.
      WaitForWebContentsReady(kGeminiAppWebContentsElementId,
                              GetGeminiAppLaunchUrl()));
}

// Initializes user state and restarts Chrome before `UninstallFromAppList`.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, PRE_UninstallFromAppList) {}

// Verifies that the Gemini app cannot be uninstalled from the app list.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, UninstallFromAppList) {
  RunTestSequence(
      // Launch app list.
      DoDefaultAction(ash::kHomeButtonElementId),
      WaitForShow(ash::kAppListBubbleViewElementId),

      // Find apps page.
      NameDescendantViewByType<ash::AppListBubbleAppsPage>(
          ash::kAppListBubbleViewElementId, kAppListBubbleAppsPageElementName),

      // Find apps grid.
      NameDescendantViewByType<ash::AppsGridView>(
          kAppListBubbleAppsPageElementName, kAppsGridViewElementName),

      // Find Gemini app.
      NameDescendantView(
          kAppsGridViewElementName, kGeminiAppElementName,
          base::BindRepeating(&IsAppListItemViewForWebApp, ash::kGeminiAppId)),

      // Open menu.
      MoveMouseTo(kGeminiAppElementName), ClickMouse(ui_controls::RIGHT),
      Check(&IsMenuShowing),

      // Activate menu.
      PressAndReleaseKey(ui::VKEY_DOWN),

      // Check Gemini app cannot be uninstalled.
      CheckResult(
          &FindMenuItemViews,
          AllOf(Not(IsEmpty()),
                Not(Contains(Pointer(Property(&views::MenuItemView::GetCommand,
                                              Eq(ash::UNINSTALL))))))));
}

// Initializes user state and restarts Chrome before `UninstallFromSettings`.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, PRE_UninstallFromSettings) {}

// Verifies that the Gemini app cannot be uninstalled from the Settings app.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, UninstallFromSettings) {
  // Views.
  raw_ptr<ash::ShelfView> shelf = nullptr;

  // Queries.
  auto get_settings_app_subpage_query = [](std::string_view query,
                                           bool shadow_dom = false) {
    constexpr char kOsSettingsAppsPage[] = "os-settings-apps-page";
    constexpr char kOsSettingsMain[] = "os-settings-main";
    constexpr char kOsSettingsMainPageContainer[] = "#mainPageContainer";
    constexpr char kOsSettingsSubpage[] = "os-settings-subpage";
    constexpr char kOsSettingsUi[] = "os-settings-ui";

    const DeepQuery deep_query({kOsSettingsUi, kOsSettingsMain,
                                kOsSettingsMainPageContainer,
                                kOsSettingsAppsPage});

    return shadow_dom
               ? (deep_query + kOsSettingsSubpage) + std::string(query)
               : (deep_query + base::StrCat({kOsSettingsSubpage, " ", query}));
  };

  // Test.
  RunTestSequence(
      // Cache shelf.
      AssignView(ash::kShelfViewElementId, std::ref(shelf)),

      // Find Gemini app.
      NameDescendantView(
          ash::kShelfViewElementId, kGeminiAppElementName,
          base::BindRepeating(&IsShelfAppButtonForWebApp, std::cref(shelf),
                              ash::kGeminiAppId)),

      // Open menu.
      MoveMouseTo(kGeminiAppElementName), ClickMouse(ui_controls::RIGHT),
      Check(&IsMenuShowing),

      // Activate menu.
      PressAndReleaseKey(ui::VKEY_DOWN),

      // Find menu item.
      NameView(kShowAppInfoMenuItemElementName,
               base::BindOnce(FindMenuItemViewForCommand, ash::SHOW_APP_INFO)
                   .Then(base::BindOnce<views::View*(views::View*)>(
                       views::AsViewClass<views::View>))),

      // Launch Settings app.
      InstrumentNextTab(kSettingsAppWebContentsElementId, AnyBrowser()),
      DoDefaultAction(kShowAppInfoMenuItemElementName),

      // Check Settings app browser.
      CheckElement(kSettingsAppWebContentsElementId,
                   base::BindOnce(&AsInstrumentedWebContents)
                       .Then(base::BindOnce(
                           &WebContentsInteractionTestUtil::web_contents))
                       .Then(base::BindOnce(&chrome::FindBrowserWithTab))
                       .Then(base::BindOnce(&IsBrowserForWebApp,
                                            ash::kOsSettingsAppId))),

      // Check Settings app launch URL.
      WaitForWebContentsReady(
          kSettingsAppWebContentsElementId,
          chrome::GetOSSettingsUrl(
              base::StrCat({chromeos::settings::mojom::kAppDetailsSubpagePath,
                            "?id=", ash::kGeminiAppId}))),

      // Check Gemini app title.
      CheckJsResultAt(
          kSettingsAppWebContentsElementId,
          get_settings_app_subpage_query("#subpageTitle", /*shadow_dom=*/true),
          base::StrCat({"subpageTitle => subpageTitle.innerText === '",
                        base::UTF16ToUTF8(GetGeminiAppTitle()), "'"})),

      // Check Gemini app cannot be uninstalled.
      CheckJsResultAt(
          kSettingsAppWebContentsElementId,
          get_settings_app_subpage_query("app-management-uninstall-button"),
          "appManagementUninstallButton => "
          "!appManagementUninstallButton.shadowRoot.querySelector('*[role="
          "button]')"));
}

// Initializes user state and restarts Chrome before `UninstallFromShelf`.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, PRE_UninstallFromShelf) {}

// Verifies that the Gemini app cannot be uninstalled from the shelf.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiTest, UninstallFromShelf) {
  // Views.
  raw_ptr<ash::ShelfView> shelf = nullptr;

  // Test.
  RunTestSequence(
      // Cache shelf.
      AssignView(ash::kShelfViewElementId, std::ref(shelf)),

      // Find Gemini app.
      NameDescendantView(
          ash::kShelfViewElementId, kGeminiAppElementName,
          base::BindRepeating(&IsShelfAppButtonForWebApp, std::cref(shelf),
                              ash::kGeminiAppId)),

      // Open menu.
      MoveMouseTo(kGeminiAppElementName), ClickMouse(ui_controls::RIGHT),
      Check(&IsMenuShowing),

      // Activate menu.
      PressAndReleaseKey(ui::VKEY_DOWN),

      // Check Gemini app cannot be uninstalled.
      CheckResult(
          &FindMenuItemViews,
          AllOf(Not(IsEmpty()),
                Not(Contains(Pointer(Property(&views::MenuItemView::GetCommand,
                                              Eq(ash::UNINSTALL))))))));
}

// GeminiAppInteractiveUiIneligibilityTest -------------------------------------

// Reasons why the user may be ineligible for Gemini app preinstallation.
enum class IneligibilityReason {
  kMinValue = 0,
  kFeatureFlagDisabled = kMinValue,
  kUserManaged,
  kUserTypeChild,
  kUserTypeGuest,
  kMaxValue = kUserTypeGuest,
};

#define INELIGIBILITY_REASON_CASE(reason) \
  case IneligibilityReason::reason:       \
    return os << std::string(#reason)

inline std::ostream& operator<<(std::ostream& os, IneligibilityReason reason) {
  switch (reason) {
    INELIGIBILITY_REASON_CASE(kFeatureFlagDisabled);
    INELIGIBILITY_REASON_CASE(kUserManaged);
    INELIGIBILITY_REASON_CASE(kUserTypeChild);
    INELIGIBILITY_REASON_CASE(kUserTypeGuest);
  }
}

// Base class for interactive UI tests of Gemini app ineligibility.
class GeminiAppInteractiveUiIneligibilityTest
    : public GeminiAppInteractiveUiTestBase,
      public WithParamInterface<IneligibilityReason> {
 public:
  GeminiAppInteractiveUiIneligibilityTest()
      : GeminiAppInteractiveUiTestBase(GetLoginType()) {
    scoped_feature_list_.InitWithFeatureState(
        chromeos::features::kGeminiAppPreinstall, IsFeatureFlagEnabled());
  }

 private:
  // GeminiAppInteractiveUiTestBase:
  void SetUpOnMainThread() override {
    // Web app preinstallation times out for child user types due to failure to
    // install some default web apps. Since this test suite only cares about the
    // preinstallation of the Gemini app, circumvent timeouts by disabling other
    // default web apps.
    std::unique_ptr<web_app::ScopedTestingPreinstalledAppData> app_data;
    if (GetLoginType() == ash::LoggedInUserMixin::LogInType::kChild) {
      app_data = std::make_unique<web_app::ScopedTestingPreinstalledAppData>();
      app_data->apps.emplace_back(
          web_app::GetConfigForGemini(/*device_info=*/std::nullopt));
    }

    GeminiAppInteractiveUiTestBase::SetUpOnMainThread();
  }

  // Returns the login type for the user given test parameterization.
  std::optional<ash::LoggedInUserMixin::LogInType> GetLoginType() const {
    switch (GetParam()) {
      case IneligibilityReason::kUserTypeChild:
        return ash::LoggedInUserMixin::LogInType::kChild;
      case IneligibilityReason::kUserTypeGuest:
        return std::nullopt;
      case IneligibilityReason::kUserManaged:
        return ash::LoggedInUserMixin::LogInType::kManaged;
      default:
        return ash::LoggedInUserMixin::LogInType::kConsumer;
    }
  }

  // Returns whether the feature flag is enabled given test parameterization.
  bool IsFeatureFlagEnabled() const {
    return GetParam() != IneligibilityReason::kFeatureFlagDisabled;
  }

  // Used to enable/disable the Gemini app preinstallation based on test
  // parameterization.
  base::test::ScopedFeatureList scoped_feature_list_;
};

INSTANTIATE_TEST_SUITE_P(
    All,
    GeminiAppInteractiveUiIneligibilityTest,
    ValuesIn(([]() {
      std::vector<IneligibilityReason> reasons(
          static_cast<int>(IneligibilityReason::kMaxValue) -
          static_cast<int>(IneligibilityReason::kMinValue) + 1);
      std::ranges::generate(
          reasons.begin(), reasons.end(),
          [i = static_cast<int>(IneligibilityReason::kMinValue)]() mutable {
            return static_cast<IneligibilityReason>(i++);
          });
      return reasons;
    })()),
    PrintToStringParamName());

// Tests -----------------------------------------------------------------------

// Verifies the Gemini app is absent from the app list for ineligible users.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiIneligibilityTest,
                       AbsentFromAppList) {
  RunTestSequence(
      // Launch app list.
      DoDefaultAction(ash::kHomeButtonElementId),
      WaitForShow(ash::kAppListBubbleViewElementId),

      // Find apps page.
      NameDescendantViewByType<ash::AppListBubbleAppsPage>(
          ash::kAppListBubbleViewElementId, kAppListBubbleAppsPageElementName),

      // Find apps grid.
      NameDescendantViewByType<ash::AppsGridView>(
          kAppListBubbleAppsPageElementName, kAppsGridViewElementName),

      // Check Gemini app absent.
      CheckView(
          kAppsGridViewElementName, [](ash::AppsGridView* apps_grid_view) {
            std::vector<raw_ptr<ash::AppListItemView>> apps;
            FindDescendantsOfClass(apps_grid_view, apps);
            return apps.size() &&
                   std::ranges::none_of(apps, [&](ash::AppListItemView* app) {
                     return IsAppListItemViewForWebApp(ash::kGeminiAppId, app);
                   });
          }));
}

// Verifies the Gemini app is absent from the shelf for ineligible users.
IN_PROC_BROWSER_TEST_P(GeminiAppInteractiveUiIneligibilityTest,
                       AbsentFromShelf) {
  RunTestSequence(
      // Check Gemini app absent.
      CheckView(ash::kShelfViewElementId, [](ash::ShelfView* shelf) {
        std::vector<raw_ptr<ash::ShelfAppButton>> apps;
        FindDescendantsOfClass(shelf, apps);
        return apps.size() &&
               std::ranges::none_of(
                   apps, [&, shelf = raw_ptr(shelf)](ash::ShelfAppButton* app) {
                     return IsShelfAppButtonForWebApp(std::cref(shelf),
                                                      ash::kGeminiAppId, app);
                   });
      }));
}