Skip to content

Media: Enable client-side uploads in the Media Library and media modal - #12585

Open
adamsilverstein wants to merge 77 commits into
WordPress:trunkfrom
adamsilverstein:add/media-library-client-side-uploads
Open

adamsilverstein wants to merge 77 commits into
WordPress:trunkfrom
adamsilverstein:add/media-library-client-side-uploads

Conversation

@adamsilverstein

@adamsilverstein adamsilverstein commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Claude drafted this description, folding in the media modal work from #13875:

Trac ticket: https://core.trac.wordpress.org/ticket/65661

This now also includes the media modal work that was in #13875 (Trac https://core.trac.wordpress.org/ticket/66220), so one PR covers every place core uploads media through wp.Uploader.

Description

Client-side media processing currently only works for files dropped straight on a block in the editor - uploads from the Media Library grid, the Add New Media File screen and the media modal (the wp.media frame behind an Image block's "Media Library" button, the featured image panel and so on) still send the original file to async-upload.php and generate every sub-size on the server. That is why a HEIC converts and uploads when dropped on an Image block but fails in the modal on a server with no HEIC support. This PR routes uploads on all three through the same client-side pipeline the editor uses, so the browser resizes the image and generates the thumbnails.

Why this matters: server-side image processing is a common source of timeouts and memory errors on large images, and results vary depending on what image libraries the host has installed. Processing in the browser avoids both problems, and users get the same upload experience everywhere media is uploaded, not just in the editor.

How it works:

Both screens send the Document-Isolation-Policy header so the page is cross-origin isolated, which the wasm-vips image library requires. This reuses wp_set_up_cross_origin_isolation(), extended to cover the grid and the Add New Media File screen. A shared media-upload-pipeline script configures the @wordpress/upload-media store, queues files, tracks progress, and builds error text; a thin script on each screen intercepts files as they are added to the existing uploader and hands them to that pipeline instead: the original is uploaded via the REST API, the browser generates the sub-sizes and sideloads them, then the attachment is finalized. The existing UI - progress bars, grid tiles, error notices - is reused, so the screens look and behave unchanged. While an upload is in flight the page warns before you navigate away, since an interrupted client-side upload would lose thumbnails that were not sideloaded yet.

If the browser does not support cross-origin isolation (currently Chromium 137+ on a secure origin, exposed as wp_is_document_isolation_policy_supported()) or client-side processing is disabled, the scripts do nothing and uploads fall back to the classic flow unchanged. Audio files also stay on the classic path, since media_handle_upload() derives their title and description from ID3 tags and the REST endpoint does not. Any extra multipart params a plugin adds through plupload_default_params or wp.Uploader.param() are forwarded to the REST request so they still arrive in $_POST. A HEIC file the browser cannot decode (Linux, and Windows without the HEVC extension) is handed back to the classic uploader when the server's image editor supports HEIC, so the server converts it instead of the upload failing; when neither can convert it, the pipeline's error is shown.

Error messages come straight from the pipeline, so the platform-specific HEIC wording from WordPress/gutenberg#81130 shows up in the grid's error sidebar and in the Add New Media File error rows the same way it does in the editor. Progress is estimated from the pipeline's remaining operations and sideloaded sub-sizes, since the store does not report a percentage of its own.

The media modal

The block editor screens are already cross-origin isolated, so the modal mostly needed wiring:

  • The grid script is now media-frame-upload and is enqueued from wp_enqueue_media(), so it loads on every screen that opens a media frame, the grid included. It only loads on requests that are actually isolated, checked by a new wp_is_cross_origin_isolated_request(), which also honors a Document-Isolation-Policy header a plugin sent itself (the Gutenberg plugin does). The Customizer, the Site Icon picker and the classic editor open the frame without isolation and keep classic uploads, without downloading the wp-upload-media chain.
  • When the block editor has already configured the upload-media store, the shared pipeline script adopts it instead of rendering a second provider into it. The editor's transport reports failures as a bare string, which the pipeline now wraps so the server's reason still reaches the modal's error list.
  • Only uploaders that post attachments (async-upload.php with the upload-attachment action) are intercepted, so a plugin's own wp.Uploader pointed somewhere else is left alone.

This replaces the plugin-side workaround in WordPress/gutenberg#82473 and resolves WordPress/gutenberg#82409. Still not covered, worth their own tickets: isolating the Customizer, the Site Icon picker and the classic editor's modal.

Testing Instructions

Test in WordPress Playground

Test in Chrome 137 or newer on a secure origin (https or localhost).

Check that client-side processing is enabled:

  1. Go to Media > Library in grid view.
  2. Open DevTools and run crossOriginIsolated in the console - it should return true. You can also confirm the page response includes the Document-Isolation-Policy: isolate-and-credentialless header in the Network tab. Client-side processing is on by default in a secure context; the wp_client_side_media_processing_enabled filter can turn it off.

Verify uploads go through the client-side pipeline:

  1. Keep the Network tab open and drag a large image onto the grid.
  2. You should see a POST to wp/v2/media creating the attachment, followed by sideload and finalize requests - and no file POST to async-upload.php. That is how you can tell the client-side pipeline handled the upload.
  3. Watch the tile while that happens: the progress bar should advance as the original uploads and thumbnails are sideloaded, rather than sitting at zero until the end.
  4. Confirm the attachment looks normal: thumbnail in the grid, sub-sizes listed in the attachment details. Server files should match what you get before the patch.
  5. Repeat on Media > Add New Media File - same network pattern, the percentage on the row should climb, and the finished upload should show the usual row with Edit and Copy URL links.
  6. Start another large upload and try closing the tab before it finishes: the browser should ask for confirmation. After uploads complete, closing the tab should not prompt.
  7. Test with multiple files at once, including the same file twice - every tile should resolve.

Error handling:

  1. Try a disallowed file type (rename a text file to .xyz): the grid's error sidebar shows the file name and a readable reason, and the placeholder tile is removed rather than left spinning. On Add New Media File the error renders the same notice a server-side failure does, with a Dismiss button that announces the error and returns focus to the browse button.
  2. To see a server error surface, block the wp/v2/media request in DevTools (Network > right-click > Block request URL) and upload again: the server's message appears in the sidebar under the file name.

Media modal:

  1. Open a post in the block editor, add an Image block and click "Media Library". Drop an image on "Upload files" with the Network tab open: same create, sideload, finalize pattern and no async-upload.php. The tile's progress bar advances, and "Select" inserts the finished image into the block.
  2. Try a HEIC or AVIF on a server whose image editor cannot process them: it uploads (HEIC as a converted JPEG) instead of erroring.
  3. Block the wp/v2/media request and upload from the modal: the server's message shows in the modal's error list.
  4. Open the Customizer and pick a site logo, or Settings > General and pick a Site Icon: uploads go through async-upload.php and media-frame-upload.js is not loaded.

Fallback:

  1. Repeat an upload in Firefox or Safari (or add ?browser-uploader on media-new.php) - files should upload through async-upload.php as before. In list mode (Media > Library, list view) the Document-Isolation-Policy header is not sent and the grid script is not loaded.
  2. Upload an MP3 or WAV on either screen: it goes through async-upload.php, and the attachment title comes from the file's tags as before.
  3. Open Media > Add New Media File with ?post_id= set to a post that does not exist and upload an image: it uploads unattached, with no error, matching the classic behavior.

Formats:

  1. Verify that all formats supported by client side media work as expected, regardless of the server's support for them. Tests should include:
  • AVIF, WebP, HEIC formats
  • HDR JPEG images with Gain maps, HDR AVIF images
  • WebP and PNGs with various transparency types and color depths
  • PDFs, Audio and Video files also upload as expected
  • GIF's get a companion video created

Automated coverage: npm run test:e2e -- media-modal-client-side-upload media-library-client-side-upload media-new-client-side-upload runs 33 tests on Chromium (which supports DIP as of the bundled Chrome 149), covering the headers, the pipeline requests, the classic fallback when the page is not isolated, multi-file uploads with duplicates, mid-upload progress, the unload guard, audio staying classic, forwarded upload params, an invalid post_id, the error message, file name, and accessible Dismiss button for rejected and failed uploads, the readiness gate before the store's settings land, the HEIC hand-off to a server that can convert it, a PostInit handler another script placed in wpUploaderInit, and in the media modal: the script loading in the block editor, an upload going create, sideload, finalize and landing in the block, a server error reaching the modal's error list, an uploader with another action left to plupload, and the classic fallback without isolation. npm run test:php -- --filter 'wpEnqueueMediaFrameUpload|wpEnqueueMediaNewUpload|CrossOriginIsolation|wpIsDocumentIsolationPolicySupported' runs 71 PHPUnit tests. All green locally.

AI Use

Code and description both came out of a long back and forth with 🤖 Claude Code. I will review and test.

The client-side media pipeline needs SharedArrayBuffer, which requires a
cross-origin isolated context. Core only isolates the block editor
screens, so uploads from the Media Library grid cannot use the pipeline.

Hook the existing Document-Isolation-Policy output buffer on
load-upload.php, gated to grid mode for users who can upload files.
The mode is resolved the same way upload.php resolves it later in the
request, without updating the saved user option. List mode has no
pipeline integration and stays untouched, avoiding isolation side
effects on a screen that gets no benefit.
Grid uploads go through wp.Uploader/plupload to async-upload.php, doing
all image processing server-side even when the browser could handle it.

Add a media-library-upload script that configures the
@wordpress/upload-media store and intercepts plupload's FilesAdded at a
higher priority, routing each file through the pipeline: REST upload of
the original, client-side thumbnails via wasm-vips, then sideload and
finalize. The grid UI is preserved by mirroring wp-plupload's
placeholder tiles, progress, queue reset, and error sidebar.
mediaSideload/mediaFinalize are thin apiFetch wrappers because the
@wordpress/media-utils equivalents are private APIs.

When the browser is not cross-origin isolated or lacks client-side
support, the script no-ops and classic plupload keeps handling uploads,
so degraded environments lose nothing.
Assert the Document-Isolation-Policy header is sent on the grid and not
in list mode, that a JPEG upload flows through the REST create,
sideload, and finalize endpoints with no async-upload.php requests, and
that a disallowed file type surfaces in the error sidebar.

Playwright's Chromium build ships without Document-Isolation-Policy
support, so the upload assertions skip when the context is not
cross-origin isolated; the header assertions still run everywhere.
@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Core Committers: Use this line as a base for the props when committing in SVN:

Props adamsilverstein, westonruter, andrewserong.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@github-actions

Copy link
Copy Markdown

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

The ticket did not exist yet when the tests were written; annotate all
new test methods now that it has been filed.
CI's Playwright Chromium now supports Document-Isolation-Policy, so the
pipeline E2E test runs for real instead of skipping. The previous asset
was the 50x50 phpunit fixture, smaller than every registered sub-size,
so the pipeline correctly generated zero thumbnails and the
sideload-count assertion failed. Swap in the 640x480 canola.jpg fixture
so thumbnail and medium sub-sizes are generated and sideloaded, and
update the skip comments that claimed Playwright lacks DIP support.

See #65661
The suites gated the isolation callback and enqueue but never proved the
callback is actually wired to load-upload.php, that the inline settings
match what the server computes, or that the pipeline's output is real:

* Assert the default-filters.php hook registration, without which none
  of the gating logic runs.
* Assert the inline settings are exactly the JSON encoding of
  wp_get_media_library_upload_settings(), and that the upload_mimes,
  image_strip_meta, and image_max_bit_depth filters flow through to the
  settings the browser pipeline consumes.
* Extend the E2E happy path past request counting: the finalized
  attachment must carry thumbnail and medium sub-sizes in its metadata,
  and the sideloaded thumbnail file must actually be servable.
Interrupting a client-side pipeline upload is worse than interrupting a
classic plupload one: classic uploads complete server-side once the bytes
arrive, but an interrupted pipeline upload loses browser-generated
thumbnails that were not sideloaded yet and leaves the attachment
unfinalized. Trigger the browser's leave confirmation while the progress
map is non-empty; the guard is scoped to the pipeline, so classic uploads
behave exactly as before.

See #65662
…eline

media-new.php was the last admin upload surface without pipeline
integration: plupload-handlers creates a raw plupload.Uploader (wp.Uploader
never loads there) posting to async-upload.php with all image processing
server-side.

Extend cross-origin isolation to the screen via a new
wp_set_up_media_new_cross_origin_isolation() on load-media-new.php, gated
on client-side processing being enabled and the upload_files capability
(the screen itself already requires it). Add a new media-new-upload admin
script that binds a higher-priority FilesAdded handler on the
plupload-handlers uploader instance and routes files through the
@wordpress/upload-media store, sharing its settings with the grid
integration via wp_get_media_library_upload_settings().

The screen's existing UI helpers are reused rather than replicated:
fileQueued() builds the progress item, uploadSuccess() renders the
finished attachment row through the existing async-upload.php markup
endpoint, itemAjaxError() surfaces per-file errors, and uploadComplete()
runs when the queue drains, so the screen looks and behaves unchanged.
The same beforeunload guard as the grid warns while pipeline uploads are
in flight. When the browser is not cross-origin isolated or lacks
client-side support the script no-ops and the classic plupload flow (and
the browser-uploader HTML fallback form) keep working unchanged.

See #65662
Assert the Document-Isolation-Policy header on media-new.php, the
happy-path pipeline upload (create, sideload, and finalize via REST with
no file upload through async-upload.php; the fetch=3 markup POST is
expected and excluded), and the disallowed-file-type error path.

CI's Playwright Chromium supports Document-Isolation-Policy, so the full
pipeline is exercised there; the upload assertions still skip in browsers
where isolation is unavailable, and the existing media-upload spec keeps
covering the classic path as the degradation check.

See #65662
The test asserts that a failed SVG upload on media-new.php shows a
dismissible error. With the client-side pipeline active (CI's Chromium is
cross-origin isolated), the disallowed file is rejected client-side and
the error renders through the standard per-file error UI, where the
dismiss control is a link, instead of the server-rendered
async-upload.php notice, where it is a button. Target the .dismiss
control by class so both variants pass; the error text and the dismissal
behavior asserted are unchanged.

See #65662
…oreunload guards

The beforeunload guards from this branch had no test coverage at all,
and the media-new.php suites had the same blind spots just closed for
the grid on the base branch:

* Assert the load-media-new.php hook registration in
  default-filters.php and that the inline settings are exactly the JSON
  encoding of wp_get_media_library_upload_settings().
* Add an E2E test per screen for the beforeunload guard: hold sideload
  requests via routing so the upload is deterministically in flight,
  then dispatch a synthetic cancelable beforeunload and assert it is
  prevented while uploading and no longer prevented after completion.
* Extend the media-new.php E2E happy path past request counting: the
  finalized attachment must carry thumbnail and medium sub-sizes and
  the sideloaded thumbnail file must actually be servable.
@adamsilverstein adamsilverstein changed the title Media: Enable client-side media uploads in the Media Library grid Media: Enable client-side media uploads in the Media Library grid and media-new.php Jul 19, 2026
@adamsilverstein adamsilverstein changed the title Media: Enable client-side media uploads in the Media Library grid and media-new.php Media: Enable client-side media uploads in the Media Library Jul 20, 2026
Copilot AI review requested due to automatic review settings July 23, 2026 02:26

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Extends WordPress’s client-side media processing pipeline beyond the block editor to the remaining admin upload surfaces (Media Library grid and Media > Add New), including cross-origin isolation setup, upload routing via the @wordpress/upload-media store, and new automated coverage to validate the end-to-end pipeline and headers.

Changes:

  • Adds Media Library mode resolution and new helpers to enable Document-Isolation-Policy isolation and enqueue upload-routing scripts for upload.php (grid) and media-new.php.
  • Introduces new admin upload integration scripts (media-library-upload, media-new-upload) that intercept plupload flows and route files through the REST-based client-side pipeline.
  • Adds comprehensive PHPUnit + Playwright E2E tests covering header gating, pipeline upload behavior (create/sideload/finalize), beforeunload guards, and error handling.

Reviewed changes

Copilot reviewed 15 out of 16 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/phpunit/tests/media/wpMediaNewCrossOriginIsolation.php Adds PHPUnit coverage for DIP isolation setup on media-new.php.
tests/phpunit/tests/media/wpMediaLibraryCrossOriginIsolation.php Adds PHPUnit coverage for DIP isolation setup and Media Library mode resolution on upload.php grid.
tests/phpunit/tests/media/wpEnqueueMediaNewUpload.php Adds PHPUnit coverage for enqueueing media-new-upload and inline settings.
tests/phpunit/tests/media/wpEnqueueMediaLibraryUpload.php Adds PHPUnit coverage for enqueueing media-library-upload, inline settings, and filter plumbing into settings.
tests/e2e/specs/media-upload.test.js Adjusts an existing E2E assertion to support both server and client-side rejection UIs.
tests/e2e/specs/media-new-client-side-upload.test.js Adds E2E coverage for media-new.php DIP header, pipeline upload, beforeunload guard, and disallowed types.
tests/e2e/specs/media-library-client-side-upload.test.js Adds E2E coverage for upload.php grid DIP header, pipeline upload, beforeunload guard, and disallowed types (plus list-mode header absence).
src/wp-includes/script-loader.php Registers the new admin script handles and their dependencies/translations.
src/wp-includes/media.php Adds mode helper, isolation setup helpers, shared upload settings helper, and enqueue helpers for the two upload surfaces.
src/wp-includes/default-filters.php Wires the new isolation setup callbacks into the relevant load-* hooks.
src/wp-admin/upload.php Enqueues the new grid upload integration script in Media Library grid mode.
src/wp-admin/media-new.php Enqueues the new Media > Add New upload integration script.
src/js/_enqueues/admin/media-new-upload.js Implements media-new.php plupload interception, pipeline routing, UI mirroring, progress sync, and beforeunload guard.
src/js/_enqueues/admin/media-library-upload.js Implements Media Library grid uploader interception, pipeline routing, UI mirroring, progress sync, and beforeunload guard.
Gruntfile.js Adds build mappings for the two new admin scripts.
Comments suppressed due to low confidence (1)

src/wp-includes/media.php:6846

  • wp_enqueue_media_new_upload() enqueues the pipeline integration on any secure origin, but wp_start_cross_origin_isolation_output_buffer() (and therefore crossOriginIsolated) is Chromium 137+ only. On other browsers this script cannot run and will always no-op, so enqueueing it adds avoidable page weight. Consider gating enqueueing on wp_get_chromium_major_version() >= 137 to skip loading unused bundles in browsers that can’t be isolated by DIP.
	if ( ! wp_is_client_side_media_processing_enabled() ) {
		return;
	}

	wp_enqueue_script( 'media-new-upload' );

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/wp-includes/media.php Outdated
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 23, 2026 03:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 16 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

tests/phpunit/tests/media/wpEnqueueMediaLibraryUpload.php:46

  • tear_down() restores HTTP_HOST but not HTTP_USER_AGENT. If set_up() sets a Chromium UA for deterministic enqueue behavior, tear_down() should restore/unset it to avoid leaking the UA into later tests.
		if ( null === $this->original_http_host ) {
			unset( $_SERVER['HTTP_HOST'] );
		} else {
			$_SERVER['HTTP_HOST'] = $this->original_http_host;
		}

Comment thread tests/phpunit/tests/media/wpEnqueueMediaLibraryUpload.php
westonruter and others added 14 commits October 16, 2026 22:00
The pipeline settings are now encoded with `JSON_HEX_TAG | JSON_UNESCAPED_SLASHES`, so the tests comparing the inline script against `wp_json_encode()` of the settings failed on the escaped slashes in MIME types. Encode with the same flags, and assert the result is a string to narrow away `false`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`WP_Scripts::get_data()` returns `mixed`, so joining its `before` value with `implode()` passed an `array<mixed, mixed>` where `array<string>` is expected. `WP_Scripts::get_inline_script_data()` already joins the inline scripts and returns a string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reading `$GLOBALS['wp_scripts']` gives `mixed`, which the `WP_Scripts|null` property does not accept. Declare the global with an `@global` tag, as other script tests do, so its type is known.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The `?string` properties holding the original `$_SERVER` and `$_GET` values were assigned `mixed`. These values are strings whenever they are set, so check with `is_string()` before storing them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The untyped `$mimes` parameter was `mixed`, so unsetting its `gif` offset was flagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PHPStan does not apply it to the closure; the native `array` types are what resolve the `mixed` offset access.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@westonruter

Copy link
Copy Markdown
Member

The PHP changes are now free of all PHPStan rule level 10 errors.

Co-authored-by: Weston Ruter <westonruter@gmail.com>
@adamsilverstein
adamsilverstein requested review from westonruter and a balanced review from Copilot October 19, 2026 20:17

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread src/wp-includes/media.php Outdated
Comment on lines +6843 to +6849
if ( ! wp_is_client_side_media_processing_enabled() || ! wp_is_document_isolation_policy_supported() ) {
return;
}

if ( ! wp_is_cross_origin_isolated_request() ) {
return;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: these two if statements could be combined.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 426c7ab.

Comment thread src/wp-includes/media.php Outdated

if ( null === $chromium_version || $chromium_version < 137 ) {
return false;
$GLOBALS['_wp_cross_origin_isolated'] = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be slightly better if this were marked as an explicit global $_wp_cross_origin_isolated, and add a @global bool $_wp_cross_origin_isolated. It feels less ad hoc this way.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 426c7ab.

Comment thread src/wp-includes/media.php Outdated
Comment thread src/wp-includes/media.php Outdated
adamsilverstein and others added 3 commits October 19, 2026 14:15
Co-authored-by: Weston Ruter <westonruter@gmail.com>
Co-authored-by: Weston Ruter <westonruter@gmail.com>
Combines the enqueue guards into one condition and sets the flag through a declared global, documented with @global, in both the function that sets it and the one that reads it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UDLDCCiR2MuQ6MeizyiAgi

@westonruter westonruter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

A code review of the branch (medium effort) turned up the findings below, attached inline and ordered roughly by severity. They have not been independently verified, so each should be confirmed before acting on it.

The ones most likely to regress behavior that works today:

  1. Arbitrary plupload params are forwarded to POST /wp/v2/media as schema fields.
  2. Document-Isolation-Policy is sent on upload.php (grid) and media-new.php with no opt-out.
  3. Plupload's client-side resize setting is bypassed.
  4. A second MediaUploadProvider can race the editor's on block editor screens.
  5. wp_max_upload_size() now coerces the upload_size_limit filter result.

The rest are parity gaps (no progress callback) and cleanups (duplicated settings logic, repeated enqueue work, global isolation state).

* @param {number} postId The validated post to attach the upload to, or 0.
* @return {Record<string, unknown>} Additional data for the upload.
*/
function additionalDataFromParams( params, postId ) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

additionalDataFromParams() forwards every plupload multipart param except action, _wpnonce, and post_id to the REST /wp/v2/media create request, where each is read as a schema field. async-upload.php simply ignored unknown $_POST keys.

Failure scenario: A plugin adds a param through plupload_default_params or wp.Uploader.param() for its own use, and the param happens to share a name with a REST attachment arg (status, author, title, caption, meta, alt_text). REST now applies it, so the attachment gets the wrong status, author, or title, or the request fails with a 400 rest_invalid_param (e.g. a non-numeric author or status=foo). The same upload worked through the classic path.

An allowlist of the params REST is meant to receive would be safer than a denylist.

Comment thread src/wp-includes/media.php
}

if ( ! $screen->is_block_editor() && 'site-editor' !== $screen->id && ! ( 'widgets' === $screen->id && wp_use_widgets_block_editor() ) ) {
$is_media_screen = 'media' === $screen->id || ( 'upload' === $screen->id && 'grid' === wp_get_media_library_mode() );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

Document-Isolation-Policy is now sent on upload.php (grid) and media-new.php with no opt-out. The action page-builder escape hatch is skipped for media screens, and wp_is_document_isolation_policy_supported() has no filter.

Failure scenario: A site turned DIP off with Gutenberg's gutenberg_use_document_isolation_policy filter because plugin iframes broke. Gutenberg only unhooks core on the post, site editor, and widgets screens, so the Media Library and Add New screens now send Document-Isolation-Policy: isolate-and-credentialless anyway. Same-origin iframes that plugins inject there (thickbox, media offload or DAM panels) lose contentDocument access, and cross-origin subresources lose credentials.

A filter to disable it on these screens would give such sites a way out.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we alraady have a way to disable client side media handling - using the wp_client_side_media_processing_enabled filter. As soon as this is set, DIP should not be set on the upload screen. I'll double check to verify that is the case.

fileQueued( file );

// canHandleBatch() already established that every file has one.
const nativeFile = /** @type {File} */ ( file.getNative() );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

file.getNative() hands the original File to the pipeline, which bypasses plupload's client-side resize setting (setResize() and the "Scale images" checkbox, or a resize passed through plupload_init). The forwarded image_resize field is ignored by REST.

Failure scenario: A user has the upload_resize setting on (the checkbox is printed by a plugin hooking media_upload_max_image_resize) and uploads a 6000px image on media-new.php. Classic plupload would have scaled it down to the large size before upload. The pipeline uploads the full-resolution original, so the resize preference is silently dropped.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this isn't accurate. the client side pipeline generates the the same -scaled version that the the server side does. I'll double check the output files before and after this change, the encoding may differ but the sizes should all be the same.

*/
window.__clientSideMediaProcessing = true;

wp.element

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

On block editor screens configure() runs when the script loads, before the editor's provider has committed. It renders a second MediaUploadProvider into the same global store with the raw wp.mediaUtils.uploadMedia as mediaUpload, so the two providers race on updateSettings.

Failure scenario: On post.php the media-frame-upload script runs before the editor initializes, so isStoreConfigured() is false and the script renders its own provider. If its effect commits after the editor's, or re-commits later, the editor's mediaUpload/mediaSideload settings are replaced with this script's. Block editor uploads then run with settings that aren't the editor's, and which settings win depends on load order.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I don't think this is possible but we can add a guard against it.

Comment thread src/wp-includes/media.php
* @param int $p_bytes Maximum size of POST data in bytes.
*/
return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
return max( 0, (int) apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes ) );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

The upload_size_limit filter result now goes through (int) and max( 0, … ). That changes the return value of a widely used public function only to satisfy a type annotation.

Failure scenario: A filter returning a shorthand string such as '64M', a float, or a negative/sentinel value used to pass through unchanged to callers and to plupload's max_file_size, which accepts shorthand. Now '64M' becomes 64 bytes, and every upload larger than that is rejected by plupload and by the pipeline's validateFileSize().

If the coercion is kept, it may be better split into its own change with a _doing_it_wrong() for non-integer filter results.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@westonruter this was likely added during type linting, what do you think? I'm fine leaving as is.

}
handleError( wpUploader, model, error, nativeFile );
},
onProgress: function ( /** @type {number} */ percent ) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

Pipeline uploads update model.percent but never call wpUploader.progress( model ), which wp-plupload.js does on every UploadProgress. That breaks parity with the classic callbacks.

Failure scenario: A plugin or view passes a progress callback to wp.Uploader to drive its own progress UI or analytics. For client-side uploads it still receives added, success, and error, but no progress events, so its UI stays at 0% until the upload completes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we probably need to fix this on the Gutenberg side, not here. I'll look.

Comment thread src/wp-includes/media.php
* imageMaxBitDepth: non-negative-int, // Maximum bit depth for generated images.
* }
*/
function wp_get_media_library_upload_settings(): array {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

wp_get_media_library_upload_settings() repeats the big_image_size_threshold, image_strip_meta, and image_max_bit_depth filter calls and the image size collection that WP_REST_Server::get_index() already does, and the two copies already disagree. The REST index casts the threshold without clamping and also exposes generate_animated_image_subsizes, which this copy omits.

Failure scenario: A plugin adjusting the pipeline settings sees different results in the editor and in the Media Library, and the copies drift further over time. Extracting one shared helper and calling it from both places would keep them in sync.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is an issue.

Comment thread src/wp-includes/media.php
JS;

wp_add_inline_script(
'media-upload-pipeline',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

_wp_enqueue_media_upload_pipeline_script() rebuilds the settings and appends another inline _wpMediaUploadPipelineSettings script to media-upload-pipeline on every call. wp_is_document_isolation_policy_supported() also re-parses the User-Agent on each of its three or more calls per request.

Failure scenario: When a plugin calls wp_enqueue_media() on media-new.php, both wp_enqueue_media_new_upload() and wp_enqueue_media_frame_upload() run. The settings blob, which includes every image size and MIME type, is computed and printed twice. A run-once guard (e.g. wp_script_is() or a static flag) and a memoized UA check would avoid this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this one, I'm not sure it is right, can add the guard if it is though.

Comment thread src/wp-includes/media.php Outdated

if ( null === $chromium_version || $chromium_version < 137 ) {
return false;
$GLOBALS['_wp_cross_origin_isolated'] = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment by Claude Opus 5.5

Isolation state is stored in the ad hoc global $_wp_cross_origin_isolated, which is never reset. The deprecated wp_start_cross_origin_isolation_output_buffer() also sets it as a side effect.

Failure scenario: In PHPUnit, once one test sends the header, every later test sees wp_is_cross_origin_isolated_request() === true and enqueues the pipeline unless it unsets the global. At runtime, any call to the deprecated wrapper or a manual header call outside a screen check sets the flag for the rest of the request. Checking headers_list() alone, or using a filterable function, would avoid the hidden global state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Uploads from the editor's media library modal still go through the server

3 participants