From 774ddc8476df9b62a2e5a19d17bed45d051b2a7d Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 22 Jul 2026 14:41:52 +0800 Subject: [PATCH 1/6] Premium Analytics: keep HTTP status on failed Stats API requests --- .../changelog/fix-stats-api-error-status | 4 + .../__tests__/error-status-middleware.test.ts | 120 ++++++++++++++++++ .../data/src/api/error-status-middleware.ts | 96 ++++++++++++++ .../packages/data/src/api/index.ts | 4 + .../packages/data/src/index.ts | 10 +- .../src/utils/__tests__/api-error.test.ts | 68 +++++----- .../packages/data/src/utils/api-error.ts | 32 ++--- .../packages/data/src/utils/index.ts | 8 +- .../packages/init/package.json | 1 + .../packages/init/src/index.ts | 4 + .../stories/mocks/register-report-mocks.ts | 9 +- .../widgets/devices/render.tsx | 32 ++--- .../widgets/devices/use-device-views.ts | 7 +- .../widgets/top-platforms/render.tsx | 32 ++--- .../top-platforms/use-platform-views.ts | 7 +- 15 files changed, 315 insertions(+), 119 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/fix-stats-api-error-status create mode 100644 projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts create mode 100644 projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts diff --git a/projects/packages/premium-analytics/changelog/fix-stats-api-error-status b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status new file mode 100644 index 000000000000..ad4ca065f788 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status @@ -0,0 +1,4 @@ +Significance: patch +Type: fixed + +Stats data layer: keep the HTTP status on failed API requests so retry, auth, and error handling behave correctly, and stop deriving plan state from ambiguous error codes. diff --git a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts new file mode 100644 index 000000000000..c575fc1dfa6b --- /dev/null +++ b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts @@ -0,0 +1,120 @@ +/** + * The middleware branches on `instanceof Response`, so it needs the real + * WHATWG `Response`. The shared jsdom environment does not provide one. + * + * @jest-environment node + */ + +/** + * Internal dependencies + */ +import { apiErrorStatusMiddleware } from '../error-status-middleware'; + +function jsonResponse( body: unknown, status: number ): Response { + return new Response( JSON.stringify( body ), { + status, + headers: { 'Content-Type': 'application/json' }, + } ); +} + +function run( response: unknown, options: Record< string, unknown > = {} ) { + const next = jest.fn().mockResolvedValue( response ); + return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) }; +} + +describe( 'apiErrorStatusMiddleware', () => { + it( 'attaches the HTTP status to a non-2xx error body', async () => { + const { result } = run( jsonResponse( { error: 'unauthorized', message: 'Nope.' }, 401 ) ); + + await expect( result ).rejects.toEqual( { + error: 'unauthorized', + message: 'Nope.', + status: 401, + } ); + } ); + + it.each( [ 502, 503, 504 ] )( 'attaches a %d server status', async status => { + const { result } = run( jsonResponse( { error: 'api_error', message: 'Upstream.' }, status ) ); + + await expect( result ).rejects.toMatchObject( { status } ); + } ); + + it( 'does not overwrite a status the body already provides at the top level', async () => { + const { result } = run( jsonResponse( { code: 'rest_forbidden', status: 403 }, 500 ) ); + + await expect( result ).rejects.toEqual( { code: 'rest_forbidden', status: 403 } ); + } ); + + it( 'leaves a WP_Error data.status alone while adding the top-level status', async () => { + const { result } = run( + jsonResponse( { code: 'rest_forbidden', message: 'Sorry.', data: { status: 403 } }, 403 ) + ); + + await expect( result ).rejects.toEqual( { + code: 'rest_forbidden', + message: 'Sorry.', + data: { status: 403 }, + status: 403, + } ); + } ); + + it( 'returns null for a 204 response', async () => { + const { result } = run( new Response( null, { status: 204 } ) ); + + await expect( result ).resolves.toBeNull(); + } ); + + it( 'parses a successful JSON response', async () => { + const { result } = run( jsonResponse( { ok: true }, 200 ) ); + + await expect( result ).resolves.toEqual( { ok: true } ); + } ); + + it( 'throws the invalid_json shape when a successful body is not JSON', async () => { + const { result } = run( new Response( 'not json', { status: 200 } ) ); + + await expect( result ).rejects.toEqual( { + code: 'invalid_json', + message: 'The response is not a valid JSON response.', + } ); + } ); + + it( 'throws the invalid_json shape when an error body is not JSON', async () => { + const { result } = run( new Response( '500', { status: 500 } ) ); + + await expect( result ).rejects.toEqual( { + code: 'invalid_json', + message: 'The response is not a valid JSON response.', + } ); + } ); + + it( 'passes the raw Response through untouched when the caller set parse: false', async () => { + const response = jsonResponse( { error: 'nope' }, 500 ); + const { next, result } = run( response, { parse: false } ); + + await expect( result ).resolves.toBe( response ); + expect( next ).toHaveBeenCalledWith( { path: '/x', parse: false } ); + } ); + + it( 'returns a non-Response value from next() unchanged', async () => { + const mocked = { data: [ 1, 2, 3 ] }; + const { result } = run( mocked ); + + await expect( result ).resolves.toBe( mocked ); + } ); + + it( 'leaves unbounded per_page=-1 queries to apiFetch so fetchAllMiddleware still paginates', async () => { + const mocked = [ { id: 1 } ]; + const { next, result } = run( mocked, { path: '/wp/v2/thing?per_page=-1' } ); + + await expect( result ).resolves.toBe( mocked ); + expect( next ).toHaveBeenCalledWith( { path: '/wp/v2/thing?per_page=-1' } ); + } ); + + it( 'forces parse: false on the request it forwards', async () => { + const { next } = run( jsonResponse( { ok: true }, 200 ), { method: 'POST' } ); + + await Promise.resolve(); + expect( next ).toHaveBeenCalledWith( { path: '/x', method: 'POST', parse: false } ); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts new file mode 100644 index 000000000000..2a1f34864010 --- /dev/null +++ b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts @@ -0,0 +1,96 @@ +/** + * External dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +import { __ } from '@wordpress/i18n'; +import type { APIFetchMiddleware } from '@wordpress/api-fetch'; + +/** + * apiFetch's own parse step throws the parsed JSON body and drops the `Response`, + * so the HTTP status is lost. Most Premium Analytics failures are WPCOM + * pass-throughs shaped `{ error, message }` with no status in the body, which + * leaves the data layer unable to tell a 401 from a 502. This middleware takes + * over parsing to keep the status on the thrown error. + * + * The parse semantics below intentionally mirror `parseResponseAndNormalizeError` + * / `parseAndThrowError` in `@wordpress/api-fetch`. + */ + +async function parseJsonAndNormalizeError( response: Response ): Promise< unknown > { + try { + return await response.json(); + } catch { + // Same shape apiFetch throws. The string is core's — translating it under + // this package's domain would hand non-English users a different message + // for the identical failure, so it stays on the `default` domain. + throw { + code: 'invalid_json', + // eslint-disable-next-line @wordpress/i18n-text-domain + message: __( 'The response is not a valid JSON response.', 'default' ), + }; + } +} + +function isPlainErrorBody( body: unknown ): body is Record< string, unknown > { + return typeof body === 'object' && body !== null && ! Array.isArray( body ); +} + +function containsUnboundedQuery( options: { path?: string; url?: string } ): boolean { + return !! options.path?.includes( 'per_page=-1' ) || !! options.url?.includes( 'per_page=-1' ); +} + +export const apiErrorStatusMiddleware: APIFetchMiddleware = async ( options, next ) => { + // The caller wants the raw `Response` (e.g. the CSV export download), so + // apiFetch's own pass-through behavior is already what they get. + if ( options.parse === false ) { + return next( options ); + } + + // apiFetch always keeps its built-in middlewares innermost, so this one + // necessarily wraps `fetchAllMiddleware` — and that middleware bails out on + // `parse: false`. Forcing parse off here would silently disable `per_page=-1` + // pagination (which the dashboard uses to enumerate widget modules), so leave + // unbounded queries to apiFetch's own handling. + if ( containsUnboundedQuery( options ) ) { + return next( options ); + } + + const result = await next( { ...options, parse: false } ); + + // Load-bearing, not defensive padding: a middleware registered outside this + // one can short-circuit and resolve with already-parsed data instead of a + // `Response` — Storybook's report mocks do exactly that. + if ( ! ( result instanceof Response ) ) { + return result; + } + + if ( ! result.ok ) { + const body = await parseJsonAndNormalizeError( result ); + + // Our own `WP_Error` responses carry `data.status`; adding a top-level + // `status` is fine, but never overwrite one the body already provides. + if ( isPlainErrorBody( body ) && ! ( 'status' in body ) ) { + throw { ...body, status: result.status }; + } + + throw body; + } + + if ( result.status === 204 ) { + return null; + } + + return parseJsonAndNormalizeError( result ); +}; + +// apiFetch middleware registers onto a shared, process-wide chain, so guard +// against a second registration from a re-mount or HMR. +let registered = false; + +export function registerApiErrorStatusMiddleware(): void { + if ( registered ) { + return; + } + registered = true; + apiFetch.use( apiErrorStatusMiddleware ); +} diff --git a/projects/packages/premium-analytics/packages/data/src/api/index.ts b/projects/packages/premium-analytics/packages/data/src/api/index.ts index 08dae2352ba7..82c7eca328c8 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/index.ts @@ -41,6 +41,10 @@ export { fetchReportVisitors } from './report-visitors-fetch'; export { fetchReportVisitorsByLocation } from './report-visitors-by-location-fetch'; export { fetchReportBookings } from './report-bookings-fetch'; export { fetchReportSessionsByDevice } from './report-sessions-by-device-fetch'; +export { + apiErrorStatusMiddleware, + registerApiErrorStatusMiddleware, +} from './error-status-middleware'; export { downloadReport, exportReport } from './report-export-fetch'; export type { DownloadReportParams, diff --git a/projects/packages/premium-analytics/packages/data/src/index.ts b/projects/packages/premium-analytics/packages/data/src/index.ts index 4659ccb85764..42d38329b696 100644 --- a/projects/packages/premium-analytics/packages/data/src/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/index.ts @@ -234,13 +234,11 @@ export { computeDateRangeFromPreset, getApiErrorCode, getApiErrorStatus, - getStatsPlanErrorReason, saveBlob, shouldRetryApiError, toPostId, useSiteHomeUrl, } from './utils'; -export type { StatsPlanErrorReason } from './utils'; export type { ReportDataMap } from './types'; export type { ReportQueryParams } from './api'; export type { FilterCondition } from './types/filter-condition'; @@ -248,7 +246,13 @@ export type { ProductType } from './types/product-type'; export { ORDER_ATTRIBUTION_VIEWS } from './api/report-order-attribution-summary-fetch'; export { getDefaultIntervalForPeriod, getDateFormatFromInterval } from './utils/interval'; export { getDefaultPreset, getDefaultQueryParams } from './defaults'; -export { downloadReport, exportReport, fetchStatsProxy, getStatsProxyPath } from './api'; +export { + downloadReport, + exportReport, + fetchStatsProxy, + getStatsProxyPath, + registerApiErrorStatusMiddleware, +} from './api'; export type { DownloadReportParams, DownloadReportResponse, diff --git a/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts b/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts index 4723bd9a3dfc..318bf7347faf 100644 --- a/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts @@ -1,17 +1,16 @@ -import { - getApiErrorCode, - getApiErrorStatus, - getStatsPlanErrorReason, - shouldRetryApiError, -} from '../api-error'; +import { getApiErrorCode, getApiErrorStatus, shouldRetryApiError } from '../api-error'; + +// Two envelopes reach the client: our own `WP_Error` responses +// (`{ code, message, data: { status } }`) and WPCOM pass-through errors +// (`{ error, message }`, with the status attached separately by the fetch layer). describe( 'getApiErrorStatus', () => { it( 'returns status from a top-level status property', () => { - expect( getApiErrorStatus( { status: 403 } ) ).toBe( 403 ); + expect( getApiErrorStatus( { error: 'unauthorized', status: 403 } ) ).toBe( 403 ); } ); it( 'returns status from WordPress REST error data', () => { - expect( getApiErrorStatus( { data: { status: 401 } } ) ).toBe( 401 ); + expect( getApiErrorStatus( { code: 'no_connection', data: { status: 401 } } ) ).toBe( 401 ); } ); it( 'returns status from a nested response object', () => { @@ -20,13 +19,24 @@ describe( 'getApiErrorStatus', () => { it( 'returns null when no numeric status is available', () => { expect( getApiErrorStatus( { data: { status: '403' } } ) ).toBeNull(); + expect( + getApiErrorStatus( { error: 'unauthorized', message: 'user cannot view stats' } ) + ).toBeNull(); expect( getApiErrorStatus( null ) ).toBeNull(); } ); } ); describe( 'getApiErrorCode', () => { - it( 'returns a top-level WordPress REST error code', () => { - expect( getApiErrorCode( { code: 'no_connection' } ) ).toBe( 'no_connection' ); + it( 'returns the code from a WP_Error envelope', () => { + expect( getApiErrorCode( { code: 'no_connection', data: { status: 403 } } ) ).toBe( + 'no_connection' + ); + } ); + + it( 'returns the code from a WPCOM pass-through envelope', () => { + expect( getApiErrorCode( { error: 'unauthorized', message: 'user cannot view stats' } ) ).toBe( + 'unauthorized' + ); } ); it( 'returns a nested data error code', () => { @@ -35,14 +45,30 @@ describe( 'getApiErrorCode', () => { it( 'returns null when no string code is available', () => { expect( getApiErrorCode( { code: 403 } ) ).toBeNull(); + expect( getApiErrorCode( { error: 403 } ) ).toBeNull(); expect( getApiErrorCode( null ) ).toBeNull(); } ); } ); describe( 'shouldRetryApiError', () => { - it( 'does not retry authentication or authorization errors', () => { - expect( shouldRetryApiError( 0, { status: 401 } ) ).toBe( false ); - expect( shouldRetryApiError( 0, { data: { status: 403 } } ) ).toBe( false ); + it( 'does not retry deterministic failures', () => { + expect( shouldRetryApiError( 0, { code: 'rest_forbidden', data: { status: 401 } } ) ).toBe( + false + ); + expect( + shouldRetryApiError( 0, { + error: 'unauthorized', + message: 'user cannot view stats', + status: 403, + } ) + ).toBe( false ); + expect( + shouldRetryApiError( 0, { + error: 'not_found', + message: 'The requested resource was not found.', + status: 404, + } ) + ).toBe( false ); } ); it( 'retries other errors up to three failures', () => { @@ -51,19 +77,3 @@ describe( 'shouldRetryApiError', () => { expect( shouldRetryApiError( 3, { status: 500 } ) ).toBe( false ); } ); } ); - -describe( 'getStatsPlanErrorReason', () => { - it( 'returns upgrade-required for plan-gated authorization errors', () => { - expect( getStatsPlanErrorReason( { data: { status: 403, code: 'rest_forbidden' } } ) ).toBe( - 'upgrade-required' - ); - } ); - - it( 'returns null for non-plan authorization errors', () => { - expect( getStatsPlanErrorReason( { status: 403, code: 'no_connection' } ) ).toBeNull(); - } ); - - it( 'returns null for non-authorization errors', () => { - expect( getStatsPlanErrorReason( { status: 500 } ) ).toBeNull(); - } ); -} ); diff --git a/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts b/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts index 5070d9dd0341..b2247d5e7481 100644 --- a/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts +++ b/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts @@ -38,6 +38,9 @@ export function getApiErrorStatus( error: unknown ): number | null { /** * Extract an API error code from common WordPress REST error shapes. * + * WPCOM pass-through errors (every real Stats failure) put the code in `error`, + * while our own `WP_Error` responses use `code`. + * * @param error - Unknown thrown error. * @return Error code, or null when unavailable. */ @@ -52,6 +55,10 @@ export function getApiErrorCode( error: unknown ): string | null { return err.code; } + if ( typeof err.error === 'string' ) { + return err.error; + } + if ( err.data && typeof err.data === 'object' ) { const data = err.data as Record< string, unknown >; if ( typeof data.code === 'string' ) { @@ -62,30 +69,11 @@ export function getApiErrorCode( error: unknown ): string | null { return null; } -export type StatsPlanErrorReason = 'upgrade-required' | null; - -const NON_PLAN_FORBIDDEN_ERROR_CODES = new Set( [ 'no_connection' ] ); - -/** - * Maps Stats API errors to widget-level plan error reasons. - * - * @param error - Unknown thrown error. - * @return The plan error reason when the response is plan-gated. - */ -export function getStatsPlanErrorReason( error: unknown ): StatsPlanErrorReason { - const errorCode = getApiErrorCode( error ); - - return getApiErrorStatus( error ) === 403 && - ! NON_PLAN_FORBIDDEN_ERROR_CODES.has( errorCode ?? '' ) - ? 'upgrade-required' - : null; -} - /** * Determine whether a failed API query should be retried. * - * Authentication and authorization failures are deterministic for the current - * user/session, so retrying only delays the widget-specific error UI. + * Authentication, authorization and not-found failures are deterministic for the + * current user/session, so retrying only delays the widget-specific error UI. * * @param failureCount - Number of failed attempts so far. * @param error - Unknown thrown error. @@ -94,7 +82,7 @@ export function getStatsPlanErrorReason( error: unknown ): StatsPlanErrorReason export function shouldRetryApiError( failureCount: number, error: unknown ): boolean { const status = getApiErrorStatus( error ); - if ( status === 401 || status === 403 ) { + if ( status === 401 || status === 403 || status === 404 ) { return false; } diff --git a/projects/packages/premium-analytics/packages/data/src/utils/index.ts b/projects/packages/premium-analytics/packages/data/src/utils/index.ts index 21ef175b2222..238ddedcb00f 100644 --- a/projects/packages/premium-analytics/packages/data/src/utils/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/utils/index.ts @@ -5,13 +5,7 @@ export { getSiteTimezone, getSiteGmtOffset, } from './date'; -export { - getApiErrorCode, - getApiErrorStatus, - getStatsPlanErrorReason, - shouldRetryApiError, -} from './api-error'; -export type { StatsPlanErrorReason } from './api-error'; +export { getApiErrorCode, getApiErrorStatus, shouldRetryApiError } from './api-error'; export { ensureCoreSettingsReady } from './ensure-core-settings'; export { getDefaultIntervalForPeriod } from './interval'; export { safeParseInt, safeParseFloat } from './parsing'; diff --git a/projects/packages/premium-analytics/packages/init/package.json b/projects/packages/premium-analytics/packages/init/package.json index f9475e8fbe39..6e83b23ab38c 100644 --- a/projects/packages/premium-analytics/packages/init/package.json +++ b/projects/packages/premium-analytics/packages/init/package.json @@ -8,6 +8,7 @@ "wpScriptModuleExports": "./build-module/index.mjs", "dependencies": { "@automattic/jetpack-script-data": "workspace:*", + "@jetpack-premium-analytics/data": "workspace:*", "@wordpress/api-fetch": "7.51.0", "@wordpress/boot": "0.18.0", "@wordpress/data": "10.51.0", diff --git a/projects/packages/premium-analytics/packages/init/src/index.ts b/projects/packages/premium-analytics/packages/init/src/index.ts index 4dd80aa0b7f7..552068c45521 100644 --- a/projects/packages/premium-analytics/packages/init/src/index.ts +++ b/projects/packages/premium-analytics/packages/init/src/index.ts @@ -2,6 +2,7 @@ * External dependencies */ import { getScriptData } from '@automattic/jetpack-script-data'; +import { registerApiErrorStatusMiddleware } from '@jetpack-premium-analytics/data'; import apiFetch from '@wordpress/api-fetch'; import { store as bootStore } from '@wordpress/boot'; import { dispatch } from '@wordpress/data'; @@ -40,6 +41,9 @@ function setupApiFetch(): void { * Runs before routes render. */ export async function init(): Promise< void > { + // Keeps the HTTP status on failed requests, which the data layer's error + // handling reads. Self-guarding against duplicate registration. + registerApiErrorStatusMiddleware(); setupApiFetch(); dispatch( bootStore ).updateMenuItem( 'dashboard', { diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts index dd3164a0d163..f2c28e34fe54 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts @@ -1255,12 +1255,13 @@ const reportMocksMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio // (`summary` / `days` / `data`), so the widget resolves to its empty state. return { date: '2026-01-01', period: 'day', summary: {}, days: {}, data: [] }; } - // A 403 is not retried by `shouldRetryApiError`, so the error UI shows at - // once instead of after the query's retry backoff. + // The WPCOM pass-through error envelope, with the status attached the way + // the fetch layer attaches it. A 403 is not retried by `shouldRetryApiError`, + // so the error UI shows at once instead of after the query's retry backoff. return Promise.reject( { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response for Storybook.', - data: { status: 403 }, + status: 403, } ); } diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 20d0373b75ba..fabf16b32ed7 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -56,12 +56,11 @@ type DevicesInnerProps = { */ function DevicesInner( { max }: DevicesInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { data, hasComparison, isLoading, isFetching, isError, errorReason, refetch } = - useDeviceViews( { - reportParams, - max, - deviceProperty: 'screensize', - } ); + const { data, hasComparison, isLoading, isFetching, isError, refetch } = useDeviceViews( { + reportParams, + max, + deviceProperty: 'screensize', + } ); const chartData: SemiCircleChartData = data.map( item => ( { label: item.displayLabel, @@ -88,10 +87,6 @@ function DevicesInner( { max }: DevicesInnerProps ) { color: segmentStyles[ index ]?.color, } ) ); - // A plan error can't be fixed by retrying, so the Retry action is only - // offered for regular fetch failures. - const isPlanError = errorReason === 'upgrade-required'; - return (
void; } @@ -89,9 +88,8 @@ export default function useDeviceViews( { deviceProperty, }; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = + const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = useStatsDevices( statsParams, { maxRows: max } ); - const errorReason = getStatsPlanErrorReason( error ); const items = ( comparisonRows?.rows ?? [] ).map( toDeviceView ); @@ -105,7 +103,6 @@ export default function useDeviceViews( { // flips true. Only surface the error when there's nothing to show, so a transient // refetch failure doesn't replace populated rows with the error state. isError: items.length === 0 && isError, - errorReason, // The data layer's combined refetch: memoized, awaits both queries, and // skips the comparison query when comparison is disabled. refetch, diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index def803a7a3de..75519979c801 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -55,12 +55,11 @@ type TopPlatformsInnerProps = { function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { data, hasComparison, isLoading, isFetching, isError, errorReason, refetch } = - usePlatformViews( { - reportParams, - max, - deviceProperty: platformDimension, - } ); + const { data, hasComparison, isLoading, isFetching, isError, refetch } = usePlatformViews( { + reportParams, + max, + deviceProperty: platformDimension, + } ); const maxViews = Math.max( ...data.map( d => d.views ), 0 ); const maxComparisonViews = Math.max( ...data.map( d => d.previousViews ?? 0 ), 0 ); @@ -89,10 +88,6 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) }; } ); - // A plan error can't be fixed by retrying, so the Retry action is only - // offered for regular fetch failures. - const isPlanError = errorReason === 'upgrade-required'; - return (
void; } @@ -100,9 +99,8 @@ export default function usePlatformViews( { deviceProperty, }; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = + const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = useStatsDevices( statsParams, { maxRows: max } ); - const errorReason = getStatsPlanErrorReason( error ); const rows = ( comparisonRows?.rows ?? [] ).map( item => toPlatformView( item, deviceProperty ) ); @@ -116,7 +114,6 @@ export default function usePlatformViews( { // flips true. Only surface the error when there's nothing to show, so a transient // refetch failure doesn't replace populated rows with the error state. isError: rows.length === 0 && isError, - errorReason, // The data layer's combined refetch: memoized, awaits both queries, and // skips the comparison query when comparison is disabled. refetch, From 91ee39bea6d2fd1904ef93f75e10061bf0718819 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 22 Jul 2026 15:11:42 +0800 Subject: [PATCH 2/6] Premium Analytics: parse error Responses that apiFetch rejects, keep status on invalid JSON --- .../__tests__/error-status-middleware.test.ts | 83 ++++++++++++++----- .../data/src/api/error-status-middleware.ts | 62 ++++++++++---- 2 files changed, 106 insertions(+), 39 deletions(-) diff --git a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts index c575fc1dfa6b..0119a2de2dfd 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts @@ -17,14 +17,35 @@ function jsonResponse( body: unknown, status: number ): Response { } ); } -function run( response: unknown, options: Record< string, unknown > = {} ) { - const next = jest.fn().mockResolvedValue( response ); +/** + * A `next` that behaves like apiFetch's own chain under `parse: false`: it + * resolves the raw `Response` for a 2xx and rejects with the raw `Response` + * for a non-2xx (see `parseAndThrowError` in `@wordpress/api-fetch`). Error + * tests that resolve a failed response instead would exercise a branch the + * real chain never reaches. + */ +function runResponse( response: Response, options: Record< string, unknown > = {} ) { + const next = jest.fn( () => + response.ok ? Promise.resolve( response ) : Promise.reject( response ) + ); + return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) }; +} + +function runResolved( value: unknown, options: Record< string, unknown > = {} ) { + const next = jest.fn().mockResolvedValue( value ); + return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) }; +} + +function runRejected( value: unknown, options: Record< string, unknown > = {} ) { + const next = jest.fn().mockRejectedValue( value ); return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) }; } describe( 'apiErrorStatusMiddleware', () => { - it( 'attaches the HTTP status to a non-2xx error body', async () => { - const { result } = run( jsonResponse( { error: 'unauthorized', message: 'Nope.' }, 401 ) ); + it( 'attaches the HTTP status to a rejected non-2xx error body', async () => { + const { result } = runResponse( + jsonResponse( { error: 'unauthorized', message: 'Nope.' }, 401 ) + ); await expect( result ).rejects.toEqual( { error: 'unauthorized', @@ -34,19 +55,35 @@ describe( 'apiErrorStatusMiddleware', () => { } ); it.each( [ 502, 503, 504 ] )( 'attaches a %d server status', async status => { - const { result } = run( jsonResponse( { error: 'api_error', message: 'Upstream.' }, status ) ); + const { result } = runResponse( + jsonResponse( { error: 'api_error', message: 'Upstream.' }, status ) + ); await expect( result ).rejects.toMatchObject( { status } ); } ); + it( 'keeps the status when a non-2xx body is not JSON (gateway HTML/text)', async () => { + // A 502/503/504 page is commonly HTML; parsing throws invalid_json, but + // the status must still reach the server-error UI and the retry guard. + const { result } = runResponse( + new Response( '502 Bad Gateway', { status: 502 } ) + ); + + await expect( result ).rejects.toEqual( { + code: 'invalid_json', + message: 'The response is not a valid JSON response.', + status: 502, + } ); + } ); + it( 'does not overwrite a status the body already provides at the top level', async () => { - const { result } = run( jsonResponse( { code: 'rest_forbidden', status: 403 }, 500 ) ); + const { result } = runResponse( jsonResponse( { code: 'rest_forbidden', status: 403 }, 500 ) ); await expect( result ).rejects.toEqual( { code: 'rest_forbidden', status: 403 } ); } ); it( 'leaves a WP_Error data.status alone while adding the top-level status', async () => { - const { result } = run( + const { result } = runResponse( jsonResponse( { code: 'rest_forbidden', message: 'Sorry.', data: { status: 403 } }, 403 ) ); @@ -58,29 +95,29 @@ describe( 'apiErrorStatusMiddleware', () => { } ); } ); + it( 'rethrows a non-Response rejection untouched (offline / fetch / abort)', async () => { + // apiFetch rejects offline and network failures with a bare + // `{ code, message }` and no Response; there is no status to add. + const offline = { code: 'offline_error', message: 'Unable to connect.' }; + const { result } = runRejected( offline ); + + await expect( result ).rejects.toBe( offline ); + } ); + it( 'returns null for a 204 response', async () => { - const { result } = run( new Response( null, { status: 204 } ) ); + const { result } = runResponse( new Response( null, { status: 204 } ) ); await expect( result ).resolves.toBeNull(); } ); it( 'parses a successful JSON response', async () => { - const { result } = run( jsonResponse( { ok: true }, 200 ) ); + const { result } = runResponse( jsonResponse( { ok: true }, 200 ) ); await expect( result ).resolves.toEqual( { ok: true } ); } ); it( 'throws the invalid_json shape when a successful body is not JSON', async () => { - const { result } = run( new Response( 'not json', { status: 200 } ) ); - - await expect( result ).rejects.toEqual( { - code: 'invalid_json', - message: 'The response is not a valid JSON response.', - } ); - } ); - - it( 'throws the invalid_json shape when an error body is not JSON', async () => { - const { result } = run( new Response( '500', { status: 500 } ) ); + const { result } = runResponse( new Response( 'not json', { status: 200 } ) ); await expect( result ).rejects.toEqual( { code: 'invalid_json', @@ -90,7 +127,7 @@ describe( 'apiErrorStatusMiddleware', () => { it( 'passes the raw Response through untouched when the caller set parse: false', async () => { const response = jsonResponse( { error: 'nope' }, 500 ); - const { next, result } = run( response, { parse: false } ); + const { next, result } = runResolved( response, { parse: false } ); await expect( result ).resolves.toBe( response ); expect( next ).toHaveBeenCalledWith( { path: '/x', parse: false } ); @@ -98,21 +135,21 @@ describe( 'apiErrorStatusMiddleware', () => { it( 'returns a non-Response value from next() unchanged', async () => { const mocked = { data: [ 1, 2, 3 ] }; - const { result } = run( mocked ); + const { result } = runResolved( mocked ); await expect( result ).resolves.toBe( mocked ); } ); it( 'leaves unbounded per_page=-1 queries to apiFetch so fetchAllMiddleware still paginates', async () => { const mocked = [ { id: 1 } ]; - const { next, result } = run( mocked, { path: '/wp/v2/thing?per_page=-1' } ); + const { next, result } = runResolved( mocked, { path: '/wp/v2/thing?per_page=-1' } ); await expect( result ).resolves.toBe( mocked ); expect( next ).toHaveBeenCalledWith( { path: '/wp/v2/thing?per_page=-1' } ); } ); it( 'forces parse: false on the request it forwards', async () => { - const { next } = run( jsonResponse( { ok: true }, 200 ), { method: 'POST' } ); + const { next } = runResponse( jsonResponse( { ok: true }, 200 ), { method: 'POST' } ); await Promise.resolve(); expect( next ).toHaveBeenCalledWith( { path: '/x', method: 'POST', parse: false } ); diff --git a/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts index 2a1f34864010..1e44376f6ce4 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts @@ -35,6 +35,34 @@ function isPlainErrorBody( body: unknown ): body is Record< string, unknown > { return typeof body === 'object' && body !== null && ! Array.isArray( body ); } +/** + * Turn a rejected error `Response` into the thrown error the caller expects, + * with the HTTP status attached. + * + * The body of a gateway failure (502/503/504) is often HTML or plain text, so + * parsing can itself fail. Either way the status must survive: it is what the + * server-error UI and the retry guard key off. On a parse failure we keep + * apiFetch's own `invalid_json` shape and still attach the status. + */ +async function normalizeErrorResponse( response: Response ): Promise< unknown > { + const { status } = response; + + let body: unknown; + try { + body = await parseJsonAndNormalizeError( response ); + } catch ( parseError ) { + body = parseError; + } + + // Our own `WP_Error` responses carry `data.status`; adding a top-level + // `status` is fine, but never overwrite one the body already provides. + if ( isPlainErrorBody( body ) && ! ( 'status' in body ) ) { + return { ...body, status }; + } + + return body; +} + function containsUnboundedQuery( options: { path?: string; url?: string } ): boolean { return !! options.path?.includes( 'per_page=-1' ) || !! options.url?.includes( 'per_page=-1' ); } @@ -55,27 +83,29 @@ export const apiErrorStatusMiddleware: APIFetchMiddleware = async ( options, nex return next( options ); } - const result = await next( { ...options, parse: false } ); + let result: unknown; + try { + result = await next( { ...options, parse: false } ); + } catch ( thrown ) { + // With `parse: false`, apiFetch throws the raw `Response` for a non-2xx + // reply rather than returning it (see `parseAndThrowError`). This catch + // is where every real API error lands. Anything that is not a + // `Response` — an offline/fetch error, an `AbortError`, a mock's own + // rejection — has no HTTP status to add, so rethrow it untouched. + if ( thrown instanceof Response ) { + throw await normalizeErrorResponse( thrown ); + } + throw thrown; + } - // Load-bearing, not defensive padding: a middleware registered outside this - // one can short-circuit and resolve with already-parsed data instead of a - // `Response` — Storybook's report mocks do exactly that. + // A resolved value that is not a `Response` means a middleware outside this + // one short-circuited with already-parsed data — Storybook's report mocks + // do exactly that. A resolved `Response` is always 2xx: apiFetch only + // throws (never resolves) a non-ok one. if ( ! ( result instanceof Response ) ) { return result; } - if ( ! result.ok ) { - const body = await parseJsonAndNormalizeError( result ); - - // Our own `WP_Error` responses carry `data.status`; adding a top-level - // `status` is fine, but never overwrite one the body already provides. - if ( isPlainErrorBody( body ) && ! ( 'status' in body ) ) { - throw { ...body, status: result.status }; - } - - throw body; - } - if ( result.status === 204 ) { return null; } From 32f559c3cbb3cb6bf29156e352925215ff4c3558 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Wed, 22 Jul 2026 15:32:27 +0800 Subject: [PATCH 3/6] Premium Analytics: cover register guard, non-object bodies, url unbounded queries --- .../__tests__/error-status-middleware.test.ts | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts index 0119a2de2dfd..8b6d5a08297e 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts @@ -5,10 +5,17 @@ * @jest-environment node */ +/** + * External dependencies + */ +import apiFetch from '@wordpress/api-fetch'; /** * Internal dependencies */ -import { apiErrorStatusMiddleware } from '../error-status-middleware'; +import { + apiErrorStatusMiddleware, + registerApiErrorStatusMiddleware, +} from '../error-status-middleware'; function jsonResponse( body: unknown, status: number ): Response { return new Response( JSON.stringify( body ), { @@ -95,6 +102,20 @@ describe( 'apiErrorStatusMiddleware', () => { } ); } ); + it( 'throws a non-object JSON error body as-is without attaching status', async () => { + // `isPlainErrorBody` exists so `status` is never spread into arrays, + // strings, or null — spreading an array would mangle it into an object. + const { result } = runResponse( jsonResponse( [ 'boom' ], 500 ) ); + + await expect( result ).rejects.toEqual( [ 'boom' ] ); + } ); + + it( 'throws a JSON string error body as-is', async () => { + const { result } = runResponse( jsonResponse( 'boom', 502 ) ); + + await expect( result ).rejects.toBe( 'boom' ); + } ); + it( 'rethrows a non-Response rejection untouched (offline / fetch / abort)', async () => { // apiFetch rejects offline and network failures with a bare // `{ code, message }` and no Response; there is no status to add. @@ -148,6 +169,15 @@ describe( 'apiErrorStatusMiddleware', () => { expect( next ).toHaveBeenCalledWith( { path: '/wp/v2/thing?per_page=-1' } ); } ); + it( 'leaves unbounded per_page=-1 url-based queries to apiFetch as well', async () => { + const url = 'https://example.com/wp-json/wp/v2/thing?per_page=-1'; + const mocked = [ { id: 1 } ]; + const { next, result } = runResolved( mocked, { url } ); + + await expect( result ).resolves.toBe( mocked ); + expect( next ).toHaveBeenCalledWith( { path: '/x', url } ); + } ); + it( 'forces parse: false on the request it forwards', async () => { const { next } = runResponse( jsonResponse( { ok: true }, 200 ), { method: 'POST' } ); @@ -155,3 +185,19 @@ describe( 'apiErrorStatusMiddleware', () => { expect( next ).toHaveBeenCalledWith( { path: '/x', method: 'POST', parse: false } ); } ); } ); + +describe( 'registerApiErrorStatusMiddleware', () => { + it( 'registers with apiFetch only once across repeated calls', () => { + const use = jest.spyOn( apiFetch, 'use' ).mockImplementation( () => {} ); + + try { + registerApiErrorStatusMiddleware(); + registerApiErrorStatusMiddleware(); + + expect( use ).toHaveBeenCalledTimes( 1 ); + expect( use ).toHaveBeenCalledWith( apiErrorStatusMiddleware ); + } finally { + use.mockRestore(); + } + } ); +} ); From 64bc15207e0caf3377e8fb6afbe07a947a87d7b7 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Mon, 27 Jul 2026 11:21:16 +0800 Subject: [PATCH 4/6] Premium Analytics: share Stats widget error descriptions (#50729) * refactor: share Stats widget error descriptions * fix: keep no_connection 403 retryable, gate hook errors, use full-sentence retry copy * test: add retryable error stories for the shared Stats error mapper --- projects/packages/premium-analytics/AGENTS.md | 35 ++++++---- .../premium-analytics/changelog/wooa7s-1649 | 4 ++ .../helpers/__tests__/describe-error.test.ts | 66 +++++++++++++++++++ .../src/helpers/describe-error.ts | 51 ++++++++++++++ .../widgets-toolkit/src/helpers/index.ts | 1 + .../packages/widgets-toolkit/src/index.ts | 1 + .../stories/mocks/register-report-mocks.ts | 21 ++++-- .../widgets/devices/render.tsx | 11 ++-- .../stories/devices-widget.stories.tsx | 20 +++++- .../widgets/devices/use-device-views.ts | 17 +++-- .../__tests__/search-terms.test.tsx | 1 + .../widgets/search-terms/render.tsx | 18 ++--- .../stories/search-terms-widget.stories.tsx | 20 +++++- .../search-terms/use-search-term-views.ts | 16 +++-- .../widgets/stories/force-stats-mock-state.ts | 18 ++++- .../widgets/top-platforms/render.tsx | 21 +++--- .../stories/top-platforms-widget.stories.tsx | 20 +++++- .../top-platforms/use-platform-views.ts | 17 +++-- .../widgets/utm-insights/render.tsx | 11 ++-- .../stories/utm-insights-widget.stories.tsx | 20 +++++- .../widgets/utm-insights/use-utm-insights.ts | 17 +++-- 21 files changed, 329 insertions(+), 77 deletions(-) create mode 100644 projects/packages/premium-analytics/changelog/wooa7s-1649 create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts create mode 100644 projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts diff --git a/projects/packages/premium-analytics/AGENTS.md b/projects/packages/premium-analytics/AGENTS.md index dcb630baa9db..70192e20ad6a 100644 --- a/projects/packages/premium-analytics/AGENTS.md +++ b/projects/packages/premium-analytics/AGENTS.md @@ -465,13 +465,17 @@ module has a special failure mode. Prefer adding those shapes to the widget's ex over creating one-off state stories unless the state needs direct review. To review a widget's loading / error / empty state directly, force it with -`setReportMockState( '', 'loading' | 'error' | 'empty' )` in the story's `beforeEach`, -clearing it in the returned cleanup. Keep such stories off the shared autodocs page -(`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise force the -sibling stories into the same state) and give each one a date preset distinct from the other -stories so it hits the mock fresh instead of reading their cached success. See +`setReportMockState( '', 'loading' | 'error' | 'error-retryable' | 'empty' )` in the +story's `beforeEach`, clearing it in the returned cleanup. Keep such stories off the shared +autodocs page (`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise +force the sibling stories into the same state) and give each one a date preset distinct from the +other stories so it hits the mock fresh instead of reading their cached success. See `widgets/search-terms/stories/` for the reference. +`error` mocks a permission-gated 403 and `error-retryable` the proxy's `no_connection` 403. A +widget that maps its error through `describeError` renders a Retry action only for the latter, so +give it a story for each; both mocks are 403s, so neither waits out the query's retry backoff. + ### Widget pitfalls - Putting new widgets under `packages/widgets-toolkit/src/widgets/*` — that path is for the @@ -538,7 +542,11 @@ the query factory — do not do it in the widget or the view hook. Render these states through `` from `@jetpack-premium-analytics/widgets-toolkit` rather than hand-rolling `if ( isError )` / empty branches or a `WidgetLoadingOverlay`. Map the -data/view hook's result to its four signals and pass generic descriptors: +data/view hook's result to its four signals. For Stats API errors, pass the raw `error` to the +shared `describeError()` mapper so 403 access failures have neutral copy and no retry action, +while other failures — including the proxy's `no_connection` 403, which can heal after +reconnecting — offer Retry. Pass the retryable copy as a full sentence (not a fragment +interpolated into a shared frame) so translators see the whole sentence: ```tsx @@ -561,6 +569,9 @@ data/view hook's result to its four signals and pass generic descriptors: `isFetching` and data are shown) and swaps only the content area. Notes: - Expose `refetch` from the data/view hook so the error state's Retry can re-run the query. +- When a view hook masks `isError` (e.g. `rows.length === 0 && isError` to keep placeholder + rows), gate `error` with the same predicate (`error: showError ? error : null`) so the two + fields can't disagree. - Give `empty.icon` a neutral glyph distinct from the error icon — the widget's own glyph from `@jetpack-premium-analytics/icons` (e.g. `search`, `customer`); omit it for no icon. Don't use a caution glyph: empty is not an error. @@ -572,8 +583,8 @@ data/view hook's result to its four signals and pass generic descriptors: > Many Stats widgets predate this and still hand-roll loading/empty via ``, > `isLoading && data.length === 0`, and `LeaderboardChart`'s `emptyStateText`. They are being > migrated to `` — follow the contract above, not those widgets. -> `widgets/search-terms/render.tsx` is the reference. (A `describeError` mapper and a -> `ReportWidget` wrapper that remove the per-widget error/retry boilerplate are planned follow-ups.) +> `widgets/search-terms/render.tsx` is the reference. (A `ReportWidget` wrapper that removes the +> remaining per-widget state boilerplate is a planned follow-up.) **Comparison data** diff --git a/projects/packages/premium-analytics/changelog/wooa7s-1649 b/projects/packages/premium-analytics/changelog/wooa7s-1649 new file mode 100644 index 000000000000..0e9700489ed6 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/wooa7s-1649 @@ -0,0 +1,4 @@ +Significance: patch +Type: changed + +Use consistent access and retry error states across Stats widgets. diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts new file mode 100644 index 000000000000..538b9fceeb48 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts @@ -0,0 +1,66 @@ +/** + * Internal dependencies + */ +import { describeError } from '../describe-error'; + +const RETRY_DESCRIPTION = "We couldn't load device data. Please try again in a moment."; + +describe( 'describeError', () => { + it( 'describes a 403 as a neutral error without actions', () => { + const descriptor = describeError( + { error: 'unauthorized', status: 403 }, + { retryDescription: RETRY_DESCRIPTION, onRetry: jest.fn() } + ); + + expect( descriptor ).toEqual( { + description: "You don't have access to this data.", + } ); + expect( descriptor ).not.toHaveProperty( 'actions' ); + } ); + + it( 'keeps a no_connection 403 retryable — a broken connection can heal', () => { + const onRetry = jest.fn(); + const descriptor = describeError( + { error: 'no_connection', status: 403 }, + { retryDescription: RETRY_DESCRIPTION, onRetry } + ); + + expect( descriptor.description ).toBe( RETRY_DESCRIPTION ); + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } ); + + it( 'describes a generic failure with the retryable copy and a retry action', () => { + const onRetry = jest.fn(); + const descriptor = describeError( + { status: 500 }, + { retryDescription: RETRY_DESCRIPTION, onRetry } + ); + + expect( descriptor.description ).toBe( RETRY_DESCRIPTION ); + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } ); + + it( 'keeps an unexpected 404 retryable', () => { + const onRetry = jest.fn(); + const descriptor = describeError( + { status: 404 }, + { retryDescription: RETRY_DESCRIPTION, onRetry } + ); + + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } ); + + it( 'returns the retryable descriptor when there is no error — widgets call it on every render', () => { + const onRetry = jest.fn(); + + for ( const noError of [ null, undefined ] ) { + const descriptor = describeError( noError, { + retryDescription: RETRY_DESCRIPTION, + onRetry, + } ); + + expect( descriptor.description ).toBe( RETRY_DESCRIPTION ); + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts new file mode 100644 index 000000000000..bc949f4ef762 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts @@ -0,0 +1,51 @@ +/** + * External dependencies + */ +import { getApiErrorCode, getApiErrorStatus } from '@jetpack-premium-analytics/data'; +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; +/** + * Types + */ +import type { WidgetStateError } from '../components/widget-state'; + +interface DescribeErrorOptions { + retryDescription: string; + onRetry: () => void; +} + +/** + * Map an API error to a Stats widget error descriptor. + * + * A 403 is a deterministic access failure, so it gets neutral copy and no retry + * action — except the proxy's `no_connection` 403, which flags a broken Jetpack + * connection that can heal, so it stays retryable like any other failure. + * + * @param error - The failed query error. + * @param options - Error-state copy and retry options. + * @param options.retryDescription - The full-sentence copy for the retryable error state. + * @param options.onRetry - Callback used by the retry action. + * @return The widget error descriptor. + */ +export function describeError( + error: unknown, + { retryDescription, onRetry }: DescribeErrorOptions +): WidgetStateError { + if ( getApiErrorStatus( error ) === 403 && getApiErrorCode( error ) !== 'no_connection' ) { + return { + description: __( "You don't have access to this data.", 'jetpack-premium-analytics' ), + }; + } + + return { + description: retryDescription, + actions: [ + { + label: __( 'Retry', 'jetpack-premium-analytics' ), + onClick: onRetry, + }, + ], + }; +} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts index 378ff0365980..8162c19f97d0 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts @@ -50,6 +50,7 @@ export { buildCsv, buildCsvDateRangeFilename, saveCsv, type CsvColumn } from './ export { sharePercentage } from './share-percentage'; export { getVideoKey, getVideoLabel } from './video-plays'; export { toMaxRows } from './to-max-rows'; +export { describeError } from './describe-error'; export { summaryCount } from './summary-count'; export { toDay } from './to-day'; export { defaultPeriodForInterval } from './default-period-for-interval'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts index fb778b6ce262..74bcb0bcccf9 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts @@ -133,6 +133,7 @@ export { getVideoKey, getVideoLabel, toMaxRows, + describeError, summaryCount, toDay, defaultPeriodForInterval, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts index f2c28e34fe54..6123d7a0b551 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts @@ -156,11 +156,13 @@ const requestCounters: Record< string, number > = {}; /** * Forced response state for a request path fragment, so stories can exercise a - * widget's loading, error, and empty UI. `error` rejects the request; `loading` - * returns a promise that never settles; `empty` resolves with a valid response - * that has no rows. + * widget's loading, error, and empty UI. `error` rejects the request with a + * permission-gated 403; `error-retryable` rejects it with the proxy's + * `no_connection` 403, which widgets on `describeError` render with a Retry + * action; `loading` returns a promise that never settles; `empty` resolves with + * a valid response that has no rows. */ -type ReportMockState = 'error' | 'loading' | 'empty'; +type ReportMockState = 'error' | 'error-retryable' | 'loading' | 'empty'; const mockStateOverrides = new Map< string, ReportMockState >(); @@ -1255,9 +1257,20 @@ const reportMocksMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio // (`summary` / `days` / `data`), so the widget resolves to its empty state. return { date: '2026-01-01', period: 'day', summary: {}, days: {}, data: [] }; } + if ( state === 'error-retryable' ) { + // The local proxy's `no_connection` shape. Still a 403, so the error UI + // shows at once, but `describeError` keeps it retryable: a broken Jetpack + // connection can heal, unlike a permission gate. + return Promise.reject( { + code: 'no_connection', + message: 'Mocked connection failure for Storybook.', + data: { status: 403 }, + } ); + } // The WPCOM pass-through error envelope, with the status attached the way // the fetch layer attaches it. A 403 is not retried by `shouldRetryApiError`, // so the error UI shows at once instead of after the query's retry backoff. + // Widgets on `describeError` read it as a permission gate and drop Retry. return Promise.reject( { error: 'unauthorized', message: 'Mocked error response for Storybook.', diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index fabf16b32ed7..96d3295de328 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -9,6 +9,7 @@ import { device } from '@jetpack-premium-analytics/icons'; import { __ } from '@wordpress/i18n'; import { Legend, + describeError, SemiCircleChart, WidgetRoot, WidgetState, @@ -56,7 +57,7 @@ type DevicesInnerProps = { */ function DevicesInner( { max }: DevicesInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { data, hasComparison, isLoading, isFetching, isError, refetch } = useDeviceViews( { + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = useDeviceViews( { reportParams, max, deviceProperty: 'screensize', @@ -94,13 +95,13 @@ function DevicesInner( { max }: DevicesInnerProps ) { isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( + error={ describeError( error, { + retryDescription: __( "We couldn't load device data. Please try again in a moment.", 'jetpack-premium-analytics' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + onRetry: refetch, + } ) } empty={ { icon: device, description: __( 'No device data in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx index dbf02713e2a9..f90da95013fe 100644 --- a/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/devices/stories/devices-widget.stories.tsx @@ -119,8 +119,9 @@ export const Loading: StoryObj< DevicesStoryControls > = { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: StoryObj< DevicesStoryControls > = { render: () => renderDevicesOnPreset( 'last-7-days' ), @@ -132,6 +133,21 @@ export const Error: StoryObj< DevicesStoryControls > = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: StoryObj< DevicesStoryControls > = { + render: () => renderDevicesOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices/screensize', 'error-retryable' ); + return () => forceStatsMockState( 'stats/devices/screensize', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral device * glyph and "No device data in this period."). diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts index c61f35ad993c..c93cb8887b60 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts @@ -41,6 +41,7 @@ interface DeviceViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; refetch: () => void; } @@ -88,21 +89,25 @@ export default function useDeviceViews( { deviceProperty, }; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = + const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = useStatsDevices( statsParams, { maxRows: max } ); const items = ( comparisonRows?.rows ?? [] ).map( toDeviceView ); + // The Stats queries carry `placeholderData: previousData => previousData`, so a + // failed range change keeps the prior period's rows in `data` while `isError` + // flips true. Only surface the error when there's nothing to show, so a transient + // refetch failure doesn't replace populated rows with the error state. `error` is + // gated by the same predicate so it is populated iff `isError` is true. + const showError = items.length === 0 && isError; + return { data: items, hasComparison, isLoading, isFetching, - // The Stats queries carry `placeholderData: previousData => previousData`, so a - // failed range change keeps the prior period's rows in `data` while `isError` - // flips true. Only surface the error when there's nothing to show, so a transient - // refetch failure doesn't replace populated rows with the error state. - isError: items.length === 0 && isError, + isError: showError, + error: showError ? error : null, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx b/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx index 5f9f999bc53c..c544078dfad9 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx @@ -21,6 +21,7 @@ describe( 'SearchTermsWidget', () => { isLoading: false, isFetching: false, isError: false, + error: null, hasComparison: false, refetch: jest.fn(), } ); diff --git a/projects/packages/premium-analytics/widgets/search-terms/render.tsx b/projects/packages/premium-analytics/widgets/search-terms/render.tsx index d02512af889f..59a132194605 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/render.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/render.tsx @@ -3,6 +3,7 @@ */ import { calculateDelta, + describeError, LeaderboardChart, ReportLink, WidgetFooter, @@ -37,10 +38,11 @@ type SearchTermsWidgetProps = WidgetRenderProps< SearchTermsRenderAttributes >; function SearchTermsInner( { max = 10 }: SearchTermsAttributes ) { const { reportParams } = useWidgetRootContext(); - const { data, isLoading, isFetching, isError, hasComparison, refetch } = useSearchTermViews( { - reportParams, - max, - } ); + const { data, isLoading, isFetching, isError, error, hasComparison, refetch } = + useSearchTermViews( { + reportParams, + max, + } ); const leaderboardData = useMemo< LeaderboardChartData >( () => { const maxValue = Math.max( ...data.map( t => t.views ), 0 ); @@ -79,13 +81,13 @@ function SearchTermsInner( { max = 10 }: SearchTermsAttributes ) { isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( + error={ describeError( error, { + retryDescription: __( "We couldn't load search terms. Please try again in a moment.", 'jetpack-premium-analytics' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + onRetry: refetch, + } ) } empty={ { icon: search, description: __( 'No search terms in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx index 22a2eac86518..e376fc167642 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx @@ -101,8 +101,9 @@ export const Loading: Story = { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: Story = { render: () => renderSearchTermsOnPreset( 'last-7-days' ), @@ -114,6 +115,21 @@ export const Error: Story = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: Story = { + render: () => renderSearchTermsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas, withStoryRouter ], + beforeEach: () => { + setReportMockState( 'stats/search-terms', 'error-retryable' ); + return () => setReportMockState( 'stats/search-terms', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral search * glyph and "No search terms in this period."). diff --git a/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts b/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts index bf1c3f5d89fd..74dc55f75a80 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts +++ b/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts @@ -26,6 +26,7 @@ interface SearchTermViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; hasComparison: boolean; refetch: () => void; } @@ -51,6 +52,7 @@ export default function useSearchTermViews( { isLoading, isFetching, isError: hasError, + error, refetch, } = useStatsSearchTerms( reportParams as Parameters< typeof useStatsSearchTerms >[ 0 ], { maxRows: max, @@ -63,15 +65,19 @@ export default function useSearchTermViews( { previousViews: comparisonUsable ? item.previousViews : undefined, } ) ); + // The Stats queries carry `placeholderData: previousData => previousData`, so a + // failed range change keeps the prior period's rows in `data` while `isError` + // flips true. Only surface the error when there's nothing to show, so a transient + // refetch failure doesn't replace populated rows with the error state. `error` is + // gated by the same predicate so it is populated iff `isError` is true. + const showError = items.length === 0 && hasError; + return { data: items, isLoading, isFetching, - // The Stats queries carry `placeholderData: previousData => previousData`, so a - // failed range change keeps the prior period's rows in `data` while `isError` - // flips true. Only surface the error when there's nothing to show, so a transient - // refetch failure doesn't replace populated rows with the error state. - isError: items.length === 0 && hasError, + isError: showError, + error: showError ? error : null, hasComparison: comparisonUsable, refetch, }; diff --git a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts index 791d76bf864f..8829267f4491 100644 --- a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts +++ b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts @@ -4,7 +4,7 @@ import apiFetch from '@wordpress/api-fetch'; import type { APIFetchMiddleware, APIFetchOptions } from '@wordpress/api-fetch'; -type ForcedMockState = 'error' | 'loading' | 'empty'; +type ForcedMockState = 'error' | 'error-retryable' | 'loading' | 'empty'; const stateOverrides = new Map< string, ForcedMockState >(); @@ -24,8 +24,19 @@ const forcedStateMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio // (`summary` / `days` / `data`), so the widget resolves to its empty state. return { date: '2026-01-01', period: 'day', summary: {}, days: {}, data: [] }; } + if ( state === 'error-retryable' ) { + // The local proxy's `no_connection` shape. Still a 403, so the error UI + // shows at once, but `describeError` keeps it retryable: a broken Jetpack + // connection can heal, unlike a permission gate. + return Promise.reject( { + code: 'no_connection', + message: 'Mocked connection failure for Storybook.', + data: { status: 403 }, + } ); + } // A 403 is not retried by `shouldRetryApiError`, so the error UI shows at - // once instead of after the query's retry backoff. + // once instead of after the query's retry backoff. Widgets on `describeError` + // read this as a permission gate and drop their Retry action. return Promise.reject( { code: 'stats_mock_error', message: 'Mocked error response for Storybook.', @@ -64,6 +75,9 @@ const forcedStateMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio * key carries no date params, a distinct preset can't isolate it — evict the * query from the shared client on enter and cleanup instead (see the * `latest-post` stories). + * - `'error'` mocks a permission-gated 403 and `'error-retryable'` the proxy's + * `no_connection` 403. Widgets on `describeError` render a Retry action only + * for the latter, so give those widgets a story for each. * * @param pathFragment - Substring matched against the request path (e.g. `stats/clicks`). * @param state - The forced state, or `null` to clear. diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index 75519979c801..d15ef562936c 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -9,6 +9,7 @@ import { __ } from '@wordpress/i18n'; import { Stack, Text } from '@wordpress/ui'; import { calculateDelta, + describeError, LeaderboardChart, sharePercentage, WidgetRoot, @@ -55,11 +56,13 @@ type TopPlatformsInnerProps = { function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { data, hasComparison, isLoading, isFetching, isError, refetch } = usePlatformViews( { - reportParams, - max, - deviceProperty: platformDimension, - } ); + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = usePlatformViews( + { + reportParams, + max, + deviceProperty: platformDimension, + } + ); const maxViews = Math.max( ...data.map( d => d.views ), 0 ); const maxComparisonViews = Math.max( ...data.map( d => d.previousViews ?? 0 ), 0 ); @@ -95,13 +98,13 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( + error={ describeError( error, { + retryDescription: __( "We couldn't load platform data. Please try again in a moment.", 'jetpack-premium-analytics' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + onRetry: refetch, + } ) } empty={ { icon: device, description: __( 'No platform data in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx index d772bf1c6f57..24a1173273ab 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/stories/top-platforms-widget.stories.tsx @@ -150,8 +150,9 @@ export const Loading: StoryObj< TopPlatformsStoryControls > = { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: StoryObj< TopPlatformsStoryControls > = { render: () => renderTopPlatformsOnPreset( 'last-7-days' ), @@ -163,6 +164,21 @@ export const Error: StoryObj< TopPlatformsStoryControls > = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: StoryObj< TopPlatformsStoryControls > = { + render: () => renderTopPlatformsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices', 'error-retryable' ); + return () => forceStatsMockState( 'stats/devices', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral device * glyph and "No platform data in this period."). diff --git a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts index 022e2ebc882b..94c8472f5c1b 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts @@ -37,6 +37,7 @@ interface PlatformViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; refetch: () => void; } @@ -99,21 +100,25 @@ export default function usePlatformViews( { deviceProperty, }; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = + const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = useStatsDevices( statsParams, { maxRows: max } ); const rows = ( comparisonRows?.rows ?? [] ).map( item => toPlatformView( item, deviceProperty ) ); + // The Stats queries carry `placeholderData: previousData => previousData`, so a + // failed range change keeps the prior period's rows in `data` while `isError` + // flips true. Only surface the error when there's nothing to show, so a transient + // refetch failure doesn't replace populated rows with the error state. `error` is + // gated by the same predicate so it is populated iff `isError` is true. + const showError = rows.length === 0 && isError; + return { data: rows, hasComparison, isLoading, isFetching, - // The Stats queries carry `placeholderData: previousData => previousData`, so a - // failed range change keeps the prior period's rows in `data` while `isError` - // flips true. Only surface the error when there's nothing to show, so a transient - // refetch failure doesn't replace populated rows with the error state. - isError: rows.length === 0 && isError, + isError: showError, + error: showError ? error : null, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx index 0c3541fe30a4..9b789f28d3f5 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx @@ -6,6 +6,7 @@ import { __, sprintf } from '@wordpress/i18n'; import { Stack, Text } from '@wordpress/ui'; import { calculateDelta, + describeError, LeaderboardChart, ReportLink, WidgetBackLink, @@ -92,7 +93,7 @@ function UtmInsightsInner( { utmDimension, max }: UtmInsightsInnerProps ) { clearSelectedUtm(); }, [ clearSelectedUtm, utmDimension ] ); - const { data, hasComparison, isLoading, isFetching, isError, refetch } = useUtmInsights( { + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = useUtmInsights( { reportParams, utmParam: utmDimension, max, @@ -177,13 +178,13 @@ function UtmInsightsInner( { utmDimension, max }: UtmInsightsInnerProps ) { isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( + error={ describeError( error, { + retryDescription: __( "We couldn't load UTM data. Please try again in a moment.", 'jetpack-premium-analytics' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + onRetry: refetch, + } ) } empty={ { icon: megaphone, description: __( 'No UTM data in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx b/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx index 4ef94b27f16a..92d9ef4b46ef 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx @@ -116,8 +116,9 @@ export const Loading: Story = { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: Story = { render: () => renderUtmInsightsOnPreset( 'last-7-days' ), @@ -129,6 +130,21 @@ export const Error: Story = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: Story = { + render: () => renderUtmInsightsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas, withStoryRouter ], + beforeEach: () => { + forceStatsMockState( 'stats/utm', 'error-retryable' ); + return () => forceStatsMockState( 'stats/utm', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral megaphone * glyph and "No UTM data in this period."). diff --git a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts index 8c998b3282a3..d5b932d68b61 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts +++ b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts @@ -45,6 +45,7 @@ interface UtmInsightsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; refetch: () => void; } @@ -83,20 +84,22 @@ export default function useUtmInsights( { max, }: UseUtmInsightsArgs ): UtmInsightsState { const params = { ...reportParams, utmParam, max } as Parameters< typeof useStatsUtm >[ 0 ]; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = useStatsUtm( - params, - { maxRows: max } - ); + const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = + useStatsUtm( params, { maxRows: max } ); const rows = ( comparisonRows?.rows ?? [] ).map( toUtmRow ); + // Stats queries keep previous data via `placeholderData`, so a failed + // range refetch should not replace populated rows with the error state. + // `error` is gated by the same predicate so it is populated iff `isError` is true. + const showError = rows.length === 0 && isError; + return { data: rows, hasComparison, isLoading, isFetching, - // Stats queries keep previous data via `placeholderData`, so a failed - // range refetch should not replace populated rows with the error state. - isError: rows.length === 0 && isError, + isError: showError, + error: showError ? error : null, refetch, }; } From 9596f6d4b86a96a8b8084e9aef231f0b625fec04 Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Mon, 27 Jul 2026 11:23:18 +0800 Subject: [PATCH 5/6] Update projects/packages/premium-analytics/changelog/fix-stats-api-error-status Co-authored-by: Justin P <228780+layoutd@users.noreply.github.com> --- .../premium-analytics/changelog/fix-stats-api-error-status | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/packages/premium-analytics/changelog/fix-stats-api-error-status b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status index ad4ca065f788..4c29fc876993 100644 --- a/projects/packages/premium-analytics/changelog/fix-stats-api-error-status +++ b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status @@ -1,4 +1,4 @@ Significance: patch Type: fixed -Stats data layer: keep the HTTP status on failed API requests so retry, auth, and error handling behave correctly, and stop deriving plan state from ambiguous error codes. +Stats: Stop retrying unavailable reports and show authentication and server errors correctly. From 31e8ceb62a3ac436afd36889a9373be9a92f91fa Mon Sep 17 00:00:00 2001 From: Chi-Hsuan Huang Date: Mon, 27 Jul 2026 12:17:01 +0800 Subject: [PATCH 6/6] fix: register Stats error-status middleware from the data package WP 7.0's Core boot ignores initModules in initSinglePage(), so the app's init() module never runs there and the middleware was not installed. Register it next to the retry policy that reads the status instead. --- .../changelog/fix-stats-api-error-status | 2 +- .../__tests__/error-status-middleware.test.ts | 32 +++++++++++++++++++ .../data/src/api/error-status-middleware.ts | 6 ++++ .../packages/data/src/index.ts | 8 +---- .../__tests__/query-client-provider.test.ts | 21 ++++++++++++ .../src/providers/query-client-provider.tsx | 10 ++++++ .../packages/init/package.json | 1 - .../packages/init/src/index.ts | 4 --- .../widgets/stories/force-stats-mock-state.ts | 9 +++--- .../__tests__/video-detail-embeds.test.tsx | 10 +++--- .../video-detail-highlights.test.tsx | 6 ++-- 11 files changed, 86 insertions(+), 23 deletions(-) create mode 100644 projects/packages/premium-analytics/packages/data/src/providers/__tests__/query-client-provider.test.ts diff --git a/projects/packages/premium-analytics/changelog/fix-stats-api-error-status b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status index ad4ca065f788..4c29fc876993 100644 --- a/projects/packages/premium-analytics/changelog/fix-stats-api-error-status +++ b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status @@ -1,4 +1,4 @@ Significance: patch Type: fixed -Stats data layer: keep the HTTP status on failed API requests so retry, auth, and error handling behave correctly, and stop deriving plan state from ambiguous error codes. +Stats: Stop retrying unavailable reports and show authentication and server errors correctly. diff --git a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts index 8b6d5a08297e..2d95d58d8707 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts @@ -200,4 +200,36 @@ describe( 'registerApiErrorStatusMiddleware', () => { use.mockRestore(); } } ); + + it( 'skips registration when the apiFetch instance exposes no use()', async () => { + // Suites that mock `@wordpress/api-fetch` with a bare function get such an + // instance, and this runs at module scope in the data package. + await jest.isolateModulesAsync( async () => { + const isolatedApiFetch = ( await import( '@wordpress/api-fetch' ) ).default as unknown as + | Record< string, unknown > + | undefined; + const original = isolatedApiFetch?.use; + delete isolatedApiFetch?.use; + + try { + const middleware = await import( '../error-status-middleware' ); + + expect( isolatedApiFetch?.use ).toBeUndefined(); + expect( () => middleware.registerApiErrorStatusMiddleware() ).not.toThrow(); + + // Skipping must not latch: a later call on a usable instance still registers. + const use = jest.fn(); + if ( isolatedApiFetch ) { + isolatedApiFetch.use = use; + } + middleware.registerApiErrorStatusMiddleware(); + + expect( use ).toHaveBeenCalledWith( middleware.apiErrorStatusMiddleware ); + } finally { + if ( isolatedApiFetch ) { + isolatedApiFetch.use = original; + } + } + } ); + } ); } ); diff --git a/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts index 1e44376f6ce4..f0ef142a8605 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts @@ -121,6 +121,12 @@ export function registerApiErrorStatusMiddleware(): void { if ( registered ) { return; } + // Unit tests replace the whole apiFetch module with a bare `jest.fn()`, which + // has no `use()`. This is called at module scope, so without the check every + // suite that renders a widget would fail to load. + if ( typeof apiFetch.use !== 'function' ) { + return; + } registered = true; apiFetch.use( apiErrorStatusMiddleware ); } diff --git a/projects/packages/premium-analytics/packages/data/src/index.ts b/projects/packages/premium-analytics/packages/data/src/index.ts index bfdd1fd838b3..193be6572f33 100644 --- a/projects/packages/premium-analytics/packages/data/src/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/index.ts @@ -247,13 +247,7 @@ export type { ProductType } from './types/product-type'; export { ORDER_ATTRIBUTION_VIEWS } from './api/report-order-attribution-summary-fetch'; export { getDefaultIntervalForPeriod, getDateFormatFromInterval } from './utils/interval'; export { getDefaultPreset, getDefaultQueryParams } from './defaults'; -export { - downloadReport, - exportReport, - fetchStatsProxy, - getStatsProxyPath, - registerApiErrorStatusMiddleware, -} from './api'; +export { downloadReport, exportReport, fetchStatsProxy, getStatsProxyPath } from './api'; export type { DownloadReportParams, DownloadReportResponse, diff --git a/projects/packages/premium-analytics/packages/data/src/providers/__tests__/query-client-provider.test.ts b/projects/packages/premium-analytics/packages/data/src/providers/__tests__/query-client-provider.test.ts new file mode 100644 index 000000000000..54e36c64a009 --- /dev/null +++ b/projects/packages/premium-analytics/packages/data/src/providers/__tests__/query-client-provider.test.ts @@ -0,0 +1,21 @@ +/** + * External dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +/** + * Internal dependencies + */ +import { apiErrorStatusMiddleware } from '../../api/error-status-middleware'; + +jest.mock( '@wordpress/api-fetch', () => Object.assign( jest.fn(), { use: jest.fn() } ) ); + +describe( 'query-client-provider module', () => { + it( 'installs the error-status middleware when the data package loads', async () => { + // The app's `init()` module is not involved: WP 7.0's Core `boot` ignores + // the `initModules` argument to `initSinglePage()`, so anything registered + // only from `init()` never runs there. + await import( '../query-client-provider' ); + + expect( apiFetch.use ).toHaveBeenCalledWith( apiErrorStatusMiddleware ); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx b/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx index 98e8b61a6d36..54002314e438 100644 --- a/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx +++ b/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx @@ -6,9 +6,19 @@ import { ReactNode } from 'react'; /** * Internal dependencies */ +import { registerApiErrorStatusMiddleware } from '../api/error-status-middleware'; import { getApiErrorStatus, shouldRetryApiError } from '../utils'; import { globalErrorManager } from './global-error-manager'; +// Both the retry policy and the global error detection below read the HTTP +// status, which apiFetch drops unless this middleware is installed. Registering +// it here, next to the policy that needs it, rather than from the app's `init()` +// module: WP 7.0's Core `boot` module ignores the `initModules` argument to +// `initSinglePage()`, so on those sites `init()` never runs and the status was +// lost again (Core-side fix in #50309). Every widget and route mounts this +// provider, so loading the data package is enough to install the middleware. +registerApiErrorStatusMiddleware(); + const DEFAULT_STALE_TIME = 5 * 60 * 1000; const DEFAULT_GC_TIME = 10 * 60 * 1000; diff --git a/projects/packages/premium-analytics/packages/init/package.json b/projects/packages/premium-analytics/packages/init/package.json index 6e83b23ab38c..f9475e8fbe39 100644 --- a/projects/packages/premium-analytics/packages/init/package.json +++ b/projects/packages/premium-analytics/packages/init/package.json @@ -8,7 +8,6 @@ "wpScriptModuleExports": "./build-module/index.mjs", "dependencies": { "@automattic/jetpack-script-data": "workspace:*", - "@jetpack-premium-analytics/data": "workspace:*", "@wordpress/api-fetch": "7.51.0", "@wordpress/boot": "0.18.0", "@wordpress/data": "10.51.0", diff --git a/projects/packages/premium-analytics/packages/init/src/index.ts b/projects/packages/premium-analytics/packages/init/src/index.ts index 552068c45521..4dd80aa0b7f7 100644 --- a/projects/packages/premium-analytics/packages/init/src/index.ts +++ b/projects/packages/premium-analytics/packages/init/src/index.ts @@ -2,7 +2,6 @@ * External dependencies */ import { getScriptData } from '@automattic/jetpack-script-data'; -import { registerApiErrorStatusMiddleware } from '@jetpack-premium-analytics/data'; import apiFetch from '@wordpress/api-fetch'; import { store as bootStore } from '@wordpress/boot'; import { dispatch } from '@wordpress/data'; @@ -41,9 +40,6 @@ function setupApiFetch(): void { * Runs before routes render. */ export async function init(): Promise< void > { - // Keeps the HTTP status on failed requests, which the data layer's error - // handling reads. Self-guarding against duplicate registration. - registerApiErrorStatusMiddleware(); setupApiFetch(); dispatch( bootStore ).updateMenuItem( 'dashboard', { diff --git a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts index 791d76bf864f..f0e50ebcf7c2 100644 --- a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts +++ b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts @@ -24,12 +24,13 @@ const forcedStateMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio // (`summary` / `days` / `data`), so the widget resolves to its empty state. return { date: '2026-01-01', period: 'day', summary: {}, days: {}, data: [] }; } - // A 403 is not retried by `shouldRetryApiError`, so the error UI shows at - // once instead of after the query's retry backoff. + // The WPCOM pass-through error envelope, with the status attached the way + // the fetch layer attaches it. A 403 is not retried by `shouldRetryApiError`, + // so the error UI shows at once instead of after the query's retry backoff. return Promise.reject( { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response for Storybook.', - data: { status: 403 }, + status: 403, } ); } diff --git a/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx b/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx index 4cf0efeced70..662c7f8e93b9 100644 --- a/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx +++ b/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx @@ -23,12 +23,14 @@ const SINGLE_VIDEO_RESPONSE = { pages: [ 'https://example.com/getting-started/', 'https://example.com/blog/weekly-recap/' ], }; -// A 403 is not retried by the data layer's `shouldRetryApiError`, so the error -// state shows at once instead of after the query's retry backoff. +// The WPCOM pass-through error envelope, with the status attached the way the +// fetch layer attaches it. A 403 is not retried by the data layer's +// `shouldRetryApiError`, so the error state shows at once instead of after the +// query's retry backoff. const MOCK_API_ERROR = { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response.', - data: { status: 403 }, + status: 403, }; function renderWidget( postId?: number ) { diff --git a/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx b/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx index 87f607fa8e47..0f42a68062b7 100644 --- a/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx +++ b/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx @@ -85,10 +85,12 @@ const COMPARISON_WITHOUT_SELECTED_VIDEO_RESPONSE = { }, }; +// The WPCOM pass-through error envelope, with the status attached the way the +// fetch layer attaches it. const MOCK_API_ERROR = { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response.', - data: { status: 403 }, + status: 403, }; function renderWidget( postId?: number, withComparison = false ) {