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
fix(canvas): straight strokes, in-place painting, crop all and merged masks in the engine
Josh Corbettd892acf4426b
diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.tsindex bc2b60165b..5d30e1ee48 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts@@ -127,6 +127,7 @@ const CANVAS_EDIT_CONFIDENCE = {replaceCanvasFontReferences: 'high',replaceCanvasDocument: 'none',replaceCanvasLayer: 'high',+ replaceCanvasLayers: 'high',resizeCanvasDocument: 'high',restoreCanvasSnapshot: 'none',rollbackStagedImageCommit: 'none',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 95ef03401b..38e1cafbfa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -74,7 +74,8 @@ Current extracted ownership includes:- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases.- `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. Locked leaves (own or ancestor lock) are skipped, and counted when their content reaches past the frame, so the result can say how many were skipped even when nothing was cropped; 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 its opacity) into a mask configured like the topmost source.- `MaskResultController`, `FilterResultController`, `GeneratedResultController`: guarded application-result adoption through narrow host ports.Controller-local tests instantiate these boundaries with fakes. Integration tests in `engine.test.ts` cover composition, document routing, cross-controller invariants.@@ -99,7 +100,7 @@ Canvas invocation first crosses paint-flush barrier, then captures post-flush do## Frame demand before allocation-Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides.+Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The screen description also carries which overlay stacks it shows: while a generation is staged (the staging area holds a candidate, shown or not, or a staged or progress preview is published) it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted; control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame, joins the description's reuse key, and its flip repaints in full once.`calculateActiveFrameLayerIds` is the pure pre-allocation pass over that description: intersects each drawable leaf's bounds with document-space viewport. Explicitly isolated operation target is the one exception to normal document visibility: stays demanded and drawable when disabled or display-hidden, because user acts on that named layer directly.@@ -160,7 +161,7 @@ Invalidate only affected effect when parameters change. Delete every derived sloEvery recorded document and pixel edit goes through one protocol, `CanvasMutationContext.begin`, and is admitted before it mutates anything. Admission reserves undo entry's bytes in `History` without clearing redo or evicting older steps, so an edit whose entry could never be kept is refused as `over-budget` with document, pixels and history untouched. Two kinds of edit are admitted before they change anything but publish afterwards: live strokes paint as they are admitted (see below), and floating selection holds its admission from lift to landing. Selection-mask changes (`selection/selectionHistory.ts`) admit their step right after applying, because new mask's size is only known then, and roll back to exact prior selection when it cannot be kept. Resulting `EditTransaction` also reserves raster memory for its preparation (`reserveRaster`), holds leases and pins until `end()`, publishes once: `publish(label, step, entry)` applies an `EditStep` — optional document mutation with its postcondition and rollback, prepared pixels to install, ancillary notifications — verifies reducer and mirror, records the entry, then routes a user edit and notifies. Step that is rejected or fails its postconditions records nothing; failed postcondition dispatches step's rollback and reports when reducer or mirror could not return. Transactions refuse while permit is stale, a gesture runs (unless edit belongs to that gesture), a replay runs, or engine is disposed. Coalescing (nudges) names the entry it replaces by its `HistoryEntryToken` and is refused once anything else became newest step.-Layer controllers build their steps from `controllers/editSteps.ts`: byte accounting, replay reservations (replay whose preparation memory does not fit throws `REPLAY_RASTER_REFUSAL` and stays in place), steps that add, replace and remove layers with their prepared pixels, and new paint layers. It also names how a publication that did not land is reported: ordinary layer operations (merge, crop, copy, rasterize, insert) report reducer refusal or failed postcondition as `failed` (`layerOperationStatus`), while guarded result operations (generated, filter, mask and staged results, mask edits, duplicate) report it as `stale` (`guardedResultRefusal`), because their target moved on after the guard was taken.+Layer controllers build their steps from `controllers/editSteps.ts`: byte accounting, replay reservations (replay whose preparation memory does not fit throws `REPLAY_RASTER_REFUSAL` and stays in place), steps that add, replace (one layer, or several as one `replaceCanvasLayers`, sharing the identity postcondition, rollback and pre-install hook) and remove layers with their prepared pixels, and new paint layers. It also names how a publication that did not land is reported: ordinary layer operations (merge, crop, copy, rasterize, insert) report reducer refusal or failed postcondition as `failed` (`layerOperationStatus`), while guarded result operations (generated, filter, mask and staged results, mask edits, duplicate) report it as `stale` (`guardedResultRefusal`), because their target moved on after the guard was taken.Floating selection (`FloatingSelectionController`) computes its commit footprint from geometry before it copies or cuts anything: before and after pixels over union of hole and landing, selection alpha before and after, entry overhead. Admitted for that footprint as part of the drag that lifts it; keeps the transaction until it lands or is dropped. Every move, scale or rotation grows admission to the footprint at the new transform, from geometry alone; transform that does not fit keeps last accepted one and reports `over-budget` once per float, so an accepted transform always fits its undo entry while permit stays current; admission never shrinks, so a live float holds its largest accepted footprint until it lands or is dropped. Refused lift is reported and moves nothing (`lift` returns `refused`), including content whose cache is not rebuilt yet; only a lift with nothing to take (`unavailable`) lets Move tool fall back to moving the layer. Cut layer's persistence is suspended while float lives. Commit lands pixels and moved selection as one entry under retained admission, renewed once when its permit went stale (an operation locked and released the document meanwhile); commit that cannot be admitted or published puts pre-lift pixels and selection back. Cancellation refills hole before persistence resumes; hole that cannot be refilled keeps layer suspended rather than uploading it. Every terminal path ends the transaction: commit, cancel, Escape, undo/redo, layer's deletion or replacement, document replacement, cooldown (which banks the float before the flush), disposal, exceptions while cutting or landing.@@ -192,7 +193,9 @@ Capability returns `exported`, `nothing`, `too-large`, `not-ready`, `over-budget## Input ownership and frame scheduling-Pointer pipeline (`input/pointerPipeline.ts`) owns gesture capture and temporary holds (Space → view, Alt → picker, C → bbox). Keyboard ownership is explicit: widget passes its focusable keyboard root to `surface.attach`, and Enter applies a session only while focus is on that root or nowhere, never on a control or editable field. Hold keys and Escape ladder also act after a pointer click left focus on a control such as a tool button or layer row, since pipeline records on `focusin` whether focus arrived by pointer (Chromium marks focused element `:focus-visible` at any keydown, so arrival is the only reliable signal); they never act over an editable field, a control reached by keyboard, or an open dialog, menu or listbox. Owned Space keydown is prevented, so clicked control does not activate; key releases are always observed, never consumed. Genuine tool switch first cancels the gesture through outgoing tool and ends any hold, restoring held tool, so the switch leaves the tool the user was really on and a later key release restores nothing.+Pointer pipeline (`input/pointerPipeline.ts`) owns gesture capture and temporary holds (Space → view, Alt → picker, C → bbox). Keyboard ownership is explicit. Widget passes its focusable keyboard root and a `resolveKeyOwner` judge to `surface.attach`; the judge names the workbench region that owns a keydown (`surface`, a `companion` widget acting on this canvas's layers, or `elsewhere`) and is asked only on keydown, after the pipeline's own refusals, so the engine imports nothing from Workbench focus and pointer paths never pay for it. No key acts over an editable field, a control reached by keyboard (pipeline records on `focusin` whether focus arrived by pointer: Chromium marks focused element `:focus-visible` at any keydown, so arrival is the only reliable signal), an open dialog, menu or listbox, or beneath a modal. Past those refusals: Enter applies a session only from the `surface` with focus on its root or nowhere, never on a control; the Escape ladder and C act from the `surface` or a `companion`; Space and Alt stay pointer-led, acting over the hovered canvas whatever the owner and otherwise only from the `surface`. Without a judge (tests, detached engines) focus alone decides: the root or no focus is the surface, and a control the pointer last clicked counts as a companion. Owned Space keydown is prevented, so a clicked control does not activate. An owned Alt keydown is prevented, and so is the release of an Alt the pipeline claimed, because Firefox and Windows otherwise activate the menu bar; that holds for a tool that reads Alt as a gesture modifier too (Marquee, Lasso), which keeps the key and only gets no picker hold, since pointer events still carry `altKey`. Every other release is observed, never consumed. Alt from the surface while the pointer is elsewhere arms a pending hold that the next `pointerenter` with Alt still held, or a `pointerdown` with Alt, begins before the press is routed, so a pen landing without hover samples on contact; release, tool switch, blur, reset and detach clear it. Genuine tool switch first cancels the gesture through outgoing tool and ends any hold, restoring held tool, so the switch leaves the tool the user was really on and a later key release restores nothing.++A pick previews each sampled color to the one-shot request or the workbench router (`setColorSampleRouter`), then commits the last preview once on release or cancels it once when the press ends any other way (Escape, a tool change, a cancelled pointer); a declined preview falls back to the brush color. The sink that took a pick's first preview gets its commit or cancel, so a request armed or settled mid-pick never sends the router a stray phase, nor the reverse. Brush and eraser share an engine-lifetime map of where the last committed stroke ended on each layer: a Shift press on a layer with a remembered end draws a straight segment from it as part of the one stroke, and the map survives tool switches but forgets on replay, document replacement and the layer's removal. `layers.beginTransform` selects a leaf, switches to transform and opens its session even when transform is already active, cancelling a session on another layer; it refuses a locked or ineligible leaf, a running gesture, a live float or locked edits without changing selection or tool. A leaf whose only content is a stroke persistence has not acknowledged yet (a new paint layer's first upload) has no persisted extent to frame, so the request waits in the `pendingTransformLayerId` interaction store and the session opens when the bitmap lands, while the leaf is still selected, transform is the tool the user is on (a Space, Alt or C hold over it counts) and no other session opened. The wait ends without a session on a genuine tool switch, a selection change, the leaf's removal, Escape, a document replacement, or an upload of that leaf failing with no retry to follow (retried failures keep the wait), which also reports a `not-ready` refusal through `tools.onEditRefused`.`RenderScheduler.beforeNextFrame(task)` runs tasks once before next frame takes its flags, so their invalidations join that frame. Tools reach it through required `ToolContext.scheduleFrame`; detached engine runs the task immediately because it produces no frames. Brush strokes append samples and decimate them incrementally per event, render accumulated stroke at most once per presented frame, render synchronously on commit.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 258771e607..a660c8cba0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -13,9 +13,9 @@ import type { LayerTransform } from '@workbench/canvas-engine/transform/transforimport type { BooleanRasterResult } from './controllers/booleanMergeController';import type { CopyLayerToRasterResult } from './controllers/copyLayerController';-import type { CropLayerResult } from './controllers/cropLayerController';+import type { CropAllLayersResult, CropLayerResult } from './controllers/cropLayerController';import type { ExtractMaskedAreaResult } from './controllers/extractMaskedAreaController';-import type { MergeDownResult, MergeVisibleResult } from './controllers/mergeLayerController';+import type { MergeDownResult, MergeInpaintMasksResult, MergeVisibleResult } from './controllers/mergeLayerController';import type { NewRasterLayerResult } from './controllers/newRasterLayerController';import type { RasterizeLayerResult } from './controllers/rasterizeLayerController';import type { PreparedDocumentEdit } from './document-model/documentCommands';@@ -142,6 +142,12 @@ export interface CanvasInteractionState {textEditSession: TextEditSession | null;textOptions: TextToolOptions;transformSession: TransformSession | null;+ /**+ * The layer `layers.beginTransform` is waiting on: its session opens once the layer's fresh pixels are persisted.+ * Null when nothing waits; it also clears on a tool switch, a selection change, Escape, the layer's removal, a+ * document replacement or a persistence failure with no retry to follow.+ */+ pendingTransformLayerId: string | null;viewportReady: boolean;zoom: number;}@@ -201,9 +207,28 @@ export interface CanvasCoreStoreCapability {readonly interaction: CanvasInteractionStateCapability;}+/**+ * Which workbench region a key belongs to, as the host's focus judge decides: this canvas (`surface`), a widget+ * that acts on this canvas's layers (`companion`), or anything else (`elsewhere`).+ */+export type CanvasKeyOwner = 'surface' | 'companion' | 'elsewhere';++export interface CanvasSurfaceAttachOptions {+ /**+ * Names the owner of a keydown the canvas would otherwise act on. Asked only on keydown, after the pipeline's own+ * refusals (editable target, open menu or dialog). Without it the canvas judges ownership from focus alone.+ */+ readonly resolveKeyOwner?: (event: KeyboardEvent) => CanvasKeyOwner;+}+export interface CanvasSurfaceCapability {/** `keyboardRoot` is the focusable element whose focus gives the canvas its session keys; defaults to the overlay. */- attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement, keyboardRoot?: HTMLElement): void;+ attach(+ screenCanvas: HTMLCanvasElement,+ overlayCanvas: HTMLCanvasElement,+ keyboardRoot?: HTMLElement,+ options?: CanvasSurfaceAttachOptions+ ): void;detach(): void;resize(cssWidth: number, cssHeight: number, dpr: number): void;}@@ -281,6 +306,13 @@ export interface CanvasHistoryCapability {stepBy(offset: number): Promise<CanvasHistoryReplayStatus>;}+/**+ * Where an eyedropper sample is in its pick: `preview` on every sampled move while the pick is held, `commit` once on+ * release, `cancel` once when the pick ends without a release over the canvas (Escape, a tool change, an aborted+ * hold), carrying the last previewed color.+ */+export type ColorSamplePhase = 'preview' | 'commit' | 'cancel';+/** Why the engine refused an edit the user started without a caller to report to (a stroke, a shape). */export type CanvasEditRefusal = SubsetOf<CanvasTransactionOutcome,@@ -516,9 +548,11 @@ export type DuplicateLayersResult =export type {BooleanRasterResult,CopyLayerToRasterResult,+ CropAllLayersResult,CropLayerResult,ExtractMaskedAreaResult,MergeDownResult,+ MergeInpaintMasksResult,MergeVisibleResult,RasterizeLayerResult,};@@ -569,16 +603,31 @@ export interface CanvasEngineToolCapability extends CanvasToolCapability {*/requestColorSample(): Promise<string | null>;/**- * Routes unclaimed eyedropper samples to the active color target, falling back to brush color if absent or- * declined. Disposal removes only this router, preserving newer registrations.+ * Routes unclaimed eyedropper samples to the active color target by phase. A pick previews each sample, then+ * commits or cancels exactly once; a declined `preview` falls back to the brush color. Disposal removes only this+ * router, preserving newer registrations.*/- setColorSampleRouter(router: (hex: string) => boolean): () => void;+ setColorSampleRouter(router: (hex: string, phase: ColorSamplePhase) => boolean): () => void;setInteractionLocked(locked: boolean): void;}+/** Why `beginTransform` opened no session; refusals leave the selection and the active tool unchanged. */+export type BeginTransformResult =+ | 'started'+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'locked'>+ | 'ineligible'+ | SubsetOf<CanvasTransactionOutcome, 'busy'>;+export interface CanvasEngineLayerCapability extends CanvasLayerCapability {applyTransform(): void;+ /**+ * Selects `layerId`, switches to the transform tool and opens its session, even when transform is already active.+ * An open session on another layer is cancelled first.+ */+ beginTransform(layerId: string): BeginTransformResult;booleanMergeRasterLayers(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult>;+ /** Whether `mergeInpaintMasks` would accept these ids; pure, for menu enablement. */+ canMergeInpaintMasks(layerIds: readonly string[]): boolean;cancelTextEdit(): void;cancelTransform(): void;clearMask(layerId: string): MaskEditResult;@@ -595,8 +644,15 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {/** `null` when there was nothing to commit: an empty creation or an unchanged edit. */commitTextEdit(content: string, styleChanges?: Partial<TextToolOptions>): StructuralCommitResult | null;copyLayerToRaster(layerId: string): Promise<CopyLayerToRasterResult>;+ /**+ * Crops every raster, control, regional and inpaint leaf to the frame as one undo step, hidden and disabled leaves+ * included; locked leaves are skipped and counted, and leaves outside the frame are emptied in place.+ */+ cropAllLayersToBbox(): Promise<CropAllLayersResult>;cropLayerToBbox(layerId: string): Promise<CropLayerResult>;duplicateLayers(layerIds: readonly string[]): Promise<DuplicateLayersResult>;+ /** Unions the masks' coverage into one new inpaint mask above the topmost source, removing the sources. */+ mergeInpaintMasks(layerIds: readonly string[]): Promise<MergeInpaintMasksResult>;mergeLayerDown(upperLayerId: string): MergeDownResult;mergeSelectedRasterLayers(layerIds: readonly string[]): Promise<MergeVisibleResult>;mergeVisibleRasterLayers(): Promise<MergeVisibleResult>;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.tsindex 2ad09f6f55..d97c207465 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts@@ -1,8 +1,13 @@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentIndex, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';import { CropLayerController } from './cropLayerController';@@ -100,3 +105,245 @@ describe('CropLayerController', () => {expect(h.history.canUndo()).toBe(true);});});++const FRAME: Rect = { height: 20, width: 20, x: 0, y: 0 };++/** Each leaf's cache rect, which the fake export also reports as its baked pixels. */+const CACHE_RECTS: Record<string, Rect> = {+ control: { height: 10, width: 30, x: 5, y: 5 },+ inside: { height: 5, width: 5, x: 2, y: 2 },+ locked: { height: 50, width: 50, x: -10, y: -10 },+ lockedByGroup: { height: 50, width: 50, x: -10, y: -10 },+ lockedInside: { height: 5, width: 5, x: 2, y: 2 },+ mask: { height: 10, width: 10, x: 60, y: 60 },+ raster: { height: 50, width: 50, x: -10, y: -10 },+ region: { height: 10, width: 10, x: -5, y: 0 },+};++const bytes = (rect: Rect): number => rect.width * rect.height * 4;++/** A locked paint leaf whose persisted pixels cover its cache rect. */+const lockedPaint = (id: string, locked = true) =>+ layerContract(id, 'raster', {+ isLocked: locked,+ source: {+ bitmap: { height: CACHE_RECTS[id]!.height, imageName: `${id}.png`, width: CACHE_RECTS[id]!.width },+ offset: { x: CACHE_RECTS[id]!.x, y: CACHE_RECTS[id]!.y },+ type: 'paint',+ },+ } as Partial<CanvasLayerContract>);++const createCropAllHarness = (options: { historyBytes?: number; onExport?: (layerId: string) => void } = {}) => {+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: FRAME,+ height: 100,+ selectedLayerId: 'raster',+ stacks: stacksFrom([+ layerContract('inside'),+ layerContract('raster'),+ lockedPaint('locked'),+ lockedPaint('lockedInside'),+ groupContract('lockedGroup', [lockedPaint('lockedByGroup', false)], { isLocked: true }),+ layerContract('control', 'control', { isEnabled: false }),+ groupContract('regions', [layerContract('region', 'regional_guidance')]),+ layerContract('mask', 'inpaint_mask', { isHidden: true } as Partial<CanvasLayerContract>),+ ]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document, { historyBytes: options.historyBytes });+ for (const [id, rect] of Object.entries(CACHE_RECTS)) {+ h.layers.getOrCreateRect(id, rect);+ }+ const exported: string[] = [];+ const released: string[] = [];+ // Reserved raster bytes when each export is read; every export holds its own reservation until released.+ const reservedAtExport: number[] = [];+ const guard = { current: true };+ const discardPersisted = vi.fn();+ const controller = new CropLayerController({+ backend: h.backend,+ captureCache: (target, _document, admit = () => true) => {+ const entry = h.layers.get(target.id)!;+ if (!admit(entry.rect)) {+ return 'over-budget';+ }+ const pixels = h.backend.createSurface(entry.rect.width, entry.rect.height);+ pixels.ctx.drawImage(entry.surface.canvas, 0, 0);+ return { pixels, rect: { ...entry.rect } };+ },+ ctx: h.ctx,+ discardPersisted,+ exportBaked: (layerId) => {+ exported.push(layerId);+ options.onExport?.(layerId);+ const entry = h.layers.get(layerId)!;+ const reservation = h.ctx.reserveRaster(bytes(entry.rect));+ reservedAtExport.push(h.reservedBytes());+ return Promise.resolve({+ guard: { layer: getDocumentLayer(h.document(), layerId) } as never,+ rect: { ...entry.rect },+ release: () => {+ reservation?.release();+ released.push(layerId);+ },+ status: 'ok' as const,+ surface: entry.surface,+ });+ },+ isGuardCurrent: () => guard.current,+ isSupportedSource: () => true,+ });+ return { ...h, controller, discardPersisted, exported, guard, original: h.document(), released, reservedAtExport };+};++describe('CropLayerController: crop all layers', () => {+ it('crops every unlocked leaf that reaches past the frame in one entry, and replays it as one', async () => {+ const h = createCropAllHarness();++ await expect(h.controller.cropAll()).resolves.toEqual({ cropped: 4, skippedLocked: 2, status: 'cropped' });++ // Hidden, disabled and grouped leaves crop too; locked ones are never read, and only those reaching past the+ // frame count as skipped.+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster']);+ // Each export is released before the next is read, keeping only the cropped pixels: the peak is one export.+ const croppedRegion = bytes({ height: 10, width: 5, x: 0, y: 0 });+ const croppedControl = bytes({ height: 10, width: 15, x: 0, y: 0 });+ expect(h.reservedAtExport).toEqual([+ bytes(CACHE_RECTS.mask!),+ bytes(CACHE_RECTS.region!),+ croppedRegion + bytes(CACHE_RECTS.control!),+ croppedRegion + croppedControl + bytes(CACHE_RECTS.inside!),+ croppedRegion + croppedControl + bytes(CACHE_RECTS.raster!),+ ]);+ expect(h.released.sort()).toEqual(h.exported.sort());+ expect(h.dispatched.map((mutation) => mutation.type)).toEqual(['replaceCanvasLayers']);+ expect(h.history.entries().past).toEqual(['Crop all layers to frame']);+ // Before and after pixels of every cropped leaf, admitted once for the entry.+ const after =+ bytes(FRAME) + bytes({ height: 10, width: 15, x: 0, y: 0 }) + bytes({ height: 10, width: 5, x: 0, y: 0 });+ const before = ['raster', 'control', 'mask', 'region'].reduce((sum, id) => sum + bytes(CACHE_RECTS[id]!), 0);+ expect(h.history.byteSize()).toBe(before + after + HISTORY_ENTRY_OVERHEAD_BYTES);+ expect(h.reservedBytes()).toBe(0);++ const cropped = h.document();+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ expect(h.layers.get('control')?.rect).toEqual({ height: 10, width: 15, x: 5, y: 5 });+ expect(h.layers.get('region')?.rect).toEqual({ height: 10, width: 5, x: 0, y: 0 });+ // The mask outside the frame stays, emptied.+ expect(h.layers.get('mask')?.rect).toMatchObject({ height: 0, width: 0 });+ expect(getDocumentLayer(cropped, 'mask')).toMatchObject({ isHidden: true, mask: { bitmap: null } });+ expect(getDocumentLayer(cropped, 'control')).toMatchObject({+ isEnabled: false,+ source: { offset: { x: 5, y: 5 } },+ });+ for (const id of ['inside', 'locked', 'lockedInside', 'lockedByGroup']) {+ expect(getDocumentLayer(cropped, id)).toBe(getDocumentLayer(h.original, id));+ expect(h.layers.get(id)?.rect).toEqual(CACHE_RECTS[id]);+ }+ // Structure is untouched: same ids, parents and order.+ const structure = (document: CanvasDocumentContractV3) =>+ [...getDocumentIndex(document).byId.values()].map((entry) => [entry.node.id, entry.parentId, entry.siblingIndex]);+ expect(structure(cropped)).toEqual(structure(h.original));+ expect(h.discardPersisted.mock.calls.map(([id]) => id).sort()).toEqual(['control', 'mask', 'raster', 'region']);++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLeaves(h.document())).toEqual(getDocumentLeaves(h.original));+ for (const id of ['raster', 'control', 'mask', 'region']) {+ expect(h.layers.get(id)?.rect).toEqual(CACHE_RECTS[id]);+ }++ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLeaves(h.document())).toEqual(getDocumentLeaves(cropped));+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ });++ it('reports nothing when every unlocked leaf already fits the frame', async () => {+ const h = createCropAllHarness();+ for (const id of ['raster', 'control', 'mask', 'region']) {+ h.layers.delete(id);+ h.layers.getOrCreateRect(id, CACHE_RECTS.inside!);+ }++ await expect(h.controller.cropAll()).resolves.toEqual({ skippedLocked: 2, status: 'nothing' });+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ });++ it('refuses a set it could never undo with nothing changed and every lease released', async () => {+ const h = createCropAllHarness({ historyBytes: 8 * 1024 });++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(h.original);+ expect(h.dispatched).toEqual([]);+ expect(h.layers.get('raster')?.rect).toEqual(CACHE_RECTS.raster);+ expect(h.history.byteSize()).toBe(0);+ expect(h.reservedBytes()).toBe(0);+ expect(h.released.sort()).toEqual(h.exported.sort());+ });++ it('releases every reservation when copying the cropped pixels throws', async () => {+ const h = createCropAllHarness();+ const createSurface = h.backend.createSurface.bind(h.backend);+ // The emptied mask's zero-sized copy succeeds; the first real crop, after its reservation, throws.+ vi.spyOn(h.backend, 'createSurface').mockImplementation((width: number, height: number) => {+ if (width > 0) {+ throw new Error('surface allocation failed');+ }+ return createSurface(width, height);+ });++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'failed' });+ expect(h.reservedBytes()).toBe(0);+ expect(h.document()).toBe(h.original);+ expect(h.released).toEqual(h.exported);+ });++ it('refuses as over-budget when the cropped pixels cannot be reserved', async () => {+ const h = createCropAllHarness();+ h.state.rasterBytes = 1024;++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(h.original);+ expect(h.history.canUndo()).toBe(false);+ });++ it('is stale when the document changes while the pixels are read, and changes nothing', async () => {+ let edited = false;+ const h = createCropAllHarness({+ onExport: (layerId) => {+ if (layerId === 'control' && !edited) {+ edited = true;+ h.ctx.applyStep({+ accepted: (document) => document?.bbox.width === 30,+ mutation: { bbox: { ...FRAME, width: 30 }, type: 'setCanvasBbox' },+ });+ }+ },+ });+ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'stale' });+ expect(h.dispatched.map((mutation) => mutation.type)).toEqual(['setCanvasBbox']);+ expect(getDocumentLeaves(h.document())).toEqual(getDocumentLeaves(h.original));+ expect(h.history.canUndo()).toBe(false);+ expect(h.released.sort()).toEqual(h.exported.sort());+ });++ it('is stale when a leaf pixel guard went out of date', async () => {+ const h = createCropAllHarness();+ h.guard.current = false;++ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'stale' });+ expect(h.dispatched).toEqual([]);+ });++ it('leaves the entry on the undo stack when its replay is refused', async () => {+ const h = createCropAllHarness();+ await h.controller.cropAll();+ h.state.refuse = () => true;++ expect((await h.history.undo()).status).toBe('failed');+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);+ expect(h.history.canUndo()).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.tsindex e5b62f7fc7..9d3063a1e4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@ -7,10 +7,11 @@ import type {import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';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 type { CanvasMutationContext, EditStep } from './mutationContext';@@ -21,6 +22,7 @@ import {withReplayReservation,type LayerEditRefusal,replaceLayerStep,+ replaceLayersStep,type LayerPixels,} from './editSteps';@@ -29,6 +31,15 @@ export type CropLayerResult =| { status: 'missing' | 'locked' | 'unsupported' | 'empty' | LayerEditRefusal }| { status: 'failed'; message: string };+/**+ * `skippedLocked` counts locked leaves (own or ancestor lock) whose content reaches past the frame. `nothing` when+ * every unlocked leaf already fits; every refusal leaves document, pixels and history alone.+ */+export type CropAllLayersResult =+ | { status: 'cropped'; cropped: number; skippedLocked: number }+ | { status: 'nothing'; skippedLocked: number }+ | { status: 'stale' | 'failed' | LayerEditRefusal };+type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };@@ -60,7 +71,53 @@ export interface CropLayerControllerOptions {const failedCrop: CropLayerResult = { message: 'The crop could not be applied.', status: 'failed' };-/** Owns guarded crop-to-bbox conversion and replayable pixel snapshots. */+/**+ * 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') {+ const { filter: _filter, ...rest } = before;+ return { ...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;+};++/** 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) {}@@ -131,36 +188,16 @@ export class CropLayerController {return { status: 'not-ready' };}const before = structuredClone(liveLayer);- const cropped = this.deps.backend.createSurface(cropRect.width, cropRect.height);- cropped.ctx.setTransform(1, 0, 0, 1, 0, 0);- cropped.ctx.clearRect(0, 0, cropRect.width, cropRect.height);- cropped.ctx.drawImage(exported.surface.canvas, exported.rect.x - cropRect.x, exported.rect.y - cropRect.y);- const identity = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };- const paint = { bitmap: null, offset: { x: cropRect.x, y: cropRect.y }, type: 'paint' } as const;- let after: CanvasLayerContract;- if (before.type === 'raster') {- const { adjustments: _adjustments, ...rest } = before;- after = { ...rest, source: paint, transform: identity };- } else if (before.type === 'control') {- const { filter: _filter, ...rest } = before;- after = { ...rest, source: paint, transform: identity };- } else {- after = { ...before, mask: { ...before.mask, bitmap: null, offset: paint.offset }, transform: identity };- }+ const cropped = cropPixels(this.deps.backend, exported.surface, exported.rect, cropRect);+ const after = croppedLayerContract(before, cropRect);const afterPixels: LayerPixels = { pixels: cropped, rect: cropRect };/** Replaces the layer's contract and cache together; a failed replacement restores the current contract. */const replaceStep = (contract: CanvasLayerContract, snapshot: LayerPixels): EditStep =>replaceLayerStep(ctx, contract, ctx.preparePixels(layerId, snapshot.rect, snapshot.pixels), {- beforeInstall: () => {- try {- this.deps.discardPersisted(layerId);- } catch {- // The installed pixels are marked dirty and persist on their own.- }- },+ beforeInstall: () => this.discardPersisted(layerId),restore: getDocumentLayer(ctx.getReducerDocument(), layerId) ?? undefined,});- const result = txn.publish('Crop layer to bbox', replaceStep(after, afterPixels), {+ const result = txn.publish('Crop layer to frame', replaceStep(after, afterPixels), {bytes: rgbaBytes(beforePixels.rect) + rgbaBytes(cropRect) + HISTORY_ENTRY_OVERHEAD_BYTES,heldAssetRefs: collectHistoryMediaRefs(before, after),redo: () =>@@ -183,7 +220,204 @@ export class CropLayerController {}}+ /**+ * Crops every leaf of every stack to the frame as one history entry. Locked leaves (their own lock or an ancestor's)+ * are skipped; leaves already inside the frame, empty ones and unsupported sources are left alone; a leaf entirely+ * outside the frame is emptied in place, so ids, order, groups and flags never change. Each leaf's export is+ * released as soon as its cropped pixels are copied, so the peak is the cropped set plus one export.+ */+ async cropAll(): Promise<CropAllLayersResult> {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {+ return { status: 'busy' };+ }+ const document = ctx.getDocument();+ if (!document) {+ return { skippedLocked: 0, status: 'nothing' };+ }+ const frame = roundOut(document.bbox);+ let skippedLocked = 0;+ const candidates: CanvasLayerContract[] = [];+ for (const leaf of compileDocumentLeaves(document)) {+ const source = renderableSourceOf(leaf.layer);+ if (!source || !this.deps.isSupportedSource(source)) {+ continue;+ }+ if (!leaf.effectiveLocked) {+ candidates.push(leaf.layer);+ continue;+ }+ // A locked leaf counts only when cropping would have changed it: content reaching past the frame.+ const content = getSourceContentRect(leaf.layer, document);+ if (!isEmpty(content) && cropRectFor(transformBounds(leaf.worldTransform, content), frame)) {+ skippedLocked += 1;+ }+ }+ const guards: LayerExportGuard[] = [];+ const cropped: CroppedLeaf[] = [];+ try {+ for (const layer of candidates) {+ const exported = await this.deps.exportBaked(layer.id);+ if (exported.status === 'missing') {+ return { status: 'stale' };+ }+ if (exported.status === 'not-ready' || exported.status === 'over-budget') {+ return { status: exported.status };+ }+ if (exported.status !== 'ok') {+ // Empty, disabled-only or unsupported content has nothing to crop.+ continue;+ }+ try {+ guards.push(exported.guard);+ const rect = cropRectFor(exported.rect, frame);+ if (!rect) {+ continue;+ }+ const reservation = ctx.reserveRaster(rgbaBytes(rect));+ if (!reservation) {+ return { status: 'over-budget' };+ }+ let pixels: RasterSurface;+ try {+ pixels = cropPixels(this.deps.backend, exported.surface, exported.rect, rect);+ } catch (error) {+ reservation.release();+ throw error;+ }+ cropped.push({ layer, pixels: { pixels, rect }, reservation });+ } finally {+ exported.release();+ }+ }+ if (!ctx.isPermitCurrent(permit)) {+ return { status: 'busy' };+ }+ const liveDocument = ctx.getDocument();+ // Any edit while the pixels were read (a layer, the frame, the stacks) makes the plan stale.+ if (+ !liveDocument ||+ liveDocument.stacks !== document.stacks ||+ !isSameRect(liveDocument.bbox, document.bbox) ||+ guards.some((guard) => !this.deps.isGuardCurrent(guard))+ ) {+ return { status: 'stale' };+ }+ if (cropped.length === 0) {+ return { skippedLocked, status: 'nothing' };+ }+ return this.publishAll(liveDocument, cropped, skippedLocked);+ } catch {+ return { status: 'failed' };+ } finally {+ for (const leaf of cropped) {+ leaf.reservation.release();+ }+ }+ }++ private publishAll(+ document: CanvasDocumentContractV3,+ cropped: readonly CroppedLeaf[],+ skippedLocked: number+ ): CropAllLayersResult {+ const { ctx } = this.deps;+ const afterBytes = cropped.reduce((sum, leaf) => sum + rgbaBytes(leaf.pixels.rect), 0);+ const txn = ctx.begin({ historyBytes: afterBytes + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ return { status: layerEditRefusal(txn.status) };+ }+ try {+ // The prepared cache replacements; the cropped pixels hold their own reservations.+ if (!txn.reserveRaster(afterBytes)) {+ return { status: 'over-budget' };+ }+ const crops: LayerCrop[] = [];+ for (const leaf of cropped) {+ // Each before snapshot grows the one admission; a set that cannot be kept refuses with nothing changed.+ const beforePixels = this.deps.captureCache(leaf.layer, document, (cacheRect) =>+ txn.growHistory(rgbaBytes(cacheRect))+ );+ if (beforePixels === 'over-budget') {+ return { status: 'over-budget' };+ }+ if (!beforePixels || beforePixels === 'not-ready') {+ return { status: 'not-ready' };+ }+ const before = structuredClone(leaf.layer);+ crops.push({+ after: croppedLayerContract(before, leaf.pixels.rect),+ afterPixels: leaf.pixels,+ before,+ beforePixels,+ });+ }+ const beforeBytes = crops.reduce((sum, crop) => sum + rgbaBytes(crop.beforePixels.rect), 0);+ const replay = (side: 'before' | 'after') => () =>+ withReplayReservation(ctx, side === 'before' ? beforeBytes : afterBytes, () =>+ ctx.applyStep(this.replaceAllStep(crops, side))+ );+ const result = txn.publish('Crop all layers to frame', this.replaceAllStep(crops, 'after'), {+ bytes: beforeBytes + afterBytes + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(...crops.flatMap((crop) => [crop.before, crop.after])),+ redo: replay('after'),+ undo: replay('before'),+ });+ const status = layerOperationStatus(result);+ return status === 'committed' ? { cropped: crops.length, skippedLocked, status: 'cropped' } : { status };+ } finally {+ txn.end();+ }+ }++ /** Every cropped leaf's contract and cache, replaced together as one step; it rolls back to the reducer's contracts. */+ private replaceAllStep(crops: readonly LayerCrop[], side: 'before' | 'after'): EditStep {+ const { ctx } = this.deps;+ const reducerDocument = ctx.getReducerDocument();+ return replaceLayersStep(+ ctx,+ crops.map((crop) => {+ const pixels = side === 'before' ? crop.beforePixels : crop.afterPixels;+ return { contract: crop[side], prepared: ctx.preparePixels(crop.before.id, pixels.rect, pixels.pixels) };+ }),+ {+ beforeInstall: (layerId) => this.discardPersisted(layerId),+ restore: crops.flatMap((crop) => getDocumentLayer(reducerDocument, crop.before.id) ?? []),+ }+ );+ }++ /** Drops a replaced layer's pending persistence; the installed pixels are marked dirty and persist on their own. */+ private discardPersisted(layerId: string): void {+ try {+ this.deps.discardPersisted(layerId);+ } catch {+ // The installed pixels persist on their own.+ }+ }+dispose(): void {this.disposed = true;}}++const isSameRect = (a: Rect, b: Rect): boolean =>+ a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;++/**+ * Where a leaf's exported pixels land once cropped to `frame`: their overlap, an empty rect at the frame origin when+ * they lie entirely outside it, or null when they already fit inside and there is nothing to crop.+ */+const cropRectFor = (exportedRect: Rect, frame: Rect): Rect | null => {+ const inside =+ exportedRect.x >= frame.x &&+ exportedRect.y >= frame.y &&+ exportedRect.x + exportedRect.width <= frame.x + frame.width &&+ exportedRect.y + exportedRect.height <= frame.y + frame.height;+ if (inside) {+ return null;+ }+ const overlap = intersect(exportedRect, frame);+ return overlap && !isEmpty(overlap) ? roundOut(overlap) : { height: 0, width: 0, x: frame.x, y: frame.y };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.tsindex dc14c3c251..663e9f62e8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts@@ -116,6 +116,43 @@ export const replayWithPixels = (// ---- Steps ---------------------------------------------------------------------------------------------------+/** Options shared by the in-place replace steps. */+export interface ReplaceLayerStepOptions {+ readonly persist?: boolean;+ /** Runs just before each layer's pixels install, once the document accepted the contracts. */+ readonly beforeInstall?: (layerId: string) => void;+ readonly notify?: () => void;+}++/** Whether `document` holds exactly these contracts, by identity. */+const holdsContracts =+ (contracts: readonly CanvasLayerContract[]) =>+ (document: CanvasDocumentContractV3 | null): boolean =>+ contracts.every((contract) => getDocumentLayer(document, contract.id) === contract);++/** Installs each replacement's prepared pixels in order, after its `beforeInstall`; nothing to do yields undefined. */+const installReplacements = (+ ctx: Pick<CanvasMutationContext, 'installPrepared'>,+ replacements: readonly LayerReplacement[],+ options: ReplaceLayerStepOptions+): (() => void) | undefined =>+ options.beforeInstall || replacements.some(({ prepared }) => prepared)+ ? () => {+ for (const { contract, prepared } of replacements) {+ options.beforeInstall?.(contract.id);+ if (prepared) {+ ctx.installPrepared(prepared, options.persist);+ }+ }+ }+ : undefined;++/** A layer's replacement contract and the pixels that land with it. */+export interface LayerReplacement {+ readonly contract: CanvasLayerContract;+ readonly prepared: PreparedLayerCacheReplacement | null;+}+/*** Swaps `contract` in for its layer and, once the document accepted it, installs the prepared pixels. A step with a* `restore` contract rolls back to it when its postconditions fail.@@ -124,34 +161,49 @@ export const replaceLayerStep = (ctx: Pick<CanvasMutationContext, 'installPrepared'>,contract: CanvasLayerContract,prepared: PreparedLayerCacheReplacement | null,- options: {- readonly restore: CanvasLayerContract | undefined;- readonly persist?: boolean;- /** Runs just before the pixels install, once the document accepted the contract. */- readonly beforeInstall?: () => void;- readonly notify?: () => void;- }+ options: ReplaceLayerStepOptions & { readonly restore: CanvasLayerContract | undefined }): EditStep => ({- accepted: (document) => getDocumentLayer(document, contract.id) === contract,- install:- prepared || options.beforeInstall- ? () => {- options.beforeInstall?.();- if (prepared) {- ctx.installPrepared(prepared, options.persist);- }- }- : undefined,+ accepted: holdsContracts([contract]),+ install: installReplacements(ctx, [{ contract, prepared }], options),mutation: { layer: contract, layerId: contract.id, type: 'replaceCanvasLayer' },notify: options.notify,rollback: options.restore? {mutation: { layer: options.restore, layerId: contract.id, type: 'replaceCanvasLayer' },- restored: (document) => getDocumentLayer(document, contract.id) === options.restore,+ restored: holdsContracts([options.restore]),}: undefined,});+/**+ * {@link replaceLayerStep} for several same-type leaves at once, as one `replaceCanvasLayers`. It rolls back to+ * `restore` (one contract per replaced layer) when its postconditions fail; without a complete restore set it has no+ * rollback.+ */+export const replaceLayersStep = (+ ctx: Pick<CanvasMutationContext, 'installPrepared'>,+ replacements: readonly LayerReplacement[],+ options: ReplaceLayerStepOptions & { readonly restore: readonly CanvasLayerContract[] | undefined }+): EditStep => {+ const contracts = replacements.map(({ contract }) => contract);+ const restore = options.restore?.length === contracts.length ? options.restore : undefined;+ return {+ accepted: holdsContracts(contracts),+ install: installReplacements(ctx, replacements, options),+ mutation: { replacements: contracts.map((layer) => ({ layer, layerId: layer.id })), type: 'replaceCanvasLayers' },+ notify: options.notify,+ rollback: restore+ ? {+ mutation: {+ replacements: restore.map((layer) => ({ layer, layerId: layer.id })),+ type: 'replaceCanvasLayers',+ },+ restored: holdsContracts(restore),+ }+ : undefined,+ };+};+const removeLayerMutation = (layerId: string, selectedLayerId: string | null) =>({ enabledUpdates: [], removeIds: [layerId], selectedLayerId, type: 'applyCanvasLayerStackMutation' }) as const;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.tsnew file mode 100644index 0000000000..3b93e36a29--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts@@ -0,0 +1,82 @@+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Rect } from '@workbench/canvas-engine/types';++import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { describe, expect, it } from 'vitest';++import { createLayerOperationHarness } from './layerOperationHarness.testing';+import { MergeLayerController } from './mergeLayerController';++/** Coverage alpha of a mask's baked pixels, filled uniformly over `rect`. */+const coverage = (rect: Rect, alpha: number): RasterSurface => {+ const surface = createDomRasterBackend().createSurface(rect.width, rect.height);+ surface.ctx.fillStyle = `rgba(255, 255, 255, ${alpha / 255})`;+ surface.ctx.fillRect(0, 0, rect.width, rect.height);+ return surface;+};++describe('MergeLayerController in Chromium: merge masks', () => {+ it('unions coverage source-over, each mask at its own opacity', async () => {+ // The top mask is half-covered at full opacity; the one below is fully covered at half opacity.+ const sources: Record<string, { alpha: number; opacity: number; rect: Rect }> = {+ below: { alpha: 255, opacity: 0.5, rect: { height: 10, width: 10, x: 5, y: 0 } },+ top: { alpha: 128, opacity: 1, rect: { height: 10, width: 10, x: 0, y: 0 } },+ };+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId: 'top',+ stacks: stacksFrom(+ ['top', 'below'].map((id) =>+ layerContract(id, 'inpaint_mask', { opacity: sources[id]!.opacity } as Partial<CanvasLayerContract>)+ )+ ),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document);+ const dom = createDomRasterBackend();+ // Real raw caches, which undo snapshots copy.+ for (const [layerId, { alpha, rect }] of Object.entries(sources)) {+ h.layers.installReplacement({ layerId, rect, surface: coverage(rect, alpha) });+ }+ const created: RasterSurface[] = [];+ const controller = new MergeLayerController({+ backend: {+ ...dom,+ createSurface: (width, height, options) => {+ const surface = dom.createSurface(width, height, options);+ created.push(surface);+ return surface;+ },+ },+ ctx: h.ctx,+ exportBaked: (layerId) =>+ Promise.resolve({+ guard: { layer: getDocumentLayer(h.document(), layerId) } as never,+ rect: { ...sources[layerId]!.rect },+ release: () => undefined,+ status: 'ok' as const,+ surface: coverage(sources[layerId]!.rect, sources[layerId]!.alpha),+ }),+ hasExportableContent: () => true,+ isCacheReady: () => true,+ layers: h.layers,+ needsPixelPersistence: () => true,+ publishSelectedLayerIds: () => undefined,+ });++ await expect(controller.mergeInpaintMasks(['top', 'below'])).resolves.toMatchObject({ status: 'merged' });++ const merged = created.find((surface) => surface.width === 15 && surface.height === 10)!;+ const alphaAt = (x: number): number => merged.ctx.getImageData(x, 5, 1, 1).data[3]!;+ // Top only: its own coverage. Below only: half of full coverage. Both: 128 over 128 = 128 + 128 * (1 - 128/255).+ expect(alphaAt(2)).toBeCloseTo(128, -0.5);+ expect(alphaAt(12)).toBeCloseTo(128, -0.5);+ expect(alphaAt(7)).toBeCloseTo(128 + 128 * (1 - 128 / 255), -0.5);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.tsindex f4d6e47db4..2dfeb49872 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts@@ -1,8 +1,12 @@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Rect } from '@workbench/canvas-engine/types';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentIndex, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { describe, expect, it } from 'vitest';import { createLayerOperationHarness } from './layerOperationHarness.testing';@@ -132,3 +136,143 @@ describe('MergeLayerController: merge down', () => {expect(h.dispatched).toEqual([]);});});++describe('MergeLayerController: merge masks', () => {+ const RECTS: Record<string, Rect> = {+ bottom: { height: 10, width: 10, x: 30, y: 30 },+ middle: { height: 10, width: 10, x: 10, y: 10 },+ top: { height: 10, width: 10, x: 0, y: 0 },+ };++ const createMaskHarness = (options: { historyBytes?: number; onExport?: () => void } = {}) => {+ const top = layerContract('top', 'inpaint_mask', {+ denoise: { isEnabled: true, limit: 0.4 },+ mask: { bitmap: null, fill: { color: '#123456', style: 'grid' } },+ noise: { isEnabled: true, level: 0.2 },+ opacity: 0.5,+ } as Partial<CanvasLayerContract>);+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId: 'middle',+ stacks: stacksFrom([+ groupContract('first', [layerContract('other', 'inpaint_mask'), top]),+ groupContract('second', [layerContract('middle', 'inpaint_mask')]),+ layerContract('bottom', 'inpaint_mask'),+ ]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document, { historyBytes: options.historyBytes });+ for (const [id, rect] of Object.entries({ ...RECTS, other: { height: 4, width: 4, x: 0, y: 0 } })) {+ h.layers.getOrCreateRect(id, rect).stale = false;+ }+ const released: string[] = [];+ const selections: [string | null, readonly string[]][] = [];+ const controller = new MergeLayerController({+ backend: h.backend,+ ctx: h.ctx,+ exportBaked: (layerId) => {+ options.onExport?.();+ const entry = h.layers.get(layerId)!;+ return Promise.resolve({+ guard: { layer: getDocumentLayer(h.document(), layerId) } as never,+ rect: { ...entry.rect },+ release: () => released.push(layerId),+ status: 'ok' as const,+ surface: entry.surface,+ });+ },+ hasExportableContent: (layerId) => (h.layers.get(layerId)?.rect.width ?? 0) > 0,+ isCacheReady: () => true,+ layers: h.layers,+ needsPixelPersistence: () => true,+ publishSelectedLayerIds: (primary, ids) => selections.push([primary, ids]),+ });+ return { ...h, controller, original: h.document(), released, selections };+ };++ const structure = (document: CanvasDocumentContractV3) =>+ [...getDocumentIndex(document).byId.values()].map((entry) => [entry.node.id, entry.parentId, entry.siblingIndex]);++ it('unions masks from different groups into one mask above the topmost, configured like it, as one step', async () => {+ const h = createMaskHarness();++ const result = await h.controller.mergeInpaintMasks(['bottom', 'top', 'middle']);+ expect(result).toEqual({ layerId: 'new-1', status: 'merged' });++ const merged = getDocumentLayer(h.document(), 'new-1');+ expect(merged).toEqual({+ blendMode: 'normal',+ denoise: { isEnabled: true, limit: 0.4 },+ id: 'new-1',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#123456', style: 'grid' }, offset: { x: 0, y: 0 } },+ name: 'top merged',+ noise: { isEnabled: true, level: 0.2 },+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ });+ // The union of the three sources' extents, in place of the topmost source; the others are gone.+ expect(h.layers.get('new-1')?.rect).toEqual({ height: 40, width: 40, x: 0, y: 0 });+ expect(getDocumentIndex(h.document()).byId.get('new-1')).toMatchObject({ parentId: 'first', siblingIndex: 1 });+ expect(leafIds(h.document())).toEqual(['other', 'new-1']);+ expect(h.document().selectedLayerId).toBe('new-1');+ expect(h.history.entries().past).toEqual(['Merge masks']);+ expect(h.released.sort()).toEqual(['bottom', 'middle', 'top']);+ expect(h.reservedBytes()).toBe(0);++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(structure(h.document())).toEqual(structure(h.original));+ for (const id of ['top', 'middle', 'bottom']) {+ expect(getDocumentLayer(h.document(), id)).toBe(getDocumentLayer(h.original, id));+ expect(h.layers.get(id)?.rect).toEqual(RECTS[id]);+ }+ expect(h.document().selectedLayerId).toBe('middle');++ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(leafIds(h.document())).toEqual(['other', 'new-1']);+ });++ it.each([+ ['one mask', ['top'], 'ineligible'],+ ['a regional or raster leaf', ['top', 'first'], 'ineligible'],+ ['a missing id', ['top', 'gone'], 'missing'],+ ] as const)('refuses %s without reading pixels', async (_, ids, status) => {+ const h = createMaskHarness({ onExport: () => expect.fail('read pixels') });++ await expect(h.controller.mergeInpaintMasks(ids)).resolves.toEqual({ status });+ expect(h.dispatched).toEqual([]);+ });++ it('refuses a merge it could never undo with nothing changed', async () => {+ const h = createMaskHarness({ historyBytes: 1024 });++ await expect(h.controller.mergeInpaintMasks(['top', 'middle'])).resolves.toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(h.original);+ expect(h.dispatched).toEqual([]);+ expect(h.reservedBytes()).toBe(0);+ });++ it('refuses when a source changes while its pixels are read', async () => {+ let edited = false;+ const h = createMaskHarness({+ onExport: () => {+ if (!edited) {+ edited = true;+ h.ctx.applyStep({+ accepted: (document) => getDocumentLayer(document, 'middle')?.name === 'Renamed',+ mutation: { id: 'middle', patch: { name: 'Renamed' }, type: 'updateCanvasLayer' },+ });+ }+ },+ });++ await expect(h.controller.mergeInpaintMasks(['top', 'middle'])).resolves.toEqual({ status: 'not-ready' });+ expect(h.dispatched.map((mutation) => mutation.type)).toEqual(['updateCanvasLayer']);+ expect(h.history.canUndo()).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex ece8ae5060..1e4ef4948c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -1,6 +1,7 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -12,12 +13,21 @@ import {mergeDownEligibility,compileDocumentLeaves,} from '@workbench/canvas-engine/document-model/documentModel';-import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import {+ getDocumentLayer,+ getDocumentLeaves,+ getDocumentNode,+ isNodeAbsent,+} from '@workbench/canvas-engine/document/documentIndex';import { removeNodes } from '@workbench/canvas-engine/document/documentTree';import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';-import { canMergeSelectedRasters, getMergeVisibleRasterLeaves } from '@workbench/canvas-engine/document/mergeVisible';+import {+ canMergeInpaintMasks,+ canMergeSelectedRasters,+ getMergeVisibleRasterLeaves,+} from '@workbench/canvas-engine/document/mergeVisible';import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';@@ -45,6 +55,52 @@ import {export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'failed';+/** Every refusal leaves document, pixels and history alone. */+export type MergeInpaintMasksResult =+ | { status: 'merged'; layerId: string }+ | { status: 'ineligible' | 'missing' | 'failed' | LayerEditRefusal };++/**+ * What tells one merge of selected leaves into a new leaf from another: who may merge (checked before the pixels are+ * read and again before publishing), which stack the result joins above the topmost contributor, what it is, and+ * the history label.+ */+interface SelectedMergeSpec {+ readonly label: string;+ readonly stack: LayerStackKind;+ canMerge(document: CanvasDocumentContractV3, selectedIds: ReadonlySet<string>): boolean;+ /** The merged leaf placing pixels at `rect`, from the contributors top first. */+ createResult(id: string, contributors: readonly CanvasLayerContract[], rect: Rect): CanvasLayerContract;+}++type SelectedMergeResult = { status: 'merged'; layerId: string } | { status: Exclude<MergeVisibleResult, 'merged'> };++const IDENTITY_TRANSFORM = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };++/**+ * One inpaint mask carrying the union of the sources' coverage at `rect`, named after and configured like the topmost+ * source: its fill, noise and denoise.+ */+const mergedMaskLayer = (id: string, contributors: readonly CanvasLayerContract[], rect: Rect): CanvasLayerContract => {+ const top = contributors[0]!;+ if (top.type !== 'inpaint_mask') {+ throw new Error('A mask merge needs inpaint mask contributors.');+ }+ return {+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: structuredClone(top.mask.fill), offset: { x: rect.x, y: rect.y } },+ name: `${top.name} merged`,+ opacity: 1,+ transform: { ...IDENTITY_TRANSFORM },+ type: 'inpaint_mask',+ ...(top.noise ? { noise: structuredClone(top.noise) } : {}),+ ...(top.denoise ? { denoise: structuredClone(top.denoise) } : {}),+ };+};+export type MergeDownResult =| 'merged'| SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>@@ -387,22 +443,55 @@ export class MergeLayerController {}}+ /** Flattens one contiguous run of selected raster siblings into a new paint layer above them. */async mergeSelected(layerIds: readonly string[]): Promise<MergeVisibleResult> {+ const result = await this.mergeSelectedInto(layerIds, {+ canMerge: (document, selectedIds) =>+ canMergeSelectedRasters(document, compileDocumentLeaves(document), selectedIds, this.deps.hasExportableContent),+ createResult: (id, contributors, rect) => paintLayerAt(id, `${contributors[0]!.name} merged`, rect),+ label: 'Merge selected layers',+ stack: 'raster',+ });+ return result.status;+ }++ /** Unions the coverage of selected inpaint masks, anywhere in the stack, into one new mask above the topmost. */+ async mergeInpaintMasks(layerIds: readonly string[]): Promise<MergeInpaintMasksResult> {+ const document = this.deps.ctx.getDocument();+ if (document && layerIds.some((id) => !getDocumentNode(document, id))) {+ return { status: 'missing' };+ }+ const result = await this.mergeSelectedInto(layerIds, {+ canMerge: (candidate, selectedIds) =>+ canMergeInpaintMasks(compileDocumentLeaves(candidate), selectedIds, this.deps.hasExportableContent),+ createResult: mergedMaskLayer,+ label: 'Merge masks',+ stack: 'inpaint_mask',+ });+ if (result.status === 'merged') {+ return result;+ }+ return { status: result.status === 'nothing' ? 'ineligible' : result.status };+ }++ /**+ * Composites the selected leaves bottom-up (source-over, each at its opacity) into a new leaf above the topmost and+ * removes them, as one undo step that restores every source in place with its raw pixels.+ */+ private async mergeSelectedInto(layerIds: readonly string[], spec: SelectedMergeSpec): Promise<SelectedMergeResult> {const { ctx } = this.deps;const permit = ctx.capturePermit();if (this.disposed || !permit) {- return 'busy';+ return { status: 'busy' };}const document = ctx.getDocument();if (!document) {- return 'nothing';+ return { status: 'nothing' };}const selectedIds = new Set(layerIds);const contributors = getDocumentLeaves(document).filter((layer) => selectedIds.has(layer.id));- if (- !canMergeSelectedRasters(document, compileDocumentLeaves(document), selectedIds, this.deps.hasExportableContent)- ) {- return 'nothing';+ if (!spec.canMerge(document, selectedIds)) {+ return { status: 'nothing' };}const owned: Extract<ExportResult, { status: 'ok' }>[] = [];const acquire = async (layerId: string): Promise<ExportResult> => {@@ -420,13 +509,13 @@ export class MergeLayerController {}const exports = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);if (!ctx.isPermitCurrent(permit)) {- return 'busy';+ return { status: 'busy' };}if (exports.some((result) => result.status === 'over-budget')) {- return 'over-budget';+ return { status: 'over-budget' };}if (exports.some((result) => result.status !== 'ok')) {- return 'not-ready';+ return { status: 'not-ready' };}for (let index = 0; index < exports.length; index += 1) {const exported = exports[index];@@ -438,7 +527,7 @@ export class MergeLayerController {exported.guard.layer !== contributor ||!ctx.isGuardCurrent(exported.guard)) {- return 'not-ready';+ return { status: 'not-ready' };}}// The merge is built from `document`: its structure and selection, the contributors' identities and their@@ -453,19 +542,14 @@ export class MergeLayerController {!haveSameStructure(liveDocument.stacks, document.stacks) ||liveContributors.length !== contributors.length ||liveContributors.some((layer, index) => layer !== contributors[index]) ||- !canMergeSelectedRasters(- liveDocument,- compileDocumentLeaves(liveDocument),- selectedIds,- this.deps.hasExportableContent- )+ !spec.canMerge(liveDocument, selectedIds)) {- return 'not-ready';+ return { status: 'not-ready' };}const rawEntries = contributors.map((contributor) => this.deps.layers.get(contributor.id));if (rawEntries.some((entry) => !entry || entry.stale)) {- return 'not-ready';+ return { status: 'not-ready' };}const successful = exports as Extract<ExportResult, { status: 'ok' }>[];let rect = successful[0]!.rect;@@ -474,7 +558,7 @@ export class MergeLayerController {}rect = roundOut(rect);if (isEmpty(rect)) {- return 'nothing';+ return { status: 'nothing' };}const rawBytes = rawEntries.reduce((bytes, entry) => bytes + rgbaBytes(entry!.rect), 0);const mergedBytes = rgbaBytes(rect);@@ -482,13 +566,13 @@ export class MergeLayerController {historyBytes: rawBytes + mergedBytes + contributors.length * HISTORY_ENTRY_OVERHEAD_BYTES,});if (!('publish' in txn)) {- return layerEditRefusal(txn.status);+ return { status: layerEditRefusal(txn.status) };}try {// Besides already-reserved baked exports, the transaction simultaneously// owns raw undo snapshots, the flattened result, and its prepared cache.if (!txn.reserveRaster(rawBytes + mergedBytes * 2)) {- return 'over-budget';+ return { status: 'over-budget' };}const rawSnapshots = contributors.map((contributor, index) => {const entry = rawEntries[index]!;@@ -510,10 +594,10 @@ export class MergeLayerController {context.globalAlpha = 1;context.globalCompositeOperation = 'source-over';- const resultLayer = paintLayerAt(ctx.createLayerId(), `${contributors[0]!.name} merged`, rect);+ const resultLayer = spec.createResult(ctx.createLayerId(), contributors, rect);const resultId = resultLayer.id;const contributorIds = contributors.map((layer) => layer.id);- const anchor = ctx.captureInsertionAnchor('raster', contributors[0]!.id);+ const anchor = ctx.captureInsertionAnchor(spec.stack, contributors[0]!.id);const restoreInsertions = contributors.map((layer) => ({anchor: ctx.captureRestoreAnchor(layer.id)!,nodes: [layer],@@ -566,14 +650,14 @@ export class MergeLayerController {};};const status = layerOperationStatus(- txn.publish('Merge selected layers', mergeStep(), {+ txn.publish(spec.label, mergeStep(), {bytes: rawBytes + mergedBytes + contributors.length * HISTORY_ENTRY_OVERHEAD_BYTES,heldAssetRefs: collectHistoryMediaRefs(rawSnapshots.map(({ layer }) => layer)),redo: () => withReplayReservation(ctx, mergedBytes, () => ctx.applyStep(mergeStep())),undo: () => withReplayReservation(ctx, rawBytes, () => ctx.applyStep(restoreStep())),}));- return status === 'committed' ? 'merged' : status;+ return status === 'committed' ? { layerId: resultId, status: 'merged' } : { status };} finally {txn.end();}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.tsindex ac3038f96b..f90dcd82f4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts@@ -1,3 +1,4 @@+import type { CanvasKeyOwner, CanvasSurfaceAttachOptions } from '@workbench/canvas-engine/capabilities';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { RenderScheduler, RenderSchedulerDeps } from '@workbench/canvas-engine/render/scheduler';@@ -70,6 +71,7 @@ export class RenderController {private overlay: RasterSurface | null = null;private input: HTMLCanvasElement | null = null;private keyboardRoot: HTMLElement | null = null;+ private resolveKeyOwner: ((event: KeyboardEvent) => CanvasKeyOwner) | null = null;private disposed = false;constructor(private readonly options: RenderControllerOptions) {@@ -92,7 +94,17 @@ export class RenderController {return this.keyboardRoot;}- attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement, keyboardRoot?: HTMLElement): void {+ /** The host's key-owner judge from the current attach; null when detached or none was given. */+ getKeyOwnerResolver(): ((event: KeyboardEvent) => CanvasKeyOwner) | null {+ return this.resolveKeyOwner;+ }++ attach(+ screenCanvas: HTMLCanvasElement,+ overlayCanvas: HTMLCanvasElement,+ keyboardRoot?: HTMLElement,+ options?: CanvasSurfaceAttachOptions+ ): void {if (this.disposed || this.options.isEngineDisposed()) {return;}@@ -103,6 +115,7 @@ export class RenderController {this.overlay = wrapCanvasSurface(overlayCanvas);this.input = overlayCanvas;this.keyboardRoot = keyboardRoot ?? overlayCanvas;+ this.resolveKeyOwner = options?.resolveKeyOwner ?? null;const handlers = this.options.getInputHandlers();this.input.addEventListener('pointerdown', handlers.onPointerDown);this.input.addEventListener('pointermove', handlers.onPointerMove);@@ -158,6 +171,7 @@ export class RenderController {this.overlay = null;this.input = null;this.keyboardRoot = null;+ this.resolveKeyOwner = null;this.options.updateAnimation();}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.tsindex 678f8c249b..73acf53b75 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts@@ -73,6 +73,21 @@ describe('planScreenComposition', () => {expect(plan.isolationLayerId).toBe('c1');});+ it('hides mask and region stacks as staging does, while an isolated mask still draws', () => {+ const nodes = [+ layer('m1', 'inpaint_mask'),+ groupContract('regions', [layer('g1', 'regional_guidance')]),+ layer('c1', 'control'),+ layer('r1', 'raster'),+ ];+ const staging = { control: true, inpaint_mask: false, regional_guidance: false };++ expect(drawn(planScreenComposition(leaves(nodes), view({ showOverlayStacks: staging })))).toEqual(['r1', 'c1']);+ expect(+ drawn(planScreenComposition(leaves(nodes), view({ isolationLayerId: 'm1', showOverlayStacks: staging })))+ ).toEqual(['m1']);+ });+it('isolates a group as every leaf beneath it', () => {const plan = planScreenComposition(leaves([diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.tsindex 07c7fe4d76..fbf8f8fbe7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts@@ -10,6 +10,7 @@ import { describe, expect, it } from 'vitest';import {areSelectedRasterLayersContiguous,+ canMergeInpaintMasks,canMergeSelectedRasters,canMergeVisibleRasters,getMergeVisibleRasterLayers,@@ -113,3 +114,37 @@ describe('merge-selected eligibility', () => {);});});++describe('merge-masks eligibility', () => {+ const nodes = [+ mask('top'),+ groupContract('a', [mask('inA')]),+ groupContract('b', [mask('inB')]),+ groupContract('lockedGroup', [mask('underLock')], { isLocked: true }),+ layerContract('disabled', 'inpaint_mask', { isEnabled: false }),+ layerContract('locked', 'inpaint_mask', { isLocked: true }),+ layerContract('region', 'regional_guidance'),+ mask('empty'),+ raster('raster'),+ ];+ const can = (ids: string[]) => canMergeInpaintMasks(leavesOf(nodes), new Set(ids), hasContent);++ it('accepts two or more contributing, unlocked masks with pixels in any groups', () => {+ expect(can(['top', 'inA', 'inB'])).toBe(true);+ expect(can(['inA', 'inB'])).toBe(true);+ });++ it.each([+ ['a single mask', ['top']],+ ['a regional guidance layer', ['top', 'region']],+ ['a raster', ['top', 'raster']],+ ['a group', ['top', 'a']],+ ['a missing id', ['top', 'gone']],+ ['a disabled mask', ['top', 'disabled']],+ ['a locked mask', ['top', 'locked']],+ ['a mask under a locked group', ['top', 'underLock']],+ ['a mask without pixels', ['top', 'empty']],+ ])('refuses a selection holding %s', (_, ids) => {+ expect(can(ids)).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.tsindex 1cc4c152d4..c1396442cb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts@@ -81,3 +81,34 @@ export const canMergeSelectedRasters = (leaf.layer.blendMode === 'normal' &&hasContent(leaf.id));++/**+ * Whether merge-masks can take the exact selection: two or more inpaint masks, each contributing, unlocked and holding+ * pixels, wherever they sit in the stack. Regional guidance never merges this way.+ */+export const canMergeInpaintMasks = (+ leaves: readonly SemanticLeaf[],+ selectedLayerIds: ReadonlySet<string>,+ hasContent: HasMergeVisibleContent+): boolean => {+ if (selectedLayerIds.size < 2) {+ return false;+ }+ let found = 0;+ for (const leaf of leaves) {+ if (!selectedLayerIds.has(leaf.id)) {+ continue;+ }+ if (+ leaf.layer.type !== 'inpaint_mask' ||+ !leaf.contributionEnabled ||+ leaf.effectiveLocked ||+ !hasContent(leaf.id)+ ) {+ return false;+ }+ found += 1;+ }+ // A selected group or a missing id is not a mask leaf.+ return found === selectedLayerIds.size;+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.tsindex 1e3334a9a7..ccb6e5aff0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts@@ -110,7 +110,20 @@ const offscreenDocument = () =>const createFramedEngine = (pendingLayerIds: ReadonlySet<string>) => {const document = offscreenDocument();- const canvas = { document, documentRevision: 0, snapshots: [], version: 3 };+ const canvas = {+ document,+ documentRevision: 0,+ snapshots: [],+ stagingArea: {+ areThumbnailsVisible: false,+ autoSwitchMode: 'off' as const,+ isVisible: false,+ pendingImageIds: [],+ pendingImages: [],+ selectedImageIndex: 0,+ },+ version: 3,+ };const store = {discardLayer: vi.fn(),dispose: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex e257044e1e..8a996a237d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -31,9 +31,10 @@ import {type EngineTestAction = WorkbenchAction | CanvasProjectMutation;import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';+import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';+import * as compositor from '@workbench/canvas-engine/render/compositor';import { DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';@@ -232,6 +233,21 @@ const rasterLayer = (id: string, opts: { imageName?: string; opacity?: number }type: 'raster',});+/** A raster the brush cannot paint in place, so a stroke on it auto-creates a paint layer. */+const textRasterLayer = (id: string): CanvasLayerContract => ({+ ...(rasterLayer(id) as CanvasRasterLayerContractV2),+ source: {+ align: 'left',+ color: '#000000',+ content: id,+ fontFamily: 'sans',+ fontSize: 20,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+});+const makeDoc = (): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },@@ -813,6 +829,61 @@ describe('createCanvasEngine', () => {engine.lifecycle.dispose();});+ it('sends a pick’s commit or cancel only to the sink that took its first preview', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const layer = {+ ...rasterLayer('a'),+ source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' as const },+ };+ const document = { ...makeDoc(), stacks: stacksFrom([layer]), selectedLayerId: layer.id };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const overlay = createInputCanvas();+ engine.surface.attach(createInputCanvas().element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ const routed: string[] = [];+ engine.tools.setColorSampleRouter((_hex, phase) => {+ routed.push(phase);+ return true;+ });++ // A standing pick is under way when a one-shot request arrives: the router's pick is cancelled, once.+ engine.tools.setTool('colorPicker');+ overlay.fire('pointerdown', pointerAt(5, 5));+ let settled: string | null | undefined;+ void engine.tools.requestColorSample().then((hex) => {+ settled = hex;+ });+ expect(routed).toEqual(['preview', 'cancel']);+ overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));+ overlay.fire('pointerdown', pointerAt(5, 5));+ overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));+ await flushMicrotasks();+ expect(settled).toBe('#000000');++ // A request settled by Escape mid-pick sends its pick's cancel nowhere near the router.+ void engine.tools.requestColorSample().then((hex) => {+ settled = hex;+ });+ overlay.fire('pointerdown', pointerAt(5, 5));+ engine.tools.handleEscapePriority({ gestureWasActive: false });+ overlay.fire('pointercancel', pointerAt(5, 5, { buttons: 0 }));+ await flushMicrotasks();+ expect(settled).toBeNull();+ expect(routed).toEqual(['preview', 'cancel']);+ engine.lifecycle.dispose();+ });+it('returns stale when cooldown changes lifecycle generation during raster detachment', async () => {const pending = createDeferred<Blob>();const { store } = createReactiveStore(makeDoc());@@ -2110,6 +2181,63 @@ describe('createCanvasEngine', () => {engine.lifecycle.dispose();});+ it('cropAllLayersToBbox crops every unlocked leaf as one undo step and replays every contract', async () => {+ const document = {+ ...makeDoc(),+ bbox: { height: 8, width: 10, x: 8, y: 2 },+ stacks: stacksFrom([+ { ...rasterLayer('a'), transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 5, y: 5 } },+ { ...rasterLayer('locked'), isLocked: true },+ { ...rasterLayer('outside'), isEnabled: false, transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 60, y: 60 } },+ {+ children: [+ {+ ...maskLayer('mask'),+ isHidden: true,+ mask: {+ bitmap: { height: 10, imageName: 'mask-img', width: 10 },+ fill: { color: '#123456', style: 'crosshatch' as const },+ offset: { x: 0, y: 0 },+ },+ },+ ],+ id: 'masks',+ isEnabled: true,+ isLocked: false,+ name: 'Masks',+ type: 'group',+ },+ ]),+ };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const before = structuredClone(engine.document.getDocument()!);++ expect(await engine.layers.cropAllLayersToBbox()).toEqual({ cropped: 3, skippedLocked: 1, status: 'cropped' });+ const cropped = structuredClone(engine.document.getDocument()!);+ expect(getDocumentLayer(cropped, 'a')).toMatchObject({ source: { bitmap: null, offset: { x: 8, y: 5 } } });+ expect(getDocumentLayer(cropped, 'outside')).toMatchObject({ isEnabled: false, source: { bitmap: null } });+ expect(getDocumentLayer(cropped, 'mask')).toMatchObject({+ isHidden: true,+ mask: { bitmap: null, fill: { color: '#123456', style: 'crosshatch' }, offset: { x: 8, y: 2 } },+ });+ expect(getDocumentLayer(cropped, 'locked')).toEqual(getDocumentLayer(before, 'locked'));+ expect(cropped.stacks.inpaint_mask.map((node) => node.id)).toEqual(['masks']);+ expect(engine.history.getEntries()).toEqual({ future: [], past: ['Crop all layers to frame'] });++ await engine.history.undo();+ expect(engine.document.getDocument()).toEqual(before);+ await engine.history.redo();+ expect(engine.document.getDocument()).toEqual(cropped);+ engine.lifecycle.dispose();+ });+it('cropLayerToBbox returns empty without mutation when the layer and bbox do not overlap', async () => {const document = { ...makeDoc(), bbox: { height: 5, width: 5, x: 50, y: 50 } };const { projectId, store } = createReducerBackedStore(document);@@ -3154,37 +3282,86 @@ const putImageDataCalls = (surfaces: StubRasterSurface[]): { image: unknown; x:);describe('engine-owned pixel editing', () => {- it('materializes an image layer plus eraser stroke as one reversible edit', async () => {- const h = createRasterImageEraserHarness();+ it.each(['eraser', 'brush'] as const)(+ 'materializes an image layer plus %s stroke as one reversible edit',+ async (tool) => {+ const h = createRasterImageEraserHarness();+ await h.publishInitialCache();+ const before = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);++ h.engine.tools.setTool(tool);+ h.overlay.fire('pointerdown', pointerAt(20, 20));+ h.overlay.fire('pointermove', pointerAt(25, 25));+ h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }));++ const after = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);+ expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);+ expect(after).toMatchObject({+ id: 'image',+ source: { type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ });+ expect(after).not.toHaveProperty('adjustments');+ expect(h.strokes).toHaveLength(1);+ expect(h.strokes[0]).toMatchObject({ layerId: 'image', tool });+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledWith('image');+ expect(h.bitmapStore.markLayerDirty).toHaveBeenCalledWith('image');+ expect(h.engine.stores.canUndo.get()).toBe(true);++ await h.engine.history.undo();+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);+ expect(h.engine.stores.canRedo.get()).toBe(true);++ await h.engine.history.redo();+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);+ h.engine.lifecycle.dispose();+ }+ );++ it('draws a Shift-click line from the last stroke end until a replay or document swap forgets it', async () => {+ const h = createRasterImageEraserHarness({ adjustments: [], blendMode: 'normal', opacity: 1 });await h.publishInitialCache();- const before = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);+ // Stroke outlines are traced through Path2D; their horizontal extent tells a dab from a line.+ let xs: number[] = [];+ vi.stubGlobal(+ 'Path2D',+ class RecordingPath2D {+ closePath() {}+ lineTo(x: number) {+ xs.push(x);+ }+ moveTo(x: number) {+ xs.push(x);+ }+ quadraticCurveTo(_cx: number, _cy: number, x: number) {+ xs.push(x);+ }+ }+ );+ const strokeSpan = (fire: () => void): number => {+ xs = [];+ fire();+ return Math.max(...xs) - Math.min(...xs);+ };+ const click = (x: number, shiftKey: boolean) => () => {+ h.overlay.fire('pointerdown', { ...pointerAt(x, 20), shiftKey });+ h.overlay.fire('pointerup', { ...pointerAt(x, 20, { buttons: 0 }), shiftKey });+ };+ h.engine.tools.setTool('brush');+ const dab = strokeSpan(click(12, false));+ // From the eraser, the line still starts where the brush stroke ended; the materialized layer keeps its id.h.engine.tools.setTool('eraser');- h.overlay.fire('pointerdown', pointerAt(20, 20));- h.overlay.fire('pointermove', pointerAt(25, 25));- h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }));-- const after = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);- expect(getDocumentLeaves(h.engine.document.getDocument()!)).toHaveLength(1);- expect(after).toMatchObject({- id: 'image',- source: { type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- });- expect(after).not.toHaveProperty('adjustments');- expect(h.strokes).toHaveLength(1);- expect(h.strokes[0]).toMatchObject({ layerId: 'image', tool: 'eraser' });- expect(h.bitmapStore.suspendLayer).toHaveBeenCalledWith('image');- expect(h.bitmapStore.markLayerDirty).toHaveBeenCalledWith('image');- expect(h.engine.stores.canUndo.get()).toBe(true);+ expect(strokeSpan(click(42, true))).toBeGreaterThanOrEqual(dab + 30);+ expect(h.strokes).toHaveLength(2);await h.engine.history.undo();- expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);- expect(h.engine.stores.canRedo.get()).toBe(true);+ expect(strokeSpan(click(12, true))).toBeCloseTo(dab, 6);- await h.engine.history.redo();- expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);+ h.engine.document.replaceDocument(structuredClone(h.engine.document.getDocument()!));+ await h.publishInitialCache();+ expect(strokeSpan(click(42, true))).toBeCloseTo(dab, 6);h.engine.lifecycle.dispose();});@@ -8713,6 +8890,11 @@ const imageSelectedDoc = (): CanvasDocumentContractV3 => ({width: 100,});+const textSelectedDoc = (): CanvasDocumentContractV3 => ({+ ...imageSelectedDoc(),+ stacks: stacksFrom([textRasterLayer('img')]),+});+describe('engine-owned history: composed auto-create + stroke entry', () => {it('undo removes the auto-created layer (no pixel restore); redo re-adds it and re-applies the stroke', async () => {const raf = createControllableRaf();@@ -8728,7 +8910,7 @@ describe('engine-owned history: composed auto-create + stroke entry', () => {});- const { store } = createReactiveStore(imageSelectedDoc());+ const { store } = createReactiveStore(textSelectedDoc());const dispatch = store.dispatch as Mock;const base = createTestStubRasterBackend();const surfaces: StubRasterSurface[] = [];@@ -15236,6 +15418,315 @@ describe('fitToView: content ∪ bbox', () => {// ---- transform session: param commit (image) + pixel bake (paint) ----------+describe('masks while a result is staged', () => {+ it('hides masks and region tints for the whole staging session, redrawing in full when it starts and ends', () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const composite = vi.spyOn(compositor, 'compositeDocument');+ let canvas = makeCanvas({ ...makeDoc(), stacks: stacksFrom([maskLayer('m'), rasterLayer('a')]) });+ const listeners = new Set<() => void>();+ const store: EngineStore = {+ dispatch: vi.fn(),+ getState: () => ({ activeProjectId: 'p1', projects: [{ canvas, id: 'p1' }] }) as unknown as WorkbenchState,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ const setCandidates = (pendingImages: CanvasStagingCandidateContract[]): void => {+ canvas = { ...canvas, stagingArea: { ...canvas.stagingArea, isVisible: false, pendingImages } };+ for (const listener of listeners) {+ listener();+ }+ };+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ engine.surface.attach(createInputCanvas().element, createInputCanvas().element);+ const frame = () => {+ composite.mockClear();+ raf.flush();+ const options = composite.mock.calls.at(-1)?.[4];+ return {+ damage: options?.damage?.kind,+ drawn: options?.preparation?.leaves.map((leaf) => leaf.id),+ regionOverlays: options?.regionOverlays,+ };+ };+ expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });++ // A candidate whose preview is toggled off still hides the masks.+ setCandidates([+ {+ height: 20,+ imageName: 'staged.png',+ imageUrl: '/staged.png',+ placement: { height: 20, opacity: 1, width: 20, x: 0, y: 0 },+ queuedAt: '2026-07-16T00:00:00.000Z',+ sourceQueueItemId: 'queue',+ thumbnailUrl: '/staged-thumb.png',+ width: 20,+ },+ ]);+ expect(frame()).toEqual({ damage: 'full', drawn: ['a'], regionOverlays: false });++ setCandidates([]);+ expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });+ composite.mockRestore();+ engine.lifecycle.dispose();+ });+});++describe('beginTransform', () => {+ const setup = (layers: CanvasLayerContract[], selectedLayerId: string | null) => {+ const { dispatch, projectId, store } = createReducerBackedStore({+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId,+ stacks: stacksFrom(layers),+ version: 3,+ width: 100,+ });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ return { dispatch, engine };+ };++ it('selects the layer and opens its session now, even with transform already active and no session', () => {+ const { engine } = setup([rasterLayer('a'), rasterLayer('b')], null);+ engine.tools.setTool('transform');+ expect(engine.stores.transformSession.get()).toBeNull();++ expect(engine.layers.beginTransform('b')).toBe('started');+ expect(engine.document.getDocument()?.selectedLayerId).toBe('b');+ expect(engine.stores.activeTool.get()).toBe('transform');+ expect(engine.stores.transformSession.get()?.layerId).toBe('b');+ engine.lifecycle.dispose();+ });++ it('cancels a session on another layer, dropping its preview, before opening one on the target', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.tools.setTool('transform');+ engine.layers.updateTransformSession({ rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 });+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('started');+ expect(engine.stores.transformSession.get()).toMatchObject({+ layerId: 'b',+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ });+ // Only the selection changed: the abandoned preview on `a` never landed.+ expect(dispatch.mock.calls.map(([action]) => action.type)).toEqual(['setCanvasSelectedLayer']);+ expect(getDocumentLayer(engine.document.getDocument(), 'a')?.transform.scaleX).toBe(1);+ engine.lifecycle.dispose();+ });++ it.each([+ ['locked', [{ ...rasterLayer('b'), isLocked: true }], 'locked'],+ ['a mask', [thumbnailMaskLayer('b', 'inpaint_mask')], 'ineligible'],+ ['missing', [rasterLayer('a')], 'missing'],+ ] as const)('refuses %s without selecting or switching tools', (_, layers, status) => {+ const { dispatch, engine } = setup([rasterLayer('a'), ...layers.filter((layer) => layer.id !== 'a')], 'a');++ expect(engine.layers.beginTransform('b')).toBe(status);+ expect(dispatch).not.toHaveBeenCalled();+ expect(engine.stores.activeTool.get()).not.toBe('transform');+ expect(engine.stores.transformSession.get()).toBeNull();+ engine.lifecycle.dispose();+ });++ /** Paints a stroke onto a new layer, then asks for its transform before persistence acknowledges the pixels. */+ const strokeThenTransform = (options: { uploadImage?: () => Promise<never> } = {}) => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );+ // The window key listeners attach adds, so a test can hold Space as the browser would deliver it.+ const windowListeners = new Map<string, (event: unknown) => void>();+ vi.stubGlobal('addEventListener', (type: string, listener: (event: unknown) => void) =>+ windowListeners.set(type, listener)+ );+ vi.stubGlobal('removeEventListener', (type: string) => windowListeners.delete(type));+ const { dispatch, projectId, store } = createReducerBackedStore({+ ...makeDoc(),+ selectedLayerId: null,+ stacks: stacksFrom([]),+ });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ ...(options.uploadImage ? { uploadImage: options.uploadImage } : { bitmapStore: createSpyBitmapStore() }),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const overlay = createInputCanvas();+ engine.surface.attach(createInputCanvas().element, overlay.element);+ const strokes: StrokeCommittedEvent[] = [];+ engine.tools.onStrokeCommitted((event) => strokes.push(event));+ const refusals: string[] = [];+ engine.tools.onEditRefused((refusal) => refusals.push(refusal));+ engine.tools.setTool('brush');+ overlay.fire('pointerenter', pointerAt(20, 20));+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(40, 40));+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));+ const stroke = strokes[0]!;+ // Its pixels live only in the cache until persistence acknowledges the bitmap.+ expect(engine.layers.beginTransform(stroke.layerId)).toBe('started');+ expect(engine.stores.activeTool.get()).toBe('transform');+ expect(engine.stores.transformSession.get()).toBeNull();+ expect(engine.interaction.get('pendingTransformLayerId')).toBe(stroke.layerId);+ const key = (type: 'keydown' | 'keyup', code: string) =>+ windowListeners.get(type)?.({ code, key: code === 'Space' ? ' ' : code, preventDefault: () => {}, target: null });+ const persist = () =>+ dispatch({+ id: stroke.layerId,+ source: {+ bitmap: { height: stroke.dirtyRect.height, imageName: 'stroke.png', width: stroke.dirtyRect.width },+ offset: { x: stroke.dirtyRect.x, y: stroke.dirtyRect.y },+ type: 'paint',+ },+ type: 'updateCanvasLayerSource',+ });+ const sessionLayerId = () => engine.stores.transformSession.get()?.layerId ?? null;+ return { engine, key, layerId: stroke.layerId, persist, refusals, sessionLayerId };+ };++ it('opens a transform requested right after a stroke once its pixels are persisted', () => {+ const h = strokeThenTransform();+ h.persist();+ expect(h.sessionLayerId()).toBe(h.layerId);+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBeNull();+ h.engine.lifecycle.dispose();+ });++ it('keeps waiting through a Space pan held meanwhile, opening when the pixels land under the hold', () => {+ const h = strokeThenTransform();+ h.key('keydown', 'Space');+ expect(h.engine.stores.activeTool.get()).toBe('view');+ h.persist();+ expect(h.sessionLayerId()).toBe(h.layerId);+ h.key('keyup', 'Space');+ expect(h.engine.stores.activeTool.get()).toBe('transform');+ expect(h.sessionLayerId()).toBe(h.layerId);+ h.engine.lifecycle.dispose();+ });++ it.each([+ ['a tool switch', (engine: CanvasEngine) => engine.tools.setTool('brush')],+ ['Escape', (engine: CanvasEngine) => engine.tools.handleEscapePriority({ gestureWasActive: false })],+ ])('stops waiting on %s', (_, end) => {+ const h = strokeThenTransform();+ end(h.engine);+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBeNull();+ h.persist();+ expect(h.sessionLayerId()).toBeNull();+ h.engine.lifecycle.dispose();+ });++ it('keeps waiting through retried upload failures, and stops with a refusal once no retry follows', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ const h = strokeThenTransform({ uploadImage: () => Promise.reject(new Error('offline')) });+ // Advances the fake clock, then yields to real I/O: hashing the encoded pixels settles outside the clock.+ const advance = async (ms: number) => {+ await vi.advanceTimersByTimeAsync(ms);+ await new Promise<void>((resolve) => {+ const channel = new MessageChannel();+ channel.port1.onmessage = () => {+ channel.port1.close();+ resolve();+ };+ channel.port2.postMessage(null);+ });+ };+ // One barrier: every upload attempt fails, its retry delays elapse on the fake clock.+ const failFlush = async () => {+ const flush = { settled: false };+ void h.engine.lifecycle+ .flushPendingUploads()+ .catch(() => undefined)+ .then(() => {+ flush.settled = true;+ });+ for (let step = 0; step < 200 && !flush.settled; step += 1) {+ await advance(250);+ }+ expect(flush.settled).toBe(true);+ };++ await failFlush();+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBe(h.layerId);+ expect(h.refusals).toEqual([]);++ // The store retries on its own backoff until its consecutive-failure limit stops it.+ for (let step = 0; step < 300 && h.engine.interaction.get('pendingTransformLayerId'); step += 1) {+ await advance(1000);+ }+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBeNull();+ expect(h.refusals).toEqual(['not-ready']);+ h.engine.lifecycle.dispose();+ } finally {+ vi.useRealTimers();+ }+ });++ it('refuses as busy while interaction is locked, leaving the selection and tool unchanged', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.tools.setInteractionLocked(true);+ // The lock itself parks the surface on the view tool.+ const lockedTool = engine.stores.activeTool.get();+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('busy');+ expect(dispatch).not.toHaveBeenCalled();+ expect(engine.document.getDocument()?.selectedLayerId).toBe('a');+ expect(engine.stores.activeTool.get()).toBe(lockedTool);+ expect(engine.stores.transformSession.get()).toBeNull();+ engine.lifecycle.dispose();+ });++ it('refuses as busy while document edits are locked, leaving the selection and tool unchanged', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.tools.setTool('brush');+ engine.stores.documentEditingLocked.set(true);+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('busy');+ expect(dispatch).not.toHaveBeenCalled();+ expect(engine.stores.activeTool.get()).toBe('brush');+ expect(engine.stores.transformSession.get()).toBeNull();+ engine.lifecycle.dispose();+ });++ it('refuses as busy once disposed, without touching the selection', () => {+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');+ engine.lifecycle.dispose();+ dispatch.mockClear();++ expect(engine.layers.beginTransform('b')).toBe('busy');+ expect(dispatch).not.toHaveBeenCalled();+ });+});+describe('transform session', () => {it('image layer Apply commits one structural transform with the exact inverse', async () => {const { store } = createReactiveStore(selectedImageDoc());@@ -18962,6 +19453,7 @@ describe('layer quick-switch memory', () => {hasSelectedStagedCandidate: false,isInteractionLocked: false,copySelection: vi.fn(),+ cropAllLayers: vi.fn(),swapActiveColors: vi.fn(),resetActiveColors: vi.fn(),pasteFromClipboard: vi.fn(),@@ -18969,6 +19461,7 @@ describe('layer quick-switch memory', () => {reportStructuralCommit: vi.fn(),reportPreparedCommit: vi.fn(),reportLayerOperation: vi.fn(),+ reportTransformRefusal: vi.fn(),t: (key) => key,});};@@ -19048,7 +19541,7 @@ describe('layer quick-switch memory', () => {vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);const document = {...makeDoc(),- stacks: stacksFrom([rasterLayer('a'), rasterLayer('b'), rasterLayer('c')]),+ stacks: stacksFrom([rasterLayer('a'), textRasterLayer('b'), rasterLayer('c')]),selectedLayerId: 'a',};const { setDocument, store } = createReactiveStore(document);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 7d850b10de..53b4a3e49e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -1,4 +1,5 @@import type {+ BeginTransformResult,CanvasEditRefusal,CanvasHistoryReplayStatus,CanvasHistoryCapability,@@ -16,17 +17,21 @@ import type {CanvasDocumentSnapshot,CanvasLifecycleCapability,CanvasSelectionCapability,+ CanvasSurfaceAttachOptions,CanvasSurfaceCapability,CanvasViewportCapability,+ ColorSamplePhase,BooleanRasterOperation,BooleanRasterResult,CopyLayerToRasterResult,+ CropAllLayersResult,CropLayerResult,ExportBakedLayerPixelsOptions,ExportLayerPixelsOptions,ExtractMaskedAreaResult,MaskEditResult,MergeDownResult,+ MergeInpaintMasksResult,MergeVisibleResult,NewRasterLayerResult,PsdExportResult,@@ -124,6 +129,7 @@ import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import {compileDocumentLeaves,createDocumentModel,+ lookupDocumentLeaf,type CanvasDocumentModel,} from '@workbench/canvas-engine/document-model/documentModel';import {@@ -178,7 +184,7 @@ import { stepBrushSize } from '@workbench/canvas-engine/tools/paintConstants';import { createSamTool } from '@workbench/canvas-engine/tools/samTool';import { createShapeTool } from '@workbench/canvas-engine/tools/shapeTool';import { createTextTool } from '@workbench/canvas-engine/tools/textTool';-import { createTransformTool } from '@workbench/canvas-engine/tools/transformTool';+import { createTransformTool, isTransformEligible } from '@workbench/canvas-engine/tools/transformTool';import { FULL_DAMAGE } from '@workbench/canvas-engine/types';import { createViewport, type Viewport } from '@workbench/canvas-engine/viewport';@@ -189,6 +195,7 @@ import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';import { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';import { decideLayerChange } from './document/layerChangeDecision';+import { canMergeInpaintMasks as canMergeInpaintMasksIn } from './document/mergeVisible';import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';import { collectCanvasFontReferences, replaceCanvasFontReferences } from './fontReferences';import { createLayerExportGuards, isSupportedExportSource } from './layerExportGuards';@@ -393,6 +400,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCtextEditSession: stores.textEditSession,textOptions: stores.textOptions,transformSession: stores.transformSession,+ pendingTransformLayerId: stores.pendingTransformLayerId,viewportReady: stores.viewportReady,zoom: stores.zoom,};@@ -622,14 +630,19 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}return { offset: { x: entry.rect.x, y: entry.rect.y }, surface: entry.surface };},- onError: (error, layerId, info) =>+ onError: (error, layerId, info) => {+ // A retry may still land the pixels; only a failure no retry follows ends the wait.+ if (!info.willRetry) {+ failPendingTransform(layerId);+ }reportError(info.willRetry ? 'Bitmap persistence failed' : 'Bitmap persistence suspended',layerId,// Lead circuit-opening feedback with persistence stopping until a fresh stroke, rather than repeating// the underlying error.info.willRetry ? error : new Error('Canvas changes are no longer uploading. A new stroke will retry.')- ),+ );+ },uploadImage: (blob) => opts.uploadImage(blob),});const persistenceController = new PersistenceController(bitmapStore);@@ -639,6 +652,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// replaying over either would land on state the entry never saw. Put both back first; neither is itself// undoable until it commits.beforeReplay: () => {+ paintLineEnds.clear();floatingSelection.cancel();structuralController.endPreview();},@@ -980,16 +994,56 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}/**- * One-shot color claims stash samples during press/drag and settle on release, after structural edits are+ * One-shot color claims take a pick's previews and settle on its release commit, after structural edits are* allowed. Escape, tool change and teardown resolve null.*/let pendingColorSample: {previousToolId: ToolId;resolve: (hex: string | null) => void;- sampledHex: string | null;} | null = null;// Where unclaimed eyedropper samples land while a workbench is attached.- let colorSampleRouter: ((hex: string) => boolean) | null = null;+ let colorSampleRouter: ((hex: string, phase: ColorSamplePhase) => boolean) | null = null;+ // Which sink took the current pick's first preview; null between picks.+ let colorPickSink: 'request' | 'router' | null = null;+ // Shift-click line starts: where the last brush or eraser stroke ended on each layer. Engine-lifetime memory,+ // kept across tool switches and forgotten on replay, document replacement and layer removal.+ const paintLineEnds = new Map<string, Vec2>();+ /**+ * A transform requested on pixels persistence has not acknowledged yet (a stroke's first upload) waits in+ * `pendingTransformLayerId`: sessions size their frame from the persisted source, so the session opens once the+ * bitmap lands, if the layer is still the selection under the transform tool (or a hold over it) with no session+ * open. Otherwise the wait ends there; a genuine tool switch, Escape, document replacement and a failed upload of+ * that layer end it too.+ */+ const openDeferredTransform = (): void => {+ const layerId = stores.pendingTransformLayerId.get();+ if (layerId === null) {+ return;+ }+ const document = mirror.getDocument();+ const layer = getDocumentLayer(document, layerId);+ // A Space, Alt or C hold only lends the surface to another tool; the user is still on transform.+ const toolId = pipeline.heldRestoreToolId() ?? interactionController.getActiveToolId();+ if (+ !document ||+ !layer ||+ document.selectedLayerId !== layerId ||+ toolId !== 'transform' ||+ stores.transformSession.get() !== null+ ) {+ stores.pendingTransformLayerId.set(null);+ } else if (isTransformEligible(layer, document)) {+ stores.pendingTransformLayerId.set(null);+ beginTransformSession(layerId);+ }+ };+ /** A pending transform whose pixels could not be persisted will not open; say so instead of waiting silently. */+ const failPendingTransform = (layerId: string): void => {+ if (stores.pendingTransformLayerId.get() === layerId) {+ stores.pendingTransformLayerId.set(null);+ reportEditRefusal('not-ready');+ }+ };const toolContext: ToolContext = {applyTransform: () => applyTransform(),@@ -1046,23 +1100,25 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetSamInteraction: () => stores.samInteraction.get(),openTextCreate: (docPoint) => openTextCreate(docPoint),openTextEdit: (layerId) => openTextEdit(layerId),+ paintLineEnds,sampleProviders: colorSampleProviders,- resolveColorSample: (hex) => {- if (pendingColorSample) {- pendingColorSample.sampledHex = hex;- return true;+ resolveColorSample: (hex, phase) => {+ // A pick belongs to whichever sink took its first preview; its commit or cancel goes there alone, so a+ // request armed or settled mid-pick never strays into the router, nor the router's pick into the request.+ if (phase === 'preview') {+ colorPickSink ??= pendingColorSample ? 'request' : 'router';}- return colorSampleRouter?.(hex) ?? false;- },- commitColorSample: () => {- if (pendingColorSample !== null && pendingColorSample.sampledHex !== null) {- settleColorSample(pendingColorSample.sampledHex, true);+ const sink = colorPickSink;+ if (phase !== 'preview') {+ colorPickSink = null;}- },- discardColorSample: () => {- if (pendingColorSample !== null) {- pendingColorSample.sampledHex = null;+ if (sink === 'request') {+ if (phase === 'commit' && pendingColorSample) {+ settleColorSample(hex, true);+ }+ return true;}+ return sink === 'router' ? (colorSampleRouter?.(hex, phase) ?? false) : false;},setLayerTransformOverride: (layerId, override) => {if (override) {@@ -1397,6 +1453,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC});const scheduler: RenderScheduler = renderController.scheduler;+ /** Whether staging holds a candidate, even while its preview is toggled off; the screen then hides masks. */+ const hasStagedCandidates = (): boolean => (mutationPort.getCanvasState()?.stagingArea.pendingImages.length ?? 0) > 0;+ let hadStagedCandidates = hasStagedCandidates();const compositeFrame = createCompositeFrame({backend,derivedSurfaceCache,@@ -1408,6 +1467,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreClayerCache,previews: renderController.previews,raster: rasterController,+ hasStagedCandidates,rasterizeLayer: (layer, doc) => void getOrStartLayerRasterization(layer, doc),stores,transformOverrides,@@ -1465,7 +1525,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC/** Actual last non-null selection, retained across deselect/reselect and updated by engine selections too. */let lastSelectedLayerId: string | null = null;const mirror: DocumentMirror = createDocumentMirror(mutationPort, {- onDocumentChanged: () => stores.documentEpoch.set(stores.documentEpoch.get() + 1),+ onDocumentChanged: () => {+ openDeferredTransform();+ stores.documentEpoch.set(stores.documentEpoch.get() + 1);+ },// Bbox changes need only overlay redraw unless a bbox-relative staged preview must move in the composite.// Explicitly placed candidates stay fixed.onBboxChanged: () => {@@ -1484,7 +1547,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// anchors and clear active-gesture state; also clear any lingering bbox preview.cleanup.run(() => stores.bboxPreview.set(null));cleanup.run(() => history.clear());+ paintLineEnds.clear();cleanup.run(() => stores.transformSession.set(null));+ cleanup.run(() => stores.pendingTransformLayerId.set(null));cleanup.run(() => transformOverrides.clear());// A text-edit session likewise belongs to the outgoing document; drop it.cleanup.run(() => stores.textEditSession.set(null));@@ -1569,6 +1634,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCsourceChanged: sourceChanged.has(id),});if (decision.kind === 'removed') {+ paintLineEnds.delete(id);rasterController.deleteThumbnailKey(id);cleanup.run(() => dropLayer(id));// Removed preview layers must drop decoded pixels and advance decode tokens so late results or restored@@ -1634,7 +1700,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => scheduler.invalidate({ overlay: true }));cleanup.throwIfFailed();},- onStagingChanged: () => scheduler.invalidate({ overlay: true }),+ // Gaining the first candidate or losing the last shows or hides masks across the whole screen.+ onStagingChanged: () => {+ const staged = hasStagedCandidates();+ scheduler.invalidate(staged === hadStagedCandidates ? { overlay: true } : { all: true });+ hadStagedCandidates = staged;+ },});// The mirror seeds silently from the current state, so the memory starts from that selection too.lastSelectedLayerId = mirror.getDocument()?.selectedLayerId ?? null;@@ -1766,6 +1837,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// finished the move.if (!switchOptions?.temporary) {floatingSelection.commit();+ // A genuine switch away also ends a transform still waiting on its pixels.+ if (to !== 'transform') {+ stores.pendingTransformLayerId.set(null);+ }}for (const listener of toolChangeListeners) {listener({ from, temporary: switchOptions?.temporary === true, to });@@ -1812,7 +1887,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCpipeline.endForToolSwitch();return new Promise<string | null>((resolve) => {- pendingColorSample = { previousToolId: interactionController.getActiveToolId(), resolve, sampledHex: null };+ pendingColorSample = { previousToolId: interactionController.getActiveToolId(), resolve };interactionController.setTool('colorPicker');});};@@ -1837,6 +1912,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcancelTransform();return;}+ if (stores.pendingTransformLayerId.get() !== null) {+ stores.pendingTransformLayerId.set(null);+ return;+ }if (floatingSelection.has()) {// Escape restores lifted pixels while retaining selection; Enter, deselect and tool switches commit the// float.@@ -1856,6 +1935,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetActiveToolId: () => interactionController.getActiveToolId(),getInputElement: () => renderController.getInputElement(),getKeyboardRoot: () => renderController.getKeyboardRoot(),+ getKeyOwnerResolver: () => renderController.getKeyOwnerResolver(),getToolContext: () => toolContext,handleEscape: handleEscapePriority,hasTool: (id) => tools.has(id),@@ -1930,8 +2010,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst attach = (screenCanvas: HTMLCanvasElement,overlayCanvas: HTMLCanvasElement,- keyboardRoot?: HTMLElement- ): void => renderController.attach(screenCanvas, overlayCanvas, keyboardRoot);+ keyboardRoot?: HTMLElement,+ options?: CanvasSurfaceAttachOptions+ ): void => renderController.attach(screenCanvas, overlayCanvas, keyboardRoot, options);const detach = (): void => renderController.detach();const activate = (): void => {@@ -2271,6 +2352,16 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst mergeSelectedRasterLayers = (layerIds: readonly string[]): Promise<MergeVisibleResult> =>layerController.merge.mergeSelected(layerIds);const mergeVisibleRasterLayers = (): Promise<MergeVisibleResult> => layerController.merge.mergeVisible();+ const canMergeInpaintMasks = (layerIds: readonly string[]): boolean => {+ const document = mirror.getDocument();+ return (+ document !== null &&+ canMergeInpaintMasksIn(compileDocumentLeaves(document), new Set(layerIds), hasExportableLayerContent)+ );+ };+ const mergeInpaintMasks = (layerIds: readonly string[]): Promise<MergeInpaintMasksResult> =>+ layerController.merge.mergeInpaintMasks(layerIds);+ const cropAllLayersToBbox = (): Promise<CropAllLayersResult> => layerController.crop.cropAll();const { captureDocumentSnapshot, captureRasterSnapshot, isDocumentSnapshotCurrent, releaseActiveSnapshots } =createRasterSnapshotCapture({@@ -2302,6 +2393,42 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// paint; Cancel drops previews. Tools and public UI share the session API.const beginTransformSession = (layerId: string): void => editingController.transform.begin(layerId);+ /** Opens a session on `layerId` now, whatever tool is active; the context menu and shortcut use it. */+ const beginTransform = (layerId: string): BeginTransformResult => {+ const document = mirror.getDocument();+ const leaf = lookupDocumentLeaf(document, layerId);+ if (disposed || !document || !leaf) {+ return disposed ? 'busy' : 'missing';+ }+ if (leaf.effectiveLocked) {+ return 'locked';+ }+ const persisted = isTransformEligible(leaf.layer, document);+ if (!persisted && !isTransformEligible(leaf.layer, document, layerCache.peek(layerId)?.rect)) {+ return 'ineligible';+ }+ if (interactionLocked || pipeline.isGestureActive() || floatingSelection.has() || !canEditDocument()) {+ return 'busy';+ }+ // Selecting cancels a session on another layer (see `onSelectionChanged`); entering the tool opens one on the+ // selection, and an already active tool is opened explicitly.+ if (document.selectedLayerId !== layerId) {+ dispatchCanvasMutation({ id: layerId, type: 'setCanvasSelectedLayer' });+ }+ setTool('transform');+ if (stores.transformSession.get()?.layerId !== layerId) {+ cancelTransform();+ if (persisted) {+ beginTransformSession(layerId);+ }+ // Every refusal is decided above, before the selection or tool changes. A layer whose pixels persistence+ // has not acknowledged yet (a stroke's first upload) opens its session once the bitmap lands.+ if (stores.transformSession.get()?.layerId !== layerId) {+ stores.pendingTransformLayerId.set(layerId);+ }+ }+ return 'started';+ };const updateTransformSession = (transform: LayerTransform): void => editingController.transform.update(transform);// A framed float is the session — Apply banks it, Cancel abandons it. Only// with no float in flight do these reach the layer transform session.@@ -2410,6 +2537,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn;}disposed = true;+ paintLineEnds.clear();releaseActiveSnapshots();rasterController.memory.releaseGeneration(lifecycleGeneration);lifecycleGeneration += 1;@@ -2768,7 +2896,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst layersCapability: CanvasEngineLayerCapability = {...layerController.layers,applyTransform,+ beginTransform,booleanMergeRasterLayers,+ canMergeInpaintMasks,cancelTextEdit,cancelTransform,clearMask,@@ -2780,8 +2910,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcommitStagedImage,commitTextEdit,copyLayerToRaster,+ cropAllLayersToBbox,cropLayerToBbox,duplicateLayers,+ mergeInpaintMasks,mergeLayerDown,mergeSelectedRasterLayers,mergeVisibleRasterLayers,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 78890b9850..c4102ed294 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -507,6 +507,8 @@ export interface EngineStores {bboxPreview: ScalarStore<Rect | null>;/** Transform session supplies numeric controls, Apply/Cancel and live preview; null when closed. */transformSession: ScalarStore<TransformSession | null>;+ /** The layer a requested transform session waits on until its fresh pixels are persisted; null when none waits. */+ pendingTransformLayerId: ScalarStore<string | null>;/** Checkerboard defaults on; disabling reveals the widget surface through transparent document pixels. */checkerboard: ScalarStore<boolean>;/**@@ -727,6 +729,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =thumbnailVersion: createKeyedVersionStore(),thumbnailStatus: createKeyedThumbnailStatusStore(),transformSession: createScalarStore<TransformSession | null>(null, transformSessionEqual),+ pendingTransformLayerId: createScalarStore<string | null>(null),viewportReady: createScalarStore<boolean>(false),zoom: createScalarStore<number>(1),});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.tsindex bbaa031e60..62dea4a9b2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts@@ -35,7 +35,7 @@ const createInputHarness = () => {const events: string[] = [];const deactivations: string[] = [];const tools = Object.fromEntries(- (['brush', 'view', 'transform', 'bbox', 'eraser'] as const).map((id): [ToolId, Tool] => [+ (['brush', 'view', 'transform', 'bbox', 'eraser', 'colorPicker'] as const).map((id): [ToolId, Tool] => [id,{id,@@ -233,3 +233,43 @@ describe('pointer pipeline in Chromium: tool switches during a hold', () => {expect(h.interaction.getActiveToolId()).toBe('brush');});});++describe('pointer pipeline in Chromium: Alt eyedropper', () => {+ it('prevents a real Alt tap on the focused canvas, keydown and keyup alike', async () => {+ const h = createInputHarness();+ h.pipeline.onPointerEnter();+ h.surface.focus();++ await userEvent.keyboard('{Alt}');+ expect(h.observed).toEqual([+ { defaultPrevented: true, type: 'keydown' },+ { defaultPrevented: true, type: 'keyup' },+ ]);+ expect(h.interaction.getActiveToolId()).toBe('brush');+ });++ it('leaves a real Alt tap in a text field to the browser', async () => {+ const h = createInputHarness();+ const input = document.createElement('input');+ document.body.append(input);+ cleanups.push(() => input.remove());+ h.pipeline.onPointerEnter();+ input.focus();++ await userEvent.keyboard('{Alt}');+ expect(h.observed.map((event) => event.defaultPrevented)).toEqual([false, false]);+ });++ it('begins the picker when the pointer enters with Alt already held on the focused canvas', async () => {+ const h = createInputHarness();+ h.surface.focus();++ await userEvent.keyboard('{Alt>}');+ expect(h.interaction.getActiveToolId()).toBe('brush');+ h.pipeline.onPointerEnter(new PointerEvent('pointerenter', { altKey: true }));+ expect(h.interaction.getActiveToolId()).toBe('colorPicker');+ await userEvent.keyboard('{/Alt}');+ expect(h.interaction.getActiveToolId()).toBe('brush');+ expect(h.observed.every((event) => event.defaultPrevented)).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.tsindex 485a22c0f1..974e49fa08 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts@@ -1,3 +1,4 @@+import type { CanvasKeyOwner } from '@workbench/canvas-engine/capabilities';import type { PointerPipelineDeps } from '@workbench/canvas-engine/input/pointerPipeline';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, ToolId } from '@workbench/canvas-engine/types';@@ -77,6 +78,7 @@ const createHarness = (handleEscape?: (o: { gestureWasActive: boolean }) => void;maybeCommitModalSession?: () => boolean;replaying?: () => boolean;+ resolveKeyOwner?: (event: KeyboardEvent) => CanvasKeyOwner;} = {}) => {const registered = new Set<ToolId>(opts.tools ?? ['view', 'brush']);@@ -124,6 +126,7 @@ const createHarness = (getActiveToolId: () => activeToolId,getInputElement: () => element,getKeyboardRoot: () => ({ contains: (node) => node === (SURFACE_TARGET as unknown) }),+ getKeyOwnerResolver: () => opts.resolveKeyOwner ?? null,getToolContext: () => ctx,handleEscape: opts.handleEscape,hasTool: (id) => registered.has(id),@@ -532,6 +535,205 @@ describe('pointer pipeline: temporary modifier tools', () => {});});+describe('pointer pipeline: Alt eyedropper hold', () => {+ const pickerHarness = (opts: { resolveKeyOwner?: (event: KeyboardEvent) => CanvasKeyOwner } = {}) =>+ createHarness({ ...opts, tools: ['view', 'brush', 'colorPicker'] });+ const altDown = (target: unknown = SURFACE_TARGET) => makeKeyEvent({ altKey: true, code: 'AltLeft', target });+ const altUp = () => makeKeyEvent({ code: 'AltLeft', target: SURFACE_TARGET });++ it('prevents both halves of an owned Alt tap so the browser menu bar stays closed', () => {+ const h = pickerHarness();+ h.pipeline.onPointerEnter();+ const down = altDown();+ const up = altUp();+ h.pipeline.onKeyDown(down);+ h.pipeline.onKeyUp(up);+ expect(down.preventDefault).toHaveBeenCalledOnce();+ expect(up.preventDefault).toHaveBeenCalledOnce();++ // An unrelated release is still only observed.+ const space = makeKeyEvent({ code: 'Space', target: SURFACE_TARGET });+ h.pipeline.onKeyUp(space);+ expect(space.preventDefault).not.toHaveBeenCalled();+ });++ it('leaves Alt alone in an editable field', () => {+ const h = pickerHarness();+ h.pipeline.onPointerEnter();+ const editable = altDown({ tagName: 'INPUT' });+ const editableUp = makeKeyEvent({ code: 'AltLeft', target: { tagName: 'INPUT' } });+ h.pipeline.onKeyDown(editable);+ h.pipeline.onKeyUp(editableUp);+ expect(editable.preventDefault).not.toHaveBeenCalled();+ expect(editableUp.preventDefault).not.toHaveBeenCalled();+ });++ it.each([+ ['hovered', true],+ ['off the canvas', false],+ ])(+ 'still prevents an owned Alt %s for a tool that uses it as a modifier, but starts and arms no picker',+ (_, hovered) => {+ const h = pickerHarness();+ (h.tool as { usesAltKey?: boolean }).usesAltKey = true;+ if (hovered) {+ h.pipeline.onPointerEnter();+ }+ const down = altDown();+ const up = altUp();+ h.pipeline.onKeyDown(down);+ h.pipeline.onPointerEnter({ altKey: true });+ h.pipeline.onKeyUp(up);+ expect(down.preventDefault).toHaveBeenCalledOnce();+ expect(up.preventDefault).toHaveBeenCalledOnce();+ expect(h.setTool).not.toHaveBeenCalled();+ }+ );++ it('arms a pending hold off the canvas that a pointerenter with Alt still held begins', () => {+ const h = pickerHarness();+ const down = altDown();+ h.pipeline.onKeyDown(down);+ expect(down.preventDefault).toHaveBeenCalledOnce();+ expect(h.setTool).not.toHaveBeenCalled();++ h.pipeline.onPointerEnter({ altKey: true });+ expect(h.setTool).toHaveBeenLastCalledWith('colorPicker', { temporary: true });+ const up = altUp();+ h.pipeline.onKeyUp(up);+ expect(up.preventDefault).toHaveBeenCalledOnce();+ expect(h.setTool).toHaveBeenLastCalledWith('brush', { temporary: true });+ });++ it('drops the pending hold when the pointer enters without Alt', () => {+ const h = pickerHarness();+ h.pipeline.onKeyDown(altDown());+ h.pipeline.onPointerEnter({ altKey: false });+ h.pipeline.onPointerLeave();+ h.pipeline.onPointerEnter({ altKey: true });+ expect(h.setTool).not.toHaveBeenCalled();+ });++ it.each([+ ['the Alt release', (h: ReturnType<typeof createHarness>) => h.pipeline.onKeyUp(altUp())],+ ['a tool switch', (h: ReturnType<typeof createHarness>) => h.pipeline.endForToolSwitch()],+ ['a reset', (h: ReturnType<typeof createHarness>) => h.pipeline.reset()],+ ])('clears the pending hold on %s', (_, clear) => {+ const h = pickerHarness();+ h.pipeline.onKeyDown(altDown());+ clear(h);+ h.pipeline.onPointerEnter({ altKey: true });+ expect(h.setTool).not.toHaveBeenCalled();+ });++ it('begins the pending hold before routing a press that lands without hover, so a pen samples on contact', () => {+ const h = pickerHarness();+ const order: string[] = [];+ h.setTool.mockImplementation((id: ToolId) => order.push(`set:${id}`));+ h.tool.onPointerDown = () => order.push('down');+ h.pipeline.onKeyDown(altDown());++ h.pipeline.onPointerDown(makePointerEvent({ altKey: true, pointerId: 5, pointerType: 'pen' }));+ expect(order).toEqual(['set:colorPicker', 'down']);+ });++ it('arms nothing off the canvas unless the surface owns the key', () => {+ const h = pickerHarness({ resolveKeyOwner: () => 'companion' });+ const down = altDown({ tagName: 'BODY' });+ h.pipeline.onKeyDown(down);+ h.pipeline.onPointerEnter({ altKey: true });+ expect(down.preventDefault).not.toHaveBeenCalled();+ expect(h.setTool).not.toHaveBeenCalled();+ });+});++describe('pointer pipeline: injected key owner', () => {+ const ownerHarness = (owner: CanvasKeyOwner) => {+ const handleEscape = vi.fn();+ const resolveKeyOwner = vi.fn((_event: KeyboardEvent) => owner);+ const h = createHarness({ handleEscape, resolveKeyOwner, tools: ['view', 'brush', 'bbox', 'colorPicker'] });+ const commands: string[] = [];+ h.tool.onKeyCommand = (_ctx, command) => commands.push(command);+ return { ...h, commands, handleEscape, resolveKeyOwner };+ };+ const BODY = { tagName: 'BODY' };++ it.each([+ ['surface', ['apply'], 1],+ ['companion', [], 1],+ ['elsewhere', [], 0],+ ] as const)('with owner %s, Enter applies %j and Escape reaches the ladder %i time(s)', (owner, applied, escapes) => {+ const h = ownerHarness(owner);+ // Focus left on the body by a click outside the canvas no longer settles ownership by itself.+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', target: BODY }));+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Escape', target: BODY }));+ expect(h.commands).toEqual(applied);+ expect(h.handleEscape).toHaveBeenCalledTimes(escapes);+ });++ it('applies Enter from the surface only while focus is on its root or nowhere, not on a clicked control', () => {+ const h = ownerHarness('surface');+ const button = { ...BUTTON_TARGET, matches: () => false };+ h.pipeline.onFocusIn({ target: button } as unknown as FocusEvent);+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', target: button }));+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', target: SURFACE_TARGET }));+ expect(h.commands).toEqual(['apply']);+ });++ it.each([+ ['surface', true],+ ['companion', true],+ ['elsewhere', false],+ ] as const)('with owner %s, a quick C tap selects the frame tool: %s', (owner, selects) => {+ const h = ownerHarness(owner);+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'KeyC', key: 'c', target: BODY }));+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'KeyC', key: 'c', target: BODY }));+ expect(h.setTool.mock.calls.some(([id]) => id === 'bbox')).toBe(selects);+ });++ it.each(['surface', 'companion', 'elsewhere'] as const)(+ 'with owner %s, Space and Alt hold over the hovered canvas',+ (owner) => {+ const h = ownerHarness(owner);+ h.pipeline.onPointerEnter();+ const space = makeKeyEvent({ code: 'Space', target: BODY });+ h.pipeline.onKeyDown(space);+ expect(h.setTool).toHaveBeenLastCalledWith('view', { temporary: true });+ expect(space.preventDefault).toHaveBeenCalledOnce();+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space', target: BODY }));++ const alt = makeKeyEvent({ altKey: true, code: 'AltLeft', target: BODY });+ h.pipeline.onKeyDown(alt);+ expect(h.setTool).toHaveBeenLastCalledWith('colorPicker', { temporary: true });+ expect(alt.preventDefault).toHaveBeenCalledOnce();+ }+ );++ it.each([+ ['companion', false],+ ['elsewhere', false],+ ['surface', true],+ ] as const)('with owner %s and no hover, Alt is claimed: %s', (owner, claimed) => {+ const h = ownerHarness(owner);+ const alt = makeKeyEvent({ altKey: true, code: 'AltLeft', target: BODY });+ h.pipeline.onKeyDown(alt);+ expect(alt.preventDefault).toHaveBeenCalledTimes(claimed ? 1 : 0);+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: BODY }));+ expect(h.setTool).not.toHaveBeenCalled();+ });++ it('asks the judge only after its own refusals', () => {+ const h = ownerHarness('surface');+ h.pipeline.onPointerEnter();+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Escape', target: { tagName: 'INPUT' } }));+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: BUTTON_TARGET }));+ h.pipeline.onKeyDown(makeKeyEvent({ defaultPrevented: true, key: 'Enter', target: BODY }));+ h.pipeline.onPointerDown(makePointerEvent({ pointerId: 1 }));+ expect(h.resolveKeyOwner).not.toHaveBeenCalled();+ expect(h.handleEscape).not.toHaveBeenCalled();+ });+});+describe('pointer pipeline: canvas keyboard ownership', () => {const applyHarness = () => {const h = createHarness();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.tsindex 7d6715f1ac..d6042453e6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts@@ -2,12 +2,14 @@* Normalizes DOM events into tool input with capture, coalesced samples and default mouse pressure 0.5. Middle* mouse pans independently. Space, Alt and held C temporarily select view, picker and bbox; release restores the* tool, while quick C selects bbox persistently. Temporary switches preserve sessions and are blocked mid-gesture.- * Escape/pointercancel cancel; extra buttons are ignored mid-gesture. Enter acts only while the keyboard root owns- * focus. Hold keys and the Escape ladder also act after a control was merely clicked, but never over an editable- * field, a keyboard-navigated control, an open overlay or beneath a modal dialog. Key releases are always observed and- * never consumed. DOM access is injected.+ * Escape/pointercancel cancel; extra buttons are ignored mid-gesture. No key acts over an editable field, a+ * keyboard-navigated control, an open overlay or beneath a modal dialog; past that, the host's key-owner judge decides:+ * Enter needs the surface itself, the Escape ladder and C also accept a companion widget, and Space and Alt act over+ * the hovered canvas whatever the owner. Owned Space and Alt are prevented, and so is the release of an Alt the+ * pipeline acted on; other releases are observed, never consumed. DOM access is injected.*/+import type { CanvasKeyOwner } from '@workbench/canvas-engine/capabilities';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, ToolId, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';@@ -30,6 +32,12 @@ export interface PointerPipelineDeps {getInputElement(): (HTMLElement & Partial<Pick<HTMLElement, 'setPointerCapture' | 'releasePointerCapture'>>) | null;/** The focusable element whose focus gives the canvas its session keys. */getKeyboardRoot(): Pick<HTMLElement, 'contains'> | null;+ /**+ * The host's judge of which region owns a keydown; asked only on keydown, after the pipeline's own refusals. Absent+ * (tests, detached engines), focus alone decides: the keyboard root or no focus is the surface, and a control the+ * pointer last clicked lends its keys like a companion.+ */+ getKeyOwnerResolver?(): ((event: KeyboardEvent) => CanvasKeyOwner) | null;getActiveTool(): Tool | undefined;getActiveToolId(): ToolId;getToolContext(): ToolContext;@@ -60,7 +68,8 @@ export interface PointerPipeline {onPointerMove(event: PointerEvent): void;onPointerUp(event: PointerEvent): void;onPointerCancel(event: PointerEvent): void;- onPointerEnter(): void;+ /** The canvas gained hover; an Alt still held consumes a pending Alt hold. */+ onPointerEnter(event?: Pick<PointerEvent, 'altKey'>): void;onPointerLeave(): void;onKeyDown(event: KeyboardEvent): void;onKeyUp(event: KeyboardEvent): void;@@ -85,6 +94,8 @@ export interface PointerPipeline {endForToolSwitch(): void;/** Replaces a matching tool id that a currently-held temporary tool would restore on release. */replaceTemporaryRestoreTool(current: ToolId, replacement: ToolId): void;+ /** The tool a held temporary switch restores on release, i.e. the tool the user is really on; null without one. */+ heldRestoreToolId(): ToolId | null;/** Clears hover/gesture/temp-tool state, cancelling any in-flight gesture (called on detach/blur). */reset(): void;}@@ -186,6 +197,11 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin// The control focus last landed on by pointer; keyboard navigation (`:focus-visible` on arrival) clears it.// Held weakly: a focused row may be removed (virtualized) without another focusin.let pointerFocused: WeakRef<EventTarget> | null = null;+ // Alt went down while the surface owned it but the pointer was elsewhere: the next hover or press with Alt still+ // held begins the picker hold, so a pen that lands without hovering samples on contact.+ let altPending = false;+ // This pipeline began or armed a hold for the Alt now down; its release is prevented too.+ let altClaimed = false;/*** Reads the input element's viewport offset. Hoisted out of@@ -217,33 +233,53 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinreturn [buildPointerInput(event, origin)];};- /**- * Enter belongs to the canvas only when focus is on its keyboard root (or nowhere), no control claims it and no modal- * dialog is open: focus can rest on the document body beneath one.- */- const ownsKeyboard = (event: KeyboardEvent): boolean => {- if (event.defaultPrevented || isModalPresent(event) || isInteractiveTarget(event.target)) {- return false;- }- return isDocumentRootTarget(event.target) || deps.getKeyboardRoot()?.contains(event.target as Node) === true;- };+ /** Enter belongs to the canvas only when focus is on its keyboard root (or nowhere) and no control claims it. */+ const focusOnSurface = (event: KeyboardEvent): boolean =>+ !isInteractiveTarget(event.target) &&+ (isDocumentRootTarget(event.target) || deps.getKeyboardRoot()?.contains(event.target as Node) === true);/**- * Hold keys and Escape also reach the canvas after a pointer click left focus on a control (a tool button, a layer- * row), but not over an editable field, a control reached by keyboard or an open overlay.+ * Who owns a keydown the canvas might act on, or null when it is refused outright: already handled, under a modal+ * dialog (focus can rest on the body beneath one), over an editable field or an open overlay, or on a control+ * reached by keyboard, whose own activation must win.*/- const ownsCanvasKey = (event: KeyboardEvent): boolean => {- if (event.defaultPrevented || isModalPresent(event) || isEditableTarget(event.target)) {- return false;+ const keyOwner = (event: KeyboardEvent): CanvasKeyOwner | null => {+ const target = event.target as KeyTarget;+ if (+ event.defaultPrevented ||+ isModalPresent(event) ||+ isEditableTarget(event.target) ||+ target?.closest?.(OVERLAY_SELECTOR)+ ) {+ return null;+ }+ const clicked = event.target !== null && event.target === pointerFocused?.deref();+ if (isInteractiveTarget(event.target) && !clicked) {+ return null;}- if (ownsKeyboard(event)) {- return true;+ const resolve = deps.getKeyOwnerResolver?.();+ if (resolve) {+ return resolve(event);}- return (- event.target !== null &&- event.target === pointerFocused?.deref() &&- !(event.target as KeyTarget)?.closest?.(OVERLAY_SELECTOR)- );+ if (focusOnSurface(event)) {+ return 'surface';+ }+ return clicked ? 'companion' : null;+ };++ /** Enter applies only from the surface itself, with focus on its keyboard root or nowhere. */+ const ownsEnter = (event: KeyboardEvent): boolean => focusOnSurface(event) && keyOwner(event) === 'surface';++ /** The Escape ladder and C act from the surface or a companion widget. */+ const ownsSessionKey = (event: KeyboardEvent): boolean => {+ const owner = keyOwner(event);+ return owner === 'surface' || owner === 'companion';+ };++ /** Space and Alt are pointer-led: any owner while the canvas is hovered, otherwise only the surface. */+ const holdOwner = (event: KeyboardEvent): CanvasKeyOwner | null => {+ const owner = keyOwner(event);+ return owner !== null && (hovered || owner === 'surface') ? owner : null;};const releaseCapture = (pointerId: number): void => {@@ -368,6 +404,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelincancelGesture();},endForToolSwitch: () => {+ altPending = false;cancelGesture();if (tempHold) {endTempTool();@@ -379,7 +416,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin// Escape may cancel a session but must preserve committed selection.const gestureWasActive = gestureActive;cancelGesture();- if (ownsCanvasKey(event)) {+ if (ownsSessionKey(event)) {deps.handleEscape?.({ gestureWasActive });}return;@@ -390,13 +427,13 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin}if (event.key === 'Enter') {// Enter applies a session-bearing tool's edit (transform). No-op otherwise.- if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && ownsKeyboard(event)) {+ if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && ownsEnter(event)) {deps.getActiveTool()?.onKeyCommand?.(deps.getToolContext(), 'apply');}return;}if (event.code === 'Space' && !event.repeat) {- if (event.ctrlKey || event.metaKey || event.altKey || !ownsCanvasKey(event)) {+ if (event.ctrlKey || event.metaKey || event.altKey || holdOwner(event) === null) {return;}beginTempTool('space', SPACE_TEMP_TOOL);@@ -406,15 +443,28 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinreturn;}if (isAltKey(event) && !event.repeat) {- if (!deps.getActiveTool()?.usesAltKey && ownsCanvasKey(event)) {+ if (holdOwner(event) === null) {+ return;+ }+ // Firefox and Windows activate the menu bar on a lone Alt unless both its press and release are prevented.+ event.preventDefault();+ altClaimed = true;+ // A tool that reads Alt as a gesture modifier keeps it; pointer events still carry `altKey`.+ if (deps.getActiveTool()?.usesAltKey) {+ return;+ }+ if (hovered) {beginTempTool('alt', ALT_TEMP_TOOL);+ } else if (!tempHold && !gestureActive) {+ altPending = true;}return;}- if (isBboxKey(event) && !event.repeat && ownsCanvasKey(event)) {+ if (isBboxKey(event) && !event.repeat && ownsSessionKey(event)) {beginBboxTempTool();}},+ heldRestoreToolId: () => (tempHold && tempSwitched ? priorToolId : null),hoverPoint: () => hoverPoint,isGestureActive: () => gestureActive,onFocusIn: (event) => {@@ -423,8 +473,15 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinonKeyUp: (event) => {if (event.code === 'Space' && tempHold === 'space') {releaseTempTool();- } else if (isAltKey(event) && tempHold === 'alt') {- releaseTempTool();+ } else if (isAltKey(event)) {+ altPending = false;+ if (altClaimed) {+ altClaimed = false;+ event.preventDefault();+ }+ if (tempHold === 'alt') {+ releaseTempTool();+ }} else if (isBboxKey(event) && tempHold === 'bbox') {releaseBboxTempTool();}@@ -466,6 +523,14 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinreturn;}cancelledPointerId = null;+ if (altPending) {+ // The press is over the canvas whether or not it hovered first; begin the hold so the pick routes it.+ altPending = false;+ hovered = true;+ if (event.altKey) {+ beginTempTool('alt', ALT_TEMP_TOOL);+ }+ }// Commit and consume modal text presses before gesture activation; prevent default focus/selection after// closing the session.if (deps.maybeCommitModalSession?.()) {@@ -480,8 +545,14 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelindeps.getActiveTool()?.onPointerDown?.(deps.getToolContext(), buildPointerInput(event));deps.updateCursor();},- onPointerEnter: () => {+ onPointerEnter: (event) => {hovered = true;+ if (altPending) {+ altPending = false;+ if (event?.altKey) {+ beginTempTool('alt', ALT_TEMP_TOOL);+ }+ }},onPointerLeave: () => {hovered = false;@@ -555,6 +626,8 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinendTempTool();}clearBboxTapTimer();+ altPending = false;+ altClaimed = false;hovered = false;hoverPoint = null;gestureActive = false;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.tsindex 1eaeeac18c..c30ef99cd2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts@@ -124,6 +124,14 @@ export type CanvasProjectMutation =| { type: 'reorderCanvasSiblings'; orders: readonly ReorderSiblingsCommand[] }| { type: 'updateCanvasLayer'; id: string; patch: CanvasLayerBasePatch }| { type: 'replaceCanvasLayer'; layerId: string; layer: CanvasLayerContract }+ | {+ /**+ * Replaces several leaves in place, each by a contract of the same id and type, as one value edit. The whole+ * mutation is refused when any id is missing, repeated, names a group, or would change its leaf's type.+ */+ type: 'replaceCanvasLayers';+ replacements: readonly { layerId: string; layer: CanvasLayerContract }[];+ }| { type: 'setCanvasLayersEnabled'; updates: readonly { id: string; isEnabled: boolean }[] }| { type: 'setCanvasLayerPositions'; updates: readonly { id: string; x: number; y: number }[] }| { type: 'setCanvasLayersHidden'; updates: readonly { id: string; isHidden: boolean }[] }diff --git 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.tsindex 95b6f69fe2..8c9cbe05c2 100644--- 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@@ -55,6 +55,7 @@ const scene = (budgetBytes = SURFACE_BYTES * 2) => {getCheckerboardTile: () => backend.createSurface(1, 1),getGroupSurface: (scope, members, matrices, content) => raster.groups.get(scope, members, matrices, content),getMaskPatternTile: () => null,+ hasStagedCandidates: () => false,layerCache: raster.layers,previews: new PreviewStateController(),raster,@@ -124,6 +125,7 @@ describe('frame description over 2,000 nodes', () => {getCheckerboardTile: () => backend.createSurface(1, 1),getGroupSurface: () => null,getMaskPatternTile: () => null,+ hasStagedCandidates: () => false,layerCache: raster.layers,previews: new PreviewStateController(),raster,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.tsindex d11ec3f225..0ab40ceaab 100644--- 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,6 +46,7 @@ const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 =>interface Harness {deps: CreateCompositeFrameDeps;+ staging: { candidates: boolean };stores: ReturnType<typeof createEngineStores>;previews: PreviewStateController;overrides: Map<string, { x: number; y: number }>;@@ -70,9 +71,12 @@ 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 {beginFrame,+ staging,deps: {+ hasStagedCandidates: () => staging.candidates,backend: {} as CreateCompositeFrameDeps['backend'],derivedSurfaceCache: { byteSize: () => 0 } as CreateCompositeFrameDeps['derivedSurfaceCache'],diagnostics: {} as CreateCompositeFrameDeps['diagnostics'],@@ -317,3 +321,57 @@ describe('the surface budget', () => {expect(composite.mock.invocationCallOrder[0]).toBeLessThan(harness.enforce.mock.invocationCallOrder[0]!);});});++describe('masks while a result is staged', () => {+ const mask = (id: string) =>+ layer(id, {+ mask: { bitmap: { height: 8, imageName: `${id}.png`, width: 8 }, fill: { color: '#e07575', style: 'solid' } },+ source: undefined,+ type: 'inpaint_mask',+ });+ const region = (id: string) => ({ ...mask(id), type: 'regional_guidance' }) as unknown as CanvasLayerContract;+ const control = (id: string) => layer(id, { type: 'control' });+ const doc = documentOf([layer('a'), control('c'), mask('m'), region('r')]);+ const drawnIds = () =>+ (lastCompositeOptions().preparation as compositor.CompositePreparation).leaves.map((leaf) => leaf.id).sort();+ const demandedIds = () => [...(harness.enforce.mock.calls.at(-1)![0] as Set<string>)].sort();+ for (const id of ['c', 'm', 'r']) {+ beforeEach(() => harness.entries.set(id, entryFor()));+ }++ it('hides mask and region stacks and the region tint, rebuilding the frame description once per flip', () => {+ const frame = createCompositeFrame(harness.deps);+ const drawFrame = () => frame.draw(surface(), doc, VIEW, null, null);++ const description = () => (lastCompositeOptions().preparation as compositor.CompositePreparation).leaves;+ drawFrame();+ const shown = description();+ expect(drawnIds()).toEqual(['a', 'c', 'm', 'r']);+ expect(lastCompositeOptions().regionOverlays).toBe(true);++ harness.staging.candidates = true;+ drawFrame();+ const hidden = description();+ expect(hidden).not.toBe(shown);+ expect(drawnIds()).toEqual(['a', 'c']);+ expect(demandedIds()).toEqual(['a', 'c']);+ expect(lastCompositeOptions().regionOverlays).toBe(false);+ drawFrame();+ expect(description()).toBe(hidden);++ harness.staging.candidates = false;+ drawFrame();+ expect(drawnIds()).toEqual(['a', 'c', 'm', 'r']);+ expect(demandedIds()).toEqual(['a', 'c', 'm', 'r']);+ });++ it('also hides them while only a staged or progress preview is published', () => {+ harness.previews.publishStaged(harness.previews.nextStagedToken(), {+ height: 8,+ surface: surface(8, 8),+ width: 8,+ } as never);+ draw(doc);+ expect(drawnIds()).toEqual(['a', 'c']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex 1801a5fb0a..e779cfa363 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -44,8 +44,16 @@ export interface CreateCompositeFrameDeps {readonly getCheckerboardTile: () => RasterSurface;/** 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(@@ -130,12 +138,14 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFconst describeFrame = (doc: CanvasDocumentContractV3,isolationLayerId: string | null,- overrides: CompositeOptions['transformOverrides']+ overrides: CompositeOptions['transformOverrides'],+ showOverlayStacks: CompositeOptions['showOverlayStacks']): CompositePreparation => {const plan = reusePreparation(preparation, doc, {backend: deps.backend,groupSurface: deps.getGroupSurface,isolationLayerId,+ showOverlayStacks,transformOverrides: overrides,});preparation = plan;@@ -185,7 +195,9 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFconst stagedPlacement = stagedPreview?.placement;const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;const overrides = !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null;- const frame = describeFrame(doc, isolatedGuard?.layerId ?? null, overrides);+ const staging = stagedPreview !== null || deps.hasStagedCandidates();+ const showOverlayStacks = staging ? STAGING_OVERLAY_STACKS : undefined;+ const frame = describeFrame(doc, isolatedGuard?.layerId ?? null, overrides, showOverlayStacks);// Snapshot filter previews only when active, avoiding an empty map allocation every frame.const layerPreviews = !isolatedGuard && previews.filterCount() > 0 ? previews.filterSnapshot() : null;const activeFrameLayerIds = calculateActiveFrameLayerIds({@@ -220,8 +232,9 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFlayerPreviews,maskPatternTile: deps.getMaskPatternTile,preparation: frame,- // Screen frames are display-time: the region tint may draw.- regionOverlays: true,+ // Screen frames are display-time: the region tint may draw, except over a staged result.+ regionOverlays: !staging,+ showOverlayStacks,// Candidate-specific placement wins for final images. Progress frames// and legacy image inputs continue to follow the CURRENT bbox origin.stagedPreview:diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex d061d94dc2..8a47c4b415 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -12,6 +12,7 @@ import type {} from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';+import type { OverlayStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { FrameDamage, Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';@@ -108,6 +109,8 @@ export interface CompositeOptions {layerPreviews?: ReadonlyMap<string, { surface: RasterSurface; rect: Rect }> | null;/** Isolate one leaf and suppress staged/filter previews; disabled or hidden leaves remain undrawn. */isolationLayerId?: string | null;+ /** Overlay stacks the screen draws; absence draws all. An isolated target draws whatever its stack. */+ showOverlayStacks?: Readonly<Record<OverlayStackKind, boolean>>;/*** Memoized adjusted raster surface, or null for raw pixels. Optional provider; without it adjustments are* ignored. Cache versions prevent per-frame recomputation.@@ -124,7 +127,7 @@ export interface CompositeOptions {diagnostics?: CanvasDiagnostics | null;/*** Reused frame description from {@link prepareComposite}; ignored unless it was prepared for this document,- * isolation, grouping and transform overrides.+ * isolation, overlay stacks, grouping and transform overrides.*/preparation?: CompositePreparation | null;/**@@ -164,14 +167,21 @@ export const transformOverridesKey = (overrides: TransformOverrides | null | undreturn key;};+/** A stable key for the overlay stack switches; absence shows every stack. */+const overlayStacksKey = (shown: CompositeOptions['showOverlayStacks']): string => {+ const stacks = shown ?? ALL_OVERLAY_STACKS_SHOWN;+ return `${+stacks.control}${+stacks.inpaint_mask}${+stacks.regional_guidance}`;+};+/*** One frame description: the leaves drawn (bottom first), their effective matrices with overrides applied, the* isolated group scopes, and optionally each leaf's document-space bounds this frame. Stable while the document,- * isolation, grouping and override contents are, so frame demand, compositing and sampling share it.+ * isolation, overlay stacks, grouping and override contents are, so frame demand, compositing and sampling share it.*/export interface CompositePreparation {readonly document: CanvasDocumentContractV3;readonly isolationLayerId: string | null;+ readonly overlayStacksKey: string;readonly grouped: boolean;readonly overridesKey: string;readonly leaves: readonly SemanticLeaf[];@@ -198,13 +208,13 @@ const effectiveMatrix = (leaf: SemanticLeaf, overrides: TransformOverrides | nul/** Plans the draw order, placement and isolated group scopes for `doc`, for callers compositing it repeatedly. */export const prepareComposite = (doc: CanvasDocumentContractV3,- opts: Pick<CompositeOptions, 'groupSurface' | 'isolationLayerId' | 'transformOverrides'> = {}+ opts: Pick<CompositeOptions, 'groupSurface' | 'isolationLayerId' | 'showOverlayStacks' | 'transformOverrides'> = {}): CompositePreparation => {const isolationLayerId = opts.isolationLayerId ?? null;// The plan lists the leaves to draw bottom first; the `stagedPreview` lands on top of every stack.const { leaves } = planScreenComposition(compileDocumentLeaves(doc), {isolationLayerId,- showOverlayStacks: ALL_OVERLAY_STACKS_SHOWN,+ showOverlayStacks: opts.showOverlayStacks ?? ALL_OVERLAY_STACKS_SHOWN,});// Isolation mode inspects raw members, so scopes are bypassed while active.const grouped = !!opts.groupSurface && isolationLayerId === null;@@ -216,6 +226,7 @@ export const prepareComposite = (isolationLayerId,leaves,matrices: leaves.map((leaf) => effectiveMatrix(leaf, overrides)),+ overlayStacksKey: overlayStacksKey(opts.showOverlayStacks),overridesKey: transformOverridesKey(overrides),scopes,};@@ -229,6 +240,7 @@ const isPreparedFor = (!!preparation &&preparation.document === doc &&preparation.isolationLayerId === (opts.isolationLayerId ?? null) &&+ preparation.overlayStacksKey === overlayStacksKey(opts.showOverlayStacks) &&preparation.grouped === (!!opts.groupSurface && !isIsolated(opts)) &&preparation.overridesKey === transformOverridesKey(opts.transformOverrides);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.tsindex d50c8750cb..0179955140 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts@@ -223,3 +223,49 @@ describe('damage-clipped compositing matches a full repaint', () => {expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });});});++describe('overlay stacks switched off while a result is staged', () => {+ it('draws the raster under a mask, a region and a regenerate region untinted, and tinted again after', () => {+ const mask: CanvasLayerContract = {+ blendMode: 'normal',+ id: 'mask',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#0000ff', style: 'solid' } },+ name: 'mask',+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ };+ const region = rasterLayer('region', { inpaint: { fill: { color: '#00ff00', style: 'solid' }, isEnabled: true } });+ const layers = [mask, region, rasterLayer('base')];+ const rects = {+ base: { height: 100, width: 300, x: 0, y: 0 },+ mask: { height: 100, width: 100, x: 0, y: 0 },+ region: { height: 100, width: 100, x: 200, y: 0 },+ };+ const { backend, caches } = scene(layers, rects, { base: '#ff0000', mask: '#ffffff', region: '#ff0000' });+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;+ const screen = backend.createSurface(SCREEN_W, SCREEN_H);+ const rgbAt = (x: number): number[] => Array.from(screen.ctx.getImageData(x, 50, 1, 1).data.slice(0, 3));+ const draw = (staging: boolean) =>+ compositeDocument(screen, doc, caches, identity(), {+ backend,+ imageSmoothing: false,+ regionOverlays: !staging,+ showOverlayStacks: staging ? { control: true, inpaint_mask: false, regional_guidance: false } : undefined,+ });++ draw(true);+ expect([rgbAt(50), rgbAt(150), rgbAt(250)]).toEqual([+ [255, 0, 0],+ [255, 0, 0],+ [255, 0, 0],+ ]);++ draw(false);+ expect(rgbAt(50)).not.toEqual([255, 0, 0]);+ expect(rgbAt(150)).toEqual([255, 0, 0]);+ expect(rgbAt(250)).not.toEqual([255, 0, 0]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.tsindex ee2e6349af..cb31cb59ce 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts@@ -88,6 +88,31 @@ describe('calculateActiveFrameLayerIds', () => {).toEqual(new Set(['off']));});+ it('demands nothing from a hidden overlay stack unless an isolated operation reads it', () => {+ const mask: CanvasLayerContract = {+ blendMode: 'normal',+ id: 'mask',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: { height: 100, imageName: 'mask.png', width: 100 }, fill: { color: '#e07575', style: 'solid' } },+ name: 'mask',+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ };+ const doc = document([mask, { ...hiddenControl('control'), isHidden: false }, layer('base', 0, 0)]);+ const viewport = { height: 200, width: 200, x: 0, y: 0 };+ const showOverlayStacks = { control: true, inpaint_mask: false, regional_guidance: false };++ expect(calculateActiveFrameLayerIds({ document: doc, viewport })).toEqual(new Set(['base', 'control', 'mask']));+ expect(calculateActiveFrameLayerIds({ document: doc, showOverlayStacks, viewport })).toEqual(+ new Set(['base', 'control'])+ );+ expect(+ calculateActiveFrameLayerIds({ document: doc, isolationLayerId: 'mask', showOverlayStacks, viewport })+ ).toEqual(new Set(['mask']));+ });+it('limits demand to isolated layers', () => {const doc = document([layer('isolated', 0, 0), layer('covered', 0, 0)]);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.tsindex b0f73b1ebe..dc097e6d95 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts@@ -11,6 +11,8 @@ export interface FrameDemandInput {readonly document: CanvasDocumentContractV3;readonly isolationLayerId?: string | null;readonly liveCacheRects?: ReadonlyMap<string, Rect>;+ /** Overlay stacks the frame draws; a hidden stack demands nothing. */+ readonly showOverlayStacks?: CompositeOptions['showOverlayStacks'];readonly transformOverrides?: CompositeOptions['transformOverrides'];readonly viewport: Rect;/** The frame description to plan against; prepared from the other inputs when absent. */@@ -42,6 +44,7 @@ export const calculateActiveFrameLayerIds = (input: FrameDemandInput): Set<strininput.preparation ??prepareComposite(input.document, {isolationLayerId: input.isolationLayerId ?? null,+ showOverlayStacks: input.showOverlayStacks,transformOverrides: input.transformOverrides,});const active = new Set<string>();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.tsindex c8233afdb0..a39fca79ca 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts@@ -188,38 +188,55 @@ describe('color picker tool', () => {expect(h.ctx.stores.brushOptions.get().color).toBe(defaultColor);});- it('stashes claimed samples without writing brushOptions and commits on release', () => {+ it('previews every sample of a pick and commits the last one once on release', () => {const h = createHarness(makeDoc());const tool = createColorPickerTool();const defaultColor = h.ctx.stores.brushOptions.get().color;- const claimed: string[] = [];- h.ctx.resolveColorSample = (hex) => {- claimed.push(hex);+ const routed: [string, string][] = [];+ h.ctx.resolveColorSample = (hex, phase) => {+ routed.push([hex, phase]);return true;};- const commit = vi.fn();- h.ctx.commitColorSample = commit;down(tool, h.ctx, pointer(10, 10));- expect(claimed).toEqual(['#0a141e']);- expect(commit).not.toHaveBeenCalled();+ h.pixel.current = [255, 0, 0, 255];+ move(tool, h.ctx, pointer(20, 20));+ up(tool, h.ctx, pointer(20, 20, { buttons: 0 }));+ // The next hover move after release samples nothing and settles nothing.+ move(tool, h.ctx, pointer(30, 30, { buttons: 0 }));++ expect(routed).toEqual([+ ['#0a141e', 'preview'],+ ['#ff0000', 'preview'],+ ['#ff0000', 'commit'],+ ]);expect(h.ctx.stores.brushOptions.get().color).toBe(defaultColor);-- up(tool, h.ctx, pointer(10, 10, { buttons: 0 }));- expect(commit).toHaveBeenCalledTimes(1);});- it('discards the stashed sample on gesture cancel and at each fresh press', () => {+ it('cancels a pick with its last preview when the gesture is cancelled or the tool deactivates', () => {const h = createHarness(makeDoc());const tool = createColorPickerTool();- const discard = vi.fn();- h.ctx.discardColorSample = discard;+ const routed: [string, string][] = [];+ h.ctx.resolveColorSample = (hex, phase) => {+ routed.push([hex, phase]);+ return true;+ };down(tool, h.ctx, pointer(10, 10));- expect(discard).toHaveBeenCalledTimes(1);-tool.onPointerCancel?.(h.ctx);- expect(discard).toHaveBeenCalledTimes(2);+ up(tool, h.ctx, pointer(10, 10, { buttons: 0 }));+ expect(routed).toEqual([+ ['#0a141e', 'preview'],+ ['#0a141e', 'cancel'],+ ]);++ routed.length = 0;+ down(tool, h.ctx, pointer(10, 10));+ tool.onDeactivate?.(h.ctx);+ expect(routed).toEqual([+ ['#0a141e', 'preview'],+ ['#0a141e', 'cancel'],+ ]);});it('never dispatches and never emits a committed stroke', () => {@@ -263,7 +280,7 @@ describe('color picker tool', () => {down(tool, h.ctx, pointer(10, 10));- expect(resolveColorSample).toHaveBeenCalledWith('#0a141e');+ expect(resolveColorSample).toHaveBeenCalledWith('#0a141e', 'preview');expect(h.ctx.stores.brushOptions.get().color).toBe(defaultColor);});@@ -276,7 +293,7 @@ describe('color picker tool', () => {down(tool, h.ctx, pointer(10, 10));- expect(resolveColorSample).toHaveBeenCalledWith('#0a141e');+ expect(resolveColorSample).toHaveBeenCalledWith('#0a141e', 'preview');expect(h.ctx.stores.brushOptions.get().color).toBe('#0a141e');});@@ -287,6 +304,7 @@ describe('color picker tool', () => {h.ctx.resolveColorSample = resolveColorSample;down(tool, h.ctx, pointer(10, 10));+ up(tool, h.ctx, pointer(10, 10, { buttons: 0 }));expect(resolveColorSample).not.toHaveBeenCalled();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.tsindex 87e601f281..45fc41dbda 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts@@ -1,7 +1,7 @@/**- * Shows a loupe of the composited pixels under the pointer, samples while pressed and routes the color to the active- * color target. Alt-hold restoration returns to the prior tool; the picker neither dispatches nor edits pixels.- * State is per engine.+ * Shows a loupe of the composited pixels under the pointer, previews samples while pressed and commits the last one+ * on release (or cancels it when the press ends any other way) through the active color target. Alt-hold restoration+ * returns to the prior tool; the picker neither dispatches nor edits pixels. State is per engine.*/import type { PointerInput } from '@workbench/canvas-engine/types';@@ -19,18 +19,19 @@ const updateLoupe = (ctx: ToolContext): void => {ctx.showColorLoupe?.(true);};-/** Offers sampled color to the one-shot claim then workbench router; standalone fallback updates brush color. */-const pickColorAt = (ctx: ToolContext, sampler: ColorSampler, input: PointerInput): void => {+/** Samples the composite under the pointer as `#rrggbb`, or null off the document. */+const sampleAt = (ctx: ToolContext, sampler: ColorSampler, input: PointerInput): string | null => {const doc = ctx.getDocument();if (!doc) {- return;+ return null;}const sample = sampler.sample(doc, ctx.layers, input.documentPoint, ctx.sampleProviders);- if (!sample) {- return;- }- const hex = rgbaToHex(sample.r, sample.g, sample.b);- if (ctx.resolveColorSample?.(hex)) {+ return sample ? rgbaToHex(sample.r, sample.g, sample.b) : null;+};++/** Previews a sample through the one-shot claim then workbench router; standalone fallback updates brush color. */+const previewColor = (ctx: ToolContext, hex: string): void => {+ if (ctx.resolveColorSample?.(hex, 'preview')) {return;}const opts = ctx.stores.brushOptions.get();@@ -43,9 +44,23 @@ const pickColorAt = (ctx: ToolContext, sampler: ColorSampler, input: PointerInpuexport const createColorPickerTool = (): Tool => {// One engine owns the tool and its backend, so the sampler can outlive a gesture.let sampler: ColorSampler | null = null;+ // The last color this press previewed; a pick commits or cancels only after previewing something.+ let pickedHex: string | null = null;const pick = (ctx: ToolContext, input: PointerInput): void => {sampler ??= createColorSampler(ctx.backend);- pickColorAt(ctx, sampler, input);+ const hex = sampleAt(ctx, sampler, input);+ if (hex !== null) {+ pickedHex = hex;+ previewColor(ctx, hex);+ }+ };+ /** Ends the pick once: release commits the last preview, anything else cancels it. */+ const settle = (ctx: ToolContext, phase: 'commit' | 'cancel'): void => {+ const hex = pickedHex;+ pickedHex = null;+ if (hex !== null) {+ ctx.resolveColorSample?.(hex, phase);+ }};return {// The loupe's boxed center pixel is the target; a system cursor would cover it.@@ -54,16 +69,17 @@ export const createColorPickerTool = (): Tool => {// A pointer already over the canvas (an Alt hold, a pick request) gets the loupe without moving.onActivate: (ctx) => updateLoupe(ctx),onDeactivate: (ctx) => {+ settle(ctx, 'cancel');ctx.showColorLoupe?.(false);},onPointerCancel: (ctx) => {- ctx.discardColorSample?.();+ settle(ctx, 'cancel');},onPointerDown: (ctx, input) => {if ((input.buttons & PRIMARY_BUTTON) === 0) {return;}- ctx.discardColorSample?.();+ settle(ctx, 'cancel');updateLoupe(ctx);pick(ctx, input);},@@ -75,7 +91,7 @@ export const createColorPickerTool = (): Tool => {},onPointerUp: (ctx) => {updateLoupe(ctx);- ctx.commitColorSample?.();+ settle(ctx, 'commit');},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex dc71e212ab..6bac3fcd0e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -2,6 +2,7 @@ import type {CanvasControlLayerContract,CanvasDocumentContractV3,CanvasLayerContract,+ CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import type {@@ -51,6 +52,21 @@ const imageLayer = (id: string): CanvasLayerContract => ({type: 'raster',});+/** A raster the brush cannot edit in place, so a stroke auto-creates a paint layer above it. */+const textLayer = (id: string): CanvasLayerContract => ({+ ...(imageLayer(id) as CanvasRasterLayerContractV2),+ source: {+ align: 'left',+ color: '#000000',+ content: id,+ fontFamily: 'sans-serif',+ fontSize: 12,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+});+const inpaintMaskLayer = (id: string): CanvasLayerContract => ({blendMode: 'normal',id,@@ -100,10 +116,14 @@ const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null):width: 100,});-const pointer = (x: number, y: number, opts: { pressure?: number; buttons?: number } = {}): PointerInput => ({+const pointer = (+ x: number,+ y: number,+ opts: { pressure?: number; buttons?: number; shift?: boolean } = {}+): PointerInput => ({buttons: opts.buttons ?? 1,documentPoint: { x, y },- modifiers: { alt: false, ctrl: false, meta: false, shift: false },+ modifiers: { alt: false, ctrl: false, meta: false, shift: opts.shift ?? false },pointerType: 'mouse',pressure: opts.pressure ?? 0.5,screenPoint: { x, y },@@ -328,20 +348,67 @@ describe('eraser tool', () => {expect(erasedHeight(0.1, false)).toBe(erasedHeight(1, false));});- it('edits a selected image layer through a materializing pixel transaction', () => {+ it.each([+ ['eraser', createEraserTool],+ ['brush', createBrushTool],+ ] as const)('%s edits a selected image layer through a materializing pixel transaction', (_, createTool) => {const transaction = controlTransaction('img1');const h = createHarness(makeDoc([imageLayer('img1')], 'img1'), transaction);- const eraser = createEraserTool();+ h.layers.getOrCreateRect('img1', { height: 10, width: 10, x: 0, y: 0 }).stale = false;+ const tool = createTool();- down(eraser, h.ctx, pointer(2, 2));- move(eraser, h.ctx, pointer(6, 6), [pointer(6, 6)]);- up(eraser, h.ctx, pointer(6, 6));+ down(tool, h.ctx, pointer(2, 2));+ move(tool, h.ctx, pointer(6, 6), [pointer(6, 6)]);+ up(tool, h.ctx, pointer(6, 6));expect(h.beginPixelEdit).toHaveBeenCalledWith('img1');expect(transaction.commit).toHaveBeenCalledOnce();expect(h.dispatched).toHaveLength(0);expect(h.createdIds).toHaveLength(0);});++ it.each([+ ['locked', { isLocked: true }, true],+ ['disabled', { isEnabled: false }, true],+ ['not rasterized yet', {}, false],+ ] as const)('brushes a %s image layer onto an auto-created paint layer instead', (_, overrides, cached) => {+ const transaction = controlTransaction('img1');+ const h = createHarness(+ makeDoc([{ ...imageLayer('img1'), ...overrides } as CanvasLayerContract], 'img1'),+ transaction+ );+ if (cached) {+ h.layers.getOrCreateRect('img1', { height: 10, width: 10, x: 0, y: 0 }).stale = false;+ }+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(2, 2));+ up(brush, h.ctx, pointer(2, 2));++ expect(h.beginPixelEdit).not.toHaveBeenCalled();+ expect(h.dispatched.map((action) => action.type)).toEqual(['addCanvasLayer']);+ expect(h.strokes.map((stroke) => stroke.layerId)).toEqual([h.createdIds[0]]);+ });++ it('brushes a transparency-locked image layer in place with source-atop, but refuses to erase it', () => {+ const locked = { ...imageLayer('img1'), isTransparencyLocked: true } as CanvasLayerContract;+ const transaction = controlTransaction('img1');+ const h = createHarness(makeDoc([locked], 'img1'), transaction);+ h.layers.getOrCreateRect('img1', { height: 100, width: 100, x: 0, y: 0 }).stale = false;++ const eraser = createEraserTool();+ down(eraser, h.ctx, pointer(2, 2));+ up(eraser, h.ctx, pointer(2, 2));+ expect(h.beginPixelEdit).not.toHaveBeenCalled();++ const brush = createBrushTool();+ down(brush, h.ctx, pointer(2, 2));+ move(brush, h.ctx, pointer(6, 6), [pointer(6, 6)]);+ expect(lastCompositeOp(cacheSurface(h, 'img1'))).toBe('source-atop');+ up(brush, h.ctx, pointer(6, 6));+ expect(transaction.commit).toHaveBeenCalledOnce();+ expect(h.dispatched).toHaveLength(0);+ });});describe('brush tool: cancel', () => {@@ -529,7 +596,7 @@ describe('paint tool: target resolution', () => {});it('auto-creates a paint layer (one dispatch) when the selection is not paintable', () => {- const doc = makeDoc([imageLayer('img1')], 'img1');+ const doc = makeDoc([textLayer('img1')], 'img1');const h = createHarness(doc);const brush = createBrushTool();@@ -714,7 +781,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves noconst kinds = (h: { dispatched: CanvasProjectMutation[] }): string[] => h.dispatched.map((action) => action.type);it('removes the layer and restores the prior selection when the stroke is fully clipped away', () => {- const h = clipped(makeDoc([imageLayer('img1'), paintLayer('p1')], 'img1'));+ const h = clipped(makeDoc([textLayer('img1'), paintLayer('p1')], 'img1'));const brush = createBrushTool();down(brush, h.ctx, pointer(80, 80));@@ -731,7 +798,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no});it('drops the provisional cache entry too', () => {- const h = clipped(makeDoc([imageLayer('img1')], 'img1'));+ const h = clipped(makeDoc([textLayer('img1')], 'img1'));const brush = createBrushTool();down(brush, h.ctx, pointer(80, 80));@@ -742,7 +809,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no});it('rolls back on pointercancel mid-drag', () => {- const h = createHarness(makeDoc([imageLayer('img1')], 'img1'));+ const h = createHarness(makeDoc([textLayer('img1')], 'img1'));const brush = createBrushTool();down(brush, h.ctx, pointer(20, 20));@@ -755,7 +822,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no});it('rolls back when the tool is switched away mid-drag', () => {- const h = createHarness(makeDoc([imageLayer('img1')], 'img1'));+ const h = createHarness(makeDoc([textLayer('img1')], 'img1'));const brush = createBrushTool();down(brush, h.ctx, pointer(20, 20));@@ -766,7 +833,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no});it('does NOT roll back for a temporary tool switch (space/alt hold keeps the gesture)', () => {- const h = createHarness(makeDoc([imageLayer('img1')], 'img1'));+ const h = createHarness(makeDoc([textLayer('img1')], 'img1'));const brush = createBrushTool();down(brush, h.ctx, pointer(20, 20));@@ -789,7 +856,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no});it('keeps the layer when the stroke DOES commit pixels', () => {- const h = createHarness(makeDoc([imageLayer('img1')], 'img1'));+ const h = createHarness(makeDoc([textLayer('img1')], 'img1'));const brush = createBrushTool();down(brush, h.ctx, pointer(20, 20));@@ -810,3 +877,117 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves noexpect(h.dispatched).toHaveLength(0);});});++describe('Shift-click straight lines', () => {+ /**+ * A harness with an engine-owned line memory and a path recorder: `span()` is the horizontal extent of the stroke+ * outlines traced since the last call, so a dab and a line read apart regardless of cache growth chunks.+ */+ const lineHarness = (layers: CanvasLayerContract[], selectedLayerId: string | null) => {+ const h = createHarness(makeDoc(layers, selectedLayerId));+ const paintLineEnds = new Map<string, { x: number; y: number }>();+ let xs: number[] = [];+ const record = (x: number): void => {+ xs.push(x);+ };+ const ctx: ToolContext = {+ ...h.ctx,+ createPath2D: () =>+ ({+ closePath: () => {},+ lineTo: record,+ moveTo: record,+ quadraticCurveTo: (_cx: number, _cy: number, x: number) => record(x),+ }) as unknown as Path2D,+ paintLineEnds,+ };+ ctx.stores.brushOptions.set({ ...ctx.stores.brushOptions.get(), size: 4 });+ ctx.stores.eraserOptions.set({ ...ctx.stores.eraserOptions.get(), size: 4 });+ const span = (): number => {+ const extent = Math.max(...xs) - Math.min(...xs);+ xs = [];+ return extent;+ };+ return { ...h, ctx, paintLineEnds, span };+ };++ it('draws from the last stroke end to a Shift press, as one committed stroke', () => {+ const h = lineHarness([paintLayer('paint1')], 'paint1');+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(10, 10));+ up(brush, h.ctx, pointer(10, 10));+ expect(h.paintLineEnds.get('paint1')).toEqual({ x: 10, y: 10 });+ // A 4 px dab is about one brush wide.+ expect(h.span()).toBeLessThanOrEqual(5);++ down(brush, h.ctx, pointer(60, 10, { shift: true }));+ up(brush, h.ctx, pointer(60, 10, { shift: true }));++ expect(h.strokes).toHaveLength(2);+ // The line runs 50 px from x=10 to x=60, plus the brush radius at each end.+ expect(h.span()).toBeGreaterThanOrEqual(50);+ expect(h.paintLineEnds.get('paint1')).toEqual({ x: 60, y: 10 });+ });++ it('paints a dab on a Shift press without a remembered point, or on a layer with none', () => {+ const h = lineHarness([paintLayer('paint1'), paintLayer('paint2')], 'paint2');+ h.paintLineEnds.set('paint1', { x: 10, y: 10 });+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(60, 10, { shift: true }));+ up(brush, h.ctx, pointer(60, 10, { shift: true }));++ expect(h.strokes).toHaveLength(1);+ expect(h.span()).toBeLessThanOrEqual(5);+ });++ it('ignores the memory on a press without Shift', () => {+ const h = lineHarness([paintLayer('paint1')], 'paint1');+ h.paintLineEnds.set('paint1', { x: 10, y: 10 });+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(60, 10));+ up(brush, h.ctx, pointer(60, 10));++ expect(h.span()).toBeLessThanOrEqual(5);+ });++ it('shares one point per layer between brush and eraser', () => {+ const h = lineHarness([paintLayer('paint1')], 'paint1');+ h.layers.getOrCreateRect('paint1', { height: 100, width: 100, x: 0, y: 0 }).stale = false;+ const brush = createBrushTool();+ const eraser = createEraserTool();++ down(brush, h.ctx, pointer(10, 10));+ up(brush, h.ctx, pointer(10, 10));+ // Switching tools keeps the memory; only the engine's lifecycle events forget it.+ brush.onDeactivate?.(h.ctx, undefined);+ h.span();+ down(eraser, h.ctx, pointer(60, 10, { shift: true }));+ up(eraser, h.ctx, pointer(60, 10, { shift: true }));++ expect(h.strokes.map((stroke) => stroke.tool)).toEqual(['brush', 'eraser']);+ expect(h.span()).toBeGreaterThanOrEqual(50);+ });++ it('remembers the end of a stroke that auto-created its layer under the new id', () => {+ const h = lineHarness([textLayer('text1')], 'text1');+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(20, 20));+ up(brush, h.ctx, pointer(25, 20));++ expect([...h.paintLineEnds]).toEqual([[h.createdIds[0], { x: 25, y: 20 }]]);+ });++ it('remembers nothing for a cancelled stroke', () => {+ const h = lineHarness([paintLayer('paint1')], 'paint1');+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(20, 20));+ cancel(brush, h.ctx);++ expect(h.paintLineEnds.size).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex c5d6dd52b4..3dda85ba2f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -1,7 +1,7 @@/*** Shared brush/eraser gesture resolves or creates a target, drives a StrokeSession and commits/cancels. Only* gesture-start layer creation dispatches here; moves never dispatch. Fill/erase differ by blend and option- * source.+ * source. A Shift press on a layer with a remembered stroke end draws a straight segment from it.*/import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';@@ -112,17 +112,27 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget: null;}- if (leaf && selected?.type === 'raster' && selected.source.type === 'image' && tool === 'eraser') {- // Erase materializes image pixels as an undoable paint layer in place; locked, disabled or unready images- // refuse without spawning.+ const imageSelected = leaf && selected?.type === 'raster' && selected.source.type === 'image';+ if (imageSelected && tool === 'eraser') {+ // Erasing materializes image pixels as an undoable paint layer in place; locked, disabled, unready or+ // transparency-locked images refuse without spawning.if (!isLeafPaintable(leaf) || isLayerTransparencyLocked(selected)) {return null;}const transaction = ctx.beginPixelEdit?.(selected.id) ?? null;+ // No transform on purpose: see the brush branch below.+ return transaction ? editTarget(transaction, transaction.layerId) : null;+ }+ const imageCache = imageSelected ? ctx.layers.peek(selected.id) : undefined;+ if (imageSelected && isLeafPaintable(leaf) && imageCache && !imageCache.stale) {+ // The brush paints a paintable, rasterized image in place the same way, under its transparency lock; a locked,+ // disabled or unready image keeps the brush's auto-created paint layer below.+ const transparencyLocked = isLayerTransparencyLocked(selected);+ const transaction = ctx.beginPixelEdit?.(selected.id) ?? null;// No transform on purpose: materialization BAKES the layer's placement// into document-space pixels and resets the layer to identity, so the// session's document coordinates already are the cache's coordinates.- return transaction ? editTarget(transaction, transaction.layerId) : null;+ return transaction ? editTarget(transaction, transaction.layerId, { transparencyLocked }) : null;}if (leaf && selected && isMaskLayer(selected)) {@@ -297,7 +307,10 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {thinning: spec.thinning(ctx),tool: spec.id,});- session.addPoints([input]);+ // Shift continues from the layer's last stroke end: both points take the press pressure, so the segment+ // renders as a line rather than collapsing to a tap.+ const lineStart = input.modifiers.shift ? ctx.paintLineEnds?.get(target.layerId) : undefined;+ session.addPoints(lineStart ? [{ ...input, documentPoint: lineStart }, input] : [input]);} catch {abortSession();}@@ -326,7 +339,9 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {throw error;}endSession();- if (!published) {+ if (published) {+ ctx.paintLineEnds?.set(activeTarget.layerId, { ...input.documentPoint });+ } else {activeTarget.cancel();}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.tsindex f7fd69bbe7..8a9c390b08 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts@@ -332,3 +332,27 @@ describe('dense stylus trace', () => {await annotate(`dense stroke ms: every batch ${everyBatch.ms}, per frame ${perFrame.ms}`);});});++describe('two-point seed (Shift-click line)', () => {+ const alphaAt = ({ pixels, rect }: { pixels: Uint8ClampedArray; rect: Rect }, x: number, y: number): number => {+ if (x < rect.x || y < rect.y || x >= rect.x + rect.width || y >= rect.y + rect.height) {+ return 0;+ }+ return pixels[((y - rect.y) * rect.width + (x - rect.x)) * 4 + 3]!;+ };++ it('rasterizes a capsule between two seeded points past the tap threshold, not a dab', () => {+ const options = { opacity: 1, size: 6, thinning: 0 };+ const line = paint([pointer(10, 20), pointer(60, 20)], 2, options);+ const dab = paint([pointer(10, 20)], 1, options);++ // Covered along the whole segment and at both ends, but not beyond the brush radius.+ for (const x of [10, 25, 35, 45, 60]) {+ expect(alphaAt(line, x, 20)).toBe(255);+ }+ expect(alphaAt(line, 35, 26)).toBe(0);+ expect(alphaAt(line, 66, 20)).toBe(0);+ expect(alphaAt(dab, 10, 20)).toBe(255);+ expect(alphaAt(dab, 25, 20)).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 7e545b3c66..ba8992bac0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -4,7 +4,7 @@* StrokeCommittedEvent} for downstream history/persistence.*/-import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';+import type { ColorSamplePhase, StructuralCommitResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';@@ -77,6 +77,13 @@ export interface LayerTransformOverride {rotation?: number;}+/** Where the last committed brush or eraser stroke ended, per layer id, in document space. */+export interface PaintLineEnds {+ get(layerId: string): Vec2 | undefined;+ set(layerId: string, point: Vec2): void;+ clear(): void;+}+/** Everything a tool is allowed to reach, injected by the engine. */export interface ToolContext {/** The pan/zoom viewport. */@@ -135,20 +142,19 @@ export interface ToolContext {/** Shows or hides the color picker's loupe, which follows the pointer while shown; optional in test harnesses. */showColorLoupe?(shown: boolean): void;/**- * Route samples to one-shot claim, then persistent workbench target. Return whether consumed; otherwise picker- * falls back to brush color. Optional in test harnesses.+ * Routes a pick's samples to the one-shot claim, else the persistent workbench target: `preview` per sample, then+ * one `commit` (pointer up only, so a structural commit in the requester's continuation is not refused as+ * `gesture-active`) or `cancel`. Returns whether consumed; a declined preview falls back to brush color. Optional+ * in test harnesses.*/- resolveColorSample?(hex: string): boolean;+ resolveColorSample?(hex: string, phase: ColorSamplePhase): boolean;/** Compositor providers that make sampling WYSIWYG; absent ⇒ raw cached pixels. */sampleProviders?: Pick<CompositeOptions, 'adjustedSurface' | 'derivedSurfaces' | 'groupSurface'>;/**- * Settles a pending one-shot sample with the gesture's stashed color. Called- * on pointer up only, so a structural commit in the requester's continuation- * is not refused as `gesture-active`.+ * Where the last committed brush or eraser stroke ended on each layer, in document space; shared by both tools for+ * Shift-click lines. The engine owns it and forgets entries on replay, document replacement and layer removal.*/- commitColorSample?(): void;- /** Drops the stashed sample (gesture cancel, fresh press) without settling the request. */- discardColorSample?(): void;+ paintLineEnds?: PaintLineEnds;/*** Refresh the input element cursor when tool state changes; ordinary pointermove does not automatically* reevaluate it.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.tsindex 5b2c2bdf3c..aa906733ac 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts@@ -9,9 +9,9 @@* down.*/-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { LayerTransform, TransformRect, TransformTarget } from '@workbench/canvas-engine/transform/transformMath';-import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';+import type { PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';@@ -81,19 +81,27 @@ interface TransformSubject {const identityPoint = (point: Vec2): Vec2 => point;+/**+ * Whether a transform session may open on `layer`: an editable, non-empty leaf that is not a mask. `liveRect` also+ * counts pixels the live cache holds but persistence has not acknowledged yet.+ */+export const isTransformEligible = (+ layer: CanvasLayerContract,+ doc: CanvasDocumentContractV3,+ liveRect?: Rect+): boolean =>+ // Masks lack an applyTransform bake path, so reject sessions that would preview but fail to apply.+ isLeafEditable(lookupDocumentLeaf(doc, layer.id)) &&+ layer.type !== 'inpaint_mask' &&+ layer.type !== 'regional_guidance' &&+ hittableLayerRect(layer, doc, liveRect) !== null;+/** Creates a fresh transform tool with its own session/gesture state. */export const createTransformTool = (): Tool => {let gesture: GestureState | null = null;// The cursor for the target under the pointer while idle (session but no drag).let hoverCursor: string | null = null;- const isEligible = (layer: CanvasLayerContract, doc: NonNullable<ReturnType<ToolContext['getDocument']>>): boolean =>- // Masks lack an applyTransform bake path, so reject sessions that would preview but fail to apply.- isLeafEditable(lookupDocumentLeaf(doc, layer.id)) &&- layer.type !== 'inpaint_mask' &&- layer.type !== 'regional_guidance' &&- hittableLayerRect(layer, doc) !== null;-/** Live floats take precedence over layer sessions so the frame follows detached pixels. */const subjectOf = (ctx: ToolContext): TransformSubject | null => {const doc = ctx.getDocument();@@ -219,7 +227,7 @@ export const createTransformTool = (): Tool => {const doc = ctx.getDocument();const selectedId = doc?.selectedLayerId;const selected = selectedId ? getDocumentLayer(doc, selectedId) : undefined;- if (doc && selected && isEligible(selected, doc)) {+ if (doc && selected && isTransformEligible(selected, doc)) {ctx.beginTransformSession?.(selected.id);}},@@ -303,7 +311,7 @@ export const createTransformTool = (): Tool => {// Open an unframed session on panel selection and begin movement without retargeting.const selectedId = doc.selectedLayerId;const selected = selectedId ? getDocumentLayer(doc, selectedId) : undefined;- if (!selected || !isEligible(selected, doc)) {+ if (!selected || !isTransformEligible(selected, doc)) {return;}const rect = hittableLayerRect(selected, doc);diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex e1d38e5c4d..89a6561f08 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -70,6 +70,7 @@ const CANVAS_PROJECT_MUTATION_TYPES: ReadonlySet<string> = new Set<CanvasProject'replaceCanvasFontReferences','replaceCanvasDocument','replaceCanvasLayer',+ 'replaceCanvasLayers','resizeCanvasDocument','restoreCanvasSnapshot','saveCanvasSnapshot',@@ -252,6 +253,26 @@ const replaceLeaf = ();};+/** Same-id, same-type leaf replacements as one value edit; any invalid entry refuses them all, so replay is atomic. */+const replaceLeavesInPlace = (+ document: CanvasDocumentContractV3,+ replacements: readonly { layerId: string; layer: CanvasLayerContract }[]+): CanvasDocumentContractV3 => {+ const ids = new Set(replacements.map(({ layerId }) => layerId));+ const valid =+ replacements.length > 0 &&+ ids.size === replacements.length &&+ replacements.every(+ ({ layer, layerId }) => layer.id === layerId && getDocumentLayer(document, layerId)?.type === layer.type+ );+ return valid+ ? mapNodes(+ document,+ replacements.map(({ layer, layerId }) => [layerId, () => layer])+ )+ : document;+};+/** The stack every leaf of `nodes` belongs to, or `null` when they disagree; an empty group fits any stack. */const nodesStack = (nodes: readonly CanvasNodeContract[], fallback: CanvasNodeInsertionAnchor['stack']) => {const stacks = new Set(nodes.flatMap((node) => collectSubtreeLeaves(node).map(layerStackOf)));@@ -851,6 +872,8 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProreturn mutation.layer.id === mutation.layerId? updateCanvasDocument(project, (document) => replaceLeaf(project.id, document, mutation.layer)): project;+ case 'replaceCanvasLayers':+ return updateCanvasDocument(project, (document) => replaceLeavesInPlace(document, mutation.replacements));case 'setCanvasLayersEnabled':return updateCanvasDocument(project, (document) => setCanvasLayersEnabled(document, mutation.updates));case 'setCanvasLayerPositions':diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex ec38b4694f..96f7d2b533 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -111,6 +111,7 @@ const CANVAS_MUTATION_TYPES = new Set<CanvasProjectMutation['type']>(['reorderCanvasSiblings','replaceCanvasDocument','replaceCanvasLayer',+ 'replaceCanvasLayers','rollbackStagedImageCommit','resizeCanvasDocument','restoreCanvasSnapshot',@@ -7880,6 +7881,48 @@ describe('workbenchReducer canvas v2 layer reducers', () => {expect(getCanvas(missing).document).toBe(getCanvas(replaced).document);});+ it('replaces several leaves in place in one edit, and refuses them all when any entry is invalid', () => {+ const state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('a'),+ createRasterLayer('b'),+ createInpaintMaskLayer('m'),+ ]);+ const before = getCanvas(state).document;+ const paintA = { ...createRasterLayer('a'), source: { bitmap: null, type: 'paint' as const } };+ const emptiedMask = { ...getDocumentLeaves(before).find((layer) => layer.id === 'm')!, name: 'Emptied' };++ const replaced = workbenchReducer(state, {+ replacements: [+ { layer: paintA, layerId: 'a' },+ { layer: emptiedMask, layerId: 'm' },+ ],+ type: 'replaceCanvasLayers',+ });+ const leaves = getDocumentLeaves(getCanvas(replaced).document);+ expect(leaves.map((layer) => layer.id)).toEqual(getDocumentLeaves(before).map((layer) => layer.id));+ expect(leaves.find((layer) => layer.id === 'a')).toBe(paintA);+ expect(leaves.find((layer) => layer.id === 'm')).toBe(emptiedMask);+ expect(leaves.find((layer) => layer.id === 'b')).toBe(getDocumentLeaves(before).find((layer) => layer.id === 'b'));++ const refusals = [+ [+ { layer: paintA, layerId: 'a' },+ { layer: { ...paintA, id: 'missing' }, layerId: 'missing' },+ ],+ [+ { layer: paintA, layerId: 'a' },+ { layer: paintA, layerId: 'a' },+ ],+ [{ layer: paintA, layerId: 'b' }],+ [{ layer: { ...createControlLayer('a') }, layerId: 'a' }],+ [],+ ];+ for (const replacements of refusals) {+ const refused = workbenchReducer(state, { replacements, type: 'replaceCanvasLayers' });+ expect(refused).toBe(state);+ }+ });+it('swaps a raster/control layer source but ignores mask-only layer types', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);const newSource = { image: { height: 10, imageName: 'swapped.png', width: 10 }, type: 'image' } as const;