Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Merge commit '0ddc9df91b6c0011ac90c525e18893d42e16d43b' into fix/canvas-v7-feedback
Josh Corbett22f2a125439b
diff --cc docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdxindex b04fd9be80,84d61ac098..b7cd08c581--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx@@@ -82,20 -78,19 +82,20 @@@ Right-click a layer, or select it and pThe icons at the top **Arrange** the layer (move it to the front, forward, backward or to the back), **Duplicate layer** and **Group layers**. Below them:* **For every layer:**- * **Rename layer** and **Fit to bbox** (scale the layer to fit inside the generation frame).+ * **Rename layer** and **Fit to frame** (scale the layer to fit inside the generation frame).- * **Merge down**.+ * **Merge down** — combines the layer with the one below. Each layer's adjustments are baked into the merged pixels; undo restores both layers with their adjustments.* **Copy to** — including **Copy layer to clipboard**, and copies to other layer types.- * **Crop layer to bbox** and **Save layer to board** (save it to the Gallery as an upload, in Uncategorized or a board you pick from its submenu).+ * **Crop layer to frame** and **Save layer to board** (save it to the Gallery as an upload, in Uncategorized or a board you pick from its submenu).* **Disable layer**, **Lock layer**, **Bookmark for quick switch** and **Color label**. A bookmarked layer is where **Q** switches on the canvas; press **Q** again to return. The bookmark is temporary and is not saved in the project. It can reset when the canvas is released, for example after switching away from its project, and resets on reload.+ * **Remove from group** — for a layer inside a group: moves it out, directly above the group. With several layers selected, it appears when they are all in the same group, and moves them together in their current order. The emptied group stays.* **Delete layer**.* **Raster layers:**- * **Transform**.+ * **Transform** (**Shift+T**) — shows the transform handles at once. It works on enabled raster and control layers with content.- * **Add adjustment** — Brightness/Contrast, Exposure, Levels, Curves, Saturation, Hue or Invert. Adjustments are non-destructive and appear as child rows.+ * **Add adjustment** — Brightness/Contrast, Exposure, Levels, Curves, Saturation, Hue, Invert, Texture, Clarity, Dehaze or Noise. Adjustments are non-destructive and appear as child rows. Texture, Clarity and Dehaze change detail and contrast; Noise adds film grain.- * **Add regenerate region** — treats the layer's own shape as an inpaint mask.+ * **Add regenerate region** — regenerates where the layer has content, as a live inpaint mask: everything on the layer marks the area to regenerate, and it follows the layer as you keep editing it. The menu shows this description under the item.* **Filter**, **Select object** and **Run workflow** — process the layer; see the [Canvas guide](/users-guide/canvas/canvas-guide/#filters-and-object-selection).* **Boolean operations** — combine the layer with the one below: intersect, cut out, cut away or exclude.- * **Convert to** — make it a control layer, inpaint mask or regional guidance layer. Text, shape and gradient layers can also be rasterized into plain pixels.+ * **Convert to** — make it a control layer, inpaint mask or regional guidance layer. Text, shape and gradient layers can also be rasterized into plain pixels. Control layers have no adjustments, so converting or copying a layer with adjustments to a control layer bakes them, with the layer's scaling and rotation, into its pixels; undo restores the raster layer with its adjustments.* **Control layers:** **Transform**, **Filter**, **Select object**, **Run workflow**, **Enable transparent preview**, and **Convert to raster layer**.* **Inpaint masks:** **Add noise**, **Add denoise limit**, **Extract masked area** (copy the masked part of the image to a new layer), and **Hide layer**.* **Regional guidance:** **Enable auto-negative**, **Add reference image**, and **Hide layer**.@@@ -123,10 -118,46 +123,48 @@@ The Layer section is dimmed while resul* **Lock transparency** — paint only where the layer already has pixels, leaving transparent areas transparent, like Photoshop's "Lock transparent pixels". Use it to recolor a shape without spilling paint around it, or to refine a subject painted on a transparent layer without growing its outline. Brushes, shapes and pen input all respect the lock.* **Filter** — start the Filter operation.+The Brush and Eraser paint directly on a selected image layer, such as an accepted result or an added picture, rather than adding a new layer. The first stroke turns it into a paint layer, with its position, scale and adjustments applied to its pixels; one undo restores the original image layer.+Adjustment child rows each have their own settings, such as **Brightness** and **Contrast**, **Exposure**, **Levels** and **Curves** with a channel selector, **Saturation**, and **Hue**. A regenerate region has a **Fill color** and **Fill style**.+ **Noise** adds film grain with these settings:++ * **Distribution** — **Gaussian** for natural, film-like grain, or **Uniform** for an even spread. Both have the same strength at the same amount; larger grain sizes look gaussian either way.+ * **Grain** — **Mono** changes brightness only; **Color** varies each color channel separately; **Chroma** varies only hue and colorfulness and leaves brightness alone, like the color speckle of a digital sensor.+ * **Tonal response** — **Midtones** (the default) gives full grain in the midtones and fades it to none in pure black and white, as film does; **Even** gives the same grain at every tone.+ * **Size** — how large each grain is, from 1 px (every pixel varies on its own, the default) to 8 px. Larger grain is softer and clumpier but keeps the same strength.+ * **Amount** — the grain's strength. 2–5% gives subtle grain, about 10% (the default) clearly visible grain, and high values very heavy noise.+ * **New pattern** (dice button) — picks a different random grain pattern.++ Things to know about Noise:++ * **The pattern stays put.** Each Noise adjustment keeps its grain pattern until you pick a new one, and reloading the project keeps it. Duplicating a Noise adjustment gives the copy a new pattern.+ * **The grain you see is the grain you get.** Generating, exporting, merging and saving to PSD all use the same pattern and strength. One exception: PSD has no group adjustments, so a group's Noise is baked onto each of its layers separately, and where semi-transparent layers in the group overlap, the PSD can look slightly different.+ * **Grain follows its layer.** It moves, scales and rotates with the layer; on a group, it stays fixed to the canvas instead. While you drag a selection, the dragged pixels keep their grain; once placed, they take the layer's grain at their new position.+ * **Baking.** Rasterizing a text, shape or gradient layer whose Noise adjustment is enabled bakes its whole adjustment stack into the pixels and removes it, so the grain stays where it was. **Merge down** bakes each layer's adjustments the same way.+ * **Older versions of Invoke.** Once a project has had a Noise adjustment, it needs a version of Invoke with Noise adjustments, even after you remove the adjustment; older versions refuse to open it.++ **Texture**, **Clarity** and **Dehaze** work on detail and contrast across an area rather than pixel by pixel. They match the [Clarity, Texture and Contrast Dehaze workflow nodes](/users-guide/workflows/image-adjustments/):++ * **Texture** — fine detail, such as skin, fabric or foliage. Positive amounts bring it out; negative amounts smooth it.+ * **Clarity** — midtone contrast in larger shapes. Positive amounts add punch; negative amounts soften the image.+ * **Dehaze** — broad contrast and color intensity. Positive amounts increase both, which can lift a flat, washed-out image; negative amounts reduce both. It is an aesthetic approximation, not physical haze removal: it does not estimate real haze or recover lost detail, and strong settings can clip tones or colors.++ Their settings:++ * **Amount** — from −200 to 200. The default, 0, changes nothing. Double-click the field or press **Backspace** in it to reset it.+ * **Size** (Texture and Clarity only) — how large the detail is that the adjustment affects: 1 to 100 px for Texture (8 by default) and 4 to 1000 px for Clarity (40 by default). It is measured in the layer's own pixels, before the layer is scaled, so resizing a layer does not change which detail is affected. On a group, it is measured in canvas pixels.++ Things to know about Texture, Clarity and Dehaze:++ * **They are computed in the background.** Each one looks at the whole layer, so the canvas computes it in the background and stays responsive. Meanwhile, the canvas shows the previous result, or the layer without them after you paint on it. A small spinner appears on the layer's row when the work takes more than a moment.+ * **Size limit.** They cannot run on content larger than 4096 × 4096 px (16.8 megapixels, measured over the area the layer's visible content spans, in the layer's own pixels before any scaling; for a group, at document resolution). A warning icon then appears on the layer's or group's row, the canvas leaves them out, and anything that uses the layer's pixels with them — generating, exporting, merging, rasterizing, filtering, copying or converting to a control layer, saving to PSD, painting on an image layer — is refused with a message naming the layer or group. Disable or remove them, or crop the content. The same warning appears when there is not enough canvas memory or the computation fails; hover over it for what to do, or select the adjustment to read it in Properties.+ * **What you see is what you get.** Generating, exporting, merging, rasterizing and saving to PSD use the same result as the canvas, computing it first if the canvas is still working on it. One exception: PSD has no group adjustments, so a group's Texture, Clarity and Dehaze are applied to each of its layers separately, and the PSD can look different from the canvas.+ * **While you drag a selection**, the dragged pixels show without them; once placed, the layer is computed again with them.+ * **Thumbnails** of layers the canvas has not shown yet can leave them out.+ * **Baking.** Rasterizing a text, shape or gradient layer with one of them enabled bakes its whole adjustment stack into the pixels and removes it. **Merge down** bakes each layer's adjustments the same way.+ * **Older versions of Invoke.** Like Noise, once a project has had one of these adjustments, older versions of Invoke refuse to open it, even after you remove the adjustment.+### Control layer* **Adapter type** — ControlNet, T2I Adapter, Control LoRA, Z-Image ControlNet or Anima ControlNet-LLLite, depending on the model selected in the Generate panel.diff --cc invokeai/frontend/webv2/performance/browser-baseline.jsonindex bfcc0bd0e8,ac6d601e26..80cc316b19--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@@ -159,12 -159,12 +159,12 @@@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 305523,+ "largestAssetRawBytes": 317101,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 531800,- "scriptRawBytes": 540817,++ "scriptRawBytes": 548565,"scriptRequestCount": 9,- "totalRawBytes": 531800- "totalRawBytes": 540817++ "totalRawBytes": 548565},"domContentLoadedMedianMs": 100.40000009536743,"id": "editor-canvas",@@@ -197,12 -197,12 +197,12 @@@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 305523,+ "largestAssetRawBytes": 317101,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 531800,- "scriptRawBytes": 540817,++ "scriptRawBytes": 548565,"scriptRequestCount": 9,- "totalRawBytes": 531800- "totalRawBytes": 540817++ "totalRawBytes": 548565},"domContentLoadedMedianMs": 97.7000002861023,"id": "editor-canvas",diff --cc invokeai/frontend/webv2/public/locales/en.jsonindex 81c140b250,668e35f542..27a7f8dbe9--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@@ -4153,8 -4130,10 +4153,11 @@@"preview": "Preview","processFailed": "The filter could not run.","replace": "Replace",+ "resetSettings": "Reset settings","running": "Running filter…",+ "sourceAdjustmentError": "Clarity, Texture or Dehaze failed on this layer, so it was not filtered. Change a setting or disable them, then try again.",+ "sourceAdjustmentOverBudget": "Not enough canvas memory to apply this layer’s Clarity, Texture or Dehaze before filtering it. Delete layers you no longer need, then try again.",+ "sourceAdjustmentTooLarge": "Clarity, Texture and Dehaze can’t run on this layer: its content is larger than 16.8 megapixels (4096 × 4096 px). Disable or remove them, or crop the layer, then try again.","sourceOverBudget": "Not enough memory is free to read this layer for the filter.","statusCommitting": "Applying filter…","statusError": "Filter needs attention.",@@@ -4164,14 -4143,17 +4167,17 @@@},"selectObject": {"autoProcess": "Auto Process",- "bbox": "BBox",- "bboxActive": "Bounding box active",- "bboxInactive": "No bounding box",+ "bbox": "Box",+ "bboxActive": "Box prompt set",+ "bboxInactive": "No box prompt","errorDecode": "The object preview could not be decoded.","errorEmpty": "The layer has no visible content to select.",- "errorInvalid": "Add an object prompt, point, or bounding box before processing.",+ "errorInvalid": "Add an object prompt, point, or box before processing.","errorLocked": "Select Object cannot finish while canvas editing is locked.","errorNoOutput": "Select Object finished without producing an image.",+ "errorAdjustment": "Clarity, Texture or Dehaze failed on this layer, so it was not used as the source. Change a setting or disable them, then try again.",+ "errorAdjustmentOverBudget": "Not enough canvas memory to apply this layer’s Clarity, Texture or Dehaze to the source. Delete layers you no longer need, then try again.",+ "errorAdjustmentTooLarge": "Clarity, Texture and Dehaze can’t run on this layer: its content is larger than 16.8 megapixels (4096 × 4096 px). Disable or remove them, or crop the layer, then try again.","errorNotReady": "The layer source is not ready. Try again when it finishes loading.","errorOutputDimension": "The Select Object result dimensions do not match the layer source.","errorQueue": "Select Object processing failed on the backend.",diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 3e4d35fbcb,97cc9ec71d..af4af734cd--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@@ -12,10 -12,11 +12,11 @@@ import type { StrokeCommittedEvent } frimport type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { BooleanRasterResult } from './controllers/booleanMergeController';- import type { CopyLayerToRasterResult } from './controllers/copyLayerController';+ import type { CopyLayerResult } from './controllers/copyLayerController';-import type { CropLayerResult } from './controllers/cropLayerController';+import type { CropAllLayersResult, CropLayerResult } from './controllers/cropLayerController';import type { ExtractMaskedAreaResult } from './controllers/extractMaskedAreaController';+ import type { ConvertLayerToControlResult } from './controllers/layerMutationController';-import type { MergeDownResult, MergeVisibleResult } from './controllers/mergeLayerController';+import type { MergeDownResult, MergeInpaintMasksResult, MergeVisibleResult } from './controllers/mergeLayerController';import type { NewRasterLayerResult } from './controllers/newRasterLayerController';import type { RasterizeLayerResult } from './controllers/rasterizeLayerController';import type { PreparedDocumentEdit } from './document-model/documentCommands';@@@ -306,18 -288,13 +313,20 @@@ export interface CanvasHistoryCapabilitstepBy(offset: number): Promise<CanvasHistoryReplayStatus>;}+/**+ * Where an eyedropper sample is in its pick: `preview` on every sampled move while the pick is held, `commit` once on+ * release, `cancel` once when the pick ends without a release over the canvas (Escape, a tool change, an aborted+ * hold), carrying the last previewed color.+ */+export type ColorSamplePhase = 'preview' | 'commit' | 'cancel';+- /** Why the engine refused an edit the user started without a caller to report to (a stroke, a shape). */- export type CanvasEditRefusal = SubsetOf<- CanvasTransactionOutcome,- 'busy' | 'gesture-active' | 'not-ready' | 'over-budget'- >;+ /**+ * Why the engine refused an edit the user started without a caller to report to (a stroke, a shape). An+ * `AdjustmentRefusal` names a layer whose spatial adjustments cannot run, so its pixels cannot be baked for painting.+ */+ export type CanvasEditRefusal =+ | SubsetOf<CanvasTransactionOutcome, 'busy' | 'gesture-active' | 'not-ready' | 'over-budget'>+ | AdjustmentRefusal;export type LayerThumbnailRequestResult =| 'ready'@@@ -547,8 -525,8 +557,9 @@@ export type DuplicateLayersResult*/export type {BooleanRasterResult,- CopyLayerToRasterResult,+ ConvertLayerToControlResult,+ CopyLayerResult,+ CropAllLayersResult,CropLayerResult,ExtractMaskedAreaResult,MergeDownResult,@@@ -643,17 -605,22 +654,29 @@@ export interface CanvasEngineLayerCapabcommitRasterFilterResult(options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult>;/** `null` when there was nothing to commit: an empty creation or an unchanged edit. */commitTextEdit(content: string, styleChanges?: Partial<TextToolOptions>): StructuralCommitResult | null;- copyLayerToRaster(layerId: string): Promise<CopyLayerToRasterResult>;+ /**+ * Converts a raster image or paint layer to a control layer in place, baking its own adjustments (exactly, or+ * refused) and transform into paint pixels; undo restores the raster layer with its adjustments and pixels. An empty+ * layer converts as a plain clone of its source and transform. A layer whose stack changes nothing can use the+ * cheaper `commitLayerConversion`, which keeps its source and transform.+ */+ convertLayerToControl(label: string, expectedLiveLayer: CanvasLayerContract): Promise<ConvertLayerToControlResult>;+ /**+ * Adds a control-layer copy holding the layer's baked pixels, as `copyLayerToRaster` does for raster copies; an empty+ * raster layer's copy is a plain clone of its source and transform.+ */+ copyLayerToControl(layerId: string): Promise<CopyLayerResult>;+ copyLayerToRaster(layerId: string): Promise<CopyLayerResult>;+ /**+ * Crops every raster, control, regional and inpaint leaf to the frame as one undo step, hidden and disabled leaves+ * included; locked leaves are skipped and counted, and leaves outside the frame are emptied in place.+ */+ cropAllLayersToBbox(): Promise<CropAllLayersResult>;cropLayerToBbox(layerId: string): Promise<CropLayerResult>;duplicateLayers(layerIds: readonly string[]): Promise<DuplicateLayersResult>;+ /** Unions the masks' coverage into one new inpaint mask above the topmost source, removing the sources. */+ mergeInpaintMasks(layerIds: readonly string[]): Promise<MergeInpaintMasksResult>;- mergeLayerDown(upperLayerId: string): MergeDownResult;+ mergeLayerDown(upperLayerId: string): Promise<MergeDownResult>;mergeSelectedRasterLayers(layerIds: readonly string[]): Promise<MergeVisibleResult>;mergeVisibleRasterLayers(): Promise<MergeVisibleResult>;/** `dispatch-rejected` also covers a selection with nothing eligible to move. */diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.tsindex d97c207465,2ad09f6f55..f9c6684f9b--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts@@@ -1,13 -1,8 +1,14 @@@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';++import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';import type { Rect } from '@workbench/canvas-engine/types';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentIndex, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';import { CropLayerController } from './cropLayerController';@@@ -105,245 -100,3 +106,275 @@@ describe('CropLayerController', () =>expect(h.history.canUndo()).toBe(true);});});++const FRAME: Rect = { height: 20, width: 20, x: 0, y: 0 };++/** Each leaf's cache rect, which the fake export also reports as its baked pixels. */+const CACHE_RECTS: Record<string, Rect> = {+ control: { height: 10, width: 30, x: 5, y: 5 },+ inside: { height: 5, width: 5, x: 2, y: 2 },+ locked: { height: 50, width: 50, x: -10, y: -10 },+ lockedByGroup: { height: 50, width: 50, x: -10, y: -10 },+ lockedInside: { height: 5, width: 5, x: 2, y: 2 },+ mask: { height: 10, width: 10, x: 60, y: 60 },+ raster: { height: 50, width: 50, x: -10, y: -10 },+ region: { height: 10, width: 10, x: -5, y: 0 },+};++const bytes = (rect: Rect): number => rect.width * rect.height * 4;++/** A locked paint leaf whose persisted pixels cover its cache rect. */+const lockedPaint = (id: string, locked = true) =>+ layerContract(id, 'raster', {+ isLocked: locked,+ source: {+ bitmap: { height: CACHE_RECTS[id]!.height, imageName: `${id}.png`, width: CACHE_RECTS[id]!.width },+ offset: { x: CACHE_RECTS[id]!.x, y: CACHE_RECTS[id]!.y },+ type: 'paint',+ },+ } as Partial<CanvasLayerContract>);+- const createCropAllHarness = (options: { historyBytes?: number; onExport?: (layerId: string) => void } = {}) => {++const createCropAllHarness = (++ options: {++ historyBytes?: number;++ onExport?: (layerId: string) => void;++ refusal?: AdjustmentRefusal;++ } = {}++) => {+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: FRAME,+ height: 100,+ selectedLayerId: 'raster',+ stacks: stacksFrom([+ layerContract('inside'),+ layerContract('raster'),+ lockedPaint('locked'),+ lockedPaint('lockedInside'),+ groupContract('lockedGroup', [lockedPaint('lockedByGroup', false)], { isLocked: true }),+ layerContract('control', 'control', { isEnabled: false }),+ groupContract('regions', [layerContract('region', 'regional_guidance')]),+ layerContract('mask', 'inpaint_mask', { isHidden: true } as Partial<CanvasLayerContract>),+ ]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document, { historyBytes: options.historyBytes });+ for (const [id, rect] of Object.entries(CACHE_RECTS)) {+ h.layers.getOrCreateRect(id, rect);+ }+ const exported: string[] = [];+ const released: string[] = [];+ // Reserved raster bytes when each export is read; every export holds its own reservation until released.+ const reservedAtExport: number[] = [];+ const guard = { current: true };+ const discardPersisted = vi.fn();+ const controller = new CropLayerController({+ backend: h.backend,+ captureCache: (target, _document, admit = () => true) => {+ const entry = h.layers.get(target.id)!;+ if (!admit(entry.rect)) {+ return 'over-budget';+ }+ const pixels = h.backend.createSurface(entry.rect.width, entry.rect.height);+ pixels.ctx.drawImage(entry.surface.canvas, 0, 0);+ return { pixels, rect: { ...entry.rect } };+ },+ ctx: h.ctx,+ discardPersisted,+ exportBaked: (layerId) => {+ exported.push(layerId);+ options.onExport?.(layerId);++ if (options.refusal?.ownerId === layerId) {++ return Promise.resolve(options.refusal);++ }+ const entry = h.layers.get(layerId)!;+ const reservation = h.ctx.reserveRaster(bytes(entry.rect));+ reservedAtExport.push(h.reservedBytes());+ return Promise.resolve({+ guard: { layer: getDocumentLayer(h.document(), layerId) } as never,+ rect: { ...entry.rect },+ release: () => {+ reservation?.release();+ released.push(layerId);+ },+ status: 'ok' as const,+ surface: entry.surface,+ });+ },+ isGuardCurrent: () => guard.current,+ isSupportedSource: () => true,+ });+ return { ...h, controller, discardPersisted, exported, guard, original: h.document(), released, reservedAtExport };+};++describe('CropLayerController: crop all layers', () => {++ it.each(['too-large', 'over-budget', 'error'] as const)(++ 'refuses the whole crop on a %s adjustment, releasing earlier copies',++ async (reason) => {++ const refusal: AdjustmentRefusal = {++ ownerId: 'control',++ ownerName: 'Control',++ reason,++ status: 'adjustment-refused',++ };++ const h = createCropAllHarness({ refusal });++++ await expect(h.controller.cropAll()).resolves.toEqual(refusal);++ expect(h.exported).toEqual(['mask', 'region', 'control']);++ expect(h.released).toEqual(['mask', 'region']);++ expect(h.document()).toBe(h.original);++ expect(h.dispatched).toEqual([]);++ expect(h.history.canUndo()).toBe(false);++ expect(h.reservedBytes()).toBe(0);++ }++ );+++ it('crops every unlocked leaf that reaches past the frame in one entry, and replays it as one', async () => {+ const h = createCropAllHarness();++ await expect(h.controller.cropAll()).resolves.toEqual({ cropped: 4, skippedLocked: 2, status: 'cropped' });++ // Hidden, disabled and grouped leaves crop too; locked ones are never read, and only those reaching past the+ // frame count as skipped.+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster']);+ // Each export is released before the next is read, keeping only the cropped pixels: the peak is one export.+ const croppedRegion = bytes({ height: 10, width: 5, x: 0, y: 0 });+ const croppedControl = bytes({ height: 10, width: 15, x: 0, y: 0 });+ expect(h.reservedAtExport).toEqual([+ bytes(CACHE_RECTS.mask!),+ bytes(CACHE_RECTS.region!),+ croppedRegion + bytes(CACHE_RECTS.control!),+ croppedRegion + croppedControl + bytes(CACHE_RECTS.inside!),+ croppedRegion + croppedControl + bytes(CACHE_RECTS.raster!),+ ]);+ expect(h.released.sort()).toEqual(h.exported.sort());+ expect(h.dispatched.map((mutation) => mutation.type)).toEqual(['replaceCanvasLayers']);+ expect(h.history.entries().past).toEqual(['Crop all layers to frame']);+ // Before and after pixels of every cropped leaf, admitted once for the entry.+ const after =+ bytes(FRAME) + bytes({ height: 10, width: 15, x: 0, y: 0 }) + bytes({ height: 10, width: 5, x: 0, y: 0 });+ const before = ['raster', 'control', 'mask', 'region'].reduce((sum, id) => sum + bytes(CACHE_RECTS[id]!), 0);+ expect(h.history.byteSize()).toBe(before + after + HISTORY_ENTRY_OVERHEAD_BYTES);+ expect(h.reservedBytes()).toBe(0);++ const cropped = h.document();+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ expect(h.layers.get('control')?.rect).toEqual({ height: 10, width: 15, x: 5, y: 5 });+ expect(h.layers.get('region')?.rect).toEqual({ height: 10, width: 5, x: 0, y: 0 });+ // The mask outside the frame stays, emptied.+ expect(h.layers.get('mask')?.rect).toMatchObject({ height: 0, width: 0 });+ expect(getDocumentLayer(cropped, 'mask')).toMatchObject({ isHidden: true, mask: { bitmap: null } });+ expect(getDocumentLayer(cropped, 'control')).toMatchObject({+ isEnabled: false,+ source: { offset: { x: 5, y: 5 } },+ });+ for (const id of ['inside', 'locked', 'lockedInside', 'lockedByGroup']) {+ expect(getDocumentLayer(cropped, id)).toBe(getDocumentLayer(h.original, id));+ expect(h.layers.get(id)?.rect).toEqual(CACHE_RECTS[id]);+ }+ // Structure is untouched: same ids, parents and order.+ const structure = (document: CanvasDocumentContractV3) =>+ [...getDocumentIndex(document).byId.values()].map((entry) => [entry.node.id, entry.parentId, entry.siblingIndex]);+ expect(structure(cropped)).toEqual(structure(h.original));+ expect(h.discardPersisted.mock.calls.map(([id]) => id).sort()).toEqual(['control', 'mask', 'raster', 'region']);++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLeaves(h.document())).toEqual(getDocumentLeaves(h.original));+ for (const id of ['raster', 'control', 'mask', 'region']) {+ expect(h.layers.get(id)?.rect).toEqual(CACHE_RECTS[id]);+ }++ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLeaves(h.document())).toEqual(getDocumentLeaves(cropped));+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ });++ it('reports nothing when every unlocked leaf already fits the frame', async () => {+ const h = createCropAllHarness();+ for (const id of ['raster', 'control', 'mask', 'region']) {+ h.layers.delete(id);+ h.layers.getOrCreateRect(id, CACHE_RECTS.inside!);+ }++ await expect(h.controller.cropAll()).resolves.toEqual({ skippedLocked: 2, status: 'nothing' });+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ });++ it('refuses a set it could never undo with nothing changed and every lease released', async () => {+ const h = createCropAllHarness({ historyBytes: 8 * 1024 });++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(h.original);+ expect(h.dispatched).toEqual([]);+ expect(h.layers.get('raster')?.rect).toEqual(CACHE_RECTS.raster);+ expect(h.history.byteSize()).toBe(0);+ expect(h.reservedBytes()).toBe(0);+ expect(h.released.sort()).toEqual(h.exported.sort());+ });++ it('releases every reservation when copying the cropped pixels throws', async () => {+ const h = createCropAllHarness();+ const createSurface = h.backend.createSurface.bind(h.backend);+ // The emptied mask's zero-sized copy succeeds; the first real crop, after its reservation, throws.+ vi.spyOn(h.backend, 'createSurface').mockImplementation((width: number, height: number) => {+ if (width > 0) {+ throw new Error('surface allocation failed');+ }+ return createSurface(width, height);+ });++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'failed' });+ expect(h.reservedBytes()).toBe(0);+ expect(h.document()).toBe(h.original);+ expect(h.released).toEqual(h.exported);+ });++ it('refuses as over-budget when the cropped pixels cannot be reserved', async () => {+ const h = createCropAllHarness();+ h.state.rasterBytes = 1024;++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(h.original);+ expect(h.history.canUndo()).toBe(false);+ });++ it('is stale when the document changes while the pixels are read, and changes nothing', async () => {+ let edited = false;+ const h = createCropAllHarness({+ onExport: (layerId) => {+ if (layerId === 'control' && !edited) {+ edited = true;+ h.ctx.applyStep({+ accepted: (document) => document?.bbox.width === 30,+ mutation: { bbox: { ...FRAME, width: 30 }, type: 'setCanvasBbox' },+ });+ }+ },+ });+ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'stale' });+ expect(h.dispatched.map((mutation) => mutation.type)).toEqual(['setCanvasBbox']);+ expect(getDocumentLeaves(h.document())).toEqual(getDocumentLeaves(h.original));+ expect(h.history.canUndo()).toBe(false);+ expect(h.released.sort()).toEqual(h.exported.sort());+ });++ it('is stale when a leaf pixel guard went out of date', async () => {+ const h = createCropAllHarness();+ h.guard.current = false;++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'stale' });+ expect(h.dispatched).toEqual([]);+ });++ it('leaves the entry on the undo stack when its replay is refused', async () => {+ const h = createCropAllHarness();+ await h.controller.cropAll();+ h.state.refuse = () => true;++ expect((await h.history.undo()).status).toBe('failed');+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ expect(h.history.canUndo()).toBe(true);+ });+});diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.tsindex 9d3063a1e4,ff89084cd5..1a1ddc5cce--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@@ -29,20 -28,13 +30,23 @@@ importexport type CropLayerResult =| { status: 'cropped' }| { status: 'missing' | 'locked' | 'unsupported' | 'empty' | LayerEditRefusal }- | { status: 'failed'; message: string };+ | { status: 'failed'; message: string }+ | AdjustmentRefusal;+/**+ * `skippedLocked` counts locked leaves (own or ancestor lock) whose content reaches past the frame. `nothing` when+ * every unlocked leaf already fits; every refusal leaves document, pixels and history alone.+ */+export type CropAllLayersResult =+ | { status: 'cropped'; cropped: number; skippedLocked: number }+ | { status: 'nothing'; skippedLocked: number }- | { status: 'stale' | 'failed' | LayerEditRefusal };++ | { status: 'stale' | 'failed' | LayerEditRefusal }++ | AdjustmentRefusal;+type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }+ | AdjustmentRefusal;export interface CropLayerControllerOptions {readonly ctx: Pick<@@@ -220,183 -189,6 +227,186 @@@ export class CropLayerController}}+ /**+ * Crops every leaf of every stack to the frame as one history entry. Locked leaves (their own lock or an ancestor's)+ * are skipped; leaves already inside the frame, empty ones and unsupported sources are left alone; a leaf entirely+ * outside the frame is emptied in place, so ids, order, groups and flags never change. Each leaf's export is+ * released as soon as its cropped pixels are copied, so the peak is the cropped set plus one export.+ */+ async cropAll(): Promise<CropAllLayersResult> {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {+ return { status: 'busy' };+ }+ const document = ctx.getDocument();+ if (!document) {+ return { skippedLocked: 0, status: 'nothing' };+ }+ const frame = roundOut(document.bbox);+ let skippedLocked = 0;+ const candidates: CanvasLayerContract[] = [];+ for (const leaf of compileDocumentLeaves(document)) {+ const source = renderableSourceOf(leaf.layer);+ if (!source || !this.deps.isSupportedSource(source)) {+ continue;+ }+ if (!leaf.effectiveLocked) {+ candidates.push(leaf.layer);+ continue;+ }+ // A locked leaf counts only when cropping would have changed it: content reaching past the frame.+ const content = getSourceContentRect(leaf.layer, document);+ if (!isEmpty(content) && cropRectFor(transformBounds(leaf.worldTransform, content), frame)) {+ skippedLocked += 1;+ }+ }+ const guards: LayerExportGuard[] = [];+ const cropped: CroppedLeaf[] = [];+ try {+ for (const layer of candidates) {+ const exported = await this.deps.exportBaked(layer.id);++ if (exported.status === 'adjustment-refused') {++ return exported;++ }+ if (exported.status === 'missing') {+ return { status: 'stale' };+ }+ if (exported.status === 'not-ready' || exported.status === 'over-budget') {+ return { status: exported.status };+ }+ if (exported.status !== 'ok') {+ // Empty, disabled-only or unsupported content has nothing to crop.+ continue;+ }+ try {+ guards.push(exported.guard);+ const rect = cropRectFor(exported.rect, frame);+ if (!rect) {+ continue;+ }+ const reservation = ctx.reserveRaster(rgbaBytes(rect));+ if (!reservation) {+ return { status: 'over-budget' };+ }+ let pixels: RasterSurface;+ try {+ pixels = cropPixels(this.deps.backend, exported.surface, exported.rect, rect);+ } catch (error) {+ reservation.release();+ throw error;+ }+ cropped.push({ layer, pixels: { pixels, rect }, reservation });+ } finally {+ exported.release();+ }+ }+ if (!ctx.isPermitCurrent(permit)) {+ return { status: 'busy' };+ }+ const liveDocument = ctx.getDocument();+ // Any edit while the pixels were read (a layer, the frame, the stacks) makes the plan stale.+ if (+ !liveDocument ||+ liveDocument.stacks !== document.stacks ||+ !isSameRect(liveDocument.bbox, document.bbox) ||+ guards.some((guard) => !this.deps.isGuardCurrent(guard))+ ) {+ return { status: 'stale' };+ }+ if (cropped.length === 0) {+ return { skippedLocked, status: 'nothing' };+ }+ return this.publishAll(liveDocument, cropped, skippedLocked);+ } catch {+ return { status: 'failed' };+ } finally {+ for (const leaf of cropped) {+ leaf.reservation.release();+ }+ }+ }++ private publishAll(+ document: CanvasDocumentContractV3,+ cropped: readonly CroppedLeaf[],+ skippedLocked: number+ ): CropAllLayersResult {+ const { ctx } = this.deps;+ const afterBytes = cropped.reduce((sum, leaf) => sum + rgbaBytes(leaf.pixels.rect), 0);+ const txn = ctx.begin({ historyBytes: afterBytes + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ return { status: layerEditRefusal(txn.status) };+ }+ try {+ // The prepared cache replacements; the cropped pixels hold their own reservations.+ if (!txn.reserveRaster(afterBytes)) {+ return { status: 'over-budget' };+ }+ const crops: LayerCrop[] = [];+ for (const leaf of cropped) {+ // Each before snapshot grows the one admission; a set that cannot be kept refuses with nothing changed.+ const beforePixels = this.deps.captureCache(leaf.layer, document, (cacheRect) =>+ txn.growHistory(rgbaBytes(cacheRect))+ );+ if (beforePixels === 'over-budget') {+ return { status: 'over-budget' };+ }+ if (!beforePixels || beforePixels === 'not-ready') {+ return { status: 'not-ready' };+ }+ const before = structuredClone(leaf.layer);+ crops.push({+ after: croppedLayerContract(before, leaf.pixels.rect),+ afterPixels: leaf.pixels,+ before,+ beforePixels,+ });+ }+ const beforeBytes = crops.reduce((sum, crop) => sum + rgbaBytes(crop.beforePixels.rect), 0);+ const replay = (side: 'before' | 'after') => () =>+ withReplayReservation(ctx, side === 'before' ? beforeBytes : afterBytes, () =>+ ctx.applyStep(this.replaceAllStep(crops, side))+ );+ const result = txn.publish('Crop all layers to frame', this.replaceAllStep(crops, 'after'), {+ bytes: beforeBytes + afterBytes + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(...crops.flatMap((crop) => [crop.before, crop.after])),+ redo: replay('after'),+ undo: replay('before'),+ });+ const status = layerOperationStatus(result);+ return status === 'committed' ? { cropped: crops.length, skippedLocked, status: 'cropped' } : { status };+ } finally {+ txn.end();+ }+ }++ /** Every cropped leaf's contract and cache, replaced together as one step; it rolls back to the reducer's contracts. */+ private replaceAllStep(crops: readonly LayerCrop[], side: 'before' | 'after'): EditStep {+ const { ctx } = this.deps;+ const reducerDocument = ctx.getReducerDocument();+ return replaceLayersStep(+ ctx,+ crops.map((crop) => {+ const pixels = side === 'before' ? crop.beforePixels : crop.afterPixels;+ return { contract: crop[side], prepared: ctx.preparePixels(crop.before.id, pixels.rect, pixels.pixels) };+ }),+ {+ beforeInstall: (layerId) => this.discardPersisted(layerId),+ restore: crops.flatMap((crop) => getDocumentLayer(reducerDocument, crop.before.id) ?? []),+ }+ );+ }++ /** Drops a replaced layer's pending persistence; the installed pixels are marked dirty and persist on their own. */+ private discardPersisted(layerId: string): void {+ try {+ this.deps.discardPersisted(layerId);+ } catch {+ // The installed pixels persist on their own.+ }+ }+dispose(): void {this.disposed = true;}diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.tsindex 3b93e36a29,ee9d6286ae..fbe7bee362--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts@@@ -1,82 -1,223 +1,297 @@@- import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+ /** Real-canvas checks that Merge Down bakes each layer's own adjustment stack as the canvas displayed it. */++ import type {+ CanvasAdjustmentsContract,+ CanvasDocumentContractV3,++ CanvasLayerContract,+ CanvasRasterLayerContractV2,+ } from '@workbench/canvas-engine/contracts';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+ import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';- import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+ import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+ import { fromTRS } from '@workbench/canvas-engine/math/mat2d';+ import { createAdjustedSurfaceCache } from '@workbench/canvas-engine/render/adjustedSurfaceCache';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';- import { describe, expect, it } from 'vitest';+ import {+ createSpatialAdjustmentService,+ type SpatialAdjustmentService,+ } from '@workbench/canvas-engine/render/spatial/spatialAdjustmentService';+ import { afterEach, describe, expect, it, vi } from 'vitest';import { createLayerOperationHarness } from './layerOperationHarness.testing';import { MergeLayerController } from './mergeLayerController';+ const NOISE: CanvasAdjustmentsContract = [+ {+ amount: 0.25,+ distribution: 'gaussian',+ grain: 'monochrome',+ id: 'grain',+ isEnabled: true,+ response: 'flat',+ seed: 21,+ size: 1,+ type: 'noise',+ },+ ];+ const IDENTITY = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };+ const UPPER_RECT: Rect = { height: 18, width: 24, x: -3, y: 2 };+ const LOWER_RECT: Rect = { height: 20, width: 20, x: 6, y: -2 };+ /** Document region covering both layers before and after the merge. */+ const VIEW: Rect = { height: 48, width: 48, x: -8, y: -8 };++ const layer = (+ id: string,+ rect: Rect,+ adjustments: CanvasAdjustmentsContract | undefined,+ transform = IDENTITY+ ): CanvasRasterLayerContractV2 => ({+ ...(adjustments ? { adjustments } : {}),+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { bitmap: { height: rect.height, imageName: `${id}.png`, width: rect.width }, offset: rect, type: 'paint' },+ transform,+ type: 'raster',+ });++ interface Scene {+ upperAdjustments?: CanvasAdjustmentsContract;+ lowerAdjustments?: CanvasAdjustmentsContract;+ upperTransform?: CanvasRasterLayerContractV2['transform'];+ }++ const mergeScene = (scene: Scene, displayed: boolean, service?: SpatialAdjustmentService) => {+ const backend = createDomRasterBackend();+ const upper = layer('upper', UPPER_RECT, scene.upperAdjustments, scene.upperTransform);+ const lower = layer('lower', LOWER_RECT, scene.lowerAdjustments);+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 64, width: 64, x: 0, y: 0 },+ height: 64,+ selectedLayerId: 'upper',+ stacks: stacksFrom([upper, lower]),+ version: 3,+ width: 64,+ };+ const h = createLayerOperationHarness(document, { backend });+ const fill = (id: string, rect: Rect, color: (x: number) => string) => {+ const entry = h.layers.getOrCreateRect(id, rect);+ for (let x = 0; x < rect.width; x += 1) {+ entry.surface.ctx.fillStyle = color(x);+ entry.surface.ctx.fillRect(x, 0, 1, rect.height);+ }+ h.layers.publishPixels(id);+ };+ fill('upper', UPPER_RECT, (x) => `rgba(${40 + x * 8}, 90, 200, ${x % 3 === 0 ? 0.6 : 1})`);+ fill('lower', LOWER_RECT, (x) => `rgb(200, ${50 + x * 9}, 70)`);+ const display = createAdjustedSurfaceCache(+ backend,+ undefined,+ service ? { spatial: { run: (request) => service.run(request) } } : {}+ );+ const contracts = {+ lower: getDocumentLayer(h.document(), 'lower')!,+ upper: getDocumentLayer(h.document(), 'upper')!,+ };+ /** What the canvas shows over {@link VIEW}: each layer's display copy (adjusted when it has a stack) through its transform. */+ const canvasPixels = (): number[] => {+ const surface = backend.createSurface(VIEW.width, VIEW.height);+ for (const contract of [...getDocumentLeaves(h.document())].reverse()) {+ const entry = h.layers.get(contract.id)!;+ const adjustments = contract.type === 'raster' ? contract.adjustments : undefined;+ const pixels = display.get(contract.id, entry, adjustments) ?? entry.surface;+ const { rotation, scaleX, scaleY, x, y } = contract.transform;+ const matrix = fromTRS({ x, y }, rotation, scaleX, scaleY);+ surface.ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - VIEW.x, matrix.f - VIEW.y);+ surface.ctx.drawImage(pixels.canvas, entry.rect.x, entry.rect.y);+ }+ return [...surface.ctx.getImageData(0, 0, VIEW.width, VIEW.height).data];+ };+ const rawPixels = (id: string): number[] => {+ const entry = h.layers.get(id)!;+ return [...entry.surface.ctx.getImageData(0, 0, entry.rect.width, entry.rect.height).data];+ };+ const controller = new MergeLayerController({+ backend,+ ctx: h.ctx,+ exportBaked: () => Promise.reject(new Error('merge down reads live caches')),+ hasExportableContent: (layerId) => (h.layers.get(layerId)?.rect.width ?? 0) > 0,+ isCacheReady: () => true,+ layers: h.layers,+ needsPixelPersistence: () => false,+ peekAdjustedSurface: (contract, entry) =>+ displayed && contract.type === 'raster' ? display.peek(contract.id, entry, contract.adjustments) : null,+ publishSelectedLayerIds: () => undefined,+ runSpatial: service ? (request) => service.run(request) : undefined,+ });+ /** Shows the canvas until every spatial result has landed, as frames would. */+ const settle = () =>+ vi.waitFor(+ () => {+ canvasPixels();+ for (const contract of getDocumentLeaves(h.document())) {+ const adjustments = contract.type === 'raster' ? contract.adjustments : undefined;+ expect(display.state(contract.id, h.layers.get(contract.id)!, adjustments)).toBe('exact');+ }+ },+ { interval: 20, timeout: 10_000 }+ );+ return { ...h, canvasPixels, contracts, controller, rawPixels, settle };+ };++ describe('Merge Down with adjustment stacks', () => {+ describe.each([+ ['noise on the upper layer', { upperAdjustments: NOISE }],+ ['noise on the layer below', { lowerAdjustments: NOISE }],+ [+ 'noise on a rotated, downscaled upper layer above a color-adjusted one',+ {+ lowerAdjustments: [{ id: 'invert', isEnabled: true, type: 'invert' }],+ upperAdjustments: NOISE,+ upperTransform: { rotation: Math.PI / 7, scaleX: 0.7, scaleY: 0.55, x: 9, y: 4 },+ },+ ],+ ] satisfies [string, Scene][])('%s', (_, scene) => {+ it.each([+ ['adjusting layer-local copies', false],+ ["drawing the display's current adjusted copies", true],+ ])('keeps the displayed pixels by %s; undo restores both raw layers and stacks', async (_label, displayed) => {+ const h = mergeScene(scene, displayed);+ const raw = { lower: h.rawPixels('lower'), upper: h.rawPixels('upper') };+ const shown = h.canvasPixels();++ expect(await h.controller.mergeDown('upper')).toBe('merged');++ // The merged layer has no stack: its baked pixels show what both layers showed.+ expect(getDocumentLayer(h.document(), 'lower')).not.toHaveProperty('adjustments');+ expect(h.canvasPixels()).toEqual(shown);++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLayer(h.document(), 'upper')).toBe(h.contracts.upper);+ expect(getDocumentLayer(h.document(), 'lower')).toBe(h.contracts.lower);+ expect(h.rawPixels('upper')).toEqual(raw.upper);+ expect(h.rawPixels('lower')).toEqual(raw.lower);+ });+ });+ });++ describe('Merge Down with spatial stacks', () => {+ const services: SpatialAdjustmentService[] = [];+ afterEach(() => {+ for (const service of services.splice(0)) {+ service.dispose();+ }+ });+ const spatialService = () => {+ const memory = new RasterMemoryBudgetController({ budgetBytes: 64 * 1024 * 1024 });+ const service = createSpatialAdjustmentService({+ reserve: (bytes) => memory.reserveOperation(bytes, { purpose: 'spatial-adjustment' }),+ });+ services.push(service);+ return service;+ };+ const scene: Scene = {+ lowerAdjustments: [{ amount: 80, id: 'texture', isEnabled: true, size: 3, type: 'texture' }],+ upperAdjustments: [+ { amount: 90, id: 'clarity', isEnabled: true, size: 8, type: 'clarity' },+ { id: 'invert', isEnabled: true, type: 'invert' },+ ],+ upperTransform: { rotation: Math.PI / 7, scaleX: 0.7, scaleY: 0.55, x: 9, y: 4 },+ };++ it.each([+ ['evaluating each stack in the spatial worker', false],+ ["drawing the display's exact copies", true],+ ])('keeps the settled display by %s; undo restores both stacks', async (_label, displayed) => {+ const h = mergeScene(scene, displayed, spatialService());+ await h.settle();+ const shown = h.canvasPixels();++ expect(await h.controller.mergeDown('upper')).toBe('merged');++ expect(getDocumentLayer(h.document(), 'lower')).not.toHaveProperty('adjustments');+ expect(h.canvasPixels()).toEqual(shown);+ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLayer(h.document(), 'upper')).toBe(h.contracts.upper);+ expect(getDocumentLayer(h.document(), 'lower')).toBe(h.contracts.lower);+ });+ });+++/** Coverage alpha of a mask's baked pixels, filled uniformly over `rect`. */+const coverage = (rect: Rect, alpha: number): RasterSurface => {+ const surface = createDomRasterBackend().createSurface(rect.width, rect.height);+ surface.ctx.fillStyle = `rgba(255, 255, 255, ${alpha / 255})`;+ surface.ctx.fillRect(0, 0, rect.width, rect.height);+ return surface;+};++describe('MergeLayerController in Chromium: merge masks', () => {+ it('unions coverage source-over, each mask at its own opacity', async () => {+ // The top mask is half-covered at full opacity; the one below is fully covered at half opacity.+ const sources: Record<string, { alpha: number; opacity: number; rect: Rect }> = {+ below: { alpha: 255, opacity: 0.5, rect: { height: 10, width: 10, x: 5, y: 0 } },+ top: { alpha: 128, opacity: 1, rect: { height: 10, width: 10, x: 0, y: 0 } },+ };+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId: 'top',+ stacks: stacksFrom(+ ['top', 'below'].map((id) =>+ layerContract(id, 'inpaint_mask', { opacity: sources[id]!.opacity } as Partial<CanvasLayerContract>)+ )+ ),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document);+ const dom = createDomRasterBackend();+ // Real raw caches, which undo snapshots copy.+ for (const [layerId, { alpha, rect }] of Object.entries(sources)) {+ h.layers.installReplacement({ layerId, rect, surface: coverage(rect, alpha) });+ }+ const created: RasterSurface[] = [];+ const controller = new MergeLayerController({+ backend: {+ ...dom,+ createSurface: (width, height, options) => {+ const surface = dom.createSurface(width, height, options);+ created.push(surface);+ return surface;+ },+ },+ ctx: h.ctx,+ exportBaked: (layerId) =>+ Promise.resolve({+ guard: { layer: getDocumentLayer(h.document(), layerId) } as never,+ rect: { ...sources[layerId]!.rect },+ release: () => undefined,+ status: 'ok' as const,+ surface: coverage(sources[layerId]!.rect, sources[layerId]!.alpha),+ }),+ hasExportableContent: () => true,+ isCacheReady: () => true,+ layers: h.layers,+ needsPixelPersistence: () => true,++ peekAdjustedSurface: () => null,+ publishSelectedLayerIds: () => undefined,+ });++ await expect(controller.mergeInpaintMasks(['top', 'below'])).resolves.toMatchObject({ status: 'merged' });++ const merged = created.find((surface) => surface.width === 15 && surface.height === 10)!;+ const alphaAt = (x: number): number => merged.ctx.getImageData(x, 5, 1, 1).data[3]!;+ // Top only: its own coverage. Below only: half of full coverage. Both: 128 over 128 = 128 + 128 * (1 - 128/255).+ expect(alphaAt(2)).toBeCloseTo(128, -0.5);+ expect(alphaAt(12)).toBeCloseTo(128, -0.5);+ expect(alphaAt(7)).toBeCloseTo(128 + 128 * (1 - 128 / 255), -0.5);+ });+});diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.tsindex 2dfeb49872,c864e10343..b44d069b2a--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts@@@ -1,13 -1,16 +1,20 @@@- import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+ import type {+ CanvasAdjustmentsContract,+ CanvasDocumentContractV3,+ CanvasLayerContract,+ } from '@workbench/canvas-engine/contracts';-import type { SpatialRunner } from '@workbench/canvas-engine/render/exactAdjustments';++import type { AdjustmentRefusal, SpatialRunner } from '@workbench/canvas-engine/render/exactAdjustments';+ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentIndex, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';- import { describe, expect, it } from 'vitest';+ import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+ import { describe, expect, it, vi } from 'vitest';import { createLayerOperationHarness } from './layerOperationHarness.testing';import { MergeLayerController } from './mergeLayerController';@@@ -127,152 -149,178 +153,340 @@@ describe('MergeLayerController: merge dexpect(h.history.canUndo()).toBe(false);});- it('refuses the bottom-most layer and a busy canvas', () => {+ it('reserves a layer-local adjusted copy only when the display has no current one', async () => {+ // Raw undo snapshots plus the merged pixels and their prepared replacement; a copy adds a surface and ImageData.+ const baseBytes = (100 + 100) * 4 + 225 * 4 * 2;+ const copying = createHarness(undefined, { lowerAdjusted: true });+ copying.state.rasterBytes = baseBytes;+ expect(await copying.controller.mergeDown('upper')).toBe('over-budget');+ copying.state.rasterBytes = baseBytes + 100 * 4 * 2;+ expect(await copying.controller.mergeDown('upper')).toBe('merged');++ const displayed = createHarness(undefined, {+ displayed: createTestStubRasterBackend().createSurface(10, 10),+ lowerAdjusted: true,+ });+ displayed.state.rasterBytes = baseBytes;+ expect(await displayed.controller.mergeDown('upper')).toBe('merged');+ });++ it('refuses the bottom-most layer and a busy canvas', async () => {const h = createHarness();- expect(h.controller.mergeDown('lower')).toBe('unsupported');- expect(h.controller.mergeDown('missing')).toBe('missing');+ expect(await h.controller.mergeDown('lower')).toBe('unsupported');+ expect(await h.controller.mergeDown('missing')).toBe('missing');h.state.gestureActive = true;- expect(h.controller.mergeDown('upper')).toBe('busy');+ expect(await h.controller.mergeDown('upper')).toBe('busy');+ expect(h.dispatched).toEqual([]);+ });++ describe('with a spatial stack', () => {+ const CLARITY: CanvasAdjustmentsContract = [+ { amount: 60, id: 'clarity', isEnabled: true, size: 20, type: 'clarity' },+ ];+ const passThrough = () =>+ vi.fn<SpatialRunner>((request) => Promise.resolve({ pixels: request.pixels, status: 'ok' }));++ it('evaluates the layer-local stack in the spatial service before merging, and drops it', async () => {+ const runSpatial = passThrough();+ const h = createHarness(undefined, { lowerAdjustments: CLARITY, runSpatial });++ expect(await h.controller.mergeDown('upper')).toBe('merged');++ expect(runSpatial).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ height: LOWER_RECT.height, priority: 'now', width: LOWER_RECT.width })+ );+ expect(getDocumentLayer(h.document(), 'lower')).not.toHaveProperty('adjustments');+ });++ it("reuses the display's exact copy without a job", async () => {+ const runSpatial = passThrough();+ const h = createHarness(undefined, {+ displayed: createTestStubRasterBackend().createSurface(10, 10),+ lowerAdjustments: CLARITY,+ runSpatial,+ });++ expect(await h.controller.mergeDown('upper')).toBe('merged');+ expect(runSpatial).not.toHaveBeenCalled();+ });++ it.each(['too-large', 'over-budget', 'error'] as const)(+ 'refuses %s with the layer name before anything changes',+ async (reason) => {+ const h = createHarness(undefined, {+ lowerAdjustments: CLARITY,+ runSpatial: () => Promise.resolve({ status: reason }),+ });++ expect(await h.controller.mergeDown('upper')).toEqual({+ ownerId: 'lower',+ ownerName: 'lower',+ reason,+ status: 'adjustment-refused',+ });+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ expect(h.reservedBytes()).toBe(0);+ }+ );++ it('refuses without a spatial runner rather than merge without the spatial entries', async () => {+ const h = createHarness(undefined, { lowerAdjustments: CLARITY });++ expect(await h.controller.mergeDown('upper')).toMatchObject({ reason: 'error', status: 'adjustment-refused' });+ expect(h.dispatched).toEqual([]);+ });++ it('lands nothing when a layer changed while the job ran', async () => {+ const h = createHarness(undefined, {+ lowerAdjustments: CLARITY,+ runSpatial: (request) => {+ h.layers.publishPixels('upper');+ return Promise.resolve({ pixels: request.pixels, status: 'ok' });+ },+ });++ expect(await h.controller.mergeDown('upper')).toBe('not-ready');+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ });+ });+ });++ describe('MergeLayerController: merge visible with a spatial group stack', () => {- const scene = (runSpatial?: SpatialRunner) => {++ const scene = (runSpatial?: SpatialRunner, exportRefusal?: AdjustmentRefusal) => {+ const first = { ...paintLayer('first'), name: 'First' };+ const second = { ...paintLayer('second'), name: 'Second' };+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId: null,+ stacks: stacksFrom([+ groupContract('group', [first, second], {+ adjustments: [{ amount: 30, id: 'dehaze', isEnabled: true, type: 'dehaze' }],+ name: 'Haze',+ }),+ ]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document);+ const rects: Record<string, Rect> = { first: UPPER_RECT, second: LOWER_RECT };+ const controller = new MergeLayerController({+ backend: h.backend,+ ctx: h.ctx,+ exportBaked: (layerId) =>- Promise.resolve({- guard: {- cacheVersion: 1,- documentGeneration: 1,- layer: getDocumentLayer(h.document(), layerId)!,- layerId,- projectId: 'p',- },- rect: rects[layerId]!,- release: () => undefined,- status: 'ok',- surface: h.backend.createSurface(rects[layerId]!.width, rects[layerId]!.height),- }),++ Promise.resolve(++ exportRefusal?.ownerId === layerId++ ? exportRefusal++ : {++ guard: {++ cacheVersion: 1,++ documentGeneration: 1,++ layer: getDocumentLayer(h.document(), layerId)!,++ layerId,++ projectId: 'p',++ },++ rect: rects[layerId]!,++ release: () => undefined,++ status: 'ok',++ surface: h.backend.createSurface(rects[layerId]!.width, rects[layerId]!.height),++ }++ ),+ hasExportableContent: () => true,+ isCacheReady: () => true,+ layers: h.layers,+ needsPixelPersistence: () => false,+ peekAdjustedSurface: () => null,+ publishSelectedLayerIds: () => undefined,+ runSpatial,+ });+ return { ...h, controller };+ };+++ it('preserves a selected layer export refusal with its owner and reason, merging nothing', async () => {++ const refusal: AdjustmentRefusal = {++ ownerId: 'second',++ ownerName: 'Second',++ reason: 'too-large',++ status: 'adjustment-refused',++ };++ const h = scene(undefined, refusal);++ const original = h.document();++++ expect(await h.controller.mergeSelected(['first', 'second'])).toEqual(refusal);++ expect(h.document()).toBe(original);+ expect(h.dispatched).toEqual([]);++ expect(h.history.canUndo()).toBe(false);++ expect(h.reservedBytes()).toBe(0);++ });+++ it("evaluates the group's spatial stack on the merged members", async () => {+ const runSpatial = vi.fn<SpatialRunner>((request) => Promise.resolve({ pixels: request.pixels, status: 'ok' }));+ const h = scene(runSpatial);++ expect(await h.controller.mergeVisible()).toBe('merged');+ // The buffer holds every member: the union of their baked rects.+ expect(runSpatial).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ height: MERGED_RECT.height,+ steps: [{ amount: 30, kind: 'dehaze' }],+ width: MERGED_RECT.width,+ })+ );+ });++ it('refuses with the group name when its stack cannot run', async () => {+ const h = scene(() => Promise.resolve({ status: 'too-large' }));++ expect(await h.controller.mergeVisible()).toEqual({+ ownerId: 'group',+ ownerName: 'Haze',+ reason: 'too-large',+ status: 'adjustment-refused',+ });+ expect(h.history.canUndo()).toBe(false);});});++describe('MergeLayerController: merge masks', () => {+ const RECTS: Record<string, Rect> = {+ bottom: { height: 10, width: 10, x: 30, y: 30 },+ middle: { height: 10, width: 10, x: 10, y: 10 },+ top: { height: 10, width: 10, x: 0, y: 0 },+ };++ const createMaskHarness = (options: { historyBytes?: number; onExport?: () => void } = {}) => {+ const top = layerContract('top', 'inpaint_mask', {+ denoise: { isEnabled: true, limit: 0.4 },+ mask: { bitmap: null, fill: { color: '#123456', style: 'grid' } },+ noise: { isEnabled: true, level: 0.2 },+ opacity: 0.5,+ } as Partial<CanvasLayerContract>);+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId: 'middle',+ stacks: stacksFrom([+ groupContract('first', [layerContract('other', 'inpaint_mask'), top]),+ groupContract('second', [layerContract('middle', 'inpaint_mask')]),+ layerContract('bottom', 'inpaint_mask'),+ ]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document, { historyBytes: options.historyBytes });+ for (const [id, rect] of Object.entries({ ...RECTS, other: { height: 4, width: 4, x: 0, y: 0 } })) {+ h.layers.getOrCreateRect(id, rect).stale = false;+ }+ const released: string[] = [];+ const selections: [string | null, readonly string[]][] = [];+ const controller = new MergeLayerController({+ backend: h.backend,+ ctx: h.ctx,+ exportBaked: (layerId) => {+ options.onExport?.();+ const entry = h.layers.get(layerId)!;+ return Promise.resolve({+ guard: { layer: getDocumentLayer(h.document(), layerId) } as never,+ rect: { ...entry.rect },+ release: () => released.push(layerId),+ status: 'ok' as const,+ surface: entry.surface,+ });+ },+ hasExportableContent: (layerId) => (h.layers.get(layerId)?.rect.width ?? 0) > 0,+ isCacheReady: () => true,+ layers: h.layers,+ needsPixelPersistence: () => true,++ peekAdjustedSurface: () => null,+ publishSelectedLayerIds: (primary, ids) => selections.push([primary, ids]),+ });+ return { ...h, controller, original: h.document(), released, selections };+ };++ const structure = (document: CanvasDocumentContractV3) =>+ [...getDocumentIndex(document).byId.values()].map((entry) => [entry.node.id, entry.parentId, entry.siblingIndex]);++ it('unions masks from different groups into one mask above the topmost, configured like it, as one step', async () => {+ const h = createMaskHarness();++ const result = await h.controller.mergeInpaintMasks(['bottom', 'top', 'middle']);+ expect(result).toEqual({ layerId: 'new-1', status: 'merged' });++ const merged = getDocumentLayer(h.document(), 'new-1');+ expect(merged).toEqual({+ blendMode: 'normal',+ denoise: { isEnabled: true, limit: 0.4 },+ id: 'new-1',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#123456', style: 'grid' }, offset: { x: 0, y: 0 } },+ name: 'top merged',+ noise: { isEnabled: true, level: 0.2 },+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ });+ // The union of the three sources' extents, in place of the topmost source; the others are gone.+ expect(h.layers.get('new-1')?.rect).toEqual({ height: 40, width: 40, x: 0, y: 0 });+ expect(getDocumentIndex(h.document()).byId.get('new-1')).toMatchObject({ parentId: 'first', siblingIndex: 1 });+ expect(leafIds(h.document())).toEqual(['other', 'new-1']);+ expect(h.document().selectedLayerId).toBe('new-1');+ expect(h.history.entries().past).toEqual(['Merge masks']);+ expect(h.released.sort()).toEqual(['bottom', 'middle', 'top']);+ expect(h.reservedBytes()).toBe(0);++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(structure(h.document())).toEqual(structure(h.original));+ for (const id of ['top', 'middle', 'bottom']) {+ expect(getDocumentLayer(h.document(), id)).toBe(getDocumentLayer(h.original, id));+ expect(h.layers.get(id)?.rect).toEqual(RECTS[id]);+ }+ expect(h.document().selectedLayerId).toBe('middle');++ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(leafIds(h.document())).toEqual(['other', 'new-1']);+ });++ it.each([+ ['one mask', ['top'], 'ineligible'],+ ['a regional or raster leaf', ['top', 'first'], 'ineligible'],+ ['a missing id', ['top', 'gone'], 'missing'],+ ] as const)('refuses %s without reading pixels', async (_, ids, status) => {+ const h = createMaskHarness({ onExport: () => expect.fail('read pixels') });++ await expect(h.controller.mergeInpaintMasks(ids)).resolves.toEqual({ status });+ expect(h.dispatched).toEqual([]);+ });++ it('refuses a merge it could never undo with nothing changed', async () => {+ const h = createMaskHarness({ historyBytes: 1024 });++ await expect(h.controller.mergeInpaintMasks(['top', 'middle'])).resolves.toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(h.original);+ expect(h.dispatched).toEqual([]);+ expect(h.reservedBytes()).toBe(0);+ });++ it('refuses when a source changes while its pixels are read', async () => {+ let edited = false;+ const h = createMaskHarness({+ onExport: () => {+ if (!edited) {+ edited = true;+ h.ctx.applyStep({+ accepted: (document) => getDocumentLayer(document, 'middle')?.name === 'Renamed',+ mutation: { id: 'middle', patch: { name: 'Renamed' }, type: 'updateCanvasLayer' },+ });+ }+ },+ });++ await expect(h.controller.mergeInpaintMasks(['top', 'middle'])).resolves.toEqual({ status: 'not-ready' });+ expect(h.dispatched.map((mutation) => mutation.type)).toEqual(['updateCanvasLayer']);+ expect(h.history.canUndo()).toBe(false);+ });+});diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex 1e4ef4948c,4cfd5d5f64..781b3ffeb1--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@@ -1,10 -1,9 +1,10 @@@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';- import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+ import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';@@@ -23,15 -17,24 +23,28 @@@ import { removeNodes } from '@workbenchimport { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';-import { canMergeSelectedRasters, getMergeVisibleRasterLeaves } from '@workbench/canvas-engine/document/mergeVisible';+import {+ canMergeInpaintMasks,+ canMergeSelectedRasters,+ getMergeVisibleRasterLeaves,+} from '@workbench/canvas-engine/document/mergeVisible';import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';- import { applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';+ import {+ applyAdjustments,+ hasSpatialAdjustments,+ isIdentityAdjustments,+ } from '@workbench/canvas-engine/render/adjustments';import { blendToComposite } from '@workbench/canvas-engine/render/compositor';+ import {+ adjustExactly,+ type AdjustmentRefusal,+ adjustmentRefusal,+ adjustSurfaceExactly,+ imageDataOf,+ isAdjustmentRefusal,+ type SpatialRunner,+ } from '@workbench/canvas-engine/render/exactAdjustments';import {collectCompositedGroups,planGroupCompositeScopes,@@@ -53,54 -56,8 +66,58 @@@ importtype LayerPixels,} from './editSteps';- export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'failed';+ export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'failed' | AdjustmentRefusal;+/** Every refusal leaves document, pixels and history alone. */+export type MergeInpaintMasksResult =+ | { status: 'merged'; layerId: string }- | { status: 'ineligible' | 'missing' | 'failed' | LayerEditRefusal };++ | { status: 'ineligible' | 'missing' | 'failed' | LayerEditRefusal }++ | AdjustmentRefusal;++/**+ * What tells one merge of selected leaves into a new leaf from another: who may merge (checked before the pixels are+ * read and again before publishing), which stack the result joins above the topmost contributor, what it is, and+ * the history label.+ */+interface SelectedMergeSpec {+ readonly label: string;+ readonly stack: LayerStackKind;+ canMerge(document: CanvasDocumentContractV3, selectedIds: ReadonlySet<string>): boolean;+ /** The merged leaf placing pixels at `rect`, from the contributors top first. */+ createResult(id: string, contributors: readonly CanvasLayerContract[], rect: Rect): CanvasLayerContract;+}+- type SelectedMergeResult = { status: 'merged'; layerId: string } | { status: Exclude<MergeVisibleResult, 'merged'> };++type SelectedMergeResult =++ | { status: 'merged'; layerId: string }++ | { status: Exclude<MergeVisibleResult, 'merged' | AdjustmentRefusal> }++ | AdjustmentRefusal;++const IDENTITY_TRANSFORM = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };++/**+ * One inpaint mask carrying the union of the sources' coverage at `rect`, named after and configured like the topmost+ * source: its fill, noise and denoise.+ */+const mergedMaskLayer = (id: string, contributors: readonly CanvasLayerContract[], rect: Rect): CanvasLayerContract => {+ const top = contributors[0]!;+ if (top.type !== 'inpaint_mask') {+ throw new Error('A mask merge needs inpaint mask contributors.');+ }+ return {+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: structuredClone(top.mask.fill), offset: { x: rect.x, y: rect.y } },+ name: `${top.name} merged`,+ opacity: 1,+ transform: { ...IDENTITY_TRANSFORM },+ type: 'inpaint_mask',+ ...(top.noise ? { noise: structuredClone(top.noise) } : {}),+ ...(top.denoise ? { denoise: structuredClone(top.denoise) } : {}),+ };+};+export type MergeDownResult =| 'merged'| SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>@@@ -443,42 -491,7 +551,42 @@@ export class MergeLayerController}}+ /** Flattens one contiguous run of selected raster siblings into a new paint layer above them. */async mergeSelected(layerIds: readonly string[]): Promise<MergeVisibleResult> {+ const result = await this.mergeSelectedInto(layerIds, {+ canMerge: (document, selectedIds) =>+ canMergeSelectedRasters(document, compileDocumentLeaves(document), selectedIds, this.deps.hasExportableContent),+ createResult: (id, contributors, rect) => paintLayerAt(id, `${contributors[0]!.name} merged`, rect),+ label: 'Merge selected layers',+ stack: 'raster',+ });- return result.status;++ return isAdjustmentRefusal(result) ? result : result.status;+ }++ /** Unions the coverage of selected inpaint masks, anywhere in the stack, into one new mask above the topmost. */+ async mergeInpaintMasks(layerIds: readonly string[]): Promise<MergeInpaintMasksResult> {+ const document = this.deps.ctx.getDocument();+ if (document && layerIds.some((id) => !getDocumentNode(document, id))) {+ return { status: 'missing' };+ }+ const result = await this.mergeSelectedInto(layerIds, {+ canMerge: (candidate, selectedIds) =>+ canMergeInpaintMasks(compileDocumentLeaves(candidate), selectedIds, this.deps.hasExportableContent),+ createResult: mergedMaskLayer,+ label: 'Merge masks',+ stack: 'inpaint_mask',+ });- if (result.status === 'merged') {++ if (result.status === 'merged' || isAdjustmentRefusal(result)) {+ return result;+ }+ return { status: result.status === 'nothing' ? 'ineligible' : result.status };+ }++ /**+ * Composites the selected leaves bottom-up (source-over, each at its opacity) into a new leaf above the topmost and+ * removes them, as one undo step that restores every source in place with its raw pixels.+ */+ private async mergeSelectedInto(layerIds: readonly string[], spec: SelectedMergeSpec): Promise<SelectedMergeResult> {const { ctx } = this.deps;const permit = ctx.capturePermit();if (this.disposed || !permit) {@@@ -509,13 -524,17 +617,17 @@@}const exports = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);if (!ctx.isPermitCurrent(permit)) {- return 'busy';+ return { status: 'busy' };}+ const refused = exports.find(isAdjustmentRefusal);+ if (refused) {+ return refused;+ }if (exports.some((result) => result.status === 'over-budget')) {- return 'over-budget';+ return { status: 'over-budget' };}if (exports.some((result) => result.status !== 'ok')) {- return 'not-ready';+ return { status: 'not-ready' };}for (let index = 0; index < exports.length; index += 1) {const exported = exports[index];diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex dc39c1227f,4699a6065b..2687dfa21e--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@@ -34,9 -38,9 +38,10 @@@ import { groupContract, stacksFrom } frimport { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';+import * as compositor from '@workbench/canvas-engine/render/compositor';import { DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+ import { createInlineSpatialExecutor } from '@workbench/canvas-engine/render/spatial/spatialAdjustmentService.testing';import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';import {createCanvasEngine as createApplicationCanvasEngine,@@@ -15412,358 -15584,8 +15766,358 @@@ describe('fitToView: content ∪ bbox'});});+describe('overview: composites the fit-to-view extent', () => {+ const paintAt = (id: string, x: number, y: number, isEnabled = true): CanvasLayerContract => ({+ ...(rasterLayer(id) as CanvasRasterLayerContractV2),+ isEnabled,+ source: { bitmap: { height: 100, imageName: `${id}-pixels`, width: 100 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y },+ });+ const overviewTarget = (): HTMLCanvasElement =>+ ({+ getContext: () => createTestStubRasterBackend().createSurface(1, 1).ctx,+ height: 0,+ width: 0,+ }) as unknown as HTMLCanvasElement;++ it('sizes, translates and reports the frame ∪ enabled content, leaving disabled layers out', () => {+ const composite = vi.spyOn(compositor, 'compositeDocument');+ // Frame (0,0)..(100,100) ∪ enabled paint (-200,-50)..(-100,50) = (-200,-50) 300×150; the disabled layer at+ // (500,500) would stretch it to 800×650.+ const { store } = createReactiveStore(+ noLayerDoc({ stacks: stacksFrom([paintAt('outside', -200, -50), paintAt('hidden', 500, 500, false)]) })+ );+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const target = overviewTarget();++ const shown = engine.previews.drawDocumentOverview(target, 150);++ expect(shown).toEqual({ height: 150, width: 300, x: -200, y: -50 });+ expect({ height: target.height, width: target.width }).toEqual({ height: 75, width: 150 });+ // Half scale, shifted so document (-200,-50) lands on target pixel (0,0).+ expect(composite.mock.calls.at(-1)?.[3]).toEqual({ a: 0.5, b: 0, c: 0, d: 0.5, e: 100, f: 25 });+ composite.mockRestore();+ engine.lifecycle.dispose();+ });+});+// ---- transform session: param commit (image) + pixel bake (paint) ----------+describe('masks while a result is staged', () => {+ it('hides masks and region tints for the whole staging session, redrawing in full when it starts and ends', () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const composite = vi.spyOn(compositor, 'compositeDocument');+ let canvas = makeCanvas({ ...makeDoc(), stacks: stacksFrom([maskLayer('m'), rasterLayer('a')]) });+ const listeners = new Set<() => void>();+ const store: EngineStore = {+ dispatch: vi.fn(),+ getState: () => ({ activeProjectId: 'p1', projects: [{ canvas, id: 'p1' }] }) as unknown as WorkbenchState,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ const setCandidates = (pendingImages: CanvasStagingCandidateContract[]): void => {+ canvas = { ...canvas, stagingArea: { ...canvas.stagingArea, isVisible: false, pendingImages } };+ for (const listener of listeners) {+ listener();+ }+ };+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ engine.surface.attach(createInputCanvas().element, createInputCanvas().element);+ const frame = () => {+ composite.mockClear();+ raf.flush();+ const options = composite.mock.calls.at(-1)?.[4];+ return {+ damage: options?.damage?.kind,+ drawn: options?.preparation?.leaves.map((leaf) => leaf.id),+ regionOverlays: options?.regionOverlays,+ };+ };+ expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });++ // A candidate whose preview is toggled off still hides the masks.+ setCandidates([+ {+ height: 20,+ imageName: 'staged.png',+ imageUrl: '/staged.png',+ placement: { height: 20, opacity: 1, width: 20, x: 0, y: 0 },+ queuedAt: '2026-07-16T00:00:00.000Z',+ sourceQueueItemId: 'queue',+ thumbnailUrl: '/staged-thumb.png',+ width: 20,+ },+ ]);+ expect(frame()).toEqual({ damage: 'full', drawn: ['a'], regionOverlays: false });++ setCandidates([]);+ expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });+ composite.mockRestore();+ engine.lifecycle.dispose();+ });+});++describe('beginTransform', () => {+ const setup = (layers: CanvasLayerContract[], selectedLayerId: string | null) => {+ const { dispatch, projectId, store } = createReducerBackedStore({+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId,+ stacks: stacksFrom(layers),+ version: 3,+ width: 100,+ });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ return { dispatch, engine };+ };++ it('selects the layer and opens its session now, even with transform already active and no session', () => {+ const { engine } = setup([rasterLayer('a'), rasterLayer('b')], null);+ engine.tools.setTool('transform');+ expect(engine.stores.transformSession.get()).toBeNull();++ expect(engine.layers.beginTransform('b')).toBe('started');+ expect(engine.document.getDocument()?.selectedLayerId).toBe('b');+ expect(engine.stores.activeTool.get()).toBe('transform');+ expect(engine.stores.transformSession.get()?.layerId).toBe('b');+ engine.lifecycle.dispose();+ });++ it('cancels a session on another layer, dropping its preview, before opening one on the target', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.tools.setTool('transform');+ engine.layers.updateTransformSession({ rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 });+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('started');+ expect(engine.stores.transformSession.get()).toMatchObject({+ layerId: 'b',+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ });+ // Only the selection changed: the abandoned preview on `a` never landed.+ expect(dispatch.mock.calls.map(([action]) => action.type)).toEqual(['setCanvasSelectedLayer']);+ expect(getDocumentLayer(engine.document.getDocument(), 'a')?.transform.scaleX).toBe(1);+ engine.lifecycle.dispose();+ });++ it.each([+ ['locked', [{ ...rasterLayer('b'), isLocked: true }], 'locked'],+ ['a mask', [thumbnailMaskLayer('b', 'inpaint_mask')], 'ineligible'],+ ['missing', [rasterLayer('a')], 'missing'],+ ] as const)('refuses %s without selecting or switching tools', (_, layers, status) => {+ const { dispatch, engine } = setup([rasterLayer('a'), ...layers.filter((layer) => layer.id !== 'a')], 'a');++ expect(engine.layers.beginTransform('b')).toBe(status);+ expect(dispatch).not.toHaveBeenCalled();+ expect(engine.stores.activeTool.get()).not.toBe('transform');+ expect(engine.stores.transformSession.get()).toBeNull();+ engine.lifecycle.dispose();+ });++ /** Paints a stroke onto a new layer, then asks for its transform before persistence acknowledges the pixels. */+ const strokeThenTransform = (options: { uploadImage?: () => Promise<never> } = {}) => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );+ // The window key listeners attach adds, so a test can hold Space as the browser would deliver it.+ const windowListeners = new Map<string, (event: unknown) => void>();+ vi.stubGlobal('addEventListener', (type: string, listener: (event: unknown) => void) =>+ windowListeners.set(type, listener)+ );+ vi.stubGlobal('removeEventListener', (type: string) => windowListeners.delete(type));+ const { dispatch, projectId, store } = createReducerBackedStore({+ ...makeDoc(),+ selectedLayerId: null,+ stacks: stacksFrom([]),+ });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ ...(options.uploadImage ? { uploadImage: options.uploadImage } : { bitmapStore: createSpyBitmapStore() }),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const overlay = createInputCanvas();+ engine.surface.attach(createInputCanvas().element, overlay.element);+ const strokes: StrokeCommittedEvent[] = [];+ engine.tools.onStrokeCommitted((event) => strokes.push(event));- const refusals: string[] = [];++ const refusals: CanvasEditRefusal[] = [];+ engine.tools.onEditRefused((refusal) => refusals.push(refusal));+ engine.tools.setTool('brush');+ overlay.fire('pointerenter', pointerAt(20, 20));+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(40, 40));+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));+ const stroke = strokes[0]!;+ // Its pixels live only in the cache until persistence acknowledges the bitmap.+ expect(engine.layers.beginTransform(stroke.layerId)).toBe('started');+ expect(engine.stores.activeTool.get()).toBe('transform');+ expect(engine.stores.transformSession.get()).toBeNull();+ expect(engine.interaction.get('pendingTransformLayerId')).toBe(stroke.layerId);+ const key = (type: 'keydown' | 'keyup', code: string) =>+ windowListeners.get(type)?.({ code, key: code === 'Space' ? ' ' : code, preventDefault: () => {}, target: null });+ const persist = () =>+ dispatch({+ id: stroke.layerId,+ source: {+ bitmap: { height: stroke.dirtyRect.height, imageName: 'stroke.png', width: stroke.dirtyRect.width },+ offset: { x: stroke.dirtyRect.x, y: stroke.dirtyRect.y },+ type: 'paint',+ },+ type: 'updateCanvasLayerSource',+ });+ const sessionLayerId = () => engine.stores.transformSession.get()?.layerId ?? null;+ return { engine, key, layerId: stroke.layerId, persist, refusals, sessionLayerId };+ };++ it('opens a transform requested right after a stroke once its pixels are persisted', () => {+ const h = strokeThenTransform();+ h.persist();+ expect(h.sessionLayerId()).toBe(h.layerId);+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBeNull();+ h.engine.lifecycle.dispose();+ });++ it('keeps waiting through a Space pan held meanwhile, opening when the pixels land under the hold', () => {+ const h = strokeThenTransform();+ h.key('keydown', 'Space');+ expect(h.engine.stores.activeTool.get()).toBe('view');+ h.persist();+ expect(h.sessionLayerId()).toBe(h.layerId);+ h.key('keyup', 'Space');+ expect(h.engine.stores.activeTool.get()).toBe('transform');+ expect(h.sessionLayerId()).toBe(h.layerId);+ h.engine.lifecycle.dispose();+ });++ it.each([+ ['a tool switch', (engine: CanvasEngine) => engine.tools.setTool('brush')],+ ['Escape', (engine: CanvasEngine) => engine.tools.handleEscapePriority({ gestureWasActive: false })],+ ])('stops waiting on %s', (_, end) => {+ const h = strokeThenTransform();+ end(h.engine);+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBeNull();+ h.persist();+ expect(h.sessionLayerId()).toBeNull();+ h.engine.lifecycle.dispose();+ });++ it('keeps waiting through retried upload failures, and stops with a refusal once no retry follows', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ const h = strokeThenTransform({ uploadImage: () => Promise.reject(new Error('offline')) });+ // Advances the fake clock, then yields to real I/O: hashing the encoded pixels settles outside the clock.+ const advance = async (ms: number) => {+ await vi.advanceTimersByTimeAsync(ms);+ await new Promise<void>((resolve) => {+ const channel = new MessageChannel();+ channel.port1.onmessage = () => {+ channel.port1.close();+ resolve();+ };+ channel.port2.postMessage(null);+ });+ };+ // One barrier: every upload attempt fails, its retry delays elapse on the fake clock.+ const failFlush = async () => {+ const flush = { settled: false };+ void h.engine.lifecycle+ .flushPendingUploads()+ .catch(() => undefined)+ .then(() => {+ flush.settled = true;+ });+ for (let step = 0; step < 200 && !flush.settled; step += 1) {+ await advance(250);+ }+ expect(flush.settled).toBe(true);+ };++ await failFlush();+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBe(h.layerId);+ expect(h.refusals).toEqual([]);++ // The store retries on its own backoff until its consecutive-failure limit stops it.+ for (let step = 0; step < 300 && h.engine.interaction.get('pendingTransformLayerId'); step += 1) {+ await advance(1000);+ }+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBeNull();+ expect(h.refusals).toEqual(['not-ready']);+ h.engine.lifecycle.dispose();+ } finally {+ vi.useRealTimers();+ }+ });++ it('refuses as busy while interaction is locked, leaving the selection and tool unchanged', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.tools.setInteractionLocked(true);+ // The lock itself parks the surface on the view tool.+ const lockedTool = engine.stores.activeTool.get();+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('busy');+ expect(dispatch).not.toHaveBeenCalled();+ expect(engine.document.getDocument()?.selectedLayerId).toBe('a');+ expect(engine.stores.activeTool.get()).toBe(lockedTool);+ expect(engine.stores.transformSession.get()).toBeNull();+ engine.lifecycle.dispose();+ });++ it('refuses as busy while document edits are locked, leaving the selection and tool unchanged', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.tools.setTool('brush');+ engine.stores.documentEditingLocked.set(true);+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('busy');+ expect(dispatch).not.toHaveBeenCalled();+ expect(engine.stores.activeTool.get()).toBe('brush');+ expect(engine.stores.transformSession.get()).toBeNull();+ engine.lifecycle.dispose();+ });++ it('refuses as busy once disposed, without touching the selection', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.lifecycle.dispose();+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('busy');+ expect(dispatch).not.toHaveBeenCalled();+ });+});+describe('transform session', () => {it('image layer Apply commits one structural transform with the exact inverse', async () => {const { store } = createReactiveStore(selectedImageDoc());diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 54f672afc6,ac9460a57f..8f3db167c4--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@@ -17,14 -16,11 +17,14 @@@ import typeCanvasDocumentSnapshot,CanvasLifecycleCapability,CanvasSelectionCapability,+ CanvasSurfaceAttachOptions,CanvasSurfaceCapability,CanvasViewportCapability,+ ColorSamplePhase,BooleanRasterOperation,BooleanRasterResult,- CopyLayerToRasterResult,+ CopyLayerResult,+ CropAllLayersResult,CropLayerResult,ExportBakedLayerPixelsOptions,ExportLayerPixelsOptions,@@@ -194,8 -192,7 +198,8 @@@ import type { StrokeCommittedEvent, Tooimport { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';- import { decideLayerChange } from './document/layerChangeDecision';+ import { decideLayerChange, nextThumbnailDisplayToken } from './document/layerChangeDecision';+import { canMergeInpaintMasks as canMergeInpaintMasksIn } from './document/mergeVisible';import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';import { collectCanvasFontReferences, replaceCanvasFontReferences } from './fontReferences';import { createLayerExportGuards, isSupportedExportSource } from './layerExportGuards';@@@ -2916,11 -2900,11 +3037,13 @@@ export const createCanvasEngine = (optscommitRasterFilterResult,commitStagedImage,commitTextEdit,+ convertLayerToControl,+ copyLayerToControl,copyLayerToRaster,+ cropAllLayersToBbox,cropLayerToBbox,duplicateLayers,+ mergeInpaintMasks,mergeLayerDown,mergeSelectedRasterLayers,mergeVisibleRasterLayers,diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex c4102ed294,734eef5139..0c36c38883--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@@ -727,9 -730,9 +732,10 @@@ export const createEngineStores = (inittextEditSession: createScalarStore<TextEditSession | null>(null, textEditSessionEqual),textOptions: createScalarStore<TextToolOptions>({ ...DEFAULT_TEXT_OPTIONS }, textOptionsEqual),thumbnailVersion: createKeyedVersionStore(),- thumbnailStatus: createKeyedThumbnailStatusStore(),+ thumbnailStatus: createKeyedStatusStore<LayerThumbnailStatus>(),+ adjustmentStatus: createKeyedStatusStore<LayerAdjustmentStatus>(),transformSession: createScalarStore<TransformSession | null>(null, transformSessionEqual),+ pendingTransformLayerId: createScalarStore<string | null>(null),viewportReady: createScalarStore<boolean>(false),zoom: createScalarStore<number>(1),});diff --cc invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.tsindex 99cd223b93,0650dd6295..d8227bd1e1--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts@@@ -88,69 -63,3 +88,82 @@@ describe('resolveCanvasContextMenu', (expect(resolveCanvasContextMenuBranch(resolution.target, false)).toBe('global');});});++describe('hasCroppableLayers', () => {+ const documentWith = (nodes: CanvasNodeContract[]): CanvasDocumentContractV3 => ({+ ...createEmptyCanvasDocument(),+ stacks: stacksFrom(nodes),+ });++ it('finds a croppable leaf in any stack, hidden or disabled ones included', () => {+ expect(hasCroppableLayers(documentWith([layerContract('mask', 'inpaint_mask', { isEnabled: false })]))).toBe(true);+ expect(hasCroppableLayers(documentWith([groupContract('G', [layerContract('region', 'regional_guidance')])]))).toBe(+ true+ );+ });++ it('has nothing to crop when every leaf is locked by itself or by a group above it', () => {+ expect(hasCroppableLayers(documentWith([]))).toBe(false);+ expect(+ hasCroppableLayers(+ documentWith([+ layerContract('locked', 'raster', { isLocked: true }),+ groupContract('G', [layerContract('inside', 'control')], { isLocked: true }),+ ])+ )+ ).toBe(false);+ });+});++describe('cropAllLayersToFrame', () => {+ type CropResult = Awaited<ReturnType<Parameters<typeof cropAllLayersToFrame>[0]['cropAllLayersToBbox']>>;+ const notices = async (result: CropResult | Error) => {+ const notify = { error: vi.fn(), info: vi.fn(), success: vi.fn() };+ const cropAllLayersToBbox = () => (result instanceof Error ? Promise.reject(result) : Promise.resolve(result));+ await cropAllLayersToFrame({ cropAllLayersToBbox }, notify, i18n.t);+ return {+ error: notify.error.mock.calls,+ info: notify.info.mock.calls,+ success: notify.success.mock.calls,+ };+ };++ it.each([+ [{ cropped: 1, skippedLocked: 0 }, ['Cropped 1 layer to the frame', undefined]],+ [{ cropped: 4, skippedLocked: 1 }, ['Cropped 4 layers to the frame', '1 locked layer skipped']],+ [{ cropped: 2, skippedLocked: 3 }, ['Cropped 2 layers to the frame', '3 locked layers skipped']],+ ])('reports %o as cropped, with the locked layers it skipped', async (counts, expected) => {+ expect(await notices({ status: 'cropped', ...counts })).toEqual({ error: [], info: [], success: [expected] });+ });++ it('says nothing needed cropping, and that only unlocked layers were checked when some were skipped', async () => {+ expect((await notices({ skippedLocked: 0, status: 'nothing' })).info).toEqual([+ ['Every layer already fits the frame', undefined],+ ]);+ expect((await notices({ skippedLocked: 2, status: 'nothing' })).info).toEqual([+ ['Every unlocked layer already fits the frame', '2 locked layers skipped'],+ ]);+ });+++ it('names the layer whose adjustments prevented the crop', async () => {++ const result = await notices({++ ownerId: 'haze',++ ownerName: 'Haze',++ reason: 'too-large',++ status: 'adjustment-refused',++ });++ expect(result.error).toHaveLength(1);++ expect(result.error[0]?.[1]).toContain('Haze');++ expect(result.info).toEqual([]);++ expect(result.success).toEqual([]);++ });+++ it('explains refusals and a rejected crop with the shared layer notice', async () => {+ expect((await notices({ status: 'over-budget' })).error).toEqual([+ [i18n.t('widgets.layers.actions.actionFailed'), i18n.t('widgets.layers.actions.overBudget')],+ ]);+ expect((await notices(new Error('rejected'))).error).toEqual([+ [i18n.t('widgets.layers.actions.actionFailed'), i18n.t('widgets.layers.actions.operationFailed')],+ ]);+ });+});diff --cc invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.tsindex f4d56ac532,316f9c0661..c5573ba4fd--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts@@@ -58,49 -50,3 +58,52 @@@ export const resolveCanvasContextMenutarget: { layerId, x: clientX, y: clientY },};};++/** Whether Crop all layers to frame has a leaf to act on: one not locked by itself or a group above it. */+export const hasCroppableLayers = (document: CanvasDocumentContractV3): boolean => {+ const { byId, leaves } = getDocumentIndex(document);+ return leaves.some((leaf) => !leaf.isLocked && !byId.get(leaf.id)?.ancestorsLocked);+};++/**+ * Crops every unlocked layer to the frame as one undo step and says what happened: how many layers it cropped, how+ * many locked ones it skipped, or that nothing needed cropping. The canvas menu and the command share it.+ */+export const cropAllLayersToFrame = async (+ layers: Pick<CanvasEngineLayerCapability, 'cropAllLayersToBbox'>,+ notify: Pick<Notify, 'error' | 'info' | 'success'>,+ t: TFunction+): Promise<void> => {+ let result: Awaited<ReturnType<typeof layers.cropAllLayersToBbox>>;+ try {+ result = await layers.cropAllLayersToBbox();+ } catch {+ // The engine leaves every layer as it was when the transaction is rejected.+ result = { status: 'failed' };+ }+ switch (result.status) {+ case 'cropped':+ case 'nothing': {+ const skipped =+ result.skippedLocked > 0+ ? t('widgets.canvas.contextMenu.croppedAllLayersSkipped', { count: result.skippedLocked })+ : undefined;+ if (result.status === 'cropped') {+ notify.success(t('widgets.canvas.contextMenu.croppedAllLayers', { count: result.cropped }), skipped);+ } else {+ notify.info(+ t(+ skipped ? 'widgets.canvas.contextMenu.cropAllNothingUnlocked' : 'widgets.canvas.contextMenu.cropAllNothing'+ ),+ skipped+ );+ }+ return;+ }++ case 'adjustment-refused':++ reportLayerOperation(result, notify.error, t);++ return;+ default:+ reportLayerOperation(result.status, notify.error, t);+ }+};diff --cc invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex 0d378a5580,266efaf4a2..6d57e1e9ed--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@@ -88,8 -78,7 +88,8 @@@ const createEngine = (interaction: Partstatus: 'duplicated',})),+ beginTransform: vi.fn((): BeginTransformResult => 'started'),- mergeLayerDown: vi.fn((): MergeDownResult => 'merged'),+ mergeLayerDown: vi.fn((): Promise<MergeDownResult> => Promise.resolve('merged')),nudgeSelectedLayer: vi.fn(() => ({ status: 'committed' as const })),},selection: {diff --cc invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex a01d77e305,25d676abf2..db6b696b48--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@@ -1,5 -1,5 +1,6 @@@import type {+ BeginTransformResult,+ AdjustmentRefusal,CanvasDocumentContractV3,CanvasEngine,LayerStackMoveKind,@@@ -300,9 -92,9 +301,8 @@@ export interface CanvasHotkeyContext exreadonly engine: CanvasEngine | null;/** Any staging slot exists, so left/right cycle candidates instead of nudging. */readonly hasStagingSlots: boolean;- readonly reportLayerOperation: (refusal: LayerOperationRefusal) => void;/** A staged candidate is selected, so Delete discards it instead of touching layers. */readonly hasSelectedStagedCandidate: boolean;- readonly isInteractionLocked: boolean;readonly selectedLayerIds: readonly string[];readonly dispatch: CanvasProjectMutationDispatch;readonly copySelection: (cut: boolean) => void;diff --cc invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex f75efbbf39,241c490610..356a4e76b2--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@@ -414,25 -413,6 +422,27 @@@ const LayerMenu = (}}, [engine, layer, makeStatusError, projectId, selectedIds, t]);+ const handleRemoveFromGroup = useCallback(() => {+ const outcome = removeFromGroup(engine, actionTargets({ layer, selectedIds }), getActionLabel('remove-from-group'));+ if (outcome.status === 'refused') {+ throw makeStatusError(outcome.refusal.status === 'locked' ? 'locked' : 'unsupported');+ }+ }, [engine, getActionLabel, layer, makeStatusError, selectedIds]);++ const handleMergeMasks = useCallback(async () => {+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ const result = await engine.layers.mergeInpaintMasks(actionTargets({ layer, selectedIds }));- if (result.status === 'ineligible') {++ if (isAdjustmentRefusal(result)) {++ reportLayerOperation(result, notify.error, t);++ } else if (result.status === 'ineligible') {+ notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.mergeMasksIneligible'));+ } else if (result.status !== 'merged') {+ reportLayerOperation(result.status, notify.error, t);+ }+ }, [engine, layer, makeStatusError, notify, selectedIds, t]);+const handleMergeSelected = useCallback(() => {if (!engine) {return;diff --cc invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex c9f12d9d61,dd1ba1c19e..4682da4751--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@@ -110,8 -107,7 +110,8 @@@ const makeEffects = (): LayerContextActextractMaskedArea: vi.fn(() => Promise.resolve()),fitToBbox: vi.fn(),group: vi.fn(),- mergeDown: vi.fn(),+ mergeDown: vi.fn(() => Promise.resolve()),+ mergeMasks: vi.fn(),mergeSelected: vi.fn(),openProperties: vi.fn(),openRename: vi.fn(),@@@ -119,8 -115,7 +119,8 @@@startSelectObject: vi.fn(),startFilter: vi.fn(),patchConfig: vi.fn(),- rasterize: vi.fn(),+ rasterize: vi.fn(() => Promise.resolve()),+ removeFromGroup: vi.fn(),reorder: vi.fn(),setColorLabel: vi.fn(),saveToBoard: vi.fn(() => Promise.resolve()),diff --cc invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex c5392c5c49,ad12fdf4ae..2105dafaa9--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@@ -71,8 -73,11 +75,12 @@@ export type LayerContextActionId| 'add-hsl'| 'add-hue'| 'add-invert'+ | 'add-texture'+ | 'add-clarity'+ | 'add-dehaze'+ | 'add-noise-adjustment'| 'merge-selected'+ | 'merge-masks'| 'move-to-front'| 'move-forward'| 'move-backward'