From 80d29b08a6b9c42627cd403656f886a2d0c0f202 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 12:16:58 +0800 Subject: [PATCH 01/16] Fix client-side media file naming The original filename was stripped and replaced with a generic prefix (e.g., "image.jpeg", "document.pdf") during client-side media processing. Two issues caused this: 1. convertBlobToFile() used instanceof File which fails for cross-realm File objects from the iframe where the block editor canvas renders. Now checks for the name property as a fallback to preserve the original filename. 2. generateThumbnails() referenced attachment.media_filename which doesn't exist. The REST API field is "filename". Thumbnails now correctly use the server-provided filename. --- .../upload-media/src/store/private-actions.ts | 4 +- packages/upload-media/src/store/types.ts | 1 - .../src/test/convert-blob-to-file.ts | 66 +++++++++++++++++++ packages/upload-media/src/utils.ts | 18 +++++ 4 files changed, 86 insertions(+), 3 deletions(-) create mode 100644 packages/upload-media/src/test/convert-blob-to-file.ts diff --git a/packages/upload-media/src/store/private-actions.ts b/packages/upload-media/src/store/private-actions.ts index 4ec74bb88b8735..4b30ac7cb4e7f8 100644 --- a/packages/upload-media/src/store/private-actions.ts +++ b/packages/upload-media/src/store/private-actions.ts @@ -1126,8 +1126,8 @@ export function generateThumbnails( id: QueueItemId ) { // Use sourceFile for thumbnail generation to preserve quality. // WordPress core generates thumbnails from the original (unscaled) image. // Vips will auto-rotate based on EXIF orientation during thumbnail generation. - const file = attachment.media_filename - ? renameFile( item.sourceFile, attachment.media_filename ) + const file = attachment.filename + ? renameFile( item.sourceFile, attachment.filename ) : item.sourceFile; const batchId = uuidv4(); diff --git a/packages/upload-media/src/store/types.ts b/packages/upload-media/src/store/types.ts index 2c18ae9cbd3a02..579ad27d5c7e9e 100644 --- a/packages/upload-media/src/store/types.ts +++ b/packages/upload-media/src/store/types.ts @@ -193,7 +193,6 @@ export interface Attachment { mime_type: string; featured_media?: number; missing_image_sizes?: string[]; - media_filename?: string; poster?: string; /** * EXIF orientation value from the original image. diff --git a/packages/upload-media/src/test/convert-blob-to-file.ts b/packages/upload-media/src/test/convert-blob-to-file.ts new file mode 100644 index 00000000000000..9156fb3314c028 --- /dev/null +++ b/packages/upload-media/src/test/convert-blob-to-file.ts @@ -0,0 +1,66 @@ +/** + * Internal dependencies + */ +import { convertBlobToFile } from '../utils'; + +describe( 'convertBlobToFile', () => { + it( 'should return a File unchanged', () => { + const file = new File( [ 'content' ], 'photo.jpg', { + type: 'image/jpeg', + } ); + const result = convertBlobToFile( file ); + expect( result ).toBe( file ); + expect( result.name ).toBe( 'photo.jpg' ); + } ); + + it( 'should convert a Blob with a default name', () => { + const blob = new Blob( [ 'content' ], { type: 'image/png' } ); + const result = convertBlobToFile( blob ); + expect( result ).toBeInstanceOf( File ); + expect( result.name ).toBe( 'image.png' ); + expect( result.type ).toBe( 'image/png' ); + } ); + + it( 'should use "document" prefix for PDF blobs', () => { + const blob = new Blob( [ 'content' ], { type: 'application/pdf' } ); + const result = convertBlobToFile( blob ); + expect( result.name ).toBe( 'document.pdf' ); + } ); + + it( 'should preserve the name from cross-realm File objects', () => { + // Simulate a cross-realm File object (e.g., from an iframe). + // These objects have a `name` property but fail `instanceof File`. + const crossRealmFile = new Blob( [ 'content' ], { + type: 'image/jpeg', + } ); + Object.defineProperty( crossRealmFile, 'name', { + value: 'IMG_7977.jpg', + writable: false, + } ); + Object.defineProperty( crossRealmFile, 'lastModified', { + value: 1700000000000, + writable: false, + } ); + + const result = convertBlobToFile( crossRealmFile ); + expect( result ).toBeInstanceOf( File ); + expect( result.name ).toBe( 'IMG_7977.jpg' ); + expect( result.type ).toBe( 'image/jpeg' ); + expect( result.lastModified ).toBe( 1700000000000 ); + } ); + + it( 'should preserve the name for non-image cross-realm File objects', () => { + const crossRealmFile = new Blob( [ 'content' ], { + type: 'application/pdf', + } ); + Object.defineProperty( crossRealmFile, 'name', { + value: 'my-document.pdf', + writable: false, + } ); + + const result = convertBlobToFile( crossRealmFile ); + expect( result ).toBeInstanceOf( File ); + expect( result.name ).toBe( 'my-document.pdf' ); + expect( result.type ).toBe( 'application/pdf' ); + } ); +} ); diff --git a/packages/upload-media/src/utils.ts b/packages/upload-media/src/utils.ts index 3950ec03887928..b326f52be41716 100644 --- a/packages/upload-media/src/utils.ts +++ b/packages/upload-media/src/utils.ts @@ -9,6 +9,10 @@ import { _x } from '@wordpress/i18n'; * * If it is already a File object, it is returned unchanged. * + * Handles cross-realm File objects (e.g., from iframes) that have a `name` + * property but fail `instanceof File` checks because the File constructor + * differs between browsing contexts. + * * @param fileOrBlob Blob object. * @return File object. */ @@ -17,6 +21,20 @@ export function convertBlobToFile( fileOrBlob: Blob | File ): File { return fileOrBlob; } + // Handle cross-realm File objects (e.g., from iframes where the block + // editor canvas renders). These objects have a `name` property but fail + // the `instanceof File` check because each browsing context has its own + // File constructor. + if ( + 'name' in fileOrBlob && + typeof ( fileOrBlob as File ).name === 'string' + ) { + return new File( [ fileOrBlob ], ( fileOrBlob as File ).name, { + type: fileOrBlob.type, + lastModified: ( fileOrBlob as File ).lastModified, + } ); + } + // Extension is only an approximation. // The server will override it if incorrect. const ext = fileOrBlob.type.split( '/' )[ 1 ]; From 320ab6493be0d06cd4b8f1cc855360fdd6e3c1a5 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 15:14:17 +0800 Subject: [PATCH 02/16] re-enable client sifde media as naming issue is resolved --- lib/compat/plugin/media.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compat/plugin/media.php b/lib/compat/plugin/media.php index eafd8b054aea32..87d5894c517298 100644 --- a/lib/compat/plugin/media.php +++ b/lib/compat/plugin/media.php @@ -16,4 +16,4 @@ */ // @core-merge: Do not merge this into WordPress core. -add_filter( 'wp_client_side_media_processing_enabled', '__return_false' ); +add_filter( 'wp_client_side_media_processing_enabled', '__return_true' ); From 1d87c66056b79ac2c168644235534331050d028f Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 16:21:26 +0700 Subject: [PATCH 03/16] expect client side media to be enabled --- phpunit/bootstrap.php | 5 ----- phpunit/media/media-processing-test.php | 10 +++------- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php index a9c91e0d7522e5..19667b25979b8e 100644 --- a/phpunit/bootstrap.php +++ b/phpunit/bootstrap.php @@ -96,11 +96,6 @@ function fail_if_died( $message ) { // Enable the widget block editor. tests_add_filter( 'gutenberg_use_widgets_block_editor', '__return_true' ); -// Enable client-side media processing for tests. -// The Gutenberg plugin disables this by default (lib/compat/plugin/media.php), -// but tests need the media functions to be loaded. -tests_add_filter( 'wp_client_side_media_processing_enabled', '__return_true', 20 ); - // Start up the WP testing environment. require $_tests_dir . '/includes/bootstrap.php'; diff --git a/phpunit/media/media-processing-test.php b/phpunit/media/media-processing-test.php index e8b2afbcdf16c0..aa7678f47ba0b4 100644 --- a/phpunit/media/media-processing-test.php +++ b/phpunit/media/media-processing-test.php @@ -202,22 +202,18 @@ public function test_gutenberg_override_media_templates(): void { } /** - * Tests that client-side media processing is disabled by default in the Gutenberg plugin. - * - * The core compat layer defaults to true, but the Gutenberg plugin - * adds a filter to disable it by default (lib/compat/plugin/media.php) - * until known issues are resolved. + * Tests that client-side media processing is enabled by default in the Gutenberg plugin. * * @covers ::gutenberg_is_client_side_media_processing_enabled */ - public function test_client_side_media_processing_disabled_by_default_in_plugin() { + public function test_client_side_media_processing_enabled_by_default_in_plugin() { // Remove the test bootstrap override to check the plugin's actual default. remove_filter( 'wp_client_side_media_processing_enabled', '__return_true', 20 ); $enabled = gutenberg_is_client_side_media_processing_enabled(); // Restore the test bootstrap override. add_filter( 'wp_client_side_media_processing_enabled', '__return_true', 20 ); - $this->assertFalse( $enabled ); + $this->assertTrue( $enabled ); } /** From f0b3a1208c11256920a3bf3d9a611f16884f27f1 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 16:25:00 +0700 Subject: [PATCH 04/16] complete removal of disabling shim --- lib/compat/plugin/media.php | 19 ------------------- lib/load.php | 3 --- 2 files changed, 22 deletions(-) delete mode 100644 lib/compat/plugin/media.php diff --git a/lib/compat/plugin/media.php b/lib/compat/plugin/media.php deleted file mode 100644 index 87d5894c517298..00000000000000 --- a/lib/compat/plugin/media.php +++ /dev/null @@ -1,19 +0,0 @@ - Date: Mon, 23 Feb 2026 17:34:00 +0700 Subject: [PATCH 05/16] Fix client-side media scaled image handling Upload the original file unscaled, then create and sideload the -scaled version after sub-sizes. This matches WordPress core's server-side behavior: original_image metadata is set correctly, sub-sizes derive names from the original, and wp_unique_filename no longer adds -1 to -scaled filenames. --- ...-gutenberg-rest-attachments-controller.php | 21 ++++- .../upload-media/src/store/private-actions.ts | 83 +++++++++++++++---- 2 files changed, 87 insertions(+), 17 deletions(-) diff --git a/lib/media/class-gutenberg-rest-attachments-controller.php b/lib/media/class-gutenberg-rest-attachments-controller.php index b457dd469bcdf6..7e3706773654d1 100644 --- a/lib/media/class-gutenberg-rest-attachments-controller.php +++ b/lib/media/class-gutenberg-rest-attachments-controller.php @@ -26,6 +26,8 @@ public function register_routes(): void { // Special case to set 'original_image' in attachment metadata. $valid_image_sizes[] = 'original'; + // Client-side big image threshold: sideload the scaled version. + $valid_image_sizes[] = 'scaled'; // Used for PDF thumbnails. $valid_image_sizes[] = 'full'; @@ -210,6 +212,8 @@ public function create_item( $request ) { // Disable server-side EXIF rotation so the client can handle it. // This preserves the original orientation value in the metadata. add_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 ); + // Disable server-side big image scaling since the client handles it. + add_filter( 'big_image_size_threshold', '__return_zero', 100 ); } if ( ! $request['convert_format'] ) { @@ -221,6 +225,7 @@ public function create_item( $request ) { remove_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 ); remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 ); remove_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 ); + remove_filter( 'big_image_size_threshold', '__return_zero', 100 ); remove_filter( 'image_editor_output_format', '__return_empty_array', 100 ); return $response; @@ -275,7 +280,7 @@ private static function filter_wp_unique_filename( $filename, $dir, $number, $at } $matches = array(); - if ( preg_match( '/(.*)(-\d+x\d+)-' . $number . '$/', $name, $matches ) ) { + if ( preg_match( '/(.*)(-\d+x\d+|-scaled)-' . $number . '$/', $name, $matches ) ) { $filename_without_suffix = $matches[1] . $matches[2] . ".$ext"; if ( $matches[1] === $orig_name && ! file_exists( "$dir/$filename_without_suffix" ) ) { return $filename_without_suffix; @@ -381,6 +386,20 @@ public function sideload_item( WP_REST_Request $request ) { if ( 'original' === $image_size ) { $metadata['original_image'] = wp_basename( $path ); + } elseif ( 'scaled' === $image_size ) { + // The current attached file is the original; record it as original_image. + $current_file = get_attached_file( $attachment_id, true ); + $metadata['original_image'] = wp_basename( $current_file ); + + // Update the attached file to point to the scaled version. + update_attached_file( $attachment_id, $path ); + + $size = wp_getimagesize( $path ); + + $metadata['width'] = $size ? $size[0] : 0; + $metadata['height'] = $size ? $size[1] : 0; + $metadata['filesize'] = wp_filesize( $path ); + $metadata['file'] = _wp_relative_upload_path( $path ); } else { $metadata['sizes'] = $metadata['sizes'] ?? array(); diff --git a/packages/upload-media/src/store/private-actions.ts b/packages/upload-media/src/store/private-actions.ts index 4b30ac7cb4e7f8..80b42462140220 100644 --- a/packages/upload-media/src/store/private-actions.ts +++ b/packages/upload-media/src/store/private-actions.ts @@ -717,22 +717,7 @@ export function prepareItem( id: QueueItemId ) { // For images that can be processed by vips, check if we need to scale down based on threshold. if ( isImage && isVipsSupported ) { - const { bigImageSizeThreshold, imageOutputFormats } = settings; - - // If a threshold is set, add a resize operation to scale down large images. - // This matches WordPress core's behavior in wp_create_image_subsizes(). - if ( bigImageSizeThreshold ) { - operations.push( [ - OperationType.ResizeCrop, - { - resize: { - width: bigImageSizeThreshold, - height: bigImageSizeThreshold, - }, - isThresholdResize: true, - }, - ] ); - } + const { imageOutputFormats } = settings; // Check if we need to transcode to a different format. // Uses WordPress image_editor_output_format filter settings. @@ -1205,6 +1190,72 @@ export function generateThumbnails( id: QueueItemId ) { operations: thumbnailOperations, } ); } + + // After all sub-sizes, create and sideload the scaled version. + // This must be added AFTER sub-sizes so it's queued last. + // The shouldPauseForSideload mechanism serializes sideloads per + // attachment, ensuring sub-sizes complete first (keeping attached_file + // as the original during sub-size sideloads). + const { bigImageSizeThreshold } = settings; + if ( bigImageSizeThreshold && attachment.id ) { + try { + // Rename sourceFile to match the server attachment filename. + const sourceForScaled = attachment.filename + ? renameFile( item.sourceFile, attachment.filename ) + : item.sourceFile; + + const scaledFile = await vipsResizeImage( + item.id, + sourceForScaled, + { + width: bigImageSizeThreshold, + height: bigImageSizeThreshold, + }, + false, // smartCrop + false, // addSuffix + item.abortController?.signal, + true // scaledSuffix + ); + + if ( scaledFile.wasResized ) { + const scaledOperations: Operation[] = []; + + // Add transcoding if format conversion is configured. + if ( thumbnailTranscodeOperation ) { + scaledOperations.push( + thumbnailTranscodeOperation + ); + } + + scaledOperations.push( OperationType.Upload ); + + dispatch.addSideloadItem( { + file: scaledFile, + onChange: ( [ updatedAttachment ] ) => { + if ( isBlobURL( updatedAttachment.url ) ) { + return; + } + item.onChange?.( [ updatedAttachment ] ); + }, + batchId, + parentId: item.id, + additionalData: { + post: attachment.id, + image_size: 'scaled', + convert_format: false, + }, + operations: scaledOperations, + } ); + } + } catch { + // If scaled version creation fails, continue. + // The original will remain as the attached file. + // eslint-disable-next-line no-console + console.warn( + 'Failed to create scaled version, continuing without it' + ); + } + } } dispatch.finishOperation( id, {} ); From eb4e116ddb2031476d0749471499282abafaaa62 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 17:52:57 +0700 Subject: [PATCH 06/16] Always register sideload route with scaled enum The parent class already registers the sideload route without 'scaled' in its enum, causing a 400 error. Always register our version so WordPress can fall through to the handler that accepts the 'scaled' image_size value. --- ...-gutenberg-rest-attachments-controller.php | 68 +++++++++---------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/lib/media/class-gutenberg-rest-attachments-controller.php b/lib/media/class-gutenberg-rest-attachments-controller.php index 7e3706773654d1..c7422090385d8e 100644 --- a/lib/media/class-gutenberg-rest-attachments-controller.php +++ b/lib/media/class-gutenberg-rest-attachments-controller.php @@ -20,43 +20,43 @@ class Gutenberg_REST_Attachments_Controller extends WP_REST_Attachments_Controll public function register_routes(): void { parent::register_routes(); - // Only register the sideload route if the parent class doesn't already have it. - if ( ! method_exists( get_parent_class( $this ), 'sideload_item' ) ) { - $valid_image_sizes = array_keys( wp_get_registered_image_subsizes() ); - - // Special case to set 'original_image' in attachment metadata. - $valid_image_sizes[] = 'original'; - // Client-side big image threshold: sideload the scaled version. - $valid_image_sizes[] = 'scaled'; - // Used for PDF thumbnails. - $valid_image_sizes[] = 'full'; - - register_rest_route( - $this->namespace, - '/' . $this->rest_base . '/(?P[\d]+)/sideload', + // Always register the sideload route to ensure 'scaled' is in the + // enum. When the parent class also registers this route, WordPress + // tries each handler and uses the first that passes validation. + $valid_image_sizes = array_keys( wp_get_registered_image_subsizes() ); + + // Special case to set 'original_image' in attachment metadata. + $valid_image_sizes[] = 'original'; + // Client-side big image threshold: sideload the scaled version. + $valid_image_sizes[] = 'scaled'; + // Used for PDF thumbnails. + $valid_image_sizes[] = 'full'; + + register_rest_route( + $this->namespace, + '/' . $this->rest_base . '/(?P[\d]+)/sideload', + array( array( - array( - 'methods' => WP_REST_Server::CREATABLE, - 'callback' => array( $this, 'sideload_item' ), - 'permission_callback' => array( $this, 'sideload_item_permissions_check' ), - 'args' => array( - 'id' => array( - 'description' => __( 'Unique identifier for the attachment.', 'gutenberg' ), - 'type' => 'integer', - ), - 'image_size' => array( - 'description' => __( 'Image size.', 'gutenberg' ), - 'type' => 'string', - 'enum' => $valid_image_sizes, - 'required' => true, - ), + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => array( $this, 'sideload_item' ), + 'permission_callback' => array( $this, 'sideload_item_permissions_check' ), + 'args' => array( + 'id' => array( + 'description' => __( 'Unique identifier for the attachment.', 'gutenberg' ), + 'type' => 'integer', + ), + 'image_size' => array( + 'description' => __( 'Image size.', 'gutenberg' ), + 'type' => 'string', + 'enum' => $valid_image_sizes, + 'required' => true, ), ), - 'allow_batch' => $this->allow_batch, - 'schema' => array( $this, 'get_public_item_schema' ), - ) - ); - } + ), + 'allow_batch' => $this->allow_batch, + 'schema' => array( $this, 'get_public_item_schema' ), + ) + ); } /** From b9e5042d0c074da8de0235c65ffd1fe4911ddaa5 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 17:59:47 +0700 Subject: [PATCH 07/16] Override core sideload route to accept scaled size Core's handler validates first and rejects 'scaled' before Gutenberg's appended handler is tried. Passing override=true replaces core's route entirely with ours. --- .../class-gutenberg-rest-attachments-controller.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/media/class-gutenberg-rest-attachments-controller.php b/lib/media/class-gutenberg-rest-attachments-controller.php index c7422090385d8e..07174668f2ce66 100644 --- a/lib/media/class-gutenberg-rest-attachments-controller.php +++ b/lib/media/class-gutenberg-rest-attachments-controller.php @@ -20,9 +20,9 @@ class Gutenberg_REST_Attachments_Controller extends WP_REST_Attachments_Controll public function register_routes(): void { parent::register_routes(); - // Always register the sideload route to ensure 'scaled' is in the - // enum. When the parent class also registers this route, WordPress - // tries each handler and uses the first that passes validation. + // Override the parent's sideload route so that 'scaled' is included + // in the image_size enum. Without the override, core's handler + // validates first and rejects 'scaled' before ours is tried. $valid_image_sizes = array_keys( wp_get_registered_image_subsizes() ); // Special case to set 'original_image' in attachment metadata. @@ -55,7 +55,8 @@ public function register_routes(): void { ), 'allow_batch' => $this->allow_batch, 'schema' => array( $this, 'get_public_item_schema' ), - ) + ), + true // Override core's route so 'scaled' is included in the enum. ); } From 965286d39f5ab29cc0ab0da57f7b855fd8b92366 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 18:11:16 +0700 Subject: [PATCH 08/16] Add backport changelog for core PR #11015 --- backport-changelog/7.0/11015.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 backport-changelog/7.0/11015.md diff --git a/backport-changelog/7.0/11015.md b/backport-changelog/7.0/11015.md new file mode 100644 index 00000000000000..557b4f1cb3c979 --- /dev/null +++ b/backport-changelog/7.0/11015.md @@ -0,0 +1,3 @@ +https://github.com/WordPress/wordpress-develop/pull/11015 + +* https://github.com/WordPress/gutenberg/pull/75817 From 8e5aafe6b128decab4782cb65a0031de1460ed40 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 19:08:59 +0700 Subject: [PATCH 09/16] Fix PHPCS equals sign alignment in sideload_item --- lib/media/class-gutenberg-rest-attachments-controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/media/class-gutenberg-rest-attachments-controller.php b/lib/media/class-gutenberg-rest-attachments-controller.php index 07174668f2ce66..6839c9153ccf2c 100644 --- a/lib/media/class-gutenberg-rest-attachments-controller.php +++ b/lib/media/class-gutenberg-rest-attachments-controller.php @@ -389,7 +389,7 @@ public function sideload_item( WP_REST_Request $request ) { $metadata['original_image'] = wp_basename( $path ); } elseif ( 'scaled' === $image_size ) { // The current attached file is the original; record it as original_image. - $current_file = get_attached_file( $attachment_id, true ); + $current_file = get_attached_file( $attachment_id, true ); $metadata['original_image'] = wp_basename( $current_file ); // Update the attached file to point to the scaled version. From 0afc2c428055a43a68732940e0e2483956460ce6 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 19:40:31 +0700 Subject: [PATCH 10/16] Fix PHPCS equals sign alignment in sideload_image Co-Authored-By: Claude Opus 4.6 --- lib/media/class-gutenberg-rest-attachments-controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/media/class-gutenberg-rest-attachments-controller.php b/lib/media/class-gutenberg-rest-attachments-controller.php index 6839c9153ccf2c..8183e75463fac1 100644 --- a/lib/media/class-gutenberg-rest-attachments-controller.php +++ b/lib/media/class-gutenberg-rest-attachments-controller.php @@ -389,7 +389,7 @@ public function sideload_item( WP_REST_Request $request ) { $metadata['original_image'] = wp_basename( $path ); } elseif ( 'scaled' === $image_size ) { // The current attached file is the original; record it as original_image. - $current_file = get_attached_file( $attachment_id, true ); + $current_file = get_attached_file( $attachment_id, true ); $metadata['original_image'] = wp_basename( $current_file ); // Update the attached file to point to the scaled version. From 6fa5ead60af1690fd21aa5b227e0e1b120ab4377 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 19:53:44 +0700 Subject: [PATCH 11/16] Add tests for scaled image sideload metadata Verify that the sideload endpoint correctly handles the -scaled image flow: original_image meta is set, attached file is updated, dimensions/filesize are recorded, and wp_get_original_image_path resolves to the original. --- .../upload-media/src/store/private-actions.ts | 6 +- ...nberg-rest-attachments-controller-test.php | 229 ++++++++++++++++++ 2 files changed, 230 insertions(+), 5 deletions(-) diff --git a/packages/upload-media/src/store/private-actions.ts b/packages/upload-media/src/store/private-actions.ts index 80b42462140220..e52ecedfe3277f 100644 --- a/packages/upload-media/src/store/private-actions.ts +++ b/packages/upload-media/src/store/private-actions.ts @@ -1191,11 +1191,7 @@ export function generateThumbnails( id: QueueItemId ) { } ); } - // After all sub-sizes, create and sideload the scaled version. - // This must be added AFTER sub-sizes so it's queued last. - // The shouldPauseForSideload mechanism serializes sideloads per - // attachment, ensuring sub-sizes complete first (keeping attached_file - // as the original during sub-size sideloads). + // Create and sideload the scaled version. const { bigImageSizeThreshold } = settings; if ( bigImageSizeThreshold && attachment.id ) { try { diff --git a/phpunit/media/class-gutenberg-rest-attachments-controller-test.php b/phpunit/media/class-gutenberg-rest-attachments-controller-test.php index 3a31dab4538fea..092a346c6177cf 100644 --- a/phpunit/media/class-gutenberg-rest-attachments-controller-test.php +++ b/phpunit/media/class-gutenberg-rest-attachments-controller-test.php @@ -593,6 +593,235 @@ public function test_exif_orientation_in_schema() { $this->assertTrue( $schema['properties']['exif_orientation']['readonly'] ); } + /** + * Verifies that sideloading a scaled image sets original_image metadata + * and updates the attached file to the scaled version, matching core behavior. + * + * @see https://github.com/WordPress/wordpress-develop/blob/trunk/tests/phpunit/tests/media.php + * Core's test_heic_image_upload_is_converted_to_jpeg() verifies equivalent server-side behavior. + * + * @covers ::sideload_item + */ + public function test_sideload_scaled_sets_original_image_metadata() { + wp_set_current_user( self::$admin_id ); + + // Upload the original image with client-side processing. + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=my-photo.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + + // Record the original attached file path before sideloading scaled. + $original_attached_file = get_attached_file( $attachment_id, true ); + + // Sideload the -scaled version (simulating client-side big image threshold resize). + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=my-photo-scaled.jpg' ); + $request->set_param( 'image_size', 'scaled' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // Verify original_image metadata points to the original filename. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + $this->assertArrayHasKey( 'original_image', $metadata, 'original_image metadata should be set after scaled sideload.' ); + $this->assertSame( wp_basename( $original_attached_file ), $metadata['original_image'], 'original_image should be the original filename before scaling.' ); + + // Verify the attached file now points to the scaled version. + $new_attached_file = get_attached_file( $attachment_id, true ); + $this->assertStringContainsString( '-scaled', wp_basename( $new_attached_file ), 'Attached file should now be the -scaled version.' ); + $this->assertSame( 'my-photo-scaled.jpg', wp_basename( $new_attached_file ) ); + + // Verify metadata dimensions and file are updated. + $this->assertArrayHasKey( 'width', $metadata ); + $this->assertArrayHasKey( 'height', $metadata ); + $this->assertArrayHasKey( 'filesize', $metadata ); + $this->assertArrayHasKey( 'file', $metadata ); + $this->assertGreaterThan( 0, $metadata['width'] ); + $this->assertGreaterThan( 0, $metadata['height'] ); + $this->assertGreaterThan( 0, $metadata['filesize'] ); + + // Verify wp_get_original_image_path returns the original file. + $original_path = wp_get_original_image_path( $attachment_id ); + $this->assertSame( 'my-photo.jpg', wp_basename( $original_path ), 'wp_get_original_image_path() should return the original file.' ); + } + + /** + * Verifies that sideloading with image_size=original sets original_image metadata + * without changing the attached file. + * + * @covers ::sideload_item + */ + public function test_sideload_original_sets_original_image_metadata() { + wp_set_current_user( self::$admin_id ); + + // Upload via REST so the file is in the uploads directory. + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=canola.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + + // The attached file before sideload. + $attached_file_before = get_attached_file( $attachment_id, true ); + + // Sideload the "original" version. + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=canola-original.jpg' ); + $request->set_param( 'image_size', 'original' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // Verify original_image metadata is set to the sideloaded file. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + $this->assertArrayHasKey( 'original_image', $metadata ); + $this->assertSame( 'canola-original.jpg', $metadata['original_image'] ); + + // Verify the attached file was NOT changed (only scaled changes it). + $attached_file_after = get_attached_file( $attachment_id, true ); + $this->assertSame( $attached_file_before, $attached_file_after, 'Attached file should not change when sideloading original.' ); + } + + /** + * Verifies the full client-side upload flow with scaled image: + * upload original, sideload sub-sizes, sideload scaled version. + * + * After the full flow, metadata should match core's server-side behavior: + * - original_image points to the unscaled original + * - attached file points to -scaled version + * - sub-sizes are present in metadata + * + * @covers ::create_item + * @covers ::sideload_item + */ + public function test_full_client_side_upload_flow_with_scaled_image() { + wp_set_current_user( self::$admin_id ); + + // Step 1: Upload the original image with client-side processing. + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=landscape.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + $this->assertNotEmpty( $data['missing_image_sizes'], 'Should have missing image sizes after client-side upload.' ); + + // Step 2: Sideload a thumbnail sub-size. + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=landscape-150x150.jpg' ); + $request->set_param( 'image_size', 'thumbnail' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $this->assertSame( 200, $response->get_status() ); + + // Verify sub-size was added to metadata. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + $this->assertArrayHasKey( 'thumbnail', $metadata['sizes'] ); + $this->assertSame( 'landscape-150x150.jpg', $metadata['sizes']['thumbnail']['file'] ); + + // Step 3: Sideload the scaled version (big image threshold). + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=landscape-scaled.jpg' ); + $request->set_param( 'image_size', 'scaled' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // Verify final metadata matches expected state. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + + // original_image should point to the original unscaled file. + $this->assertArrayHasKey( 'original_image', $metadata ); + $this->assertSame( 'landscape.jpg', $metadata['original_image'], 'original_image should be the original filename.' ); + + // The attached file should now be the scaled version. + $attached_file = get_attached_file( $attachment_id, true ); + $this->assertSame( 'landscape-scaled.jpg', wp_basename( $attached_file ), 'Attached file should be the -scaled version.' ); + + // The metadata file should reflect the scaled version. + $this->assertStringContainsString( 'landscape-scaled.jpg', $metadata['file'] ); + + // Sub-sizes should still be present. + $this->assertArrayHasKey( 'thumbnail', $metadata['sizes'] ); + $this->assertSame( 'landscape-150x150.jpg', $metadata['sizes']['thumbnail']['file'] ); + + // wp_get_original_image_path should resolve to the original. + $original_path = wp_get_original_image_path( $attachment_id ); + $this->assertSame( 'landscape.jpg', wp_basename( $original_path ) ); + } + + /** + * Verifies that the scaled sideload filename filter works correctly + * and prevents WordPress from adding numeric suffixes to -scaled filenames. + * + * @covers ::sideload_item + */ + public function test_sideload_scaled_filename_not_suffixed() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=test-photo.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + + // Sideload the scaled version. + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=test-photo-scaled.jpg' ); + $request->set_param( 'image_size', 'scaled' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // The filename should not have a numeric suffix like -scaled-1.jpg. + $attached_file = get_attached_file( $attachment_id, true ); + $this->assertSame( 'test-photo-scaled.jpg', wp_basename( $attached_file ), 'Scaled filename should not have a numeric suffix.' ); + $this->assertStringNotContainsString( '-scaled-1', wp_basename( $attached_file ) ); + } + /** * Verifies metadata consistency between server-side and client-side upload flows. * From 3c926e8891da78ac135ccae8ce4167dab599271c Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 20:07:56 +0700 Subject: [PATCH 12/16] improve doc block --- .../media/class-gutenberg-rest-attachments-controller-test.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit/media/class-gutenberg-rest-attachments-controller-test.php b/phpunit/media/class-gutenberg-rest-attachments-controller-test.php index 092a346c6177cf..5b18f17ad0f93c 100644 --- a/phpunit/media/class-gutenberg-rest-attachments-controller-test.php +++ b/phpunit/media/class-gutenberg-rest-attachments-controller-test.php @@ -598,7 +598,7 @@ public function test_exif_orientation_in_schema() { * and updates the attached file to the scaled version, matching core behavior. * * @see https://github.com/WordPress/wordpress-develop/blob/trunk/tests/phpunit/tests/media.php - * Core's test_heic_image_upload_is_converted_to_jpeg() verifies equivalent server-side behavior. + * For similar core media tests that verify equivalent server-side behavior. * * @covers ::sideload_item */ From 6c24c1bebacdb83407e5ece6fa852691d993f447 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 22:38:09 +0700 Subject: [PATCH 13/16] Use ResizeCrop queue step for scaled image Move the scaled image resize from an inline vipsResizeImage call to a proper ResizeCrop queue operation. This ensures the resize respects maxConcurrentImageProcessing limits and follows the same pattern used for thumbnail generation. --- .../upload-media/src/store/private-actions.ts | 90 ++++++++----------- 1 file changed, 38 insertions(+), 52 deletions(-) diff --git a/packages/upload-media/src/store/private-actions.ts b/packages/upload-media/src/store/private-actions.ts index e52ecedfe3277f..231c3cb4e219a9 100644 --- a/packages/upload-media/src/store/private-actions.ts +++ b/packages/upload-media/src/store/private-actions.ts @@ -1194,63 +1194,49 @@ export function generateThumbnails( id: QueueItemId ) { // Create and sideload the scaled version. const { bigImageSizeThreshold } = settings; if ( bigImageSizeThreshold && attachment.id ) { - try { - // Rename sourceFile to match the server attachment filename. - const sourceForScaled = attachment.filename - ? renameFile( item.sourceFile, attachment.filename ) - : item.sourceFile; - - const scaledFile = await vipsResizeImage( - item.id, - sourceForScaled, + // Rename sourceFile to match the server attachment filename. + const sourceForScaled = attachment.filename + ? renameFile( item.sourceFile, attachment.filename ) + : item.sourceFile; + + // Add scaling to queue. + const scaledOperations: Operation[] = [ + [ + OperationType.ResizeCrop, { - width: bigImageSizeThreshold, - height: bigImageSizeThreshold, + resize: { + width: bigImageSizeThreshold, + height: bigImageSizeThreshold, + }, + isThresholdResize: true, }, - false, // smartCrop - false, // addSuffix - item.abortController?.signal, - true // scaledSuffix - ); - - if ( scaledFile.wasResized ) { - const scaledOperations: Operation[] = []; + ], + ]; - // Add transcoding if format conversion is configured. - if ( thumbnailTranscodeOperation ) { - scaledOperations.push( - thumbnailTranscodeOperation - ); - } + // Add transcoding if format conversion is configured. + if ( thumbnailTranscodeOperation ) { + scaledOperations.push( thumbnailTranscodeOperation ); + } - scaledOperations.push( OperationType.Upload ); + scaledOperations.push( OperationType.Upload ); - dispatch.addSideloadItem( { - file: scaledFile, - onChange: ( [ updatedAttachment ] ) => { - if ( isBlobURL( updatedAttachment.url ) ) { - return; - } - item.onChange?.( [ updatedAttachment ] ); - }, - batchId, - parentId: item.id, - additionalData: { - post: attachment.id, - image_size: 'scaled', - convert_format: false, - }, - operations: scaledOperations, - } ); - } - } catch { - // If scaled version creation fails, continue. - // The original will remain as the attached file. - // eslint-disable-next-line no-console - console.warn( - 'Failed to create scaled version, continuing without it' - ); - } + dispatch.addSideloadItem( { + file: sourceForScaled, + onChange: ( [ updatedAttachment ] ) => { + if ( isBlobURL( updatedAttachment.url ) ) { + return; + } + item.onChange?.( [ updatedAttachment ] ); + }, + batchId, + parentId: item.id, + additionalData: { + post: attachment.id, + image_size: 'scaled', + convert_format: false, + }, + operations: scaledOperations, + } ); } } From 7c36bbf52e7db27cfbcdce30c4faa85e7c53fd1c Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Mon, 23 Feb 2026 23:55:09 +0700 Subject: [PATCH 14/16] Add thorough e2e tests for client-side media Replace weak conditional tests with four unconditional tests covering filename preservation, scaled image sideloading, thumbnail base filename correctness, and below-threshold no-op behavior. Add uploadWithName() helper to enable filename-aware assertions. --- .../various/big-image-size-threshold.spec.js | 326 ++++++++++++------ 1 file changed, 220 insertions(+), 106 deletions(-) diff --git a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js index 30239f121c7e38..a574b4f4ef83c4 100644 --- a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js +++ b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js @@ -21,6 +21,38 @@ test.use( { }, } ); +/** + * Waits for the upload queue to drain and returns the attachment ID + * from the currently selected image block. + * + * @param {Page} page Playwright page object. + * @return {Promise} The attachment ID. + */ +async function waitForUploadAndGetImageId( page ) { + // Wait for the upload queue to be empty. + await page.waitForFunction( + () => { + const uploadStore = window.wp.data.select( 'core/upload-media' ); + if ( ! uploadStore ) { + return true; // Store not available, upload happened server-side. + } + const items = uploadStore.getItems(); + return items.length === 0; + }, + { timeout: 120000 } + ); + + // Get the image ID from the block. + const imageId = await page.evaluate( + () => + window.wp.data.select( 'core/block-editor' ).getSelectedBlock() + ?.attributes?.id + ); + + expect( imageId ).toBeTruthy(); + return imageId; +} + test.describe( 'Big image size threshold', () => { test.beforeAll( async ( { requestUtils } ) => { await requestUtils.deleteAllMedia(); @@ -34,14 +66,60 @@ test.describe( 'Big image size threshold', () => { await requestUtils.deleteAllMedia(); } ); - test( 'should scale down images larger than the threshold', async ( { + test( 'should preserve original filename through client-side upload', async ( { + page, + editor, + imageBlockUtils, + requestUtils, + } ) => { + // Skip if cross-origin isolation is not enabled. + const isCrossOriginIsolated = await page.evaluate( + () => window.crossOriginIsolated + ); + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! isCrossOriginIsolated, + 'Cross-origin isolation headers not configured on server' + ); + + await editor.insertBlock( { name: 'core/image' } ); + + const imageBlock = editor.canvas.locator( + 'role=document[name="Block: Image"i]' + ); + await expect( imageBlock ).toBeVisible(); + + // Upload with a specific filename to verify it is preserved + // through the cross-realm File handling in convertBlobToFile(). + await imageBlockUtils.uploadWithName( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '1024x768_e2e_test_image_size.jpeg', + 'my-vacation-photo.jpeg' + ); + + const image = imageBlock.getByRole( 'img', { + name: 'This image has an empty alt attribute', + } ); + await expect( image ).toBeVisible(); + + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The uploaded filename should be preserved in the source URL. + expect( media.source_url ).toContain( 'my-vacation-photo' ); + } ); + + test( 'should create scaled version with original_image metadata for large images', async ( { page, editor, imageBlockUtils, requestUtils, } ) => { // Skip if cross-origin isolation is not enabled. - // The vips library requires SharedArrayBuffer which needs cross-origin isolation. const isCrossOriginIsolated = await page.evaluate( () => window.crossOriginIsolated ); @@ -67,85 +145,115 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a large image (3200x2400) that exceeds the default threshold (2560). - await imageBlockUtils.upload( + await imageBlockUtils.uploadWithName( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '3200x2400_e2e_test_image_responsive_lightbox.jpeg', + 'landscape-photo.jpeg' + ); + + const image = imageBlock.getByRole( 'img', { + name: 'This image has an empty alt attribute', + } ); + await expect( image ).toBeVisible(); + + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The scaled version should be set as the main image. + expect( media.source_url ).toContain( '-scaled' ); + + // The original_image metadata should be set to the unscaled filename. + expect( media.media_details.original_image ).toBe( + 'landscape-photo.jpeg' + ); + + // The scaled image should be within the threshold dimensions. + expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); + expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); + + // The max dimension should be exactly 2560 (the default threshold). + const maxDimension = Math.max( + media.media_details.width, + media.media_details.height + ); + expect( maxDimension ).toBe( 2560 ); + + // The scaled filename should not have a numeric suffix (e.g. -scaled-1). + // This verifies the regex fix for filter_wp_unique_filename(). + expect( media.source_url ).not.toMatch( /-scaled-\d+/ ); + } ); + + test( 'should generate thumbnails with correct base filename', async ( { + page, + editor, + imageBlockUtils, + requestUtils, + } ) => { + // Skip if cross-origin isolation is not enabled. + const isCrossOriginIsolated = await page.evaluate( + () => window.crossOriginIsolated + ); + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! isCrossOriginIsolated, + 'Cross-origin isolation headers not configured on server' + ); + + await editor.insertBlock( { name: 'core/image' } ); + + const imageBlock = editor.canvas.locator( + 'role=document[name="Block: Image"i]' + ); + await expect( imageBlock ).toBeVisible(); + + // Upload a large image with a known filename. + await imageBlockUtils.uploadWithName( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '3200x2400_e2e_test_image_responsive_lightbox.jpeg' + '3200x2400_e2e_test_image_responsive_lightbox.jpeg', + 'my-photo.jpeg' ); - // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - // Wait for the image URL to be updated to the final uploaded URL. - await page.waitForFunction( - () => { - const uploadStore = - window.wp.data.select( 'core/upload-media' ); - if ( ! uploadStore ) { - return true; // Store not available, upload happened server-side. - } - const items = uploadStore.getItems(); - return items.length === 0; - }, - { timeout: 120000 } - ); - - // Get the image ID from the block. - const imageId = await page.evaluate( - () => - window.wp.data.select( 'core/block-editor' ).getSelectedBlock() - ?.attributes?.id - ); - - if ( imageId ) { - // Fetch the attachment details from the REST API. - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The image should be scaled down (either client-side or server-side). - expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); - expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); - - if ( media.source_url.includes( '-scaled' ) ) { - // When client-side scaling adds the -scaled suffix, - // original_image may or may not be set depending on whether - // the server also processes the image. Only check if present. - if ( media.media_details.original_image ) { - expect( media.media_details.original_image ).toBeDefined(); - } - - // Verify thumbnails were generated. - const sizes = media.media_details.sizes; - expect( sizes ).toBeDefined(); - - // Check that at least some standard sizes were created. - // The exact sizes depend on theme/site configuration. - const hasStandardSizes = - sizes.thumbnail || sizes.medium || sizes.large; - expect( hasStandardSizes ).toBeTruthy(); - - // If thumbnail exists, verify it has reasonable dimensions. - // Default thumbnail size is 150x150. - if ( sizes.thumbnail ) { - expect( sizes.thumbnail.width ).toBeLessThanOrEqual( 150 ); - expect( sizes.thumbnail.height ).toBeLessThanOrEqual( 150 ); - } - - // If medium exists, verify dimensions. - // Default medium size is 300x300. - if ( sizes.medium ) { - expect( sizes.medium.width ).toBeLessThanOrEqual( 300 ); - expect( sizes.medium.height ).toBeLessThanOrEqual( 300 ); - } + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // Verify thumbnails were generated. + const sizes = media.media_details.sizes; + expect( sizes ).toBeDefined(); + + // Check that at least some standard sizes were created. + const hasStandardSizes = sizes.thumbnail || sizes.medium || sizes.large; + expect( hasStandardSizes ).toBeTruthy(); + + // Verify thumbnail filenames use the correct base filename (my-photo), + // not a UUID or wrong name. This validates the attachment.filename fix + // in generateThumbnails(). + const sizeEntries = Object.entries( sizes ); + for ( const [ sizeName, sizeData ] of sizeEntries ) { + if ( sizeName === 'full' ) { + continue; } + // Each thumbnail file should start with "my-photo-". + expect( sizeData.file ).toMatch( /^my-photo-/ ); } + + // Verify the scaled version filename. + expect( media.source_url ).toContain( 'my-photo-scaled' ); } ); - test( 'should not scale images smaller than the threshold', async ( { + test( 'should not scale or set original_image for images below threshold', async ( { page, editor, imageBlockUtils, @@ -169,51 +277,33 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a small image (1024x768) that is below the default threshold (2560). - await imageBlockUtils.upload( + await imageBlockUtils.uploadWithName( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '1024x768_e2e_test_image_size.jpeg' + '1024x768_e2e_test_image_size.jpeg', + 'small-photo.jpeg' ); - // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - // Wait for the upload queue to be empty. - await page.waitForFunction( - () => { - const uploadStore = - window.wp.data.select( 'core/upload-media' ); - if ( ! uploadStore ) { - return true; - } - const items = uploadStore.getItems(); - return items.length === 0; - }, - { timeout: 120000 } - ); - - // Get the image ID from the block. - const imageId = await page.evaluate( - () => - window.wp.data.select( 'core/block-editor' ).getSelectedBlock() - ?.attributes?.id - ); - - if ( imageId ) { - // Fetch the attachment details from the REST API. - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The image should NOT be scaled since it's below the threshold. - expect( media.source_url ).not.toContain( '-scaled' ); - // Original dimensions should be preserved. - expect( media.media_details.width ).toBe( 1024 ); - expect( media.media_details.height ).toBe( 768 ); - } + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The image should NOT be scaled since it's below the threshold. + expect( media.source_url ).not.toContain( '-scaled' ); + + // original_image should NOT be set for images below the threshold. + expect( media.media_details.original_image ).toBeUndefined(); + + // Original dimensions should be preserved exactly. + expect( media.media_details.width ).toBe( 1024 ); + expect( media.media_details.height ).toBe( 768 ); } ); } ); @@ -245,4 +335,28 @@ class ImageBlockUtils { return fileName; } + + /** + * Uploads a file while preserving or renaming to a specific filename. + * Unlike upload() which renames to a UUID, this keeps the original name + * (or uses a custom rename), enabling tests that verify filename handling. + * + * @param {import('@playwright/test').Locator} inputElement The file input element. + * @param {string} customFile Source file in assets directory. + * @param {string|null} rename Optional filename to use instead of original. + * @return {Promise} The filename used for upload. + */ + async uploadWithName( inputElement, customFile, rename = null ) { + const tmpDirectory = await fs.mkdtemp( + path.join( os.tmpdir(), 'gutenberg-test-image-' ) + ); + const targetName = rename || customFile; + const tmpFileName = path.join( tmpDirectory, targetName ); + const filePath = path.join( this.basePath, customFile ); + await fs.copyFile( filePath, tmpFileName ); + + await inputElement.setInputFiles( tmpFileName ); + + return targetName; + } } From 99e311e171e8e508381f22423993d8dc28444e88 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Tue, 24 Feb 2026 12:01:11 +0700 Subject: [PATCH 15/16] Remove re-enabling of client-side media from this PR Move the re-enabling of client-side media processing to a separate PR so this PR focuses only on the file naming fix. Restores the disabling shim, bootstrap test override, and reverts the e2e tests to the trunk version. Co-Authored-By: Claude Opus 4.6 --- lib/compat/plugin/media.php | 19 + lib/load.php | 3 + phpunit/bootstrap.php | 5 + phpunit/media/media-processing-test.php | 10 +- .../various/big-image-size-threshold.spec.js | 326 ++++++------------ 5 files changed, 140 insertions(+), 223 deletions(-) create mode 100644 lib/compat/plugin/media.php diff --git a/lib/compat/plugin/media.php b/lib/compat/plugin/media.php new file mode 100644 index 00000000000000..eafd8b054aea32 --- /dev/null +++ b/lib/compat/plugin/media.php @@ -0,0 +1,19 @@ +assertTrue( $enabled ); + $this->assertFalse( $enabled ); } /** diff --git a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js index a574b4f4ef83c4..30239f121c7e38 100644 --- a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js +++ b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js @@ -21,38 +21,6 @@ test.use( { }, } ); -/** - * Waits for the upload queue to drain and returns the attachment ID - * from the currently selected image block. - * - * @param {Page} page Playwright page object. - * @return {Promise} The attachment ID. - */ -async function waitForUploadAndGetImageId( page ) { - // Wait for the upload queue to be empty. - await page.waitForFunction( - () => { - const uploadStore = window.wp.data.select( 'core/upload-media' ); - if ( ! uploadStore ) { - return true; // Store not available, upload happened server-side. - } - const items = uploadStore.getItems(); - return items.length === 0; - }, - { timeout: 120000 } - ); - - // Get the image ID from the block. - const imageId = await page.evaluate( - () => - window.wp.data.select( 'core/block-editor' ).getSelectedBlock() - ?.attributes?.id - ); - - expect( imageId ).toBeTruthy(); - return imageId; -} - test.describe( 'Big image size threshold', () => { test.beforeAll( async ( { requestUtils } ) => { await requestUtils.deleteAllMedia(); @@ -66,60 +34,14 @@ test.describe( 'Big image size threshold', () => { await requestUtils.deleteAllMedia(); } ); - test( 'should preserve original filename through client-side upload', async ( { - page, - editor, - imageBlockUtils, - requestUtils, - } ) => { - // Skip if cross-origin isolation is not enabled. - const isCrossOriginIsolated = await page.evaluate( - () => window.crossOriginIsolated - ); - // eslint-disable-next-line playwright/no-skipped-test - test.skip( - ! isCrossOriginIsolated, - 'Cross-origin isolation headers not configured on server' - ); - - await editor.insertBlock( { name: 'core/image' } ); - - const imageBlock = editor.canvas.locator( - 'role=document[name="Block: Image"i]' - ); - await expect( imageBlock ).toBeVisible(); - - // Upload with a specific filename to verify it is preserved - // through the cross-realm File handling in convertBlobToFile(). - await imageBlockUtils.uploadWithName( - imageBlock.locator( 'data-testid=form-file-upload-input' ), - '1024x768_e2e_test_image_size.jpeg', - 'my-vacation-photo.jpeg' - ); - - const image = imageBlock.getByRole( 'img', { - name: 'This image has an empty alt attribute', - } ); - await expect( image ).toBeVisible(); - - const imageId = await waitForUploadAndGetImageId( page ); - - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The uploaded filename should be preserved in the source URL. - expect( media.source_url ).toContain( 'my-vacation-photo' ); - } ); - - test( 'should create scaled version with original_image metadata for large images', async ( { + test( 'should scale down images larger than the threshold', async ( { page, editor, imageBlockUtils, requestUtils, } ) => { // Skip if cross-origin isolation is not enabled. + // The vips library requires SharedArrayBuffer which needs cross-origin isolation. const isCrossOriginIsolated = await page.evaluate( () => window.crossOriginIsolated ); @@ -145,115 +67,85 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a large image (3200x2400) that exceeds the default threshold (2560). - await imageBlockUtils.uploadWithName( - imageBlock.locator( 'data-testid=form-file-upload-input' ), - '3200x2400_e2e_test_image_responsive_lightbox.jpeg', - 'landscape-photo.jpeg' - ); - - const image = imageBlock.getByRole( 'img', { - name: 'This image has an empty alt attribute', - } ); - await expect( image ).toBeVisible(); - - const imageId = await waitForUploadAndGetImageId( page ); - - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The scaled version should be set as the main image. - expect( media.source_url ).toContain( '-scaled' ); - - // The original_image metadata should be set to the unscaled filename. - expect( media.media_details.original_image ).toBe( - 'landscape-photo.jpeg' - ); - - // The scaled image should be within the threshold dimensions. - expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); - expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); - - // The max dimension should be exactly 2560 (the default threshold). - const maxDimension = Math.max( - media.media_details.width, - media.media_details.height - ); - expect( maxDimension ).toBe( 2560 ); - - // The scaled filename should not have a numeric suffix (e.g. -scaled-1). - // This verifies the regex fix for filter_wp_unique_filename(). - expect( media.source_url ).not.toMatch( /-scaled-\d+/ ); - } ); - - test( 'should generate thumbnails with correct base filename', async ( { - page, - editor, - imageBlockUtils, - requestUtils, - } ) => { - // Skip if cross-origin isolation is not enabled. - const isCrossOriginIsolated = await page.evaluate( - () => window.crossOriginIsolated - ); - // eslint-disable-next-line playwright/no-skipped-test - test.skip( - ! isCrossOriginIsolated, - 'Cross-origin isolation headers not configured on server' - ); - - await editor.insertBlock( { name: 'core/image' } ); - - const imageBlock = editor.canvas.locator( - 'role=document[name="Block: Image"i]' - ); - await expect( imageBlock ).toBeVisible(); - - // Upload a large image with a known filename. - await imageBlockUtils.uploadWithName( + await imageBlockUtils.upload( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '3200x2400_e2e_test_image_responsive_lightbox.jpeg', - 'my-photo.jpeg' + '3200x2400_e2e_test_image_responsive_lightbox.jpeg' ); + // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - const imageId = await waitForUploadAndGetImageId( page ); - - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // Verify thumbnails were generated. - const sizes = media.media_details.sizes; - expect( sizes ).toBeDefined(); - - // Check that at least some standard sizes were created. - const hasStandardSizes = sizes.thumbnail || sizes.medium || sizes.large; - expect( hasStandardSizes ).toBeTruthy(); - - // Verify thumbnail filenames use the correct base filename (my-photo), - // not a UUID or wrong name. This validates the attachment.filename fix - // in generateThumbnails(). - const sizeEntries = Object.entries( sizes ); - for ( const [ sizeName, sizeData ] of sizeEntries ) { - if ( sizeName === 'full' ) { - continue; + // Wait for the image URL to be updated to the final uploaded URL. + await page.waitForFunction( + () => { + const uploadStore = + window.wp.data.select( 'core/upload-media' ); + if ( ! uploadStore ) { + return true; // Store not available, upload happened server-side. + } + const items = uploadStore.getItems(); + return items.length === 0; + }, + { timeout: 120000 } + ); + + // Get the image ID from the block. + const imageId = await page.evaluate( + () => + window.wp.data.select( 'core/block-editor' ).getSelectedBlock() + ?.attributes?.id + ); + + if ( imageId ) { + // Fetch the attachment details from the REST API. + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The image should be scaled down (either client-side or server-side). + expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); + expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); + + if ( media.source_url.includes( '-scaled' ) ) { + // When client-side scaling adds the -scaled suffix, + // original_image may or may not be set depending on whether + // the server also processes the image. Only check if present. + if ( media.media_details.original_image ) { + expect( media.media_details.original_image ).toBeDefined(); + } + + // Verify thumbnails were generated. + const sizes = media.media_details.sizes; + expect( sizes ).toBeDefined(); + + // Check that at least some standard sizes were created. + // The exact sizes depend on theme/site configuration. + const hasStandardSizes = + sizes.thumbnail || sizes.medium || sizes.large; + expect( hasStandardSizes ).toBeTruthy(); + + // If thumbnail exists, verify it has reasonable dimensions. + // Default thumbnail size is 150x150. + if ( sizes.thumbnail ) { + expect( sizes.thumbnail.width ).toBeLessThanOrEqual( 150 ); + expect( sizes.thumbnail.height ).toBeLessThanOrEqual( 150 ); + } + + // If medium exists, verify dimensions. + // Default medium size is 300x300. + if ( sizes.medium ) { + expect( sizes.medium.width ).toBeLessThanOrEqual( 300 ); + expect( sizes.medium.height ).toBeLessThanOrEqual( 300 ); + } } - // Each thumbnail file should start with "my-photo-". - expect( sizeData.file ).toMatch( /^my-photo-/ ); } - - // Verify the scaled version filename. - expect( media.source_url ).toContain( 'my-photo-scaled' ); } ); - test( 'should not scale or set original_image for images below threshold', async ( { + test( 'should not scale images smaller than the threshold', async ( { page, editor, imageBlockUtils, @@ -277,33 +169,51 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a small image (1024x768) that is below the default threshold (2560). - await imageBlockUtils.uploadWithName( + await imageBlockUtils.upload( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '1024x768_e2e_test_image_size.jpeg', - 'small-photo.jpeg' + '1024x768_e2e_test_image_size.jpeg' ); + // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - const imageId = await waitForUploadAndGetImageId( page ); - - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The image should NOT be scaled since it's below the threshold. - expect( media.source_url ).not.toContain( '-scaled' ); - - // original_image should NOT be set for images below the threshold. - expect( media.media_details.original_image ).toBeUndefined(); - - // Original dimensions should be preserved exactly. - expect( media.media_details.width ).toBe( 1024 ); - expect( media.media_details.height ).toBe( 768 ); + // Wait for the upload queue to be empty. + await page.waitForFunction( + () => { + const uploadStore = + window.wp.data.select( 'core/upload-media' ); + if ( ! uploadStore ) { + return true; + } + const items = uploadStore.getItems(); + return items.length === 0; + }, + { timeout: 120000 } + ); + + // Get the image ID from the block. + const imageId = await page.evaluate( + () => + window.wp.data.select( 'core/block-editor' ).getSelectedBlock() + ?.attributes?.id + ); + + if ( imageId ) { + // Fetch the attachment details from the REST API. + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The image should NOT be scaled since it's below the threshold. + expect( media.source_url ).not.toContain( '-scaled' ); + // Original dimensions should be preserved. + expect( media.media_details.width ).toBe( 1024 ); + expect( media.media_details.height ).toBe( 768 ); + } } ); } ); @@ -335,28 +245,4 @@ class ImageBlockUtils { return fileName; } - - /** - * Uploads a file while preserving or renaming to a specific filename. - * Unlike upload() which renames to a UUID, this keeps the original name - * (or uses a custom rename), enabling tests that verify filename handling. - * - * @param {import('@playwright/test').Locator} inputElement The file input element. - * @param {string} customFile Source file in assets directory. - * @param {string|null} rename Optional filename to use instead of original. - * @return {Promise} The filename used for upload. - */ - async uploadWithName( inputElement, customFile, rename = null ) { - const tmpDirectory = await fs.mkdtemp( - path.join( os.tmpdir(), 'gutenberg-test-image-' ) - ); - const targetName = rename || customFile; - const tmpFileName = path.join( tmpDirectory, targetName ); - const filePath = path.join( this.basePath, customFile ); - await fs.copyFile( filePath, tmpFileName ); - - await inputElement.setInputFiles( tmpFileName ); - - return targetName; - } } From a4399e7c0a1a3846a3ac84b516840ee5aec92caa Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Tue, 24 Feb 2026 12:24:56 +0700 Subject: [PATCH 16/16] Restore improved e2e tests for client-side media file naming These tests validate the file naming fix, not the re-enabling, so they belong in this PR. Co-Authored-By: Claude Opus 4.6 --- .../various/big-image-size-threshold.spec.js | 326 ++++++++++++------ 1 file changed, 220 insertions(+), 106 deletions(-) diff --git a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js index 30239f121c7e38..a574b4f4ef83c4 100644 --- a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js +++ b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js @@ -21,6 +21,38 @@ test.use( { }, } ); +/** + * Waits for the upload queue to drain and returns the attachment ID + * from the currently selected image block. + * + * @param {Page} page Playwright page object. + * @return {Promise} The attachment ID. + */ +async function waitForUploadAndGetImageId( page ) { + // Wait for the upload queue to be empty. + await page.waitForFunction( + () => { + const uploadStore = window.wp.data.select( 'core/upload-media' ); + if ( ! uploadStore ) { + return true; // Store not available, upload happened server-side. + } + const items = uploadStore.getItems(); + return items.length === 0; + }, + { timeout: 120000 } + ); + + // Get the image ID from the block. + const imageId = await page.evaluate( + () => + window.wp.data.select( 'core/block-editor' ).getSelectedBlock() + ?.attributes?.id + ); + + expect( imageId ).toBeTruthy(); + return imageId; +} + test.describe( 'Big image size threshold', () => { test.beforeAll( async ( { requestUtils } ) => { await requestUtils.deleteAllMedia(); @@ -34,14 +66,60 @@ test.describe( 'Big image size threshold', () => { await requestUtils.deleteAllMedia(); } ); - test( 'should scale down images larger than the threshold', async ( { + test( 'should preserve original filename through client-side upload', async ( { + page, + editor, + imageBlockUtils, + requestUtils, + } ) => { + // Skip if cross-origin isolation is not enabled. + const isCrossOriginIsolated = await page.evaluate( + () => window.crossOriginIsolated + ); + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! isCrossOriginIsolated, + 'Cross-origin isolation headers not configured on server' + ); + + await editor.insertBlock( { name: 'core/image' } ); + + const imageBlock = editor.canvas.locator( + 'role=document[name="Block: Image"i]' + ); + await expect( imageBlock ).toBeVisible(); + + // Upload with a specific filename to verify it is preserved + // through the cross-realm File handling in convertBlobToFile(). + await imageBlockUtils.uploadWithName( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '1024x768_e2e_test_image_size.jpeg', + 'my-vacation-photo.jpeg' + ); + + const image = imageBlock.getByRole( 'img', { + name: 'This image has an empty alt attribute', + } ); + await expect( image ).toBeVisible(); + + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The uploaded filename should be preserved in the source URL. + expect( media.source_url ).toContain( 'my-vacation-photo' ); + } ); + + test( 'should create scaled version with original_image metadata for large images', async ( { page, editor, imageBlockUtils, requestUtils, } ) => { // Skip if cross-origin isolation is not enabled. - // The vips library requires SharedArrayBuffer which needs cross-origin isolation. const isCrossOriginIsolated = await page.evaluate( () => window.crossOriginIsolated ); @@ -67,85 +145,115 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a large image (3200x2400) that exceeds the default threshold (2560). - await imageBlockUtils.upload( + await imageBlockUtils.uploadWithName( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '3200x2400_e2e_test_image_responsive_lightbox.jpeg', + 'landscape-photo.jpeg' + ); + + const image = imageBlock.getByRole( 'img', { + name: 'This image has an empty alt attribute', + } ); + await expect( image ).toBeVisible(); + + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The scaled version should be set as the main image. + expect( media.source_url ).toContain( '-scaled' ); + + // The original_image metadata should be set to the unscaled filename. + expect( media.media_details.original_image ).toBe( + 'landscape-photo.jpeg' + ); + + // The scaled image should be within the threshold dimensions. + expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); + expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); + + // The max dimension should be exactly 2560 (the default threshold). + const maxDimension = Math.max( + media.media_details.width, + media.media_details.height + ); + expect( maxDimension ).toBe( 2560 ); + + // The scaled filename should not have a numeric suffix (e.g. -scaled-1). + // This verifies the regex fix for filter_wp_unique_filename(). + expect( media.source_url ).not.toMatch( /-scaled-\d+/ ); + } ); + + test( 'should generate thumbnails with correct base filename', async ( { + page, + editor, + imageBlockUtils, + requestUtils, + } ) => { + // Skip if cross-origin isolation is not enabled. + const isCrossOriginIsolated = await page.evaluate( + () => window.crossOriginIsolated + ); + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! isCrossOriginIsolated, + 'Cross-origin isolation headers not configured on server' + ); + + await editor.insertBlock( { name: 'core/image' } ); + + const imageBlock = editor.canvas.locator( + 'role=document[name="Block: Image"i]' + ); + await expect( imageBlock ).toBeVisible(); + + // Upload a large image with a known filename. + await imageBlockUtils.uploadWithName( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '3200x2400_e2e_test_image_responsive_lightbox.jpeg' + '3200x2400_e2e_test_image_responsive_lightbox.jpeg', + 'my-photo.jpeg' ); - // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - // Wait for the image URL to be updated to the final uploaded URL. - await page.waitForFunction( - () => { - const uploadStore = - window.wp.data.select( 'core/upload-media' ); - if ( ! uploadStore ) { - return true; // Store not available, upload happened server-side. - } - const items = uploadStore.getItems(); - return items.length === 0; - }, - { timeout: 120000 } - ); - - // Get the image ID from the block. - const imageId = await page.evaluate( - () => - window.wp.data.select( 'core/block-editor' ).getSelectedBlock() - ?.attributes?.id - ); - - if ( imageId ) { - // Fetch the attachment details from the REST API. - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The image should be scaled down (either client-side or server-side). - expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); - expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); - - if ( media.source_url.includes( '-scaled' ) ) { - // When client-side scaling adds the -scaled suffix, - // original_image may or may not be set depending on whether - // the server also processes the image. Only check if present. - if ( media.media_details.original_image ) { - expect( media.media_details.original_image ).toBeDefined(); - } - - // Verify thumbnails were generated. - const sizes = media.media_details.sizes; - expect( sizes ).toBeDefined(); - - // Check that at least some standard sizes were created. - // The exact sizes depend on theme/site configuration. - const hasStandardSizes = - sizes.thumbnail || sizes.medium || sizes.large; - expect( hasStandardSizes ).toBeTruthy(); - - // If thumbnail exists, verify it has reasonable dimensions. - // Default thumbnail size is 150x150. - if ( sizes.thumbnail ) { - expect( sizes.thumbnail.width ).toBeLessThanOrEqual( 150 ); - expect( sizes.thumbnail.height ).toBeLessThanOrEqual( 150 ); - } - - // If medium exists, verify dimensions. - // Default medium size is 300x300. - if ( sizes.medium ) { - expect( sizes.medium.width ).toBeLessThanOrEqual( 300 ); - expect( sizes.medium.height ).toBeLessThanOrEqual( 300 ); - } + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // Verify thumbnails were generated. + const sizes = media.media_details.sizes; + expect( sizes ).toBeDefined(); + + // Check that at least some standard sizes were created. + const hasStandardSizes = sizes.thumbnail || sizes.medium || sizes.large; + expect( hasStandardSizes ).toBeTruthy(); + + // Verify thumbnail filenames use the correct base filename (my-photo), + // not a UUID or wrong name. This validates the attachment.filename fix + // in generateThumbnails(). + const sizeEntries = Object.entries( sizes ); + for ( const [ sizeName, sizeData ] of sizeEntries ) { + if ( sizeName === 'full' ) { + continue; } + // Each thumbnail file should start with "my-photo-". + expect( sizeData.file ).toMatch( /^my-photo-/ ); } + + // Verify the scaled version filename. + expect( media.source_url ).toContain( 'my-photo-scaled' ); } ); - test( 'should not scale images smaller than the threshold', async ( { + test( 'should not scale or set original_image for images below threshold', async ( { page, editor, imageBlockUtils, @@ -169,51 +277,33 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a small image (1024x768) that is below the default threshold (2560). - await imageBlockUtils.upload( + await imageBlockUtils.uploadWithName( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '1024x768_e2e_test_image_size.jpeg' + '1024x768_e2e_test_image_size.jpeg', + 'small-photo.jpeg' ); - // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - // Wait for the upload queue to be empty. - await page.waitForFunction( - () => { - const uploadStore = - window.wp.data.select( 'core/upload-media' ); - if ( ! uploadStore ) { - return true; - } - const items = uploadStore.getItems(); - return items.length === 0; - }, - { timeout: 120000 } - ); - - // Get the image ID from the block. - const imageId = await page.evaluate( - () => - window.wp.data.select( 'core/block-editor' ).getSelectedBlock() - ?.attributes?.id - ); - - if ( imageId ) { - // Fetch the attachment details from the REST API. - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The image should NOT be scaled since it's below the threshold. - expect( media.source_url ).not.toContain( '-scaled' ); - // Original dimensions should be preserved. - expect( media.media_details.width ).toBe( 1024 ); - expect( media.media_details.height ).toBe( 768 ); - } + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The image should NOT be scaled since it's below the threshold. + expect( media.source_url ).not.toContain( '-scaled' ); + + // original_image should NOT be set for images below the threshold. + expect( media.media_details.original_image ).toBeUndefined(); + + // Original dimensions should be preserved exactly. + expect( media.media_details.width ).toBe( 1024 ); + expect( media.media_details.height ).toBe( 768 ); } ); } ); @@ -245,4 +335,28 @@ class ImageBlockUtils { return fileName; } + + /** + * Uploads a file while preserving or renaming to a specific filename. + * Unlike upload() which renames to a UUID, this keeps the original name + * (or uses a custom rename), enabling tests that verify filename handling. + * + * @param {import('@playwright/test').Locator} inputElement The file input element. + * @param {string} customFile Source file in assets directory. + * @param {string|null} rename Optional filename to use instead of original. + * @return {Promise} The filename used for upload. + */ + async uploadWithName( inputElement, customFile, rename = null ) { + const tmpDirectory = await fs.mkdtemp( + path.join( os.tmpdir(), 'gutenberg-test-image-' ) + ); + const targetName = rename || customFile; + const tmpFileName = path.join( tmpDirectory, targetName ); + const filePath = path.join( this.basePath, customFile ); + await fs.copyFile( filePath, tmpFileName ); + + await inputElement.setInputFiles( tmpFileName ); + + return targetName; + } }