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 branch 'main' into fix/canvas-v7-feedback
Josh Corbett06f73cf5ea4d
diff --cc docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdxindex 8710b8171c,767ac24af2..b9c0b9392c--- 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,22 -78,21 +82,23 @@@ 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** — 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 frame** — keeps only the part of the layer inside the generation frame. It refuses, saying why, a layer that is locked or inside a locked group, a layer that lies entirely outside the frame (cropping would leave it empty), and a layer whose image could not be read, for example because it was deleted from the Gallery.- * **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** — keeps only the part of the layer inside the generation frame. It refuses, saying why, a layer that is locked or inside a locked group, a layer that lies entirely outside the frame (cropping would leave it empty), and a layer whose image could not be read, for example because it was deleted from the Gallery. A cropped control layer keeps its **Type**, but its cropped map becomes its image: the original it was detected from is no longer kept, and **Detection** changes to **None**.+ * **Save layer to board** — saves the layer 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, 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).+ * **Use as control layer** — copies the layer's pixels to a new control layer, whose Properties then ask for its **Type**.* **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. 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**.+ * **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 a layer with adjustments to a control layer, or using it as one, bakes them, with the layer's scaling and rotation, into its pixels; undo restores the raster layer with its adjustments.+ * **Control layers:** **Transform**, **Select object**, **Run workflow**, **Enable transparent preview**, and **Convert to raster layer**. A control layer's map comes from its **Detection** row in Properties, so it has no **Filter**.* **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**.@@@ -159,7 -152,7 +160,7 @@@ Their settingsThings 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, cropping to the frame (one layer, or all layers when this one reaches past the frame), 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.-* **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.++* **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, converting to or using as a control layer, cropping to the frame (one layer, or all layers when this one reaches past the frame), 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.diff --cc invokeai/frontend/webv2/performance/browser-baseline.jsonindex 50dbacf2d3,0182034957..419f122313--- 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": 317101,+ "largestAssetRawBytes": 341949,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 548565,- "scriptRawBytes": 567866,++ "scriptRawBytes": 575614,"scriptRequestCount": 9,- "totalRawBytes": 548565- "totalRawBytes": 567866++ "totalRawBytes": 575614},"domContentLoadedMedianMs": 100.40000009536743,"id": "editor-canvas",@@@ -197,12 -197,12 +197,12 @@@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 317101,+ "largestAssetRawBytes": 341949,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 548565,- "scriptRawBytes": 567866,++ "scriptRawBytes": 575614,"scriptRequestCount": 9,- "totalRawBytes": 548565- "totalRawBytes": 567866++ "totalRawBytes": 575614},"domContentLoadedMedianMs": 97.7000002861023,"id": "editor-canvas",@@@ -1381,8 -1381,9 +1381,10 @@@"source:src/workbench/canvas-engine/color.ts","source:src/workbench/canvas-engine/contracts.ts","source:src/workbench/canvas-engine/controllers/booleanMergeController.ts",+ "source:src/workbench/canvas-engine/controllers/colorSampleController.ts",+ "source:src/workbench/canvas-engine/controllers/controlDerivationController.ts","source:src/workbench/canvas-engine/controllers/controlPixelController.ts",+ "source:src/workbench/canvas-engine/controllers/controlViewController.ts","source:src/workbench/canvas-engine/controllers/copyLayerController.ts","source:src/workbench/canvas-engine/controllers/cropLayerController.ts","source:src/workbench/canvas-engine/controllers/editSteps.ts",@@@ -2497,8 -2505,9 +2507,10 @@@"source:src/workbench/canvas-engine/color.ts","source:src/workbench/canvas-engine/contracts.ts","source:src/workbench/canvas-engine/controllers/booleanMergeController.ts",+ "source:src/workbench/canvas-engine/controllers/colorSampleController.ts",+ "source:src/workbench/canvas-engine/controllers/controlDerivationController.ts","source:src/workbench/canvas-engine/controllers/controlPixelController.ts",+ "source:src/workbench/canvas-engine/controllers/controlViewController.ts","source:src/workbench/canvas-engine/controllers/copyLayerController.ts","source:src/workbench/canvas-engine/controllers/cropLayerController.ts","source:src/workbench/canvas-engine/controllers/editSteps.ts",@@@ -3069,7 -3090,8 +3097,8 @@@"source:src/workbench/widgets/layers/runLayerWorkflow.ts","source:src/workbench/widgets/layers/selectedModel.ts","source:src/workbench/widgets/layers/useAddLayer.ts",- "source:src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts",+ "source:src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts",+ "source:src/workbench/widgets/layers/useControlSourceActions.ts","source:src/workbench/widgets/layers/useLayerSelectionCommands.ts","source:src/workbench/widgets/layers/useLayerStackActions.ts","source:src/workbench/widgets/layers/useSelectedMainModel.ts",@@@ -3840,8 -3862,9 +3869,10 @@@"source:src/workbench/canvas-engine/color.ts","source:src/workbench/canvas-engine/contracts.ts","source:src/workbench/canvas-engine/controllers/booleanMergeController.ts",+ "source:src/workbench/canvas-engine/controllers/colorSampleController.ts",+ "source:src/workbench/canvas-engine/controllers/controlDerivationController.ts","source:src/workbench/canvas-engine/controllers/controlPixelController.ts",+ "source:src/workbench/canvas-engine/controllers/controlViewController.ts","source:src/workbench/canvas-engine/controllers/copyLayerController.ts","source:src/workbench/canvas-engine/controllers/cropLayerController.ts","source:src/workbench/canvas-engine/controllers/editSteps.ts",diff --cc invokeai/frontend/webv2/public/locales/en.jsonindex 2484376867,d2869ea7f7..3eecedf568--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@@ -3665,8 -3638,25 +3662,26 @@@"shape": "Shape","text": "Text","transform": "Transform",- "view": "View"+ "view": "View",+ "withHotkey": "{{label}} ({{hotkey}})"+ },+ "controlHint": {+ "title": "Drop an image here",+ "body": "or pick one in Properties",+ "uploading": "Uploading…"+ },+ "fileDrop": {+ "oneFile": "Drop one image at a time.",+ "notImage": "Only image files can be dropped on the canvas.",+ "noTarget": "Select an empty control layer to drop an image on it."+ },+ "controlView": {+ "label": "Control layer view",+ "original": "Original",+ "map": "Map",+ "overlay": "Overlay",+ "failed": "Couldn't show the original image",+ "overBudget": "Not enough canvas memory to show the original image"}},"workflow": {@@@ -3983,15 -3970,7 +3997,16 @@@"addDenoiseLimit": "Add denoise limit","addNoise": "Add noise","addRegenerateRegion": "Add regenerate region",+ "addRegenerateRegionDescription": "Regenerate where this layer has content, as a live inpaint mask.",+ "canvasNotReady": "The canvas is still starting. Try again in a moment.",+ "interactionLocked": "Unavailable while the canvas is generating, has staged results, or is applying an edit.",+ "mergeMasks": "Merge masks",+ "mergeMasksIneligible": "Merge masks needs two or more enabled, unlocked inpaint masks with content.",+ "mergeMasksSettingsDiffer": "The masks have different noise or denoise settings. Match them to merge.",+ "removeFromGroup": "Remove from group",+ "removeFromGroupLocked": "Unlock the layer and the groups that contain it first.",- "transformIneligible": "Transform works on enabled raster and control layers with content."++ "transformIneligible": "Transform works on enabled raster and control layers with content.",+ "useAsControlLayer": "Use as control layer"},"control": {"apply": "Apply",diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 7721b5c435,a8bb912056..43dafeb518--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@@ -67,19 -67,17 +67,21 @@@ Current extracted ownership includes- `RasterMemoryBudgetController`: base, derived, group, decoded, detached, reserved and overage byte accounting plus generation-scoped reservations and operation-owned reservations and pins.- `RenderController`: render targets, scheduler construction, previews, render lifecycle.- `HistoryController`: engine-owned history, guarded async replay with failure reporting, inactive byte trimming.- - `PersistenceController`: dirty-bitmap flush barriers and disposal.+ - `PersistenceController`: dirty-bitmap flush barriers (whole document, or one layer through `applicationHost.flushLayerUploads`) and disposal.- `EditingController`: selection state and exclusive edit-lease lifecycle.+- `TransformEditingController` (under `EditingController`): transform sessions, previews, parameter commits and paint bakes, plus `layers.beginTransform` and the wait of a session requested before its layer's pixels persist. It alone decides when that wait opens a session or ends; `engine.ts` routes it document changes, tool switches, Escape, replays, document replacement and final upload failures.+- `ColorSampleController`: one-shot color requests and the workbench color router, and which of them receives each pick.+- `PaintLineEndController`: where the last brush or eraser stroke ended on each layer, followed through the layer's changes (see "Input ownership and frame scheduling").- `InteractionController`: public tool commands and their disposal boundary.- `LayerController`: guarded layer mutations and thumbnail capability ports.-- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases.+- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases. A rasterization that failed because the source cannot be read reports a `LayerUnreadable` refusal (`layerExportGuards.ts`) carrying the layer's id and name, never `not-ready`: waiting cannot fix it, so every consumer (crop, merges, boolean merges, copies, conversion, extraction, duplicate, filter, Select Object, Run Workflow, snapshots for generation and PSD, composite export) refuses with it instead of asking the user to retry, and the message names the layer to disable, delete or replace. An operation reading several layers names the first that failed in its read order; crop all lists each one it skipped. Unreadable means the image resolver threw `CanvasImageMissingError` (the `ImageResolver` contract: the image is missing, or not readable by this user; the production resolver maps 403, 404 and 410 to it), the fetched image did not decode, or rendering threw. Any other resolver failure (network, server, an expired session) is wrapped as `ImageUnavailableError` and is transient: operations and readiness gates report `not-ready`, and crop all refuses the whole crop as `not-ready` instead of skipping the layer. The rasterizer remembers either failure per cache entry, keyed by cache version, document generation and source, with its kind, and a retry of the same source that fails again with the same kind raises no second error notice; a change of kind (a fetch outage that turns out to be a deleted image) is reported, with the `ImageUnavailableError` itself (naming the image, the resolver's error as its cause) for a transient one. Two questions read that record. `getFailure` (the kind recorded for the layer's current key) drives the readiness gates that never rasterize themselves (Merge Down, boolean merges, extraction): they answer unreadable for as long as an `unreadable` failure holds, and `not-ready` for an `unavailable` one. `isBackingOff` (either failure's retry backoff, 3 s doubling per repeated failure up to 60 s, is still running) drives the compositor, which skips the layer meanwhile instead of reading its image every frame; the backoff's end invalidates the layer, so a displayed layer retries on its own. A readiness gate asked about a layer also retries it in the background while it answers from the record (a layer off screen or disabled is never redrawn to do so): at once for an `unavailable` failure, so trying again after an outage ends fetches without waiting out the backoff, and only once the backoff is over for an `unreadable` one. A running job is joined, never duplicated. Explicit operations (crop, export, merges) always try again. A retry that fails again restarts the backoff without a second notice; a success or any change to the layer clears the failure. Thumbnails show `error` for both kinds.- `PsdExportController`: immutable PSD planning, snapshot capture, reservation, execution, cancellation.- `StagedResultController`: guarded staged-candidate acceptance and its history entry.-- `PixelEditController`, `SelectionImageController`, `LayerMutationController`: atomic pixel/document publication at their respective boundaries. Pixel editor materializes control layers and raster-image layers in place before destructive edits, keeping conversion plus pixels in one undoable transaction.+- `PixelEditController`, `SelectionImageController`, `LayerMutationController`: atomic pixel/document publication at their respective boundaries. Pixel editor materializes control layers and raster-image layers in place before destructive edits (brush and eraser alike), keeping conversion plus pixels in one undoable transaction.+- `CropLayerController`: crops one layer, or every leaf of every stack, to the frame; crop-all is one entry. Both paths share one eligibility rule: a leaf locked by itself or an ancestor, or with a source the export cannot bake, is never cropped. A single crop refuses such a leaf, an `unreadable` one, and one wholly outside the frame (`outside-frame`: the explicit crop would empty it). Crop all first crosses the paint-upload barrier (`flushPendingPixels`, not waiting for held pixels), so an acknowledgement replacing a just-painted leaf cannot land mid-read and refuse it as `stale`. It skips locked and unreadable leaves when their contract's content reaches past the frame, counting the locked ones (`skippedLocked`) and listing the unreadable ones in document order (`skippedUnreadable`), so the result can say what was left alone, by name, even when nothing was cropped, and one leaf that cannot be read never blocks the rest; a leaf already inside the frame, empty or unsupported is left alone; a leaf wholly outside is emptied in place, so ids, order, groups and flags never change. It reads one leaf at a time through a read lease, copies the cropped pixels into a surface under their own raster reservation and releases the lease before the next leaf, so the peak is the cropped set plus one export; it refuses `stale` when the stacks, frame or any pixel guard moved meanwhile, admits one history entry for every before and after snapshot, and publishes one `replaceCanvasLayers` (same-id, same-type leaves, refused whole when any entry is invalid). `MergeLayerController` merges selected leaves into a new one through one pipeline parameterized by eligibility, result stack, result leaf and label: merge-selected flattens a contiguous raster run into a paint layer, merge-masks unions any inpaint masks' coverage (each at full alpha, since a mask's opacity only tints it on screen) into a mask configured like the topmost source.- `MaskResultController`, `FilterResultController`, `GeneratedResultController`: guarded application-result adoption through narrow host ports.+ - `ControlDerivationController`: control-layer intent patches and detected-map commits (see "Control derivation").+ - `ControlViewController`: the display-only Original / Overlay view of one control layer (see "Control layer view").Controller-local tests instantiate these boundaries with fakes. Integration tests in `engine.test.ts` cover composition, document routing, cross-controller invariants.diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.tsindex 4264ca4c28,981e6973c7..1736e29317--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts@@@ -15,7 -16,7 +16,8 @@@ import typeCommitMaskImageResult,CommitMaskImageResultOptions,} from '@workbench/canvas-engine/controllers/maskResultController';+ import type { LayerFlushOptions, LayerFlushResult } from '@workbench/canvas-engine/controllers/persistenceController';+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';import type { CanvasCompositeExecutorDeps } from '@workbench/canvas-engine/rasterTransactions';import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 68359e2cd4,b9e9de7e02..1e1c8459d9--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@@ -698,12 -717,20 +777,22 @@@ export interface CanvasEngineExportCapaextractMaskedArea(maskLayerId: string): Promise<ExtractMaskedAreaResult>;}+ /** How a control layer displays: its detected map (the default), the kept original, or the original under the map. */+ export type ControlLayerViewMode = 'original' | 'map' | 'overlay';++ /**+ * `missing`: no control layer with a kept original; `locked`: an operation or a generation holds the canvas;+ * `stale`: a newer request or an edit of the layer superseded it; `over-budget`: the original's pixels do not fit the+ * raster budget; `failed`: the original could not be decoded.+ */+ export type ControlLayerViewOutcome = 'shown' | 'missing' | 'locked' | 'stale' | 'over-budget' | 'failed';+export interface CanvasEnginePreviewCapability extends CanvasPreviewCapability {/**- * Sizes `target` and draws the whole document fitted to `maxSizePx`. Returns its drawn rect, or null without a- * document.+ * Sizes `target` to fit `maxSizePx` (never above 1:1) and draws the committed document's extent into it: the frame+ * joined with every enabled renderable layer's bounds, the same extent `fitToView` fits. Returns that+ * document-space rect, which the caller maps between target pixels and document space with (target pixel =+ * (document point - rect origin) * target.width / rect.width); null without a document or 2D context.*/drawDocumentOverview(target: HTMLCanvasElement, maxSizePx: number): Rect | null;preloadStagedPreview(imageName: string): void;diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.tsindex 02f24721e2,32bf5ebb81..0d9c68f4d5--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts@@@ -100,6 -80,38 +100,39 @@@ describe('CropLayerController', () =>expect(h.layers.get('paint')?.rect).toEqual(BBOX);});+ it("keeps a control layer's type but drops the original its cropped pixels no longer derive from", async () => {+ const depth = { settings: {}, type: 'depth_anything_depth_estimation' };- const h = createHarness(undefined, {++ const control: CanvasLayerContract = {+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'normal',+ controlType: 'depth',+ detection: depth,+ filter: depth,+ id: 'paint',+ isEnabled: true,+ isLocked: false,+ name: 'Depth 1',+ opacity: 1,+ original: { image: { height: 50, imageName: 'photo', width: 50 }, type: 'image' },+ originalTransform: { rotation: 0, scaleX: 1, scaleY: 1, x: 2, y: 2 },+ source: { bitmap: { height: 50, imageName: 'map', width: 50 }, offset: { x: -10, y: -10 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: true,- });++ };++ const h = createHarness(undefined, { nodes: [control] });++ await expect(h.controller.crop('paint')).resolves.toEqual({ status: 'cropped' });+ const cropped = getDocumentLayer(h.document(), 'paint');+ expect(cropped).toMatchObject({ controlType: 'depth', detection: null });+ expect(cropped).not.toHaveProperty('original');+ expect(cropped).not.toHaveProperty('originalTransform');+ expect(cropped).not.toHaveProperty('filter');++ await h.history.undo();+ expect(getDocumentLayer(h.document(), 'paint')).toEqual(h.original);+ });+it('refuses a crop it could never undo before anything changes', async () => {const h = createHarness(1024);const before = h.document();@@@ -149,411 -132,3 +182,421 @@@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 CLARITY: CanvasAdjustmentsContract = [{ amount: 90, id: 'clarity', isEnabled: true, size: 8, type: 'clarity' }];++const createCropAllHarness = (+ options: {+ /** Raster leaves carrying a Clarity stack. */+ adjusted?: readonly string[];+ historyBytes?: number;+ onExport?: (layerId: string) => void;+ /** Refuses the owner's bake; its raw export still succeeds. */+ refusal?: AdjustmentRefusal;+ /** Leaves added on top whose pixels cannot be read. */+ unreadable?: readonly CanvasLayerContract[];+ /** Leaves whose pixels are not ready (still loading, or their image could not be fetched for now). */+ notReady?: readonly string[];+ /** Settles pending paint uploads; resolves at once by default. */+ flushPendingPixels?: () => Promise<void>;+ } = {}+) => {+ const raster = (id: string) =>+ layerContract(+ id,+ 'raster',+ options.adjusted?.includes(id) ? ({ adjustments: CLARITY } as Partial<CanvasLayerContract>) : {}+ );+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: FRAME,+ height: 100,+ selectedLayerId: 'raster',+ stacks: stacksFrom([+ ...(options.unreadable ?? []),+ raster('inside'),+ raster('raster'),+ lockedPaint('locked'),+ lockedPaint('lockedInside'),+ groupContract('lockedGroup', [lockedPaint('lockedByGroup', false)], { isLocked: true }),- layerContract('control', 'control', { isEnabled: false }),++ // A depth layer keeping the original its map was detected from.++ layerContract('control', 'control', {++ controlType: 'depth',++ detection: { settings: {}, type: 'depth_anything_depth_estimation' },++ isEnabled: false,++ original: { image: { height: 20, imageName: 'photo.png', width: 20 }, type: 'image' },++ } as Partial<CanvasLayerContract>),+ 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);+ }+ // Raw reads of adjusted leaves are recorded as `<id>:raw`.+ 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, exportOptions) => {+ const read = exportOptions?.applyAdjustments === false ? `${layerId}:raw` : layerId;+ exported.push(read);+ options.onExport?.(layerId);+ const unreadable = options.unreadable?.find((leaf) => leaf.id === layerId);+ if (unreadable) {+ return Promise.resolve({ layerId, layerName: unreadable.name, status: 'unreadable' as const });+ }+ if (options.notReady?.includes(layerId)) {+ return Promise.resolve({ status: 'not-ready' as const });+ }+ if (options.refusal?.ownerId === layerId && read === 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(read);+ },+ status: 'ok' as const,+ surface: entry.surface,+ });+ },+ flushPendingPixels: options.flushPendingPixels ?? (() => Promise.resolve()),+ 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 of a leaf it must crop, releasing earlier copies',+ async (reason) => {+ const refusal: AdjustmentRefusal = {+ ownerId: 'raster',+ ownerName: 'Raster',+ reason,+ status: 'adjustment-refused',+ };+ const h = createCropAllHarness({ adjusted: ['raster'], refusal });++ await expect(h.controller.cropAll()).resolves.toEqual(refusal);+ // The raw read shows the leaf reaches past the frame, so its stack must run.+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw', 'raster']);+ expect(h.released).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw']);+ expect(h.document()).toBe(h.original);+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ expect(h.reservedBytes()).toBe(0);+ }+ );++ it('never runs the stack of an adjusted leaf already inside the frame', async () => {+ const refusal: AdjustmentRefusal = {+ ownerId: 'inside',+ ownerName: 'Inside',+ reason: 'too-large',+ status: 'adjustment-refused',+ };+ const h = createCropAllHarness({ adjusted: ['inside'], refusal });++ await expect(h.controller.cropAll()).resolves.toEqual({+ cropped: 4,+ skippedLocked: 2,+ skippedUnreadable: [],+ status: 'cropped',+ });+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside:raw', 'raster']);+ expect(getDocumentLayer(h.document(), 'inside')).toBe(getDocumentLayer(h.original, 'inside'));+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ expect(h.reservedBytes()).toBe(0);+ });++ it('bakes an adjusted leaf it must crop, after releasing its raw read', async () => {+ const h = createCropAllHarness({ adjusted: ['raster'] });++ await expect(h.controller.cropAll()).resolves.toEqual({+ cropped: 4,+ skippedLocked: 2,+ skippedUnreadable: [],+ status: 'cropped',+ });+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw', 'raster']);+ // The raw read is released before the bake reserves, so the peak stays 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.at(-1)).toBe(croppedRegion + croppedControl + bytes(CACHE_RECTS.raster!));+ expect(getDocumentLayer(h.document(), 'raster')).not.toHaveProperty('adjustments');+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ 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,+ skippedUnreadable: [],+ 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({++ controlType: 'depth',++ detection: null,+ isEnabled: false,+ source: { offset: { x: 5, y: 5 } },+ });++ // The cropped map no longer derives from the original, so the original goes; undo brings it back.++ expect(getDocumentLayer(cropped, 'control')).not.toHaveProperty('original');+ 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('skips leaves whose pixels cannot be read and crops the rest, naming those that reach past the frame', async () => {+ /** An image layer whose decode failed; its contract still says where its content lies. */+ const unreadableImage = (id: string, name: string, x: number) =>+ layerContract(id, 'raster', {+ name,+ source: { image: { height: 10, imageName: `${id}.png`, width: 10 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y: 0 },+ } as Partial<CanvasLayerContract>);+ const h = createCropAllHarness({+ unreadable: [+ unreadableImage('gone', 'Sky', 15),+ unreadableImage('goneInside', 'Inside sky', 5),+ unreadableImage('goneLeft', 'Hills', -5),+ ],+ });++ await expect(h.controller.cropAll()).resolves.toEqual({+ cropped: 4,+ skippedLocked: 2,+ skippedUnreadable: [+ { layerId: 'gone', layerName: 'Sky', status: 'unreadable' },+ { layerId: 'goneLeft', layerName: 'Hills', status: 'unreadable' },+ ],+ status: 'cropped',+ });+ expect(h.exported).toEqual(['mask', 'region', 'control', 'gone', 'goneInside', 'goneLeft', 'inside', 'raster']);+ expect(getDocumentLayer(h.document(), 'gone')).toBe(getDocumentLayer(h.original, 'gone'));+ expect(getDocumentLayer(h.document(), 'raster')).not.toBe(getDocumentLayer(h.original, 'raster'));+ expect(h.history.entries().past).toEqual(['Crop all layers to frame']);+ });++ it('refuses as not ready, without skipping, when a leaf it must read is not ready', async () => {+ const h = createCropAllHarness({ notReady: ['control'] });++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'not-ready' });+ expect(h.document()).toBe(h.original);+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ expect(h.reservedBytes()).toBe(0);+ });++ it('settles pending paint uploads before it reads any leaf', async () => {+ let settle!: () => void;+ const h = createCropAllHarness({+ flushPendingPixels: () =>+ new Promise<void>((resolve) => {+ settle = resolve;+ }),+ });++ const crop = h.controller.cropAll();+ await Promise.resolve();+ expect(h.exported).toEqual([]);+ settle();++ await expect(crop).resolves.toMatchObject({ cropped: 4, status: 'cropped' });+ });++ 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,+ skippedUnreadable: [],+ 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 3e7a163663,08f7281ed1..69ee3836d4--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@@ -10,12 -8,11 +10,13 @@@ import type { AdjustmentRefusal } fromimport type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+ import { detachControlDerivation } from '@workbench/canvas-engine/document/controlDerivation';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';-import { renderableSourceOf } from '@workbench/canvas-engine/document/sources';+import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';-import { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';+import { intersect, isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';+import { isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';import type { CanvasMutationContext, EditStep } from './mutationContext';@@@ -101,71 -64,7 +102,72 @@@ export interface CropLayerControllerOptconst failedCrop: CropLayerResult = { message: 'The crop could not be applied.', status: 'failed' };-/** Owns guarded crop-to-bbox conversion and replayable pixel snapshots. */+/**+ * Whether a crop may change `leaf`, asked by single crop and crop all alike: never when it or a group above it is+ * locked, and only for a source the export can bake.+ */+const cropEligibility = (+ leaf: SemanticLeaf,+ isSupportedSource: (source: CanvasLayerSourceContract) => boolean+): 'eligible' | 'locked' | 'unsupported' => {+ if (leaf.effectiveLocked) {+ return 'locked';+ }+ const source = renderableSourceOf(leaf.layer);+ return source && isSupportedSource(source) ? 'eligible' : 'unsupported';+};++/**+ * The contract of `layer` cropped to `rect`: its baked pixels now sit at `rect` in a paint source (or mask bitmap) with+ * an identity transform, so transform, raster adjustments and control filter no longer apply. The bitmap is+ * written by persistence once the cropped pixels land.+ */+const croppedLayerContract = (layer: CanvasLayerContract, rect: Rect): CanvasLayerContract => {+ const before = structuredClone(layer);+ const identity = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };+ const offset = { x: rect.x, y: rect.y };+ if (before.type === 'raster') {+ const { adjustments: _adjustments, ...rest } = before;+ return { ...rest, source: { bitmap: null, offset, type: 'paint' }, transform: identity };+ }+ if (before.type === 'control') {++ // The cropped pixels become the image itself: no original's frame survives the crop.+ const { filter: _filter, ...rest } = before;- return { ...rest, source: { bitmap: null, offset, type: 'paint' }, transform: identity };++ return detachControlDerivation({ ...rest, source: { bitmap: null, offset, type: 'paint' }, transform: identity });+ }+ return { ...before, mask: { ...before.mask, bitmap: null, offset }, transform: identity };+};++/** `exported` pixels (placed at `exportedRect`) copied into a new surface covering exactly `rect`. */+const cropPixels = (backend: RasterBackend, exported: RasterSurface, exportedRect: Rect, rect: Rect): RasterSurface => {+ const cropped = backend.createSurface(rect.width, rect.height);+ if (rect.width > 0 && rect.height > 0) {+ cropped.ctx.setTransform(1, 0, 0, 1, 0, 0);+ cropped.ctx.clearRect(0, 0, rect.width, rect.height);+ cropped.ctx.drawImage(exported.canvas, exportedRect.x - rect.x, exportedRect.y - rect.y);+ }+ return cropped;+};++/** What crop all makes of one leaf's export. */+type CropExport = Extract<ExportResult, { status: 'ok' }> | { status: 'skip' } | LayerUnreadable | CropAllLayersResult;++/** One leaf's crop: its contract and pixels before and after. */+interface LayerCrop {+ readonly before: CanvasLayerContract;+ readonly beforePixels: LayerPixels;+ readonly after: CanvasLayerContract;+ readonly afterPixels: LayerPixels;+}++/** A leaf's cropped pixels, copied out of its export under their own reservation, so the export is already released. */+interface CroppedLeaf {+ readonly layer: CanvasLayerContract;+ readonly pixels: LayerPixels;+ readonly reservation: { release(): void };+}++/** Owns guarded crop-to-frame conversion, of one layer or all of them, and replayable pixel snapshots. */export class CropLayerController {private disposed = false;constructor(private readonly deps: CropLayerControllerOptions) {}diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.tsindex fca5eba3bc,90b79e5818..68eb02fdfe--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts@@@ -1,7 -1,6 +1,7 @@@- import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+ import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { ToolId } from '@workbench/canvas-engine/types';import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';@@@ -218,177 -186,78 +220,251 @@@ describe('TransformEditingController',expect(h.history.entries().past).toEqual(['Transform layer']);expect(h.calls.restoreCache).toHaveBeenCalledOnce();});++ it("moves a detected control layer's original with the baked map, in the same undo step", async () => {+ const depth = { settings: {}, type: 'depth_anything_depth_estimation' };+ const originalTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 2, y: 3 };+ const detected: CanvasControlLayerContract = {+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'normal',+ controlType: 'depth',+ detection: depth,+ filter: depth,+ id: 'control',+ isEnabled: true,+ isLocked: false,+ name: 'Depth 1',+ opacity: 1,+ original: { image: { height: 4, imageName: 'photo', width: 4 }, type: 'image' },+ originalTransform,+ source: { bitmap: { height: 4, imageName: 'map.png', width: 4 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 0 },+ type: 'control',+ withTransparencyEffect: true,+ };+ const applied = { rotation: 0, scaleX: 2, scaleY: 2, x: 12, y: 4 };+ const h = createHarness(detected);+ h.controller.begin('control');+ h.controller.update(applied);+ h.controller.apply();++ const baked = h.layer() as CanvasControlLayerContract;+ expect(baked.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });+ expect(baked).toMatchObject({ controlType: 'depth', detection: depth, original: detected.original });+ // Re-detection and "None" both land the original where the applied transform put it.+ const placed = composeLayerTransforms(applied, originalTransform);+ expect(restoreControlOriginal(baked).transform).toEqual(placed);+ const map = { image: { height: 4, imageName: 'next-map', width: 4 }, rect: { height: 4, width: 4, x: 0, y: 0 } };+ expect(withDetectedMap(baked, map, depth)?.transform).toEqual(placed);+ expect(h.history.entries().past).toEqual(['Transform layer']);++ await h.history.undo();+ expect(h.layer()).toEqual(detected);+ });++ it('holds the original a shearing bake detaches, so undo can restore it', async () => {+ const depth = { settings: {}, type: 'depth_anything_depth_estimation' };+ const detected: CanvasControlLayerContract = {+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'normal',+ controlType: 'depth',+ detection: depth,+ filter: depth,+ id: 'control',+ isEnabled: true,+ isLocked: false,+ name: 'Depth 1',+ opacity: 1,+ original: { image: { height: 4, imageName: 'photo', width: 4 }, type: 'image' },+ originalTransform: { rotation: Math.PI / 4, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ source: { bitmap: { height: 4, imageName: 'map.png', width: 4 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: true,+ };+ const h = createHarness(detected);+ h.controller.begin('control');+ h.controller.update({ rotation: 0, scaleX: 2, scaleY: 1, x: 0, y: 0 });+ h.controller.apply();++ expect(h.layer()).not.toHaveProperty('original');+ expect(h.layer()).toMatchObject({ detection: null });+ expect(h.history.heldAssetRefs().images).toContain('photo');++ await h.history.undo();+ expect(h.layer()).toEqual(detected);+ });});++describe('TransformEditingController.request', () => {+ const persistedPaint = (id: string) =>+ layerContract(id, 'raster', {+ source: { bitmap: { height: 4, imageName: `${id}.png`, width: 4 }, type: 'paint' },+ } as Partial<CanvasLayerContract>);+ const a = persistedPaint('a');+ const b = persistedPaint('b');++ it('selects the layer, enters the tool and opens its session', () => {+ const h = createHarness([a, b]);++ expect(h.controller.request('b')).toBe('started');+ expect(h.document()?.selectedLayerId).toBe('b');+ expect(h.calls.enterTool).toHaveBeenCalledOnce();+ expect(h.session()?.layerId).toBe('b');+ expect(h.pending()).toBeNull();+ });++ it('cancels a session on another layer, dropping its preview, before opening one on the target', () => {+ const h = createHarness([a, b]);+ h.controller.begin('a');+ h.controller.update(MOVED);++ expect(h.controller.request('b')).toBe('started');+ expect(h.calls.setOverride).toHaveBeenCalledWith('a', null);+ expect(h.session()).toMatchObject({ layerId: 'b', transform: { scaleX: 1, x: 0, y: 0 } });+ // The abandoned preview on `a` never landed.+ expect(getDocumentLayer(h.document(), 'a')?.transform.x).toBe(0);+ });++ it.each([+ ['a locked leaf', { ...b, isLocked: true }, 'locked'],+ ['a mask', layerContract('b', 'inpaint_mask'), 'ineligible'],+ ['a missing leaf', null, 'missing'],+ ] as const)('refuses %s without selecting or switching tools', (_, target, status) => {+ const h = createHarness(target ? [a, target] : [a]);++ expect(h.controller.request('b')).toBe(status);+ expect(h.calls.select).not.toHaveBeenCalled();+ expect(h.calls.enterTool).not.toHaveBeenCalled();+ expect(h.session()).toBeNull();+ expect(h.pending()).toBeNull();+ });++ it.each([+ ['interaction is locked', (s: HarnessState) => (s.interactionLocked = true)],+ ['a gesture runs', (s: HarnessState) => (s.gesture = true)],+ ['a float is live', (s: HarnessState) => (s.floating = true)],+ ['document edits are locked', (s: HarnessState) => (s.canEdit = false)],+ ])('refuses as busy while %s, leaving the selection and tool unchanged', (_, lock) => {+ const h = createHarness([a, b]);+ lock(h.state);++ expect(h.controller.request('b')).toBe('busy');+ expect(h.calls.select).not.toHaveBeenCalled();+ expect(h.calls.enterTool).not.toHaveBeenCalled();+ expect(h.session()).toBeNull();+ });++ it('refuses as busy once disposed', () => {+ const h = createHarness([a, b]);+ h.controller.dispose();+ h.controller.dispose();++ expect(h.controller.request('b')).toBe('busy');+ expect(h.calls.select).not.toHaveBeenCalled();+ });+});++describe('TransformEditingController pending transform', () => {+ /** A paint layer whose only pixels are a stroke persistence has not acknowledged yet. */+ const unpersisted = layerContract('stroke', 'raster');+ const other = layerContract('other', 'raster', {+ source: { bitmap: { height: 4, imageName: 'other.png', width: 4 }, type: 'paint' },+ } as Partial<CanvasLayerContract>);++ const requestUnpersisted = () => {+ const h = createHarness([unpersisted, other]);+ expect(h.controller.request('stroke')).toBe('started');+ expect(h.session()).toBeNull();+ expect(h.pending()).toBe('stroke');+ const persist = () => {+ h.dispatch({+ id: 'stroke',+ source: { bitmap: { height: 4, imageName: 'stroke.png', width: 4 }, type: 'paint' },+ type: 'updateCanvasLayerSource',+ });+ h.controller.onDocumentChanged();+ };+ return { ...h, persist };+ };++ it('opens the session once the pixels are persisted, and not before', () => {+ const h = requestUnpersisted();+ h.controller.onDocumentChanged();+ expect(h.pending()).toBe('stroke');++ h.persist();+ expect(h.session()?.layerId).toBe('stroke');+ expect(h.pending()).toBeNull();+ });++ it('keeps waiting through a switch to the transform tool itself', () => {+ const h = requestUnpersisted();+ h.controller.onToolSwitch('transform');+ h.persist();+ expect(h.session()?.layerId).toBe('stroke');+ });++ it.each([+ ['a tool switch', (h: ReturnType<typeof requestUnpersisted>) => h.controller.onToolSwitch('brush')],+ ['Escape', (h: ReturnType<typeof requestUnpersisted>) => expect(h.controller.onEscape()).toBe(true)],+ ['a history replay', (h: ReturnType<typeof requestUnpersisted>) => h.controller.onReplay()],+ ['a document replacement', (h: ReturnType<typeof requestUnpersisted>) => h.controller.onDocumentReplaced()],+ [+ 'a selection change',+ (h: ReturnType<typeof requestUnpersisted>) => {+ h.dispatch({ id: 'other', type: 'setCanvasSelectedLayer' });+ h.controller.onDocumentChanged();+ h.dispatch({ id: 'stroke', type: 'setCanvasSelectedLayer' });+ },+ ],+ [+ 'leaving transform for a tool the user is on',+ (h: ReturnType<typeof requestUnpersisted>) => {+ h.state.tool = 'brush';+ h.controller.onDocumentChanged();+ h.state.tool = 'transform';+ },+ ],+ [+ 'another session opening',+ (h: ReturnType<typeof requestUnpersisted>) => {+ h.controller.begin('other');+ h.controller.onDocumentChanged();+ h.controller.cancel();+ },+ ],+ ['disposal', (h: ReturnType<typeof requestUnpersisted>) => h.controller.dispose()],+ ])('stops waiting on %s, silently', (_, end) => {+ const h = requestUnpersisted();+ end(h);+ expect(h.pending()).toBeNull();++ h.persist();+ expect(h.session()).toBeNull();+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();+ });++ it('stops waiting when the layer is removed', () => {+ const h = requestUnpersisted();+ h.dispatch({ ids: ['stroke'], type: 'removeCanvasLayers' });+ h.controller.onDocumentChanged();+ expect(h.pending()).toBeNull();+ });++ it('leaves Escape to the next handler when nothing waits', () => {+ const h = createHarness([other]);+ expect(h.controller.onEscape()).toBe(false);+ });++ it('reports not-ready when the waiting layer’s upload fails with no retry to follow', () => {+ const h = requestUnpersisted();+ h.controller.onUploadFailed('other');+ expect(h.pending()).toBe('stroke');+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();++ h.controller.onUploadFailed('stroke');+ expect(h.pending()).toBeNull();+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('not-ready');+ });+});diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.tsindex 672254d10a,45e9e2abb7..ada811455e--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts@@@ -1,24 -1,24 +1,29 @@@-import type { CanvasEditRefusal, StructuralCommitResult } from '@workbench/canvas-engine/capabilities';+import type {+ BeginTransformResult,+ CanvasEditRefusal,+ StructuralCommitResult,+} from '@workbench/canvas-engine/capabilities';- import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+ import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';-import type { Rect } from '@workbench/canvas-engine/types';+import type { Rect, ToolId } from '@workbench/canvas-engine/types';import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';+ import { rebaseControlOriginal } from '@workbench/canvas-engine/document/controlDerivation';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';- import { HISTORY_ENTRY_OVERHEAD_BYTES, NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';+ import {+ collectHistoryMediaRefs,+ HISTORY_ENTRY_OVERHEAD_BYTES,+ NO_HELD_ASSET_REFS,+ } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { hittableLayerSize } from '@workbench/canvas-engine/tools/moveHitTest';+import { isTransformEligible } from '@workbench/canvas-engine/tools/transformTool';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';import type { CanvasMutationContext, EditStep } from './mutationContext';@@@ -27,14 -27,10 +32,14 @@@ import { replaceLayerStep, rgbaBytes, wexport interface TransformEditingControllerOptions {readonly session: { get(): TransformSession | null; set(value: TransformSession | null): void };+ /** A requested session waiting for its layer's pixels to persist; see {@link TransformEditingController.request}. */+ readonly pending: { get(): string | null; set(value: string | null): void };readonly backend: RasterBackend;- readonly ctx: Pick<CanvasMutationContext, 'applyStep' | 'begin' | 'reserveRaster'>;+ readonly ctx: Pick<CanvasMutationContext, 'applyStep' | 'begin' | 'installPrepared' | 'reserveRaster'>;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getCache: (layerId: string) => LayerCacheEntry | null;+ /** The live cache extent, read without touching residency order. */+ readonly peekCacheRect: (layerId: string) => Rect | undefined;readonly setOverride: (layerId: string, transform: LayerTransform | null) => void;/** Installs whole-layer pixels at a layer-local rect, marking them painted and dirty. */readonly restoreCache: (layerId: string, rect: Rect, pixels: ImageData) => void;diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 98bc5430c2,45f0f25150..d661663b5f--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@@ -99,8 -95,9 +99,10 @@@ import type { CanvasProjectMutationPorimport { createItemId } from '@platform/browser/randomUuid';import { areJsonValuesStructurallyEqual } from '@platform/core/json';+import { ColorSampleController } from '@workbench/canvas-engine/controllers/colorSampleController';+ import { ControlDerivationController } from '@workbench/canvas-engine/controllers/controlDerivationController';import { PixelEditController } from '@workbench/canvas-engine/controllers/controlPixelController';+ import { ControlViewController } from '@workbench/canvas-engine/controllers/controlViewController';import { EditingController } from '@workbench/canvas-engine/controllers/editingController';import { FilterResultController } from '@workbench/canvas-engine/controllers/filterResultController';import { GeneratedResultController } from '@workbench/canvas-engine/controllers/generatedResultController';diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.tsindex 8c9cbe05c2,e21b5f9bbe..84e24e15c1--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts@@@ -53,9 -53,9 +53,10 @@@ const scene = (budgetBytes = SURFACE_BYdiagnostics,getAdjustedSurface: (layer, entry) => raster.getAdjustedSurface(layer, entry),getCheckerboardTile: () => backend.createSurface(1, 1),+ getControlView: () => null,getGroupSurface: (scope, members, matrices, content) => raster.groups.get(scope, members, matrices, content),getMaskPatternTile: () => null,+ hasStagedCandidates: () => false,layerCache: raster.layers,previews: new PreviewStateController(),raster,@@@ -123,9 -123,9 +124,10 @@@ describe('frame description over 2,000diagnostics: createCanvasDiagnostics(true),getAdjustedSurface: () => null,getCheckerboardTile: () => backend.createSurface(1, 1),+ getControlView: () => null,getGroupSurface: () => null,getMaskPatternTile: () => null,+ hasStagedCandidates: () => false,layerCache: raster.layers,previews: new PreviewStateController(),raster,diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.tsindex 0ab40ceaab,0696d76bcb..bc30afdd7b--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts@@@ -46,7 -46,7 +46,8 @@@ const documentOf = (layers: CanvasLayerinterface Harness {deps: CreateCompositeFrameDeps;+ controlView: ReturnType<CreateCompositeFrameDeps['getControlView']>;+ staging: { candidates: boolean };stores: ReturnType<typeof createEngineStores>;previews: PreviewStateController;overrides: Map<string, { x: number; y: number }>;@@@ -71,12 -71,10 +72,13 @@@ const makeHarness = (): Harness =>const rasterizeLayer = vi.fn();const beginFrame = vi.fn(() => FRAME_USAGE);const enforce = vi.fn(() => ({ evictedBaseLayerIds: [] as string[], overageBytes: 0 }));+ const staging = { candidates: false };- return {+ const harness: Harness = {beginFrame,+ controlView: null,+ staging,deps: {+ hasStagedCandidates: () => staging.candidates,backend: {} as CreateCompositeFrameDeps['backend'],derivedSurfaceCache: { byteSize: () => 0 } as CreateCompositeFrameDeps['derivedSurfaceCache'],diagnostics: {} as CreateCompositeFrameDeps['diagnostics'],diff --cc invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex e779cfa363,4b142a946b..e624898eee--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@@ -42,18 -42,12 +42,20 @@@ export interface CreateCompositeFrameDereadonly getGroupSurface: NonNullable<CompositeOptions['groupSurface']>;readonly getMaskPatternTile: (style: string, color: string) => RasterSurface | null;readonly getCheckerboardTile: () => RasterSurface;+ /** The control layer shown as its kept original, if any. */+ readonly getControlView: () => CompositeOptions['controlView'];/** Starts (or joins) the rasterization of a layer whose cache is stale. */readonly rasterizeLayer: (layer: CanvasLayerContract, doc: CanvasDocumentContractV3) => void;+ /** Whether the staging area holds a candidate, shown or not. */+ readonly hasStagedCandidates: () => boolean;}+/**+ * While a generation is staged (a candidate waits, or a staged or progress preview is published) masks and regions+ * stop tinting the screen, so the result reads as it would be accepted; control layers stay.+ */+const STAGING_OVERLAY_STACKS = { control: true, inpaint_mask: false, regional_guidance: false } as const;+export interface CompositeFrame {/** Composites the document onto the screen surface and enforces the surface budget. */draw(diff --cc invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.tsindex 0000000000,3ff6e42270..395424438fmode 000000,100644..100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.ts@@@ -1,0 -1,374 +1,376 @@@+ import type { AccountScope } from '@platform/state/accountLifecycle';+ import type {+ AdjustmentRefusal,+ CanvasDocumentCapability,+ CanvasDocumentContractV3,+ CanvasExportCapability,++ LayerUnreadable,+ } from '@workbench/canvas-engine/api';+ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+ import type { Project } from '@workbench/projectContracts';++ import { galleryTransfers, type GalleryImage } from '@features/gallery';+ import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+ } from '@platform/state/accountLifecycle';+ import { getDocumentLayer, lookupDocumentLeaf } from '@workbench/canvas-engine/api';+ import { getControlImageState } from '@workbench/canvasLayerContent';++ import type { ControlLayerIntentResult } from './operationTypes';++ import { uploadCanvasImage } from './backend/canvasImages';+ import { exportCanvasComposite, type CanvasCompositeExportEngine } from './exportCanvasComposite';+ import {+ importGalleryImagesToCanvas,+ type GalleryImportEngine,+ type ImportGalleryImagesResult,+ } from './importGalleryImages';+ import { getCanvasOperations } from './operationAccess';++ /** Where a control layer's image came from, when this canvas placed it: a file (by name) or the frame. */+ export type ControlSourceOrigin = { kind: 'file'; name: string } | { kind: 'frame' };++ export interface ControlSourceSnapshot {+ /** Control layers with an image upload on its way; another upload to one is refused until it lands. */+ readonly uploading: ReadonlySet<string>;+ /** Origins of images placed from a file or the frame, by image name; others are described by their size. */+ readonly origins: Readonly<Record<string, ControlSourceOrigin>>;+ }++ const EMPTY_SOURCE_SNAPSHOT: ControlSourceSnapshot = { origins: {}, uploading: new Set() };++ interface ControlSourceState {+ snapshot: ControlSourceSnapshot;+ readonly listeners: Set<() => void>;+ }++ // Kept per engine, as its operations are: an account or project switch replaces the engine, and this state with it.+ const sourceStates = new WeakMap<object, ControlSourceState>();++ const sourceStateOf = (engine: object): ControlSourceState => {+ let state = sourceStates.get(engine);+ if (!state) {+ state = { listeners: new Set(), snapshot: EMPTY_SOURCE_SNAPSHOT };+ sourceStates.set(engine, state);+ }+ return state;+ };++ const updateSourceState = (engine: object, next: (snapshot: ControlSourceSnapshot) => ControlSourceSnapshot) => {+ const state = sourceStateOf(engine);+ state.snapshot = next(state.snapshot);+ for (const listener of state.listeners) {+ listener();+ }+ };++ export const getControlSourceSnapshot = (engine: object): ControlSourceSnapshot =>+ sourceStates.get(engine)?.snapshot ?? EMPTY_SOURCE_SNAPSHOT;++ export const subscribeControlSourceSnapshot = (engine: object, listener: () => void): (() => void) => {+ const { listeners } = sourceStateOf(engine);+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ };++ const recordOrigin = (engine: object, imageName: string, origin: ControlSourceOrigin) =>+ updateSourceState(engine, (snapshot) => ({ ...snapshot, origins: { ...snapshot.origins, [imageName]: origin } }));++ const setUploading = (engine: object, layerId: string, uploading: boolean) =>+ updateSourceState(engine, (snapshot) => {+ const next = new Set(snapshot.uploading);+ if (uploading) {+ next.add(layerId);+ } else {+ next.delete(layerId);+ }+ return { ...snapshot, uploading: next };+ });++ export type UploadControlImageResult =+ | { status: 'applied'; result: ControlLayerIntentResult; imageName: string }+ /** Another upload to the layer is still on its way. */+ | { status: 'uploading' }+ /** The layer was empty when the upload started and is not now (drawn on, or no longer a control layer). */+ | { status: 'changed' }+ | { status: 'stale' }+ | { status: 'failed'; message: string };++ /**+ * Uploads an image file and makes it a control layer's image at the bbox origin (`replace-image`, which detects its+ * map), recording the file's name as the image's origin. The Properties Upload button and a file dropped on the+ * canvas share it. One upload per layer at a time; `onUploaded` runs once the file is stored, for the caller to+ * refresh the gallery it now appears in. A layer that was empty when the upload started must still be, so strokes+ * drawn meanwhile are never replaced; replacing an image the layer already had is what was asked for. The upload+ * stays with the account that started it.+ */+ export const uploadControlImageFile = async (options: {+ engine: {+ readonly document: Pick<CanvasDocumentCapability, 'getDocument'>;+ readonly exports: Pick<CanvasExportCapability, 'hasExportableLayerContent'>;+ };+ layerId: string;+ file: File;+ onUploaded?: (owner: AccountScope) => void;+ uploadImage?: typeof galleryTransfers.upload;+ }): Promise<UploadControlImageResult> => {+ const { engine, file, layerId, onUploaded, uploadImage = galleryTransfers.upload } = options;+ if (getControlSourceSnapshot(engine).uploading.has(layerId)) {+ return { status: 'uploading' };+ }+ const isEmptyControlLayer = (): boolean => {+ const document = engine.document.getDocument();+ const layer = document ? getDocumentLayer(document, layerId) : null;+ return (+ layer?.type === 'control' &&+ getControlImageState(layer, engine.exports.hasExportableLayerContent(layerId)) === 'empty'+ );+ };+ const wasEmpty = isEmptyControlLayer();+ const owner = captureAccountScope();+ setUploading(engine, layerId, true);+ try {+ const uploaded = await uploadImage(file, 'none', { signal: owner.signal });+ assertAccountScopeCurrent(owner);+ onUploaded?.(owner);+ if (wasEmpty && !isEmptyControlLayer()) {+ return { status: 'changed' };+ }+ const bbox = engine.document.getDocument()?.bbox;+ const result = getCanvasOperations(engine).applyControlLayerIntent(layerId, {+ image: { height: uploaded.height, imageName: uploaded.imageName, width: uploaded.width },+ kind: 'replace-image',+ // New images land at the bbox origin, as every other canvas import does.+ transform: bbox ? { rotation: 0, scaleX: 1, scaleY: 1, x: bbox.x, y: bbox.y } : undefined,+ });+ if (result === 'updated') {+ recordOrigin(engine, uploaded.imageName, { kind: 'file', name: file.name });+ }+ return { imageName: uploaded.imageName, result, status: 'applied' };+ } catch (error) {+ return isAccountScopeCurrent(owner)+ ? { message: error instanceof Error ? error.message : String(error), status: 'failed' }+ : { status: 'stale' };+ } finally {+ setUploading(engine, layerId, false);+ }+ };++ /** A notice for the user: locale keys for the title and message, or a message as the server gave it. */+ export interface ControlSourceNotice {+ kind: 'info' | 'error';+ titleKey: string;+ messageKey?: string;+ message?: string;+ }++ /** Why a control layer intent did not land; `updated`, `unchanged` and `missing` (the layer went away) say nothing. */+ export const getControlIntentNotice = (result: ControlLayerIntentResult): ControlSourceNotice | null => {+ switch (result) {+ case 'blocked':+ return { kind: 'info', titleKey: 'widgets.layers.actions.busy' };+ case 'locked':+ return { kind: 'info', titleKey: 'widgets.layers.actions.locked' };+ case 'no-detection-input':+ return { kind: 'info', titleKey: 'widgets.layers.control.detectionNoInput' };+ case 'over-budget':+ return {+ kind: 'error',+ messageKey: 'widgets.layers.actions.overBudget',+ titleKey: 'widgets.layers.actions.actionFailed',+ };+ case 'failed':+ return {+ kind: 'error',+ messageKey: 'widgets.layers.actions.operationFailed',+ titleKey: 'widgets.layers.actions.actionFailed',+ };+ default:+ return null;+ }+ };++ export const getControlUploadNotice = (outcome: UploadControlImageResult): ControlSourceNotice | null => {+ switch (outcome.status) {+ case 'applied':+ return getControlIntentNotice(outcome.result);+ case 'uploading':+ return { kind: 'info', titleKey: 'widgets.layers.control.source.uploadPending' };+ case 'changed':+ return { kind: 'info', titleKey: 'widgets.layers.control.source.changedDuringUpload' };+ case 'failed':+ return { kind: 'error', message: outcome.message, titleKey: 'widgets.layers.control.source.uploadFailed' };+ case 'stale':+ // The account changed on the way; the result belongs to nobody here.+ return null;+ }+ };++ export type ControlFileDropResolution =+ | { status: 'accepted'; layerId: string }+ | { status: 'refused'; notice: ControlSourceNotice };++ /**+ * Whether files dragged onto the canvas can fill the selected control layer: exactly one image file, the canvas+ * accepting edits, and the selected layer a control layer that is not locked (by itself or a group) and still empty.+ * `files` are the drag's file items while it hovers (their `type` is readable then, to set the drop effect), and its+ * files once dropped.+ */+ export const resolveControlFileDrop = (input: {+ document: CanvasDocumentContractV3;+ engine: { readonly exports: Pick<CanvasExportCapability, 'hasExportableLayerContent'> };+ files: readonly { readonly type: string }[];+ isCanvasLocked: boolean;+ }): ControlFileDropResolution => {+ const { document, engine, files, isCanvasLocked } = input;+ const refuse = (titleKey: string): ControlFileDropResolution => ({+ notice: { kind: 'info', titleKey },+ status: 'refused',+ });+ if (files.length !== 1) {+ return refuse('widgets.canvas.fileDrop.oneFile');+ }+ if (!files[0]!.type.startsWith('image/')) {+ return refuse('widgets.canvas.fileDrop.notImage');+ }+ if (isCanvasLocked) {+ return refuse('widgets.layers.actions.busy');+ }+ const layer = getDocumentLayer(document, document.selectedLayerId);+ if (+ layer?.type !== 'control' ||+ getControlImageState(layer, engine.exports.hasExportableLayerContent(layer.id)) !== 'empty'+ ) {+ return refuse('widgets.canvas.fileDrop.noTarget');+ }+ if (lookupDocumentLeaf(document, layer.id)?.effectiveLocked !== false) {+ return refuse('widgets.layers.actions.locked');+ }+ return { layerId: layer.id, status: 'accepted' };+ };++ export type FillControlFromBboxResult =+ | { status: 'applied'; result: ControlLayerIntentResult; imageName: string }+ | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }- | AdjustmentRefusal;++ | AdjustmentRefusal++ | LayerUnreadable;++ /**+ * Uses the visible raster content inside the bbox as a control layer's image: the composite is uploaded as a control+ * image and replaces the layer's image at the bbox origin, which detects its map again. The upload stays with the+ * account that started it; a sign-out on the way reports `stale`.+ */+ export const fillControlFromBbox = async (options: {+ engine: CanvasCompositeExportEngine & { readonly projectId: string };+ layerId: string;+ uploadImage?: typeof uploadCanvasImage;+ }): Promise<FillControlFromBboxResult> => {+ const { engine, layerId, uploadImage = uploadCanvasImage } = options;+ const owner = captureAccountScope();+ try {+ const exported = await exportCanvasComposite(engine, 'bbox');+ assertAccountScopeCurrent(owner);+ if (exported.status !== 'ok') {+ return exported;+ }+ const uploaded = await uploadImage(exported.blob, {+ fileName: 'control.png',+ imageCategory: 'control',+ projectId: engine.projectId,+ signal: owner.signal,+ });+ assertAccountScopeCurrent(owner);+ const result = getCanvasOperations(engine).applyControlLayerIntent(layerId, {+ image: { height: uploaded.height, imageName: uploaded.imageName, width: uploaded.width },+ kind: 'replace-image',+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: exported.rect.x, y: exported.rect.y },+ });+ if (result === 'updated') {+ recordOrigin(engine, uploaded.imageName, { kind: 'frame' });+ }+ return { imageName: uploaded.imageName, result, status: 'applied' };+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {+ return { status: 'stale' };+ }+ throw error;+ }+ };++ export type SendGalleryImageAsControlResult =+ | { status: 'filled'; layerId: string; layerName: string }+ | { status: 'created'; layerId: string }+ | Exclude<ImportGalleryImagesResult, { status: 'imported' }>;++ type SendAsControlEngine = GalleryImportEngine & {+ readonly exports: Pick<CanvasExportCapability, 'hasExportableLayerContent'>;+ };++ /**+ * Uses a gallery image as a control layer's image. The selected control layer takes it when that layer has no image+ * yet and the project is the one on the live canvas (`filled`, detected like any replaced image); otherwise a new+ * control layer holds it (`created`), as the canvas import makes it. Every refusal of either path is reported, and a+ * `project` older than the latest document is `stale-document`.+ */+ export const sendGalleryImageAsControl = async (options: {+ applyCanvasMutation: (projectId: string, mutation: CanvasProjectMutation) => boolean | void;+ engine: SendAsControlEngine | null;+ getProject: (projectId: string) => Project | null;+ image: GalleryImage;+ isActiveProject: (projectId: string) => boolean;+ project: Project;+ }): Promise<SendGalleryImageAsControlResult> => {+ const { engine, getProject, image, isActiveProject, project } = options;+ const latest = getProject(project.id);+ if (!latest) {+ return { status: 'stale-project' };+ }+ if (latest.canvas.document !== project.canvas.document) {+ return { status: 'stale-document' };+ }++ const { document } = project.canvas;+ const selected = getDocumentLayer(document, document.selectedLayerId);+ const liveEngine = engine !== null && engine.projectId === project.id && isActiveProject(project.id) ? engine : null;+ if (+ liveEngine &&+ selected?.type === 'control' &&+ // Locked by itself or by a group above it: the image goes to a new layer instead.+ lookupDocumentLeaf(document, selected.id)?.effectiveLocked === false &&+ getControlImageState(selected, liveEngine.exports.hasExportableLayerContent(selected.id)) === 'empty'+ ) {+ const result = getCanvasOperations(liveEngine).applyControlLayerIntent(selected.id, {+ image: { height: image.height, imageName: image.imageName, width: image.width },+ kind: 'replace-image',+ // At the bbox origin, as every other canvas import places an image.+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: document.bbox.x, y: document.bbox.y },+ });+ switch (result) {+ case 'updated':+ case 'unchanged':+ case 'no-detection-input':+ return { layerId: selected.id, layerName: selected.name, status: 'filled' };+ case 'missing':+ return { status: 'stale-document' };+ case 'blocked':+ case 'over-budget':+ return { status: 'blocked' };+ case 'failed':+ throw new Error(`Could not use ${image.imageName} as the image of control layer ${selected.id}.`);+ case 'locked':+ // Locked by a group above it: the image goes to a new layer instead.+ break;+ }+ }++ const imported = await importGalleryImagesToCanvas({ ...options, destination: 'control', images: [image] });+ if (imported.status !== 'imported') {+ return imported;+ }+ const [layerId] = imported.layerIds;+ return layerId === undefined ? { status: 'empty' } : { layerId, status: 'created' };+ };diff --cc invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.tsindex ed4a55b6f2,3e0d6a4310..80a3f26de4--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts@@@ -65,7 -70,7 +72,14 @@@ export type CanvasEngine = CoreCanvasEn/** Application composition root: owns SAM/filter sessions, queues, uploads, and their core capability adapters. */export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine => {- const { ensureProjectOnServer, filterDeps, readSelectObjectAutoProcess, selectObjectDeps, ...coreOptions } = options;- const { controlDetectionDeps, ensureProjectOnServer, filterDeps, selectObjectDeps, ...coreOptions } = options;++ const {++ controlDetectionDeps,++ ensureProjectOnServer,++ filterDeps,++ readSelectObjectAutoProcess,++ selectObjectDeps,++ ...coreOptions++ } = options;const owner = captureAccountScope();const uploadLifetime = new AbortController();let projectMissingAt = -Infinity;diff --cc invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.tsindex 66aa914a57,198e5cf85e..3386606b7f--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts@@@ -2,12 -2,8 +2,10 @@@ import type { CanvasEngine, ImageResolvimport { useFontRuntime } from '@features/fonts/react';import { galleryImageUrls } from '@features/gallery/utility';- import { getModelsSnapshot } from '@features/models';+import { CanvasImageMissingError } from '@workbench/canvas-engine/api';import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import { publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';+import { getWorkbenchPreferences } from '@workbench/settings/store';- import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/controlModelOptions';import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';import {useActiveProjectId,diff --cc invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 3b3ce1c630,dee57607ab..1f9a321dcf--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@@ -542,8 -657,10 +621,9 @@@ export const CanvasWidgetView = ({ runt{engine ? (<><ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} />+ <ControlLayerCanvasOverlay engine={engine} isInteractionLocked={isInteractionLocked} /><CanvasLayerContextMenubeforeDangerItems={compositeSubmenus}- dispatch={canvasDispatch}engine={engine}showGroupLabelstarget={layerContextMenuTarget}diff --cc invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex 31cbc7062a,4a35ce9790..df44d62856--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@@ -9,17 -8,13 +9,16 @@@ import typeNewRasterLayerResult,} from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { TFunction } from 'i18next';- import { createDocumentModel } from '@workbench/canvas-engine/api';+ import { createControlLayer, createDocumentModel } from '@workbench/canvas-engine/api';import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';- import { createControlLayer } from '@workbench/widgets/layers/layerOps';import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';-import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';+import { CANVAS_HEADER_HOTKEYS } from './canvasHeaderCommands';+import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';+import { CANVAS_COMPANION_HOTKEYS, executeCanvasToolCommand, reportTransformRefusal } from './canvasToolCommands';const rasterLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>({diff --cc invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex c57d6d4704,aa5ecfec54..6ed6286c47--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@@ -800,9 -742,10 +788,10 @@@ const LayerMenu = (}const result = await engine.layers.copyLayerToControl(layer.id);if (result.status !== 'copied') {- throw makeStatusError(isAdjustmentRefusal(result) ? result : result.status);+ throw makeStatusError(isAdjustmentRefusal(result) || result.status === 'unreadable' ? result : result.status);}- }, [addCopy, base, defaultControlModel, engine, getActionLabel, layer, makeStatusError]);+ revealProperties(result.layerId);+ }, [addCopy, base, engine, getActionLabel, layer, makeStatusError, revealProperties]);const handleCopyToInpaintMask = useCallback(() => {const id = createLayerId();diff --cc invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex adccdeaebb,f73b62f365..0f60c9dab0--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@@ -6,7 -5,8 +6,8 @@@ import type} from '@workbench/canvas-engine/contracts';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+ import { createControlLayer } from '@workbench/canvas-engine/api';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi } from 'vitest';import {diff --cc invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsxindex 7c0d9456bc,6bb016b18e..e83c618aed--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx@@@ -236,11 -235,7 +239,11 @@@ const GRADIENT_SOURCE =width: 10,} satisfies Extract<CanvasLayerSourceContract, { type: 'gradient' }>;-const mount = async (View: typeof PropertiesPane, selection: Selection = 'none', width = 450) => {+const mount = async (+ View: typeof PropertiesPane,+ selection: Selection = 'none',- extraNodes: Parameters<typeof stacksFrom>[0] = []++ { extraNodes = [], width = 450 }: { extraNodes?: Parameters<typeof stacksFrom>[0]; width?: number } = {}+) => {const base = { ...createInitialWorkbenchState().projects[0]!, id: 'p' };const nodes =selection === 'none'@@@ -604,6 -601,23 +609,23 @@@ describe('Properties pane', () =>});});+ describe('Control layer properties', () => {+ it('fits a 320 px pane without horizontal overflow or clipped text', async () => {- await mount(PropertiesPane, 'control', 320);++ await mount(PropertiesPane, 'control', { width: 320 });+ await expect.element(page.getByRole('combobox', { exact: true, name: 'Type' })).toBeVisible();++ const overflowing = [host!, ...host!.querySelectorAll<HTMLElement>('*')].filter(+ (element) =>+ element.scrollWidth > element.clientWidth + 1 &&+ getComputedStyle(element).overflowX !== 'visible' &&+ // Screen-reader-only labels are clipped on purpose.+ getComputedStyle(element).position !== 'absolute'+ );+ expect(overflowing.map((element) => element.outerHTML.slice(0, 80))).toEqual([]);+ expect(host!.scrollWidth).toBeLessThanOrEqual(320);+ });+ });+describe('Tool property scrubbers', () => {beforeEach(() => resetPropertyGroupCollapse());afterEach(() => resetPropertyGroupCollapse());@@@ -1063,104 -1077,4 +1085,104 @@@ describe('Overview pane', () =>const after = viewport.getState().pan;expect(after.x === before.x && after.y === before.y).toBe(false);});++ it('shows content beyond the frame and centres the view on the clicked point there', async () => {+ // Outpainted pixels left of the default 1024² frame at the origin.+ const outpaint = layerContract('outpaint', 'raster', {+ source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },+ transform: { ...IDENTITY, x: -1024 },+ });- await mount(OverviewHarness, 'none', [outpaint]);++ await mount(OverviewHarness, 'none', { extraNodes: [outpaint] });+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });+ await expect.element(pan).toBeVisible();+ const canvas = pan.element().querySelector('canvas')!;+ // Frame (0,0) 1024×1024 ∪ content (-1024,0) 1024×512 = (-1024,0) 2048×1024.+ expect(canvas.width).toBeGreaterThan(0);+ expect(canvas.width / canvas.height).toBeCloseTo(2, 1);+ const unitsPerPx = 2048 / canvas.width;+ const viewport = engine!.viewport.getViewport();+ engine!.surface.resize(400, 300, 1);++ const offset = { x: 3, y: 3 };+ await act(async () => {+ await userEvent.click(canvas, { position: offset });+ });+ await settle();++ const centre = viewport.screenToDocument({ x: 200, y: 150 });+ const expected = { x: -1024 + offset.x * unitsPerPx, y: offset.y * unitsPerPx };+ expect(expected.x).toBeLessThan(0);+ expect(Math.abs(centre.x - expected.x)).toBeLessThan(unitsPerPx);+ expect(Math.abs(centre.y - expected.y)).toBeLessThan(unitsPerPx);+ // The outline is centred where the click landed on the bitmap.+ const outline = pan.element().querySelector('div')!;+ await expect+ .poll(() => parseFloat(outline.style.left) + parseFloat(outline.style.width) / 2)+ .toBeCloseTo(offset.x, 0);+ await expect+ .poll(() => parseFloat(outline.style.top) + parseFloat(outline.style.height) / 2)+ .toBeCloseTo(offset.y, 0);+ });++ it('zooms the view around the document point under the wheel', async () => {+ const outpaint = layerContract('outpaint', 'raster', {+ source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },+ transform: { ...IDENTITY, x: -1024 },+ });- await mount(OverviewHarness, 'none', [outpaint]);++ await mount(OverviewHarness, 'none', { extraNodes: [outpaint] });+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });+ await expect.element(pan).toBeVisible();+ const canvas = pan.element().querySelector('canvas')!;+ const unitsPerPx = 2048 / canvas.width;+ const viewport = engine!.viewport.getViewport();+ engine!.surface.resize(400, 300, 1);+ const offset = { x: 10, y: 20 };+ // Frame (0,0) 1024×1024 ∪ content (-1024,0) 1024×512 puts document (-1024,0) at the overview's top-left.+ const documentPoint = { x: -1024 + offset.x * unitsPerPx, y: offset.y * unitsPerPx };+ const anchor = viewport.documentToScreen(documentPoint);+ const zoomBefore = viewport.getZoom();++ const bounds = canvas.getBoundingClientRect();+ act(() => {+ pan.element().dispatchEvent(+ new WheelEvent('wheel', {+ bubbles: true,+ cancelable: true,+ clientX: bounds.left + offset.x,+ clientY: bounds.top + offset.y,+ deltaY: -100,+ })+ );+ });++ expect(viewport.getZoom()).toBeGreaterThan(zoomBefore);+ const anchored = viewport.documentToScreen(documentPoint);+ expect(Math.abs(anchored.x - anchor.x)).toBeLessThan(0.5);+ expect(Math.abs(anchored.y - anchor.y)).toBeLessThan(0.5);+ });++ it('redraws to the new extent when a document edit moves content after mount', async () => {+ await mount(OverviewHarness);+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });+ await expect.element(pan).toBeVisible();+ const canvas = pan.element().querySelector('canvas')!;+ // The empty document shows only its 1024² frame.+ expect(canvas.width / canvas.height).toBeCloseTo(1, 1);++ // Content 1024×512 placed above the frame: (0,-512)..(1024,1024) = 1024×1536.+ const outpaint = layerContract('outpaint', 'raster', {+ source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },+ transform: { ...IDENTITY, y: -512 },+ });+ act(() => {+ const project = harness.project!;+ harness.project = applyCanvasProjectMutation(project, {+ document: { ...project.canvas.document, stacks: stacksFrom([outpaint]) },+ type: 'replaceCanvasDocument',+ });+ harness.listeners.forEach((listener) => listener());+ });++ await expect.poll(() => canvas.width / canvas.height, { timeout: 2000 }).toBeCloseTo(1024 / 1536, 1);+ });});diff --cc invokeai/frontend/webv2/src/workbench/widgets/layers/useControlSourceActions.tsindex 0000000000,a2271deacc..d615217458mode 000000,100644..100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useControlSourceActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useControlSourceActions.ts@@@ -1,0 -1,152 +1,158 @@@+ import type {+ CanvasDocumentCapability,+ CanvasExportCapability,+ CanvasToolCapability,+ } from '@workbench/canvas-engine/api';+ import type {+ CanvasCompositeExportEngine,+ ControlLayerIntent,+ ControlLayerIntentResult,+ ControlSourceNotice,+ ControlSourceSnapshot,+ } from '@workbench/canvas-operations/api';++ import { invalidateGallery } from '@features/gallery/queries';+ import { useExternalStoreSelector } from '@platform/state/selectors';+ import { useQueryClient } from '@tanstack/react-query';+ import {+ fillControlFromBbox,+ getControlIntentNotice,+ getControlSourceSnapshot,+ getControlUploadNotice,+ subscribeControlSourceSnapshot,+ uploadControlImageFile,+ } from '@workbench/canvas-operations/api';+ import { useNotify } from '@workbench/useNotify';+ import { describeAdjustmentRefusal } from '@workbench/widgets/canvas/useStructuralCommit';+ import { useCallback, useState } from 'react';+ import { useTranslation } from 'react-i18next';++ export type ControlSourceAction = 'upload' | 'frame' | 'draw';++ /** The engine surface the Image row's actions need. */+ export type ControlSourceEngine = CanvasCompositeExportEngine & {+ readonly document: CanvasDocumentCapability;+ readonly exports: Pick<CanvasExportCapability, 'hasExportableLayerContent'>;+ readonly projectId: string;+ readonly tools: Pick<CanvasToolCapability, 'setTool'>;+ };++ /** Stands in for a missing engine: it has no source state, so it reads the empty snapshot. */+ const NO_ENGINE = {};+ const noSubscription = (): (() => void) => () => undefined;+ const selectSnapshot = (snapshot: ControlSourceSnapshot) => snapshot;++ /** Shows a control source notice through the workbench notices. */+ const useControlNoticeReporter = (): ((notice: ControlSourceNotice | null) => void) => {+ const { t } = useTranslation();+ const notify = useNotify();+ return useCallback(+ (notice: ControlSourceNotice | null) => {+ if (notice) {+ notify[notice.kind](t(notice.titleKey), notice.messageKey ? t(notice.messageKey) : notice.message);+ }+ },+ [notify, t]+ );+ };++ /** Says why a control layer intent did not land; `updated`, `unchanged` and `missing` say nothing. */+ export const useControlIntentReporter = (): ((result: ControlLayerIntentResult) => void) => {+ const report = useControlNoticeReporter();+ return useCallback((result: ControlLayerIntentResult) => report(getControlIntentNotice(result)), [report]);+ };++ /**+ * The Image row's three ways to fill a control layer. Each ends in one Properties intent (`replace-image` or `draw`),+ * so the coordinator detects the map, and reports a refusal. An action outlives the panel: its result still lands on+ * the layer by id. An upload started from the canvas shows here as busy too.+ */+ export const useControlSourceActions = ({+ applyIntent,+ engine,+ layerId,+ }: {+ /** Applies an intent and reports a refusal. */+ applyIntent: (intent: ControlLayerIntent) => ControlLayerIntentResult | null;+ engine: ControlSourceEngine | null;+ layerId: string;+ }) => {+ const { t } = useTranslation();+ const notify = useNotify();+ const queryClient = useQueryClient();+ const report = useControlNoticeReporter();+ const reportIntent = useControlIntentReporter();+ const [isFillingFromFrame, setIsFillingFromFrame] = useState(false);+ const subscribe = useCallback(+ (listener: () => void) => (engine ? subscribeControlSourceSnapshot(engine, listener) : noSubscription()),+ [engine]+ );+ const getSnapshot = useCallback(() => getControlSourceSnapshot(engine ?? NO_ENGINE), [engine]);+ const { origins, uploading } = useExternalStoreSelector(subscribe, getSnapshot, selectSnapshot);+ const busy: ControlSourceAction | null = isFillingFromFrame ? 'frame' : uploading.has(layerId) ? 'upload' : null;++ const upload = useCallback(+ async (file: File) => {+ if (!engine || isFillingFromFrame) {+ return;+ }+ const outcome = await uploadControlImageFile({+ engine,+ file,+ layerId,+ onUploaded: (owner) => void invalidateGallery(queryClient, owner),+ });+ report(getControlUploadNotice(outcome));+ },+ [engine, isFillingFromFrame, layerId, queryClient, report]+ );++ const fromFrame = useCallback(async () => {+ if (!engine || busy) {+ return;+ }+ setIsFillingFromFrame(true);+ try {+ const filled = await fillControlFromBbox({ engine, layerId });+ switch (filled.status) {+ case 'applied':+ reportIntent(filled.result);+ return;+ case 'empty':+ notify.info(t('widgets.layers.control.source.frameEmpty'));+ return;+ case 'not-ready':+ case 'over-budget':+ notify.info(t('widgets.layers.control.source.frameNotReady'));+ return;+ case 'adjustment-refused':+ notify.error(t('widgets.layers.control.source.frameFailed'), describeAdjustmentRefusal(filled, t));+ return;++ case 'unreadable':++ notify.error(++ t('widgets.layers.control.source.frameFailed'),++ t('widgets.canvas.contextMenu.unreadable', { name: filled.layerName })++ );++ return;+ case 'stale':+ // The account changed on the way; the result belongs to nobody here.+ }+ } catch (error) {+ notify.error(+ t('widgets.layers.control.source.frameFailed'),+ error instanceof Error ? error.message : String(error)+ );+ } finally {+ setIsFillingFromFrame(false);+ }+ }, [busy, engine, layerId, notify, reportIntent, t]);++ const draw = useCallback(() => {+ const result = applyIntent({ kind: 'draw' });+ if (result === 'updated' || result === 'unchanged') {+ engine?.tools.setTool('brush');+ }+ }, [applyIntent, engine]);++ return { busy, draw, fromFrame, origins, upload };+ };