Commit ef7c853b199 for woocommerce
commit ef7c853b1998d52fa2aff94949e578c68d3d23a0
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date: Wed Nov 25 21:12:01 2026 +0100
Agent readiness: a switch to stop the daily check (#71443)
* Agent readiness: best sellers first on large catalogs, daily scan at night, sales read in SQL
On a catalog over the 5,000 product limit, the scan takes the best sellers
of the last 90 days first, then the most recently changed products. A saved
product is already checked again on save, and a best seller nobody edits was
never checked. Catalogs that fit the limit are unchanged.
The daily run is scheduled for a fixed minute between 1:00 and 5:00 on the
store's clock, at least 6 hours after the run that schedules it, instead of
24 hours after the last run started.
ProductSales::last_days() sums the store total and lists the top products in
SQL, instead of loading every sold product's sales into PHP.
WOOAI-1843
* Agent readiness: a switch to stop the daily check
AI shopping health gets "Check your store every day" in the last checked
card, on by default. Off removes the scheduled daily run, and a check run by
hand no longer schedules one. On schedules the next run for a checked store.
The last checked line no longer ends with "Checks run each day.", as the
switch says it, and the lines that named the next daily check have a form for
when it is off.
WOOAI-1843
* Skip ineligible products when choosing bestsellers for a large catalog
* Mark the large-catalog scan changelog as a dev entry
* Keep ProductScan::start() compatible with existing overrides
* Fix the daily check switch losing a save to an older view read
A poll started before the save could paint the old switch position, and a scan already running could queue another night after daily checks were turned off.
* Agent readiness: content review wording for the daily check switch
The switch reads "Automatically run checks daily". When it is off, a line
under it says how to get an updated report.
WOOAI-1843
* Agent readiness: mark the second option read for PHPStan
The daily option is read again after scheduling because another request can
change it meanwhile. PHPStan can't see that and reported the check as always
false.
* Agent readiness: content review wording for the daily check lines
The lines that say when a check runs next name the Check again button, in
both the daily-on and daily-off forms, and a failed save of the switch says
whether it was being turned on or off.
WOOAI-1843
* Agent readiness: say the product list shows only the products from AI shopping health
Wording from the content review.
WOOAI-1843
* Fix daily checks staying queued and a poll dropping the result
A worker that already read the daily option kept that value, so turning the switch off left the next run queued and that run still scanned. The daily callback reads the saved option and skips the scan when it is off. Turning the switch on during the first check keeps the next run that check already queued. A poll waits while a view read is still in flight, so a slow response that says the check finished is shown.
---------
diff --git a/plugins/woocommerce/changelog/add-agent-readiness-daily-check-setting b/plugins/woocommerce/changelog/add-agent-readiness-daily-check-setting
new file mode 100644
index 00000000000..71a1d9b1b55
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-agent-readiness-daily-check-setting
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: AI shopping health: a switch to stop the daily check. The feature is unreleased.
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/components/checked-card.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/components/checked-card.tsx
index 31f6fc797bc..b88ac998303 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/components/checked-card.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/components/checked-card.tsx
@@ -4,7 +4,7 @@
/* eslint-disable @wordpress/use-recommended-components -- The design asks for these @wordpress/ui components; this chunk bundles the package. */
import { Button, Card, Link, Text } from '@wordpress/ui';
/* eslint-enable @wordpress/use-recommended-components */
-import { Spinner } from '@wordpress/components';
+import { Spinner, ToggleControl } from '@wordpress/components';
import { createInterpolateElement } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
@@ -20,19 +20,23 @@ interface CheckedCardProps {
running: boolean;
onRun: () => void;
onDownloadError: ( message: string ) => void;
+ onDailyChecks?: ( enabled: boolean ) => void;
+ savingDailyChecks?: boolean;
}
/**
* When the store was last checked, with Check again. Before the first check it says Not checked
* yet and offers Check your store. While a check runs it shows a spinner and Checking your store,
* with Check again turned off. From the first check on, Need help? offers the results to
- * download for support (built from the last check).
+ * download for support (built from the last check), and a switch turns the daily check off or on.
*/
export const CheckedCard = ( {
view,
running,
onRun,
onDownloadError,
+ onDailyChecks,
+ savingDailyChecks = false,
}: CheckedCardProps ) => {
const checking = ( view.run.pending && ! view.run.stalled ) || running;
return (
@@ -102,6 +106,28 @@ export const CheckedCard = ( {
</Button>
</div>
{ ! checking && <RunStatus run={ view.run } /> }
+ { view.checked && onDailyChecks && (
+ <div className="wc-sales-readiness-checked__daily">
+ <ToggleControl
+ __nextHasNoMarginBottom
+ label={ __(
+ 'Automatically run checks daily',
+ 'woocommerce'
+ ) }
+ help={
+ view.daily_checks
+ ? undefined
+ : __(
+ 'For an updated report on how well AI assistants can find and shop your store, select Check again above.',
+ 'woocommerce'
+ )
+ }
+ checked={ view.daily_checks }
+ disabled={ savingDailyChecks }
+ onChange={ onDailyChecks }
+ />
+ </div>
+ ) }
</Card.Content>
</Card.Root>
);
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/index.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/index.tsx
index 387de4e5dfa..a2f11e06156 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/index.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/index.tsx
@@ -22,8 +22,15 @@ import { DeclaredCard, SectionCard } from './components/section-card';
* merchant question with the checks from the last scan, and what the store shares with agents.
*/
export default function SalesReadiness() {
- const { view, error, reload, running, runCheck } =
- useReadinessView( 'page' );
+ const {
+ view,
+ error,
+ reload,
+ running,
+ runCheck,
+ setDailyChecks,
+ savingDailyChecks,
+ } = useReadinessView( 'page' );
const [ downloadError, setDownloadError ] = useState( '' );
return (
@@ -60,6 +67,8 @@ export default function SalesReadiness() {
running={ running }
onRun={ runCheck }
onDownloadError={ setDownloadError }
+ onDailyChecks={ setDailyChecks }
+ savingDailyChecks={ savingDailyChecks }
/>
{ view.coming_soon && (
<ComingSoonNotice
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/sales-readiness.scss b/plugins/woocommerce/client/admin/client/sales-readiness/sales-readiness.scss
index e671bd1cd7e..779f48948d1 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/sales-readiness.scss
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/sales-readiness.scss
@@ -452,6 +452,12 @@ body:has(.wc-sales-readiness) {
}
}
+.wc-sales-readiness-checked__daily {
+ margin-block-start: var(--wpds-dimension-gap-lg);
+ padding-block-start: var(--wpds-dimension-gap-lg);
+ border-block-start: 1px solid var(--wpds-color-stroke-surface-neutral-weak);
+}
+
// Download your results: a button styled like the contact support link.
.wc-sales-readiness__link-button {
padding: 0;
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/test/checked-card.test.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/test/checked-card.test.tsx
index 1f11f82ce63..64d7e9c0692 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/test/checked-card.test.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/test/checked-card.test.tsx
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
/**
* Internal dependencies
@@ -111,6 +111,80 @@ describe( 'CheckedCard', () => {
'Checking your store'
);
} );
+
+ it( 'offers the daily check switch once the store has been checked, and reports a change', () => {
+ const onDailyChecks = jest.fn();
+ const checked = {
+ ...firstVisit,
+ last_checked: 'Last checked today at 10:42 am.',
+ checked: true,
+ daily_checks: true,
+ support_url: 'https://example.com/support',
+ run: { ...firstVisit.run, label: 'Check again' },
+ };
+ const { rerender } = render(
+ <CheckedCard
+ view={ checked }
+ running={ false }
+ onRun={ jest.fn() }
+ onDownloadError={ jest.fn() }
+ onDailyChecks={ onDailyChecks }
+ />
+ );
+ const toggle = screen.getByRole( 'checkbox', {
+ name: 'Automatically run checks daily',
+ } );
+ expect( toggle ).toBeChecked();
+ expect( screen.queryByText( /select Check again above/ ) ).toBeNull();
+ fireEvent.click( toggle );
+ expect( onDailyChecks ).toHaveBeenCalledWith( false );
+
+ rerender(
+ <CheckedCard
+ view={ { ...checked, daily_checks: false } }
+ running={ false }
+ onRun={ jest.fn() }
+ onDownloadError={ jest.fn() }
+ onDailyChecks={ onDailyChecks }
+ />
+ );
+ expect(
+ screen.getByText(
+ 'For an updated report on how well AI assistants can find and shop your store, select Check again above.'
+ )
+ ).toBeInTheDocument();
+
+ rerender(
+ <CheckedCard
+ view={ checked }
+ running={ false }
+ onRun={ jest.fn() }
+ onDownloadError={ jest.fn() }
+ onDailyChecks={ onDailyChecks }
+ savingDailyChecks
+ />
+ );
+ expect(
+ screen.getByRole( 'checkbox', {
+ name: 'Automatically run checks daily',
+ } )
+ ).toBeDisabled();
+
+ rerender(
+ <CheckedCard
+ view={ firstVisit }
+ running={ false }
+ onRun={ jest.fn() }
+ onDownloadError={ jest.fn() }
+ onDailyChecks={ onDailyChecks }
+ />
+ );
+ expect(
+ screen.queryByRole( 'checkbox', {
+ name: 'Automatically run checks daily',
+ } )
+ ).toBeNull();
+ } );
} );
describe( 'RowLink', () => {
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/test/use-readiness-view.test.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/test/use-readiness-view.test.tsx
index f3020aae8d7..dd1cd627f60 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/test/use-readiness-view.test.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/test/use-readiness-view.test.tsx
@@ -11,6 +11,7 @@ import {
POLL_FOR_MS,
POLL_MS,
SCAN_PATH,
+ DAILY_CHECKS_PATH,
useReadinessView,
} from '../use-readiness-view';
import { RunStatus } from '../components/run-status';
@@ -190,6 +191,91 @@ describe( 'useReadinessView', () => {
expect.anything()
);
} );
+
+ it( 'saves the daily check switch and reads the view again; a failed save puts the switch back', async () => {
+ mockFetch
+ .mockResolvedValueOnce( { ...view( false ), daily_checks: true } )
+ .mockResolvedValueOnce( { enabled: false } )
+ .mockResolvedValueOnce( { ...view( false ), daily_checks: false } )
+ .mockRejectedValueOnce( new Error( 'offline' ) );
+ const { result } = renderHook( () => useReadinessView( 'page' ) );
+ await act( async () => jest.advanceTimersByTime( 0 ) );
+
+ await act( async () => result.current.setDailyChecks( false ) );
+ expect( mockFetch ).toHaveBeenCalledWith( {
+ path: DAILY_CHECKS_PATH,
+ method: 'POST',
+ data: { enabled: false },
+ } );
+ expect( result.current.view?.daily_checks ).toBe( false );
+ expect( result.current.error ).toBeNull();
+
+ await act( async () => result.current.setDailyChecks( true ) );
+ expect( result.current.view?.daily_checks ).toBe( false );
+ expect( result.current.error ).toBe(
+ 'Automatic daily checks weren’t turned on. Try again in a few minutes.'
+ );
+
+ mockFetch.mockRejectedValueOnce( new Error( 'offline' ) );
+ await act( async () => result.current.setDailyChecks( false ) );
+ expect( result.current.error ).toBe(
+ 'Automatic daily checks weren’t turned off. Try again in a few minutes.'
+ );
+ } );
+
+ it( 'keeps the saved daily check when an older view read returns later', async () => {
+ let finishStale: ( value: unknown ) => void = () => {};
+ mockFetch
+ .mockResolvedValueOnce( { ...view( true ), daily_checks: true } )
+ .mockImplementationOnce(
+ () =>
+ new Promise( ( resolve ) => {
+ finishStale = resolve;
+ } )
+ )
+ .mockResolvedValueOnce( { enabled: false } )
+ .mockResolvedValueOnce( {
+ ...view( false ),
+ daily_checks: false,
+ } );
+ const { result } = renderHook( () => useReadinessView( 'page' ) );
+ await act( async () => jest.advanceTimersByTime( 0 ) );
+
+ await act( async () => jest.advanceTimersByTime( POLL_MS ) );
+ await act( async () => result.current.setDailyChecks( false ) );
+ expect( result.current.view?.daily_checks ).toBe( false );
+
+ await act( async () => {
+ finishStale( { ...view( false ), daily_checks: true } );
+ } );
+ expect( result.current.view?.daily_checks ).toBe( false );
+ expect( result.current.error ).toBeNull();
+ } );
+
+ it( 'waits for a view read to finish before polling again, and shows that result', async () => {
+ let finishPoll: ( value: unknown ) => void = () => {};
+ mockFetch.mockResolvedValueOnce( view( true ) ).mockImplementationOnce(
+ () =>
+ new Promise( ( resolve ) => {
+ finishPoll = resolve;
+ } )
+ );
+ const { result } = renderHook( () => useReadinessView( 'page' ) );
+ await act( async () => jest.advanceTimersByTime( 0 ) );
+ expect( result.current.view?.run.pending ).toBe( true );
+
+ await act( async () => jest.advanceTimersByTime( POLL_MS ) );
+ await act( async () => jest.advanceTimersByTime( POLL_MS * 3 ) );
+ // The first load, then one poll. Later ticks wait for that poll.
+ expect( viewCalls() ).toBe( 2 );
+ expect( result.current.view?.run.pending ).toBe( true );
+
+ await act( async () => {
+ finishPoll( view( false, 'Check again' ) );
+ } );
+ expect( result.current.view?.run.label ).toBe( 'Check again' );
+ expect( result.current.view?.run.pending ).toBe( false );
+ } );
} );
describe( 'RunStatus', () => {
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/types.ts b/plugins/woocommerce/client/admin/client/sales-readiness/types.ts
index fb0ee66ed7b..cc198f46a3e 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/types.ts
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/types.ts
@@ -114,6 +114,8 @@ export interface ReadinessView {
checked_note: string | null;
/** False before the first check. */
checked: boolean;
+ /** Whether the store is checked every day. */
+ daily_checks: boolean;
run: {
label: string;
pending: boolean;
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/use-readiness-view.ts b/plugins/woocommerce/client/admin/client/sales-readiness/use-readiness-view.ts
index 88fc1472e30..37b7d0b1391 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/use-readiness-view.ts
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/use-readiness-view.ts
@@ -13,6 +13,7 @@ import { trackReadiness, viewedProps, type Surface } from './tracks';
export const VIEW_PATH = '/wc/v3/agent-readiness/view';
export const SCAN_PATH = '/wc/v3/agent-readiness/scan';
+export const DAILY_CHECKS_PATH = '/wc/v3/agent-readiness/daily-checks';
/**
* How often the view is read again while a check is pending, so its results show once it finishes.
@@ -40,18 +41,28 @@ export function useReadinessView(
// True when the results didn't load, so the page shows no Check again and offers Reload page.
const [ reload, setReload ] = useState( false );
const [ running, setRunning ] = useState( false );
+ // True while the daily check switch is being saved, so a second click can't race the first.
+ const [ savingDailyChecks, setSavingDailyChecks ] = useState( false );
const viewed = useRef( false );
const pendingSince = useRef< number | null >( null );
// True after a view has been shown: poll failures must not spam Tracks, replace the view or stop polling.
const hasView = useRef( initialView !== null );
const mounted = useRef( true );
+ // The latest view read wins, so a poll that started before a save can't put the switch back.
+ const viewRead = useRef( 0 );
+ // The view read that has not returned. The next poll waits, so a slow read can't discard the one that says the check finished.
+ const viewFlight = useRef( 0 );
+ // True while the daily switch is saving, so a poll can't start with the switch's old position.
+ const pausePoll = useRef( false );
const load = useCallback( async () => {
+ const read = ++viewRead.current;
+ viewFlight.current = read;
try {
const loaded = await apiFetch< ReadinessView >( {
path: VIEW_PATH,
} );
- if ( ! mounted.current ) {
+ if ( ! mounted.current || read !== viewRead.current ) {
return;
}
setView( loaded );
@@ -63,7 +74,11 @@ export function useReadinessView(
trackReadiness( 'viewed', viewedProps( loaded, surface ) );
}
} catch {
- if ( ! mounted.current || hasView.current ) {
+ if (
+ ! mounted.current ||
+ read !== viewRead.current ||
+ hasView.current
+ ) {
return;
}
trackReadiness( 'error', { surface, action: 'load' } );
@@ -74,6 +89,10 @@ export function useReadinessView(
'woocommerce'
)
);
+ } finally {
+ if ( viewFlight.current === read ) {
+ viewFlight.current = 0;
+ }
}
}, [ surface ] );
@@ -105,6 +124,10 @@ export function useReadinessView(
clearInterval( timer );
return;
}
+ // A poll still waiting, or a switch save, would make this read stale before it returned.
+ if ( viewFlight.current !== 0 || pausePoll.current ) {
+ return;
+ }
void load();
}, POLL_MS );
return () => clearInterval( timer );
@@ -132,5 +155,62 @@ export function useReadinessView(
}
}, [ load, surface, view?.checked ] );
- return { view, error, reload, running, runCheck };
+ // Shows the switch in its new position at once, then reads the view again: some rows say when checks run next.
+ const setDailyChecks = useCallback(
+ async ( enabled: boolean ) => {
+ // Drop a view read already in flight. It still has the switch's old position.
+ ++viewRead.current;
+ pausePoll.current = true;
+ setView(
+ ( current ) => current && { ...current, daily_checks: enabled }
+ );
+ setSavingDailyChecks( true );
+ try {
+ await apiFetch( {
+ path: DAILY_CHECKS_PATH,
+ method: 'POST',
+ data: { enabled },
+ } );
+ await load();
+ } catch {
+ if ( ! mounted.current ) {
+ return;
+ }
+ // A poll that started during the save must not clear this error.
+ ++viewRead.current;
+ trackReadiness( 'error', { surface, action: 'daily_checks' } );
+ setView(
+ ( current ) =>
+ current && { ...current, daily_checks: ! enabled }
+ );
+ setError(
+ enabled
+ ? __(
+ 'Automatic daily checks weren’t turned on. Try again in a few minutes.',
+ 'woocommerce'
+ )
+ : __(
+ 'Automatic daily checks weren’t turned off. Try again in a few minutes.',
+ 'woocommerce'
+ )
+ );
+ } finally {
+ pausePoll.current = false;
+ if ( mounted.current ) {
+ setSavingDailyChecks( false );
+ }
+ }
+ },
+ [ load, surface ]
+ );
+
+ return {
+ view,
+ error,
+ reload,
+ running,
+ runCheck,
+ setDailyChecks,
+ savingDailyChecks,
+ };
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
index 3ade1e476fd..d925471659e 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
@@ -329,7 +329,7 @@ class ProductsList {
}
printf(
'<div class="notice notice-info"><p>%s <a href="%s">%s</a></p></div>',
- esc_html__( 'Showing products from AI shopping health.', 'woocommerce' ),
+ esc_html__( 'Showing only products from AI shopping health.', 'woocommerce' ),
esc_url( admin_url( 'edit.php?post_type=product' ) ),
esc_html__( 'Show all products', 'woocommerce' )
);
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/README.md b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
index e13cceb483d..d3151ad90c2 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/README.md
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
@@ -186,7 +186,7 @@ Per check, `channels` maps a channel id to the feed field and the effect, the sa
## Background scan and REST
-"Check your store" on WooCommerce > Sales readiness, or `POST wc/v3/agent-readiness/scan`, queues the scan in Action Scheduler (`ScheduledScan`). The report is stored in the `woocommerce_agent_readiness_report` option (not autoloaded). Each run schedules the next one for the coming night before scanning (`ScheduledScan::next_daily_run()`: a minute between 1:00 and 5:00 on the store's clock, fixed per store by its address), so a failed scan doesn't stop the daily refresh and a run that starts late doesn't move the next one. A slot less than 6 hours away is left for the night after. Cancelling the scheduled actions under Tools > Scheduled Actions stops the chain until the next manual check. If a queued scan still hasn't started 10 minutes after it was due and no other scheduled action has finished, failed or started in that time (Action Scheduler isn't running), the Sales readiness page says so and the scan stays queued. The scan never runs in a page or REST request.
+"Check your store" on WooCommerce > Sales readiness, or `POST wc/v3/agent-readiness/scan`, queues the scan in Action Scheduler (`ScheduledScan`). The report is stored in the `woocommerce_agent_readiness_report` option (not autoloaded). When daily checks are on, each run schedules the next one for the coming night before scanning (`ScheduledScan::next_daily_run()`: a minute between 1:00 and 5:00 on the store's clock, fixed per store by its address), so a failed scan doesn't stop the daily refresh and a run that starts late doesn't move the next one. A slot less than 6 hours away is left for the night after. "Automatically run checks daily" on the page (`POST wc/v3/agent-readiness/daily-checks`, option `woocommerce_agent_readiness_daily_scan`) turns the daily run off: its action is removed, runs schedule no next one, and checks only run on request. Cancelling the scheduled actions under Tools > Scheduled Actions stops the chain until the next manual check. If a queued scan still hasn't started 10 minutes after it was due and no other scheduled action has finished, failed or started in that time (Action Scheduler isn't running), the Sales readiness page says so and the scan stays queued. The scan never runs in a page or REST request.
A scan runs as a chain of actions (`NEXT_HOOK`, with the scan's id), so no action tests more than one batch of products. The first lists the products to test, newest change first (on a catalog over 5,000 products with sales to rank by, best sellers of the last 90 days first, skipping any the scan does not check and reading the next sellers until the limit is filled or the sales run out, then newest change), and stores that list with the totals in the `woocommerce_agent_readiness_scan` option (not autoloaded). Starting reads the store's 90-day totals once (`ProductSales::last_days()`). When those totals say the scan can rank, it then reads the best seller ids, summed in SQL and limited to published products, so memory doesn't grow with the number of products sold. A page of sellers the scan cannot check is followed by the next page, up to ten pages. Each later batch reads only its own products' sales, so the whole store's sales map is never loaded. Each action tests the next batch of 200, saves the totals and queues the next; the last builds the report, with the store output checks, and stores it. Before testing, an action queues a retry RETRY_AFTER (10 minutes) later, which it removes when it finishes, so a batch that ends early, as on a timeout, is tried again from the last finished batch. After MAX_ATTEMPTS (3) tries of the same batch, the scan stops and the last report stays. Giving up, cancelling, or replacing a scan removes failure rows it wrote for products the last report never covered, so the Products list stays aligned with that report. A new request (or the daily run) replaces a scan in progress and starts over; the replaced scan's actions change nothing. `refresh_report()` runs the same steps in one request.
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php
index 7f0549fdd8b..0df668bc018 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php
@@ -327,6 +327,8 @@ class ReadinessCheckPage implements RegisterHooksInterface {
'last_checked' => self::last_checked( $report ),
'checked_note' => $truncated,
'checked' => null !== $report,
+ // Whether the store is checked every day; the merchant can turn it off on the page.
+ 'daily_checks' => ScheduledScan::daily_enabled(),
'run' => array(
'label' => null === $report ? __( 'Check your store', 'woocommerce' ) : __( 'Check again', 'woocommerce' ),
'pending' => $pending,
@@ -611,10 +613,10 @@ class ReadinessCheckPage implements RegisterHooksInterface {
}
if ( wp_date( 'Y-m-d', $time ) === wp_date( 'Y-m-d' ) ) {
/* translators: %s: time of day, such as 10:42 am. */
- return sprintf( __( 'Last checked today at %s. Checks run each day.', 'woocommerce' ), wp_date( (string) get_option( 'time_format' ), $time ) );
+ return sprintf( __( 'Last checked today at %s.', 'woocommerce' ), wp_date( (string) get_option( 'time_format' ), $time ) );
}
/* translators: 1: date, such as November 3, 2026. 2: time of day, such as 10:42 am. */
- return sprintf( __( 'Last checked %1$s at %2$s. Checks run each day.', 'woocommerce' ), wp_date( (string) get_option( 'date_format' ), $time ), wp_date( (string) get_option( 'time_format' ), $time ) );
+ return sprintf( __( 'Last checked %1$s at %2$s.', 'woocommerce' ), wp_date( (string) get_option( 'date_format' ), $time ), wp_date( (string) get_option( 'time_format' ), $time ) );
}
@@ -835,9 +837,19 @@ class ReadinessCheckPage implements RegisterHooksInterface {
}
// Checked in coming soon mode, then the store went live: nothing was blocked; the checks haven't run since.
if ( false === $was_live ) {
- return array( __( 'Your store wasn’t live at the last check', 'woocommerce' ), __( 'These checks run at the next daily check, or you can run the check again now.', 'woocommerce' ) );
+ return array(
+ __( 'Your store wasn’t live at the last check', 'woocommerce' ),
+ ScheduledScan::daily_enabled()
+ ? __( 'If your store is live now, these checks run at the next daily check. To run them now, select Check again.', 'woocommerce' )
+ : __( 'If your store is live now, select Check again to run these checks.', 'woocommerce' ),
+ );
}
- return array( __( 'Your pages couldn’t be checked', 'woocommerce' ), __( 'Your hosting setup blocked the check from opening them. Checks run again each day. If this keeps happening, contact your hosting provider.', 'woocommerce' ) );
+ return array(
+ __( 'Your pages couldn’t be checked', 'woocommerce' ),
+ ScheduledScan::daily_enabled()
+ ? __( 'Your hosting setup blocked the check from opening them. Checks run again each day. If this keeps happening, contact your hosting provider.', 'woocommerce' )
+ : __( 'Your hosting setup blocked the check from opening them. Select Check again to try again later. If this keeps happening, contact your hosting provider.', 'woocommerce' ),
+ );
}
/**
@@ -864,12 +876,22 @@ class ReadinessCheckPage implements RegisterHooksInterface {
return array( true, __( 'Launch your store to run this check.', 'woocommerce' ) );
}
if ( false === $was_live ) {
- return array( true, __( 'Your store wasn’t live at the last check. This check runs at the next daily check, or you can run the check again now.', 'woocommerce' ) );
+ return array(
+ true,
+ ScheduledScan::daily_enabled()
+ ? __( 'Your store wasn’t live at the last check. If it’s live now, this check runs at the next daily check, or select Check again to run it now.', 'woocommerce' )
+ : __( 'Your store wasn’t live at the last check. If it’s live now, select Check again to run this check.', 'woocommerce' ),
+ );
}
if ( ! empty( $check['no_product'] ) ) {
return array( true, __( 'This check needs a product page. It runs once you have a published product that AI assistants can see.', 'woocommerce' ) );
}
- return array( false, __( 'This check couldn’t run. It runs again each day, or you can run the check again now.', 'woocommerce' ) );
+ return array(
+ false,
+ ScheduledScan::daily_enabled()
+ ? __( 'This check couldn’t run. It runs again each day, or select Check again to run it now.', 'woocommerce' )
+ : __( 'This check couldn’t run. Select Check again to try again.', 'woocommerce' ),
+ );
}
/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessRestController.php b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessRestController.php
index ff67e164d18..b01e8da1aa1 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessRestController.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessRestController.php
@@ -136,6 +136,24 @@ class ReadinessRestController extends RestApiControllerBase {
'schema' => array( $this, 'get_support_report_schema' ),
)
);
+ register_rest_route(
+ $this->route_namespace,
+ '/agent-readiness/daily-checks',
+ array(
+ array(
+ 'methods' => \WP_REST_Server::CREATABLE,
+ 'callback' => fn( $request ) => $this->run( $request, 'set_daily_checks' ),
+ 'permission_callback' => fn( $request ) => $this->check_permission( $request, 'manage_woocommerce' ),
+ 'args' => array(
+ 'enabled' => array(
+ 'description' => __( 'Whether the store is checked every day.', 'woocommerce' ),
+ 'type' => 'boolean',
+ 'required' => true,
+ ),
+ ),
+ ),
+ )
+ );
register_rest_route(
$this->route_namespace,
'/agent-readiness/ucp',
@@ -212,6 +230,18 @@ class ReadinessRestController extends RestApiControllerBase {
return new \WP_REST_Response( $this->get_status( $request ), 202 );
}
+ /**
+ * Turn the daily check on or off. Off, checks only run when asked for.
+ *
+ * @param WP_REST_Request $request Request.
+ * @phpstan-param WP_REST_Request<array<string, mixed>> $request
+ * @return array{enabled:bool}
+ */
+ protected function set_daily_checks( WP_REST_Request $request ): array {
+ $this->scheduled_scan->set_daily_enabled( (bool) $request->get_param( 'enabled' ) );
+ return array( 'enabled' => ScheduledScan::daily_enabled() );
+ }
+
/**
* Turn UCP on or off. A failing required check keeps it from being turned on, and that request answers 409.
*
@@ -298,6 +328,11 @@ class ReadinessRestController extends RestApiControllerBase {
'type' => 'boolean',
'context' => array( 'view' ),
),
+ 'daily_checks' => array(
+ 'description' => __( 'Whether the store is checked every day.', 'woocommerce' ),
+ 'type' => 'boolean',
+ 'context' => array( 'view' ),
+ ),
'run' => array(
'description' => __( 'The check button: its label, whether a check is pending or stalled, and a status message.', 'woocommerce' ),
'type' => 'object',
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php b/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
index 2f9e40f7329..fb86340fc19 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
@@ -13,7 +13,8 @@ defined( 'ABSPATH' ) || exit;
* and keeps the stored report fresh with one run a day.
*
* Each run schedules the next one for the coming night, on the store's clock
- * (next_daily_run()), so nothing is queued until a
+ * (next_daily_run()), unless the merchant turned daily checks off (DAILY_OPTION),
+ * so nothing is queued until a
* merchant or the REST API asks for the first scan, and no request pays for a
* scheduling check. The next run is scheduled before the scan, so a scan that
* fails or times out does not end the chain. Cancelling the scheduled actions
@@ -46,6 +47,11 @@ class ScheduledScan implements RegisterHooksInterface {
public const GROUP = 'woocommerce-agent-readiness';
+ /**
+ * Option that holds whether the store is checked every day: 'no' when the merchant turned it off.
+ */
+ public const DAILY_OPTION = 'woocommerce_agent_readiness_daily_scan';
+
/**
* Hours of the night, on the store's clock, between which the daily scan is scheduled.
*/
@@ -173,20 +179,94 @@ class ScheduledScan implements RegisterHooksInterface {
}
/**
- * Schedule the next daily run, fetch the rules file, then start the scan, replacing one in progress.
+ * When daily checks are on, schedule the next one, then fetch the rules file and start the scan, replacing one in progress.
+ * A daily run does nothing when the saved switch is off, so one queued before the merchant turned it off does not scan.
* Each batch of products runs in its own action, then the last stores the report.
*
* @internal
*/
public function run(): void {
- as_unschedule_all_actions( self::DAILY_HOOK, array(), self::GROUP );
- as_schedule_single_action( self::next_daily_run(), self::DAILY_HOOK, array(), self::GROUP );
+ // The row in the database, not the value this request already read. The merchant may have saved since.
+ if ( self::DAILY_HOOK === current_action() && ! self::daily_enabled_saved() ) {
+ as_unschedule_all_actions( self::DAILY_HOOK, array(), self::GROUP );
+ return;
+ }
+
+ $this->sync_daily_run();
$this->remote_rules->refresh( array_keys( $this->agent_readiness->get_default_rules() ) );
as_unschedule_all_actions( self::NEXT_HOOK );
as_schedule_single_action( time(), self::NEXT_HOOK, array( $this->agent_readiness->start_refresh() ), self::GROUP );
}
+ /**
+ * Whether the store is checked every day. On unless the merchant turned it off.
+ *
+ * @since 11.4.0
+ */
+ public static function daily_enabled(): bool {
+ return 'no' !== get_option( self::DAILY_OPTION, 'yes' );
+ }
+
+ /**
+ * Turn the daily scan on or off. Off removes the scheduled run, and checks only run on request.
+ * On schedules the next run once the store has been checked, or when a check is already running.
+ * Before the first check, nothing is queued.
+ *
+ * @since 11.4.0
+ *
+ * @param bool $enable Whether to check the store every day.
+ */
+ public function set_daily_enabled( bool $enable ): void {
+ update_option( self::DAILY_OPTION, $enable ? 'yes' : 'no', false );
+ // A check already running queued its next run before it saved a report. Keep that run.
+ if ( $enable && null === $this->agent_readiness->get_cached_report() && ! $this->is_pending() ) {
+ as_unschedule_all_actions( self::DAILY_HOOK, array(), self::GROUP );
+ return;
+ }
+ $this->sync_daily_run();
+ }
+
+ /**
+ * Queue the next nightly run when daily checks are on, and remove it when they are off.
+ * The saved option is read again after scheduling, so a switch turned off while this runs drops the queued run.
+ */
+ private function sync_daily_run(): void {
+ as_unschedule_all_actions( self::DAILY_HOOK, array(), self::GROUP );
+ if ( ! self::daily_enabled_saved() ) {
+ return;
+ }
+ as_schedule_single_action( self::next_daily_run(), self::DAILY_HOOK, array(), self::GROUP );
+ $this->drop_queued_daily_run_if_off();
+ }
+
+ /**
+ * Remove the run just queued when daily checks were turned off while it was stored.
+ */
+ private function drop_queued_daily_run_if_off(): void {
+ if ( self::daily_enabled_saved() ) {
+ return;
+ }
+ as_unschedule_all_actions( self::DAILY_HOOK, array(), self::GROUP );
+ }
+
+ /**
+ * Whether daily checks are on in the database.
+ * get_option() would repeat the value this request already read, which can be from before the merchant saved.
+ */
+ private static function daily_enabled_saved(): bool {
+ global $wpdb;
+
+ $value = $wpdb->get_var(
+ $wpdb->prepare(
+ "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
+ self::DAILY_OPTION
+ )
+ );
+
+ return ! is_string( $value ) || 'no' !== $value;
+ }
+
/**
* When the next daily scan is due: the next time the store's clock shows its night slot.
* The slot is a minute between NIGHT_FROM and NIGHT_TO, fixed per store by its address,
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
index 8e31e452129..6994fa0a547 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
@@ -677,7 +677,7 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
'fix_url' => '',
);
update_option( AgentReadiness::REPORT_OPTION, array( 'store_checks' => array( $launched( true ), $sitemap, $robots ) ), false );
- $this->assertSame( 'This check couldn’t run. It runs again each day, or you can run the check again now.', $this->row( 'Add a sitemap that lists your products' )['text'], 'Titled by what the check looks for, not as if it passed' );
+ $this->assertSame( 'This check couldn’t run. It runs again each day, or select Check again to run it now.', $this->row( 'Add a sitemap that lists your products' )['text'], 'Titled by what the check looks for, not as if it passed' );
update_option( AgentReadiness::REPORT_OPTION, array( 'store_checks' => array( $launched( true ), $sitemap, array( 'ok' => null ) + $robots ) ), false );
$card = array_column( $this->view()['sections'], null, 'id' )['find'];
@@ -685,6 +685,16 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
$this->assertSame( array( 'Your pages couldn’t be checked' ), array_column( $card['rows'], 'title' ), 'One row for the card, not one per check' );
$this->assertFalse( $card['rows'][0]['waiting'], 'Screen readers hear Couldn\'t check' );
$this->assertSame( 'Your hosting setup blocked the check from opening them. Checks run again each day. If this keeps happening, contact your hosting provider.', $card['rows'][0]['text'] );
+ $this->assertTrue( $this->view()['daily_checks'] );
+
+ update_option( ScheduledScan::DAILY_OPTION, 'no' );
+ $card = array_column( $this->view()['sections'], null, 'id' )['find'];
+ $this->assertSame( 'Your hosting setup blocked the check from opening them. Select Check again to try again later. If this keeps happening, contact your hosting provider.', $card['rows'][0]['text'], 'With daily checks off, no line says they run each day' );
+ $this->assertFalse( $this->view()['daily_checks'] );
+ update_option( AgentReadiness::REPORT_OPTION, array( 'store_checks' => array( $launched( true ), $sitemap, $robots ) ), false );
+ $this->assertSame( 'This check couldn’t run. Select Check again to try again.', $this->row( 'Add a sitemap that lists your products' )['text'] );
+ delete_option( ScheduledScan::DAILY_OPTION );
+ update_option( AgentReadiness::REPORT_OPTION, array( 'store_checks' => array( $launched( true ), $sitemap, array( 'ok' => null ) + $robots ) ), false );
update_option( 'woocommerce_coming_soon', 'yes' );
$card = array_column( $this->view()['sections'], null, 'id' )['find'];
@@ -698,7 +708,11 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
update_option( AgentReadiness::REPORT_OPTION, array( 'store_checks' => array( $launched( false ), $sitemap, array( 'ok' => null ) + $robots ) ), false );
$card = array_column( $this->view()['sections'], null, 'id' )['find'];
$this->assertSame( 'Your store wasn’t live at the last check', $card['rows'][0]['title'] );
- $this->assertSame( 'These checks run at the next daily check, or you can run the check again now.', $card['rows'][0]['text'] );
+ $this->assertSame( 'If your store is live now, these checks run at the next daily check. To run them now, select Check again.', $card['rows'][0]['text'] );
+ update_option( ScheduledScan::DAILY_OPTION, 'no' );
+ $card = array_column( $this->view()['sections'], null, 'id' )['find'];
+ $this->assertSame( 'If your store is live now, select Check again to run these checks.', $card['rows'][0]['text'], 'With daily checks off, the line still says the merchant can run the check' );
+ delete_option( ScheduledScan::DAILY_OPTION );
$this->assertSame( 'Not checked yet', $card['badge']['text'], 'The checks wait for the next run after launch' );
$this->assertTrue( $card['rows'][0]['waiting'], 'Screen readers hear Not checked yet' );
}
@@ -725,7 +739,11 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
list( $badge, $by_id ) = $rows();
$this->assertSame( 'Not checked yet', $badge );
$this->assertTrue( $by_id['sitemap_lists_products']['waiting'], 'Screen readers hear Not checked yet' );
- $this->assertSame( 'Your store wasn’t live at the last check. This check runs at the next daily check, or you can run the check again now.', $by_id['sitemap_lists_products']['text'] );
+ $this->assertSame( 'Your store wasn’t live at the last check. If it’s live now, this check runs at the next daily check, or select Check again to run it now.', $by_id['sitemap_lists_products']['text'] );
+ update_option( ScheduledScan::DAILY_OPTION, 'no' );
+ $by_id = $rows()[1];
+ $this->assertSame( 'Your store wasn’t live at the last check. If it’s live now, select Check again to run this check.', $by_id['sitemap_lists_products']['text'] );
+ delete_option( ScheduledScan::DAILY_OPTION );
update_option( AgentReadiness::REPORT_OPTION, array( 'store_checks' => array( $check( 'launched', true, array( 'group' => 'access' ) ), $check( 'canonical_url', null, array( 'no_product' => true ) ), $check( 'robots_txt', true ) ) ), false );
list( $badge, $by_id ) = $rows();
@@ -1655,7 +1673,7 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
update_option( 'date_format', 'F j, Y' );
update_option( 'time_format', 'g:i a' );
update_option( 'timezone_string', 'UTC' );
- $this->assertSame( 'Last checked November 18, 2026 at 9:14 am. Checks run each day.', $last->invoke( null, array( 'generated_at' => '2026-11-18T09:14:00+00:00' ) ), 'An earlier day reads as a date, then at and the time' );
+ $this->assertSame( 'Last checked November 18, 2026 at 9:14 am.', $last->invoke( null, array( 'generated_at' => '2026-11-18T09:14:00+00:00' ) ), 'An earlier day reads as a date, then at and the time' );
$this->assertNotNull( $view['fix_first'], 'When it last ran, Fix first, then a card per question' );
$brand = $this->row( 'Add a brand to ' . $product->get_name() );
$this->assertSame( 'ChatGPT only lists products that have a brand. In Google and Copilot, a brand makes products easier to find.', $brand['text'], 'One failing product is named in the title; the text says why a brand matters' );
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
index 818d8141ff1..90dbd317a8d 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
@@ -338,7 +338,7 @@ class ProductsListTest extends WC_Unit_Test_Case {
$_GET[ ProductsList::FILTER_PARAM ] = 'missing_images';
$html = $notice();
- $this->assertStringContainsString( 'Showing products from AI shopping health.', $html );
+ $this->assertStringContainsString( 'Showing only products from AI shopping health.', $html );
$this->assertStringContainsString( 'Show all products</a>', $html );
$this->assertStringContainsString( 'href="' . esc_url( admin_url( 'edit.php?post_type=product' ) ) . '"', $html, 'The link drops the filter' );
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
index 9eca699c49d..10f790d03b8 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
@@ -382,7 +382,7 @@ class ReadinessRestControllerTest extends WC_REST_Unit_Test_Case {
false
);
$text = $this->server->dispatch( new WP_REST_Request( 'GET', '/wc/v3/agent-readiness/support-report' ) )->get_data()['text'];
- $this->assertStringContainsString( "### Store checks ###\n\nYour store wasn’t live at the last check. These checks run at the next daily check, or you can run the check again now.", $text );
+ $this->assertStringContainsString( "### Store checks ###\n\nYour store wasn’t live at the last check. If your store is live now, these checks run at the next daily check. To run them now, select Check again.", $text );
$this->assertStringNotContainsString( 'Your hosting setup blocked', $text );
$this->assertStringContainsString( 'Open Graph tags (open_graph_tags): Not checked yet. Your store wasn’t live at the last check.', $text, 'Each check says so too, as on the page' );
$this->assertStringContainsString( 'Shipping details (product_shipping_schema): Not available yet', $text, 'A check a coming update builds is still not available' );
@@ -639,6 +639,54 @@ class ReadinessRestControllerTest extends WC_REST_Unit_Test_Case {
$this->assertSame( 'no', get_option( 'woocommerce_feature_ucp_enabled' ) );
}
+ /**
+ * @testdox POST daily-checks turns the daily check off, which removes the scheduled run, and on again, which schedules it for a checked store.
+ */
+ public function test_daily_checks_switch(): void {
+ \WC_Helper_Product::create_simple_product();
+ wc_get_container()->get( AgentReadiness::class )->refresh_report();
+ $scheduled = wc_get_container()->get( ScheduledScan::class );
+ $scheduled->set_daily_enabled( true );
+ $this->assertIsInt( as_next_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ) );
+
+ $response = $this->dispatch_daily_checks( false );
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertFalse( $response->get_data()['enabled'] );
+ $this->assertFalse( as_has_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ) );
+
+ $scheduled->run();
+ $this->assertFalse( as_has_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ), 'A check run by hand does not bring the daily one back' );
+
+ $response = $this->dispatch_daily_checks( true );
+ $this->assertTrue( $response->get_data()['enabled'] );
+ $this->assertSame( ScheduledScan::next_daily_run(), as_next_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ) );
+ }
+
+ /**
+ * @testdox Before the first check, turning daily checks on queues nothing, and a user without manage_woocommerce can't change the setting.
+ */
+ public function test_daily_checks_switch_before_first_check_and_permission(): void {
+ delete_option( AgentReadiness::REPORT_OPTION );
+
+ $this->assertTrue( $this->dispatch_daily_checks( true )->get_data()['enabled'] );
+ $this->assertFalse( as_has_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ) );
+
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'customer' ) ) );
+ $this->assertSame( 403, $this->dispatch_daily_checks( false )->get_status() );
+ $this->assertTrue( ScheduledScan::daily_enabled() );
+ }
+
+ /**
+ * Send POST wc/v3/agent-readiness/daily-checks.
+ *
+ * @param bool $enabled Whether to check the store every day.
+ */
+ private function dispatch_daily_checks( bool $enabled ): \WP_REST_Response {
+ $request = new WP_REST_Request( 'POST', '/wc/v3/agent-readiness/daily-checks' );
+ $request->set_param( 'enabled', $enabled );
+ return $this->server->dispatch( $request );
+ }
+
/**
* Send POST wc/v3/agent-readiness/ucp.
*
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
index 2dac52f0f8e..f789c9e3038 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
@@ -381,6 +381,122 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
$this->assertCount( 1, $this->pending( ScheduledScan::DAILY_HOOK ) );
}
+ /**
+ * @testdox A daily run does not scan when the saved switch is off, even while this request still has the old value cached.
+ */
+ public function test_daily_run_skips_when_the_saved_switch_is_off(): void {
+ update_option( ScheduledScan::DAILY_OPTION, 'no', false );
+ $this->cache_daily_checks_as_on();
+ $this->assertTrue( ScheduledScan::daily_enabled(), 'This request still has daily checks cached as on' );
+
+ $this->run_daily_hook();
+
+ $this->assertFalse( as_has_scheduled_action( ScheduledScan::NEXT_HOOK, null, ScheduledScan::GROUP ) );
+ $this->assertFalse( as_has_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ) );
+ $this->assertNull( wc_get_container()->get( AgentReadiness::class )->get_cached_report() );
+ }
+
+ /**
+ * @testdox The daily run still scans when the switch is on.
+ */
+ public function test_daily_run_scans_when_the_switch_is_on(): void {
+ WC_Helper_Product::create_simple_product();
+
+ $this->run_daily_hook();
+
+ $this->assertTrue( $this->sut->is_pending() );
+ $this->assertCount( 1, $this->pending( ScheduledScan::DAILY_HOOK ) );
+ }
+
+ /**
+ * @testdox A next run queued as the switch is turned off is dropped, even when this request cached the old value during the queue.
+ */
+ public function test_daily_run_queued_as_the_switch_turns_off_is_dropped(): void {
+ update_option( ScheduledScan::DAILY_OPTION, 'yes', false );
+ WC_Helper_Product::create_simple_product();
+ $flipped = false;
+ $flip = function ( $action_id ) use ( &$flipped ) {
+ if ( $flipped ) {
+ return;
+ }
+ $action = \ActionScheduler::store()->fetch_action( (int) $action_id );
+ if ( ScheduledScan::DAILY_HOOK !== $action->get_hook() ) {
+ return;
+ }
+ $flipped = true;
+ update_option( ScheduledScan::DAILY_OPTION, 'no', false );
+ $this->cache_daily_checks_as_on();
+ };
+ add_action( 'action_scheduler_stored_action', $flip );
+
+ try {
+ $this->sut->run();
+ } finally {
+ remove_action( 'action_scheduler_stored_action', $flip );
+ }
+
+ $this->assertTrue( $flipped, 'The switch turned off while the next run was queued' );
+ $this->assertTrue( ScheduledScan::daily_enabled(), 'This request still has daily checks cached as on' );
+ $this->assertFalse( as_has_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ) );
+ }
+
+ /**
+ * @testdox Turning daily checks on while the first check is running keeps the next run that check already queued.
+ */
+ public function test_enabling_daily_checks_during_the_first_scan_keeps_its_next_run(): void {
+ delete_option( AgentReadiness::REPORT_OPTION );
+ WC_Helper_Product::create_simple_product();
+
+ $this->sut->run();
+ $queued = as_next_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP );
+
+ $this->assertNull( wc_get_container()->get( AgentReadiness::class )->get_cached_report() );
+ $this->assertTrue( $this->sut->is_pending() );
+ $this->assertIsInt( $queued );
+ $this->sut->set_daily_enabled( true );
+
+ $this->assertSame( $queued, as_next_scheduled_action( ScheduledScan::DAILY_HOOK, array(), ScheduledScan::GROUP ) );
+ }
+
+ /**
+ * Run the daily scan the way Action Scheduler does, so the callback can tell it from a check run by hand.
+ */
+ private function run_daily_hook(): void {
+ $callback = array( $this->sut, 'run' );
+ $added = false === has_action( ScheduledScan::DAILY_HOOK, $callback );
+ if ( $added ) {
+ add_action( ScheduledScan::DAILY_HOOK, $callback );
+ }
+ try {
+ do_action( ScheduledScan::DAILY_HOOK );
+ } finally {
+ if ( $added ) {
+ remove_action( ScheduledScan::DAILY_HOOK, $callback );
+ }
+ }
+ }
+
+ /**
+ * Leave this request's option caches saying daily checks are on, whatever the database row says.
+ */
+ private function cache_daily_checks_as_on(): void {
+ wp_cache_set( ScheduledScan::DAILY_OPTION, 'yes', 'options' );
+
+ $alloptions = wp_cache_get( 'alloptions', 'options' );
+ if ( ! is_array( $alloptions ) ) {
+ $alloptions = array();
+ }
+ $alloptions[ ScheduledScan::DAILY_OPTION ] = 'yes';
+ wp_cache_set( 'alloptions', $alloptions, 'options' );
+
+ $notoptions = wp_cache_get( 'notoptions', 'options' );
+ if ( ! is_array( $notoptions ) ) {
+ $notoptions = array();
+ }
+ $notoptions[ ScheduledScan::DAILY_OPTION ] = true;
+ wp_cache_set( 'notoptions', $notoptions, 'options' );
+ }
+
/**
* Run the scan's batch actions as Action Scheduler would, until the scan stores its report.
*