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

#include "base/base64.h"
#include "base/functional/callback.h"
#include "base/strings/to_string.h"
#include "base/test/bind.h"
#include "base/test/protobuf_matchers.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/actor/actor_test_util.h"
#include "chrome/browser/actor/execution_engine.h"
#include "chrome/browser/devtools/devtools_window_testing.h"
#include "chrome/browser/glic/host/context/glic_page_context_fetcher.h"
#include "chrome/browser/glic/host/glic.mojom-shared.h"
#include "chrome/browser/glic/test_support/interactive_glic_test.h"
#include "chrome/browser/glic/test_support/interactive_test_util.h"
#include "chrome/browser/ui/browser_element_identifiers.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/interaction/interactive_browser_test.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/proto/features/actions_data.pb.h"
#include "components/optimization_guide/proto/features/common_quality_data.pb.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "ui/base/interaction/element_identifier.h"

namespace glic::test {

namespace {

using ::base::test::EqualsProto;
using ::optimization_guide::proto::AnnotatedPageContent;
using ::optimization_guide::proto::BrowserAction;
using ::optimization_guide::proto::ClickAction;
using ::optimization_guide::proto::ContentAttributes;
using ::optimization_guide::proto::ContentNode;

constexpr char kActivateSurfaceIncompatibilityNotice[] =
    "Programmatic window activation does not work on the Weston reference "
    "implementation of Wayland used on Linux testbots. It also doesn't work "
    "reliably on Linux in general. For this reason, some of these tests which "
    "use ActivateSurface() may be skipped on machine configurations which do "
    "not reliably support them.";

std::string EncodeActionProto(const BrowserAction& action) {
  return base::Base64Encode(action.SerializeAsString());
}

class GlicActorControllerUiTest : public test::InteractiveGlicTest {
 public:
  using ActionProtoProvider = base::OnceCallback<std::string()>;

  GlicActorControllerUiTest() {
    scoped_feature_list_.InitWithFeatures(
        /*enabled_features=*/{features::kGlicActor,
                              optimization_guide::features::
                                  kAnnotatedPageContentWithActionableElements},
        /*disabled_features=*/{});
  }
  ~GlicActorControllerUiTest() override = default;

  void SetUpOnMainThread() override {
    // Add rule for resolving cross origin host names.
    InteractiveGlicTest::SetUpOnMainThread();
    host_resolver()->AddRule("*", "127.0.0.1");
  }

  // Executes a BrowserAction and verifies it succeeds. Optionally takes an
  // error reason which, when provided, causes failure if the action is
  // successful or fails with an unexpected reason.
  //
  // The action is passed as a proto "provider" which is a callback that returns
  // a string which is the base-64 representation of the BrowserAction proto to
  // invoke. This is a callback rather than a BrowserAction since, in some
  // cases, the parameters in the proto may depend on prior test steps (such as
  // extracting the AnnotatedPageContent, so that the provider can then find the
  // content node id from the APC). See the Provider methods below (e.g.
  // ClickActionProvider).
  auto ExecuteAction(ActionProtoProvider proto_provider,
                     base::Value::Dict context_options,
                     std::optional<glic::mojom::ActInFocusedTabErrorReason>
                         expected_error = std::nullopt) {
    constexpr int kResultSuccess = -1;
    constexpr std::string kSuccessString = "<Success>";
    CHECK_LT(kResultSuccess,
             static_cast<int>(mojom::ActInFocusedTabErrorReason::kMinValue));

    auto result_buffer = std::make_unique<std::optional<int>>();
    std::optional<int>* buffer_raw = result_buffer.get();
    return Steps(
        InAnyContext(WithElement(
            kGlicContentsElementId,
            [result_out = buffer_raw,
             proto_provider = std::move(proto_provider),
             context_options = std::move(context_options),
             kResultSuccess](ui::TrackedElement* el) mutable {
              content::WebContents* glic_contents =
                  AsInstrumentedWebContents(el)->web_contents();
              std::string script = content::JsReplace(
                  R"js(
                              (async () => {
                                const base64ToArrayBuffer = (base64) => {
                                  const bytes = window.atob(base64);
                                  const len = bytes.length;
                                  const ret = new Uint8Array(len);
                                  for (var i = 0; i < len; i++) {
                                    ret[i] = bytes.charCodeAt(i);
                                  }
                                  return ret.buffer;
                                }
                                try {
                                  await client.browser.actInFocusedTab({
                                    actionProto: base64ToArrayBuffer($1),
                                    tabContextOptions: $2
                                  });
                                  // Return success.
                                  return $3;
                                } catch (err) {
                                  return err.reason;
                                }
                              })();
                            )js",
                  std::move(proto_provider).Run(), std::move(context_options),
                  kResultSuccess);
              *result_out = content::EvalJs(glic_contents, std::move(script))
                                .ExtractInt();
            })),
        CheckResult(
            [result_in = std::move(result_buffer), &kSuccessString]() {
              CHECK(result_in->has_value());

              int result = result_in->value();
              if (result == kResultSuccess) {
                return kSuccessString;
              }
              auto result_enum =
                  static_cast<mojom::ActInFocusedTabErrorReason>(result);
              EXPECT_TRUE(mojom::IsKnownEnumValue(result_enum));
              return base::ToString(result_enum);
            },
            expected_error.has_value() ? base::ToString(expected_error.value())
                                       : kSuccessString,
            "ExecuteAction"));
  }

  // Overload of the above method that allows passing a BrowserAction directly,
  // if one can be constructed ahead of time i.e. does not depend on an
  // observation.
  auto ExecuteAction(const BrowserAction& action,
                     base::Value::Dict context_options,
                     std::optional<glic::mojom::ActInFocusedTabErrorReason>
                         expected_error = std::nullopt) {
    return ExecuteAction(PassthroughProvider(action),
                         std::move(context_options), expected_error);
  }
  // Starts a new task by executing an initial navigate action to `task_url` to
  // create a new tab. The new tab can then be referenced by the identifier
  // passed in `new_tab_id`.
  auto StartActorTaskInNewTab(const GURL& task_url,
                              ui::ElementIdentifier new_tab_id) {
    BrowserAction start_navigate = actor::MakeNavigate(task_url.spec());

    return Steps(InstrumentNextTab(new_tab_id),
                 ExecuteAction(start_navigate, AnnotationsOnlyContextOptions()),
                 WaitForWebContentsReady(new_tab_id, task_url));
  }

  // After invoking APIs that don't return promises, we round trip to both the
  // client and host to make sure the call has made it to the browser.
  auto RoundTrip() {
    return Steps(InAnyContext(WithElement(
                     kGlicContentsElementId,
                     [](ui::TrackedElement* el) {
                       content::WebContents* glic_contents =
                           AsInstrumentedWebContents(el)->web_contents();
                       ASSERT_TRUE(content::ExecJs(glic_contents, "true;"));
                     })),
                 InAnyContext(WithElement(
                     kGlicHostElementId, [](ui::TrackedElement* el) {
                       content::WebContents* webui_contents =
                           AsInstrumentedWebContents(el)->web_contents();
                       ASSERT_TRUE(content::ExecJs(webui_contents, "true;"));
                     })));
  }

  // Stops a running task by calling the glic StopActorTask API.
  auto StopActorTask() {
    return Steps(InAnyContext(WithElement(
                     kGlicContentsElementId,
                     [](ui::TrackedElement* el) {
                       content::WebContents* glic_contents =
                           AsInstrumentedWebContents(el)->web_contents();
                       constexpr std::string_view script =
                           "client.browser.stopActorTask(0);";
                       ASSERT_TRUE(content::ExecJs(glic_contents, script));
                     })),
                 RoundTrip());
  }

  // Pauses a running task by calling the glic PauseActorTask API.
  auto PauseActorTask() {
    return Steps(InAnyContext(WithElement(
                     kGlicContentsElementId,
                     [](ui::TrackedElement* el) {
                       content::WebContents* glic_contents =
                           AsInstrumentedWebContents(el)->web_contents();
                       constexpr std::string_view script =
                           "client.browser.pauseActorTask(0);";
                       ASSERT_TRUE(content::ExecJs(glic_contents, script));
                     })),
                 RoundTrip());
  }

  // Resumes a paused task by calling the glic ResumeActorTask API.
  auto ResumeActorTask(base::Value::Dict context_options, bool expected) {
    return Steps(InAnyContext(CheckElement(
        kGlicContentsElementId,
        [context_options =
             std::move(context_options)](ui::TrackedElement* el) mutable {
          content::WebContents* glic_contents =
              AsInstrumentedWebContents(el)->web_contents();
          std::string script = content::JsReplace(
              R"js(
                              (async () => {
                                try {
                                  await client.browser.resumeActorTask(0, $1);
                                  return true;
                                } catch (err) {
                                  return false;
                                }
                              })();
                            )js",
              std::move(context_options));
          return content::EvalJs(glic_contents, script).ExtractBool();
        },
        expected)));
  }

  // Returns a callback that builds an encoded proto for a click action on a
  // ContentNode that matches the passed in label.
  // Note: This currently assumes acting is occurring on the focused tab.
  ActionProtoProvider ClickActionProvider(std::string_view label) {
    return base::BindLambdaForTesting([this, label]() {
      content::RenderFrameHost* rfh = browser()
                                          ->tab_strip_model()
                                          ->GetActiveWebContents()
                                          ->GetPrimaryMainFrame();
      int32_t node_id = this->SearchAnnotatedPageContent(label);
      return EncodeActionProto(actor::MakeClick(*rfh, node_id));
    });
  }

  // Returns a callback that builds an encoded proto for a click action on a
  // specific dom_node_id.
  // Note: This currently assumes acting is occurring on the focused tab.
  ActionProtoProvider ClickActionProvider(int32_t node_id) {
    return base::BindLambdaForTesting([this, node_id]() {
      content::RenderFrameHost* rfh = browser()
                                          ->tab_strip_model()
                                          ->GetActiveWebContents()
                                          ->GetPrimaryMainFrame();
      return EncodeActionProto(actor::MakeClick(*rfh, node_id));
    });
  }

  // Returns a callback that builds an encoded proto for a click action on a
  // specific coordinate
  ActionProtoProvider ClickActionProvider(const gfx::Point& coordinate) {
    return base::BindLambdaForTesting([coordinate]() {
      return EncodeActionProto(actor::MakeClick(coordinate));
    });
  }

  // Returns a callback that simply encodes the given action.
  ActionProtoProvider PassthroughProvider(const BrowserAction& action) {
    return base::BindLambdaForTesting(
        [action]() { return EncodeActionProto(action); });
  }

  // Returns a callback that returns the given string as the action proto. Meant
  // for testing error handling since this allows providing an invalid proto.
  ActionProtoProvider ArbitraryStringProvider(std::string_view str) {
    return base::BindLambdaForTesting([str]() { return std::string(str); });
  }

  // Gets the context options to capture a new observation after completing an
  // action. This includes both annotations (i.e. AnnotatedPageContent) and a
  // screenshot.
  base::Value::Dict UpdatedContextOptions() {
    return base::Value::Dict()
        .Set("annotatedPageContent", true)
#if BUILDFLAG(IS_LINUX)
        // TODO(https://crbug.com/40191775): Tests on Linux aren't producing
        // graphical output so requesting a screenshot hangs forever.
        .Set("viewportScreenshot", false);
#else
        .Set("viewportScreenshot", true);
#endif
  }

  // Gets the context options to capture a new observation that only has the
  // annotations (AnnotatedPageContent). Taking screenshots can be slow or flaky
  // in the test. This is intended to be used for interim steps, *before*
  // returning the final context of an action.
  base::Value::Dict AnnotationsOnlyContextOptions() {
    return base::Value::Dict()
        .Set("annotatedPageContent", true)
        .Set("viewportScreenshot", false);
  }

  auto InitializeWithOpenGlicWindow() {
    DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kCurrentActiveTabId);

    // Navigate to ensure the initial tab has some valid content loaded that the
    // Glic window can observe.
    const GURL start_url =
        embedded_test_server()->GetURL("/actor/blank.html?start");

    return Steps(InstrumentTab(kCurrentActiveTabId),
                 NavigateWebContents(kCurrentActiveTabId, start_url),
                 OpenGlicWindow(GlicWindowMode::kAttached));
  }

  // Retrieves AnnotatedPageContent for the currently focused tab (and caches
  // it in `annotated_page_content_`).
  auto GetPageContextFromFocusedTab() {
    return Steps(Do([&]() {
      GlicKeyedService* glic_service =
          GlicKeyedServiceFactory::GetGlicKeyedService(browser()->GetProfile());
      ASSERT_TRUE(glic_service);

      base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);

      auto options = mojom::GetTabContextOptions::New();
      options->include_annotated_page_content = true;
      FocusedTabData data = glic_service->sharing_manager().GetFocusedTabData();
      if (data.focus()) {
        FetchPageContext(
            data.focus(), *options,
            /*include_actionable_data=*/false,
            base::BindLambdaForTesting([&](mojom::GetContextResultPtr result) {
              mojo_base::ProtoWrapper& serialized_apc =
                  *result->get_tab_context()
                       ->annotated_page_data->annotated_page_content;
              annotated_page_content_ = std::make_unique<AnnotatedPageContent>(
                  serialized_apc.As<AnnotatedPageContent>().value());
              run_loop.Quit();
            }));

        run_loop.Run();
      }
    }));
  }

  auto CheckHasTaskForTab(ui::ElementIdentifier tab, bool expected) {
    return Steps(InAnyContext(CheckElement(
        tab,
        [](ui::TrackedElement* el) {
          content::WebContents* tab_contents =
              AsInstrumentedWebContents(el)->web_contents();
          const auto* glic_service =
              GlicKeyedService::Get(tab_contents->GetBrowserContext());
          return glic_service &&
                 glic_service->IsExecutionEngineActingOnTab(tab_contents);
        },
        expected)));
  }

  // Check ExecutionEngine caches the last apc observation.
  auto CheckExecutionEngineHasAnnotatedPageContentCache() {
    return Steps(Do([&]() {
      GlicKeyedService* glic_service =
          GlicKeyedServiceFactory::GetGlicKeyedService(browser()->GetProfile());
      ASSERT_TRUE(glic_service);

      const AnnotatedPageContent& cached_apc =
          *glic_service->GetExecutionEngineForTesting(/*tab=*/nullptr)
               .GetLastObservedPageContent();
      EXPECT_THAT(*annotated_page_content_, EqualsProto(cached_apc));
    }));
  }

  auto OpenDevToolsWindow(ui::ElementIdentifier contents_to_inspect) {
    return Steps(InAnyContext(
        WithElement(contents_to_inspect, [](ui::TrackedElement* el) {
          content::WebContents* contents =
              AsInstrumentedWebContents(el)->web_contents();
          DevToolsWindowTesting::OpenDevToolsWindowSync(contents,
                                                        /*is_docked=*/false);
        })));
  }

 private:
  int32_t SearchAnnotatedPageContent(std::string_view label) {
    CHECK(annotated_page_content_)
        << "An observation must be made with GetPageContextFromFocusedTab "
           "before searching annotated page content.";

    // Traverse the APC in depth-first preorder, returning the first node that
    // matches the given label.
    std::stack<const ContentNode*> nodes;
    nodes.push(&annotated_page_content_->root_node());

    while (!nodes.empty()) {
      const ContentNode* current = nodes.top();
      nodes.pop();

      if (current->content_attributes().label() == label) {
        return current->content_attributes().common_ancestor_dom_node_id();
      }

      for (const auto& child : current->children_nodes()) {
        nodes.push(&child);
      }
    }

    // Tests must pass a label that matches one of the content nodes.
    NOTREACHED() << "Label [" << label << "] not found in page.";
  }

  base::test::ScopedFeatureList scoped_feature_list_;
  std::unique_ptr<AnnotatedPageContent> annotated_page_content_;
};

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, OpensNewTabOnFirstNavigate) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");
  BrowserAction navigate = actor::MakeNavigate(task_url.spec());

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  InstrumentNextTab(kNewActorTabId),
                  ExecuteAction(navigate, UpdatedContextOptions()),
                  WaitForWebContentsReady(kNewActorTabId, task_url));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest,
                       CachesLastObservedPageContentAfterActionFinish) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");
  BrowserAction navigate = actor::MakeNavigate(task_url.spec());

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(task_url, kNewActorTabId),
                  GetPageContextFromFocusedTab(),
                  CheckExecutionEngineHasAnnotatedPageContentCache());
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest,
                       ToctouCheckFailWhenCrossOriginTargetFrameChange) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  const GURL task_url =
      embedded_test_server()->GetURL("/actor/two_cross_origin_iframes.html");
  BrowserAction navigate = actor::MakeNavigate(task_url.spec());

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      StartActorTaskInNewTab(task_url, kNewActorTabId),
      ExecuteAction(ClickActionProvider({10, 10}), UpdatedContextOptions()),
      GetPageContextFromFocusedTab(),
      CheckExecutionEngineHasAnnotatedPageContentCache(),
      ExecuteJs(kNewActorTabId,
                "()=>{document.getElementById('topframe').remove();}"),
      ExecuteAction(ClickActionProvider({10, 10}), UpdatedContextOptions(),
                    glic::mojom::ActInFocusedTabErrorReason::kTargetNotFound));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest,
                       ToctouCheckFailWhenSameSiteTargetFrameChange) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  const GURL task_url =
      embedded_test_server()->GetURL("/actor/two_same_site_iframes.html");
  BrowserAction navigate = actor::MakeNavigate(task_url.spec());

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      StartActorTaskInNewTab(task_url, kNewActorTabId),
      ExecuteAction(ClickActionProvider({10, 10}), UpdatedContextOptions()),
      GetPageContextFromFocusedTab(),
      CheckExecutionEngineHasAnnotatedPageContentCache(),
      ExecuteJs(kNewActorTabId,
                "()=>{document.getElementById('topframe').remove();}"),
      ExecuteAction(ClickActionProvider({10, 10}), UpdatedContextOptions(),
                    glic::mojom::ActInFocusedTabErrorReason::kTargetNotFound));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest,
                       UsesExistingActorTabOnSubsequentNavigate) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");
  const GURL second_navigate_url =
      embedded_test_server()->GetURL("/actor/blank.html?second");
  BrowserAction second_navigate =
      actor::MakeNavigate(second_navigate_url.spec());

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(task_url, kNewActorTabId),
                  // Now that the task is started in a new tab, do the
                  // second navigation.
                  ExecuteAction(second_navigate, UpdatedContextOptions()),
                  WaitForWebContentsReady(kNewActorTabId, second_navigate_url));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, ActionSucceeds) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  constexpr std::string_view kClickableButtonLabel = "clickable";

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(task_url, kNewActorTabId),
                  GetPageContextFromFocusedTab(),
                  ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                                UpdatedContextOptions()),
                  WaitForJsResult(kNewActorTabId, "() => button_clicked"));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, ActionProtoInvalid) {
  std::string encodedProto = base::Base64Encode("invalid serialized bytes");
  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      ExecuteAction(
          ArbitraryStringProvider(encodedProto), UpdatedContextOptions(),
          glic::mojom::ActInFocusedTabErrorReason::kInvalidActionProto));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, ActionTargetNotFound) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  constexpr int32_t kNonExistentContentNodeId =
      std::numeric_limits<int32_t>::max();
  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      StartActorTaskInNewTab(task_url, kNewActorTabId),
      ExecuteAction(ClickActionProvider(kNonExistentContentNodeId),
                    UpdatedContextOptions(),
                    glic::mojom::ActInFocusedTabErrorReason::kTargetNotFound));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, HistoryTool) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  const GURL url_1 = embedded_test_server()->GetURL("/actor/blank.html?1");
  const GURL url_2 = embedded_test_server()->GetURL("/actor/blank.html?2");
  BrowserAction navigate_url_2 = actor::MakeNavigate(url_2.spec());
  BrowserAction back = actor::MakeHistoryBack();
  BrowserAction forward = actor::MakeHistoryForward();

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(url_1, kNewActorTabId),
                  ExecuteAction(navigate_url_2, UpdatedContextOptions()),
                  ExecuteAction(back, UpdatedContextOptions()),
                  WaitForWebContentsReady(kNewActorTabId, url_1),
                  ExecuteAction(forward, UpdatedContextOptions()),
                  WaitForWebContentsReady(kNewActorTabId, url_2));
}

// Ensure that a task can be stopped and that further actions fail.
IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, StopActorTask) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  constexpr std::string_view kClickableButtonLabel = "clickable";

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      StartActorTaskInNewTab(task_url, kNewActorTabId),
      GetPageContextFromFocusedTab(),
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions()),
      WaitForJsResult(kNewActorTabId, "() => button_clicked"),
      CheckHasTaskForTab(kNewActorTabId, true), StopActorTask(),
      // TODO(crbug.com/409558980): Expect kTargetNotFound since that's
      // currently the error returned anytime a tool fails but in the future we
      // should add an error code for "NoActiveTask".
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions(),
                    glic::mojom::ActInFocusedTabErrorReason::kTargetNotFound),
      CheckHasTaskForTab(kNewActorTabId, false));
}

// Ensure that a task can be started after a previous task was stopped.
IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, StopThenStartActTask) {
  constexpr std::string_view kClickableButtonLabel = "clickable";
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kFirstTabId);
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kSecondTabId);
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kThirdTabId);

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      // Start and stop.
      StartActorTaskInNewTab(task_url, kFirstTabId), StopActorTask(),

      // Start, click, stop.
      StartActorTaskInNewTab(task_url, kSecondTabId),
      GetPageContextFromFocusedTab(),
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions()),
      WaitForJsResult(kSecondTabId, "() => button_clicked"), StopActorTask(),

      // Start, click, stop.
      StartActorTaskInNewTab(task_url, kThirdTabId),
      GetPageContextFromFocusedTab(),
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions()),
      WaitForJsResult(kThirdTabId, "() => button_clicked"), StopActorTask());
}

// Ensure that a task can be paused and that further actions fail.
IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, PauseActorTask) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  constexpr std::string_view kClickableButtonLabel = "clickable";

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      StartActorTaskInNewTab(task_url, kNewActorTabId),
      GetPageContextFromFocusedTab(),
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions()),
      WaitForJsResult(kNewActorTabId, "() => button_clicked"),
      CheckHasTaskForTab(kNewActorTabId, true), PauseActorTask(),
      // TODO(crbug.com/409558980): Expect kTargetNotFound since that's
      // currently the error returned anytime a tool fails but in the future we
      // should add an error code for "NoActiveTask".
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions(),
                    glic::mojom::ActInFocusedTabErrorReason::kTargetNotFound),
      // Unlike stopping, pausing keeps the task.
      CheckHasTaskForTab(kNewActorTabId, true));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, PauseThenStopActorTask) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  constexpr std::string_view kClickableButtonLabel = "clickable";

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(task_url, kNewActorTabId),
                  GetPageContextFromFocusedTab(),
                  ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                                UpdatedContextOptions()),
                  WaitForJsResult(kNewActorTabId, "() => button_clicked"),
                  PauseActorTask(), CheckHasTaskForTab(kNewActorTabId, true),
                  StopActorTask(), CheckHasTaskForTab(kNewActorTabId, false));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, PauseAlreadyPausedActorTask) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  constexpr std::string_view kClickableButtonLabel = "clickable";

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(task_url, kNewActorTabId),
                  GetPageContextFromFocusedTab(),
                  ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                                UpdatedContextOptions()),
                  WaitForJsResult(kNewActorTabId, "() => button_clicked"),
                  PauseActorTask(), PauseActorTask(),
                  CheckHasTaskForTab(kNewActorTabId, true));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, PauseThenResumeActorTask) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  constexpr std::string_view kClickableButtonLabel = "clickable";

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      StartActorTaskInNewTab(task_url, kNewActorTabId),
      GetPageContextFromFocusedTab(),
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions()),
      WaitForJsResult(kNewActorTabId, "() => button_clicked"),
      ExecuteJs(kNewActorTabId, "() => { button_clicked = false; }"),
      PauseActorTask(), ResumeActorTask(UpdatedContextOptions(), true),
      CheckHasTaskForTab(kNewActorTabId, true),
      ExecuteAction(ClickActionProvider(kClickableButtonLabel),
                    UpdatedContextOptions()),
      WaitForJsResult(kNewActorTabId, "() => button_clicked"));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, ResumeActorTaskWithoutATask) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(task_url, kNewActorTabId),
                  StopActorTask(), CheckHasTaskForTab(kNewActorTabId, false),
                  // Once a task is stopped, it can't be resumed.
                  ResumeActorTask(UpdatedContextOptions(), false));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest,
                       ResumeActorTaskWhenAlreadyResumed) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(InitializeWithOpenGlicWindow(),
                  StartActorTaskInNewTab(task_url, kNewActorTabId),
                  PauseActorTask(),
                  ResumeActorTask(UpdatedContextOptions(), true),
                  ResumeActorTask(UpdatedContextOptions(), false));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, GetPageContextWithoutFocus) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kOtherTabId);

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  RunTestSequence(
      InitializeWithOpenGlicWindow(),
      StartActorTaskInNewTab(task_url, kNewActorTabId),
      SetOnIncompatibleAction(OnIncompatibleAction::kSkipTest,
                              kActivateSurfaceIncompatibilityNotice),
      AddInstrumentedTab(kOtherTabId, GURL(chrome::kChromeUISettingsURL)),
      FocusWebContents(kOtherTabId),
      // After waiting, this should get the context for `kNewActorTabId`, not
      // the currently focused settings page. The choice of the settings page is
      // to make ExecuteAction fail if we try to fetch the page context of the
      // wrong tab.
      ExecuteAction(actor::MakeWait(), AnnotationsOnlyContextOptions()));
}

IN_PROC_BROWSER_TEST_F(GlicActorControllerUiTest, StartTaskWithDevtoolsOpen) {
  DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kNewActorTabId);

  const GURL task_url =
      embedded_test_server()->GetURL("/actor/page_with_clickable_element.html");

  // Ensure a new tab can be created without crashing when the most recently
  // focused browser window is not a normal tabbed browser (e.g. a DevTools
  // window).
  RunTestSequence(InitializeWithOpenGlicWindow(),
                  OpenDevToolsWindow(kGlicContentsElementId),
                  StartActorTaskInNewTab(task_url, kNewActorTabId));
}

class GlicActorControllerWithActorDisabledUiTest
    : public test::InteractiveGlicTest {
 public:
  GlicActorControllerWithActorDisabledUiTest() {
    scoped_feature_list_.InitAndDisableFeature(features::kGlicActor);
  }
  ~GlicActorControllerWithActorDisabledUiTest() override = default;

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_F(GlicActorControllerWithActorDisabledUiTest,
                       ActorNotAvailable) {
  RunTestSequence(OpenGlicWindow(GlicWindowMode::kAttached),
                  InAnyContext(CheckJsResult(
                      kGlicContentsElementId,
                      "() => { return !(client.browser.actInFocusedTab); }")));
}

}  //  namespace

}  // namespace glic::test