File: execution_engine.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 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 (501 lines) | stat: -rw-r--r-- 16,680 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
// 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 "chrome/browser/actor/execution_engine.h"

#include <cstddef>
#include <utility>

#include "base/check.h"
#include "base/check_deref.h"
#include "base/feature_list.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/notimplemented.h"
#include "base/types/id_type.h"
#include "chrome/browser/actor/actor_keyed_service.h"
#include "chrome/browser/actor/browser_action_util.h"
#include "chrome/browser/actor/site_policy.h"
#include "chrome/browser/actor/tools/tool_controller.h"
#include "chrome/browser/actor/tools/tool_request.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/common/actor.mojom.h"
#include "chrome/common/actor/action_result.h"
#include "chrome/common/chrome_features.h"
#include "components/optimization_guide/content/browser/page_content_proto_provider.h"
#include "components/optimization_guide/proto/features/actions_data.pb.h"
#include "components/tabs/public/tab_interface.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "mojo/public/cpp/base/proto_wrapper.h"
#include "url/origin.h"

using content::RenderFrameHost;
using content::WebContents;
using optimization_guide::DocumentIdentifierUserData;
using optimization_guide::proto::Action;
using optimization_guide::proto::Actions;
using optimization_guide::proto::ActionTarget;
using optimization_guide::proto::AnnotatedPageContent;
using optimization_guide::proto::BrowserAction;
using tabs::TabInterface;

namespace actor {

namespace {

// Whether we need to run synchronous and asynchronous, tab-scoped safety
// checks.
bool ActionRequiresTabScopedSafetyChecks(const Action& action) {
  switch (action.action_case()) {
    case Action::kClick:
    case Action::kType:
    case Action::kScroll:
    case Action::kMoveMouse:
    case Action::kDragAndRelease:
    case Action::kSelect:
      return true;
    // TODO(crbug.com/411462297): It's not clear that navigate and wait requests
    // should be doing tab safety checks. For now we return `true` to preserve
    // existing behavior.
    case Action::kBack:
    case Action::kForward:
    case Action::kNavigate:
    case Action::kWait:
      return true;
    case Action::kCreateTab:
    case Action::kCloseTab:
    case Action::kActivateTab:
    case Action::kCreateWindow:
    case Action::kCloseWindow:
    case Action::kActivateWindow:
    case Action::kYieldToUser:
    case Action::ACTION_NOT_SET:
      return false;
  }
}

tabs::TabHandle GetTabHandleFromAction(
    const optimization_guide::proto::Action& action) {
  switch (action.action_case()) {
    case Action::kClick:
      return tabs::TabHandle(action.click().tab_id());
    case Action::kType:
      return tabs::TabHandle(action.type().tab_id());
    case Action::kScroll:
      return tabs::TabHandle(action.scroll().tab_id());
    case Action::kMoveMouse:
      return tabs::TabHandle(action.move_mouse().tab_id());
    case Action::kDragAndRelease:
      return tabs::TabHandle(action.drag_and_release().tab_id());
    case Action::kSelect:
      return tabs::TabHandle(action.select().tab_id());
    case Action::kBack:
      return tabs::TabHandle(action.back().tab_id());
    case Action::kForward:
      return tabs::TabHandle(action.forward().tab_id());
    case Action::kNavigate:
      return tabs::TabHandle(action.navigate().tab_id());
    case Action::kCloseTab:
      return tabs::TabHandle(action.close_tab().tab_id());
    case Action::kActivateTab:
      return tabs::TabHandle(action.activate_tab().tab_id());
    case Action::kWait:
    case Action::kCreateTab:
    case Action::kCreateWindow:
    case Action::kCloseWindow:
    case Action::kActivateWindow:
    case Action::kYieldToUser:
    case Action::ACTION_NOT_SET:
      return tabs::TabHandle();
  }
}

// Whether the action requires a tab.
bool ActionRequiresTab(const Action& action) {
  switch (action.action_case()) {
    case Action::kClick:
    case Action::kType:
    case Action::kScroll:
    case Action::kMoveMouse:
    case Action::kDragAndRelease:
    case Action::kSelect:
    case Action::kBack:
    case Action::kForward:
    case Action::kNavigate:
    case Action::kWait:
    case Action::kCloseTab:
    case Action::kActivateTab:
      return true;
    case Action::kCreateTab:
    case Action::kCreateWindow:
    case Action::kCloseWindow:
    case Action::kActivateWindow:
    case Action::kYieldToUser:
    case Action::ACTION_NOT_SET:
      return false;
  }
}

void PostTaskForActCallback(ExecutionEngine::ActionResultCallback callback,
                            mojom::ActionResultPtr result) {
  UMA_HISTOGRAM_ENUMERATION("Actor.ExecutionEngine.Action.ResultCode",
                            result->code);
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), std::move(result)));
}

}  // namespace

ExecutionEngine::ExecutionEngine(Profile* profile)
    : profile_(profile),
      journal_(ActorKeyedService::Get(profile)->GetJournal().GetSafeRef()) {
  CHECK(profile_);
  // Idempotent. Enables the action blocklist if it isn't already enabled.
  InitActionBlocklist(profile_.get());
}

ExecutionEngine::ExecutionEngine(Profile* profile, tabs::TabInterface* tab)
    : profile_(profile),
      journal_(ActorKeyedService::Get(profile)->GetJournal().GetSafeRef()),
      tab_scoped_actions_deprecated_(true),
      tab_(tab) {
  CHECK(profile_);
  // Idempotent. Enables the action blocklist if it isn't already enabled.
  InitActionBlocklist(profile_.get());

  CHECK(tab_);
  tab_will_detach_subscription_ = tab_->RegisterWillDetach(base::BindRepeating(
      &ExecutionEngine::OnTabWillDetach, base::Unretained(this)));
}

ExecutionEngine::~ExecutionEngine() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void ExecutionEngine::SetOwner(ActorTask* task) {
  task_ = task;
  tool_controller_ = std::make_unique<ToolController>(task_->id(), *journal_);
}

// static
void ExecutionEngine::RegisterWithProfile(Profile* profile) {
  InitActionBlocklist(profile);
}

void ExecutionEngine::CancelOngoingActions(mojom::ActionResultCode reason) {
  if (actions_v1_) {
    CompleteActions(MakeResult(reason));
  }
}

tabs::TabInterface* ExecutionEngine::GetTabOfCurrentTask() const {
  return tab_;
}

bool ExecutionEngine::HasTask() const {
  return !!actions_v1_ || !!actions_v2_;
}

bool ExecutionEngine::HasTaskForTab(const content::WebContents* tab) const {
  return HasTask() && tab_ && tab_->GetContents() == tab;
}

void ExecutionEngine::Act(const BrowserAction& action,
                          ActionResultCallback callback) {
  CHECK(base::FeatureList::IsEnabled(features::kGlicActor));
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TaskId task_id(action.task_id());

  if (task_->IsPaused()) {
    journal_->Log(LastCommittedURLOfCurrentTask(), task_id, "Act Failed",
                  "Unable to perform action: task is paused");
    PostTaskForActCallback(std::move(callback),
                           MakeResult(mojom::ActionResultCode::kTaskPaused));
    return;
  }

  // NOTE: Improve this API by queuing the action instead.
  if (actions_v1_ || actions_v2_) {
    journal_->Log(
        LastCommittedURLOfCurrentTask(), task_id, "Act Failed",
        "Unable to perform action: task already has action in progress");
    PostTaskForActCallback(std::move(callback),
                           MakeResult(mojom::ActionResultCode::kError,
                                      "Task already has action in progress"));
    return;
  }

  actions_v1_.emplace(action, std::move(callback));
  action_index_ = 0;

  // Kick off the first action.
  KickOffNextAction(/*previous_action_result=*/MakeOkResult());
}

void ExecutionEngine::Act(const Actions& actions,
                          ActionsResultCallback callback) {
  // actions_v2_ never uses tab-scoped tasks.
  CHECK(!tab_scoped_actions_deprecated_);
  CHECK(base::FeatureList::IsEnabled(features::kGlicActor));
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TaskId task_id(actions.task_id());

  if (task_->IsPaused()) {
    journal_->Log(LastCommittedURLOfCurrentTask(), task_id, "Act Failed",
                  "Unable to perform action: task is paused");
    optimization_guide::proto::ActionsResult result;
    result.set_action_result(
        static_cast<int32_t>(mojom::ActionResultCode::kTaskPaused));
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), std::move(result)));
    return;
  }

  if (actions_v1_ || actions_v2_) {
    journal_->Log(
        LastCommittedURLOfCurrentTask(), task_id, "Act Failed",
        "Unable to perform action: task already has action in progress");
    optimization_guide::proto::ActionsResult result;
    result.set_action_result(
        static_cast<int32_t>(mojom::ActionResultCode::kError));
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), std::move(result)));
    return;
  }

  actions_v2_.emplace(actions, std::move(callback));
  action_index_ = 0;

  // Kick off the first action.
  KickOffNextAction(/*previous_action_result=*/MakeOkResult());
}

void ExecutionEngine::KickOffNextAction(
    mojom::ActionResultPtr previous_action_result) {
  if (actions_v1_) {
    BrowserAction& proto = actions_v1_->proto;
    if (proto.actions_size() <= action_index_) {
      CompleteActionsV1(std::move(previous_action_result));
      return;
    }
  } else {
    auto& proto = actions_v2_->proto;
    if (proto.actions_size() <= action_index_) {
      CompleteActionsV2(std::move(previous_action_result));
      return;
    }
  }

  if (ActionRequiresTabScopedSafetyChecks(GetNextAction())) {
    SafetyChecksForNextAction();
  } else {
    ExecuteNextAction();
  }
}

void ExecutionEngine::SafetyChecksForNextAction() {
  CHECK(ActionRequiresTab(GetNextAction()));
  tabs::TabInterface* tab = GetTab(GetNextAction());

  if (!tab) {
    journal_->Log(GURL::EmptyGURL(), task_->id(), "Act Failed",
                  "The tab is no longer present");
    CompleteActions(MakeResult(mojom::ActionResultCode::kTabWentAway,
                               "The tab is no longer present."));
    return;
  }

  // Asynchronously check if we can act on the tab.
  MayActOnTab(
      *tab, *journal_, task_->id(),
      base::BindOnce(
          &ExecutionEngine::DidFinishAsyncSafetyChecks, GetWeakPtr(),
          tab->GetContents()->GetPrimaryMainFrame()->GetLastCommittedOrigin()));
}

void ExecutionEngine::DidFinishAsyncSafetyChecks(
    const url::Origin& evaluated_origin,
    bool may_act) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(actions_v1_ || actions_v2_);

  auto task_id = task_->id();
  tabs::TabInterface* tab = GetTab(GetNextAction());
  CHECK(tab);

  if (!evaluated_origin.IsSameOriginWith(tab->GetContents()
                                             ->GetPrimaryMainFrame()
                                             ->GetLastCommittedOrigin())) {
    // A cross-origin navigation occurred before we got permission. The result
    // is no longer applicable. For now just fail.
    // TODO(mcnee): Handle this gracefully.
    journal_->Log(LastCommittedURLOfCurrentTask(), task_id, "Act Failed",
                  "Acting after cross-origin navigation occurred");
    CompleteActions(
        MakeResult(mojom::ActionResultCode::kCrossOriginNavigation,
                   "Acting after cross-origin navigation occurred"));
    return;
  }

  if (!may_act) {
    journal_->Log(LastCommittedURLOfCurrentTask(), task_id, "Act Failed",
                  "URL blocked for actions");
    CompleteActions(MakeResult(mojom::ActionResultCode::kUrlBlocked,
                               "URL blocked for actions"));
    return;
  }

  ExecuteNextAction();
}

void ExecutionEngine::ExecuteNextAction() {
  CHECK(actions_v1_ || actions_v2_);
  CHECK(tool_controller_);

  const Action& action = GetNextAction();
  ++action_index_;

  // TODO(bokan): ExecutionEngine shouldn't know about the Action proto, it
  // should operate in terms of ToolRequest.
  active_tool_request_ = CreateToolRequest(action, tab_);
  if (!active_tool_request_) {
    journal_->Log(GURL::EmptyGURL(), task_->id(), "Act Failed",
                  "Failed to convert ActionInformation proto to ToolRequest");
    CompleteActions(MakeResult(mojom::ActionResultCode::kArgumentsInvalid));
    return;
  }

  tool_controller_->Invoke(
      *active_tool_request_, last_observed_page_content_.get(),
      base::BindOnce(&ExecutionEngine::FinishOneAction, GetWeakPtr()));
}

void ExecutionEngine::FinishOneAction(mojom::ActionResultPtr result) {
  CHECK(actions_v1_ || actions_v2_);

  active_tool_request_.reset();

  // The current action errored out. Stop the chain.
  if (!IsOk(*result)) {
    CompleteActions(std::move(result));
    return;
  }

  KickOffNextAction(std::move(result));
}

void ExecutionEngine::CompleteActions(mojom::ActionResultPtr result) {
  if (actions_v1_) {
    CompleteActionsV1(std::move(result));
    return;
  }
  if (actions_v2_) {
    CompleteActionsV2(std::move(result));
    return;
  }
}

void ExecutionEngine::CompleteActionsV1(mojom::ActionResultPtr result) {
  CHECK(actions_v1_);

  if (!IsOk(*result)) {
    journal_->Log(LastCommittedURLOfCurrentTask(),
                  TaskId(actions_v1_->proto.task_id()), "Act Failed",
                  ToDebugString(*result));
  }

  PostTaskForActCallback(std::move(actions_v1_->callback), std::move(result));
  actions_v1_.reset();
  action_index_ = 0;
  actions_weak_ptr_factory_.InvalidateWeakPtrs();
  // TODO(crbug.com/409559623): Conceptually this should also reset
  // `last_observed_page_content_`.
}

void ExecutionEngine::CompleteActionsV2(mojom::ActionResultPtr result) {
  CHECK(actions_v2_);

  optimization_guide::proto::ActionsResult actions_result;
  actions_result.set_action_result(static_cast<int32_t>(result->code));

  // TODO(crbug.com/411462297): Populate observation.
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(std::move(actions_v2_->callback),
                                std::move(actions_result)));
  actions_v2_.reset();
  action_index_ = 0;
  actions_weak_ptr_factory_.InvalidateWeakPtrs();
}

void ExecutionEngine::OnTabWillDetach(tabs::TabInterface* tab,
                                      tabs::TabInterface::DetachReason reason) {
  if (reason != tabs::TabInterface::DetachReason::kDelete) {
    return;
  }
  if (!tab_) {
    return;
  }
  CHECK_EQ(tab, tab_);
  tab_ = nullptr;

  // actions_v2_ never uses tab-scoped tasks.
  if (tab_scoped_actions_deprecated_ && actions_v1_) {
    journal_->Log(LastCommittedURLOfCurrentTask(),
                  TaskId(actions_v1_->proto.task_id()), "Act Failed",
                  "The tab is no longer present");
    CompleteActions(MakeResult(mojom::ActionResultCode::kTabWentAway,
                               "The tab is no longer present."));
  }
}

void ExecutionEngine::DidObserveContext(
    const mojo_base::ProtoWrapper& apc_proto) {
  last_observed_page_content_ = std::make_unique<AnnotatedPageContent>(
      apc_proto.As<AnnotatedPageContent>().value());
}

const AnnotatedPageContent* ExecutionEngine::GetLastObservedPageContent() {
  return last_observed_page_content_.get();
}

base::WeakPtr<ExecutionEngine> ExecutionEngine::GetWeakPtr() {
  return actions_weak_ptr_factory_.GetWeakPtr();
}

const GURL& ExecutionEngine::LastCommittedURLOfCurrentTask() {
  if (!tab_) {
    return GURL::EmptyGURL();
  }
  return tab_->GetContents()->GetLastCommittedURL();
}

const optimization_guide::proto::Action& ExecutionEngine::GetNextAction() {
  if (actions_v1_) {
    return actions_v1_->proto.actions().at(action_index_);
  } else {
    return actions_v2_->proto.actions().at(action_index_);
  }
}

tabs::TabInterface* ExecutionEngine::GetTab(
    const optimization_guide::proto::Action& action) {
  tabs::TabHandle tab_handle = GetTabHandleFromAction(action);
  tabs::TabInterface* tab = tab_handle.Get();
  if (tab) {
    return tab;
  }
  if (tab_scoped_actions_deprecated_) {
    return tab_;
  }
  return nullptr;
}

}  // namespace actor