File: assistant_browser_delegate_impl.cc

package info (click to toggle)
chromium 140.0.7339.127-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,192,880 kB
  • sloc: cpp: 35,093,808; ansic: 7,161,670; javascript: 4,199,694; python: 1,441,797; asm: 949,904; xml: 747,503; pascal: 187,748; perl: 88,691; sh: 88,248; objc: 79,953; sql: 52,714; cs: 44,599; fortran: 24,137; makefile: 22,114; tcl: 15,277; php: 13,980; yacc: 9,000; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (333 lines) | stat: -rw-r--r-- 13,328 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
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
// Copyright 2018 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/ui/ash/assistant/assistant_browser_delegate_impl.h"

#include <string>
#include <utility>

#include "ash/constants/ash_features.h"
#include "ash/constants/web_app_id_constants.h"
#include "ash/public/cpp/network_config_service.h"
#include "ash/public/cpp/new_window_delegate.h"
#include "base/check_is_test.h"
#include "base/containers/fixed_flat_set.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_util.h"
#include "base/types/expected.h"
#include "base/types/expected_macros.h"
#include "chrome/browser/apps/app_service/app_launch_params.h"
#include "chrome/browser/apps/app_service/app_service_proxy_ash.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/ash/assistant/assistant_util.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/common/webui_url_constants.h"
#include "chromeos/ash/services/assistant/public/cpp/assistant_browser_delegate.h"
#include "chromeos/ash/services/assistant/public/cpp/features.h"
#include "chromeos/services/assistant/public/shared/constants.h"
#include "components/session_manager/core/session_manager.h"
#include "components/user_manager/user_manager.h"

namespace {

using AssistantBrowserDelegate = ash::assistant::AssistantBrowserDelegate;

Profile* GetActiveUserProfile() {
  user_manager::User* active_user =
      user_manager::UserManager::Get()->GetActiveUser();
  CHECK(active_user);

  return ash::ProfileHelper::Get()->GetProfileByUser(active_user);
}

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused. If any value is added, please update
// `AssistantNewEntryPointEligibility` in `enums.xml`
// TODO: crbug.com/388361414 - Delete all new entry point related code from this
// class.
// LINT.IfChange(AssistantNewEntryPointEligibility)
enum class AssistantNewEntryPointEligibility {
  // A profile is eligible for the new entry point.
  kEligible = 0,
  // A profile is not ready for eligibility check. This can be both permanent
  // error (e.g., guest session) and transient error (e.g., queried before user
  // session started).
  kErrorProfileNotReady = 1,
  // Web provider is not ready for eligibility check. The eligibility check
  // waits for external managers synchornization of `WebAppProvider`.
  kErrorWebProviderNotReady = 2,
  // Not eligible because the new entry point flag is off.
  kNotEligibleFlagOff = 3,
  // Not eligible because the new entry point is not installed.
  kNotEligibleNotInstalled = 4,
  // Not eligible because the build is not Google Chrome.
  kNotEligibleNonGoogleChrome = 5,
  kMaxValue = kNotEligibleNonGoogleChrome,
};
// LINT.ThenChange(/tools/metrics/histograms/enums.xml:AssistantNewEntryPointEligibility)

AssistantNewEntryPointEligibility ToHistogramEnum(
    base::expected<const web_app::WebApp*, AssistantBrowserDelegate::Error>
        maybe_web_app) {
  if (maybe_web_app.has_value()) {
    return AssistantNewEntryPointEligibility::kEligible;
  }

  switch (maybe_web_app.error()) {
    case AssistantBrowserDelegate::Error::kProfileNotReady:
      return AssistantNewEntryPointEligibility::kErrorProfileNotReady;
    case AssistantBrowserDelegate::Error::kWebAppProviderNotReadyToRead:
      return AssistantNewEntryPointEligibility::kErrorWebProviderNotReady;
    case AssistantBrowserDelegate::Error::kNewEntryPointNotEnabled:
      return AssistantNewEntryPointEligibility::kNotEligibleFlagOff;
    case AssistantBrowserDelegate::Error::kNewEntryPointNotFound:
      return AssistantNewEntryPointEligibility::kNotEligibleNotInstalled;
    case AssistantBrowserDelegate::Error::kNonGoogleChromeBuild:
      return AssistantNewEntryPointEligibility::kNotEligibleNonGoogleChrome;
  }

  CHECK(false) << "Invalid error value is specified";
}

base::expected<bool, AssistantBrowserDelegate::Error> ToEligibilityBool(
    base::expected<const web_app::WebApp*, AssistantBrowserDelegate::Error>
        maybe_web_app) {
  if (maybe_web_app.has_value()) {
    return true;
  }

  static constexpr auto non_transient_error =
      base::MakeFixedFlatSet<AssistantBrowserDelegate::Error>(
          {AssistantBrowserDelegate::Error::kNewEntryPointNotEnabled,
           AssistantBrowserDelegate::Error::kNewEntryPointNotFound,
           AssistantBrowserDelegate::Error::kNonGoogleChromeBuild});
  if (non_transient_error.contains(maybe_web_app.error())) {
    return false;
  }

  return base::unexpected(maybe_web_app.error());
}

bool IsGoogleChrome() {
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
  return true;
#else
  return false;
#endif
}

}  // namespace

AssistantBrowserDelegateImpl::AssistantBrowserDelegateImpl() {
  auto* session_manager = session_manager::SessionManager::Get();
  // AssistantBrowserDelegateImpl must be created before any user session is
  // created. Otherwise, it will not get OnUserProfileLoaded notification.
  DCHECK(session_manager->sessions().empty());
  session_manager->AddObserver(this);
}

AssistantBrowserDelegateImpl::~AssistantBrowserDelegateImpl() {
  session_manager::SessionManager::Get()->RemoveObserver(this);
}

void AssistantBrowserDelegateImpl::InitializeNewEntryPointFor(
    Profile* profile) {
  CHECK(profile);

  web_app::WebAppProvider* provider =
      web_app::WebAppProvider::GetForWebApps(profile);
  if (!provider) {
    // `WebAppProvider` is not available if `GetBrowserContextForWebApps` in
    // `web_app_utils.cc` returns nullptr, e.g., guest session. This is
    // non-recoverable, i.e., no need to wait and/or re-try.
    return;
  }

  if (profile_for_new_entry_point_) {
    CHECK_EQ(profile_for_new_entry_point_, profile)
        << "profile_for_new_entry_point_ is already initialized with a "
           "different profile. There should be only a single primary profile.";
    return;
  }

  // Profile is set only if `WebAppProvider` is available for the profile.
  profile_for_new_entry_point_ = profile;

  // Assistant new entry point is loaded to `WebAppProvider` as an async
  // operation. We have to wait for the async load before checking if Assistant
  // new entry point is installed on a device/profile.
  provider->on_external_managers_synchronized().Post(
      FROM_HERE,
      base::BindOnce(
          &AssistantBrowserDelegateImpl::OnExternalManagersSynchronized,
          weak_ptr_factory_.GetWeakPtr()));
}

void AssistantBrowserDelegateImpl::OnAssistantStatusChanged(
    ash::assistant::AssistantStatus new_status) {}

void AssistantBrowserDelegateImpl::RequestAssistantVolumeControl(
    mojo::PendingReceiver<ash::mojom::AssistantVolumeControl> receiver) {}

void AssistantBrowserDelegateImpl::RequestBatteryMonitor(
    mojo::PendingReceiver<device::mojom::BatteryMonitor> receiver) {}

void AssistantBrowserDelegateImpl::RequestWakeLockProvider(
    mojo::PendingReceiver<device::mojom::WakeLockProvider> receiver) {}

void AssistantBrowserDelegateImpl::RequestAudioStreamFactory(
    mojo::PendingReceiver<media::mojom::AudioStreamFactory> receiver) {}

void AssistantBrowserDelegateImpl::RequestAudioDecoderFactory(
    mojo::PendingReceiver<ash::assistant::mojom::AssistantAudioDecoderFactory>
        receiver) {}

void AssistantBrowserDelegateImpl::RequestAudioFocusManager(
    mojo::PendingReceiver<media_session::mojom::AudioFocusManager> receiver) {}

void AssistantBrowserDelegateImpl::RequestMediaControllerManager(
    mojo::PendingReceiver<media_session::mojom::MediaControllerManager>
        receiver) {}

void AssistantBrowserDelegateImpl::RequestNetworkConfig(
    mojo::PendingReceiver<chromeos::network_config::mojom::CrosNetworkConfig>
        receiver) {}

void AssistantBrowserDelegateImpl::OpenUrl(GURL url) {
  // The new tab should be opened with a user activation since the user
  // interacted with the Assistant to open the url. |in_background| describes
  // the relationship between |url| and Assistant UI, not the browser. As
  // such, the browser will always be instructed to open |url| in a new
  // browser tab and Assistant UI state will be updated downstream to respect
  // |in_background|.
  ash::NewWindowDelegate::GetInstance()->OpenUrl(
      url, ash::NewWindowDelegate::OpenUrlFrom::kUserInteraction,
      ash::NewWindowDelegate::Disposition::kNewForegroundTab);
}

base::expected<const web_app::WebAppRegistrar*, AssistantBrowserDelegate::Error>
AssistantBrowserDelegateImpl::GetWebAppRegistrarForNewEntryPoint() {
  if (!profile_for_new_entry_point_) {
    return base::unexpected(AssistantBrowserDelegate::Error::kProfileNotReady);
  }

  if (!on_is_new_entry_point_eligible_ready_.is_signaled()) {
    return base::unexpected(
        AssistantBrowserDelegate::Error::kWebAppProviderNotReadyToRead);
  }

  if (!ash::assistant::features::IsNewEntryPointEnabled()) {
    return base::unexpected(
        AssistantBrowserDelegate::Error::kNewEntryPointNotEnabled);
  }

  web_app::WebAppProvider* provider =
      web_app::WebAppProvider::GetForWebApps(profile_for_new_entry_point_);
  CHECK(provider) << "WebAppProvider must be available if "
                     "on_is_new_entry_point_eligible_ready_ is signaled";

  return &(provider->registrar_unsafe());
}

base::expected<const web_app::WebApp*, AssistantBrowserDelegate::Error>
AssistantBrowserDelegateImpl::ResolveNewEntryPointIfEligible() {
  if (!IsGoogleChrome() && !is_google_chrome_override_for_testing_) {
    return base::unexpected(
        AssistantBrowserDelegate::Error::kNonGoogleChromeBuild);
  }

  ASSIGN_OR_RETURN(const web_app::WebAppRegistrar* web_app_registrar,
                   GetWebAppRegistrarForNewEntryPoint());

  std::string app_id = entry_point_id_for_testing_.empty()
                           ? ash::kGeminiAppId
                           : entry_point_id_for_testing_;
  const web_app::WebApp* web_app = web_app_registrar->GetAppById(app_id);
  if (!web_app) {
    return base::unexpected(
        AssistantBrowserDelegate::Error::kNewEntryPointNotFound);
  }

  return web_app;
}

void AssistantBrowserDelegateImpl::OnExternalManagersSynchronized() {
  on_is_new_entry_point_eligible_ready_.Signal();
}

base::expected<bool, AssistantBrowserDelegate::Error>
AssistantBrowserDelegateImpl::IsNewEntryPointEligibleForPrimaryProfile() {
  base::expected<const web_app::WebApp*, AssistantBrowserDelegate::Error>
      maybe_web_app = ResolveNewEntryPointIfEligible();

  base::UmaHistogramEnumeration("Assistant.NewEntryPoint.Eligibility",
                                ToHistogramEnum(maybe_web_app));
  return ToEligibilityBool(maybe_web_app);
}

void AssistantBrowserDelegateImpl::OpenNewEntryPoint() {
  ASSIGN_OR_RETURN(const web_app::WebApp* web_app,
                   ResolveNewEntryPointIfEligible(), [](auto) {});
  CHECK(profile_for_new_entry_point_);

  // Check if the app is already running. If it is, bring the window to front.
  for (Browser* browser : BrowserList::GetInstance()->OrderedByActivation()) {
    if ((browser->is_type_app() || browser->is_type_app_popup()) &&
        web_app->app_id() ==
            web_app::GetAppIdFromApplicationName(browser->app_name()) &&
        profile_for_new_entry_point_ == browser->profile()) {
      browser->window()->Show();
      return;
    }
  }

  apps::AppServiceProxyFactory::GetForProfile(profile_for_new_entry_point_)
      ->LaunchAppWithParams(apps::AppLaunchParams(
          web_app->app_id(), apps::LaunchContainer::kLaunchContainerWindow,
          WindowOpenDisposition::NEW_WINDOW,
          // TODO(xiaohuic): maybe add new source
          apps::LaunchSource::kUnknown));
}

std::optional<std::string>
AssistantBrowserDelegateImpl::GetNewEntryPointName() {
  ASSIGN_OR_RETURN(
      const web_app::WebApp* web_app, ResolveNewEntryPointIfEligible(),
      [](auto) -> std::optional<std::string> { return std::nullopt; });
  ASSIGN_OR_RETURN(
      const web_app::WebAppRegistrar* web_app_registrar,
      GetWebAppRegistrarForNewEntryPoint(),
      [](auto) -> std::optional<std::string> { return std::nullopt; });

  return web_app_registrar->GetAppShortName(web_app->app_id());
}

void AssistantBrowserDelegateImpl::OverrideEntryPointIdForTesting(
    const std::string& test_entry_point_id) {
  CHECK_IS_TEST();
  entry_point_id_for_testing_ = test_entry_point_id;
}

void AssistantBrowserDelegateImpl::SetGoogleChromeBuildForTesting() {
  CHECK_IS_TEST();
  CHECK(!is_google_chrome_override_for_testing_)
      << "Already marked as google chrome";
  is_google_chrome_override_for_testing_ = true;
}

void AssistantBrowserDelegateImpl::OnUserSessionStarted(bool is_primary_user) {
  if (is_primary_user) {
    InitializeNewEntryPointFor(GetActiveUserProfile());
  }
}