File: mantis_untrusted_service_manager.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; 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 (198 lines) | stat: -rw-r--r-- 7,747 bytes parent folder | download | duplicates (5)
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
// 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.

#include "chromeos/ash/components/mantis/media_app/mantis_untrusted_service_manager.h"

#include <memory>
#include <optional>
#include <utility>

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "ash/constants/generative_ai_country_restrictions.h"
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/sequence_checker.h"
#include "base/uuid.h"
#include "chromeos/ash/components/mantis/media_app/mantis_untrusted_service.h"
#include "chromeos/ash/components/mantis/mojom/mantis_service.mojom.h"
#include "chromeos/ash/components/mojo_service_manager/connection.h"
#include "chromeos/ash/components/mojo_service_manager/mojom/mojo_service_manager.mojom.h"
#include "chromeos/ash/components/specialized_features/feature_access_checker.h"
#include "chromeos/services/machine_learning/public/cpp/service_connection.h"
#include "chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom.h"
#include "chromeos/services/machine_learning/public/mojom/text_classifier.mojom.h"
#include "components/signin/public/identity_manager/account_capabilities.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/cros_system_api/mojo/service_constants.h"

namespace ash {
namespace {

using ::ash::media_app_ui::mojom::MantisUntrustedPage;
using ::chromeos::machine_learning::mojom::LoadModelResult;
using ::chromeos::machine_learning::mojom::TextClassifier;
using ::mantis::mojom::PlatformModelProgressObserver;

enum class GenAIPhotoEditingSettings {
  kAllowed = 0,                // Allow and improve AI models
  kAllowedWithoutLogging = 1,  // Allow without improving AI models
  kDisabled = 2,               // Do not allow
};

// A helper class that wraps `MantisUntrustedPage::ReportMantisProgress()` as
// `PlatformModelProgressObserver::Progress()`.
class InitializeProgressObserver : public PlatformModelProgressObserver {
 public:
  explicit InitializeProgressObserver(
      mojo::PendingRemote<MantisUntrustedPage> page)
      : page_(std::move(page)) {}

  // implements PlatformModelProgressObserver:
  void Progress(double progress) override {
    page_->ReportMantisProgress(progress);
  }

 private:
  mojo::Remote<MantisUntrustedPage> page_;
};

}  // namespace

MantisUntrustedServiceManager::MantisUntrustedServiceManager(
    std::unique_ptr<specialized_features::FeatureAccessChecker> access_checker)
    : access_checker_(std::move(access_checker)) {
  ash::mojo_service_manager::GetServiceManagerProxy()->Request(
      chromeos::mojo_services::kCrosMantisService, std::nullopt,
      cros_service_.BindNewPipeAndPassReceiver().PassPipe());
  cros_service_.reset_on_disconnect();
  chromeos::machine_learning::ServiceConnection::GetInstance()
      ->BindMachineLearningService(ml_service_.BindNewPipeAndPassReceiver());
}

MantisUntrustedServiceManager::~MantisUntrustedServiceManager() = default;

// static
specialized_features::FeatureAccessConfig
MantisUntrustedServiceManager::GetFeatureAccessConfig() {
  specialized_features::FeatureAccessConfig access_config;
  access_config.capability_callback =
      base::BindRepeating([](AccountCapabilities capabilities) {
        return capabilities.can_use_generative_ai_photo_editing();
      });
  access_config.country_codes = ash::GetGenerativeAiCountryAllowlist();
  return access_config;
}

void MantisUntrustedServiceManager::OnQueryDone(
    base::OnceCallback<void(bool)> callback,
    chromeos::mojo_service_manager::mojom::ErrorOrServiceStatePtr result) {
  if (!result->is_state() || !result->get_state()->is_registered_state()) {
    std::move(callback).Run(false);
    return;
  }
  cros_service_->GetMantisFeatureStatus(base::BindOnce(
      [](base::OnceCallback<void(bool)> callback,
         mantis::mojom::MantisFeatureStatus status) {
        std::move(callback).Run(status ==
                                mantis::mojom::MantisFeatureStatus::kAvailable);
      },
      std::move(callback)));
}

void MantisUntrustedServiceManager::IsAvailable(
    PrefService* pref_service,
    base::OnceCallback<void(bool)> callback) {
  if (switches::IsMantisSecretKeyMatched()) {
    std::move(callback).Run(true);
    return;
  }
  if (!base::FeatureList::IsEnabled(ash::features::kMediaAppImageMantisModel)) {
    std::move(callback).Run(false);
    return;
  }

  specialized_features::FeatureAccessFailureSet failure_set =
      access_checker_->Check();
  if (!failure_set.empty()) {
    std::move(callback).Run(false);
    return;
  }

  if (pref_service->GetInteger(ash::prefs::kGenAIPhotoEditingSettings) ==
      static_cast<int>(GenAIPhotoEditingSettings::kDisabled)) {
    std::move(callback).Run(false);
    return;
  }

  // Query kCrosMantisService first since it might not be available on every
  // devices.
  ash::mojo_service_manager::GetServiceManagerProxy()->Query(
      chromeos::mojo_services::kCrosMantisService,
      base::BindOnce(&MantisUntrustedServiceManager::OnQueryDone,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

mojo::PendingRemote<PlatformModelProgressObserver>
MantisUntrustedServiceManager::CreateProgressObserver(
    mojo::PendingRemote<media_app_ui::mojom::MantisUntrustedPage> page) {
  mojo::PendingRemote<PlatformModelProgressObserver> progress_observer;
  progress_observers_.Add(
      std::make_unique<InitializeProgressObserver>(std::move(page)),
      progress_observer.InitWithNewPipeAndPassReceiver());
  return progress_observer;
}

mojo::PendingRemote<TextClassifier>
MantisUntrustedServiceManager::GetTextClassifier() {
  mojo::PendingRemote<TextClassifier> text_classifier;
  ml_service_->LoadTextClassifier(
      text_classifier.InitWithNewPipeAndPassReceiver(),
      base::BindOnce([](LoadModelResult result) {
        LOG_IF(ERROR, result != LoadModelResult::OK)
            << "LoadTextClassifier error: " << result;
      }));
  return text_classifier;
}

void MantisUntrustedServiceManager::Create(
    mojo::PendingRemote<MantisUntrustedPage> page,
    const std::optional<base::Uuid>& dlc_uuid,
    CreateCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  mojo::PendingRemote<mantis::mojom::MantisProcessor> processor;
  // This API is designed by CrOS service to handle multiple calls safely.
  cros_service_->Initialize(
      CreateProgressObserver(std::move(page)),
      processor.InitWithNewPipeAndPassReceiver(), dlc_uuid, GetTextClassifier(),
      base::BindOnce(&MantisUntrustedServiceManager::OnInitializeDone,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback),
                     std::move(processor)));
}

void MantisUntrustedServiceManager::ResetService() {
  mantis_untrusted_service_.reset();
}

void MantisUntrustedServiceManager::OnInitializeDone(
    CreateCallback callback,
    mojo::PendingRemote<mantis::mojom::MantisProcessor> processor,
    mantis::mojom::InitializeResult result) {
  if (result != mantis::mojom::InitializeResult::kSuccess) {
    std::move(callback).Run(CreateResult::NewError(result));
    return;
  }
  mantis_untrusted_service_ =
      std::make_unique<MantisUntrustedService>(std::move(processor));
  std::move(callback).Run(CreateResult::NewService(
      mantis_untrusted_service_->BindNewPipeAndPassRemote(
          base::BindOnce(&MantisUntrustedServiceManager::ResetService,
                         weak_ptr_factory_.GetWeakPtr()))));
}

}  // namespace ash