PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.7
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.7
1.3.7 1.3.6 1.3.5 1.3.4 1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 All 33 releases
← All changes | includes/modules/Score/ScoreModule.php +285 -61 1.2.4 → 1.3.7 View file →
@@ -27,8 +27,9 @@
27 27 defined( 'ABSPATH' ) || exit;
28 28
29 29 use XSpeed\Module;
30 30 use XSpeed\Modules\Mcp\Mcp_Hub;
31 +use XSpeed\Modules\Mcp\Mcp_Pairing;
31 32 use XSpeed\Scan;
32 33 use XSpeed\Score;
33 34 use XSpeed\Settings_Manager;
34 35
@@ -37,18 +38,33 @@
37 38 public const SLUG = 'score';
38 39 public const TIER = self::TIER_FREE;
39 40 public const VERSION = '1.1.0';
40 41
42 + /**
43 + * No On/Off state (#425).
44 + *
45 + * The default reports the `enabled` setting, which put an "Off" pill on a
46 + * panel whose Test button works regardless — the press is the consent and
47 + * flips the setting itself. A run-on-demand panel has no meaningful
48 + * on/off, exactly like Health; the setting stays as the internal gate for
49 + * non-press callers (optimize runs, GTmetrix polling), it just is not a
50 + * state this panel wears.
51 + */
52 + public function is_active(): ?bool {
53 + return null;
54 + }
55 +
41 56 public function ui_metadata(): array {
42 57 return array(
43 - 'label' => 'Speed Test',
58 + 'label' => __( 'Speed Test', 'xspeed' ),
44 59 'icon' => 'Gauge',
45 60 // Provider-neutral: the panel runs whichever provider the site has
46 61 // configured (PageSpeed Insights by default, no API key needed).
47 62 // The Hub-run test has its own copy and is gated behind
48 63 // hub_speed_test_enabled(), so this line must not promise it.
49 - 'description' => 'Run a PageSpeed Insights or GTmetrix audit from the dashboard and keep the history next to your TTFB benchmark.',
64 + 'description' => __( 'Run a PageSpeed Insights or GTmetrix test and keep a history of the scores.', 'xspeed' ),
50 65 'custom_panel' => 'ScorePanel',
66 + 'group' => 'insights',
51 67 );
52 68 }
53 69
54 70 public function settings_schema(): array {
@@ -55,12 +71,23 @@
55 71 return array(
56 72 'enabled' => array(
57 73 'type' => 'bool',
58 74 'default' => false,
59 - 'label' => 'Enable external scores',
60 - // Off by default and stated plainly: this is the only part
61 - // of the plugin that talks to a third party on your behalf.
62 - 'description' => 'Lets you run a PageSpeed Insights or GTmetrix audit from this dashboard. Nothing is sent anywhere until you press Test.',
75 + // Meaningful for the surfaces it still reaches (REST schema,
76 + // CLI settings, a wp-config override): it names what the
77 + // value permits, not a switch nobody sees.
78 + 'label' => __( 'Allow speed tests', 'xspeed' ),
79 + // Off by default, but pressing Test IS the consent: the first
80 + // run turns this on rather than refusing (#425). What it
81 + // still guards is everything that is NOT a Test press — an
82 + // optimize run measuring its own effect, for instance.
83 + // Switch it off (REST/CLI) and nothing contacts a provider.
84 + 'description' => __( 'Turns on the first time you run a speed test. Switch it off and no feature, not even an optimize run, contacts a test provider.', 'xspeed' ),
85 + // No dashboard control: the Test press manages it, and a
86 + // visible switch that gates a button elsewhere was the
87 + // confusion #425 removed. Hidden fields are skipped by the
88 + // panel renderer and by settings search.
89 + 'hidden' => true,
63 90 ),
64 91 'provider' => array(
65 92 'type' => 'enum',
66 93 'default' => 'psi',
@@ -68,20 +95,20 @@
68 95 'option_labels' => array(
69 96 'psi' => 'PageSpeed Insights',
70 97 'gtmetrix' => 'GTmetrix',
71 98 ),
72 - 'label' => 'Provider',
73 - 'description' => 'PageSpeed Insights works without an API key. GTmetrix requires one.',
74 - 'dependsOn' => array( 'field' => 'enabled' ),
99 + 'label' => __( 'Test provider', 'xspeed' ),
100 + 'description' => __( 'PageSpeed Insights works without an API key. GTmetrix needs one.', 'xspeed' ),
75 101 ),
76 102 'psi_api_key' => array(
77 103 'type' => 'secret',
78 104 'default' => '',
79 - 'label' => 'PageSpeed API key (optional)',
80 - 'description' => 'Only needed if you hit Google\'s anonymous rate limit. Free from cloud.google.com.',
105 + 'label' => __( 'PageSpeed API key (optional)', 'xspeed' ),
106 + 'description' => __( 'Only needed if Google starts refusing tests without a key. You can get a free key at cloud.google.com.', 'xspeed' ),
81 107 // Rendered as a trailing "Check the documentation" link —
82 108 // descriptions themselves are plain text (#111).
83 109 'doc_url' => 'https://xspeedcache.com/docs/pagespeed-insights-integration/',
110 + 'advanced' => true,
84 111 'dependsOn' => array(
85 112 'field' => 'provider',
86 113 'value' => 'psi',
87 114 ),
@@ -88,10 +115,10 @@
88 115 ),
89 116 'gtmetrix_api_key' => array(
90 117 'type' => 'secret',
91 118 'default' => '',
92 - 'label' => 'GTmetrix API key',
93 - 'description' => 'Required — GTmetrix has no anonymous mode. Found in your GTmetrix account settings.',
119 + 'label' => __( 'GTmetrix API key', 'xspeed' ),
120 + 'description' => __( 'GTmetrix does not run tests without a key. Find it in your GTmetrix account settings.', 'xspeed' ),
94 121 'dependsOn' => array(
95 122 'field' => 'provider',
96 123 'value' => 'gtmetrix',
97 124 ),
@@ -98,18 +125,17 @@
98 125 ),
99 126 'test_url' => array(
100 127 'type' => 'url',
101 128 'default' => '',
102 - 'label' => 'URL to test',
103 - 'description' => 'Leave empty to test your home page.',
104 - 'dependsOn' => array( 'field' => 'enabled' ),
129 + 'label' => __( 'URL to test', 'xspeed' ),
130 + 'description' => __( 'Leave empty to test your home page.', 'xspeed' ),
105 131 ),
106 132 'default_strategy' => array(
107 133 'type' => 'enum',
108 134 'default' => 'mobile',
109 135 'options' => array( 'mobile', 'desktop' ),
110 - 'label' => 'Strategy',
111 - 'description' => 'PageSpeed Insights only. Mobile is what Google ranks on.',
136 + 'label' => __( 'Device', 'xspeed' ),
137 + 'description' => __( 'Test as a phone or a desktop visitor. Google ranks sites on the mobile result.', 'xspeed' ),
112 138 'dependsOn' => array(
113 139 'field' => 'provider',
114 140 'value' => 'psi',
115 141 ),
@@ -409,18 +435,10 @@
409 435 * POST, never GET: this spends someone else's rate limit and takes up
410 436 * to a minute. A GET would be prefetched by a browser.
411 437 */
412 438 public function rest_run( \WP_REST_Request $request ) {
413 - $opts = Settings_Manager::get( self::SLUG );
439 + $opts = $this->consent_by_running( Settings_Manager::get( self::SLUG ) );
414 440
415 - if ( empty( $opts['enabled'] ) ) {
416 - return new \WP_Error(
417 - 'xspeed_score_disabled',
418 - __( 'External scores are turned off. Enable them first — this is the only feature that contacts a third party.', 'xspeed' ),
419 - array( 'status' => 409 )
420 - );
421 - }
422 -
423 441 $url = $this->resolve_url( (string) $request->get_param( 'url' ), $opts );
424 442 if ( '' === $url ) {
425 443 return new \WP_Error(
426 444 'xspeed_score_no_url',
@@ -436,12 +454,200 @@
436 454 return is_wp_error( $started ) ? $started : rest_ensure_response( $started );
437 455 }
438 456
439 457 $strategy = (string) ( $request->get_param( 'strategy' ) ?: $opts['default_strategy'] );
440 - return rest_ensure_response( Score::run_psi( $url, $strategy, (string) $opts['psi_api_key'] ) );
458 + $api_key = (string) $opts['psi_api_key'];
459 +
460 + // No key of their own → run it through the Hub when this site is
461 + // connected. The Hub holds a real Google key, so this is the path
462 + // that does NOT die on the shared anonymous quota (#426). When the
463 + // Hub can't take it, fall through to the anonymous direct call —
464 + // worse odds, but exactly what the plugin did before.
465 + if ( '' === trim( $api_key ) ) {
466 + $via_hub = $this->start_psi_via_hub( $url, $strategy );
467 + if ( null !== $via_hub ) {
468 + return $via_hub;
469 + }
470 + }
471 +
472 + return rest_ensure_response( Score::run_psi( $url, $strategy, $api_key ) );
441 473 }
442 474
443 475 /**
476 + * Record the Test press as the opt-in (#425).
477 + *
478 + * The five-step funnel — find the toggle, enable it, come back, press
479 + * Test — existed to make the outbound call opt-in. The press already is
480 + * the opt-in: it is an explicit, authenticated request to contact a
481 + * provider right now. So a run no longer refuses when the toggle is off;
482 + * it turns the toggle on and proceeds, and the toggle keeps its real job
483 + * of gating everything that is NOT a Test press (optimize runs measuring
484 + * their own effect, GTmetrix polling).
485 + *
486 + * @param array<string,mixed> $opts Current module settings.
487 + * @return array<string,mixed> Settings with `enabled` true.
488 + */
489 + private function consent_by_running( array $opts ): array {
490 + if ( empty( $opts['enabled'] ) ) {
491 + Settings_Manager::update( self::SLUG, array( 'enabled' => true ) );
492 + $opts['enabled'] = true;
493 + }
494 + return $opts;
495 + }
496 +
497 + /**
498 + * Start a keyless PSI audit through the Hub, or null when the Hub cannot
499 + * take it and the caller should fall back to the direct anonymous call.
500 + *
501 + * Null — fall back — only for "the Hub was never an option here": not
502 + * connected, PSI not configured on it, or unreachable. A real refusal
503 + * (rate-limited, a run already active) is surfaced, because retrying it
504 + * anonymously would spend the shared quota to report a worse error.
505 + *
506 + * The Hub audits the site's HOME page, so a custom test URL also skips
507 + * this path rather than silently testing a different page than asked.
508 + *
509 + * @return \WP_REST_Response|\WP_Error|null
510 + */
511 + private function start_psi_via_hub( string $url, string $strategy ) {
512 + if ( untrailingslashit( $url ) !== untrailingslashit( (string) home_url( '/' ) ) ) {
513 + return null;
514 + }
515 +
516 + $result = Mcp_Hub::psi_test( $strategy );
517 +
518 + if ( is_wp_error( $result ) ) {
519 + if ( in_array( $result->get_error_code(), array( 'not_connected', 'psi_not_configured', 'hub_unreachable' ), true ) ) {
520 + return null;
521 + }
522 + // A 401/403 means the pairing is dead (revoked, detached, stale
523 + // token) — for THIS feature that is the same as not connected,
524 + // not an error the Test button should wear.
525 + $data = $result->get_error_data();
526 + if ( is_array( $data ) && in_array( (int) ( $data['status'] ?? 0 ), array( 401, 403 ), true ) ) {
527 + return null;
528 + }
529 + return $this->hub_result( $result );
530 + }
531 +
532 + $run_id = isset( $result['run']['id'] ) ? (string) $result['run']['id'] : '';
533 +
534 + // No run id means nothing can ever be polled — writing a marker here
535 + // would orphan it (may_poll() rejects an empty test_id before the
536 + // staleness check, so it would never expire either). A 202 without an
537 + // id is a malformed Hub response; say so rather than pretend a test
538 + // is pending.
539 + if ( '' === $run_id ) {
540 + return new \WP_Error(
541 + 'hub_error',
542 + __( 'xSpeed Hub accepted the test but returned no run id. Please try again.', 'xspeed' ),
543 + array( 'status' => 502 )
544 + );
545 + }
546 +
547 + // The Hub answers 202 before the audit runs; the result arrives via
548 + // the same pending/poll machinery GTmetrix already uses.
549 + update_option(
550 + Score::PENDING_OPTION,
551 + array(
552 + 'test_id' => $run_id,
553 + 'url' => $url,
554 + 'started' => time(),
555 + 'provider' => 'hub-psi',
556 + ),
557 + false
558 + );
559 +
560 + return rest_ensure_response(
561 + array(
562 + 'ok' => true,
563 + 'provider' => 'psi',
564 + 'source' => 'hub',
565 + 'state' => 'queued',
566 + 'test_id' => $run_id,
567 + 'url' => $url,
568 + 'strategy' => $strategy,
569 + 'pending' => true,
570 + )
571 + );
572 + }
573 +
574 + /**
575 + * Poll an in-flight Hub-run PSI audit.
576 + *
577 + * psi_runs() has already copied any finished run into the local history,
578 + * so resolving here is: find our run, see whether it is still going, and
579 + * drop the marker the moment it is not.
580 + *
581 + * @param array<string,mixed> $pending The stored pending marker.
582 + * @return array<string,mixed>|\WP_Error
583 + */
584 + private function poll_hub_psi( array $pending ) {
585 + $result = Mcp_Hub::psi_runs();
586 + if ( is_wp_error( $result ) ) {
587 + return $result;
588 + }
589 +
590 + $mine = null;
591 + foreach ( (array) ( $result['runs'] ?? array() ) as $run ) {
592 + if ( is_array( $run ) && (string) ( $run['id'] ?? '' ) === (string) $pending['test_id'] ) {
593 + $mine = $run;
594 + break;
595 + }
596 + }
597 +
598 + $state = is_array( $mine ) ? (string) ( $mine['status'] ?? '' ) : '';
599 +
600 + if ( 'queued' === $state || 'running' === $state ) {
601 + return array(
602 + 'ok' => true,
603 + 'provider' => 'psi',
604 + 'source' => 'hub',
605 + 'state' => $state,
606 + 'test_id' => (string) $pending['test_id'],
607 + 'pending' => true,
608 + );
609 + }
610 +
611 + // Terminal — done, error, or the Hub no longer lists it at all.
612 + delete_option( Score::PENDING_OPTION );
613 +
614 + if ( 'error' === $state ) {
615 + $row = array(
616 + 'ok' => false,
617 + 'provider' => 'psi',
618 + 'source' => 'hub',
619 + 'state' => 'error',
620 + 'pending' => false,
621 + 'error' => (string) ( $mine['error'] ?? __( 'The audit did not produce a result.', 'xspeed' ) ),
622 + );
623 + Score::record(
624 + array(
625 + 'ok' => false,
626 + 'provider' => 'psi',
627 + 'ts' => time(),
628 + 'url' => (string) ( $pending['url'] ?? '' ),
629 + 'strategy' => 'mobile',
630 + 'score' => null,
631 + 'metrics' => array(),
632 + 'issues' => array(),
633 + 'error' => $row['error'],
634 + 'source' => 'hub',
635 + )
636 + );
637 + return $row;
638 + }
639 +
640 + return array(
641 + 'ok' => true,
642 + 'provider' => 'psi',
643 + 'source' => 'hub',
644 + 'state' => 'completed',
645 + 'pending' => false,
646 + );
647 + }
648 +
649 + /**
444 650 * Poll an in-flight GTmetrix test.
445 651 *
446 652 * GET because it is a read of state we already started — the browser
447 653 * calls it every few seconds while a test is queued.
@@ -449,12 +655,13 @@
449 655 public function rest_status() {
450 656 $opts = Settings_Manager::get( self::SLUG );
451 657 $pending = get_option( Score::PENDING_OPTION, array() );
452 658
453 - // Same opt-in gate as rest_run(). Without it, `status` — which is
454 - // also the CLI's DEFAULT action — polled GTmetrix with the feature
455 - // switched off and no API key, which falsified readme.txt's promise
456 - // that nothing is sent while it is off.
659 + // Same opt-in gate as the rest of the module. Without it, `status` —
660 + // which is also the CLI's DEFAULT action — polled GTmetrix with the
661 + // feature switched off and no API key, which falsified readme.txt's
662 + // promise that nothing is sent while it is off. (A Hub-run test polls
663 + // only the Hub the site is deliberately connected to.)
457 664 if ( ! $this->may_poll( $opts, $pending ) ) {
458 665 return rest_ensure_response(
459 666 array(
460 667 'pending' => false,
@@ -463,19 +670,11 @@
463 670 )
464 671 );
465 672 }
466 673
467 - if ( ! is_array( $pending ) || empty( $pending['test_id'] ) ) {
468 - return rest_ensure_response(
469 - array(
470 - 'pending' => false,
471 - 'state' => 'idle',
472 - 'latest' => Score::latest(),
473 - )
474 - );
475 - }
476 -
477 - $polled = Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
674 + $polled = 'hub-psi' === ( $pending['provider'] ?? '' )
675 + ? $this->poll_hub_psi( $pending )
676 + : Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
478 677 if ( is_wp_error( $polled ) ) {
479 678 return $polled;
480 679 }
481 680
@@ -497,33 +696,35 @@
497 696 );
498 697 }
499 698
500 699 /**
501 - * May we contact GTmetrix to poll the in-flight test?
700 + * May we contact anyone to poll the in-flight test?
502 701 *
503 - * Three conditions, all necessary: the feature is on, an API key exists
504 - * (there is no anonymous GTmetrix), and the pending marker is real and
505 - * not stale. A marker with no expiry turned one failed start into a
506 - * permanent poll loop against a third party.
702 + * The pending marker must be real and not stale — a marker with no expiry
703 + * turned one failed start into a permanent poll loop against a third
704 + * party. Beyond that, who we may poll depends on who ran the test: a
705 + * GTmetrix test needs the feature on and an API key (there is no
706 + * anonymous GTmetrix); a Hub-run test needs only the Hub connection the
707 + * site already has — the Hub is not a third party the toggle guards.
507 708 *
508 709 * @param array<string,mixed> $opts Module settings.
509 710 * @param mixed $pending The stored pending marker.
510 711 */
511 712 private function may_poll( array $opts, $pending ): bool {
512 - if ( empty( $opts['enabled'] ) || '' === trim( (string) $opts['gtmetrix_api_key'] ) ) {
513 - return false;
514 - }
515 713 if ( ! is_array( $pending ) || empty( $pending['test_id'] ) ) {
516 714 return false;
517 715 }
518 - // A GTmetrix test that hasn't resolved within the window is not going
519 - // to; drop the marker rather than poll it forever.
716 + // A test that hasn't resolved within the window is not going to;
717 + // drop the marker rather than poll it forever.
520 718 $started = isset( $pending['started'] ) ? (int) $pending['started'] : 0;
521 719 if ( $started > 0 && ( time() - $started ) > Score::PENDING_MAX_AGE ) {
522 720 delete_option( Score::PENDING_OPTION );
523 721 return false;
524 722 }
525 - return true;
723 + if ( 'hub-psi' === ( $pending['provider'] ?? '' ) ) {
724 + return '' !== Mcp_Pairing::site_token();
725 + }
726 + return ! empty( $opts['enabled'] ) && '' !== trim( (string) $opts['gtmetrix_api_key'] );
526 727 }
527 728
528 729 /**
529 730 * Fall back to the home page when no URL is configured — testing "my
@@ -804,12 +1005,11 @@
804 1005 return;
805 1006 }
806 1007
807 1008 if ( 'run' === $action ) {
808 - if ( empty( $opts['enabled'] ) ) {
809 - \WP_CLI::error( 'External scores are turned off. Enable the score module first — this is the only feature that contacts a third party.' );
810 - return;
811 - }
1009 + // Running the command IS the opt-in — same consent rule as the
1010 + // dashboard's Test button (#425).
1011 + $opts = $this->consent_by_running( $opts );
812 1012
813 1013 $url = $this->resolve_url( isset( $assoc['target'] ) ? (string) $assoc['target'] : '', $opts );
814 1014 $provider = isset( $assoc['provider'] ) ? (string) $assoc['provider'] : (string) $opts['provider'];
815 1015
@@ -823,10 +1023,25 @@
823 1023 return;
824 1024 }
825 1025
826 1026 $strategy = isset( $assoc['strategy'] ) ? (string) $assoc['strategy'] : (string) $opts['default_strategy'];
827 - $run = Score::run_psi( $url, $strategy, (string) $opts['psi_api_key'] );
1027 + $api_key = (string) $opts['psi_api_key'];
828 1028
1029 + // No key → prefer the Hub, same ladder as rest_run() (#426).
1030 + if ( '' === trim( $api_key ) ) {
1031 + $via_hub = $this->start_psi_via_hub( $url, $strategy );
1032 + if ( $via_hub instanceof \WP_Error ) {
1033 + \WP_CLI::error( $via_hub->get_error_message() );
1034 + return;
1035 + }
1036 + if ( null !== $via_hub ) {
1037 + \WP_CLI::success( 'PageSpeed audit started via xSpeed Hub. Poll with: wp xspeed score status' );
1038 + return;
1039 + }
1040 + }
1041 +
1042 + $run = Score::run_psi( $url, $strategy, $api_key );
1043 +
829 1044 if ( empty( $run['ok'] ) ) {
830 1045 \WP_CLI::error( (string) $run['error'] );
831 1046 return;
832 1047 }
@@ -844,15 +1059,24 @@
844 1059
845 1060 // status
846 1061 $pending = get_option( Score::PENDING_OPTION, array() );
847 1062 if ( $this->may_poll( $opts, $pending ) ) {
848 - $polled = Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
1063 + $polled = 'hub-psi' === ( $pending['provider'] ?? '' )
1064 + ? $this->poll_hub_psi( $pending )
1065 + : Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
849 1066 if ( is_wp_error( $polled ) ) {
850 1067 \WP_CLI::error( $polled->get_error_message() );
851 1068 return;
852 1069 }
853 1070 if ( ! empty( $polled['pending'] ) ) {
854 - \WP_CLI::log( sprintf( 'GTmetrix test %s is %s.', (string) $pending['test_id'], (string) ( $polled['state'] ?? 'running' ) ) );
1071 + \WP_CLI::log(
1072 + sprintf(
1073 + '%s test %s is %s.',
1074 + 'hub-psi' === ( $pending['provider'] ?? '' ) ? 'PageSpeed (Hub)' : 'GTmetrix',
1075 + (string) $pending['test_id'],
1076 + (string) ( $polled['state'] ?? 'running' )
1077 + )
1078 + );
855 1079 return;
856 1080 }
857 1081 }
858 1082