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 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
|
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/feature_list.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/task/current_thread.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test.pb.h"
#include "base/test/with_feature_override.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/optimization_guide/model_execution/chrome_on_device_model_service_controller.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/webauthn/sheet_models.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/metrics_services_manager/metrics_services_manager.h"
#include "components/optimization_guide/core/feature_registry/feature_registration.h"
#include "components/optimization_guide/core/feature_registry/mqls_feature_registry.h"
#include "components/optimization_guide/core/model_execution/feature_keys.h"
#include "components/optimization_guide/core/model_execution/model_execution_features.h"
#include "components/optimization_guide/core/model_execution/model_execution_manager.h"
#include "components/optimization_guide/core/model_execution/model_execution_prefs.h"
#include "components/optimization_guide/core/model_execution/on_device_model_adaptation_loader.h"
#include "components/optimization_guide/core/model_execution/on_device_model_service_controller.h"
#include "components/optimization_guide/core/model_execution/optimization_guide_model_execution_error.h"
#include "components/optimization_guide/core/model_execution/test/fake_model_assets.h"
#include "components/optimization_guide/core/model_execution/test/feature_config_builder.h"
#include "components/optimization_guide/core/model_quality/model_execution_logging_wrappers.h"
#include "components/optimization_guide/core/model_quality/model_quality_log_entry.h"
#include "components/optimization_guide/core/optimization_guide_constants.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/core/optimization_guide_logger.h"
#include "components/optimization_guide/core/optimization_guide_model_executor.h"
#include "components/optimization_guide/core/optimization_guide_switches.h"
#include "components/optimization_guide/core/optimization_guide_util.h"
#include "components/optimization_guide/proto/model_quality_service.pb.h"
#include "components/optimization_guide/proto/on_device_model_execution_config.pb.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/account_capabilities_test_mutator.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/tflite/buildflags.h"
namespace optimization_guide {
namespace {
enum class ModelExecutionRemoteResponseType {
kSuccessful = 0,
kUnsuccessful = 1,
kMalformed = 2,
kErrorFiltered = 3,
kUnsupportedLanguage = 4,
};
proto::ExecuteResponse BuildComposeResponse(const std::string& output) {
proto::ComposeResponse compose_response;
compose_response.set_output(output);
proto::ExecuteResponse execute_response;
proto::Any* any_metadata = execute_response.mutable_response_metadata();
any_metadata->set_type_url(
base::StrCat({"type.googleapis.com/", compose_response.GetTypeName()}));
compose_response.SerializeToString(any_metadata->mutable_value());
auto response_data = ParsedAnyMetadata<proto::ComposeResponse>(*any_metadata);
EXPECT_TRUE(response_data);
return execute_response;
}
proto::ExecuteResponse BuildTestErrorExecuteResponse(
const proto::ErrorState& state) {
proto::ExecuteResponse execute_response;
execute_response.mutable_error_response()->set_error_state(state);
return execute_response;
}
class ScopedSetMetricsConsent {
public:
// Enables or disables metrics consent based off of |consent|.
explicit ScopedSetMetricsConsent(bool consent) : consent_(consent) {
ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting(
&consent_);
}
ScopedSetMetricsConsent(const ScopedSetMetricsConsent&) = delete;
ScopedSetMetricsConsent& operator=(const ScopedSetMetricsConsent&) = delete;
~ScopedSetMetricsConsent() {
ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting(
nullptr);
}
private:
const bool consent_;
};
constexpr float kTestDefaultTemperature = 0.9;
constexpr uint32_t kTestDefaultTopK = 7;
} // namespace
class ModelExecutionBrowserTestBase : public InProcessBrowserTest {
public:
ModelExecutionBrowserTestBase() = default;
~ModelExecutionBrowserTestBase() override = default;
ModelExecutionBrowserTestBase(const ModelExecutionBrowserTestBase&) = delete;
ModelExecutionBrowserTestBase& operator=(
const ModelExecutionBrowserTestBase&) = delete;
void SetUp() override {
InitializeFeatureList();
model_execution_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
net::EmbeddedTestServer::ServerCertificateConfig cert_config;
cert_config.dns_names = {
GURL(kOptimizationGuideServiceModelExecutionDefaultURL).host(),
};
model_execution_server_->SetSSLConfig(cert_config);
model_execution_server_->RegisterRequestHandler(base::BindRepeating(
&ModelExecutionBrowserTestBase::HandleGetModelExecutionRequest,
base::Unretained(this)));
// Start ModelQualityLogsUploaderService to upload the model quality logs on
// receiving it from model execution.
model_quality_logs_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
cert_config.dns_names = {
GURL(kOptimizationGuideServiceModelQualtiyDefaultURL).host(),
};
model_quality_logs_server_->SetSSLConfig(cert_config);
model_quality_logs_server_->RegisterRequestHandler(base::BindRepeating(
&ModelExecutionBrowserTestBase::HandleGetModelQualityLogsUploadRequest,
base::Unretained(this)));
num_logs_requests_ = 0;
ASSERT_TRUE(model_execution_server_->Start());
ASSERT_TRUE(model_quality_logs_server_->Start());
InProcessBrowserTest::SetUp();
}
void SetUpCommandLine(base::CommandLine* cmd) override {
cmd->AppendSwitchASCII(
switches::kOptimizationGuideServiceModelExecutionURL,
model_execution_server_
->GetURL(
GURL(kOptimizationGuideServiceModelExecutionDefaultURL).host(),
"/")
.spec());
cmd->AppendSwitchASCII(
switches::kModelQualityServiceURL,
model_quality_logs_server_
->GetURL(
GURL(kOptimizationGuideServiceModelQualtiyDefaultURL).host(),
"/")
.spec());
}
void SetUpBrowserContextKeyedServices(
content::BrowserContext* context) override {
InProcessBrowserTest::SetUpBrowserContextKeyedServices(context);
IdentityTestEnvironmentProfileAdaptor::
SetIdentityTestEnvironmentFactoriesOnBrowserContext(context);
}
void SetUpOnMainThread() override {
InProcessBrowserTest::SetUpOnMainThread();
identity_test_env_adaptor_ =
std::make_unique<IdentityTestEnvironmentProfileAdaptor>(
browser()->profile());
host_resolver()->AddRule("*", "127.0.0.1");
}
void TearDownOnMainThread() override {
EXPECT_TRUE(model_execution_server_->ShutdownAndWaitUntilComplete());
EXPECT_TRUE(model_quality_logs_server_->ShutdownAndWaitUntilComplete());
InProcessBrowserTest::TearDownOnMainThread();
}
void EnableSignin() {
auto account_info =
identity_test_env_adaptor_->identity_test_env()
->MakePrimaryAccountAvailable("user@gmail.com",
signin::ConsentLevel::kSignin);
AccountCapabilitiesTestMutator mutator(&account_info.capabilities);
mutator.set_can_use_model_execution_features(true);
identity_test_env_adaptor_->identity_test_env()
->UpdateAccountInfoForAccount(account_info);
identity_test_env_adaptor_->identity_test_env()
->SetAutomaticIssueOfAccessTokens(true);
}
bool IsSignedIn() const {
return identity_test_env_adaptor_->identity_test_env()
->identity_manager()
->HasPrimaryAccount(signin::ConsentLevel::kSignin);
}
OptimizationGuideKeyedService* GetOptimizationGuideKeyedService(
Profile* profile = nullptr) {
if (!profile) {
profile = browser()->profile();
}
return OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
}
// Executes the model for the feature, waits until the response is received,
// and returns the response.
void ExecuteModel(UserVisibleFeatureKey feature,
const proto::ComposeRequest& request_metadata,
Profile* profile = nullptr) {
if (!profile) {
profile = browser()->profile();
}
base::RunLoop run_loop;
ExecuteModelWithLogging(
GetOptimizationGuideKeyedService(profile),
ToModelBasedCapabilityKey(feature), request_metadata,
/*execution_timeout=*/std::nullopt,
base::BindOnce(&ModelExecutionBrowserTestBase::OnModelExecutionResponse,
base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run();
}
OnDeviceModelEligibilityReason GetOnDeviceModelEligibility(
ModelBasedCapabilityKey feature,
Profile* profile = nullptr) {
return GetOptimizationGuideKeyedService(profile)
->GetOnDeviceModelEligibility(feature);
}
void SetExpectedBearerAccessToken(
const std::string& expected_bearer_access_token) {
expected_bearer_access_token_ = expected_bearer_access_token;
}
void SetResponseType(ModelExecutionRemoteResponseType response_type) {
response_type_ = response_type;
}
void SetMetricsConsent(bool consent) {
scoped_metrics_consent_.emplace(consent);
}
void WaitForModelQualityLogsUpload(int expected_num_logs_requests) {
while (num_logs_requests_ < expected_num_logs_requests) {
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(100));
run_loop.Run();
}
EXPECT_EQ(num_logs_requests_, expected_num_logs_requests);
}
protected:
void OnModelExecutionResponse(
base::OnceClosure on_model_execution_closure,
OptimizationGuideModelExecutionResult result,
std::unique_ptr<proto::ComposeLoggingData> logging_data) {
ModelQualityLogsUploaderService* logs_uploader =
GetOptimizationGuideKeyedService()
->GetModelQualityLogsUploaderService();
base::WeakPtr<ModelQualityLogsUploaderService> logs_uploader_weak_ptr;
if (logs_uploader) {
logs_uploader_weak_ptr = logs_uploader->GetWeakPtr();
}
auto log_entry =
std::make_unique<ModelQualityLogEntry>(logs_uploader_weak_ptr);
*log_entry->log_ai_data_request()->mutable_compose() = *logging_data;
if (result.response.has_value() ||
result.response.error().error() ==
OptimizationGuideModelExecutionError::ModelExecutionError::
kFiltered ||
result.response.error().error() ==
OptimizationGuideModelExecutionError::ModelExecutionError::
kUnsupportedLanguage) {
EXPECT_TRUE(logging_data->has_request());
}
if (result.response.has_value()) {
EXPECT_TRUE(logging_data->has_response());
}
model_execution_result_.emplace(std::move(result));
ModelQualityLogEntry::Upload(std::move(log_entry));
std::move(on_model_execution_closure).Run();
}
std::unique_ptr<net::test_server::HttpResponse>
HandleGetModelExecutionRequest(const net::test_server::HttpRequest& request) {
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
EXPECT_EQ(request.method, net::test_server::METHOD_POST);
EXPECT_NE(request.headers.end(), request.headers.find("X-Client-Data"));
// Access token should be set.
EXPECT_TRUE(base::Contains(request.headers,
net::HttpRequestHeaders::kAuthorization));
EXPECT_EQ(expected_bearer_access_token_,
request.headers.at(net::HttpRequestHeaders::kAuthorization));
if (response_type_ == ModelExecutionRemoteResponseType::kSuccessful) {
std::string serialized_response;
proto::ExecuteResponse execute_response =
BuildComposeResponse("foo response");
execute_response.SerializeToString(&serialized_response);
response->set_code(net::HTTP_OK);
response->set_content(serialized_response);
} else if (response_type_ ==
ModelExecutionRemoteResponseType::kUnsuccessful) {
response->set_code(net::HTTP_NOT_FOUND);
} else if (response_type_ == ModelExecutionRemoteResponseType::kMalformed) {
response->set_code(net::HTTP_OK);
response->set_content("Not a proto");
} else if (response_type_ ==
ModelExecutionRemoteResponseType::kErrorFiltered) {
std::string serialized_response;
proto::ExecuteResponse execute_response = BuildTestErrorExecuteResponse(
proto::ErrorState::ERROR_STATE_FILTERED);
execute_response.SerializeToString(&serialized_response);
response->set_code(net::HTTP_OK);
response->set_content(serialized_response);
} else if (response_type_ ==
ModelExecutionRemoteResponseType::kUnsupportedLanguage) {
std::string serialized_response;
proto::ExecuteResponse execute_response = BuildTestErrorExecuteResponse(
proto::ErrorState::ERROR_STATE_UNSUPPORTED_LANGUAGE);
execute_response.SerializeToString(&serialized_response);
response->set_code(net::HTTP_OK);
response->set_content(serialized_response);
} else {
NOTREACHED();
}
return std::move(response);
}
std::unique_ptr<net::test_server::HttpResponse>
HandleGetModelQualityLogsUploadRequest(
const net::test_server::HttpRequest& request) {
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
EXPECT_EQ(request.method, net::test_server::METHOD_POST);
EXPECT_NE(request.headers.end(), request.headers.find("X-Client-Data"));
// Access token should not be set.
EXPECT_FALSE(base::Contains(request.headers,
net::HttpRequestHeaders::kAuthorization));
std::string serialized_response;
response->set_code(net::HTTP_OK);
response->set_content(serialized_response);
num_logs_requests_++;
return std::move(response);
}
// Virtualize for testing different feature configurations.
virtual void InitializeFeatureList() {}
base::test::ScopedFeatureList scoped_feature_list_;
std::unique_ptr<net::EmbeddedTestServer> model_execution_server_;
std::unique_ptr<net::EmbeddedTestServer> model_quality_logs_server_;
base::HistogramTester histogram_tester_;
ModelExecutionRemoteResponseType response_type_ =
ModelExecutionRemoteResponseType::kSuccessful;
// The last model execution response received.
std::optional<OptimizationGuideModelExecutionResult> model_execution_result_;
// Identity test support.
std::unique_ptr<IdentityTestEnvironmentProfileAdaptor>
identity_test_env_adaptor_;
std::optional<ScopedSetMetricsConsent> scoped_metrics_consent_;
// The expected authorization header holding the bearer access token.
std::string expected_bearer_access_token_;
// The number of requests received by the model quality logs server.
std::atomic<int> num_logs_requests_ = 0;
};
class ModelExecutionDisabledBrowserTest : public ModelExecutionBrowserTestBase {
void InitializeFeatureList() override {
scoped_feature_list_.InitAndDisableFeature(
features::kOptimizationGuideModelExecution);
}
};
IN_PROC_BROWSER_TEST_F(ModelExecutionDisabledBrowserTest,
ModelExecutionDisabled) {
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_FALSE(model_execution_result_->response.has_value());
EXPECT_EQ(OptimizationGuideModelExecutionError::ModelExecutionError::
kGenericFailure,
model_execution_result_->response.error().error());
EXPECT_TRUE(model_execution_result_->response.error().transient());
}
IN_PROC_BROWSER_TEST_F(ModelExecutionDisabledBrowserTest,
GetOnDeviceModelEligibilityExecutionDisabled) {
EXPECT_EQ(GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose),
OnDeviceModelEligibilityReason::kFeatureNotEnabled);
}
IN_PROC_BROWSER_TEST_F(
ModelExecutionDisabledBrowserTest,
GetOnDeviceModelEligibilityExecutionDisabledNullDebugReason) {
EXPECT_NE(GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose),
OnDeviceModelEligibilityReason::kSuccess);
}
class ModelExecutionEnabledOnDeviceDisabledBrowserTest
: public ModelExecutionBrowserTestBase {
void InitializeFeatureList() override {
scoped_feature_list_.InitWithFeatures(
{features::kOptimizationGuideModelExecution,
features::kModelQualityLogging},
{features::kOptimizationGuideOnDeviceModel});
}
};
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledOnDeviceDisabledBrowserTest,
GetOnDeviceModelEligibilityOnDeviceDisabled) {
EXPECT_EQ(GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose),
OnDeviceModelEligibilityReason::kFeatureNotEnabled);
}
IN_PROC_BROWSER_TEST_F(
ModelExecutionEnabledOnDeviceDisabledBrowserTest,
GetOnDeviceModelEligibilityExecutionDisabledNullDebugReason) {
EXPECT_NE(GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose),
OnDeviceModelEligibilityReason::kSuccess);
}
class ModelExecutionEnabledBrowserTest : public ModelExecutionBrowserTestBase {
public:
void InitializeFeatureList() override {
scoped_feature_list_.InitWithFeatures(
{features::kOptimizationGuideModelExecution,
features::kModelQualityLogging,
features::kOptimizationGuideOnDeviceModel},
{});
}
OptimizationGuideKeyedService* GetOptGuideKeyedService() {
return OptimizationGuideKeyedServiceFactory::GetForProfile(
browser()->profile());
}
bool IsSettingVisible(UserVisibleFeatureKey feature) {
return GetOptGuideKeyedService()->IsSettingVisible(feature);
}
bool ShouldFeatureBeCurrentlyEnabledForUser(UserVisibleFeatureKey feature) {
return GetOptGuideKeyedService()
->model_execution_features_controller_
->ShouldFeatureBeCurrentlyEnabledForUser(feature);
}
bool ShouldFeatureBeCurrentlyAllowedForLogging(
proto::LogAiDataRequest::FeatureCase feature) {
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(feature);
return GetOptGuideKeyedService()
->model_execution_features_controller_
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata);
}
};
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionDisabledInIncognito) {
Browser* otr_browser = CreateIncognitoBrowser(browser()->profile());
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request,
otr_browser->profile());
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_FALSE(model_execution_result_->response.has_value());
EXPECT_EQ(OptimizationGuideModelExecutionError::ModelExecutionError::
kPermissionDenied,
model_execution_result_->response.error().error());
EXPECT_FALSE(model_execution_result_->response.error().transient());
// The logs shouldn't be uploaded because model execution is disabled for
// incognito and we wouldn't be receiving any log entry.
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus", 0);
}
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionFailsNoUserSignIn) {
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_FALSE(model_execution_result_->response.has_value());
EXPECT_EQ(OptimizationGuideModelExecutionError::ModelExecutionError::
kPermissionDenied,
model_execution_result_->response.error().error());
EXPECT_FALSE(model_execution_result_->response.error().transient());
// The logs shouldn't be uploaded because model execution is denied without
// user signin, also model quality logs.
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus", 0);
}
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionSuccess_WithoutMetricsConsent) {
EnableSignin();
SetMetricsConsent(false);
SetExpectedBearerAccessToken("Bearer access_token");
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_TRUE(model_execution_result_->response.has_value());
auto response = ParsedAnyMetadata<proto::ComposeResponse>(
model_execution_result_->response.value());
EXPECT_EQ("foo response", response->output());
// The logs shouldn't be uploaded because there is no metrics consent.
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
ModelQualityLogsUploadStatus::kMetricsReportingDisabled, 1);
}
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionSuccess_WithMetricsConsent) {
EnableSignin();
SetMetricsConsent(true);
SetExpectedBearerAccessToken("Bearer access_token");
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_TRUE(model_execution_result_->response.has_value());
auto response = ParsedAnyMetadata<proto::ComposeResponse>(
model_execution_result_->response.value());
EXPECT_EQ("foo response", response->output());
WaitForModelQualityLogsUpload(1);
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
ModelQualityLogsUploadStatus::kUploadSuccessful, 1);
}
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionFailsForUnsuccessfulResponse) {
EnableSignin();
SetExpectedBearerAccessToken("Bearer access_token");
SetResponseType(ModelExecutionRemoteResponseType::kUnsuccessful);
// Enable metrics consent for logging.
SetMetricsConsent(true);
ASSERT_TRUE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_FALSE(model_execution_result_->response.has_value());
EXPECT_EQ(OptimizationGuideModelExecutionError::ModelExecutionError::
kGenericFailure,
model_execution_result_->response.error().error());
EXPECT_TRUE(model_execution_result_->response.error().transient());
// The logs shouldn't be uploaded when model execution fails for unsuccessful
// response.
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus", 0);
}
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionFailsForMalformedResponse) {
EnableSignin();
SetExpectedBearerAccessToken("Bearer access_token");
SetResponseType(ModelExecutionRemoteResponseType::kMalformed);
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_FALSE(model_execution_result_->response.has_value());
EXPECT_EQ(OptimizationGuideModelExecutionError::ModelExecutionError::
kGenericFailure,
model_execution_result_->response.error().error());
EXPECT_TRUE(model_execution_result_->response.error().transient());
}
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionFailsForErrorFilteredResponse) {
EnableSignin();
SetExpectedBearerAccessToken("Bearer access_token");
SetResponseType(ModelExecutionRemoteResponseType::kErrorFiltered);
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_FALSE(model_execution_result_->response.has_value());
EXPECT_EQ(
OptimizationGuideModelExecutionError::ModelExecutionError::kFiltered,
model_execution_result_->response.error().error());
}
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
ModelExecutionFailsForUnsupportedLanguageResponse) {
EnableSignin();
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kCompose),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
SetExpectedBearerAccessToken("Bearer access_token");
SetResponseType(ModelExecutionRemoteResponseType::kUnsupportedLanguage);
// Enable metrics consent for logging.
SetMetricsConsent(true);
ASSERT_TRUE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_FALSE(model_execution_result_->response.has_value());
EXPECT_EQ(OptimizationGuideModelExecutionError::ModelExecutionError::
kUnsupportedLanguage,
model_execution_result_->response.error().error());
// There should be no error-status reports about log uploading (we don't try
// to upload logs in this test, so there's no success report either).
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
0);
}
// TODO(crbug.com/388544208): Flaky on linux-win-cross-rel.
#if BUILDFLAG(IS_WIN)
#define MAYBE_GetOnDeviceModelEligibilityModelNotEligible \
DISABLED_GetOnDeviceModelEligibilityModelNotEligible
#else
#define MAYBE_GetOnDeviceModelEligibilityModelNotEligible \
GetOnDeviceModelEligibilityModelNotEligible
#endif
IN_PROC_BROWSER_TEST_F(ModelExecutionEnabledBrowserTest,
MAYBE_GetOnDeviceModelEligibilityModelNotEligible) {
EXPECT_EQ(GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose),
OnDeviceModelEligibilityReason::kModelNotEligible);
}
IN_PROC_BROWSER_TEST_F(
ModelExecutionEnabledBrowserTest,
GetOnDeviceModelEligibilityExecutionDisabledNullDebugReason) {
EXPECT_NE(GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose),
OnDeviceModelEligibilityReason::kSuccess);
}
class OnDeviceModelExecutionEnabledBrowserTest
: public ModelExecutionEnabledBrowserTest {
public:
void InitializeFeatureList() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{features::kOptimizationGuideModelExecution, {}},
{features::kModelQualityLogging, {}},
{features::kOptimizationGuideOnDeviceModel, {}},
{features::kOnDeviceModelPerformanceParams,
{{"compatible_on_device_performance_classes", "*"}}}},
{});
}
void SetUpGlobalAssets() {
model_execution::prefs::RecordFeatureUsage(
g_browser_process->local_state(), ModelBasedCapabilityKey::kCompose);
base_model_asset_.SetReadyIn(
*OnDeviceModelComponentStateManager::GetInstanceForTesting());
}
// Set up assets which are registered per-profile.
void SetUpProfileAssets() {
compose_asset_.SendTo(
*ChromeOnDeviceModelServiceController::GetSingleInstanceMayBeNull());
}
private:
optimization_guide::FakeBaseModelAsset base_model_asset_;
FakeAdaptationAsset compose_asset_{{
.config =
[]() {
proto::OnDeviceModelExecutionFeatureConfig config;
config.set_feature(proto::MODEL_EXECUTION_FEATURE_COMPOSE);
config.set_can_skip_text_safety(true);
auto* params = config.mutable_sampling_params();
params->set_top_k(kTestDefaultTopK);
params->set_temperature(kTestDefaultTemperature);
return config;
}(),
}};
};
IN_PROC_BROWSER_TEST_F(OnDeviceModelExecutionEnabledBrowserTest,
GetOnDeviceModelEligibilityInRegularProfile) {
SetUpGlobalAssets();
SetUpProfileAssets();
ASSERT_TRUE(base::test::RunUntil([&]() {
return GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose,
nullptr) ==
OnDeviceModelEligibilityReason::kSuccess;
})) << "Timeout waiting for model to be marked eligible.";
}
IN_PROC_BROWSER_TEST_F(OnDeviceModelExecutionEnabledBrowserTest,
GetOnDeviceModelEligibilityInIncognito) {
SetUpGlobalAssets();
Browser* otr_browser = CreateIncognitoBrowser();
SetUpProfileAssets();
ASSERT_TRUE(base::test::RunUntil([&]() {
return GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose,
otr_browser->profile()) ==
OnDeviceModelEligibilityReason::kSuccess;
})) << "Timeout waiting for model to be marked eligible.";
}
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
// Guest profile only available in some platforms.
IN_PROC_BROWSER_TEST_F(OnDeviceModelExecutionEnabledBrowserTest,
GetOnDeviceModelEligibilityInGuestProfile) {
SetUpGlobalAssets();
Browser* guest_browser = CreateGuestBrowser();
SetUpProfileAssets();
ASSERT_TRUE(base::test::RunUntil([&]() {
return GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose,
guest_browser->profile()) ==
OnDeviceModelEligibilityReason::kSuccess;
})) << "Timeout waiting for model to be marked eligible.";
}
#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(OnDeviceModelExecutionEnabledBrowserTest,
GetSamplingParamsConfig) {
SetUpGlobalAssets();
SetUpProfileAssets();
ASSERT_TRUE(base::test::RunUntil([&]() {
return GetOnDeviceModelEligibility(ModelBasedCapabilityKey::kCompose,
nullptr) ==
OnDeviceModelEligibilityReason::kSuccess;
})) << "Timeout waiting for model to be marked eligible.";
auto sampling_config =
GetOptimizationGuideKeyedService()->GetSamplingParamsConfig(
ModelBasedCapabilityKey::kCompose);
EXPECT_EQ(sampling_config->default_top_k, kTestDefaultTopK);
EXPECT_EQ(sampling_config->default_temperature, kTestDefaultTemperature);
}
class ModelExecutionInternalsPageBrowserTest
: public ModelExecutionEnabledBrowserTest {
public:
void SetUpCommandLine(base::CommandLine* cmd) override {
ModelExecutionEnabledBrowserTest::SetUpCommandLine(cmd);
cmd->AppendSwitch(switches::kDebugLoggingEnabled);
}
void CheckInternalsLog(std::string_view message) {
auto* logger =
GetOptimizationGuideKeyedService()->GetOptimizationGuideLogger();
EXPECT_THAT(logger->recent_log_messages_,
testing::Contains(testing::Field(
&OptimizationGuideLogger::LogMessage::message,
testing::HasSubstr(message))));
}
};
IN_PROC_BROWSER_TEST_F(ModelExecutionInternalsPageBrowserTest,
LoggedInInternalsPage) {
EnableSignin();
SetExpectedBearerAccessToken("Bearer access_token");
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("foo");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_TRUE(model_execution_result_->response.has_value());
CheckInternalsLog("ExecuteModel");
// CheckInternalsLog("TabOrganization Request");
CheckInternalsLog("OnModelExecutionResponse");
}
class ModelExecutionEnabledBrowserTestWithExplicitBrowserSignin
: public ModelExecutionEnabledBrowserTest {
public:
void InitializeFeatureList() override {
scoped_feature_list_.InitWithFeatures(
{features::internal::kHistorySearchSettingsVisibility},
{features::internal::kTabOrganizationGraduated});
}
};
IN_PROC_BROWSER_TEST_F(
ModelExecutionEnabledBrowserTestWithExplicitBrowserSignin,
PRE_EnableFeatureViaPref) {
EnableSignin();
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kTabOrganization),
static_cast<int>(prefs::FeatureOptInState::kDisabled));
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtStartup.Compose", false,
1);
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtStartup."
"TabOrganization",
false, 1);
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtStartup."
"WallpaperSearch",
false, 1);
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelExecution.FeatureEnabledAtSettingsChange.Compose",
0);
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtSettingsChange."
"TabOrganization",
false, 1);
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtSettingsChange."
"WallpaperSearch",
true, 1);
}
IN_PROC_BROWSER_TEST_F(
ModelExecutionEnabledBrowserTestWithExplicitBrowserSignin,
EnableFeatureViaPref) {
#if !BUILDFLAG(IS_CHROMEOS)
EXPECT_TRUE(IsSignedIn());
#endif
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtStartup.Compose", false,
1);
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtStartup."
"TabOrganization",
false, 1);
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelExecution.FeatureEnabledAtStartup."
"WallpaperSearch",
false, 1);
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelExecution.FeatureEnabledAtSettingsChange.Compose",
0);
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelExecution.FeatureEnabledAtSettingsChange."
"TabOrganization",
0);
histogram_tester_.ExpectTotalCount(
"OptimizationGuide.ModelExecution.FeatureEnabledAtSettingsChange."
"WallpaperSearch",
0);
}
IN_PROC_BROWSER_TEST_F(
ModelExecutionEnabledBrowserTestWithExplicitBrowserSignin,
PRE_HistorySearchRecordsSyntheticFieldTrial) {
EnableSignin();
#if BUILDFLAG(BUILD_TFLITE_WITH_XNNPACK)
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kHistorySearch));
#else
EXPECT_FALSE(IsSettingVisible(UserVisibleFeatureKey::kHistorySearch));
#endif
browser()->profile()->GetPrefs()->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kHistorySearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
EXPECT_TRUE(variations::IsInSyntheticTrialGroup(
"SyntheticModelExecutionFeatureHistorySearch", "Disabled"));
}
IN_PROC_BROWSER_TEST_F(
ModelExecutionEnabledBrowserTestWithExplicitBrowserSignin,
HistorySearchRecordsSyntheticFieldTrial) {
#if !BUILDFLAG(IS_CHROMEOS)
EXPECT_TRUE(IsSignedIn());
#endif
EXPECT_TRUE(ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kHistorySearch));
EXPECT_TRUE(variations::IsInSyntheticTrialGroup(
"SyntheticModelExecutionFeatureHistorySearch", "Enabled"));
}
class ModelExecutionComposeLoggingDisabledTest
: public ModelExecutionEnabledBrowserTest {
public:
void InitializeFeatureList() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{features::kOptimizationGuideModelExecution, {}},
{features::kModelQualityLogging, {}}},
{features::kComposeMqlsLogging});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(ModelExecutionComposeLoggingDisabledTest,
LoggingForFeatureNotEnabled) {
EnableSignin();
SetExpectedBearerAccessToken("Bearer access_token");
// Enable metrics consent for logging.
SetMetricsConsent(true);
ASSERT_TRUE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
proto::ComposeRequest request;
request.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request);
EXPECT_TRUE(model_execution_result_.has_value());
EXPECT_TRUE(model_execution_result_->response.has_value());
auto response = ParsedAnyMetadata<proto::ComposeResponse>(
model_execution_result_->response.value());
EXPECT_EQ("foo response", response->output());
// The logs shouldn't be uploaded because the feature is not enabled for
// logging.
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
ModelQualityLogsUploadStatus::kLoggingNotEnabled, 1);
}
class ModelExecutionNewFeaturesEnabledAutomaticallyTest
: public ModelExecutionEnabledBrowserTest {
public:
void InitializeFeatureList() override {
std::vector<base::test::FeatureRefAndParams> enabled_features = {
{features::kOptimizationGuideModelExecution, {}},
{features::internal::kTabOrganizationSettingsVisibility, {}}};
std::vector<base::test::FeatureRef> disabled_features = {
features::internal::kTabOrganizationGraduated,
features::internal::kComposeGraduated};
std::string test_name =
::testing::UnitTest::GetInstance()->current_test_info()->name();
// Make the new feature visible in the second start of the test.
if (!base::StartsWith(test_name, "PRE_")) {
enabled_features.push_back(
{features::internal::kComposeSettingsVisibility, {}});
enabled_features.push_back(
{features::internal::kHistorySearchSettingsVisibility,
{{"enable_feature_when_main_toggle_on", "false"}}});
} else {
disabled_features.push_back(
features::internal::kHistorySearchSettingsVisibility);
}
scoped_feature_list_.InitWithFeaturesAndParameters(enabled_features,
disabled_features);
}
};
#if !BUILDFLAG(IS_ANDROID)
class ModelExecutionEnterprisePolicyBrowserTest
: public ModelExecutionEnabledBrowserTest,
public ::testing::WithParamInterface<bool> {
public:
void SetUp() override {
policy_provider_.SetDefaultReturns(
/*is_initialization_complete_return=*/true,
/*is_first_policy_load_complete_return=*/true);
policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
&policy_provider_);
ModelExecutionEnabledBrowserTest::SetUp();
}
void InitializeFeatureList() override {
std::vector<base::test::FeatureRef> enabled_features = {
features::kOptimizationGuideModelExecution,
features::kModelQualityLogging,
features::internal::kTabOrganizationSettingsVisibility,
features::internal::kWallpaperSearchSettingsVisibility};
std::vector<base::test::FeatureRef> disabled_features = {
features::internal::kComposeGraduated,
features::internal::kComposeSettingsVisibility,
features::internal::kTabOrganizationGraduated,
features::internal::kWallpaperSearchGraduated};
if (ShowEnterpriseDisabledFeatures()) {
enabled_features.push_back(features::kAiSettingsPageEnterpriseDisabledUi);
} else {
disabled_features.push_back(
features::kAiSettingsPageEnterpriseDisabledUi);
}
scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
}
bool ShowEnterpriseDisabledFeatures() { return GetParam(); }
protected:
testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_;
};
IN_PROC_BROWSER_TEST_P(ModelExecutionEnterprisePolicyBrowserTest,
EnableComposeWithoutLogging) {
EnableSignin();
SetExpectedBearerAccessToken("Bearer access_token");
SetResponseType(ModelExecutionRemoteResponseType::kUnsupportedLanguage);
// Enable metrics consent for logging.
SetMetricsConsent(true);
ASSERT_TRUE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kCompose),
static_cast<int>(optimization_guide::prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
// Enable without logging via the enterprise policy.
policy::PolicyMap policies;
policies.Set(policy::key::kHelpMeWriteSettings,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
base::Value(static_cast<int>(
model_execution::prefs::ModelExecutionEnterprisePolicyValue::
kAllowWithoutLogging)),
nullptr);
policy_provider_.UpdateChromePolicy(policies);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
EXPECT_TRUE(
ShouldFeatureBeCurrentlyEnabledForUser(UserVisibleFeatureKey::kCompose));
proto::ComposeRequest request_1;
request_1.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request_1);
// The logs should be disabled via enterprise policy.
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
ModelQualityLogsUploadStatus::kDisabledDueToEnterprisePolicy, 1);
// Enable via the enterprise policy and check upload.
policies.Set(
policy::key::kHelpMeWriteSettings, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
base::Value(static_cast<int>(
model_execution::prefs::ModelExecutionEnterprisePolicyValue::kAllow)),
nullptr);
policy_provider_.UpdateChromePolicy(policies);
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kCompose),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
EXPECT_TRUE(
ShouldFeatureBeCurrentlyEnabledForUser(UserVisibleFeatureKey::kCompose));
proto::ComposeRequest request_2;
request_2.mutable_generate_params()->set_user_input("a user typed this");
ExecuteModel(UserVisibleFeatureKey::kCompose, request_2);
// No new blocked logs samples should have been recorded.
histogram_tester_.ExpectUniqueSample(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
optimization_guide::ModelQualityLogsUploadStatus::
kDisabledDueToEnterprisePolicy,
1);
}
IN_PROC_BROWSER_TEST_P(ModelExecutionEnterprisePolicyBrowserTest,
DisableThenEnableWallpaperSearch) {
EnableSignin();
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
// Default policy value allows the feature.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_TRUE(ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
// Disable via the enterprise policy.
policy::PolicyMap policies;
policies.Set(policy::key::kCreateThemesSettings,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
base::Value(static_cast<int>(
model_execution::prefs::ModelExecutionEnterprisePolicyValue::
kDisable)),
nullptr);
policy_provider_.UpdateChromePolicy(policies);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(ShowEnterpriseDisabledFeatures(),
IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
// Enable via the enterprise policy.
policies.Set(
policy::key::kCreateThemesSettings, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
base::Value(static_cast<int>(
model_execution::prefs::ModelExecutionEnterprisePolicyValue::kAllow)),
nullptr);
policy_provider_.UpdateChromePolicy(policies);
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_TRUE(ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
}
INSTANTIATE_TEST_SUITE_P(,
ModelExecutionEnterprisePolicyBrowserTest,
::testing::Bool());
#endif // !BUILDFLAG(IS_ANDROID)
} // namespace optimization_guide
|