File: proactive_nudge_tracker.h

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; 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 (232 lines) | stat: -rw-r--r-- 8,629 bytes parent folder | download | duplicates (4)
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
// 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.

#ifndef CHROME_BROWSER_COMPOSE_PROACTIVE_NUDGE_TRACKER_H_
#define CHROME_BROWSER_COMPOSE_PROACTIVE_NUDGE_TRACKER_H_

#include <map>
#include <memory>
#include <optional>
#include <string>

#include "base/functional/callback_forward.h"
#include "base/memory/raw_ref.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/compose/proto/compose_optimization_guide.pb.h"
#include "components/autofill/content/browser/scoped_autofill_managers_observation.h"
#include "components/autofill/core/browser/suggestions/suggestion.h"
#include "components/autofill/core/common/unique_ids.h"
#include "components/compose/core/browser/compose_metrics.h"
#include "components/segmentation_platform/public/segmentation_platform_service.h"

namespace compose {

// This class is a state machine tracking whether the proactive nudge should
// show for Compose. It has the following states:
//   - kInitial,
//   - kWaitingForTimerToStop,
//   - kTimerCanceled,
//   - kWaitingForSegmentation,
//   - kWaitingForProactiveNudgeRequest,
//   - kBlockedBySegmentation,
//   - kShown
//
// Generally, states transition forward through the list (skipping states if
// required). If the active form field changes (or the form loses focus), the
// state is reset to `kInitial`.
//
// The state is represented by a unique pointer to a `State` struct that is
// reset whenever a field loses focus.
// * If the struct is `null` then the state is `kInitial`.
// * The state remains in `kInitial` until any of the three delay times can be
//   triggered.
// * If the struct has a value, the value of `show_state` differentiates between
//   the remaining states.
// * The Delegate is called at the transition from `kWaitingForSegmentation` to
//   `kWaitingForProactiveNudgeRequest`.
// * Unintuitively, `ProactiveNudgeRequestedForFormField` can cause a transition
//   from kWaitingForProactiveNudgeRequest to `kShown`. Compose interacts with
//   Autofill such that it cannot directly show the nudge; instead it requests
//   the Autofill Agent for the current frame to ask for values to fill. Thus,
//   the entry point is the same both for new nudge states, and for the final
//   step of actually showing the nudge. Thus, the only way to transition to
//   `kShown` is to call after the tracker has entered the state
//   `kWaitingForProactiveNudgeRequest`.
class ProactiveNudgeTracker : public autofill::AutofillManager::Observer {
 public:
  using FallbackShowResult = base::RepeatingCallback<float()>;

  class Delegate {
   public:
    virtual void ShowProactiveNudge(autofill::FormGlobalId form,
                                    autofill::FieldGlobalId field,
                                    compose::ComposeEntryPoint entry_point) = 0;

    virtual compose::PageUkmTracker* GetPageUkmTracker() = 0;

    // Return the ComposeHintMetadata for the associated page. If no hint is
    // available return an empty ComposeHintMetadata object.
    virtual compose::ComposeHintMetadata GetComposeHintMetadata() = 0;

    // Compared with compose's Config random nudge probability to determine if
    // we should show the nudge if segmentation fails.
    virtual float SegmentationFallbackShowResult();

    // Returns a random number between 0 and 1. Controls whether the proactive
    // nudge is force-shown when segmentation is enabled.
    virtual float SegmentationForceShowResult();
  };

  enum class ShowState {
    kInitial,
    kWaitingForTimerToStop,
    kTimerCanceled,
    kWaitingForSegmentation,
    kWaitingForProactiveNudgeRequest,
    kBlockedBySegmentation,
    kShown
  };

  // Signals that determine whether the nudge should be shown.
  struct Signals {
    Signals();
    Signals(Signals&&);
    Signals& operator=(Signals&&);
    ~Signals();

    ukm::SourceId ukm_source_id;
    url::Origin page_origin;
    GURL page_url;
    autofill::FormData form;
    autofill::FormFieldData field;
    // Time the page started to show in a tab.
    base::TimeTicks page_change_time;
  };

  class State final {
   public:
    State();
    ~State();

    Signals signals;
    std::u16string initial_text_value;
    std::optional<segmentation_platform::ClassificationResult>
        segmentation_result = std::nullopt;
    bool segmentation_result_ignored_for_training = false;
    base::OneShotTimer timer;
    bool selection_nudge_requested = false;
    bool selection_nudge_shown = false;
    bool timer_canceled = false;

    int text_change_count = 0;

    ShowState show_state = ShowState::kInitial;

    base::WeakPtr<State> AsWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); }

   private:
    base::WeakPtrFactory<State> weak_ptr_factory_{this};
  };

  ProactiveNudgeTracker(
      segmentation_platform::SegmentationPlatformService* segmentation_service,
      Delegate* delegate);

  ~ProactiveNudgeTracker() override;

  // Call so that focus events can be obtained from the AutofillManager for this
  // `web_contents`.
  void StartObserving(content::WebContents* web_contents);

  // If the field from `signals` is not the currently matched field sets up
  // internal state to start tracking the new field waiting in `kInitial` for
  // any possible delay timer to start.
  //
  // If the current state is kWaitingForProactiveNudgeRequest, updates the state
  // to kShown.
  //
  // Returns true if the nudge shown but can be.
  bool ProactiveNudgeRequestedForFormField(Signals signals);

  // Returns whether or not the tracker is currently waiting.
  bool IsTimerRunning();

  void FocusChangedInPage();

  void Clear();

  void ComposeSessionCompleted(autofill::FieldGlobalId field_renderer_id,
                               ComposeSessionCloseReason session_close_reason,
                               const compose::ComposeSessionEvents& events);
  void OnUserDisabledNudge(bool single_site_only);

  // autofill::AutofillManager::Observer:
  void OnAfterFocusOnFormField(autofill::AutofillManager& manager,
                               autofill::FormGlobalId form,
                               autofill::FieldGlobalId field) override;
  void OnAfterCaretMovedInFormField(autofill::AutofillManager& manager,
                                    const autofill::FormGlobalId& form,
                                    const autofill::FieldGlobalId& field,
                                    const std::u16string& selection,
                                    const gfx::Rect& caret_bounds) override;
  void OnAfterTextFieldValueChanged(autofill::AutofillManager& manager,
                                    autofill::FormGlobalId form,
                                    autofill::FieldGlobalId field,
                                    const std::u16string& text_value) override;

 private:
  class EngagementTracker;

  bool SegmentationStateIsValid();
  void ResetState();

  void UpdateStateForCurrentFormField();
  std::optional<ShowState> CheckForStateTransition();
  void TransitionToState(ShowState new_show_state);

  void BeginWaitingForTimerToStop();
  void BeginTimerCanceled();
  void BeginSegmentation();
  void BeginWaitingForProactiveNudgeRequest();
  void BeginBlockedBySegmentation();
  void BeginShown();

  void ShowTimerElapsed();
  void StartOrRestartTimer();
  bool CanStartFocusTimer();
  bool CanStartTextSettledTimer();
  bool CanStartSelectionTimer();

  void GotClassificationResult(
      const segmentation_platform::ClassificationResult& result);
  bool MatchesCurrentField(autofill::FormGlobalId form,
                           autofill::FieldGlobalId field);
  void CollectTrainingData(
      const segmentation_platform::TrainingRequestId training_request_id,
      ProactiveNudgeDerivedEngagement engagement);

  std::optional<bool> CachedSegmentationResult();

  std::unique_ptr<State> state_;

  bool nudge_currently_requested_ = false;

  // Map indicating if the classification result from the segmentation platform
  // allows the nudge to be shown for previously queried fields.
  std::map<autofill::FieldGlobalId, bool> seen_fields_;

  std::map<autofill::FieldGlobalId, std::unique_ptr<EngagementTracker>>
      engagement_trackers_;

  raw_ptr<segmentation_platform::SegmentationPlatformService>
      segmentation_service_;
  raw_ptr<Delegate> delegate_;

  autofill::ScopedAutofillManagersObservation autofill_managers_observation_{
      this};
  base::WeakPtrFactory<ProactiveNudgeTracker> weak_ptr_factory_{this};
};

}  // namespace compose
#endif  // CHROME_BROWSER_COMPOSE_PROACTIVE_NUDGE_TRACKER_H_