File: glic_ui_interactive_uitest.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 (611 lines) | stat: -rw-r--r-- 24,887 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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sstream>

#include "base/scoped_observation.h"
#include "base/strings/stringprintf.h"
#include "base/strings/to_string.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "chrome/browser/glic/host/glic.mojom-shared.h"
#include "chrome/browser/glic/host/glic_ui.h"
#include "chrome/browser/glic/test_support/interactive_glic_test.h"
#include "chrome/browser/glic/test_support/interactive_test_util.h"
#include "chrome/browser/glic/widget/glic_window_controller.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_test_util.h"
#include "chrome/browser/ui/browser_element_identifiers.h"
#include "chrome/common/chrome_features.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/state_observer.h"

namespace glic {

namespace {

using mojom::WebUiState;

class GlicUiStateHistoryObserver
    : public ui::test::StateObserver<std::vector<WebUiState>>,
      public Host::Observer {
 public:
  explicit GlicUiStateHistoryObserver(Host* host) : host_(*host) {
    states_.push_back(host->GetPrimaryWebUiState());
    host->AddObserver(this);
  }

  ~GlicUiStateHistoryObserver() override { host_->RemoveObserver(this); }

  ValueType GetStateObserverInitialState() const override { return states_; }

 private:
  void WebUiStateChanged(WebUiState state) override {
    states_.push_back(state);
    OnStateObserverStateChanged(states_);
  }

  const raw_ref<Host> host_;
  ValueType states_;
};

DEFINE_LOCAL_STATE_IDENTIFIER_VALUE(GlicUiStateHistoryObserver,
                                    kGlicUiStateHistory);

class ContextAccessIndicatorObserver
    : public ui::test::StateObserver<std::vector<bool>> {
 public:
  explicit ContextAccessIndicatorObserver(GlicKeyedService* service) {
    scoped_subscription_ =
        service->AddContextAccessIndicatorStatusChangedCallback(
            base::BindRepeating(&ContextAccessIndicatorObserver::
                                    ContextAccessIndicatorStatusChanged,
                                base::Unretained(this)));
  }

  ~ContextAccessIndicatorObserver() override = default;

  ValueType GetStateObserverInitialState() const override { return states_; }

 private:
  void ContextAccessIndicatorStatusChanged(bool status) {
    states_.push_back(status);
    OnStateObserverStateChanged(states_);
  }

  base::CallbackListSubscription scoped_subscription_;
  ValueType states_;
};

DEFINE_LOCAL_STATE_IDENTIFIER_VALUE(ContextAccessIndicatorObserver,
                                    kGlicContextAccessIndicatorHistory);

// Specifies artificial parameters for how network and loading should behave for
// tests in this file.
struct TestParams {
  TestParams() = default;
  explicit TestParams(bool connected) : start_connected(connected) {}
  TestParams(base::TimeDelta time_before_loading_page_,
             base::TimeDelta min_loading_page_duration_,
             base::TimeDelta max_loading_page_duration_,
             base::TimeDelta loading_delay_)
      : time_before_loading_page(time_before_loading_page_),
        min_loading_page_duration(min_loading_page_duration_),
        max_loading_page_duration(max_loading_page_duration_),
        loading_delay(loading_delay_) {}
  ~TestParams() = default;

  // Time before loading page shows.
  std::optional<base::TimeDelta> time_before_loading_page;
  // Minimum time loading page shows.
  std::optional<base::TimeDelta> min_loading_page_duration;
  // Maximum time loading page shows before error.
  std::optional<base::TimeDelta> max_loading_page_duration;
  // Time to load the glic UI.
  std::optional<base::TimeDelta> loading_delay;
  // Whether the page believes it has network at startup.
  bool start_connected = true;

  base::FieldTrialParams GetFieldTrialParams() const {
    base::FieldTrialParams params;
    if (time_before_loading_page) {
      params.emplace(
          features::kGlicPreLoadingTimeMs.name,
          base::StringPrintf("%u", time_before_loading_page->InMilliseconds()));
    }
    if (min_loading_page_duration) {
      params.emplace(features::kGlicMinLoadingTimeMs.name,
                     base::StringPrintf(
                         "%u", min_loading_page_duration->InMilliseconds()));
    }
    if (max_loading_page_duration) {
      params.emplace(features::kGlicMaxLoadingTimeMs.name,
                     base::StringPrintf(
                         "%u", max_loading_page_duration->InMilliseconds()));
    }
    return params;
  }
};

const ui::Accelerator escape_key(ui::VKEY_ESCAPE, ui::EF_NONE);

}  // namespace

// Base class that sets up network connection mode and timeouts based on
// `TestParams` (see above).
class GlicUiInteractiveUiTestBase : public test::InteractiveGlicTest {
 public:
  explicit GlicUiInteractiveUiTestBase(const TestParams& params)
      : InteractiveGlicTestT(params.GetFieldTrialParams()) {
    if (!params.start_connected) {
      GlicUI::simulate_no_connection_for_testing();
    }
    if (params.loading_delay) {
      std::ostringstream oss;
      oss << params.loading_delay->InMilliseconds();
      add_mock_glic_query_param("delay_ms", oss.str());
    }
  }
  ~GlicUiInteractiveUiTestBase() override = default;

  auto CheckElementVisible(const DeepQuery& where, bool visible) {
    MultiStep steps;
    if (visible) {
      steps =
          InAnyContext(WaitForElementVisible(test::kGlicHostElementId, where));
    }
    steps += InAnyContext(CheckJsResultAt(test::kGlicHostElementId, where,
                                          "(el) => el.hidden",
                                          testing::Ne(visible)));
    AddDescriptionPrefix(steps, "CheckElementVisible");
    return steps;
  }

  auto CheckMockElementChecked(const DeepQuery& where, bool checked) {
    MultiStep steps = Steps(InAnyContext(WaitForElementVisible(
                                test::kGlicContentsElementId, {"body"})),
                            InAnyContext(CheckJsResultAt(
                                test::kGlicContentsElementId, where,
                                "(el) => el.checked", testing::Eq(checked))));
    AddDescriptionPrefix(steps, "CheckElementChecked");
    return steps;
  }

  auto CheckEscapeKeyDismisses(const DeepQuery& panel) {
    return InAnyContext(
        WaitForShow(test::kGlicHostElementId), CheckElementVisible(panel, true),
        InSameContext(SendAccelerator(test::kGlicHostElementId, escape_key)
                          .SetMustRemainVisible(false),
                      WaitForHide(kGlicViewElementId)),
        CheckControllerHasWidget(false));
  }

  auto ChangeConnectionState(bool online) {
    return ExecuteJs(test::kGlicHostElementId,
                     base::StringPrintf(R"(
        function () {
          window.appController.simulateNoConnection = %s;
          window.appController.%s();
        }
      )",
                                        base::ToString(!online),
                                        online ? "online" : "offline"));
  }

  static auto CurrentStateMatcher(testing::Matcher<WebUiState> target) {
    return testing::AllOf(
        testing::Not(testing::IsEmpty()),
        testing::Property(&GlicUiStateHistoryObserver::ValueType::back,
                          target));
  }

  static auto IsCurrently(WebUiState state) {
    return CurrentStateMatcher(state);
  }

  static auto IsNotCurrently(WebUiState state) {
    return CurrentStateMatcher(testing::Ne(state));
  }

  static auto IsContextAccessIndicatorCurrently(bool showing) {
    return testing::AllOf(
        testing::Not(testing::IsEmpty()),
        testing::Property(&ContextAccessIndicatorObserver::ValueType::back,
                          showing));
  }

  const DeepQuery kOfflinePanel = {"#offlinePanel"};
  const DeepQuery kLoadingPanel = {"#loadingPanel"};
  const DeepQuery kErrorPanel = {"#errorPanel"};
  const DeepQuery kContentsPanel = {"#guestPanel"};
};

class GlicUiInteractiveTest : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiInteractiveTest()
      : GlicUiInteractiveUiTestBase(TestParams(/*connected=*/true)) {}
  ~GlicUiInteractiveTest() override = default;
};

IN_PROC_BROWSER_TEST_F(GlicUiInteractiveTest, OpenGlicWindow) {
  base::HistogramTester histogram_tester;
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kDetached, GlicInstrumentMode::kHostOnly));
  // The browser is active when opening the Glic window.
  histogram_tester.ExpectUniqueSample("Glic.Session.Open.BrowserActiveState",
                                      0 /*kBrowserActive*/, 1);
}

// Tests the network being connected at startup (as normal).
class GlicUiConnectedUiTest : public GlicUiInteractiveUiTestBase,
                              public testing::WithParamInterface<bool> {
 public:
  GlicUiConnectedUiTest()
      : GlicUiInteractiveUiTestBase(TestParams(/*connected=*/true)) {
    if (IsDetachedOnlyModeEnabled()) {
      feature_list_.InitAndEnableFeature(features::kGlicDetached);
    } else {
      feature_list_.InitAndDisableFeature(features::kGlicDetached);
    }
  }
  ~GlicUiConnectedUiTest() override = default;

  bool IsDetachedOnlyModeEnabled() const { return GetParam(); }

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

INSTANTIATE_TEST_SUITE_P(All, GlicUiConnectedUiTest, testing::Bool());

IN_PROC_BROWSER_TEST_P(GlicUiConnectedUiTest, DisconnectedPanelHidden) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsNotCurrently(WebUiState::kOffline)),
      CheckElementVisible(kOfflinePanel, false));
}

IN_PROC_BROWSER_TEST_P(GlicUiConnectedUiTest,
                       DoesNotHidePanelWhenReadyButOffline) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kReady)),
      ChangeConnectionState(false), CheckElementVisible(kContentsPanel, true),
      CheckState(kGlicUiStateHistory, IsCurrently(WebUiState::kReady)));
}

IN_PROC_BROWSER_TEST_P(GlicUiConnectedUiTest, CanAttachWithBrowserWindow) {
  if (IsDetachedOnlyModeEnabled()) {
    GTEST_SKIP();
  }
  RunTestSequence(OpenGlicWindow(GlicWindowMode::kDetached,
                                 GlicInstrumentMode::kHostAndContents),
                  CheckMockElementChecked({"#canAttachCheckbox"}, true));
}

// DISABLED: Not reliable yet.
IN_PROC_BROWSER_TEST_P(GlicUiConnectedUiTest,
                       DISABLED_CanNotAttachWithMinimizedBrowser) {
  RunTestSequence(
      OpenGlicWindow(GlicWindowMode::kDetached,
                     GlicInstrumentMode::kHostAndContents),
      CheckMockElementChecked({"#canAttachCheckbox"}, true),
      Do([&]() { browser()->GetBrowserView().Minimize(); }),
      // TODO(harringtond): Ideally this would wait until not checked, rather
      // than check only once. There's no guarantee the web client
      // has been updated before this code runs. Currently, this
      // test works, though it's a risk for flakiness.
      CheckMockElementChecked({"#canAttachCheckbox"}, false));
}

IN_PROC_BROWSER_TEST_P(GlicUiConnectedUiTest,
                       DoesNotNavigateToUnsupportedOrigin) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached,
                     GlicInstrumentMode::kHostAndContents),
      WaitForElementVisible(test::kGlicContentsElementId, {"body"}),
      InAnyContext(ExecuteJs(test::kGlicContentsElementId,
                             R"js(()=>{location = 'http://b.test/page';})js")),
      // Just wait a bit and make sure the page doesn't navigate.
      InAnyContext(CheckJsResult(test::kGlicContentsElementId, R"js(
  ()=>{
    const {promise, resolve} = Promise.withResolvers();
    window.setTimeout(() => resolve(true), 1000);
    return promise;
  })js")));
}

IN_PROC_BROWSER_TEST_P(GlicUiConnectedUiTest,
                       HidesTabAccessUIOnWebClientCrash) {
  content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      ObserveState(kGlicContextAccessIndicatorHistory, glic_service()),
      OpenGlicWindow(GlicWindowMode::kAttached,
                     GlicInstrumentMode::kHostAndContents),
      WaitForElementVisible(test::kGlicContentsElementId, {"body"}),
      InAnyContext(ExecuteJs(
          test::kGlicContentsElementId,
          R"js(()=>{client.browser.setContextAccessIndicator(true);})js")),
      InAnyContext(WaitForState(kGlicContextAccessIndicatorHistory,
                                IsContextAccessIndicatorCurrently(true))),
      // Kills the web client process, simulating a renderer crash.
      Do([this] { FindGlicGuestMainFrame()->GetProcess()->Shutdown(0); }),
      InAnyContext(
          WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kError))),
      InAnyContext(WaitForState(kGlicContextAccessIndicatorHistory,
                                IsContextAccessIndicatorCurrently(false))));
}

// Tests the network being unavailable at startup.
class GlicUiDisconnectedUiTest : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiDisconnectedUiTest()
      : GlicUiInteractiveUiTestBase(TestParams(/*connected=*/false)) {}
  ~GlicUiDisconnectedUiTest() override = default;
};

IN_PROC_BROWSER_TEST_F(GlicUiDisconnectedUiTest, DisconnectedPanelShown) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kOffline)),
      CheckElementVisible(kOfflinePanel, true));
}

IN_PROC_BROWSER_TEST_F(GlicUiDisconnectedUiTest, LoadsWhenBackOnline) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      ChangeConnectionState(true),
      WaitForState(kGlicUiStateHistory, IsNotCurrently(WebUiState::kOffline)),
      WaitForElementVisible(test::kGlicHostElementId, kContentsPanel),
      CheckElementVisible(kOfflinePanel, false),
      CheckState(kGlicUiStateHistory, IsCurrently(WebUiState::kReady)));
}

// Tests the entire loading sequence through to error if Glic is slow to load.
class GlicUiFullLoadingSequenceTest : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiFullLoadingSequenceTest()
      : GlicUiInteractiveUiTestBase(
            TestParams(base::Milliseconds(250),  // Pre-load
                       base::Milliseconds(250),  // Min loading time
                       base::Milliseconds(500),  // Max loading time
                       base::Hours(1)))          // Actual loading time
  {}
  ~GlicUiFullLoadingSequenceTest() override = default;
};

IN_PROC_BROWSER_TEST_F(GlicUiFullLoadingSequenceTest, Test) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kError)),
      CheckElementVisible(kErrorPanel, true),
      CheckElementVisible(kContentsPanel, false),
      CheckState(kGlicUiStateHistory,
                 testing::ElementsAre(
                     WebUiState::kUninitialized, WebUiState::kBeginLoad,
                     WebUiState::kShowLoading, WebUiState::kFinishLoading,
                     WebUiState::kError)));
}

// Tests the loading sequence where Glic loads almost immediately and there is
// no hold.
class GlicUiQuickLoadingSequenceNoHoldTest
    : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiQuickLoadingSequenceNoHoldTest()
      : GlicUiInteractiveUiTestBase(
            TestParams(base::Milliseconds(250),  // Pre-load
                       base::Milliseconds(0),    // Min loading time
                       base::Hours(1),           // Max loading time
                       base::Seconds(1)))        // Actual loading time
  {}
  ~GlicUiQuickLoadingSequenceNoHoldTest() override = default;
};

IN_PROC_BROWSER_TEST_F(GlicUiQuickLoadingSequenceNoHoldTest, Test) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kReady)),
      CheckElementVisible(kContentsPanel, true),
      CheckState(kGlicUiStateHistory,
                 testing::ElementsAre(
                     WebUiState::kUninitialized, WebUiState::kBeginLoad,
                     WebUiState::kShowLoading, WebUiState::kFinishLoading,
                     WebUiState::kReady)));
}

// Tests the loading sequence where Glic loads almost immediately and there is a
// hold.
class GlicUiQuickLoadingSequenceWithHoldTest
    : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiQuickLoadingSequenceWithHoldTest()
      : GlicUiInteractiveUiTestBase(
            TestParams(base::Milliseconds(0),     // Pre-load
                       base::Seconds(5),          // Min loading time
                       base::Hours(1),            // Max loading time
                       base::Milliseconds(500)))  // Actual loading time
  {}
  ~GlicUiQuickLoadingSequenceWithHoldTest() override = default;
};

IN_PROC_BROWSER_TEST_F(GlicUiQuickLoadingSequenceWithHoldTest, Test) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kReady)),
      CheckElementVisible(kContentsPanel, true),
      CheckState(
          kGlicUiStateHistory,
          testing::ElementsAre(WebUiState::kUninitialized,
                               WebUiState::kBeginLoad, WebUiState::kShowLoading,
                               WebUiState::kHoldLoading, WebUiState::kReady)));
}

// Tests the loading sequence where Glic loads almost immediately during
// preload.
class GlicUiQuickLoadingSequenceWithPreloadTest
    : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiQuickLoadingSequenceWithPreloadTest()
      : GlicUiInteractiveUiTestBase(
            TestParams(base::Seconds(3),         // Pre-load
                       base::Seconds(5),         // Min loading time
                       base::Seconds(10),        // Max loading time
                       base::Milliseconds(10)))  // Actual loading time
  {}
  ~GlicUiQuickLoadingSequenceWithPreloadTest() override = default;
};

// See https://crbug.com/418639389 - these probably need to be broken into unit
// tests with only integration tests for the messaging being passed back and
// forth; slow test runners can cause any time limit to be overrun.
IN_PROC_BROWSER_TEST_F(GlicUiQuickLoadingSequenceWithPreloadTest,
                       DISABLED_Test) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kReady)),
      CheckElementVisible(kContentsPanel, true),
      CheckState(
          kGlicUiStateHistory,
          testing::ElementsAre(WebUiState::kUninitialized,
                               WebUiState::kBeginLoad, WebUiState::kReady)));
}

// Tests the loading panel is visible during load.
class GlicUiLoadingPanelWaitingTest : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiLoadingPanelWaitingTest()
      : GlicUiInteractiveUiTestBase(
            TestParams(base::Milliseconds(0),  // Pre-load
                       base::Milliseconds(0),  // Min loading time
                       base::Hours(1),         // Max loading time
                       base::Hours(1)))        // Actual loading time
  {}
  ~GlicUiLoadingPanelWaitingTest() override = default;
};

IN_PROC_BROWSER_TEST_F(GlicUiLoadingPanelWaitingTest, Test) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory,
                   IsCurrently(WebUiState::kFinishLoading)),
      CheckElementVisible(kLoadingPanel, true));
}

// Tests the loading panel is visible during hold.
class GlicUiLoadingPanelHoldingTest : public GlicUiInteractiveUiTestBase {
 public:
  GlicUiLoadingPanelHoldingTest()
      : GlicUiInteractiveUiTestBase(
            TestParams(base::Milliseconds(0),     // Pre-load
                       base::Hours(1),            // Min loading time
                       base::Hours(2),            // Max loading time
                       base::Milliseconds(500)))  // Actual loading time
  {}
  ~GlicUiLoadingPanelHoldingTest() override = default;
};

IN_PROC_BROWSER_TEST_F(GlicUiLoadingPanelHoldingTest, Test) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kHoldLoading)),
      CheckElementVisible(kLoadingPanel, true));
}

// Test that the escape key can be used to dismiss the floaty window in various
// loading and error states.

IN_PROC_BROWSER_TEST_F(GlicUiDisconnectedUiTest, EscapeKeyDismisses) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kOffline)),
      CheckEscapeKeyDismisses(kOfflinePanel));
}

IN_PROC_BROWSER_TEST_F(GlicUiLoadingPanelWaitingTest, EscapeKeyDismisses) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory,
                   IsCurrently(WebUiState::kFinishLoading)),
      CheckEscapeKeyDismisses(kLoadingPanel));
}

IN_PROC_BROWSER_TEST_F(GlicUiLoadingPanelHoldingTest, EscapeKeyDismisses) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kHoldLoading)),
      CheckEscapeKeyDismisses(kLoadingPanel));
}

IN_PROC_BROWSER_TEST_F(GlicUiFullLoadingSequenceTest, EscapeKeyDismisses) {
  RunTestSequence(
      ObserveState(kGlicUiStateHistory, &host()),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly),
      WaitForState(kGlicUiStateHistory, IsCurrently(WebUiState::kError)),
      CheckEscapeKeyDismisses(kErrorPanel));
}

class GlicWithMultipleProfilesTest : public GlicUiInteractiveUiTestBase {
 public:
  GlicWithMultipleProfilesTest() : GlicUiInteractiveUiTestBase({}) {}
  ~GlicWithMultipleProfilesTest() override = default;

  Browser* CreateBrowserWithNewProfile() {
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    base::FilePath new_path =
        profile_manager->GenerateNextProfileDirectoryPath();
    Profile& new_profile =
        profiles::testing::CreateProfileSync(profile_manager, new_path);

    return CreateBrowser(&new_profile);
  }
};

// Creates two browsers with different profiles. Opens glic in each and verifies
// it loads, doesn't crash, and hides the other glic window.
IN_PROC_BROWSER_TEST_F(GlicWithMultipleProfilesTest, OpenGlicInEachProfile) {
  Browser* first_browser = browser();
  Browser* second_browser = CreateBrowserWithNewProfile();
  SetActiveBrowser(second_browser);

  RunTestSequence(
      // Warning!: `kAttached` really just clicks the glic button, the window
      // will open in detached mode because `features::kGlicDetached` is
      // enabled. We do this because InteractiveGlicTestT::ToggleGlicWindow
      // doesn't work right in detached mode with multiple profiles.
      // TODO(b/418284946): Fix ToggleGlicWindow.
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly));

  SetActiveBrowser(first_browser);
  RunTestSequence(
      CheckControllerShowing(false),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly));

  SetActiveBrowser(second_browser);
  RunTestSequence(
      CheckControllerShowing(false),
      OpenGlicWindow(GlicWindowMode::kAttached, GlicInstrumentMode::kHostOnly));
}

}  // namespace glic