diff --git a/projects/packages/activity-log/changelog/add-backup-overview-open-older-backups b/projects/packages/activity-log/changelog/add-backup-overview-open-older-backups new file mode 100644 index 000000000000..82680c331c54 --- /dev/null +++ b/projects/packages/activity-log/changelog/add-backup-overview-open-older-backups @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Link backups to that backup in the Backup dashboard when the new dashboard is on. diff --git a/projects/packages/activity-log/src/class-initial-state.php b/projects/packages/activity-log/src/class-initial-state.php index 0f5eaa221327..f653835319e9 100644 --- a/projects/packages/activity-log/src/class-initial-state.php +++ b/projects/packages/activity-log/src/class-initial-state.php @@ -62,6 +62,15 @@ private function get_data() { * @param string $template Restore URL template, or an empty string. */ 'restoreUrlTemplate' => (string) apply_filters( 'jetpack_activity_log_restore_url_template', '' ), + /** + * Filters the in-admin address a link to a backup opens, with `{rewindId}` as the placeholder. + * Empty leaves such links as plain text. + * + * @since $$next-version$$ + * + * @param string $template Backup URL template, or an empty string. + */ + 'backupUrlTemplate' => (string) apply_filters( 'jetpack_activity_log_backup_url_template', '' ), ), 'config' => array( // Simple sites have no Jetpack REST API to proxy through, so the app calls WordPress.com directly. diff --git a/projects/packages/activity-log/src/js/components/ActivityLog/formatted-block/index.tsx b/projects/packages/activity-log/src/js/components/ActivityLog/formatted-block/index.tsx index d634de540fe3..1218baeed881 100644 --- a/projects/packages/activity-log/src/js/components/ActivityLog/formatted-block/index.tsx +++ b/projects/packages/activity-log/src/js/components/ActivityLog/formatted-block/index.tsx @@ -75,6 +75,30 @@ const AnchorBlock: BlockRenderer = ( { content, children, onClick, meta } ) => { ); }; +interface InitialStateWithBackupUrl { + jetpackStatus?: { backupUrlTemplate?: string }; +} + +declare const JPACTIVITYLOG_INITIAL_STATE: InitialStateWithBackupUrl | undefined; + +// The Backup dashboard's view of one backup, with `{rewindId}` to fill in; empty when it can't show one. +const backupUrlTemplate: string = + ( typeof JPACTIVITYLOG_INITIAL_STATE !== 'undefined' + ? JPACTIVITYLOG_INITIAL_STATE?.jetpackStatus?.backupUrlTemplate + : undefined ) ?? ''; + +const REWIND_ID = /^\d+(\.\d+)?$/; + +// A backup token opens that backup in the Backup dashboard, when there is one to open it in. +const BackupLink: BlockRenderer = ( { content, children } ) => { + if ( ! backupUrlTemplate || ! REWIND_ID.test( content.rewindId ?? '' ) ) { + return { children }; + } + // Encoded twice: the template puts the id inside the already-encoded `p` query arg. + const rewindId = encodeURIComponent( encodeURIComponent( content.rewindId as string ) ); + return { children }; +}; + // Resolve a token's wp-admin destination (if any). Entities without a // target (site, backup, or a malformed payload missing an id/slug) fall // through to plain text. @@ -100,10 +124,9 @@ const blockTypeMapping: Record< string, BlockRenderer > = { person: EntityLink, plugin: EntityLink, theme: EntityLink, - // site (we're already on it) and backup (needs the Backup plugin's own - // route) have no generic wp-admin target — render as plain text. + // site has no wp-admin target (we're already on it) — render as plain text. site: ( { children } ) => { children }, - backup: ( { children } ) => { children }, + backup: BackupLink, }; export const createFormattedBlock = ( mapping: Record< string, BlockRenderer > ) => { diff --git a/projects/packages/activity-log/tests/js/formatted-block.test.tsx b/projects/packages/activity-log/tests/js/formatted-block.test.tsx new file mode 100644 index 000000000000..874b57416b42 --- /dev/null +++ b/projects/packages/activity-log/tests/js/formatted-block.test.tsx @@ -0,0 +1,51 @@ +import { render, screen } from '@testing-library/react'; + +const FORMATTED_BLOCK = '../../src/js/components/ActivityLog/formatted-block'; +const TEMPLATE = '/wp-admin/admin.php?page=jetpack-backup&p=%2F%3Fselected%3D%2522{rewindId}%2522'; + +/** + * Render a backup range with the Backup dashboard's link template in place. + * + * @param rewindId - The range's rewind id. + */ +function renderBackupRange( rewindId: string ) { + ( globalThis as Record< string, unknown > ).JPACTIVITYLOG_INITIAL_STATE = { + jetpackStatus: { backupUrlTemplate: TEMPLATE }, + }; + jest.isolateModules( () => { + // The template is read when the module loads. + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { renderFormattedContent } = require( FORMATTED_BLOCK ); + render( + <> + { renderFormattedContent( { + items: [ { type: 'backup', rewindId, children: [ 'Oct 17, 2026' ] } ], + } ) } + + ); + } ); +} + +describe( 'a backup range', () => { + it.each( [ '1792247404', '1792247404.817' ] )( + 'links rewind id %s inside the encoded path', + rewindId => { + renderBackupRange( rewindId ); + + const href = + screen.getByRole( 'link', { name: 'Oct 17, 2026' } ).getAttribute( 'href' ) ?? ''; + const path = new URL( href, 'https://example.com' ).searchParams.get( 'p' ); + expect( path ).toBe( `/?selected=%22${ rewindId }%22` ); + } + ); + + it.each( [ '123%22&foo=bar', '1792247404.', 'abc', '' ] )( + 'stays plain text for rewind id %p', + rewindId => { + renderBackupRange( rewindId ); + + expect( screen.queryByRole( 'link' ) ).not.toBeInTheDocument(); + expect( screen.getByText( 'Oct 17, 2026' ) ).toBeInTheDocument(); + } + ); +} ); diff --git a/projects/packages/activity-log/tests/php/Initial_State_Test.php b/projects/packages/activity-log/tests/php/Initial_State_Test.php index 372924e697ee..b90ceefb8f99 100644 --- a/projects/packages/activity-log/tests/php/Initial_State_Test.php +++ b/projects/packages/activity-log/tests/php/Initial_State_Test.php @@ -18,6 +18,7 @@ protected function tearDown(): void { Status_Cache::clear(); wp_set_current_user( 0 ); remove_all_filters( 'jetpack_activity_log_restore_url_template' ); + remove_all_filters( 'jetpack_activity_log_backup_url_template' ); parent::tearDown(); } @@ -86,4 +87,20 @@ function () use ( $template ) { $this->assertSame( $template, $this->get_rendered_state()['jetpackStatus']['restoreUrlTemplate'] ); } + + public function test_backup_url_template_defaults_to_empty() { + $this->assertSame( '', $this->get_rendered_state()['jetpackStatus']['backupUrlTemplate'] ); + } + + public function test_backup_url_template_comes_from_the_filter() { + $template = 'https://example.org/wp-admin/admin.php?page=jetpack-backup&p=%2F%3Fselected%3D%2522{rewindId}%2522'; + add_filter( + 'jetpack_activity_log_backup_url_template', + function () use ( $template ) { + return $template; + } + ); + + $this->assertSame( $template, $this->get_rendered_state()['jetpackStatus']['backupUrlTemplate'] ); + } } diff --git a/projects/packages/backup/changelog/add-backup-overview-open-older-backups b/projects/packages/backup/changelog/add-backup-overview-open-older-backups new file mode 100644 index 000000000000..beeaef8c6542 --- /dev/null +++ b/projects/packages/backup/changelog/add-backup-overview-open-older-backups @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Overview: Open a backup from a link even when it is not on the activity page currently shown. diff --git a/projects/packages/backup/changelog/fix-backup-overview-backups-with-warnings b/projects/packages/backup/changelog/fix-backup-overview-backups-with-warnings new file mode 100644 index 000000000000..cfdee22694da --- /dev/null +++ b/projects/packages/backup/changelog/fix-backup-overview-backups-with-warnings @@ -0,0 +1,4 @@ +Significance: patch +Type: fixed + +Overview: Treat backups that finished with warnings as backups, so they can be opened and restored and their links work. diff --git a/projects/packages/backup/src/class-jetpack-backup.php b/projects/packages/backup/src/class-jetpack-backup.php index f4cea8d36e9d..f4616e4d4e36 100644 --- a/projects/packages/backup/src/class-jetpack-backup.php +++ b/projects/packages/backup/src/class-jetpack-backup.php @@ -184,6 +184,7 @@ public static function initialize( array $options = array() ) { add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) ); add_action( 'rest_api_init', array( \Automattic\Jetpack\Backup\V0005\REST\Rest_Controller::class, 'register_routes' ) ); add_filter( 'jetpack_activity_log_restore_url_template', array( __CLASS__, 'activity_log_restore_url_template' ) ); + add_filter( 'jetpack_activity_log_backup_url_template', array( __CLASS__, 'activity_log_backup_url_template' ) ); add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 ); add_action( 'admin_menu', array( __CLASS__, 'add_wp_admin_submenu' ), 1 ); // Akismet uses 4, so we need to use 1 to ensure both menus are added when only they exist. @@ -1326,6 +1327,22 @@ public static function activity_log_restore_url_template( $template ) { return admin_url( 'admin.php?page=' . self::JETPACK_BACKUP_SLUG . '&p=%2Frestore%2F{rewindId}' ); } + /** + * Sends the Activity Log's links to a backup to this dashboard's Overview, with that backup selected, when it is on. + * + * The router reads search values as JSON, so the rewind id is quoted to stay a string. + * + * @param string $template Backup URL template, with `{rewindId}` as the placeholder. + * @return string + */ + public static function activity_log_backup_url_template( $template ) { + if ( ! self::is_modernized() ) { + return $template; + } + + return admin_url( 'admin.php?page=' . self::JETPACK_BACKUP_SLUG . '&p=%2F%3Fselected%3D%2522{rewindId}%2522' ); + } + /** * Returns the modernization filter's value, which defaults to true unless the site has the legacy dashboard sticker. * diff --git a/projects/packages/backup/src/dashboard/data/api/activity-log.ts b/projects/packages/backup/src/dashboard/data/api/activity-log.ts index 6ca61662ad1d..e50ca7c616a2 100644 --- a/projects/packages/backup/src/dashboard/data/api/activity-log.ts +++ b/projects/packages/backup/src/dashboard/data/api/activity-log.ts @@ -30,6 +30,9 @@ type FetchArgs = { number?: number; page?: number; sort_order?: ActivitySortOrder; + /** ISO 8601 date-time bounds, so a single backup can be fetched without paging to it. */ + after?: string; + before?: string; }; /** @@ -46,6 +49,8 @@ type FetchArgs = { * @param args.page - 1-indexed page number. * @param args.number - Items per page. * @param args.sort_order - Sort direction. + * @param args.after - Only activity after this date-time. + * @param args.before - Only activity before this date-time. * @return The raw WPCOM-shaped response. */ export async function fetchActivityLog( @@ -56,6 +61,8 @@ export async function fetchActivityLog( number: args.number, page: args.page, sort_order: args.sort_order, + after: args.after, + before: args.before, } ), } ); } diff --git a/projects/packages/backup/src/dashboard/data/normalize/activity-log.ts b/projects/packages/backup/src/dashboard/data/normalize/activity-log.ts index 16ca2ac0ef31..cf224a83a7b6 100644 --- a/projects/packages/backup/src/dashboard/data/normalize/activity-log.ts +++ b/projects/packages/backup/src/dashboard/data/normalize/activity-log.ts @@ -18,6 +18,27 @@ const GRIDICON_TO_KIND: Record< string, ActivityKind > = { themes: 'theme-update', }; +/** + * A completed backup's activity names. WPCOM swaps a backup's gridicon from + * `cloud` to `notice` when it finished with warnings, so the gridicon alone + * misses those backups (and their "N Warnings" links). Storage-limit failures + * share these names but can't be restored, so they need `is_rewindable` too. + */ +const BACKUP_NAME = /^rewind__backup(_only)?_complete/; + +/** + * Whether an entry is a completed backup. + * + * @param entry - WPCOM entry. + * @return True for a backup row. + */ +function isBackupEntry( entry: WpcomActivityEntry ): boolean { + return ( + entry.gridicon === 'cloud' || + ( BACKUP_NAME.test( entry.name ?? '' ) && entry.is_rewindable !== false ) + ); +} + /** * Convert a single WPCOM rewindable-activity entry into the UI's * `ActivityItem` shape. @@ -30,7 +51,9 @@ const GRIDICON_TO_KIND: Record< string, ActivityKind > = { * @return The mapped item. */ export function normalizeEntry( entry: WpcomActivityEntry ): ActivityItem { - const kind = GRIDICON_TO_KIND[ entry.gridicon ] ?? 'other'; + const kind = isBackupEntry( entry ) + ? 'backup' + : ( GRIDICON_TO_KIND[ entry.gridicon ] ?? 'other' ); const actor = entry.actor ?? { type: 'Application', name: 'Jetpack' }; const base = { diff --git a/projects/packages/backup/src/dashboard/data/normalize/test/activity-log.test.ts b/projects/packages/backup/src/dashboard/data/normalize/test/activity-log.test.ts index 388c337d712d..38733cb718b1 100644 --- a/projects/packages/backup/src/dashboard/data/normalize/test/activity-log.test.ts +++ b/projects/packages/backup/src/dashboard/data/normalize/test/activity-log.test.ts @@ -63,6 +63,19 @@ const unknownEntry: WpcomActivityEntry = { }; describe( 'normalizeEntry', () => { + test( 'maps a backup with warnings to a backup ActivityItem', () => { + expect( normalizeEntry( { ...backupEntry, gridicon: 'notice' } ) ).toMatchObject( { + kind: 'backup', + rewindId: '1777035492', + } ); + } ); + + test( 'keeps a backup-named entry that cannot be restored as other', () => { + expect( + normalizeEntry( { ...backupEntry, gridicon: 'notice', is_rewindable: false } ) + ).toMatchObject( { kind: 'other' } ); + } ); + test( 'maps a backup entry to a backup ActivityItem', () => { const item = normalizeEntry( backupEntry ); expect( item ).toMatchObject( { diff --git a/projects/packages/backup/src/dashboard/data/query-client.ts b/projects/packages/backup/src/dashboard/data/query-client.ts index 811f25574f74..2477f415996a 100644 --- a/projects/packages/backup/src/dashboard/data/query-client.ts +++ b/projects/packages/backup/src/dashboard/data/query-client.ts @@ -81,6 +81,9 @@ export const keys = { // descending are different rows. activityLogPage: ( page: number, pageSize: number, sortOrder: ActivitySortOrder ) => [ 'backup', 'activity-log', { page, pageSize, sortOrder } ] as const, + // The few seconds of the log around one backup, for a selection no loaded page holds. + activityLogAround: ( rewindId: string ) => + [ 'backup', 'activity-log', 'around', rewindId ] as const, // Every loaded page of backup sizes, as one infinite query. backupSizes: () => [ 'backup', 'sizes' ] as const, fileTree: ( rewindId: string, folderPath: string | null ) => diff --git a/projects/packages/backup/src/dashboard/hooks/test/use-activity-log.test.ts b/projects/packages/backup/src/dashboard/hooks/test/use-activity-log.test.ts index b751e0e799ad..17c0034586c0 100644 --- a/projects/packages/backup/src/dashboard/hooks/test/use-activity-log.test.ts +++ b/projects/packages/backup/src/dashboard/hooks/test/use-activity-log.test.ts @@ -403,3 +403,127 @@ describe( 'useActivityById', () => { expect( requestedPaths() ).toEqual( [ expect.stringContaining( 'sort_order=asc' ) ] ); } ); } ); + +describe( 'useActivityById for an id no loaded page holds', () => { + const UNLISTED_ID = '1786300000'; + + it.each( [ true, false ] )( + 'exhausts a busy window unless it finds the backup (present: %s)', + async present => { + mockedApiFetch.mockImplementation( ( options: { path?: string } ) => { + const args = new URLSearchParams( options.path?.split( '?' )[ 1 ] ); + if ( ! args.has( 'after' ) ) { + return Promise.resolve( DESCENDING ); + } + const page = Number( args.get( 'page' ) ); + return Promise.resolve( { + current: { + orderedItems: + present && page === 2 + ? [ backupEntry( UNLISTED_ID, '2026-08-09T18:26:40Z' ) ] + : Array.from( { length: 10 }, ( _, i ) => ( { + activity_id: `post-${ page }-${ i }`, + gridicon: 'posts', + summary: 'Post published', + published: '2026-08-09T18:26:39Z', + } ) ), + }, + totalPages: 3, + } ); + } ); + const { result } = renderHook( + () => useActivityById( UNLISTED_ID, 1, ACTIVITY_LOG_DEFAULT_PER_PAGE, 'desc' ), + { wrapper: wrapper() } + ); + await waitFor( () => expect( result.current.hasAnswered ).toBe( true ) ); + expect( result.current.item?.id ?? null ).toBe( + present ? `activity-${ UNLISTED_ID }` : null + ); + expect( windowRequests().map( args => args.get( 'page' ) ) ).toEqual( + present ? [ '1', '2' ] : [ '1', '2', '3' ] + ); + } + ); + + it( 'gives up after three pages when the window is ignored', async () => { + mockedApiFetch.mockImplementation( ( options: { path?: string } ) => { + const args = new URLSearchParams( options.path?.split( '?' )[ 1 ] ); + if ( ! args.has( 'after' ) ) { + return Promise.resolve( DESCENDING ); + } + // The site's whole log, as WordPress.com returns it without the full activity log. + return Promise.resolve( { + current: { + orderedItems: Array.from( { length: 20 }, ( _, i ) => ( { + activity_id: `post-${ args.get( 'page' ) }-${ i }`, + gridicon: 'posts', + summary: 'Post published', + published: '2026-08-09T18:26:39Z', + } ) ), + }, + totalPages: 50, + } ); + } ); + const { result } = renderHook( + () => useActivityById( UNLISTED_ID, 1, ACTIVITY_LOG_DEFAULT_PER_PAGE, 'desc' ), + { wrapper: wrapper() } + ); + await waitFor( () => expect( result.current.hasAnswered ).toBe( true ) ); + expect( result.current.item ).toBeFalsy(); + expect( windowRequests().map( args => args.get( 'page' ) ) ).toEqual( [ '1', '2', '3' ] ); + } ); + + /** + * Requests for a time window rather than a page. + * + * @return The window requests' query args. + */ + function windowRequests(): URLSearchParams[] { + return requestedPaths() + .map( path => new URLSearchParams( path.split( '?' )[ 1 ] ) ) + .filter( args => args.has( 'after' ) ); + } + + it.each( [ UNLISTED_ID, `${ UNLISTED_ID }.817` ] )( + 'asks for the seconds around backup %s', + async rewindId => { + const { result } = renderHook( + () => useActivityById( rewindId, 1, ACTIVITY_LOG_DEFAULT_PER_PAGE, 'desc' ), + { wrapper: wrapper() } + ); + + await waitFor( () => expect( result.current.hasAnswered ).toBe( true ) ); + + expect( windowRequests() ).toHaveLength( 1 ); + const args = windowRequests()[ 0 ]; + expect( args.get( 'after' ) ).toBe( '2026-08-09T18:26:39Z' ); + expect( args.get( 'before' ) ).toBe( '2026-08-09T18:26:42Z' ); + expect( args.get( 'sort_order' ) ).toBe( 'asc' ); + } + ); + + it( 'waits for that lookup rather than answering from the page', async () => { + mockedApiFetch.mockImplementation( ( options: { path?: string } ) => + options?.path?.includes( 'after=' ) ? new Promise( () => {} ) : Promise.resolve( DESCENDING ) + ); + const { result } = renderHook( + () => useActivityById( UNLISTED_ID, 1, ACTIVITY_LOG_DEFAULT_PER_PAGE, 'desc' ), + { wrapper: wrapper() } + ); + + await waitFor( () => expect( windowRequests() ).toHaveLength( 1 ) ); + + expect( result.current ).toMatchObject( { item: null, hasAnswered: false, isFetching: true } ); + } ); + + it( 'leaves any other id to the loaded pages', async () => { + const { result } = renderHook( + () => useActivityById( 'activity-unlisted', 1, ACTIVITY_LOG_DEFAULT_PER_PAGE, 'desc' ), + { wrapper: wrapper() } + ); + + await waitFor( () => expect( result.current.hasAnswered ).toBe( true ) ); + + expect( windowRequests() ).toHaveLength( 0 ); + } ); +} ); diff --git a/projects/packages/backup/src/dashboard/hooks/use-activity-log.ts b/projects/packages/backup/src/dashboard/hooks/use-activity-log.ts index c0fa7a6efe34..bcf949062a79 100644 --- a/projects/packages/backup/src/dashboard/hooks/use-activity-log.ts +++ b/projects/packages/backup/src/dashboard/hooks/use-activity-log.ts @@ -9,6 +9,7 @@ import { import { normalizeActivityLog } from '../data/normalize/activity-log'; import { findRestoreRow, isRestoreRowId, mergeRestoreRows } from '../data/normalize/restores'; import { keys } from '../data/query-client'; +import { isValidRewindId } from '../types/rewind-id'; import { useCanQueryWpcom } from './use-connection'; import { useRecentRestores } from './use-recent-restores'; import { useStickyError } from './use-sticky-error'; @@ -196,15 +197,15 @@ export function useActivityLog( { page, pageSize, sortOrder }: Args ): Result { * selections that are not clicks — a bookmarked `?selected=` on a page nothing * has loaded, and the newest-backup default pinned by the hook below. * - * A null item never means "no such row": it is equally the answer while the page - * query is in flight, after it failed, and while the row sits on a page nothing - * has loaded — `hasAnswered` is the list's page verdict, not the whole log's. + * A backup the loaded pages don't hold is fetched on its own, by the few seconds + * around its rewind id, so `hasAnswered` with a null item means it doesn't exist. + * For any other id it means only that no loaded page holds it. * * @param id - Selection id: `rewindId` for backup items, `activity_id` otherwise. * @param page - The page currently shown in the list. * @param pageSize - The per-page setting currently shown in the list. * @param sortOrder - The sort direction currently shown in the list. - * @return The matching item or null, whether the list's page query has answered, its failure if it did, and whether it is fetching now (false when paused or disabled). + * @return The matching item or null, whether the lookup has answered, its failure if it did, and whether it is fetching now (false when paused or disabled). */ export function useActivityById( id: string | null, @@ -216,17 +217,19 @@ export function useActivityById( hasAnswered: boolean; error: Error | null; isFetching: boolean; + retryLookup?: () => void; } { // Follows the list's `sortOrder`: it is part of the cache key, so pinning it // here would open a second query for rows already on screen. const query = useActivityPageQuery( page, pageSize, sortOrder ); - const restores = useRecentRestores( useCanQueryWpcom() ); + const canQuery = useCanQueryWpcom(); + const restores = useRecentRestores( canQuery ); const queryClient = useQueryClient(); // A merged restore row is never in the feed, so its id is answered by the // collection instead — including which query decides `hasAnswered`. const isRestore = id !== null && isRestoreRowId( id ); - const item = useMemo( () => { + const loadedItem = useMemo( () => { if ( ! id ) { return null; } @@ -255,14 +258,80 @@ export function useActivityById( // eslint-disable-next-line react-hooks/exhaustive-deps }, [ id, isRestore, restores.data, query.data ] ); + const searchesAround = + canQuery && id !== null && isValidRewindId( id ) && query.isSuccess && ! loadedItem; + const around = useQuery( { + queryKey: keys.activityLogAround( id ?? '' ), + queryFn: () => fetchActivityAroundBackup( id as string ), + enabled: searchesAround, + // A finished backup's row never changes. + staleTime: Infinity, + } ); + const lookupError = useStickyError( around.error, around.isFetching ); + const { refetch: refetchAround } = around; + const retryLookup = useCallback( () => { + refetchAround(); + }, [ refetchAround ] ); + + if ( searchesAround ) { + return { + item: findById( around.data?.current?.orderedItems, id as string ), + hasAnswered: around.isSuccess, + error: lookupError, + isFetching: around.isFetching, + retryLookup, + }; + } return { - item, + item: loadedItem, hasAnswered: isRestore ? restores.isSuccess : query.isSuccess, error: isRestore ? restores.error : query.error, isFetching: isRestore ? restores.isFetching : query.isFetching, }; } +// The window is a few seconds wide, so a backup's row is on its first page or two. More pages +// mean WordPress.com ignored the window (it only honours it with the full activity log), and +// paging through the whole log one request at a time would never end well. +const MAX_PAGES_AROUND_BACKUP = 3; + +/** + * Search the window's pages, up to `MAX_PAGES_AROUND_BACKUP`, before declaring a backup absent. + * + * @param rewindId - The backup to find. + * @return The matching page, or the last page searched when no match exists. + */ +async function fetchActivityAroundBackup( rewindId: string ): Promise< WpcomActivityLogResponse > { + const args = aroundRewindId( rewindId ); + let page = 1; + let response: WpcomActivityLogResponse; + do { + response = await fetchActivityLog( { ...args, page } ); + if ( findById( response.current?.orderedItems, rewindId ) ) { + return response; + } + page++; + } while ( page <= Math.min( response.totalPages ?? 1, MAX_PAGES_AROUND_BACKUP ) ); + return response; +} + +/** + * The query for the log around one backup: its "Backup complete" row is stamped with its rewind id. + * + * @param rewindId - A rewind id that has passed `isValidRewindId`. + * @return Fetch args for a narrow, oldest-first window. + */ +function aroundRewindId( rewindId: string ) { + const seconds = Number.parseInt( rewindId, 10 ); + const iso = ( at: number ) => new Date( at * 1000 ).toISOString().replace( '.000Z', 'Z' ); + return { + after: iso( seconds - 1 ), + before: iso( seconds + 2 ), + sort_order: 'asc' as const, + number: 10, + }; +} + /** * Returns the newest backup row in the first page of rewindable * activity, or null when the cache isn't populated or holds no backup diff --git a/projects/packages/backup/src/dashboard/screens/overview.tsx b/projects/packages/backup/src/dashboard/screens/overview.tsx index 2a5de5b53282..4e36da40094e 100644 --- a/projects/packages/backup/src/dashboard/screens/overview.tsx +++ b/projects/packages/backup/src/dashboard/screens/overview.tsx @@ -31,6 +31,7 @@ import { useBackupRequested } from '../hooks/use-enqueue-backup'; import { useRefreshActivityOnBackupComplete } from '../hooks/use-refresh-activity-on-backup-complete'; import { useRevealDetail } from '../hooks/use-reveal-detail'; import { isBackupItem } from '../types/activity'; +import { isValidRewindId } from '../types/rewind-id'; import { overviewState } from './overview-state'; import type { ActivitySortOrder } from '../data/api/activity-log'; import type { View } from '@wordpress/dataviews'; @@ -379,6 +380,34 @@ function OverviewBody() { ); } +/** + * Why the pane has no item for a selection every lookup has answered for. + * + * @param selectedId - The selection id from the URL. + * @return The message to show beside the way out. + */ +function notFoundMessage( selectedId: string ): string { + if ( isRestoreRowId( selectedId ) ) { + // The collection is the last ten restores and has no pages, so there is nowhere else to send the reader. + return __( + "That restore isn't among this site's most recent ones any more.", + 'jetpack-backup-pkg' + ); + } + if ( isValidRewindId( selectedId ) ) { + // `useActivityById` searched the log around the backup itself, not just loaded pages. + return __( + "That backup couldn't be found. It may no longer be available.", + 'jetpack-backup-pkg' + ); + } + // Only loaded pages were searched, so "gone" is not ours to claim. + return __( + "That item isn't on this page of the activity log. It may be on another page, or no longer available.", + 'jetpack-backup-pkg' + ); +} + /** * Right-pane router for the Overview screen. * @@ -410,7 +439,7 @@ function RightPane( { onClearSelected: () => void; } ) { // All four must match the list's arguments — this reads its cache entry. - const { item, hasAnswered, error, isFetching } = useActivityById( + const { item, hasAnswered, error, isFetching, retryLookup } = useActivityById( selectedId, page, pageSize, @@ -443,13 +472,14 @@ function RightPane( { if ( ! item && error ) { return (
- { /* - * Neither the upstream reason nor a retry: the list beside this pane - * reports the activity feed's failure with both, and a second copy of - * each is two error notices and two buttons for one thing to fix. - * Silent too: spoken beside the list's notice, it would only repeat the failure. - */ } - + { /* Only the independent lookup needs its own report; the list reports page failures. */ } +
); } @@ -457,20 +487,7 @@ function RightPane( { return (
- - { isRestoreRowId( selectedId ) - ? // The collection is the last ten restores and has no pages, - // so there is nowhere else to send the reader. - __( - "That restore isn't among this site's most recent ones any more.", - 'jetpack-backup-pkg' - ) - : // Only loaded pages were searched, so "gone" is not ours to claim. - __( - "That item isn't on this page of the activity log. It may be on another page, or no longer available.", - 'jetpack-backup-pkg' - ) } - + { notFoundMessage( selectedId ) } diff --git a/projects/packages/backup/src/rest/class-activity-log-bridge.php b/projects/packages/backup/src/rest/class-activity-log-bridge.php index 64e5aa73e9ed..3a4fd36fe4d3 100644 --- a/projects/packages/backup/src/rest/class-activity-log-bridge.php +++ b/projects/packages/backup/src/rest/class-activity-log-bridge.php @@ -67,6 +67,17 @@ public static function register_routes() { 'type' => 'string', 'enum' => array( 'asc', 'desc' ), ), + // `format` makes the REST server refuse anything `rest_parse_date()` can't read. + 'after' => array( + 'description' => __( 'Only activity after this ISO 8601 date-time.', 'jetpack-backup-pkg' ), + 'type' => 'string', + 'format' => 'date-time', + ), + 'before' => array( + 'description' => __( 'Only activity before this ISO 8601 date-time.', 'jetpack-backup-pkg' ), + 'type' => 'string', + 'format' => 'date-time', + ), ), ) ); @@ -85,6 +96,9 @@ public static function register_routes() { * the real result set rather than the ten rows already on screen. * Omitted when absent: WPCOM defaults it to `desc`. * + * `after` and `before` narrow it to a time window, so the Overview can + * fetch a backup that isn't on any page it has loaded. + * * @param WP_REST_Request $request The REST request. * @return \WP_REST_Response|WP_Error */ @@ -99,6 +113,8 @@ public static function get_activity_log( WP_REST_Request $request ) { 'number' => $request->get_param( 'number' ), 'page' => $request->get_param( 'page' ), 'sort_order' => $request->get_param( 'sort_order' ), + 'after' => $request->get_param( 'after' ), + 'before' => $request->get_param( 'before' ), // Activity summaries are rendered by WPCOM. Without this they // come back in English whatever the reader's language is. '_locale' => get_user_locale(), diff --git a/projects/packages/backup/tests/cleared-selection-back-stack.test.tsx b/projects/packages/backup/tests/cleared-selection-back-stack.test.tsx index dac2fbd8756c..8deeb7ea1b24 100644 --- a/projects/packages/backup/tests/cleared-selection-back-stack.test.tsx +++ b/projects/packages/backup/tests/cleared-selection-back-stack.test.tsx @@ -145,10 +145,14 @@ function renderApp() { * The back link carries no search, which is what leaves the selection with no address — * see `screens/download.tsx`'s ``. * - * @param view - The app's router (a `renderApp` result), to read the address back off. + * @param view - The app's router (a `renderApp` result), to read the address back off. + * @param expire - Remove the chosen backup while away. * @return The chosen row's rewind id. */ -async function roundTripViaDownload( view: ReturnType< typeof renderApp > ): Promise< string > { +async function roundTripViaDownload( + view: ReturnType< typeof renderApp >, + expire = false +): Promise< string > { const chosen = rewindId( PER_PAGE - 1 ); await userEvent.click( await screen.findByRole( 'button', { name: named( chosen ) } ) ); await waitFor( () => expect( view.state.location.search ).toEqual( { selected: chosen } ) ); @@ -159,6 +163,9 @@ async function roundTripViaDownload( view: ReturnType< typeof renderApp > ): Pro // One new row lands while they are away — a completed restore writes one, and so does a // finished backup via `useRefreshActivityOnBackupComplete` — pushing their row onto page 2. log.unshift( rewindId( -1 ) ); + if ( expire ) { + log = log.filter( id => id !== chosen ); + } await userEvent.click( back ); return chosen; @@ -200,10 +207,9 @@ describe( 'Coming back from Download with a row chosen', () => { it( 'lets Back undo clearing a selection that came from memory', async () => { const view = renderApp(); - const chosen = await roundTripViaDownload( view ); + const chosen = await roundTripViaDownload( view, true ); - // The row is on page 2 now and the list is still on page 1, so the pane - // cannot resolve it and hedges instead of claiming it is gone. + // The backup disappeared while away, so the lookup cannot resolve the remembered selection. await userEvent.click( await screen.findByRole( 'button', { name: CLEAR } ) ); await waitFor( () => expect( screen.queryByRole( 'button', { name: CLEAR } ) ).not.toBeInTheDocument() @@ -213,9 +219,7 @@ describe( 'Coming back from Download with a row chosen', () => { view.history.back(); } ); - // The copy admits the row may still be fine, so the discard has to be - // undoable — landing back on the Overview with the selection restored, - // not on the Download screen the return trip came from. + // Clearing remains undoable: Back restores the selection instead of opening Download. await expect( screen.findByRole( 'button', { name: CLEAR } ) ).resolves.toBeInTheDocument(); expect( view.state.location.search ).toEqual( { selected: chosen } ); } ); diff --git a/projects/packages/backup/tests/overview-takeover.test.tsx b/projects/packages/backup/tests/overview-takeover.test.tsx index 54e9ff8bb0f6..eca5d21fb19a 100644 --- a/projects/packages/backup/tests/overview-takeover.test.tsx +++ b/projects/packages/backup/tests/overview-takeover.test.tsx @@ -34,7 +34,7 @@ const CONNECTED = { isRegistered: true, hasConnectedOwner: true, isUserConnected /** * One rewindable-activity entry, in WPCOM's shape. * - * @param gridicon - `cloud` marks a backup row; anything else does not. + * @param gridicon - `cloud` makes a backup row; anything else is a post, which isn't one. * @return A raw activity entry. */ function activityEntry( gridicon: string ) { @@ -46,7 +46,8 @@ function activityEntry( gridicon: string ) { rewind_id: '1786644531.123', actor: { type: 'Application', name: 'Jetpack' }, content: { text: '46 plugins, 23 themes' }, - name: 'rewind__backup_complete_full', + // The Overview also treats a rewindable entry with a backup name as a backup. + name: gridicon === 'cloud' ? 'rewind__backup_complete_full' : 'post__published', }; } diff --git a/projects/packages/backup/tests/php/Admin_Modernization_Gating_Test.php b/projects/packages/backup/tests/php/Admin_Modernization_Gating_Test.php index 3eb2febc318d..bbb43b6a6f94 100644 --- a/projects/packages/backup/tests/php/Admin_Modernization_Gating_Test.php +++ b/projects/packages/backup/tests/php/Admin_Modernization_Gating_Test.php @@ -110,6 +110,21 @@ public function test_activity_log_restore_url_points_at_the_restore_screen_when_ ); } + public function test_activity_log_backup_url_keeps_the_given_template_when_not_modernized() { + add_filter( Jetpack_Backup::MODERNIZATION_FILTER, '__return_false' ); + + $this->assertSame( '', Jetpack_Backup::activity_log_backup_url_template( '' ) ); + } + + public function test_activity_log_backup_url_selects_the_backup_on_the_overview_when_modernized() { + add_filter( Jetpack_Backup::MODERNIZATION_FILTER, '__return_true' ); + + $this->assertSame( + admin_url( 'admin.php?page=jetpack-backup&p=%2F%3Fselected%3D%2522{rewindId}%2522' ), + Jetpack_Backup::activity_log_backup_url_template( '' ) + ); + } + public function test_is_modernized_follows_the_filter() { add_filter( Jetpack_Backup::MODERNIZATION_FILTER, '__return_false' ); $this->assertFalse( Jetpack_Backup::is_modernized() ); diff --git a/projects/packages/backup/tests/php/Rest_Activity_Log_Bridge_Test.php b/projects/packages/backup/tests/php/Rest_Activity_Log_Bridge_Test.php index db1b1ef094a6..1d6564cf9e24 100644 --- a/projects/packages/backup/tests/php/Rest_Activity_Log_Bridge_Test.php +++ b/projects/packages/backup/tests/php/Rest_Activity_Log_Bridge_Test.php @@ -9,6 +9,7 @@ use Automattic\Jetpack\Backup\V0005\Jetpack_Backup; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use WorDBless\Options as WorDBless_Options; use WorDBless\Users as WorDBless_Users; @@ -211,6 +212,54 @@ public function test_rejects_a_direction_outside_the_enum() { $this->assertSame( 'rest_invalid_param', $response->get_data()['code'] ); } + /** + * A time window reaches WordPress.com, which is how the Overview finds a backup on no loaded page. + */ + public function test_forwards_a_time_window() { + $this->arrange_wpcom( array( 'current' => array( 'orderedItems' => array() ) ) ); + + $request = new WP_REST_Request( 'GET', '/jetpack/v4/site/rewindable-activity' ); + $request->set_param( 'after', '2026-10-17T04:30:03Z' ); + $request->set_param( 'before', '2026-10-17T04:30:06+00:00' ); + $response = $this->server->dispatch( $request ); + + $this->assertSame( 200, $response->get_status() ); + parse_str( (string) wp_parse_url( $this->captured_url, PHP_URL_QUERY ), $query ); + $this->assertSame( '2026-10-17T04:30:03Z', $query['after'] ); + $this->assertSame( '2026-10-17T04:30:06+00:00', $query['before'] ); + } + + /** + * A bound that isn't a date-time is refused before anything is sent upstream. + * + * @dataProvider provide_malformed_bounds + * @param string $param Bound to set. + * @param string $value Its malformed value. + */ + #[DataProvider( 'provide_malformed_bounds' )] + public function test_refuses_a_malformed_bound( $param, $value ) { + $this->arrange_wpcom( array( 'current' => array( 'orderedItems' => array() ) ) ); + + $request = new WP_REST_Request( 'GET', '/jetpack/v4/site/rewindable-activity' ); + $request->set_param( $param, $value ); + $response = $this->server->dispatch( $request ); + + $this->assertSame( 400, $response->get_status() ); + $this->assertSame( '', $this->captured_url ); + } + + /** + * Bounds that aren't ISO 8601 date-times. + * + * @return array + */ + public static function provide_malformed_bounds() { + return array( + 'unix timestamp' => array( 'after', '1792247404' ), + 'date only' => array( 'before', '2026-10-17' ), + ); + } + /** * A success code reported as a string is a success. * diff --git a/projects/packages/backup/tests/stale-selection-recovery.test.tsx b/projects/packages/backup/tests/stale-selection-recovery.test.tsx index cf2657d5fea4..1a6588c5f447 100644 --- a/projects/packages/backup/tests/stale-selection-recovery.test.tsx +++ b/projects/packages/backup/tests/stale-selection-recovery.test.tsx @@ -3,8 +3,8 @@ // dead end — the empty state had to offer a way out of it. // // That message also answered for a log in flight and a log that failed, which get -// their own states here. It could never answer "the row is gone": only loaded -// pages are searched, so the way out has to stay recoverable. +// their own states here. Only a backup is looked up beyond the loaded pages, so +// only a backup can be reported as gone. const mockApiFetch = jest.fn(); const mockSearch = jest.fn< Record< string, unknown >, [] >(); @@ -59,6 +59,7 @@ const PAGE_TWO_ID = '1786558131.200'; const NOT_FOUND = "That item isn't on this page of the activity log. It may be on another page, or no longer available."; +const BACKUP_NOT_FOUND = "That backup couldn't be found. It may no longer be available."; // The claim the pane must not make while pages of the log are still unread. const GONE_CLAIM = 'That item is no longer in the activity log.'; const NO_SELECTION = 'Select an item from the list to see details.'; @@ -101,6 +102,15 @@ function pageTwoEntry() { }; } +/** + * A published post on the log's second page, which only a backup lookup can reach past. + * + * @return A raw activity entry. + */ +function pageTwoPostEntry() { + return { ...postEntry(), activity_id: 'act-post-2', summary: 'Post published (page 2)' }; +} + /** * A published post, in the same shape. Carries no `rewind_id`, so a log * holding only this has no default backup for the pane to fall back on. @@ -140,7 +150,7 @@ function finishedBackup() { }; } -type ActivityRows = ReturnType< typeof backupEntry | typeof postEntry >[]; +type ActivityRows = ( ReturnType< typeof backupEntry > | ReturnType< typeof postEntry > )[]; /** What the activity log does: answer per page, never answer, or fail. */ type ActivityAnswer = ActivityRows | ( ( page: number ) => ActivityRows ) | 'pending' | 'error'; @@ -174,8 +184,25 @@ function mockEndpoints( { if ( activity === 'error' ) { return Promise.reject( { code: 'activity_log_fetch_failed', message: FAILURE_REASON } ); } - const requested = Number( /[?&]page=(\d+)/.exec( path )?.[ 1 ] ?? 1 ); - const rows = typeof activity === 'function' ? activity( requested ) : activity; + const rowsOn = ( page: number ) => + typeof activity === 'function' ? activity( page ) : activity; + const args = new URLSearchParams( path.split( '?' )[ 1 ] ); + if ( args.has( 'after' ) ) { + // What WordPress.com does with a window: every page's rows from inside it. + const after = Date.parse( args.get( 'after' ) as string ) / 1000; + const before = Date.parse( args.get( 'before' ) as string ) / 1000; + const all = Array.from( { length: totalPages }, ( _, i ) => rowsOn( i + 1 ) ).flat(); + const inside = all.filter( row => { + const at = Number( ( row as { rewind_id?: string } ).rewind_id ); + return at > after && at < before; + } ); + return Promise.resolve( { + current: { orderedItems: inside }, + totalItems: inside.length, + totalPages: 1, + } ); + } + const rows = rowsOn( Number( args.get( 'page' ) ?? 1 ) ); return Promise.resolve( { current: { orderedItems: rows }, totalItems: rows.length * totalPages, @@ -221,7 +248,7 @@ describe( 'A selection the activity log cannot resolve', () => { // The message is the positive: without it the button below could be // missing because the pane never reached this branch — or threw. - await expect( screen.findByText( NOT_FOUND ) ).resolves.toBeInTheDocument(); + await expect( screen.findByText( BACKUP_NOT_FOUND ) ).resolves.toBeInTheDocument(); expect( screen.getByRole( 'button', { name: CLEAR } ) ).toBeInTheDocument(); } ); @@ -254,7 +281,7 @@ describe( 'A selection the activity log cannot resolve', () => { await expect( screen.findByRole( 'heading', { name: 'Backup complete' } ) ).resolves.toBeInTheDocument(); - expect( screen.queryByText( NOT_FOUND ) ).not.toBeInTheDocument(); + expect( screen.queryByText( BACKUP_NOT_FOUND ) ).not.toBeInTheDocument(); } ); it( 'hands focus to the two-pane region, so the next Tab is in the list', async () => { @@ -278,37 +305,80 @@ describe( 'A selection the activity log cannot resolve', () => { describe( 'A selection on a page nothing has loaded', () => { beforeEach( () => { mockEndpoints( { - activity: page => ( page === 2 ? [ pageTwoEntry() ] : [ backupEntry() ] ), + activity: page => ( page === 2 ? [ pageTwoEntry(), pageTwoPostEntry() ] : [ backupEntry() ] ), backups: [], totalPages: 2, } ); + } ); + + it.each( [ 'cloud', 'notice' ] )( 'opens a backup without paging to it (%s)', async gridicon => { + mockEndpoints( { + activity: page => + page === 2 ? [ { ...pageTwoEntry(), gridicon }, pageTwoPostEntry() ] : [ backupEntry() ], + backups: [], + totalPages: 2, + } ); + mockSearch.mockReturnValue( { selected: PAGE_TWO_ID } ); + + render( ); + + await expect( + screen.findByRole( 'heading', { name: 'Backup complete (page 2)' } ) + ).resolves.toBeInTheDocument(); + } ); + + it( 'announces and retries a lookup failure while the list remains healthy', async () => { mockSearch.mockReturnValue( { selected: PAGE_TWO_ID } ); + const answer = mockApiFetch.getMockImplementation()!; + let failLookup = true; + mockApiFetch.mockImplementation( ( options: { path?: string } ) => + failLookup && options.path?.includes( 'after=' ) + ? Promise.reject( new Error( FAILURE_REASON ) ) + : answer( options ) + ); + render( ); + await expect( screen.findByText( LOAD_FAILED ) ).resolves.toBeInTheDocument(); + expect( screen.queryByText( ACTIVITY_FAILED ) ).not.toBeInTheDocument(); + expect( screen.getByText( FAILURE_REASON ) ).toBeInTheDocument(); + await waitFor( () => + expect( speak ).toHaveBeenCalledWith( expect.stringContaining( LOAD_FAILED ), 'assertive' ) + ); + failLookup = false; + await userEvent.click( screen.getByRole( 'button', { name: 'Try again' } ) ); + await expect( + screen.findByRole( 'heading', { name: 'Backup complete (page 2)' } ) + ).resolves.toBeInTheDocument(); + expect( screen.queryByText( LOAD_FAILED ) ).not.toBeInTheDocument(); } ); - it( 'does not report the row as gone', async () => { + it( 'does not report any other row as gone', async () => { + mockSearch.mockReturnValue( { selected: 'act-post-2' } ); + render( ); // The button is the positive control: it renders in this branch either // way, so a missing claim below cannot be a pane that never rendered. await expect( screen.findByRole( 'button', { name: CLEAR } ) ).resolves.toBeInTheDocument(); - // Page 1 answering says nothing about page 2, which holds this row and - // which nothing has fetched. expect( screen.queryByText( GONE_CLAIM ) ).not.toBeInTheDocument(); expect( screen.getByText( NOT_FOUND ) ).toBeInTheDocument(); } ); - // The control for the two above: without it they rest on a fixture nothing + // The control for the one above: without it, it rests on a fixture nothing // checks, and would read the same way if page 2 held no such row. it( 'resolves the row once the list reaches the page holding it', async () => { + mockSearch.mockReturnValue( { selected: 'act-post-2' } ); + render( ); await userEvent.click( await screen.findByRole( 'button', { name: 'Next page' } ) ); await expect( - screen.findByRole( 'heading', { name: 'Backup complete (page 2)' } ) + screen.findByRole( 'heading', { name: 'Post published (page 2)' } ) ).resolves.toBeInTheDocument(); } ); it( 'leaves the cleared selection on the back stack', async () => { + mockSearch.mockReturnValue( { selected: 'act-post-2' } ); + render( ); await userEvent.click( await screen.findByRole( 'button', { name: CLEAR } ) ); diff --git a/projects/plugins/backup/changelog/add-backup-overview-open-older-backups b/projects/plugins/backup/changelog/add-backup-overview-open-older-backups new file mode 100644 index 000000000000..2d8c33020adf --- /dev/null +++ b/projects/plugins/backup/changelog/add-backup-overview-open-older-backups @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Activity Log: Link backups to that backup in the Backup dashboard, which now opens any backup from a link, not only those on the activity page it shows. Backups that finished with warnings can now be opened and restored there too. diff --git a/projects/plugins/jetpack/changelog/add-backup-overview-open-older-backups b/projects/plugins/jetpack/changelog/add-backup-overview-open-older-backups new file mode 100644 index 000000000000..cf7832be666f --- /dev/null +++ b/projects/plugins/jetpack/changelog/add-backup-overview-open-older-backups @@ -0,0 +1,4 @@ +Significance: minor +Type: enhancement + +Backup: Link backups in the Activity Log to that backup in the Backup dashboard, which now opens any backup from a link, not only those on the activity page it shows. Backups that finished with warnings can now be opened and restored there too.