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 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
|
// Copyright 2019 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/optimization_guide/optimization_guide_keyed_service.h"
#include <memory>
#include "base/base64.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/strings/escape.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.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/browser_test_util.h"
#include "chrome/browser/optimization_guide/chrome_hints_manager.h"
#include "chrome/browser/optimization_guide/chrome_model_quality_logs_uploader_service.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/profile_waiter.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/mqls_feature_registry.h"
#include "components/optimization_guide/core/filters/optimization_hints_component_update_listener.h"
#include "components/optimization_guide/core/filters/test_hints_component_creator.h"
#include "components/optimization_guide/core/hints/command_line_top_host_provider.h"
#include "components/optimization_guide/core/hints/optimization_guide_store.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_features_controller.h"
#include "components/optimization_guide/core/model_execution/model_execution_prefs.h"
#include "components/optimization_guide/core/model_execution/on_device_model_component.h"
#include "components/optimization_guide/core/optimization_guide_enums.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/core/optimization_guide_prefs.h"
#include "components/optimization_guide/core/optimization_guide_switches.h"
#include "components/optimization_guide/proto/hints.pb.h"
#include "components/optimization_guide/proto/model_quality_service.pb.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/account_capabilities_test_mutator.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/variations/active_field_trials.h"
#include "components/variations/hashing.h"
#include "components/variations/service/variations_service.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source.h"
#include "services/network/public/cpp/network_connection_tracker.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/on_device_model/public/cpp/features.h"
namespace optimization_guide {
using model_execution::prefs::ModelExecutionEnterprisePolicyValue;
using ::testing::ElementsAre;
namespace {
using proto::OptimizationType;
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_;
};
// A WebContentsObserver that asks whether an optimization type can be applied.
class OptimizationGuideConsumerWebContentsObserver
: public content::WebContentsObserver {
public:
OptimizationGuideConsumerWebContentsObserver(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents) {}
~OptimizationGuideConsumerWebContentsObserver() override = default;
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override {
if (callback_) {
OptimizationGuideKeyedService* service =
OptimizationGuideKeyedServiceFactory::GetForProfile(
Profile::FromBrowserContext(web_contents()->GetBrowserContext()));
service->CanApplyOptimization(navigation_handle->GetURL(),
proto::NOSCRIPT, std::move(callback_));
}
}
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override {
OptimizationGuideKeyedService* service =
OptimizationGuideKeyedServiceFactory::GetForProfile(
Profile::FromBrowserContext(web_contents()->GetBrowserContext()));
last_can_apply_optimization_decision_ = service->CanApplyOptimization(
navigation_handle->GetURL(), proto::NOSCRIPT,
/*optimization_metadata=*/nullptr);
}
// Returns the last optimization guide decision that was returned by the
// OptimizationGuideKeyedService's CanApplyOptimization() method.
OptimizationGuideDecision last_can_apply_optimization_decision() {
return last_can_apply_optimization_decision_;
}
void set_callback(OptimizationGuideDecisionCallback callback) {
callback_ = std::move(callback);
}
private:
OptimizationGuideDecision last_can_apply_optimization_decision_ =
OptimizationGuideDecision::kUnknown;
OptimizationGuideDecisionCallback callback_;
};
// A WebContentsObserver that specifically calls the new API that automatically
// decided whether to use the sync or async api in the background.
class OptimizationGuideNewApiConsumerWebContentsObserver
: public content::WebContentsObserver {
public:
OptimizationGuideNewApiConsumerWebContentsObserver(
content::WebContents* web_contents,
OptimizationGuideDecisionCallback callback)
: content::WebContentsObserver(web_contents),
callback_(std::move(callback)) {}
~OptimizationGuideNewApiConsumerWebContentsObserver() override = default;
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override {
if (callback_) {
OptimizationGuideKeyedService* service =
OptimizationGuideKeyedServiceFactory::GetForProfile(
Profile::FromBrowserContext(web_contents()->GetBrowserContext()));
service->CanApplyOptimization(navigation_handle->GetURL(),
proto::NOSCRIPT, std::move(callback_));
}
}
private:
OptimizationGuideDecisionCallback callback_;
};
} // namespace
class OptimizationGuideKeyedServiceDisabledBrowserTest
: public InProcessBrowserTest {
public:
OptimizationGuideKeyedServiceDisabledBrowserTest() {
feature_list_.InitWithFeatures({}, {features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceDisabledBrowserTest,
KeyedServiceEnabledButOptimizationHintsDisabled) {
EXPECT_EQ(nullptr, OptimizationGuideKeyedServiceFactory::GetForProfile(
browser()->profile()));
}
class OptimizationGuideKeyedServiceBrowserTest
: public OptimizationGuideKeyedServiceDisabledBrowserTest {
public:
OptimizationGuideKeyedServiceBrowserTest()
: network_connection_tracker_(
network::TestNetworkConnectionTracker::CreateInstance()) {
// Enable visibility of tab organization feature.
scoped_feature_list_.InitWithFeaturesAndParameters(
/*enabled_features=*/
{{features::kOptimizationHints, {}},
{features::kOptimizationGuideModelExecution, {}},
{features::internal::kComposeSettingsVisibility, {}},
{features::internal::kWallpaperSearchSettingsVisibility, {}},
{on_device_model::features::kUseFakeChromeML, {}},
{features::kLogOnDeviceMetricsOnStartup,
{
{"on_device_startup_metric_delay", "0"},
}},
{features::internal::kTabOrganizationSettingsVisibility,
{{"allow_unsigned_user", "true"}}}},
/*disabled_features=*/
{features::internal::kWallpaperSearchGraduated,
features::internal::kComposeGraduated,
features::internal::kTabOrganizationGraduated});
}
OptimizationGuideKeyedServiceBrowserTest(
const OptimizationGuideKeyedServiceBrowserTest&) = delete;
OptimizationGuideKeyedServiceBrowserTest& operator=(
const OptimizationGuideKeyedServiceBrowserTest&) = delete;
~OptimizationGuideKeyedServiceBrowserTest() override = default;
void SetUpCommandLine(base::CommandLine* cmd) override {
cmd->AppendSwitch(switches::kPurgeHintsStore);
}
void SetUp() override {
policy_provider_.SetDefaultReturns(
/*is_initialization_complete_return=*/true,
/*is_first_policy_load_complete_return=*/true);
policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
&policy_provider_);
InProcessBrowserTest::SetUp();
}
void SetUpBrowserContextKeyedServices(
content::BrowserContext* context) override {
OptimizationGuideKeyedServiceDisabledBrowserTest::
SetUpBrowserContextKeyedServices(context);
IdentityTestEnvironmentProfileAdaptor::
SetIdentityTestEnvironmentFactoriesOnBrowserContext(context);
// Note: Behavior for unofficial builds is tested by unit tests.
SetIsOfficialBuildForTesting(true);
}
void SetUpOnMainThread() override {
OptimizationGuideKeyedServiceDisabledBrowserTest::SetUpOnMainThread();
https_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_->ServeFilesFromSourceDirectory(GetChromeTestDataDir());
https_server_->RegisterRequestHandler(base::BindRepeating(
&OptimizationGuideKeyedServiceBrowserTest::HandleRequest,
base::Unretained(this)));
ASSERT_TRUE(https_server_->Start());
url_with_hints_ = https_server_->GetURL("/simple.html");
url_that_redirects_ =
https_server_->GetURL("/redirect?" + url_with_hints_.spec());
url_that_redirects_to_no_hints_ =
https_server_->GetURL("/redirect?https://nohints.com/");
SetConnectionType(network::mojom::ConnectionType::CONNECTION_2G);
identity_test_env_adaptor_ =
std::make_unique<IdentityTestEnvironmentProfileAdaptor>(
browser()->profile());
}
void TearDownOnMainThread() override {
EXPECT_TRUE(https_server_->ShutdownAndWaitUntilComplete());
OptimizationGuideKeyedServiceDisabledBrowserTest::TearDownOnMainThread();
}
void RegisterWithKeyedService() {
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile())
->RegisterOptimizationTypes({proto::NOSCRIPT});
// Set up an OptimizationGuideKeyedService consumer.
consumer_ = std::make_unique<OptimizationGuideConsumerWebContentsObserver>(
browser()->tab_strip_model()->GetActiveWebContents());
}
void CanApplyOptimizationOnDemand(
const std::vector<GURL>& urls,
const std::vector<proto::OptimizationType>& optimization_types,
OnDemandOptimizationGuideDecisionRepeatingCallback callback) {
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile())
->CanApplyOptimizationOnDemand(urls, optimization_types,
proto::CONTEXT_BATCH_UPDATE_ACTIVE_TABS,
callback);
}
PredictionManager* prediction_manager() {
auto* optimization_guide_keyed_service =
OptimizationGuideKeyedServiceFactory::GetForProfile(
browser()->profile());
return optimization_guide_keyed_service->GetPredictionManager();
}
void PushHintsComponentAndWaitForCompletion() {
RetryForHistogramUntilCountReached(
histogram_tester(),
"OptimizationGuide.HintsManager.HintCacheInitialized", 1);
base::RunLoop run_loop;
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile())
->GetHintsManager()
->ListenForNextUpdateForTesting(run_loop.QuitClosure());
const HintsComponentInfo& component_info =
test_hints_component_creator_.CreateHintsComponentInfoWithPageHints(
proto::NOSCRIPT, {url_with_hints_.host()}, "simple.html");
OptimizationHintsComponentUpdateListener::GetInstance()
->MaybeUpdateHintsComponent(component_info);
run_loop.Run();
}
// Sets the connection type that the Network Connection Tracker will report.
void SetConnectionType(network::mojom::ConnectionType connection_type) {
network_connection_tracker_->SetConnectionType(connection_type);
}
// Sets the callback on the consumer of the OptimizationGuideKeyedService. If
// set, this will call the async version of CanApplyOptimization.
void SetCallbackOnConsumer(OptimizationGuideDecisionCallback callback) {
ASSERT_TRUE(consumer_);
consumer_->set_callback(std::move(callback));
}
// Returns the last decision from the CanApplyOptimization() method seen by
// the consumer of the OptimizationGuideKeyedService.
OptimizationGuideDecision last_can_apply_optimization_decision() {
return consumer_->last_can_apply_optimization_decision();
}
OptimizationGuideKeyedService* service() {
auto* profile = browser()->profile();
return OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
}
ModelExecutionFeaturesController* model_execution_features_controller() {
return service()->model_execution_features_controller_.get();
}
std::unique_ptr<ModelQualityLogEntry> GetModelQualityLogEntryForCompose() {
auto log_entry = std::make_unique<ModelQualityLogEntry>(
service()->GetModelQualityLogsUploaderService()->GetWeakPtr());
*log_entry->log_ai_data_request()->mutable_compose() =
proto::ComposeLoggingData();
return log_entry;
}
GURL url_with_hints() { return url_with_hints_; }
GURL url_that_redirects_to_hints() { return url_that_redirects_; }
GURL url_that_redirects_to_no_hints() {
return url_that_redirects_to_no_hints_;
}
base::HistogramTester* histogram_tester() { return &histogram_tester_; }
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);
}
void SignOut() {
identity_test_env_adaptor_->identity_test_env()->ClearPrimaryAccount();
}
bool IsSettingVisible(UserVisibleFeatureKey feature) {
return OptimizationGuideKeyedServiceFactory::GetForProfile(
browser()->profile())
->IsSettingVisible(feature);
}
void SetMetricsConsent(bool consent) {
scoped_metrics_consent_.emplace(consent);
}
void EnableFeature(UserVisibleFeatureKey feature) {
// Sign in must be enabled as a prerequisite for enabling any user-visible
// feature.
EnableSignIn();
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(prefs::GetSettingEnabledPrefName(feature),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
}
void SetEnterprisePolicy(const std::string& key,
ModelExecutionEnterprisePolicyValue value) {
// Enable logging via the enterprise policy.
policies_.Set(key, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
base::Value(static_cast<int>(value)), nullptr);
policy_provider_.UpdateChromePolicy(policies_);
base::RunLoop().RunUntilIdle();
}
void SetIsDogfoodClient(bool is_dogfood_client) {
g_browser_process->variations_service()->SetIsLikelyDogfoodClientForTesting(
is_dogfood_client);
}
void SetIsOfficialBuildForTesting(bool is_official_build) {
OptimizationGuideKeyedService::SetIsOfficialBuildForTesting(
is_official_build);
}
protected:
base::test::ScopedFeatureList scoped_feature_list_;
::testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_;
private:
std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
const net::test_server::HttpRequest& request) {
if (request.GetURL().spec().find("redirect") == std::string::npos) {
return nullptr;
}
GURL request_url = request.GetURL();
std::string dest =
base::UnescapeBinaryURLComponent(request_url.query_piece());
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_FOUND);
http_response->AddCustomHeader("Location", dest);
return http_response;
}
std::unique_ptr<net::EmbeddedTestServer> https_server_;
GURL url_with_hints_;
GURL url_that_redirects_;
GURL url_that_redirects_to_no_hints_;
std::optional<ScopedSetMetricsConsent> scoped_metrics_consent_;
std::unique_ptr<network::TestNetworkConnectionTracker>
network_connection_tracker_;
// Enterprise policies. Stored as a member variable because each call to
// `UpdateChromePolicy` clears previous updates; so accumulate the policies
// in this `PolicyMap` instead.
policy::PolicyMap policies_;
testing::TestHintsComponentCreator test_hints_component_creator_;
std::unique_ptr<OptimizationGuideConsumerWebContentsObserver> consumer_;
// Histogram tester used specifically to capture metrics that are recorded
// during browser initialization.
base::HistogramTester histogram_tester_;
// Identity test support.
std::unique_ptr<IdentityTestEnvironmentProfileAdaptor>
identity_test_env_adaptor_;
};
// Configures the global VariationsService to treat this client as a likely
// dogfood client, before any keyed services are created.
class DogfoodOptimizationGuideKeyedServiceBrowserTest
: public OptimizationGuideKeyedServiceBrowserTest {
public:
DogfoodOptimizationGuideKeyedServiceBrowserTest() = default;
DogfoodOptimizationGuideKeyedServiceBrowserTest(
const OptimizationGuideKeyedServiceBrowserTest&) = delete;
DogfoodOptimizationGuideKeyedServiceBrowserTest& operator=(
const OptimizationGuideKeyedServiceBrowserTest&) = delete;
~DogfoodOptimizationGuideKeyedServiceBrowserTest() override = default;
void SetUpBrowserContextKeyedServices(
content::BrowserContext* context) override {
OptimizationGuideKeyedServiceBrowserTest::SetUpBrowserContextKeyedServices(
context);
SetIsDogfoodClient(true);
}
};
class OptimizationGuideKeyedServiceStartupLogDisabledBrowserTest
: public OptimizationGuideKeyedServiceBrowserTest {
public:
OptimizationGuideKeyedServiceStartupLogDisabledBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
{
{features::kOptimizationGuideOnDeviceModel, {}},
},
{features::kLogOnDeviceMetricsOnStartup});
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
RemoteFetchingDisabled) {
// ChromeOS has multiple profiles and optimization guide currently does not
// run on non-Android.
#if !BUILDFLAG(IS_CHROMEOS)
histogram_tester()->ExpectUniqueSample(
"OptimizationGuide.RemoteFetchingEnabled", false, 1);
EXPECT_TRUE(variations::IsInSyntheticTrialGroup(
"SyntheticOptimizationGuideRemoteFetching", "Disabled"));
#endif
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
NavigateToPageWithAsyncCallbackReturnsAnswerRedirect) {
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
SetCallbackOnConsumer(base::BindOnce(
[](base::RunLoop* run_loop, OptimizationGuideDecision decision,
const OptimizationMetadata& metadata) {
EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
run_loop->Quit();
},
run_loop.get()));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
url_that_redirects_to_no_hints()));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
NavigateToPageWithAsyncCallbackReturnsAnswer) {
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
SetCallbackOnConsumer(base::BindOnce(
[](base::RunLoop* run_loop, OptimizationGuideDecision decision,
const OptimizationMetadata& metadata) {
EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
run_loop->Quit();
},
run_loop.get()));
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_hints()));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
NavigateToPageWithAsyncCallbackReturnsAnswerEventually) {
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
SetCallbackOnConsumer(base::BindOnce(
[](base::RunLoop* run_loop, OptimizationGuideDecision decision,
const OptimizationMetadata& metadata) {
EXPECT_EQ(OptimizationGuideDecision::kFalse, decision);
run_loop->Quit();
},
run_loop.get()));
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL("https://nohints.com/")));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
NavigateToPageWithHintsLoadsHint) {
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
ukm::TestAutoSetUkmRecorder ukm_recorder;
base::HistogramTester histogram_tester;
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_hints()));
EXPECT_GT(RetryForHistogramUntilCountReached(
&histogram_tester, "OptimizationGuide.LoadedHint.Result", 1),
0);
// There is a hint that matches this URL, so there should be an attempt to
// load a hint that succeeds.
histogram_tester.ExpectUniqueSample("OptimizationGuide.LoadedHint.Result",
true, 1);
// We had a hint and it was loaded.
EXPECT_EQ(OptimizationGuideDecision::kTrue,
last_can_apply_optimization_decision());
// Navigate away so metrics get recorded.
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_hints()));
// Expect that UKM is recorded.
auto entries = ukm_recorder.GetEntriesByName(
ukm::builders::OptimizationGuide::kEntryName);
EXPECT_EQ(1u, entries.size());
auto* entry = entries[0].get();
EXPECT_TRUE(ukm_recorder.EntryHasMetric(
entry,
ukm::builders::OptimizationGuide::kRegisteredOptimizationTypesName));
const int64_t* entry_metric = ukm_recorder.GetEntryMetric(
entry,
ukm::builders::OptimizationGuide::kRegisteredOptimizationTypesName);
EXPECT_TRUE(*entry_metric & (1 << proto::NOSCRIPT));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
RecordsMetricsWhenTabHidden) {
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
ukm::TestAutoSetUkmRecorder ukm_recorder;
base::HistogramTester histogram_tester;
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_hints()));
EXPECT_GT(RetryForHistogramUntilCountReached(
&histogram_tester, "OptimizationGuide.LoadedHint.Result", 1),
0);
// There is a hint that matches this URL, so there should be an attempt to
// load a hint that succeeds.
histogram_tester.ExpectUniqueSample("OptimizationGuide.LoadedHint.Result",
true, 1);
// We had a hint and it was loaded.
EXPECT_EQ(OptimizationGuideDecision::kTrue,
last_can_apply_optimization_decision());
// Make sure metrics get recorded when tab is hidden.
browser()->tab_strip_model()->GetActiveWebContents()->WasHidden();
// Expect that the optimization guide UKM is recorded.
auto entries = ukm_recorder.GetEntriesByName(
ukm::builders::OptimizationGuide::kEntryName);
EXPECT_EQ(1u, entries.size());
auto* entry = entries[0].get();
EXPECT_TRUE(ukm_recorder.EntryHasMetric(
entry,
ukm::builders::OptimizationGuide::kRegisteredOptimizationTypesName));
const int64_t* entry_metric = ukm_recorder.GetEntryMetric(
entry,
ukm::builders::OptimizationGuide::kRegisteredOptimizationTypesName);
EXPECT_TRUE(*entry_metric & (1 << proto::NOSCRIPT));
}
IN_PROC_BROWSER_TEST_F(
OptimizationGuideKeyedServiceBrowserTest,
NavigateToPageThatRedirectsToUrlWithHintsShouldAttemptTwoLoads) {
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
base::HistogramTester histogram_tester;
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), url_that_redirects_to_hints()));
EXPECT_EQ(RetryForHistogramUntilCountReached(
&histogram_tester, "OptimizationGuide.LoadedHint.Result", 2),
2);
// Should attempt and succeed to load a hint once for the initial navigation
// and redirect.
histogram_tester.ExpectBucketCount("OptimizationGuide.LoadedHint.Result",
true, 2);
// Hint is still applicable so we expect it to be allowed to be applied.
EXPECT_EQ(OptimizationGuideDecision::kTrue,
last_can_apply_optimization_decision());
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
NavigateToPageWithoutHint) {
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
base::HistogramTester histogram_tester;
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL("https://nohints.com/")));
EXPECT_EQ(RetryForHistogramUntilCountReached(
&histogram_tester, "OptimizationGuide.LoadedHint.Result", 1),
1);
// There were no hints that match this URL, but there should still be an
// attempt to load a hint but still fail.
histogram_tester.ExpectUniqueSample("OptimizationGuide.LoadedHint.Result",
false, 1);
EXPECT_EQ(OptimizationGuideDecision::kFalse,
last_can_apply_optimization_decision());
histogram_tester.ExpectUniqueSample(
"OptimizationGuide.ApplyDecision.NoScript",
static_cast<int>(OptimizationTypeDecision::kNoHintAvailable), 1);
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CheckForBlocklistFilter) {
PushHintsComponentAndWaitForCompletion();
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
{
base::HistogramTester histogram_tester;
// Register an optimization type with an optimization filter.
ogks->RegisterOptimizationTypes({proto::FAST_HOST_HINTS});
// Wait until filter is loaded. This histogram will record twice: once when
// the config is found and once when the filter is created.
RetryForHistogramUntilCountReached(
&histogram_tester,
"OptimizationGuide.OptimizationFilterStatus.FastHostHints", 2);
EXPECT_EQ(
OptimizationGuideDecision::kFalse,
ogks->CanApplyOptimization(GURL("https://blockedhost.com/whatever"),
proto::FAST_HOST_HINTS, nullptr));
histogram_tester.ExpectUniqueSample(
"OptimizationGuide.ApplyDecision.FastHostHints",
static_cast<int>(
OptimizationTypeDecision::kNotAllowedByOptimizationFilter),
1);
}
// Register another type with optimization filter.
{
base::HistogramTester histogram_tester;
ogks->RegisterOptimizationTypes({proto::LITE_PAGE_REDIRECT});
// Wait until filter is loaded. This histogram will record twice: once when
// the config is found and once when the filter is created.
RetryForHistogramUntilCountReached(
&histogram_tester,
"OptimizationGuide.OptimizationFilterStatus.LitePageRedirect", 2);
// The previously loaded filter should still be loaded and give the same
// result.
EXPECT_EQ(
OptimizationGuideDecision::kFalse,
ogks->CanApplyOptimization(GURL("https://blockedhost.com/whatever"),
proto::FAST_HOST_HINTS, nullptr));
histogram_tester.ExpectUniqueSample(
"OptimizationGuide.ApplyDecision.FastHostHints",
static_cast<int>(
OptimizationTypeDecision::kNotAllowedByOptimizationFilter),
1);
}
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CanApplyOptimizationOnDemand) {
PushHintsComponentAndWaitForCompletion();
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
ogks->RegisterOptimizationTypes({proto::OptimizationType::NOSCRIPT,
proto::OptimizationType::FAST_HOST_HINTS});
base::HistogramTester histogram_tester;
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_hints()));
RetryForHistogramUntilCountReached(&histogram_tester,
"OptimizationGuide.LoadedHint.Result", 1);
std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
base::flat_set<GURL> received_callbacks;
CanApplyOptimizationOnDemand(
{url_with_hints(), GURL("https://blockedhost.com/whatever")},
{proto::OptimizationType::NOSCRIPT,
proto::OptimizationType::FAST_HOST_HINTS},
base::BindRepeating(
[](base::RunLoop* run_loop, base::flat_set<GURL>* received_callbacks,
const GURL& url,
const base::flat_map<proto::OptimizationType,
OptimizationGuideDecisionWithMetadata>&
decisions) {
received_callbacks->insert(url);
// Expect one decision per requested type.
EXPECT_EQ(decisions.size(), 2u);
if (received_callbacks->size() == 2) {
run_loop->Quit();
}
},
run_loop.get(), &received_callbacks));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CanApplyOptimizationNewAPI) {
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
ogks->RegisterOptimizationTypes({proto::OptimizationType::NOSCRIPT});
std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>();
// Before the hints or navigation are initiated, we should get a negative
// response.
ogks->CanApplyOptimization(
url_with_hints(), proto::OptimizationType::NOSCRIPT,
base::BindOnce(
[](base::RunLoop* run_loop, OptimizationGuideDecision decision,
const OptimizationMetadata& metadata) {
EXPECT_EQ(decision, OptimizationGuideDecision::kFalse);
run_loop->Quit();
},
run_loop.get()));
run_loop->Run();
// Now attach a WebContentsObserver to make a request while a navigation is
// in progress.
run_loop = std::make_unique<base::RunLoop>();
OptimizationGuideNewApiConsumerWebContentsObserver observer(
browser()->tab_strip_model()->GetActiveWebContents(),
base::BindOnce(
[](base::RunLoop* run_loop, OptimizationGuideDecision decision,
const OptimizationMetadata& metadata) {
EXPECT_EQ(OptimizationGuideDecision::kTrue, decision);
run_loop->Quit();
},
run_loop.get()));
PushHintsComponentAndWaitForCompletion();
RegisterWithKeyedService();
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_hints()));
run_loop->Run();
// After the navigation has finished, we should still be able to query and
// get the correct response.
run_loop = std::make_unique<base::RunLoop>();
ogks->CanApplyOptimization(
url_with_hints(), proto::OptimizationType::NOSCRIPT,
base::BindOnce(
[](base::RunLoop* run_loop, OptimizationGuideDecision decision,
const OptimizationMetadata& metadata) {
EXPECT_EQ(decision, OptimizationGuideDecision::kTrue);
run_loop->Quit();
},
run_loop.get()));
run_loop->Run();
}
class TestSettingsEnabledObserver : public SettingsEnabledObserver {
public:
explicit TestSettingsEnabledObserver(UserVisibleFeatureKey feature)
: SettingsEnabledObserver(feature) {}
void OnChangeInFeatureCurrentlyEnabledState(bool is_now_enabled) override {
count_feature_enabled_state_changes_++;
is_currently_enabled_ = is_now_enabled;
}
int count_feature_enabled_state_changes_ = 0;
bool is_currently_enabled_ = false;
};
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
SettingsVisibilitySignedOutVsSignedIn) {
// User is not signed-in.
EXPECT_FALSE(IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
// Visibility of tab organizer is allowed for unsigned users.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kTabOrganization));
// Visibility of this feature is enabled via finch but the feature is still
// not visible.
EXPECT_FALSE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
// kCompose should now be visible after
// sign-in.
EnableSignIn();
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kTabOrganization));
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
#if !BUILDFLAG(IS_CHROMEOS)
// SignOut not supported on ChromeOS.
SignOut();
// Tab Organizer is visible to unsigned users.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kTabOrganization));
EXPECT_FALSE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
#endif
}
// Verifies that Model Execution Features Controller is available for incognito
// profiles and the visibility of settings is correct.
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
SettingsVisibilityUpdatedCorrectly) {
EnableSignIn();
// Visibility of wallpaper search is enabled on ToT.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
// Visibility of tab organizer is enabled via finch.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kTabOrganization));
// Visibility of compose is enabled via finch.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
// Restarting the browser should cause wallpaper setting to be visible since
// the feature is enabled.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kTabOrganization));
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kDisabled));
// Restarting the browser should cause wallpaper setting to still be visible
// since the feature is still enabled.
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kTabOrganization));
EXPECT_TRUE(IsSettingVisible(UserVisibleFeatureKey::kCompose));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
SettingsOptInRevokedAfterSignOut) {
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
EnableSignIn();
TestSettingsEnabledObserver wallpaper_search_observer(
UserVisibleFeatureKey::kWallpaperSearch);
TestSettingsEnabledObserver compose_observer(UserVisibleFeatureKey::kCompose);
ogks->AddModelExecutionSettingsEnabledObserver(&wallpaper_search_observer);
ogks->AddModelExecutionSettingsEnabledObserver(&compose_observer);
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kTabOrganization));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kCompose));
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
EXPECT_EQ(1, wallpaper_search_observer.count_feature_enabled_state_changes_);
EXPECT_TRUE(wallpaper_search_observer.is_currently_enabled_);
EXPECT_EQ(0, compose_observer.count_feature_enabled_state_changes_);
EXPECT_TRUE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kTabOrganization));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kCompose));
#if !BUILDFLAG(IS_CHROMEOS)
// SignOut not supported on ChromeOS.
SignOut();
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kTabOrganization));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kCompose));
EXPECT_EQ(2, wallpaper_search_observer.count_feature_enabled_state_changes_);
EXPECT_FALSE(wallpaper_search_observer.is_currently_enabled_);
#endif
}
// Verifies that Model Execution Features Controller is available for incognito
// profiles and the setting opt-in toggle and pref is updated correctly.
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
SettingsOptInUpdatedCorrectly) {
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
EnableSignIn();
TestSettingsEnabledObserver wallpaper_search_observer(
UserVisibleFeatureKey::kWallpaperSearch);
TestSettingsEnabledObserver compose_observer(UserVisibleFeatureKey::kCompose);
ogks->AddModelExecutionSettingsEnabledObserver(&wallpaper_search_observer);
ogks->AddModelExecutionSettingsEnabledObserver(&compose_observer);
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kTabOrganization));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kCompose));
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
EXPECT_EQ(1, wallpaper_search_observer.count_feature_enabled_state_changes_);
EXPECT_TRUE(wallpaper_search_observer.is_currently_enabled_);
EXPECT_EQ(0, compose_observer.count_feature_enabled_state_changes_);
EXPECT_TRUE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kTabOrganization));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kCompose));
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kDisabled));
EXPECT_EQ(2, wallpaper_search_observer.count_feature_enabled_state_changes_);
EXPECT_FALSE(wallpaper_search_observer.is_currently_enabled_);
EXPECT_EQ(0, compose_observer.count_feature_enabled_state_changes_);
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kTabOrganization));
EXPECT_FALSE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kCompose));
}
// Verifies that Model Execution Features Controller returns null for incognito
// profiles.
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
SettingsVisibilityIncognito) {
EnableSignIn();
// Set up incognito browser and incognito OptimizationGuideKeyedService
// consumer.
Browser* otr_browser = CreateIncognitoBrowser(browser()->profile());
EXPECT_TRUE(otr_browser);
// Instantiate off the record Optimization Guide Service.
OptimizationGuideKeyedService* otr_ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(
browser()->profile()->GetPrimaryOTRProfile(
/*create_if_needed=*/true));
auto* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
EXPECT_FALSE(otr_ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
}
IN_PROC_BROWSER_TEST_F(
OptimizationGuideKeyedServiceStartupLogDisabledBrowserTest,
PerformanceClassOnlyComputedOnce) {
constexpr auto kKey = optimization_guide::ModelBasedCapabilityKey::kCompose;
auto* service =
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
base::RunLoop loop1;
base::RunLoop loop2;
base::RunLoop loop3;
// Call multiple times, should only get performance class once.
service->GetOnDeviceModelEligibilityAsync(
kKey,
/*capabilities=*/{},
base::IgnoreArgs<optimization_guide::OnDeviceModelEligibilityReason>(
loop1.QuitClosure()));
service->GetOnDeviceModelEligibilityAsync(
kKey,
/*capabilities=*/{},
base::IgnoreArgs<optimization_guide::OnDeviceModelEligibilityReason>(
loop2.QuitClosure()));
service->GetOnDeviceModelEligibilityAsync(
kKey,
/*capabilities=*/{},
base::IgnoreArgs<optimization_guide::OnDeviceModelEligibilityReason>(
loop3.QuitClosure()));
loop1.Run();
histogram_tester()->ExpectTotalCount(
"OptimizationGuide.ModelExecution.OnDeviceModelPerformanceClass", 1);
loop2.Run();
loop3.Run();
histogram_tester()->ExpectTotalCount(
"OptimizationGuide.ModelExecution.OnDeviceModelPerformanceClass", 1);
// Call again after waiting, should not get performance class again..
base::RunLoop loop4;
service->GetOnDeviceModelEligibilityAsync(
kKey,
/*capabilities=*/{},
base::IgnoreArgs<optimization_guide::OnDeviceModelEligibilityReason>(
loop4.QuitClosure()));
loop4.Run();
histogram_tester()->ExpectTotalCount(
"OptimizationGuide.ModelExecution.OnDeviceModelPerformanceClass", 1);
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
LogOnDeviceMetricsAfterStart) {
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
OnDeviceModelComponentStateManager* on_device_component_state_manager =
OnDeviceModelComponentStateManager::GetInstanceForTesting();
ASSERT_TRUE(on_device_component_state_manager);
EXPECT_TRUE(base::test::RunUntil([&]() {
return histogram_tester()
->GetAllSamples(
"OptimizationGuide.ModelExecution."
"OnDeviceModelPerformanceClass")
.size() > 0;
}));
histogram_tester()->ExpectTotalCount(
"OptimizationGuide.ModelExecution.OnDeviceModelPerformanceClass", 1);
}
// Creating multiple profiles isn't supported easily on ChromeOS and android.
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
LogOnDeviceMetricsSingleTimeForMultipleProfiles) {
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
OnDeviceModelComponentStateManager* on_device_component_state_manager =
OnDeviceModelComponentStateManager::GetInstanceForTesting();
ASSERT_TRUE(on_device_component_state_manager);
// Add a second profile which should not log performance class.
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath path = profile_manager->GenerateNextProfileDirectoryPath();
ProfileWaiter profile_waiter;
profile_manager->CreateProfileAsync(path, {});
profile_waiter.WaitForProfileAdded();
EXPECT_TRUE(base::test::RunUntil([&]() {
return histogram_tester()
->GetAllSamples(
"OptimizationGuide.ModelExecution."
"OnDeviceModelPerformanceClass")
.size() > 0;
}));
// Make sure all tasks have finished running.
content::RunAllTasksUntilIdle();
histogram_tester()->ExpectTotalCount(
"OptimizationGuide.ModelExecution.OnDeviceModelPerformanceClass", 1);
}
#endif
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
// CreateGuestBrowser() is not supported for Android or ChromeOS out of the box.
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
GuestProfileUniqueKeyedService) {
Browser* guest_browser = CreateGuestBrowser();
OptimizationGuideKeyedService* guest_ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(
guest_browser->profile());
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
EXPECT_TRUE(guest_ogks);
EXPECT_TRUE(ogks);
EXPECT_NE(guest_ogks, ogks);
auto* prefs = browser()->profile()->GetPrefs();
auto* guest_prefs = guest_browser->profile()->GetPrefs();
EnableSignIn();
prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
guest_prefs->SetInteger(
prefs::GetSettingEnabledPrefName(UserVisibleFeatureKey::kWallpaperSearch),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
EXPECT_TRUE(ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_FALSE(guest_ogks->ShouldFeatureBeCurrentlyEnabledForUser(
UserVisibleFeatureKey::kWallpaperSearch));
}
#endif
// Test the visibility of features with `kOptimizationGuideModelExecution`
// enabled or disabled.
class OptimizationGuideKeyedServiceBrowserWithModelExecutionFeatureDisabledTest
: public ::testing::WithParamInterface<bool>,
public OptimizationGuideKeyedServiceBrowserTest {
public:
OptimizationGuideKeyedServiceBrowserWithModelExecutionFeatureDisabledTest()
: OptimizationGuideKeyedServiceBrowserTest() {
// Enable visibility of tab organization feature.
scoped_feature_list_.Reset();
if (ShouldFeatureBeEnabled()) {
scoped_feature_list_.InitWithFeatures(
{features::kOptimizationHints,
// Enabled.
features::kOptimizationGuideModelExecution,
features::internal::kTabOrganizationSettingsVisibility},
{features::internal::kTabOrganizationGraduated});
} else {
scoped_feature_list_.InitWithFeatures(
{features::kOptimizationHints,
features::internal::kTabOrganizationSettingsVisibility},
// Disabled.
{features::kOptimizationGuideModelExecution,
features::internal::kTabOrganizationGraduated});
}
}
bool ShouldFeatureBeEnabled() const { return GetParam(); }
};
INSTANTIATE_TEST_SUITE_P(
All,
OptimizationGuideKeyedServiceBrowserWithModelExecutionFeatureDisabledTest,
::testing::Bool());
IN_PROC_BROWSER_TEST_P(
OptimizationGuideKeyedServiceBrowserWithModelExecutionFeatureDisabledTest,
SettingsNotVisible) {
EnableSignIn();
EXPECT_EQ(ShouldFeatureBeEnabled(),
IsSettingVisible(UserVisibleFeatureKey::kWallpaperSearch));
EXPECT_EQ(ShouldFeatureBeEnabled(),
IsSettingVisible(UserVisibleFeatureKey::kTabOrganization));
}
class OptimizationGuideKeyedServicePermissionsCheckDisabledTest
: public OptimizationGuideKeyedServiceBrowserTest {
public:
OptimizationGuideKeyedServicePermissionsCheckDisabledTest() = default;
~OptimizationGuideKeyedServicePermissionsCheckDisabledTest() override =
default;
void SetUp() override {
scoped_feature_list_.InitAndEnableFeature(
features::kRemoteOptimizationGuideFetching);
OptimizationGuideKeyedServiceBrowserTest::SetUp();
}
void TearDown() override {
OptimizationGuideKeyedServiceBrowserTest::TearDown();
scoped_feature_list_.Reset();
}
void SetUpCommandLine(base::CommandLine* cmd) override {
OptimizationGuideKeyedServiceBrowserTest::SetUpCommandLine(cmd);
cmd->AppendSwitch(switches::kDisableCheckingUserPermissionsForTesting);
// Add switch to avoid racing navigations in the test.
cmd->AppendSwitch(
switches::kDisableFetchingHintsAtNavigationStartForTesting);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(
OptimizationGuideKeyedServicePermissionsCheckDisabledTest,
RemoteFetchingAllowed) {
// ChromeOS has multiple profiles and optimization guide currently does not
// run on non-Android.
#if !BUILDFLAG(IS_CHROMEOS)
histogram_tester()->ExpectUniqueSample(
"OptimizationGuide.RemoteFetchingEnabled", true, 1);
EXPECT_TRUE(variations::IsInSyntheticTrialGroup(
"SyntheticOptimizationGuideRemoteFetching", "Enabled"));
#endif
}
IN_PROC_BROWSER_TEST_F(
OptimizationGuideKeyedServicePermissionsCheckDisabledTest,
IncognitoCanStillReadFromComponentHints) {
// Wait until initialization logic finishes running and component pushed to
// both incognito and regular browsers.
PushHintsComponentAndWaitForCompletion();
// Set up incognito browser and incognito OptimizationGuideKeyedService
// consumer.
Browser* otr_browser = CreateIncognitoBrowser(browser()->profile());
// Instantiate off the record Optimization Guide Service.
OptimizationGuideKeyedService* otr_ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(
browser()->profile()->GetPrimaryOTRProfile(
/*create_if_needed=*/true));
otr_ogks->RegisterOptimizationTypes({proto::NOSCRIPT});
// Navigate to a URL that has a hint from a component and wait for that hint
// to have loaded.
base::HistogramTester histogram_tester;
ASSERT_TRUE(ui_test_utils::NavigateToURL(otr_browser, url_with_hints()));
RetryForHistogramUntilCountReached(&histogram_tester,
"OptimizationGuide.LoadedHint.Result", 1);
EXPECT_EQ(OptimizationGuideDecision::kTrue,
otr_ogks->CanApplyOptimization(url_with_hints(), proto::NOSCRIPT,
nullptr));
}
IN_PROC_BROWSER_TEST_F(
OptimizationGuideKeyedServicePermissionsCheckDisabledTest,
IncognitoStillProcessesBloomFilter) {
PushHintsComponentAndWaitForCompletion();
CreateIncognitoBrowser(browser()->profile());
// Instantiate off the record Optimization Guide Service.
OptimizationGuideKeyedService* otr_ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(
browser()->profile()->GetPrimaryOTRProfile(
/*create_if_needed=*/true));
base::HistogramTester histogram_tester;
// Register an optimization type with an optimization filter.
otr_ogks->RegisterOptimizationTypes({proto::FAST_HOST_HINTS});
// Wait until filter is loaded. This histogram will record twice: once when
// the config is found and once when the filter is created.
RetryForHistogramUntilCountReached(
&histogram_tester,
"OptimizationGuide.OptimizationFilterStatus.FastHostHints", 2);
EXPECT_EQ(
OptimizationGuideDecision::kFalse,
otr_ogks->CanApplyOptimization(GURL("https://blockedhost.com/whatever"),
proto::FAST_HOST_HINTS, nullptr));
histogram_tester.ExpectUniqueSample(
"OptimizationGuide.ApplyDecision.FastHostHints",
static_cast<int>(
OptimizationTypeDecision::kNotAllowedByOptimizationFilter),
1);
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CheckUploadWithMetricsConsent) {
// Enable metrics consent.
SetMetricsConsent(true);
ASSERT_TRUE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
// Attempt to upload a new quality log.
ModelQualityLogEntry::Upload(GetModelQualityLogEntryForCompose());
// Upload shouldn't be blocked by metrics consent.
histogram_tester()->ExpectBucketCount(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
ModelQualityLogsUploadStatus::kMetricsReportingDisabled, 0);
// Disable metrics consent.
SetMetricsConsent(false);
ASSERT_FALSE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
// Attempt to upload a new quality log.
ModelQualityLogEntry::Upload(GetModelQualityLogEntryForCompose());
// Upload should be disabled as there is no metrics consent, so total
// histogram bucket count will be 1.
histogram_tester()->ExpectBucketCount(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
ModelQualityLogsUploadStatus::kMetricsReportingDisabled, 1);
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CheckUploadWithoutMetricsConsent) {
auto* profile = browser()->profile();
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
// Disable metrics consent.
SetMetricsConsent(false);
ASSERT_FALSE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_FALSE(
ogks->GetModelQualityLogsUploaderService()->CanUploadLogs(metadata));
// Upload should be disabled as there is no metrics consent, so total
// histogram bucket count will be 1.
histogram_tester()->ExpectBucketCount(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus.Compose",
ModelQualityLogsUploadStatus::kMetricsReportingDisabled, 1);
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CheckUploadOnDestructionWithoutMetricsConsent) {
// Disable metrics consent.
SetMetricsConsent(false);
ASSERT_FALSE(
g_browser_process->GetMetricsServicesManager()->IsMetricsConsentGiven());
// Intercept network requests.
network::TestURLLoaderFactory url_loader_factory;
service()
->GetModelQualityLogsUploaderService()
->SetUrlLoaderFactoryForTesting(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&url_loader_factory));
// Create a new ModelQualityLogEntry for compose.
std::unique_ptr<ModelQualityLogEntry> log_entry =
GetModelQualityLogEntryForCompose();
// Destruct the log entry, this should trigger uploading the logs.
log_entry.reset();
// Upload should be stopped on destruction as there is no metrics consent.
base::RunLoop().RunUntilIdle();
content::RunAllTasksUntilIdle();
EXPECT_EQ(0, url_loader_factory.NumPending());
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CheckUploadWithEnterprisePolicy) {
// Enable metrics consent and sign in.
SetMetricsConsent(true);
EnableSignIn();
auto* profile = browser()->profile();
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
auto compose_feature = UserVisibleFeatureKey::kCompose;
auto* prefs = profile->GetPrefs();
prefs->SetInteger(prefs::GetSettingEnabledPrefName(compose_feature),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
policy::PolicyMap policies;
// Disable logging via the enterprise policy to state kAllowWithoutLogging.
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();
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_FALSE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
// Attempt to upload a new quality log.
ModelQualityLogEntry::Upload(GetModelQualityLogEntryForCompose());
// Disable logging via via the enterprise policy to kDisable state.
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::
kDisable)),
nullptr);
policy_provider_.UpdateChromePolicy(policies);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
// Attempt to upload a new quality log.
ModelQualityLogEntry::Upload(GetModelQualityLogEntryForCompose());
// Enable logging via via the enterprise policy to state kAllow this shouldn't
// stop 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(compose_feature),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
EXPECT_TRUE(
ogks->GetModelQualityLogsUploaderService()->CanUploadLogs(metadata));
// Attempt to upload a new quality log.
ModelQualityLogEntry::Upload(GetModelQualityLogEntryForCompose());
// Log uploads should have been recorded as disabled twice because of
// enterprise policy.
EXPECT_THAT(
histogram_tester()->GetAllSamples(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus."
"Compose"),
ElementsAre(base::Bucket(
ModelQualityLogsUploadStatus::kDisabledDueToEnterprisePolicy, 2)));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CheckCanUploadLogsWithEnterprisePolicy) {
// Enable metrics consent and sign in.
SetMetricsConsent(true);
EnableSignIn();
auto* profile = browser()->profile();
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
auto compose_feature = UserVisibleFeatureKey::kCompose;
auto* prefs = profile->GetPrefs();
prefs->SetInteger(prefs::GetSettingEnabledPrefName(compose_feature),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
policy::PolicyMap policies;
// Disable logging via via the enterprise policy to state
// kAllowWithoutLogging this should return
// ChromeModelQualityLogsUploaderService::CanUploadLogs to false.
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();
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_FALSE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
EXPECT_FALSE(
ogks->GetModelQualityLogsUploaderService()->CanUploadLogs(metadata));
// Disable logging via the enterprise policy to kDisable state this should
// return ChromeModelQualityLogsUploaderService::CanUploadLogs to false.
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::
kDisable)),
nullptr);
policy_provider_.UpdateChromePolicy(policies);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
EXPECT_FALSE(
ogks->GetModelQualityLogsUploaderService()->CanUploadLogs(metadata));
// Enable logging via the enterprise policy to state kAllow this shouldn't
// stop upload and should return
// ChromeModelQualityLogsUploaderService::CanUploadLogs to true.
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(compose_feature),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
EXPECT_TRUE(
ogks->GetModelQualityLogsUploaderService()->CanUploadLogs(metadata));
// Log uploads should have been recorded as disabled twice because of
// enterprise policy.
EXPECT_THAT(
histogram_tester()->GetAllSamples(
"OptimizationGuide.ModelQualityLogsUploaderService.UploadStatus."
"Compose"),
ElementsAre(base::Bucket(
ModelQualityLogsUploadStatus::kDisabledDueToEnterprisePolicy, 2)));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
LoggingDisabledByEnterprisePolicy_NonDogfood_NoSwitch) {
auto compose_feature = UserVisibleFeatureKey::kCompose;
EnableFeature(compose_feature);
SetEnterprisePolicy(
policy::key::kHelpMeWriteSettings,
ModelExecutionEnterprisePolicyValue::kAllowWithoutLogging);
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_FALSE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
}
IN_PROC_BROWSER_TEST_F(
OptimizationGuideKeyedServiceBrowserTest,
LoggingDisabledByEnterprisePolicy_NonDogfood_WithSwitch) {
auto compose_feature = UserVisibleFeatureKey::kCompose;
EnableFeature(compose_feature);
SetEnterprisePolicy(
policy::key::kHelpMeWriteSettings,
ModelExecutionEnterprisePolicyValue::kAllowWithoutLogging);
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableModelQualityDogfoodLogging);
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_FALSE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
}
IN_PROC_BROWSER_TEST_F(DogfoodOptimizationGuideKeyedServiceBrowserTest,
LoggingDisabledByEnterprisePolicy_Dogfood_NoSwitch) {
auto compose_feature = UserVisibleFeatureKey::kCompose;
EnableFeature(compose_feature);
SetEnterprisePolicy(
policy::key::kHelpMeWriteSettings,
ModelExecutionEnterprisePolicyValue::kAllowWithoutLogging);
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_FALSE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
}
IN_PROC_BROWSER_TEST_F(DogfoodOptimizationGuideKeyedServiceBrowserTest,
LoggingDisabledByEnterprisePolicy_Dogfood_WithSwitch) {
auto compose_feature = UserVisibleFeatureKey::kCompose;
EnableFeature(compose_feature);
SetEnterprisePolicy(
policy::key::kHelpMeWriteSettings,
ModelExecutionEnterprisePolicyValue::kAllowWithoutLogging);
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableModelQualityDogfoodLogging);
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_TRUE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
FeedbackIsEnabledWhenLoggingIsEnabled) {
auto compose_feature = UserVisibleFeatureKey::kCompose;
EnableFeature(compose_feature);
SetEnterprisePolicy(policy::key::kHelpMeWriteSettings,
ModelExecutionEnterprisePolicyValue::kAllow);
EXPECT_TRUE(service()->ShouldFeatureBeCurrentlyAllowedForFeedback(
proto::LogAiDataRequest::FeatureCase::kCompose));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
FeedbackIsDisabledWhenLoggingIsDisabled_NotDogfood) {
auto compose_feature = UserVisibleFeatureKey::kCompose;
EnableFeature(compose_feature);
SetEnterprisePolicy(
policy::key::kHelpMeWriteSettings,
ModelExecutionEnterprisePolicyValue::kAllowWithoutLogging);
SetIsDogfoodClient(false);
EXPECT_FALSE(service()->ShouldFeatureBeCurrentlyAllowedForFeedback(
proto::LogAiDataRequest::FeatureCase::kCompose));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
FeedbackIsEnabledWhenLoggingIsDisabled_Dogfood) {
auto compose_feature = UserVisibleFeatureKey::kCompose;
EnableFeature(compose_feature);
SetEnterprisePolicy(
policy::key::kHelpMeWriteSettings,
ModelExecutionEnterprisePolicyValue::kAllowWithoutLogging);
SetIsDogfoodClient(true);
EXPECT_TRUE(service()->ShouldFeatureBeCurrentlyAllowedForFeedback(
proto::LogAiDataRequest::FeatureCase::kCompose));
}
IN_PROC_BROWSER_TEST_F(OptimizationGuideKeyedServiceBrowserTest,
CheckModelQualityLogsUploadOnDestruction) {
// Enable metrics consent and sign in.
SetMetricsConsent(true);
EnableSignIn();
auto* profile = browser()->profile();
OptimizationGuideKeyedService* ogks =
OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
auto compose_feature = UserVisibleFeatureKey::kCompose;
auto* prefs = profile->GetPrefs();
policy::PolicyMap policies;
// Enable logging via via the enterprise policy to state kAllow this shouldn't
// stop upload and should return
// ChromeModelQualityLogsUploaderService::CanUploadLogs to true.
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(compose_feature),
static_cast<int>(prefs::FeatureOptInState::kEnabled));
base::RunLoop().RunUntilIdle();
const MqlsFeatureMetadata* metadata =
MqlsFeatureRegistry::GetInstance().GetFeature(
proto::LogAiDataRequest::FeatureCase::kCompose);
EXPECT_TRUE(model_execution_features_controller()
->ShouldFeatureBeCurrentlyAllowedForLogging(metadata));
EXPECT_TRUE(
ogks->GetModelQualityLogsUploaderService()->CanUploadLogs(metadata));
// Intercept network requests.
network::TestURLLoaderFactory url_loader_factory;
service()
->GetModelQualityLogsUploaderService()
->SetUrlLoaderFactoryForTesting(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&url_loader_factory));
// Create a new ModelQualityLogEntry for compose.
std::unique_ptr<ModelQualityLogEntry> log_entry =
GetModelQualityLogEntryForCompose();
// Destruct the log entry, this should upload the logs.
log_entry.reset();
// Logs should be uploaded on destruction.
base::RunLoop().RunUntilIdle();
content::RunAllTasksUntilIdle();
EXPECT_EQ(1, url_loader_factory.NumPending());
}
} // namespace optimization_guide
|