PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.2
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.2
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 1.1.5 1.1.6 1.1.7 1.1.8 1.2.0 All 28 releases
← All changes | includes/modules/Score/ScoreModule.php +568 -61 1.2.01.3.2 View file →
@@ -27,8 +27,10 @@
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;
32 +use XSpeed\Scan;
31 33 use XSpeed\Score;
32 34 use XSpeed\Settings_Manager;
33 35
34 36 final class ScoreModule extends Module {
@@ -36,17 +38,31 @@
36 38 public const SLUG = 'score';
37 39 public const TIER = self::TIER_FREE;
38 40 public const VERSION = '1.1.0';
39 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 +
40 56 public function ui_metadata(): array {
41 57 return array(
42 - 'label' => 'Speed Test',
58 + 'label' => __( 'Speed Test', 'xspeed' ),
43 59 'icon' => 'Gauge',
44 60 // Provider-neutral: the panel runs whichever provider the site has
45 61 // configured (PageSpeed Insights by default, no API key needed).
46 62 // The Hub-run test has its own copy and is gated behind
47 63 // hub_speed_test_enabled(), so this line must not promise it.
48 - '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 audit from the dashboard and keep the history next to your TTFB benchmark.', 'xspeed' ),
49 65 'custom_panel' => 'ScorePanel',
50 66 );
51 67 }
52 68
@@ -54,12 +70,23 @@
54 70 return array(
55 71 'enabled' => array(
56 72 'type' => 'bool',
57 73 'default' => false,
58 - 'label' => 'Enable external scores',
59 - // Off by default and stated plainly: this is the only part
60 - // of the plugin that talks to a third party on your behalf.
61 - 'description' => 'Lets you run a PageSpeed Insights or GTmetrix audit from this dashboard. Nothing is sent anywhere until you press Test.',
74 + // Meaningful for the surfaces it still reaches (REST schema,
75 + // CLI settings, a wp-config override): it names what the
76 + // value permits, not a switch nobody sees.
77 + 'label' => __( 'Allow speed tests', 'xspeed' ),
78 + // Off by default, but pressing Test IS the consent: the first
79 + // run turns this on rather than refusing (#425). What it
80 + // still guards is everything that is NOT a Test press — an
81 + // optimize run measuring its own effect, for instance.
82 + // Switch it off (REST/CLI) and nothing contacts a provider.
83 + 'description' => __( 'Turns on automatically the first time you run a speed test — the button press is the consent. Switch it off to stop every feature, including optimize runs, from contacting a score provider.', 'xspeed' ),
84 + // No dashboard control: the Test press manages it, and a
85 + // visible switch that gates a button elsewhere was the
86 + // confusion #425 removed. Hidden fields are skipped by the
87 + // panel renderer and by settings search.
88 + 'hidden' => true,
62 89 ),
63 90 'provider' => array(
64 91 'type' => 'enum',
65 92 'default' => 'psi',
@@ -67,17 +94,16 @@
67 94 'option_labels' => array(
68 95 'psi' => 'PageSpeed Insights',
69 96 'gtmetrix' => 'GTmetrix',
70 97 ),
71 - 'label' => 'Provider',
72 - 'description' => 'PageSpeed Insights works without an API key. GTmetrix requires one.',
73 - 'dependsOn' => array( 'field' => 'enabled' ),
98 + 'label' => __( 'Provider', 'xspeed' ),
99 + 'description' => __( 'PageSpeed Insights works without an API key. GTmetrix requires one.', 'xspeed' ),
74 100 ),
75 101 'psi_api_key' => array(
76 102 'type' => 'secret',
77 103 'default' => '',
78 - 'label' => 'PageSpeed API key (optional)',
79 - 'description' => 'Only needed if you hit Google\'s anonymous rate limit. Free from cloud.google.com.',
104 + 'label' => __( 'PageSpeed API key (optional)', 'xspeed' ),
105 + 'description' => __( 'Only needed if you hit Google\'s anonymous rate limit. Free from cloud.google.com.', 'xspeed' ),
80 106 // Rendered as a trailing "Check the documentation" link —
81 107 // descriptions themselves are plain text (#111).
82 108 'doc_url' => 'https://xspeedcache.com/docs/pagespeed-insights-integration/',
83 109 'dependsOn' => array(
@@ -87,10 +113,10 @@
87 113 ),
88 114 'gtmetrix_api_key' => array(
89 115 'type' => 'secret',
90 116 'default' => '',
91 - 'label' => 'GTmetrix API key',
92 - 'description' => 'Required — GTmetrix has no anonymous mode. Found in your GTmetrix account settings.',
117 + 'label' => __( 'GTmetrix API key', 'xspeed' ),
118 + 'description' => __( 'Required — GTmetrix has no anonymous mode. Found in your GTmetrix account settings.', 'xspeed' ),
93 119 'dependsOn' => array(
94 120 'field' => 'provider',
95 121 'value' => 'gtmetrix',
96 122 ),
@@ -97,18 +123,17 @@
97 123 ),
98 124 'test_url' => array(
99 125 'type' => 'url',
100 126 'default' => '',
101 - 'label' => 'URL to test',
102 - 'description' => 'Leave empty to test your home page.',
103 - 'dependsOn' => array( 'field' => 'enabled' ),
127 + 'label' => __( 'URL to test', 'xspeed' ),
128 + 'description' => __( 'Leave empty to test your home page.', 'xspeed' ),
104 129 ),
105 130 'default_strategy' => array(
106 131 'type' => 'enum',
107 132 'default' => 'mobile',
108 133 'options' => array( 'mobile', 'desktop' ),
109 - 'label' => 'Strategy',
110 - 'description' => 'PageSpeed Insights only. Mobile is what Google ranks on.',
134 + 'label' => __( 'Strategy', 'xspeed' ),
135 + 'description' => __( 'PageSpeed Insights only. Mobile is what Google ranks on.', 'xspeed' ),
111 136 'dependsOn' => array(
112 137 'field' => 'provider',
113 138 'value' => 'psi',
114 139 ),
@@ -176,13 +201,124 @@
176 201 'path' => '/hub-status',
177 202 'methods' => 'GET',
178 203 'callback' => array( $this, 'rest_hub_status' ),
179 204 ),
205 + /*
206 + * xSpeed Scan. Like the Hub routes above, deliberately NOT
207 + * gated on the `enabled` setting: that toggle guards sending
208 + * the site's URL to Google or GTmetrix with the SITE owner's
209 + * own API key. The scan engine is our own service, needs no
210 + * key, and the user starts it by pressing Scan — the consent
211 + * is the press, and requiring a settings toggle first would
212 + * reinstate exactly the funnel this feature removes.
213 + *
214 + * What the UI MUST NOT skip is telling the user whether the
215 + * resulting report is public; see Scan::private_supported().
216 + */
217 + array(
218 + 'path' => '/scan',
219 + 'methods' => 'POST',
220 + 'callback' => array( $this, 'rest_scan_start' ),
221 + ),
222 + array(
223 + 'path' => '/scan-status',
224 + 'methods' => 'GET',
225 + 'callback' => array( $this, 'rest_scan_status' ),
226 + ),
180 227 )
181 228 );
182 229 }
183 230
184 231 /**
232 + * Start an xSpeed Scan.
233 + *
234 + * Answers as soon as the engine accepts the run — a scan takes 20-60s,
235 + * so holding the request open would trip every proxy between here and
236 + * the browser. The caller polls /scan-status.
237 + *
238 + * @return \WP_REST_Response|\WP_Error
239 + */
240 + public function rest_scan_start( \WP_REST_Request $request ) {
241 + // One at a time. Without this a double-click spends two runs against
242 + // the engine's rate limit and leaves two pending markers racing.
243 + $pending = Scan::pending();
244 + if ( null !== $pending ) {
245 + return rest_ensure_response(
246 + array(
247 + 'status' => 'running',
248 + 'scan_id' => $pending['scan_id'],
249 + 'step' => '',
250 + )
251 + );
252 + }
253 +
254 + $started = Scan::start(
255 + (string) ( $request->get_param( 'url' ) ?? '' ),
256 + (bool) $request->get_param( 'fresh' )
257 + );
258 + if ( is_wp_error( $started ) ) {
259 + return $started;
260 + }
261 +
262 + return rest_ensure_response(
263 + array(
264 + 'status' => 'running',
265 + 'scan_id' => $started['scan_id'],
266 + 'report_url' => $started['report_url'],
267 + 'cached' => $started['cached'],
268 + )
269 + );
270 + }
271 +
272 + /**
273 + * Poll the in-flight scan, or report the last completed one.
274 + *
275 + * Always 200: "nothing has been scanned yet" is an empty state, not an
276 + * error, and the dashboard renders it on first paint.
277 + *
278 + * @return \WP_REST_Response|\WP_Error
279 + */
280 + public function rest_scan_status() {
281 + $pending = Scan::pending();
282 +
283 + if ( null !== $pending ) {
284 + $polled = Scan::poll( (string) $pending['scan_id'] );
285 + if ( is_wp_error( $polled ) ) {
286 + return $polled;
287 + }
288 + if ( isset( $polled['status'] ) && 'running' === $polled['status'] ) {
289 + return rest_ensure_response(
290 + array(
291 + 'status' => 'running',
292 + 'scan_id' => $polled['scan_id'],
293 + 'step' => $polled['step'],
294 + 'latest' => Scan::latest(),
295 + 'visibility' => Scan::visibility(),
296 + 'private_supported' => Scan::private_supported(),
297 + )
298 + );
299 + }
300 + return rest_ensure_response(
301 + array(
302 + 'status' => 'complete',
303 + 'latest' => $polled,
304 + 'visibility' => Scan::visibility(),
305 + 'private_supported' => Scan::private_supported(),
306 + )
307 + );
308 + }
309 +
310 + return rest_ensure_response(
311 + array(
312 + 'status' => 'idle',
313 + 'latest' => Scan::latest(),
314 + 'visibility' => Scan::visibility(),
315 + 'private_supported' => Scan::private_supported(),
316 + )
317 + );
318 + }
319 +
320 + /**
185 321 * Start a Hub-run GTmetrix test.
186 322 *
187 323 * Returns the Hub's payload on success. On failure the WP_Error code is
188 324 * the Hub's own stable code (site_not_verified, gtmetrix_quota_exceeded,
@@ -297,18 +433,10 @@
297 433 * POST, never GET: this spends someone else's rate limit and takes up
298 434 * to a minute. A GET would be prefetched by a browser.
299 435 */
300 436 public function rest_run( \WP_REST_Request $request ) {
301 - $opts = Settings_Manager::get( self::SLUG );
437 + $opts = $this->consent_by_running( Settings_Manager::get( self::SLUG ) );
302 438
303 - if ( empty( $opts['enabled'] ) ) {
304 - return new \WP_Error(
305 - 'xspeed_score_disabled',
306 - __( 'External scores are turned off. Enable them first — this is the only feature that contacts a third party.', 'xspeed' ),
307 - array( 'status' => 409 )
308 - );
309 - }
310 -
311 439 $url = $this->resolve_url( (string) $request->get_param( 'url' ), $opts );
312 440 if ( '' === $url ) {
313 441 return new \WP_Error(
314 442 'xspeed_score_no_url',
@@ -324,12 +452,200 @@
324 452 return is_wp_error( $started ) ? $started : rest_ensure_response( $started );
325 453 }
326 454
327 455 $strategy = (string) ( $request->get_param( 'strategy' ) ?: $opts['default_strategy'] );
328 - return rest_ensure_response( Score::run_psi( $url, $strategy, (string) $opts['psi_api_key'] ) );
456 + $api_key = (string) $opts['psi_api_key'];
457 +
458 + // No key of their own → run it through the Hub when this site is
459 + // connected. The Hub holds a real Google key, so this is the path
460 + // that does NOT die on the shared anonymous quota (#426). When the
461 + // Hub can't take it, fall through to the anonymous direct call —
462 + // worse odds, but exactly what the plugin did before.
463 + if ( '' === trim( $api_key ) ) {
464 + $via_hub = $this->start_psi_via_hub( $url, $strategy );
465 + if ( null !== $via_hub ) {
466 + return $via_hub;
467 + }
468 + }
469 +
470 + return rest_ensure_response( Score::run_psi( $url, $strategy, $api_key ) );
329 471 }
330 472
331 473 /**
474 + * Record the Test press as the opt-in (#425).
475 + *
476 + * The five-step funnel — find the toggle, enable it, come back, press
477 + * Test — existed to make the outbound call opt-in. The press already is
478 + * the opt-in: it is an explicit, authenticated request to contact a
479 + * provider right now. So a run no longer refuses when the toggle is off;
480 + * it turns the toggle on and proceeds, and the toggle keeps its real job
481 + * of gating everything that is NOT a Test press (optimize runs measuring
482 + * their own effect, GTmetrix polling).
483 + *
484 + * @param array<string,mixed> $opts Current module settings.
485 + * @return array<string,mixed> Settings with `enabled` true.
486 + */
487 + private function consent_by_running( array $opts ): array {
488 + if ( empty( $opts['enabled'] ) ) {
489 + Settings_Manager::update( self::SLUG, array( 'enabled' => true ) );
490 + $opts['enabled'] = true;
491 + }
492 + return $opts;
493 + }
494 +
495 + /**
496 + * Start a keyless PSI audit through the Hub, or null when the Hub cannot
497 + * take it and the caller should fall back to the direct anonymous call.
498 + *
499 + * Null — fall back — only for "the Hub was never an option here": not
500 + * connected, PSI not configured on it, or unreachable. A real refusal
501 + * (rate-limited, a run already active) is surfaced, because retrying it
502 + * anonymously would spend the shared quota to report a worse error.
503 + *
504 + * The Hub audits the site's HOME page, so a custom test URL also skips
505 + * this path rather than silently testing a different page than asked.
506 + *
507 + * @return \WP_REST_Response|\WP_Error|null
508 + */
509 + private function start_psi_via_hub( string $url, string $strategy ) {
510 + if ( untrailingslashit( $url ) !== untrailingslashit( (string) home_url( '/' ) ) ) {
511 + return null;
512 + }
513 +
514 + $result = Mcp_Hub::psi_test( $strategy );
515 +
516 + if ( is_wp_error( $result ) ) {
517 + if ( in_array( $result->get_error_code(), array( 'not_connected', 'psi_not_configured', 'hub_unreachable' ), true ) ) {
518 + return null;
519 + }
520 + // A 401/403 means the pairing is dead (revoked, detached, stale
521 + // token) — for THIS feature that is the same as not connected,
522 + // not an error the Test button should wear.
523 + $data = $result->get_error_data();
524 + if ( is_array( $data ) && in_array( (int) ( $data['status'] ?? 0 ), array( 401, 403 ), true ) ) {
525 + return null;
526 + }
527 + return $this->hub_result( $result );
528 + }
529 +
530 + $run_id = isset( $result['run']['id'] ) ? (string) $result['run']['id'] : '';
531 +
532 + // No run id means nothing can ever be polled — writing a marker here
533 + // would orphan it (may_poll() rejects an empty test_id before the
534 + // staleness check, so it would never expire either). A 202 without an
535 + // id is a malformed Hub response; say so rather than pretend a test
536 + // is pending.
537 + if ( '' === $run_id ) {
538 + return new \WP_Error(
539 + 'hub_error',
540 + __( 'xSpeed Hub accepted the test but returned no run id. Please try again.', 'xspeed' ),
541 + array( 'status' => 502 )
542 + );
543 + }
544 +
545 + // The Hub answers 202 before the audit runs; the result arrives via
546 + // the same pending/poll machinery GTmetrix already uses.
547 + update_option(
548 + Score::PENDING_OPTION,
549 + array(
550 + 'test_id' => $run_id,
551 + 'url' => $url,
552 + 'started' => time(),
553 + 'provider' => 'hub-psi',
554 + ),
555 + false
556 + );
557 +
558 + return rest_ensure_response(
559 + array(
560 + 'ok' => true,
561 + 'provider' => 'psi',
562 + 'source' => 'hub',
563 + 'state' => 'queued',
564 + 'test_id' => $run_id,
565 + 'url' => $url,
566 + 'strategy' => $strategy,
567 + 'pending' => true,
568 + )
569 + );
570 + }
571 +
572 + /**
573 + * Poll an in-flight Hub-run PSI audit.
574 + *
575 + * psi_runs() has already copied any finished run into the local history,
576 + * so resolving here is: find our run, see whether it is still going, and
577 + * drop the marker the moment it is not.
578 + *
579 + * @param array<string,mixed> $pending The stored pending marker.
580 + * @return array<string,mixed>|\WP_Error
581 + */
582 + private function poll_hub_psi( array $pending ) {
583 + $result = Mcp_Hub::psi_runs();
584 + if ( is_wp_error( $result ) ) {
585 + return $result;
586 + }
587 +
588 + $mine = null;
589 + foreach ( (array) ( $result['runs'] ?? array() ) as $run ) {
590 + if ( is_array( $run ) && (string) ( $run['id'] ?? '' ) === (string) $pending['test_id'] ) {
591 + $mine = $run;
592 + break;
593 + }
594 + }
595 +
596 + $state = is_array( $mine ) ? (string) ( $mine['status'] ?? '' ) : '';
597 +
598 + if ( 'queued' === $state || 'running' === $state ) {
599 + return array(
600 + 'ok' => true,
601 + 'provider' => 'psi',
602 + 'source' => 'hub',
603 + 'state' => $state,
604 + 'test_id' => (string) $pending['test_id'],
605 + 'pending' => true,
606 + );
607 + }
608 +
609 + // Terminal — done, error, or the Hub no longer lists it at all.
610 + delete_option( Score::PENDING_OPTION );
611 +
612 + if ( 'error' === $state ) {
613 + $row = array(
614 + 'ok' => false,
615 + 'provider' => 'psi',
616 + 'source' => 'hub',
617 + 'state' => 'error',
618 + 'pending' => false,
619 + 'error' => (string) ( $mine['error'] ?? __( 'The audit did not produce a result.', 'xspeed' ) ),
620 + );
621 + Score::record(
622 + array(
623 + 'ok' => false,
624 + 'provider' => 'psi',
625 + 'ts' => time(),
626 + 'url' => (string) ( $pending['url'] ?? '' ),
627 + 'strategy' => 'mobile',
628 + 'score' => null,
629 + 'metrics' => array(),
630 + 'issues' => array(),
631 + 'error' => $row['error'],
632 + 'source' => 'hub',
633 + )
634 + );
635 + return $row;
636 + }
637 +
638 + return array(
639 + 'ok' => true,
640 + 'provider' => 'psi',
641 + 'source' => 'hub',
642 + 'state' => 'completed',
643 + 'pending' => false,
644 + );
645 + }
646 +
647 + /**
332 648 * Poll an in-flight GTmetrix test.
333 649 *
334 650 * GET because it is a read of state we already started — the browser
335 651 * calls it every few seconds while a test is queued.
@@ -337,12 +653,13 @@
337 653 public function rest_status() {
338 654 $opts = Settings_Manager::get( self::SLUG );
339 655 $pending = get_option( Score::PENDING_OPTION, array() );
340 656
341 - // Same opt-in gate as rest_run(). Without it, `status` — which is
342 - // also the CLI's DEFAULT action — polled GTmetrix with the feature
343 - // switched off and no API key, which falsified readme.txt's promise
344 - // that nothing is sent while it is off.
657 + // Same opt-in gate as the rest of the module. Without it, `status` —
658 + // which is also the CLI's DEFAULT action — polled GTmetrix with the
659 + // feature switched off and no API key, which falsified readme.txt's
660 + // promise that nothing is sent while it is off. (A Hub-run test polls
661 + // only the Hub the site is deliberately connected to.)
345 662 if ( ! $this->may_poll( $opts, $pending ) ) {
346 663 return rest_ensure_response(
347 664 array(
348 665 'pending' => false,
@@ -351,19 +668,11 @@
351 668 )
352 669 );
353 670 }
354 671
355 - if ( ! is_array( $pending ) || empty( $pending['test_id'] ) ) {
356 - return rest_ensure_response(
357 - array(
358 - 'pending' => false,
359 - 'state' => 'idle',
360 - 'latest' => Score::latest(),
361 - )
362 - );
363 - }
364 -
365 - $polled = Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
672 + $polled = 'hub-psi' === ( $pending['provider'] ?? '' )
673 + ? $this->poll_hub_psi( $pending )
674 + : Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
366 675 if ( is_wp_error( $polled ) ) {
367 676 return $polled;
368 677 }
369 678
@@ -385,33 +694,35 @@
385 694 );
386 695 }
387 696
388 697 /**
389 - * May we contact GTmetrix to poll the in-flight test?
698 + * May we contact anyone to poll the in-flight test?
390 699 *
391 - * Three conditions, all necessary: the feature is on, an API key exists
392 - * (there is no anonymous GTmetrix), and the pending marker is real and
393 - * not stale. A marker with no expiry turned one failed start into a
394 - * permanent poll loop against a third party.
700 + * The pending marker must be real and not stale — a marker with no expiry
701 + * turned one failed start into a permanent poll loop against a third
702 + * party. Beyond that, who we may poll depends on who ran the test: a
703 + * GTmetrix test needs the feature on and an API key (there is no
704 + * anonymous GTmetrix); a Hub-run test needs only the Hub connection the
705 + * site already has — the Hub is not a third party the toggle guards.
395 706 *
396 707 * @param array<string,mixed> $opts Module settings.
397 708 * @param mixed $pending The stored pending marker.
398 709 */
399 710 private function may_poll( array $opts, $pending ): bool {
400 - if ( empty( $opts['enabled'] ) || '' === trim( (string) $opts['gtmetrix_api_key'] ) ) {
401 - return false;
402 - }
403 711 if ( ! is_array( $pending ) || empty( $pending['test_id'] ) ) {
404 712 return false;
405 713 }
406 - // A GTmetrix test that hasn't resolved within the window is not going
407 - // to; drop the marker rather than poll it forever.
714 + // A test that hasn't resolved within the window is not going to;
715 + // drop the marker rather than poll it forever.
408 716 $started = isset( $pending['started'] ) ? (int) $pending['started'] : 0;
409 717 if ( $started > 0 && ( time() - $started ) > Score::PENDING_MAX_AGE ) {
410 718 delete_option( Score::PENDING_OPTION );
411 719 return false;
412 720 }
413 - return true;
721 + if ( 'hub-psi' === ( $pending['provider'] ?? '' ) ) {
722 + return '' !== Mcp_Pairing::site_token();
723 + }
724 + return ! empty( $opts['enabled'] ) && '' !== trim( (string) $opts['gtmetrix_api_key'] );
414 725 }
415 726
416 727 /**
417 728 * Fall back to the home page when no URL is configured — testing "my
@@ -434,8 +745,9 @@
434 745 array(
435 746 'name' => 'xspeed score',
436 747 'callback' => array( $this, 'cli_handler' ),
437 748 'shortdesc' => 'External performance scores: `run` a PageSpeed Insights / GTmetrix audit (use --target=<url>, not --url, which WP-CLI reserves), `status` for an in-flight GTmetrix test, `history` for past runs.',
749 + 'ai_hint' => 'Measure real-world performance with an external audit (PageSpeed Insights / GTmetrix), or read past scores. Use to answer "did that change actually help" with a measured before/after instead of an assumption, and to get Core Web Vitals for a specific page. `run` starts an audit (pass --target=<url> for a page other than the home page; --url is reserved by WP-CLI), `status` polls an in-flight GTmetrix test, `history` returns previous runs. An audit takes up to a couple of minutes, so say so before starting one.',
438 750 'synopsis' => array(
439 751 array(
440 752 'type' => 'positional',
441 753 'name' => 'action',
@@ -464,11 +776,183 @@
464 776 'optional' => true,
465 777 ),
466 778 ),
467 779 ),
780 + /*
781 + * A SEPARATE command, not another action on `score`, because the
782 + * two produce different numbers. A scan score is the xSpeed
783 + * rubric (four weighted dimensions, ~20 checks); a score run is a
784 + * raw provider score. Folding them together would invite exactly
785 + * the comparison the two scales cannot support.
786 + */
787 + array(
788 + 'name' => 'xspeed scan',
789 + 'callback' => array( $this, 'cli_scan_handler' ),
790 + 'shortdesc' => 'xSpeed Scan: `run` a full graded site report, `status` to poll one or read the last, `fixes` for what to do next.',
791 + 'ai_hint' => 'Run a full xSpeed Scan and read the graded result. This is BROADER than `xspeed score`: it grades four weighted dimensions (speed, delivery, assets, platform) over ~20 checks and returns what to fix ranked by how many points each recovers, which a raw PageSpeed score cannot tell you. The scan score and a Lighthouse score are DIFFERENT SCALES - never present them as the same number or compare one to the other. `run` starts a scan (20-60s; poll with `status`), `fixes` lists the ranked remediations. Reports are published to a public per-host list unless the site is connected to the Hub, so say so before starting one.',
792 + 'synopsis' => array(
793 + array(
794 + 'type' => 'positional',
795 + 'name' => 'action',
796 + 'options' => array( 'run', 'status', 'fixes' ),
797 + 'optional' => true,
798 + ),
799 + array(
800 + 'type' => 'assoc',
801 + // NOT `--url`, which WP-CLI reserves as a global.
802 + 'name' => 'target',
803 + 'description' => 'URL to scan. Defaults to the home page.',
804 + 'optional' => true,
805 + ),
806 + array(
807 + 'type' => 'flag',
808 + 'name' => 'fresh',
809 + 'description' => 'Force a new scan instead of reusing a recent cached report.',
810 + 'optional' => true,
811 + ),
812 + array(
813 + 'type' => 'flag',
814 + 'name' => 'wait',
815 + 'description' => 'Poll until the scan finishes instead of returning immediately.',
816 + 'optional' => true,
817 + ),
818 + ),
819 + ),
468 820 );
469 821 }
470 822
823 + /**
824 + * `wp xspeed scan [run|status|fixes]`
825 + *
826 + * @param array<int,string> $args Positional.
827 + * @param array<string,string> $assoc_args Flags.
828 + */
829 + public function cli_scan_handler( array $args, array $assoc_args ): void {
830 + $action = $args[0] ?? 'status';
831 +
832 + if ( 'fixes' === $action ) {
833 + $latest = Scan::latest();
834 + if ( null === $latest || empty( $latest['fixes'] ) ) {
835 + \WP_CLI::log( 'No scan result yet. Run `wp xspeed scan run --wait` first.' );
836 + return;
837 + }
838 + $rows = array();
839 + foreach ( $latest['fixes'] as $f ) {
840 + $rows[] = array(
841 + 'check' => $f['id'] . ' ' . $f['name'],
842 + 'status' => $f['status'],
843 + 'recoverable' => $f['recoverable'],
844 + 'evidence' => $f['evidence'],
845 + );
846 + }
847 + \WP_CLI\Utils\format_items( 'table', $rows, array( 'check', 'status', 'recoverable', 'evidence' ) );
848 + return;
849 + }
850 +
851 + if ( 'run' === $action ) {
852 + // Said before the call, not after: on an unconnected site this
853 + // publishes a report about the user's site to a public list.
854 + // Name the remedy too -- connecting the Hub is what makes a
855 + // report unlisted, and a warning without it leaves no move.
856 + if ( 'private' !== Scan::visibility() || ! Scan::private_supported() ) {
857 + \WP_CLI::warning(
858 + 'This report will be publicly visible at xspeedcache.com, listed under your domain. '
859 + . 'Connect xSpeed Hub from the dashboard to keep your reports unlisted.'
860 + );
861 + }
862 +
863 + $started = Scan::start(
864 + (string) ( $assoc_args['target'] ?? '' ),
865 + ! empty( $assoc_args['fresh'] )
866 + );
867 + if ( is_wp_error( $started ) ) {
868 + \WP_CLI::error( $started->get_error_message() );
869 + return;
870 + }
871 + \WP_CLI::log( 'Scan started: ' . $started['scan_id'] );
872 + \WP_CLI::log( 'Report: ' . $started['report_url'] );
873 +
874 + if ( empty( $assoc_args['wait'] ) ) {
875 + \WP_CLI::log( 'Poll with `wp xspeed scan status`.' );
876 + return;
877 + }
878 +
879 + // A scan is 20-60s; cap the wait so a stuck engine cannot hang
880 + // a CLI session indefinitely.
881 + $deadline = time() + 180;
882 + while ( time() < $deadline ) {
883 + sleep( 5 );
884 + $polled = Scan::poll( (string) $started['scan_id'] );
885 + if ( is_wp_error( $polled ) ) {
886 + \WP_CLI::error( $polled->get_error_message() );
887 + return;
888 + }
889 + if ( ! isset( $polled['status'] ) || 'running' !== $polled['status'] ) {
890 + self::cli_print_scan( $polled );
891 + return;
892 + }
893 + \WP_CLI::log( ' ' . ( $polled['step'] ?: 'working' ) . '...' );
894 + }
895 + \WP_CLI::warning( 'Still running. Poll with `wp xspeed scan status`.' );
896 + return;
897 + }
898 +
899 + // status
900 + $pending = Scan::pending();
901 + if ( null !== $pending ) {
902 + $polled = Scan::poll( (string) $pending['scan_id'] );
903 + if ( is_wp_error( $polled ) ) {
904 + \WP_CLI::error( $polled->get_error_message() );
905 + return;
906 + }
907 + if ( isset( $polled['status'] ) && 'running' === $polled['status'] ) {
908 + \WP_CLI::log( 'Running: ' . ( $polled['step'] ?: 'working' ) );
909 + return;
910 + }
911 + self::cli_print_scan( $polled );
912 + return;
913 + }
914 +
915 + $latest = Scan::latest();
916 + if ( null === $latest ) {
917 + \WP_CLI::log( 'No scan yet. Run `wp xspeed scan run --wait`.' );
918 + return;
919 + }
920 + self::cli_print_scan( $latest );
921 + }
922 +
923 + /** Shared rendering for a completed scan. */
924 + private static function cli_print_scan( array $r ): void {
925 + \WP_CLI::log(
926 + sprintf(
927 + 'Score %s/100 grade %s (%s)%s',
928 + null === $r['score'] ? '-' : $r['score'],
929 + $r['grade'] ?: '-',
930 + $r['level_name'] ?: '-',
931 + ! empty( $r['partial'] ) ? ' [partial scan]' : ''
932 + )
933 + );
934 + foreach ( (array) ( $r['dimensions'] ?? array() ) as $key => $d ) {
935 + \WP_CLI::log( sprintf( ' %-9s %3s/100 (%s of %s pts)', $key, $d['score'] ?? '-', $d['earned'] ?? '-', $d['weight'] ?? '-' ) );
936 + }
937 + $lh = $r['measured']['lighthouse'] ?? null;
938 + $lhd = $r['measured']['lighthouse_desktop'] ?? null;
939 + if ( null !== $lh || null !== $lhd ) {
940 + // Both strategies: the engine measures both and they diverge
941 + // widely, so reporting only mobile states the harsher number as
942 + // though it were the whole picture. Labelled, and never as "the
943 + // score": different scale.
944 + \WP_CLI::log(
945 + sprintf(
946 + 'Lighthouse: mobile %s, desktop %s - a different scale, one check inside the score above.',
947 + null === $lh ? '-' : $lh . '/100',
948 + null === $lhd ? '-' : $lhd . '/100'
949 + )
950 + );
951 + }
952 + \WP_CLI::log( 'Report: ' . ( $r['report_url'] ?? '' ) );
953 + }
954 +
471 955 public function cli_handler( array $args, array $assoc ): void {
472 956 $action = isset( $args[0] ) ? (string) $args[0] : 'status';
473 957 $opts = Settings_Manager::get( self::SLUG );
474 958
@@ -519,12 +1003,11 @@
519 1003 return;
520 1004 }
521 1005
522 1006 if ( 'run' === $action ) {
523 - if ( empty( $opts['enabled'] ) ) {
524 - \WP_CLI::error( 'External scores are turned off. Enable the score module first — this is the only feature that contacts a third party.' );
525 - return;
526 - }
1007 + // Running the command IS the opt-in — same consent rule as the
1008 + // dashboard's Test button (#425).
1009 + $opts = $this->consent_by_running( $opts );
527 1010
528 1011 $url = $this->resolve_url( isset( $assoc['target'] ) ? (string) $assoc['target'] : '', $opts );
529 1012 $provider = isset( $assoc['provider'] ) ? (string) $assoc['provider'] : (string) $opts['provider'];
530 1013
@@ -538,10 +1021,25 @@
538 1021 return;
539 1022 }
540 1023
541 1024 $strategy = isset( $assoc['strategy'] ) ? (string) $assoc['strategy'] : (string) $opts['default_strategy'];
542 - $run = Score::run_psi( $url, $strategy, (string) $opts['psi_api_key'] );
1025 + $api_key = (string) $opts['psi_api_key'];
543 1026
1027 + // No key → prefer the Hub, same ladder as rest_run() (#426).
1028 + if ( '' === trim( $api_key ) ) {
1029 + $via_hub = $this->start_psi_via_hub( $url, $strategy );
1030 + if ( $via_hub instanceof \WP_Error ) {
1031 + \WP_CLI::error( $via_hub->get_error_message() );
1032 + return;
1033 + }
1034 + if ( null !== $via_hub ) {
1035 + \WP_CLI::success( 'PageSpeed audit started via xSpeed Hub. Poll with: wp xspeed score status' );
1036 + return;
1037 + }
1038 + }
1039 +
1040 + $run = Score::run_psi( $url, $strategy, $api_key );
1041 +
544 1042 if ( empty( $run['ok'] ) ) {
545 1043 \WP_CLI::error( (string) $run['error'] );
546 1044 return;
547 1045 }
@@ -559,15 +1057,24 @@
559 1057
560 1058 // status
561 1059 $pending = get_option( Score::PENDING_OPTION, array() );
562 1060 if ( $this->may_poll( $opts, $pending ) ) {
563 - $polled = Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
1061 + $polled = 'hub-psi' === ( $pending['provider'] ?? '' )
1062 + ? $this->poll_hub_psi( $pending )
1063 + : Score::poll_gtmetrix( (string) $opts['gtmetrix_api_key'] );
564 1064 if ( is_wp_error( $polled ) ) {
565 1065 \WP_CLI::error( $polled->get_error_message() );
566 1066 return;
567 1067 }
568 1068 if ( ! empty( $polled['pending'] ) ) {
569 - \WP_CLI::log( sprintf( 'GTmetrix test %s is %s.', (string) $pending['test_id'], (string) ( $polled['state'] ?? 'running' ) ) );
1069 + \WP_CLI::log(
1070 + sprintf(
1071 + '%s test %s is %s.',
1072 + 'hub-psi' === ( $pending['provider'] ?? '' ) ? 'PageSpeed (Hub)' : 'GTmetrix',
1073 + (string) $pending['test_id'],
1074 + (string) ( $polled['state'] ?? 'running' )
1075 + )
1076 + );
570 1077 return;
571 1078 }
572 1079 }
573 1080