Skip to content

Image Editor: Add applyImageEdit public function - #86665

Merged
ramonjd merged 23 commits into
trunkfrom
add/image-editor-apply-image-edit
Nov 24, 2026
Merged

ramonjd merged 23 commits into
trunkfrom
add/image-editor-apply-image-edit

Conversation

@ramonjd

@ramonjd ramonjd commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

What?

Part of:

Introduces applyImageEdit( state, edit ), the reverse of getImageEdit. The former is a setter, the latter a getter.

How

applyImageEdit turns an ImageEdit back into an editor state, that is, what the canvas shows (ImageEditorState):

applyImageEdit( state, { rotation: 90, crop: { x: 0, y: 0, width: 1, height: 0.5 } } );
// { state } or { rejected: 'no-image' | 'invalid' | 'locked-ratio' | 'outside-image' }

The intended use is to apply crop instructions to an image programmatically, with or without a crop canvas. See follow ups for what needs to happen to enable this.

Contrast with getImageEdit, which turns ImageEditorState into a state that describes the crop against the image (ImageEdit):

See for reference

A crop the image doesn't cover is fitted, as in the editor. { strict: true } rejects it instead. Invalid input is always rejected.

Why?

#86630 made ImageEdit the type for reading and writing, but nothing wrote one. This tests the shape before applyImageEdit is published. The type needed no change.

Testing Instructions

No UI calls it yet, but you can test in storybook

  1. Run npm run storybook:dev and open Editor/Image Editor/Canvas › Apply An Edit.
  2. Click Apply. The image turns a quarter turn and the crop keeps the left half.
  3. Enter { "rotation": 10 } and click Apply. The image tilts and zooms in, as with the rotate control.
  4. Turn on Lock the crop to a square and apply the first edit again. The crop becomes a square as wide as before. With Reject edits that need fitting on, it is rejected with locked-ratio.
  5. Crop and rotate by hand, click Copy the current edit, click Reset, then click Apply. The canvas returns to your edit.
Screenshot 2026-11-23 at 3 43 36 pm

@ramonjd ramonjd added [Type] New API New API to be used by plugin developers or package users. [Package] Image Editor Related to packages/image-editor labels Nov 11, 2026
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🤖 PR meta 🤖

Preview in WordPress Playground Preview in Storybook

🎉 Props

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: ramonjd <ramonopoly@git.wordpress.org>
Co-authored-by: andrewserong <andrewserong@git.wordpress.org>

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


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

Updated as activity occurs, without notifying anyone named here. Add the props-bot label to refresh.

📦 Bundle size

Size Change: -73 B (0%)

Total Size: 8.71 MB

📦 View Changed
Filename Size Change
build/scripts/editor/index.min.js 574 kB -73 B (-0.01%)

12370f1 Run

⚡ Performance

Show the results

Client side metrics exclude the server response time.

front-end-block-theme

Metric ae9c4a2 trunk % Change
timeToFirstByte 49.4 ms +4.86% -2.23% 49.35 ms +3.34% -1.32% 0.1%
largestContentfulPaint 84 ms +4.76% -9.52% 82 ms +7.32% -7.32% 2.44%
lcpMinusTtfb 31.45 ms +19.4% -12.72% 32.05 ms +22.31% -14.51% -1.87%
wpBeforeTemplate 24.7 ms +4.45% -2.35% 24.57 ms +3.5% -2.12% 0.53%
wpTemplate 20.79 ms +3.99% -4.28% 20.82 ms +4.51% -3.7% -0.14%
wpTotal 45.48 ms +5.15% -2.64% 45.49 ms +3.14% -1.63% -0.02%
wpMemoryUsage 7.75 MB +0% -0% 7.72 MB +0% -0% 0.45%
wpDbQueries 16 +0% -0% 16 +0% -0% 0%

front-end-classic-theme

Metric ae9c4a2 trunk % Change
timeToFirstByte 41.2 ms +5.22% -1.94% 41.25 ms +9.21% -3.15% -0.12%
largestContentfulPaint 76 ms +2.63% -0% 76 ms +2.63% -5.26% 0%
lcpMinusTtfb 35.2 ms +1.14% -2.84% 33.25 ms +4.51% -2.41% 5.86%
wpBeforeTemplate 21.44 ms +7.14% -1.35% 21.66 ms +8.77% -2.4% -1.02%
wpTemplate 16.17 ms +2.29% -5.94% 15.74 ms +6.29% -4.64% 2.73%
wpTotal 37.83 ms +5.6% -2.7% 37.74 ms +9.78% -2.68% 0.24%
wpMemoryUsage 6.44 MB +0% -0% 6.41 MB +0% -0% 0.56%
wpDbQueries 13 +0% -0% 13 +0% -0% 0%

media-processing

Metric ae9c4a2 trunk % Change
mediaProcessingJpeg 393.55 ms +0.7% -1.23% 391.73 ms +0.49% -0.76% 0.46%
mediaProcessingAvif 5755.09 ms +0.06% -0.16% 5705.44 ms +0.45% -0.1% 0.87%
mediaProcessingJpegToAvif 3929.94 ms +0.21% -0.15% 3894.72 ms +0.26% -0.36% 0.9%

media-upload

Metric ae9c4a2 trunk % Change
jpegUploadProcessing 1519.43 ms +33.23% -1.54% 1503.04 ms +0.34% -0.38% 1.09%
pngUploadProcessing 266.1 ms +1.39% -3.53% 257.56 ms +3.11% -1.52% 3.32%
largeJpegUploadProcessing 1499.1 ms +1.88% -0.26% 1489.54 ms +1.51% -0.68% 0.64%
multipleImageUploadProcessing 2086.26 ms +0.9% -20.19% 1662.61 ms +7.68% -0.23% 25.48%

post-editor

Metric ae9c4a2 trunk % Change
serverResponse 273.87 ms +1.28% -9.76% 264.14 ms +4.19% -10.98% 3.68%
firstPaint 271.71 ms +11.18% -5.54% 261.91 ms +10.23% -5.51% 3.74%
domContentLoaded 545.21 ms +2.64% -3.21% 532.65 ms +1.01% -2.45% 2.36%
loaded 546.03 ms +2.66% -3.22% 533.38 ms +1% -2.46% 2.37%
firstContentfulPaint 309.45 ms +6.26% -2.92% 314.34 ms +2.7% -8.32% -1.56%
firstBlock 1476.88 ms +7.32% -4.02% 1414.22 ms +1.84% -1.67% 4.43%
type 13.89 ms +6.48% -10.3% 13.31 ms +4.73% -2.33% 4.36%
typeWithoutInspector 12.73 ms +4.48% -5.42% 12.93 ms +5.41% -6.57% -1.55%
typeWithTopToolbar 17.14 ms +2.63% -4.38% 17.2 ms +7.62% -4.42% -0.35%
typeContainer 5.91 ms +3.89% -4.23% 6.34 ms +4.89% -3% -6.78%
focus 69.15 ms +4.89% -3.64% 78.1 ms +4.23% -6.36% -11.46%
firstFocus 172.32 ms +0% -0% 188.15 ms +0% -0% -8.41%
selectAll 249.43 ms +15.46% -1.12% 257.75 ms +0.62% -2.55% -3.23%
undo 24.31 ms +2.55% -5.51% 21.92 ms +11.09% -4.38% 10.9%
listViewOpen 29.57 ms +21.2% -16.1% 26.37 ms +10.35% -3.15% 12.14%
inserterOpen 27.58 ms +2.1% -1.74% 32.39 ms +14.54% -8.46% -14.85%
inserterHover 9.1 ms +7.69% -9.12% 9.56 ms +6.69% -7.43% -4.81%
inserterSearch 6.87 ms +13.39% -10.92% 7.48 ms +6.28% -10.96% -8.16%
loadPatterns 430.62 ms +13.86% -1.17% 496.42 ms +5.87% -1.49% -13.25%
wpTotal 266.7 ms +0.93% -9.93% 257.43 ms +3.91% -11.34% 3.6%
wpMemoryUsage 14.81 MB +0% -0% 14.76 MB +0% -0% 0.33%
wpDbQueries 55 +0% -0% 55 +0% -0% 0%

site-editor

Metric ae9c4a2 trunk % Change
serverResponse 250.13 ms +5.02% -3.67% 264.87 ms +3.27% -7.42% -5.56%
firstPaint 293.55 ms +12.69% -9.89% 272.91 ms +17.67% -3.7% 7.56%
domContentLoaded 561.79 ms +1.64% -1.75% 559.6 ms +2.43% -1.18% 0.39%
loaded 562.53 ms +1.66% -1.74% 560.37 ms +2.43% -1.18% 0.39%
firstContentfulPaint 325.75 ms +1.55% -5.19% 321.65 ms +1.13% -1.24% 1.27%
firstBlock 1735.04 ms +6.55% -0.94% 1736.26 ms +2.43% -1.4% -0.07%
type 12.34 ms +8.27% -5.92% 14.91 ms +15.69% -5.23% -17.24%
navigate 87.38 ms +26.22% -3.16% 80.88 ms +2.15% -4.95% 8.04%
loadPatterns 894.85 ms +7.95% -6.76% 986.24 ms +13.48% -13.01% -9.27%
loadPages 926.55 ms +1.57% -3.05% 924.97 ms +0.7% -2.42% 0.17%
wpTotal 243.63 ms +5.19% -3.82% 258.27 ms +3.32% -7.58% -5.67%
wpMemoryUsage 12.84 MB +0% -0% 12.80 MB +0% -0% 0.28%
wpDbQueries 45 +0% -0% 45 +0% -0% 0%

12370f1 Run

🏁 Flaky tests

Some 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.

As a user I want to be able to add multiple close buttons so that users can close the overlay from different positions in /test/e2e/specs/site-editor/navigation-overlay-template-part.spec.js, passed after 1 failed attempt.
Error: expect(locator).toHaveCount(expected) failed

Locator:  getByRole('button', { name: 'Close' })
Expected: 2
Received: 1
Timeout:  5000ms

Call log:
  - Expect "toHaveCount" getByRole('button', { name: 'Close' }) with timeout 5000ms
  - waiting for getByRole('button', { name: 'Close' })
    14 × locator resolved to 1 element
       - unexpected value "1"

    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/navigation-overlay-template-part.spec.js:228:33

12370f1 Run

@andrewserong andrewserong left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I really like the ideas here! Conceptually, allowing a simple applyImageEdit function to pass along instructions to the image editor is a great idea. And I can imagine this being combined with tools or abilities (as you mention) eventually so that we can have clever programmatic or AI-enabled interactions.

One wrinkle, though, is that when interacting with the image editor via the UI, we naturally contain things to do a best effort to perform an action on behalf of a user. Or to put it more plainly, we allow fine-grained rotation and then contain / zoom in accordingly to make sure everything still fits. Whereas here, if I give it a bare fine-grained rotation like 5, I get an error:

image

Should this function (applyImageEdit) bake in the containment logic so that the consumer is effectively driving the image editor UI, rather than needing to be responsible for containment on its own?

Another option, we could have applyImageEdit default to including the containment, and have a third optional options param that allows a consumer to switch that off, enable a strict mode, or perhaps eventually, even allow crops that go outside the image editor in order to bake in a background color of some kind? The latter wouldn't be for this PR — just brainstorming some ideas for how this function could work over time.

For now, I think the main thing we'd want to add is the automatic containment so that consumers don't need to worry about it.


// What each rejection means, from the `ImageEditRejection` docs.
const REJECTIONS: Record<
Extract< ApplyImageEditResult, { rejected: unknown } >[ 'rejected' ],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Rather than having to extract here, would it be worth exporting ImageEditRejection to make it easier for consumers to work with?

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.

Yes, I can see how that type would be handy. Good call.

@ramonjd

ramonjd commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Or to put it more plainly, we allow fine-grained rotation and then contain / zoom in accordingly to make sure everything still fits. Whereas here, if I give it a bare fine-grained rotation like 5, I get an error:

Should this function (applyImageEdit) bake in the containment logic so that the consumer is effectively driving the image editor UI, rather than needing to be responsible for containment on its own?

Thanks for bringing this up.

It was something I did think about, and I think in general it would be nice to be able to fit the crop to the bounding area by default. In other words, it should do exactly what the rotate control does.

Here's where my brain was going for the record: I was imagining an agent-feedback loop, or someone trying to restore a previously described edit, where we wouldn't want to change a crop silently.

That said, I agree with the idea that anyone using this API should be able to decide whether they want this at all, like you said, it might be a layered image on top of some background.

This relates indirectly to circle cropping too, where there's no choice but to have transparent corners.

So, here's what I think we can do:

  • this PR: fit edit by default like the canvas does, export ImageEditRejection, add an options prop to enable "strict" mode (rejects crops)
  • next PR: add an editor setting for transparent edges (outside bounding box), so the reducer stops fitting the crop, the canvas shows the empty area, and exportImage leaves it transparent, letting applyImageEdit apply any crop exactly.

Does that make sense?

@andrewserong

Copy link
Copy Markdown
Contributor

Does that make sense?

Sure does! I think your "this PR" notes will cover the majority use case (essentially use an AI tool to replicate the behaviour of using the existing UI tools).

next PR: add an editor setting for transparent edges

For this, my weakly held opinion is that it's kind of a nice-to-have. I.e. this could be part of either the circle-crop thingie as you mention, but it also sort of forms part of being able to adjust the size of the canvas, which sounds like a new feature to me rather than just about API changes. I think the point I'm trying to make here is that this sounds like "feature" territory rather than "build out the image-editor package's API so plugins or agents can use the existing cropper".

Not at all a bad idea to pursue that, I mostly mention it as it can be easy to get into a "one more thing" situation with APIs and so from my perspective I'd say that the "this PR" scope is already good.


All that said, one of the things I'm interested in with all this is seeing how the image cropper might look and feel once it's hooked up to client-side abilities or possibly WebMCP. It'd be interesting to see, for example, in the block editor, can we go from an uploaded 4:3 image of a landscape with a horizon that isn't level and pass a prompt in a browser's chat window (e.g. Gemini in Chrome), and have it:

  • Discover tools for image editing in the current page
  • Apply the right tools to perform the fine-grained rotation
  • And the desired crop

E.g. the prompt might be "level out the horizon on this image and crop it to 16:9", and based on the tools exposed, it can fire off the (hopefully simple) tools to do just that.

When it comes to containment, the main question on my mind in the above agent loop is whether it makes it easier or harder to complete the task if containment is applied by default. My hunch is that it'll be easier with containment happening automatically, in the same way that it's easier for a human user to not have to perform a manual crop when fine-grain rotating something.

In any case, this is all a very long way of saying a big +1 to the idea of making sure the API plays nicely with agents! Ideally we're building a cropper that works great for humans and programatic applications.

Once this PR is in, it might be fun to try out a proof of concept demo with WebMCP or the like to get a feel for the overall shape of it, test out what we will or won't need?

(Also a necessary caveat with all the above — I have no idea what I'm talking about when it comes to WebMCP other than having watched a 30 minute demo covering what it can do, so please take my opinions here with a grain of salt 😄)

@ramonjd

ramonjd commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Great feedback and ideas, thanks @andrewserong

seeing how the image cropper might look and feel once it's hooked up to client-side abilities or possibly WebMCP.
...
Once this PR is in, it might be fun to try out a proof of concept demo with WebMCP or the like to get a feel for the overall shape of it, test out what we will or won't need?

That sounds like a great, and probably necessary, stepping stone. Like you say, we'll probably turn up things we didn't anticipate, e.g., agents trying to perform other operations that the core library doesn't offer (scale comes to mind) who knows?!

I'll chalk that up as the next phase to look into before taking it furhter.

sounds like "feature" territory rather than "build out the image-editor package's API so plugins or agents can use the existing cropper".
...
When it comes to containment, the main question on my mind in the above agent loop is whether it makes it easier or harder to complete the task if containment is applied by default. My hunch is that it'll be easier with containment happening automatically

Yes, well put. Specifically with the canvas on the page, I think it'll be a good bridge between agent and what the user is seeing on the page.

Agree on the nice-to-have point, and it's not something we should rush into now.

My intention was to really provide an entry point to the underlying crop operations for any canvas or crop operation, so a consumer (or agent) can decide that they don't care about filling the canvas.

I'm imagining it being part of a tool chain, e.g., so a consumer might crop an image as part of a wider design imperative like "rotate the image, make it fix within the boundary (no zoom) and paint the transparent pixels green".

We don't need this now, and I like your call of testing applyImageEdit first in the wild with some bots.

@ramonjd

ramonjd commented Nov 23, 2026 •

Copy link
Copy Markdown
Member Author

I set up a local testing env in node using @modelcontextprotocol/server to get a feel about how an agent would interact with this functions.

Here's the report:

Agent test of applyImageEdit (plain prompts)

Setup. Same harness as the precise set, with one change: the server behaves as if one 1600 by 900 photo is already open, so the agent gets the size from the state rather than from the person, as it would in the modal. The prompts are a sentence each, no numbers, no sizes, no API words. Eight prompts, Sonnet and Opus, 16 runs, about $0.60.

Results

# Prompt Sonnet Opus What happened
11 "Straighten it a bit, the horizon's off." Asked Asked Both said they cannot see the photo and asked which way and how far. Opus offered to start at 2° if the person prefers.
12 "Crop out the sky." Asked Asked Both asked where the horizon is, and offered to accept a fraction or a pixel row.
13 "Zoom in on the left side." Done, left half Done, left half at middle height Two readings of "zoom in". Sonnet cropped the left half at full height. Opus kept 16:9 and took 800×450 from the left. Both said they guessed. Sonnet's first call was the top-left quarter by mistake. It caught the slip from its own arguments, before any read-back, and redid it.
14 "Make it portrait for Instagram." Done, 4:5 Done, 4:5 Both locked the ratio to 0.8 and took the editor's default crop, 720×900, centered. Both said the subject may be off-center. Opus noted Instagram's 1080×1350 and the upscale.
15 "Make it square." Done, 900×900 Done, 900×900 Both locked the ratio to 1. Sonnet took the default crop. Opus also applied the crop in strict mode. Opus then pasted the full raw state JSON to the person, including basePan, baseZoom and baseRotation.
16 "Rotate it, it's sideways." Done, 90° Done, 90° Both guessed clockwise, said so, and offered 270° if it comes out upside down.
17 "Take a bit off the edges." Done, 5% each side Done, 5% each side Same default from both. Sonnet did not read the size back and said so. Opus did and got 1439.9999999999998 by 809.9999999999999.
18 "Crop it to the top half. Actually no, undo that." Nothing applied Nothing applied Both read the retraction and did not apply the crop. No tool was needed.

What this set showed

Observation Runs Shared by both models
Vision-dependent asks ended in a question to the person, not a guess 4 of 4 (11, 12) Yes
Vague asks got a stated default: 5% off edges, 4:5 for Instagram, left half, 90° clockwise, and an offer to adjust 10 of 10 (13 to 17) Yes
Used the ratio lock, not a computed crop, to get "square" or "portrait" 4 of 4 (14, 15) Yes
Said the tools "only build a state" and asked how to apply it to the open photo 7 of 16 Yes
Noted that a fresh state loses edits already made in the editor 1 of 16 Opus
Pasted the raw state JSON, with internal fields, to the person 1 of 16 Opus
Float noise in a read-back, now also for a plain axis-aligned crop 3 of 16 Yes
Wrong final edit 0 of 16

Follow-ups

None changes #86665. Items 1 and 3 repeat the precise set, now with more evidence.

  1. Snap float noise at the read-back boundary. getOutputSize returned 1439.9999999999998 for a 5% crop with no rotation. Round values within a small tolerance of a whole number or of zero in getImageEdit and getOutputSize. Small, separate PR.
  2. The entry point needs three calls, not one. Describe the current edit, so the agent starts from what the person already did rather than from a fresh state. Apply an edit and commit it as one undo step, which is the "apply to the open photo" the agents kept asking for. And set or clear the ratio lock, because both models reached for the lock to make a square or a portrait, and ImageEdit has no ratio in it.
  3. Keep the state opaque to the agent, and stop the base fields escaping the public state. One run pasted basePan, baseZoom and baseRotation to the person. The entry point should return edits, never states. The leak of undeclared fields predates this PR and wants its own decision.
  4. Design for the agent not seeing the picture. Half the plain prompts could not be done without the person's answer or a look at the canvas. The loop that works is: apply a stated guess, the person looks, the person says "a bit more" or "the other way", one undo step takes the guess back. The entry point should make that loop cheap: apply returns the edit as it now stands, undo is one step, and the defaults the agent chose are stated in words.
  5. Not needed: a fitted flag, an undo in the package API, a pixel-to-fraction helper. Both models converted pixels and fractions without trouble in both sets.
Previous run

Agent test summary

Setup. A scratch MCP server wraps the built package with four tools: createImageEditorState, applyImageEdit, getImageEdit, getOutputSize. Tool descriptions are the README text and nothing else. Each scenario ran as a fresh claude -p with only those tools. Eight scenarios, Sonnet and Opus, 16 runs The photo is 1600 by 900. "Correct" means the final edit and the reported region or size match the task.

Results

# Scenario Sonnet Opus What happened
1 Largest centered square Correct Correct Both locked the ratio to 1. Sonnet never called applyImageEdit: it read back the editor's default square and reported it. Opus applied { x: 0.21875, width: 0.5625 } in strict mode.
2 Left half, then a quarter turn Correct Correct Both re-expressed the crop in the turned frame as the top half. Sonnet did it in one call. Opus did two, both strict.
3 800×600 at pixel 100, 50 Correct Correct Both divided by the image size, applied strict, and confirmed 800×600 by reading the size back.
4 Half width starting at 80 percent Correct Correct Both tried strict first and got outside-image. Sonnet stopped and offered options. Opus re-applied in default mode, read back x: 0.5, and reported the slide.
5 800×400 region under a square lock Correct Correct Both got locked-ratio in strict mode, re-applied in default mode, read back 800×800 at y 50 to 850, and said it is not what was asked.
6 Straighten by 5 degrees Correct Correct Both read back the inscribed crop and the size 1389.9 by 781.8, and explained what is lost.
7 Mirror, then a quarter turn Correct Correct Read-back matched. Both noticed the state object holds rotation: 270 and explained it as the flip's sign rule.
8 Crop, rotate, undo the rotation Correct Correct Sonnet re-applied the crop without a rotation. Opus kept the earlier state and returned to it. Sonnet remapped the crop to the turned frame correctly this time, so the first run's error did not recur.

Patterns across both runs (32 transcripts)

Observation Runs Shared by both models
Chose strict: true without being told to, then fell back to default mode to show the fit 24 of 28 crop calls Yes
Spent a paragraph on float noise in read-back values such as -6.8e-8, 2.3e-9 and 900.0000000000001 28 of 32 Yes
Reconciled internal fields in the state JSON (rotation: 270, baseRotation, cropRect.y) with the read-back edit 6 of 32 Yes
Reused crop numbers across a rotation, framing the wrong region 1 of 32, first run only No, Sonnet once
Misread the crop frame, the replace rule, or a rejection reason 0 of 32

Follow-ups

In priority order. None changes #86665.

  1. Snap float noise at the read-back boundary. In getImageEdit and getOutputSize, round a value within a small tolerance of zero or of a whole number to that number. Every agent handled the noise, and every agent explained it to the person. Small, separate PR.
  2. Keep the state opaque to an agent. The entry point for the media editor modal should hand back an id or a token, never the state object. Six runs went off reconciling rotation: 270 with 90. A design rule for the follow-up PR, not a package change.
  3. Stop internal base fields leaking from the public state. The object the package returns carries basePan, baseZoom and baseRotation, which ImageEditorState does not declare. Anyone serialising a state gets them. Predates this PR. Decide whether to strip them at the public boundary or declare them.
  4. Say in the README when to use strict. (Added in aa6df6d) Both models reached for it unprompted in nearly every crop and used the rejection to decide what to do next. One sentence: code that needs the crop taken as given should pass strict and handle the rejection.
  5. No fitted flag. The runs argue against one. The pattern agents invented, strict first and fit on purpose, already tells them when fitting happened.
  6. No undo in the package API. Both approaches worked with states as values. Undo belongs to the modal's entry point, as planned.

@andrewserong

Copy link
Copy Markdown
Contributor

Oh, interesting! Thanks for giving that a try. One of the reasons I think WebMCP will be interesting to try is that I think the web versions can see what's happening in the browser, so they might have an easier time working with the tools? So we'll likely wind up with two agent-based use cases: headless (where it can't see what's happening) and those that can 🤔

@ramonjd

ramonjd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

One of the reasons I think WebMCP will be interesting to try is that I think the web versions can see what's happening in the browser

I'm not 100% sure we'd get "sight" out the box, if you mean an image/screenshot of the canvas reaching the model. WebMCP will offer whatever tools to the agent we register with it. An agent could take screenshots of the page for itself I guess too.

So after this PR the package exposes pure functions (not a state ): you pass a state in, you get an edit or a new state out.

What I do have planned is access to the canvas state, which is kinda the same I think. Right now only the consumer has access to its own session state, so we'll need to work out an entry point for that.

I think we can register MCP from within the consumer's state provider, e.g, in useMediaEditor

	const context = navigator.modelContext;

	context.registerTool( {
		name: 'get_image_edit',
		description: 'The current flip, rotation and crop of the open image, and its output size.',
		inputSchema: { type: 'object', properties: {} },
		execute: () => ( {
			edit: session.getImageEdit(),
			size: getOutputSize( session.imageEditor.state ), // we have access to the current session's state here, so we feed it to the tool call
		} ),
	} );

   // Agent calls: get_image_edit
  // Agent gets: { edit: { rotation: 5, crop: { x: 0.084, y: 0.123, width: 0.831, height: 0.755 } }, size: { width: 1390, height: 782 } }

So the next step is to try that. I'm not sure anything needs to change in this PR for the next steps to take place, but I can definitely try to set it up locally to see.

It looks like I can "simulate" a test locally without setting all this up using storybook. There's the "Apply an Edit " story so the agent looks at the canvas, types JSON into the box, clicks Apply, looks again. I did that in the mean time. Posting below for the record. No need to read all the slops!

Agent test of `applyImageEdit` with sight

Setup. The same eight plain prompts, run against the Storybook story "Apply an Edit" in a headless Chrome through a Playwright MCP server. The agent can screenshot the page, type into the "Edit to apply" box and click Apply, and read the edit the editor holds from the text under the canvas. The prompt tells it to use the box and not the canvas handles, because a first run showed Sonnet zooming and panning with the keyboard instead. The story's sample picture is not a landscape photo: it is a 1000 by 1464 upright scan of an 1887 print, a grid of labelled illustrations. That turned out to matter. Sonnet and Opus, 16 runs.

Results

# Prompt Sonnet Opus What happened
11 "Straighten it a bit, the horizon's off." Declined Declined Both looked, said the picture is a flat print with no horizon and already level, and asked for the angle and direction if a tilt was meant anyway.
12 "Crop out the sky." Declined Declined Both said there is no sky in this image. Opus noted a crop is one rectangle and could not remove the scattered bits of sky inside tiles.
13 "Zoom in on the left side." Done, left half Done, left half Both applied { crop: { x: 0, y: 0, width: 0.5, height: 1 } }, confirmed "Applied." and the read-back, and offered a tighter crop.
14 "Make it portrait for Instagram." Done, about 4:5 Done, 4:5 Opus read the real size from the DOM and computed height: 0.8538 for 1000×1250, then said what is lost: the title row. Sonnet estimated from the on-screen size and got height: 0.85, close but not exact, and said it had not measured.
15 "Make it square." Done, 1000×1000 Done, 1000×1000 Both read the size, kept the full width, and centred height: 0.6831. Opus listed which rows of the grid survive.
16 "Rotate it, it's sideways." Done, then flagged Declined Opus looked, saw upright text, and did not rotate. Sonnet applied 90°, looked again, said the picture is now sideways and was not before, and offered to reset.
17 "Take a bit off the edges." Done, 5% each side Done, 5% each side Same default as the blind set. Both said it removes the printed border.
18 "Crop it to the top half. Actually no, undo that." Applied, then applied {} Nothing applied Sonnet did both steps and used the replace rule to undo: an empty edit is the clean state. Opus read the retraction and did nothing.

What sight changed

Observation Blind set With sight
Vision-dependent asks (11, 12, 16) Asked the person which way or where Looked, found the request did not fit the picture, declined and said why
Image size Read from the state Read from the DOM with evaluate, used for exact square and 4:5 crops
Vague asks (13, 17) Same stated defaults Same stated defaults, plus a description of what the crop removes
Undo Re-applied the earlier edit, or kept the earlier state Applied {}, since the edit replaces the current one
Wrong final edit 0 of 16 0 of 16

Two things about the harness, not the API:

  • Left to itself, Sonnet drove the canvas with the keyboard rather than the JSON box. With a UI in front of it, an agent uses the UI. The entry point's tools will have to be more attractive than the handles, or the only route.
  • The story prefills the box with a sample edit, rotate 90 and keep the left half. Every Opus run spent words on it, and two warned the person not to click Apply by accident. For an agent-facing story, start the box empty.

Follow-ups

Nothing new for the package. The list from the two earlier sets stands, with one change of emphasis.

  1. Media editor entry point first. Describe the current edit, apply an edit as one undo step, undo. The agents' behaviour with sight is exactly the loop that entry point serves: look, apply a stated guess, look again, correct or undo. Sonnet's run 16 is that loop by hand.
  2. Give the agent sight in the entry point's design. With it, both models refused edits that made no sense for the picture and explained themselves. Without it, they asked. Either is acceptable, but sight produced the better answers. A screenshot from the browser agent is enough; the package needs nothing.
  3. Snap float noise in getImageEdit and getOutputSize. Unchanged from before. Small, separate PR.
  4. Keep the state opaque to the agent, and decide about the base fields. Unchanged from before.
  5. Say in the README when to use strict. Done in aa6df6dd0fb.
  6. For the Storybook copy of the entry point: start the edit box empty, and expose the tools so the agent does not need the box at all.

@ramonjd

ramonjd commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

An agent could take screenshots of the page for itself I guess to

Hmm, just thinking further on this. We could also expose ways to get the image (original for benchmark) and its cropped preview (for checking what has been done). Lots of ideas to test here!

@ramonjd

ramonjd commented Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

WebMCP results (not perfect env, and just more data dump. feel free to ignore) 😄

Example

Agent test of applyImageEdit over WebMCP

Can it be set up locally? Yes. Chrome 158 stable on this machine has the flag "WebMCP for testing" (chrome://flags/#enable-webmcp-testing), and a Playwright-launched Chrome gets the same with --enable-features=WebMCP. The API is document.modelContext, not navigator.modelContext, and it is not exposed on about:blank, only on real pages. No Canary, origin trial or extension was needed.

Setup. An untracked scratch story registers three tools on the page from the live editor state: get_image_edit, apply_image_edit (with strict) and reset_image. A claude -p agent with Playwright MCP opens the story in a Chrome launched with the flag, discovers the tools with document.modelContext.getTools(), and calls them with document.modelContext.executeTool( tool, input ). It is told not to touch the canvas or any control. Same eight plain prompts, Sonnet and Opus, 16 runs, about $1.10, cheaper than the clicking set because there is no typing.

Results

# Prompt Sonnet Opus What happened
11 "Straighten it a bit, the horizon's off." Declined Declined Both loaded the image pixels in the page and measured the grid lines: tilt under 0.1°. Both said rotating would only crop and soften, and asked for an angle if one was meant.
12 "Crop out the sky." Declined Declined No sky in the print. Opus offered alternatives: trim the title strip, or zoom in on one cell.
13 "Zoom in on the left side." Done, left half Done, left half apply_image_edit with { crop: { x: 0, y: 0, width: 0.5, height: 1 } }, Opus in strict mode. Both reported 500×1464.
14 "Make it portrait for Instagram." Done, 4:5 Done, 4:5 Both read the size from get_image_edit and computed height: 1250/1464, centered. Opus said what is lost: the title strip.
15 "Make it square." Done, 1000×1000 Done, 1000×1000 Both computed height: 1000/1464, centered. Sonnet used strict and said the editor took it as given. Opus listed the rows lost top and bottom.
16 "Rotate it, it's sideways." Declined Declined Both looked, saw upright text, and asked which way.
17 "Take a bit off the edges." Done, 5% Done, 5% Both strict. Both read the current edit first "to preserve any existing parts", then applied.
18 "Crop it to the top half. Actually no, undo that." Applied, then reset_image Nothing applied Sonnet did both steps and confirmed with get_image_edit. Opus read the retraction.

Compared with the two earlier sets

Blind MCP Clicking the story WebMCP tools
Wrong final edit 0 of 16 0 of 16 0 of 16
Vision-dependent asks Asked the person Looked, declined Looked, declined; two runs measured tilt from pixels
Used the API rather than the UI Only option Had to be told Had to be told; all 16 complied
Cost per 16 runs about $1.10 about $2 about $1.10
Read the edit back after applying Most runs Most runs Every run that applied, via the tool's own return value

What WebMCP itself taught us

These are about the platform, and they are the things the entry point PR has to get right.

  1. Register once per page. React's development mode runs effects twice. The second registerTool threw "Duplicate tool name", because unregistering through the AbortSignal is asynchronous. The scratch story registers once at module level and reads the live state through a target the component updates on each render. The media editor modal will need the same care, or a guard on getTools() before registering.
  2. Registration is late for a client that looks straight away. In about half the runs, getTools() returned an empty list on the first call because the story had not mounted yet. The agents retried after two seconds. A real client should listen to ontoolchange. The entry point should register as early as the session exists.
  3. executeTool takes the tool object, not its name. executeTool( 'apply_image_edit', … ) throws "parameter 1 is not of type 'Tool'". Every client has to call getTools() first.
  4. Results come back as a string. The tool returned { content: [ { type: 'text', text } ] }, and executeTool handed the agent that object JSON-encoded. Agents parsed it without trouble. Whether to return a plain object instead is a choice for the entry point.
  5. No real WebMCP client is on this machine. Claude in Chrome does not discover WebMCP tools, per the open issues on the Claude Code repository. Google's example extension at GoogleChromeLabs/webmcp-extension is a true client with a model behind it, and needs Chrome 155 or newer, the flag, and a model server with an API key. This test used Playwright evaluate as the client, which exercises the page side fully and the discovery path, but not out-of-band discovery by a browser agent.

Follow-ups, updated

The list stands. WebMCP changes two items.

  1. Media editor entry point: getImageEdit, applyImageEdit as one undo step, undo. Unchanged, still first.
  2. Expose the entry point as WebMCP tools in the modal. Now known to be testable locally with the flag. Register once, early, through an AbortSignal; return the edit, not the state; put the README text in the descriptions. The scratch story is a working draft of this.
  3. Storybook copy for the agent test. Promote the scratch story, minus the hacks, once the entry point's shape is settled, so the test runs without a WordPress site.
  4. Snap float noise in getImageEdit and getOutputSize. Unchanged. The read-back still shows -4.7e-8 and 500.00000000000006.
  5. Keep the state opaque, and decide about the base fields. Unchanged, and now demonstrated: with the tools returning edits, no run saw an internal field.
  6. Try Google's example extension as a second client when the entry point exists, to test out-of-band discovery. Needs an API key in a local model server.

.

@andrewserong

Copy link
Copy Markdown
Contributor

WebMCP results (not perfect env, and just more data dump. feel free to ignore) 😄

Funnily enough there's some promising stuff in there, that the agents actively rejected the instruction because it really was looking at the image. E.g. for the declined on "Rotate it, it's sideways":

Both looked, saw upright text, and asked which way.

So yeah, sounds like there'll be some fun stuff to play with in follow-ups!

I think we can register MCP from within the consumer's state provider

Might also be worth checking out how the WebMCP experiment has been implemented in the AI plugin: WordPress/ai#1081. That said, I couldn't quite tell from that PR why it wasn't using registerAbility from the wordpress/abilities package to register the abilities as an intermediate step 🤔. I imagine all that's continuing to be shaped, but for our purposes, it'll be interesting to see where image editor tools can slot in, in amongst all the other WP and block editor tools/abilities 🤔

In any case, thanks for the discussion here! I'll leave it there and get back to giving this a code review 😄

@andrewserong andrewserong left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for all the updates here, this is looking so good!

image

Just left a few comments, nothing blocking, especially my nit-picky feedback on the docs. Wording for this stuff can be hard, and we can tweak in follow-ups if need be!

Overall I really like the shape of the function, the default containment behaviour, it's nice having the strict option, and the story works really well for playing around with it.

LGTM! 🚀

Comment thread packages/image-editor/README.md Resolved
Comment thread packages/image-editor/README.md Resolved
`getImageEdit` reads the edit out of a state. Nothing could take one back
in, so nobody had checked that the shape works for writing before the
package is first published.

`applyImageEdit( state, edit )` builds the state through the reducer's
reset, then reads the result back with `getImageEdit`. If the two differ,
the editor could not hold the edit and it is rejected with a cause. The
edit is the whole edit: a part left out means none. The view is the one
the editor settles on after a resize, so the pan and zoom are replaced.

It is not exported yet. Three checks cover it:

- Every state the invariants test reaches hands its own edit back to a
  clean state and reads the same edit again.
- For two edits written by hand, the export camera picks the pixels the
  edit names.
- None of the 864 hand-built parity states applies as a different edit.
  Each comes back the same or is rejected.
Export `applyImageEdit` and its result type from the package root, next
to `getImageEdit`.

The public API test opens the canvas on a state built by
`applyImageEdit`: a quarter turn and the left half of the turned image.
The canvas keeps that edit, and the size tooltip shows 300 by 1200
pixels. If loading the image reset a state that already holds it, this
is the only test that fails.
Add a README entry and a recipe. The README says what a consumer cannot
guess from the type: a part left out means none, changing the flip or
rotation without the crop frames a different part of the image, the pan
and zoom are replaced, and what each rejection means.

The recipe applies an edit with no canvas and exports the result. Its
code was type-checked against the package exports.

The function's own comment said the crop's longer side fills the view.
On a view that is not square the side that fills it can be the shorter
one, so it now says the crop is zoomed in until it meets an edge of the
view or the zoom limit.
Keep only what the code and names do not already say.
…eEdit

The check that the new state holds the edit compared angles with a signed
remainder, so 720° and above came out as -180 and the edit was rejected as
outside-image. Reduce the difference to within one turn first.
…yImageEdit

Only a width or height of exactly 0 counted as no image. A missing, NaN or
negative size went on to the crop check and was rejected as outside-image,
which blames the crop for a problem with the image.
Any crop with a positive size was accepted, down to a fraction of a pixel.
Export rounds the crop to whole pixels, so one under half a pixel gives an
empty canvas and the export fails. Reject a crop under one source pixel wide
or high as invalid; any larger minimum is left to the caller.
The invariants round trip required every reachable edit to apply, but
applyImageEdit now rejects crops under one pixel, and setCropRect can
reach them. No seed lands on one yet. Expect invalid for those instead.
getImageEdit and getOutputSize only treated a size of exactly 0 as no
image, so a NaN, missing or negative size gave a NaN edit and size.
applyImageEdit already calls that no-image. Use its guard in both.
Type an ImageEdit as JSON and apply it to the canvas. The story shows why an edit was rejected, the edit the canvas now holds, and can copy that edit back into the box. A switch locks the crop to a square, to try a locked ratio.
The README and the ImageEditRejection comment explained invalid and outside-image only. Add no-image and locked-ratio, and show the explanation in the story next to the reason, so a tester does not have to look it up.
The story shows the image credit, whose text fails color-contrast, so
Storybook's accessibility check failed it. The other stories that show
the credit are marked todo for the same reason (#81596).
"A part missing from edit means none" read as if a missing part might be kept or might be required. Say that the edit replaces the current one, what each missing part resets to, and how to keep a part. List the rejection reasons, and add a short example.
A bare fine rotation such as { rotation: 5 } was rejected, because a
missing crop meant the whole tilted bounding box, empty corners and
all. A missing crop now gets the crop the rotate control picks.

A crop the image does not cover is fitted as the editor fits one: it
shrinks about its centre only as far as its shape needs, then moves
the shortest way inside. Under a locked ratio it keeps its centre and
width, as the crop setter does, so an 800 by 400 crop under a square
lock becomes 800 by 800 rather than 450 by 450.

Pass { strict: true } to reject an edit that needs fitting instead,
which is what applyImageEdit did before.
Export ApplyImageEditOptions and ImageEditRejection from the package
root, as ExportImageOptions is, so a consumer can name the rejection
reasons without extracting them from the result type.

The Apply an Edit story uses ImageEditRejection for its messages and
gains a switch for strict mode, so all four reasons can be tried.
JSON.parse accepts values that are not an edit. null threw when
applyImageEdit read it, and an array, a number or a string read as an
empty edit, which reset the canvas. Say what is wrong instead.
A missing crop is the editor's choice in both modes, so { rotation: 5 }
applies with strict too. The README and the option say so, and the
recipe says which rejections are left without strict.
…ested branches

Fill the empty @PARAM tags and say why strict skips the locked-ratio
pre-fit. Replace the test that only checked the lock survived, which
the missing-crop test already proves, with one that a conforming crop
under a lock is accepted as passed in strict mode. Cover both axes
flipped, a negative rotation and a non-finite crop number.
List the rejection reasons one per line, and say in plain sentences what
holdsEdit checks and what applyImageEdit keeps and resets. Spell center
the US way in the lines this PR adds.
…t docs

A string flip value is truthy, so "false" would flip the image. Reject
it as invalid, like a non-finite number. In the README, say in plain
words that every call describes the whole result, keep the strict
option with the fitting it changes, and list the four rejection
reasons together.
@ramonjd
ramonjd force-pushed the add/image-editor-apply-image-edit branch from de42150 to 12370f1 Compare November 24, 2026 08:37
@ramonjd
ramonjd enabled auto-merge (squash) November 24, 2026 08:37
@ramonjd ramonjd changed the title Image Editor: Add applyImageEdit Image Editor: Add applyImageEdit public function Nov 24, 2026
@ramonjd
ramonjd merged commit 61bfeb3 into trunk Nov 24, 2026
88 checks passed
@ramonjd
ramonjd deleted the add/image-editor-apply-image-edit branch November 24, 2026 08:57
@github-actions github-actions Bot added this to the Gutenberg 24.6 milestone Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Package] Image Editor Related to packages/image-editor [Type] New API New API to be used by plugin developers or package users.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants