Repository navigation
Client Side Media: Optimize previously uploaded media - #79509
adamsilverstein wants to merge 34 commits into
Conversation
…ration Add the store primitives to re-process an already-uploaded attachment client-side: a public optimizeExistingItem action that enqueues a queue item which fetches the original file, re-compresses it (same format) via the existing TranscodeImage operation, uploads the result as a new attachment, and regenerates sub-sizes. Introduce the FetchRemoteFile operation (and a fetchFile utility) to download an existing file by URL, and a FETCH_REMOTE_FILE_ERROR code. Unsupported or unprocessable formats are skipped via onError, leaving the original attachment untouched. Part of #79364.
…images Register an editor.BlockEdit filter that adds an "Optimize" inspector panel to image-bearing blocks (image, cover, media-text, post-featured-image, site-logo). The control resolves the block's attachment, dispatches optimizeExistingItem against its full-size original, repoints the block at the new optimized attachment, and reports progress and errors via snackbars. Gated on window.__clientSideMediaProcessing and isClientSideMediaSupported() so it only appears when client-side media processing is active. Part of #79364.
…e2e flow Add store unit tests for the optimizeExistingItem enqueue shape, its unsupported/non-image/duplicate guards, and fetchRemoteFile success and error paths. Extend the client-side media processing e2e spec with an 'optimize a previously uploaded image' case asserting the block repoints to a new -optimized attachment that is no larger than the original. Part of #79364.
|
Size Change: +1.45 kB (+0.02%) Total Size: 7.92 MB 📦 View Changed
|
The optimizeExistingItem action was added without regenerating the autogenerated API docs, causing the check-local-changes CI step to fail.
|
Flaky tests detected in e5f749a. 🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/33421132919 Should save the changes in
|
…ze-existing-media # Conflicts: # packages/editor/CHANGELOG.md # packages/upload-media/src/store/private-actions.ts # packages/upload-media/src/utils.ts
…peration resolves Trunk's cancelItem gained additional async steps (retry scheduling, GIF-to-video cancellation), so a fire-and-forget dispatch no longer guarantees the caller's onError has run by the time fetchRemoteFile settles.
…2e test Trunk migrated the image block inspector to media and settings groups (1e3ad1f), so the inspector now opens on the Content tab and the Optimize panel on the Settings tab is no longer visible by default.
|
Can you share a screenshot or demo of how this looks (to aid other reviewers in assessing this)? I'm a little hesitant about how we expose UI controls for image optimisation as it's quite an advanced feature for the casual user and for much of the rest of client-side media processing we're attempting to hide or abstract this away for folks so that the user is unaware of what's happening. If and when you're ready it'd be good to ping some designers to help guide where and how we expose this in the UI. My leaning would be to not include this in the 7.1 cycle, as my hunch is that overall the client-side media processing feature is a good one for future uploads, and reprocessing or optimising existing images feels a bit like plugin territory (or an administrative task). But I'd be keen to hear what others think. |
I agree, this probably needs some design feedback. I've modeled it on what Pascal built for media experiments. I'd also love to explore a bulk optimization feature separately. I'll capture some screencasts/screenshots. |
Added to the PR and Issue descriptions |
|
LGTM 👍 Nice to see some familiar code :) We can probably put it behind a flag to continue refining it. |
Thanks for the canonical example! By flag do you mean making it an experiment (enabled in settings) or something else? |
|
Yes an experiment |
|
An experiment sounds good 👍 It could be a good way to play around with other UI ideas, too. The sidebar panel idea is fairly prominent. Another option if we wanted something a little more power-user-ey could be to add a command for it, so folks can click the command palette and see it available there. One question that I wondered while giving this another skim — is the only guard to tell if an image has already been optimized the filename? How else might we see which files are eligible... or to put the question slightly differently, how might we tell when it's beneficial to the user to run the optimization versus those times when it's of little benefit? This might be sort of the more admin UI idea (and therefore a rabbit hole)... but for image optimization I sort of crave a UI where we can see before / after and the user can drag a slider for quality, a bit like Photoshop export, etc. And possibly even see estimated file size changes and so on. Definitely post 7.1 sort of stuff that kind of complex UI idea. In any case, this comment is mostly me attempting to say I like the overall goal of this feature and I think there'll be lots of cool things to explore for it, so creating an experiment makes sense to me. |
…ze-existing-media # Conflicts: # packages/upload-media/CHANGELOG.md
I like the power user command although that is a bit hidden.
Two cases here:
For case 1, I'm comfortable having WordPress recommend and enable auto-backfilling of missing sizes. For case 2, I would tread much more cautiously. Maybe we can add the capability to do this in Gutenberg/Core, but implement it first in the Performance Lab plugin.
Yes, this would be super cool, I know squoosh has this as well. Again, maybe this could start in the Performance Lab plugin if we made sure the right APIs were available to support that.
🎉 Thanks for the feedback. I'll encapsulate as an experiment for now, maybe we will wind up with several media related features we can bundle in a media section, or possibly as a single experiment. |
Reviewers asked for the optimize-existing-media UI to be opt-in while the feature is refined. Register a new 'Optimize existing media' experiment on the Experiments screen, bridge it to the editor via window.__experimentalOptimizeExistingMedia, and only render the Optimize inspector panel when the experiment is enabled. The e2e test now enables the experiment for its scope and resets it afterward.
|
Done in 38f2ede: the Optimize panel is now gated behind a new "Optimize existing media" experiment (Settings → Experiments, Media group). The e2e test enables the experiment for its scope. Added the command palette idea to the follow-ups list. |
The trunk merge brought in the tsconfig build/dev split from #81514, which type checks this test file for the first time. registry.register now types cleanly, so the directive is unused and fails the type check with TS2578.
|
Hey 👋 I wanted to give you a heads-up since this pull request adds new files containing JSX. #80123 enables an ESLint rule that requires that files containing JSX must use the What you'll need to do: You'll need to rename any new files containing JSX to use the This comment is automated, based on pull requests with recent activity that contain affected |
…ze-existing-media
Trunk's react/jsx-filename-extension rule rejects JSX in .js files. Match the sibling editor hooks by using the .jsx extension and record the suppression alongside them.
New files containing JSX must use the .tsx extension per the coding guidelines, so drop the react/jsx-filename-extension suppression rather than carry it. Typing the file surfaced a bug: editEntityRecord takes ( kind, name, recordId, edits ), so the site-logo control was passing its edits as the record ID and never repointed the logo.
…ze-existing-media # Conflicts: # packages/upload-media/CHANGELOG.md # packages/upload-media/src/store/private-actions.ts # test/e2e/specs/editor/various/client-side-media-processing.spec.js
🤖 PR meta 🤖🎉 PropsIf you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
Updated as activity occurs, without notifying anyone named here. Add the 📦 Bundle sizeSize Change: +1.35 kB (+0.02%) Total Size: 8.69 MB 📦 View Changed
⚡ PerformanceShow the resultsClient side metrics exclude the server response time. front-end-block-theme
front-end-classic-theme
media-processing
media-upload
post-editor
site-editor
🏁 Flaky testsSome tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information. does not select blocks in the canvas preview when editing from the sidebar (Site Editor v2) in
|
Vitest runs with `globals: false`, so the test helpers have to be imported rather than picked up from the environment as they were under Jest. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RtZdDWdC33cNHfY4U238A5
`jest.Mock` was a namespace type; Vitest exports `Mock` as a regular type, so it has to be imported rather than reached through the `vi` object. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RtZdDWdC33cNHfY4U238A5
The conventions validator requires it, and it type checks the factory against the real module, so each one is cast the way the other upload-media tests do. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RtZdDWdC33cNHfY4U238A5
…rdPress/gutenberg into feature/79364-optimize-existing-media
…ze-existing-media # Conflicts: # packages/upload-media/CHANGELOG.md # packages/upload-media/src/store/actions.ts
Trunk upgraded wp-prettier, which changes the indentation of chained object arguments and the spacing inside type-only import() calls. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KhPEP5AwC5d1HyshWG5Bya
|
Hey 👋 I wanted to give you a heads-up since this pull request is affected by recent validation changes for changelog files. #83043 adds additional validation for changelog files. You'll note that this pull request is currently failing a "Required changes from trunk" check. What you'll need to do: You will need to either rebase or merge the latest code from |
The 15.0.0 release renamed the `## Unreleased` heading it was written under, stranding this PR's entry inside the published 14.51.0 section. The "Validate CHANGELOG structure" check requires an open PR's entry to sit under `## Unreleased`, so recreate a `New Features` subsection there and move the entry into it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XymJGmRuNKwf8srrtsrcLR
Bring the branch current with trunk. Two conflicts: the upload-media changelog, where trunk published 0.41.0 and this PR's entry stays under Unreleased, and the private-actions utils import, which keeps both this branch's fetchFile and trunk's getFileBasename. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GqepyjmFSryBt88j6f6ubY
Trunk removed them as unused (#85094); this branch's fetchFile and optimizeExistingItem still need them. Also adapt the optimize hook to trunk's typed block-editor entry point and @wordpress/ui Spinner.
|
I tried the flow and I'm not sure what's the value it brings to user when editing a document. The feature suits better in flows to manage the whole library or settings at the document level, but this image-level optimization is for power users that are aware of what the optimization does and how that impacts the site. |
Fair point @fcoveram - this is a bit of a power user feature, probably plugin territory. I'll see if we can add it to the Performance Lab plugin. For core, maybe something to consider for the media library rebuild. |
# Conflicts: # packages/editor/CHANGELOG.md # packages/upload-media/CHANGELOG.md # packages/upload-media/src/utils.ts

What?
Adds the ability to optimize previously uploaded media using the client-side (WASM/libvips) pipeline, gated behind a new "Optimize existing media" experiment. When the experiment is enabled, a new "Optimize" control appears in the inspector of image-bearing blocks; clicking it fetches the attachment's original file, re-compresses it in the browser, regenerates sub-sizes, uploads the result as a new attachment, and repoints the block at it.
Closes #79364
Why?
Client-side media currently optimizes media only at upload time. Sites that predate the feature (or media uploaded before it was enabled) get no benefit. This lets users re-process existing media (e.g. compress a legacy JPEG, regenerate sub-sizes) using the same in-browser pipeline, with graceful fallback when the browser can't process an item. This is one of the capabilities called out for the 7.1 cycle.
Per review feedback (swissspidy, andrewserong), the UI ships behind an experiment so the exposure (sidebar panel vs. command palette vs. admin/bulk UI) can continue to be refined with design input before it is on by default.
How?
Experiment gating:
gutenberg-optimize-existing-mediaexperiment registered in the Media group on the Experiments screen (lib/experimental/experiments/load.php).gutenberg_enable_experiments()bridges it to the editor aswindow.__experimentalOptimizeExistingMedia(lib/experimental/editor-settings.php).Store (
@wordpress/upload-media):optimizeExistingItem( { id, url, fileName, onSuccess, onError, additionalData } )that enqueues a queue item (withsourceUrl/sourceAttachmentIdand aStubFileplaceholder) whose operations are[ FetchRemoteFile, TranscodeImage(same format), Upload, ThumbnailGeneration, Finalize ].FetchRemoteFileoperation +fetchFile()utility to download the original by URL.TranscodeImageoperation for same-format re-compression (no duplicateCompressop), and the existing sideload/finalize chain to regenerate sub-sizes.FETCH_REMOTE_FILE_ERRORcode. Unsupported/unprocessable formats are skipped viaonError, leaving the original attachment untouched.UI (
@wordpress/editor):editor.BlockEditfilter adds an "Optimize" inspector panel tocore/image,core/cover,core/media-text,core/post-featured-image, andcore/site-logo. (Gallery items are themselvescore/imageblocks, so they're covered when selected.)isUploadingById).window.__experimentalOptimizeExistingMedia,window.__clientSideMediaProcessing, andisClientSideMediaSupported().The optimized result is uploaded as a new attachment and the block is repointed at it (matching the media-experiments prototype). This reuses the existing
mediaUpload/mediaSideload/mediaFinalizesettings, so no PHP/REST changes are required.Screencast
optimize.existing.mp4
Testing Instructions
Test with Playground: https://playground.wordpress.net/?gutenberg-pr=79509
-optimizedattachment that is no larger than the original.Automated
npm run test:unit packages/upload-media— store unit tests foroptimizeExistingItemandfetchRemoteFile.npm run test:e2e -- test/e2e/specs/editor/various/client-side-media-processing.spec.js— "optimizes a previously uploaded image into a new attachment" (enables the experiment for its scope).Out of scope (follow-ups)