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
refactor(canvas): admit every edit before it mutates and replay history failure-atomically
Josh Corbettd56ff17c39b4
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 890ff90f4d..b6f2308cd0 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2994,9 +2994,11 @@"savedDescription": "{{name}} added to your gallery."},"structural": {+ "busy": "Another canvas operation is in progress, so this edit was not kept.","failed": "Canvas edit failed","gestureActive": "Finish the current canvas gesture, then try again.","notReady": "The canvas is not ready to record this edit.",+ "overBudget": "This edit is too large to undo, so it was not made.","refusedInvalidTarget": "That layer cannot be the target of this edit.","refusedLocked": "A locked layer is in the way. Unlock it first.","refusedMissing": "A layer this edit needs is no longer in the canvas.",@@ -3257,6 +3259,9 @@"moveToFront": "Move to front","notReady": "The layer content is still loading. Try again shortly.","opacity": "Opacity",+ "operationFailed": "The canvas could not apply this change, so nothing was changed.",+ "overBudget": "There is not enough canvas memory to make this change undoable, so nothing was changed.",+ "stale": "The layer changed before this action finished, so nothing was changed. Try again.","rasterize": "Rasterize layer","rename": "Rename layer","reorder": "Reorder layer",@@ -3525,6 +3530,7 @@"missing": "The source layer no longer exists.","noBindings": "The active workflow has no compatible image input and output.","notReady": "The active workflow is not ready with this layer input.",+ "overBudget": "The workflow result is too large to apply undoably, so the layer was not changed.","output": "Workflow image output","replace": "Replace layer","replaceSuccess": "Replaced the layer with the workflow result.",diff --git a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.tsindex 3f8e564072..53b4698d3b 100644--- a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts+++ b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts@@ -52,14 +52,10 @@ const STRUCTURAL_MUTATION_TYPES = [/** Explicitly allowlist structural-mutation owners to prevent bypassing the prepared-edit seam. */const STRUCTURAL_MUTATION_OWNER_PATHS = new Set(['workbench/canvasProjectMutations.ts',- 'workbench/canvas-engine/controllers/booleanMergeController.ts',- 'workbench/canvas-engine/controllers/copyLayerController.ts',+ 'workbench/canvas-engine/controllers/controlPixelController.ts','workbench/canvas-engine/controllers/cropLayerController.ts',- 'workbench/canvas-engine/controllers/extractMaskedAreaController.ts',- 'workbench/canvas-engine/controllers/filterResultController.ts',- 'workbench/canvas-engine/controllers/generatedResultController.ts',+ 'workbench/canvas-engine/controllers/layerResultSteps.ts','workbench/canvas-engine/controllers/layerMutationController.ts',- 'workbench/canvas-engine/controllers/maskResultController.ts','workbench/canvas-engine/controllers/mergeLayerController.ts','workbench/canvas-engine/controllers/newRasterLayerController.ts','workbench/canvas-engine/controllers/rasterizeLayerController.ts',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 49806bdc16..dc5f3cde12 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -64,7 +64,7 @@ Current extracted ownership includes:- `RasterController`: base layer caches, decoded bitmap leases, derived, adjusted and group surfaces, rasterization jobs, invalidation, residency pins, working-set eviction, and the unified raster-memory controller.- `RasterMemoryBudgetController`: base, derived, group, decoded, detached, reserved and overage byte accounting plus generation-scoped reservations and operation-owned reservations and pins.- `RenderController`: render targets, scheduler construction, previews, and render lifecycle.-- `HistoryController`: engine-owned history and inactive byte trimming.+- `HistoryController`: engine-owned history, guarded asynchronous replay with failure reporting, and inactive byte trimming.- `PersistenceController`: dirty-bitmap flush barriers and disposal.- `EditingController`: selection state and exclusive edit-lease lifecycle.- `InteractionController`: public tool commands and their disposal boundary.@@ -140,7 +140,7 @@ Staged results use a separate compressed-Blob cache rather than retaining a decoDamage is explicit: `FrameDamage` is a full repaint, no visible repaint, or layer-local regions. The scheduler widens to full on any invalidation without a region, a viewport change or a forced repaint. The compositor resolves regions through the frame's matrices into one padded screen rect: regions entirely off the target draw nothing, and a bounded repaint clips to the rect and culls every leaf, group scope and staged preview whose screen bounds miss it. Unknown layers or non-finite geometry repaint everything.-Compositing always renders through the canonical `RasterBackend`; there is no approximate backend-free path. Filter previews and the floating selection of a grouped member compose inside the group's isolated surface, under the group's opacity, blend and adjustments, exactly as the member's committed pixels would. Committed content composes with the same semantics for display, sampling and export; previews and floats are display-only.+Compositing always renders through the canonical `RasterBackend`; there is no approximate backend-free path. Filter previews and the floating selection of a grouped member compose inside the group's isolated surface, under the group's opacity, blend and adjustments, exactly as the member's committed pixels would. Committed content composes with the same semantics for display, sampling and export; previews and floats are display-only. A layer's own adjustments apply to its layer-local pixels before resampling: export draws the display's memoized adjusted copy of a leased live cache, and otherwise adjusts only the layer region the output samples (plus one pixel of resampling margin). A downscaled layer samples more pixels than the output holds, so a detached copy of it is adjusted after resampling instead; export work stays bounded by the output size.A group surface is keyed by everything except its members' pixels and the float's placement (scope shape, member appearance and matrices, in-scope previews, the float's surface). While that key and the bounds hold, the cache refreshes in place: it unions the damage each member's cache recorded since the version it last drew, padded by one source pixel before the member's matrix maps it (bilinear reach at any scale), plus the old and new landing of a moved float, clears that region with one pixel of antialiasing margin and redraws every contributor there, then applies the group's per-pixel adjustments to the region alone. Unknown member damage, a changed member set or new bounds redraw the whole surface, reallocating only when its size changed; a new key reuses the least-recently-used of a group's two slots once both are taken.@@ -152,6 +152,14 @@ Every display-only pixel effect uses `DerivedSurfaceCache`. A slot is identifiedInvalidate only the affected effect when parameters change. Delete every derived slot when a layer is removed, replaced, or its base cache is evicted. Frame-demand culling happens before derived lookup or construction.+## Edits, history and replay++Every recorded document and pixel edit goes through one protocol, `CanvasMutationContext.begin`, and is admitted before it mutates anything. Admission reserves the 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` while the document, pixels and history are untouched. Two kinds of edit are admitted before they change anything but publish afterwards: live strokes paint as they are admitted (see below), and a floating selection is admitted when it lands. Selection-mask changes (`selection/selectionHistory.ts`) admit their step right after applying, because the new mask's size is only known then, and roll back to the exact prior selection when it cannot be kept. The resulting `EditTransaction` also reserves raster memory for its preparation (`reserveRaster`), holds leases and pins until `end()`, and publishes once: `publish(label, step, entry)` applies an `EditStep` — an optional document mutation with its postcondition and rollback, prepared pixels to install, and ancillary notifications — verifies the reducer and mirror, records the entry, then routes a user edit and notifies. A step that is rejected or fails its postconditions records nothing; a failed postcondition dispatches the step's rollback and reports when the reducer or mirror could not return. Transactions refuse while the permit is stale, a gesture runs (unless the edit belongs to that gesture), a replay runs, or the engine is disposed. Coalescing (nudges) names the entry it replaces by its `HistoryEntryToken` and is refused once anything else became the newest step.++Live pixel edits (brush, eraser, shapes, pixel transactions on control and image layers) are admitted before their first pixel changes and grow their admission before the stroke's before/after footprint does; a refused growth restores the layer's pixels and extent and the engine reports the refusal through `tools.onEditRefused`, which the canvas widget turns into a notice. Widget previews of structural edits run in one owned `StructuralPreviewSession` (`useStructuralPreview`), which coalesces live dispatches to one per frame and records the gesture as a single step; a refused commit or a cancel restores the baseline, even while edits are locked.++Undo and redo are asynchronous and failure-atomic: an entry moves to the other stack only after its replay completes, a replay that throws leaves it in place and is reported, and edits and new gestures are refused while one runs. Replays apply steps through the same verified path (`applyStep`). Pixel replays land only on trustworthy pixels: an evicted or stale cache is rasterized first under a read lease, and a layer that no longer exists moves the step as a no-op.+## Edit leases and staged-result acceptanceApplication operations acquire one exclusive lease from `CanvasEditGate`. A lease carries an `AbortSignal`, has an explicit `isCurrent()` freshness check, and is idempotently released. Release, document/project invalidation, cooldown, or disposal aborts and stales the lease. Expected cancellation and stale results use status unions; exceptions represent unexpected failures.@@ -162,7 +170,7 @@ The initial `commitStagedImage` mutation atomically inserts the new raster layerThe continue-staging variant uses the same guarded transaction but inserts the candidate as a disabled raster layer, preserves the exact staging-area state and current layer selection, and keeps the staged preview active. This lets users bank candidates without visually doubling the preview or ending comparison. Undo and redo affect only the banked layer after the initial transaction.-Undo removes the accepted layer and restores the prior selection. Redo restores the identical layer and selection without recreating the event or staging candidate. The history entry uses failure-atomic replay, and a successful commit uses the normal history `push`, which clears any previous redo stack. Undo intentionally does not return the accepted candidate to staging.+Undo removes the accepted layer and restores the prior selection. Redo restores the identical layer and selection without recreating the event or staging candidate. The history entry replays failure-atomically, and a successful commit publishes through an admitted transaction, which clears any previous redo stack. Undo intentionally does not return the accepted candidate to staging.## PSD exportdiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.tsindex d840d2946d..f1746ac10d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts@@ -168,27 +168,29 @@ describe('real browser raster acceptance', () => {bitmap.close();});- it('undoes and redoes a real pixel patch', () => {+ it('undoes and redoes a real pixel patch', async () => {const backend = createDomRasterBackend();const surface = backend.createSurface(1, 1);const before = new ImageData(new Uint8ClampedArray([255, 0, 0, 255]), 1, 1);const after = new ImageData(new Uint8ClampedArray([0, 0, 255, 255]), 1, 1);const history = createHistory();surface.ctx.putImageData(after, 0, 0);- history.push(- createImagePatchEntry({- after,- apply: (_layerId, rect, pixels) => surface.ctx.putImageData(pixels, rect.x, rect.y),- before,- label: 'Browser pixel edit',- layerId: 'paint',- rect: { height: 1, width: 1, x: 0, y: 0 },- })- );+ const entry = createImagePatchEntry({+ after,+ apply: (_layerId, rect, pixels) => {+ surface.ctx.putImageData(pixels, rect.x, rect.y);+ return Promise.resolve();+ },+ before,+ label: 'Browser pixel edit',+ layerId: 'paint',+ rect: { height: 1, width: 1, x: 0, y: 0 },+ });+ history.admit(entry.bytes)!.publish(entry);- history.undo();+ await history.undo();expectPixel(surface, 0, 0, [255, 0, 0, 255]);- history.redo();+ await history.redo();expectPixel(surface, 0, 0, [0, 0, 255, 255]);});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 7a5b11bae2..6574dfa7f6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -11,7 +11,13 @@ import type { CanvasMutationOrigin } from '@workbench/canvas-engine/mutationContimport type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';+import type { BooleanRasterResult } from './controllers/booleanMergeController';+import type { CopyLayerToRasterResult } from './controllers/copyLayerController';+import type { CropLayerResult } from './controllers/cropLayerController';+import type { ExtractMaskedAreaResult } from './controllers/extractMaskedAreaController';+import type { MergeDownResult, MergeVisibleResult } from './controllers/mergeLayerController';import type { NewRasterLayerResult } from './controllers/newRasterLayerController';+import type { RasterizeLayerResult } from './controllers/rasterizeLayerController';import type { PreparedDocumentEdit } from './document-model/documentCommands';import type { CanvasDocumentModel } from './document-model/documentModel';import type { CanvasCommandRefusal } from './document/commandRefusal';@@ -56,12 +62,19 @@ export interface LayerExportGuard {/*** Guarded mutations can decline as busy (another edit or gesture), stale (pixels changed), aborted (caller- * signal), or command-specific refusals. Structural commits use {@link StructuralCommitResult}.+ * signal), not-ready (pixels still loading), over-budget (too large to undo or prepare), or command-specific+ * refusals. Structural commits use {@link StructuralCommitResult}.*/export type GuardedMutationRefusal =- | SubsetOf<CanvasTransactionOutcome, 'aborted' | 'busy' | 'stale'>+ | SubsetOf<CanvasTransactionOutcome, 'aborted' | 'busy' | 'stale' | 'not-ready' | 'over-budget'>| SubsetOf<CanvasCommandRefusal, 'locked' | 'missing' | 'unsupported'>;+/** A destructive mask edit (clear, invert); `nothing` when the mask holds no pixels to change. */+export type MaskEditResult =+ | { status: 'committed' }+ | { status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'over-budget' | 'stale'> }+ | { status: SubsetOf<CanvasCommandRefusal, 'locked' | 'missing' | 'unsupported'> | 'nothing' };+export type CommitRasterFilterResult =| { status: 'committed'; layerId: string }| { status: GuardedMutationRefusal }@@ -114,8 +127,8 @@ export interface CanvasInteractionState {invertBrushSizeScroll: boolean;lassoOptions: LassoToolOptions;marqueeOptions: MarqueeToolOptions;- /** Monotonic signal for live layer-pixel/cache content changes. */- rasterContentEpoch: number;+ /** Monotonic signal: some layer published new cache pixels (thumbnails, overview). */+ layerPixelEpoch: number;ruleOfThirds: boolean;shapeOptions: ShapeToolOptions;showBbox: boolean;@@ -128,9 +141,32 @@ export interface CanvasInteractionState {zoom: number;}+/** Settings callers may write; every other interaction key is engine-owned state they only observe. */+export type CanvasWritableInteractionKey = Extract<+ keyof CanvasInteractionState,+ | 'bboxOptions'+ | 'bboxOverlay'+ | 'brushOptions'+ | 'checkerboard'+ | 'checkerColors'+ | 'clipToBbox'+ | 'colorPair'+ | 'eraserOptions'+ | 'gradientOptions'+ | 'invertBrushSizeScroll'+ | 'lassoOptions'+ | 'marqueeOptions'+ | 'ruleOfThirds'+ | 'shapeOptions'+ | 'showBbox'+ | 'showGrid'+ | 'snapToGrid'+ | 'textOptions'+>;+export interface CanvasInteractionStateCapability {get<K extends keyof CanvasInteractionState>(key: K): CanvasInteractionState[K];- set<K extends keyof CanvasInteractionState>(key: K, value: CanvasInteractionState[K]): void;+ set<K extends CanvasWritableInteractionKey>(key: K, value: CanvasInteractionState[K]): void;subscribe<K extends keyof CanvasInteractionState>(key: K, listener: () => void): () => void;getLayerThumbnailStatus(layerId: string): LayerThumbnailStatus | 'idle';getLayerThumbnailVersion(layerId: string): number | undefined;@@ -223,16 +259,28 @@ export interface CanvasHistoryEntries {future: readonly string[];}+/**+ * How a replay ended: `applied`, nothing to replay (`empty`), another replay or edit in progress (`busy`/`refused`),+ * or `failed`, in which case the step stayed where it was and the engine reported why.+ */+export type CanvasHistoryReplayStatus = 'applied' | 'empty' | 'busy' | 'refused' | 'failed';+export interface CanvasHistoryCapability {- undo(): void;- redo(): void;+ undo(): Promise<CanvasHistoryReplayStatus>;+ redo(): Promise<CanvasHistoryReplayStatus>;clearHistory(): void;getEntries(): CanvasHistoryEntries;getHeldAssetRefs(): { images: readonly string[]; videos: readonly string[] };- /** Replays `offset` steps — negative undoes, positive redoes — clamped to the stacks. */- stepBy(offset: number): void;+ /** Replays `offset` steps, one at a time, stopping at the first that does not apply. */+ stepBy(offset: number): Promise<CanvasHistoryReplayStatus>;}+/** Why the engine refused an edit the user started without a caller to report to (a stroke, a shape). */+export type CanvasEditRefusal = SubsetOf<+ CanvasTransactionOutcome,+ 'busy' | 'gesture-active' | 'not-ready' | 'over-budget'+>;+export type LayerThumbnailRequestResult =| 'ready'| 'error'@@ -324,7 +372,11 @@ export type ReplaceSelectionFromImageResult =*/export type StructuralCommitResult =| { status: 'committed' }- | { status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'gesture-active' | 'not-ready'> | 'dispatch-rejected' }+ | {+ status:+ | SubsetOf<CanvasTransactionOutcome, 'busy' | 'gesture-active' | 'not-ready' | 'over-budget'>+ | 'dispatch-rejected';+ }| { status: SubsetOf<CanvasTransactionOutcome, 'stale'>; expectedRevision: number; actualRevision: number }| { status: 'postcondition-failed'; recovered: 'reverted' | 'reverted-unmirrored' | 'unreverted' };@@ -350,8 +402,22 @@ export interface CanvasStructuralEngine {readonly layers: CanvasLayerCapability;}+/**+ * An owned live preview of a structural edit. `apply` publishes previews at most once per frame; `commit` records+ * the gesture as one undo step from its prepared baseline, without dispatching again when the preview already+ * reached it, and returns to the baseline when it is refused; `cancel` drops pending previews and dispatches+ * `restore`, unrecorded, to return to the baseline. A newer session or any other commit ends it, and later calls are+ * refused (`commit` reports `busy`); while edits are locked, `apply` and `commit` refuse.+ */+export interface StructuralPreviewSession {+ apply(action: CanvasLayerPreviewMutation): boolean;+ commit(label: string, edit: PreparedDocumentEdit): StructuralCommitResult;+ cancel(restore?: CanvasLayerPreviewMutation): void;+}+export interface CanvasLayerCapability {- applyStructuralPreview(action: CanvasLayerPreviewMutation): boolean;+ /** Starts a preview session, or null while edits are refused. */+ beginStructuralPreview(): StructuralPreviewSession | null;canCommitStructural(): boolean;commitGeneratedImageResult(options: CommitGeneratedImageOptions): Promise<CommitGeneratedImageResult>;commitStagedImage(options: CommitStagedImageOptions): CommitStagedImageResult;@@ -363,7 +429,7 @@ export interface CanvasLayerCapability {): StructuralCommitResult;/** Runs a prepared flat edit through the transaction: refusals, dispatch, verification and history. */commitPrepared(label: string, edit: PreparedDocumentEdit, options?: PreparedCommitOptions): StructuralCommitResult;- invertMask(layerId: string): boolean;+ invertMask(layerId: string): MaskEditResult;}export interface PreparedCommitOptions {@@ -379,7 +445,11 @@ export interface CommitStagedImageOptions {export type CommitStagedImageResult =| { status: 'committed'; layerId: string }- | { status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'stale'> | SubsetOf<CanvasCommandRefusal, 'missing'> };+ | {+ status:+ | SubsetOf<CanvasTransactionOutcome, 'busy' | 'stale' | 'not-ready' | 'over-budget'>+ | SubsetOf<CanvasCommandRefusal, 'missing'>;+ };export type GeneratedImageTarget = 'replace' | 'copy-raster' | 'copy-control';@@ -424,41 +494,22 @@ export interface FilterPreviewInput {filterType?: string;}-/**- * Merge result: inserted composite, inconsistent contributor raster, allocation refusal, edit contention, or fewer- * than two eligible nonempty rasters.- */-export type MergeVisibleResult =- | 'merged'- | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'busy'>- | 'over-budget'- | 'nothing';export type DuplicateLayersResult =| { readonly status: 'duplicated'; readonly duplicateIds: readonly string[]; readonly selectedLayerId: string }| { readonly status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'stale'> | 'nothing' | 'over-budget' };-export type BooleanRasterResult =- | 'merged'- | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>- | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'busy'>- | 'empty';-export type ExtractMaskedAreaResult =- | { status: 'extracted'; layerId: string }- | {- status:- | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>- | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'busy'>- | 'empty';- };-export type CropLayerResult =- | { status: 'cropped' }- | {- status:- | SubsetOf<CanvasCommandRefusal, 'missing' | 'locked' | 'unsupported'>- | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'busy'>- | 'empty'- | 'over-budget';- }- | { status: 'failed'; message: string };+/**+ * Layer pixel operations report a distinct outcome: refused before anything changed (`busy`, `not-ready`,+ * `over-budget` when the edit could never be undone), nothing to do, or `failed` when the document refused it.+ */+export type {+ BooleanRasterResult,+ CopyLayerToRasterResult,+ CropLayerResult,+ ExtractMaskedAreaResult,+ MergeDownResult,+ MergeVisibleResult,+ RasterizeLayerResult,+};export interface CanvasDiagnosticsCapability {clearCaches(): Promise<void>;getDiagnostics(): Readonly<CanvasDiagnosticsSnapshot>;@@ -498,6 +549,8 @@ export interface CanvasEngineToolCapability extends CanvasToolCapability {canTargetLayerFromContextMenu(): boolean;handleEscapePriority(options: { gestureWasActive: boolean }): void;onStrokeCommitted(listener: (event: StrokeCommittedEvent) => void): () => void;+ /** Refusals of edits that have no caller to report to, such as a stroke too large to undo. */+ onEditRefused(listener: (refusal: CanvasEditRefusal) => void): () => void;/*** Samples the composite once as `#rrggbb`, or null on Escape, tool change or disposal. Restores the previous* tool on either outcome.@@ -516,7 +569,7 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {booleanMergeRasterLayers(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult>;cancelTextEdit(): void;cancelTransform(): void;- clearMask(layerId: string): boolean;+ clearMask(layerId: string): MaskEditResult;commitLayerConversion(label: string, expectedLiveLayer: CanvasLayerContract, after: CanvasLayerContract): boolean;commitLayerCopy(label: string,@@ -529,17 +582,17 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {commitRasterFilterResult(options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult>;/** `null` when there was nothing to commit: an empty creation or an unchanged edit. */commitTextEdit(content: string, styleChanges?: Partial<TextToolOptions>): StructuralCommitResult | null;- copyLayerToRaster(layerId: string): Promise<string | null>;+ copyLayerToRaster(layerId: string): Promise<CopyLayerToRasterResult>;cropLayerToBbox(layerId: string): Promise<CropLayerResult>;duplicateLayers(layerIds: readonly string[]): Promise<DuplicateLayersResult>;- mergeLayerDown(upperLayerId: string): boolean;+ mergeLayerDown(upperLayerId: string): MergeDownResult;mergeSelectedRasterLayers(layerIds: readonly string[]): Promise<MergeVisibleResult>;mergeVisibleRasterLayers(): Promise<MergeVisibleResult>;/** `dispatch-rejected` also covers a selection with nothing eligible to move. */nudgeSelectedLayer(dx: number, dy: number): StructuralCommitResult;openTextCreate(docPoint: Vec2): void;openTextEdit(layerId: string): void;- rasterizeLayer(layerId: string): boolean;+ rasterizeLayer(layerId: string): RasterizeLayerResult;setTextEditContentReader(reader: (() => string) | null): void;updateTextEditStyle(patch: TextStylePatch): void;updateTransformSession(transform: LayerTransform): void;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.tsindex e4166c862a..894244d01f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts@@ -1,45 +1,42 @@import type { LayerExportGuard } 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';-import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import { lookupLayerBelow, mergeDownEligibility } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';+import type { CanvasMutationContext } from './mutationContext';++import {+ addedLayerHistoryBytes,+ layerEditRefusal,+ layerEditStatus,+ paintLayerAt,+ publishAddedRasterLayer,+ rgbaBytes,+ type AddedLayerContext,+ type LayerEditRefusal,+} from './newRasterLayerController';+export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';-export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty';+export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'empty' | 'failed' | LayerEditRefusal;type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };export interface BooleanMergeControllerOptions {- readonly concurrency: CanvasEditConcurrency;+ readonly ctx: AddedLayerContext &+ Pick<+ CanvasMutationContext,+ 'begin' | 'capturePermit' | 'captureInsertionAnchor' | 'createLayerId' | 'getDocument' | 'isPermitCurrent'+ >;readonly backend: RasterBackend;- readonly history: History;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly getReducerDocument: () => CanvasDocumentContractV3 | null;- readonly endBurst: () => void;readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;- readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- expectedReducer: () => boolean,- expectedMirror: () => boolean- ) => void;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;}const modes: Record<BooleanRasterOperation, GlobalCompositeOperation> = {@@ -56,12 +53,12 @@ export class BooleanMergeController {constructor(private readonly deps: BooleanMergeControllerOptions) {}async merge(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult> {- const permit = this.deps.concurrency.capturePermit();- if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {return 'busy';}- this.deps.endBurst();- const document = this.deps.getDocument();+ const document = ctx.getDocument();if (!document) {return 'missing';}@@ -94,10 +91,13 @@ export class BooleanMergeController {const [upperPixels, belowPixels] = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);- if (!this.deps.concurrency.isPermitCurrent(permit)) {+ if (!ctx.isPermitCurrent(permit)) {return 'busy';}if (upperPixels.status !== 'ok' || belowPixels.status !== 'ok') {+ if (upperPixels.status === 'over-budget' || belowPixels.status === 'over-budget') {+ return 'over-budget';+ }if (upperPixels.status === 'not-ready' || belowPixels.status === 'not-ready') {return 'not-ready';}@@ -112,16 +112,14 @@ export class BooleanMergeController {return 'empty';}if (- !this.deps.concurrency.isPermitCurrent(permit) ||- this.deps.concurrency.isGestureActive() ||upperPixels.guard.layer !== upper ||belowPixels.guard.layer !== below ||!this.deps.isGuardCurrent(upperPixels.guard) ||!this.deps.isGuardCurrent(belowPixels.guard)) {- return this.deps.concurrency.isPermitCurrent(permit) ? 'not-ready' : 'busy';+ return 'not-ready';}- const liveDocument = this.deps.getDocument();+ const liveDocument = ctx.getDocument();if (!liveDocument ||getDocumentLayer(liveDocument, upperLayerId) !== upper ||@@ -133,82 +131,50 @@ export class BooleanMergeController {if (isEmpty(resultRect)) {return 'empty';}- const pixels = this.deps.backend.createSurface(resultRect.width, resultRect.height);- pixels.ctx.setTransform(1, 0, 0, 1, 0, 0);- pixels.ctx.clearRect(0, 0, resultRect.width, resultRect.height);- pixels.ctx.globalAlpha = below.opacity;- pixels.ctx.globalCompositeOperation = 'source-over';- pixels.ctx.drawImage(- belowPixels.surface.canvas,- belowPixels.rect.x - resultRect.x,- belowPixels.rect.y - resultRect.y- );- pixels.ctx.globalAlpha = upper.opacity;- pixels.ctx.globalCompositeOperation = modes[operation];- pixels.ctx.drawImage(- upperPixels.surface.canvas,- upperPixels.rect.x - resultRect.x,- upperPixels.rect.y - resultRect.y- );- const resultId = this.deps.createLayerId();- const resultLayer: CanvasLayerContract = {- blendMode: 'normal',- id: resultId,- isEnabled: true,- isLocked: false,- name: `${upper.name} ${operation}`,- opacity: 1,- source: { bitmap: null, offset: { x: resultRect.x, y: resultRect.y }, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };- const original = [- { id: upper.id, isEnabled: upper.isEnabled },- { id: below.id, isEnabled: below.isEnabled },- ];- const disabled = original.map(({ id }) => ({ id, isEnabled: false }));- const selectedLayerId = liveDocument.selectedLayerId;- const anchor = this.deps.captureInsertionAnchor('raster', upper.id);- const hasState = (doc: CanvasDocumentContractV3 | null, updates: typeof original): boolean =>- updates.every((update) => getDocumentLayer(doc, update.id)?.isEnabled === update.isEnabled);- const apply = (): void => {- const prepared = this.deps.preparePixels(resultId, resultRect, pixels);- this.deps.dispatchPrepared(- {- add: [{ anchor, nodes: [resultLayer] }],- enabledUpdates: disabled,- selectedLayerId: resultId,- type: 'applyCanvasLayerStackMutation',- },- () =>- this.deps.getReducerDocument()?.selectedLayerId === resultId &&- hasState(this.deps.getReducerDocument(), disabled),- () => this.deps.getDocument()?.selectedLayerId === resultId && hasState(this.deps.getDocument(), disabled)+ const txn = ctx.begin({ historyBytes: addedLayerHistoryBytes(resultRect) });+ if (!('publish' in txn)) {+ return layerEditRefusal(txn.status);+ }+ try {+ if (!txn.reserveRaster(rgbaBytes(resultRect))) {+ return 'over-budget';+ }+ const pixels = this.deps.backend.createSurface(resultRect.width, resultRect.height);+ pixels.ctx.setTransform(1, 0, 0, 1, 0, 0);+ pixels.ctx.clearRect(0, 0, resultRect.width, resultRect.height);+ pixels.ctx.globalAlpha = below.opacity;+ pixels.ctx.globalCompositeOperation = 'source-over';+ pixels.ctx.drawImage(+ belowPixels.surface.canvas,+ belowPixels.rect.x - resultRect.x,+ belowPixels.rect.y - resultRect.y);- this.deps.installPrepared(prepared);- };- if (!this.deps.concurrency.isPermitCurrent(permit)) {- return 'busy';+ pixels.ctx.globalAlpha = upper.opacity;+ pixels.ctx.globalCompositeOperation = modes[operation];+ pixels.ctx.drawImage(+ upperPixels.surface.canvas,+ upperPixels.rect.x - resultRect.x,+ upperPixels.rect.y - resultRect.y+ );+ const layer = paintLayerAt(ctx.createLayerId(), `${upper.name} ${operation}`, resultRect);+ const status = layerEditStatus(+ publishAddedRasterLayer(ctx, txn, {+ anchor: ctx.captureInsertionAnchor('raster', upper.id),+ enabled: {+ after: [upper, below].map(({ id }) => ({ id, isEnabled: false })),+ before: [upper, below].map(({ id, isEnabled }) => ({ id, isEnabled })),+ },+ label: `Boolean ${operation}`,+ layer,+ pixels,+ rect: resultRect,+ selectedLayerId: liveDocument.selectedLayerId,+ })+ );+ return status === 'committed' ? 'merged' : status;+ } finally {+ txn.end();}- apply();- this.deps.history.push({- bytes: resultRect.width * resultRect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(resultLayer),- label: `Boolean ${operation}`,- redo: apply,- replayFailureAtomic: true,- undo: () =>- this.deps.dispatchPrepared(- { enabledUpdates: original, removeIds: [resultId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },- () =>- this.deps.getReducerDocument()?.selectedLayerId === selectedLayerId &&- hasState(this.deps.getReducerDocument(), original),- () =>- this.deps.getDocument()?.selectedLayerId === selectedLayerId &&- hasState(this.deps.getDocument(), original)- ),- });- return 'merged';} finally {for (const result of owned) {result.release();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.tsindex 408a923daa..8e084928dc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.test.ts@@ -1,14 +1,14 @@-import type {- CanvasControlLayerContract,- CanvasDocumentContractV3,- CanvasRasterLayerContractV2,-} from '@workbench/canvas-engine/contracts';--import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';-import { createHistory } from '@workbench/canvas-engine/history/history';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';++import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { createHistory, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';import { PixelEditController } from './controlPixelController';@@ -16,180 +16,194 @@ import { PixelEditController } from './controlPixelController';const imageData = (data: readonly number[], width = 1, height = 1): ImageData =>({ colorSpace: 'srgb', data: new Uint8ClampedArray(data), height, width }) as ImageData;+const PATCH = {+ after: imageData([255, 0, 0, 255]),+ before: imageData([0, 0, 0, 0]),+ rect: { height: 1, width: 1, x: 0, y: 0 },+};++const control = layerContract('control', 'control');+const image = layerContract('image', 'raster', {+ source: { image: { height: 1, imageName: 'image', width: 1 }, type: 'image' },+} as Partial<CanvasLayerContract>);++/** The controller over a real reducer, mutation context and history. */+const createHarness = (+ layer: CanvasLayerContract,+ options: { byteBudget?: number; gestureActive?: boolean; notifyPainted?: () => void } = {}+) => {+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document: documentFrom([layer], layer.id),+ type: 'replaceCanvasDocument',+ });+ const history = createHistory({ byteBudget: options.byteBudget });+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreateRect(layer.id, { height: 1, width: 1, x: 0, y: 0 });+ const dispatch = (action: CanvasProjectMutation): boolean => {+ project = applyCanvasProjectMutation(project, action);+ return true;+ };+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch,+ editOwner: Symbol('owner'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => project.canvas.document,+ getReducerDocument: () => project.canvas.document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => options.gestureActive ?? false,+ isGuardCurrent: () => true,+ preparePixels: () => {+ throw new Error('unused');+ },+ projectId: project.id,+ refreshMirror: () => undefined,+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),+ subscribeReducer: () => () => undefined,+ });+ const release = vi.fn();+ const calls = {+ installPrepared: vi.fn(),+ markLayerDirty: vi.fn(),+ release,+ reportRefusal: vi.fn(),+ suspendLayer: vi.fn(() => release),+ };+ const controller = new PixelEditController({+ applyImagePatch: vi.fn(() => Promise.resolve()),+ backend,+ bitmapStore: { discardLayer: vi.fn(), markLayerDirty: calls.markLayerDirty, suspendLayer: calls.suspendLayer },+ canEdit: () => true,+ ctx,+ deleteDerived: vi.fn(),+ getActiveProjectId: () => project.id,+ getAdjustedSurface: () => null,+ getDocument: () => project.canvas.document,+ getTransformSession: () => null,+ installPrepared: calls.installPrepared,+ invalidate: vi.fn(),+ isCacheReady: () => true,+ isOperationIdle: () => true,+ layers,+ notifyPainted: options.notifyPainted ?? vi.fn(),+ preparePixels: (layerId, rect, pixels) => layers.prepareReplacement(layerId, rect, pixels),+ projectId: project.id,+ publishStroke: vi.fn(),+ reportRefusal: calls.reportRefusal,+ setTransformOverride: vi.fn(),+ });+ return {+ calls,+ controller,+ dispatch,+ history,+ layer: () => getDocumentLayer(project.canvas.document, layer.id),+ layers,+ };+};+describe('PixelEditController', () => {- it('can be instantiated with narrow fakes and rejects edits without a document', () => {- const controller = new PixelEditController({- applyImagePatch: vi.fn(),- backend: createTestStubRasterBackend(),- bitmapStore: { discardLayer: vi.fn(), markLayerDirty: vi.fn(), suspendLayer: vi.fn() } as never,- canEdit: () => true,- deleteDerived: vi.fn(),- dispatchReplacement: vi.fn(),- endBurst: vi.fn(),- getActiveProjectId: () => 'project-1',- getAdjustedSurface: vi.fn(),- getDocument: () => null,- getTransformSession: () => null,- history: {} as never,- installPrepared: vi.fn(),- invalidate: vi.fn(),- isCacheReady: () => false,- isOperationIdle: () => true,- layers: {} as never,- notifyPainted: vi.fn(),- preparePixels: vi.fn(),- projectId: 'project-1',- publishStroke: vi.fn(),- setTransformOverride: vi.fn(),- });+ it('rejects edits on a layer that is gone', () => {+ const h = createHarness(control);+ h.dispatch({ ids: ['control'], type: 'removeCanvasLayers' });- expect(controller.begin('control-1')).toBeNull();- expect(controller.isOpenFor(['control-1'])).toBe(false);- expect(() => controller.dispose()).not.toThrow();+ expect(h.controller.begin('control')).toBeNull();+ expect(h.controller.isOpenFor(['control'])).toBe(false);});- it('dirties pixels and releases persistence when direct-edit cleanup throws', () => {- const backend = createTestStubRasterBackend();- const layers = createLayerCacheStore(backend);- const release = vi.fn();- const markLayerDirty = vi.fn();- const layer: CanvasControlLayerContract = {- adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: 'm', weight: 1 },- blendMode: 'normal',- id: 'control',- isEnabled: true,- isLocked: false,- name: 'Control',- opacity: 1,- source: { bitmap: null, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'control',- withTransparencyEffect: false,- };- const document: CanvasDocumentContractV3 = {- background: 'transparent',- bbox: { height: 8, width: 8, x: 0, y: 0 },- height: 8,- stacks: stacksFrom([layer]),- selectedLayerId: layer.id,- version: 3,- width: 8,- };- const history = createHistory();- const controller = new PixelEditController({- applyImagePatch: vi.fn(),- backend,- bitmapStore: { discardLayer: vi.fn(), markLayerDirty, suspendLayer: vi.fn(() => release) },- canEdit: () => true,- deleteDerived: vi.fn(),- dispatchReplacement: vi.fn(),- endBurst: () => {- throw new Error('end burst failed');- },- getActiveProjectId: () => 'project-1',- getAdjustedSurface: vi.fn(),- getDocument: () => document,- getTransformSession: () => null,- history,- installPrepared: vi.fn(),- invalidate: vi.fn(),- isCacheReady: () => true,- isOperationIdle: () => true,- layers,- notifyPainted: vi.fn(),- preparePixels: (layerId, rect, pixels) => layers.prepareReplacement(layerId, rect, pixels),- projectId: 'project-1',- publishStroke: vi.fn(),- setTransformOverride: vi.fn(),- });- const transaction = controller.begin(layer.id)!;- layers.getOrCreateRect(layer.id, { height: 1, width: 1, x: 0, y: 0 });-- expect(() =>- transaction.commitPatch('Direct edit', {- after: imageData([255, 0, 0, 255]),- before: imageData([0, 0, 0, 0]),- rect: { height: 1, width: 1, x: 0, y: 0 },- })- ).toThrow('end burst failed');- expect(history.canUndo()).toBe(true);- expect(markLayerDirty).toHaveBeenCalledWith(layer.id);- expect(release).toHaveBeenCalledOnce();- expect(controller.isOpenFor([layer.id])).toBe(false);+ it('records a direct edit as one step, persisting it once the suspension ends', () => {+ const h = createHarness(control);+ const transaction = h.controller.begin('control')!;+ expect(h.calls.suspendLayer).toHaveBeenCalledWith('control');++ expect(transaction.commitPatch('Direct edit', PATCH)).toBe(true);+ expect(h.history.entries().past).toEqual(['Direct edit']);+ expect(h.calls.markLayerDirty).toHaveBeenCalledWith('control');+ expect(h.calls.release).toHaveBeenCalledOnce();+ expect(h.controller.isOpenFor(['control'])).toBe(false);});- it('keeps an accepted materialization dirty and releases persistence when transform cleanup throws', () => {- const backend = createTestStubRasterBackend();- const layers = createLayerCacheStore(backend);- const release = vi.fn();- const markLayerDirty = vi.fn();- const layer: CanvasRasterLayerContractV2 = {- blendMode: 'normal',- id: 'image',- isEnabled: true,- isLocked: false,- name: 'Image',- opacity: 1,- source: { image: { height: 1, imageName: 'image', width: 1 }, type: 'image' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };- let document: CanvasDocumentContractV3 = {- background: 'transparent',- bbox: { height: 8, width: 8, x: 0, y: 0 },- height: 8,- stacks: stacksFrom([layer]),- selectedLayerId: layer.id,- version: 3,- width: 8,- };- const entry = layers.getOrCreate(layer.id, 1, 1);- entry.surface.ctx.putImageData(imageData([255, 255, 255, 255]), 0, 0);- layers.publishPixels(layer.id);- const history = createHistory();- const controller = new PixelEditController({- applyImagePatch: vi.fn(),- backend,- bitmapStore: { discardLayer: vi.fn(), markLayerDirty, suspendLayer: vi.fn(() => release) },- canEdit: () => true,- deleteDerived: vi.fn(),- dispatchReplacement: (replacement) => {- document = { ...document, stacks: stacksFrom([replacement]) };- },- endBurst: vi.fn(),- getActiveProjectId: () => 'project-1',- getAdjustedSurface: () => null,- getDocument: () => document,- getTransformSession: () => null,- history,- installPrepared: vi.fn(),- invalidate: vi.fn(),- isCacheReady: () => true,- isOperationIdle: () => true,- layers,- notifyPainted: vi.fn(),- preparePixels: (layerId, rect, pixels) => layers.prepareReplacement(layerId, rect, pixels),- projectId: 'project-1',- publishStroke: vi.fn(),- setTransformOverride: (_layerId, transform) => {- if (transform === null) {- throw new Error('transform cleanup failed');- }+ it('keeps an accepted edit recorded and persisted when a notification throws', () => {+ const h = createHarness(control, {+ notifyPainted: () => {+ throw new Error('observer failed');},});- const transaction = controller.begin(layer.id)!;-- expect(() =>- transaction.commitPatch('Materialized edit', {- after: imageData([0, 0, 0, 0]),- before: imageData([255, 255, 255, 255]),- rect: { height: 1, width: 1, x: 0, y: 0 },- })- ).toThrow('transform cleanup failed');- expect(getDocumentLeaves(document)[0]).toMatchObject({ source: { type: 'paint' }, type: 'raster' });- expect(history.canUndo()).toBe(true);- expect(markLayerDirty).toHaveBeenCalledWith(layer.id);- expect(release).toHaveBeenCalledOnce();- expect(controller.isOpenFor([layer.id])).toBe(false);+ const transaction = h.controller.begin('control')!;++ expect(transaction.commitPatch('Direct edit', PATCH)).toBe(true);+ expect(h.history.canUndo()).toBe(true);+ expect(h.calls.markLayerDirty).toHaveBeenCalledWith('control');+ expect(h.calls.release).toHaveBeenCalledOnce();+ });++ it('refuses a gesture-time edit unless the gesture itself starts it', () => {+ const h = createHarness(control, { gestureActive: true });++ expect(h.controller.begin('control')).toBeNull();+ expect(h.calls.reportRefusal).toHaveBeenCalledWith('gesture-active');+ expect(h.controller.begin('control', { gesture: true })).not.toBeNull();+ });++ it('records a materialization as one replace step and replays it whole', async () => {+ const h = createHarness(image);+ const transaction = h.controller.begin('image')!;++ expect(transaction.commitPatch('Erase', PATCH)).toBe(true);+ expect(h.layer()).toMatchObject({ source: { type: 'paint' }, type: 'raster' });+ expect(h.calls.release).toHaveBeenCalledOnce();++ expect(await h.history.undo()).toEqual({ status: 'applied' });+ expect(h.layer()).toMatchObject({ source: { type: 'image' } });+ expect(await h.history.redo()).toEqual({ status: 'applied' });+ expect(h.layer()).toMatchObject({ source: { type: 'paint' } });+ expect(h.calls.installPrepared).toHaveBeenCalledTimes(2);+ });++ it('leaves a materialization step in place when its layer is gone', async () => {+ const h = createHarness(image);+ h.controller.begin('image')!.commitPatch('Erase', PATCH);+ h.dispatch({ ids: ['image'], type: 'removeCanvasLayers' });++ expect(await h.history.undo()).toMatchObject({ status: 'failed' });+ expect(h.history.entries().past).toEqual(['Erase']);+ expect(h.calls.installPrepared).not.toHaveBeenCalled();+ });++ it('refuses a materialization too large to undo before baking anything', () => {+ const h = createHarness(image, { byteBudget: 4 });+ const surface = h.layers.get('image')!.surface;++ expect(h.controller.begin('image')).toBeNull();+ expect(h.calls.reportRefusal).toHaveBeenCalledWith('over-budget');+ expect(h.layers.get('image')!.surface).toBe(surface);+ expect(h.calls.suspendLayer).not.toHaveBeenCalled();+ });++ it("admits a materialization's whole-layer snapshots once, not again for the stroke inside it", () => {+ const { rect } = createHarness(image).layers.get('image')!;+ const snapshots = rect.width * rect.height * 4 * 2 + HISTORY_ENTRY_OVERHEAD_BYTES;+ const h = createHarness(image, { byteBudget: snapshots });+ const transaction = h.controller.begin('image')!;++ expect(transaction.grow(rect.width * rect.height * 8)).toBe(true);+ expect(transaction.commitPatch('Erase', PATCH)).toBe(true);+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();+ });++ it('reinstates the unbaked cache when a materialized edit is cancelled', () => {+ const h = createHarness(image);+ const surface = h.layers.get('image')!.surface;+ const transaction = h.controller.begin('image')!;+ expect(h.layers.get('image')!.surface).not.toBe(surface);++ transaction.cancel();+ expect(h.layers.get('image')!.surface).toBe(surface);+ expect(h.layer()).toMatchObject({ source: { type: 'image' } });+ expect(h.calls.release).toHaveBeenCalledOnce();+ expect(h.history.canUndo()).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.tsindex 2c597eecfb..d15f9df641 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/controlPixelController.ts@@ -1,8 +1,12 @@/** Transactional pixel editing for controls and destructively edited raster images. */-import type { CanvasControlLayerContract, CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import type { CanvasEditRefusal } from '@workbench/canvas-engine/capabilities';+import type {+ CanvasControlLayerContract,+ CanvasDocumentContractV3,+ CanvasLayerContract,+} from '@workbench/canvas-engine/contracts';import type { BitmapStore } from '@workbench/canvas-engine/document/bitmapStore';-import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { LayerPixelSnapshot, LayerPixelSnapshotApply } from '@workbench/canvas-engine/history/layerSnapshot';import type {@@ -15,6 +19,7 @@ import type { PixelEditTransaction, PixelEditPatch, StrokeCommittedEvent } fromimport type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';+import { areJsonValuesStructurallyEqual } from '@platform/core/json';import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';@@ -24,24 +29,25 @@ import {decidePixelEdit,type PixelEditableLayer,} from '@workbench/canvas-engine/editing/controlPixelEdit';+import { HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';import { createLayerSnapshotEntry } from '@workbench/canvas-engine/history/layerSnapshot';import { isEmpty } from '@workbench/canvas-engine/math/rect';import { strokeCommitLabel } from '@workbench/canvas-engine/strokeCommit';+import type { CanvasMutationContext, EditStep, EditTransaction } from './mutationContext';+export interface PixelEditControllerOptions {+ readonly ctx: Pick<CanvasMutationContext, 'applyStep' | 'begin'>;readonly applyImagePatch: ImagePatchApply;readonly backend: RasterBackend;readonly bitmapStore: Pick<BitmapStore, 'discardLayer' | 'markLayerDirty' | 'suspendLayer'>;readonly canEdit: () => boolean;readonly deleteDerived: (layerId: string) => void;- readonly dispatchReplacement: (layer: PixelEditableLayer) => void;- readonly endBurst: () => void;readonly getActiveProjectId: () => string | null;readonly getAdjustedSurface: (layer: PixelEditableLayer, entry: LayerCacheEntry) => RasterSurface | null;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getTransformSession: () => unknown;- readonly history: History;readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;readonly invalidate: (layerId: string, overlay?: boolean) => void;readonly isCacheReady: (layer: PixelEditableLayer, document: CanvasDocumentContractV3) => boolean;@@ -55,6 +61,7 @@ export interface PixelEditControllerOptions {) => PreparedLayerCacheReplacement;readonly projectId: string;readonly publishStroke: (event: StrokeCommittedEvent) => void;+ readonly reportRefusal: (refusal: CanvasEditRefusal) => void;readonly setTransformOverride: (layerId: string, transform: LayerTransform | null) => void;}@@ -70,9 +77,21 @@ const isImageDataEqual = (left: ImageData, right: ImageData): boolean => {return true;};-/** Owns the exclusive direct/materialized pixel transaction for control layers and raster images. */+/** Conversion reducers clone contracts, so the replacement postcondition compares by value. */+const hasLayerContract = (document: CanvasDocumentContractV3 | null, expected: CanvasLayerContract): boolean => {+ const current = getDocumentLayer(document, expected.id);+ return current !== undefined && areJsonValuesStructurallyEqual(current, expected);+};++/**+ * Owns the exclusive direct/materialized pixel transaction for control layers and raster images. Each is admitted+ * before the first pixel changes. A commit that records nothing leaves the edit open: callers restore the pixels+ * they touched, then cancel, which releases the transaction and, for a materialized edit, reinstates the unbaked+ * cache last.+ */export class PixelEditController {- private open: { cancel: () => void; layerId: string } | null = null;+ // `publishing` while the edit records its own step: the document change it makes is not an external one.+ private open: { cancel: () => void; layerId: string; publishing: boolean } | null = null;constructor(private readonly options: PixelEditControllerOptions) {}@@ -81,25 +100,27 @@ export class PixelEditController {}isOpenFor(layerIds: readonly string[]): boolean {- return this.open !== null && layerIds.includes(this.open.layerId);+ return this.open !== null && !this.open.publishing && layerIds.includes(this.open.layerId);}+ /** Replays a whole-layer snapshot; throws, leaving the layer unchanged, when the document refuses it. */private applySnapshot: LayerPixelSnapshotApply = (snapshot) => {- const pixels = this.options.backend.createSurface(snapshot.rect.width, snapshot.rect.height);+ const o = this.options;+ const pixels = o.backend.createSurface(snapshot.rect.width, snapshot.rect.height);if (snapshot.pixels) {pixels.ctx.putImageData(snapshot.pixels, 0, 0);}- const prepared = this.options.preparePixels(snapshot.layer.id, snapshot.rect, pixels);- this.options.dispatchReplacement(snapshot.layer);- try {- this.options.bitmapStore.discardLayer(snapshot.layer.id);- } catch {- // Persistence bookkeeping is ancillary after reducer acceptance.- }- this.options.installPrepared(prepared, snapshot.layer.source.type === 'paint');+ const prepared = o.preparePixels(snapshot.layer.id, snapshot.rect, pixels);+ o.ctx.applyStep({+ accepted: (document) => hasLayerContract(document, snapshot.layer),+ install: () => o.installPrepared(prepared, snapshot.layer.source.type === 'paint'),+ mutation: { layer: snapshot.layer, layerId: snapshot.layer.id, type: 'replaceCanvasLayer' },+ notify: () => o.bitmapStore.discardLayer(snapshot.layer.id),+ });};- begin(layerId: string): PixelEditTransaction | null {+ /** `gesture` admits an edit the gesture in progress starts (a stroke's first press). */+ begin(layerId: string, options: { gesture?: boolean } = {}): PixelEditTransaction | null {const o = this.options;const document = o.getDocument();const layer = getDocumentLayer(document, layerId);@@ -124,154 +145,188 @@ export class PixelEditController {isCacheReady: o.isCacheReady(layer, document),layer,});- if (decision.status === 'rejected') {+ if (decision.status === 'rejected' || (decision.status === 'direct' && layer.type !== 'control')) {return null;}- if (decision.status === 'direct') {- if (layer.type !== 'control') {- return null;- }- return this.beginDirect(layerId, layer);+ const entry = o.layers.get(layerId);+ const beforeBytes = entry && !isEmpty(entry.rect) ? entry.rect.width * entry.rect.height * 4 : 0;+ // A materialized edit records the whole layer before and after.+ const historyBytes =+ decision.status === 'direct' ? HISTORY_ENTRY_OVERHEAD_BYTES : beforeBytes * 2 + HISTORY_ENTRY_OVERHEAD_BYTES;+ const txn = o.ctx.begin({ gesture: options.gesture, historyBytes });+ if (!('publish' in txn)) {+ o.reportRefusal(txn.status);+ return null;}- return this.beginMaterialized(layerId, layer, contentRect);+ // The unbaked surface stays alive outside the cache's accounting until the edit ends.+ if (decision.status !== 'direct' && !txn.reserveRaster(beforeBytes)) {+ txn.end();+ o.reportRefusal('over-budget');+ return null;+ }+ const opened =+ decision.status === 'direct'+ ? this.beginDirect(txn, layerId, layer as CanvasControlLayerContract)+ : this.beginMaterialized(txn, layerId, layer, contentRect);+ if (!opened) {+ txn.end();+ }+ return opened;}- private beginDirect(layerId: string, layer: CanvasControlLayerContract): PixelEditTransaction | null {+ /** The shared lifecycle: exclusive ownership, persistence suspension and refusal reporting. */+ private openTransaction(+ txn: EditTransaction,+ layerId: string,+ rollback: () => void+ ): {+ readonly owns: () => boolean;+ readonly close: (restore: boolean) => void;+ readonly grow: (bytes: number) => boolean;+ readonly refused: () => void;+ readonly publish: <T>(run: () => T) => T;+ } {const o = this.options;- const originalEntry = o.layers.get(layerId);- let originalPixels: ImageData | null = null;- if (originalEntry && !isEmpty(originalEntry.rect)) {- try {- originalPixels = originalEntry.surface.ctx.getImageData(- 0,- 0,- originalEntry.rect.width,- originalEntry.rect.height- );- } catch {- return null;- }- }- const original = o.layers.captureState(layerId);const releasePersistence = o.bitmapStore.suspendLayer(layerId);let closed = false;- let owner: { cancel: () => void; layerId: string };- const close = (): boolean => {- if (closed || this.open !== owner) {- return false;+ let refusalReported = false;+ const owner = {+ cancel: () => close(true),+ layerId,+ publishing: false,+ };+ const owns = (): boolean => !closed && this.open === owner;+ const close = (restore: boolean): void => {+ if (!owns()) {+ return;}closed = true;this.open = null;- return true;- };- const restore = (): void => {try {- if (original) {- original.surface.resize(original.rect.width, original.rect.height);- if (originalPixels) {- original.surface.ctx.putImageData(originalPixels, 0, 0);- }+ if (restore) {+ rollback();}- // An exact rollback; the store re-accounts the reinstated surface.- o.layers.restoreState(layerId, original);- } finally {- o.deleteDerived(layerId);- o.invalidate(layerId);- }- };- const restoreAndRelease = (): void => {- try {- restore();} finally {- releasePersistence();+ try {+ releasePersistence();+ } finally {+ txn.end();+ }}};- const cancel = (): void => {- if (close()) {- restoreAndRelease();+ const refused = (): void => {+ if (!refusalReported) {+ refusalReported = true;+ o.reportRefusal('over-budget');}};- const commitPatch = (label: string, patch: PixelEditPatch): boolean => {- if (closed || this.open !== owner) {+ this.open = owner;+ return {+ close,+ grow: (bytes) => {+ if (txn.growHistory(bytes)) {+ return true;+ }+ refused();return false;+ },+ owns,+ publish: (run) => {+ owner.publishing = true;+ try {+ return run();+ } finally {+ owner.publishing = false;+ }+ },+ refused,+ };+ }++ private isStillTarget(layerId: string, layer: PixelEditableLayer): boolean {+ const o = this.options;+ const document = o.getDocument();+ return (+ o.getActiveProjectId() === o.projectId &&+ o.canEdit() &&+ o.isOperationIdle() &&+ document?.selectedLayerId === layerId &&+ getDocumentLayer(document, layerId) === layer+ );+ }++ private beginDirect(txn: EditTransaction, layerId: string, layer: CanvasControlLayerContract): PixelEditTransaction {+ const o = this.options;+ const original = o.layers.captureState(layerId);+ const lifecycle = this.openTransaction(txn, layerId, () => {+ // The caller already put back the pixels and extent it touched; reinstate the exact entry, version included,+ // so guards captured before the edit stay current. An extent it could not restore falls back to rasterizing.+ const surface = original?.surface;+ if (!original || (surface!.width === original.rect.width && surface!.height === original.rect.height)) {+ o.layers.restoreState(layerId, original);+ } else {+ o.layers.invalidate(layerId);}- if (isImageDataEqual(patch.before, patch.after)) {- cancel();+ o.deleteDerived(layerId);+ o.invalidate(layerId);+ });+ const commitPatch = (label: string, patch: PixelEditPatch, event?: StrokeCommittedEvent): boolean => {+ if (!lifecycle.owns()) {return false;}- const document = o.getDocument();- if (- o.getActiveProjectId() !== o.projectId ||- !o.canEdit() ||- !o.isOperationIdle() ||- document?.selectedLayerId !== layerId ||- getDocumentLayer(document, layerId) !== layer- ) {- cancel();+ if (isImageDataEqual(patch.before, patch.after) || !this.isStillTarget(layerId, layer)) {return false;}- close();- let entry = null;- try {- if (!o.history.isApplying()) {- entry = createImagePatchEntry({- after: patch.after,- apply: o.applyImagePatch,- before: patch.before,- label,- layerId,- rect: patch.rect,- });- }- } catch (error) {- restoreAndRelease();- throw error;+ const entry = createImagePatchEntry({+ after: patch.after,+ apply: o.applyImagePatch,+ before: patch.before,+ label,+ layerId,+ rect: patch.rect,+ });+ const result = lifecycle.publish(() =>+ txn.publish(+ label,+ {+ notify: () => {+ o.bitmapStore.markLayerDirty(layerId);+ o.notifyPainted(layerId);+ if (event) {+ o.publishStroke(event);+ }+ },+ },+ entry,+ { origin: 'system' }+ )+ );+ if (result.status === 'over-budget') {+ lifecycle.refused();}- try {- // Once the pixels are accepted, persistence and history are the- // authoritative consequences. Publish UI/render notifications only- // afterwards: a faulty observer must not make a visible edit ephemeral.- if (entry) {- o.history.push(entry);- }- o.bitmapStore.markLayerDirty(layerId);- o.endBurst();- try {- o.notifyPainted(layerId);- } catch {- // Accepted pixels are already dirty in the live cache; later invalidation reconciles UI observers.- }- } finally {- releasePersistence();+ if (result.status === 'committed') {+ lifecycle.close(false);}- return true;+ return result.status === 'committed';};- const transaction: PixelEditTransaction = {- cancel,- commitPatch: (label, patch) => void commitPatch(label, patch),- commitStroke: (event) => {- if (event.layerId !== layerId) {- cancel();- return;- }- if (- commitPatch(strokeCommitLabel(event.tool), {- after: event.afterImageData,- before: event.beforeImageData,- rect: event.dirtyRect,- })- ) {- o.publishStroke(event);- }- },+ return {+ cancel: () => lifecycle.close(true),+ commit: (event) =>+ event.layerId === layerId+ ? commitPatch(+ strokeCommitLabel(event.tool),+ { after: event.afterImageData, before: event.beforeImageData, rect: event.dirtyRect },+ event+ )+ : false,+ commitPatch: (label, patch) => commitPatch(label, patch),+ grow: lifecycle.grow,layerId,};- owner = { cancel, layerId };- this.open = owner;- return transaction;}private beginMaterialized(+ txn: EditTransaction,layerId: string,layer: PixelEditableLayer,contentRect: Rect@@ -312,7 +367,7 @@ export class PixelEditController {return null;}const before: LayerPixelSnapshot = { layer: structuredClone(layer), pixels: beforePixels, rect: beforeRect };- const restore = (): void => {+ const lifecycle = this.openTransaction(txn, layerId, () => {try {o.layers.restoreState(layerId, original);} finally {@@ -320,106 +375,69 @@ export class PixelEditController {o.setTransformOverride(layerId, null);o.invalidate(layerId, true);}- };- const releasePersistence = o.bitmapStore.suspendLayer(layerId);- const restoreAndRelease = (): void => {- try {- restore();- } finally {- releasePersistence();- }- };+ });try {o.layers.installReplacement(prepared);o.deleteDerived(layerId);o.setTransformOverride(layerId, { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });o.invalidate(layerId, true);} catch {- restoreAndRelease();+ lifecycle.close(true);return null;}- let closed = false;- let owner: { cancel: () => void; layerId: string };- const close = (): boolean => {- if (closed || this.open !== owner) {+ const commit = (label: string, event?: StrokeCommittedEvent): boolean => {+ if (!lifecycle.owns()) {return false;}- closed = true;- this.open = null;- return true;- };- const cancel = (): void => {- if (close()) {- restoreAndRelease();- }- };- const commit = (label: string, event?: StrokeCommittedEvent): void => {- if (!close()) {- return;- }- const document = o.getDocument();const edited = o.layers.get(layerId);- if (- o.getActiveProjectId() !== o.projectId ||- !o.canEdit() ||- !o.isOperationIdle() ||- document?.selectedLayerId !== layerId ||- getDocumentLayer(document, layerId) !== layer ||- !edited ||- (event && event.layerId !== layerId)- ) {- restoreAndRelease();- return;- }- let entry = null;- try {- const pixels = isEmpty(edited.rect)- ? null- : edited.surface.ctx.getImageData(0, 0, edited.rect.width, edited.rect.height);- const materialized = buildMaterializedPixelLayer(layer, edited.rect);- const after: LayerPixelSnapshot = { layer: materialized, pixels, rect: { ...edited.rect } };- if (!o.history.isApplying()) {- entry = createLayerSnapshotEntry({ after, apply: this.applySnapshot, before, label });- }- o.dispatchReplacement(materialized);- } catch (error) {- restoreAndRelease();- throw error;+ if (!this.isStillTarget(layerId, layer) || !edited || (event && event.layerId !== layerId)) {+ return false;}- try {- // The replacement has passed reducer and mirror postconditions. From- // here on it must never be treated as rollback-safe, even if cleanup or- // an observer fails.- if (entry) {- o.history.push(entry);- }- o.bitmapStore.markLayerDirty(layerId);- o.setTransformOverride(layerId, null);- o.endBurst();- try {+ // A preparation failure throws with the edit still open; the caller restores its pixels and cancels.+ const pixels = isEmpty(edited.rect)+ ? null+ : edited.surface.ctx.getImageData(0, 0, edited.rect.width, edited.rect.height);+ const materialized = buildMaterializedPixelLayer(layer, edited.rect);+ const after: LayerPixelSnapshot = { layer: materialized, pixels, rect: { ...edited.rect } };+ const entry = createLayerSnapshotEntry({ after, apply: this.applySnapshot, before, label });++ const step: EditStep = {+ accepted: (document) => hasLayerContract(document, materialized),+ mutation: { layer: materialized, layerId, type: 'replaceCanvasLayer' },+ notify: () => {+ o.bitmapStore.markLayerDirty(layerId);+ o.setTransformOverride(layerId, null);o.notifyPainted(layerId);- } catch {- // See the direct path: persistence is already authoritative.- }- } finally {- releasePersistence();+ if (event) {+ o.publishStroke(event);+ }+ },+ rollback: {+ mutation: { layer, layerId, type: 'replaceCanvasLayer' },+ restored: (document) => hasLayerContract(document, layer),+ },+ };+ const result = lifecycle.publish(() => txn.publish(label, step, entry));+ if (result.status === 'over-budget') {+ lifecycle.refused();}- if (event) {- o.publishStroke(event);+ if (result.status === 'committed') {+ lifecycle.close(false);}+ return result.status === 'committed';};- const transaction: PixelEditTransaction = {- cancel,- commitPatch: (label, patch) => (isImageDataEqual(patch.before, patch.after) ? cancel() : commit(label)),- commitStroke: (event) =>+ return {+ cancel: () => lifecycle.close(true),+ commit: (event) =>isImageDataEqual(event.beforeImageData, event.afterImageData)- ? cancel()+ ? false: commit(strokeCommitLabel(event.tool), event),+ commitPatch: (label, patch) => (isImageDataEqual(patch.before, patch.after) ? false : commit(label)),+ // The entry is two whole-layer snapshots, admitted at begin; the stroke's own footprint is never retained.+ // A cache the stroke grew past that admission grows it at publication instead.+ grow: () => lifecycle.owns(),layerId,};- owner = { cancel, layerId };- this.open = owner;- return transaction;}dispose(): void {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.tsindex ef2cf8d0dd..ac5ed70ccb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts@@ -1,38 +1,41 @@import type { LayerExportGuard } 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';-import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';+import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';+import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';++import type { CanvasMutationContext } from './mutationContext';++import {+ addedLayerHistoryBytes,+ layerEditRefusal,+ layerEditStatus,+ paintLayerAt,+ publishAddedRasterLayer,+ rgbaBytes,+ type AddedLayerContext,+ type LayerEditRefusal,+} from './newRasterLayerController';type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };+export type CopyLayerToRasterResult =+ | { status: 'copied'; layerId: string }+ | { status: LayerEditRefusal | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'> | 'empty' | 'failed' };+export interface CopyLayerControllerOptions {- readonly concurrency: CanvasEditConcurrency;- readonly history: History;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly getReducerDocument: () => CanvasDocumentContractV3 | null;- readonly endBurst: () => void;+ readonly ctx: AddedLayerContext &+ Pick<+ CanvasMutationContext,+ 'begin' | 'capturePermit' | 'captureInsertionAnchor' | 'createLayerId' | 'getDocument' | 'isPermitCurrent'+ >;+ readonly backend: RasterBackend;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;- readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- expectedReducer: () => boolean,- expectedMirror: () => boolean- ) => void;}/** Owns guarded baked copies into new raster paint layers. */@@ -40,90 +43,59 @@ export class CopyLayerController {private disposed = false;constructor(private readonly deps: CopyLayerControllerOptions) {}- async copyToRaster(layerId: string): Promise<string | null> {- const permit = this.deps.concurrency.capturePermit();- if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {- return null;+ async copyToRaster(layerId: string): Promise<CopyLayerToRasterResult> {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {+ return { status: 'busy' };}- this.deps.endBurst();- const document = this.deps.getDocument();- const sourceLayer = getDocumentLayer(document, layerId);- if (!document || !sourceLayer) {- return null;+ const sourceLayer = getDocumentLayer(ctx.getDocument(), layerId);+ if (!sourceLayer) {+ return { status: 'missing' };}const baked = await this.deps.exportBaked(layerId);if (baked.status !== 'ok') {- return null;+ return { status: baked.status === 'disabled' ? 'not-ready' : baked.status };}try {- if (!this.deps.concurrency.isPermitCurrent(permit)) {- return null;+ if (!ctx.isPermitCurrent(permit)) {+ return { status: 'busy' };}+ const liveDocument = ctx.getDocument();if (- this.deps.concurrency.isGestureActive() ||- !this.deps.isGuardCurrent(baked.guard) ||- baked.guard.layer !== sourceLayer+ !liveDocument ||+ getDocumentLayer(liveDocument, sourceLayer.id) !== sourceLayer ||+ baked.guard.layer !== sourceLayer ||+ !this.deps.isGuardCurrent(baked.guard)) {- return null;+ return { status: 'not-ready' };}- const liveDocument = this.deps.getDocument();- if (!liveDocument || getDocumentLayer(liveDocument, sourceLayer.id) !== sourceLayer) {- return null;+ const txn = ctx.begin({ historyBytes: addedLayerHistoryBytes(baked.rect) });+ if (!('publish' in txn)) {+ return { status: layerEditRefusal(txn.status) };}- const newId = this.deps.createLayerId();- const layer: CanvasLayerContract = {- blendMode: 'normal',- id: newId,- isEnabled: true,- isLocked: false,- name: `${sourceLayer.name} copy`,- opacity: 1,- source: { bitmap: null, offset: { x: baked.rect.x, y: baked.rect.y }, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };- const selectedLayerId = liveDocument.selectedLayerId;- const anchor = this.deps.captureInsertionAnchor('raster', layerId);- const apply = (): void => {- const prepared = this.deps.preparePixels(newId, baked.rect, baked.surface);- this.deps.dispatchPrepared(- {- add: [{ anchor, nodes: [layer] }],- enabledUpdates: [],- selectedLayerId: newId,- type: 'applyCanvasLayerStackMutation',- },- () =>- this.deps.getReducerDocument()?.selectedLayerId === newId &&- getDocumentLayer(this.deps.getReducerDocument(), layer.id) === layer,- () =>- this.deps.getDocument()?.selectedLayerId === newId &&- getDocumentLayer(this.deps.getDocument(), layer.id) === layer+ try {+ // The entry owns a copy: the leased cache keeps changing once the lease ends.+ if (!txn.reserveRaster(rgbaBytes(baked.rect))) {+ return { status: 'over-budget' };+ }+ const pixels = this.deps.backend.createSurface(baked.rect.width, baked.rect.height);+ pixels.ctx.drawImage(baked.surface.canvas, 0, 0);+ const layer = paintLayerAt(ctx.createLayerId(), `${sourceLayer.name} copy`, baked.rect);+ const status = layerEditStatus(+ publishAddedRasterLayer(ctx, txn, {+ anchor: ctx.captureInsertionAnchor('raster', layerId),+ label: 'Copy layer to raster',+ layer,+ pixels,+ rect: baked.rect,+ selectedLayerId: liveDocument.selectedLayerId,+ }));- this.deps.installPrepared(prepared);- };- if (!this.deps.concurrency.isPermitCurrent(permit)) {- return null;+ return status === 'committed' ? { layerId: layer.id, status: 'copied' } : { status };+ } finally {+ txn.end();}- apply();- this.deps.history.push({- bytes: baked.rect.width * baked.rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(layer),- label: 'Copy layer to raster',- redo: apply,- replayFailureAtomic: true,- undo: () =>- this.deps.dispatchPrepared(- { enabledUpdates: [], removeIds: [newId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },- () =>- this.deps.getReducerDocument()?.selectedLayerId === selectedLayerId &&- isNodeAbsent(this.deps.getReducerDocument(), newId),- () =>- this.deps.getDocument()?.selectedLayerId === selectedLayerId &&- isNodeAbsent(this.deps.getDocument(), newId)- ),- });- return newId;} finally {baked.release();}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.tsnew file mode 100644index 0000000000..2ad09f6f55--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts@@ -0,0 +1,102 @@+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 { describe, expect, it, vi } from 'vitest';++import { CropLayerController } from './cropLayerController';+import { createLayerOperationHarness } from './layerOperationHarness.testing';++const layer: CanvasLayerContract = {+ blendMode: 'normal',+ id: 'paint',+ isEnabled: true,+ isLocked: false,+ name: 'Paint',+ opacity: 1,+ source: { bitmap: null, offset: { x: -10, y: -10 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+};++const CACHE_RECT: Rect = { height: 50, width: 50, x: -10, y: -10 };+const BBOX: Rect = { height: 20, width: 20, x: 0, y: 0 };++const createHarness = (historyBytes?: number) => {+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: BBOX,+ height: 100,+ selectedLayerId: 'paint',+ stacks: stacksFrom([layer]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document, { historyBytes });+ h.layers.getOrCreateRect('paint', CACHE_RECT);+ const discardPersisted = vi.fn();+ const controller = new CropLayerController({+ backend: h.backend,+ captureCache: (target) => {+ const entry = h.layers.get(target.id)!;+ 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) => {+ const entry = h.layers.get(layerId)!;+ const current = getDocumentLayer(h.document(), layerId)!;+ return Promise.resolve({+ guard: { layer: current } as never,+ rect: { ...entry.rect },+ release: () => undefined,+ status: 'ok' as const,+ surface: entry.surface,+ });+ },+ isGuardCurrent: () => true,+ isSupportedSource: () => true,+ });+ return { ...h, controller, discardPersisted, original: getDocumentLayer(h.document(), 'paint')! };+};++describe('CropLayerController', () => {+ it('crops the layer to the bbox and replays the contract and pixels together', async () => {+ const h = createHarness();++ await expect(h.controller.crop('paint')).resolves.toEqual({ status: 'cropped' });+ expect(getDocumentLayer(h.document(), 'paint')).toMatchObject({ source: { offset: { x: 0, y: 0 } } });+ expect(h.layers.get('paint')?.rect).toEqual(BBOX);+ expect(h.discardPersisted).toHaveBeenCalledWith('paint');++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLayer(h.document(), 'paint')).toEqual(h.original);+ expect(h.layers.get('paint')?.rect).toEqual(CACHE_RECT);++ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(h.layers.get('paint')?.rect).toEqual(BBOX);+ });++ it('refuses a crop it could never undo before anything changes', async () => {+ const h = createHarness(1024);+ const before = h.document();++ await expect(h.controller.crop('paint')).resolves.toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(before);+ expect(h.dispatched).toEqual([]);+ expect(h.layers.get('paint')?.rect).toEqual(CACHE_RECT);+ });++ it('leaves the step on the undo stack when its replay is refused', async () => {+ const h = createHarness();+ await h.controller.crop('paint');+ h.state.refuse = () => true;++ expect((await h.history.undo()).status).toBe('failed');+ expect(h.layers.get('paint')?.rect).toEqual(BBOX);+ 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 9d4d972a54..128fd4f8f5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@ -4,21 +4,27 @@ import type {CanvasLayerContract,CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';-import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { renderableSourceOf } from '@workbench/canvas-engine/document/sources';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';+import type { CanvasMutationContext, EditStep } from './mutationContext';++import {+ layerEditRefusal,+ layerEditStatus,+ rgbaBytes,+ withReplayReservation,+ type LayerEditRefusal,+} from './newRasterLayerController';+export type CropLayerResult =| { status: 'cropped' }- | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'busy' }+ | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | LayerEditRefusal }| { status: 'failed'; message: string };type ExportResult =@@ -31,41 +37,44 @@ interface PixelSnapshot {}export interface CropLayerControllerOptions {- readonly concurrency: CanvasEditConcurrency;+ readonly ctx: Pick<+ CanvasMutationContext,+ | 'applyStep'+ | 'begin'+ | 'capturePermit'+ | 'getDocument'+ | 'getReducerDocument'+ | 'installPrepared'+ | 'isPermitCurrent'+ | 'preparePixels'+ | 'reserveRaster'+ >;readonly backend: RasterBackend;- readonly history: History;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly getReducerDocument: () => CanvasDocumentContractV3 | null;- readonly endBurst: () => void;readonly isSupportedSource: (source: CanvasLayerSourceContract) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;readonly captureCache: (layer: CanvasLayerContract,- document: CanvasDocumentContractV3- ) => PixelSnapshot | null | 'not-ready';- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;+ document: CanvasDocumentContractV3,+ admit?: (rect: Rect) => boolean+ ) => PixelSnapshot | null | 'not-ready' | 'over-budget';readonly discardPersisted: (layerId: string) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- expectedReducer: () => boolean,- expectedMirror: () => boolean- ) => void;}+const failedCrop: CropLayerResult = { message: 'The crop could not be applied.', status: 'failed' };+/** Owns guarded crop-to-bbox conversion and replayable pixel snapshots. */export class CropLayerController {private disposed = false;constructor(private readonly deps: CropLayerControllerOptions) {}async crop(layerId: string): Promise<CropLayerResult> {- const permit = this.deps.concurrency.capturePermit();- if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {return { status: 'busy' };}- this.deps.endBurst();- const document = this.deps.getDocument();+ const document = ctx.getDocument();const layer = getDocumentLayer(document, layerId);if (!document || !layer) {return { status: 'missing' };@@ -83,17 +92,14 @@ export class CropLayerController {return { status: exported.status === 'disabled' ? 'not-ready' : exported.status };}try {- if (!this.deps.concurrency.isPermitCurrent(permit)) {+ if (!ctx.isPermitCurrent(permit)) {return { status: 'busy' };}- const liveDocument = this.deps.getDocument();+ const liveDocument = ctx.getDocument();const liveLayer = getDocumentLayer(liveDocument, layerId);if (!liveDocument || !liveLayer) {return { status: 'missing' };}- if (!this.deps.concurrency.isPermitCurrent(permit) || this.deps.concurrency.isGestureActive()) {- return { status: 'busy' };- }if (liveLayer.isLocked) {return { status: 'locked' };}@@ -109,57 +115,80 @@ export class CropLayerController {return { status: 'empty' };}const cropRect = roundOut(overlap);- const beforePixels = this.deps.captureCache(liveLayer, liveDocument);- if (!beforePixels || beforePixels === 'not-ready') {- return { status: 'not-ready' };+ const txn = ctx.begin({ historyBytes: rgbaBytes(cropRect) + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ return { status: layerEditRefusal(txn.status) };}- 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 publish = (contract: CanvasLayerContract, prepared: PreparedLayerCacheReplacement): void => {- this.deps.dispatchPrepared(- { layer: contract, layerId, type: 'replaceCanvasLayer' },- () => getDocumentLayer(this.deps.getReducerDocument(), layerId) === contract,- () => getDocumentLayer(this.deps.getDocument(), layerId) === contract+ try {+ // The cropped pixels and their prepared cache replacement.+ if (!txn.reserveRaster(rgbaBytes(cropRect) * 2)) {+ return { status: 'over-budget' };+ }+ const beforePixels = this.deps.captureCache(liveLayer, liveDocument, (rect) =>+ txn.growHistory(rgbaBytes(rect)));- try {- this.deps.discardPersisted(layerId);- } catch {- /* ancillary */+ if (beforePixels === 'over-budget') {+ return { status: 'over-budget' };}- this.deps.installPrepared(prepared);- };- const apply = (contract: CanvasLayerContract, snapshot: PixelSnapshot): void =>- publish(contract, this.deps.preparePixels(layerId, snapshot.rect, snapshot.pixels));- const afterPixels = { pixels: cropped, rect: cropRect };- const prepared = this.deps.preparePixels(layerId, cropRect, cropped);- if (!this.deps.concurrency.isPermitCurrent(permit)) {- return { status: 'busy' };+ if (!beforePixels || beforePixels === 'not-ready') {+ 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 afterPixels: PixelSnapshot = { pixels: cropped, rect: cropRect };+ /** Replaces the layer's contract and cache together; a failed replacement restores the current contract. */+ const replaceStep = (contract: CanvasLayerContract, snapshot: PixelSnapshot): EditStep => {+ const previous = getDocumentLayer(ctx.getReducerDocument(), layerId);+ const prepared = ctx.preparePixels(layerId, snapshot.rect, snapshot.pixels);+ return {+ accepted: (candidate) => getDocumentLayer(candidate, layerId) === contract,+ install: () => {+ try {+ this.deps.discardPersisted(layerId);+ } catch {+ // The installed pixels are marked dirty and persist on their own.+ }+ ctx.installPrepared(prepared);+ },+ mutation: { layer: contract, layerId, type: 'replaceCanvasLayer' },+ rollback: previous+ ? {+ mutation: { layer: previous, layerId, type: 'replaceCanvasLayer' },+ restored: (candidate) => getDocumentLayer(candidate, layerId) === previous,+ }+ : undefined,+ };+ };+ const result = txn.publish('Crop layer to bbox', replaceStep(after, afterPixels), {+ bytes: rgbaBytes(beforePixels.rect) + rgbaBytes(cropRect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(before, after),+ redo: () =>+ withReplayReservation(ctx, rgbaBytes(cropRect), () => ctx.applyStep(replaceStep(after, afterPixels))),+ undo: () =>+ withReplayReservation(ctx, rgbaBytes(beforePixels.rect), () =>+ ctx.applyStep(replaceStep(before, beforePixels))+ ),+ });+ const status = layerEditStatus(result);+ return status === 'committed' ? { status: 'cropped' } : status === 'failed' ? failedCrop : { status };+ } finally {+ txn.end();}- publish(after, prepared);- this.deps.history.push({- bytes: beforePixels.rect.width * beforePixels.rect.height * 4 + cropRect.width * cropRect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(before, after),- label: 'Crop layer to bbox',- redo: () => apply(after, afterPixels),- replayFailureAtomic: true,- undo: () => apply(before, beforePixels),- });- return { status: 'cropped' };} finally {exported.release();}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.tsindex c3bd6eca90..7b677629a2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts@@ -39,14 +39,13 @@ const createTextOptions = () => ({const createTransformOptions = () => ({backend: {} as never,canEdit: () => true,- dispatch: vi.fn(),- endBurst: vi.fn(),+ commitStructural: vi.fn(),+ ctx: {} as never,getCache: () => null,getDocument: () => null,invalidate: vi.fn(),isGestureActive: () => false,- pushHistory: vi.fn(),- replaceCache: vi.fn(),+ reportRefusal: vi.fn(),restoreCache: vi.fn(),session: { get: () => null, set: vi.fn() },setOverride: vi.fn(),@@ -57,17 +56,17 @@ const createSelectionPixelOptions = () => ({backend: {} as never,beginPixelEdit: () => null,canEdit: () => true,+ ctx: {} as never,deleteDerived: vi.fn(),- endBurst: vi.fn(),getDocument: () => null,getFillColor: () => '#000',- history: {} as never,invalidateLayer: vi.fn(),isRasterCacheReady: () => true,isGestureActive: () => false,layers: {} as never,markDirty: vi.fn(),notifyPainted: vi.fn(),+ reportRefusal: vi.fn(),requestRasterization: vi.fn(),});@@ -75,14 +74,15 @@ const createFloatingSelectionOptions = () => ({applyImagePatch: vi.fn(),backend: {} as never,canEdit: () => true,- endBurst: vi.fn(),+ ctx: {} as never,getDocument: () => null,- history: {} as never,invalidateLayer: vi.fn(),layers: {} as never,markDirty: vi.fn(),notifyPainted: vi.fn(),onChange: vi.fn(),+ reportRefusal: vi.fn(),+ suspendPersistence: () => () => undefined,});const createSelectionImageOptions = () => ({diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.tsindex 6715c84434..ab3ac281b9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts@@ -20,7 +20,7 @@ import { TransformEditingController, type TransformEditingControllerOptions } frexport interface EditingControllerOptions {readonly selection: SelectionStateDeps;/** Records selection changes; the float folds its own mask move into its entry instead. */- readonly history: History;+ readonly history: Pick<History, 'admit' | 'isReplaying'>;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly createSelectionState?: (deps: SelectionStateDeps) => SelectionState;readonly createEditGate?: () => CanvasEditGateController;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.tsindex 79f4d869e8..534cca71de 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts@@ -5,47 +5,52 @@ import type {CanvasNodeContract,} from '@workbench/canvas-engine/contracts';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';-import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';-import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';+import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';import type { CompositeOptions } from '@workbench/canvas-engine/render/compositor';import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';-import type {- LayerCacheEntry,- LayerCacheStore,- PreparedLayerCacheReplacement,-} from '@workbench/canvas-engine/render/layerCache';+import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';-import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createEmptyStacks, isGroupNode } from '@workbench/canvas-engine/document/documentTree';import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';import { isEmpty } from '@workbench/canvas-engine/math/rect';import { compositeDocument } from '@workbench/canvas-engine/render/compositor';+import type { CanvasMutationContext } from './mutationContext';++import {+ addedLayerHistoryBytes,+ layerEditRefusal,+ layerEditStatus,+ paintLayerAt,+ publishAddedRasterLayer,+ rgbaBytes,+ type AddedLayerContext,+ type LayerEditRefusal,+} from './newRasterLayerController';+export type ExtractMaskedAreaResult =| { status: 'extracted'; layerId: string }- | { status: 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty' };+ | { status: LayerEditRefusal | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'> | 'empty' | 'failed' };type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };export interface ExtractMaskedAreaControllerOptions {- readonly concurrency: CanvasEditConcurrency;+ readonly ctx: AddedLayerContext &+ Pick<+ CanvasMutationContext,+ 'begin' | 'capturePermit' | 'captureInsertionAnchor' | 'createLayerId' | 'getDocument' | 'isPermitCurrent'+ >;readonly backend: RasterBackend;readonly layers: LayerCacheStore;readonly derived: DerivedSurfaceCache;readonly diagnostics: CanvasDiagnostics;- readonly history: History;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly getReducerDocument: () => CanvasDocumentContractV3 | null;- readonly endBurst: () => void;readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly hasExportableContent: (layerId: string) => boolean;readonly exportBaked: (layerId: string, includeDisabled?: boolean) => Promise<ExportResult>;@@ -54,15 +59,6 @@ export interface ExtractMaskedAreaControllerOptions {readonly getAdjustedSurface: (layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null;readonly getGroupSurface?: CompositeOptions['groupSurface'];readonly getMaskPattern: (style: string, color: string) => RasterSurface | null;- readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- expectedReducer: () => boolean,- expectedMirror: () => boolean- ) => void;}/** The raster forest reduced to `keep` leaves, groups intact so their stacks still apply. */@@ -89,12 +85,12 @@ export class ExtractMaskedAreaController {constructor(private readonly deps: ExtractMaskedAreaControllerOptions) {}async extract(maskLayerId: string): Promise<ExtractMaskedAreaResult> {- const permit = this.deps.concurrency.capturePermit();- if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {return { status: 'busy' };}- this.deps.endBurst();- const document = this.deps.getDocument();+ const document = ctx.getDocument();if (!document) {return { status: 'missing' };}@@ -140,22 +136,20 @@ export class ExtractMaskedAreaController {const [maskPixels, ...contributorPixels] = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);- if (!this.deps.concurrency.isPermitCurrent(permit)) {+ if (!ctx.isPermitCurrent(permit)) {return { status: 'busy' };}- if (maskPixels.status !== 'ok') {- return { status: maskPixels.status === 'not-ready' ? 'not-ready' : 'empty' };+ const statuses = [maskPixels, ...contributorPixels].map((pixels) => pixels.status);+ if (statuses.includes('over-budget') || statuses.includes('not-ready')) {+ return { status: statuses.includes('over-budget') ? 'over-budget' : 'not-ready' };}- if (contributorPixels.some((pixels) => pixels.status !== 'ok')) {- return { status: contributorPixels.some((pixels) => pixels.status === 'not-ready') ? 'not-ready' : 'empty' };- }- if (this.deps.concurrency.isGestureActive()) {- return { status: 'busy' };+ if (maskPixels.status !== 'ok' || statuses.some((status) => status !== 'ok')) {+ return { status: 'empty' };}if (maskPixels.guard.layer !== mask || !this.deps.isGuardCurrent(maskPixels.guard)) {return { status: 'not-ready' };}- const liveDocument = this.deps.getDocument();+ const liveDocument = ctx.getDocument();const liveMaskIndex =getDocumentLeaves(liveDocument ?? null).findIndex((layer) => layer.id === maskLayerId) ?? -1;const currentMask = getDocumentLeaves(liveDocument ?? null)[liveMaskIndex];@@ -190,85 +184,54 @@ export class ExtractMaskedAreaController {if (isEmpty(rect)) {return { status: 'empty' };}- const pixels = this.deps.backend.createSurface(rect.width, rect.height);- compositeDocument(- pixels,- {- ...document,- stacks: {- ...createEmptyStacks(),- raster: filterRasterForest(document.stacks.raster, new Set(contributors.map((layer) => layer.id))),- },- },- this.deps.layers,- { a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y },- {- adjustedSurface: this.deps.getAdjustedSurface,- groupSurface: this.deps.getGroupSurface,- backend: this.deps.backend,- derivedSurfaces: this.deps.derived,- diagnostics: this.deps.diagnostics,- maskPatternTile: this.deps.getMaskPattern,+ const txn = ctx.begin({ historyBytes: addedLayerHistoryBytes(rect) });+ if (!('publish' in txn)) {+ return { status: layerEditRefusal(txn.status) };+ }+ try {+ if (!txn.reserveRaster(rgbaBytes(rect))) {+ return { status: 'over-budget' };}- );- pixels.ctx.setTransform(1, 0, 0, 1, 0, 0);- pixels.ctx.globalAlpha = 1;- pixels.ctx.globalCompositeOperation = 'destination-in';- pixels.ctx.drawImage(maskPixels.surface.canvas, 0, 0);- const resultId = this.deps.createLayerId();- const layer: CanvasLayerContract = {- blendMode: 'normal',- id: resultId,- isEnabled: true,- isLocked: false,- name: `${mask.name} extraction`,- opacity: 1,- source: { bitmap: null, offset: { x: rect.x, y: rect.y }, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };- const selectedLayerId = liveDocument.selectedLayerId;- const anchor = this.deps.captureInsertionAnchor('raster', null);- const apply = (): void => {- const prepared = this.deps.preparePixels(resultId, rect, pixels);- this.deps.dispatchPrepared(+ const pixels = this.deps.backend.createSurface(rect.width, rect.height);+ compositeDocument(+ pixels,{- add: [{ anchor, nodes: [layer] }],- enabledUpdates: [],- selectedLayerId: resultId,- type: 'applyCanvasLayerStackMutation',+ ...document,+ stacks: {+ ...createEmptyStacks(),+ raster: filterRasterForest(document.stacks.raster, new Set(contributors.map((layer) => layer.id))),+ },},- () =>- this.deps.getReducerDocument()?.selectedLayerId === resultId &&- getDocumentLayer(this.deps.getReducerDocument(), layer.id) === layer,- () =>- this.deps.getDocument()?.selectedLayerId === resultId &&- getDocumentLayer(this.deps.getDocument(), layer.id) === layer+ this.deps.layers,+ { a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y },+ {+ adjustedSurface: this.deps.getAdjustedSurface,+ groupSurface: this.deps.getGroupSurface,+ backend: this.deps.backend,+ derivedSurfaces: this.deps.derived,+ diagnostics: this.deps.diagnostics,+ maskPatternTile: this.deps.getMaskPattern,+ });- this.deps.installPrepared(prepared);- };- if (!this.deps.concurrency.isPermitCurrent(permit)) {- return { status: 'busy' };+ pixels.ctx.setTransform(1, 0, 0, 1, 0, 0);+ pixels.ctx.globalAlpha = 1;+ pixels.ctx.globalCompositeOperation = 'destination-in';+ pixels.ctx.drawImage(maskPixels.surface.canvas, 0, 0);+ const layer = paintLayerAt(ctx.createLayerId(), `${mask.name} extraction`, rect);+ const status = layerEditStatus(+ publishAddedRasterLayer(ctx, txn, {+ anchor: ctx.captureInsertionAnchor('raster', null),+ label: 'Extract masked area',+ layer,+ pixels,+ rect,+ selectedLayerId: liveDocument.selectedLayerId,+ })+ );+ return status === 'committed' ? { layerId: layer.id, status: 'extracted' } : { status };+ } finally {+ txn.end();}- apply();- this.deps.history.push({- bytes: rect.width * rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(layer),- label: 'Extract masked area',- redo: apply,- replayFailureAtomic: true,- undo: () =>- this.deps.dispatchPrepared(- { enabledUpdates: [], removeIds: [resultId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },- () =>- this.deps.getReducerDocument()?.selectedLayerId === selectedLayerId &&- isNodeAbsent(this.deps.getReducerDocument(), resultId),- () =>- this.deps.getDocument()?.selectedLayerId === selectedLayerId &&- isNodeAbsent(this.deps.getDocument(), resultId)- ),- });- return { layerId: resultId, status: 'extracted' };} finally {for (const result of owned) {result.release();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.tsindex a1e55e3b44..ee2b87ee33 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts@@ -1,24 +1,30 @@import type { CommitRasterFilterOptions, CommitRasterFilterResult } from '@workbench/canvas-engine/capabilities';import type {CanvasControlLayerContract,- CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';-import type { CapturedLayerCache } from '@workbench/canvas-engine/controllers/layerMutationController';+import type { LayerMutationControllerOptions } from '@workbench/canvas-engine/controllers/layerMutationController';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { Rect } from '@workbench/canvas-engine/types';-import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { createControlLayer } from '@workbench/canvas-engine/document/layerFactories';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import type { CanvasMutationContext } from './mutationContext';+import {+ addLayerStep,+ pixelBytes,+ publishRefusal,+ removeLayerStep,+ replaceLayerStep,+ replayWithPixels,+} from './layerResultSteps';+export type {CommitRasterFilterOptions,CommitRasterFilterResult,@@ -27,8 +33,22 @@ export type {} from '@workbench/canvas-engine/capabilities';export interface FilterResultControllerOptions {- readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => CapturedLayerCache;- readonly ctx: CanvasMutationContext;+ readonly captureCache: LayerMutationControllerOptions['captureCache'];+ readonly ctx: Pick<+ CanvasMutationContext,+ | 'applyStep'+ | 'begin'+ | 'capturePermit'+ | 'captureInsertionAnchor'+ | 'createLayerId'+ | 'getDocument'+ | 'installPrepared'+ | 'isGestureActive'+ | 'isGuardCurrent'+ | 'isPermitCurrent'+ | 'preparePixels'+ | 'reserveRaster'+ >;readonly decodeImage: (image: CanvasImageRef,options: {@@ -99,137 +119,127 @@ export class FilterResultController {if (options.signal?.aborted) {return { status: 'aborted' };}- o.ctx.endBurst();const image = structuredClone(options.image);const rect = { ...options.rect };const paintSource = { bitmap: image, offset: { x: rect.x, y: rect.y }, type: 'paint' } as const;- if (options.mode === 'replace') {- const beforePixels = o.captureCache(liveLayer, document);- if (!beforePixels || beforePixels === 'not-ready') {- return { status: 'stale' };+ const afterPixels = { pixels, rect };+ const txn = o.ctx.begin({ historyBytes: pixelBytes(rect) + HISTORY_ENTRY_OVERHEAD_BYTES, owner });+ if (!('publish' in txn)) {+ return { status: txn.status === 'gesture-active' ? 'busy' : txn.status };+ }+ try {+ if (!txn.reserveRaster(pixelBytes(rect))) {+ return { status: 'over-budget' };}- const before = structuredClone(liveLayer);- const after: CanvasLayerContract =- liveLayer.type === 'raster'- ? (() => {- const { adjustments: _adjustments, ...base } = liveLayer;- return structuredClone({ ...base, filter: options.filter, source: paintSource });- })()- : structuredClone({ ...liveLayer, filter: options.filter, source: paintSource });- const afterPixels = { pixels, rect };- const publish = (- contract: CanvasLayerContract,- prepared: PreparedLayerCacheReplacement,- publishOptions: { discardPersistence: boolean; persist: boolean }- ): void => {- o.ctx.dispatchPrepared(- { layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },- () => getDocumentLayer(o.ctx.getReducerDocument(), liveLayer.id) === contract,- () => getDocumentLayer(o.ctx.getDocument(), liveLayer.id) === contract- );- if (publishOptions.discardPersistence) {- try {- o.discardPersisted(liveLayer.id);- } catch {- /* Ancillary after commit. */- }+ if (options.mode === 'replace') {+ const beforePixels = o.captureCache(liveLayer, document, (rect) => txn.growHistory(pixelBytes(rect)));+ if (beforePixels === 'not-ready' || beforePixels === 'over-budget') {+ return { status: beforePixels };}- o.ctx.installPrepared(prepared, publishOptions.persist);- };- const apply = (- contract: CanvasLayerContract,- snapshot: { pixels: RasterSurface; rect: Rect },- publishOptions: { discardPersistence: boolean; persist: boolean }- ): void => publish(contract, o.ctx.preparePixels(liveLayer.id, snapshot.rect, snapshot.pixels), publishOptions);- publish(after, o.ctx.preparePixels(liveLayer.id, rect, pixels), { discardPersistence: true, persist: false });- o.ctx.history.push({- bytes: beforePixels.rect.width * beforePixels.rect.height * 4 + rect.width * rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(before, after),- label: 'Replace layer with filter result',- redo: () => apply(after, afterPixels, { discardPersistence: true, persist: false }),- replayFailureAtomic: true,- undo: () =>- apply(before, beforePixels, { discardPersistence: false, persist: o.needsPixelPersistence(before) }),- });- return { layerId: liveLayer.id, status: 'committed' };- }- const selectedLayerId = document.selectedLayerId;- const layerId = o.ctx.createLayerId();- let copy: CanvasLayerContract;- if (options.target === 'control') {- const buildControlBase = (): CanvasControlLayerContract => {- const mainBase = o.getMainModelBase();- return createControlLayer(- `${liveLayer.name} filtered`,- layerId,- mainBase,- o.getDefaultControlModel(mainBase)+ if (!beforePixels) {+ return { status: 'stale' };+ }+ const before = structuredClone(liveLayer);+ const after: CanvasLayerContract =+ liveLayer.type === 'raster'+ ? (() => {+ const { adjustments: _adjustments, ...base } = liveLayer;+ return structuredClone({ ...base, filter: options.filter, source: paintSource });+ })()+ : structuredClone({ ...liveLayer, filter: options.filter, source: paintSource });+ const discard = (): void => o.discardPersisted(liveLayer.id);+ const prepared = o.ctx.preparePixels(liveLayer.id, rect, pixels);+ const interrupted = this.interrupted(options);+ if (interrupted) {+ return interrupted;+ }+ const result = txn.publish(+ 'Replace layer with filter result',+ replaceLayerStep(o.ctx, after, prepared, { notify: discard, persist: false, restore: liveLayer }),+ {+ bytes: pixelBytes(beforePixels.rect) + pixelBytes(rect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(before, after),+ redo: () =>+ replayWithPixels(o.ctx, liveLayer.id, afterPixels, (prepared) =>+ replaceLayerStep(o.ctx, after, prepared, { notify: discard, persist: false, restore: before })+ ),+ undo: () =>+ replayWithPixels(o.ctx, liveLayer.id, beforePixels, (prepared) =>+ replaceLayerStep(o.ctx, before, prepared, {+ persist: o.needsPixelPersistence(before),+ restore: after,+ })+ ),+ });- };- const base = liveLayer.type === 'control' ? structuredClone(liveLayer) : buildControlBase();- copy = {- ...base,- filter: options.filter,- id: layerId,- name: `${liveLayer.name} filtered`,- source: paintSource,- transform: structuredClone(liveLayer.transform),- };- } else if (options.target === 'raster' && liveLayer.type === 'control') {- copy = {- blendMode: liveLayer.blendMode,- filter: options.filter,- id: layerId,- isEnabled: true,- isLocked: false,- name: `${liveLayer.name} filtered`,- opacity: liveLayer.opacity,- source: paintSource,- transform: structuredClone(liveLayer.transform),- type: 'raster',- };- } else {- const { adjustments: _adjustments, ...base } = structuredClone(liveLayer as CanvasRasterLayerContractV2);- copy = {- ...base,- filter: options.filter,- id: layerId,- name: `${liveLayer.name} filtered`,- source: paintSource,- type: 'raster',- };- }- const anchor = o.ctx.captureInsertionAnchor(copy.type, liveLayer.id);- const apply = (): void => {+ return result.status === 'committed'+ ? { layerId: liveLayer.id, status: 'committed' }+ : { status: publishRefusal(result) };+ }+ const selectedLayerId = document.selectedLayerId;+ const layerId = o.ctx.createLayerId();+ let copy: CanvasLayerContract;+ if (options.target === 'control') {+ const buildControlBase = (): CanvasControlLayerContract => {+ const mainBase = o.getMainModelBase();+ return createControlLayer(+ `${liveLayer.name} filtered`,+ layerId,+ mainBase,+ o.getDefaultControlModel(mainBase)+ );+ };+ const base = liveLayer.type === 'control' ? structuredClone(liveLayer) : buildControlBase();+ copy = {+ ...base,+ filter: options.filter,+ id: layerId,+ name: `${liveLayer.name} filtered`,+ source: paintSource,+ transform: structuredClone(liveLayer.transform),+ };+ } else if (options.target === 'raster' && liveLayer.type === 'control') {+ copy = {+ blendMode: liveLayer.blendMode,+ filter: options.filter,+ id: layerId,+ isEnabled: true,+ isLocked: false,+ name: `${liveLayer.name} filtered`,+ opacity: liveLayer.opacity,+ source: paintSource,+ transform: structuredClone(liveLayer.transform),+ type: 'raster',+ };+ } else {+ const { adjustments: _adjustments, ...base } = structuredClone(liveLayer as CanvasRasterLayerContractV2);+ copy = {+ ...base,+ filter: options.filter,+ id: layerId,+ name: `${liveLayer.name} filtered`,+ source: paintSource,+ type: 'raster',+ };+ }+ const anchor = o.ctx.captureInsertionAnchor(copy.type, liveLayer.id);+ const added = (prepared: PreparedLayerCacheReplacement | null) =>+ addLayerStep(o.ctx, copy, anchor, prepared, { persist: false, previousSelectedLayerId: selectedLayerId });const prepared = o.ctx.preparePixels(layerId, rect, pixels);- o.ctx.dispatchPrepared(- { anchor, layer: copy, type: 'addCanvasLayer' },- () => getDocumentLayer(o.ctx.getReducerDocument(), copy.id) === copy,- () => getDocumentLayer(o.ctx.getDocument(), copy.id) === copy- );- o.ctx.installPrepared(prepared, false);- };- apply();- o.ctx.history.push({- bytes: rect.width * rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(copy),- label: 'Copy layer filter result',- redo: apply,- replayFailureAtomic: true,- undo: () => {- o.ctx.dispatchPrepared(- { id: selectedLayerId, type: 'setCanvasSelectedLayer' },- () => o.ctx.getReducerDocument()?.selectedLayerId === selectedLayerId,- () => o.ctx.getDocument()?.selectedLayerId === selectedLayerId- );- o.ctx.dispatchPrepared(- { ids: [layerId], type: 'removeCanvasLayers' },- () => isNodeAbsent(o.ctx.getReducerDocument(), layerId),- () => isNodeAbsent(o.ctx.getDocument(), layerId)- );- },- });- return { layerId, status: 'committed' };+ const interrupted = this.interrupted(options);+ if (interrupted) {+ return interrupted;+ }+ const result = txn.publish('Copy layer filter result', added(prepared), {+ bytes: pixelBytes(rect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(copy),+ redo: () => replayWithPixels(o.ctx, layerId, afterPixels, added),+ undo: () => o.ctx.applyStep(removeLayerStep(layerId, selectedLayerId)),+ });+ return result.status === 'committed' ? { layerId, status: 'committed' } : { status: publishRefusal(result) };+ } finally {+ txn.end();+ }} catch (error) {if (options.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {return { status: 'aborted' };@@ -239,4 +249,12 @@ export class FilterResultController {}dispose(): void {}++ /** Preparation may run long enough for the caller to abort or the source to change; check both last. */+ private interrupted(options: CommitRasterFilterOptions): CommitRasterFilterResult | null {+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }+ return this.options.ctx.isGuardCurrent(options.guard) ? null : { status: 'stale' };+ }}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.tsindex 8df2095650..67026022ce 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts@@ -2,6 +2,7 @@ import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/cimport type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';+import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -32,10 +33,12 @@ const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({width: 100,});-const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect; cacheRect?: Rect } = {}) => {+const createHarness = (+ options: { layer?: CanvasLayerContract; maskRect?: Rect; cacheRect?: Rect; byteBudget?: number } = {}+) => {const backend = createTestStubRasterBackend();const layers = createLayerCacheStore(backend);- const history = createHistory();+ const history = createHistory({ byteBudget: options.byteBudget });const layer = options.layer ?? paintLayer('a');let document: CanvasDocumentContractV3 | null = makeDoc([layer]);@@ -64,28 +67,52 @@ const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect;// Seed a cache so there is something to lift out of.layers.getOrCreateRect(layer.id, options.cacheRect ?? { height: 100, width: 100, x: 0, y: 0 });+ const releasePersistence = vi.fn();const calls = {- applyImagePatch: vi.fn(),- endBurst: vi.fn(),+ applyImagePatch: vi.fn((_layerId: string, _rect: Rect, _pixels: ImageData) => Promise.resolve()),invalidateLayer: vi.fn(),markDirty: vi.fn(),notifyPainted: vi.fn(),onChange: vi.fn(),+ releasePersistence,+ reportRefusal: vi.fn(),+ suspendPersistence: vi.fn(() => releasePersistence),};+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch: () => true,+ editOwner: Symbol('owner'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => document,+ getReducerDocument: () => document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => false,+ isGuardCurrent: () => true,+ preparePixels: () => {+ throw new Error('unused');+ },+ projectId: 'p',+ refreshMirror: () => undefined,+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),+ subscribeReducer: () => () => undefined,+ });const controller = new FloatingSelectionController({applyImagePatch: calls.applyImagePatch,backend,canEdit: () => true,- endBurst: calls.endBurst,+ ctx,getDocument: () => document,- history,invalidateLayer: calls.invalidateLayer,layers,markDirty: calls.markDirty,notifyPainted: calls.notifyPainted,onChange: calls.onChange,+ reportRefusal: calls.reportRefusal,selection,+ suspendPersistence: calls.suspendPersistence,});return {@@ -132,10 +159,23 @@ describe('FloatingSelectionController: lift', () => {expect(h.history.canUndo()).toBe(false);});- it('closes any coalescing burst before touching pixels', () => {- const h = createHarness();- h.controller.lift('a');- expect(h.calls.endBurst).toHaveBeenCalled();+ it('suspends persistence of the layer until the float commits or cancels', () => {+ const committed = createHarness();+ committed.controller.lift('a');+ expect(committed.calls.suspendPersistence).toHaveBeenCalledWith('a');+ expect(committed.calls.releasePersistence).not.toHaveBeenCalled();+ move(committed.controller, 40, 0);+ committed.controller.commit();+ expect(committed.calls.releasePersistence).toHaveBeenCalledOnce();+ // Dirty before release, so the landed pixels are what persists.+ expect(committed.calls.markDirty.mock.invocationCallOrder[0]).toBeLessThan(+ committed.calls.releasePersistence.mock.invocationCallOrder[0]!+ );++ const cancelled = createHarness();+ cancelled.controller.lift('a');+ cancelled.controller.cancel();+ expect(cancelled.calls.releasePersistence).toHaveBeenCalledOnce();});it('refuses a second lift while a float is live', () => {@@ -223,7 +263,7 @@ describe('FloatingSelectionController: display effects', () => {});describe('FloatingSelectionController: commit', () => {- it('pushes exactly one undoable entry for the whole move, however many drags', () => {+ it('pushes exactly one undoable entry for the whole move, however many drags', async () => {const h = createHarness();h.controller.lift('a');move(h.controller, 5, 0);@@ -233,11 +273,11 @@ describe('FloatingSelectionController: commit', () => {expect(h.controller.has()).toBe(false);expect(h.history.canUndo()).toBe(true);- h.history.undo();+ await h.history.undo();expect(h.history.canUndo()).toBe(false);});- it('spans both the hole and the landing region so one undo restores both', () => {+ it('spans both the hole and the landing region so one undo restores both', async () => {const h = createHarness();h.controller.lift('a');move(h.controller, 40, 0);@@ -246,16 +286,16 @@ describe('FloatingSelectionController: commit', () => {// The commit writes the cache directly; `applyImagePatch` is the history// entry's replay bridge, so it first runs on undo.expect(h.calls.applyImagePatch).not.toHaveBeenCalled();- h.history.undo();+ await h.history.undo();- const [layerId, rect] = h.calls.applyImagePatch.mock.calls[0] as [string, Rect];+ const [layerId, rect] = h.calls.applyImagePatch.mock.calls[0];expect(layerId).toBe('a');// The hole at x ∈ [20,50) unioned with the landing region at x ∈ [60,90).expect(rect.x).toBe(20);expect(rect.x + rect.width).toBe(90);});- it('moves the ants inside the same step as the pixels, so one undo puts both back', () => {+ it('moves the ants inside the same step as the pixels, so one undo puts both back', async () => {const h = createHarness();const before = { alpha: null, bounds: null, commits: [], rect: null, selected: false };const after = { ...before, selected: true };@@ -265,13 +305,40 @@ describe('FloatingSelectionController: commit', () => {h.controller.commit();expect(h.history.entries()).toEqual({ future: [], past: ['Move selection'] });- h.history.undo();+ await h.history.undo();expect(h.calls.applyImagePatch).toHaveBeenCalledTimes(1);expect(h.selection.restore).toHaveBeenLastCalledWith(before);- h.history.redo();+ await h.history.redo();expect(h.selection.restore).toHaveBeenLastCalledWith(after);});+ it('puts the pixels back and reports a move too large to undo, recording nothing', () => {+ // The 100×30 patch alone exceeds the whole budget.+ const h = createHarness({ byteBudget: 1000 });+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.controller.commit();++ expect(h.controller.has()).toBe(false);+ expect(h.history.canUndo()).toBe(false);+ expect(h.calls.reportRefusal).toHaveBeenCalledWith('over-budget');+ expect(h.calls.markDirty).not.toHaveBeenCalled();+ expect(h.replaceMask).not.toHaveBeenCalled();+ expect(h.calls.releasePersistence).toHaveBeenCalledOnce();+ });++ it('keeps the step and the ants in place when its pixels cannot be restored', async () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.controller.commit();+ h.calls.applyImagePatch.mockRejectedValueOnce(new Error('evicted'));++ expect(await h.history.undo()).toMatchObject({ status: 'failed' });+ expect(h.history.entries()).toEqual({ future: [], past: ['Move selection'] });+ expect(h.selection.restore).not.toHaveBeenCalled();+ });+it('marks the layer dirty so the baked pixels persist', () => {const h = createHarness();h.controller.lift('a');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.tsindex 226cc4711d..451fefff4d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts@@ -1,5 +1,5 @@+import type { CanvasEditRefusal } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';@@ -23,15 +23,19 @@ import { eraseMaskedRegion } from '@workbench/canvas-engine/selection/selectionOimport { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';import { bakeMatrix, IDENTITY_TRANSFORM } from '@workbench/canvas-engine/transform/transformMath';+import type { CanvasMutationContext } from './mutationContext';+export interface FloatingSelectionControllerOptions {readonly backend: RasterBackend;readonly layers: LayerCacheStore;readonly selection: SelectionState;- readonly history: History;+ readonly ctx: Pick<CanvasMutationContext, 'begin'>;readonly applyImagePatch: ImagePatchApply;+ /** Holds back persistence of a layer until the returned release; the cut hole must never upload. */+ readonly suspendPersistence: (layerId: string) => () => void;+ readonly reportRefusal: (refusal: CanvasEditRefusal) => void;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly canEdit: () => boolean;- readonly endBurst: () => void;readonly notifyPainted: (layerId: string) => void;readonly markDirty: (layerId: string) => void;readonly invalidateLayer: (layerId: string) => void;@@ -47,12 +51,14 @@ const isIdentity = (transform: LayerTransform): boolean =>transform.rotation === 0;/**- * Lifts pixels without history or dirtying, preventing persistence of the temporary hole. Commit records pre-lift- * and post-bake pixels across the hole/landing union as one undo entry and marks dirty. Cancellation restores- * pixels without history.+ * Lifts pixels without history or dirtying, suspending the layer's persistence so the temporary hole never uploads.+ * Commit is admitted before it lands anything and records pre-lift and post-bake pixels across the hole/landing union+ * as one undo entry; a commit that cannot be recorded puts the pixels back instead. Cancellation restores pixels+ * without history.*/export class FloatingSelectionController {private float: FloatingSelection | null = null;+ private releasePersistence: (() => void) | null = null;private disposed = false;constructor(private readonly deps: FloatingSelectionControllerOptions) {}@@ -98,9 +104,7 @@ export class FloatingSelectionController {return false;}- // Close any coalescing burst before mutating pixels, so a pending nudge does- // not absorb this edit.- this.deps.endBurst();+ this.releasePersistence = this.deps.suspendPersistence(layerId);const region = lifted.pixels.rect;const before = entry.surface.ctx.getImageData(region.x - entry.rect.x,@@ -155,8 +159,7 @@ export class FloatingSelectionController {const layer = this.layerOf(float);if (!layer) {// The layer went away under the float; the pixels have nowhere to land.- this.float = null;- this.deps.onChange();+ this.settle();return;}if (isIdentity(float.transform)) {@@ -169,8 +172,35 @@ export class FloatingSelectionController {// The patch spans both the hole left behind and where the pixels land, so a// single undo restores both halves of the move.const patchRect = union(float.before.rect, landing);+ const selectionBefore = this.deps.selection.snapshot();+ const selectionBytes = (selectionBefore.alpha?.byteLength ?? 0) * 2;+ // Banking a float is part of whatever the user moved on to, even mid-gesture.+ const txn = this.deps.ctx.begin({+ gesture: true,+ historyBytes: patchRect.width * patchRect.height * 8 + selectionBytes,+ });+ if (!('publish' in txn)) {+ this.cancel();+ this.deps.reportRefusal(txn.status);+ return;+ }+ try {+ this.land(float, layer, matrix, patchRect, selectionBefore, txn);+ } finally {+ txn.end();+ }+ }- this.deps.endBurst();+ private land(+ float: FloatingSelection,+ layer: CanvasLayerContract,+ matrix: ReturnType<typeof bakeMatrix>,+ patchRect: Rect,+ selectionBefore: ReturnType<SelectionState['snapshot']>,+ txn: Extract<ReturnType<CanvasMutationContext['begin']>, { publish: unknown }>+ ): void {+ const existing = this.deps.layers.get(float.layerId);+ const originalRect = existing ? { ...existing.rect } : null;const entry = this.deps.layers.growToRect(float.layerId, patchRect);// Reconstruct the pre-lift pixels over the patch: the live cache is correct@@ -202,40 +232,70 @@ export class FloatingSelectionController {patchRect.height);- this.float = null;- this.deps.onChange();- this.deps.notifyPainted(float.layerId);- this.deps.markDirty(float.layerId);- this.deps.invalidateLayer(float.layerId);-// The ants travel with the pixels inside the same step, so one undo puts// both back; the raw selection records nothing of its own here.- const selectionBefore = this.deps.selection.snapshot();this.moveSelectionWithFloat(layer, matrix, float);const selectionAfter = this.deps.selection.snapshot();- if (!this.deps.history.isApplying()) {- const patch = createImagePatchEntry({- after,- apply: this.deps.applyImagePatch,- before,- label: 'Move selection',- layerId: float.layerId,- rect: patchRect,- });- this.deps.history.push({+ const patch = createImagePatchEntry({+ after,+ apply: this.deps.applyImagePatch,+ before,+ label: 'Move selection',+ layerId: float.layerId,+ rect: patchRect,+ });+ const result = txn.publish(+ patch.label,+ {+ notify: () => {+ this.deps.notifyPainted(float.layerId);+ this.deps.markDirty(float.layerId);+ this.deps.invalidateLayer(float.layerId);+ },+ },+ {bytes: patch.bytes + (selectionBefore.alpha?.byteLength ?? 0) + (selectionAfter.alpha?.byteLength ?? 0),heldAssetRefs: patch.heldAssetRefs,- label: patch.label,- redo: () => {- patch.redo();+ redo: async () => {+ await patch.redo();this.deps.selection.restore(selectionAfter);},- undo: () => {- patch.undo();+ undo: async () => {+ await patch.undo();this.deps.selection.restore(selectionBefore);},- });+ },+ { origin: 'system' }+ );+ if (result.status !== 'committed') {+ // Nothing was recorded: return the layer and the ants to their pre-lift state.+ const live = this.deps.layers.get(float.layerId);+ live?.surface.ctx.putImageData(before, patchRect.x - live.rect.x, patchRect.y - live.rect.y);+ if (originalRect) {+ this.deps.layers.shrinkToRect(float.layerId, originalRect);+ } else {+ this.deps.layers.delete(float.layerId);+ }+ this.deps.selection.restore(selectionBefore);+ this.deps.notifyPainted(float.layerId);+ this.deps.invalidateLayer(float.layerId);+ if (result.status === 'over-budget') {+ this.deps.reportRefusal('over-budget');+ }+ }+ this.settle();+ }++ /** Drops the float and lets its layer persist again. */+ private settle(): void {+ this.float = null;+ const release = this.releasePersistence;+ this.releasePersistence = null;+ try {+ release?.();+ } finally {+ this.deps.onChange();}}@@ -260,19 +320,14 @@ export class FloatingSelectionController {if (!float) {return;}- this.float = null;- this.deps.onChange();- if (!this.layerOf(float)) {- return;- }const restoreRect: Rect = float.before.rect;- if (isEmpty(restoreRect)) {- return;+ if (this.layerOf(float) && !isEmpty(restoreRect)) {+ const entry = this.deps.layers.growToRect(float.layerId, restoreRect);+ entry.surface.ctx.putImageData(float.before.data, restoreRect.x - entry.rect.x, restoreRect.y - entry.rect.y);+ this.deps.notifyPainted(float.layerId);+ this.deps.invalidateLayer(float.layerId);}- const entry = this.deps.layers.growToRect(float.layerId, restoreRect);- entry.surface.ctx.putImageData(float.before.data, restoreRect.x - entry.rect.x, restoreRect.y - entry.rect.y);- this.deps.notifyPainted(float.layerId);- this.deps.invalidateLayer(float.layerId);+ this.settle();}dispose(): void {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.tsindex d58f4e2811..9a3ec4e94d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts@@ -1,22 +1,43 @@import type { CommitGeneratedImageOptions, CommitGeneratedImageResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { CapturedLayerCache } from '@workbench/canvas-engine/controllers/layerMutationController';+import type { LayerMutationControllerOptions } from '@workbench/canvas-engine/controllers/layerMutationController';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';-import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';-import type { Rect } from '@workbench/canvas-engine/types';-import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createControlLayer, nextControlLayerName } from '@workbench/canvas-engine/document/layerFactories';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import type { CanvasMutationContext } from './mutationContext';+import {+ addLayerStep,+ pixelBytes,+ publishRefusal,+ removeLayerStep,+ replaceLayerStep,+ replayWithPixels,+} from './layerResultSteps';+export interface GeneratedResultControllerOptions {- readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => CapturedLayerCache;+ readonly captureCache: LayerMutationControllerOptions['captureCache'];readonly clearPreview: (layerId: string) => void;- readonly ctx: CanvasMutationContext;+ readonly ctx: Pick<+ CanvasMutationContext,+ | 'applyStep'+ | 'begin'+ | 'capturePermit'+ | 'captureInsertionAnchor'+ | 'createLayerId'+ | 'getDocument'+ | 'installPrepared'+ | 'isGestureActive'+ | 'isGuardCurrent'+ | 'isPermitCurrent'+ | 'preparePixels'+ | 'reserveRaster'+ >;readonly decodeImage: (image: CanvasImageRef,options: { signal?: AbortSignal; isCurrent?: () => boolean }@@ -86,149 +107,118 @@ export class GeneratedResultController {const rect = { height: image.height, width: image.width, ...origin };const source = { bitmap: image, offset: origin, type: 'paint' } as const;const identityTransform: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };- const publishSnapshot = (- contract: CanvasLayerContract,- prepared: PreparedLayerCacheReplacement,- publishOptions: { discardPersistence: boolean; persist: boolean }- ): void => {- o.ctx.dispatchPrepared(- { layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },- () => getDocumentLayer(o.ctx.getReducerDocument(), liveLayer.id) === contract,- () => getDocumentLayer(o.ctx.getDocument(), liveLayer.id) === contract- );- if (publishOptions.discardPersistence) {- try {+ const afterPixels = { pixels: decoded.surface, rect };+ const txn = o.ctx.begin({ historyBytes: pixelBytes(rect) + HISTORY_ENTRY_OVERHEAD_BYTES, owner });+ if (!('publish' in txn)) {+ return { status: txn.status === 'gesture-active' ? 'busy' : txn.status };+ }+ try {+ if (!txn.reserveRaster(pixelBytes(rect))) {+ return { status: 'over-budget' };+ }+ if (options.target === 'replace') {+ const beforePixels = o.captureCache(liveLayer, document, (rect) => txn.growHistory(pixelBytes(rect)));+ if (beforePixels === 'not-ready' || beforePixels === 'over-budget') {+ return { status: beforePixels };+ }+ if (!beforePixels) {+ return { status: 'stale' };+ }+ const before = structuredClone(liveLayer);+ let after: CanvasLayerContract;+ if (liveLayer.type === 'raster') {+ const { adjustments: _adjustments, ...base } = structuredClone(liveLayer);+ after = { ...base, source, transform: identityTransform };+ } else {+ after = { ...structuredClone(liveLayer), source, transform: identityTransform };+ }+ const clearPreview = (): void => o.clearPreview(liveLayer.id);+ const publishAfter = (): void => {o.discardPersisted(liveLayer.id);- } catch {- /* Ancillary after reducer acceptance. */+ clearPreview();+ };+ const prepared = o.ctx.preparePixels(liveLayer.id, rect, decoded.surface);+ const interrupted = this.interrupted(options, validate);+ if (interrupted) {+ return interrupted;}+ const result = txn.publish(+ options.historyLabel ?? 'Replace layer with workflow result',+ replaceLayerStep(o.ctx, after, prepared, { notify: publishAfter, persist: false, restore: liveLayer }),+ {+ bytes: pixelBytes(beforePixels.rect) + pixelBytes(rect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(before, after),+ redo: () =>+ replayWithPixels(o.ctx, liveLayer.id, afterPixels, (prepared) =>+ replaceLayerStep(o.ctx, after, prepared, { notify: publishAfter, persist: false, restore: before })+ ),+ undo: () =>+ replayWithPixels(o.ctx, liveLayer.id, beforePixels, (prepared) =>+ replaceLayerStep(o.ctx, before, prepared, {+ notify: clearPreview,+ persist: o.needsPixelPersistence(before),+ restore: after,+ })+ ),+ }+ );+ return result.status === 'committed'+ ? { layerId: liveLayer.id, status: 'committed' }+ : { status: publishRefusal(result) };}- try {- o.clearPreview(liveLayer.id);- } catch {- /* Transient preview is ancillary. */- }- o.ctx.installPrepared(prepared, publishOptions.persist);- };- const applySnapshot = (- contract: CanvasLayerContract,- snapshot: { pixels: RasterSurface; rect: Rect },- publishOptions: { discardPersistence: boolean; persist: boolean }- ): void =>- publishSnapshot(contract, o.ctx.preparePixels(liveLayer.id, snapshot.rect, snapshot.pixels), publishOptions);- if (options.target === 'replace') {- const beforePixels = o.captureCache(liveLayer, document);- if (!beforePixels || beforePixels === 'not-ready') {- return { status: 'stale' };- }- if (options.signal?.aborted) {- return { status: 'aborted' };- }- const before = structuredClone(liveLayer);- let after: CanvasLayerContract;- if (liveLayer.type === 'raster') {- const { adjustments: _adjustments, ...base } = structuredClone(liveLayer);- after = { ...base, source, transform: identityTransform };- } else {- after = { ...structuredClone(liveLayer), source, transform: identityTransform };- }- const afterPixels = { pixels: decoded.surface, rect };- const prepared = o.ctx.preparePixels(liveLayer.id, rect, decoded.surface);- if (options.signal?.aborted) {- return { status: 'aborted' };- }- const finalCheck = validate();- if ('result' in finalCheck) {- return finalCheck.result;- }- o.ctx.endBurst();- publishSnapshot(after, prepared, { discardPersistence: true, persist: false });- o.ctx.history.push({- bytes: beforePixels.rect.width * beforePixels.rect.height * 4 + rect.width * rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(before, after),- label: options.historyLabel ?? 'Replace layer with workflow result',- redo: () => applySnapshot(after, afterPixels, { discardPersistence: true, persist: false }),- replayFailureAtomic: true,- undo: () =>- applySnapshot(before, beforePixels, {- discardPersistence: false,- persist: o.needsPixelPersistence(before),- }),- });- return { layerId: liveLayer.id, status: 'committed' };- }- const layerId = o.ctx.createLayerId();- const selectedLayerId = document.selectedLayerId;- const buildControlCopy = (): CanvasLayerContract => {- const mainBase = o.getMainModelBase();- return {- ...createControlLayer(- options.copyLayerName ?? nextControlLayerName(getDocumentLeaves(document).map((layer) => layer.name)),- layerId,- mainBase,- o.getDefaultControlModel(mainBase)- ),- source,- transform: identityTransform,+ const layerId = o.ctx.createLayerId();+ const selectedLayerId = document.selectedLayerId;+ const buildControlCopy = (): CanvasLayerContract => {+ const mainBase = o.getMainModelBase();+ return {+ ...createControlLayer(+ options.copyLayerName ?? nextControlLayerName(getDocumentLeaves(document).map((layer) => layer.name)),+ layerId,+ mainBase,+ o.getDefaultControlModel(mainBase)+ ),+ source,+ transform: identityTransform,+ };};- };- const copy: CanvasLayerContract =- options.target === 'copy-control'- ? buildControlCopy()- : {- blendMode: 'normal',- id: layerId,- isEnabled: true,- isLocked: false,- name: options.copyLayerName ?? `${liveLayer.name} workflow result`,- opacity: 1,- source,- transform: identityTransform,- type: 'raster',- };- const anchor = o.ctx.captureInsertionAnchor(copy.type, liveLayer.id);- const publishCopy = (prepared: PreparedLayerCacheReplacement): void => {- o.ctx.dispatchPrepared(- { anchor, layer: copy, type: 'addCanvasLayer' },- () => getDocumentLayer(o.ctx.getReducerDocument(), copy.id) === copy,- () => getDocumentLayer(o.ctx.getDocument(), copy.id) === copy- );- o.ctx.installPrepared(prepared, false);- };- const applyCopy = (): void => publishCopy(o.ctx.preparePixels(layerId, rect, decoded.surface));- const prepared = o.ctx.preparePixels(layerId, rect, decoded.surface);- if (options.signal?.aborted) {- return { status: 'aborted' };- }- const finalCheck = validate();- if ('result' in finalCheck) {- return finalCheck.result;- }- o.ctx.endBurst();- publishCopy(prepared);- o.ctx.history.push({- bytes: rect.width * rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(copy),- label:+ const copy: CanvasLayerContract =+ options.target === 'copy-control'+ ? buildControlCopy()+ : {+ blendMode: 'normal',+ id: layerId,+ isEnabled: true,+ isLocked: false,+ name: options.copyLayerName ?? `${liveLayer.name} workflow result`,+ opacity: 1,+ source,+ transform: identityTransform,+ type: 'raster',+ };+ const anchor = o.ctx.captureInsertionAnchor(copy.type, liveLayer.id);+ const added = (prepared: PreparedLayerCacheReplacement | null) =>+ addLayerStep(o.ctx, copy, anchor, prepared, { persist: false, previousSelectedLayerId: selectedLayerId });+ const prepared = o.ctx.preparePixels(layerId, rect, decoded.surface);+ const interrupted = this.interrupted(options, validate);+ if (interrupted) {+ return interrupted;+ }+ const result = txn.publish(options.target === 'copy-control'? 'Copy workflow result to control layer': 'Copy workflow result to raster layer',- redo: applyCopy,- replayFailureAtomic: true,- undo: () => {- o.ctx.dispatchPrepared(- { id: selectedLayerId, type: 'setCanvasSelectedLayer' },- () => o.ctx.getReducerDocument()?.selectedLayerId === selectedLayerId,- () => o.ctx.getDocument()?.selectedLayerId === selectedLayerId- );- o.ctx.dispatchPrepared(- { ids: [layerId], type: 'removeCanvasLayers' },- () => isNodeAbsent(o.ctx.getReducerDocument(), layerId),- () => isNodeAbsent(o.ctx.getDocument(), layerId)- );- },- });- return { layerId, status: 'committed' };+ added(prepared),+ {+ bytes: pixelBytes(rect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(copy),+ redo: () => replayWithPixels(o.ctx, layerId, afterPixels, added),+ undo: () => o.ctx.applyStep(removeLayerStep(layerId, selectedLayerId)),+ }+ );+ return result.status === 'committed' ? { layerId, status: 'committed' } : { status: publishRefusal(result) };+ } finally {+ txn.end();+ }} catch (error) {if (options.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {return { status: 'aborted' };@@ -238,4 +228,16 @@ export class GeneratedResultController {}dispose(): void {}++ /** Preparation may run long enough for the caller to abort or the source to change; check both last. */+ private interrupted(+ options: CommitGeneratedImageOptions,+ validate: () => { result: CommitGeneratedImageResult } | object+ ): CommitGeneratedImageResult | null {+ if (options.signal?.aborted) {+ return { status: 'aborted' };+ }+ const checked = validate();+ return 'result' in checked ? checked.result : null;+ }}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.tsindex 367ebe07d2..c5c1dfa458 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.test.ts@@ -1,25 +1,28 @@+import type { HistoryEntry } from '@workbench/canvas-engine/history/history';+import { NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';import { HistoryController } from './historyController';+const entry = (label: string, bytes: number, overrides: Partial<HistoryEntry> = {}): HistoryEntry => ({+ bytes,+ heldAssetRefs: NO_HELD_ASSET_REFS,+ label,+ redo: () => undefined,+ undo: () => undefined,+ ...overrides,+});++const record = (controller: HistoryController, recorded: HistoryEntry): void => {+ controller.history.admit(recorded.bytes)!.publish(recorded);+};+describe('HistoryController', () => {it('owns history and trims it to the inactive byte budget', () => {const controller = new HistoryController({ activeByteBudget: 1_000, inactiveByteBudget: 100 });- controller.history.push({- bytes: 60,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'old',- redo: () => undefined,- undo: () => undefined,- });- controller.history.push({- bytes: 70,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'new',- redo: () => undefined,- undo: () => undefined,- });+ record(controller, entry('old', 60));+ record(controller, entry('new', 70));controller.cooldown();@@ -30,62 +33,50 @@ describe('HistoryController', () => {expect(controller.history.byteSize()).toBe(0);});- it('owns guarded commands and synchronizes undo/redo stores', () => {+ it('refuses replay while locked or mid-gesture and mirrors undo/redo availability', async () => {let canEdit = true;let gestureActive = false;const canUndo = { set: vi.fn() };const canRedo = { set: vi.fn() };- const endBurst = vi.fn();const controller = new HistoryController({canEdit: () => canEdit,canRedoStore: canRedo,canUndoStore: canUndo,- endBurst,isGestureActive: () => gestureActive,});const undo = vi.fn();const redo = vi.fn();- controller.history.push({ bytes: 1, heldAssetRefs: NO_HELD_ASSET_REFS, label: 'edit', redo, undo });+ record(controller, entry('edit', 1, { redo, undo }));- controller.undo();+ await expect(controller.undo()).resolves.toEqual({ status: 'applied' });expect(undo).toHaveBeenCalledOnce();- expect(endBurst).toHaveBeenCalledOnce();expect(canUndo.set).toHaveBeenLastCalledWith(false);expect(canRedo.set).toHaveBeenLastCalledWith(true);gestureActive = true;- controller.redo();- expect(redo).not.toHaveBeenCalled();+ await expect(controller.redo()).resolves.toEqual({ status: 'refused' });gestureActive = false;canEdit = false;- controller.clear();- expect(controller.history.canRedo()).toBe(true);-- canEdit = true;- controller.clear();- expect(controller.history.canRedo()).toBe(false);- controller.dispose();+ await expect(controller.redo()).resolves.toEqual({ status: 'refused' });+ expect(redo).not.toHaveBeenCalled();});- it('isolates store subscriber failures while synchronizing both flags', () => {- const canUndo = {- set: vi.fn(() => {- throw new Error('observer');- }),- };- const canRedo = { set: vi.fn() };- const controller = new HistoryController({ canRedoStore: canRedo, canUndoStore: canUndo });-- expect(() =>- controller.history.push({- bytes: 1,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'edit',- redo: () => undefined,- undo: () => undefined,+ it('reports a failed replay and leaves the step where it was', async () => {+ const reportFailure = vi.fn();+ const controller = new HistoryController({ reportFailure });+ const failure = new Error('pixels unavailable');+ record(+ controller,+ entry('Brush stroke', 1, {+ undo: () => {+ throw failure;+ },})- ).not.toThrow();- expect(canRedo.set).toHaveBeenCalled();- controller.dispose();+ );++ await expect(controller.undo()).resolves.toMatchObject({ status: 'failed' });++ expect(reportFailure).toHaveBeenCalledWith('Brush stroke', failure);+ expect(controller.history.entries()).toEqual({ future: [], past: ['Brush stroke'] });});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.tsindex 3615e511cf..a64d68273b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/historyController.ts@@ -1,4 +1,9 @@-import { createHistory, HISTORY_BYTE_BUDGET, type History } from '@workbench/canvas-engine/history/history';+import {+ createHistory,+ HISTORY_BYTE_BUDGET,+ type History,+ type HistoryReplayResult,+} from '@workbench/canvas-engine/history/history';export const INACTIVE_HISTORY_BYTE_BUDGET = 64 * 1024 * 1024;@@ -7,26 +12,28 @@ export interface HistoryControllerOptions {readonly inactiveByteBudget?: number;readonly canEdit?: () => boolean;readonly isGestureActive?: () => boolean;- readonly endBurst?: () => void;readonly canUndoStore?: { set(value: boolean): void };readonly canRedoStore?: { set(value: boolean): void };+ /** Reports a step whose replay failed and therefore stayed where it was. */+ readonly reportFailure?: (label: string, error: unknown) => void;}+export type HistoryCommandResult = HistoryReplayResult | { status: 'refused' };++/** Owns engine history, its guarded replay commands and the undo/redo store mirrors. */export class HistoryController {readonly history: History;private readonly inactiveByteBudget: number;private readonly canEdit: () => boolean;private readonly isGestureActive: () => boolean;- private readonly endBurst: () => void;private readonly unsubscribe: () => void;private disposed = false;- constructor(options: HistoryControllerOptions = {}) {+ constructor(private readonly options: HistoryControllerOptions = {}) {this.inactiveByteBudget = options.inactiveByteBudget ?? INACTIVE_HISTORY_BYTE_BUDGET;this.history = createHistory({ byteBudget: options.activeByteBudget ?? HISTORY_BYTE_BUDGET });this.canEdit = options.canEdit ?? (() => true);this.isGestureActive = options.isGestureActive ?? (() => false);- this.endBurst = options.endBurst ?? (() => undefined);const syncStores = (): void => {try {options.canUndoStore?.set(this.history.canUndo());@@ -43,27 +50,18 @@ export class HistoryController {syncStores();}- undo(): void {- if (this.disposed || !this.canEdit() || this.isGestureActive()) {- return;- }- this.endBurst();- this.history.undo();+ undo(): Promise<HistoryCommandResult> {+ return this.replay('undo');}- redo(): void {- if (this.disposed || !this.canEdit() || this.isGestureActive()) {- return;- }- this.endBurst();- this.history.redo();+ redo(): Promise<HistoryCommandResult> {+ return this.replay('redo');}clear(): void {if (this.disposed || !this.canEdit()) {return;}- this.endBurst();this.history.clear();}@@ -81,4 +79,19 @@ export class HistoryController {this.unsubscribe();this.history.clear();}++ private async replay(direction: 'undo' | 'redo'): Promise<HistoryCommandResult> {+ if (this.disposed || !this.canEdit() || this.isGestureActive()) {+ return { status: 'refused' };+ }+ const result = await (direction === 'undo' ? this.history.undo() : this.history.redo());+ if (result.status === 'failed') {+ try {+ this.options.reportFailure?.(result.label, result.error);+ } catch {+ // Diagnostics cannot change the replay outcome.+ }+ }+ return result;+ }}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.tsindex 14ee4ce554..572da2c5eb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts@@ -1,8 +1,5 @@-import type { CanvasLayerPreviewMutation } from '@workbench/canvas-engine/capabilities';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';-import { createTestEditConcurrency } from '@workbench/canvas-engine/editConcurrency.testStub';import { describe, expect, it, vi } from 'vitest';import { LayerController } from './layerController';@@ -11,15 +8,10 @@ import { StructuralLayerController } from './structuralLayerController';describe('LayerController', () => {const mask = {applyImagePatch: vi.fn(),- canEdit: () => true,+ ctx: {} as never,deleteDerived: vi.fn(),discardPersisted: vi.fn(),- dispatch: vi.fn(),- endBurst: vi.fn(),- getDocument: () => null,- history: {} as never,isCacheReady: () => false,- isGestureActive: () => false,layers: {} as never,markDirty: vi.fn(),notifyPainted: vi.fn(),@@ -41,129 +33,62 @@ describe('LayerController', () => {};const structural = new StructuralLayerController({ctx: {+ applyStep: vi.fn(),+ begin: () => ({ status: 'not-ready' }),canEdit: () => true,- capturePermit: () => ({ epoch: 0 }),- projectId: 'p',dispatch: vi.fn(() => true),- dispatchPrepared: vi.fn(),getDocument: () => null,getEditRevision: () => 0,getReducerDocument: () => null,- history: { push: vi.fn() } as never,+ historyTop: () => null,isGestureActive: () => false,+ projectId: 'p',},});- const rasterize = {- backend: {} as never,- canEdit: () => true,- dispatch: vi.fn(),- endBurst: vi.fn(),- getDocument: () => null,- history: {} as never,- isGestureActive: () => false,- layers: {} as never,- markDirty: vi.fn(),- notifyPainted: vi.fn(),- rasterizeDeps: vi.fn(),- };+ // The layer operations are exercised by their own tests; here they only need to construct.+ const rasterize = { backend: {} as never, ctx: {} as never, rasterizeDeps: vi.fn() };const merge = {backend: {} as never,- canEdit: () => true,ctx: {} as never,exportBaked: vi.fn(),hasExportableContent: () => false,isCacheReady: () => true,layers: {} as never,- markDirty: vi.fn(),needsPixelPersistence: () => false,- notifyPainted: vi.fn(),publishSelectedLayerIds: vi.fn(),- reserve: vi.fn(),};const booleanMerge = {backend: {} as never,- concurrency: createTestEditConcurrency({ capturePermit: () => null }),- createLayerId: () => 'result',- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- dispatchPrepared: vi.fn(),- endBurst: vi.fn(),+ ctx: {} as never,exportBaked: vi.fn(),- getDocument: () => null,- getReducerDocument: () => null,- history: {} as never,- installPrepared: vi.fn(),isCacheReady: () => true,isGuardCurrent: () => true,- preparePixels: vi.fn(),};const extractMaskedArea = {backend: {} as never,- concurrency: createTestEditConcurrency({ capturePermit: () => null }),- createLayerId: () => 'result',- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),+ ctx: {} as never,derived: {} as never,diagnostics: {} as never,- dispatchPrepared: vi.fn(),- endBurst: vi.fn(),exportBaked: vi.fn(),getAdjustedSurface: vi.fn(),- getDocument: () => null,getMaskPattern: () => null,- getReducerDocument: () => null,hasExportableContent: () => false,- history: {} as never,- installPrepared: vi.fn(),isCacheReady: () => true,isGuardCurrent: () => true,layers: {} as never,- preparePixels: vi.fn(),rasterize: vi.fn(),};const crop = {backend: {} as never,captureCache: vi.fn(),- concurrency: createTestEditConcurrency({ capturePermit: () => null }),+ ctx: {} as never,discardPersisted: vi.fn(),- dispatchPrepared: vi.fn(),- endBurst: vi.fn(),exportBaked: vi.fn(),- getDocument: () => null,- getReducerDocument: () => null,- history: {} as never,- installPrepared: vi.fn(),isGuardCurrent: () => true,isSupportedSource: () => true,- preparePixels: vi.fn(),- };- const copy = {- concurrency: createTestEditConcurrency({ capturePermit: () => null }),- createLayerId: () => 'copy',- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- dispatchPrepared: vi.fn(),- endBurst: vi.fn(),- exportBaked: vi.fn(),- getDocument: () => null,- getReducerDocument: () => null,- history: {} as never,- installPrepared: vi.fn(),- isGuardCurrent: () => true,- preparePixels: vi.fn(),- };- const newRasterLayer = {- backend: {} as never,- concurrency: createTestEditConcurrency({ capturePermit: () => null }),- createLayerId: () => 'new',- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- dispatchPrepared: vi.fn(),- endBurst: vi.fn(),- getDocument: () => null,- getReducerDocument: () => null,- history: {} as never,- installPrepared: vi.fn(),- layers: {} as never,- preparePixels: vi.fn(),- selection: {} as never,};+ const copy = { backend: {} as never, ctx: {} as never, exportBaked: vi.fn(), isGuardCurrent: () => true };+ const newRasterLayer = { backend: {} as never, ctx: {} as never, layers: {} as never, selection: {} as never };it('exposes only declared layer and preview ports', async () => {const forward: CanvasProjectMutation = { id: 'layer', type: 'setCanvasSelectedLayer' };const inverse: CanvasProjectMutation = { id: null, type: 'setCanvasSelectedLayer' };@@ -183,7 +108,9 @@ describe('LayerController', () => {const controller = new LayerController(deps);expect(- controller.layers.applyStructuralPreview({ id: 'layer', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' })+ controller.layers+ .beginStructuralPreview()+ ?.apply({ id: 'layer', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' })).toBe(true);controller.layers.commitStructural('edit', forward, inverse);expect(controller.previews.drawLayerThumbnail('layer', {} as HTMLCanvasElement, 96)).toBe(false);@@ -208,7 +135,7 @@ describe('LayerController', () => {controller.dispose();controller.dispose();- expect(controller.layers.applyStructuralPreview({} as CanvasLayerPreviewMutation)).toBe(false);+ expect(controller.layers.beginStructuralPreview()).toBeNull();controller.layers.commitStructural('late', {} as CanvasProjectMutation, {} as CanvasProjectMutation);expect(controller.previews.drawLayerThumbnail('layer', {} as HTMLCanvasElement, 96)).toBe(false);});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.tsindex c1521d4ee1..5e0e319989 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts@@ -15,7 +15,7 @@ import { ThumbnailController, type ThumbnailControllerOptions } from './thumbnaiexport type LayerControllerDeps = Omit<CanvasLayerCapability,- | 'applyStructuralPreview'+ | 'beginStructuralPreview'| 'canCommitStructural'| 'commitPrepared'| 'commitStagedImage'@@ -63,7 +63,7 @@ export class LayerController {this.copy = new CopyLayerController(deps.copy);this.newRasterLayer = new NewRasterLayerController(deps.newRasterLayer);this.layers = {- applyStructuralPreview: (action) => (this.disposed ? false : this.structural.preview(action)),+ beginStructuralPreview: () => (this.disposed ? null : this.structural.beginPreview()),canCommitStructural: () => this.structural.canCommit(),commitGeneratedImageResult: (options) =>this.disposed ? Promise.resolve({ status: 'aborted' }) : deps.commitGeneratedImageResult(options),@@ -71,7 +71,7 @@ export class LayerController {this.disposed ? { status: 'not-ready' } : this.structural.commitPrepared(label, edit, options),commitStructural: (label, forward, inverse, options) =>this.disposed ? { status: 'not-ready' } : this.structural.commit(label, forward, inverse, options),- invertMask: (layerId) => (this.disposed ? false : this.mask.invert(layerId)),+ invertMask: (layerId) => (this.disposed ? { status: 'not-ready' } : this.mask.invert(layerId)),};this.previews = {drawLayerThumbnail: (layerId, target, maxSize) =>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.tsindex cb9bd3cb48..06ea58fe0b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts@@ -1,10 +1,6 @@import type { DuplicateLayersResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { RasterMemoryReservationResult } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';-import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';@@ -22,9 +18,13 @@ import {import { cloneSubtree, collectSubtreeLeaves } from '@workbench/canvas-engine/document/documentTree';import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';-export type CapturedLayerCache = { pixels: RasterSurface; rect: Rect } | null | 'not-ready';+import type { CanvasMutationContext, EditStep } from './mutationContext';++import { pixelBytes, publishRefusal } from './layerResultSteps';++export type CapturedLayerCache = { pixels: RasterSurface; rect: Rect } | null | 'not-ready' | 'over-budget';export type DuplicateLayerRasterPlan =| {@@ -43,40 +43,56 @@ type DuplicateRasterPreparationResult =| { readonly status: 'not-ready' | 'over-budget' };export interface LayerMutationControllerOptions {- readonly concurrency: CanvasEditConcurrency;- readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => CapturedLayerCache;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;- readonly captureRestoreAnchor: (nodeId: string) => CanvasNodeInsertionAnchor | null;- readonly createLayerId: () => string;+ readonly ctx: Pick<+ CanvasMutationContext,+ | 'applyStep'+ | 'begin'+ | 'canEdit'+ | 'captureInsertionAnchor'+ | 'capturePermit'+ | 'captureRestoreAnchor'+ | 'createLayerId'+ | 'getDocument'+ | 'getEditRevision'+ | 'installPrepared'+ | 'isGestureActive'+ | 'isPermitCurrent'+ | 'preparePixels'+ | 'reserveRaster'+ >;+ /** Copies a layer's live cache; `admit` accounts its bytes first and refuses the copy as `over-budget`. */+ readonly captureCache: (+ layer: CanvasLayerContract,+ document: CanvasDocumentContractV3,+ admit?: (rect: Rect) => boolean+ ) => CapturedLayerCache;readonly discardPersisted: (layerId: string) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- reducerAccepted: () => boolean,- mirrorAccepted: () => boolean- ) => void;- readonly endBurst: () => void;readonly getDuplicateRasterPlan: (layer: CanvasLayerContract,document: CanvasDocumentContractV3) => DuplicateLayerRasterPlan;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly getEditRevision: () => number;- readonly getReducerDocument: () => CanvasDocumentContractV3 | null;readonly getSelectedLayerIds: (document: CanvasDocumentContractV3) => readonly string[];- readonly history: History;readonly hasPendingPixelWork: (layerId: string) => boolean;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;readonly needsPixelPersistence: (layer: CanvasLayerContract) => boolean;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly publishSelectedLayerIds: (primaryId: string | null, selectedIds: readonly string[]) => void;readonly prepareDuplicateRasterSource: (layerId: string) => Promise<DuplicateRasterPreparationResult>;readonly pinDuplicateRasterSources: (layerIds: readonly string[]) => { release(): void };- readonly reserve: (bytes: number) => RasterMemoryReservationResult;readonly scheduleDuplicateRasterization: (layerIds: readonly string[]) => void;readonly sameContract: (document: CanvasDocumentContractV3 | null, layer: CanvasLayerContract) => boolean;readonly trackDetached: (bytes: number) => { release(): void };}+type StackMutation = Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>;++/** A stack edit verified by `accepted`, rolled back by `rollback` until `restored` holds. */+const stackStep = (+ mutation: StackMutation,+ accepted: (document: CanvasDocumentContractV3 | null) => boolean,+ rollback: StackMutation,+ restored: (document: CanvasDocumentContractV3 | null) => boolean,+ effects: Pick<EditStep, 'install' | 'notify'> = {}+): EditStep => ({ ...effects, accepted, mutation, rollback: { mutation: rollback, restored } });+/** The outermost requested nodes in document order, or `null` when any id is absent or none is given. */const duplicateRoots = (document: CanvasDocumentContractV3, ids: readonly string[]): CanvasNodeEntry[] | null => {const index = getDocumentIndex(document);@@ -87,19 +103,19 @@ const duplicateRoots = (document: CanvasDocumentContractV3, ids: readonly stringreturn outermostNodes(index, unique);};-/** Owns failure-atomic copy and cross-type conversion mutations. */+/** Owns admitted, failure-atomic copy and cross-type conversion edits. */export class LayerMutationController {private duplicateInFlight = false;constructor(private readonly options: LayerMutationControllerOptions) {}async duplicate(layerIds: readonly string[]): Promise<DuplicateLayersResult> {- const o = this.options;- const permit = o.concurrency.capturePermit();- if (this.duplicateInFlight || !permit || !o.concurrency.canEdit() || o.concurrency.isGestureActive()) {+ const { ctx, ...o } = this.options;+ const permit = ctx.capturePermit();+ if (this.duplicateInFlight || !permit || ctx.isGestureActive()) {return { status: 'busy' };}- const document = o.getDocument();+ const document = ctx.getDocument();if (!document) {return { status: 'nothing' };}@@ -129,7 +145,7 @@ export class LayerMutationController {return { status: 'stale' };}}- if (!o.concurrency.isPermitCurrent(permit) || o.concurrency.isGestureActive() || o.getDocument() !== document) {+ if (!ctx.isPermitCurrent(permit) || ctx.isGestureActive() || ctx.getDocument() !== document) {return { status: 'stale' };}return this.commitDuplicate(layerIds);@@ -140,12 +156,8 @@ export class LayerMutationController {}private commitDuplicate(layerIds: readonly string[]): DuplicateLayersResult {- const o = this.options;- if (!o.concurrency.canEdit() || o.concurrency.isGestureActive()) {- return { status: 'busy' };- }- o.endBurst();- const document = o.getDocument();+ const { ctx, ...o } = this.options;+ const document = ctx.getDocument();if (!document) {return { status: 'nothing' };}@@ -168,27 +180,27 @@ export class LayerMutationController {reserveBytes += plan.initialReserveBytes;}}- const historyBytes = retainedBytes + sources.length * 256;- if (!o.history.canRetain(historyBytes)) {- return { status: 'over-budget' };- }- // Immutable durable sources rebuild caches on redo, needing one insertion copy. Unpersisted paint/mask pixels- // need separate history and live copies; both remain within the raster reservation.- const reservation = o.reserve(reserveBytes);- if (reservation.status === 'over-budget') {- return { status: 'over-budget' };+ const historyBytes = retainedBytes + sources.length * HISTORY_ENTRY_OVERHEAD_BYTES;+ const txn = ctx.begin({ historyBytes });+ if (!('publish' in txn)) {+ return { status: txn.status === 'gesture-active' ? 'busy' : txn.status };}try {+ // Immutable durable sources rebuild caches on redo, needing one insertion copy. Unpersisted paint/mask+ // pixels need separate history and live copies; both remain within the raster reservation.+ if (!txn.reserveRaster(reserveBytes)) {+ return { status: 'over-budget' };+ }const captures = sources.map((source, index) =>plans[index]?.type === 'capture' ? o.captureCache(source, document) : null);- if (captures.some((capture) => capture === 'not-ready')) {+ if (captures.some((capture) => capture === 'not-ready' || capture === 'over-budget')) {return { status: 'not-ready' };}const existingIds = new Set(getDocumentIndex(document).byId.keys());const idMap = new Map<string, string>();const clones = roots.map((entry) => {- const { node } = cloneSubtree(entry.node, o.createLayerId, idMap);+ const { node } = cloneSubtree(entry.node, ctx.createLayerId, idMap);return { ...node, name: `${entry.node.name} copy` };});const cloneLeaves = new Map(@@ -214,7 +226,7 @@ export class LayerMutationController {return { status: 'stale' };}const insertions = roots.map((entry, index) => ({- anchor: o.captureInsertionAnchor(entry.stack, entry.node.id),+ anchor: ctx.captureInsertionAnchor(entry.stack, entry.node.id),nodes: [clones[index]!],}));const expectedStacks = insertions.reduce(@@ -230,29 +242,34 @@ export class LayerMutationController {candidate?.selectedLayerId === selectedLayerId && haveSameStructure(candidate.stacks, expectedStacks);const hasOriginals = (candidate: CanvasDocumentContractV3 | null): boolean =>candidate?.selectedLayerId === previousSelectedLayerId && haveSameStructure(candidate.stacks, document.stacks);- const applyPrepared = (+ const addDuplicates: StackMutation = {+ add: insertions,+ enabledUpdates: [],+ selectedLayerId,+ type: 'applyCanvasLayerStackMutation',+ };+ const removeDuplicates: StackMutation = {+ enabledUpdates: [],+ removeIds: duplicateIds,+ selectedLayerId: previousSelectedLayerId,+ type: 'applyCanvasLayerStackMutation',+ };+ const added = (prepared: readonly { duplicate: CanvasLayerContract; replacement: PreparedLayerCacheReplacement }[]- ): void => {- o.dispatchPrepared(- {- add: insertions,- enabledUpdates: [],- selectedLayerId,- type: 'applyCanvasLayerStackMutation',+ ): EditStep =>+ stackStep(addDuplicates, hasDuplicates, removeDuplicates, hasOriginals, {+ install: () => {+ for (const { duplicate, replacement } of prepared) {+ ctx.installPrepared(replacement, o.needsPixelPersistence(duplicate));+ }},- () => hasDuplicates(o.getReducerDocument()),- () => hasDuplicates(o.getDocument())- );- prepared.forEach(({ duplicate, replacement }) => {- o.installPrepared(replacement, o.needsPixelPersistence(duplicate));+ notify: () => o.publishSelectedLayerIds(selectedLayerId, duplicateIds),});- o.publishSelectedLayerIds(selectedLayerId, duplicateIds);- };const retainedCaptures = captures.map((capture, index) =>plans[index]?.type === 'capture' && plans[index].retainForHistory ? capture : null);const initialPrepared = captures.flatMap((capture, index) => {- if (!capture || capture === 'not-ready') {+ if (!capture || typeof capture === 'string') {return [];}const duplicate = duplicates[index]!;@@ -262,25 +279,13 @@ export class LayerMutationController {duplicate,replacement:plan.type === 'capture' && plan.retainForHistory- ? o.preparePixels(duplicate.id, capture.rect, capture.pixels)+ ? ctx.preparePixels(duplicate.id, capture.rect, capture.pixels): { layerId: duplicate.id, rect: capture.rect, surface: capture.pixels },},];});- applyPrepared(initialPrepared);- initialPrepared.length = 0;- captures.forEach((_capture, index) => {- const plan = plans[index];- if (plan?.type !== 'capture' || !plan.retainForHistory) {- captures[index] = null;- }- });- const detachedLease = retainedBytes > 0 ? o.trackDetached(retainedBytes) : null;+ let detachedLease: { release(): void } | null = null;const redo = (): void => {- const current = o.getDocument();- if (!current) {- throw new Error('Canvas document is not ready to restore duplicated layers');- }const replayPlans = sources.map((_source, index) => {const originalPlan = plans[index]!;if (originalPlan.type === 'capture' && originalPlan.retainForHistory) {@@ -292,8 +297,8 @@ export class LayerMutationController {(total, plan) => total + (plan.type === 'capture' ? plan.replayReserveBytes : 0),0);- const replayReservation = o.reserve(replayBytes);- if (replayReservation.status === 'over-budget') {+ const replayReservation = ctx.reserveRaster(replayBytes);+ if (!replayReservation) {throw new Error('Not enough raster memory to restore duplicated layers');}try {@@ -303,123 +308,115 @@ export class LayerMutationController {}const duplicate = duplicates[index]!;const retained = retainedCaptures[index];- if (!retained || retained === 'not-ready') {+ if (!retained || typeof retained === 'string') {throw new Error('Layer pixels are not ready to restore duplicated layers');}- return [- {- duplicate,- replacement: o.preparePixels(duplicate.id, retained.rect, retained.pixels),- },- ];+ return [{ duplicate, replacement: ctx.preparePixels(duplicate.id, retained.rect, retained.pixels) }];});- applyPrepared(prepared);- o.scheduleDuplicateRasterization(- replayPlans.flatMap((plan, index) =>- plan.type === 'reference' && plans[index]?.type === 'capture' ? [duplicates[index]!.id] : []- )- );+ ctx.applyStep(added(prepared));} finally {- replayReservation.lease.release();+ replayReservation.release();}+ o.scheduleDuplicateRasterization(+ replayPlans.flatMap((plan, index) =>+ plan.type === 'reference' && plans[index]?.type === 'capture' ? [duplicates[index]!.id] : []+ )+ );};- o.history.push({- bytes: historyBytes,- heldAssetRefs: collectHistoryMediaRefs(duplicates),- dispose: () => detachedLease?.release(),- label: duplicates.length === 1 ? 'Duplicate layer' : 'Duplicate layers',- redo,- replayFailureAtomic: true,- undo: () => {- o.dispatchPrepared(- {- enabledUpdates: [],- removeIds: duplicateIds,- selectedLayerId: previousSelectedLayerId,- type: 'applyCanvasLayerStackMutation',- },- () => hasOriginals(o.getReducerDocument()),- () => hasOriginals(o.getDocument())- );- o.publishSelectedLayerIds(previousSelectedLayerId, previousSelectedIds);- },- });+ const result = txn.publish(+ duplicates.length === 1 ? 'Duplicate layer' : 'Duplicate layers',+ added(initialPrepared),+ {+ bytes: historyBytes,+ dispose: () => detachedLease?.release(),+ heldAssetRefs: collectHistoryMediaRefs(duplicates),+ redo,+ undo: () =>+ ctx.applyStep(+ stackStep(removeDuplicates, hasOriginals, addDuplicates, hasDuplicates, {+ notify: () => o.publishSelectedLayerIds(previousSelectedLayerId, previousSelectedIds),+ })+ ),+ }+ );+ if (result.status !== 'committed') {+ return { status: publishRefusal(result) };+ }+ if (retainedBytes > 0) {+ detachedLease = o.trackDetached(retainedBytes);+ }return { duplicateIds, selectedLayerId, status: 'duplicated' };} finally {- reservation.lease.release();+ txn.end();}}copy(label: string, sourceLayerId: string, layer: CanvasLayerContract, anchor: CanvasNodeInsertionAnchor): boolean {- const o = this.options;- if (!o.concurrency.canEdit() || o.concurrency.isGestureActive()) {- return false;- }- o.endBurst();- const document = o.getDocument();+ const { ctx, ...o } = this.options;+ const document = ctx.getDocument();const source = getDocumentLayer(document, sourceLayerId);if (!document ||!source ||- anchor.capturedEditRevision !== o.getEditRevision() ||+ anchor.capturedEditRevision !== ctx.getEditRevision() ||hasDocumentNode(document, layer.id)) {return false;}- const captured = o.captureCache(source, document);- if (captured === 'not-ready') {+ const txn = ctx.begin({ historyBytes: HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {return false;}- const selectedLayerId = document.selectedLayerId;- const apply = (): void => {- const prepared = captured ? o.preparePixels(layer.id, captured.rect, captured.pixels) : null;- o.dispatchPrepared(- {- add: [{ anchor, nodes: [layer] }],- enabledUpdates: [],- selectedLayerId: layer.id,- type: 'applyCanvasLayerStackMutation',- },- () =>- o.getReducerDocument()?.selectedLayerId === layer.id &&- getDocumentLayer(o.getReducerDocument(), layer.id) === layer,- () => o.getDocument()?.selectedLayerId === layer.id && getDocumentLayer(o.getDocument(), layer.id) === layer+ try {+ const captured = o.captureCache(+ source,+ document,+ (rect) => txn.growHistory(pixelBytes(rect)) && txn.reserveRaster(pixelBytes(rect)));- if (prepared) {- o.installPrepared(prepared, o.needsPixelPersistence(layer));+ if (captured === 'not-ready' || captured === 'over-budget') {+ return false;}- };- apply();- o.history.push({- bytes: captured ? captured.rect.width * captured.rect.height * 4 + 256 : 256,- heldAssetRefs: collectHistoryMediaRefs(layer),- label,- redo: apply,- replayFailureAtomic: true,- undo: () =>- o.dispatchPrepared(- { enabledUpdates: [], removeIds: [layer.id], selectedLayerId, type: 'applyCanvasLayerStackMutation' },- () =>- o.getReducerDocument()?.selectedLayerId === selectedLayerId &&- isNodeAbsent(o.getReducerDocument(), layer.id),- () => o.getDocument()?.selectedLayerId === selectedLayerId && isNodeAbsent(o.getDocument(), layer.id)- ),- });- return true;+ const selectedLayerId = document.selectedLayerId;+ const hasCopy = (candidate: CanvasDocumentContractV3 | null): boolean =>+ candidate?.selectedLayerId === layer.id && getDocumentLayer(candidate, layer.id) === layer;+ const hasNoCopy = (candidate: CanvasDocumentContractV3 | null): boolean =>+ candidate?.selectedLayerId === selectedLayerId && isNodeAbsent(candidate, layer.id);+ const addCopy: StackMutation = {+ add: [{ anchor, nodes: [layer] }],+ enabledUpdates: [],+ selectedLayerId: layer.id,+ type: 'applyCanvasLayerStackMutation',+ };+ const removeCopy: StackMutation = {+ enabledUpdates: [],+ removeIds: [layer.id],+ selectedLayerId,+ type: 'applyCanvasLayerStackMutation',+ };+ const added = (prepared: PreparedLayerCacheReplacement | null): EditStep =>+ stackStep(addCopy, hasCopy, removeCopy, hasNoCopy, {+ install: prepared ? () => ctx.installPrepared(prepared, o.needsPixelPersistence(layer)) : undefined,+ });+ const prepare = (): PreparedLayerCacheReplacement | null =>+ captured ? ctx.preparePixels(layer.id, captured.rect, captured.pixels) : null;+ const result = txn.publish(label, added(prepare()), {+ bytes: (captured ? pixelBytes(captured.rect) : 0) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(layer),+ redo: () => replayPrepared(ctx, captured, () => ctx.applyStep(added(prepare()))),+ undo: () => ctx.applyStep(stackStep(removeCopy, hasNoCopy, addCopy, hasCopy)),+ });+ return result.status === 'committed';+ } finally {+ txn.end();+ }}convert(label: string, expected: CanvasLayerContract, after: CanvasLayerContract): boolean {- const o = this.options;- if (- !o.concurrency.canEdit() ||- o.concurrency.isGestureActive() ||- expected.id !== after.id ||- expected.type === after.type- ) {+ const { ctx, ...o } = this.options;+ if (expected.id !== after.id || expected.type === after.type) {return false;}- o.endBurst();- const document = o.getDocument();+ const document = ctx.getDocument();const current = getDocumentLayer(document, expected.id);if (!document ||@@ -430,40 +427,76 @@ export class LayerMutationController {) {return false;}- const captured = o.captureCache(current, document);- if (captured === 'not-ready') {+ const txn = ctx.begin({ historyBytes: HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {return false;}- // A conversion changes stacks, so undo carries the leaf back to its captured place.- const restoreAnchor = o.captureRestoreAnchor(current.id) ?? undefined;- const apply = (layer: CanvasLayerContract, anchor?: CanvasNodeInsertionAnchor): void => {- const prepared = captured ? o.preparePixels(layer.id, captured.rect, captured.pixels) : null;- o.dispatchPrepared(- { anchor, id: layer.id, layer, targetType: layer.type, type: 'convertCanvasLayer' },- () => o.sameContract(o.getReducerDocument(), layer),- () => o.sameContract(o.getDocument(), layer)+ try {+ const captured = o.captureCache(+ current,+ document,+ (rect) => txn.growHistory(pixelBytes(rect)) && txn.reserveRaster(pixelBytes(rect)));- try {- o.discardPersisted(layer.id);- } catch {- /* Ancillary after reducer acceptance. */- }- if (prepared) {- o.installPrepared(prepared, o.needsPixelPersistence(layer));+ if (captured === 'not-ready' || captured === 'over-budget') {+ return false;}- };- const before = structuredClone(current);- apply(after);- o.history.push({- bytes: captured ? captured.rect.width * captured.rect.height * 4 + 256 : 256,- heldAssetRefs: collectHistoryMediaRefs(before, after),- label,- redo: () => apply(after),- replayFailureAtomic: true,- undo: () => apply(before, restoreAnchor),- });- return true;+ // A conversion changes stacks, so undo carries the leaf back to its captured place.+ const restoreAnchor = ctx.captureRestoreAnchor(current.id) ?? undefined;+ const before = structuredClone(current);+ const converted = (+ layer: CanvasLayerContract,+ restore: CanvasLayerContract,+ anchor?: CanvasNodeInsertionAnchor+ ): EditStep => {+ const prepared = captured ? ctx.preparePixels(layer.id, captured.rect, captured.pixels) : null;+ return {+ accepted: (candidate) => o.sameContract(candidate, layer),+ install: () => {+ try {+ o.discardPersisted(layer.id);+ } catch {+ /* Ancillary after reducer acceptance. */+ }+ if (prepared) {+ ctx.installPrepared(prepared, o.needsPixelPersistence(layer));+ }+ },+ mutation: { anchor, id: layer.id, layer, targetType: layer.type, type: 'convertCanvasLayer' },+ rollback: {+ mutation: { id: layer.id, layer: restore, targetType: restore.type, type: 'convertCanvasLayer' },+ restored: (candidate) => o.sameContract(candidate, restore),+ },+ };+ };+ const result = txn.publish(label, converted(after, current), {+ bytes: (captured ? pixelBytes(captured.rect) : 0) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(before, after),+ redo: () => replayPrepared(ctx, captured, () => ctx.applyStep(converted(after, before))),+ undo: () => replayPrepared(ctx, captured, () => ctx.applyStep(converted(before, after, restoreAnchor))),+ });+ return result.status === 'committed';+ } finally {+ txn.end();+ }}dispose(): void {}}++/** Runs a replay whose step prepares a copy of `captured`, reserving that copy first. */+const replayPrepared = (+ ctx: Pick<CanvasMutationContext, 'reserveRaster'>,+ captured: CapturedLayerCache,+ replay: () => void+): void => {+ const bytes = captured && typeof captured !== 'string' ? pixelBytes(captured.rect) : 0;+ const reservation = bytes > 0 ? ctx.reserveRaster(bytes) : null;+ if (bytes > 0 && !reservation) {+ throw new Error('Not enough raster memory to restore this step.');+ }+ try {+ replay();+ } finally {+ reservation?.release();+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerOperationHarness.testing.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerOperationHarness.testing.tsnew file mode 100644index 0000000000..06dd280c58--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerOperationHarness.testing.ts@@ -0,0 +1,105 @@+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';++import { createHistory } from '@workbench/canvas-engine/history/history';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';++import { createCanvasMutationContext } from './mutationContext';++export interface LayerOperationHarnessOptions {+ /** History byte budget; an edit whose entry can never fit is refused. */+ readonly historyBytes?: number;+ readonly gestureActive?: boolean;+}++/**+ * Layer operations over the real reducer, mutation context, history and layer caches. The mirror is the reducer+ * document; `rasterBytes` and `refuse` let a test starve memory or make the reducer reject a mutation.+ */+export const createLayerOperationHarness = (+ document: CanvasDocumentContractV3,+ options: LayerOperationHarnessOptions = {}+) => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const history = createHistory({ byteBudget: options.historyBytes });+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document,+ type: 'replaceCanvasDocument',+ });+ const listeners = new Set<() => void>();+ const dispatched: CanvasProjectMutation[] = [];+ const installed: PreparedLayerCacheReplacement[] = [];+ const state = {+ gestureActive: options.gestureActive ?? false,+ rasterBytes: Number.POSITIVE_INFINITY,+ refuse: (_mutation: CanvasProjectMutation): boolean => false,+ };+ let reserved = 0;+ let nextId = 0;+ const ctx = createCanvasMutationContext({+ commitEdit: () => undefined,+ createLayerId: () => `new-${(nextId += 1)}`,+ dispatch: (action) => {+ dispatched.push(action);+ if (!state.refuse(action)) {+ project = applyCanvasProjectMutation(project, action);+ for (const listener of listeners) {+ listener();+ }+ }+ return true;+ },+ editOwner: Symbol('harness'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => project.canvas.document,+ getReducerDocument: () => project.canvas.document,+ history,+ installPrepared: (prepared) => {+ installed.push(prepared);+ layers.installReplacement(prepared);+ },+ isGestureActive: () => state.gestureActive,+ isGuardCurrent: () => true,+ preparePixels: (layerId, rect, pixels) => layers.prepareReplacement(layerId, rect, pixels),+ projectId: project.id,+ refreshMirror: () => undefined,+ reserveRaster: (bytes) => {+ if (reserved + bytes > state.rasterBytes) {+ return { availableBytes: state.rasterBytes - reserved, requestedBytes: bytes, status: 'over-budget' };+ }+ reserved += bytes;+ let released = false;+ return {+ lease: {+ release: () => {+ if (!released) {+ released = true;+ reserved -= bytes;+ }+ },+ },+ status: 'ok',+ };+ },+ subscribeReducer: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ });+ return {+ backend,+ ctx,+ dispatched,+ document: () => project.canvas.document,+ history,+ installed,+ layers,+ reservedBytes: () => reserved,+ state,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerResultSteps.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerResultSteps.tsnew file mode 100644index 0000000000..4c63780da0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerResultSteps.ts@@ -0,0 +1,105 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';+import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Rect } from '@workbench/canvas-engine/types';++import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';++import type { CanvasMutationContext, EditPublishResult, EditStep } from './mutationContext';++export type LayerResultContext = Pick<+ CanvasMutationContext,+ 'applyStep' | 'installPrepared' | 'preparePixels' | 'reserveRaster'+>;++/** Layer-local pixels a result or its undo step installs. */+export interface LayerPixels {+ readonly pixels: RasterSurface;+ readonly rect: Rect;+}++export const pixelBytes = (rect: Rect): number => Math.max(0, rect.width) * Math.max(0, rect.height) * 4;++/** Swaps `contract` in for its layer and, once the document accepted it, installs the prepared pixels. */+export const replaceLayerStep = (+ ctx: LayerResultContext,+ contract: CanvasLayerContract,+ prepared: PreparedLayerCacheReplacement | null,+ options: { readonly persist: boolean; readonly restore: CanvasLayerContract; readonly notify?: () => void }+): EditStep => ({+ accepted: (document) => getDocumentLayer(document, contract.id) === contract,+ install: prepared ? () => ctx.installPrepared(prepared, options.persist) : undefined,+ mutation: { layer: contract, layerId: contract.id, type: 'replaceCanvasLayer' },+ notify: options.notify,+ rollback: {+ mutation: { layer: options.restore, layerId: contract.id, type: 'replaceCanvasLayer' },+ restored: (document) => getDocumentLayer(document, contract.id) === options.restore,+ },+});++/** Inserts `layer` (selecting it) and installs its prepared pixels; rolls back to the prior selection. */+export const addLayerStep = (+ ctx: LayerResultContext,+ layer: CanvasLayerContract,+ anchor: CanvasNodeInsertionAnchor,+ prepared: PreparedLayerCacheReplacement | null,+ options: { readonly persist: boolean; readonly previousSelectedLayerId: string | null }+): EditStep => ({+ accepted: (document) => getDocumentLayer(document, layer.id) === layer,+ install: prepared ? () => ctx.installPrepared(prepared, options.persist) : undefined,+ mutation: { anchor, layer, type: 'addCanvasLayer' },+ rollback: {+ mutation: removeLayerMutation(layer.id, options.previousSelectedLayerId),+ restored: (document) => isNodeAbsent(document, layer.id),+ },+});++const removeLayerMutation = (layerId: string, selectedLayerId: string | null) =>+ ({ enabledUpdates: [], removeIds: [layerId], selectedLayerId, type: 'applyCanvasLayerStackMutation' }) as const;++/** Removes a layer an edit added and restores the selection it replaced. */+export const removeLayerStep = (layerId: string, selectedLayerId: string | null): EditStep => ({+ accepted: (document) => isNodeAbsent(document, layerId) && document?.selectedLayerId === selectedLayerId,+ mutation: removeLayerMutation(layerId, selectedLayerId),+});++/**+ * Replays a step that installs `snapshot`, reserving the prepared copy first. Throws (leaving the entry in place)+ * when the copy does not fit or the step does not land.+ */+export const replayWithPixels = (+ ctx: LayerResultContext,+ layerId: string,+ snapshot: LayerPixels | null,+ step: (prepared: PreparedLayerCacheReplacement | null) => EditStep+): void => {+ if (!snapshot) {+ ctx.applyStep(step(null));+ return;+ }+ const reservation = ctx.reserveRaster(pixelBytes(snapshot.rect));+ if (!reservation) {+ throw new Error('Not enough raster memory to restore this step.');+ }+ try {+ ctx.applyStep(step(ctx.preparePixels(layerId, snapshot.rect, snapshot.pixels)));+ } finally {+ reservation.release();+ }+};++/** The refusal a failed publication reports to its caller: a step that did not land is stale. */+export const publishRefusal = (+ result: Exclude<EditPublishResult, { status: 'committed' }>+): 'busy' | 'not-ready' | 'over-budget' | 'stale' => {+ switch (result.status) {+ case 'gesture-active':+ return 'busy';+ case 'dispatch-rejected':+ case 'postcondition-failed':+ return 'stale';+ default:+ return result.status;+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.test.tsnew file mode 100644index 0000000000..46ee54aa73--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.test.ts@@ -0,0 +1,170 @@+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { Project } from '@workbench/projectContracts';++import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { createHistory } from '@workbench/canvas-engine/history/history';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { describe, expect, it, vi } from 'vitest';++import { MaskLayerController } from './maskLayerController';+import { createCanvasMutationContext } from './mutationContext';++const PERSISTED = { height: 20, imageName: 'persisted-mask', width: 20 };+const CACHE_RECT = { height: 20, width: 20, x: 0, y: 0 };++/** A real reducer, history, transaction protocol and layer cache around one persisted inpaint mask. */+const createHarness = (options: { byteBudget?: number } = {}) => {+ const base = createInitialWorkbenchState().projects[0]!;+ const mask = layerContract('mask', 'inpaint_mask');+ if (mask.type !== 'inpaint_mask') {+ throw new Error('expected an inpaint mask fixture');+ }+ mask.mask = { ...mask.mask, bitmap: PERSISTED, offset: { x: 0, y: 0 } };+ let project: Project = applyCanvasProjectMutation(base, {+ document: documentFrom([mask]),+ type: 'replaceCanvasDocument',+ });+ let mirrorBroken = false;+ let mirrorDocument = project.canvas.document;+ let reserveFits = true;+ // Fault injection: edits lock while the operation prepares, so its publication is refused.+ let lockWhilePreparing = false;+ let locked = false;+ const dispatched: CanvasProjectMutation[] = [];+ const history = createHistory({ byteBudget: options.byteBudget });+ const layers = createLayerCacheStore(createTestStubRasterBackend());+ layers.getOrCreateRect('mask', CACHE_RECT).stale = false;+ layers.publishPixels('mask');+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch: (mutation) => {+ dispatched.push(mutation);+ const next = applyCanvasProjectMutation(project, mutation);+ const changed = next !== project;+ project = next;+ if (!mirrorBroken) {+ mirrorDocument = project.canvas.document;+ }+ return changed;+ },+ editOwner: Symbol('owner'),+ editingLocked: { get: () => locked, subscribe: () => () => undefined },+ getDocument: () => mirrorDocument,+ getReducerDocument: () => project.canvas.document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => false,+ isGuardCurrent: () => true,+ preparePixels: () => ({}) as never,+ projectId: base.id,+ refreshMirror: () => {+ if (mirrorBroken) {+ throw new Error('mirror broken');+ }+ mirrorDocument = project.canvas.document;+ },+ reserveRaster: () => {+ locked ||= lockWhilePreparing;+ return reserveFits+ ? { lease: { release: () => undefined }, status: 'ok' }+ : { availableBytes: 0, requestedBytes: 1, status: 'over-budget' };+ },+ subscribeReducer: () => () => undefined,+ });+ const restoreCache = vi.fn();+ const controller = new MaskLayerController({+ applyImagePatch: () => Promise.resolve(),+ ctx,+ deleteDerived: vi.fn(),+ discardPersisted: vi.fn(),+ isCacheReady: () => true,+ layers,+ markDirty: vi.fn(),+ notifyPainted: vi.fn(),+ restoreCache,+ });+ const maskBitmap = () => {+ const layer = getDocumentLayer(project.canvas.document, 'mask');+ return layer?.type === 'inpaint_mask' ? layer.mask.bitmap : undefined;+ };+ return {+ breakMirror: (broken: boolean) => {+ mirrorBroken = broken;+ },+ controller,+ dispatched,+ history,+ layers,+ maskBitmap,+ restoreCache,+ lockWhilePreparing: () => {+ lockWhilePreparing = true;+ },+ setReserveFits: (fits: boolean) => {+ reserveFits = fits;+ },+ };+};++describe('MaskLayerController', () => {+ it('refuses an invert whose grown extent does not fit before touching the cache or history', () => {+ const h = createHarness();+ h.setReserveFits(false);+ const before = h.layers.get('mask')!;++ expect(h.controller.invert('mask')).toEqual({ status: 'over-budget' });+ expect(h.layers.get('mask')!.rect).toEqual(CACHE_RECT);+ expect(h.layers.get('mask')!.version).toBe(before.version);+ expect(h.history.canUndo()).toBe(false);+ });++ it('returns the cache to its extent when an invert cannot be recorded', () => {+ const h = createHarness();+ h.lockWhilePreparing();++ expect(h.controller.invert('mask').status).not.toBe('committed');+ expect(h.layers.get('mask')!.rect).toEqual(CACHE_RECT);+ expect(h.history.canUndo()).toBe(false);+ });++ it('refuses a clear history could never retain before dispatching', () => {+ const h = createHarness({ byteBudget: 64 });++ expect(h.controller.clear('mask')).toEqual({ status: 'over-budget' });+ expect(h.dispatched).toEqual([]);+ expect(h.maskBitmap()).toEqual(PERSISTED);+ expect(h.layers.get('mask')!.rect).toEqual(CACHE_RECT);+ });++ it('rolls the mask back and keeps its pixels when the mirror cannot follow a clear', () => {+ const h = createHarness();+ h.breakMirror(true);++ expect(h.controller.clear('mask')).toEqual({ status: 'stale' });+ expect(h.maskBitmap()).toEqual(PERSISTED);+ expect(h.layers.get('mask')!.rect).toEqual(CACHE_RECT);+ expect(h.history.canUndo()).toBe(false);+ });++ it('restores the cleared pixels on undo, and keeps the step when their copy does not fit', async () => {+ const h = createHarness();+ expect(h.controller.clear('mask')).toEqual({ status: 'committed' });+ expect(h.maskBitmap()).toBeNull();+ expect(h.layers.get('mask')!.rect.width).toBe(0);++ h.setReserveFits(false);+ expect((await h.history.undo()).status).toBe('failed');+ expect(h.maskBitmap()).toBeNull();+ expect(h.history.canUndo()).toBe(true);++ h.setReserveFits(true);+ expect(await h.history.undo()).toEqual({ status: 'applied' });+ expect(h.maskBitmap()).toEqual(PERSISTED);+ expect(h.restoreCache).toHaveBeenCalledWith('mask', CACHE_RECT, expect.anything());+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.tsindex 941b4d05c4..d6a4cf2a23 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskLayerController.ts@@ -1,7 +1,6 @@+import type { MaskEditResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { Rect } from '@workbench/canvas-engine/types';@@ -9,99 +8,118 @@ import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/docuimport { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { getSourceContentRect, isMaskLayer } from '@workbench/canvas-engine/document/sources';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';import { invert as invertMatrix } from '@workbench/canvas-engine/math/mat2d';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';+import type { CanvasMutationContext, EditStep } from './mutationContext';++import { pixelBytes, publishRefusal } from './layerResultSteps';+export interface MaskLayerControllerOptions {+ readonly ctx: Pick<CanvasMutationContext, 'applyStep' | 'begin' | 'getDocument' | 'reserveRaster'>;readonly layers: LayerCacheStore;- readonly history: History;readonly applyImagePatch: ImagePatchApply;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly canEdit: () => boolean;- readonly isGestureActive: () => boolean;readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;- readonly endBurst: () => void;readonly discardPersisted: (layerId: string) => void;readonly markDirty: (layerId: string) => void;- readonly dispatch: (action: CanvasProjectMutation) => void;readonly deleteDerived: (layerId: string) => void;readonly notifyPainted: (layerId: string) => void;readonly restoreCache: (layerId: string, rect: Rect, pixels: ImageData) => void;}-/** Owns destructive mask pixel operations and their history/persistence lifecycle. */+type MaskLayer = Extract<CanvasLayerContract, { mask: unknown }>;++/** Owns destructive mask pixel operations as admitted, failure-atomic undo steps. */export class MaskLayerController {private disposed = false;constructor(private readonly deps: MaskLayerControllerOptions) {}- clear(layerId: string): boolean {- if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {- return false;+ clear(layerId: string): MaskEditResult {+ const { ctx } = this.deps;+ if (this.disposed) {+ return { status: 'not-ready' };}- const document = this.deps.getDocument();+ const document = ctx.getDocument();const layer = getDocumentLayer(document, layerId);- if (!document || !layer || !isMaskLayer(layer) || layer.isLocked) {- return false;+ if (!document || !layer) {+ return { status: 'missing' };+ }+ if (!isMaskLayer(layer)) {+ return { status: 'unsupported' };+ }+ if (layer.isLocked) {+ return { status: 'locked' };}const originalBitmap = layer.mask.bitmap;const originalOffset = layer.mask.offset ?? { x: 0, y: 0 };const entry = this.deps.isCacheReady(layer, document) ? this.deps.layers.get(layerId) : undefined;const rect = entry && !isEmpty(entry.rect) ? { ...entry.rect } : null;- const before = rect ? entry?.surface.ctx.getImageData(0, 0, rect.width, rect.height) : null;- if (!originalBitmap && (!before || !rect)) {- return false;+ if (!originalBitmap && !rect) {+ return { status: 'nothing' };}- this.deps.endBurst();- const dispatchMask = (bitmap: CanvasImageRef | null, offset: { x: number; y: number }): void => {- this.deps.dispatch({- config: { layerType: layer.type, mask: { bitmap, offset } },- id: layerId,- type: 'updateCanvasLayerConfig',+ const txn = ctx.begin({ historyBytes: (rect ? pixelBytes(rect) : 0) + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ return { status: txn.status === 'gesture-active' ? 'busy' : txn.status };+ }+ try {+ const before = rect && entry ? entry.surface.ctx.getImageData(0, 0, rect.width, rect.height) : null;+ const cleared = this.maskStep(layer, null, { x: 0, y: 0 }, originalBitmap, originalOffset, () => {+ this.deps.layers.delete(layerId);+ this.deps.deleteDerived(layerId);+ this.deps.layers.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 }).stale = false;+ this.deps.notifyPainted(layerId);});- };- const applyClear = (): void => {- this.deps.discardPersisted(layerId);- dispatchMask(null, { x: 0, y: 0 });- this.deps.layers.delete(layerId);- this.deps.deleteDerived(layerId);- const empty = this.deps.layers.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });- empty.stale = false;- this.deps.notifyPainted(layerId);- };- const applyRestore = (): void => {- this.deps.discardPersisted(layerId);- dispatchMask(originalBitmap, originalOffset);- if (before && rect) {- this.deps.restoreCache(layerId, rect, before);- }- };- applyClear();- this.deps.history.push({- bytes: (before?.data.byteLength ?? 0) + 256,- heldAssetRefs: collectHistoryMediaRefs(originalBitmap),- label: 'Clear mask',- redo: applyClear,- undo: applyRestore,- });- return true;+ const result = txn.publish('Clear mask', cleared, {+ bytes: (before?.data.byteLength ?? 0) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(originalBitmap),+ redo: () => ctx.applyStep(cleared),+ undo: () => {+ const reservation = rect ? ctx.reserveRaster(pixelBytes(rect)) : null;+ if (rect && !reservation) {+ throw new Error('Not enough raster memory to restore the mask.');+ }+ try {+ ctx.applyStep(+ this.maskStep(layer, originalBitmap, originalOffset, null, { x: 0, y: 0 }, () => {+ if (before && rect) {+ this.deps.restoreCache(layerId, rect, before);+ }+ })+ );+ } finally {+ reservation?.release();+ }+ },+ });+ return result.status === 'committed' ? { status: 'committed' } : { status: publishRefusal(result) };+ } finally {+ txn.end();+ }}- invert(layerId: string): boolean {- if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {- return false;+ invert(layerId: string): MaskEditResult {+ const { ctx } = this.deps;+ if (this.disposed) {+ return { status: 'not-ready' };}- const document = this.deps.getDocument();+ const document = ctx.getDocument();const leaf = lookupDocumentLeaf(document, layerId);const layer = leaf?.layer;- if (!document || !layer || !isMaskLayer(layer) || !isLeafEditable(leaf)) {- return false;+ if (!document || !layer) {+ return { status: 'missing' };+ }+ if (!isMaskLayer(layer)) {+ return { status: 'unsupported' };+ }+ if (!isLeafEditable(leaf)) {+ return { status: 'locked' };}if (!this.deps.isCacheReady(layer, document)) {- return false;+ return { status: 'not-ready' };}const content = getSourceContentRect(layer, document);const liveRect = this.deps.layers.get(layerId)?.rect;@@ -111,24 +129,38 @@ export class MaskLayerController {const bbox = inverse ? roundOut(transformBounds(inverse, document.bbox)) : document.bbox;const domain = roundOut(isEmpty(contentUnion) ? bbox : union(contentUnion, bbox));if (isEmpty(domain)) {- return false;+ return { status: 'nothing' };}- this.deps.endBurst();- const entry = this.deps.layers.growToRect(layerId, domain);- const readX = domain.x - entry.rect.x;- const readY = domain.y - entry.rect.y;- const before = entry.surface.ctx.getImageData(readX, readY, domain.width, domain.height);- const work = entry.surface.ctx.getImageData(readX, readY, domain.width, domain.height);- for (let index = 3; index < work.data.length; index += 4) {- work.data[index] = 255 - (work.data[index] ?? 0);+ const txn = ctx.begin({ historyBytes: pixelBytes(domain) * 2 + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ return { status: txn.status === 'gesture-active' ? 'busy' : txn.status };}- entry.surface.ctx.putImageData(work, readX, readY);- this.deps.notifyPainted(layerId);- this.deps.markDirty(layerId);- if (!this.deps.history.isApplying()) {- this.deps.history.push(+ try {+ if (!txn.reserveRaster(pixelBytes(domain))) {+ return { status: 'over-budget' };+ }+ const originalRect = this.deps.layers.peek(layerId)?.rect;+ const restoreExtent = originalRect ? { ...originalRect } : null;+ // Growing changes no visible pixel; a refused publication only has to return the cache to its extent.+ const entry = this.deps.layers.growToRect(layerId, domain);+ const readX = domain.x - entry.rect.x;+ const readY = domain.y - entry.rect.y;+ const before = entry.surface.ctx.getImageData(readX, readY, domain.width, domain.height);+ const after = entry.surface.ctx.getImageData(readX, readY, domain.width, domain.height);+ for (let index = 3; index < after.data.length; index += 4) {+ after.data[index] = 255 - (after.data[index] ?? 0);+ }+ const result = txn.publish(+ 'Invert mask',+ {+ install: () => entry.surface.ctx.putImageData(after, readX, readY),+ notify: () => {+ this.deps.notifyPainted(layerId);+ this.deps.markDirty(layerId);+ },+ },createImagePatchEntry({- after: work,+ after,apply: this.deps.applyImagePatch,before,label: 'Invert mask',@@ -136,11 +168,56 @@ export class MaskLayerController {rect: domain,}));+ if (result.status === 'committed') {+ return { status: 'committed' };+ }+ if (restoreExtent) {+ this.deps.layers.shrinkToRect(layerId, restoreExtent);+ } else {+ this.deps.layers.delete(layerId);+ }+ return { status: publishRefusal(result) };+ } finally {+ txn.end();}- return true;}dispose(): void {this.disposed = true;}++ /** Sets the mask's persisted bitmap; once accepted, drops pending uploads and installs the matching pixels. */+ private maskStep(+ layer: MaskLayer,+ bitmap: CanvasImageRef | null,+ offset: { x: number; y: number },+ restoreBitmap: CanvasImageRef | null,+ restoreOffset: { x: number; y: number },+ install: () => void+ ): EditStep {+ const configured = (expected: CanvasImageRef | null) => (document: CanvasDocumentContractV3 | null) => {+ const current = getDocumentLayer(document, layer.id);+ return !!current && isMaskLayer(current) && current.mask.bitmap === expected;+ };+ return {+ accepted: configured(bitmap),+ install: () => {+ this.deps.discardPersisted(layer.id);+ install();+ },+ mutation: {+ config: { layerType: layer.type, mask: { bitmap, offset } },+ id: layer.id,+ type: 'updateCanvasLayerConfig',+ },+ rollback: {+ mutation: {+ config: { layerType: layer.type, mask: { bitmap: restoreBitmap, offset: restoreOffset } },+ id: layer.id,+ type: 'updateCanvasLayerConfig',+ },+ restored: configured(restoreBitmap),+ },+ };+ }}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.tsindex 94dadff63f..2d251f0a14 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts@@ -1,16 +1,6 @@-import type {- CommitMaskImageResult,- CommitMaskImageResultOptions,- LayerExportGuard,-} from '@workbench/canvas-engine/capabilities';-import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';-import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';-import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { CommitMaskImageResult, CommitMaskImageResultOptions } from '@workbench/canvas-engine/capabilities';-import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import {createInpaintMaskFromImage,createRegionalGuidanceFromImage,@@ -19,7 +9,11 @@ import {nextRegionalGuidanceFillColor,nextRegionalGuidanceName,} from '@workbench/canvas-engine/document/layerFactories';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';++import type { CanvasMutationContext } from './mutationContext';++import { addLayerStep, publishRefusal, removeLayerStep } from './layerResultSteps';export type {CommitMaskImageResult,@@ -28,19 +22,20 @@ export type {} from '@workbench/canvas-engine/capabilities';export interface MaskResultControllerOptions {- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;- readonly concurrency: CanvasEditConcurrency;- readonly createLayerId: () => string;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- reducerAccepted: () => boolean,- mirrorAccepted: () => boolean- ) => void;- readonly endBurst: () => void;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly getReducerDocument: () => CanvasDocumentContractV3 | null;- readonly history: History;- readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;+ readonly ctx: Pick<+ CanvasMutationContext,+ | 'applyStep'+ | 'begin'+ | 'canEdit'+ | 'captureInsertionAnchor'+ | 'createLayerId'+ | 'getDocument'+ | 'installPrepared'+ | 'isGestureActive'+ | 'isGuardCurrent'+ | 'preparePixels'+ | 'reserveRaster'+ >;}/** Converts a guarded object-selection result into a structural mask layer. */@@ -49,13 +44,13 @@ export class MaskResultController {commit(options: CommitMaskImageResultOptions, owner?: symbol): Promise<CommitMaskImageResult> {const o = this.options;- if (!o.concurrency.canEdit(owner)) {+ if (!o.ctx.canEdit(owner)) {return Promise.resolve({ status: 'busy' });}if (options.signal?.aborted) {return Promise.resolve({ status: 'aborted' });}- const document = o.getDocument();+ const document = o.ctx.getDocument();if (!document) {return Promise.resolve({ status: 'missing' });}@@ -69,17 +64,17 @@ export class MaskResultController {if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {return Promise.resolve({ status: 'unsupported' });}- if (o.concurrency.isGestureActive()) {+ if (o.ctx.isGestureActive()) {return Promise.resolve({ status: 'busy' });}- if (!o.isGuardCurrent(options.guard)) {+ if (!o.ctx.isGuardCurrent(options.guard)) {return Promise.resolve({ status: 'stale' });}if (options.signal?.aborted) {return Promise.resolve({ status: 'aborted' });}const names = getDocumentLeaves(document).map((layer) => layer.name);- const layerId = o.createLayerId();+ const layerId = o.ctx.createLayerId();const layer =options.target === 'inpaint_mask'? createInpaintMaskFromImage({@@ -102,35 +97,30 @@ export class MaskResultController {rect: options.rect,});const selectedLayerId = document.selectedLayerId;- const anchor = o.captureInsertionAnchor(layer.type, liveLayer.id);- const apply = (): void =>- o.dispatchPrepared(- { anchor, layer, type: 'addCanvasLayer' },- () => getDocumentLayer(o.getReducerDocument(), layer.id) === layer,- () => getDocumentLayer(o.getDocument(), layer.id) === layer+ const anchor = o.ctx.captureInsertionAnchor(layer.type, liveLayer.id);+ const txn = o.ctx.begin({ historyBytes: HISTORY_ENTRY_OVERHEAD_BYTES, owner });+ if (!('publish' in txn)) {+ return Promise.resolve({ status: txn.status === 'gesture-active' ? 'busy' : txn.status });+ }+ try {+ const added = () =>+ addLayerStep(o.ctx, layer, anchor, null, { persist: false, previousSelectedLayerId: selectedLayerId });+ const result = txn.publish(+ options.target === 'inpaint_mask' ? 'Create inpaint mask from object' : 'Create region from object',+ added(),+ {+ bytes: HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(layer),+ redo: () => o.ctx.applyStep(added()),+ undo: () => o.ctx.applyStep(removeLayerStep(layerId, selectedLayerId)),+ });- o.endBurst();- apply();- o.history.push({- bytes: 256,- heldAssetRefs: collectHistoryMediaRefs(layer),- label: options.target === 'inpaint_mask' ? 'Create inpaint mask from object' : 'Create region from object',- redo: apply,- replayFailureAtomic: true,- undo: () => {- o.dispatchPrepared(- { id: selectedLayerId, type: 'setCanvasSelectedLayer' },- () => o.getReducerDocument()?.selectedLayerId === selectedLayerId,- () => o.getDocument()?.selectedLayerId === selectedLayerId- );- o.dispatchPrepared(- { ids: [layerId], type: 'removeCanvasLayers' },- () => isNodeAbsent(o.getReducerDocument(), layerId),- () => isNodeAbsent(o.getDocument(), layerId)- );- },- });- return Promise.resolve({ layerId, status: 'committed' });+ return Promise.resolve(+ result.status === 'committed' ? { layerId, status: 'committed' } : { status: publishRefusal(result) }+ );+ } finally {+ txn.end();+ }}dispose(): void {}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.tsnew file mode 100644index 0000000000..f4d6e47db4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts@@ -0,0 +1,134 @@+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 { describe, expect, it } from 'vitest';++import { createLayerOperationHarness } from './layerOperationHarness.testing';+import { MergeLayerController } from './mergeLayerController';++const paintLayer = (id: string): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+});++const UPPER_RECT: Rect = { height: 10, width: 10, x: 0, y: 0 };+const LOWER_RECT: Rect = { height: 10, width: 10, x: 5, y: 5 };+const MERGED_RECT: Rect = { height: 15, width: 15, x: 0, y: 0 };++const createHarness = (historyBytes?: number) => {+ const upper = paintLayer('upper');+ const lower = paintLayer('lower');+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId: 'upper',+ stacks: stacksFrom([upper, lower]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document, { historyBytes });+ h.layers.getOrCreateRect('upper', UPPER_RECT);+ h.layers.getOrCreateRect('lower', LOWER_RECT);+ const controller = new MergeLayerController({+ backend: h.backend,+ ctx: h.ctx,+ exportBaked: () => Promise.reject(new Error('merge down reads live caches')),+ hasExportableContent: (layerId) => (h.layers.get(layerId)?.rect.width ?? 0) > 0,+ isCacheReady: () => true,+ layers: h.layers,+ needsPixelPersistence: () => true,+ publishSelectedLayerIds: () => undefined,+ });+ // The reducer's own contracts, which merge and undo must restore by identity.+ const originals = {+ lower: getDocumentLayer(h.document(), 'lower')!,+ upper: getDocumentLayer(h.document(), 'upper')!,+ };+ return { ...h, controller, originals };+};++const leafIds = (document: CanvasDocumentContractV3 | null): string[] =>+ getDocumentLeaves(document).map((layer) => layer.id);++describe('MergeLayerController: merge down', () => {+ it('bakes the upper layer into the lower one as one undo step', () => {+ const h = createHarness();++ expect(h.controller.mergeDown('upper')).toBe('merged');+ expect(leafIds(h.document())).toEqual(['lower']);+ expect(getDocumentLayer(h.document(), 'lower')).toMatchObject({+ source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },+ });+ expect(h.layers.get('lower')?.rect).toEqual(MERGED_RECT);+ expect(h.history.entries().past).toEqual(['Merge down']);+ });++ it('undo restores both layers, their pixels and the selection; redo merges again', async () => {+ const h = createHarness();+ h.controller.mergeDown('upper');++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(leafIds(h.document())).toEqual(['upper', 'lower']);+ expect(getDocumentLayer(h.document(), 'upper')).toBe(h.originals.upper);+ expect(getDocumentLayer(h.document(), 'lower')).toBe(h.originals.lower);+ expect(h.document().selectedLayerId).toBe('upper');+ expect(h.layers.get('upper')?.rect).toEqual(UPPER_RECT);+ expect(h.layers.get('lower')?.rect).toEqual(LOWER_RECT);++ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(leafIds(h.document())).toEqual(['lower']);+ expect(h.layers.get('lower')?.rect).toEqual(MERGED_RECT);+ });++ it('puts the merge back and keeps the step when the upper layer cannot be reinserted', async () => {+ const h = createHarness();+ h.controller.mergeDown('upper');+ const merged = h.document();+ h.state.refuse = (mutation) => mutation.type === 'applyCanvasLayerStackMutation';++ expect((await h.history.undo()).status).toBe('failed');+ expect(leafIds(h.document())).toEqual(['lower']);+ expect(getDocumentLayer(h.document(), 'lower')).toBe(getDocumentLayer(merged, 'lower'));+ expect(h.layers.get('lower')?.rect).toEqual(MERGED_RECT);+ expect(h.history.canUndo()).toBe(true);+ expect(h.history.canRedo()).toBe(false);+ });++ it('refuses a merge it could never undo before anything changes', () => {+ const h = createHarness(1024);+ const before = h.document();++ expect(h.controller.mergeDown('upper')).toBe('over-budget');+ expect(h.document()).toBe(before);+ expect(h.dispatched).toEqual([]);+ expect(h.layers.get('upper')?.rect).toEqual(UPPER_RECT);+ });++ it('refuses when its pixels cannot be reserved', () => {+ const h = createHarness();+ h.state.rasterBytes = 1024;++ expect(h.controller.mergeDown('upper')).toBe('over-budget');+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ });++ it('refuses the bottom-most layer and a busy canvas', () => {+ const h = createHarness();+ expect(h.controller.mergeDown('lower')).toBe('unsupported');+ expect(h.controller.mergeDown('missing')).toBe('missing');+ h.state.gestureActive = true;+ expect(h.controller.mergeDown('upper')).toBe('busy');+ expect(h.dispatched).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex abe951b3c5..7a4615787c 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,8 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { RasterMemoryReservationResult } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';+import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';+import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';@@ -16,7 +18,7 @@ import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionimport { 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 { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';import { blendToComposite } from '@workbench/canvas-engine/render/compositor';@@ -26,9 +28,26 @@ import {type GroupCompositeScope,} from '@workbench/canvas-engine/render/groupCompositeScopes';-import type { CanvasMutationContext } from './mutationContext';+import type { CanvasMutationContext, EditStep } from './mutationContext';-export type MergeVisibleResult = 'merged' | 'not-ready' | 'over-budget' | 'busy' | 'nothing';+import {+ addedLayerHistoryBytes,+ layerEditRefusal,+ layerEditStatus,+ paintLayerAt,+ publishAddedRasterLayer,+ rgbaBytes,+ withReplayReservation,+ type LayerEditRefusal,+} from './newRasterLayerController';++export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'failed';++export type MergeDownResult =+ | 'merged'+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>+ | LayerEditRefusal+ | 'failed';type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }@@ -38,35 +57,46 @@ export interface MergeLayerControllerOptions {readonly backend: RasterBackend;readonly ctx: CanvasMutationContext;readonly layers: LayerCacheStore;- readonly canEdit: () => boolean;readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;readonly hasExportableContent: (layerId: string) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;- readonly notifyPainted: (layerId: string) => void;- readonly markDirty: (layerId: string) => void;readonly needsPixelPersistence: (layer: CanvasLayerContract) => boolean;readonly publishSelectedLayerIds: (primaryId: string | null, selectedIds: readonly string[]) => void;- readonly reserve: (bytes: number) => RasterMemoryReservationResult;}+/** A layer's cache pixels copied out for undo. */+interface PixelSnapshot {+ readonly rect: Rect;+ readonly pixels: RasterSurface;+}++const EMPTY_RECT: Rect = { height: 0, width: 0, x: 0, y: 0 };++const countScopes = (scopes: readonly GroupCompositeScope[]): number =>+ scopes.reduce((count, scope) => count + 1 + countScopes(scope.children), 0);+/** Owns destructive merge-down and non-destructive merge-visible pixel operations. */export class MergeLayerController {private disposed = false;constructor(private readonly deps: MergeLayerControllerOptions) {}- mergeDown(upperLayerId: string): boolean {- if (this.disposed || !this.deps.canEdit() || this.deps.ctx.isGestureActive()) {- return false;+ /**+ * Bakes the upper layer into the one below as one undo step: the lower layer keeps its id and takes the merged+ * pixels. Undo restores the lower contract and pixels, then reinserts the upper layer with its own.+ */+ mergeDown(upperLayerId: string): MergeDownResult {+ const { ctx } = this.deps;+ if (this.disposed) {+ return 'not-ready';}- this.deps.ctx.endBurst();- const document = this.deps.ctx.getDocument();+ const document = ctx.getDocument();if (!document) {- return false;+ return 'missing';}const eligibility = mergeDownEligibility(document, upperLayerId);if (eligibility.status !== 'eligible') {- return false;+ return eligibility.status === 'missing' ? 'missing' : 'unsupported';}const upper = lookupDocumentLayer(document, eligibility.upperId)!;const below = lookupDocumentLayer(document, eligibility.lowerId)!;@@ -80,73 +110,146 @@ export class MergeLayerController {!this.deps.isCacheReady(upper, document) ||!this.deps.isCacheReady(below, document)) {- return false;+ return 'not-ready';}const matrix = mergeDownMatrix(below.transform, upper.transform);if (!matrix) {- return false;- }- if (!belowHasContent && !upperHasContent) {- this.deps.ctx.dispatch({- source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },- type: 'mergeCanvasLayersDown',- upperLayerId,- });- // An empty live cache, not a missing one: the paint barrier treats a dirty layer without a cache as lost.- this.deps.layers.delete(below.id);- this.deps.layers.getOrCreateRect(below.id, { height: 0, width: 0, x: 0, y: 0 }).stale = false;- this.deps.notifyPainted(below.id);- this.deps.markDirty(below.id);- return true;+ return 'unsupported';}- const mergedRect = roundOut(- belowHasContent && upperHasContent- ? union(belowCache!.rect, transformBounds(matrix, upperCache!.rect))- : belowHasContent- ? belowCache!.rect- : transformBounds(matrix, upperCache!.rect)- );- const merged = this.deps.backend.createSurface(mergedRect.width, mergedRect.height);- const context = merged.ctx;- context.setTransform(1, 0, 0, 1, 0, 0);- context.clearRect(0, 0, mergedRect.width, mergedRect.height);- if (belowHasContent) {- context.drawImage(- belowCache!.surface.canvas,- belowCache!.rect.x - mergedRect.x,- belowCache!.rect.y - mergedRect.y- );+ const upperRect = upperHasContent ? { ...upperCache!.rect } : EMPTY_RECT;+ const belowRect = belowHasContent ? { ...belowCache!.rect } : EMPTY_RECT;+ const mergedRect =+ !belowHasContent && !upperHasContent+ ? EMPTY_RECT+ : roundOut(+ belowHasContent && upperHasContent+ ? union(belowRect, transformBounds(matrix, upperRect))+ : belowHasContent+ ? belowRect+ : transformBounds(matrix, upperRect)+ );+ const snapshotBytes = rgbaBytes(upperRect) + rgbaBytes(belowRect);+ const txn = ctx.begin({+ historyBytes: snapshotBytes + rgbaBytes(mergedRect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ });+ if (!('publish' in txn)) {+ return layerEditRefusal(txn.status);}- if (upperHasContent) {- context.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - mergedRect.x, matrix.f - mergedRect.y);- context.globalAlpha = upper.opacity;- context.globalCompositeOperation = blendToComposite(upper.blendMode);- context.drawImage(upperCache!.surface.canvas, upperCache!.rect.x, upperCache!.rect.y);+ try {+ // Undo snapshots, the merged pixels and their prepared cache replacement.+ if (!txn.reserveRaster(snapshotBytes + rgbaBytes(mergedRect) * 2)) {+ return 'over-budget';+ }+ const snapshot = (rect: Rect, layerId: string): PixelSnapshot => {+ const pixels = this.deps.backend.createSurface(rect.width, rect.height);+ if (!isEmpty(rect)) {+ pixels.ctx.drawImage(this.deps.layers.get(layerId)!.surface.canvas, 0, 0);+ }+ return { pixels, rect };+ };+ const upperPixels = snapshot(upperRect, upper.id);+ const belowPixels = snapshot(belowRect, below.id);+ const merged = this.deps.backend.createSurface(mergedRect.width, mergedRect.height);+ const context = merged.ctx;context.setTransform(1, 0, 0, 1, 0, 0);- context.globalAlpha = 1;- context.globalCompositeOperation = 'source-over';+ context.clearRect(0, 0, mergedRect.width, mergedRect.height);+ if (belowHasContent) {+ context.drawImage(belowPixels.pixels.canvas, belowRect.x - mergedRect.x, belowRect.y - mergedRect.y);+ }+ if (upperHasContent) {+ context.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - mergedRect.x, matrix.f - mergedRect.y);+ context.globalAlpha = upper.opacity;+ context.globalCompositeOperation = blendToComposite(upper.blendMode);+ context.drawImage(upperPixels.pixels.canvas, upperRect.x, upperRect.y);+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.globalAlpha = 1;+ context.globalCompositeOperation = 'source-over';+ }+ const mergedPixels: PixelSnapshot = { pixels: merged, rect: mergedRect };+ const source = { bitmap: null, offset: { x: mergedRect.x, y: mergedRect.y }, type: 'paint' } as const;+ const mergeMutation: CanvasProjectMutation = { source, type: 'mergeCanvasLayersDown', upperLayerId: upper.id };+ const upperAnchor = ctx.captureRestoreAnchor(upper.id)!;+ const selectedLayerId = document.selectedLayerId;+ const persist = (layer: CanvasLayerContract) => this.deps.needsPixelPersistence(layer);++ // A merge the reducer accepts cannot be expressed back as one mutation; replays split undo into two steps.+ const mergeStep = (): EditStep => {+ const prepared = ctx.preparePixels(below.id, mergedRect, merged);+ return {+ accepted: (candidate) =>+ isNodeAbsent(candidate, upper.id) &&+ (getDocumentLayer(candidate, below.id) as { source?: unknown } | undefined)?.source === source,+ install: () => ctx.installPrepared(prepared),+ mutation: mergeMutation,+ };+ };+ const replaceBelowStep = (contract: CanvasLayerContract, pixels: PixelSnapshot): EditStep => {+ const previous = getDocumentLayer(ctx.getReducerDocument(), below.id);+ const prepared = ctx.preparePixels(below.id, pixels.rect, pixels.pixels);+ return {+ accepted: (candidate) => getDocumentLayer(candidate, below.id) === contract,+ install: () => ctx.installPrepared(prepared, persist(contract)),+ mutation: { layer: contract, layerId: below.id, type: 'replaceCanvasLayer' },+ rollback: previous+ ? {+ mutation: { layer: previous, layerId: below.id, type: 'replaceCanvasLayer' },+ restored: (candidate) => getDocumentLayer(candidate, below.id) === previous,+ }+ : undefined,+ };+ };+ const reinsertUpperStep = (): EditStep => {+ const prepared = ctx.preparePixels(upper.id, upperRect, upperPixels.pixels);+ return {+ accepted: (candidate) =>+ getDocumentLayer(candidate, upper.id) === upper && candidate?.selectedLayerId === selectedLayerId,+ install: () => ctx.installPrepared(prepared, persist(upper)),+ mutation: {+ add: [{ anchor: upperAnchor, nodes: [upper] }],+ enabledUpdates: [],+ selectedLayerId,+ type: 'applyCanvasLayerStackMutation',+ },+ rollback: {+ mutation: { enabledUpdates: [], removeIds: [upper.id], type: 'applyCanvasLayerStackMutation' },+ restored: (candidate) => isNodeAbsent(candidate, upper.id),+ },+ };+ };+ const undo = (): void =>+ withReplayReservation(ctx, snapshotBytes, () => {+ const mergedBelow = getDocumentLayer(ctx.getReducerDocument(), below.id);+ ctx.applyStep(replaceBelowStep(below, belowPixels));+ try {+ ctx.applyStep(reinsertUpperStep());+ } catch (error) {+ if (mergedBelow) {+ ctx.applyStep(replaceBelowStep(mergedBelow, mergedPixels));+ }+ throw error;+ }+ });+ const status = layerEditStatus(+ txn.publish('Merge down', mergeStep(), {+ bytes: snapshotBytes + rgbaBytes(mergedRect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(upper, below),+ redo: () => withReplayReservation(ctx, rgbaBytes(mergedRect), () => ctx.applyStep(mergeStep())),+ undo,+ })+ );+ return status === 'committed' ? 'merged' : status;+ } finally {+ txn.end();}- this.deps.ctx.dispatch({- source: { bitmap: null, offset: { x: mergedRect.x, y: mergedRect.y }, type: 'paint' },- type: 'mergeCanvasLayersDown',- upperLayerId,- });- this.deps.layers.delete(below.id);- const target = this.deps.layers.getOrCreateRect(below.id, mergedRect);- target.surface.ctx.drawImage(merged.canvas, 0, 0);- target.stale = false;- this.deps.notifyPainted(below.id);- this.deps.markDirty(below.id);- return true;}async mergeVisible(): Promise<MergeVisibleResult> {- const permit = this.deps.ctx.capturePermit();- if (this.disposed || !permit || !this.deps.canEdit() || this.deps.ctx.isGestureActive()) {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {return 'busy';}- this.deps.ctx.endBurst();- const document = this.deps.ctx.getDocument();+ const document = ctx.getDocument();if (!document) {return 'nothing';}@@ -173,7 +276,7 @@ export class MergeLayerController {throw rejected.reason instanceof Error ? rejected.reason : new Error(String(rejected.reason));}const exports = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);- if (!this.deps.ctx.isPermitCurrent(permit)) {+ if (!ctx.isPermitCurrent(permit)) {return 'busy';}if (exports.some((result) => result.status === 'over-budget')) {@@ -182,9 +285,6 @@ export class MergeLayerController {if (exports.some((result) => result.status !== 'ok')) {return 'not-ready';}- if (this.deps.ctx.isGestureActive()) {- return 'busy';- }for (let index = 0; index < exports.length; index += 1) {const exported = exports[index];const contributor = contributors[index];@@ -193,13 +293,13 @@ export class MergeLayerController {exported.status !== 'ok' ||!contributor ||exported.guard.layer !== contributor ||- !this.deps.ctx.isGuardCurrent(exported.guard)+ !ctx.isGuardCurrent(exported.guard)) {return 'not-ready';}}- const liveDocument = this.deps.ctx.getDocument();+ const liveDocument = ctx.getDocument();const liveLeaves = liveDocument? getMergeVisibleRasterLeaves(compileDocumentLeaves(liveDocument), this.deps.hasExportableContent): [];@@ -227,101 +327,73 @@ export class MergeLayerController {if (isEmpty(rect)) {return 'nothing';}- const pixels = this.deps.backend.createSurface(rect.width, rect.height);- const context = pixels.ctx;- context.setTransform(1, 0, 0, 1, 0, 0);- context.clearRect(0, 0, rect.width, rect.height);- // Composite the group to preserve member opacity and blending in merged pixels.- const drawMerged = (- target: RasterSurface['ctx'],- from: number,- to: number,- range: readonly GroupCompositeScope[]- ): void => {- let scopeIndex = range.length - 1;- for (let index = to - 1; index >= from;) {- const scope = scopeIndex >= 0 ? range[scopeIndex]! : null;- if (scope && index >= scope.start && index < scope.end) {- const buffer = this.deps.backend.createSurface(rect.width, rect.height);- buffer.ctx.setTransform(1, 0, 0, 1, 0, 0);- buffer.ctx.clearRect(0, 0, rect.width, rect.height);- drawMerged(buffer.ctx, scope.start, scope.end, scope.children);- if (!isIdentityAdjustments(scope.adjustments)) {- const scoped = buffer.ctx.getImageData(0, 0, rect.width, rect.height);- applyAdjustments(scoped, scope.adjustments);- buffer.ctx.putImageData(scoped, 0, 0);+ const txn = ctx.begin({ historyBytes: addedLayerHistoryBytes(rect) });+ if (!('publish' in txn)) {+ return layerEditRefusal(txn.status);+ }+ try {+ // The flattened result plus one buffer per isolated group scope.+ if (!txn.reserveRaster(rgbaBytes(rect) * (1 + countScopes(scopes)))) {+ return 'over-budget';+ }+ const pixels = this.deps.backend.createSurface(rect.width, rect.height);+ const context = pixels.ctx;+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, rect.width, rect.height);+ // Composite the group to preserve member opacity and blending in merged pixels.+ const drawMerged = (+ target: RasterSurface['ctx'],+ from: number,+ to: number,+ range: readonly GroupCompositeScope[]+ ): void => {+ let scopeIndex = range.length - 1;+ for (let index = to - 1; index >= from;) {+ const scope = scopeIndex >= 0 ? range[scopeIndex]! : null;+ if (scope && index >= scope.start && index < scope.end) {+ const buffer = this.deps.backend.createSurface(rect.width, rect.height);+ buffer.ctx.setTransform(1, 0, 0, 1, 0, 0);+ buffer.ctx.clearRect(0, 0, rect.width, rect.height);+ drawMerged(buffer.ctx, scope.start, scope.end, scope.children);+ if (!isIdentityAdjustments(scope.adjustments)) {+ const scoped = buffer.ctx.getImageData(0, 0, rect.width, rect.height);+ applyAdjustments(scoped, scope.adjustments);+ buffer.ctx.putImageData(scoped, 0, 0);+ }+ target.globalAlpha = scope.opacity;+ target.globalCompositeOperation = blendToComposite(scope.blendMode);+ target.drawImage(buffer.canvas, 0, 0);+ index = scope.start - 1;+ scopeIndex -= 1;+ continue;}- target.globalAlpha = scope.opacity;- target.globalCompositeOperation = blendToComposite(scope.blendMode);- target.drawImage(buffer.canvas, 0, 0);- index = scope.start - 1;- scopeIndex -= 1;- continue;+ const exported = successful[index]!;+ const contributor = contributors[index]!;+ target.globalAlpha = contributor.opacity;+ target.globalCompositeOperation = blendToComposite(contributor.blendMode);+ target.drawImage(exported.surface.canvas, exported.rect.x - rect.x, exported.rect.y - rect.y);+ index -= 1;}- const exported = successful[index]!;- const contributor = contributors[index]!;- target.globalAlpha = contributor.opacity;- target.globalCompositeOperation = blendToComposite(contributor.blendMode);- target.drawImage(exported.surface.canvas, exported.rect.x - rect.x, exported.rect.y - rect.y);- index -= 1;- }- };- drawMerged(context, 0, successful.length, scopes);- context.globalAlpha = 1;- context.globalCompositeOperation = 'source-over';+ };+ drawMerged(context, 0, successful.length, scopes);+ context.globalAlpha = 1;+ context.globalCompositeOperation = 'source-over';- const resultId = this.deps.ctx.createLayerId();- const resultLayer: CanvasLayerContract = {- blendMode: 'normal',- id: resultId,- isEnabled: true,- isLocked: false,- name: `${contributors[0]!.name} merged`,- opacity: 1,- source: { bitmap: null, offset: { x: rect.x, y: rect.y }, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };- const selectedLayerId = liveDocument.selectedLayerId;- const anchor = this.deps.ctx.captureInsertionAnchor('raster', null);- const hasResult = (doc: CanvasDocumentContractV3 | null): boolean =>- doc?.selectedLayerId === resultId && getDocumentLayer(doc, resultLayer.id) === resultLayer;- const apply = (): void => {- const prepared = this.deps.ctx.preparePixels(resultId, rect, pixels);- this.deps.ctx.dispatchPrepared(- {- add: [{ anchor, nodes: [resultLayer] }],- enabledUpdates: [],- selectedLayerId: resultId,- type: 'applyCanvasLayerStackMutation',- },- () => hasResult(this.deps.ctx.getReducerDocument()),- () => hasResult(this.deps.ctx.getDocument())+ const status = layerEditStatus(+ publishAddedRasterLayer(ctx, txn, {+ anchor: ctx.captureInsertionAnchor('raster', null),+ heldAssetRefs: collectHistoryMediaRefs(contributors),+ label: 'Merge visible',+ layer: paintLayerAt(ctx.createLayerId(), `${contributors[0]!.name} merged`, rect),+ pixels,+ rect,+ selectedLayerId: liveDocument.selectedLayerId,+ }));- this.deps.ctx.installPrepared(prepared);- };- if (!this.deps.ctx.isPermitCurrent(permit)) {- return 'busy';+ return status === 'committed' ? 'merged' : status;+ } finally {+ txn.end();}- apply();- this.deps.ctx.history.push({- bytes: rect.width * rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(contributors),- label: 'Merge visible',- redo: apply,- replayFailureAtomic: true,- undo: () =>- this.deps.ctx.dispatchPrepared(- { enabledUpdates: [], removeIds: [resultId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },- () =>- this.deps.ctx.getReducerDocument()?.selectedLayerId === selectedLayerId &&- isNodeAbsent(this.deps.ctx.getReducerDocument(), resultId),- () =>- this.deps.ctx.getDocument()?.selectedLayerId === selectedLayerId &&- isNodeAbsent(this.deps.ctx.getDocument(), resultId)- ),- });- return 'merged';} finally {for (const result of owned) {result.release();@@ -330,12 +402,12 @@ export class MergeLayerController {}async mergeSelected(layerIds: readonly string[]): Promise<MergeVisibleResult> {- const permit = this.deps.ctx.capturePermit();- if (this.disposed || !permit || !this.deps.canEdit() || this.deps.ctx.isGestureActive()) {+ const { ctx } = this.deps;+ const permit = ctx.capturePermit();+ if (this.disposed || !permit) {return 'busy';}- this.deps.ctx.endBurst();- const document = this.deps.ctx.getDocument();+ const document = ctx.getDocument();if (!document) {return 'nothing';}@@ -361,13 +433,13 @@ export class MergeLayerController {throw rejected.reason instanceof Error ? rejected.reason : new Error(String(rejected.reason));}const exports = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);- if (!this.deps.ctx.isPermitCurrent(permit)) {+ if (!ctx.isPermitCurrent(permit)) {return 'busy';}if (exports.some((result) => result.status === 'over-budget')) {return 'over-budget';}- if (exports.some((result) => result.status !== 'ok') || this.deps.ctx.isGestureActive()) {+ if (exports.some((result) => result.status !== 'ok')) {return 'not-ready';}for (let index = 0; index < exports.length; index += 1) {@@ -378,13 +450,12 @@ export class MergeLayerController {exported.status !== 'ok' ||!contributor ||exported.guard.layer !== contributor ||- !this.deps.ctx.isGuardCurrent(exported.guard)+ !ctx.isGuardCurrent(exported.guard)) {return 'not-ready';}}- const liveDocument = this.deps.ctx.getDocument();- if (liveDocument !== document) {+ if (ctx.getDocument() !== document) {return 'not-ready';}@@ -401,19 +472,20 @@ export class MergeLayerController {if (isEmpty(rect)) {return 'nothing';}- const rawBytes = rawEntries.reduce((bytes, entry) => bytes + entry!.rect.width * entry!.rect.height * 4, 0);- const mergedBytes = rect.width * rect.height * 4;- const historyBytes = rawBytes + mergedBytes + contributors.length * 256;- if (!this.deps.ctx.history.canRetain(historyBytes)) {- return 'over-budget';- }- // Besides already-reserved baked exports, the transaction simultaneously- // owns raw undo snapshots, the flattened result, and its prepared cache.- const reservation = this.deps.reserve(rawBytes + mergedBytes * 2);- if (reservation.status === 'over-budget') {- return 'over-budget';+ const rawBytes = rawEntries.reduce((bytes, entry) => bytes + rgbaBytes(entry!.rect), 0);+ const mergedBytes = rgbaBytes(rect);+ const txn = ctx.begin({+ historyBytes: rawBytes + mergedBytes + contributors.length * HISTORY_ENTRY_OVERHEAD_BYTES,+ });+ if (!('publish' in txn)) {+ return 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';+ }const rawSnapshots = contributors.map((contributor, index) => {const entry = rawEntries[index]!;const snapshotPixels = this.deps.backend.createSurface(entry.rect.width, entry.rect.height);@@ -434,22 +506,12 @@ export class MergeLayerController {context.globalAlpha = 1;context.globalCompositeOperation = 'source-over';- const resultId = this.deps.ctx.createLayerId();- const resultLayer: CanvasLayerContract = {- blendMode: 'normal',- id: resultId,- isEnabled: true,- isLocked: false,- name: `${contributors[0]!.name} merged`,- opacity: 1,- source: { bitmap: null, offset: { x: rect.x, y: rect.y }, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };+ const resultLayer = paintLayerAt(ctx.createLayerId(), `${contributors[0]!.name} merged`, rect);+ const resultId = resultLayer.id;const contributorIds = contributors.map((layer) => layer.id);- const anchor = this.deps.ctx.captureInsertionAnchor('raster', contributors[0]!.id);+ const anchor = ctx.captureInsertionAnchor('raster', contributors[0]!.id);const restoreInsertions = contributors.map((layer) => ({- anchor: this.deps.ctx.captureRestoreAnchor(layer.id)!,+ anchor: ctx.captureRestoreAnchor(layer.id)!,nodes: [layer],}));const mergedStacks = removeNodes(insertNodesAtAnchor(document.stacks, anchor, [resultLayer]), selectedIds);@@ -458,77 +520,58 @@ export class MergeLayerController {candidate?.selectedLayerId === resultId && haveSameStructure(candidate.stacks, mergedStacks);const hasOriginals = (candidate: CanvasDocumentContractV3 | null): boolean =>candidate?.selectedLayerId === selectedLayerId && haveSameStructure(candidate.stacks, document.stacks);- const applyPrepared = (): void => {- const prepared = this.deps.ctx.preparePixels(resultId, rect, pixels);- this.deps.ctx.dispatchPrepared(- {- add: [{ anchor, nodes: [resultLayer] }],- enabledUpdates: [],- removeIds: contributorIds,- selectedLayerId: resultId,- type: 'applyCanvasLayerStackMutation',- },- () => hasMerged(this.deps.ctx.getReducerDocument()),- () => hasMerged(this.deps.ctx.getDocument())- );- this.deps.ctx.installPrepared(prepared);- this.deps.publishSelectedLayerIds(resultId, [resultId]);+ const merge: CanvasProjectMutation = {+ add: [{ anchor, nodes: [resultLayer] }],+ enabledUpdates: [],+ removeIds: contributorIds,+ selectedLayerId: resultId,+ type: 'applyCanvasLayerStackMutation',};- const redo = (): void => {- const replayReservation = this.deps.reserve(mergedBytes);- if (replayReservation.status === 'over-budget') {- throw new Error('Not enough raster memory to restore the merged layer');- }- try {- applyPrepared();- } finally {- replayReservation.lease.release();- }+ const restore: CanvasProjectMutation = {+ add: restoreInsertions,+ enabledUpdates: [],+ removeIds: [resultId],+ selectedLayerId,+ type: 'applyCanvasLayerStackMutation',};- const undo = (): void => {- const replayReservation = this.deps.reserve(rawBytes);- if (replayReservation.status === 'over-budget') {- throw new Error('Not enough raster memory to restore the source layers');- }- try {- const prepared = rawSnapshots.map((captured) => ({- layer: captured.layer,- replacement: this.deps.ctx.preparePixels(captured.layer.id, captured.rect, captured.pixels),- }));- this.deps.ctx.dispatchPrepared(- {- add: restoreInsertions,- enabledUpdates: [],- removeIds: [resultId],- selectedLayerId,- type: 'applyCanvasLayerStackMutation',- },- () => hasOriginals(this.deps.ctx.getReducerDocument()),- () => hasOriginals(this.deps.ctx.getDocument())- );- for (const { layer, replacement } of prepared) {- this.deps.ctx.installPrepared(replacement, this.deps.needsPixelPersistence(layer));- }- this.deps.publishSelectedLayerIds(selectedLayerId, contributorIds);- } finally {- replayReservation.lease.release();- }+ const mergeStep = (): EditStep => {+ const prepared = ctx.preparePixels(resultId, rect, pixels);+ return {+ accepted: hasMerged,+ install: () => ctx.installPrepared(prepared),+ mutation: merge,+ notify: () => this.deps.publishSelectedLayerIds(resultId, [resultId]),+ rollback: { mutation: restore, restored: hasOriginals },+ };};- if (!this.deps.ctx.isPermitCurrent(permit)) {- return 'busy';- }- applyPrepared();- this.deps.ctx.history.push({- bytes: historyBytes,- heldAssetRefs: collectHistoryMediaRefs(rawSnapshots.map(({ layer }) => layer)),- label: 'Merge selected layers',- redo,- replayFailureAtomic: true,- undo,- });- return 'merged';+ const restoreStep = (): EditStep => {+ const prepared = rawSnapshots.map((captured) => ({+ layer: captured.layer,+ replacement: ctx.preparePixels(captured.layer.id, captured.rect, captured.pixels),+ }));+ return {+ accepted: hasOriginals,+ install: () => {+ for (const { layer, replacement } of prepared) {+ ctx.installPrepared(replacement, this.deps.needsPixelPersistence(layer));+ }+ },+ mutation: restore,+ notify: () => this.deps.publishSelectedLayerIds(selectedLayerId, contributorIds),+ rollback: { mutation: merge, restored: hasMerged },+ };+ };+ const status = layerEditStatus(+ txn.publish('Merge selected layers', 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;} finally {- reservation.lease.release();+ txn.end();}} finally {for (const result of owned) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.tsindex be771df1a0..ef311c3c0e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts@@ -7,8 +7,6 @@ import { describe, expect, it, vi } from 'vitest';import { createCanvasMutationContext, type CanvasMutationContextDeps } from './mutationContext';-const action: CanvasProjectMutation = { id: 'layer-1', type: 'setCanvasSelectedLayer' };-interface LockStore {get(): boolean;subscribe(listener: () => void): () => void;@@ -48,7 +46,6 @@ const createHarness = (overrides: Partial<CanvasMutationContextDeps> = {}) => {editOwner,projectId: 'p1',editingLocked: lock,- endBurst: () => undefined,getDocument: () => null,getReducerDocument: () => null,history: createHistory(),@@ -57,6 +54,7 @@ const createHarness = (overrides: Partial<CanvasMutationContextDeps> = {}) => {isGuardCurrent: () => true,preparePixels: (layerId, rect) => ({ layerId, rect, surface: {} }) as PreparedLayerCacheReplacement,refreshMirror: vi.fn(),+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),subscribeReducer: () => () => undefined,...overrides,};@@ -117,225 +115,383 @@ describe('createCanvasMutationContext', () => {});});- describe('dispatchPrepared', () => {- it('defers a user edit route until reducer and mirror postconditions succeed', () => {- const { context, deps } = createHarness();+ describe('transactions', () => {+ const entry = (bytes = 10) => ({ bytes, heldAssetRefs: NO_HELD_ASSET_REFS, redo: vi.fn(), undo: vi.fn() });+ const select = (id: string): CanvasProjectMutation => ({ id, type: 'setCanvasSelectedLayer' });++ /** A reducer whose documents record the selected id; the mirror follows unless told to lag. */+ const createDocuments = () => {+ const state = {+ dispatchError: null as Error | null,+ mirror: { selectedLayerId: null } as unknown as CanvasDocumentContractV3,+ mirrorLags: false,+ reducer: { selectedLayerId: null } as unknown as CanvasDocumentContractV3,+ rejects: false,+ };+ const dispatch = vi.fn((mutation: CanvasProjectMutation) => {+ if (!state.rejects && mutation.type === 'setCanvasSelectedLayer') {+ state.reducer = { selectedLayerId: mutation.id } as unknown as CanvasDocumentContractV3;+ if (!state.mirrorLags) {+ state.mirror = state.reducer;+ }+ }+ if (state.dispatchError) {+ throw state.dispatchError;+ }+ return !state.rejects;+ });+ return {+ deps: {+ dispatch,+ getDocument: () => state.mirror,+ getReducerDocument: () => state.reducer,+ refreshMirror: vi.fn(),+ },+ state,+ };+ };+ const selected = (id: string) => (document: CanvasDocumentContractV3 | null) => document?.selectedLayerId === id;++ const begin = (context: ReturnType<typeof createHarness>['context'], historyBytes = 10) => {+ const txn = context.begin({ historyBytes });+ if (!('publish' in txn)) {+ throw new Error(`refused: ${txn.status}`);+ }+ return txn;+ };- context.dispatchPrepared(- action,- () => true,- () => true- );+ it('refuses before anything is admitted or dispatched', () => {+ const documents = createDocuments();+ const history = createHistory({ byteBudget: 100 });+ const { context, deps, lock } = createHarness({ ...documents.deps, history });- expect(deps.dispatch).toHaveBeenCalledWith(action, 'system');- expect(deps.commitEdit).toHaveBeenCalledWith({ kind: 'mutation', mutation: action });+ expect(context.begin({ historyBytes: 101 })).toEqual({ status: 'over-budget' });+ lock.setLocked(true);+ expect(context.begin({ historyBytes: 10 })).toEqual({ status: 'busy' });+ lock.setLocked(false);+ const gesture = createHarness({ ...documents.deps, isGestureActive: () => true });+ expect(gesture.context.begin({ historyBytes: 10 })).toEqual({ status: 'gesture-active' });+ const empty = createHarness({ getReducerDocument: () => null });+ expect(empty.context.begin({ historyBytes: 10 })).toEqual({ status: 'not-ready' });+ context.dispose();+ expect(context.begin({ historyBytes: 10 })).toEqual({ status: 'not-ready' });++ expect(deps.dispatch).not.toHaveBeenCalled();+ expect(history.canUndo()).toBe(false);});- it('contains a routing failure after reducer and mirror acceptance', () => {- const failure = new Error('edit routing observer exploded');+ it('publishes a verified step once, records it and routes a user edit after it landed', () => {+ const documents = createDocuments();+ const history = createHistory();+ const order: string[] = [];const { context, deps } = createHarness({- commitEdit: vi.fn(() => {- throw failure;- }),+ ...documents.deps,+ commitEdit: vi.fn(() => order.push('route')),+ history,});+ const txn = begin(context);++ const result = txn.publish(+ 'Select',+ {+ accepted: selected('a'),+ install: () => order.push('install'),+ mutation: select('a'),+ notify: () => order.push('notify'),+ },+ entry()+ );+ txn.end();- expect(() =>- context.dispatchPrepared(- action,- () => true,- () => true- )- ).not.toThrow();- expect(deps.commitEdit).toHaveBeenCalledWith({ kind: 'mutation', mutation: action });+ expect(result.status).toBe('committed');+ expect(history.entries().past).toEqual(['Select']);+ expect(deps.dispatch).toHaveBeenCalledWith(select('a'), 'system');+ expect(order).toEqual(['install', 'route', 'notify']);+ expect(context.historyTop()).toBe('token' in result ? result.token : null);});- it('does not commit system-originated or history-replayed edit intent', () => {+ it('routes only user edits, never system-originated ones or history replays', async () => {+ const documents = createDocuments();const history = createHistory();- const { context, deps } = createHarness({ history });+ const { context, deps } = createHarness({ ...documents.deps, history });+ const system = begin(context);+ system.publish('Select', { accepted: selected('a'), mutation: select('a') }, entry(), { origin: 'system' });+ system.end();+ expect(deps.commitEdit).not.toHaveBeenCalled();- context.dispatchPrepared(- action,- () => true,- () => true,- 'system'+ const user = begin(context);+ user.publish(+ 'Select',+ { accepted: selected('b'), mutation: select('b') },+ {+ ...entry(),+ redo: () => context.applyStep({ accepted: selected('b'), mutation: select('b') }),+ undo: () => context.applyStep({ accepted: selected('a'), mutation: select('a') }),+ });- history.push({- bytes: 1,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'Replay',- redo: () => undefined,- undo: () =>- context.dispatchPrepared(- action,- () => true,- () => true- ),- });- history.undo();+ user.end();+ expect(deps.commitEdit).toHaveBeenCalledOnce();+ await history.undo();+ await history.redo();+ expect(deps.commitEdit).toHaveBeenCalledOnce();+ expect(documents.deps.dispatch).toHaveBeenLastCalledWith(select('b'), 'system');+ });+ it('records nothing when the reducer leaves the document unchanged', () => {+ const documents = createDocuments();+ documents.state.rejects = true;+ const history = createHistory();+ const { context, deps } = createHarness({ ...documents.deps, history });+ const txn = begin(context);++ expect(txn.publish('Select', { accepted: selected('a'), mutation: select('a') }, entry())).toEqual({+ status: 'dispatch-rejected',+ });+ txn.end();+ expect(history.canUndo()).toBe(false);expect(deps.commitEdit).not.toHaveBeenCalled();});- it('throws when dispatch rejects the mutation and the reducer shows no postcondition', () => {- const commitEdit = vi.fn();- const { context } = createHarness({ commitEdit, dispatch: () => false });- expect(() =>- context.dispatchPrepared(- action,- () => false,- () => false- )- ).toThrow('Canvas document mutation was rejected');- expect(commitEdit).not.toHaveBeenCalled();- });+ it('rolls back an accepted mutation whose postconditions fail and reports an unmirrored rollback', () => {+ const documents = createDocuments();+ const report = vi.fn();+ const { context } = createHarness({ ...documents.deps, report });+ const step = {+ accepted: () => false,+ mutation: select('a'),+ rollback: { mutation: select('origin'), restored: selected('origin') },+ };- it('rethrows a dispatch error when the reducer did not apply the mutation', () => {- const failure = new Error('subscriber exploded');- const { context } = createHarness({- dispatch: () => {- throw failure;- },+ const reverted = begin(context);+ expect(reverted.publish('Select', step, entry())).toEqual({+ recovered: 'reverted',+ status: 'postcondition-failed',});- expect(() =>- context.dispatchPrepared(- action,- () => false,- () => true- )- ).toThrow(failure);+ reverted.end();+ expect(documents.state.reducer.selectedLayerId).toBe('origin');+ expect(report).not.toHaveBeenCalled();++ documents.state.mirrorLags = true;+ const unmirrored = begin(context);+ expect(unmirrored.publish('Select', step, entry())).toEqual({+ recovered: 'reverted-unmirrored',+ status: 'postcondition-failed',+ });+ unmirrored.end();+ expect(report).toHaveBeenCalledOnce();});- it('swallows a dispatch error when the mutation is applied and mirrored', () => {- const failure = new Error('subscriber exploded');- const refreshMirror = vi.fn();+ it('rolls back when the document cannot be read after the mutation', () => {+ const documents = createDocuments();+ let unreadable = false;const { context } = createHarness({- dispatch: () => {- throw failure;+ ...documents.deps,+ dispatch: (mutation) => {+ const dispatched = documents.deps.dispatch(mutation);+ unreadable = mutation.type === 'setCanvasSelectedLayer' && mutation.id === 'a';+ return dispatched;+ },+ getReducerDocument: () => {+ if (unreadable) {+ throw new Error('state read failed');+ }+ return documents.state.reducer;},- refreshMirror,});- expect(() =>- context.dispatchPrepared(- action,- () => true,- () => true+ const txn = begin(context);++ expect(+ txn.publish(+ 'Select',+ {+ accepted: selected('a'),+ mutation: select('a'),+ rollback: { mutation: select('origin'), restored: selected('origin') },+ },+ entry())- ).not.toThrow();- expect(refreshMirror).toHaveBeenCalledTimes(1);+ ).toEqual({ recovered: 'reverted', status: 'postcondition-failed' });+ txn.end();+ expect(documents.state.reducer.selectedLayerId).toBe('origin');});- it('reconciles the mirror after a dispatch error and succeeds once it converges', () => {- const failure = new Error('subscriber exploded');- let mirrored = false;- const refreshMirror = vi.fn(() => {- mirrored = true;+ it('accepts a landed mutation whose observer threw once the mirror reconciles', () => {+ const documents = createDocuments();+ documents.state.dispatchError = new Error('observer exploded');+ documents.state.mirrorLags = true;+ documents.deps.refreshMirror.mockImplementation(() => {+ documents.state.mirror = documents.state.reducer;});- const { context } = createHarness({- dispatch: () => {- throw failure;- },- refreshMirror,- });- expect(() =>- context.dispatchPrepared(- action,- () => true,- () => mirrored- )- ).not.toThrow();- expect(refreshMirror).toHaveBeenCalledTimes(1);+ const { context } = createHarness(documents.deps);+ const txn = begin(context);++ expect(txn.publish('Select', { accepted: selected('a'), mutation: select('a') }, entry()).status).toBe(+ 'committed'+ );+ txn.end();+ expect(documents.deps.refreshMirror).toHaveBeenCalledOnce();});- it('rethrows the original dispatch error when the mirror never converges', () => {- const failure = new Error('subscriber exploded');- const refreshMirror = vi.fn();+ it('contains routing and notification failures once the step is recorded', () => {+ const documents = createDocuments();+ const history = createHistory();const { context } = createHarness({- dispatch: () => {- throw failure;+ ...documents.deps,+ commitEdit: () => {+ throw new Error('router exploded');},- refreshMirror,+ history,});- expect(() =>- context.dispatchPrepared(- action,- () => true,- () => false- )- ).toThrow(failure);- expect(refreshMirror).toHaveBeenCalledTimes(1);+ const txn = begin(context);++ const result = txn.publish(+ 'Select',+ {+ accepted: selected('a'),+ mutation: select('a'),+ notify: () => {+ throw new Error('listener exploded');+ },+ },+ entry()+ );+ txn.end();+ expect(result.status).toBe('committed');+ expect(history.canUndo()).toBe(true);});- it('swallows a refresh error when the mirror converged anyway', () => {- const failure = new Error('subscriber exploded');- let mirrored = false;- const refreshMirror = vi.fn(() => {- mirrored = true;- throw new Error('refresh exploded');- });+ it('refuses publication once the permit is stale, without dispatching', () => {+ const documents = createDocuments();+ const { context, deps, lock } = createHarness(documents.deps);+ const txn = begin(context);+ lock.setLocked(true);+ lock.setLocked(false);++ expect(txn.publish('Select', { mutation: select('a') }, entry())).toEqual({ status: 'busy' });+ txn.end();+ expect(deps.dispatch).not.toHaveBeenCalled();+ });++ it('grows its admission for a larger entry and refuses one history could never keep', () => {+ const documents = createDocuments();+ const history = createHistory({ byteBudget: 100 });+ const { context, deps } = createHarness({ ...documents.deps, history });+ const txn = begin(context, 10);++ expect(txn.growHistory(50)).toBe(true);+ expect(txn.publish('Select', { mutation: select('a') }, entry(101))).toEqual({ status: 'over-budget' });+ expect(deps.dispatch).not.toHaveBeenCalled();+ expect(txn.publish('Select', { accepted: selected('a'), mutation: select('a') }, entry(60)).status).toBe(+ 'committed'+ );+ txn.end();+ });++ it('keeps its admission when an observer of the step ends it mid-publication', () => {+ const documents = createDocuments();+ const history = createHistory();+ let txn: ReturnType<typeof begin> | null = null;const { context } = createHarness({- dispatch: () => {- throw failure;+ ...documents.deps,+ dispatch: (mutation) => {+ const dispatched = documents.deps.dispatch(mutation);+ txn?.end();+ return dispatched;},- refreshMirror,+ history,});- expect(() =>- context.dispatchPrepared(- action,- () => true,- () => mirrored- )- ).not.toThrow();- });+ txn = begin(context);- it('detects a reducer that rejects by returning unchanged state without throwing', () => {- const { context } = createHarness();- expect(() =>- context.dispatchPrepared(- action,- () => false,- () => false- )- ).toThrow('Canvas document mutation was rejected');+ expect(txn.publish('Select', { accepted: selected('a'), mutation: select('a') }, entry()).status).toBe(+ 'committed'+ );+ expect(history.entries().past).toEqual(['Select']);});- it('reconciles an unmirrored accepted mutation and throws when the mirror stays behind', () => {- const refreshMirror = vi.fn();- const { context } = createHarness({ refreshMirror });- expect(() =>- context.dispatchPrepared(- action,- () => true,- () => false- )- ).toThrow('Canvas document mutation was not mirrored');- expect(refreshMirror).toHaveBeenCalledTimes(1);+ it('releases admission, raster reservations and held resources when it ends', () => {+ const documents = createDocuments();+ const history = createHistory({ byteBudget: 100 });+ const lease = { release: vi.fn() };+ const held = { release: vi.fn() };+ const reserveRaster = vi.fn((bytes: number) =>+ bytes > 50+ ? ({ availableBytes: 50, requestedBytes: bytes, status: 'over-budget' } as const)+ : ({ lease, status: 'ok' } as const)+ );+ const { context } = createHarness({ ...documents.deps, history, reserveRaster });+ const txn = begin(context, 100);++ expect(txn.reserveRaster(60)).toBe(false);+ expect(txn.reserveRaster(40)).toBe(true);+ txn.hold(held);+ expect(context.begin({ historyBytes: 1 })).toEqual({ status: 'over-budget' });+ txn.end();+ txn.end();++ expect(lease.release).toHaveBeenCalledOnce();+ expect(held.release).toHaveBeenCalledOnce();+ expect('publish' in context.begin({ historyBytes: 100 })).toBe(true);});- it('accepts an unmirrored mutation once the mirror refresh converges', () => {- let mirrored = false;- const refreshMirror = vi.fn(() => {- mirrored = true;+ it('coalesces only into the entry it names while that entry is still newest', () => {+ const documents = createDocuments();+ const history = createHistory();+ const { context } = createHarness({ ...documents.deps, history });+ const first = begin(context);+ const recorded = first.publish('Nudge', { accepted: selected('a'), mutation: select('a') }, entry());+ first.end();+ const token = 'token' in recorded ? recorded.token : undefined;++ const second = begin(context);+ expect(+ second.publish('Nudge', { accepted: selected('b'), mutation: select('b') }, entry(), { replacing: token })+ .status+ ).toBe('committed');+ second.end();+ expect(history.entries().past).toEqual(['Nudge']);++ const stale = begin(context);+ expect(stale.publish('Nudge', { mutation: select('c') }, entry(), { replacing: token })).toEqual({+ status: 'busy',});- const { context } = createHarness({ refreshMirror });- expect(() =>- context.dispatchPrepared(- action,- () => true,- () => mirrored- )- ).not.toThrow();- expect(refreshMirror).toHaveBeenCalledTimes(1);+ stale.end();+ });++ it('refuses edits while a replay is running', async () => {+ const documents = createDocuments();+ const history = createHistory();+ const { context } = createHarness({ ...documents.deps, history });+ let finish!: () => void;+ const txn = begin(context);+ txn.publish(+ 'Slow',+ { accepted: selected('a'), mutation: select('a') },+ {+ ...entry(),+ undo: () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ }+ );+ txn.end();++ const replay = history.undo();+ expect(context.canEdit()).toBe(false);+ expect(context.begin({ historyBytes: 1 })).toEqual({ status: 'busy' });+ finish();+ await replay;+ expect(context.canEdit()).toBe(true);});});describe('dispose', () => {- it('stops tracking lock transitions so pre-dispose permits stay current', () => {- const { context, lock } = createHarness();+ it('makes every permit stale and refuses later edits', () => {+ const { context } = createHarness();const permit = context.capturePermit()!;context.dispose();- lock.setLocked(true);- lock.setLocked(false);- expect(context.isPermitCurrent(permit)).toBe(true);+ expect(context.isPermitCurrent(permit)).toBe(false);+ expect(context.canEdit()).toBe(false);});});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.tsindex 94a2892d8f..5201f716bd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts@@ -1,9 +1,15 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasStackForests } from '@workbench/canvas-engine/contracts';+import type { RasterMemoryReservationResult } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';-import type { CanvasEditConcurrency, DocumentEditPermit } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';+import type {+ CanvasEditConcurrency,+ CanvasTransactionOutcome,+ DocumentEditPermit,+ SubsetOf,+} from '@workbench/canvas-engine/editConcurrency';+import type { History, HistoryEntry, HistoryEntryToken } from '@workbench/canvas-engine/history/history';import type {CanvasEditIntent,CanvasMutationOrigin,@@ -17,11 +23,77 @@ import { EMPTY_STACKS } from '@workbench/canvas-engine/document/documentTree';import { captureInsertionAnchor, captureRestoreAnchor } from '@workbench/canvas-engine/document/insertionAnchors';/**- * Shared guarded mutation protocol: edit permits, prepared-cache dispatch with reducer/mirror postconditions,- * cache replacement, and required engine services.+ * One visible change: an optional document mutation verified on reducer and mirror, then in-memory publication of+ * prepared pixels. Publication and history replay apply steps the same way.*/+export interface EditStep {+ readonly mutation?: CanvasProjectMutation;+ /** The postcondition `mutation` must establish on the reducer document; the mirror must then follow it. */+ readonly accepted?: (document: CanvasDocumentContractV3 | null) => boolean;+ /** Restores the reducer when the mutation landed but its postconditions failed. */+ readonly rollback?: {+ readonly mutation: CanvasProjectMutation;+ readonly restored: (document: CanvasDocumentContractV3 | null) => boolean;+ };+ /** Publishes prepared pixels once the document accepted the mutation. Must not fail partially. */+ readonly install?: () => void;+ /** Ancillary consequences (dirty marks, selection mirrors); a failure cannot undo the accepted step. */+ readonly notify?: () => void;+}++/** Why a step did not land: the reducer left the document unchanged, or its postconditions failed. */+export class EditStepError extends Error {+ constructor(+ readonly outcome: 'rejected' | 'reverted' | 'reverted-unmirrored' | 'unreverted',+ options?: { cause?: unknown }+ ) {+ super(`Canvas edit step ${outcome === 'rejected' ? 'was rejected' : 'failed its postconditions'}.`, options);+ this.name = 'EditStepError';+ }+}++export type EditRefusal = SubsetOf<CanvasTransactionOutcome, 'busy' | 'gesture-active' | 'not-ready' | 'over-budget'>;++export type EditPublishResult =+ | { readonly status: 'committed'; readonly token: HistoryEntryToken }+ | { readonly status: EditRefusal }+ | { readonly status: 'dispatch-rejected' }+ | { readonly status: 'postcondition-failed'; readonly recovered: 'reverted' | 'reverted-unmirrored' | 'unreverted' };++/** The undo entry a publication records; its label comes from the publication. */+export type EditEntry = Omit<HistoryEntry, 'label'>;++/**+ * An admitted edit. Admission happens before any mutation, so an edit that could never keep its undo entry is+ * refused while the document, pixels and history are still untouched. Every resource the transaction reserves or+ * holds is released by `end`, which callers run in `finally`.+ */+export interface EditTransaction {+ /** Whether publication would still be accepted (permit, gesture, replay, disposal). */+ isCurrent(): boolean;+ /** Admits `bytes` more history; false when the edit could no longer keep its undo entry. */+ growHistory(bytes: number): boolean;+ /** Reserves raster bytes for preparation allocations until the transaction ends; false when they do not fit. */+ reserveRaster(bytes: number): boolean;+ /** Releases `resource` when the transaction ends. */+ hold<T extends { release(): void }>(resource: T): T;+ /** Applies `step`, records `entry` and routes the edit; refusals and failed steps leave history untouched. */+ publish(+ label: string,+ step: EditStep,+ entry: EditEntry,+ options?: {+ readonly replacing?: HistoryEntryToken;+ readonly origin?: CanvasMutationOrigin;+ /** The mutation this edit represents for routing; defaults to the step's own. */+ readonly routed?: CanvasProjectMutation;+ }+ ): EditPublishResult;+ end(): void;+}++/** The engine's single edit protocol: permits, admission, verified steps, history publication and cleanup. */export interface CanvasMutationContext extends CanvasEditConcurrency {- readonly history: History;getDocument(): CanvasDocumentContractV3 | null;getReducerDocument(): CanvasDocumentContractV3 | null;/** Where a new `stack` layer lands: above `aboveId` when it belongs to the stack, else the stack top. */@@ -29,17 +101,26 @@ export interface CanvasMutationContext extends CanvasEditConcurrency {/** The anchor that restores `layerId` between its current same-stack neighbours; null when absent. */captureRestoreAnchor(layerId: string): CanvasNodeInsertionAnchor | null;isGuardCurrent(guard: LayerExportGuard): boolean;+ createLayerId(): string;+ /** The newest history entry, for coalescing edits that amend it. */+ historyTop(): HistoryEntryToken | null;+ /** Unrecorded dispatch for previews and reconciliation. */dispatch(action: CanvasProjectMutation, origin?: CanvasMutationOrigin): boolean;- dispatchPrepared(- action: CanvasProjectMutation,- reducerAccepted: () => boolean,- mirrorAccepted: () => boolean,- origin?: CanvasMutationOrigin- ): void;+ /**+ * Admits an edit. `gesture` marks an edit that belongs to the interaction in progress (a live stroke, a float landing+ * as the user moves on), which an active gesture therefore neither refuses nor holds back.+ */+ begin(options: {+ readonly historyBytes: number;+ readonly owner?: symbol;+ readonly gesture?: boolean;+ }): EditTransaction | { status: EditRefusal };+ /** Applies a step with verified postconditions; throws {@link EditStepError} when it does not land. */+ applyStep(step: EditStep): void;+ /** Reserves raster bytes for a replay's preparation; null when they do not fit. */+ reserveRaster(bytes: number): { release(): void } | null;preparePixels(layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement;installPrepared(prepared: PreparedLayerCacheReplacement, persist?: boolean): void;- endBurst(): void;- createLayerId(): string;}/** Engine-side wiring for {@link createCanvasMutationContext}. */@@ -57,18 +138,28 @@ export interface CanvasMutationContextDeps {readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;- readonly endBurst: () => void;+ readonly reserveRaster: (bytes: number) => RasterMemoryReservationResult;readonly isGestureActive: () => boolean;readonly createLayerId: () => string;+ readonly report?: (error: EditStepError, label: string) => void;}+const runBestEffort = (notify: (() => void) | undefined): void => {+ try {+ notify?.();+ } catch {+ // The step is already accepted; a later render, dirty mark or store sync reconciles ancillary state.+ }+};+/**- * Owns edit-permit epochs and prepared-dispatch postconditions. The editing-lock subscription lasts until {@link- * dispose}; other services delegate to `deps`.+ * Owns edit-permit epochs and the transaction protocol. The editing-lock and reducer subscriptions last until+ * {@link dispose}.*/export const createCanvasMutationContext = (deps: CanvasMutationContextDeps): CanvasMutationContext & { dispose(): void } => {+ let disposed = false;let documentEditEpoch = 0;let documentEditingLocked = false;const syncDocumentEditingLock = (): void => {@@ -94,78 +185,216 @@ export const createCanvasMutationContext = (return editRevision;};const currentStacks = (): CanvasStackForests => deps.getDocument()?.stacks ?? EMPTY_STACKS;- const canEdit = (owner?: symbol): boolean => owner === deps.editOwner || !deps.editingLocked.get();+ const canEdit = (owner?: symbol): boolean =>+ !disposed && !deps.history.isReplaying() && (owner === deps.editOwner || !deps.editingLocked.get());const capturePermit = (owner?: symbol): DocumentEditPermit | null =>canEdit(owner) ? { epoch: documentEditEpoch, owner } : null;const isPermitCurrent = (permit: DocumentEditPermit): boolean =>- permit.owner === deps.editOwner || (!deps.editingLocked.get() && permit.epoch === documentEditEpoch);-- const dispatchPrepared = (- action: CanvasProjectMutation,- isApplied: () => boolean,- isMirrored: () => boolean,- origin: CanvasMutationOrigin = deps.history.isApplying() ? 'system' : 'user'- ): void => {+ !disposed &&+ !deps.history.isReplaying() &&+ (permit.owner === deps.editOwner || (!deps.editingLocked.get() && permit.epoch === documentEditEpoch));++ /** A postcondition that throws (a faulty state read) does not hold. */+ const holds = (check: () => boolean): boolean => {try {- // Prepared mutations are not route-worthy until both reducer and mirror- // postconditions succeed. Commit their edit intent separately below.- if (!deps.dispatch(action, 'system')) {- throw new Error('Canvas document mutation was rejected');- }- } catch (error) {- // Ignore observer throws only when authoritative reducer state proves the exact mutation landed, so matching- // engine state/history can publish. Preserve actual dispatch failures.- if (!isApplied()) {- throw error;+ return check();+ } catch {+ return false;+ }+ };+ const mirrored = (): boolean => holds(() => deps.getDocument() === deps.getReducerDocument());++ /** Re-runs the mirror subscriber when an interrupted notification left it behind the reducer. */+ const reconcileMirror = (): boolean => {+ if (mirrored()) {+ return true;+ }+ try {+ deps.refreshMirror();+ } catch {+ // Judged by the identity check below.+ }+ return mirrored();+ };++ const applyStep = (step: EditStep): void => {+ if (step.mutation) {+ const before = deps.getReducerDocument();+ const accepted = step.accepted ?? ((document) => document !== before);+ let dispatchError: unknown;+ try {+ deps.dispatch(step.mutation, 'system');+ } catch (error) {+ // An observer may throw after the reducer committed; the postconditions decide.+ dispatchError = error;}- // Notification may have been interrupted before DocumentMirror's- // subscriber ran. Reconcile it synchronously from authoritative state- // before publishing follow-up state or history.+ let reducerDocument: CanvasDocumentContractV3 | null | undefined;try {- deps.refreshMirror();- } catch (refreshError) {- if (!isMirrored()) {- throw refreshError;- }+ reducerDocument = deps.getReducerDocument();+ } catch {+ // Unreadable: neither rejected nor accepted, so the rollback decides.+ }+ const landed = reducerDocument !== undefined && holds(() => accepted(reducerDocument!));+ if (reducerDocument === before && !landed) {+ throw new EditStepError('rejected', { cause: dispatchError });}- if (!isMirrored()) {- throw error;+ if (!landed || !reconcileMirror()) {+ throw new EditStepError(rollBack(step, reducerDocument), { cause: dispatchError });}+ } else if (!reconcileMirror()) {+ throw new EditStepError('unreverted');}+ step.install?.();+ runBestEffort(step.notify);+ };- // A reducer may reject a guarded transaction by returning the unchanged- // state without throwing. Do not install its prepared cache or consume a- // failure-atomic history entry unless the authoritative postcondition- // actually landed.- if (!isApplied()) {- throw new Error('Canvas document mutation was rejected');+ /** Dispatches the step's rollback and reports how far the reducer and mirror returned. */+ const rollBack = (+ step: EditStep,+ /** The document the step left, or undefined when it could not be read. */+ failed: CanvasDocumentContractV3 | null | undefined+ ): 'reverted' | 'reverted-unmirrored' | 'unreverted' => {+ const { rollback } = step;+ if (!rollback) {+ return 'unreverted';}- if (!isMirrored()) {- try {- deps.refreshMirror();- } catch (refreshError) {- if (!isMirrored()) {- throw refreshError;- }- }- if (!isMirrored()) {- throw new Error('Canvas document mutation was not mirrored');- }+ try {+ deps.dispatch(rollback.mutation, 'system');+ } catch {+ // Judged by the restoration postcondition below.+ }+ const restored = holds(() => {+ const reducerDocument = deps.getReducerDocument();+ return reducerDocument !== failed && rollback.restored(reducerDocument);+ });+ if (!restored) {+ return 'unreverted';}+ return reconcileMirror() ? 'reverted' : 'reverted-unmirrored';+ };- if (origin === 'user') {- try {- deps.commitEdit({ kind: 'mutation', mutation: action });- } catch {- // Reducer and mirror acceptance are the transaction boundary. Routing- // the resulting edit intent is ancillary after that point; surfacing an- // observer failure would invite callers to roll back only their cache- // half and split it from the accepted document contract.- }+ const refusal = (owner?: symbol, gesture = false): EditRefusal | null => {+ if (disposed) {+ return 'not-ready';+ }+ if (!canEdit(owner)) {+ return 'busy';+ }+ if (!gesture && deps.isGestureActive()) {+ return 'gesture-active';}+ return deps.getReducerDocument() ? null : 'not-ready';+ };++ const begin = (options: {+ readonly historyBytes: number;+ readonly owner?: symbol;+ readonly gesture?: boolean;+ }): EditTransaction | { status: EditRefusal } => {+ const refused = refusal(options.owner, options.gesture);+ if (refused) {+ return { status: refused };+ }+ const permit: DocumentEditPermit = { epoch: documentEditEpoch, owner: options.owner };+ const admission = deps.history.admit(options.historyBytes);+ if (!admission) {+ return { status: 'over-budget' };+ }+ const held: { release(): void }[] = [admission];+ let ended = false;+ // An observer of the step may end the transaction mid-publication; its resources outlive that publication.+ let publishing = false;+ // A gesture's own edit may publish within it; any other waits until no gesture runs.+ const isCurrent = (): boolean =>+ !ended && isPermitCurrent(permit) && (options.gesture === true || !deps.isGestureActive());+ const release = (): void => {+ for (const resource of held.splice(0).reverse()) {+ try {+ resource.release();+ } catch {+ // Release every remaining resource regardless.+ }+ }+ };+ return {+ end: () => {+ if (ended) {+ return;+ }+ ended = true;+ if (!publishing) {+ release();+ }+ },+ growHistory: (bytes) => !ended && admission.grow(bytes),+ hold: (resource) => {+ if (ended) {+ resource.release();+ } else {+ held.push(resource);+ }+ return resource;+ },+ isCurrent,+ publish: (label, step, entry, publishOptions = {}) => {+ if (ended) {+ throw new Error('Canvas edit transaction has already ended.');+ }+ if (!isCurrent()) {+ return { status: refusal(options.owner) ?? 'busy' };+ }+ if (entry.bytes > admission.bytes && !admission.grow(entry.bytes - admission.bytes)) {+ return { status: 'over-budget' };+ }+ if (publishOptions.replacing !== undefined && deps.history.top() !== publishOptions.replacing) {+ return { status: 'busy' };+ }+ publishing = true;+ let token: HistoryEntryToken;+ try {+ applyStep({ ...step, notify: undefined });+ token = admission.publish({ ...entry, label }, publishOptions.replacing);+ } catch (error) {+ if (!(error instanceof EditStepError)) {+ throw error;+ }+ if (error.outcome === 'rejected') {+ return { status: 'dispatch-rejected' };+ }+ if (error.outcome !== 'reverted') {+ deps.report?.(error, label);+ }+ return { recovered: error.outcome, status: 'postcondition-failed' };+ } finally {+ publishing = false;+ if (ended) {+ release();+ }+ }+ const routed = publishOptions.routed ?? step.mutation;+ if (routed && (publishOptions.origin ?? 'user') === 'user') {+ runBestEffort(() => deps.commitEdit({ kind: 'mutation', mutation: routed }));+ }+ runBestEffort(step.notify);+ return { status: 'committed', token };+ },+ reserveRaster: (bytes) => {+ if (ended) {+ return false;+ }+ const reservation = deps.reserveRaster(bytes);+ if (reservation.status !== 'ok') {+ return false;+ }+ held.push(reservation.lease);+ return true;+ },+ };};return {+ applyStep,+ begin,canEdit,captureInsertionAnchor: (stack, aboveId) =>captureInsertionAnchor(currentStacks(), {@@ -179,21 +408,24 @@ export const createCanvasMutationContext = (captureRestoreAnchor(currentStacks(), layerId, deps.projectId, getEditRevision()),createLayerId: () => deps.createLayerId(),dispatch: (action, origin) => deps.dispatch(action, origin),- dispatchPrepared,dispose: () => {+ disposed = true;unsubscribeDocumentEditingLock();unsubscribeReducer();},- endBurst: () => deps.endBurst(),getDocument: () => deps.getDocument(),getEditRevision,getReducerDocument: () => deps.getReducerDocument(),- history: deps.history,+ historyTop: () => deps.history.top(),installPrepared: (prepared, persist) => deps.installPrepared(prepared, persist),isGestureActive: () => deps.isGestureActive(),isGuardCurrent: (guard) => deps.isGuardCurrent(guard),isPermitCurrent,- projectId: deps.projectId,preparePixels: (layerId, rect, pixels) => deps.preparePixels(layerId, rect, pixels),+ projectId: deps.projectId,+ reserveRaster: (bytes) => {+ const reservation = deps.reserveRaster(bytes);+ return reservation.status === 'ok' ? reservation.lease : null;+ },};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.tsindex c63639ef7c..6dabb3d10f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts@@ -4,22 +4,14 @@ import type {CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';-import type { DocumentEditPermit } from '@workbench/canvas-engine/editConcurrency';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';-import { EMPTY_STACKS, removeNodes } from '@workbench/canvas-engine/document/documentTree';-import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';-import { createTestEditConcurrency } from '@workbench/canvas-engine/editConcurrency.testStub';-import { createHistory } from '@workbench/canvas-engine/history/history';-import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';-import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';+import { createLayerOperationHarness } from './layerOperationHarness.testing';import { NewRasterLayerController } from './newRasterLayerController';const paintLayer = (id: string, transform: Partial<CanvasLayerContract['transform']> = {}): CanvasLayerContract => ({@@ -56,184 +48,153 @@ const createdRaster = (document: CanvasDocumentContractV3 | null, id: string): Cconst imageData = (width: number, height: number): ImageData =>({ colorSpace: 'srgb', data: new Uint8ClampedArray(width * height * 4), height, width }) as ImageData;+const RECT: Rect = { height: 10, width: 10, x: 5, y: 5 };+interface HarnessOptions {stacks?: CanvasStackForests;selectedLayerId?: string | null;maskRect?: Rect | null;cacheRect?: Rect;- permit?: DocumentEditPermit | null;gestureActive?: boolean;+ historyBytes?: number;}const createHarness = (options: HarnessOptions = {}) => {- const backend = createTestStubRasterBackend();- const layerCache = createLayerCacheStore(backend);- const history = createHistory();const stacks = options.stacks ?? stacksFrom([paintLayer('a')]);const selectedLayerId =options.selectedLayerId === undefined ? (stacks.raster[0]?.id ?? null) : options.selectedLayerId;- let document: CanvasDocumentContractV3 | null = makeDoc(stacks, selectedLayerId);-+ const h = createLayerOperationHarness(makeDoc(stacks, selectedLayerId), options);const maskRect = options.maskRect === undefined ? { height: 30, width: 30, x: 20, y: 20 } : options.maskRect;const mask: PlacedSurface | null = maskRect- ? { rect: maskRect, surface: backend.createSurface(maskRect.width, maskRect.height) }+ ? { rect: maskRect, surface: h.backend.createSurface(maskRect.width, maskRect.height) }: null;- const selection = { mask: () => mask } as SelectionState;-if (selectedLayerId) {- layerCache.getOrCreateRect(selectedLayerId, options.cacheRect ?? { height: 100, width: 100, x: 0, y: 0 });+ h.layers.getOrCreateRect(selectedLayerId, options.cacheRect ?? { height: 100, width: 100, x: 0, y: 0 });}-- const dispatched: CanvasProjectMutation[] = [];- const installed = vi.fn();- let nextId = 0;-const controller = new NewRasterLayerController({- backend,- captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.stacks ?? EMPTY_STACKS),- concurrency: createTestEditConcurrency({- capturePermit: () => (options.permit === undefined ? { epoch: 0 } : options.permit),- isGestureActive: () => options.gestureActive === true,- }),- createLayerId: () => `new-${(nextId += 1)}`,- dispatchPrepared: (action) => {- dispatched.push(action);- // Apply the local stack mutation so controller postconditions see the inserted layer.- if (action.type === 'applyCanvasLayerStackMutation' && document) {- let next = document.stacks;- for (const insertion of action.add ?? []) {- next = insertNodesAtAnchor(next, insertion.anchor, insertion.nodes);- }- if (action.removeIds) {- next = removeNodes(next, new Set(action.removeIds));- }- document = { ...document, selectedLayerId: action.selectedLayerId ?? null, stacks: next };- }- },- endBurst: vi.fn(),- getDocument: () => document,- getReducerDocument: () => document,- history,- installPrepared: installed,- layers: layerCache,- preparePixels: (layerId, rect) => ({ layerId, rect }) as never,- selection,+ backend: h.backend,+ ctx: h.ctx,+ layers: h.layers,+ selection: { mask: () => mask } as SelectionState,});-- return {- backend,- controller,- dispatched,- document: () => document,- history,- installed,- layerCache,- };+ const insert = () => controller.insert(RECT, h.backend.createSurface(10, 10), 'New', 'Insert');+ return { ...h, controller, insert };};+const leafIds = (document: CanvasDocumentContractV3 | null): string[] =>+ getDocumentLeaves(document).map((layer) => layer.id);+describe('NewRasterLayerController: insert', () => {- it('inserts a paint layer above the active one and selects it', () => {+ it('inserts a paint layer above the active one, selects it and installs its pixels', () => {const h = createHarness({stacks: stacksFrom([paintLayer('top'), paintLayer('bottom')]),selectedLayerId: 'bottom',});- const surface = h.backend.createSurface(10, 10);-- const result = h.controller.insert({ height: 10, width: 10, x: 5, y: 5 }, surface, 'New', 'Insert');- expect(result).toEqual({ layerId: 'new-1', status: 'created' });+ expect(h.insert()).toEqual({ layerId: 'new-1', status: 'created' });// Index 0 is top-most, so "above bottom" is bottom's own index.- expect(getDocumentLeaves(h.document()!).map((layer) => layer.id)).toEqual(['top', 'new-1', 'bottom']);- expect(h.document()!.selectedLayerId).toBe('new-1');- expect(h.installed).toHaveBeenCalledTimes(1);+ expect(leafIds(h.document())).toEqual(['top', 'new-1', 'bottom']);+ expect(h.document().selectedLayerId).toBe('new-1');+ expect(h.layers.get('new-1')?.rect).toEqual(RECT);+ expect(h.history.entries().past).toEqual(['Insert']);});it('places the pixels via the source offset, leaving the transform identity', () => {const h = createHarness();- const surface = h.backend.createSurface(10, 10);-- h.controller.insert({ height: 10, width: 10, x: 40, y: 60 }, surface, 'New', 'Insert');+ h.controller.insert({ height: 10, width: 10, x: 40, y: 60 }, h.backend.createSurface(10, 10), 'New', 'Insert');const created = createdRaster(h.document(), 'new-1');expect(created.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });expect(created.source).toMatchObject({ offset: { x: 40, y: 60 }, type: 'paint' });});- it('undo removes the layer and restores the previous selection', () => {- const h = createHarness({ stacks: stacksFrom([paintLayer('a')]), selectedLayerId: 'a' });- const surface = h.backend.createSurface(10, 10);+ it('undo removes the layer and restores the previous selection; redo reinstalls its pixels', async () => {+ const h = createHarness();+ h.insert();- h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert');- expect(h.history.canUndo()).toBe(true);+ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(leafIds(h.document())).toEqual(['a']);+ expect(h.document().selectedLayerId).toBe('a');- h.history.undo();- expect(getDocumentLeaves(h.document()!).map((layer) => layer.id)).toEqual(['a']);- expect(h.document()!.selectedLayerId).toBe('a');+ h.layers.delete('new-1');+ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(createdRaster(h.document(), 'new-1')).toBeDefined();+ expect(h.document().selectedLayerId).toBe('new-1');+ expect(h.layers.get('new-1')?.rect).toEqual(RECT);});- it('redo re-inserts the same layer', () => {+ it('refuses an edit it could never undo before anything changes', () => {+ const h = createHarness({ historyBytes: 100 });+ const before = h.document();++ expect(h.insert()).toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(before);+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ });++ it('refuses when its pixels cannot be reserved, leaving document and history untouched', () => {const h = createHarness();- const surface = h.backend.createSurface(10, 10);+ h.state.rasterBytes = 100;+ const before = h.document();- h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert');- h.history.undo();- h.history.redo();+ expect(h.insert()).toEqual({ status: 'over-budget' });+ expect(h.document()).toBe(before);+ expect(h.installed).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ expect(h.reservedBytes()).toBe(0);+ });- expect(getDocumentLeaves(h.document()!).some((layer) => layer.id === 'new-1')).toBe(true);- expect(h.document()!.selectedLayerId).toBe('new-1');+ it('keeps the step on the redo stack when its replay cannot reserve memory', async () => {+ const h = createHarness();+ h.insert();+ await h.history.undo();+ h.state.rasterBytes = 0;++ const result = await h.history.redo();+ expect(result.status).toBe('failed');+ expect(leafIds(h.document())).toEqual(['a']);+ expect(h.history.canRedo()).toBe(true);});- it('refuses an empty rect', () => {+ it('reports a reducer refusal as failed and records nothing', () => {const h = createHarness();- const surface = h.backend.createSurface(0, 0);- expect(h.controller.insert({ height: 0, width: 0, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({- status: 'empty',- });+ h.state.refuse = () => true;++ expect(h.insert()).toEqual({ status: 'failed' });+ expect(h.installed).toEqual([]);+ expect(h.history.canUndo()).toBe(false);});- it('refuses while the document edit lease is unavailable', () => {- const h = createHarness({ permit: null });- const surface = h.backend.createSurface(10, 10);- expect(h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({- status: 'busy',- });+ it('refuses an empty rect', () => {+ const h = createHarness();+ expect(+ h.controller.insert({ height: 0, width: 0, x: 0, y: 0 }, h.backend.createSurface(0, 0), 'New', 'Insert')+ ).toEqual({ status: 'empty' });});it('refuses mid-gesture', () => {- const h = createHarness({ gestureActive: true });- const surface = h.backend.createSurface(10, 10);- expect(h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({- status: 'busy',- });+ expect(createHarness({ gestureActive: true }).insert()).toEqual({ status: 'busy' });});it('refuses once disposed', () => {const h = createHarness();- const surface = h.backend.createSurface(10, 10);h.controller.dispose();- expect(h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({- status: 'busy',- });+ expect(h.insert()).toEqual({ status: 'not-ready' });});});describe('NewRasterLayerController: pasteImage', () => {it('centres the pasted pixels on the given point', () => {const h = createHarness();-h.controller.pasteImage(imageData(20, 10), 'Pasted', 'Paste', { x: 50, y: 50 });-- const created = createdRaster(h.document(), 'new-1');- expect(created.source).toMatchObject({ offset: { x: 40, y: 45 } });+ expect(createdRaster(h.document(), 'new-1').source).toMatchObject({ offset: { x: 40, y: 45 } });});it('places at the origin with no centre given', () => {const h = createHarness();-h.controller.pasteImage(imageData(20, 10), 'Pasted', 'Paste');-- const created = createdRaster(h.document(), 'new-1');- expect(created.source).toMatchObject({ offset: { x: 0, y: 0 } });+ expect(createdRaster(h.document(), 'new-1').source).toMatchObject({ offset: { x: 0, y: 0 } });});it('refuses zero-sized pixels', () => {@@ -245,28 +206,24 @@ describe('NewRasterLayerController: pasteImage', () => {describe('NewRasterLayerController: liftSelectionToLayer', () => {it('creates a layer covering the selection ∩ content region', () => {const h = createHarness();-- const result = h.controller.liftSelectionToLayer('Selection', 'Layer via copy');-- expect(result).toEqual({ layerId: 'new-1', status: 'created' });- const created = createdRaster(h.document(), 'new-1');- expect(created.source).toMatchObject({ offset: { x: 20, y: 20 } });+ expect(h.controller.liftSelectionToLayer('Selection', 'Layer via copy')).toEqual({+ layerId: 'new-1',+ status: 'created',+ });+ expect(createdRaster(h.document(), 'new-1').source).toMatchObject({ offset: { x: 20, y: 20 } });});it('leaves the source layer untouched — it is a copy, not a cut', () => {const h = createHarness();- const before = h.layerCache.get('a')!.version;-+ const before = h.layers.get('a')!.version;h.controller.liftSelectionToLayer('Selection', 'Layer via copy');-- expect(h.layerCache.get('a')!.version).toBe(before);+ expect(h.layers.get('a')!.version).toBe(before);});it('bakes the source layer transform into the new layer placement', () => {// The copy comes out layer-local; a new layer lives in document space, so a// translated source must shift where the pixels land.const h = createHarness({ stacks: stacksFrom([paintLayer('a', { x: 10, y: 5 })]) });-h.controller.liftSelectionToLayer('Selection', 'Layer via copy');const created = createdRaster(h.document(), 'new-1');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.tsindex 2eabcec7d4..0636481f1e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts@@ -1,146 +1,217 @@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';-import type {- CanvasEditConcurrency,- CanvasTransactionOutcome,- SubsetOf,-} from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';+import type { CanvasTransactionOutcome, SubsetOf } from '@workbench/canvas-engine/editConcurrency';+import type { HeldAssetRefs } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import type { LayerCacheStore, PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';+import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { Rect, Vec2 } from '@workbench/canvas-engine/types';import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';+import type {+ CanvasMutationContext,+ EditPublishResult,+ EditRefusal,+ EditStep,+ EditTransaction,+} from './mutationContext';++/** A refused admission as its caller reports it; a gesture in progress reads as contention. */+export type LayerEditRefusal = SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'over-budget'>;++/** How a layer operation's publication ended; a reducer refusal or failed postcondition applied nothing. */+export type LayerEditStatus = 'committed' | LayerEditRefusal | 'failed';++export const layerEditRefusal = (status: EditRefusal): LayerEditRefusal =>+ status === 'gesture-active' ? 'busy' : status;++export const layerEditStatus = (result: EditPublishResult): LayerEditStatus => {+ switch (result.status) {+ case 'committed':+ return 'committed';+ case 'dispatch-rejected':+ case 'postcondition-failed':+ return 'failed';+ default:+ return layerEditRefusal(result.status);+ }+};++export const rgbaBytes = (rect: Rect): number => Math.max(0, rect.width) * Math.max(0, rect.height) * 4;++export type ReplayContext = Pick<CanvasMutationContext, 'reserveRaster'>;++/** Runs a replay's preparation under a raster reservation; a replay that does not fit throws and stays in place. */+export const withReplayReservation = <T>(ctx: ReplayContext, bytes: number, run: () => T): T => {+ const lease = ctx.reserveRaster(bytes);+ if (!lease) {+ throw new Error('Not enough raster memory to replay this step.');+ }+ try {+ return run();+ } finally {+ lease.release();+ }+};++type EnabledUpdates = readonly { readonly id: string; readonly isEnabled: boolean }[];++/** A new paint layer whose pixels the undo entry owns, inserted and selected in one step. */+export interface AddedRasterLayerEdit {+ readonly label: string;+ /** A raster paint layer whose source offset places `pixels` at `rect`. */+ readonly layer: CanvasLayerContract;+ readonly rect: Rect;+ readonly pixels: RasterSurface;+ readonly anchor: CanvasNodeInsertionAnchor;+ /** The selection undo restores. */+ readonly selectedLayerId: string | null;+ /** Enabled flags the edit sets on other layers, and the values undo restores. */+ readonly enabled?: { readonly before: EnabledUpdates; readonly after: EnabledUpdates };+ readonly heldAssetRefs?: HeldAssetRefs;+}++export type AddedLayerContext = Pick<CanvasMutationContext, 'applyStep' | 'installPrepared' | 'preparePixels'> &+ ReplayContext;++/** Bytes an {@link AddedRasterLayerEdit} entry retains. */+export const addedLayerHistoryBytes = (rect: Rect): number => rgbaBytes(rect) + HISTORY_ENTRY_OVERHEAD_BYTES;++/**+ * Inserts the layer with its prepared pixels as one undo step. The cache replacement is reserved and prepared+ * before the document changes; replays prepare again under their own reservation.+ */+export const publishAddedRasterLayer = (+ ctx: AddedLayerContext,+ txn: EditTransaction,+ edit: AddedRasterLayerEdit+): EditPublishResult => {+ const { anchor, layer, pixels, rect, selectedLayerId } = edit;+ const after = edit.enabled?.after ?? [];+ const before = edit.enabled?.before ?? [];+ const forward: CanvasProjectMutation = {+ add: [{ anchor, nodes: [layer] }],+ enabledUpdates: after,+ selectedLayerId: layer.id,+ type: 'applyCanvasLayerStackMutation',+ };+ const inverse: CanvasProjectMutation = {+ enabledUpdates: before,+ removeIds: [layer.id],+ selectedLayerId,+ type: 'applyCanvasLayerStackMutation',+ };+ const hasEnabled = (document: CanvasDocumentContractV3 | null, updates: EnabledUpdates): boolean =>+ updates.every((update) => getDocumentLayer(document, update.id)?.isEnabled === update.isEnabled);+ const added = (document: CanvasDocumentContractV3 | null): boolean =>+ document?.selectedLayerId === layer.id &&+ getDocumentLayer(document, layer.id) === layer &&+ hasEnabled(document, after);+ const removed = (document: CanvasDocumentContractV3 | null): boolean =>+ document !== null &&+ document.selectedLayerId === selectedLayerId &&+ isNodeAbsent(document, layer.id) &&+ hasEnabled(document, before);+ const addStep = (): EditStep => {+ const prepared = ctx.preparePixels(layer.id, rect, pixels);+ return {+ accepted: added,+ install: () => ctx.installPrepared(prepared),+ mutation: forward,+ rollback: { mutation: inverse, restored: removed },+ };+ };+ if (!txn.reserveRaster(rgbaBytes(rect))) {+ return { status: 'over-budget' };+ }+ return txn.publish(edit.label, addStep(), {+ bytes: addedLayerHistoryBytes(rect),+ heldAssetRefs: edit.heldAssetRefs ?? collectHistoryMediaRefs(layer),+ redo: () => withReplayReservation(ctx, rgbaBytes(rect), () => ctx.applyStep(addStep())),+ undo: () =>+ ctx.applyStep({ accepted: removed, mutation: inverse, rollback: { mutation: forward, restored: added } }),+ });+};++/** A raster paint layer placing pixels at `rect` with an identity transform. */+export const paintLayerAt = (id: string, name: string, rect: Rect): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name,+ opacity: 1,+ source: { bitmap: null, offset: { x: rect.x, y: rect.y }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+});+export type NewRasterLayerResult =| { status: 'created'; layerId: string }- | { status: SubsetOf<CanvasTransactionOutcome, 'busy'> | SubsetOf<CanvasCommandRefusal, 'missing'> | 'empty' };+ | { status: LayerEditRefusal | SubsetOf<CanvasCommandRefusal, 'missing'> | 'empty' | 'failed' };export interface NewRasterLayerControllerOptions {- readonly concurrency: CanvasEditConcurrency;+ readonly ctx: AddedLayerContext &+ Pick<CanvasMutationContext, 'begin' | 'captureInsertionAnchor' | 'createLayerId' | 'getDocument'>;readonly backend: RasterBackend;readonly layers: LayerCacheStore;readonly selection: SelectionState;- readonly history: History;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly getReducerDocument: () => CanvasDocumentContractV3 | null;- readonly endBurst: () => void;- readonly createLayerId: () => string;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- expectedReducer: () => boolean,- expectedMirror: () => boolean- ) => void;}-/**- * Shared undoable insertion for Paste and Layer via Copy. Acquire a permit, verify reducer/mirror postconditions,- * install the prepared cache, then record failure-atomic history with the same redo path. Insert above and select- * the active layer's new sibling.- */+/** Shared undoable insertion for Paste and Layer via Copy, inserted above and selecting the active layer. */export class NewRasterLayerController {private disposed = false;constructor(private readonly deps: NewRasterLayerControllerOptions) {}/**- * Inserts `pixels` as a new paint layer covering `rect` (document space).- * `pixels` is consumed as-is — the caller owns getting it into document space.+ * Inserts `pixels` as a new paint layer covering `rect` (document space). The undo entry takes ownership of+ * `pixels`; the caller owns getting it into document space.*/insert(rect: Rect, pixels: RasterSurface, name: string, label: string): NewRasterLayerResult {- const permit = this.deps.concurrency.capturePermit();- if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {- return { status: 'busy' };+ const { ctx } = this.deps;+ if (this.disposed) {+ return { status: 'not-ready' };}- const document = this.deps.getDocument();+ const document = ctx.getDocument();if (!document) {return { status: 'missing' };}if (isEmpty(rect)) {return { status: 'empty' };}- this.deps.endBurst();-- const layerId = this.deps.createLayerId();- // Place pixels with the source offset, leaving the transform at identity for ordinary move, transform and- // float handling.- const layer: CanvasLayerContract = {- blendMode: 'normal',- id: layerId,- isEnabled: true,- isLocked: false,- name,- opacity: 1,- source: { bitmap: null, offset: { x: rect.x, y: rect.y }, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };-- const anchor = this.deps.captureInsertionAnchor('raster', document.selectedLayerId);- const previousSelectedLayerId = document.selectedLayerId;-- const apply = (): void => {- const prepared = this.deps.preparePixels(layerId, rect, pixels);- this.deps.dispatchPrepared(- {- add: [{ anchor, nodes: [layer] }],- enabledUpdates: [],- selectedLayerId: layerId,- type: 'applyCanvasLayerStackMutation',- },- () =>- this.deps.getReducerDocument()?.selectedLayerId === layerId &&- getDocumentLayer(this.deps.getReducerDocument(), layer.id) === layer,- () =>- this.deps.getDocument()?.selectedLayerId === layerId &&- getDocumentLayer(this.deps.getDocument(), layer.id) === layer+ const txn = ctx.begin({ historyBytes: addedLayerHistoryBytes(rect) });+ if (!('publish' in txn)) {+ return { status: layerEditRefusal(txn.status) };+ }+ try {+ const layer = paintLayerAt(ctx.createLayerId(), name, rect);+ const status = layerEditStatus(+ publishAddedRasterLayer(ctx, txn, {+ anchor: ctx.captureInsertionAnchor('raster', document.selectedLayerId),+ label,+ layer,+ pixels,+ rect,+ selectedLayerId: document.selectedLayerId,+ }));- this.deps.installPrepared(prepared);- };-- if (!this.deps.concurrency.isPermitCurrent(permit)) {- return { status: 'busy' };+ return status === 'committed' ? { layerId: layer.id, status: 'created' } : { status };+ } finally {+ txn.end();}- apply();- this.deps.history.push({- bytes: rect.width * rect.height * 4 + 256,- heldAssetRefs: collectHistoryMediaRefs(layer),- label,- redo: apply,- replayFailureAtomic: true,- undo: () =>- this.deps.dispatchPrepared(- {- enabledUpdates: [],- removeIds: [layerId],- selectedLayerId: previousSelectedLayerId,- type: 'applyCanvasLayerStackMutation',- },- () =>- this.deps.getReducerDocument()?.selectedLayerId === previousSelectedLayerId &&- isNodeAbsent(this.deps.getReducerDocument(), layerId),- () =>- this.deps.getDocument()?.selectedLayerId === previousSelectedLayerId &&- isNodeAbsent(this.deps.getDocument(), layerId)- ),- });- return { layerId, status: 'created' };}- /** Copies selected pixels into a new layer above the active layer without changing the source. */+ /** Copies selected pixels into a new layer above the active one without changing the source. */liftSelectionToLayer(name: string, label: string): NewRasterLayerResult {- const document = this.deps.getDocument();+ const document = this.deps.ctx.getDocument();const layer = getDocumentLayer(document, document?.selectedLayerId);const mask = this.deps.selection.mask();const entry = layer ? this.deps.layers.get(layer.id) : undefined;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.tsindex 9b16db6d26..8fa441c3e2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts@@ -50,6 +50,26 @@ const publish = (controller: RasterController, layerId: string) => {};describe('RasterController', () => {+ it("shares a live cache's adjusted copy with export, never a detached copy's or baked pixels'", () => {+ let baked = false;+ const controller = new RasterController({+ backend: createTestStubRasterBackend(),+ diagnostics: createCanvasDiagnostics(true),+ isAdjustmentBaked: () => baked,+ });+ const entry = publish(controller, 'layer');+ const { adjustments } = adjustedLayer('layer');++ const shared = controller.getAdjustedCacheSurface('layer', entry.surface, adjustments!);+ expect(shared).not.toBeNull();+ expect(shared).toBe(controller.getAdjustedSurface(adjustedLayer('layer'), entry));+ expect(+ controller.getAdjustedCacheSurface('layer', createTestStubRasterBackend().createSurface(1, 1), adjustments!)+ ).toBeNull();+ baked = true;+ expect(controller.getAdjustedCacheSurface('layer', entry.surface, adjustments!)).toBeNull();+ });+it('accounts base, derived and group surfaces as they are allocated and released', () => {const controller = createController(10_000);const entry = publish(controller, 'a');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.tsindex bffafc59f0..d2d966c5ce 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts@@ -1,4 +1,5 @@import type {+ CanvasAdjustmentsContract,CanvasDocumentContractV3,CanvasImageRef,CanvasLayerContract,@@ -41,7 +42,6 @@ export interface RasterControllerOptions {readonly budgetBytes?: number;readonly onVersionChange?: (layerId: string) => void;readonly getDocument?: () => CanvasDocumentContractV3 | null;- readonly getLayerImageName?: (layer: CanvasLayerContract) => string | null;readonly imageResolver?: (imageName: string, signal?: AbortSignal) => Promise<Blob>;/** Layers whose live pixels nothing else can reconstruct: unpersisted paint and open edit sessions. */readonly isLayerHeld?: (layerId: string) => boolean;@@ -73,13 +73,10 @@ export class RasterController {private readonly isAdjustmentBaked: (layerId: string) => boolean;private readonly jobs = new Map<string, RasterizationJob>();private readonly activeJobs = new Set<RasterizationJob>();- private readonly trackedImages = new Map<string, string>();- private readonly mirroredImages = new Map<string, string>();private readonly thumbnailKeys = new Map<string, string>();private documentGeneration = 0;private disposed = false;private readonly getDocument: () => CanvasDocumentContractV3 | null;- private readonly getLayerImageName: (layer: CanvasLayerContract) => string | null;private readonly backend: RasterBackend;private readonly imageResolver: ((imageName: string, signal?: AbortSignal) => Promise<Blob>) | null;@@ -96,7 +93,6 @@ export class RasterController {onVersionChange: options.onVersionChange,});this.getDocument = options.getDocument ?? (() => null);- this.getLayerImageName = options.getLayerImageName ?? (() => null);this.imageResolver = options.imageResolver ?? null;this.derived = createDerivedSurfaceCache(options.diagnostics, (bytes) => memory.setCategoryBytes('derived', bytes));this.adjustments = createAdjustedSurfaceCache(options.backend, this.derived, (layerId, version) =>@@ -234,6 +230,18 @@ export class RasterController {: null;}+ /** The memoized adjusted copy of a layer's live cache, when `surface` is that cache and its pixels are unbaked. */+ getAdjustedCacheSurface(+ layerId: string,+ surface: RasterSurface,+ adjustments: CanvasAdjustmentsContract+ ): RasterSurface | null {+ const entry = this.layers.peek(layerId);+ return entry?.surface === surface && !this.isAdjustmentBaked(layerId)+ ? this.adjustments.get(layerId, entry, adjustments)+ : null;+ }+deleteDerivedSurfaces(layerId: string): void {this.adjustments.delete(layerId);this.derived.deleteLayer(layerId);@@ -290,41 +298,6 @@ export class RasterController {return false;}- getTrackedImage(layerId: string): string | undefined {- return this.trackedImages.get(layerId);- }- setTrackedImage(layerId: string, imageName: string): void {- this.trackedImages.set(layerId, imageName);- }- deleteTrackedImage(layerId: string): void {- this.trackedImages.delete(layerId);- }- trackedImageIds(): string[] {- return [...this.trackedImages.keys()];- }- hasTrackedImage(imageName: string): boolean {- return [...this.trackedImages.values()].includes(imageName);- }- clearTrackedImages(): void {- this.trackedImages.clear();- }-- getMirroredImage(layerId: string): string | undefined {- return this.mirroredImages.get(layerId);- }- setMirroredImage(layerId: string, imageName: string): void {- this.mirroredImages.set(layerId, imageName);- }- deleteMirroredImage(layerId: string): void {- this.mirroredImages.delete(layerId);- }- mirroredImageNames(): string[] {- return [...this.mirroredImages.values()];- }- clearMirroredImages(): void {- this.mirroredImages.clear();- }-getThumbnailKey(layerId: string): string | undefined {return this.thumbnailKeys.get(layerId);}@@ -338,37 +311,8 @@ export class RasterController {this.thumbnailKeys.clear();}- releaseBitmapIfUnreferenced(imageName: string): void {- // Leases close decoded bitmaps after the final rasterizer releases them; this hook also supports tracking- // callers.- void imageName;- }-- untrackLayerImage(layerId: string): void {- const imageName = this.getTrackedImage(layerId);- if (!imageName) {- return;- }- this.deleteTrackedImage(layerId);- this.releaseBitmapIfUnreferenced(imageName);- }-- trackPublishedLayerImage(layer: CanvasLayerContract): void {- const previous = this.getTrackedImage(layer.id);- const current = this.getLayerImageName(layer);- if (current) {- this.setTrackedImage(layer.id, current);- } else {- this.deleteTrackedImage(layer.id);- }- if (previous && previous !== current) {- this.releaseBitmapIfUnreferenced(previous);- }- }-dropLayer(layerId: string): void {this.cancelRasterization(layerId);- this.untrackLayerImage(layerId);this.layers.delete(layerId);this.deleteDerivedSurfaces(layerId);}@@ -379,8 +323,6 @@ export class RasterController {}this.disposed = true;this.cancelAllRasterization();- this.clearTrackedImages();- this.clearMirroredImages();this.clearThumbnailKeys();this.layers.dispose();this.derived.dispose();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.test.tsnew file mode 100644index 0000000000..9886b9c732--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.test.ts@@ -0,0 +1,99 @@+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';++import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { describe, expect, it } from 'vitest';++import { createLayerOperationHarness } from './layerOperationHarness.testing';+import { RasterizeLayerController } from './rasterizeLayerController';++const shapeLayer: CanvasLayerContract = {+ blendMode: 'normal',+ id: 'shape',+ isEnabled: true,+ isLocked: false,+ name: 'Shape',+ opacity: 1,+ source: { fill: '#000', height: 40, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 60 },+ transform: { rotation: 0, scaleX: 2, scaleY: 1, x: 10, y: 20 },+ type: 'raster',+};++const createHarness = (historyBytes?: number) => {+ const document: CanvasDocumentContractV3 = {+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ selectedLayerId: 'shape',+ stacks: stacksFrom([shapeLayer]),+ version: 3,+ width: 100,+ };+ const h = createLayerOperationHarness(document, { historyBytes });+ const controller = new RasterizeLayerController({+ backend: h.backend,+ ctx: h.ctx,+ rasterizeDeps: () => ({+ backend: h.backend,+ documentSize: { height: 100, width: 100 },+ resolver: () => Promise.reject(new Error('shapes need no images')),+ store: h.layers,+ }),+ });+ return { ...h, controller };+};++const BAKED_RECT = { height: 40, width: 120, x: 10, y: 20 };++describe('RasterizeLayerController', () => {+ it('bakes source and transform into paint pixels as one undo step', () => {+ const h = createHarness();++ expect(h.controller.rasterize('shape')).toBe('rasterized');+ expect(getDocumentLayer(h.document(), 'shape')).toMatchObject({+ source: { bitmap: null, offset: { x: 10, y: 20 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ });+ expect(h.layers.get('shape')?.rect).toEqual(BAKED_RECT);+ expect(h.history.entries().past).toEqual(['Rasterize layer']);+ });++ it('undo restores the parametric layer; redo reinstalls the same baked pixels without rerendering', async () => {+ const h = createHarness();+ h.controller.rasterize('shape');+ const baked = h.installed[0]!;++ await expect(h.history.undo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLayer(h.document(), 'shape')).toEqual(shapeLayer);++ await expect(h.history.redo()).resolves.toEqual({ status: 'applied' });+ expect(getDocumentLayer(h.document(), 'shape')).toMatchObject({ source: { type: 'paint' } });+ expect(h.installed).toHaveLength(2);+ expect(h.installed[1]!.rect).toEqual(baked.rect);+ });++ it('refuses a conversion it could never undo, leaving the layer parametric', () => {+ const h = createHarness(1024);+ const before = h.document();++ expect(h.controller.rasterize('shape')).toBe('over-budget');+ expect(h.document()).toBe(before);+ expect(h.dispatched).toEqual([]);+ });++ it('reports a refused conversion as failed and installs nothing', () => {+ const h = createHarness();+ h.state.refuse = () => true;++ expect(h.controller.rasterize('shape')).toBe('failed');+ expect(h.installed).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ });++ it('refuses missing, locked and already-painted layers', () => {+ const h = createHarness();+ expect(h.controller.rasterize('nope')).toBe('missing');+ h.controller.rasterize('shape');+ expect(h.controller.rasterize('shape')).toBe('unsupported');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.tsindex de009f5921..7a5312da0a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterizeLayerController.ts@@ -1,29 +1,41 @@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { History } from '@workbench/canvas-engine/history/history';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';-import type { RasterBackend } from '@workbench/canvas-engine/render/raster';+import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';+import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';+import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';+import type { Rect } from '@workbench/canvas-engine/types';+import { areJsonValuesStructurallyEqual } from '@platform/core/json';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { getSourceContentRect, isEmptyPolygonShape } from '@workbench/canvas-engine/document/sources';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { rasterizeSource } from '@workbench/canvas-engine/render/rasterizers';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';+import type { CanvasMutationContext, EditStep } from './mutationContext';++import {+ layerEditRefusal,+ layerEditStatus,+ rgbaBytes,+ withReplayReservation,+ type LayerEditRefusal,+} from './newRasterLayerController';++export type RasterizeLayerResult =+ | 'rasterized'+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'locked' | 'unsupported'>+ | LayerEditRefusal+ | 'failed';+export interface RasterizeLayerControllerOptions {+ readonly ctx: Pick<+ CanvasMutationContext,+ 'applyStep' | 'begin' | 'getDocument' | 'installPrepared' | 'preparePixels' | 'reserveRaster'+ >;readonly backend: RasterBackend;- readonly layers: LayerCacheStore;- readonly history: History;- readonly getDocument: () => CanvasDocumentContractV3 | null;readonly rasterizeDeps: (document: CanvasDocumentContractV3) => RasterizeDeps;- readonly dispatch: (action: CanvasProjectMutation) => void;- readonly canEdit: () => boolean;- readonly isGestureActive: () => boolean;- readonly endBurst: () => void;- readonly notifyPainted: (layerId: string) => void;- readonly markDirty: (layerId: string) => void;}/** Owns conversion of parametric raster layers into persisted paint pixels. */@@ -32,39 +44,47 @@ export class RasterizeLayerController {constructor(private readonly deps: RasterizeLayerControllerOptions) {}- rasterize(layerId: string): boolean {- if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {- return false;+ /**+ * Bakes the layer's source and transform into paint pixels as one undo step. Undo restores the parametric+ * contract, which rerasterizes from its source; redo reinstalls the baked pixels, never a rerender.+ */+ rasterize(layerId: string): RasterizeLayerResult {+ const { ctx } = this.deps;+ if (this.disposed) {+ return 'not-ready';}- this.deps.endBurst();- const document = this.deps.getDocument();+ const document = ctx.getDocument();const layer = getDocumentLayer(document, layerId);- if (!document || !layer || layer.type !== 'raster' || layer.isLocked) {- return false;+ if (!document || !layer) {+ return 'missing';+ }+ if (layer.isLocked) {+ return 'locked';+ }+ if (layer.type !== 'raster') {+ return 'unsupported';}const source = layer.source;if ((source.type !== 'shape' && source.type !== 'gradient' && source.type !== 'text') ||(source.type === 'shape' && isEmptyPolygonShape(source))) {- return false;+ return 'unsupported';}- const parametricLayer: CanvasLayerContract = structuredClone(layer);- const apply = (): void => {- const liveDocument = this.deps.getDocument();- const liveLayer = getDocumentLayer(liveDocument, layerId);- if (!liveDocument || !liveLayer || liveLayer.type !== 'raster') {- return;- }- const liveSource = liveLayer.source;- if (liveSource.type !== 'shape' && liveSource.type !== 'gradient' && liveSource.type !== 'text') {- return;+ const contentRect = getSourceContentRect(layer, document);+ const matrix = bakeMatrix(layer.transform);+ const bakedRect = roundOut(transformBounds(matrix, contentRect));+ const txn = ctx.begin({ historyBytes: rgbaBytes(bakedRect) + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ return layerEditRefusal(txn.status);+ }+ try {+ // The source render, the baked pixels the entry keeps, and their prepared cache replacement.+ if (!txn.reserveRaster(rgbaBytes(contentRect) + rgbaBytes(bakedRect) * 2)) {+ return 'over-budget';}- const contentRect = getSourceContentRect(liveLayer, liveDocument);const scratch = this.deps.backend.createSurface(contentRect.width, contentRect.height);- void rasterizeSource(liveSource, this.deps.rasterizeDeps(liveDocument), scratch);- const matrix = bakeMatrix(liveLayer.transform);- const bakedRect = roundOut(transformBounds(matrix, contentRect));+ void rasterizeSource(source, this.deps.rasterizeDeps(document), scratch);const baked = this.deps.backend.createSurface(bakedRect.width, bakedRect.height);baked.ctx.setTransform(1, 0, 0, 1, 0, 0);baked.ctx.clearRect(0, 0, bakedRect.width, bakedRect.height);@@ -72,32 +92,54 @@ export class RasterizeLayerController {baked.ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - bakedRect.x, matrix.f - bakedRect.y);baked.ctx.drawImage(scratch.canvas, contentRect.x, contentRect.y);baked.ctx.setTransform(1, 0, 0, 1, 0, 0);- const paintLayer: CanvasLayerContract = {- ...liveLayer,+ const parametric = structuredClone(layer);+ const paint: CanvasLayerContract = {+ ...parametric,source: { bitmap: null, offset: { x: bakedRect.x, y: bakedRect.y }, type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },};- this.deps.dispatch({ id: layerId, layer: paintLayer, targetType: 'raster', type: 'convertCanvasLayer' });- this.deps.layers.delete(layerId);- const target = this.deps.layers.getOrCreateRect(layerId, bakedRect);- target.surface.ctx.drawImage(baked.canvas, 0, 0);- target.stale = false;- this.deps.notifyPainted(layerId);- this.deps.markDirty(layerId);- };- apply();- this.deps.history.push({- bytes: 256,- heldAssetRefs: collectHistoryMediaRefs(parametricLayer),- label: 'Rasterize layer',- redo: apply,- undo: () =>- this.deps.dispatch({ id: layerId, layer: parametricLayer, targetType: 'raster', type: 'convertCanvasLayer' }),- });- return true;+ const status = layerEditStatus(+ txn.publish('Rasterize layer', this.convertStep(layerId, paint, parametric, bakedRect, baked), {+ bytes: rgbaBytes(bakedRect) + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(parametric),+ redo: () =>+ withReplayReservation(ctx, rgbaBytes(bakedRect), () =>+ ctx.applyStep(this.convertStep(layerId, paint, parametric, bakedRect, baked))+ ),+ undo: () => ctx.applyStep(this.convertStep(layerId, parametric, paint)),+ })+ );+ return status === 'committed' ? 'rasterized' : status;+ } finally {+ txn.end();+ }}dispose(): void {this.disposed = true;}++ /** Converts the layer to `target`, installing `pixels` with it; a failed conversion converts back to `previous`. */+ private convertStep(+ layerId: string,+ target: CanvasLayerContract,+ previous: CanvasLayerContract,+ rect?: Rect,+ pixels?: RasterSurface+ ): EditStep {+ const { ctx } = this.deps;+ const prepared = rect && pixels ? ctx.preparePixels(layerId, rect, pixels) : null;+ // Conversion clones the contract, so it is matched by value.+ const holds = (contract: CanvasLayerContract) => (document: CanvasDocumentContractV3 | null) =>+ areJsonValuesStructurallyEqual(getDocumentLayer(document, layerId), contract);+ return {+ accepted: holds(target),+ install: prepared ? () => ctx.installPrepared(prepared) : undefined,+ mutation: { id: layerId, layer: target, targetType: 'raster', type: 'convertCanvasLayer' },+ rollback: {+ mutation: { id: layerId, layer: previous, targetType: 'raster', type: 'convertCanvasLayer' },+ restored: holds(previous),+ },+ };+ }}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.tsindex a24cba5799..f0d281dfe9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts@@ -1,6 +1,9 @@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';+import type { Rect } from '@workbench/canvas-engine/types';+import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -9,110 +12,159 @@ import { describe, expect, it, vi } from 'vitest';import { SelectionPixelController } from './selectionPixelController';-describe('SelectionPixelController', () => {- it('owns raster fill persistence and history through declared ports', () => {- const backend = createTestStubRasterBackend();- const layers = createLayerCacheStore(backend);- layers.getOrCreateRect('paint', { height: 2, width: 2, x: 0, y: 0 });- const mask = backend.createSurface(2, 2);- mask.ctx.fillStyle = '#fff';- mask.ctx.fillRect(0, 0, 2, 2);- const selection = {- bounds: () => ({ height: 2, width: 2, x: 0, y: 0 }),- mask: () => ({ rect: { height: 2, width: 2, x: 0, y: 0 }, surface: mask }),- } as unknown as SelectionState;- const document = {- stacks: stacksFrom([- {- id: 'paint',- isEnabled: true,- isLocked: false,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- source: { type: 'paint' },- type: 'raster',- } as unknown as CanvasLayerContract,- ]),- selectedLayerId: 'paint',- } as CanvasDocumentContractV3;- const history = createHistory();- const markDirty = vi.fn();- const notifyPainted = vi.fn();- const controller = new SelectionPixelController({- applyImagePatch: vi.fn(),- backend,- beginPixelEdit: () => null,- canEdit: () => true,- deleteDerived: vi.fn(),- endBurst: vi.fn(),- getDocument: () => document,- getFillColor: () => '#f00',- history,- invalidateLayer: vi.fn(),- isRasterCacheReady: () => true,- isGestureActive: () => false,- layers,- markDirty,- notifyPainted,- requestRasterization: vi.fn(),- selection,+const paintDocument = (source: Record<string, unknown> = { type: 'paint' }): CanvasDocumentContractV3 =>+ ({+ stacks: stacksFrom([+ {+ id: 'paint',+ isEnabled: true,+ isLocked: false,+ source,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ } as unknown as CanvasLayerContract,+ ]),+ selectedLayerId: 'paint',+ }) as CanvasDocumentContractV3;++const createHarness = (+ options: {+ document?: CanvasDocumentContractV3;+ cacheRect?: Rect | null;+ selectionRect?: Rect;+ byteBudget?: number;+ mirrored?: boolean;+ cacheReady?: boolean;+ } = {}+) => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const cacheRect = options.cacheRect === undefined ? { height: 2, width: 2, x: 0, y: 0 } : options.cacheRect;+ if (cacheRect) {+ const { ctx } = layers.getOrCreateRect('paint', cacheRect).surface;+ // Stub readbacks are constant; number them so a fill's before and after differ.+ const read = ctx.getImageData.bind(ctx);+ let reads = 0;+ Object.defineProperty(ctx, 'getImageData', {+ value: (...args: Parameters<typeof read>) => {+ const pixels = read(...args);+ pixels.data[0] = reads++;+ return pixels;+ },});+ }+ const selectionRect = options.selectionRect ?? { height: 2, width: 2, x: 0, y: 0 };+ const mask = backend.createSurface(selectionRect.width, selectionRect.height);+ const selection = {+ bounds: () => selectionRect,+ mask: () => ({ rect: selectionRect, surface: mask }),+ } as unknown as SelectionState;+ const document = options.document ?? paintDocument();+ // A mirror that never follows the reducer fails every publication's postconditions.+ const reducerDocument = options.mirrored === false ? { ...document } : document;+ const history = createHistory({ byteBudget: options.byteBudget });+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch: () => true,+ editOwner: Symbol('owner'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => document,+ getReducerDocument: () => reducerDocument,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => false,+ isGuardCurrent: () => true,+ preparePixels: () => {+ throw new Error('unused');+ },+ projectId: 'p',+ refreshMirror: () => undefined,+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),+ subscribeReducer: () => () => undefined,+ });+ const calls = {+ deleteDerived: vi.fn(),+ markDirty: vi.fn(),+ notifyPainted: vi.fn(),+ reportRefusal: vi.fn(),+ requestRasterization: vi.fn(),+ };+ const controller = new SelectionPixelController({+ applyImagePatch: vi.fn(() => Promise.resolve()),+ backend,+ beginPixelEdit: () => null,+ canEdit: () => true,+ ctx,+ deleteDerived: calls.deleteDerived,+ getDocument: () => document,+ getFillColor: () => '#f00',+ invalidateLayer: vi.fn(),+ isGestureActive: () => false,+ isRasterCacheReady: () => options.cacheReady ?? true,+ layers,+ markDirty: calls.markDirty,+ notifyPainted: calls.notifyPainted,+ reportRefusal: calls.reportRefusal,+ requestRasterization: calls.requestRasterization,+ selection,+ });+ return { calls, controller, history, layers };+};- controller.run('fill');+describe('SelectionPixelController', () => {+ it('records a raster fill as one step and persists it', () => {+ const h = createHarness();++ h.controller.run('fill');- expect(markDirty).toHaveBeenCalledWith('paint');- expect(notifyPainted).toHaveBeenCalledWith('paint');- expect(history.canUndo()).toBe(true);+ expect(h.calls.markDirty).toHaveBeenCalledWith('paint');+ expect(h.calls.notifyPainted).toHaveBeenCalledWith('paint');+ expect(h.history.entries().past).toEqual(['Fill selection']);+ // Before and after of the touched 2×2 region only.+ expect(h.history.byteSize()).toBe(2 * 2 * 4 * 2);});it('requests durable paint pixels instead of growing a transparent fill cache', () => {- const backend = createTestStubRasterBackend();- const layers = createLayerCacheStore(backend);- const mask = backend.createSurface(2, 2);- const selection = {- bounds: () => ({ height: 2, width: 2, x: 0, y: 0 }),- mask: () => ({ rect: { height: 2, width: 2, x: 0, y: 0 }, surface: mask }),- } as unknown as SelectionState;- const document = {- stacks: stacksFrom([- {- id: 'paint',- isEnabled: true,- isLocked: false,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- source: { bitmap: { height: 2, imageName: 'durable', width: 2 }, type: 'paint' },- type: 'raster',- } as unknown as CanvasLayerContract,- ]),- selectedLayerId: 'paint',- } as CanvasDocumentContractV3;- const markDirty = vi.fn();- const requestRasterization = vi.fn();- const history = createHistory();- const controller = new SelectionPixelController({- applyImagePatch: vi.fn(),- backend,- beginPixelEdit: () => null,- canEdit: () => true,- deleteDerived: vi.fn(),- endBurst: vi.fn(),- getDocument: () => document,- getFillColor: () => '#f00',- history,- invalidateLayer: vi.fn(),- isGestureActive: () => false,- isRasterCacheReady: () => false,- layers,- markDirty,- notifyPainted: vi.fn(),- requestRasterization,- selection,+ const h = createHarness({+ cacheReady: false,+ cacheRect: null,+ document: paintDocument({ bitmap: { height: 2, imageName: 'durable', width: 2 }, type: 'paint' }),});- controller.run('fill');+ h.controller.run('fill');++ expect(h.calls.requestRasterization).toHaveBeenCalledWith('paint');+ expect(h.layers.peek('paint')).toBeUndefined();+ expect(h.calls.markDirty).not.toHaveBeenCalled();+ expect(h.history.canUndo()).toBe(false);+ });++ it('refuses a fill too large to undo before touching the cache', () => {+ const h = createHarness({ byteBudget: 10, selectionRect: { height: 4, width: 4, x: -1, y: -1 } });+ const version = h.layers.version('paint');++ h.controller.run('fill');++ expect(h.calls.reportRefusal).toHaveBeenCalledWith('over-budget');+ expect(h.layers.get('paint')!.rect).toEqual({ height: 2, width: 2, x: 0, y: 0 });+ expect(h.layers.version('paint')).toBe(version);+ expect(h.calls.markDirty).not.toHaveBeenCalled();+ expect(h.history.canUndo()).toBe(false);+ });++ it('restores the touched region and the original extent when the fill cannot be published', () => {+ const h = createHarness({ mirrored: false, selectionRect: { height: 4, width: 4, x: -1, y: -1 } });+ const surface = h.layers.get('paint')!.surface as StubRasterSurface;++ h.controller.run('fill');- expect(requestRasterization).toHaveBeenCalledWith('paint');- expect(layers.peek('paint')).toBeUndefined();- expect(markDirty).not.toHaveBeenCalled();- expect(history.canUndo()).toBe(false);+ expect(h.layers.get('paint')!.rect).toEqual({ height: 2, width: 2, x: 0, y: 0 });+ // The before pixels went back over the whole touched (grown) region before the crop.+ const restored = surface.callLog.filter((entry) => entry.op === 'putImageData').at(-1);+ expect(restored?.args.slice(1, 3)).toEqual([0, 0]);+ expect(h.calls.deleteDerived).toHaveBeenCalledWith('paint');+ expect(h.calls.markDirty).not.toHaveBeenCalled();+ expect(h.history.canUndo()).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.tsindex 83186fe396..5a553e2687 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts@@ -1,8 +1,8 @@+import type { CanvasEditRefusal } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { History } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';-import type { LayerCacheEntryState, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';-import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { PixelEditTransaction } from '@workbench/canvas-engine/tools/tool';import type { Rect } from '@workbench/canvas-engine/types';@@ -15,6 +15,8 @@ import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatimport { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';import { eraseMaskedRegion, fillMaskedRegion } from '@workbench/canvas-engine/selection/selectionOps';+import type { CanvasMutationContext, EditTransaction } from './mutationContext';+type PixelTarget =| { kind: 'raster'; layerId: string; transparencyLocked: boolean }| { kind: 'control'; transaction: PixelEditTransaction; transparencyLocked: false };@@ -23,14 +25,14 @@ export interface SelectionPixelControllerOptions {readonly selection: SelectionState;readonly backend: RasterBackend;readonly layers: LayerCacheStore;- readonly history: History;+ readonly ctx: Pick<CanvasMutationContext, 'begin'>;+ readonly reportRefusal: (refusal: CanvasEditRefusal) => void;readonly applyImagePatch: ImagePatchApply;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly beginPixelEdit: (layerId: string) => PixelEditTransaction | null;readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;readonly getFillColor: () => string;- readonly endBurst: () => void;readonly deleteDerived: (layerId: string) => void;readonly invalidateLayer: (layerId: string) => void;readonly isRasterCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;@@ -105,102 +107,84 @@ export class SelectionPixelController {if (!target) {return;}- const cancelControl = (): void => {- if (target.kind === 'control') {- target.transaction.cancel();- }- };if (kind === 'erase' && target.transparencyLocked) {- cancelControl();return;}- const layerId = target.kind === 'control' ? target.transaction.layerId : target.layerId;+ if (target.kind === 'control') {+ this.edit(kind, target.transaction.layerId, target, selectionRect, placedMask);+ return;+ }+ const txn = this.deps.ctx.begin({ historyBytes: 0 });+ if (!('publish' in txn)) {+ this.deps.reportRefusal(txn.status);+ return;+ }+ try {+ this.edit(kind, target.layerId, { ...target, txn }, selectionRect, placedMask);+ } finally {+ txn.end();+ }+ }++ /**+ * Fills or erases the selection on one target. Only the touched region is captured: it is admitted before any+ * pixel changes, and a refused or failed publication restores it and the cache's original extent.+ */+ private edit(+ kind: 'fill' | 'erase',+ layerId: string,+ target:+ | Exclude<PixelTarget, { kind: 'raster' }>+ | (Extract<PixelTarget, { kind: 'raster' }> & { txn: EditTransaction }),+ selectionRect: Rect,+ placedMask: NonNullable<ReturnType<SelectionState['mask']>>+ ): void {+ const { deps } = this;+ const live = target.kind === 'control' ? target.transaction : null;+ const existing = deps.layers.get(layerId);+ const grows = kind === 'fill' && !target.transparencyLocked;+ const rect = grows+ ? selectionRect+ : existing && !isEmpty(existing.rect)+ ? intersect(selectionRect, existing.rect)+ : null;+ if (!rect || isEmpty(rect)) {+ live?.cancel();+ return;+ }+ const footprint = rect.width * rect.height * 8;+ if (!(live ? live.grow(footprint) : target.kind === 'raster' && target.txn.growHistory(footprint))) {+ if (!live) {+ deps.reportRefusal('over-budget');+ }+ live?.cancel();+ return;+ }+ const originalRect = existing ? { ...existing.rect } : null;let before: ImageData | null = null;- let editOrigin: { x: number; y: number } | null = null;- let editRect: Rect | null = null;- let editSurface: RasterSurface | null = null;- let commitStarted = false;- let rollbackStarted = false;- let growthSnapshot: { pixels: ImageData | null; state: LayerCacheEntryState } | null | undefined;const rollback = (): void => {- if (target.kind !== 'control' || rollbackStarted) {- return;+ const entry = deps.layers.get(layerId);+ if (entry && before) {+ entry.surface.ctx.putImageData(before, rect.x - entry.rect.x, rect.y - entry.rect.y);}- rollbackStarted = true;- try {- if (growthSnapshot !== undefined) {- if (growthSnapshot) {- const { pixels, state } = growthSnapshot;- state.surface.resize(state.rect.width, state.rect.height);- if (pixels) {- state.surface.ctx.putImageData(pixels, 0, 0);- }- }- // An exact rollback; the store re-accounts the reinstated surface.- this.deps.layers.restoreState(layerId, growthSnapshot?.state ?? null);- this.deps.deleteDerived(layerId);- this.deps.invalidateLayer(layerId);- } else if (before && editOrigin && editRect && editSurface) {- editSurface.ctx.putImageData(before, editRect.x - editOrigin.x, editRect.y - editOrigin.y);- this.deps.deleteDerived(layerId);- this.deps.invalidateLayer(layerId);- }- } finally {- target.transaction.cancel();+ if (!originalRect) {+ deps.layers.delete(layerId);+ } else {+ deps.layers.shrinkToRect(layerId, originalRect);}+ deps.deleteDerived(layerId);+ deps.invalidateLayer(layerId);};+ let published = false;try {- if (target.kind === 'control' && kind === 'fill') {- const existing = this.deps.layers.get(layerId);- const needsGrowth =- !existing ||- isEmpty(existing.rect) ||- selectionRect.x < existing.rect.x ||- selectionRect.y < existing.rect.y ||- selectionRect.x + selectionRect.width > existing.rect.x + existing.rect.width ||- selectionRect.y + selectionRect.height > existing.rect.y + existing.rect.height;- if (needsGrowth) {- const state = this.deps.layers.captureState(layerId);- growthSnapshot =- existing && state- ? {- pixels: isEmpty(existing.rect)- ? null- : existing.surface.ctx.getImageData(0, 0, existing.rect.width, existing.rect.height),- state,- }- : null;- }- }- let rect: Rect | null;- let entry;- if (kind === 'fill' && !target.transparencyLocked) {- rect = selectionRect;- entry = this.deps.layers.growToRect(layerId, selectionRect);- } else {- const existing = this.deps.layers.get(layerId);- if (!existing || isEmpty(existing.rect)) {- cancelControl();- return;- }- rect = intersect(selectionRect, existing.rect);- entry = existing;- }- if (!rect || isEmpty(rect)) {- cancelControl();- return;- }- this.deps.endBurst();+ const entry = grows ? deps.layers.growToRect(layerId, rect) : existing!;const surface = entry.surface;const origin = { x: entry.rect.x, y: entry.rect.y };before = surface.ctx.getImageData(rect.x - origin.x, rect.y - origin.y, rect.width, rect.height);- editOrigin = origin;- editRect = rect;- editSurface = surface;if (kind === 'fill') {fillMaskedRegion({- backend: this.deps.backend,- color: this.deps.getFillColor(),+ backend: deps.backend,+ color: deps.getFillColor(),composite: target.transparencyLocked ? 'source-atop' : 'source-over',mask: placedMask.surface,maskOrigin: placedMask.rect,@@ -210,7 +194,7 @@ export class SelectionPixelController {});} else {eraseMaskedRegion({- backend: this.deps.backend,+ backend: deps.backend,mask: placedMask.surface,maskOrigin: placedMask.rect,rect,@@ -220,35 +204,36 @@ export class SelectionPixelController {}const after = surface.ctx.getImageData(rect.x - origin.x, rect.y - origin.y, rect.width, rect.height);const label = kind === 'fill' ? 'Fill selection' : 'Erase selection';- if (target.kind === 'control') {- if (imageDataEqual(before, after)) {+ if (live) {+ published = live.commitPatch(label, { after, before, rect });+ return;+ }+ if (target.kind !== 'raster' || imageDataEqual(before, after)) {+ return;+ }+ const result = target.txn.publish(+ label,+ {+ notify: () => {+ deps.notifyPainted(layerId);+ deps.markDirty(layerId);+ },+ },+ createImagePatchEntry({ after, apply: deps.applyImagePatch, before, label, layerId, rect }),+ { origin: 'system' }+ );+ if (result.status === 'over-budget') {+ deps.reportRefusal('over-budget');+ }+ published = result.status === 'committed';+ } finally {+ if (!published) {+ try {rollback();- return;- }- commitStarted = true;- target.transaction.commitPatch(label, { after, before, rect });- } else {- this.deps.notifyPainted(target.layerId);- this.deps.markDirty(target.layerId);- if (!this.deps.history.isApplying()) {- this.deps.history.push(- createImagePatchEntry({- after,- apply: this.deps.applyImagePatch,- before,- label,- layerId: target.layerId,- rect,- })- );+ } finally {+ live?.cancel();}}- } catch (error) {- if (target.kind !== 'control' || commitStarted) {- throw error;- }- rollback();- throw error;}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.tsindex 0dbaf3420f..dc2c045f1d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.integration.test.ts@@ -81,7 +81,7 @@ describe('staged result project-port integration', () => {engine.lifecycle.dispose();});- it('banks a disabled layer without changing the staged session or current layer selection', () => {+ it('banks a disabled layer without changing the staged session or current layer selection', async () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;const currentLayerId = store.getState().projects[0]!.canvas.document.selectedLayerId;@@ -110,11 +110,11 @@ describe('staged result project-port integration', () => {expect(projectAfterSave.canvas.stagingArea.pendingImages).toEqual([candidate]);expect(projectAfterSave.canvas.stagingArea.isVisible).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(store.getState().projects[0]!.canvas.document)).not.toContain(savedLayer);expect(store.getState().projects[0]!.canvas.stagingArea).toBe(stagedBefore);- engine.history.redo();+ await engine.history.redo();expect(store.getState().projects[0]!.canvas.document.stacks.raster[0]).toBe(savedLayer);expect(store.getState().projects[0]!.canvas.document.selectedLayerId).toBe(currentLayerId);expect(store.getState().projects[0]!.canvas.stagingArea).toBe(stagedBefore);@@ -149,7 +149,7 @@ describe('staged result project-port integration', () => {});- it('compensates a reducer-accepted undo when mirror acceptance fails and keeps history retryable', () => {+ it('reconciles the mirror when state reads fail transiently during an undo', async () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;store.commands.canvas.appendStagingCandidate({ candidate, projectId });@@ -166,15 +166,16 @@ describe('staged result project-port integration', () => {const accepted = structuredClone(store.getState().projects.find((project) => project.id === projectId)!);rejectingPort.arm('applyCanvasLayerStackMutation');- expect(() => engine.history.undo()).toThrow('document mirror read failed');- expect(store.getState().projects.find((project) => project.id === projectId)).toEqual(accepted);- expect(engine.document.getDocument()).toEqual(accepted.canvas.document);- expect(engine.stores.canUndo.get()).toBe(true);- expect(engine.stores.canRedo.get()).toBe(false);+ expect(await engine.history.undo()).toBe('applied');+ const undone = store.getState().projects.find((project) => project.id === projectId)!;+ expect(undone.canvas.document).not.toEqual(accepted.canvas.document);+ expect(engine.document.getDocument()).toBe(undone.canvas.document);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(engine.stores.canRedo.get()).toBe(true);engine.lifecycle.dispose();});- it('compensates a reducer-accepted redo when mirror acceptance fails and keeps history retryable', () => {+ it('reconciles the mirror when state reads fail transiently during a redo', async () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;store.commands.canvas.appendStagingCandidate({ candidate, projectId });@@ -188,15 +189,16 @@ describe('staged result project-port integration', () => {reportError: () => undefined,});expect(engine.layers.commitStagedImage(selection).status).toBe('committed');- engine.history.undo();+ await engine.history.undo();const undone = structuredClone(store.getState().projects.find((project) => project.id === projectId)!);rejectingPort.arm('applyCanvasLayerStackMutation');- expect(() => engine.history.redo()).toThrow('document mirror read failed');- expect(store.getState().projects.find((project) => project.id === projectId)).toEqual(undone);- expect(engine.document.getDocument()).toEqual(undone.canvas.document);- expect(engine.stores.canUndo.get()).toBe(false);- expect(engine.stores.canRedo.get()).toBe(true);+ expect(await engine.history.redo()).toBe('applied');+ const redone = store.getState().projects.find((project) => project.id === projectId)!;+ expect(redone.canvas.document).not.toEqual(undone.canvas.document);+ expect(engine.document.getDocument()).toBe(redone.canvas.document);+ expect(engine.stores.canUndo.get()).toBe(true);+ expect(engine.stores.canRedo.get()).toBe(false);engine.lifecycle.dispose();});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.tsindex b0dc9ae842..d6d30b2b19 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts@@ -1,15 +1,14 @@-import type { CanvasStagingCandidateContract, CanvasStateContractV3 } from '@workbench/canvas-engine/contracts';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';+import type { Project } from '@workbench/projectContracts';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';-import { removeNodes } from '@workbench/canvas-engine/document/documentTree';-import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';-import { createTestEditConcurrency } from '@workbench/canvas-engine/editConcurrency.testStub';+import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { createHistory, NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';+import { createCanvasMutationContext } from './mutationContext';import { StagedResultController } from './stagedResultController';const candidate: CanvasStagingCandidateContract = {@@ -24,280 +23,208 @@ const candidate: CanvasStagingCandidateContract = {};const selection = { candidate, selectedImageIndex: 0 } as const;-const makeCanvas = (): CanvasStateContractV3 => ({- document: {- background: 'transparent',- bbox: { height: 100, width: 100, x: 0, y: 0 },- height: 100,- stacks: stacksFrom([]),- selectedLayerId: null,- version: 3,- width: 100,- },- documentRevision: 0,- snapshots: [],- stagingArea: {- areThumbnailsVisible: false,- autoSwitchMode: 'off',- isVisible: true,- pendingImageIds: [candidate.imageName],- pendingImages: [candidate],- selectedImageIndex: 0,- },- version: 3,-});+interface HarnessOptions {+ readonly byteBudget?: number;+ readonly gestureActive?: boolean;+ readonly locked?: boolean;+ /** The reducer keeps the project unchanged, as when the candidate moved on. */+ readonly rejectDispatch?: boolean;+ /** Mirror refresh fails, so an accepted mutation can never be mirrored. */+ readonly mirrorBroken?: boolean;+ readonly staged?: boolean;+}++/** A real reducer, history and transaction protocol around the controller; the mirror follows the reducer. */+const createHarness = (options: HarnessOptions = {}) => {+ const base = createInitialWorkbenchState().projects[0]!;+ let project: Project = {+ ...base,+ canvas: {+ ...base.canvas,+ stagingArea: {+ ...base.canvas.stagingArea,+ isVisible: true,+ pendingImageIds: options.staged === false ? [] : [candidate.imageName],+ pendingImages: options.staged === false ? [] : [candidate],+ selectedImageIndex: 0,+ },+ },+ };+ let mirrorBroken = options.mirrorBroken ?? false;+ let mirrorDocument = project.canvas.document;+ const dispatched: CanvasProjectMutation[] = [];+ const listeners = new Set<() => void>();+ const history = createHistory({ byteBudget: options.byteBudget });+ const dispatch = (mutation: CanvasProjectMutation): boolean => {+ dispatched.push(mutation);+ if (options.rejectDispatch) {+ return false;+ }+ const next = applyCanvasProjectMutation(project, mutation);+ const changed = next !== project;+ project = next;+ if (!mirrorBroken) {+ mirrorDocument = project.canvas.document;+ }+ listeners.forEach((listener) => listener());+ return changed;+ };+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'layer-1',+ dispatch,+ editOwner: Symbol('owner'),+ editingLocked: { get: () => options.locked ?? false, subscribe: () => () => undefined },+ getDocument: () => mirrorDocument,+ getReducerDocument: () => project.canvas.document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => options.gestureActive ?? false,+ isGuardCurrent: () => true,+ preparePixels: () => ({}) as never,+ projectId: base.id,+ refreshMirror: () => {+ if (mirrorBroken) {+ throw new Error('mirror broken');+ }+ mirrorDocument = project.canvas.document;+ },+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),+ subscribeReducer: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ });+ const controller = new StagedResultController({+ createEventId: () => 'event-1',+ ctx,+ getCanvasState: () => project.canvas,+ now: () => '2026-07-16T01:00:00.000Z',+ });+ return {+ breakMirror: (broken: boolean) => {+ mirrorBroken = broken;+ },+ controller,+ dispatched,+ history,+ project: () => project,+ };+};describe('StagedResultController', () => {- it('commits the guarded candidate and records history only after reducer and mirror acceptance', () => {- let reducerCanvas = makeCanvas();- let mirrorDocument = reducerCanvas.document;- const history = createHistory();- const dispatchPrepared = vi.fn(- (mutation: CanvasProjectMutation, reducerAccepted: () => boolean, mirrorAccepted: () => boolean) => {- if (mutation.type === 'applyCanvasLayerStackMutation') {- reducerCanvas = {- ...reducerCanvas,- document: {- ...reducerCanvas.document,- stacks: mutation.removeIds- ? removeNodes(reducerCanvas.document.stacks, new Set(mutation.removeIds))- : (mutation.add ?? []).reduce(- (stacks, insertion) => insertNodesAtAnchor(stacks, insertion.anchor, insertion.nodes),- reducerCanvas.document.stacks- ),- selectedLayerId:- mutation.selectedLayerId === undefined- ? reducerCanvas.document.selectedLayerId- : mutation.selectedLayerId,- },- };- expect(reducerAccepted()).toBe(true);- expect(mirrorAccepted()).toBe(false);- mirrorDocument = reducerCanvas.document;- expect(mirrorAccepted()).toBe(true);- return;- }- expect(mutation).toMatchObject({ selectedImageIndex: 0, type: 'commitStagedImage' });- if (mutation.type !== 'commitStagedImage') {- throw new Error('unexpected mutation');- }- const layer = mutation.layer;- reducerCanvas = {- ...reducerCanvas,- document: { ...reducerCanvas.document, stacks: stacksFrom([layer]), selectedLayerId: layer.id },- stagingArea: { ...reducerCanvas.stagingArea, isVisible: false, pendingImageIds: [], pendingImages: [] },- };- mirrorDocument = reducerCanvas.document;- expect(reducerAccepted()).toBe(true);- expect(mirrorAccepted()).toBe(true);- }- );- const controller = new StagedResultController({- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),- createEventId: () => 'event-1',- createLayerId: () => 'layer-1',- dispatchPrepared,- endBurst: vi.fn(),- getCanvasState: () => reducerCanvas,- getDocument: () => mirrorDocument,- history,- now: () => '2026-07-16T01:00:00.000Z',- });+ it('commits the selected candidate as one undo step that replays both ways', async () => {+ const h = createHarness();+ const initial = h.project().canvas.document;- expect(controller.commit(selection)).toEqual({ status: 'committed', layerId: 'layer-1' });- expect(getDocumentLeaves(reducerCanvas.document)[0]).toMatchObject({+ expect(h.controller.commit(selection)).toEqual({ layerId: 'layer-1', status: 'committed' });+ expect(getDocumentLayer(h.project().canvas.document, 'layer-1')).toMatchObject({id: 'layer-1',opacity: 0.5,source: { image: { imageName: 'result.png' }, type: 'image' },transform: { scaleX: 2, scaleY: 2, x: 12, y: 18 },type: 'raster',});- expect(history.canUndo()).toBe(true);+ expect(h.project().canvas.stagingArea.pendingImages).toEqual([]);- history.undo();- expect(getDocumentLeaves(reducerCanvas.document)).toEqual([]);- expect(reducerCanvas.document.selectedLayerId).toBeNull();- expect(reducerCanvas.stagingArea.pendingImages).toEqual([]);+ expect(await h.history.undo()).toEqual({ status: 'applied' });+ expect(getDocumentLeaves(h.project().canvas.document)).toEqual(getDocumentLeaves(initial));+ expect(h.project().canvas.document.selectedLayerId).toBe(initial.selectedLayerId);+ expect(h.project().canvas.stagingArea.pendingImages).toEqual([]);- history.redo();- expect(getDocumentLeaves(reducerCanvas.document)[0]).toBe(getDocumentLeaves(reducerCanvas.document)[0]);- expect(getDocumentLeaves(reducerCanvas.document)[0]?.id).toBe('layer-1');- expect(reducerCanvas.stagingArea.pendingImages).toEqual([]);+ expect(await h.history.redo()).toEqual({ status: 'applied' });+ expect(getDocumentLayer(h.project().canvas.document, 'layer-1')).not.toBeNull();+ expect(h.project().canvas.document.selectedLayerId).toBe('layer-1');});- it('returns stale without history when the selected candidate changes before reducer acceptance', () => {- const canvas = makeCanvas();- const history = createHistory();- const controller = new StagedResultController({- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),- createEventId: () => 'event-1',- createLayerId: () => 'layer-1',- dispatchPrepared: () => {- throw new Error('reducer rejected stale candidate');- },- endBurst: vi.fn(),- getCanvasState: () => canvas,- getDocument: () => canvas.document,- history,- now: () => '2026-07-16T01:00:00.000Z',- });+ it('returns stale without history when the reducer leaves the project unchanged', () => {+ const h = createHarness({ rejectDispatch: true });++ expect(h.controller.commit(selection)).toEqual({ status: 'stale' });+ expect(h.project().canvas.stagingArea.pendingImages).toEqual([candidate]);+ expect(h.history.canUndo()).toBe(false);+ });++ it('rolls the accepted commit back when the mirror cannot follow it', () => {+ const h = createHarness({ mirrorBroken: true });+ const before = h.project().canvas;- expect(controller.commit(selection)).toEqual({ status: 'stale' });- expect(getDocumentLeaves(canvas.document)).toEqual([]);- expect(canvas.stagingArea.pendingImages).toEqual([candidate]);- expect(history.canUndo()).toBe(false);+ expect(h.controller.commit(selection)).toEqual({ status: 'stale' });+ expect(getDocumentLeaves(h.project().canvas.document)).toEqual(getDocumentLeaves(before.document));+ expect(h.project().canvas.stagingArea).toBe(before.stagingArea);+ expect(h.dispatched.map((mutation) => mutation.type)).toEqual(['commitStagedImage', 'rollbackStagedImageCommit']);+ expect(h.history.canUndo()).toBe(false);});it.each([- { gestureActive: false, name: 'edit lease is unavailable', permit: null, permitCurrent: false },- { gestureActive: true, name: 'a gesture is active', permit: { epoch: 1 }, permitCurrent: true },- { gestureActive: false, name: 'the captured edit permit is stale', permit: { epoch: 1 }, permitCurrent: false },- ])('returns busy without mutation when $name', ({ gestureActive, permit, permitCurrent }) => {- const canvas = makeCanvas();- const dispatchPrepared = vi.fn();- const history = createHistory();- const controller = new StagedResultController({- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- concurrency: createTestEditConcurrency({- capturePermit: () => permit,- isGestureActive: () => gestureActive,- isPermitCurrent: () => permitCurrent,- }),- createEventId: () => 'event-1',- createLayerId: () => 'layer-1',- dispatchPrepared,- endBurst: vi.fn(),- getCanvasState: () => canvas,- getDocument: () => canvas.document,- history,- now: () => '2026-07-16T01:00:00.000Z',- });+ { name: 'editing is locked', options: { locked: true } },+ { name: 'a gesture is active', options: { gestureActive: true } },+ ])('returns busy without mutation when $name', ({ options }) => {+ const h = createHarness(options);++ expect(h.controller.commit(selection)).toEqual({ status: 'busy' });+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);+ });- expect(controller.commit(selection)).toEqual({ status: 'busy' });- expect(dispatchPrepared).not.toHaveBeenCalled();- expect(history.canUndo()).toBe(false);+ it('refuses before mutating when history could never retain the step', () => {+ const h = createHarness({ byteBudget: 16 });++ expect(h.controller.commit(selection)).toEqual({ status: 'over-budget' });+ expect(h.dispatched).toEqual([]);+ expect(h.project().canvas.stagingArea.pendingImages).toEqual([candidate]);});- it.each(['reducer', 'mirror'])('does not record history when %s acceptance rejects the commit', () => {- const canvas = makeCanvas();- const history = createHistory();- const controller = new StagedResultController({- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),- createEventId: () => 'event-1',- createLayerId: () => 'layer-1',- dispatchPrepared: () => {- throw new Error('acceptance rejected');- },- endBurst: vi.fn(),- getCanvasState: () => canvas,- getDocument: () => canvas.document,- history,- now: () => '2026-07-16T01:00:00.000Z',- });+ it('keeps a failed undo on the stack with the document unchanged', async () => {+ const h = createHarness();+ h.controller.commit(selection);+ const committed = getDocumentLeaves(h.project().canvas.document);+ h.breakMirror(true);- expect(controller.commit(selection)).toEqual({ status: 'stale' });- expect(canvas.stagingArea.pendingImages).toEqual([candidate]);- expect(history.canUndo()).toBe(false);+ expect((await h.history.undo()).status).toBe('failed');+ expect(h.history.canUndo()).toBe(true);+ expect(h.history.canRedo()).toBe(false);+ expect(getDocumentLeaves(h.project().canvas.document)).toEqual(committed);});- it('clears the redo stack after a new staged image commit', () => {- let reducerCanvas = makeCanvas();- let mirrorDocument = reducerCanvas.document;- const history = createHistory();- history.push({ bytes: 1, heldAssetRefs: NO_HELD_ASSET_REFS, label: 'older edit', redo: vi.fn(), undo: vi.fn() });- history.undo();- expect(history.canRedo()).toBe(true);- const controller = new StagedResultController({- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),- createEventId: () => 'event-1',- createLayerId: () => 'layer-1',- dispatchPrepared: (mutation, reducerAccepted, mirrorAccepted) => {- if (mutation.type !== 'commitStagedImage') {- throw new Error('unexpected mutation');- }- reducerCanvas = {- ...reducerCanvas,- document: {- ...reducerCanvas.document,- stacks: stacksFrom([mutation.layer]),- selectedLayerId: mutation.layer.id,- },- stagingArea: {- ...reducerCanvas.stagingArea,- isVisible: false,- pendingImageIds: [],- pendingImages: [],- selectedImageIndex: 0,- },- };- expect(reducerAccepted()).toBe(true);- mirrorDocument = reducerCanvas.document;- expect(mirrorAccepted()).toBe(true);- },- endBurst: vi.fn(),- getCanvasState: () => reducerCanvas,- getDocument: () => mirrorDocument,- history,- now: () => '2026-07-16T01:00:00.000Z',- });+ it('clears the redo stack after a new staged image commit', async () => {+ const h = createHarness();+ h.history+ .admit(1)!+ .publish({ bytes: 1, heldAssetRefs: NO_HELD_ASSET_REFS, label: 'older edit', redo: vi.fn(), undo: vi.fn() });+ await h.history.undo();+ expect(h.history.canRedo()).toBe(true);- expect(controller.commit(selection).status).toBe('committed');- expect(history.canRedo()).toBe(false);+ expect(h.controller.commit(selection).status).toBe('committed');+ expect(h.history.canRedo()).toBe(false);});it.each([- { canvas: null, name: 'project', options: selection },- {- canvas: makeCanvas(),- name: 'candidate',- options: { candidate: { ...candidate, imageName: 'missing.png' }, selectedImageIndex: 0 },- },- ])('returns missing without mutation when the $name is absent', ({ canvas, options }) => {- const dispatchPrepared = vi.fn();- const history = createHistory();- const controller = new StagedResultController({- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),- createEventId: () => 'event-1',- createLayerId: () => 'layer-1',- dispatchPrepared,- endBurst: vi.fn(),- getCanvasState: () => canvas,- getDocument: () => canvas?.document ?? null,- history,- now: () => '2026-07-16T01:00:00.000Z',- });+ ['edits are locked', { locked: true }],+ ['a gesture is active', { gestureActive: true }],+ ])('refuses without mutating staging or history while %s', (_, options) => {+ const h = createHarness(options);+ const before = h.project();++ expect(h.controller.commit(selection).status).not.toBe('committed');+ expect(h.dispatched).toEqual([]);+ expect(h.project()).toBe(before);+ expect(h.history.canUndo()).toBe(false);+ });- expect(controller.commit(options)).toEqual({ status: 'missing' });- expect(dispatchPrepared).not.toHaveBeenCalled();- expect(history.canUndo()).toBe(false);+ it('returns missing without mutation when the candidate is no longer staged', () => {+ const h = createHarness({ staged: false });++ expect(h.controller.commit(selection)).toEqual({ status: 'missing' });+ expect(h.dispatched).toEqual([]);});it('rejects retained commit capabilities after disposal', () => {- const canvas = makeCanvas();- const dispatchPrepared = vi.fn();- const history = createHistory();- const controller = new StagedResultController({- captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),- createEventId: () => 'event-1',- createLayerId: () => 'layer-1',- dispatchPrepared,- endBurst: vi.fn(),- getCanvasState: () => canvas,- getDocument: () => canvas.document,- history,- now: () => '2026-07-16T01:00:00.000Z',- });-- controller.dispose();+ const h = createHarness();+ h.controller.dispose();- expect(controller.commit(selection)).toEqual({ status: 'missing' });- expect(dispatchPrepared).not.toHaveBeenCalled();- expect(history.canUndo()).toBe(false);+ expect(h.controller.commit(selection)).toEqual({ status: 'missing' });+ expect(h.dispatched).toEqual([]);+ expect(h.history.canUndo()).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.tsindex e9c620196e..823ae9df13 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts@@ -5,34 +5,32 @@ import type {CanvasStagingCandidateContract,CanvasStateContractV3,} from '@workbench/canvas-engine/contracts';-import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';-import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';-import type { History } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { ProjectEvent } from '@workbench/projectContracts';import { getDocumentLayer, getDocumentLeaves, hasDocumentNode } from '@workbench/canvas-engine/document/documentIndex';import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { getCanvasStagingCandidateFingerprint } from '@workbench/canvasStagingView';+import type { CanvasMutationContext, EditStep } from './mutationContext';++import { publishRefusal } from './layerResultSteps';+export interface StagedResultControllerOptions {- readonly concurrency: CanvasEditConcurrency;- readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;+ readonly ctx: Pick<+ CanvasMutationContext,+ | 'applyStep'+ | 'begin'+ | 'capturePermit'+ | 'captureInsertionAnchor'+ | 'createLayerId'+ | 'isGestureActive'+ | 'isPermitCurrent'+ >;readonly createEventId: () => string;- readonly createLayerId: () => string;- readonly dispatchPrepared: (- mutation: CanvasProjectMutation,- reducerAccepted: () => boolean,- mirrorAccepted: () => boolean,- origin?: 'system' | 'user'- ) => void;- readonly endBurst: () => void;readonly getCanvasState: () => CanvasStateContractV3 | null;- readonly getDocument: () => CanvasDocumentContractV3 | null;- readonly history: History;readonly now: () => string;}@@ -75,8 +73,8 @@ export class StagedResultController {if (this.disposed) {return { status: 'missing' };}- const permit = o.concurrency.capturePermit(owner);- if (!permit || o.concurrency.isGestureActive()) {+ const permit = o.ctx.capturePermit(owner);+ if (!permit || o.ctx.isGestureActive()) {return { status: 'busy' };}const canvas = o.getCanvasState();@@ -91,13 +89,17 @@ export class StagedResultController {) {return { status: 'missing' };}- if (!o.concurrency.isPermitCurrent(permit) || o.concurrency.isGestureActive()) {+ if (!o.ctx.isPermitCurrent(permit) || o.ctx.isGestureActive()) {return { status: 'busy' };}const continueStaging = options.continueStaging === true;const layer = {- ...createLayer(o.createLayerId(), `Layer ${getDocumentLeaves(canvas.document).length + 1}`, options.candidate),+ ...createLayer(+ o.ctx.createLayerId(),+ `Layer ${getDocumentLeaves(canvas.document).length + 1}`,+ options.candidate+ ),isEnabled: !continueStaging,};const event: ProjectEvent = {@@ -110,7 +112,7 @@ export class StagedResultController {};const previousSelectedLayerId = canvas.document.selectedLayerId;const previousStacks = canvas.document.stacks;- const anchor = o.captureInsertionAnchor('raster', null);+ const anchor = o.ctx.captureInsertionAnchor('raster', null);const acceptedStacks = insertNodesAtAnchor(previousStacks, anchor, [layer]);const previousStagingArea = canvas.stagingArea;const acceptedSelectedLayerId = continueStaging ? previousSelectedLayerId : layer.id;@@ -131,100 +133,84 @@ export class StagedResultController {next.stagingArea.pendingImageIds.length === 0 &&next.stagingArea.selectedImageIndex === 0 &&!next.stagingArea.isVisible);- const isMirrored = (): boolean =>- o.getDocument()?.selectedLayerId === acceptedSelectedLayerId &&- getDocumentLayer(o.getDocument(), layer.id) === layer;-- try {- o.endBurst();- o.dispatchPrepared(- {- anchor,- candidateFingerprint,- continueStaging,- event,- layer,- selectedImageIndex: options.selectedImageIndex,- type: 'commitStagedImage',- },- () => isCommitted(o.getCanvasState()),- isMirrored- );- } catch {- if (isCommitted(o.getCanvasState())) {- o.dispatchPrepared(- {- continueStaging,- event,- layer,- selectedLayerId: previousSelectedLayerId,- stagingArea: previousStagingArea,- type: 'rollbackStagedImageCommit',- },- () =>- hasPreviousLayerStack(o.getCanvasState()?.document ?? null) &&- o.getCanvasState()?.stagingArea === previousStagingArea,- () => hasPreviousLayerStack(o.getDocument()),- 'system'- );- }- return { status: 'stale' };- }-- const applyLayerStack = (- mutation: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>,- reducerAccepted: () => boolean,- mirrorAccepted: () => boolean,- rollback: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>,- reducerRolledBack: () => boolean,- mirrorRolledBack: () => boolean- ): void => {- try {- o.dispatchPrepared(mutation, reducerAccepted, mirrorAccepted);- } catch (error) {- if (reducerAccepted()) {- o.dispatchPrepared(rollback, reducerRolledBack, mirrorRolledBack, 'system');- }- throw error;- }- };- const addAcceptedLayer: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }> = {+ type StackMutation = Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>;+ const addAcceptedLayer: StackMutation = {add: [{ anchor, nodes: [layer] }],enabledUpdates: [],selectedLayerId: acceptedSelectedLayerId,type: 'applyCanvasLayerStackMutation',};- const removeAcceptedLayer: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }> = {+ const removeAcceptedLayer: StackMutation = {enabledUpdates: [],removeIds: [layer.id],selectedLayerId: previousSelectedLayerId,type: 'applyCanvasLayerStackMutation',};- o.history.push({- bytes: 256,- heldAssetRefs: collectHistoryMediaRefs(layer),- label: continueStaging ? 'Save staged image as disabled layer' : 'Accept staged image',- redo: () =>- applyLayerStack(- addAcceptedLayer,- () => hasAcceptedLayerStack(o.getCanvasState()?.document ?? null),- () => hasAcceptedLayerStack(o.getDocument()),- removeAcceptedLayer,- () => hasPreviousLayerStack(o.getCanvasState()?.document ?? null),- () => hasPreviousLayerStack(o.getDocument())- ),- replayFailureAtomic: true,- undo: () =>- applyLayerStack(- removeAcceptedLayer,- () => hasPreviousLayerStack(o.getCanvasState()?.document ?? null),- () => hasPreviousLayerStack(o.getDocument()),- addAcceptedLayer,- () => hasAcceptedLayerStack(o.getCanvasState()?.document ?? null),- () => hasAcceptedLayerStack(o.getDocument())- ),- });- return { layerId: layer.id, status: 'committed' };+ const added: EditStep = {+ accepted: hasAcceptedLayerStack,+ mutation: addAcceptedLayer,+ rollback: { mutation: removeAcceptedLayer, restored: hasPreviousLayerStack },+ };+ const removed: EditStep = {+ accepted: hasPreviousLayerStack,+ mutation: removeAcceptedLayer,+ rollback: { mutation: addAcceptedLayer, restored: hasAcceptedLayerStack },+ };++ // A failed read cannot prove that the commit (or its rollback) landed.+ const readCanvas = (): CanvasStateContractV3 | null => {+ try {+ return o.getCanvasState();+ } catch {+ return null;+ }+ };+ const txn = o.ctx.begin({ historyBytes: HISTORY_ENTRY_OVERHEAD_BYTES, owner });+ if (!('publish' in txn)) {+ return { status: txn.status === 'gesture-active' ? 'busy' : txn.status };+ }+ try {+ const result = txn.publish(+ continueStaging ? 'Save staged image as disabled layer' : 'Accept staged image',+ {+ accepted: () => isCommitted(readCanvas()),+ mutation: {+ anchor,+ candidateFingerprint,+ continueStaging,+ event,+ layer,+ selectedImageIndex: options.selectedImageIndex,+ type: 'commitStagedImage',+ },+ rollback: {+ mutation: {+ continueStaging,+ event,+ layer,+ selectedLayerId: previousSelectedLayerId,+ stagingArea: previousStagingArea,+ type: 'rollbackStagedImageCommit',+ },+ restored: () => {+ const restored = readCanvas();+ return hasPreviousLayerStack(restored?.document ?? null) && restored?.stagingArea === previousStagingArea;+ },+ },+ },+ {+ bytes: HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: collectHistoryMediaRefs(layer),+ redo: () => o.ctx.applyStep(added),+ undo: () => o.ctx.applyStep(removed),+ }+ );+ return result.status === 'committed'+ ? { layerId: layer.id, status: 'committed' }+ : { status: publishRefusal(result) };+ } finally {+ txn.end();+ }}dispose(): void {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.tsindex e442bcc190..9b5b19c84a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts@@ -16,7 +16,8 @@ import { createCanvasMutationContext } from './mutationContext';import { StructuralLayerController } from './structuralLayerController';interface HarnessOptions {- locked?: boolean;+ /** A live flag lets a test lock edits mid-gesture. */+ locked?: boolean | { value: boolean };gestureActive?: boolean;schedulePreview?: (flush: () => void) => () => void;/** Mirror refreshes only when asked, as when a store observer threw mid-notification. */@@ -54,22 +55,35 @@ const createHarness = (options: HarnessOptions & { now?: () => number } = {}) =>listeners.forEach((listener) => listener());return changed;};+ const history = createHistory();const ctx = createCanvasMutationContext({commitEdit: vi.fn(),createLayerId: () => 'new',projectId: base.id,dispatch,editOwner: Symbol('owner'),- editingLocked: { get: () => options.locked ?? false, subscribe: () => () => undefined },- endBurst: () => undefined,+ editingLocked: {+ get: () => (typeof options.locked === 'object' ? options.locked.value : (options.locked ?? false)),+ subscribe: () => () => undefined,+ },getDocument: () => mirrorDocument,getReducerDocument: () => project.canvas.document,- history: createHistory(),+ history,installPrepared: () => undefined,isGestureActive: () => options.gestureActive ?? false,isGuardCurrent: () => true,preparePixels: () => ({}) as never,refreshMirror,+ // As the engine wires it: unrecoverable step failures are reported with the edit's label.+ report: (error, label) =>+ report(+ error.outcome === 'reverted-unmirrored'+ ? 'Structural edit could not be mirrored'+ : 'Structural edit could not be reverted',+ label,+ error+ ),+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),subscribeReducer: (listener) => {listeners.add(listener);return () => listeners.delete(listener);@@ -87,14 +101,14 @@ const createHarness = (options: HarnessOptions & { now?: () => number } = {}) =>dispatched,projectId: base.id,document: () => project.canvas.document,- history: ctx.history,+ history,layer,mirror: () => mirrorDocument,report,};};-const rename = (id: string, name: string): CanvasProjectMutation => ({+const rename = (id: string, name: string): Extract<CanvasProjectMutation, { type: 'updateCanvasLayer' }> => ({id,patch: { name },type: 'updateCanvasLayer',@@ -111,8 +125,9 @@ describe('StructuralLayerController', () => {return () => undefined;},});- expect(harness.controller.preview(rename('layer', 'A'))).toBe(true);- expect(harness.controller.preview(rename('layer', 'B'))).toBe(true);+ const session = harness.controller.beginPreview()!;+ expect(session.apply(rename('layer', 'A'))).toBe(true);+ expect(session.apply(rename('layer', 'B'))).toBe(true);expect(harness.dispatched).toHaveLength(0);flush!();expect(harness.dispatched).toHaveLength(1);@@ -126,13 +141,13 @@ describe('StructuralLayerController', () => {cancelled += 1;},});- harness.controller.preview(rename('layer', 'Stale'));+ harness.controller.beginPreview()!.apply(rename('layer', 'Stale'));expect(harness.controller.commit('Rename', rename('layer', 'Final'), rename('layer', 'Layer'))).toMatchObject({status: 'committed',});expect(cancelled).toBe(1);expect(layerName(harness.document())).toBe('Final');- harness.controller.preview(rename('layer', 'Orphan'));+ harness.controller.beginPreview()!.apply(rename('layer', 'Orphan'));harness.controller.dispose();expect(cancelled).toBe(2);expect(layerName(harness.document())).toBe('Final');@@ -140,11 +155,11 @@ describe('StructuralLayerController', () => {it('dispatches previews synchronously without an animation frame', () => {const harness = createHarness();- expect(harness.controller.preview(rename('layer', 'Live'))).toBe(true);+ expect(harness.controller.beginPreview()!.apply(rename('layer', 'Live'))).toBe(true);expect(layerName(harness.document())).toBe('Live');});- it('commits through the guarded dispatch and records one failure-atomic history entry', () => {+ it('commits through the guarded dispatch and records one failure-atomic history entry', async () => {const { controller, document, history, mirror } = createHarness();expect(controller.canCommit()).toBe(true);@@ -155,9 +170,9 @@ describe('StructuralLayerController', () => {expect(mirror()).toBe(document());expect(history.canUndo()).toBe(true);- history.undo();+ await history.undo();expect(layerName(document())).toBe('Layer');- history.redo();+ await history.redo();expect(layerName(document())).toBe('Renamed');});@@ -267,14 +282,14 @@ describe('StructuralLayerController', () => {return result.edit;};- it('applies a prepared edit, verifies its postconditions and records one entry', () => {+ it('applies a prepared edit, verifies its postconditions and records one entry', async () => {const { controller, ctx, document, history, projectId } = createHarness();const model = createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });expect(controller.commitPrepared('Rename', prepareRename(model, 'Renamed'))).toEqual({ status: 'committed' });expect(layerName(document())).toBe('Renamed');expect(history.canUndo()).toBe(true);- history.undo();+ await history.undo();expect(layerName(document())).toBe('Layer');});@@ -296,6 +311,66 @@ describe('StructuralLayerController', () => {expect(history.canUndo()).toBe(false);});+ it('records a previewed gesture as one step without dispatching its final value again', async () => {+ const { controller, ctx, dispatched, document, history, projectId } = createHarness();+ const edit = prepareRename(+ createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId }),+ 'Live'+ );+ const session = controller.beginPreview()!;+ session.apply(rename('layer', 'Draft'));+ session.apply(rename('layer', 'Live'));+ const previews = dispatched.length;++ expect(session.commit('Rename', edit)).toEqual({ status: 'committed' });+ expect(dispatched).toHaveLength(previews);+ expect(history.entries().past).toEqual(['Rename']);+ await history.undo();+ expect(layerName(document())).toBe('Layer');+ });++ it('restores the baseline on cancel and refuses a session a newer one replaced', () => {+ const { controller, ctx, document, history, projectId } = createHarness();+ const first = controller.beginPreview()!;+ first.apply(rename('layer', 'Draft'));+ const second = controller.beginPreview()!;++ expect(first.apply(rename('layer', 'Ignored'))).toBe(false);+ expect(+ first.commit(+ 'Rename',+ prepareRename(createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId }), 'X')+ )+ ).toEqual({ status: 'busy' });+ second.apply(rename('layer', 'Other'));+ second.cancel(rename('layer', 'Layer'));+ expect(layerName(document())).toBe('Layer');+ expect(history.canUndo()).toBe(false);+ });++ it('returns to the baseline when a previewed gesture is refused, even under a lock', () => {+ const locked = { value: false };+ const { controller, ctx, document, history, projectId } = createHarness({ locked });+ const edit = prepareRename(+ createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId }),+ 'Live'+ );+ const session = controller.beginPreview()!;+ session.apply(rename('layer', 'Live'));+ locked.value = true;++ expect(session.commit('Rename', edit)).toEqual({ status: 'busy' });+ expect(layerName(document())).toBe('Layer');+ expect(history.canUndo()).toBe(false);++ locked.value = false;+ const cancelled = controller.beginPreview()!;+ cancelled.apply(rename('layer', 'Draft'));+ locked.value = true;+ cancelled.cancel(rename('layer', 'Layer'));+ expect(layerName(document())).toBe('Layer');+ });+it('skips history for an edit whose policy is none', () => {const { controller, ctx, document, history, projectId } = createHarness();const model = createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });@@ -331,7 +406,7 @@ describe('StructuralLayerController', () => {expect(anchor.projectId).toBe(projectId);});- it('moves a replay the reducer refuses as a reported no-op instead of wedging history', () => {+ it('moves a replay the reducer refuses as a reported no-op instead of wedging history', async () => {const { controller, ctx, document, history, projectId, report } = createHarness();const added = createEmptyPaintLayer('Added', 'added');@@ -342,14 +417,14 @@ describe('StructuralLayerController', () => {);ctx.dispatch({ ids: ['added'], type: 'removeCanvasLayers' }, 'system');- expect(() => history.undo()).not.toThrow();+ await expect(history.undo()).resolves.toEqual({ status: 'applied' });expect(report).toHaveBeenCalledWith('Structural history replay was refused', 'Add', expect.any(Error));expect(history.canUndo()).toBe(false);expect(history.canRedo()).toBe(true);expect(layerName(document(), 'added')).toBeUndefined();});- it('coalesces rapid nudges into one entry and reports an ineligible nudge as rejected', () => {+ it('coalesces rapid nudges into one entry and reports an ineligible nudge as rejected', async () => {let now = 0;const { controller, document, history } = createHarness({ now: () => now });@@ -358,7 +433,7 @@ describe('StructuralLayerController', () => {expect(controller.nudge(1, 0)).toEqual({ status: 'committed' });expect(getDocumentLayer(document(), 'layer')?.transform.x).toBe(2);- history.undo();+ await history.undo();expect(getDocumentLayer(document(), 'layer')?.transform.x).toBe(0);expect(history.canUndo()).toBe(false);@@ -372,7 +447,7 @@ describe('StructuralLayerController', () => {});describe('hierarchy recovery', () => {- it('reverts a reparent whose postconditions fail and leaves the tree, selection and history untouched', () => {+ it('reverts a reparent whose postconditions fail and leaves the tree, selection and history untouched', async () => {const { controller, ctx, document, history, projectId } = createHarness();const inner = createEmptyPaintLayer('Inner', 'inner');const group = {@@ -427,7 +502,7 @@ describe('hierarchy recovery', () => {}expect(controller.commitPrepared('Reparent', fresh.edit)).toEqual({ status: 'committed' });expect(parentOf('layer')).toBe('g');- history.undo();+ await history.undo();expect(haveSameStructure(document().stacks, before.stacks)).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.tsindex c4a2f3e1fe..34afae34f3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts@@ -1,17 +1,21 @@import type {+ CanvasLayerPreviewMutation,PreparedCommitOptions,StructuralCommitOptions,StructuralCommitResult,+ StructuralPreviewSession,} from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { PreparedDocumentEdit } from '@workbench/canvas-engine/document-model/documentCommands';+import type { HistoryEntryToken } from '@workbench/canvas-engine/history/history';import type { CanvasMutationOrigin, CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import { createDocumentModel } from '@workbench/canvas-engine/document-model/documentModel';import { checkEditPostconditions } from '@workbench/canvas-engine/document-model/postconditions';import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';+import { HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';-import type { CanvasMutationContext } from './mutationContext';+import { EditStepError, type CanvasMutationContext, type EditStep } from './mutationContext';/** The edit revision a mutation's insertion was anchored at; a commit refuses an anchor captured earlier. */const anchorRevisionOf = (mutation: CanvasProjectMutation): number | undefined => {@@ -27,21 +31,19 @@ const anchorRevisionOf = (mutation: CanvasProjectMutation): number | undefined =export type StructuralMutationContext = Pick<CanvasMutationContext,+ | 'applyStep'+ | 'begin'| 'canEdit'- | 'capturePermit'| 'dispatch'- | 'dispatchPrepared'| 'getDocument'| 'getEditRevision'| 'getReducerDocument'- | 'history'+ | 'historyTop'| 'isGestureActive'| 'projectId'>;export type StructuralFailureReport =- | 'Structural edit could not be reverted'- | 'Structural edit could not be mirrored'| 'Structural history replay was refused'| 'Structural history replay could not be mirrored';@@ -64,9 +66,10 @@ const defaultSchedulePreview = (flush: () => void): (() => void) => {};interface NudgeBurst {- expiresAt: number;- selectionKey: string;- origins: readonly { id: string; x: number; y: number }[];+ readonly token: HistoryEntryToken;+ readonly expiresAt: number;+ readonly selectionKey: string;+ readonly origins: readonly { id: string; x: number; y: number }[];}const NUDGE_COALESCE_MS = 500;@@ -78,29 +81,23 @@ const positionMutation = (positions: readonly { id: string; x: number; y: numberconst unique = (ids: readonly string[]): string[] => [...new Set(ids)];-/** Owns guarded, failure-atomic structural document edits and nudge coalescing. */+type RecordedResult = StructuralCommitResult | { status: 'committed'; token: HistoryEntryToken };++/** The public result; the history token stays internal. */+const publicResult = (result: RecordedResult): StructuralCommitResult =>+ result.status === 'committed' ? { status: 'committed' } : result;++/** Owns guarded, failure-atomic structural document edits, nudge coalescing and live preview sessions. */export class StructuralLayerController {private burst: NudgeBurst | null = null;private disposed = false;private readonly now: () => number;- private pendingPreview: CanvasProjectMutation | null = null;- private cancelPreviewFlush: (() => void) | null = null;+ private preview: { session: StructuralPreviewSession; flushPending(): void; drop(): void } | null = null;constructor(private readonly deps: StructuralLayerControllerOptions) {this.now = deps.now ?? Date.now;}- /** A commit supersedes any preview still waiting for its frame. */- private discardPendingPreview(): void {- this.cancelPreviewFlush?.();- this.cancelPreviewFlush = null;- this.pendingPreview = null;- }-- endBurst(): void {- this.burst = null;- }-canCommit(): boolean {const { ctx } = this.deps;return !this.disposed && ctx.canEdit() && !ctx.isGestureActive();@@ -112,20 +109,14 @@ export class StructuralLayerController {inverse: CanvasProjectMutation,options: StructuralCommitOptions = {}): StructuralCommitResult {- const refusal = this.refuse({- ...options,- expectedRevision: options.expectedRevision ?? anchorRevisionOf(forward) ?? anchorRevisionOf(inverse),- });- if (refusal) {- return refusal;- }- this.endBurst();- this.discardPendingPreview();- const applied = this.apply(label, forward, inverse, options.verify);- if (applied.status === 'committed') {- this.deps.ctx.history.push(this.entry(label, forward, inverse));+ const stale = this.staleRevision(+ options.expectedRevision ?? anchorRevisionOf(forward) ?? anchorRevisionOf(inverse)+ );+ if (stale) {+ return stale;}- return applied;+ this.endPreview();+ return publicResult(this.publish(label, this.step(forward, inverse, options.verify), forward, inverse));}/** A prepared flat edit: refused as `stale` unless its revision and project still match, verified by its postconditions. */@@ -134,64 +125,109 @@ export class StructuralLayerController {edit: PreparedDocumentEdit,options: PreparedCommitOptions = {}): StructuralCommitResult {- const refusal = this.refuse({ expectedRevision: edit.expectedRevision });- if (refusal) {- return refusal;+ const stale = this.staleRevision(edit.expectedRevision);+ if (stale) {+ return stale;}if (edit.projectId !== this.deps.ctx.projectId) {return { status: 'dispatch-rejected' };}- this.endBurst();- this.discardPendingPreview();- const applied = this.apply(- label,- edit.forward,- edit.inverse,- (document) => checkEditPostconditions(document, edit.postconditions),- options.origin+ this.endPreview();+ const step = this.step(edit.forward, edit.inverse, (document) =>+ checkEditPostconditions(document, edit.postconditions));- if (applied.status === 'committed' && edit.history === 'record') {- this.deps.ctx.history.push(this.entry(label, edit.forward, edit.inverse));+ if (edit.history !== 'record') {+ return this.applyUnrecorded(step);}- return applied;+ return publicResult(this.publish(label, step, edit.forward, edit.inverse, options.origin));}/**- * Coalesce gesture previews to one dispatch per frame to limit project subscriptions. True means queued; a lock,- * gesture or disposal before flush discards it.+ * Starts an owned preview: `apply` coalesces live dispatches to one per frame, and `commit` records the gesture+ * as one step from its prepared baseline without dispatching again when the preview already reached it, restoring+ * the baseline when it is refused. A newer session, any commit or disposal ends this one.*/- preview(action: CanvasProjectMutation): boolean {+ beginPreview(): StructuralPreviewSession | null {if (!this.canCommit()) {- return false;+ return null;}- this.pendingPreview = action;- if (this.cancelPreviewFlush === null) {- const schedule = this.deps.schedulePreview ?? defaultSchedulePreview;- // The scheduler may flush synchronously (no rAF); the cancel handle must not outlive the flush.- let flushed = false;- const cancel = schedule(() => {- flushed = true;- this.cancelPreviewFlush = null;- const pending = this.pendingPreview;- this.pendingPreview = null;- if (pending && this.canCommit()) {- this.deps.ctx.dispatch(pending);+ this.endPreview();+ let pending: CanvasProjectMutation | null = null;+ let cancelFlush: (() => void) | null = null;+ const owns = (): boolean => this.preview?.session === session;+ const flushPending = (): void => {+ cancelFlush?.();+ cancelFlush = null;+ const next = pending;+ pending = null;+ if (next && this.canCommit()) {+ this.deps.ctx.dispatch(next, 'system');+ }+ };+ const drop = (): void => {+ cancelFlush?.();+ cancelFlush = null;+ pending = null;+ };+ const session: StructuralPreviewSession = {+ apply: (action: CanvasLayerPreviewMutation) => {+ if (!owns() || !this.canCommit()) {+ return false;}- });- this.cancelPreviewFlush = flushed ? null : cancel;- }- return true;+ pending = action;+ if (cancelFlush === null) {+ let flushed = false;+ const cancel = (this.deps.schedulePreview ?? defaultSchedulePreview)(() => {+ flushed = true;+ cancelFlush = null;+ flushPending();+ });+ cancelFlush = flushed ? null : cancel;+ }+ return true;+ },+ cancel: (restore) => {+ if (owns()) {+ drop();+ this.preview = null;+ // Returning to the baseline undoes this session's own unrecorded previews, so a lock does not block it.+ if (restore && !this.disposed) {+ this.deps.ctx.dispatch(restore, 'system');+ }+ }+ },+ commit: (label, edit) => {+ if (!owns()) {+ return { status: 'busy' };+ }+ flushPending();+ this.preview = null;+ if (edit.projectId !== this.deps.ctx.projectId) {+ return { status: 'dispatch-rejected' };+ }+ const verify = (document: CanvasDocumentContractV3 | null): boolean =>+ document !== null && checkEditPostconditions(document, edit.postconditions);+ // The preview already published the final values: record the step without another reducer allocation.+ const step: EditStep = verify(this.deps.ctx.getReducerDocument())+ ? {}+ : this.step(edit.forward, edit.inverse, verify);+ const result = publicResult(this.publish(label, step, edit.forward, edit.inverse));+ // A refused gesture must not leave its unrecorded previews behind.+ if (result.status !== 'committed' && !this.disposed) {+ this.deps.ctx.dispatch(edit.inverse, 'system');+ }+ return result;+ },+ };+ this.preview = { drop, flushPending, session };+ return session;}nudge(dx: number, dy: number): StructuralCommitResult {const { ctx } = this.deps;- const refusal = this.refuse({});- if (refusal) {- return refusal;- }const document = ctx.getDocument();- if (!document?.selectedLayerId) {- return { status: 'dispatch-rejected' };+ if (this.disposed || !document?.selectedLayerId) {+ return { status: this.disposed ? 'not-ready' : 'dispatch-rejected' };}const ids = unique([document.selectedLayerId, ...(this.deps.getSelectedLayerIds?.(document) ?? [])]);const model = createDocumentModel(document, { editRevision: ctx.getEditRevision(), projectId: ctx.projectId });@@ -203,136 +239,131 @@ export class StructuralLayerController {if (prepared.edit.touchedIds.some((id) => !leaves.find((leaf) => leaf.id === id)?.contributionEnabled)) {return { status: 'dispatch-rejected' };}+ this.endPreview();const selectionKey = prepared.edit.touchedIds.join('\0');const now = this.now();- const coalesce = !!this.burst && this.burst.selectionKey === selectionKey && now < this.burst.expiresAt;- const origins =- coalesce && this.burst- ? this.burst.origins- : (prepared.edit.inverse as Extract<CanvasProjectMutation, { type: 'setCanvasLayerPositions' }>).updates;- const label = 'Nudge layer';+ // Coalesce only into the step this burst recorded: any interleaved entry starts a fresh one.+ const burst = this.burst;+ const coalesce =+ burst !== null &&+ burst.token === ctx.historyTop() &&+ burst.selectionKey === selectionKey &&+ now < burst.expiresAt;+ const origins = coalesce+ ? burst.origins+ : (prepared.edit.inverse as Extract<CanvasProjectMutation, { type: 'setCanvasLayerPositions' }>).updates;const forward = prepared.edit.forward;const inverse = positionMutation(origins);- const applied = this.apply(label, forward, inverse, (next) =>- checkEditPostconditions(next, prepared.edit.postconditions)+ const result = this.publish(+ 'Nudge layer',+ this.step(forward, inverse, (next) => checkEditPostconditions(next, prepared.edit.postconditions)),+ forward,+ inverse,+ undefined,+ coalesce ? burst.token : undefined);- if (applied.status !== 'committed') {- this.burst = null;- return applied;- }- const entry = this.entry(label, forward, inverse);- if (coalesce) {- ctx.history.amendLast(entry);- } else {- ctx.history.push(entry);- }- this.burst = { expiresAt: now + NUDGE_COALESCE_MS, origins, selectionKey };- return applied;+ this.burst =+ 'token' in result ? { expiresAt: now + NUDGE_COALESCE_MS, origins, selectionKey, token: result.token } : null;+ return publicResult(result);}dispose(): void {this.disposed = true;- this.endBurst();- this.discardPendingPreview();+ this.burst = null;+ this.endPreview();+ }++ private endPreview(): void {+ this.preview?.drop();+ this.preview = null;+ }++ private staleRevision(expectedRevision: number | undefined): StructuralCommitResult | null {+ const actualRevision = this.deps.ctx.getEditRevision();+ return expectedRevision !== undefined && expectedRevision !== actualRevision+ ? { actualRevision, expectedRevision, status: 'stale' }+ : null;}- private refuse(options: StructuralCommitOptions): StructuralCommitResult | null {+ /** A step that dispatches `forward`, verifies it, and dispatches `inverse` back when verification fails. */+ private step(+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation,+ verify?: (document: CanvasDocumentContractV3) => boolean+ ): EditStep {const { ctx } = this.deps;+ const before = ctx.getReducerDocument();+ return {+ accepted: (document) => document !== null && document !== before && (verify?.(document) ?? true),+ mutation: forward,+ rollback: { mutation: inverse, restored: () => true },+ };+ }++ private publish(+ label: string,+ step: EditStep,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation,+ origin?: CanvasMutationOrigin,+ replacing?: HistoryEntryToken+ ): RecordedResult {if (this.disposed) {return { status: 'not-ready' };}- if (!ctx.capturePermit()) {- return { status: 'busy' };- }- if (ctx.isGestureActive()) {- return { status: 'gesture-active' };+ const txn = this.deps.ctx.begin({ historyBytes: HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ return { status: txn.status };}- if (!ctx.getReducerDocument()) {- return { status: 'not-ready' };- }- const actualRevision = ctx.getEditRevision();- if (options.expectedRevision !== undefined && options.expectedRevision !== actualRevision) {- return { actualRevision, expectedRevision: options.expectedRevision, status: 'stale' };+ try {+ const entry = createDocumentPatchEntry({+ dispatch: (action) => this.replay(label, action, action === forward ? inverse : forward),+ forward,+ inverse,+ label,+ });+ const published = txn.publish(label, step, entry, { origin, replacing, routed: forward });+ return published.status === 'committed' ? { status: 'committed', token: published.token } : published;+ } finally {+ txn.end();}- return null;}- /** Dispatches `forward` once through the guarded context; a verified failure applies `inverse`. */- private apply(- label: string,- forward: CanvasProjectMutation,- inverse: CanvasProjectMutation,- verify: (document: CanvasDocumentContractV3) => boolean = () => true,- origin?: CanvasMutationOrigin- ): StructuralCommitResult {+ private applyUnrecorded(step: EditStep): StructuralCommitResult {const { ctx } = this.deps;- const before = ctx.getReducerDocument();- const isMirrored = (): boolean => ctx.getDocument() === ctx.getReducerDocument();- const isApplied = (): boolean => {- const document = ctx.getReducerDocument();- return document !== null && document !== before && verify(document);- };+ if (this.disposed || !ctx.canEdit()) {+ return { status: this.disposed ? 'not-ready' : 'busy' };+ }+ if (ctx.isGestureActive()) {+ return { status: 'gesture-active' };+ }try {- ctx.dispatchPrepared(forward, isApplied, isMirrored, origin);+ ctx.applyStep(step);return { status: 'committed' };} catch (error) {- const after = ctx.getReducerDocument();- if (after === before) {- return { status: 'dispatch-rejected' };- }- let recoveryError: unknown = error;- try {- ctx.dispatchPrepared(inverse, () => ctx.getReducerDocument() !== after, isMirrored, 'system');- } catch (inverseError) {- recoveryError = inverseError;- }- const recovered =- ctx.getReducerDocument() === after ? 'unreverted' : isMirrored() ? 'reverted' : 'reverted-unmirrored';- if (recovered === 'unreverted') {- this.deps.report?.('Structural edit could not be reverted', label, recoveryError);- } else if (recovered === 'reverted-unmirrored') {- this.deps.report?.('Structural edit could not be mirrored', label, recoveryError);+ if (!(error instanceof EditStepError)) {+ throw error;}- return { recovered, status: 'postcondition-failed' };+ return error.outcome === 'rejected'+ ? { status: 'dispatch-rejected' }+ : { recovered: error.outcome, status: 'postcondition-failed' };}}- private entry(label: string, forward: CanvasProjectMutation, inverse: CanvasProjectMutation) {- return createDocumentPatchEntry({- dispatch: (action) => this.replay(label, action, forward, inverse),- forward,- inverse,- label,- replayFailureAtomic: true,- });- }-/**- * A reducer that refuses a replay (its target changed since) is expected: the entry moves as a- * no-op and the refusal is reported. A mirror that cannot follow an accepted replay is not: the- * opposite action restores the reducer and the failure surfaces.+ * A reducer that refuses a replay (its target changed since) is expected: the entry moves as a no-op and the+ * refusal is reported. A mirror that cannot follow an accepted replay is not: the opposite action restores the+ * reducer and the step stays where it was.*/- private replay(- label: string,- action: CanvasProjectMutation,- forward: CanvasProjectMutation,- inverse: CanvasProjectMutation- ): void {- const { ctx } = this.deps;- const before = ctx.getReducerDocument();+ private replay(label: string, action: CanvasProjectMutation, opposite: CanvasProjectMutation): void {try {- ctx.dispatchPrepared(- action,- () => ctx.getReducerDocument() !== before,- () => ctx.getDocument() === ctx.getReducerDocument()- );+ this.deps.ctx.applyStep({ mutation: action, rollback: { mutation: opposite, restored: () => true } });} catch (error) {- if (ctx.getReducerDocument() === before) {+ if (error instanceof EditStepError && error.outcome === 'rejected') {this.deps.report?.('Structural history replay was refused', label, error);return;}this.deps.report?.('Structural history replay could not be mirrored', label, error);- ctx.dispatch(action === forward ? inverse : forward, 'system');throw error;}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.tsindex 263029bf14..0f49ad5bab 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts@@ -1,62 +1,187 @@-import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';+import { createHistory } from '@workbench/canvas-engine/history/history';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';import { TransformEditingController } from './transformEditingController';-const document = {- bbox: { height: 100, width: 100, x: 0, y: 0 },- height: 100,- stacks: stacksFrom([- {- blendMode: 'normal',- id: 'shape',- isEnabled: true,- isLocked: false,- name: 'Shape',- opacity: 1,- source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',+const MOVED = { rotation: 0, scaleX: 1, scaleY: 1, x: 12, y: 4 };++/** The controller over a real reducer, mutation context and history. */+const createHarness = (+ layer: CanvasLayerContract,+ options: { byteBudget?: number; commitStatus?: 'committed' | 'busy' } = {}+) => {+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document: documentFrom([layer], layer.id),+ type: 'replaceCanvasDocument',+ });+ const history = createHistory({ byteBudget: options.byteBudget });+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreateRect(layer.id, { height: 4, width: 4, x: 0, y: 0 });+ const dispatch = (action: CanvasProjectMutation): boolean => {+ project = applyCanvasProjectMutation(project, action);+ return true;+ };+ const rasterFits = { value: true };+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch,+ editOwner: Symbol('owner'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => project.canvas.document,+ getReducerDocument: () => project.canvas.document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => false,+ isGuardCurrent: () => true,+ preparePixels: () => {+ throw new Error('unused');},- ]),- width: 100,-} as CanvasDocumentContractV3;+ projectId: project.id,+ refreshMirror: () => undefined,+ reserveRaster: () =>+ rasterFits.value+ ? { lease: { release: () => undefined }, status: 'ok' }+ : { availableBytes: 0, requestedBytes: 1, status: 'over-budget' },+ subscribeReducer: () => () => undefined,+ });+ let session: TransformSession | null = null;+ const calls = {+ commitStructural: vi.fn(() => ({ status: options.commitStatus ?? ('committed' as const) })),+ reportRefusal: vi.fn(),+ restoreCache: vi.fn(),+ setOverride: vi.fn(),+ };+ const controller = new TransformEditingController({+ backend,+ canEdit: () => true,+ commitStructural: calls.commitStructural,+ ctx,+ getCache: (layerId) => layers.get(layerId) ?? null,+ getDocument: () => project.canvas.document,+ invalidate: vi.fn(),+ isGestureActive: () => false,+ reportRefusal: calls.reportRefusal,+ restoreCache: calls.restoreCache,+ session: { get: () => session, set: (value) => (session = value) },+ setOverride: calls.setOverride,+ });+ return {+ calls,+ controller,+ dispatch,+ history,+ layer: () => getDocumentLayer(project.canvas.document, layer.id),+ rasterFits,+ session: () => session,+ };+};++const shape = layerContract('shape', 'raster', {+ source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },+} as Partial<CanvasLayerContract>);+const paint = layerContract('paint', 'raster', {+ source: { bitmap: { height: 4, imageName: 'paint.png', width: 4 }, type: 'paint' },+} as Partial<CanvasLayerContract>);describe('TransformEditingController', () => {- it('owns preview state and commits parametric transforms through declared ports', () => {- let session: TransformSession | null = null;- const dispatch = vi.fn();- const pushHistory = vi.fn();- const setOverride = vi.fn();- const controller = new TransformEditingController({- backend: createTestStubRasterBackend(),- canEdit: () => true,- dispatch,- endBurst: vi.fn(),- getCache: () => null,- getDocument: () => document,- invalidate: vi.fn(),- isGestureActive: () => false,- pushHistory,- replaceCache: vi.fn(),- restoreCache: vi.fn(),- session: { get: () => session, set: (value) => (session = value) },- setOverride,- });-- controller.begin('shape');- controller.update({ rotation: 0, scaleX: 1, scaleY: 1, x: 12, y: 4 });- controller.apply();-- expect(session).toBeNull();- expect(dispatch).toHaveBeenCalledWith(- expect.objectContaining({ id: 'shape', patch: { transform: expect.objectContaining({ x: 12, y: 4 }) } })+ it('commits a parametric transform as a structural edit and ends the session', () => {+ const h = createHarness(shape);+ h.controller.begin('shape');+ h.controller.update(MOVED);+ h.controller.apply();++ expect(h.calls.commitStructural).toHaveBeenCalledWith(+ 'Transform layer',+ expect.objectContaining({ id: 'shape', patch: { transform: MOVED } }),+ expect.objectContaining({ id: 'shape', patch: { transform: expect.objectContaining({ x: 0 }) } })+ );+ expect(h.session()).toBeNull();+ expect(h.calls.setOverride).toHaveBeenLastCalledWith('shape', null);+ });++ it('keeps the session open and reports a refused commit', () => {+ const h = createHarness(shape, { commitStatus: 'busy' });+ h.controller.begin('shape');+ h.controller.update(MOVED);+ h.controller.apply();++ expect(h.calls.reportRefusal).toHaveBeenCalledWith('busy');+ expect(h.session()).toMatchObject({ layerId: 'shape', transform: MOVED });+ });++ it('bakes a paint transform into one step that undo and redo replay as a unit', async () => {+ const h = createHarness(paint);+ h.controller.begin('paint');+ h.controller.update(MOVED);+ h.controller.apply();++ expect(h.session()).toBeNull();+ expect(h.layer()?.transform).toMatchObject({ x: 0, y: 0 });+ expect(h.calls.restoreCache).toHaveBeenLastCalledWith(+ 'paint',+ { height: 4, width: 4, x: 12, y: 4 },+ expect.anything()+ );+ expect(h.history.entries().past).toEqual(['Transform layer']);++ expect(await h.history.undo()).toEqual({ status: 'applied' });+ expect(h.calls.restoreCache).toHaveBeenLastCalledWith(+ 'paint',+ { height: 4, width: 4, x: 0, y: 0 },+ expect.anything());- expect(pushHistory).toHaveBeenCalledOnce();- expect(setOverride).toHaveBeenLastCalledWith('shape', null);+ expect(await h.history.redo()).toEqual({ status: 'applied' });+ expect(h.calls.restoreCache).toHaveBeenCalledTimes(3);+ });++ it('refuses a bake too large to undo before changing the layer', () => {+ const h = createHarness(paint, { byteBudget: 10 });+ h.controller.begin('paint');+ h.controller.update(MOVED);+ h.controller.apply();++ expect(h.calls.reportRefusal).toHaveBeenCalledWith('over-budget');+ expect(h.calls.restoreCache).not.toHaveBeenCalled();+ expect(h.session()).toMatchObject({ transform: MOVED });+ expect(h.history.canUndo()).toBe(false);+ });++ it('keeps the step in place when the pixels it restores do not fit', async () => {+ const h = createHarness(paint);+ h.controller.begin('paint');+ h.controller.update(MOVED);+ h.controller.apply();+ h.rasterFits.value = false;++ expect(await h.history.undo()).toMatchObject({ status: 'failed' });+ expect(h.layer()?.transform).toMatchObject({ x: 0, y: 0 });+ expect(h.calls.restoreCache).toHaveBeenCalledOnce();+ h.rasterFits.value = true;+ expect(await h.history.undo()).toEqual({ status: 'applied' });+ });++ it('leaves the step in place when its layer can no longer take the transform', async () => {+ const h = createHarness(paint);+ h.controller.begin('paint');+ h.controller.update(MOVED);+ h.controller.apply();+ h.dispatch({ ids: ['paint'], type: 'removeCanvasLayers' });++ expect(await h.history.undo()).toMatchObject({ status: 'failed' });+ expect(h.history.entries().past).toEqual(['Transform layer']);+ expect(h.calls.restoreCache).toHaveBeenCalledOnce();});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.tsindex c63a486289..5c237ddcf4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts@@ -1,9 +1,9 @@+import type { CanvasEditRefusal, StructuralCommitResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';import type { TransformSession } from '@workbench/canvas-engine/engineStores';-import type { HistoryEntry } from '@workbench/canvas-engine/history/history';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';-import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { Rect } from '@workbench/canvas-engine/types';@@ -11,28 +11,38 @@ import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/docuimport { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';-import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';-import { NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';+import { HISTORY_ENTRY_OVERHEAD_BYTES, NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { hittableLayerSize } from '@workbench/canvas-engine/tools/moveHitTest';import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';+import type { CanvasMutationContext, EditStep } from './mutationContext';+export interface TransformEditingControllerOptions {readonly session: { get(): TransformSession | null; set(value: TransformSession | null): void };readonly backend: RasterBackend;+ readonly ctx: Pick<CanvasMutationContext, 'applyStep' | 'begin' | 'reserveRaster'>;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly getCache: (layerId: string) => LayerCacheEntry | null;readonly setOverride: (layerId: string, transform: LayerTransform | null) => void;- readonly replaceCache: (layerId: string, rect: Rect, surface: RasterSurface) => void;+ /** Installs whole-layer pixels at a layer-local rect, marking them painted and dirty. */readonly restoreCache: (layerId: string, rect: Rect, pixels: ImageData) => void;- readonly dispatch: (action: CanvasProjectMutation) => void;- readonly pushHistory: (entry: HistoryEntry) => void;+ readonly commitStructural: (+ label: string,+ forward: CanvasProjectMutation,+ inverse: CanvasProjectMutation+ ) => StructuralCommitResult;+ readonly reportRefusal: (refusal: CanvasEditRefusal) => void;readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;- readonly endBurst: () => void;readonly invalidate: (payload: { layers: string[]; overlay: true }) => void;}+const IDENTITY: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };++const isRefusal = (status: string): status is CanvasEditRefusal =>+ status === 'busy' || status === 'gesture-active' || status === 'not-ready' || status === 'over-budget';+const unchanged = (left: LayerTransform, right: LayerTransform): boolean =>left.x === right.x &&left.y === right.y &&@@ -90,30 +100,26 @@ export class TransformEditingController {this.deps.invalidate({ layers: [session.layerId], overlay: true });}- private bakeEntry(- layerId: string,- beforeRect: Rect,- before: ImageData,- afterRect: Rect,- after: ImageData,- oldTransform: LayerTransform,- newTransform: LayerTransform- ): HistoryEntry {+ /** A step that sets the layer's transform and installs matching whole-layer pixels, or rolls the transform back. */+ private bakeStep(layerId: string, from: LayerTransform, to: LayerTransform, rect: Rect, pixels: ImageData): EditStep {+ const hasTransform =+ (transform: LayerTransform) =>+ (document: CanvasDocumentContractV3 | null): boolean => {+ const current = getDocumentLayer(document, layerId);+ return !!current && unchanged(current.transform, transform);+ };return {- bytes: before.data.byteLength + after.data.byteLength + 256,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'Transform layer',- redo: () => {- this.deps.dispatch({ id: layerId, patch: { transform: newTransform }, type: 'updateCanvasLayer' });- this.deps.restoreCache(layerId, afterRect, after);- },- undo: () => {- this.deps.dispatch({ id: layerId, patch: { transform: oldTransform }, type: 'updateCanvasLayer' });- this.deps.restoreCache(layerId, beforeRect, before);+ accepted: hasTransform(to),+ install: () => this.deps.restoreCache(layerId, rect, pixels),+ mutation: { id: layerId, patch: { transform: to }, type: 'updateCanvasLayer' },+ rollback: {+ mutation: { id: layerId, patch: { transform: from }, type: 'updateCanvasLayer' },+ restored: hasTransform(from),},};}+ /** Commits the session; a refusal keeps it open and is reported, any other failure ends it. */apply(): void {if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {return;@@ -143,56 +149,79 @@ export class TransformEditingController {source?.type === 'gradient' ||source?.type === 'text') {- this.deps.endBurst();- this.deps.setOverride(session.layerId, null);- this.deps.session.set(null);- const forward: CanvasProjectMutation = {- id: session.layerId,- patch: { transform: session.transform },- type: 'updateCanvasLayer',- };- const inverse: CanvasProjectMutation = {- id: session.layerId,- patch: { transform: session.startTransform },- type: 'updateCanvasLayer',- };- this.deps.dispatch(forward);- this.deps.pushHistory(- createDocumentPatchEntry({ dispatch: this.deps.dispatch, forward, inverse, label: 'Transform layer' })+ const result = this.deps.commitStructural(+ 'Transform layer',+ { id: session.layerId, patch: { transform: session.transform }, type: 'updateCanvasLayer' },+ { id: session.layerId, patch: { transform: session.startTransform }, type: 'updateCanvasLayer' });- this.deps.invalidate({ layers: [session.layerId], overlay: true });- return;- }- if (source?.type !== 'paint') {- this.cancel();+ this.settle(result.status);return;}const cache = this.deps.getCache(layer.id);- if (!cache || isEmpty(cache.rect)) {+ if (source?.type !== 'paint' || !cache || isEmpty(cache.rect)) {this.cancel();return;}- this.deps.endBurst();const beforeRect = { ...cache.rect };- const before = cache.surface.ctx.getImageData(0, 0, beforeRect.width, beforeRect.height);const matrix = bakeMatrix(session.transform);const afterRect = roundOut(transformBounds(matrix, beforeRect));- const baked = this.deps.backend.createSurface(afterRect.width, afterRect.height);- const context = baked.ctx;- context.setTransform(1, 0, 0, 1, 0, 0);- context.clearRect(0, 0, afterRect.width, afterRect.height);- context.imageSmoothingEnabled = true;- context.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - afterRect.x, matrix.f - afterRect.y);- context.drawImage(cache.surface.canvas, beforeRect.x, beforeRect.y);- context.setTransform(1, 0, 0, 1, 0, 0);- const after = context.getImageData(0, 0, afterRect.width, afterRect.height);- const oldTransform = { ...session.startTransform };- const identity: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };- this.deps.setOverride(layer.id, null);- this.deps.session.set(null);- this.deps.dispatch({ id: layer.id, patch: { transform: identity }, type: 'updateCanvasLayer' });- this.deps.replaceCache(layer.id, afterRect, baked);- this.deps.pushHistory(this.bakeEntry(layer.id, beforeRect, before, afterRect, after, oldTransform, identity));+ const beforeBytes = beforeRect.width * beforeRect.height * 4;+ const afterBytes = afterRect.width * afterRect.height * 4;+ const txn = this.deps.ctx.begin({ historyBytes: beforeBytes + afterBytes + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ this.settle(txn.status);+ return;+ }+ try {+ // The bake surface lives beside the cache until the step installs its pixels.+ if (!txn.reserveRaster(afterBytes)) {+ this.settle('over-budget');+ return;+ }+ const before = cache.surface.ctx.getImageData(0, 0, beforeRect.width, beforeRect.height);+ const baked = this.deps.backend.createSurface(afterRect.width, afterRect.height);+ const context = baked.ctx;+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, afterRect.width, afterRect.height);+ context.imageSmoothingEnabled = true;+ context.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - afterRect.x, matrix.f - afterRect.y);+ context.drawImage(cache.surface.canvas, beforeRect.x, beforeRect.y);+ context.setTransform(1, 0, 0, 1, 0, 0);+ const after = context.getImageData(0, 0, afterRect.width, afterRect.height);+ const oldTransform = { ...session.startTransform };+ const forward = this.bakeStep(layer.id, oldTransform, IDENTITY, afterRect, after);+ const backward = this.bakeStep(layer.id, IDENTITY, oldTransform, beforeRect, before);+ const result = txn.publish('Transform layer', forward, {+ bytes: before.data.byteLength + after.data.byteLength + HISTORY_ENTRY_OVERHEAD_BYTES,+ heldAssetRefs: NO_HELD_ASSET_REFS,+ redo: () => this.replay(forward, afterRect),+ undo: () => this.replay(backward, beforeRect),+ });+ this.settle(result.status);+ } finally {+ txn.end();+ }+ }++ /** Replays a bake step, reserving the whole-layer pixels it installs; throws, leaving it in place, when they do not fit. */+ private replay(step: EditStep, rect: Rect): void {+ const reservation = this.deps.ctx.reserveRaster(rect.width * rect.height * 4);+ if (!reservation) {+ throw new Error('Not enough raster memory to restore the transformed layer.');+ }+ try {+ this.deps.ctx.applyStep(step);+ } finally {+ reservation.release();+ }+ }++ private settle(status: StructuralCommitResult['status']): void {+ if (isRefusal(status)) {+ this.deps.reportRefusal(status);+ return;+ }+ this.cancel();}dispose(): void {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.tsindex 2c23dba66a..7e28d461b6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts@@ -25,7 +25,6 @@ const decide = (overrides: Partial<LayerChangeInput> = {}) =>hasTransformSession: false,isSelfEcho: () => false,layer: layerOf(),- previousImageName: undefined,sourceChanged: false,...overrides,});@@ -35,16 +34,6 @@ describe('a layer that is gone', () => {expect(decide({ layer: undefined }).kind).toBe('removed');});- it('releases the image it referenced', () => {- expect(decide({ layer: undefined, previousImageName: 'old.png' })).toMatchObject({- releaseImageName: 'old.png',- });- });-- it('releases nothing when it referenced no image', () => {- expect(decide({ layer: undefined })).toMatchObject({ releaseImageName: null });- });-it.each([['transform', { hasTransformSession: true }, 'cancelTransformSession'],['text-edit', { hasTextEditSession: true }, 'cancelTextEditSession'],@@ -128,15 +117,6 @@ describe('a genuine source swap', () => {expect(decision).toMatchObject({ thumbnailKey: getLayerThumbnailDisplayKey(layer) });});- it('releases the image it previously referenced, echo or not', () => {- expect(decide({ previousImageName: 'old.png', sourceChanged: true })).toMatchObject({- releaseImageName: 'old.png',- });- expect(decide({ isSelfEcho: () => true, previousImageName: 'old.png', sourceChanged: true })).toMatchObject({- releaseImageName: 'old.png',- });- });-it('re-keys the thumbnail even for an echo it will not re-rasterize', () => {expect(decide({ isSelfEcho: () => true, sourceChanged: true })).toMatchObject({thumbnailKey: expect.any(String),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.tsindex 33c02b7247..a23dfa6565 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts@@ -10,8 +10,6 @@ export interface LayerChangeInput {readonly layer: CanvasLayerContract | undefined;/** Whether the mirror reported this layer's SOURCE reference as changed. */readonly sourceChanged: boolean;- /** The image this layer referenced before the change, if any. */- readonly previousImageName: string | null | undefined;/** The display key recorded for this layer's last-rendered thumbnail. */readonly currentThumbnailKey: string | undefined;/** The version recorded for this layer's thumbnail, if any. */@@ -27,7 +25,6 @@ export interface LayerChangeInput {export type LayerChangeDecision =| {readonly kind: 'removed';- readonly releaseImageName: string | null;readonly cancelTransformSession: boolean;readonly cancelTextEditSession: boolean;}@@ -39,7 +36,6 @@ export type LayerChangeDecision =| {readonly kind: 'source-changed';readonly thumbnailKey: string;- readonly releaseImageName: string | null;/** `false` when the swap is the bitmap store's own echo, whose pixels the cache already holds. */readonly invalidateCache: boolean;};@@ -50,15 +46,13 @@ export type LayerChangeDecision =* pixels already match.*/export const decideLayerChange = (input: LayerChangeInput): LayerChangeDecision => {- const { layer, previousImageName } = input;- const releaseImageName = previousImageName ?? null;+ const { layer } = input;if (!layer) {return {cancelTextEditSession: input.hasTextEditSession,cancelTransformSession: input.hasTransformSession,kind: 'removed',- releaseImageName,};}@@ -83,7 +77,6 @@ export const decideLayerChange = (input: LayerChangeInput): LayerChangeDecisionreturn {invalidateCache: !input.isSelfEcho(),kind: 'source-changed',- releaseImageName,thumbnailKey: getLayerThumbnailDisplayKey(layer),};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.tsindex b6a52a2c9a..ef634cc3b2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts@@ -3,9 +3,9 @@* replacement or owned-layer changes. Permits capture the editing-lock epoch and recheck before publishing; lock* owners bypass the lock.*- * Structural/pixel commits and history replay refuse active gestures; tools own stroke commits, and floats guard- * lift rather than bake. Project ids and edit revisions fence insertion/structural commits; exports also guard- * layer reference, cache version and document generation.+ * Structural/pixel commits and history replay refuse active gestures, and every edit is refused while a history+ * step replays; tools own stroke commits, and floats guard lift rather than bake. Project ids and edit revisions+ * fence insertion/structural commits; exports also guard layer reference, cache version and document generation.** {@link CanvasTransactionOutcome} describes runtime refusals. Document command refusals remain* runtime-independent; combined results use {@link SubsetOf} to verify their vocabulary.@@ -25,7 +25,7 @@ export interface DocumentEditPermit {readonly owner?: symbol;}-export type CanvasTransactionOutcome = 'busy' | 'gesture-active' | 'stale' | 'aborted' | 'not-ready';+export type CanvasTransactionOutcome = 'busy' | 'gesture-active' | 'stale' | 'aborted' | 'not-ready' | 'over-budget';/** Names members of a vocabulary; a member outside `T` is a compile error rather than a silent drop. */export type SubsetOf<T, U extends T> = U;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.tsindex 3525ab94b0..ff701f02ae 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.browser.test.ts@@ -4,6 +4,7 @@ import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCacheimport type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import { PixelEditController } from '@workbench/canvas-engine/controllers/controlPixelController';+import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { createHistory } from '@workbench/canvas-engine/history/history';@@ -74,27 +75,46 @@ const setup = (width: 8,};const history = createHistory();+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch: (action) => {+ if (action.type !== 'replaceCanvasLayer' || action.layer.type !== 'raster') {+ throw new Error('expected raster replacement');+ }+ layer = action.layer;+ document = { ...document, stacks: stacksFrom([action.layer]) };+ resources.onReplacement?.(action.layer);+ return true;+ },+ editOwner: Symbol('owner'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => document,+ getReducerDocument: () => document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => false,+ isGuardCurrent: () => true,+ preparePixels: () => {+ throw new Error('unused');+ },+ projectId: 'project',+ refreshMirror: () => undefined,+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),+ subscribeReducer: () => () => undefined,+ });const controller = new PixelEditController({- applyImagePatch: vi.fn(),+ applyImagePatch: vi.fn(() => Promise.resolve()),backend,bitmapStore,canEdit: () => true,+ ctx,deleteDerived: (layerId) => adjusted.delete(layerId),- dispatchReplacement: (replacement) => {- if (replacement.type !== 'raster') {- throw new Error('expected raster replacement');- }- layer = replacement;- document = { ...document, stacks: stacksFrom([replacement]) };- resources.onReplacement?.(replacement);- },- endBurst: vi.fn(),getActiveProjectId: () => 'project',getAdjustedSurface: (candidate, candidateEntry) =>candidate.type === 'raster' ? adjusted.get(candidate.id, candidateEntry, candidate.adjustments) : null,getDocument: () => document,getTransformSession: () => null,- history,installPrepared: (prepared) => {layers.installReplacement(prepared);},@@ -108,6 +128,7 @@ const setup = (preparePixels: (layerId, rect, pixels) => layers.prepareReplacement(layerId, rect, pixels),projectId: 'project',publishStroke: vi.fn(),+ reportRefusal: vi.fn(),setTransformOverride: (layerId, transform) => {if (transform) {transformOverrides.set(layerId, transform);@@ -139,7 +160,7 @@ const pixels = (surface: RasterSurface): number[] => [];describe('image-layer erasing with real browser pixels', () => {- it('preserves adjustment-before-transform rendering for untouched pixels', () => {+ it('preserves adjustment-before-transform rendering for untouched pixels', async () => {const original = imageLayer();const h = setup(original);const originalEntry = h.layers.get(original.id)!;@@ -171,7 +192,7 @@ describe('image-layer erasing with real browser pixels', () => {// byte-identical to the pre-edit display, not a raw-then-adjusted variant.preview.surface.ctx.clearRect(preview.rect.width - 1, 0, 1, 1);const afterStroke = preview.surface.ctx.getImageData(0, 0, preview.rect.width, preview.rect.height);- transaction!.commitStroke({+ transaction!.commit({afterImageData: afterStroke,beforeImageData: beforeStroke,dirtyRect: { ...preview.rect },@@ -184,7 +205,7 @@ describe('image-layer erasing with real browser pixels', () => {expect(h.getLayer()).toMatchObject({ source: { type: 'paint' }, transform: { scaleX: 1, scaleY: 1 } });expect(h.getLayer()).not.toHaveProperty('adjustments');- h.history.undo();+ expect(await h.history.undo()).toEqual({ status: 'applied' });expect(h.getLayer()).toEqual(original);expect(pixels(h.layers.get(original.id)!.surface)).toEqual([0, 0, 0, 255, 255, 255, 255, 255]);h.controller.dispose();@@ -231,7 +252,7 @@ describe('image-layer erasing with real browser pixels', () => {const beforeStroke = preview.surface.ctx.getImageData(0, 0, preview.rect.width, preview.rect.height);preview.surface.ctx.clearRect(0, 0, preview.rect.width, preview.rect.height);const afterStroke = preview.surface.ctx.getImageData(0, 0, preview.rect.width, preview.rect.height);- transaction.commitStroke({+ transaction.commit({afterImageData: afterStroke,beforeImageData: beforeStroke,dirtyRect: { ...preview.rect },diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.tsindex c9697529d6..206a7d0f35 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts@@ -301,7 +301,7 @@ describe('Canvas history holds resurrectable media', () => {expect(engine.stores.canUndo.get()).toBe(true);expect(engine.history.getHeldAssetRefs().images).toEqual(expect.arrayContaining(heldAfterOp));- engine.history.undo();+ await engine.history.undo();expect(engine.stores.canRedo.get()).toBe(true);expect(engine.history.getHeldAssetRefs().images).toEqual(expect.arrayContaining(heldAfterUndo));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.tsindex c44d7a5aa0..8a767fccf8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts@@ -361,26 +361,25 @@ describe('inpaint mask painting', () => {});describe('mask invert', () => {- it('inverts a mask as an undoable op and returns true', () => {+ it('inverts a mask as one undoable step', async () => {const { engine } = setupEngine(maskDoc());expect(engine.stores.canUndo.get()).toBe(false);- expect(engine.layers.invertMask('mask1')).toBe(true);- // One undoable image patch was recorded.+ expect(engine.layers.invertMask('mask1')).toEqual({ status: 'committed' });expect(engine.stores.canUndo.get()).toBe(true);- // Round trips: undo then redo restore without throwing.- engine.history.undo();+ expect(await engine.history.undo()).toBe('applied');expect(engine.stores.canRedo.get()).toBe(true);- engine.history.redo();+ expect(await engine.history.redo()).toBe('applied');expect(engine.stores.canUndo.get()).toBe(true);engine.lifecycle.dispose();});- it('returns false for a missing layer, a non-mask layer, or a locked mask', () => {+ it('reports a missing layer and a locked mask distinctly without recording history', () => {const lockedDoc = maskDoc();getDocumentLeaves(lockedDoc)[0]!.isLocked = true;const { engine } = setupEngine(lockedDoc);- expect(engine.layers.invertMask('nope')).toBe(false);- expect(engine.layers.invertMask('mask1')).toBe(false); // locked+ expect(engine.layers.invertMask('nope')).toEqual({ status: 'missing' });+ expect(engine.layers.invertMask('mask1')).toEqual({ status: 'locked' });+ expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();});@@ -428,7 +427,7 @@ describe('mask invert', () => {overlay.fire('pointermove', pointerAt(180, 180));overlay.fire('pointerup', pointerAt(180, 180, 0));- expect(engine.layers.invertMask('mask1')).toBe(true);+ expect(engine.layers.invertMask('mask1')).toEqual({ status: 'committed' });// Growth replaces backing surfaces. Inspect the last surface receiving `putImageData`, which owns the final// invert extent.@@ -498,23 +497,23 @@ describe('mask invert', () => {});describe('mask clear', () => {- it('clears a live unflushed inpaint mask and restores it through undo', () => {+ it('clears a live unflushed inpaint mask and restores it through undo', async () => {const { engine, overlay } = setupEngine(maskDoc());engine.tools.setTool('brush');overlay.fire('pointerdown', pointerAt(20, 20));overlay.fire('pointermove', pointerAt(50, 50));overlay.fire('pointerup', pointerAt(50, 50, 0));- expect(engine.layers.clearMask('mask1')).toBe(true);- expect(engine.layers.clearMask('mask1')).toBe(false);+ expect(engine.layers.clearMask('mask1')).toEqual({ status: 'committed' });+ expect(engine.layers.clearMask('mask1')).toEqual({ status: 'nothing' });expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ expect(await engine.history.undo()).toBe('applied');expect(engine.stores.canRedo.get()).toBe(true);- engine.history.redo();- expect(engine.layers.clearMask('mask1')).toBe(false);- engine.history.undo();- expect(engine.layers.clearMask('mask1')).toBe(true);+ expect(await engine.history.redo()).toBe('applied');+ expect(engine.layers.clearMask('mask1')).toEqual({ status: 'nothing' });+ expect(await engine.history.undo()).toBe('applied');+ expect(engine.layers.clearMask('mask1')).toEqual({ status: 'committed' });engine.lifecycle.dispose();});@@ -541,11 +540,11 @@ describe('mask clear', () => {overlay.fire('pointermove', pointerAt(50, 50));overlay.fire('pointerup', pointerAt(50, 50, 0));- expect(engine.layers.clearMask('mask1')).toBe(true);+ expect(engine.layers.clearMask('mask1')).toEqual({ status: 'committed' });engine.lifecycle.dispose();});- it('clears a cold hidden persisted mask and restores its bitmap reference on undo', () => {+ it('clears a cold hidden persisted mask and restores its bitmap reference on undo', async () => {const doc = maskDoc();const mask = getDocumentLeaves(doc)[0]!;if (mask.type !== 'inpaint_mask') {@@ -559,14 +558,14 @@ describe('mask clear', () => {};const { dispatch, engine } = setupEngine(doc);- expect(engine.layers.clearMask('mask1')).toBe(true);+ expect(engine.layers.clearMask('mask1')).toEqual({ status: 'committed' });expect(dispatch.mock.calls.at(-1)?.[0]).toMatchObject({config: { mask: { bitmap: null } },id: 'mask1',type: 'updateCanvasLayerConfig',});- engine.history.undo();+ expect(await engine.history.undo()).toBe('applied');expect(dispatch.mock.calls.at(-1)?.[0]).toMatchObject({config: {mask: { bitmap: { imageName: 'persisted-mask' }, offset: { x: 7, y: 9 } },@@ -577,13 +576,13 @@ describe('mask clear', () => {engine.lifecycle.dispose();});- it('refuses missing, non-mask, locked, and empty layers', () => {+ it('reports missing, non-mask, locked, and empty layers distinctly', () => {const locked = maskDoc();(locked.stacks.inpaint_mask[0] as CanvasLayerContract).isLocked = true;const { engine } = setupEngine(locked);- expect(engine.layers.clearMask('missing')).toBe(false);- expect(engine.layers.clearMask('mask1')).toBe(false);+ expect(engine.layers.clearMask('missing')).toEqual({ status: 'missing' });+ expect(engine.layers.clearMask('mask1')).toEqual({ status: 'locked' });engine.lifecycle.dispose();const raster = maskDoc();@@ -600,11 +599,11 @@ describe('mask clear', () => {type: 'raster',};const { engine: rasterEngine } = setupEngine(raster);- expect(rasterEngine.layers.clearMask('mask1')).toBe(false);+ expect(rasterEngine.layers.clearMask('mask1')).toEqual({ status: 'unsupported' });rasterEngine.lifecycle.dispose();const { engine: emptyEngine } = setupEngine(maskDoc());- expect(emptyEngine.layers.clearMask('mask1')).toBe(false);+ expect(emptyEngine.layers.clearMask('mask1')).toEqual({ status: 'nothing' });emptyEngine.lifecycle.dispose();});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 92448b3a0b..f2cbff24c6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -143,9 +143,20 @@ const createCanvasEngine = ({getMainModelBase ?? (() => canvasApplicationPort.getSelectedModelBase(store.getState(), projectId)),mutationPort: mutationPort ?? createTestMutationPort(store, projectId),projectId,- reportError: reportError ?? (() => undefined),+ reportError: reportError ?? ((report) => reportedErrors.push(report)),});+/** Reports the test engine made when a test passed no `reportError` of its own. */+const reportedErrors: Parameters<CanvasEngineOptions['reportError']>[0][] = [];++/** A replay that failed leaves its step in place and reports the failure that stopped it. */+const expectReplayFailure = async (replay: Promise<string>, failure: string | RegExp): Promise<void> => {+ expect(await replay).toBe('failed');+ const report = reportedErrors.at(-1);+ expect(report?.message).toBe('History replay failed');+ expect((report?.context.error as Error | undefined)?.message).toMatch(failure);+};+// Wraps the real adjusted cache to record access without exposing engine internals.const adjustedSurfaceCacheDeletes = vi.hoisted(() => [] as string[]);const adjustedSurfaceCacheGets = vi.hoisted(() => [] as string[]);@@ -603,6 +614,7 @@ const drainMicrotasksUntil = async (predicate: () => boolean, maxTicks = 100): P};afterEach(() => {+ reportedErrors.length = 0;adjustedSurfaceCacheDeleteFaults.clear();historyPreparationFaults.imagePatch = false;historyPreparationFaults.imagePatchBefore = null;@@ -1946,7 +1958,7 @@ describe('createCanvasEngine', () => {expect(forwardExport.rect).toEqual({ height: 5, width: 7, x: 8, y: 5 });const forwardSources = backend.drawSourcesFor(forwardExport.surface as StubRasterSurface);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(beforeContract);expect(bitmapStore.markLayerDirty).toHaveBeenCalledTimes(2);expect(thumbnailListener).toHaveBeenCalledTimes(2);@@ -1962,7 +1974,7 @@ describe('createCanvasEngine', () => {backend.surfaceId(beforeExport.surface as StubRasterSurface));- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(afterContract);expect(bitmapStore.markLayerDirty).toHaveBeenCalledTimes(3);expect(thumbnailListener).toHaveBeenCalledTimes(3);@@ -2300,7 +2312,7 @@ describe('createCanvasEngine', () => {setActiveProjectId('p2');pending.resolve(new Blob());- expect(await copy).not.toBeNull();+ expect((await copy).status).toBe('copied');expect(store.dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: 'applyCanvasLayerStackMutation' }));engine.lifecycle.dispose();});@@ -2325,7 +2337,8 @@ describe('createCanvasEngine', () => {store,});- const newId = await engine.layers.copyLayerToRaster('a');+ const copied = await engine.layers.copyLayerToRaster('a');+ const newId = copied.status === 'copied' ? copied.layerId : null;expect(newId).toMatch(/^layer-/);const mutation = dispatch.mock.calls@@ -2352,7 +2365,7 @@ describe('createCanvasEngine', () => {engine.lifecycle.dispose();});- it('copyLayerToRaster returns null for empty layers', async () => {+ it('copyLayerToRaster refuses empty layers as empty', async () => {const empty = { ...rasterLayer('empty'), source: { bitmap: null, type: 'paint' } as const };const { store } = createFakeStore({ ...makeDoc(), stacks: stacksFrom([empty]) });const dispatch = store.dispatch as Mock;@@ -2363,7 +2376,7 @@ describe('createCanvasEngine', () => {store,});- expect(await engine.layers.copyLayerToRaster('empty')).toBeNull();+ expect(await engine.layers.copyLayerToRaster('empty')).toEqual({ status: 'empty' });expect(dispatch).not.toHaveBeenCalled();engine.lifecycle.dispose();});@@ -2384,12 +2397,14 @@ describe('createCanvasEngine', () => {store,});- const newId = await engine.layers.copyLayerToRaster('mask');+ const copied = await engine.layers.copyLayerToRaster('mask');+ expect(copied.status).toBe('copied');+ const newId = copied.status === 'copied' ? copied.layerId : null;expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === newId)).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === newId)).toBe(false);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === newId)).toBe(true);engine.lifecycle.dispose();});@@ -2414,24 +2429,25 @@ describe('createCanvasEngine', () => {store,});- const newId = await engine.layers.copyLayerToRaster('a');- expect(newId).not.toBeNull();- engine.history.undo();+ const copied = await engine.layers.copyLayerToRaster('a');+ expect(copied.status).toBe('copied');+ const newId = copied.status === 'copied' ? copied.layerId : null;+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(0);failNextAllocation = true;- expect(() => engine.history.redo()).toThrow('copy replay allocation failed');+ await expectReplayFailure(engine.history.redo(), 'copy replay allocation failed');expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(0);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(1);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id === newId)).toHaveLength(0);engine.lifecycle.dispose();});@@ -2772,8 +2788,8 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {const thumbnailListener = vi.fn();const unsubscribe = engine.stores.thumbnailVersion.subscribeKey('a', thumbnailListener);const contentListener = vi.fn();- const unsubscribeContent = engine.interaction.subscribe('rasterContentEpoch', contentListener);- expect(engine.interaction.get('rasterContentEpoch')).toBe(0);+ const unsubscribeContent = engine.interaction.subscribe('layerPixelEpoch', contentListener);+ expect(engine.interaction.get('layerPixelEpoch')).toBe(0);raf.flush();expect(resolver).toHaveBeenCalledTimes(1);@@ -2793,7 +2809,7 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {expect(thumbnailListener).toHaveBeenCalledTimes(1);expect(engine.stores.thumbnailVersion.get('a')).toBe(2);expect(contentListener).toHaveBeenCalledTimes(1);- expect(engine.interaction.get('rasterContentEpoch')).toBe(1);+ expect(engine.interaction.get('layerPixelEpoch')).toBe(1);// The older decode may draw scratch pixels but must neither publish nor notify.deferreds.get('a')!.resolve(new Blob());@@ -2835,6 +2851,41 @@ type ControlPaintHarnessOverrides = Partial<Omit<CanvasControlLayerContract, 'sosource: CanvasControlLayerContract['source'];};+/**+ * A stub backend whose readbacks change with each draw, so a real write is distinguishable from a no-op (edits that+ * change nothing record nothing). `pixelWrites.enabled` can be toggled mid-test.+ */+const createPixelWritingBackend = <Backend extends StubRasterBackend = StubRasterBackend>(+ pixelWrites: { enabled: boolean } = { enabled: true },+ baseBackend: Backend = createTestStubRasterBackend() as Backend+): Backend => {+ return {+ ...baseBackend,+ createSurface: (width, height) => {+ const surface = baseBackend.createSurface(width, height);+ const originalCtx = surface.ctx;+ const ctx = new Proxy(originalCtx, {+ get(target, property, receiver) {+ const value = Reflect.get(target, property, receiver);+ if (property !== 'getImageData' || typeof value !== 'function') {+ return value;+ }+ return (...args: unknown[]) => {+ const imageData = Reflect.apply(value, target, args) as ImageData;+ if (pixelWrites.enabled && imageData.data.length > 0) {+ const drawCount = surface.callLog.filter((entry) => entry.op === 'drawImage').length;+ imageData.data[0] = drawCount % 256;+ }+ return imageData;+ };+ },+ });+ Object.defineProperty(surface, 'ctx', { configurable: true, value: ctx });+ return surface;+ },+ };+};+interface ControlPaintHarnessOptions {bitmapStoreFactory?: (deps: {backend: StubRasterBackend;@@ -2871,33 +2922,7 @@ const createPixelEditHarness = (width: 100,};const { projectId, store } = createReducerBackedStore(document);- const baseBackend = createTestStubRasterBackend();- const pixelWrites = options.pixelWrites ?? { enabled: true };- const backend: StubRasterBackend = {- ...baseBackend,- createSurface: (width, height) => {- const surface = baseBackend.createSurface(width, height);- const originalCtx = surface.ctx;- const ctx = new Proxy(originalCtx, {- get(target, property, receiver) {- const value = Reflect.get(target, property, receiver);- if (property !== 'getImageData' || typeof value !== 'function') {- return value;- }- return (...args: unknown[]) => {- const imageData = Reflect.apply(value, target, args) as ImageData;- if (pixelWrites.enabled && imageData.data.length > 0) {- const drawCount = surface.callLog.filter((entry) => entry.op === 'drawImage').length;- imageData.data[0] = drawCount % 256;- }- return imageData;- };- },- });- Object.defineProperty(surface, 'ctx', { configurable: true, value: ctx });- return surface;- },- };+ const backend = createPixelWritingBackend(options.pixelWrites);const bitmapStore = options.bitmapStoreFactory?.({ backend, projectId, store }) ?? createSpyBitmapStore();const engine = createCanvasEngine({backend,@@ -3152,11 +3177,11 @@ describe('engine-owned pixel editing', () => {expect(h.bitmapStore.markLayerDirty).toHaveBeenCalledWith('image');expect(h.engine.stores.canUndo.get()).toBe(true);- h.engine.history.undo();+ await h.engine.history.undo();expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);expect(h.engine.stores.canRedo.get()).toBe(true);- h.engine.history.redo();+ await h.engine.history.redo();expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);h.engine.lifecycle.dispose();});@@ -3335,10 +3360,8 @@ describe('engine-owned pixel editing', () => {expect(restored.surface).toBe(before.surface);expect(restored.rect).toEqual(before.rect);expect(restored.guard.cacheVersion).toBe(before.version);- const finalWrite = (restored.surface as StubRasterSurface).callLog- .filter((entry) => entry.op === 'putImageData')- .at(-1);- expect(finalWrite?.args[0]).toMatchObject({ height: before.rect.height, width: before.rect.width });+ // The stroke lay outside the original extent, so restoring it is returning the surface to that extent.+ expect([restored.surface.width, restored.surface.height]).toEqual([before.rect.width, before.rect.height]);}expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();@@ -3551,12 +3574,12 @@ describe('engine-owned pixel editing', () => {h.bitmapStore.releaseSuspendedLayer.mock.invocationCallOrder[0]!);- h.engine.history.undo();+ await h.engine.history.undo();expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);expect(h.engine.stores.canUndo.get()).toBe(false);expect(h.engine.stores.canRedo.get()).toBe(true);- h.engine.history.redo();+ await h.engine.history.redo();expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);h.engine.lifecycle.dispose();});@@ -3659,7 +3682,7 @@ describe('engine-owned pixel editing', () => {h.engine.lifecycle.dispose();});- it('normalizes a transformed empty control before its first brush stroke', () => {+ it('normalizes a transformed empty control before its first brush stroke', async () => {const h = createControlPaintHarness({source: { bitmap: null, type: 'paint' },transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 30, y: 40 },@@ -3673,7 +3696,7 @@ describe('engine-owned pixel editing', () => {transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'control',});- h.engine.history.undo();+ await h.engine.history.undo();expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toMatchObject({transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 30, y: 40 },});@@ -3906,7 +3929,7 @@ describe('engine-owned history: stroke → undo → redo', () => {engine.lifecycle.dispose();});- it('records a stroke and restores before/after pixels on undo/redo', () => {+ it('records a stroke and restores before/after pixels on undo/redo', async () => {const { bitmapStore, commitEdit, engine, strokes, surfaces } = drawStroke();// One stroke committed and one history entry recorded.@@ -3923,7 +3946,7 @@ describe('engine-owned history: stroke → undo → redo', () => {// Undo restores pre-stroke pixels and marks dirty. The content-sized cache starts at the dirty-rect origin, so// restoration lands at (0,0).- engine.history.undo();+ await engine.history.undo();const undoPut = putImageDataCalls(surfaces).find((call) => call.image === event.beforeImageData);expect(undoPut).toBeDefined();expect(undoPut!.x).toBe(0);@@ -3933,7 +3956,7 @@ describe('engine-owned history: stroke → undo → redo', () => {expect(bitmapStore.markLayerDirty.mock.calls.length).toBeGreaterThan(dirtyAfterStroke);// Redo: putImageData(after) restores the post-stroke pixels.- engine.history.redo();+ await engine.history.redo();const redoPut = putImageDataCalls(surfaces).find((call) => call.image === event.afterImageData);expect(redoPut).toBeDefined();expect(engine.stores.canUndo.get()).toBe(true);@@ -3943,7 +3966,7 @@ describe('engine-owned history: stroke → undo → redo', () => {engine.lifecycle.dispose();});- it('round-trips pixels exactly across a cache-growing stroke → undo → redo', () => {+ it('round-trips pixels exactly across a cache-growing stroke → undo → redo', async () => {// Multiple pointer batches grow the cache; integrated undo/redo must restore exact pixels over the full grown// extent.const raf = createControllableRaf();@@ -4002,7 +4025,7 @@ describe('engine-owned history: stroke → undo → redo', () => {expect(event.afterImageData.height).toBe(event.dirtyRect.height);// Undo restores exact pre-stroke pixels at (0,0), since cache and padded dirty rect share an origin.- engine.history.undo();+ await engine.history.undo();const undoPut = putImageDataCalls(surfaces).find((call) => call.image === event.beforeImageData);expect(undoPut).toBeDefined();expect(undoPut!.x).toBe(0);@@ -4011,7 +4034,7 @@ describe('engine-owned history: stroke → undo → redo', () => {expect(engine.stores.canRedo.get()).toBe(true);// Redo writes the EXACT post-stroke ImageData back — a lossless round-trip.- engine.history.redo();+ await engine.history.redo();const redoPut = putImageDataCalls(surfaces).find((call) => call.image === event.afterImageData);expect(redoPut).toBeDefined();expect(redoPut!.x).toBe(0);@@ -4159,7 +4182,7 @@ describe('engine-owned history: stroke → undo → redo', () => {});describe('engine-owned history: undo/redo guarded during an active gesture', () => {- it('no-ops undo/redo mid-stroke, then works after the gesture ends', () => {+ it('no-ops undo/redo mid-stroke, then works after the gesture ends', async () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -4212,15 +4235,15 @@ describe('engine-owned history: undo/redo guarded during an active gesture', ()const putsMidGesture = putImageDataCalls(surfaces);// Mid-gesture undo/redo must leave history and the entire pixel-write log unchanged.- engine.history.undo();- engine.history.redo();+ await engine.history.undo();+ await engine.history.redo();expect(engine.stores.canUndo.get()).toBe(true);expect(putImageDataCalls(surfaces)).toEqual(putsMidGesture);// End the gesture; now undo works and writes the newest stroke's before pixels.overlay.fire('pointerup', pointerAt(60, 60, { buttons: 0 }));expect(strokes).toHaveLength(2);- engine.history.undo();+ await engine.history.undo();expect(putImageDataCalls(surfaces).some((call) => call.image === strokes[1]!.beforeImageData)).toBe(true);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(true);@@ -4259,7 +4282,7 @@ describe('commitStructural', () => {engine.lifecycle.dispose();});- it('dispatches forward immediately and records a reversible history entry', () => {+ it('dispatches forward immediately and records a reversible history entry', async () => {const { store } = createFakeStore(makeDoc());const dispatch = store.dispatch as Mock;const engine = createCanvasEngine({@@ -4278,13 +4301,13 @@ describe('commitStructural', () => {expect(engine.stores.canRedo.get()).toBe(false);// Undo dispatches the inverse and flips the stacks.- engine.history.undo();+ await engine.history.undo();expect(dispatch).toHaveBeenNthCalledWith(2, inverse);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);// Redo re-dispatches the forward.- engine.history.redo();+ await engine.history.redo();expect(dispatch).toHaveBeenNthCalledWith(3, forward);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -4342,7 +4365,7 @@ describe('commitStructural', () => {engine.lifecycle.dispose();});- it('moves a refused undo as a no-op instead of throwing out of history', () => {+ it('moves a refused undo as a no-op instead of throwing out of history', async () => {const layer = rasterLayer('L');const { dispatch, projectId, store } = createReducerBackedStore({...makeDoc(),@@ -4368,7 +4391,7 @@ describe('commitStructural', () => {).toEqual({ status: 'committed' });dispatch({ ids: ['added'], type: 'removeCanvasLayers' });- expect(() => engine.history.undo()).not.toThrow();+ expect(await engine.history.undo()).toBe('applied');expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);expect(reportError).toHaveBeenCalledWith(@@ -5321,7 +5344,7 @@ describe('mergeLayerDown', () => {raf.flush();const surfacesBeforeMerge = surfaces.length;- expect(engine.layers.mergeLayerDown('upper')).toBe(true);+ expect(engine.layers.mergeLayerDown('upper')).toBe('merged');// The reducer is asked to collapse the two layers into a paint layer.const mergeCall = dispatch.mock.calls@@ -5333,8 +5356,11 @@ describe('mergeLayerDown', () => {upperLayerId: 'upper',});- // Below-local union of {0,0,60,60} and {20,20,40,40} remains 60x60 at the origin.- const merged = surfaces[surfacesBeforeMerge];+ // Below-local union of {0,0,60,60} and {20,20,40,40} remains 60x60 at the origin. Undo snapshots of both+ // sources are allocated alongside; the merged surface is the one cleared and composited into.+ const merged = surfaces+ .slice(surfacesBeforeMerge)+ .find((surface) => surface.callLog.some((entry) => entry.op === 'clearRect'));expect(merged).toBeDefined();expect(merged!.width).toBe(60);expect(merged!.height).toBe(60);@@ -5399,7 +5425,7 @@ describe('mergeLayerDown', () => {engine.surface.attach(screen.element, overlay.element);raf.flush();- expect(engine.layers.mergeLayerDown('below')).toBe(false);+ expect(engine.layers.mergeLayerDown('below')).toBe('unsupported');expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(false);@@ -5434,7 +5460,7 @@ describe('mergeLayerDown', () => {engine.surface.attach(screen.element, overlay.element);raf.flush();- expect(engine.layers.mergeLayerDown('upper')).toBe(false);+ expect(engine.layers.mergeLayerDown('upper')).toBe('unsupported');expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(false);@@ -5495,16 +5521,24 @@ describe('mergeLayerDown', () => {raf.flush();const surfacesBeforeMerge = surfaces.length;- expect(engine.layers.mergeLayerDown('upper')).toBe(true);+ expect(engine.layers.mergeLayerDown('upper')).toBe('merged');// Single-dispatch collapse still happens (undo semantics unchanged).expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(true);- const merged = surfaces[surfacesBeforeMerge];+ const created = surfaces.slice(surfacesBeforeMerge);+ const merged = created.find((surface) => surface.callLog.some((entry) => entry.op === 'clearRect'));expect(merged).toBeDefined();const draws = merged!.callLog.filter((entry) => entry.op === 'drawImage');+ // No surface the merge allocated is ever drawn from while empty.+ for (const surface of created) {+ for (const draw of surface.callLog.filter((entry) => entry.op === 'drawImage')) {+ const src = draw.args[0] as { width: number; height: number };+ expect(src.width * src.height).toBeGreaterThan(0);+ }+ }expect(draws).toHaveLength(1);for (const draw of draws) {const src = draw.args[0] as { width: number; height: number };@@ -5517,7 +5551,7 @@ describe('mergeLayerDown', () => {);// Two empty layers must still collapse, allowing merge-visible to make progress.- it('folds a both-empty pair trivially: dispatches the collapse and allocates no merged surface (F4)', async () => {+ it('folds a both-empty pair trivially: dispatches the collapse and allocates only empty surfaces (F4)', async () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -5558,15 +5592,17 @@ describe('mergeLayerDown', () => {raf.flush();const surfacesBeforeMerge = surfaces.length;- expect(engine.layers.mergeLayerDown('upper')).toBe(true);+ expect(engine.layers.mergeLayerDown('upper')).toBe('merged');// The collapse still dispatches (the upper layer is removed).expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(true);- // Only the merged layer's empty cache is allocated; zero-sized union canvases would throw.- expect(surfaces.length).toBe(surfacesBeforeMerge + 1);- expect(surfaces.at(-1)).toMatchObject({ height: 0, width: 0 });+ // Every allocation (undo snapshots, the merged layer's cache) is empty, and nothing draws from one.+ const created = surfaces.slice(surfacesBeforeMerge);+ expect(created.length).toBeGreaterThan(0);+ expect(created.every((surface) => surface.width === 0 && surface.height === 0)).toBe(true);+ expect(created.every((surface) => surface.callLog.every((entry) => entry.op !== 'drawImage'))).toBe(true);// The merged layer is empty, not lost: the paint barrier succeeds.await expect(engine.lifecycle.flushPendingUploads()).resolves.toBeUndefined();@@ -5601,7 +5637,7 @@ describe('mergeLayerDown', () => {engine.surface.attach(screen.element, overlay.element);raf.flush();- expect(engine.layers.mergeLayerDown('upper')).toBe(false);+ expect(engine.layers.mergeLayerDown('upper')).toBe('unsupported');expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(false);@@ -5635,7 +5671,7 @@ describe('mergeLayerDown', () => {engine.surface.attach(screen.element, overlay.element);raf.flush();- expect(engine.layers.mergeLayerDown('upper')).toBe(false);+ expect(engine.layers.mergeLayerDown('upper')).toBe('unsupported');expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(false);@@ -5708,13 +5744,13 @@ describe('boolean raster operations', () => {expect(getDocumentLeaves(merged).find((layer) => layer.id === 'upper')?.isEnabled).toBe(false);expect(getDocumentLeaves(merged).find((layer) => layer.id === 'below')?.isEnabled).toBe(false);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => [layer.id, layer.isEnabled])).toEqual([['upper', true],['below', true],]);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => [layer.id, layer.isEnabled])).toEqual([[result!.id, true],['upper', false],@@ -5916,9 +5952,9 @@ describe('extract masked canvas area', () => {true);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(false);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);engine.lifecycle.dispose();});@@ -6199,7 +6235,7 @@ describe('staged result acceptance', () => {selectedImageIndex,});- it('commits through the project-bound engine and preserves layer identity and staging semantics across undo/redo', () => {+ it('commits through the project-bound engine and preserves layer identity and staging semantics across undo/redo', async () => {const reducer = createReducerBackedStore({ ...makeDoc(), selectedLayerId: 'a' });const candidate = stagedCandidate();reducer.store.dispatch({@@ -6232,7 +6268,7 @@ describe('staged result acceptance', () => {expect(projectAfterCommit.canvas.stagingArea.pendingImages).toEqual([]);expect(acceptedEvent.type).toBe('canvas-layer-accepted');- engine.history.undo();+ await engine.history.undo();const projectAfterUndo = reducer.store.getState().projects[0]!;expect(getDocumentLeaves(projectAfterUndo.canvas.document)).not.toContainEqual(expect.objectContaining({ id: result.layerId })@@ -6240,14 +6276,14 @@ describe('staged result acceptance', () => {expect(projectAfterUndo.canvas.document.selectedLayerId).toBe('a');expect(projectAfterUndo.canvas.stagingArea.pendingImages).toEqual([]);- engine.history.redo();+ await engine.history.redo();const projectAfterRedo = reducer.store.getState().projects[0]!;expect(getDocumentLeaves(projectAfterRedo.canvas.document)[0]).toBe(acceptedLayer);expect(projectAfterRedo.canvas.stagingArea.pendingImages).toEqual([]);expect(projectAfterRedo.events).toContain(acceptedEvent);expect(projectAfterRedo.events.filter((event) => event.id === acceptedEvent.id)).toHaveLength(1);- engine.history.undo();+ await engine.history.undo();expect(engine.stores.canRedo.get()).toBe(true);reducer.store.dispatch({candidate: { ...candidate, imageName: 'new-staged-result.png' },@@ -6727,14 +6763,14 @@ describe('structural raster publication failure atomicity', () => {const committedCache = await snapshotLayerCache(harness.engine, harness.source.id);armStructuralFault(harness.faults, failure, { allocation: 0, draw: 0 });- expect(() => harness.engine.history.undo()).toThrow(structuralFaultMessage(failure));+ expect(await harness.engine.history.undo()).toBe('failed');expect(harness.engine.document.getDocument()).toBe(committedDocument);expect(harness.engine.document.getDocument()).toEqual(committedDocument);expect(harness.engine.stores.canUndo.get()).toBe(true);expect(harness.engine.stores.canRedo.get()).toBe(false);await expectLayerCacheExact(harness.engine, harness.source.id, committedCache);- harness.engine.history.undo();+ await harness.engine.history.undo();expect(harness.engine.document.getDocument()).toEqual(harness.originalDocument);harness.engine.lifecycle.dispose();}@@ -6745,19 +6781,19 @@ describe('structural raster publication failure atomicity', () => {async (failure) => {const harness = await createCropReplayHarness();const committedDocument = structuredClone(harness.engine.document.getDocument()!);- harness.engine.history.undo();+ await harness.engine.history.undo();const restoredDocument = harness.engine.document.getDocument()!;const restoredCache = await snapshotLayerCache(harness.engine, harness.source.id);armStructuralFault(harness.faults, failure, { allocation: 0, draw: 0 });- expect(() => harness.engine.history.redo()).toThrow(structuralFaultMessage(failure));+ expect(await harness.engine.history.redo()).toBe('failed');expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(harness.originalDocument);expect(harness.engine.stores.canUndo.get()).toBe(false);expect(harness.engine.stores.canRedo.get()).toBe(true);await expectLayerCacheExact(harness.engine, harness.source.id, restoredCache);- harness.engine.history.redo();+ await harness.engine.history.redo();expect(harness.engine.document.getDocument()).toEqual(committedDocument);harness.engine.lifecycle.dispose();}@@ -6783,11 +6819,11 @@ describe('structural raster publication failure atomicity', () => {)).toBe(true);const committedDocument = structuredClone(harness.engine.document.getDocument()!);- harness.engine.history.undo();+ await harness.engine.history.undo();const restoredDocument = harness.engine.document.getDocument()!;harness.faults.armDraw(0);- expect(() => harness.engine.history.redo()).toThrow('structural cache draw failed');+ await expectReplayFailure(harness.engine.history.redo(), 'structural cache draw failed');expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(originalDocument);@@ -6795,7 +6831,7 @@ describe('structural raster publication failure atomicity', () => {expect(harness.engine.stores.canUndo.get()).toBe(false);expect(harness.engine.stores.canRedo.get()).toBe(true);await expectLayerCacheExact(harness.engine, source.id, originalCache);- harness.engine.history.redo();+ await harness.engine.history.redo();expect(harness.engine.document.getDocument()).toEqual(committedDocument);expect(getDocumentLeaves(harness.engine.document.getDocument()!).filter((layer) => layer.id === copy.id)@@ -6828,26 +6864,26 @@ describe('structural raster publication failure atomicity', () => {const committedCache = await snapshotLayerCache(harness.engine, source.id);harness.faults.armDraw(0);- expect(() => harness.engine.history.undo()).toThrow('structural cache draw failed');+ await expectReplayFailure(harness.engine.history.undo(), 'structural cache draw failed');expect(harness.engine.document.getDocument()).toBe(committedDocument);expect(harness.engine.stores.canUndo.get()).toBe(true);expect(harness.engine.stores.canRedo.get()).toBe(false);await expectLayerCacheExact(harness.engine, source.id, committedCache);- harness.engine.history.undo();+ await harness.engine.history.undo();expect(harness.engine.document.getDocument()).toEqual(originalDocument);const restoredDocument = harness.engine.document.getDocument()!;const restoredCache = await snapshotLayerCache(harness.engine, source.id);harness.faults.armAllocation(0);- expect(() => harness.engine.history.redo()).toThrow('structural cache allocation failed');+ await expectReplayFailure(harness.engine.history.redo(), 'structural cache allocation failed');expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(originalDocument);expect(harness.engine.stores.canUndo.get()).toBe(false);expect(harness.engine.stores.canRedo.get()).toBe(true);await expectLayerCacheExact(harness.engine, source.id, restoredCache);- harness.engine.history.redo();+ await harness.engine.history.redo();expect(harness.engine.document.getDocument()).toEqual(committedDocument);harness.engine.lifecycle.dispose();});@@ -6866,11 +6902,11 @@ describe('structural raster publication failure atomicity', () => {await expect(harness.engine.layers.booleanMergeRasterLayers('upper', 'exclude')).resolves.toBe('merged');const committedDocument = structuredClone(harness.engine.document.getDocument()!);const resultId = harness.engine.document.getDocument()!.selectedLayerId!;- harness.engine.history.undo();+ await harness.engine.history.undo();const restoredDocument = harness.engine.document.getDocument()!;harness.faults.armDraw(0);- expect(() => harness.engine.history.redo()).toThrow('structural cache draw failed');+ await expectReplayFailure(harness.engine.history.redo(), 'structural cache draw failed');expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(originalDocument);@@ -6881,7 +6917,7 @@ describe('structural raster publication failure atomicity', () => {expect(harness.engine.stores.canRedo.get()).toBe(true);await expectLayerCacheExact(harness.engine, 'upper', upperCache);await expectLayerCacheExact(harness.engine, 'below', belowCache);- harness.engine.history.redo();+ await harness.engine.history.redo();expect(harness.engine.document.getDocument()).toEqual(committedDocument);harness.engine.lifecycle.dispose();});@@ -6912,11 +6948,11 @@ describe('structural raster publication failure atomicity', () => {throw new Error('expected masked extraction');}const committedDocument = structuredClone(harness.engine.document.getDocument()!);- harness.engine.history.undo();+ await harness.engine.history.undo();const restoredDocument = harness.engine.document.getDocument()!;harness.faults.armDraw(0);- expect(() => harness.engine.history.redo()).toThrow('structural cache draw failed');+ await expectReplayFailure(harness.engine.history.redo(), 'structural cache draw failed');expect(harness.engine.document.getDocument()).toBe(restoredDocument);expect(harness.engine.document.getDocument()).toEqual(originalDocument);@@ -6928,7 +6964,7 @@ describe('structural raster publication failure atomicity', () => {await expectLayerCacheExact(harness.engine, mask.id, maskCache);await expectLayerCacheExact(harness.engine, 'upper', upperCache);await expectLayerCacheExact(harness.engine, 'below', belowCache);- harness.engine.history.redo();+ await harness.engine.history.redo();expect(harness.engine.document.getDocument()).toEqual(committedDocument);harness.engine.lifecycle.dispose();});@@ -6942,10 +6978,9 @@ describe('structural raster publication failure atomicity', () => {};const harness = createFaultHarness(document);const originalDocument = harness.engine.document.getDocument()!;- const copiedId = await harness.engine.layers.copyLayerToRaster(source.id);- expect(copiedId).not.toBeNull();+ expect((await harness.engine.layers.copyLayerToRaster(source.id)).status).toBe('copied');- harness.engine.history.undo();+ await harness.engine.history.undo();expect(harness.engine.document.getDocument()).toEqual(originalDocument);expect(harness.engine.document.getDocument()!.selectedLayerId).toBe('selection-sentinel');@@ -6959,13 +6994,14 @@ describe('structural raster publication failure atomicity', () => {const sentinel = sentinelLayer();const document = { ...makeDoc(), stacks: stacksFrom([source, sentinel]), selectedLayerId: sentinel.id };const harness = createFaultHarness(document);- const copiedId = await harness.engine.layers.copyLayerToRaster(source.id);- expect(copiedId).not.toBeNull();+ const copied = await harness.engine.layers.copyLayerToRaster(source.id);+ expect(copied.status).toBe('copied');+ const copiedId = copied.status === 'copied' ? copied.layerId : null;harness.store.dispatch({ ids: [sentinel.id], type: 'removeCanvasLayers' });expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copiedId)).toBe(true);- expect(() => harness.engine.history.undo()).toThrow('Canvas document mutation was rejected');+ await expectReplayFailure(harness.engine.history.undo(), /rejected/);expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copiedId)).toBe(true);expect(harness.engine.stores.canUndo.get()).toBe(true);expect(harness.engine.stores.canRedo.get()).toBe(false);@@ -6975,7 +7011,7 @@ describe('structural raster publication failure atomicity', () => {layer: sentinel,type: 'addCanvasLayer',});- expect(() => harness.engine.history.undo()).not.toThrow();+ expect(await harness.engine.history.undo()).toBe('applied');expect(getDocumentLeaves(harness.engine.document.getDocument()!).some((layer) => layer.id === copiedId)).toBe(false);@@ -7153,7 +7189,7 @@ describe('mergeVisibleRasterLayers', () => {...baseMutationPort,dispatch: (mutation, origin) => (rejectMutations ? false : baseMutationPort.dispatch(mutation, origin)),};- const base = createTestStubRasterBackend();+ const base = createPixelWritingBackend();const surfaces: StubRasterSurface[] = [];const backend: StubRasterBackend = {...base,@@ -7226,7 +7262,7 @@ describe('mergeVisibleRasterLayers', () => {expect(engine.exports.hasExportableLayerContent(upperCopyId!)).toBe(true);expect(engine.exports.hasExportableLayerContent(belowCopyId!)).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['mid-mask','upper',@@ -7235,7 +7271,7 @@ describe('mergeVisibleRasterLayers', () => {expect(engine.document.getDocument()!.selectedLayerId).toBe('upper');expect(getPanelSelectedIds()).toEqual(['upper', 'below']);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['mid-mask',upperCopyId,@@ -7258,9 +7294,7 @@ describe('mergeVisibleRasterLayers', () => {setPanelSelectedIds(['upper', 'below']);setRejectMutations(true);- await expect(engine.layers.duplicateLayers(['upper', 'below'])).rejects.toThrow(- 'Canvas document mutation was rejected'- );+ expect(await engine.layers.duplicateLayers(['upper', 'below'])).toEqual({ status: 'stale' });expect(getPanelSelectedIds()).toEqual(['upper', 'below']);expect(selectionChanges).toHaveLength(0);expect(engine.stores.canUndo.get()).toBe(false);@@ -7274,18 +7308,18 @@ describe('mergeVisibleRasterLayers', () => {expect(selectionChanges).toHaveLength(1);setRejectMutations(true);- expect(() => engine.history.undo()).toThrow('Canvas document mutation was rejected');+ await expectReplayFailure(engine.history.undo(), /rejected/);expect(getPanelSelectedIds()).toEqual(result.duplicateIds);expect(selectionChanges).toHaveLength(1);expect(engine.stores.canUndo.get()).toBe(true);setRejectMutations(false);- engine.history.undo();+ await engine.history.undo();expect(getPanelSelectedIds()).toEqual(['upper', 'below']);expect(selectionChanges).toHaveLength(2);setRejectMutations(true);- expect(() => engine.history.redo()).toThrow('Canvas document mutation was rejected');+ await expectReplayFailure(engine.history.redo(), /rejected/);expect(getPanelSelectedIds()).toEqual(['upper', 'below']);expect(selectionChanges).toHaveLength(2);expect(engine.stores.canRedo.get()).toBe(true);@@ -7320,13 +7354,13 @@ describe('mergeVisibleRasterLayers', () => {expect(bitmapStore.markLayerDirty).toHaveBeenCalledWith(result.duplicateIds[0]);expect(bitmapStore.markLayerDirty).not.toHaveBeenCalledWith('upper');- engine.history.undo();+ await engine.history.undo();const restored = await engine.exports.exportLayerPixels(result.duplicateIds[0]!);expect(restored.status).toBe('ok');// Past the selection's own step, then the duplicate itself.- engine.history.undo();- engine.history.undo();- engine.history.redo();+ await engine.history.undo();+ await engine.history.undo();+ await engine.history.redo();const redone = await engine.exports.exportLayerPixels(result.duplicateIds[0]!);expect(redone.status).toBe('ok');if (restored.status === 'ok' && redone.status === 'ok') {@@ -7421,7 +7455,7 @@ describe('mergeVisibleRasterLayers', () => {expect(engine.document.getDocument()!.selectedLayerId).toBe(merged.id);expect(getPanelSelectedIds()).toEqual([merged.id]);- engine.history.undo();+ await engine.history.undo();const restored = engine.document.getDocument()!;expect(haveSameStructure(restored.stacks, before.stacks)).toBe(true);expect(@@ -7434,7 +7468,7 @@ describe('mergeVisibleRasterLayers', () => {expect(engine.exports.hasExportableLayerContent('below')).toBe(true);expect(getPanelSelectedIds()).toEqual(['upper', 'below']);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['mid-mask', merged.id]);expect(engine.exports.hasExportableLayerContent(merged.id)).toBe(true);expect(getPanelSelectedIds()).toEqual([merged.id]);@@ -7450,9 +7484,8 @@ describe('mergeVisibleRasterLayers', () => {setPanelSelectedIds(['upper', 'below']);setRejectMutations(true);- await expect(engine.layers.mergeSelectedRasterLayers(['upper', 'below'])).rejects.toThrow(- 'Canvas document mutation was rejected'- );+ // A reducer refusal is a reported outcome, with nothing recorded or published.+ expect(await engine.layers.mergeSelectedRasterLayers(['upper', 'below'])).toBe('failed');expect(getPanelSelectedIds()).toEqual(['upper', 'below']);expect(selectionChanges).toHaveLength(0);expect(engine.stores.canUndo.get()).toBe(false);@@ -7464,17 +7497,17 @@ describe('mergeVisibleRasterLayers', () => {expect(selectionChanges).toHaveLength(1);setRejectMutations(true);- expect(() => engine.history.undo()).toThrow('Canvas document mutation was rejected');+ await expectReplayFailure(engine.history.undo(), /rejected/);expect(getPanelSelectedIds()).toEqual([resultId]);expect(selectionChanges).toHaveLength(1);setRejectMutations(false);- engine.history.undo();+ await engine.history.undo();expect(getPanelSelectedIds()).toEqual(['upper', 'below']);expect(selectionChanges).toHaveLength(2);setRejectMutations(true);- expect(() => engine.history.redo()).toThrow('Canvas document mutation was rejected');+ await expectReplayFailure(engine.history.redo(), /rejected/);expect(getPanelSelectedIds()).toEqual(['upper', 'below']);expect(selectionChanges).toHaveLength(2);expect(engine.stores.canRedo.get()).toBe(true);@@ -7597,11 +7630,11 @@ describe('mergeVisibleRasterLayers', () => {}const duplicateId = result.duplicateIds[0]!;- engine.history.undo();+ await engine.history.undo();expect(await engine.lifecycle.beginCooldown()).toBe('cooled');engine.lifecycle.activate();const beforeRedo = surfaces.length;- engine.history.redo();+ await engine.history.redo();await flushMicrotasks();expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(@@ -7628,9 +7661,9 @@ describe('mergeVisibleRasterLayers', () => {throw new Error(`unexpected duplicate result: ${result.status}`);}expect(surfaces).toHaveLength(beforeDuplicate + 2);- engine.history.undo();+ await engine.history.undo();const beforeRedo = surfaces.length;- engine.history.redo();+ await engine.history.redo();expect(surfaces).toHaveLength(beforeRedo + 1);expect(engine.exports.hasExportableLayerContent(result.duplicateIds[0]!)).toBe(true);engine.lifecycle.dispose();@@ -7817,11 +7850,11 @@ describe('mergeVisibleRasterLayers', () => {expect(await engine.layers.mergeVisibleRasterLayers()).toBe('merged');const merged = engine.document.getDocument()!.stacks.raster[0]!;- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(getDocumentLeaves(before));expect(engine.document.getDocument()!.selectedLayerId).toBe(before.selectedLayerId);- engine.history.redo();+ await engine.history.redo();expect(engine.document.getDocument()!.stacks.raster[0]).toEqual(merged);expect(getDocumentLeaves(engine.document.getDocument()!).filter((layer) => layer.id !== merged.id)).toEqual(getDocumentLeaves(before)@@ -7947,7 +7980,7 @@ describe('rasterizeLayer (parametric → paint)', () => {const { dispatch, engine, surfaces } = setup(shapeLayerDoc());const before = surfaces.length;- expect(engine.layers.rasterizeLayer('shape1')).toBe(true);+ expect(engine.layers.rasterizeLayer('shape1')).toBe('rasterized');const converts = convertCalls(dispatch);expect(converts).toHaveLength(1);@@ -7972,11 +8005,11 @@ describe('rasterizeLayer (parametric → paint)', () => {engine.lifecycle.dispose();});- it('undo re-converts to the ORIGINAL parametric source (no pixel snapshot)', () => {+ it('undo re-converts to the ORIGINAL parametric source (no pixel snapshot)', async () => {const { dispatch, engine } = setup(shapeLayerDoc());engine.layers.rasterizeLayer('shape1');- engine.history.undo();+ await engine.history.undo();const converts = convertCalls(dispatch);// forward convert + undo convert.expect(converts).toHaveLength(2);@@ -7997,7 +8030,7 @@ describe('rasterizeLayer (parametric → paint)', () => {}// Redo re-applies the paint conversion (bitmap:null at the baked offset).- engine.history.redo();+ await engine.history.redo();const afterRedo = convertCalls(dispatch);expect(afterRedo).toHaveLength(3);if (afterRedo[2]?.type === 'convertCanvasLayer' && afterRedo[2].layer.type === 'raster') {@@ -8006,19 +8039,19 @@ describe('rasterizeLayer (parametric → paint)', () => {engine.lifecycle.dispose();});- it('redo re-bakes from params rather than pinning the doc-sized surface (byte-budget honesty)', () => {+ it('redo re-bakes from params rather than pinning the doc-sized surface (byte-budget honesty)', async () => {// Redo must rebake; capturing the full baked surface under a 256-byte history entry bypasses the history// memory budget.const { engine, surfaces } = setup(shapeLayerDoc());- expect(engine.layers.rasterizeLayer('shape1')).toBe(true);+ expect(engine.layers.rasterizeLayer('shape1')).toBe('rasterized');const afterApply = surfaces.length;- engine.history.undo();+ await engine.history.undo();// Undo only re-converts (a dispatch) — it bakes nothing.expect(surfaces.length).toBe(afterApply);- engine.history.redo();+ await engine.history.redo();expect(surfaces.length).toBeGreaterThan(afterApply);const rebaked = surfaces.at(-1);expect(rebaked?.width).toBe(60);@@ -8035,15 +8068,15 @@ describe('rasterizeLayer (parametric → paint)', () => {source: { angle: 45, kind: 'linear', stops: [{ color: '#000', offset: 0 }], type: 'gradient' },} as CanvasLayerContract;const { dispatch, engine } = setup(doc);- expect(engine.layers.rasterizeLayer('shape1')).toBe(true);+ expect(engine.layers.rasterizeLayer('shape1')).toBe('rasterized');expect(convertCalls(dispatch)).toHaveLength(1);engine.lifecycle.dispose();});it('is a no-op for a locked layer, a missing layer, and a non-parametric (paint) layer', () => {const { dispatch, engine } = setup(shapeLayerDoc({ isLocked: true }));- expect(engine.layers.rasterizeLayer('shape1')).toBe(false);- expect(engine.layers.rasterizeLayer('nope')).toBe(false);+ expect(engine.layers.rasterizeLayer('shape1')).toBe('locked');+ expect(engine.layers.rasterizeLayer('nope')).toBe('missing');expect(convertCalls(dispatch)).toHaveLength(0);engine.lifecycle.dispose();@@ -8053,7 +8086,7 @@ describe('rasterizeLayer (parametric → paint)', () => {source: { bitmap: null, type: 'paint' },} as CanvasLayerContract;const paint = setup(paintDoc);- expect(paint.engine.layers.rasterizeLayer('shape1')).toBe(false);+ expect(paint.engine.layers.rasterizeLayer('shape1')).toBe('unsupported');paint.engine.lifecycle.dispose();});@@ -8126,18 +8159,18 @@ describe('rasterizeLayer (parametric → paint)', () => {* Drives rasterize and undo through mirrored conversions, restoring the parametric source while leaving the* paint dirty mark pending.*/- const rasterizeThenUndo = () => {+ const rasterizeThenUndo = async () => {vi.useFakeTimers();let doc = shapeLayerDoc();const harness = setupWithRealBitmapStore(doc);const { dispatch, engine, raf, setDocument } = harness;- expect(engine.layers.rasterizeLayer('shape1')).toBe(true);+ expect(engine.layers.rasterizeLayer('shape1')).toBe('rasterized');doc = applyLastConvert(doc, dispatch);setDocument(doc);raf.flush();- engine.history.undo();+ await engine.history.undo();doc = applyLastConvert(doc, dispatch);setDocument(doc);raf.flush();@@ -8155,7 +8188,7 @@ describe('rasterizeLayer (parametric → paint)', () => {);it('await flushPendingUploads(): the layer stays the parametric shape and no paint dispatch fires', async () => {- const { dispatch, engine, uploadImage } = rasterizeThenUndo();+ const { dispatch, engine, uploadImage } = await rasterizeThenUndo();await engine.lifecycle.flushPendingUploads();@@ -8169,7 +8202,7 @@ describe('rasterizeLayer (parametric → paint)', () => {});it('advancing the debounce timer: the layer stays the parametric shape and no paint dispatch fires', async () => {- const { dispatch, engine, uploadImage } = rasterizeThenUndo();+ const { dispatch, engine, uploadImage } = await rasterizeThenUndo();await vi.advanceTimersByTimeAsync(1500);@@ -8189,7 +8222,7 @@ describe('rasterizeLayer (parametric → paint)', () => {const { dispatch, engine, raf, setDocument, uploadImage } = setupWithRealBitmapStore(doc);// Rasterize → bake to paint → flush lands img-x.- expect(engine.layers.rasterizeLayer('shape1')).toBe(true);+ expect(engine.layers.rasterizeLayer('shape1')).toBe('rasterized');doc = applyLastConvert(doc, dispatch);setDocument(doc);raf.flush();@@ -8213,13 +8246,13 @@ describe('rasterizeLayer (parametric → paint)', () => {raf.flush();// Undo → back to the parametric shape source.- engine.history.undo();+ await engine.history.undo();doc = applyLastConvert(doc, dispatch);setDocument(doc);raf.flush();// Redo resets to paint with null bitmap until the next persistence flush.- engine.history.redo();+ await engine.history.redo();doc = applyLastConvert(doc, dispatch);setDocument(doc);raf.flush();@@ -8262,7 +8295,7 @@ describe('rasterizeLayer (parametric → paint)', () => {let doc = shapeLayerDoc();const { dispatch, engine, raf, setDocument, uploadImage } = setupWithRealBitmapStore(doc);- expect(engine.layers.rasterizeLayer('shape1')).toBe(true);+ expect(engine.layers.rasterizeLayer('shape1')).toBe('rasterized');doc = applyLastConvert(doc, dispatch);setDocument(doc);raf.flush();@@ -8330,7 +8363,7 @@ describe('nudgeSelectedLayer', () => {engine.lifecycle.dispose();});- it('dispatches a transform update and records an undoable entry', () => {+ it('dispatches a transform update and records an undoable entry', async () => {const { dispatch, engine } = setup(selectedImageDoc());engine.layers.nudgeSelectedLayer(3, -2);expect(dispatch).toHaveBeenCalledTimes(1);@@ -8341,7 +8374,7 @@ describe('nudgeSelectedLayer', () => {expect(engine.stores.canUndo.get()).toBe(true);// Undo dispatches the inverse (back to the original position).- engine.history.undo();+ await engine.history.undo();expect(dispatch).toHaveBeenNthCalledWith(2, {type: 'setCanvasLayerPositions',updates: [{ id: 'a', x: 0, y: 0 }],@@ -8349,7 +8382,7 @@ describe('nudgeSelectedLayer', () => {engine.lifecycle.dispose();});- it('nudges every selected layer together and undoes the batch atomically', () => {+ it('nudges every selected layer together and undoes the batch atomically', async () => {const doc = selectedImageDoc();const second = { ...rasterLayer('b'), transform: { ...rasterLayer('b').transform, x: 10, y: 20 } };const { dispatch, engine } = setup({ ...doc, stacks: stacksFrom([getDocumentLeaves(doc)[0]!, second]) }, [@@ -8366,7 +8399,7 @@ describe('nudgeSelectedLayer', () => {],});- engine.history.undo();+ await engine.history.undo();expect(dispatch).toHaveBeenNthCalledWith(2, {type: 'setCanvasLayerPositions',updates: [@@ -8377,7 +8410,7 @@ describe('nudgeSelectedLayer', () => {engine.lifecycle.dispose();});- it('coalesces a rapid same-layer burst into one history entry', () => {+ it('coalesces a rapid same-layer burst into one history entry', async () => {vi.spyOn(Date, 'now').mockReturnValue(1_000);const { engine } = setup(selectedImageDoc());engine.layers.nudgeSelectedLayer(1, 0);@@ -8385,13 +8418,13 @@ describe('nudgeSelectedLayer', () => {engine.layers.nudgeSelectedLayer(1, 0);// A single undo empties the stack: the burst collapsed to one entry.expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();vi.restoreAllMocks();});- it('starts a fresh entry once the coalescing window elapses', () => {+ it('starts a fresh entry once the coalescing window elapses', async () => {const now = vi.spyOn(Date, 'now');now.mockReturnValue(1_000);const { engine } = setup(selectedImageDoc());@@ -8399,9 +8432,9 @@ describe('nudgeSelectedLayer', () => {now.mockReturnValue(2_000); // > 500ms laterengine.layers.nudgeSelectedLayer(1, 0);// Two distinct entries: one undo still leaves something to undo.- engine.history.undo();+ await engine.history.undo();expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();vi.restoreAllMocks();@@ -8489,7 +8522,7 @@ const imageSelectedDoc = (): CanvasDocumentContractV3 => ({});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', () => {+ it('undo removes the auto-created layer (no pixel restore); redo re-adds it and re-applies the stroke', async () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -8550,7 +8583,7 @@ describe('engine-owned history: composed auto-create + stroke entry', () => {const putBefore = () => putImageDataCalls(surfaces).some((call) => call.image === strokes[0]!.beforeImageData);const beforeUndoPutBefore = putBefore();- engine.history.undo();+ await engine.history.undo();const removeAfterUndo = dispatch.mock.calls.map((call) => call[0] as EngineTestAction).filter((action) => action.type === 'removeCanvasLayers');@@ -8562,7 +8595,7 @@ describe('engine-owned history: composed auto-create + stroke entry', () => {expect(engine.stores.canRedo.get()).toBe(true);// Redo: re-adds the layer and re-applies the stroke's after pixels.- engine.history.redo();+ await engine.history.redo();const addAfterRedo = dispatch.mock.calls.map((call) => call[0] as EngineTestAction).filter((action) => action.type === 'addCanvasLayer');@@ -8896,7 +8929,7 @@ describe('commitRasterFilterResult', () => {}const forwardSources = backend.drawSourcesFor(forwardExport.surface as StubRasterSurface);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(before);expect(engine.stores.canUndo.get()).toBe(false);const undoExport = await engine.exports.exportLayerPixels(layer.id);@@ -8910,7 +8943,7 @@ describe('commitRasterFilterResult', () => {);}- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(after);expect(engine.stores.canRedo.get()).toBe(false);const redoExport = await engine.exports.exportLayerPixels(layer.id);@@ -8973,14 +9006,14 @@ describe('commitRasterFilterResult', () => {expect('adjustments' in copy).toBe(false);expect((await engine.exports.exportLayerPixels(result.layerId)).status).toBe('ok');- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).map((candidate) => candidate.id)).toEqual(['source','below',]);expect(engine.document.getDocument()!.selectedLayerId).toBe(below.id);expect(engine.stores.canUndo.get()).toBe(false);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).map((candidate) => candidate.id)).toEqual([result.layerId,'source',@@ -9038,9 +9071,9 @@ describe('commitRasterFilterResult', () => {transform: source.transform,type: 'control',});- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(before);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(after);engine.lifecycle.dispose();});@@ -9204,7 +9237,7 @@ describe('commitRasterFilterResult', () => {(store.dispatch as Mock).mockClear();faults.arm(failure);- expect(() => engine.history.undo()).toThrow(`replay cache ${failure} failed`);+ await expectReplayFailure(engine.history.undo(), `replay cache ${failure} failed`);expect(engine.document.getDocument()).toEqual(expectedDocument);expect(engine.stores.canUndo.get()).toBe(true);@@ -9222,7 +9255,7 @@ describe('commitRasterFilterResult', () => {expect((afterFailure.surface as StubRasterSurface).callLog).toEqual(expectedCalls);}- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(source);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);@@ -9257,7 +9290,7 @@ describe('commitRasterFilterResult', () => {});expect(result.status).toBe('committed');const filteredDocument = structuredClone(engine.document.getDocument()!);- engine.history.undo();+ await engine.history.undo();const expectedDocument = structuredClone(engine.document.getDocument()!);const expectedCache = await engine.exports.exportLayerPixels(source.id);if (expectedCache.status !== 'ok') {@@ -9271,7 +9304,7 @@ describe('commitRasterFilterResult', () => {(store.dispatch as Mock).mockClear();faults.arm(failure);- expect(() => engine.history.redo()).toThrow(`replay cache ${failure} failed`);+ await expectReplayFailure(engine.history.redo(), `replay cache ${failure} failed`);expect(engine.document.getDocument()).toEqual(expectedDocument);expect(engine.stores.canUndo.get()).toBe(false);@@ -9289,7 +9322,7 @@ describe('commitRasterFilterResult', () => {expect((afterFailure.surface as StubRasterSurface).callLog).toEqual(expectedCalls);}- engine.history.redo();+ await engine.history.redo();expect(engine.document.getDocument()).toEqual(filteredDocument);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -9324,9 +9357,9 @@ describe('commitRasterFilterResult', () => {).resolves.toEqual({ layerId: source.id, status: 'committed' });expect(bitmapStore.discardLayer).toHaveBeenCalledTimes(1);- engine.history.undo();+ await engine.history.undo();bitmapStore.markLayerDirty.mockClear();- engine.history.redo();+ await engine.history.redo();expect(bitmapStore.discardLayer).toHaveBeenCalledTimes(2);expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();@@ -9371,7 +9404,7 @@ describe('commitRasterFilterResult', () => {};const { projectId, store } = createReducerBackedStore(filterDoc([source]));const backend = {- ...createRecordingRasterBackend(),+ ...createPixelWritingBackend(undefined, createRecordingRasterBackend()),encodeSurface: vi.fn(() => Promise.resolve(new Blob(['paint-pixels'], { type: 'image/png' }))),};let bitmapCall = 0;@@ -9528,13 +9561,13 @@ describe('commitRasterFilterResult', () => {).resolves.toEqual({ layerId: harness.source.id, status: 'committed' });const committed = structuredClone(harness.engine.document.getDocument()!);- harness.engine.history.undo();+ await harness.engine.history.undo();await harness.refreshPlacement();const barrier = harness.bitmapStore.flushPendingUploads();await drainUntil(() => uploadImage.mock.calls.length === 1);expect(uploadImage).toHaveBeenCalledOnce();- harness.engine.history.redo();+ await harness.engine.history.redo();await harness.refreshPlacement();expect(harness.engine.document.getDocument()).toEqual(committed);uploaded.resolve({ height: 10, imageName: 'stale-undo-paint', width: 10 });@@ -9580,12 +9613,12 @@ describe('commitRasterFilterResult', () => {// Undo the paint edit and the selection, then undo the copy itself. Redo// reuses the exact layer id while the pre-undo upload is still unresolved.- harness.engine.history.undo();+ await harness.engine.history.undo();await harness.refreshPlacement(copied.layerId);- harness.engine.history.undo();- harness.engine.history.undo();+ await harness.engine.history.undo();+ await harness.engine.history.undo();expect((await harness.engine.exports.exportLayerPixels(copied.layerId)).status).toBe('missing');- harness.engine.history.redo();+ await harness.engine.history.redo();expect(getDocumentLeaves(harness.engine.document.getDocument()!).find((layer) => layer.id === copied.layerId)).toEqual(durableCopy);@@ -9644,7 +9677,7 @@ describe('commitRasterFilterResult', () => {throw new Error('expected a committed copy');}const copy = structuredClone(getDocumentLeaves(engine.document.getDocument()!)[0]!);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(beforeDocument);const adjustedDeletesBefore = adjustedSurfaceCacheDeletes.length;const thumbnailListener = vi.fn();@@ -9653,7 +9686,7 @@ describe('commitRasterFilterResult', () => {(store.dispatch as Mock).mockClear();faults.arm(failure);- expect(() => engine.history.redo()).toThrow(`replay cache ${failure} failed`);+ expect(await engine.history.redo()).toBe('failed');expect(engine.document.getDocument()).toEqual(beforeDocument);expect(engine.document.getDocument()!.selectedLayerId).toBe(selected.id);@@ -9665,7 +9698,7 @@ describe('commitRasterFilterResult', () => {expect(thumbnailListener).not.toHaveBeenCalled();expect(adjustedSurfaceCacheDeletes).toHaveLength(adjustedDeletesBefore);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(copy);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect((await engine.exports.exportLayerPixels(result.layerId)).status).toBe('ok');@@ -10291,7 +10324,7 @@ describe('commitRasterFilterResult', () => {throw new Error('copy undo observer failed');});- expect(() => engine.history.undo()).not.toThrow();+ expect(await engine.history.undo()).toBe('applied');expect(engine.document.getDocument()).toEqual(beforeDocument);expect(engine.document.getDocument()!.selectedLayerId).toBe(selected.id);@@ -10300,7 +10333,7 @@ describe('commitRasterFilterResult', () => {expect(engine.stores.canRedo.get()).toBe(true);unsubscribeFault();- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(copy);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect(engine.stores.canUndo.get()).toBe(true);@@ -10308,7 +10341,7 @@ describe('commitRasterFilterResult', () => {engine.lifecycle.dispose();});- it('keeps copy undo retryable when removal fails after restoring the prior selection', async () => {+ it('keeps copy undo retryable and the copy selected when its removal fails', async () => {const source = filterLayer('source');const selected = filterLayer('selected');const beforeDocument = { ...filterDoc([source, selected]), selectedLayerId: selected.id };@@ -10339,21 +10372,21 @@ describe('commitRasterFilterResult', () => {}let failRemoval = true;dispatch.mockImplementation((action: EngineTestAction) => {- if (failRemoval && action.type === 'removeCanvasLayers') {+ if (failRemoval && action.type === 'applyCanvasLayerStackMutation') {failRemoval = false;throw new Error('copy removal failed');}reducerDispatch(action);});- expect(() => engine.history.undo()).toThrow('copy removal failed');+ expect(await engine.history.undo()).toBe('failed');expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);- expect(engine.document.getDocument()!.selectedLayerId).toBe(selected.id);+ expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(beforeDocument);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);@@ -10631,12 +10664,12 @@ describe('commitGeneratedImageResult', () => {}expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(before);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(after);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -10673,9 +10706,9 @@ describe('commitGeneratedImageResult', () => {source: { bitmap: generatedImage, offset: generatedOrigin, type: 'paint' },transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },});- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toEqual(source);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]).toMatchObject({adapter: source.type === 'control' ? source.adapter : undefined,filter: source.type === 'control' ? source.filter : undefined,@@ -10730,10 +10763,10 @@ describe('commitGeneratedImageResult', () => {});expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);- engine.history.redo();+ await engine.history.redo();expect(engine.document.getDocument()!.stacks.raster[0]?.id).toBe(result.layerId);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect(engine.stores.canRedo.get()).toBe(false);@@ -11249,23 +11282,23 @@ describe('commitGeneratedImageResult', () => {const committed = structuredClone(engine.document.getDocument()!);faults.armAllocation(0);- expect(() => engine.history.undo()).toThrow('generated cache allocation failed');+ await expectReplayFailure(engine.history.undo(), 'generated cache allocation failed');expect(engine.document.getDocument()).toEqual(committed);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);faults.armDraw(0);- expect(() => engine.history.redo()).toThrow('generated cache draw failed');+ await expectReplayFailure(engine.history.redo(), 'generated cache draw failed');expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);- engine.history.redo();+ await engine.history.redo();expect(engine.document.getDocument()).toEqual(committed);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);@@ -11300,17 +11333,17 @@ describe('commitGeneratedImageResult', () => {}const committed = structuredClone(engine.document.getDocument()!);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);faults.armAllocation(0);- expect(() => engine.history.redo()).toThrow('generated cache allocation failed');+ await expectReplayFailure(engine.history.redo(), 'generated cache allocation failed');expect(engine.document.getDocument()).toEqual(document);expect(engine.document.getDocument()!.selectedLayerId).toBe(selected.id);expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(false);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);- engine.history.redo();+ await engine.history.redo();expect(engine.document.getDocument()).toEqual(committed);expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);expect(engine.stores.canUndo.get()).toBe(true);@@ -11871,14 +11904,14 @@ describe('commitMaskImageResult', () => {expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);expect(engine.document.getDocument()!.selectedLayerId).toBe('below');expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);expect(engine.history.getHeldAssetRefs().images).toContain(resultImage.imageName);- engine.history.redo();+ await engine.history.redo();expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === result.layerId)).toEqual(created);@@ -11925,7 +11958,7 @@ describe('commitMaskImageResult', () => {expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);engine.lifecycle.dispose();});@@ -11957,7 +11990,7 @@ describe('commitMaskImageResult', () => {throw new Error('mask undo observer failed');});- expect(() => engine.history.undo()).not.toThrow();+ expect(await engine.history.undo()).toBe('applied');expect(engine.document.getDocument()).toEqual(document);expect(engine.document.getDocument()!.selectedLayerId).toBe('below');@@ -11967,7 +12000,7 @@ describe('commitMaskImageResult', () => {engine.lifecycle.dispose();});- it('keeps mask undo failure-atomic when restoring the prior selection fails before reducer application', async () => {+ it('keeps mask undo failure-atomic when its removal fails before reducer application', async () => {const document = docFor('inpaint_mask');const { dispatch, projectId, store } = createReducerBackedStore(document);const engine = createCanvasEngine({@@ -11995,72 +12028,22 @@ describe('commitMaskImageResult', () => {if (!reducerDispatch) {throw new Error('expected reducer-backed dispatch');}- let failSelection = true;- dispatch.mockImplementation((action: EngineTestAction) => {- if (failSelection && action.type === 'setCanvasSelectedLayer') {- failSelection = false;- throw new Error('mask selection restore failed');- }- reducerDispatch(action);- });-- expect(() => engine.history.undo()).toThrow('mask selection restore failed');-- expect(engine.document.getDocument()).toEqual(committedDocument);- expect(engine.stores.canUndo.get()).toBe(true);- expect(engine.stores.canRedo.get()).toBe(false);-- engine.history.undo();- expect(engine.document.getDocument()).toEqual(document);- expect(engine.stores.canUndo.get()).toBe(false);- expect(engine.stores.canRedo.get()).toBe(true);- engine.lifecycle.dispose();- });-- it('keeps mask undo retryable when removal fails after restoring the prior selection', async () => {- const document = docFor('regional_guidance');- const { dispatch, projectId, store } = createReducerBackedStore(document);- const engine = createCanvasEngine({- backend: createTestStubRasterBackend(),- bitmapStore: createSpyBitmapStore(),- imageResolver: () => Promise.resolve(new Blob()),- projectId,- store,- });- const exported = await engine.exports.exportLayerPixels('source');- if (exported.status !== 'ok') {- throw new Error('expected an export guard');- }- const result = await engine.layers.commitMaskImageResult({- guard: exported.guard,- image: resultImage,- rect: resultRect,- target: 'regional_guidance',- });- if (result.status !== 'committed') {- throw new Error('expected a committed mask');- }- const reducerDispatch = dispatch.getMockImplementation();- if (!reducerDispatch) {- throw new Error('expected reducer-backed dispatch');- }let failRemoval = true;dispatch.mockImplementation((action: EngineTestAction) => {- if (failRemoval && action.type === 'removeCanvasLayers') {+ if (failRemoval && action.type === 'applyCanvasLayerStackMutation') {failRemoval = false;throw new Error('mask removal failed');}reducerDispatch(action);});- expect(() => engine.history.undo()).toThrow('mask removal failed');+ expect(await engine.history.undo()).toBe('failed');- expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === result.layerId)).toBe(true);- expect(engine.document.getDocument()!.selectedLayerId).toBe('below');+ expect(engine.document.getDocument()).toEqual(committedDocument);expect(engine.stores.canUndo.get()).toBe(true);expect(engine.stores.canRedo.get()).toBe(false);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);expect(engine.stores.canRedo.get()).toBe(true);@@ -12866,10 +12849,10 @@ describe('guarded filter previews', () => {expect(committedExport.status === 'ok' ? committedExport.rect : null).toEqual(expectedRect);expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);- engine.history.redo();+ await engine.history.redo();const redone = getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === committedId)!;expect(redone).toEqual(committed);expect(engine.stores.canRedo.get()).toBe(false);@@ -12910,7 +12893,7 @@ describe('guarded filter previews', () => {type: sourceType,});expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(engine.document.getDocument()).toEqual(document);expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();@@ -12936,7 +12919,7 @@ describe('guarded filter previews', () => {transform: source.transform,});expect(engine.stores.canUndo.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual([source]);expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();@@ -13100,10 +13083,8 @@ describe('guarded filter previews', () => {expect(engine.stores.documentEditingLocked.get()).toBe(true);expect(engine.stores.documentEditingLayerId.get()).toBe('L');- engine.history.undo();- expect(- engine.layers.applyStructuralPreview({ id: 'L', patch: { opacity: 0.2 }, type: 'updateCanvasLayer' })- ).toBe(false);+ await engine.history.undo();+ expect(engine.layers.beginStructuralPreview()).toBeNull();engine.layers.commitStructural('Blocked rename',{ id: 'L', patch: { name: 'Blocked' }, type: 'updateCanvasLayer' },@@ -13135,7 +13116,7 @@ describe('guarded filter previews', () => {}expect(engine.stores.documentEditingLocked.get()).toBe(false);expect(engine.stores.documentEditingLayerId.get()).toBeNull();- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!)[0]?.name).toBe('L');engine.lifecycle.dispose();}@@ -13407,7 +13388,7 @@ describe('guarded filter previews', () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);- const backend = createRecordingRasterBackend();+ const backend = createPixelWritingBackend(undefined, createRecordingRasterBackend());const sourceNeedsBitmap =layer.type === 'raster' &&(layer.source.type === 'image' || (layer.source.type === 'paint' && layer.source.bitmap !== null));@@ -13911,9 +13892,9 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',)).toBe(true);expect((await engine.exports.exportLayerPixels(copy.id)).status).toBe('ok');- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).some((layer) => layer.id === copy.id)).toBe(false);- engine.history.redo();+ await engine.history.redo();expect((await engine.exports.exportLayerPixels(copy.id)).status).toBe('ok');expect(engine.layers.commitLayerConversion('Convert layer', raster, control)).toBe(true);@@ -13921,7 +13902,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)','control');expect((await engine.exports.exportLayerPixels(raster.id)).status).toBe('ok');- engine.history.undo();+ await engine.history.undo();expect(getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === raster.id)?.type).toBe('raster');@@ -14419,15 +14400,15 @@ describe('gesture guard: nudge / commitStructural mid-stroke', () => {overlay.fire('pointerdown', pointerAt(20, 20));overlay.fire('pointermove', pointerAt(30, 30));- // Mid-gesture merge is refused (matches commitStructural/nudge): not undoable.- expect(engine.layers.mergeLayerDown('upper')).toBe(false);+ // Mid-gesture merge is refused before anything changes, like commitStructural/nudge.+ expect(engine.layers.mergeLayerDown('upper')).toBe('busy');expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(false);// After the gesture ends, the merge lands.overlay.fire('pointerup', pointerAt(30, 30, { buttons: 0 }));- expect(engine.layers.mergeLayerDown('upper')).toBe(true);+ expect(engine.layers.mergeLayerDown('upper')).toBe('merged');expect(dispatch.mock.calls.some((call) => (call[0] as EngineTestAction).type === 'mergeCanvasLayersDown')).toBe(true);@@ -15015,7 +14996,7 @@ describe('fitToView: content ∪ bbox', () => {// ---- transform session: param commit (image) + pixel bake (paint) ----------describe('transform session', () => {- it('image layer Apply commits one structural transform with the exact inverse', () => {+ it('image layer Apply commits one structural transform with the exact inverse', async () => {const { store } = createReactiveStore(selectedImageDoc());const dispatch = store.dispatch as Mock;const engine = createCanvasEngine({@@ -15046,7 +15027,7 @@ describe('transform session', () => {// Undo dispatches the exact inverse (the captured start transform).dispatch.mockClear();- engine.history.undo();+ await engine.history.undo();const undoDispatch = dispatch.mock.calls.map((call) => call[0] as EngineTestAction).find((action) => action.type === 'updateCanvasLayer');@@ -15059,7 +15040,7 @@ describe('transform session', () => {engine.lifecycle.dispose();});- it('parametric (text) layer Apply commits ONE param transform, stays type text, no bake; undo restores', () => {+ it('parametric (text) layer Apply commits ONE param transform, stays type text, no bake; undo restores', async () => {const textLayerDoc: CanvasDocumentContractV3 = {background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },@@ -15120,7 +15101,7 @@ describe('transform session', () => {expect(engine.stores.transformSession.get()).toBeNull();dispatch.mockClear();- engine.history.undo();+ await engine.history.undo();const undo = dispatch.mock.calls.map((call) => call[0] as EngineTestAction).find((a) => a.type === 'updateCanvasLayer');@@ -15197,7 +15178,7 @@ describe('transform session', () => {engine.lifecycle.dispose();});- it('paint layer Apply bakes pixels through the matrix, resets the transform, and composes one undo entry', () => {+ it('paint layer Apply bakes pixels through the matrix, resets the transform, and composes one undo entry', async () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);@@ -15284,7 +15265,7 @@ describe('transform session', () => {// Undo restores BOTH the old transform and the old pixels in one step.dispatch.mockClear();- engine.history.undo();+ await engine.history.undo();const undoDispatch = dispatch.mock.calls.map((call) => call[0] as EngineTestAction).find((action) => action.type === 'updateCanvasLayer');@@ -15538,7 +15519,7 @@ describe('engine selection: select all / deselect / invert + hasSelection store'engine.lifecycle.dispose();});- it('selection changes are their own history steps, undone and redone through the engine', () => {+ it('selection changes are their own history steps, undone and redone through the engine', async () => {vi.stubGlobal('Path2D',class FakePath2D {@@ -15560,11 +15541,11 @@ describe('engine selection: select all / deselect / invert + hasSelection store'engine.selection.deselect();expect(engine.history.getEntries().past).toEqual(['Select all', 'Deselect']);- engine.history.undo();+ await engine.history.undo();expect(engine.stores.hasSelection.get()).toBe(true);- engine.history.undo();+ await engine.history.undo();expect(engine.stores.hasSelection.get()).toBe(false);- engine.history.redo();+ await engine.history.redo();expect(engine.stores.hasSelection.get()).toBe(true);expect(engine.history.getEntries()).toEqual({ future: ['Deselect'], past: ['Select all'] });engine.lifecycle.dispose();@@ -15590,7 +15571,7 @@ describe('engine selection: fill / erase', () => {const { store } = createFakeStore(doc);const bitmapStore = createSpyBitmapStore();const engine = createCanvasEngine({- backend: createTestStubRasterBackend(),+ backend: createPixelWritingBackend(),bitmapStore,imageResolver: () => Promise.resolve(new Blob()),projectId: 'p1',@@ -15637,9 +15618,9 @@ describe('engine selection: fill / erase', () => {}const after = structuredClone(getDocumentLeaves(h.engine.document.getDocument()!)[0]);expect(after).toMatchObject({ id: 'control', source: { type: 'paint' }, type: 'control' });- h.engine.history.undo();+ await h.engine.history.undo();expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(before);- h.engine.history.redo();+ await h.engine.history.redo();expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]).toEqual(after);h.engine.lifecycle.dispose();});@@ -15811,13 +15792,14 @@ describe('engine selection: fill / erase', () => {let didThrow = false;vi.spyOn(h.backend, 'createSurface').mockImplementation((width, height) => {const surface = createSurface(width, height);- const resize = surface.resize.bind(surface);- surface.resize = (nextWidth, nextHeight) => {+ // The touched-region rollback shrinks the grown materialized cache back to its baked extent.+ const resizePreserving = surface.resizePreserving.bind(surface);+ surface.resizePreserving = (nextWidth, nextHeight, dx, dy) => {if (!didThrow && surface.width === 100 && nextWidth === 20 && nextHeight === 20) {didThrow = true;throw new Error('selection rollback restoration failed');}- resize(nextWidth, nextHeight);+ resizePreserving(nextWidth, nextHeight, dx, dy);};return surface;});@@ -15891,11 +15873,13 @@ describe('engine selection: fill / erase', () => {expect(h.engine.document.getDocument()).toEqual(beforeDocument);expect(editSteps(h.engine)).toEqual([]);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();- expect(capturedReads[0]).toMatchObject({ height: 10, width: 10 });- expect(capturedReads.at(-1)).toMatchObject({ height: 5, width: 5 });+ // Only the touched region is captured, and that capture is what goes back.+ expect(capturedReads[0]).toMatchObject({ height: 5, width: 5 });expect((beforeCache.surface as StubRasterSurface).callLog.filter((entry) => entry.op === 'putImageData').at(-1)?.args[0]).toBe(capturedReads[0]);+ const restored = await h.engine.exports.exportLayerPixels('control', { includeDisabled: true });+ expect(restored.status === 'ok' && restored.guard.cacheVersion).toBe(beforeCache.version);Object.defineProperty(beforeCache.surface, 'ctx', { configurable: true, value: originalCtx });h.engine.selection.fillSelection();@@ -15982,7 +15966,7 @@ describe('engine selection: fill / erase', () => {h.engine.lifecycle.dispose();});- it('fillSelection on the selected paint layer records one undoable edit + persists', () => {+ it('fillSelection on the selected paint layer records one undoable edit + persists', async () => {const { bitmapStore, engine } = makeEngine(paintDoc());engine.selection.selectAll();expect(editSteps(engine)).toEqual([]);@@ -15990,7 +15974,7 @@ describe('engine selection: fill / erase', () => {expect(editSteps(engine)).toEqual(['Fill selection']);expect(bitmapStore.markLayerDirty).toHaveBeenCalledWith('paint1');// Undo restores (canRedo becomes available).- engine.history.undo();+ await engine.history.undo();expect(engine.stores.canRedo.get()).toBe(true);engine.lifecycle.dispose();});@@ -16388,7 +16372,7 @@ describe('text edit session', () => {return { dispatch, engine, layerActions, setDocument };};- it('create-mode commit dispatches ONE addCanvasLayer with the typed content; undo removes it', () => {+ it('create-mode commit dispatches ONE addCanvasLayer with the typed content; undo removes it', async () => {const { dispatch, engine, layerActions } = makeEngine(paintDoc());engine.tools.setTool('text');engine.layers.openTextCreate({ x: 10, y: 20 });@@ -16409,7 +16393,7 @@ describe('text edit session', () => {expect(engine.stores.textEditSession.get()).toBeNull();dispatch.mockClear();- engine.history.undo();+ await engine.history.undo();const removes = layerActions().filter((a) => a.type === 'removeCanvasLayers');expect(removes).toHaveLength(1);engine.lifecycle.dispose();@@ -16446,7 +16430,7 @@ describe('text edit session', () => {engine.lifecycle.dispose();});- it('edit-mode commit dispatches ONE updateCanvasLayerSource with the exact inverse', () => {+ it('edit-mode commit dispatches ONE updateCanvasLayerSource with the exact inverse', async () => {const { dispatch, engine, layerActions } = makeEngine(textDoc());engine.tools.setTool('text');engine.layers.openTextEdit('txt1');@@ -16466,7 +16450,7 @@ describe('text edit session', () => {}dispatch.mockClear();- engine.history.undo();+ await engine.history.undo();const inverse = layerActions().find((a) => a.type === 'updateCanvasLayerSource');if (inverse?.type === 'updateCanvasLayerSource' && inverse.source.type === 'text') {expect(inverse.source.content).toBe('hello');@@ -17327,10 +17311,10 @@ describe('Select Object canvas engine integration', () => {expect(h.engine.stores.activeTool.get()).toBe('view');expect(h.engine.stores.canUndo.get()).toBe(true);- h.engine.history.undo();+ await h.engine.history.undo();expect(h.engine.document.getDocument()).toEqual(h.document);expect(h.engine.stores.canUndo.get()).toBe(false);- h.engine.history.redo();+ await h.engine.history.redo();expect(getDocumentLeaves(h.engine.document.getDocument()!).find((layer) => layer.id === 'source')).toEqual(replaced);@@ -17525,9 +17509,9 @@ describe('Select Object canvas engine integration', () => {getCanvasOperations(h.engine).cancelSelectObjectSession();expect(h.engine.stores.canUndo.get()).toBe(true);- h.engine.history.undo();+ await h.engine.history.undo();expect(getDocumentLeaves(h.engine.document.getDocument()).map((layer) => layer.id)).toEqual(['source']);- h.engine.history.redo();+ await h.engine.history.redo();expect(getDocumentLeaves(h.engine.document.getDocument())[0]?.type).toBe(target);h.engine.lifecycle.dispose();}@@ -17797,19 +17781,21 @@ describe('Select Object canvas engine integration', () => {throw new Error('commit rejected');});+ // The transaction judges a throwing dispatch by the reducer, which did not change: nothing was recorded.await expect(getCanvasOperations(h.engine).saveSelectObjectSession('inpaint_mask', () => Promise.resolve())- ).resolves.toEqual({- message: 'commit rejected',- status: 'failed',- });+ ).resolves.toEqual({ status: 'stale' });expect(getCanvasOperations(h.engine).stores.samSession.get()).toMatchObject({- error: { code: 'unknown', detail: 'commit rejected' },+ error: { code: 'unknown', detail: 'Select Object commit is stale.' },hasPreview: true,});expect(getCanvasOperations(h.engine).stores.samSession.get()?.input).toEqual(previewInput);expect(h.engine.document.getDocument()).toEqual(h.document);+ expect(h.engine.stores.canUndo.get()).toBe(false);+ await expect(+ getCanvasOperations(h.engine).saveSelectObjectSession('inpaint_mask', () => Promise.resolve())+ ).resolves.toMatchObject({ status: 'committed' });h.engine.lifecycle.dispose();});@@ -18495,13 +18481,93 @@ describe('history entries and stepBy', () => {expect(afterStroke.past).toHaveLength(1);expect(afterStroke.future).toHaveLength(0);- engine.history.stepBy(-1);+ await engine.history.stepBy(-1);expect(engine.history.getEntries()).toEqual({ future: afterStroke.past, past: [] });// Clamped: asking for more redos than exist replays what is there and stops.- engine.history.stepBy(5);+ await engine.history.stepBy(5);expect(engine.history.getEntries()).toEqual({ future: [], past: afterStroke.past });engine.lifecycle.dispose();});});++describe('pixel undo onto a cache that is no longer trustworthy', () => {+ it('rasterizes the layer from its source before writing the patch', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );+ const document = paintDoc();+ const persisted = {+ ...getDocumentLeaves(document)[0]!,+ source: { bitmap: { height: 100, imageName: 'persisted', width: 100 }, type: 'paint' as const },+ };+ const { store } = createReactiveStore({ ...document, stacks: stacksFrom([persisted]) });+ const imageResolver = vi.fn(() => Promise.resolve(new Blob()));+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver,+ projectId: 'p1',+ store,+ });+ const overlay = createInputCanvas();+ engine.surface.attach(createInputCanvas().element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ engine.tools.setTool('brush');+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(40, 40));+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));+ expect(engine.history.getEntries().past).toEqual(['Brush stroke']);++ await engine.diagnostics.clearCaches();+ const fetchesBeforeUndo = imageResolver.mock.calls.length;+ expect(await engine.history.undo()).toBe('applied');++ expect(imageResolver.mock.calls.length).toBeGreaterThan(fetchesBeforeUndo);+ expect(engine.history.getEntries()).toEqual({ future: ['Brush stroke'], past: [] });+ engine.lifecycle.dispose();+ });+});++describe('refused strokes', () => {+ it('reports a stroke refused before its first pixel and leaves the layer untouched', () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const { store } = createReactiveStore(paintDoc());+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const refusals: string[] = [];+ engine.tools.onEditRefused((refusal) => refusals.push(refusal));+ const overlay = createInputCanvas();+ engine.surface.attach(createInputCanvas().element, overlay.element);+ engine.tools.setTool('brush');+ engine.stores.documentEditingLocked.set(true);++ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(40, 40));+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));++ expect(refusals).toEqual(['busy']);+ expect(engine.history.getEntries().past).toEqual([]);+ expect(engine.document.getDocument()).toBe(store.getState().projects[0]!.canvas.document);+ engine.lifecycle.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 58c1edbb12..15f5f4fc78 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -1,4 +1,6 @@import type {+ CanvasEditRefusal,+ CanvasHistoryReplayStatus,CanvasHistoryCapability,CanvasDiagnosticsCapability,CanvasEngine,@@ -18,13 +20,17 @@ import type {CanvasViewportCapability,BooleanRasterOperation,BooleanRasterResult,+ CopyLayerToRasterResult,CropLayerResult,ExportBakedLayerPixelsOptions,ExportLayerPixelsOptions,ExtractMaskedAreaResult,+ MaskEditResult,+ MergeDownResult,MergeVisibleResult,NewRasterLayerResult,PsdExportResult,+ RasterizeLayerResult,StructuralCommitOptions,StructuralCommitResult,} from '@workbench/canvas-engine/capabilities';@@ -93,6 +99,7 @@ import { HistoryController } from '@workbench/canvas-engine/controllers/historyCimport { InteractionController } from '@workbench/canvas-engine/controllers/interactionController';import { LayerController } from '@workbench/canvas-engine/controllers/layerController';import {+ type CapturedLayerCache,type DuplicateLayerRasterPlan,LayerMutationController,} from '@workbench/canvas-engine/controllers/layerMutationController';@@ -184,7 +191,7 @@ import { createCompositeFrame } from './render/compositeFrame';import { floatingSelectionFrame } from './render/floatingSelectionFrame';import { createOverlayFrame } from './render/overlayFrame';import { createSelectObjectBridge } from './selectObjectBridge';-import { createStrokeCommit } from './strokeCommit';+import { createStrokeEdits } from './strokeCommit';import { createViewTool } from './tools/viewTool';/**@@ -221,7 +228,7 @@ const createCleanupAccumulator = (): { run: (step: () => void) => void; throwIfFexport interface CanvasEngineErrorReport {area: 'canvas-engine';/** The raw failure; notifications show its message and diagnostics keep its stack. */- context: { error: unknown; layerId: string };+ context: { error: unknown; layerId?: string; label?: string };message:| 'Layer thumbnail rasterization failed'| 'Bitmap persistence failed'@@ -230,7 +237,8 @@ export interface CanvasEngineErrorReport {| 'Structural edit could not be reverted'| 'Structural edit could not be mirrored'| 'Structural history replay was refused'- | 'Structural history replay could not be mirrored';+ | 'Structural history replay could not be mirrored'+ | 'History replay failed';namespace: 'canvas';projectId: string;}@@ -304,22 +312,6 @@ export interface CanvasEngineCoreComposition {readonly applicationHost: CanvasApplicationHost;}-const sourceImageName = (source: CanvasLayerSourceContract): string | null => {- if (source.type === 'image') {- return source.image.imageName;- }- if (source.type === 'paint') {- return source.bitmap?.imageName ?? null;- }- return null;-};--/** The image name a layer's source references, if any (raster/control source or mask bitmap). */-const layerImageName = (layer: CanvasLayerContract): string | null => {- const source = renderableSourceOf(layer);- return source ? sourceImageName(source) : null;-};-/** Mints a fresh layer id for engine-created paint layers. */const createLayerId = (): string => `layer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;const createEventId = (): string => `event-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;@@ -348,7 +340,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbackend,diagnostics,getDocument: () => mirror.getDocument(),- getLayerImageName: layerImageName,imageResolver,// A raster-image pixel transaction replaces the live cache with pixels that already include adjustments while// the contract keeps them until commit; applying them again would double them and snap back on pointer-up.@@ -360,7 +351,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst stores = createEngineStores();const publishLayerThumbnailVersion = (layerId: string, version: number): void => {stores.thumbnailVersion.set(layerId, version);- stores.rasterContentEpoch.set(stores.rasterContentEpoch.get() + 1);+ stores.layerPixelEpoch.set(stores.layerPixelEpoch.get() + 1);};const interactionStores: { [K in keyof CanvasInteractionState]: ScalarStore<CanvasInteractionState[K]> } = {activeTool: stores.activeTool,@@ -383,7 +374,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCinvertBrushSizeScroll: stores.invertBrushSizeScroll,lassoOptions: stores.lassoOptions,marqueeOptions: stores.marqueeOptions,- rasterContentEpoch: stores.rasterContentEpoch,+ layerPixelEpoch: stores.layerPixelEpoch,ruleOfThirds: stores.ruleOfThirds,shapeOptions: stores.shapeOptions,showBbox: stores.showBbox,@@ -628,18 +619,23 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcanEdit: () => canEditDocument(),canRedoStore: stores.canRedo,canUndoStore: stores.canUndo,- endBurst: () => endNudgeBurst(),isGestureActive: () => pipeline.isGestureActive(),+ reportFailure: (label, error) =>+ opts.reportError({+ area: 'canvas-engine',+ context: { error, label },+ message: 'History replay failed',+ namespace: 'canvas',+ projectId,+ }),});const history = historyController.history;const unsubscribeHistoryEpoch = history.subscribe(() => stores.historyEpoch.set(stores.historyEpoch.get() + 1));- const dispatchCanvasMutation = (- action: CanvasProjectMutation,- origin: 'system' | 'user' = history.isApplying() ? 'system' : 'user'- ): boolean => mutationPort.dispatch(action, origin);+ const dispatchCanvasMutation = (action: CanvasProjectMutation, origin: 'system' | 'user' = 'user'): boolean =>+ mutationPort.dispatch(action, origin);// Direct pixel writes do not replace the reducer canvas object. Snapshot- // freshness therefore also binds to this engine-local content epoch.- let rasterContentEpoch = 0;+ // freshness therefore also binds to this engine-local direct-pixel epoch.+ let directPixelEpoch = 0;const resolveSelectedLayerIds = (document: CanvasDocumentContractV3): readonly string[] => {const primaryId = document.selectedLayerId;if (!primaryId) {@@ -656,22 +652,38 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};let structuralController: StructuralLayerController;- const endNudgeBurst = (): void => structuralController.endBurst();/**- * Undo/redo restores cache pixels and marks dirty. An in-flight newer upload self-echoes without replacing- * restored pixels; the serialized follow-up flush persists the restored state.+ * Undo/redo restores cache pixels and marks dirty. A patch lands only on trustworthy pixels: an evicted or stale+ * cache is rasterized first under a read lease, and a layer that is gone moves the step as a no-op. An in-flight+ * newer upload self-echoes without replacing restored pixels; the serialized follow-up flush persists them.*/- const applyImagePatch: ImagePatchApply = (layerId, rect, pixels) => {- if (!layerCache.get(layerId)) {- // The layer's cache is gone (removed/evicted); nothing to restore into.+ const applyImagePatch: ImagePatchApply = async (layerId, rect, pixels) => {+ if (!getDocumentLayer(mirror.getDocument(), layerId)) {return;}- // Grow to the layer-local patch rect before writing; undo/redo may reach beyond a cache trimmed since capture.- const entry = layerCache.growToRect(layerId, rect);- entry.surface.ctx.putImageData(pixels, rect.x - entry.rect.x, rect.y - entry.rect.y);+ const prepared = await rasterizeLayerPixels(layerId, { includeDisabled: true });+ if (prepared.status === 'missing') {+ return;+ }+ const resident = layerCache.get(layerId);+ if (prepared.status === 'empty' && resident?.stale) {+ // The source holds no pixels now, so stale ones must not survive around the patch.+ layerCache.delete(layerId);+ } else if (prepared.status !== 'ok' && prepared.status !== 'empty' && (!resident || resident.stale)) {+ throw new Error(`Layer pixels could not be restored (${prepared.status}).`);+ }+ try {+ // Grow to the layer-local patch rect before writing; undo/redo may reach beyond a cache trimmed since capture.+ const entry = layerCache.growToRect(layerId, rect);+ entry.surface.ctx.putImageData(pixels, rect.x - entry.rect.x, rect.y - entry.rect.y);+ entry.stale = false;+ } finally {+ if (prepared.status === 'ok') {+ prepared.release();+ }+ }notifyLayerPainted(layerId);- // Re-persist the restored pixels (converges the contract ref; see above).bitmapStore.markLayerDirty(layerId);};@@ -697,7 +709,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst notifyLayerPainted = (layerId: string): void => {const entry = layerCache.publishPixels(layerId);if (entry) {- rasterContentEpoch += 1;+ directPixelEpoch += 1;publishLayerThumbnailVersion(layerId, entry.version);stores.thumbnailStatus.set(layerId, 'ready');}@@ -717,22 +729,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}};- /**- * Auto-created stroke history removes the layer on undo; redo recreates its blank cache and reapplies- * after-pixels.- */- const { commitOrdinaryStroke } = createStrokeCommit({- applyImagePatch,- commitPaintEdit: () => mutationPort.commitEdit({ kind: 'paint' }),- dispatchCanvasMutation,- endNudgeBurst,- history,- layerCache,- markLayerDirty: (layerId) => bitmapStore.markLayerDirty(layerId),- notifyLayerPainted,- strokeListeners,- });-// Engine-owned selection masks clip strokes and drive fill/erase. Marching ants redraw only the overlay while// selection exists and the engine is attached.@@ -769,7 +765,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCdispatch: (action, origin) => dispatchCanvasMutation(action, origin),editOwner: documentEditOwner,editingLocked: stores.documentEditingLocked,- endBurst: () => endNudgeBurst(),getDocument: () => mirror.getDocument(),getReducerDocument: () => mutationPort.getCanvasState()?.document ?? null,history,@@ -778,8 +773,38 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCisGuardCurrent: (guard) => isLayerExportGuardCurrent(guard),preparePixels: (layerId, rect, pixels) => prepareGeneratedPaintCache(layerId, rect, pixels),refreshMirror: () => mirror.refresh(),+ report: (error, label) =>+ reportError(+ error.outcome === 'reverted-unmirrored'+ ? 'Structural edit could not be mirrored'+ : 'Structural edit could not be reverted',+ label,+ error+ ),+ reserveRaster: (bytes) => rasterController.memory.reserveOperation(bytes, { purpose: 'layer-operation' }),subscribeReducer: (listener) => mutationPort.subscribe(listener),});+ const editRefusalListeners = new Set<(refusal: CanvasEditRefusal) => void>();+ const reportEditRefusal = (refusal: CanvasEditRefusal): void => {+ for (const listener of editRefusalListeners) {+ try {+ listener(refusal);+ } catch {+ // A faulty notice must not affect the refused edit's cleanup.+ }+ }+ };+ /** Live strokes are admitted before their first pixel; auto-created layers compose into the same undo step. */+ const strokeEdits = createStrokeEdits({+ applyImagePatch,+ commitPaintEdit: () => mutationPort.commitEdit({ kind: 'paint' }),+ ctx: mutationContext,+ layerCache,+ markLayerDirty: (layerId) => bitmapStore.markLayerDirty(layerId),+ notifyLayerPainted,+ reportRefusal: reportEditRefusal,+ strokeListeners,+ });const captureInsertionAnchor: CanvasMutationContext['captureInsertionAnchor'] = (stack, aboveId) =>mutationContext.captureInsertionAnchor(stack, aboveId);const editingController = new EditingController({@@ -787,14 +812,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCapplyImagePatch,backend,canEdit: () => canEditDocument(),- endBurst: () => endNudgeBurst(),+ ctx: mutationContext,getDocument: () => mirror.getDocument(),- history,invalidateLayer: (layerId) => scheduler.invalidate({ layers: [layerId] }),layers: layerCache,markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),notifyPainted: notifyLayerPainted,onChange: () => stores.hasFloatingSelection.set(floatingSelection.has()),+ reportRefusal: reportEditRefusal,+ suspendPersistence: (layerId) => bitmapStore.suspendLayer(layerId),},getDocument: () => mirror.getDocument(),history,@@ -813,16 +839,16 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbeginPixelEdit: (layerId) => beginPixelEdit(layerId),canEdit: () => canEditDocument(),deleteDerived: deleteDerivedSurfaces,- endBurst: () => endNudgeBurst(),getDocument: () => mirror.getDocument(),+ ctx: mutationContext,getFillColor: () => stores.brushOptions.get().color,- history,invalidateLayer: (layerId) => scheduler.invalidate({ layers: [layerId] }),isRasterCacheReady: (layer, document) => isLayerCacheReadyForOp(layer, document),isGestureActive: () => pipeline.isGestureActive(),layers: layerCache,markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),notifyPainted: notifyLayerPainted,+ reportRefusal: reportEditRefusal,requestRasterization: (layerId) => scheduleLayerRasterization([layerId]),},selectionImage: {@@ -846,21 +872,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCtransform: {backend,canEdit: () => canEditDocument(),- dispatch: (action) => dispatchCanvasMutation(action),- endBurst: () => endNudgeBurst(),+ commitStructural: (label, forward, inverse) => commitStructural(label, forward, inverse),+ ctx: mutationContext,getCache: (layerId) => layerCache.get(layerId) ?? null,getDocument: () => mirror.getDocument(),invalidate: (payload) => scheduler.invalidate(payload),isGestureActive: () => pipeline.isGestureActive(),- pushHistory: (entry) => history.push(entry),- replaceCache: (layerId, rect, surface) => {- layerCache.delete(layerId);- const target = layerCache.getOrCreateRect(layerId, rect);- target.surface.ctx.drawImage(surface.canvas, 0, 0);- target.stale = false;- notifyLayerPainted(layerId);- bitmapStore.markLayerDirty(layerId);- },+ reportRefusal: reportEditRefusal,restoreCache: restoreLayerCache,session: stores.transformSession,setOverride: (layerId, transform) => {@@ -942,7 +960,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCapplyTransform: () => applyTransform(),backend,captureInsertionAnchor,- beginPixelEdit: (layerId) => beginPixelEdit(layerId),+ beginPixelEdit: (layerId) => beginPixelEdit(layerId, { gesture: true }),beginTransformSession: (layerId) => beginTransformSession(layerId),cancelTextEdit: () => cancelTextEdit(),cancelTransform: () => cancelTransform(),@@ -966,7 +984,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcreateLayerId,createPath2D: createPath2DImpl,dispatch: (action) => dispatchCanvasMutation(action),- emitStrokeCommitted: (event) => commitOrdinaryStroke(event),+ beginStrokeEdit: (initialBytes) => strokeEdits.begin(initialBytes),getDocument: () => mirror.getDocument(),getSelectedLayerIds: () => {const document = mirror.getDocument();@@ -1113,13 +1131,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},layerCache,rasterize: (source, document, scratch, signal) => rasterizeSource(source, rasterizeDeps(document, signal), scratch),- releaseBitmapIfUnreferenced: (imageName) => rasterController.releaseBitmapIfUnreferenced(imageName),reportError,thumbnails: {setStatus: (layerId, status) => stores.thumbnailStatus.set(layerId, status),setVersion: publishLayerThumbnailVersion,},- trackPublishedLayerImage: (layer) => rasterController.trackPublishedLayerImage(layer),});structuralController = new StructuralLayerController({@@ -1246,7 +1262,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst cropLayerToBbox = (layerId: string): Promise<CropLayerResult> => layerController.crop.crop(layerId);- const copyLayerToRaster = (layerId: string): Promise<string | null> => layerController.copy.copyToRaster(layerId);+ const copyLayerToRaster = (layerId: string): Promise<CopyLayerToRasterResult> =>+ layerController.copy.copyToRaster(layerId);/*** Leases rasterized layer pixels for a composite export. Missing, ineligible or unsupported layers throw so@@ -1263,9 +1280,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCthrow new Error(`Cannot rasterize layer ${layerId} for export: ${result.status}.`);};- const releaseBitmapIfUnreferenced = (imageName: string): void =>- rasterController.releaseBitmapIfUnreferenced(imageName);-const dropLayer = (layerId: string): void => {// Generation-cancel persistence before the id can be restored by undo/redo.// A late upload from the removed incarnation must never target a recreated@@ -1398,14 +1412,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => editingController.invalidateDocument());cleanup.run(() => pipeline.cancelActiveGesture());cleanup.run(cancelOpenPixelEdit);- const previousImageNames = rasterController.mirroredImageNames();cleanup.run(() => rasterController.invalidateDocument());cleanup.run(() => stores.thumbnailStatus.clear());// Whole-document swaps invalidate pixel history. Cancel the pointer gesture first to discard stale tool// anchors and clear active-gesture state; also clear any lingering bbox preview.cleanup.run(() => stores.bboxPreview.set(null));cleanup.run(() => history.clear());- cleanup.run(endNudgeBurst);cleanup.run(() => stores.transformSession.set(null));cleanup.run(() => transformOverrides.clear());// A text-edit session likewise belongs to the outgoing document; drop it.@@ -1423,21 +1435,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => stores.marqueePreview.set(null));const doc = mirror.getDocument();const present = new Set(doc ? getDocumentLeaves(doc).map((layer) => layer.id) : []);- rasterController.clearMirroredImages();rasterController.clearThumbnailKeys();for (const layer of getDocumentLeaves(doc)) {rasterController.setThumbnailKey(layer.id, getLayerThumbnailDisplayKey(layer));- const imageName = layerImageName(layer);- if (imageName) {- rasterController.setMirroredImage(layer.id, imageName);- }}- const trackedIds = rasterController.trackedImageIds();- for (const layerId of trackedIds) {+ for (const layerId of layerCache.layerIds()) {if (!present.has(layerId)) {cleanup.run(() => dropLayer(layerId));- } else {- cleanup.run(() => rasterController.untrackLayerImage(layerId));}}// Invalidate every incoming cache on wholesale replacement: reused ids may still hold outgoing pixels,@@ -1445,9 +1449,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCfor (const layerId of present) {cleanup.run(() => invalidateLayerCache(layerId));}- for (const imageName of previousImageNames) {- cleanup.run(() => releaseBitmapIfUnreferenced(imageName));- }// Discard old-document self-echo and pending persistence state before ids are reused.cleanup.run(() => bitmapStore.reset());cleanup.run(() => scheduler.invalidate({ all: true }));@@ -1485,16 +1486,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => editingController.invalidateLayer(id));}const sourceChanged = new Set(sourceChangedIds);- const previousImageNames = new Map(ids.map((id) => [id, rasterController.getMirroredImage(id)]));- for (const id of ids) {- const layer = getDocumentLayer(doc, id);- const imageName = layer ? layerImageName(layer) : null;- if (imageName) {- rasterController.setMirroredImage(id, imageName);- } else {- rasterController.deleteMirroredImage(id);- }- }// Remove transform sessions and preview overrides when their layer disappears, even during temporary tool// switches.const session = stores.transformSession.get();@@ -1507,16 +1498,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreChasTransformSession: session?.layerId === id,isSelfEcho: () => bitmapStore.isSelfEcho(id, getLayerSourceById(id)),layer: getDocumentLayer(doc, id) ?? undefined,- previousImageName: previousImageNames.get(id),sourceChanged: sourceChanged.has(id),});if (decision.kind === 'removed') {- const { releaseImageName } = decision;rasterController.deleteThumbnailKey(id);cleanup.run(() => dropLayer(id));- if (releaseImageName) {- cleanup.run(() => releaseBitmapIfUnreferenced(releaseImageName));- }// Removed preview layers must drop decoded pixels and advance decode tokens so late results or restored// ids cannot revive stale previews.cleanup.run(() => clearFilterPreview(id));@@ -1539,12 +1525,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}continue;}- const { releaseImageName } = decision;rasterController.setThumbnailKey(id, decision.thumbnailKey);- cleanup.run(() => rasterController.untrackLayerImage(id));- if (releaseImageName) {- cleanup.run(() => releaseBitmapIfUnreferenced(releaseImageName));- }if (decision.invalidateCache) {cleanup.run(() => invalidateLayerCache(id));}@@ -1613,10 +1594,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCfor (const layer of getDocumentLeaves(mirror.getDocument())) {rasterController.setThumbnailKey(layer.id, getLayerThumbnailDisplayKey(layer));- const imageName = layerImageName(layer);- if (imageName) {- rasterController.setMirroredImage(layer.id, imageName);- }}// A guarded filter preview belongs to one continuous active-project epoch.@@ -1798,6 +1775,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetToolContext: () => toolContext,handleEscape: handleEscapePriority,hasTool: (id) => tools.has(id),+ isReplaying: () => history.isReplaying(),// A primary-button pointerdown while a text-edit session is open commits it// (engine reads the live portal content). The pipeline swallows that press.maybeCommitModalSession: () => commitOpenTextSession(),@@ -2012,7 +1990,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}};- const getReducerDocument = (): CanvasDocumentContractV3 | null => mutationPort.getCanvasState()?.document ?? null;const getMainModelBase = (): string | null => {return opts.getMainModelBase?.() ?? null;};@@ -2020,8 +1997,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn opts.getDefaultControlModel?.(base) ?? null;};- const dispatchPreparedMutation = mutationContext.dispatchPrepared;-/** Conversion reducers clone contracts, so their publication postcondition compares by value. */const documentHasLayerContract = (document: CanvasDocumentContractV3 | null,@@ -2036,19 +2011,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbackend,bitmapStore,canEdit: () => canEditDocument(),+ ctx: mutationContext,deleteDerived: deleteDerivedSurfaces,- dispatchReplacement: (layer) =>- dispatchPreparedMutation(- { layer, layerId: layer.id, type: 'replaceCanvasLayer' },- () => documentHasLayerContract(getReducerDocument(), layer),- () => documentHasLayerContract(mirror.getDocument(), layer)- ),- endBurst: () => endNudgeBurst(),getActiveProjectId: () => projectId,getAdjustedSurface,getDocument: () => mirror.getDocument(),getTransformSession: () => stores.transformSession.get(),- history,installPrepared: installGeneratedPaintCache,invalidate: (layerId, overlay) => scheduler.invalidate({ layers: [layerId], overlay: overlay || undefined }),isCacheReady: isLayerCacheReadyForOp,@@ -2062,6 +2030,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreClistener(event);}},+ reportRefusal: reportEditRefusal,setTransformOverride: (layerId, transform) => {if (transform) {transformOverrides.set(layerId, transform);@@ -2074,8 +2043,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst captureLayerCache = (layer: CanvasLayerContract,- doc: CanvasDocumentContractV3- ): { pixels: RasterSurface; rect: Rect } | null | 'not-ready' => {+ doc: CanvasDocumentContractV3,+ admit: (rect: Rect) => boolean = () => true+ ): CapturedLayerCache => {const entry = layerCache.get(layer.id);if (!entry || isEmpty(entry.rect)) {return null;@@ -2083,6 +2053,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCif (isCurrentRasterizationJob(layer) || (entry.stale && !isEmpty(getSourceContentRect(layer, doc)))) {return 'not-ready';}+ if (!admit(entry.rect)) {+ return 'over-budget';+ }const pixels = backend.createSurface(entry.rect.width, entry.rect.height, { willReadFrequently: true });pixels.ctx.drawImage(entry.surface.canvas, 0, 0);return { pixels, rect: { ...entry.rect } };@@ -2134,31 +2107,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};};- const reserveLayerOperation = (bytes: number) =>- rasterController.memory.reserveOperation(bytes, { purpose: 'layer-operation' });-const layerNeedsPixelPersistence = (layer: CanvasLayerContract): boolean =>renderableSourceOf(layer)?.type === 'paint';const layerMutationController = new LayerMutationController({- captureInsertionAnchor,- captureRestoreAnchor: (nodeId) => mutationContext.captureRestoreAnchor(nodeId),captureCache: captureLayerCache,- createLayerId,- concurrency: mutationContext,+ ctx: mutationContext,discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),getDuplicateRasterPlan,- getDocument: () => mirror.getDocument(),- getEditRevision: () => mutationContext.getEditRevision(),- getReducerDocument,getSelectedLayerIds: resolveSelectedLayerIds,hasPendingPixelWork: (layerId) => bitmapStore.hasPendingWork(layerId),- history,- installPrepared: installGeneratedPaintCache,needsPixelPersistence: layerNeedsPixelPersistence,- preparePixels: prepareGeneratedPaintCache,prepareDuplicateRasterSource: prepareLayerRasterCache,pinDuplicateRasterSources: (layerIds) => {const leases = layerIds.map((layerId) => rasterController.memory.pin(layerId));@@ -2171,7 +2130,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};},publishSelectedLayerIds: (primaryId, selectedIds) => opts.setSelectedLayerIds?.(primaryId, selectedIds),- reserve: reserveLayerOperation,scheduleDuplicateRasterization: scheduleLayerRasterization,sameContract: documentHasLayerContract,trackDetached: (bytes) => rasterController.memory.trackDetached(bytes),@@ -2182,17 +2140,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst replaceSelectionFromImage = editingController.selectionImage.replace.bind(editingController.selectionImage);- const maskResultController = new MaskResultController({- captureInsertionAnchor,- concurrency: mutationContext,- createLayerId,- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),- getDocument: () => mirror.getDocument(),- getReducerDocument,- history,- isGuardCurrent: isLayerExportGuardCurrent,- });+ const maskResultController = new MaskResultController({ ctx: mutationContext });const commitMaskImageResult = maskResultController.commit.bind(maskResultController);const filterResultController = new FilterResultController({@@ -2219,15 +2167,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst commitGeneratedImageResult = generatedResultController.commit.bind(generatedResultController);const stagedResultController = new StagedResultController({- captureInsertionAnchor,createEventId,- createLayerId,- concurrency: mutationContext,- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),+ ctx: mutationContext,getCanvasState: () => mutationPort.getCanvasState(),- getDocument: () => mirror.getDocument(),- history,now: () => new Date().toISOString(),});const commitStagedImage = stagedResultController.commit.bind(stagedResultController);@@ -2240,7 +2182,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst extractMaskedArea = (maskLayerId: string): Promise<ExtractMaskedAreaResult> =>layerController.extractMaskedArea.extract(maskLayerId);- const mergeLayerDown = (upperLayerId: string): boolean => layerController.merge.mergeDown(upperLayerId);+ const mergeLayerDown = (upperLayerId: string): MergeDownResult => layerController.merge.mergeDown(upperLayerId);const mergeSelectedRasterLayers = (layerIds: readonly string[]): Promise<MergeVisibleResult> =>layerController.merge.mergeSelected(layerIds);const mergeVisibleRasterLayers = (): Promise<MergeVisibleResult> => layerController.merge.mergeVisible();@@ -2249,7 +2191,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcreateRasterSnapshotCapture({createSurface: (width, height) => backend.createSurface(width, height),getCanvasState: () => mutationPort.getCanvasState(),- getContentEpoch: () => rasterContentEpoch,+ getDirectPixelEpoch: () => directPixelEpoch,getDocumentGeneration: () => rasterController.getDocumentGeneration(),getLifecycleGeneration: () => lifecycleGeneration,isDisposed: () => disposed,@@ -2269,7 +2211,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC});const exportRasterLayersToPsd = (fileName: string): Promise<PsdExportResult> => psdExportController.export(fileName);- const rasterizeLayer = (layerId: string): boolean => layerController.rasterize.rasterize(layerId);+ const rasterizeLayer = (layerId: string): RasterizeLayerResult => layerController.rasterize.rasterize(layerId);// Transform sessions span gestures. Apply records one undoable parameter edit for image layers or pixel bake for// paint; Cancel drops previews. Tools and public UI share the session API.@@ -2377,7 +2319,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn layerController.newRasterLayer.liftSelectionToLayer('Selection', 'Layer via copy');};- const clearMask = (layerId: string): boolean => layerController.mask.clear(layerId);+ const clearMask = (layerId: string): MaskEditResult => layerController.mask.clear(layerId);const dispose = (): void => {if (disposed) {return;@@ -2432,6 +2374,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => fontLoader.dispose());cleanup.run(() => stores.thumbnailStatus.clear());cleanup.run(() => strokeListeners.clear());+ cleanup.run(() => editRefusalListeners.clear());cleanup.run(() => toolChangeListeners.clear());cleanup.run(() => {samInputHandler = null;@@ -2446,6 +2389,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};};+ const onEditRefused = (listener: (refusal: CanvasEditRefusal) => void): (() => void) => {+ editRefusalListeners.add(listener);+ return () => {+ editRefusalListeners.delete(listener);+ };+ };+const clearCaches = async (): Promise<void> => {// Flush paint before invalidating caches; otherwise rerasterizing the older persisted source would erase// unuploaded strokes.@@ -2492,14 +2442,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// A live float holds pixels that no history entry knows about, so replaying an// entry over them would write into a layer with a hole in it. Put them back// first; the float is not itself undoable until it commits.- const undo = (): void => {- floatingSelection.cancel();- historyController.undo();- };- const redo = (): void => {- floatingSelection.cancel();- historyController.redo();+ const replayHistory = async (direction: 'undo' | 'redo'): Promise<CanvasHistoryReplayStatus> => {+ if (!history.isReplaying()) {+ floatingSelection.cancel();+ }+ const result = await (direction === 'undo' ? historyController.undo() : historyController.redo());+ return result.status;};+ const undo = (): Promise<CanvasHistoryReplayStatus> => replayHistory('undo');+ const redo = (): Promise<CanvasHistoryReplayStatus> => replayHistory('redo');const setBboxGrid = (size: number): void => stores.bboxGrid.set(size > 0 ? size : 1);const getViewport = (): Viewport => viewport;const getCompositeExecutorDeps = (): CanvasCompositeExecutorDeps => ({@@ -2512,16 +2463,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCexportRasterCompositeWithDeps(request, {backend,captureSnapshot: (): RasterCompositeExportSnapshot => ({- contentEpoch: rasterContentEpoch,+ directPixelEpoch: directPixelEpoch,document: mirror.getDocument(),documentGeneration: rasterController.getDocumentGeneration(),lifecycleGeneration,}),+ adjustedSurface: (layerId, surface, adjustments) =>+ rasterController.getAdjustedCacheSurface(layerId, surface, adjustments),getLayerSurface: requireLayerSurfaceForExport,isSnapshotCurrent: (snapshot) =>!disposed &&mutationPort.getCanvasState() !== null &&- snapshot.contentEpoch === rasterContentEpoch &&+ snapshot.directPixelEpoch === directPixelEpoch &&snapshot.document === mirror.getDocument() &&snapshot.documentGeneration === rasterController.getDocumentGeneration() &&snapshot.lifecycleGeneration === lifecycleGeneration,@@ -2539,18 +2492,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC});const surface: CanvasSurfaceCapability = { attach, detach, resize };const viewportCapability: CanvasViewportCapability = { fitToView, fitToViewOnFirstShow, getViewport, setBboxGrid };- const stepHistoryBy = (offset: number): void => {- const steps = Math.abs(Math.trunc(offset));- for (let i = 0; i < steps; i += 1) {- if (offset < 0 ? !history.canUndo() : !history.canRedo()) {- return;- }- if (offset < 0) {- undo();- } else {- redo();+ const stepHistoryBy = async (offset: number): Promise<CanvasHistoryReplayStatus> => {+ let status: CanvasHistoryReplayStatus = 'empty';+ for (let step = 0; step < Math.abs(Math.trunc(offset)); step += 1) {+ status = await (offset < 0 ? undo() : redo());+ if (status !== 'applied') {+ break;}}+ return status;};const historyCapability: CanvasHistoryCapability = {clearHistory,@@ -2570,101 +2520,54 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst layerController = new LayerController({booleanMerge: {backend,- captureInsertionAnchor,- createLayerId,- concurrency: mutationContext,- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),+ ctx: mutationContext,exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId),- getDocument: () => mirror.getDocument(),- getReducerDocument,- history,- installPrepared: (prepared) => installGeneratedPaintCache(prepared),isCacheReady: isLayerCacheReadyForOp,isGuardCurrent: isLayerExportGuardCurrent,- preparePixels: prepareGeneratedPaintCache,},crop: {backend,captureCache: captureLayerCache,- concurrency: mutationContext,+ ctx: mutationContext,discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId, { includeDisabled: true }),- getDocument: () => mirror.getDocument(),- getReducerDocument,- history,- installPrepared: (prepared) => installGeneratedPaintCache(prepared),isGuardCurrent: isLayerExportGuardCurrent,isSupportedSource: isSupportedExportSource,- preparePixels: prepareGeneratedPaintCache,},copy: {- captureInsertionAnchor,- createLayerId,- concurrency: mutationContext,- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),+ backend,+ ctx: mutationContext,exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId, { includeDisabled: true }),- getDocument: () => mirror.getDocument(),- getReducerDocument,- history,- installPrepared: (prepared) => installGeneratedPaintCache(prepared),isGuardCurrent: isLayerExportGuardCurrent,- preparePixels: prepareGeneratedPaintCache,},extractMaskedArea: {backend,- captureInsertionAnchor,- createLayerId,- concurrency: mutationContext,+ ctx: mutationContext,derived: derivedSurfaceCache,diagnostics,- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),exportBaked: (layerId, includeDisabled) => exportBakedLayerPixelsForStructural(layerId, { includeDisabled }),getAdjustedSurface,getGroupSurface,- getDocument: () => mirror.getDocument(),getMaskPattern: getMaskPatternTile,- getReducerDocument,hasExportableContent: hasExportableLayerContent,- history,- installPrepared: (prepared) => installGeneratedPaintCache(prepared),isCacheReady: isLayerCacheReadyForOp,isGuardCurrent: isLayerExportGuardCurrent,layers: layerCache,- preparePixels: prepareGeneratedPaintCache,rasterize: (layerId) => rasterizeLayerPixelsForStructural(layerId),},commitGeneratedImageResult,newRasterLayer: {backend,- captureInsertionAnchor,- createLayerId,- concurrency: mutationContext,- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),- getDocument: () => mirror.getDocument(),- getReducerDocument,- history,- installPrepared: (prepared) => installGeneratedPaintCache(prepared),+ ctx: mutationContext,layers: layerCache,- preparePixels: prepareGeneratedPaintCache,selection: editingController.selection,},mask: {applyImagePatch,- canEdit: () => canEditDocument(),+ ctx: mutationContext,deleteDerived: deleteDerivedSurfaces,discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),- dispatch: (action) => dispatchCanvasMutation(action),- endBurst: () => endNudgeBurst(),- getDocument: () => mirror.getDocument(),- history,isCacheReady: isLayerCacheReadyForOp,- isGestureActive: () => pipeline.isGestureActive(),layers: layerCache,markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),notifyPainted: notifyLayerPainted,@@ -2672,29 +2575,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},merge: {backend,- canEdit: () => canEditDocument(),ctx: mutationContext,exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId),hasExportableContent: hasExportableLayerContent,isCacheReady: isLayerCacheReadyForOp,layers: layerCache,- markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),needsPixelPersistence: layerNeedsPixelPersistence,- notifyPainted: notifyLayerPainted,publishSelectedLayerIds: (primaryId, selectedIds) => opts.setSelectedLayerIds?.(primaryId, selectedIds),- reserve: reserveLayerOperation,},rasterize: {backend,- canEdit: () => canEditDocument(),- dispatch: (action) => dispatchCanvasMutation(action),- endBurst: () => endNudgeBurst(),- getDocument: () => mirror.getDocument(),- history,- isGestureActive: () => pipeline.isGestureActive(),- layers: layerCache,- markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),- notifyPainted: notifyLayerPainted,+ ctx: mutationContext,rasterizeDeps: (document) => rasterizeDeps(document),},structural: structuralController,@@ -2781,6 +2672,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC...interactionController.tools,canTargetLayerFromContextMenu,handleEscapePriority,+ onEditRefused,onStrokeCommitted,requestColorSample,setColorSampleRouter: (router) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 08eea6bc3b..5387a7416e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -430,7 +430,7 @@ export interface EngineStores {thumbnailVersion: KeyedVersionStore;thumbnailStatus: KeyedThumbnailStatusStore;/** Monotonic aggregate version for consumers whose eligibility depends on live layer content. */- rasterContentEpoch: ScalarStore<number>;+ layerPixelEpoch: ScalarStore<number>;/** Brush tool options (size / color / opacity / pressure). */brushOptions: ScalarStore<BrushOptions>;/** One-way foreground/background mirror for gesture-start reads; the engine never writes it. */@@ -683,7 +683,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =lassoPreview: createScalarStore<LassoPreview | null>(null),marqueeOptions: createScalarStore<MarqueeToolOptions>({ ...DEFAULT_MARQUEE_OPTIONS }, marqueeOptionsEqual),marqueePreview: createScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>(null, rectShapePreviewEqual),- rasterContentEpoch: createScalarStore<number>(0),+ layerPixelEpoch: createScalarStore<number>(0),ruleOfThirds: createScalarStore<boolean>(false),samInteraction: createScalarStore(null),shapeOptions: createScalarStore<ShapeToolOptions>({ ...DEFAULT_SHAPE_OPTIONS }, shapeOptionsEqual),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.tsindex 4e871ecbf5..bbbbeef197 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.test.ts@@ -60,7 +60,7 @@ const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({const makeDeps = (document: CanvasDocumentContractV3) => {const stub = createTestStubRasterBackend();const snapshot: RasterCompositeExportSnapshot = {- contentEpoch: 1,+ directPixelEpoch: 1,document,documentGeneration: 1,lifecycleGeneration: 1,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.tsindex fe8991c0b8..eed1b08dc3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts@@ -18,7 +18,7 @@ export type RasterCompositeExportResult =| { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' };export interface RasterCompositeExportSnapshot {- contentEpoch: number;+ directPixelEpoch: number;document: CanvasDocumentContractV3 | null;documentGeneration: number;lifecycleGeneration: number;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.tsindex 5e801ab677..430a4e4172 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.test.ts@@ -1,8 +1,9 @@import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { describe, expect, it, vi } from 'vitest';-import { createDocumentPatchEntry, DOCUMENT_PATCH_DEFAULT_BYTES } from './documentPatch';+import { createDocumentPatchEntry } from './documentPatch';const forward: CanvasProjectMutation = { direction: 1, type: 'cycleStagedImage' };const inverse: CanvasProjectMutation = { direction: -1, type: 'cycleStagedImage' };@@ -21,7 +22,7 @@ describe('createDocumentPatchEntry', () => {it('defaults bytes to a small nominal cost, overridable', () => {const dispatch = vi.fn();const entry = createDocumentPatchEntry({ dispatch, forward, inverse, label: 'Cycle' });- expect(entry.bytes).toBe(DOCUMENT_PATCH_DEFAULT_BYTES);+ expect(entry.bytes).toBe(HISTORY_ENTRY_OVERHEAD_BYTES);const heavier = createDocumentPatchEntry({ bytes: 4096, dispatch, forward, inverse, label: 'Cycle' });expect(heavier.bytes).toBe(4096);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.tsindex 21dd071e0d..52eb2ebcbd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/documentPatch.ts@@ -7,10 +7,7 @@ import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationConimport type { HistoryEntry } from './history';-import { collectHistoryMediaRefs } from './history';--/** Nominal byte cost for a structural entry (small; actions are plain objects). */-export const DOCUMENT_PATCH_DEFAULT_BYTES = 256;+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from './history';/** Options for {@link createDocumentPatchEntry}. */export interface CreateDocumentPatchEntryOptions {@@ -19,18 +16,16 @@ export interface CreateDocumentPatchEntryOptions {forward: CanvasProjectMutation;/** The action that reverses the change (dispatched on undo). */inverse: CanvasProjectMutation;- /** Applies one side of the patch; may throw to leave a failure-atomic entry in place. */+ /** Applies one side of the patch; throws without applying to leave the entry in place. */dispatch(action: CanvasProjectMutation): void;- /** Approximate retained size (default {@link DOCUMENT_PATCH_DEFAULT_BYTES}). */+ /** Approximate retained size (default {@link HISTORY_ENTRY_OVERHEAD_BYTES}). */bytes?: number;- /** Marks the entry failure-atomic: `dispatch` must throw without applying for History to keep it in place. */- replayFailureAtomic?: boolean;}/** Creates a reversible structural entry that dispatches inverse on undo, forward on redo. */export const createDocumentPatchEntry = (opts: CreateDocumentPatchEntryOptions): HistoryEntry => {const { dispatch, forward, inverse, label } = opts;- const bytes = opts.bytes ?? DOCUMENT_PATCH_DEFAULT_BYTES;+ const bytes = opts.bytes ?? HISTORY_ENTRY_OVERHEAD_BYTES;return {bytes,@@ -38,6 +33,5 @@ export const createDocumentPatchEntry = (opts: CreateDocumentPatchEntryOptions):label,redo: () => dispatch(forward),undo: () => dispatch(inverse),- ...(opts.replayFailureAtomic ? { replayFailureAtomic: true } : {}),};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.tsindex 4c94733bd0..82778d259f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts@@ -1,584 +1,306 @@import { describe, expect, it, vi } from 'vitest';-import type { HistoryEntry } from './history';+import type { History, HistoryEntry } from './history';import { createHistory, HISTORY_BYTE_BUDGET, HISTORY_MAX_ENTRIES, NO_HELD_ASSET_REFS } from './history';-/** A tiny entry that records undo/redo calls into a shared log. */-const makeEntry = (label: string, log: string[], bytes = 0): HistoryEntry => ({+const makeEntry = (label: string, log: string[], bytes = 1): HistoryEntry => ({bytes,heldAssetRefs: NO_HELD_ASSET_REFS,label,- redo: () => log.push(`redo:${label}`),- undo: () => log.push(`undo:${label}`),+ redo: () => {+ log.push(`redo:${label}`);+ },+ undo: () => {+ log.push(`undo:${label}`);+ },});-describe('createHistory: push / undo / redo ordering', () => {- it('undoes and redoes entries in LIFO order', () => {+const push = (history: History, entry: HistoryEntry) => {+ const admission = history.admit(entry.bytes);+ if (!admission) {+ throw new Error(`"${entry.label}" was not admitted`);+ }+ return admission.publish(entry);+};++describe('createHistory: replay ordering', () => {+ it('undoes and redoes entries in LIFO order', async () => {const log: string[] = [];const history = createHistory();- history.push(makeEntry('a', log));- history.push(makeEntry('b', log));- history.push(makeEntry('c', log));+ push(history, makeEntry('a', log));+ push(history, makeEntry('b', log));- history.undo();- history.undo();- expect(log).toEqual(['undo:c', 'undo:b']);+ await history.undo();+ await history.undo();+ await history.redo();- history.redo();- expect(log).toEqual(['undo:c', 'undo:b', 'redo:b']);+ expect(log).toEqual(['undo:b', 'undo:a', 'redo:a']);+ expect(history.entries()).toEqual({ future: ['b'], past: ['a'] });+ });- history.undo();- history.undo();- expect(log).toEqual(['undo:c', 'undo:b', 'redo:b', 'undo:b', 'undo:a']);+ it('reports empty stacks without replaying', async () => {+ const history = createHistory();+ await expect(history.undo()).resolves.toEqual({ status: 'empty' });+ await expect(history.redo()).resolves.toEqual({ status: 'empty' });});- it('undo / redo are no-ops on empty stacks', () => {+ it('drops the redo stack when a new entry is published', async () => {const log: string[] = [];const history = createHistory();- history.undo();- history.redo();- expect(log).toEqual([]);- expect(history.canUndo()).toBe(false);+ push(history, makeEntry('a', log));+ await history.undo();+ push(history, makeEntry('b', log));+expect(history.canRedo()).toBe(false);+ expect(history.entries()).toEqual({ future: [], past: ['b'] });});});-describe('createHistory: redo cleared on push', () => {- it('drops the redo stack when a new entry is pushed', () => {+describe('createHistory: entries', () => {+ it('lists past oldest-first and future next-redo-first, tracking every mutation', async () => {const log: string[] = [];const history = createHistory();- history.push(makeEntry('a', log));- history.push(makeEntry('b', log));- history.undo(); // b -> redo- expect(history.canRedo()).toBe(true);+ expect(history.entries()).toEqual({ future: [], past: [] });- history.push(makeEntry('c', log));- expect(history.canRedo()).toBe(false);+ push(history, makeEntry('a', log));+ push(history, makeEntry('b', log));+ push(history, makeEntry('c', log));+ expect(history.entries()).toEqual({ future: [], past: ['a', 'b', 'c'] });- // Redoing does nothing: the redo stack was cleared by the push.- history.redo();- expect(log).toEqual(['undo:b']);- });-});+ await history.undo();+ await history.undo();+ expect(history.entries()).toEqual({ future: ['b', 'c'], past: ['a'] });++ await history.redo();+ expect(history.entries()).toEqual({ future: ['c'], past: ['a', 'b'] });++ push(history, makeEntry('d', log));+ expect(history.entries()).toEqual({ future: [], past: ['a', 'b', 'd'] });-describe('createHistory: entry-count eviction', () => {- it('keeps undo and redo media held until their entry is evicted', () => {- const history = createHistory({ maxEntries: 1 });- const first = { ...makeEntry('remove first', []), heldAssetRefs: { images: ['first.png'], videos: [] } };- const second = { ...makeEntry('remove second', []), heldAssetRefs: { images: ['second.png'], videos: [] } };- history.push(first);- history.undo();- expect(history.heldAssetRefs().images).toEqual(['first.png']);- history.redo();- history.push(second);- expect(history.heldAssetRefs().images).toEqual(['second.png']);history.clear();- expect(history.heldAssetRefs().images).toEqual([]);+ expect(history.entries()).toEqual({ future: [], past: [] });});+});- it('evicts the oldest entry beyond the 64-entry budget', () => {+describe('createHistory: admission', () => {+ it('reserves capacity without clearing redo or evicting retained steps', async () => {const log: string[] = [];- const history = createHistory();- // Push one past the default cap.- for (let i = 0; i < HISTORY_MAX_ENTRIES + 1; i += 1) {- history.push(makeEntry(`e${i}`, log));- }- let undos = 0;- while (history.canUndo()) {- history.undo();- undos += 1;- }- expect(undos).toBe(HISTORY_MAX_ENTRIES);- expect(log).not.toContain('undo:e0');- expect(log).toContain('undo:e1');- expect(log[log.length - 1]).toBe('undo:e1');+ const history = createHistory({ byteBudget: 10 });+ push(history, makeEntry('kept', log, 6));+ push(history, makeEntry('undone', log, 2));+ await history.undo();++ const admission = history.admit(10);++ expect(admission).not.toBeNull();+ expect(history.entries()).toEqual({ future: ['undone'], past: ['kept'] });+ admission!.release();+ admission!.release();+ expect(history.admit(10)).not.toBeNull();});- it('honors a custom maxEntries', () => {+ it('refuses an entry that could never be retained and leaves earlier steps undoable', () => {const log: string[] = [];- const history = createHistory({ maxEntries: 2 });- history.push(makeEntry('a', log));- history.push(makeEntry('b', log));- history.push(makeEntry('c', log)); // evicts 'a'- let undos = 0;- while (history.canUndo()) {- history.undo();- undos += 1;- }- expect(undos).toBe(2);- expect(log).toEqual(['undo:c', 'undo:b']);- });-});+ const history = createHistory({ byteBudget: 10 });+ push(history, makeEntry('previous', log, 2));-describe('createHistory: byte-budget eviction', () => {- it('evicts oldest entries until under the byte budget', () => {- const log: string[] = [];- // Budget fits two 10-byte entries but not three.- const history = createHistory({ byteBudget: 25 });- history.push(makeEntry('a', log, 10));- history.push(makeEntry('b', log, 10));+ expect(history.admit(11)).toBeNull();+ expect(history.entries().past).toEqual(['previous']);expect(history.canUndo()).toBe(true);- history.push(makeEntry('c', log, 10)); // total 30 > 25 -> evict 'a'-- let undos = 0;- while (history.canUndo()) {- history.undo();- undos += 1;- }- expect(undos).toBe(2);- expect(log).toEqual(['undo:c', 'undo:b']);});- it('exports the 256 MB default byte budget', () => {- expect(HISTORY_BYTE_BUDGET).toBe(256 * 1024 * 1024);+ it('keeps concurrent admissions within the budget so publishing one cannot evict the other', () => {+ const history = createHistory({ byteBudget: 10 });+ const first = history.admit(6)!;+ expect(history.admit(6)).toBeNull();+ const second = history.admit(4)!;++ first.publish(makeEntry('first', [], 6));+ second.publish(makeEntry('second', [], 4));++ expect(history.entries().past).toEqual(['first', 'second']);});- it('reports whether one entry can remain undoable after eviction', () => {- const history = createHistory({ byteBudget: 25 });+ it('grows an admission only while the larger entry still fits', () => {+ const history = createHistory({ byteBudget: 10 });+ const admission = history.admit(4)!;+ const other = history.admit(3)!;++ expect(admission.grow(3)).toBe(true);+ expect(admission.bytes).toBe(7);+ expect(admission.grow(1)).toBe(false);+ expect(admission.bytes).toBe(7);+ other.release();+ expect(admission.grow(3)).toBe(true);+ });- expect(history.canRetain(25)).toBe(true);- expect(history.canRetain(26)).toBe(false);- expect(history.canRetain(Number.POSITIVE_INFINITY)).toBe(false);+ it('refuses to publish an entry larger than its admission', () => {+ const history = createHistory();+ const admission = history.admit(1)!;+ expect(() => admission.publish(makeEntry('too large', [], 2))).toThrow(/exceeds its admission/);+ expect(history.canUndo()).toBe(false);});});-describe('createHistory: change listener', () => {- it('fires on push / undo / redo / clear', () => {+describe('createHistory: tokens and replacement', () => {+ it('replaces only the expected newest entry and returns a fresh token', () => {const log: string[] = [];const history = createHistory();- const listener = vi.fn();- const unsubscribe = history.subscribe(listener);-- history.push(makeEntry('a', log));- expect(listener).toHaveBeenCalledTimes(1);- history.undo();- expect(listener).toHaveBeenCalledTimes(2);- history.redo();- expect(listener).toHaveBeenCalledTimes(3);- history.clear();- expect(listener).toHaveBeenCalledTimes(4);+ const first = push(history, makeEntry('nudge', log));+ expect(history.top()).toBe(first);- // Clear again with empty stacks: no change, no notification.- history.clear();- expect(listener).toHaveBeenCalledTimes(4);-- unsubscribe();- history.push(makeEntry('b', log));- expect(listener).toHaveBeenCalledTimes(4);- });+ const second = history.admit(1)!.publish(makeEntry('nudge again', log), first);- it('reflects canUndo / canRedo transitions', () => {- const log: string[] = [];- const history = createHistory();- expect(history.canUndo()).toBe(false);- history.push(makeEntry('a', log));- expect(history.canUndo()).toBe(true);- expect(history.canRedo()).toBe(false);- history.undo();- expect(history.canUndo()).toBe(false);- expect(history.canRedo()).toBe(true);+ expect(second).not.toBe(first);+ expect(history.top()).toBe(second);+ expect(history.entries().past).toEqual(['nudge again']);+ expect(() => history.admit(1)!.publish(makeEntry('stale', log), first)).toThrow(/no longer the newest/);});});-describe('createHistory: amendLast', () => {- it('replaces the most recent entry in place and adjusts the byte total', () => {- const log: string[] = [];- const history = createHistory({ byteBudget: 25 });- history.push(makeEntry('a', log, 10));- history.push(makeEntry('b', log, 10));- history.amendLast(makeEntry('b2', log, 10));-- let undos = 0;- while (history.canUndo()) {- history.undo();- undos += 1;- }- // Two entries retained (a + b2), not three: amend did not grow the stack.- expect(undos).toBe(2);- expect(log).toEqual(['undo:b2', 'undo:a']);+describe('createHistory: eviction', () => {+ it('keeps undo and redo media held until their entry is evicted', async () => {+ const history = createHistory({ maxEntries: 1 });+ const first = { ...makeEntry('remove first', []), heldAssetRefs: { images: ['first.png'], videos: [] } };+ const second = { ...makeEntry('remove second', []), heldAssetRefs: { images: ['second.png'], videos: [] } };+ push(history, first);+ await history.undo();+ expect(history.heldAssetRefs().images).toEqual(['first.png']);+ await history.redo();+ push(history, second);+ expect(history.heldAssetRefs().images).toEqual(['second.png']);+ history.clear();+ expect(history.heldAssetRefs().images).toEqual([]);});- it('pushes when the undo stack is empty', () => {- const log: string[] = [];+ it('evicts the oldest entry beyond the entry budget', () => {const history = createHistory();- history.amendLast(makeEntry('a', log));- expect(history.canUndo()).toBe(true);- history.undo();- expect(log).toEqual(['undo:a']);+ for (let index = 0; index <= HISTORY_MAX_ENTRIES; index += 1) {+ push(history, makeEntry(`entry-${index}`, []));+ }+ expect(history.entries().past).toHaveLength(HISTORY_MAX_ENTRIES);+ expect(history.entries().past[0]).toBe('entry-1');});- it('clears the redo stack like push', () => {- const log: string[] = [];- const history = createHistory();- history.push(makeEntry('a', log));- history.push(makeEntry('b', log));- history.undo(); // b -> redo- expect(history.canRedo()).toBe(true);- history.amendLast(makeEntry('a2', log));- expect(history.canRedo()).toBe(false);+ it('evicts oldest entries until under the byte budget, never the newest', () => {+ const history = createHistory({ byteBudget: 10 });+ push(history, makeEntry('a', [], 4));+ push(history, makeEntry('b', [], 4));+ push(history, makeEntry('c', [], 4));++ expect(history.entries().past).toEqual(['b', 'c']);+ expect(history.byteSize()).toBe(8);+ expect(HISTORY_BYTE_BUDGET).toBe(256 * 1024 * 1024);});- it('is a no-op while applying', () => {+ it('trims oldest entries by retained bytes while preserving the newest undo history', () => {const log: string[] = [];- const history = createHistory();- const reentrant: HistoryEntry = {- bytes: 0,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'reentrant',- redo: () => {},- undo: () => history.amendLast(makeEntry('sneaky', log)),- };- history.push(reentrant);- history.undo();- // The amend during undo was dropped; only the reentrant entry is reachable.- history.redo();- let undos = 0;- while (history.canUndo()) {- history.undo();- undos += 1;- }- expect(undos).toBe(1);+ const history = createHistory({ byteBudget: 1_000 });+ push(history, makeEntry('oldest', log, 40));+ push(history, makeEntry('middle', log, 50));+ push(history, makeEntry('newest', log, 60));++ history.trimToBytes(110);++ expect(history.byteSize()).toBe(110);+ expect(history.entries().past).toEqual(['middle', 'newest']);});-});-describe('createHistory: re-entrancy guard', () => {- it('reports isApplying during undo/redo and drops entries pushed while applying', () => {- const log: string[] = [];- const history = createHistory();- const observed: boolean[] = [];-- const reentrant: HistoryEntry = {- bytes: 0,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'reentrant',- redo: () => {- observed.push(history.isApplying());- // A replay must not be able to record a new entry.- history.push(makeEntry('sneaky', log));- },- undo: () => {- observed.push(history.isApplying());- history.push(makeEntry('sneaky', log));- },- };-- expect(history.isApplying()).toBe(false);- history.push(reentrant);- history.undo();- expect(observed).toEqual([true]);- expect(history.isApplying()).toBe(false);- expect(history.canRedo()).toBe(true);-- history.redo();- expect(observed).toEqual([true, true]);- let undos = 0;- while (history.canUndo()) {- history.undo();- undos += 1;- }- expect(undos).toBe(1);+ it('disposes entries whenever stack ownership permanently ends', async () => {+ const disposed: string[] = [];+ const entry = (label: string) => ({ ...makeEntry(label, []), dispose: () => disposed.push(label) });+ const history = createHistory({ maxEntries: 1 });++ const evicted = push(history, entry('evicted'));+ void evicted;+ push(history, entry('redo-cleared'));+ expect(disposed).toEqual(['evicted']);+ await history.undo();+ const replaced = push(history, entry('replaced'));+ expect(disposed).toEqual(['evicted', 'redo-cleared']);+ history.admit(1)!.publish(entry('cleared'), replaced);+ expect(disposed).toEqual(['evicted', 'redo-cleared', 'replaced']);+ history.clear();+ expect(disposed).toEqual(['evicted', 'redo-cleared', 'replaced', 'cleared']);});});-describe('createHistory: failure-atomic replay', () => {- it('keeps a failed undo on the undo stack and allows an exact retry', () => {+describe('createHistory: failure-atomic asynchronous replay', () => {+ it('keeps a failed undo in place for an exact retry', async () => {const history = createHistory();- const listener = vi.fn();- let shouldFail = true;+ let fail = true;const undo = vi.fn(() => {- if (shouldFail) {- throw new Error('undo preparation failed');+ if (fail) {+ throw new Error('pixels unavailable');}});- const redo = vi.fn();- history.subscribe(listener);- history.push({- bytes: 17,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'fallible',- redo,- replayFailureAtomic: true,- undo,- });- listener.mockClear();+ push(history, { ...makeEntry('stroke', []), undo });- expect(() => history.undo()).toThrow('undo preparation failed');- expect(history.canUndo()).toBe(true);- expect(history.canRedo()).toBe(false);- expect(history.isApplying()).toBe(false);- expect(listener).not.toHaveBeenCalled();+ await expect(history.undo()).resolves.toMatchObject({ label: 'stroke', status: 'failed' });+ expect(history.entries()).toEqual({ future: [], past: ['stroke'] });- shouldFail = false;- history.undo();+ fail = false;+ await expect(history.undo()).resolves.toEqual({ status: 'applied' });+ expect(history.entries()).toEqual({ future: ['stroke'], past: [] });expect(undo).toHaveBeenCalledTimes(2);- expect(history.canUndo()).toBe(false);- expect(history.canRedo()).toBe(true);- expect(listener).toHaveBeenCalledOnce();});- it('keeps a failed redo on the redo stack and allows an exact retry', () => {+ it('keeps a rejected asynchronous redo in place', async () => {const history = createHistory();- const listener = vi.fn();- let shouldFail = true;- const undo = vi.fn();- const redo = vi.fn(() => {- if (shouldFail) {- throw new Error('redo preparation failed');- }- });- history.subscribe(listener);- history.push({- bytes: 23,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'fallible',- redo,- replayFailureAtomic: true,- undo,- });- history.undo();- listener.mockClear();-- expect(() => history.redo()).toThrow('redo preparation failed');- expect(history.canUndo()).toBe(false);- expect(history.canRedo()).toBe(true);- expect(history.isApplying()).toBe(false);- expect(listener).not.toHaveBeenCalled();+ push(history, { ...makeEntry('merge', []), redo: () => Promise.reject(new Error('over budget')) });+ await history.undo();- shouldFail = false;- history.redo();- expect(redo).toHaveBeenCalledTimes(2);- expect(history.canUndo()).toBe(true);- expect(history.canRedo()).toBe(false);- expect(listener).toHaveBeenCalledOnce();+ await expect(history.redo()).resolves.toMatchObject({ status: 'failed' });+ expect(history.entries()).toEqual({ future: ['merge'], past: [] });+ expect(history.byteSize()).toBe(1);});- it('preserves byte-budget accounting after a failed replay', () => {- const log: string[] = [];- const history = createHistory({ byteBudget: 20 });- let shouldFail = true;- history.push(makeEntry('a', log, 10));- history.push({- bytes: 10,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'b',- redo: () => log.push('redo:b'),- replayFailureAtomic: true,- undo: () => {- if (shouldFail) {- throw new Error('failed');- }- log.push('undo:b');- },- });-- expect(() => history.undo()).toThrow('failed');- shouldFail = false;- history.push(makeEntry('c', log, 10));-- // Correct restored accounting is 30 bytes, so the oldest entry is evicted.- history.undo();- history.undo();- expect(log).toEqual(['undo:c', 'undo:b']);- expect(history.canUndo()).toBe(false);- });-- it.each([false, true])(- 'does not resurrect an entry when undo clears history (failure-atomic: %s)',- (replayFailureAtomic) => {- const history = createHistory();- const listener = vi.fn();- history.subscribe(listener);- history.push({- bytes: 10,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'clear-on-undo',- redo: () => {},- replayFailureAtomic,- undo: () => history.clear(),- });- listener.mockClear();-- history.undo();-- expect(history.canUndo()).toBe(false);- expect(history.canRedo()).toBe(false);- expect(listener).toHaveBeenCalledOnce();- }- );-- it.each([false, true])(- 'does not resurrect an entry when redo clears history (failure-atomic: %s)',- (replayFailureAtomic) => {- const history = createHistory();- const listener = vi.fn();- let clearOnRedo = false;- history.subscribe(listener);- history.push({- bytes: 10,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'clear-on-redo',- redo: () => {- if (clearOnRedo) {- history.clear();- }- },- replayFailureAtomic,- undo: () => {},- });- history.undo();- clearOnRedo = true;- listener.mockClear();-- history.redo();-- expect(history.canUndo()).toBe(false);- expect(history.canRedo()).toBe(false);- expect(listener).toHaveBeenCalledOnce();- }- );-- it('moves a legacy undo before replay, notifies, and rethrows a post-application failure', () => {+ it('refuses a second replay while one is pending and reports replay state', async () => {const history = createHistory();- const listener = vi.fn();- const applied: string[] = [];- history.subscribe(listener);- history.push({- bytes: 10,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'legacy-fallible-undo',- redo: () => applied.push('redo'),- undo: () => {- applied.push('undo');- throw new Error('undo observer failed');- },+ let finish!: () => void;+ push(history, makeEntry('a', []));+ push(history, {+ ...makeEntry('b', []),+ undo: () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),});- listener.mockClear();- expect(() => history.undo()).toThrow('undo observer failed');-- expect(history.canUndo()).toBe(false);- expect(history.canRedo()).toBe(true);- expect(history.isApplying()).toBe(false);- expect(applied).toEqual(['undo']);- expect(listener).toHaveBeenCalledOnce();-- history.redo();- expect(applied).toEqual(['undo', 'redo']);+ const pending = history.undo();+ expect(history.isReplaying()).toBe(true);+ await expect(history.undo()).resolves.toEqual({ status: 'busy' });+ finish();+ await expect(pending).resolves.toEqual({ status: 'applied' });+ expect(history.isReplaying()).toBe(false);+ expect(history.entries()).toEqual({ future: ['b'], past: ['a'] });});- it('moves a legacy redo before replay, notifies, and rethrows a post-application failure', () => {+ it('lets a replay that clears history win instead of resurrecting its entry', async () => {const history = createHistory();- const listener = vi.fn();- const applied: string[] = [];- let shouldFail = false;- history.subscribe(listener);- history.push({- bytes: 10,- heldAssetRefs: NO_HELD_ASSET_REFS,- label: 'legacy-fallible-redo',- redo: () => {- applied.push('redo');- if (shouldFail) {- throw new Error('redo observer failed');- }- },- undo: () => applied.push('undo'),- });- history.undo();- shouldFail = true;- listener.mockClear();+ push(history, { ...makeEntry('replace document', []), undo: () => history.clear() });- expect(() => history.redo()).toThrow('redo observer failed');+ await history.undo();- expect(history.canUndo()).toBe(true);- expect(history.canRedo()).toBe(false);- expect(history.isApplying()).toBe(false);- expect(applied).toEqual(['undo', 'redo']);- expect(listener).toHaveBeenCalledOnce();-- history.undo();- expect(applied).toEqual(['undo', 'redo', 'undo']);+ expect(history.entries()).toEqual({ future: [], past: [] });});+});- it('isolates listener failures after successful stack mutations', () => {- const log: string[] = [];+describe('createHistory: change listener', () => {+ it('fires on publication, replay and clear, isolating faulty observers', async () => {const history = createHistory();const listener = vi.fn();history.subscribe(() => {- throw new Error('history listener failed');+ throw new Error('observer failed');});history.subscribe(listener);- expect(() => history.push(makeEntry('a', log))).not.toThrow();- expect(() => history.undo()).not.toThrow();- expect(() => history.redo()).not.toThrow();- expect(() => history.clear()).not.toThrow();-- expect(listener).toHaveBeenCalledTimes(4);- expect(history.canUndo()).toBe(false);- expect(history.canRedo()).toBe(false);- });-- it('trims oldest entries by retained bytes while preserving the newest undo history', () => {- const log: string[] = [];- const history = createHistory({ byteBudget: 1_000 });- history.push({ ...makeEntry('oldest', log), bytes: 40 });- history.push({ ...makeEntry('middle', log), bytes: 50 });- history.push({ ...makeEntry('newest', log), bytes: 60 });-- history.trimToBytes(110);-- expect(history.byteSize()).toBe(110);- history.undo();- history.undo();- history.undo();- expect(log).toEqual(['undo:newest', 'undo:middle']);- });-- it('disposes entries whenever stack ownership permanently ends', () => {- const disposed: string[] = [];- const entry = (label: string) => ({- ...makeEntry(label, []),- dispose: () => disposed.push(label),- });- const history = createHistory({ maxEntries: 1 });-- history.push(entry('evicted'));- history.push(entry('redo-cleared'));- expect(disposed).toEqual(['evicted']);- history.undo();- history.push(entry('amended'));- expect(disposed).toEqual(['evicted', 'redo-cleared']);- history.amendLast(entry('cleared'));- expect(disposed).toEqual(['evicted', 'redo-cleared', 'amended']);+ push(history, makeEntry('a', []));+ await history.undo();history.clear();- expect(disposed).toEqual(['evicted', 'redo-cleared', 'amended', 'cleared']);- });-});--describe('createHistory: entries enumeration', () => {- it('lists past oldest-first and future next-redo-first, tracking every mutation', () => {- const log: string[] = [];- const history = createHistory();- expect(history.entries()).toEqual({ future: [], past: [] });-- history.push(makeEntry('a', log));- history.push(makeEntry('b', log));- history.push(makeEntry('c', log));- expect(history.entries()).toEqual({ future: [], past: ['a', 'b', 'c'] });-- history.undo();- history.undo();- expect(history.entries()).toEqual({ future: ['b', 'c'], past: ['a'] });-- history.redo();- expect(history.entries()).toEqual({ future: ['c'], past: ['a', 'b'] });- history.push(makeEntry('d', log));- expect(history.entries()).toEqual({ future: [], past: ['a', 'b', 'd'] });-- history.clear();- expect(history.entries()).toEqual({ future: [], past: [] });+ expect(listener.mock.calls.length).toBeGreaterThanOrEqual(3);+ expect(history.canUndo()).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.tsindex 995bf22aec..97cd0993a9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts@@ -1,7 +1,9 @@/**- * Engine-owned opaque undo/redo entries account for pixel and structural edits. Evict oldest entries beyond {@link- * HISTORY_MAX_ENTRIES} or {@link HISTORY_BYTE_BUDGET} across both stacks. During replay `isApplying` prevents- * recording and `push` is a no-op, avoiding recursive history.+ * Engine-owned undo/redo stacks for pixel, selection and structural edits. An edit is admitted before it mutates+ * anything: admission reserves byte capacity (without clearing redo or evicting older steps), so an edit that could+ * never keep its undo entry is refused up front. Publication consumes the admission, clears redo and evicts the+ * oldest entries beyond {@link HISTORY_MAX_ENTRIES} or the byte budget. Replay is asynchronous and failure-atomic:+ * an entry moves to the opposite stack only after its callback completes.*/import { collectRestorableAssetRefs } from '@workbench/mediaReferences';@@ -12,6 +14,9 @@ export const HISTORY_MAX_ENTRIES = 64;/** Max total bytes retained across the undo + redo stacks before the oldest is evicted (256 MB). */export const HISTORY_BYTE_BUDGET = 256 * 1024 * 1024;+/** Fixed bytes every undo entry is admitted for beyond the pixels or actions it retains. */+export const HISTORY_ENTRY_OVERHEAD_BYTES = 256;+export interface HeldAssetRefs {readonly images: readonly string[];readonly videos: readonly string[];@@ -26,35 +31,48 @@ export const collectHistoryMediaRefs = (...values: unknown[]): HeldAssetRefs =>return { images: [...images], videos: [...videos] };};-/** One reversible step. `bytes` is the (approximate) memory the entry pins, for the budget. */+/** One reversible step. `bytes` is the memory the entry retains. */export interface HistoryEntry {/** Human-readable label (e.g. "Brush stroke"). */readonly label: string;- /** Approximate retained size in bytes (e.g. before+after ImageData byteLength). */+ /** Retained size in bytes; publication requires it to fit the admission. */readonly bytes: number;/*** Media names this entry can restore after they leave the current document; cleanup keeps them while the entry is* on either stack.*/readonly heldAssetRefs: HeldAssetRefs;- /**- * Opts into failure-atomic replay. When true, History moves this entry only- * after `undo`/`redo` returns successfully, so a preparation failure remains- * exactly retryable. The callback must leave its domain unchanged on throw.- *- * Legacy entries default to move-before-replay semantics: a throw is treated- * as post-application observer failure and the entry stays on its destination- * stack, preventing a retry from applying the same mutation twice.- */- readonly replayFailureAtomic?: boolean;/** Releases resources retained only by this entry when it is permanently dropped. */readonly dispose?: () => void;- /** Reverts the change. Must not push new history entries. */- undo(): void;- /** Re-applies the change. Must not push new history entries. */- redo(): void;+ /** Reverts the change. A throw or rejection must leave the domain unchanged; the entry then stays in place. */+ undo(): void | Promise<void>;+ /** Re-applies the change, with the same failure contract as `undo`. */+ redo(): void | Promise<void>;+}++/** Identifies one published entry; equality is the only operation. */+export interface HistoryEntryToken {+ readonly __historyEntryToken: unique symbol;+}++/** Byte capacity reserved for an edit that has not published its entry yet. */+export interface HistoryAdmission {+ readonly bytes: number;+ /** Reserves `bytes` more; false (and unchanged) when the larger entry could never be retained. */+ grow(bytes: number): boolean;+ /**+ * Records `entry`, which must fit the admission, and consumes it. With `replacing`, the entry takes the place of+ * that top entry instead (coalescing); callers check {@link History.top} first.+ */+ publish(entry: HistoryEntry, replacing?: HistoryEntryToken): HistoryEntryToken;+ /** Returns unpublished capacity. Idempotent; a no-op after `publish`. */+ release(): void;}+export type HistoryReplayResult =+ | { status: 'applied' | 'empty' | 'busy' }+ | { status: 'failed'; label: string; error: unknown };+/** Options for {@link createHistory}. */export interface CreateHistoryOptions {/** Undo-entry cap (default {@link HISTORY_MAX_ENTRIES}). */@@ -65,29 +83,22 @@ export interface CreateHistoryOptions {/** The imperative history handle. */export interface History {- /** Records a new entry (clearing the redo stack) and enforces the budgets. No-op while applying. */- push(entry: HistoryEntry): void;- /**- * Replaces the latest undo entry for coalescing, adjusts bytes and clears redo. Falls back to {@link push} if- * empty; no-op during replay.- */- amendLast(entry: HistoryEntry): void;- /** Reverts the most recent entry (moving it onto the redo stack). No-op when empty or already applying. */- undo(): void;- /** Re-applies the most recently undone entry (moving it back onto the undo stack). No-op when empty or applying. */- redo(): void;- /** True when there is at least one entry that can be undone. */+ /** Reserves capacity for an edit's entry, or null when an entry that size could never be retained. */+ admit(bytes: number): HistoryAdmission | null;+ /** The newest undo entry, or null. */+ top(): HistoryEntryToken | null;+ /** Reverts the newest entry. Resolves `busy` while another replay runs. */+ undo(): Promise<HistoryReplayResult>;+ /** Re-applies the most recently undone entry. */+ redo(): Promise<HistoryReplayResult>;canUndo(): boolean;- /** True when there is at least one entry that can be redone. */canRedo(): boolean;- /** True while an entry's `undo`/`redo` is executing (re-entrancy guard). */- isApplying(): boolean;+ /** True while an entry's replay is running; edits are refused meanwhile. */+ isReplaying(): boolean;/** Drops both stacks (document replace / project switch / snapshot restore). */clear(): void;/** Current retained bytes across undo and redo stacks. */byteSize(): number;- /** Whether one entry can remain undoable after normal oldest-entry eviction. */- canRetain(bytes: number): boolean;/** Evicts oldest entries until retained bytes are at or below `budgetBytes`. */trimToBytes(budgetBytes: number): void;/**@@ -97,18 +108,29 @@ export interface History {entries(): { past: readonly string[]; future: readonly string[] };/** Union of media references retained by undo and redo entries. */heldAssetRefs(): HeldAssetRefs;- /** Subscribes to every stack mutation (push, amend, undo, redo, clear, eviction). Returns an unsubscribe function. */+ /** Subscribes to every stack mutation (publish, undo, redo, clear, eviction). Returns an unsubscribe function. */subscribe(listener: () => void): () => void;}+interface StackRecord {+ readonly entry: HistoryEntry;+ readonly token: HistoryEntryToken;+}++const normalizedBytes = (bytes: number): number => (Number.isFinite(bytes) ? Math.max(0, Math.ceil(bytes)) : Infinity);+/** Creates a bounded history stack. */export const createHistory = (opts: CreateHistoryOptions = {}): History => {const maxEntries = Math.max(1, opts.maxEntries ?? HISTORY_MAX_ENTRIES);const byteBudget = Math.max(0, opts.byteBudget ?? HISTORY_BYTE_BUDGET);- const undoStack: HistoryEntry[] = [];- const redoStack: HistoryEntry[] = [];+ const undoStack: StackRecord[] = [];+ const redoStack: StackRecord[] = [];const listeners = new Set<() => void>();+ let undoBytes = 0;+ let redoBytes = 0;+ let admittedBytes = 0;+ let replaying = false;const disposeEntry = (entry: HistoryEntry): void => {try {@@ -119,12 +141,6 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {}};- // Running byte totals, kept in sync with the stacks so eviction is O(1) per drop.- let undoBytes = 0;- let redoBytes = 0;- // Re-entrancy flag: true while replaying an entry.- let applying = false;-const notify = (): void => {for (const listener of listeners) {try {@@ -137,196 +153,110 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {};const clearRedo = (): void => {- if (redoStack.length === 0) {- return;- }const discarded = redoStack.splice(0);- discarded.forEach(disposeEntry);+ discarded.forEach(({ entry }) => disposeEntry(entry));redoBytes = 0;};- /** Evicts the oldest undo entries until BOTH budgets are satisfied. */- const enforceBudgets = (): void => {- while (undoStack.length > maxEntries && undoStack.length > 0) {- const evicted = undoStack.shift();- if (evicted) {- undoBytes -= evicted.bytes;- disposeEntry(evicted);- }- }- while (undoBytes + redoBytes > byteBudget && undoStack.length > 0) {- const evicted = undoStack.shift();- if (evicted) {- undoBytes -= evicted.bytes;- disposeEntry(evicted);- }+ const evictOldest = (): void => {+ while (undoStack.length > maxEntries || (undoBytes + redoBytes > byteBudget && undoStack.length > 1)) {+ const evicted = undoStack.shift()!;+ undoBytes -= evicted.entry.bytes;+ disposeEntry(evicted.entry);}};- const entries = (): { past: readonly string[]; future: readonly string[] } => ({- future: redoStack.map((entry) => entry.label).reverse(),- past: undoStack.map((entry) => entry.label),- });-- // Reused while the stacks hold the same entries, so an unchanged union keeps its identity for the hold lease.- let heldUnion: { parts: HeldAssetRefs[]; refs: HeldAssetRefs } | null = null;- const heldAssetRefs = (): HeldAssetRefs => {- const parts = [...undoStack, ...redoStack].map((entry) => entry.heldAssetRefs);- if (- heldUnion &&- heldUnion.parts.length === parts.length &&- parts.every((part, i) => part === heldUnion!.parts[i])- ) {- return heldUnion.refs;- }- const images = new Set<string>();- const videos = new Set<string>();- for (const part of parts) {- part.images.forEach((name) => images.add(name));- part.videos.forEach((name) => videos.add(name));+ const admit = (requestedBytes: number): HistoryAdmission | null => {+ let bytes = normalizedBytes(requestedBytes);+ if (admittedBytes + bytes > byteBudget) {+ return null;}- heldUnion = { parts, refs: { images: [...images], videos: [...videos] } };- return heldUnion.refs;- };-- const push = (entry: HistoryEntry): void => {- // Replaying an entry must never record a new one; drop it defensively.- if (applying) {- disposeEntry(entry);- return;- }- clearRedo();- undoStack.push(entry);- undoBytes += entry.bytes;- enforceBudgets();- notify();+ admittedBytes += bytes;+ let state: 'open' | 'published' | 'released' = 'open';+ const close = (): void => {+ admittedBytes -= bytes;+ };+ return {+ get bytes() {+ return bytes;+ },+ grow: (additional) => {+ const extra = normalizedBytes(additional);+ if (state !== 'open' || admittedBytes + extra > byteBudget) {+ return false;+ }+ admittedBytes += extra;+ bytes += extra;+ return true;+ },+ publish: (entry, replacing) => {+ if (state !== 'open') {+ throw new Error('History admission was already consumed.');+ }+ if (entry.bytes > bytes) {+ throw new Error(`History entry "${entry.label}" exceeds its admission (${entry.bytes} > ${bytes} bytes).`);+ }+ if (replacing !== undefined && undoStack.at(-1)?.token !== replacing) {+ throw new Error('History entry to replace is no longer the newest step.');+ }+ state = 'published';+ close();+ clearRedo();+ if (replacing !== undefined) {+ const replaced = undoStack.pop()!;+ undoBytes -= replaced.entry.bytes;+ disposeEntry(replaced.entry);+ }+ const token = Object.freeze({}) as HistoryEntryToken;+ undoStack.push({ entry, token });+ undoBytes += entry.bytes;+ evictOldest();+ notify();+ return token;+ },+ release: () => {+ if (state === 'open') {+ state = 'released';+ close();+ }+ },+ };};- const amendLast = (entry: HistoryEntry): void => {- if (applying) {- disposeEntry(entry);- return;- }- if (undoStack.length === 0) {- push(entry);- return;+ /** Replays the top of `from`; moves it to `to` only when its callback completes and nothing reset the stacks. */+ const replay = async (direction: 'undo' | 'redo'): Promise<HistoryReplayResult> => {+ const from = direction === 'undo' ? undoStack : redoStack;+ if (replaying) {+ return { status: 'busy' };}- clearRedo();- const replaced = undoStack.pop();- if (replaced) {- undoBytes -= replaced.bytes;- disposeEntry(replaced);+ const record = from.at(-1);+ if (!record) {+ return { status: 'empty' };}- undoStack.push(entry);- undoBytes += entry.bytes;- enforceBudgets();+ replaying = true;notify();- };-- const undo = (): void => {- if (applying || undoStack.length === 0) {- return;- }- const entry = undoStack.at(-1);- if (!entry) {- return;- }- if (!entry.replayFailureAtomic) {- // Legacy replay may mutate before observer failure: move first to prevent duplicate retries. A replay-time- // clear owns reset and notification.- undoStack.pop();- undoBytes -= entry.bytes;- redoStack.push(entry);- redoBytes += entry.bytes;- let replayError: unknown;- let didThrow = false;- applying = true;- try {- entry.undo();- } catch (error) {- replayError = error;- didThrow = true;- } finally {- applying = false;- }- if (redoStack.at(-1) === entry) {- notify();- }- if (didThrow) {- // Preserve the callback's exact exception value for legacy callers.- // eslint-disable-next-line no-throw-literal- throw replayError;- }- return;- }- applying = true;try {- entry.undo();+ await (direction === 'undo' ? record.entry.undo() : record.entry.redo());+ } catch (error) {+ return { error, label: record.entry.label, status: 'failed' };} finally {- applying = false;+ replaying = false;}- // A replay callback may intentionally clear history (for example a- // synchronous document replacement). Let that reset win; never resurrect- // the entry onto the opposite stack after its original stack changed.- if (undoStack.at(-1) !== entry) {- return;- }- // Fallible replay moves entries only after success, preserving stacks and byte totals for an exact retry.- undoStack.pop();- undoBytes -= entry.bytes;- redoStack.push(entry);- redoBytes += entry.bytes;- notify();- };-- const redo = (): void => {- if (applying || redoStack.length === 0) {- return;- }- const entry = redoStack.at(-1);- if (!entry) {- return;- }- if (!entry.replayFailureAtomic) {- redoStack.pop();- redoBytes -= entry.bytes;- undoStack.push(entry);- undoBytes += entry.bytes;- let replayError: unknown;- let didThrow = false;- applying = true;- try {- entry.redo();- } catch (error) {- replayError = error;- didThrow = true;- } finally {- applying = false;+ // A replay may itself clear history (a document replacement); never resurrect the entry onto the other stack.+ if (from.at(-1) === record) {+ from.pop();+ if (direction === 'undo') {+ undoBytes -= record.entry.bytes;+ redoStack.push(record);+ redoBytes += record.entry.bytes;+ } else {+ redoBytes -= record.entry.bytes;+ undoStack.push(record);+ undoBytes += record.entry.bytes;}- if (undoStack.at(-1) === entry) {- notify();- }- if (didThrow) {- // Preserve the callback's exact exception value for legacy callers.- // eslint-disable-next-line no-throw-literal- throw replayError;- }- return;- }- applying = true;- try {- entry.redo();- } finally {- applying = false;- }- if (redoStack.at(-1) !== entry) {- return;}- redoStack.pop();- redoBytes -= entry.bytes;- undoStack.push(entry);- undoBytes += entry.bytes;notify();+ return { status: 'applied' };};const clear = (): void => {@@ -336,7 +266,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const discarded = [...undoStack, ...redoStack];undoStack.length = 0;redoStack.length = 0;- discarded.forEach(disposeEntry);+ discarded.forEach(({ entry }) => disposeEntry(entry));undoBytes = 0;redoBytes = 0;notify();@@ -346,45 +276,64 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {const budget = Math.max(0, budgetBytes);let changed = false;while (undoBytes + redoBytes > budget && undoStack.length > 0) {- const evicted = undoStack.shift();- if (evicted) {- undoBytes -= evicted.bytes;- disposeEntry(evicted);- changed = true;- }+ const evicted = undoStack.shift()!;+ undoBytes -= evicted.entry.bytes;+ disposeEntry(evicted.entry);+ changed = true;}while (undoBytes + redoBytes > budget && redoStack.length > 0) {- const evicted = redoStack.shift();- if (evicted) {- redoBytes -= evicted.bytes;- disposeEntry(evicted);- changed = true;- }+ const evicted = redoStack.shift()!;+ redoBytes -= evicted.entry.bytes;+ disposeEntry(evicted.entry);+ changed = true;}if (changed) {notify();}};+ // Reused while the stacks hold the same entries, so an unchanged union keeps its identity for the hold lease.+ let heldUnion: { parts: HeldAssetRefs[]; refs: HeldAssetRefs } | null = null;+ const heldAssetRefs = (): HeldAssetRefs => {+ const parts = [...undoStack, ...redoStack].map(({ entry }) => entry.heldAssetRefs);+ if (+ heldUnion &&+ heldUnion.parts.length === parts.length &&+ parts.every((part, i) => part === heldUnion!.parts[i])+ ) {+ return heldUnion.refs;+ }+ const images = new Set<string>();+ const videos = new Set<string>();+ for (const part of parts) {+ part.images.forEach((name) => images.add(name));+ part.videos.forEach((name) => videos.add(name));+ }+ heldUnion = { parts, refs: { images: [...images], videos: [...videos] } };+ return heldUnion.refs;+ };+return {- amendLast,+ admit,byteSize: () => undoBytes + redoBytes,- entries,- heldAssetRefs,- canRetain: (bytes) => Number.isFinite(bytes) && Math.max(0, Math.ceil(bytes)) <= byteBudget,canRedo: () => redoStack.length > 0,canUndo: () => undoStack.length > 0,clear,- isApplying: () => applying,- push,- redo,+ entries: () => ({+ future: redoStack.map(({ entry }) => entry.label).reverse(),+ past: undoStack.map(({ entry }) => entry.label),+ }),+ heldAssetRefs,+ isReplaying: () => replaying,+ redo: () => replay('redo'),subscribe: (listener) => {listeners.add(listener);return () => {listeners.delete(listener);};},+ top: () => undoStack.at(-1)?.token ?? null,trimToBytes,- undo,+ undo: () => replay('undo'),};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.tsindex 1a97759ef4..4494320e37 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/imagePatch.ts@@ -12,9 +12,10 @@ import { NO_HELD_ASSET_REFS } from './history';/*** Engine-owned pixel write at the layer-local rect, including invalidation/versioning and dirty persistence- * marking.+ * marking. It first makes the layer's cache trustworthy (rasterizing an evicted or stale one) and rejects, leaving+ * the cache unchanged, when it cannot.*/-export type ImagePatchApply = (layerId: string, rect: Rect, pixels: ImageData) => void;+export type ImagePatchApply = (layerId: string, rect: Rect, pixels: ImageData) => Promise<void>;/** Options for {@link createImagePatchEntry}. */export interface CreateImagePatchEntryOptions {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.tsindex 0e1a7b409e..f24c21ee4b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.test.ts@@ -45,7 +45,6 @@ describe('createLayerSnapshotEntry', () => {expect(entry.bytes).toBe(before.pixels!.data.byteLength + after.pixels!.data.byteLength + 256);expect(entry.heldAssetRefs?.images).toEqual(['before']);- expect(entry.replayFailureAtomic).toBe(true);entry.undo();entry.redo();expect(apply).toHaveBeenNthCalledWith(1, before);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.tsindex 22d4d2c818..f192d9e9b1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/layerSnapshot.ts@@ -12,7 +12,8 @@ export interface LayerPixelSnapshot {pixels: ImageData | null;}-export type LayerPixelSnapshotApply = (snapshot: LayerPixelSnapshot) => void;+/** Installs a snapshot; throws or rejects, leaving the layer unchanged, when it cannot land. */+export type LayerPixelSnapshotApply = (snapshot: LayerPixelSnapshot) => void | Promise<void>;export interface CreateLayerSnapshotEntryOptions {before: LayerPixelSnapshot;@@ -62,7 +63,6 @@ export const createLayerSnapshotEntry = ({heldAssetRefs: collectHistoryMediaRefs(beforeSnapshot.layer, afterSnapshot.layer),label,redo: () => apply(afterSnapshot),- replayFailureAtomic: true,undo: () => apply(beforeSnapshot),};};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 dcc42bf780..bbaa031e60 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@@ -72,6 +72,7 @@ const createInputHarness = () => {getToolContext: () => ctx,handleEscape: () => events.push('escape'),hasTool: (id) => id in tools,+ isReplaying: () => false,setTool: (id, options) => interaction.setTool(id, options),updateCursor: () => undefined,viewport: createViewport(),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 6518ab61f0..5d9af7eb32 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@@ -75,6 +75,7 @@ const createHarness = (tools?: ToolId[];handleEscape?: (o: { gestureWasActive: boolean }) => void;maybeCommitModalSession?: () => boolean;+ replaying?: () => boolean;} = {}) => {const registered = new Set<ToolId>(opts.tools ?? ['view', 'brush']);@@ -125,6 +126,7 @@ const createHarness = (getToolContext: () => ctx,handleEscape: opts.handleEscape,hasTool: (id) => registered.has(id),+ isReplaying: () => opts.replaying?.() ?? false,maybeCommitModalSession: opts.maybeCommitModalSession,setTool,updateCursor: vi.fn(),@@ -570,6 +572,26 @@ describe('pointer pipeline: canvas keyboard ownership', () => {});});+describe('pointer pipeline: history replay', () => {+ it('starts no gesture while a replay runs, but still pans with the middle button', () => {+ let replaying = true;+ const h = createHarness({ replaying: () => replaying });+ const press = makePointerEvent({ pointerId: 1 });+ h.pipeline.onPointerDown(press);++ expect(h.tool.downs).toHaveLength(0);+ expect(h.pipeline.isGestureActive()).toBe(false);+ expect(press.preventDefault).toHaveBeenCalled();+ h.pipeline.onPointerDown(makePointerEvent({ button: 1, pointerId: 2 }));+ expect(h.captures).toEqual([2]);++ replaying = false;+ h.pipeline.onPointerUp(makePointerEvent({ buttons: 0, pointerId: 2 }));+ h.pipeline.onPointerDown(makePointerEvent({ pointerId: 3 }));+ expect(h.tool.downs).toHaveLength(1);+ });+});+describe('pointer pipeline: cancellation ownership', () => {it('a tool-switch cancel turns the rest of the pressed drag into hover until the pointer is released', () => {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 188496e2ca..e927906f1a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts@@ -48,6 +48,8 @@ export interface PointerPipelineDeps {* without capture or tool routing, avoiding mid-gesture commit guards.*/maybeCommitModalSession?(): boolean;+ /** True while an undo/redo replays; primary presses start no gesture then (panning stays available). */+ isReplaying(): boolean;}/** The pipeline handle: DOM handlers plus lifecycle reset. */@@ -448,6 +450,10 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinif (event.button !== 0) {return;}+ if (deps.isReplaying()) {+ event.preventDefault();+ return;+ }cancelledPointerId = null;// Commit and consume modal text presses before gesture activation; prevent default focus/selection after// closing the session.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.tsindex c7c6455723..76d2ca1dbe 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts@@ -59,11 +59,9 @@ interface Harness {cancel: ReturnType<typeof vi.fn>;invalidateLayerCache: ReturnType<typeof vi.fn>;invalidateLayerRender: ReturnType<typeof vi.fn>;- releaseBitmapIfUnreferenced: ReturnType<typeof vi.fn>;reportError: ReturnType<typeof vi.fn>;setStatus: ReturnType<typeof vi.fn>;setVersion: ReturnType<typeof vi.fn>;- trackPublishedLayerImage: ReturnType<typeof vi.fn>;};}@@ -85,11 +83,9 @@ const makeHarness = (overrides: Partial<CreateLayerRasterizerDeps> = {}): Harnescancel: vi.fn(),invalidateLayerCache: vi.fn(),invalidateLayerRender: vi.fn(),- releaseBitmapIfUnreferenced: vi.fn(),reportError: vi.fn(),setStatus: vi.fn(),setVersion: vi.fn(),- trackPublishedLayerImage: vi.fn(),};const result: Harness = {document,@@ -134,10 +130,8 @@ const makeHarness = (overrides: Partial<CreateLayerRasterizerDeps> = {}): Harnesversion: vi.fn(() => entry.version),} as unknown as CreateLayerRasterizerDeps['layerCache'],rasterize: rasterize as unknown as CreateLayerRasterizerDeps['rasterize'],- releaseBitmapIfUnreferenced: spies.releaseBitmapIfUnreferenced,reportError: spies.reportError,thumbnails: { setStatus: spies.setStatus, setVersion: spies.setVersion },- trackPublishedLayerImage: spies.trackPublishedLayerImage,...overrides,},};@@ -226,16 +220,10 @@ describe('publishing', () => {harness.rasterize.mockResolvedValue({ rect, surface: pixels });await expect(start()).resolves.toBe('published');expect(harness.deps.layerCache.publishRasterized).toHaveBeenCalledWith('layer-1', rect, pixels, undefined);- expect(harness.spies.trackPublishedLayerImage).toHaveBeenCalled();expect(harness.spies.setVersion).toHaveBeenCalledWith('layer-1', 4);expect(harness.spies.setStatus).toHaveBeenCalledWith('layer-1', 'ready');expect(harness.spies.invalidateLayerRender).toHaveBeenCalledWith('layer-1');});-- it('keeps the decoded bitmap it published', async () => {- await start();- expect(harness.spies.releaseBitmapIfUnreferenced).not.toHaveBeenCalled();- });});describe('a result that no longer describes the live layer', () => {@@ -275,15 +263,6 @@ describe('a result that no longer describes the live layer', () => {});await expect(start()).resolves.toBe('stale');});-- it('releases the bitmap it pulled in but never published', async () => {- harness.rasterize.mockImplementation(() => {- harness.state.disposed = true;- return Promise.resolve({ rect: { height: 4, width: 4, x: 0, y: 0 }, surface: surface() });- });- await start();- expect(harness.spies.releaseBitmapIfUnreferenced).toHaveBeenCalledWith('a.png');- });});describe('failure', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.tsindex 40efb2803a..394271e514 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts@@ -17,17 +17,6 @@ import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGua/** How a rasterization ended: pixels landed, the world moved, it threw, or it was cancelled. */export type LayerRasterizationOutcome = 'published' | 'stale' | 'error' | 'aborted';-/** The image a source references, whose decoded bitmap the job holds a reference to. */-const sourceImageName = (source: CanvasLayerSourceContract): string | null => {- if (source.type === 'image') {- return source.image.imageName;- }- if (source.type === 'paint') {- return source.bitmap?.imageName ?? null;- }- return null;-};-/** The registry of in-flight rasterizations, keyed by layer. */export interface RasterizationJobRegistry {getDocumentGeneration(): number;@@ -57,8 +46,6 @@ export interface CreateLayerRasterizerDeps {readonly isDisposed: () => boolean;readonly invalidateLayerCache: (layerId: string) => void;readonly invalidateLayerRender: (layerId: string) => void;- readonly trackPublishedLayerImage: (layer: CanvasLayerContract) => void;- readonly releaseBitmapIfUnreferenced: (imageName: string) => void;readonly reportError: (message: 'Layer thumbnail rasterization failed', layerId: string, error: unknown) => void;}@@ -161,7 +148,6 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas};signal?.addEventListener('abort', abort, { once: true });jobs.install(layer.id, job);- let published = false;void (async () => {try {const result = await deps.rasterize(source, document, scratch, controller.signal);@@ -181,8 +167,6 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas}const publishedEntry = layerCache.publishRasterized(layer.id, result.rect, result.surface, renderedFontFamily);- deps.trackPublishedLayerImage(currentLayer);- published = true;deps.thumbnails.setVersion(layer.id, publishedEntry.version);deps.thumbnails.setStatus(layer.id, 'ready');deps.invalidateLayerRender(layer.id);@@ -214,11 +198,6 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas} finally {signal?.removeEventListener('abort', abort);jobs.finish(layer.id, job);- // A job that did not publish still holds the decoded bitmap it pulled in.- const imageName = sourceImageName(source);- if (!published && imageName) {- deps.releaseBitmapIfUnreferenced(imageName);- }}})().then(settleJob, () => settleJob('stale'));return promise;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.tsindex e3ba4dc4d4..008526e815 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts@@ -49,7 +49,7 @@ interface Harness {memory: RasterMemoryBudgetController;state: {canvas: CanvasStateContractV3 | null;- contentEpoch: number;+ directPixelEpoch: number;disposed: boolean;documentGeneration: number;lifecycleGeneration: number;@@ -66,7 +66,7 @@ const makeHarness = (): Harness => {const state = {canvas: canvasState() as CanvasStateContractV3 | null,- contentEpoch: 0,+ directPixelEpoch: 0,disposed: false,documentGeneration: 1,lifecycleGeneration: 0,@@ -80,7 +80,7 @@ const makeHarness = (const deps: CreateRasterSnapshotCaptureDeps = {createSurface: (width, height) => surface(width, height),getCanvasState: () => state.canvas,- getContentEpoch: () => state.contentEpoch,+ getDirectPixelEpoch: () => state.directPixelEpoch,getDocumentGeneration: () => state.documentGeneration,getLifecycleGeneration: () => state.lifecycleGeneration,isDisposed: () => state.disposed,@@ -122,7 +122,7 @@ describe('isDocumentSnapshotCurrent', () => {it.each([['the canvas object is replaced', (h: Harness) => (h.state.canvas = canvasState())],- ['the raster content epoch advances', (h: Harness) => (h.state.contentEpoch += 1)],+ ['the raster content epoch advances', (h: Harness) => (h.state.directPixelEpoch += 1)],['the lifecycle generation advances', (h: Harness) => (h.state.lifecycleGeneration += 1)],['the document generation advances', (h: Harness) => (h.state.documentGeneration += 1)],['the engine is disposed', (h: Harness) => (h.state.disposed = true)],@@ -318,7 +318,7 @@ describe('captureRasterSnapshot', () => {harness.state.canvas = canvasState(['a', 'b']);harness.rasterize.mockImplementation((layerId: string) => {if (layerId === 'b') {- harness.state.contentEpoch += 1;+ harness.state.directPixelEpoch += 1;}const result = okPixels(layerId);harness.currentGuards.add(result.status === 'ok' ? result.guard : guard(layerId));@@ -335,7 +335,7 @@ describe('captureRasterSnapshot', () => {detaching.state.canvas = canvasState(['a', 'b']);detaching.rasterize.mockImplementation((layerId: string) => {// The edit lands while the FIRST layer is still rasterizing.- detaching.state.contentEpoch += 1;+ detaching.state.directPixelEpoch += 1;const result = okPixels(layerId);detaching.currentGuards.add(result.status === 'ok' ? result.guard : guard(layerId));return Promise.resolve(result);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.tsindex 7c6d9fec24..ade1fc6137 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts@@ -34,7 +34,7 @@ export interface CreateRasterSnapshotCaptureDeps {readonly createSurface: (width: number, height: number) => RasterSurface;readonly getCanvasState: () => CanvasStateContractV3 | null;readonly getDocumentGeneration: () => number;- readonly getContentEpoch: () => number;+ readonly getDirectPixelEpoch: () => number;readonly getLifecycleGeneration: () => number;readonly isDisposed: () => boolean;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;@@ -72,7 +72,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDepconst activeSnapshots = new Set<CanvasRasterSnapshot>();const snapshotSources = new WeakMap<CanvasDocumentSnapshot,- { canvas: CanvasStateContractV3; contentEpoch: number; lifecycleGeneration: number }+ { canvas: CanvasStateContractV3; directPixelEpoch: number; lifecycleGeneration: number }>();const isDocumentSnapshotCurrent = (snapshot: CanvasDocumentSnapshot): boolean => {@@ -81,7 +81,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep!deps.isDisposed() &&source !== undefined &&source.canvas === deps.getCanvasState() &&- source.contentEpoch === deps.getContentEpoch() &&+ source.directPixelEpoch === deps.getDirectPixelEpoch() &&source.lifecycleGeneration === deps.getLifecycleGeneration() &&snapshot.documentGeneration === deps.getDocumentGeneration());@@ -238,7 +238,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep};snapshotSources.set(snapshot, {canvas,- contentEpoch: deps.getContentEpoch(),+ directPixelEpoch: deps.getDirectPixelEpoch(),lifecycleGeneration: deps.getLifecycleGeneration(),});return snapshot;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.tsindex 05627ed524..0cbaf13780 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts@@ -82,6 +82,8 @@ export interface LayerCacheEntryState {export interface LayerCacheStore {/** Returns an entry without changing LRU order. */peek(layerId: string): LayerCacheEntry | undefined;+ /** Ids of every layer that holds a cache entry. */+ layerIds(): string[];/** Returns the existing cache entry for a layer, or `undefined`. Touches LRU order. */get(layerId: string): LayerCacheEntry | undefined;/**@@ -604,6 +606,7 @@ export const createLayerCacheStore = (installReplacement,damageSince,invalidate,+ layerIds: () => [...entries.keys()],peek,prepareReplacement,publishPixels,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.tsindex 80f816a5bd..bed9962ec8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts@@ -11,8 +11,8 @@ const DOC = { height: 100, width: 100 };const rectBounds = (x: number, y: number, w: number, h: number): Rect => ({ height: h, width: w, x, y });const fakePath = (id: string): Path2D => ({ id }) as unknown as Path2D;-const createHarness = () => {- const history = createHistory();+const createHarness = (options: Parameters<typeof createHistory>[0] = {}) => {+ const history = createHistory(options);const onChange = vi.fn();const selection = withSelectionHistory(createSelectionState({@@ -38,20 +38,20 @@ describe('withSelectionHistory', () => {expect(history.entries().past).toEqual(['Select all', 'Subtract from selection', 'Invert selection', 'Deselect']);});- it('undo and redo replay the captured selections without recording again', () => {+ it('undo and redo replay the captured selections without recording again', async () => {const { history, selection } = createHarness();selection.commit({ bounds: rectBounds(10, 10, 20, 20), op: 'replace', path: fakePath('a') });selection.commit({ bounds: rectBounds(40, 40, 10, 10), op: 'add', path: fakePath('b') });expect(selection.bounds()).toEqual(rectBounds(10, 10, 40, 40));- history.undo();+ await history.undo();expect(selection.bounds()).toEqual(rectBounds(10, 10, 20, 20));expect(selection.antsPaths()).toHaveLength(1);- history.undo();+ await history.undo();expect(selection.hasSelection()).toBe(false);expect(selection.antsPaths()).toEqual([]);- history.redo();- history.redo();+ await history.redo();+ await history.redo();expect(selection.bounds()).toEqual(rectBounds(10, 10, 40, 40));expect(selection.antsPaths()).toHaveLength(2);expect(history.entries()).toEqual({ future: [], past: ['Select', 'Add to selection'] });@@ -64,7 +64,7 @@ describe('withSelectionHistory', () => {expect(history.canUndo()).toBe(false);});- it('records a pixel-mask replacement as Select object and undoes it to the prior selection', () => {+ it('records a pixel-mask replacement as Select object and undoes it to the prior selection', async () => {const { history, selection } = createHarness();const backend = createTestStubRasterBackend();const surface = backend.createSurface(2, 2);@@ -80,7 +80,7 @@ describe('withSelectionHistory', () => {expect(history.entries().past).toEqual(['Select object']);expect(selection.bounds()).toEqual(rectBounds(7, -3, 2, 2));- history.undo();+ await history.undo();expect(selection.hasSelection()).toBe(false);});@@ -100,4 +100,35 @@ describe('withSelectionHistory', () => {// The inverted plane is new; the select-all plane it started from was already charged.expect(history.byteSize()).toBe(2 * 100 * 100);});++ it('rolls a change back exactly when its step could never be kept', () => {+ // A 100×100 selection plane alone exceeds the whole budget.+ const { history, selection } = createHarness({ byteBudget: 100 });++ selection.selectAll(rectBounds(0, 0, 100, 100));+ expect(selection.hasSelection()).toBe(false);+ expect(history.entries().past).toEqual([]);+ });++ it('refuses a change while another step replays', async () => {+ const { history, selection } = createHarness();+ let finish = (): void => undefined;+ history.admit(0)!.publish({+ bytes: 0,+ heldAssetRefs: { images: [], videos: [] },+ label: 'Slow step',+ redo: () => undefined,+ undo: () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ });+ const replay = history.undo();++ selection.selectAll(rectBounds(0, 0, 100, 100));+ expect(selection.hasSelection()).toBe(false);+ finish();+ await replay;+ expect(history.entries()).toEqual({ future: ['Slow step'], past: [] });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.tsindex 6b66b91e25..c27be761ed 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.ts@@ -1,6 +1,7 @@/*** Snapshots selection-changing calls into individual engine-history steps. Unchanged selections record nothing;- * replay restores snapshots directly without recording again.+ * replay restores snapshots directly without recording again. A change is refused while a replay runs, and one+ * whose step history could never keep is rolled back to the exact prior snapshot.*/import type { History } from '@workbench/canvas-engine/history/history';@@ -54,12 +55,14 @@ const commitLabel = (commit: SelectionCommit): string =>commit.op === 'replace' && isEmpty(commit.bounds) ? 'Deselect' : COMMIT_LABELS[commit.op];/** Wraps `selection` so its mutations record on `history`; reads and replay pass through untouched. */-export const withSelectionHistory = (selection: SelectionState, history: History): SelectionState => {+export const withSelectionHistory = (+ selection: SelectionState,+ history: Pick<History, 'admit' | 'isReplaying'>+): SelectionState => {// Consecutive steps share their boundary capture; charge a plane once.let lastAfter: SelectionSnapshot | null = null;const record = (label: string, mutate: () => void): void => {- if (history.isApplying()) {- mutate();+ if (history.isReplaying()) {return;}const before = selection.snapshot();@@ -69,9 +72,15 @@ export const withSelectionHistory = (selection: SelectionState, history: Historyreturn;}const beforeBytes = before === lastAfter ? 0 : (before.alpha?.byteLength ?? 0);+ // The result's size is known only once computed; restoring the snapshot is exact.+ const admission = history.admit(beforeBytes + (after.alpha?.byteLength ?? 0));+ if (!admission) {+ selection.restore(before);+ return;+ }lastAfter = after;- history.push({- bytes: beforeBytes + (after.alpha?.byteLength ?? 0),+ admission.publish({+ bytes: admission.bytes,heldAssetRefs: NO_HELD_ASSET_REFS,label,redo: () => selection.restore(after),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.tsindex 5769a3faf5..caddbb9f76 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts@@ -1,123 +1,195 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';+import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';-import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';--import { createStrokeCommit, type CreateStrokeCommitDeps } from './strokeCommit';--/** Dimensions must match the event's dirty rect — `createImagePatchEntry` asserts it. */-const imageData = (bytes = 4): ImageData =>- ({ data: { byteLength: bytes }, height: 4, width: 4 }) as unknown as ImageData;--const strokeEvent = (overrides: Partial<StrokeCommittedEvent> = {}): StrokeCommittedEvent =>- ({- afterImageData: imageData(),- beforeImageData: imageData(),- createdLayer: undefined,- dirtyRect: { height: 4, width: 4, x: 1, y: 2 },- layerId: 'layer-1',- tool: 'brush',- ...overrides,- }) as unknown as StrokeCommittedEvent;--type TestDeps = {- -readonly [K in keyof CreateStrokeCommitDeps]: CreateStrokeCommitDeps[K];-} & { history: { isApplying: ReturnType<typeof vi.fn>; push: ReturnType<typeof vi.fn> } };--let deps: TestDeps;-let listener: Mock<(event: StrokeCommittedEvent) => void>;--beforeEach(() => {- listener = vi.fn<(event: StrokeCommittedEvent) => void>();- deps = {- applyImagePatch: vi.fn(),+import { createHistory, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { describe, expect, it, vi } from 'vitest';++import { createStrokeEdits } from './strokeCommit';++const RECT = { height: 4, width: 4, x: 1, y: 2 };+const pixels = (): ImageData => ({ data: new Uint8ClampedArray(64), height: 4, width: 4 }) as unknown as ImageData;++const strokeEvent = (overrides: Partial<StrokeCommittedEvent> = {}): StrokeCommittedEvent => ({+ afterImageData: pixels(),+ beforeImageData: pixels(),+ dirtyRect: RECT,+ layerId: 'paint',+ tool: 'brush',+ ...overrides,+});++/** The stroke edits over a real reducer, mutation context and history. */+const createHarness = (byteBudget?: number, gesture = { active: false }) => {+ let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {+ document: documentFrom([layerContract('paint')]),+ type: 'replaceCanvasDocument',+ });+ const history = createHistory({ byteBudget });+ const layerCache = createLayerCacheStore(createTestStubRasterBackend());+ const context = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch: (action: CanvasProjectMutation) => {+ project = applyCanvasProjectMutation(project, action);+ return true;+ },+ editOwner: Symbol('owner'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => project.canvas.document,+ getReducerDocument: () => project.canvas.document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => gesture.active,+ isGuardCurrent: () => true,+ preparePixels: () => {+ throw new Error('unused');+ },+ projectId: project.id,+ refreshMirror: () => undefined,+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),+ subscribeReducer: () => () => undefined,+ });+ const deps = {+ applyImagePatch: vi.fn(() => Promise.resolve()),commitPaintEdit: vi.fn(),- dispatchCanvasMutation: vi.fn(() => true),- endNudgeBurst: vi.fn(),- history: { isApplying: vi.fn(() => false), push: vi.fn() },- layerCache: { getOrCreateRect: vi.fn(() => ({ stale: true })) } as unknown as CreateStrokeCommitDeps['layerCache'],+ ctx: context,+ layerCache,markLayerDirty: vi.fn(),notifyLayerPainted: vi.fn(),- strokeListeners: new Set<(event: StrokeCommittedEvent) => void>([listener]),- } as unknown as TestDeps;-});--describe('commitOrdinaryStroke', () => {- it('ends the nudge burst, repaints, and marks the layer dirty before recording history', () => {- createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent());- expect(deps.endNudgeBurst).toHaveBeenCalled();- expect(deps.notifyLayerPainted).toHaveBeenCalledWith('layer-1');- expect(deps.markLayerDirty).toHaveBeenCalledWith('layer-1');- expect(deps.history.push).toHaveBeenCalledTimes(1);+ reportRefusal: vi.fn(),+ strokeListeners: new Set<(event: StrokeCommittedEvent) => void>(),+ };+ return {+ deps,+ document: () => project.canvas.document,+ dispatch: (action: CanvasProjectMutation) => {+ project = applyCanvasProjectMutation(project, action);+ },+ edits: createStrokeEdits(deps),+ history,+ };+};++describe('stroke edits', () => {+ it('records the painted pixels as one labelled step and publishes the paint afterwards', () => {+ const h = createHarness();+ const listener = vi.fn();+ h.deps.strokeListeners.add(listener);+ const event = strokeEvent({ tool: 'eraser' });++ const edit = h.edits.begin()!;+ expect(edit.grow(128)).toBe(true);+ expect(edit.commit(event)).toBe(true);++ expect(h.history.entries().past).toEqual(['Eraser stroke']);+ expect(h.history.byteSize()).toBe(128);+ expect(h.deps.notifyLayerPainted).toHaveBeenCalledWith('paint');+ expect(h.deps.markLayerDirty).toHaveBeenCalledWith('paint');+ expect(h.deps.commitPaintEdit).toHaveBeenCalledOnce();+ expect(listener).toHaveBeenCalledWith(event);});- it('labels the entry by the committing tool', () => {- createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ tool: 'eraser' } as Partial<StrokeCommittedEvent>));- expect(deps.history.push.mock.calls[0]?.[0]).toMatchObject({ label: 'Eraser stroke' });+ it('admits a stroke during its own gesture and records it once the gesture ends', () => {+ const gesture = { active: true };+ const h = createHarness(undefined, gesture);- deps.history.push.mockClear();- createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent());- expect(deps.history.push.mock.calls[0]?.[0]).toMatchObject({ label: 'Brush stroke' });+ const edit = h.edits.begin()!;+ expect(edit).not.toBeNull();+ edit.grow(128);+ gesture.active = false;+ expect(edit.commit(strokeEvent())).toBe(true);+ expect(h.history.canUndo()).toBe(true);});- it('records no history while a replay is applying, but still repaints and notifies', () => {- deps.history.isApplying = vi.fn(() => true);- createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent());- expect(deps.history.push).not.toHaveBeenCalled();- expect(deps.commitPaintEdit).not.toHaveBeenCalled();- expect(deps.notifyLayerPainted).toHaveBeenCalled();- expect(listener).toHaveBeenCalled();+ it('refuses a stroke whose undo footprint could never be kept, before it paints', () => {+ const h = createHarness(HISTORY_ENTRY_OVERHEAD_BYTES + 64);++ expect(h.edits.begin(HISTORY_ENTRY_OVERHEAD_BYTES + 65)).toBeNull();+ expect(h.deps.reportRefusal).toHaveBeenCalledWith('over-budget');++ const edit = h.edits.begin()!;+ expect(edit.grow(64)).toBe(true);+ expect(edit.grow(1)).toBe(false);+ expect(edit.grow(1)).toBe(false);+ expect(h.deps.reportRefusal).toHaveBeenCalledTimes(2);+ edit.cancel();+ expect(h.history.canUndo()).toBe(false);});- it('fans the event out to every subscriber', () => {- const second = vi.fn<(event: StrokeCommittedEvent) => void>();- deps.strokeListeners = new Set<(event: StrokeCommittedEvent) => void>([listener, second]);+ it('replays the before and after pixels through the engine bridge', async () => {+ const h = createHarness();const event = strokeEvent();- createStrokeCommit(deps).commitOrdinaryStroke(event);- expect(listener).toHaveBeenCalledWith(event);- expect(second).toHaveBeenCalledWith(event);+ const edit = h.edits.begin()!;+ edit.grow(128);+ edit.commit(event);++ await h.history.undo();+ expect(h.deps.applyImagePatch).toHaveBeenLastCalledWith('paint', RECT, event.beforeImageData);+ await h.history.redo();+ expect(h.deps.applyImagePatch).toHaveBeenLastCalledWith('paint', RECT, event.afterImageData);});-});-describe('a stroke that auto-created its layer', () => {- const created = { anchor: stackTopAnchor('p'), layer: { id: 'layer-1' } as never };+ it('keeps a step in place when its pixels cannot be restored', async () => {+ const h = createHarness();+ const edit = h.edits.begin()!;+ edit.grow(128);+ edit.commit(strokeEvent());+ h.deps.applyImagePatch.mockRejectedValueOnce(new Error('not ready'));- it('undoes by removing the layer, not just the pixels', () => {- createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));- const entry = deps.history.push.mock.calls[0]?.[0] as { undo(): void };- entry.undo();- expect(deps.dispatchCanvasMutation).toHaveBeenCalledWith({ ids: ['layer-1'], type: 'removeCanvasLayers' });+ expect((await h.history.undo()).status).toBe('failed');+ expect(h.history.entries()).toEqual({ future: [], past: ['Brush stroke'] });});+});- it('redoes by re-adding the layer at its anchor, then writing the pixels back', () => {- createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));- const entry = deps.history.push.mock.calls[0]?.[0] as { redo(): void };- entry.redo();- expect(deps.dispatchCanvasMutation).toHaveBeenCalledWith({- anchor: created.anchor,- layer: created.layer,- type: 'addCanvasLayer',- });- expect(deps.applyImagePatch).toHaveBeenCalledWith(- 'layer-1',- { height: 4, width: 4, x: 1, y: 2 },- expect.anything()- );+describe('a stroke that auto-created its layer', () => {+ const createdStroke = (h: ReturnType<typeof createHarness>) => {+ const anchor = stackTopAnchor(h.deps.ctx.projectId);+ h.dispatch({ anchor, layer: layerContract('created') as CanvasLayerContract, type: 'addCanvasLayer' });+ const created = getDocumentLayer(h.document(), 'created')!;+ const edit = h.edits.begin()!;+ edit.grow(128);+ edit.commit(strokeEvent({ createdLayer: { anchor, layer: created }, layerId: 'created' }));+ return created;+ };++ it('undoes by removing the layer and redoes by restoring it with its pixels', async () => {+ const h = createHarness();+ const created = createdStroke(h);++ await h.history.undo();+ expect(getDocumentLayer(h.document(), 'created')).toBeNull();++ await h.history.redo();+ expect(getDocumentLayer(h.document(), 'created')).toEqual(created);+ expect(h.deps.layerCache.peek('created')?.stale).toBe(false);+ expect(h.deps.applyImagePatch).toHaveBeenLastCalledWith('created', RECT, expect.anything());});- it('marks the re-created cache fresh so an async rasterize cannot clobber the restored stroke', () => {- const entry_ = { stale: true };- deps.layerCache = { getOrCreateRect: vi.fn(() => entry_) } as unknown as CreateStrokeCommitDeps['layerCache'];- createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));- const entry = deps.history.push.mock.calls[0]?.[0] as { redo(): void };- entry.redo();- expect(entry_.stale).toBe(false);+ it('takes the layer back out when a redo cannot restore its pixels, so the redo stays retryable', async () => {+ const h = createHarness();+ const created = createdStroke(h);+ await h.history.undo();+ h.deps.applyImagePatch.mockRejectedValueOnce(new Error('not ready'));++ expect((await h.history.redo()).status).toBe('failed');+ expect(getDocumentLayer(h.document(), 'created')).toBeNull();+ expect(h.history.canRedo()).toBe(true);+ expect((await h.history.redo()).status).toBe('applied');+ expect(getDocumentLayer(h.document(), 'created')).toEqual(created);});- it('sizes the entry from both pixel buffers plus overhead', () => {- createStrokeCommit(deps).commitOrdinaryStroke(- strokeEvent({ afterImageData: imageData(10), beforeImageData: imageData(6), createdLayer: created } as never)- );- expect(deps.history.push.mock.calls[0]?.[0]).toMatchObject({ bytes: 6 + 10 + 256 });+ it('accounts for both pixel buffers plus overhead', () => {+ const h = createHarness();+ createdStroke(h);+ expect(h.history.byteSize()).toBe(64 + 64 + HISTORY_ENTRY_OVERHEAD_BYTES);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.tsindex 1a6572a1a5..484a4dcf03 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts@@ -1,96 +1,138 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasMutationContext, EditRefusal } from '@workbench/canvas-engine/controllers/mutationContext';import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-import type { History, HistoryEntry } from '@workbench/canvas-engine/history/history';+import type { HistoryEntry } from '@workbench/canvas-engine/history/history';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';-import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';-import type { Rect } from '@workbench/canvas-engine/types';+import type { StrokeCommittedEvent, StrokeEdit } from '@workbench/canvas-engine/tools/tool';-import { collectHistoryMediaRefs } from '@workbench/canvas-engine/history/history';+import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';+import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';-export interface CreateStrokeCommitDeps {- readonly history: History;+export interface CreateStrokeEditsDeps {+ readonly ctx: Pick<CanvasMutationContext, 'applyStep' | 'begin'>;readonly layerCache: LayerCacheStore;readonly applyImagePatch: ImagePatchApply;- readonly dispatchCanvasMutation: (mutation: CanvasProjectMutation) => boolean;- readonly endNudgeBurst: () => void;readonly notifyLayerPainted: (layerId: string) => void;readonly markLayerDirty: (layerId: string) => void;readonly commitPaintEdit: () => void;readonly strokeListeners: ReadonlySet<(event: StrokeCommittedEvent) => void>;+ readonly reportRefusal: (status: EditRefusal) => void;}/** The history label for a committed pixel stroke. */export const strokeCommitLabel = (tool: StrokeCommittedEvent['tool']): string =>tool === 'eraser' ? 'Eraser stroke' : tool === 'shape' ? 'Draw shape' : 'Brush stroke';-export interface StrokeCommit {- /** Records one committed tool stroke: persistence, history, then subscriber fanout. */- commitOrdinaryStroke(event: StrokeCommittedEvent): void;+export interface StrokeEdits {+ /**+ * Admits a live pixel edit before its first pixel changes. Null when it is refused; the refusal is reported once,+ * here or when a later `grow` fails.+ */+ begin(initialBytes?: number): StrokeEdit | null;}/**- * Ordinary strokes record pixel patches; auto-created layers need composed history that also removes/recreates the- * layer.+ * Ordinary strokes paint their preview straight into the layer cache, so publication records the already-applied+ * pixels as one undo step. Auto-created layers compose layer removal/recreation into the same step.*/-export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit => {- const { applyImagePatch, dispatchCanvasMutation, history, layerCache } = deps;+export const createStrokeEdits = (deps: CreateStrokeEditsDeps): StrokeEdits => {+ const { applyImagePatch, ctx, layerCache } = deps;- const createComposedPaintEntry = (+ const composedEntry = (created: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor },- event: StrokeCommittedEvent,- label: string- ): HistoryEntry => {+ event: StrokeCommittedEvent+ ): Omit<HistoryEntry, 'label'> => {const { afterImageData, dirtyRect, layerId } = event;- const rect: Rect = { height: dirtyRect.height, width: dirtyRect.width, x: dirtyRect.x, y: dirtyRect.y };- const bytes = event.beforeImageData.data.byteLength + afterImageData.data.byteLength + 256;+ const rect = { ...dirtyRect };+ const removeCreated = (): void =>+ ctx.applyStep({+ accepted: (document) => isNodeAbsent(document, layerId),+ mutation: { ids: [layerId], type: 'removeCanvasLayers' },+ });return {- bytes,+ bytes: event.beforeImageData.data.byteLength + afterImageData.data.byteLength + HISTORY_ENTRY_OVERHEAD_BYTES,heldAssetRefs: collectHistoryMediaRefs(created.layer),- label,- redo: () => {- dispatchCanvasMutation({ anchor: created.anchor, layer: created.layer, type: 'addCanvasLayer' });- // Create a fresh empty cache to fence async rasterization before restoring stroke pixels and bounds.- const entry = layerCache.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });- entry.stale = false;- applyImagePatch(layerId, rect, afterImageData);- },- undo: () => {- dispatchCanvasMutation({ ids: [layerId], type: 'removeCanvasLayers' });+ redo: async () => {+ ctx.applyStep({+ accepted: (document) => getDocumentLayer(document, layerId) === created.layer,+ mutation: { anchor: created.anchor, layer: created.layer, type: 'addCanvasLayer' },+ // A fresh empty cache fences async rasterization before the stroke pixels land.+ install: () => {+ layerCache.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 }).stale = false;+ },+ });+ try {+ await applyImagePatch(layerId, rect, afterImageData);+ } catch (error) {+ // A redo that cannot restore the pixels takes the layer back out, so it stays retryable.+ removeCreated();+ throw error;+ }},+ undo: () => removeCreated(),};};return {- commitOrdinaryStroke: (event) => {- // A fresh stroke ends any open nudge-coalescing burst.- deps.endNudgeBurst();- deps.notifyLayerPainted(event.layerId);- // Persistence first: mark the layer dirty so a debounced upload fires even- // when no external subscriber is attached.- deps.markLayerDirty(event.layerId);- // Guard history recording during replay, which restores via image patches rather than fresh strokes.- if (!history.isApplying()) {- deps.commitPaintEdit();- const label = strokeCommitLabel(event.tool);- history.push(- event.createdLayer- ? createComposedPaintEntry(event.createdLayer, event, label)+ begin: (initialBytes = 0) => {+ // The stroke's own gesture starts the edit; it publishes on release, once that gesture has ended.+ const txn = ctx.begin({ gesture: true, historyBytes: initialBytes + HISTORY_ENTRY_OVERHEAD_BYTES });+ if (!('publish' in txn)) {+ deps.reportRefusal(txn.status);+ return null;+ }+ let refusalReported = false;+ return {+ cancel: () => txn.end(),+ commit: (event) => {+ const entry = event.createdLayer+ ? composedEntry(event.createdLayer, event): createImagePatchEntry({after: event.afterImageData,apply: applyImagePatch,before: event.beforeImageData,- label,+ label: strokeCommitLabel(event.tool),layerId: event.layerId,rect: event.dirtyRect,- })- );- }- for (const listener of deps.strokeListeners) {- listener(event);- }+ });+ try {+ const result = txn.publish(+ strokeCommitLabel(event.tool),+ {+ notify: () => {+ deps.notifyLayerPainted(event.layerId);+ deps.markLayerDirty(event.layerId);+ deps.commitPaintEdit();+ for (const listener of deps.strokeListeners) {+ listener(event);+ }+ },+ },+ entry,+ { origin: 'system' }+ );+ if (result.status !== 'committed' && !refusalReported) {+ refusalReported = true;+ deps.reportRefusal(result.status === 'over-budget' ? 'over-budget' : 'busy');+ }+ return result.status === 'committed';+ } finally {+ txn.end();+ }+ },+ grow: (bytes) => {+ if (txn.growHistory(bytes)) {+ return true;+ }+ if (!refusalReported) {+ refusalReported = true;+ deps.reportRefusal('over-budget');+ }+ return false;+ },+ };},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.tsindex 2658b80179..7029af36ee 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts@@ -77,7 +77,7 @@ const createHarness = (doc: CanvasDocumentContractV3): Harness => {createLayerId: () => 'x',createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),- emitStrokeCommitted: vi.fn(),+ beginStrokeEdit: () => null,getDocument: () => doc,invalidate: vi.fn(),layers: null as never,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 261c602d84..b8e10cdba3 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@@ -104,7 +104,10 @@ const createHarness = (doc: CanvasDocumentContractV3 | null): Harness => {createLayerId: () => 'unused',createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),- emitStrokeCommitted: (event) => strokes.push(event),+ beginStrokeEdit: () => {+ strokes.push('begin');+ return null;+ },getDocument: () => doc,invalidate: vi.fn(),layers,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.tsindex 914275ee92..34df0599c5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts@@ -80,7 +80,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {createLayerId: () => `grad-${++idCounter}`,createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),- emitStrokeCommitted: vi.fn(),+ beginStrokeEdit: () => null,getDocument: () => doc,invalidate: vi.fn(),layers: null as never,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex f674b98e9f..479a9e2fc8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -142,7 +142,7 @@ const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions =createLayerId: () => 'x',createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),- emitStrokeCommitted: vi.fn(),+ beginStrokeEdit: () => null,getDocument: () => doc,getSelectedLayerIds: () => options.selectedLayerIds ?? (doc.selectedLayerId ? [doc.selectedLayerId] : []),getFloatingSelection: () => float.current,@@ -564,6 +564,24 @@ describe('move tool: dragging a floating selection', () => {expect(h.overrides).toHaveLength(0);});+ it('cuts nothing for a click inside the ants, lifting only once the press becomes a drag', () => {+ const h = createHarness(doc(), { selectionContainsPoint: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(11, 10));+ up(tool, h.ctx, pointer(11, 10));+ expect(h.lifts).toEqual([]);++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(11, 10));+ expect(h.lifts).toEqual([]);+ move(tool, h.ctx, pointer(20, 10));+ expect(h.lifts).toEqual(['a']);+ up(tool, h.ctx, pointer(20, 10));+ expect(h.transforms.at(-1)).toMatchObject({ x: 10, y: 0 });+ });+it('moves the layer when the press lands outside the ants', () => {const h = createHarness(doc(), { selectionContainsPoint: false });const tool = createMoveTool();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.tsindex 80504deddc..f10c9bf13c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts@@ -1,7 +1,7 @@/*** Move targets panel selection, never stack hit tests. Dragging inside selection, or an existing float, moves- * pixels across multiple drags until commit/cancel; otherwise move eligible selected layers with a primary-layer- * fallback.+ * pixels across multiple drags until commit/cancel; the pixels are cut only once a press becomes a drag, so a click+ * leaves the layer whole. Otherwise move eligible selected layers with a primary-layer fallback.** Shift locks the dominant axis. Layer movement uses the visible model grid unless Alt bypasses; local-space* floats never snap. Preview only during drag; changed layer moves commit once, float history waits for its later@@ -35,12 +35,15 @@ export const constrainDelta = (dx: number, dy: number, shift: boolean): Vec2 =>return Math.abs(dx) >= Math.abs(dy) ? { x: dx, y: 0 } : { x: 0, y: dy };};-/** Which thing this gesture moves. */+type LayerDrag = {+ kind: 'layer';+ targets: readonly { id: string; origin: { x: number; y: number }; primary: boolean }[];+};++/** Which thing this gesture moves. `lift` cuts the selected pixels only once the press becomes a drag. */type DragMode =- | {- kind: 'layer';- targets: readonly { id: string; origin: { x: number; y: number }; primary: boolean }[];- }+ | LayerDrag+ | { kind: 'lift'; layerId: string; fallback: LayerDrag }| { kind: 'float'; layerId: string; origin: LayerTransform }| { kind: 'none' };@@ -107,13 +110,7 @@ export const createMoveTool = (): Tool => {if (!primary) {return { kind: 'none' };}- if (ctx.isPointInSelection?.(point) && ctx.liftFloatingSelection?.(primary.id)) {- const lifted = ctx.getFloatingSelection?.();- if (lifted) {- return { kind: 'float', layerId: lifted.layerId, origin: { ...lifted.transform } };- }- }- return {+ const layerDrag: LayerDrag = {kind: 'layer',targets: layers.map((layer) => ({id: layer.id,@@ -121,6 +118,20 @@ export const createMoveTool = (): Tool => {primary: layer === primary,})),};+ return ctx.isPointInSelection?.(point) && ctx.liftFloatingSelection+ ? { fallback: layerDrag, kind: 'lift', layerId: primary.id }+ : layerDrag;+ };++ /** A click must leave the layer whole, so the pixels are cut only when the drag starts. */+ const liftOnDrag = (ctx: ToolContext, mode: Extract<DragMode, { kind: 'lift' }>): DragMode => {+ if (ctx.liftFloatingSelection?.(mode.layerId)) {+ const lifted = ctx.getFloatingSelection?.();+ if (lifted) {+ return { kind: 'float', layerId: lifted.layerId, origin: { ...lifted.transform } };+ }+ }+ return mode.fallback;};/** The constrained document-space delta from the gesture start to `input`. */@@ -211,6 +222,9 @@ export const createMoveTool = (): Tool => {return;}state.moved = true;+ if (state.mode.kind === 'lift') {+ state.mode = liftOnDrag(ctx, state.mode);+ }}applyDelta(ctx, state, input);},@@ -225,7 +239,7 @@ export const createMoveTool = (): Tool => {// A click never re-targets the layer selection — that is the panel's job.return;}- if (current.mode.kind === 'none') {+ if (current.mode.kind === 'none' || current.mode.kind === 'lift') {// No movable layer is selected — nothing to commit.return;}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 e076f5be2f..d341d0784e 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@@ -84,8 +84,9 @@ const controlImageLayer = (id: string): CanvasControlLayerContract => ({const controlTransaction = (layerId = 'control'): PixelEditTransaction => ({cancel: vi.fn(),- commitPatch: vi.fn(),- commitStroke: vi.fn(),+ commit: vi.fn(() => true),+ commitPatch: vi.fn(() => true),+ grow: vi.fn(() => true),layerId,});@@ -126,17 +127,21 @@ interface Harness {painted: string[];requestLayerRasterization: ReturnType<typeof vi.fn>;createdIds: string[];+ /** Every admitted stroke edit, so a test can check each one ended. */+ strokeEdits: { cancel: ReturnType<typeof vi.fn> }[];}const createHarness = (doc: CanvasDocumentContractV3,- transaction: PixelEditTransaction | null | undefined = undefined+ transaction: PixelEditTransaction | null | undefined = undefined,+ refuseStrokes = false): Harness => {const backend = createTestStubRasterBackend();const layers = createLayerCacheStore(backend);const stores = createEngineStores();const dispatched: CanvasProjectMutation[] = [];const strokes: StrokeCommittedEvent[] = [];+ const strokeEdits: Harness['strokeEdits'] = [];const painted: string[] = [];const createdIds: string[] = [];const beginPixelEdit = transaction === undefined ? null : vi.fn(() => transaction);@@ -162,9 +167,21 @@ const createHarness = (return path as unknown as Path2D;},dispatch: (action) => dispatched.push(action),- emitStrokeCommitted: (event) => {- painted.push(event.layerId);- strokes.push(event);+ beginStrokeEdit: () => {+ if (refuseStrokes) {+ return null;+ }+ const edit = {+ cancel: vi.fn(),+ commit: (event: StrokeCommittedEvent) => {+ painted.push(event.layerId);+ strokes.push(event);+ return true;+ },+ grow: () => true,+ };+ strokeEdits.push(edit);+ return edit;},getDocument: () => doc,invalidate: vi.fn(),@@ -178,7 +195,18 @@ const createHarness = (viewport: null as never,};- return { backend, beginPixelEdit, createdIds, ctx, dispatched, layers, painted, requestLayerRasterization, strokes };+ return {+ backend,+ beginPixelEdit,+ createdIds,+ ctx,+ dispatched,+ layers,+ painted,+ requestLayerRasterization,+ strokeEdits,+ strokes,+ };};const cacheOps = (surface: StubRasterSurface): string[] => surface.callLog.map((entry) => entry.op);@@ -287,7 +315,7 @@ describe('eraser tool', () => {up(eraser, h.ctx, pointer(6, 6));expect(h.beginPixelEdit).toHaveBeenCalledWith('img1');- expect(transaction.commitStroke).toHaveBeenCalledOnce();+ expect(transaction.commit).toHaveBeenCalledOnce();expect(h.dispatched).toHaveLength(0);expect(h.createdIds).toHaveLength(0);});@@ -297,6 +325,7 @@ describe('brush tool: cancel', () => {it('restores pixels via putImageData and emits no event', () => {const doc = makeDoc([paintLayer('paint1')], 'paint1');const h = createHarness(doc);+ h.layers.getOrCreateRect('paint1', { height: 100, width: 100, x: 0, y: 0 }).stale = false;const brush = createBrushTool();down(brush, h.ctx, pointer(20, 20));@@ -307,6 +336,30 @@ describe('brush tool: cancel', () => {expect(h.painted).toHaveLength(0);expect(cacheOps(cacheSurface(h, 'paint1'))).toContain('putImageData');});++ it('removes a cache the cancelled stroke created', () => {+ const h = createHarness(makeDoc([paintLayer('paint1')], 'paint1'));+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(20, 20));+ move(brush, h.ctx, pointer(40, 40), [pointer(40, 40)]);+ cancel(brush, h.ctx);++ expect(h.layers.peek('paint1')).toBeUndefined();+ });++ it('paints nothing and creates no layer when the stroke is refused admission', () => {+ const h = createHarness(makeDoc([], null), undefined, true);+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(20, 20));+ move(brush, h.ctx, pointer(40, 40), [pointer(40, 40)]);+ up(brush, h.ctx, pointer(40, 40, { buttons: 0 }));++ expect(h.dispatched).toEqual([]);+ expect(h.createdIds).toEqual([]);+ expect(h.strokes).toEqual([]);+ });});describe('paint tool: target resolution', () => {@@ -320,7 +373,7 @@ describe('paint tool: target resolution', () => {up(brush, h.ctx, pointer(20, 20, { buttons: 0 }));expect(h.beginPixelEdit).toHaveBeenCalledWith('control');- expect(transaction.commitStroke).toHaveBeenCalledOnce();+ expect(transaction.commit).toHaveBeenCalledOnce();expect(transaction.cancel).not.toHaveBeenCalled();expect(h.dispatched).toHaveLength(0);});@@ -336,7 +389,7 @@ describe('paint tool: target resolution', () => {brush.onDeactivate?.(h.ctx);}expect(transaction.cancel).toHaveBeenCalledOnce();- expect(transaction.commitStroke).not.toHaveBeenCalled();+ expect(transaction.commit).not.toHaveBeenCalled();});it('aborts the control transaction and releases the gesture after pointer-move painting fails', () => {@@ -351,7 +404,7 @@ describe('paint tool: target resolution', () => {expect(() => move(brush, h.ctx, pointer(20, 20), [pointer(20, 20)])).toThrow('move paint failed');expect(transaction.cancel).toHaveBeenCalledOnce();- expect(transaction.commitStroke).not.toHaveBeenCalled();+ expect(transaction.commit).not.toHaveBeenCalled();expect(h.dispatched).toHaveLength(0);expect(h.painted).toHaveLength(0);expect(h.strokes).toHaveLength(0);@@ -380,7 +433,7 @@ describe('paint tool: target resolution', () => {expect(transaction.cancel).toHaveBeenCalledOnce();up(brush, h.ctx, pointer(30, 30));- expect(transaction.commitStroke).not.toHaveBeenCalled();+ expect(transaction.commit).not.toHaveBeenCalled();expect(h.strokes).toHaveLength(0);});@@ -396,7 +449,7 @@ describe('paint tool: target resolution', () => {expect(() => up(brush, h.ctx, pointer(10, 10, { buttons: 0 }))).toThrow('stroke finalization failed');expect(transaction.cancel).toHaveBeenCalledOnce();- expect(transaction.commitStroke).not.toHaveBeenCalled();+ expect(transaction.commit).not.toHaveBeenCalled();expect(h.dispatched).toHaveLength(0);expect(h.painted).toHaveLength(0);expect(h.strokes).toHaveLength(0);@@ -418,7 +471,7 @@ describe('paint tool: target resolution', () => {expect(() => cancel(brush, h.ctx)).toThrow('pixel restoration failed');expect(transaction.cancel).toHaveBeenCalledOnce();- expect(transaction.commitStroke).not.toHaveBeenCalled();+ expect(transaction.commit).not.toHaveBeenCalled();expect(h.dispatched).toHaveLength(0);expect(h.painted).toHaveLength(0);expect(h.strokes).toHaveLength(0);@@ -428,19 +481,19 @@ describe('paint tool: target resolution', () => {expect(h.beginPixelEdit).toHaveBeenCalledTimes(2);});- it('does not roll back an accepted stroke when transaction publication throws', () => {+ it('abandons the stroke when its edit fails to publish, leaving the tool ready', () => {const transaction = controlTransaction();- vi.mocked(transaction.commitStroke).mockImplementation(() => {- throw new Error('listener publication failed');+ vi.mocked(transaction.commit).mockImplementation(() => {+ throw new Error('publication failed');});const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);const brush = createBrushTool();down(brush, h.ctx, pointer(10, 10));- expect(() => up(brush, h.ctx, pointer(10, 10, { buttons: 0 }))).toThrow('listener publication failed');+ expect(() => up(brush, h.ctx, pointer(10, 10, { buttons: 0 }))).toThrow('publication failed');- expect(transaction.commitStroke).toHaveBeenCalledOnce();- expect(transaction.cancel).not.toHaveBeenCalled();+ expect(transaction.commit).toHaveBeenCalledOnce();+ expect(transaction.cancel).toHaveBeenCalledOnce();down(brush, h.ctx, pointer(30, 30));expect(h.beginPixelEdit).toHaveBeenCalledTimes(2);});@@ -531,6 +584,30 @@ describe('transparency lock', () => {expect(h.strokes).toHaveLength(0);expect(h.painted).toEqual([]);+ expect(h.strokeEdits.map((edit) => edit.cancel.mock.calls.length)).toEqual([1]);+ });++ it('ends the admitted edit and removes the layer it created when the stroke is cancelled', () => {+ const h = createHarness(makeDoc([], null));+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(20, 20));+ cancel(brush, h.ctx);++ expect(h.strokeEdits.map((edit) => edit.cancel.mock.calls.length)).toEqual([1]);+ expect(h.dispatched).toContainEqual({ ids: [h.createdIds[0]], type: 'removeCanvasLayers' });+ });++ it('ends the admitted edit when a zero-scale layer leaves nothing to paint into', () => {+ const flat = { ...paintLayer('paint1'), transform: { rotation: 0, scaleX: 0, scaleY: 1, x: 0, y: 0 } };+ const h = createHarness(makeDoc([flat], 'paint1'));+ const brush = createBrushTool();++ down(brush, h.ctx, pointer(20, 20));+ up(brush, h.ctx, pointer(20, 20));++ expect(h.strokes).toHaveLength(0);+ expect(h.strokeEdits.map((edit) => edit.cancel.mock.calls.length)).toEqual([1]);});it('brush is unaffected (source-over) when transparency is NOT locked', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex 5ea4762319..0443ece65b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -14,7 +14,7 @@ import { isLeafPaintable, isLayerTransparencyLocked } from '@workbench/canvas-enimport { isMaskLayer } from '@workbench/canvas-engine/document/sources';import { fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';-import type { StrokeCommittedEvent, Tool, ToolContext } from './tool';+import type { StrokeEdit, Tool, ToolContext } from './tool';import { createStrokeSession, type StrokeSession } from './strokeSession';@@ -45,7 +45,9 @@ const MASK_STROKE_COLOR = '#ffffff';/** The resolved paint target for a gesture. `createdLayer` is set only when auto-created. */interface PaintTarget {layerId: string;- commit(event: StrokeCommittedEvent): void;+ /** The admitted edit that records the finished stroke. */+ edit: StrokeEdit;+ /** Ends the gesture unrecorded, removing a layer it auto-created. */cancel(): void;/** When the gesture auto-created its layer, the created contract + its anchor (for history). */createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor };@@ -66,6 +68,17 @@ interface PaintTarget {transform?: CanvasLayerContract['transform'];}+const editTarget = (+ edit: StrokeEdit,+ layerId: string,+ extra: Omit<PaintTarget, 'cancel' | 'edit' | 'layerId'> = {}+) => ({+ cancel: () => edit.cancel(),+ edit,+ layerId,+ ...extra,+});+/** Resolves (or auto-creates) the paint target for a gesture, or `null` to no-op. */const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget | null => {const doc = ctx.getDocument();@@ -91,14 +104,14 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetreturn null;}}+ const edit = ctx.beginStrokeEdit();// The cache (if any) keeps its current content extent; the stroke grows it.- return {- cancel: () => undefined,- commit: (event) => ctx.emitStrokeCommitted(event),- layerId: selected.id,- transform: selected.transform,- transparencyLocked: selected.isTransparencyLocked === true,- };+ return edit+ ? editTarget(edit, selected.id, {+ transform: selected.transform,+ transparencyLocked: selected.isTransparencyLocked === true,+ })+ : null;}if (leaf && selected?.type === 'raster' && selected.source.type === 'image' && tool === 'eraser') {@@ -108,17 +121,10 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetreturn null;}const transaction = ctx.beginPixelEdit?.(selected.id) ?? null;- if (!transaction) {- return null;- }- return {- cancel: transaction.cancel,- commit: transaction.commitStroke,- layerId: transaction.layerId,- // 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.- };+ // 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;}if (leaf && selected && isMaskLayer(selected)) {@@ -134,29 +140,23 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetreturn null;}}- return {- cancel: () => undefined,- color: MASK_STROKE_COLOR,- commit: (event) => ctx.emitStrokeCommitted(event),- forceOpaque: true,- layerId: selected.id,- transform: selected.transform,- };+ const edit = ctx.beginStrokeEdit();+ return edit+ ? editTarget(edit, selected.id, { color: MASK_STROKE_COLOR, forceOpaque: true, transform: selected.transform })+ : null;}if (selected?.type === 'control') {const transaction = ctx.beginPixelEdit?.(selected.id) ?? null;- if (!transaction) {- return null;- }- return {- cancel: transaction.cancel,- commit: transaction.commitStroke,- layerId: transaction.layerId,- // No transform on purpose: see the materialized-eraser branch above.- };+ // No transform on purpose: see the materialized-eraser branch above.+ return transaction ? editTarget(transaction, transaction.layerId) : null;}+ // Admit the stroke before the layer exists, so a refusal leaves the document untouched.+ const edit = ctx.beginStrokeEdit();+ if (!edit) {+ return null;+ }// Other eligible selections create a selected paint layer at the top via the sole gesture-start dispatch.const layerId = ctx.createLayerId();const previousSelectedLayerId = doc.selectedLayerId;@@ -179,16 +179,17 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetentry.stale = false;return {// Gesture-start creation is outside history until a stroke commits. Roll it back for fully clipped strokes,- // cancellation or mid-drag switching.+ // refusals, cancellation or mid-drag switching.cancel: () => {+ edit.cancel();ctx.layers.delete(layerId);ctx.dispatch({ ids: [layerId], type: 'removeCanvasLayers' });// The reducer's nearest-neighbour fallback would otherwise select whatever sits// at the top, not what the user had selected when the gesture began.ctx.dispatch({ id: previousSelectedLayerId, type: 'setCanvasSelectedLayer' });},- commit: (event) => ctx.emitStrokeCommitted(event),createdLayer: { anchor, layer },+ edit,layerId,};};@@ -251,7 +252,9 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {if (!resolvedTarget) {return;}+ // Every refusal below ends the admitted edit (and removes a layer the gesture created).if (resolvedTarget.transparencyLocked && spec.id === 'eraser') {+ resolvedTarget.cancel();return;}const composite = resolvedTarget.transparencyLocked && spec.id === 'brush' ? 'source-atop' : spec.composite;@@ -265,6 +268,7 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {: null;if (layerTransform && !invert(layerTransform)) {// A zero-scale layer has no paintable geometry to invert into.+ resolvedTarget.cancel();return;}target = resolvedTarget;@@ -282,8 +286,11 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {ctx,layerId: target.layerId,layerTransform,+ edit: target.edit,// A deferred frame render fails outside this handler; abandon the stroke there too.onRenderError: () => abortSession(),+ // The session restored the layer; the target still removes a layer it created.+ onRefused: () => abortSession(),opacity: target.forceOpaque ? 1 : spec.opacity(ctx),// A mask stroke is an all-or-nothing alpha stencil, so pressure must not thin it —// a partially-transparent mask would silently attenuate the denoise strength.@@ -313,17 +320,15 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {if (session && target) {const activeSession = session;const activeTarget = target;- let event: StrokeCommittedEvent | null;+ let published: boolean;try {- event = activeSession.commit();+ published = activeSession.commit((event) => activeTarget.edit.commit(event));} catch (error) {abortSession();throw error;}endSession();- if (event) {- activeTarget.commit(event);- } else {+ if (!published) {activeTarget.cancel();}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex a45b2971e1..07de9b4682 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -9,6 +9,7 @@ import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/documimport { createEngineStores } from '@workbench/canvas-engine/engineStores';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend, type StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';+import { createRecordingStrokeEdit } from '@workbench/canvas-engine/tools/strokeEdit.testStub';import { describe, expect, it, vi } from 'vitest';import { createShapeTool, polygonShapeFrom, rectFromDrag } from './shapeTool';@@ -63,6 +64,8 @@ interface StructuralCommit {}const createHarness = (doc: CanvasDocumentContractV3) => {+ const strokeEdit = createRecordingStrokeEdit();+ const admission = { refuse: false };const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];const stores = createEngineStores();@@ -80,7 +83,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {createLayerId: () => `shape-${++idCounter}`,createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),- emitStrokeCommitted: vi.fn(),+ beginStrokeEdit: () => (admission.refuse ? null : strokeEdit.edit),getDocument: () => doc,invalidate: vi.fn(),layers,@@ -91,7 +94,16 @@ const createHarness = (doc: CanvasDocumentContractV3) => {updateCursor: vi.fn(),viewport: identityViewport,};- return { commits, ctx, dispatched, layers, previewOf: () => stores.shapePreview.get(), stores };+ return {+ commits,+ ctx,+ dispatched,+ layers,+ previewOf: () => stores.shapePreview.get(),+ admission,+ stores,+ strokeEdit,+ };};const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);@@ -391,8 +403,8 @@ describe('shape tool: placement', () => {up(tool, h.ctx, pointer(170, 100));expect(h.commits).toHaveLength(0);- expect(h.ctx.emitStrokeCommitted).toHaveBeenCalledOnce();- const event = vi.mocked(h.ctx.emitStrokeCommitted).mock.calls[0]![0];+ expect(h.strokeEdit.record.commits).toHaveLength(1);+ const event = h.strokeEdit.record.commits[0]!;// Layer-local: the document rect minus the layer's offset.expect(event.dirtyRect).toEqual({ height: 40, width: 60, x: 10, y: 10 });expect(event.tool).toBe('shape');@@ -402,6 +414,40 @@ describe('shape tool: placement', () => {expect(surface.callLog.some((entry) => entry.op === 'drawImage')).toBe(true);});+ it('leaves the paint layer untouched when the shape is refused admission', () => {+ const layer = paintLayer({ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 100, y: 50 } });+ const h = createHarness(makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'paint-1' }));+ h.admission.refuse = true;+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(110, 60));+ move(tool, h.ctx, pointer(170, 100));+ up(tool, h.ctx, pointer(170, 100));++ expect(h.strokeEdit.record.commits).toHaveLength(0);+ expect(h.commits).toHaveLength(0);+ expect(h.layers.peek('paint-1')).toBeUndefined();+ });++ it('restores the pixels and cache extent when the shape cannot be recorded', () => {+ const layer = paintLayer({ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 100, y: 50 } });+ const h = createHarness(makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'paint-1' }));+ h.layers.getOrCreateRect('paint-1', { height: 4, width: 4, x: 0, y: 0 }).stale = false;+ const cancel = vi.spyOn(h.strokeEdit.edit, 'cancel');+ h.strokeEdit.edit.commit = () => false;+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(110, 60));+ move(tool, h.ctx, pointer(170, 100));+ up(tool, h.ctx, pointer(170, 100));++ expect(h.layers.peek('paint-1')?.rect).toEqual({ height: 4, width: 4, x: 0, y: 0 });+ const writes = (h.layers.peek('paint-1')!.surface as StubRasterSurface).callLog.map((entry) => entry.op);+ expect(writes.lastIndexOf('putImageData')).toBeGreaterThan(writes.lastIndexOf('drawImage'));+ expect(cancel).toHaveBeenCalledOnce();+ expect(h.commits).toHaveLength(0);+ });+it('maps the shape through a scaled layer and clamps the cache growth to the selection', () => {const layer = paintLayer({ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 100, y: 50 } });const h = createHarness(makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'paint-1' }));@@ -413,7 +459,7 @@ describe('shape tool: placement', () => {move(tool, h.ctx, pointer(170, 100));up(tool, h.ctx, pointer(170, 100));- const event = vi.mocked(h.ctx.emitStrokeCommitted).mock.calls[0]![0];+ const event = h.strokeEdit.record.commits[0]!;// Document 110..140 × 60..90 (the selection's extent) → local (5..20, 5..20) at half scale.expect(event.dirtyRect).toEqual({ height: 15, width: 15, x: 5, y: 5 });expect(h.layers.get('paint-1')?.rect).toEqual(event.dirtyRect);@@ -429,7 +475,7 @@ describe('shape tool: placement', () => {down(tool, h.ctx, pointer(4, 4));move(tool, h.ctx, pointer(60, 60));up(tool, h.ctx, pointer(60, 60));- expect(vi.mocked(h.ctx.emitStrokeCommitted).mock.calls[0]![0].dirtyRect).toEqual({+ expect(h.strokeEdit.record.commits[0]!.dirtyRect).toEqual({height: 4,width: 4,x: 4,@@ -440,7 +486,7 @@ describe('shape tool: placement', () => {move(tool, h.ctx, pointer(60, 60));up(tool, h.ctx, pointer(60, 60));// Nothing to draw: no stroke event, no history, no new layer.- expect(h.ctx.emitStrokeCommitted).toHaveBeenCalledOnce();+ expect(h.strokeEdit.record.commits).toHaveLength(1);expect(h.commits).toHaveLength(0);expect(h.layers.get('paint-1')?.rect).toEqual({ height: 4, width: 4, x: 4, y: 4 });});@@ -455,7 +501,7 @@ describe('shape tool: placement', () => {move(tool, h.ctx, pointer(70, 50));up(tool, h.ctx, pointer(70, 50));- expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits).toHaveLength(0);});@@ -470,7 +516,7 @@ describe('shape tool: placement', () => {up(tool, h.ctx, pointer(70, 50));expect(h.ctx.requestLayerRasterization).toHaveBeenCalledWith('paint-1');- expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits).toHaveLength(0);});@@ -486,7 +532,7 @@ describe('shape tool: placement', () => {move(tool, h.ctx, pointer(70, 50));up(tool, h.ctx, pointer(70, 50));- expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits[0]?.forward.type).toBe('addCanvasLayer');});@@ -499,7 +545,7 @@ describe('shape tool: placement', () => {move(tool, h.ctx, pointer(70, 50));up(tool, h.ctx, pointer(70, 50));- expect(h.ctx.emitStrokeCommitted).not.toHaveBeenCalled();+ expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits[0]?.forward.type).toBe('addCanvasLayer');});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.tsindex a99d8c7fc6..42b92b4193 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts@@ -171,40 +171,72 @@ export const createShapeTool = (): Tool => {if (!dirtyRect || dirtyRect.width < 1 || dirtyRect.height < 1) {return 'refused';}- const entry = ctx.layers.growToRect(layer.id, dirtyRect);- const surfaceCtx = entry.surface.ctx;- const sx = dirtyRect.x - entry.rect.x;- const sy = dirtyRect.y - entry.rect.y;- const beforeImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);-- // Draw into dirty-rect-local scratch so clipping and transparency lock apply in one composite; map through- // layer inverse then scratch offset.- const scratch = ctx.backend.createSurface(dirtyRect.width, dirtyRect.height);- const draw = scratch.ctx;- const { rect, source } = placed;- const toScratch = multiply(translate(identity(), { x: -dirtyRect.x, y: -dirtyRect.y }), toLocal);- draw.setTransform(toScratch.a, toScratch.b, toScratch.c, toScratch.d, toScratch.e, toScratch.f);- drawShapeSource(draw, source, rect.x, rect.y, rect.width, rect.height);- draw.globalCompositeOperation = 'destination-in';- if (clipMask) {- // The mask sits in document space, so it goes through the same mapping.- draw.drawImage(clipMask.surface.canvas, clipMask.rect.x, clipMask.rect.y);+ // Admitted before the first pixel changes: the before/after pair is the step's footprint.+ const edit = ctx.beginStrokeEdit(dirtyRect.width * dirtyRect.height * 8);+ if (!edit) {+ return 'refused';}- if (clipRect && (toLocal.b !== 0 || toLocal.c !== 0)) {- // The dirty-rect clamp only bounds the AABB on a rotated/sheared layer;- // keep exactly the pixels inside the document-space rect.- draw.fillStyle = '#000';- draw.beginPath();- draw.rect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);- draw.fill();+ const original = ctx.layers.peek(layer.id);+ const originalRect = original ? { ...original.rect } : null;+ let beforeImageData: ImageData | null = null;+ let sx = 0;+ let sy = 0;+ /** Puts the pre-shape pixels and cache extent back and ends the edit unrecorded. */+ const restore = (): void => {+ const entry = ctx.layers.peek(layer.id);+ if (entry && beforeImageData) {+ entry.surface.ctx.putImageData(beforeImageData, sx, sy);+ }+ if (originalRect) {+ ctx.layers.shrinkToRect(layer.id, originalRect);+ } else {+ ctx.layers.delete(layer.id);+ }+ ctx.notifyLayerPainted(layer.id);+ edit.cancel();+ };+ try {+ const entry = ctx.layers.growToRect(layer.id, dirtyRect);+ const surfaceCtx = entry.surface.ctx;+ sx = dirtyRect.x - entry.rect.x;+ sy = dirtyRect.y - entry.rect.y;+ beforeImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);++ // Draw into dirty-rect-local scratch so clipping and transparency lock apply in one composite; map through+ // layer inverse then scratch offset.+ const scratch = ctx.backend.createSurface(dirtyRect.width, dirtyRect.height);+ const draw = scratch.ctx;+ const { rect, source } = placed;+ const toScratch = multiply(translate(identity(), { x: -dirtyRect.x, y: -dirtyRect.y }), toLocal);+ draw.setTransform(toScratch.a, toScratch.b, toScratch.c, toScratch.d, toScratch.e, toScratch.f);+ drawShapeSource(draw, source, rect.x, rect.y, rect.width, rect.height);+ draw.globalCompositeOperation = 'destination-in';+ if (clipMask) {+ // The mask sits in document space, so it goes through the same mapping.+ draw.drawImage(clipMask.surface.canvas, clipMask.rect.x, clipMask.rect.y);+ }+ if (clipRect && (toLocal.b !== 0 || toLocal.c !== 0)) {+ // The dirty-rect clamp only bounds the AABB on a rotated/sheared layer;+ // keep exactly the pixels inside the document-space rect.+ draw.fillStyle = '#000';+ draw.beginPath();+ draw.rect(clipRect.x, clipRect.y, clipRect.width, clipRect.height);+ draw.fill();+ }+ surfaceCtx.save();+ surfaceCtx.setTransform(1, 0, 0, 1, 0, 0);+ surfaceCtx.globalCompositeOperation = layer.isTransparencyLocked ? 'source-atop' : 'source-over';+ surfaceCtx.drawImage(scratch.canvas, sx, sy);+ surfaceCtx.restore();+ const afterImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);+ if (!edit.commit({ afterImageData, beforeImageData, dirtyRect, layerId: layer.id, tool: 'shape' })) {+ restore();+ return 'refused';+ }+ } catch (error) {+ restore();+ throw error;}- surfaceCtx.save();- surfaceCtx.setTransform(1, 0, 0, 1, 0, 0);- surfaceCtx.globalCompositeOperation = layer.isTransparencyLocked ? 'source-atop' : 'source-over';- surfaceCtx.drawImage(scratch.canvas, sx, sy);- surfaceCtx.restore();- const afterImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);- ctx.emitStrokeCommitted({ afterImageData, beforeImageData, dirtyRect, layerId: layer.id, tool: 'shape' });return 'placed';};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeEdit.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeEdit.testStub.tsnew file mode 100644index 0000000000..cf10e4d9cf--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeEdit.testStub.ts@@ -0,0 +1,37 @@+import type { StrokeSession } from './strokeSession';+import type { StrokeCommittedEvent, StrokeEdit } from './tool';++/** An admission that always grows. */+export const ADMIT_ALL: Pick<StrokeEdit, 'grow'> = { grow: () => true };++/** Commits `session`, accepting its event, and returns the event (null when nothing was published). */+export const commitStroke = (session: StrokeSession): StrokeCommittedEvent | null => {+ let committed: StrokeCommittedEvent | null = null;+ session.commit((event) => {+ committed = event;+ return true;+ });+ return committed;+};++/** A stroke edit that records what it admits and publishes; `admitBytes` caps growth to simulate refusal. */+export const createRecordingStrokeEdit = (admitBytes = Infinity) => {+ const record = { admitted: 0, cancelled: 0, commits: [] as StrokeCommittedEvent[] };+ const edit: StrokeEdit = {+ cancel: () => {+ record.cancelled += 1;+ },+ commit: (event) => {+ record.commits.push(event);+ return true;+ },+ grow: (bytes) => {+ if (record.admitted + bytes > admitBytes) {+ return false;+ }+ record.admitted += bytes;+ return true;+ },+ };+ return { edit, record };+};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 cd8441bac8..f7fd69bbe7 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@@ -3,6 +3,7 @@ import type { PointerInput, Rect } from '@workbench/canvas-engine/types';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { ADMIT_ALL, commitStroke } from '@workbench/canvas-engine/tools/strokeEdit.testStub';import { createStrokeSession } from '@workbench/canvas-engine/tools/strokeSession';import { describe, expect, it, vi } from 'vitest';@@ -44,7 +45,6 @@ const paint = (const ctx = {backend,createPath2D: (d?: string) => new Path2D(d),- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),@@ -59,6 +59,7 @@ const paint = (},} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask,color: '#3b82f6',composite: 'source-over',@@ -78,7 +79,7 @@ const paint = (frames.splice(0).forEach((task) => task());}}- const event = session.commit()!;+ const event = commitStroke(session)!;return { pixels: event.afterImageData.data, rect: event.dirtyRect };};@@ -100,7 +101,6 @@ const tapCoverage = (const ctx = {backend,createPath2D: (d?: string) => new Path2D(d),- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),@@ -110,6 +110,7 @@ const tapCoverage = (},} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,color: '#3b82f6',composite,ctx,@@ -122,7 +123,7 @@ const tapCoverage = (tool: composite === 'source-over' ? 'brush' : 'eraser',});session.addPoints([pointer(16.5, 16.5, options.pressure)]);- const event = session.commit()!;+ const event = commitStroke(session)!;let max = 0;let sum = 0;for (let index = 3; index < event.afterImageData.data.length; index += 4) {@@ -288,7 +289,6 @@ describe('dense stylus trace', () => {const ctx = {backend,createPath2D: (d?: string) => new Path2D(d),- emitStrokeCommitted: vi.fn(),invalidate,layers,notifyLayerPainted: vi.fn(),@@ -298,6 +298,7 @@ describe('dense stylus trace', () => {},} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask: null,color: '#3b82f6',composite: 'source-over',@@ -317,7 +318,7 @@ describe('dense stylus trace', () => {frames.splice(0).forEach((task) => task());}}- session.commit();+ commitStroke(session);return { ms: Math.round((performance.now() - start) * 10) / 10, renders: invalidate.mock.calls.length };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.tsindex 4ef0524cca..392c0f69c4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts@@ -1,12 +1,13 @@import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';import type { StubRasterBackend, StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';-import type { ToolContext } from '@workbench/canvas-engine/tools/tool';+import type { StrokeEdit, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput } from '@workbench/canvas-engine/types';import * as freehand from '@workbench/canvas-engine/freehand';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { ADMIT_ALL, commitStroke, createRecordingStrokeEdit } from '@workbench/canvas-engine/tools/strokeEdit.testStub';import { createStrokeSession } from '@workbench/canvas-engine/tools/strokeSession';import { describe, expect, it, vi } from 'vitest';@@ -49,7 +50,6 @@ const runStroke = (opts: { withMask: boolean }) => {const entry: LayerCacheEntry = layers.getOrCreate('L', 100, 100);const mask = opts.withMask ? backend.createSurface(100, 100) : null;const clipMask = mask ? { rect: { height: 100, width: 100, x: 0, y: 0 }, surface: mask } : null;- const emitStrokeCommitted = vi.fn();const notifyLayerPainted = vi.fn();const ctx = {@@ -58,7 +58,6 @@ const runStroke = (opts: { withMask: boolean }) => {const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted,invalidate: vi.fn(),layers,notifyLayerPainted,@@ -68,6 +67,7 @@ const runStroke = (opts: { withMask: boolean }) => {// Only the scratch is created after this point.created.length = 0;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask,color: '#ff0000',hardness: 1,@@ -82,10 +82,10 @@ const runStroke = (opts: { withMask: boolean }) => {});session.addPoints([pointer(10, 10)]);session.addPoints([pointer(40, 10), pointer(40, 40)]);- const event = session.commit();+ const event = commitStroke(session);const scratch = created[0]!;- return { cache: entry.surface as StubRasterSurface, emitStrokeCommitted, event, notifyLayerPainted, scratch };+ return { cache: entry.surface as StubRasterSurface, event, notifyLayerPainted, scratch };};const compositeOps = (surface: StubRasterSurface): unknown[] =>@@ -134,7 +134,6 @@ describe('strokeSession: bbox-clipped painting', () => {const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),@@ -143,6 +142,7 @@ describe('strokeSession: bbox-clipped painting', () => {created.length = 0;const session = createStrokeSession({+ edit: ADMIT_ALL,clipRect,color: '#ff0000',hardness: 1,@@ -157,7 +157,7 @@ describe('strokeSession: bbox-clipped painting', () => {});session.addPoints([pointer(10, 10)]);session.addPoints([pointer(40, 10), pointer(40, 40)]);- const event = session.commit();+ const event = commitStroke(session);return { cache: entry.surface as StubRasterSurface, event, scratch: created[0] as StubRasterSurface | undefined };};@@ -205,12 +205,14 @@ describe('strokeSession: bbox-clipped painting', () => {});describe('strokeSession: content-sized cache growth', () => {- const makeSession = (initialRect: { x: number; y: number; width: number; height: number }) => {+ const makeSession = (+ initialRect: { x: number; y: number; width: number; height: number },+ edit: Pick<StrokeEdit, 'grow'> = ADMIT_ALL+ ) => {const { backend } = createCapturingBackend();const layers = createLayerCacheStore(backend);const entry = layers.getOrCreateRect('L', initialRect);entry.stale = false;- const emitStrokeCommitted = vi.fn();const notifyLayerPainted = vi.fn();const ctx = {backend,@@ -218,32 +220,34 @@ describe('strokeSession: content-sized cache growth', () => {const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted,invalidate: vi.fn(),layers,notifyLayerPainted,scheduleFrame: runFrameNow,} as unknown as ToolContext;+ const onRefused = vi.fn();const session = createStrokeSession({+ edit,clipMask: null,color: '#ff0000',hardness: 1,composite: 'source-over',ctx,layerId: 'L',+ onRefused,opacity: 1,size: 20,pressureOpacity: false,thinning: 0,tool: 'brush',});- return { emitStrokeCommitted, entry, notifyLayerPainted, session };+ return { entry, layers, notifyLayerPainted, onRefused, session };};it('grows an EMPTY (brand-new) paint cache to the stroke bounds on the first stroke', () => {const { entry, session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });session.addPoints([pointer(50, 60)]);- const event = session.commit();+ const event = commitStroke(session);// A dab near (50,60) grows to a small outward chunk-aligned rect, not a document-sized surface.expect(entry.rect.width).toBeGreaterThan(0);@@ -268,26 +272,100 @@ describe('strokeSession: content-sized cache growth', () => {});it('returns the completed event without publishing engine side effects', () => {- const { emitStrokeCommitted, notifyLayerPainted, session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });+ const { notifyLayerPainted, session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });session.addPoints([pointer(10, 10)]);- const event = session.commit();+ const event = commitStroke(session);expect(event).toMatchObject({ layerId: 'L', tool: 'brush' });expect(event!.dirtyRect.width).toBeGreaterThan(0);expect(event!.dirtyRect.height).toBeGreaterThan(0);- expect(emitStrokeCommitted).not.toHaveBeenCalled();expect(notifyLayerPainted).not.toHaveBeenCalled();});+ it('restores the layer and its extent once when the undo footprint cannot grow', () => {+ const first = makeSession({ height: 20, width: 20, x: 0, y: 0 }, createRecordingStrokeEdit().edit);+ first.session.addPoints([pointer(10, 10)]);+ const firstFootprint = first.entry.rect.width * first.entry.rect.height * 8;++ const { edit } = createRecordingStrokeEdit(firstFootprint);+ const { layers, onRefused, session } = makeSession({ height: 20, width: 20, x: 0, y: 0 }, edit);+ session.addPoints([pointer(10, 10)]);+ session.addPoints([pointer(400, 400)]);+ session.addPoints([pointer(410, 410)]);++ expect(onRefused).toHaveBeenCalledOnce();+ expect(layers.peek('L')!.rect).toEqual({ height: 20, width: 20, x: 0, y: 0 });+ expect(session.commit(() => true)).toBe(false);+ });++ it('restores the layer when the final paint at commit cannot grow', () => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreateRect('L', { height: 20, width: 20, x: 0, y: 0 }).stale = false;+ const deferred: (() => void)[] = [];+ const ctx = {+ backend,+ createPath2D: () =>+ ({ closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} }) as unknown as Path2D,+ invalidate: vi.fn(),+ layers,+ notifyLayerPainted: vi.fn(),+ scheduleFrame: (task: () => void) => {+ deferred.push(task);+ return () => undefined;+ },+ } as unknown as ToolContext;+ let admitted = Infinity;+ const session = createStrokeSession({+ clipMask: null,+ color: '#ff0000',+ composite: 'source-over',+ ctx,+ edit: { grow: (bytes) => bytes <= admitted },+ hardness: 1,+ layerId: 'L',+ opacity: 1,+ pressureOpacity: false,+ size: 20,+ thinning: 0,+ tool: 'brush',+ });+ session.addPoints([pointer(10, 10)]);+ deferred.splice(0).forEach((task) => task());+ admitted = 0;+ // Painted only by the commit-time render, whose growth is refused.+ session.addPoints([pointer(400, 400)]);++ expect(session.commit(() => true)).toBe(false);+ expect(layers.peek('L')!.rect).toEqual({ height: 20, width: 20, x: 0, y: 0 });+ });++ it('restores the layer when publication is declined', () => {+ const { layers, session } = makeSession({ height: 20, width: 20, x: 0, y: 0 });+ session.addPoints([pointer(-40, -40)]);++ expect(session.commit(() => false)).toBe(false);+ expect(layers.peek('L')!.rect).toEqual({ height: 20, width: 20, x: 0, y: 0 });+ });++ it('returns an empty cache to empty when the stroke is cancelled', () => {+ const { layers, session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });+ session.addPoints([pointer(10, 10)]);+ expect(layers.peek('L')!.rect.width).toBeGreaterThan(0);+ session.cancel();++ expect(layers.peek('L')!.rect).toMatchObject({ height: 0, width: 0 });+ });+it('returns null when the gesture produced no dirty pixels', () => {const { session } = makeSession({ height: 0, width: 0, x: 0, y: 0 });- expect(session.commit()).toBeNull();+ expect(commitStroke(session)).toBeNull();});it('grows an existing cache to the UNION of its extent and an out-of-extent stroke (negative coords included)', () => {const { entry, session } = makeSession({ height: 20, width: 20, x: 0, y: 0 });session.addPoints([pointer(-40, -40)]);- session.commit();+ commitStroke(session);// Union of the pre-stroke [0,20)² extent and the stroke bounds around// (-40,-40): the origin moved into negative layer-local space and the old@@ -312,7 +390,7 @@ describe('strokeSession: content-sized cache growth', () => {for (let i = 0; i < batches; i++) {session.addPoints([pointer(100 + i * 10, 100)]);}- session.commit();+ commitStroke(session);const resizes = resizeCount();expect(resizes).toBeLessThanOrEqual(2);@@ -332,13 +410,13 @@ describe('strokeSession: cache version bump (live adjusted-surface invalidation)const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask: null,color: '#ff0000',hardness: 1,@@ -386,13 +464,13 @@ describe('incremental "before" snapshot', () => {const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,color: '#ff0000',hardness: 1,composite: 'source-over',@@ -469,7 +547,6 @@ describe('strokeSession: pressure-dependent opacity', () => {const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),@@ -478,6 +555,7 @@ describe('strokeSession: pressure-dependent opacity', () => {created.length = 0;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask: null,color: '#ff0000',hardness: 1,@@ -496,7 +574,7 @@ describe('strokeSession: pressure-dependent opacity', () => {// would couple these assertions to the batch count, so clear the log and let commit's// single repaint be the one under test.scratch.callLog.length = 0;- session.commit();+ commitStroke(session);return scratch;};@@ -559,13 +637,13 @@ describe('layer transforms', () => {const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,color: '#ff0000',hardness: 1,composite: 'source-over',@@ -579,7 +657,7 @@ describe('layer transforms', () => {tool: 'brush',});session.addPoints([pointer(point.x, point.y)]);- return session.commit();+ return commitStroke(session);};it('maps document points through the layer inverse, so the stroke lands under the cursor', () => {@@ -609,13 +687,13 @@ describe('tap collapse', () => {backend,createPath2D: () =>({ closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} }) as unknown as Path2D,- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask: null,color: '#f00',composite: 'source-over',@@ -633,7 +711,7 @@ describe('tap collapse', () => {session.addPoints([pointer(100 + drift / 2, 100)]);session.addPoints([pointer(100 + drift, 100)]);}- return session.commit();+ return commitStroke(session);};it('renders a click that drifted under a quarter diameter as the round tap dot', () => {@@ -662,7 +740,6 @@ describe('frame-coalesced rendering', () => {const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };return path as unknown as Path2D;},- emitStrokeCommitted: vi.fn(),invalidate,layers,notifyLayerPainted: vi.fn(),@@ -677,6 +754,7 @@ describe('frame-coalesced rendering', () => {},} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask: null,color: '#ff0000',composite: 'source-over',@@ -716,7 +794,7 @@ describe('frame-coalesced rendering', () => {session.addPoints([pointer(60, 10)]);expect(renders()).toBe(0);- const event = session.commit();+ const event = commitStroke(session);expect(renders()).toBe(1);expect(frames).toHaveLength(0);@@ -735,7 +813,7 @@ describe('frame-coalesced rendering', () => {expect(frames).toHaveLength(0);expect(renders()).toBe(0);expect(layers.version('L')).toBe(version);- expect(session.commit()).toBeNull();+ expect(commitStroke(session)).toBeNull();});it('hands a failed frame render to its owner before propagating it', () => {@@ -761,13 +839,13 @@ describe('strokeSession: incremental decimation', () => {backend,createPath2D: () =>({ closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} }) as unknown as Path2D,- emitStrokeCommitted: vi.fn(),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),scheduleFrame: runFrameNow,} as unknown as ToolContext;const session = createStrokeSession({+ edit: ADMIT_ALL,clipMask: null,color: '#ff0000',composite: 'source-over',@@ -784,7 +862,7 @@ describe('strokeSession: incremental decimation', () => {for (let x = 0; x < 300; x += 1) {session.addPoints([pointer(x, 50)]);}- session.commit();+ commitStroke(session);expect(decimate).not.toHaveBeenCalled();decimate.mockRestore();});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 142f54d696..c92dca3021 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -27,7 +27,7 @@ import { applyToPoint, getScale, identity, invert, multiply } from '@workbench/cimport { expand, intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { getPressureBands } from '@workbench/canvas-engine/pressureBands';-import type { StrokeCommittedEvent, ToolContext } from './tool';+import type { StrokeCommittedEvent, StrokeEdit, ToolContext } from './tool';/** Everything a stroke session needs, resolved by the owning tool on pointer-down. */export interface StrokeSessionConfig {@@ -72,17 +72,24 @@ export interface StrokeSessionConfig {* local. Absence uses identity.*/layerTransform?: Mat2d | null;+ /** The admitted edit; its undo footprint grows before the stroke's before/after pixels do. */+ edit: Pick<StrokeEdit, 'grow'>;/** Called when a scheduled frame render throws, before the error propagates; the owner aborts the stroke. */onRenderError?: (error: unknown) => void;+ /** Called once when a frame's growth is refused; the session has already restored the layer. */+ onRefused?: () => void;}/** The imperative handle a tool drives across a gesture. */export interface StrokeSession {/** Appends coalesced samples and schedules one repaint of the accumulated stroke for the next frame. */addPoints(inputs: readonly PointerInput[]): void;- /** Finalizes the stroke and returns the completed edit for its owner to publish. */- commit(): StrokeCommittedEvent | null;- /** Restores the pre-stroke pixels and drops the session without an event. */+ /**+ * Renders the final stroke and hands it to `publish`. Returns whether it was published; when nothing was painted,+ * growth was refused, or `publish` declined, the layer is restored first.+ */+ commit(publish: (event: StrokeCommittedEvent) => boolean): boolean;+ /** Restores the pre-stroke pixels and extent and drops the session without an event. */cancel(): void;}@@ -288,6 +295,10 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionlet accumRect: Rect | null = null;let previousPolygon: Vec2[] | null = null;const chunk = growthChunk(localSize);+ const original = layers.peek(layerId);+ const originalRect = original ? { ...original.rect } : null;+ // Bytes of before/after pixels the admitted edit already covers.+ let admittedFootprint = 0;/** Ensures the scratch surface is at least `w`×`h`. */const ensureStroke = (w: number, h: number): RasterSurface => {@@ -308,9 +319,10 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionreturn soft;};- const paint = (last: boolean): void => {+ /** Renders the accumulated stroke; false when the undo footprint could not grow to cover it. */+ const paint = (last: boolean): boolean => {if (points.length === 0) {- return;+ return true;}const isTap = travel < tapCollapseLength;const effective: readonly StrokeSamplePoint[] = isTap ? [points[0]!] : points;@@ -327,7 +339,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessiondirty = intersect(dirty, clipRectLocal);}if (!dirty || isEmpty(dirty)) {- return;+ return true;}// Outward chunk-padding amortizes growth; dirty regions and history use the same padded extent. Clamp padding// to selection bounds, and trim visible content during persistence.@@ -346,7 +358,15 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession}}if (isEmpty(region)) {- return;+ return true;+ }+ // Before and after pixels each cover the region; admit them before either is captured.+ const footprint = region.width * region.height * 8;+ if (footprint > admittedFootprint) {+ if (!config.edit.grow(footprint - admittedFootprint)) {+ return false;+ }+ admittedFootprint = footprint;}// Grow preserving pixels at chunk crossings while retaining surface-object identity.@@ -507,6 +527,33 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// Report layer-local damage; compositor transforms it to screen space, avoiding full-layer resampling as zoom// increases.ctx.invalidate({ damage: { layerId, rect: changed }, layers: [layerId] });+ return true;+ };++ let settled = false;+ /** Puts the pre-stroke pixels back and returns the cache to its pre-stroke extent, once. */+ const restore = (): void => {+ const entry = layers.peek(layerId);+ if (settled || !entry || !accumRect || !beforeImageData) {+ return;+ }+ settled = true;+ entry.surface.ctx.putImageData(beforeImageData, accumRect.x - entry.rect.x, accumRect.y - entry.rect.y);+ if (originalRect) {+ layers.shrinkToRect(layerId, originalRect);+ } else {+ layers.delete(layerId);+ }+ // The whole restored rect is damage, so adjusted caches discard the live stroke preview.+ const restored = layers.peek(layerId);+ if (restored && !isEmpty(restored.rect)) {+ const visible = intersect(accumRect, restored.rect);+ layers.publishPixels(+ layerId,+ visible ? { ...visible, x: visible.x - restored.rect.x, y: visible.y - restored.rect.y } : null+ );+ }+ ctx.invalidate({ layers: [layerId] });};const append = (sample: StrokeSamplePoint): void => {@@ -528,12 +575,18 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionif (closed) {return;}+ let painted: boolean;try {- paint(false);+ painted = paint(false);} catch (error) {config.onRenderError?.(error);throw error;}+ if (!painted) {+ closed = true;+ restore();+ config.onRefused?.();+ }};return {@@ -559,30 +612,21 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessioncancel: () => {closed = true;unschedule();- const entry = layers.get(layerId);- if (entry && accumRect && beforeImageData) {- entry.surface.ctx.putImageData(beforeImageData, accumRect.x - entry.rect.x, accumRect.y - entry.rect.y);- // Cancellation reports the whole restored accumulated rect so adjusted caches discard the live stroke- // preview.- layers.publishPixels(layerId, {- height: accumRect.height,- width: accumRect.width,- x: accumRect.x - entry.rect.x,- y: accumRect.y - entry.rect.y,- });- ctx.invalidate({ layers: [layerId] });- }+ restore();},- commit: () => {+ commit: (publish) => {if (closed) {- return null;+ return false;}closed = true;unschedule();- paint(true);+ if (!paint(true)) {+ restore();+ return false;+ }const entry = layers.get(layerId);if (!entry || !accumRect || !beforeImageData) {- return null;+ return false;}const afterImageData = entry.surface.ctx.getImageData(accumRect.x - entry.rect.x,@@ -590,14 +634,20 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionaccumRect.width,accumRect.height);- return {+ const published = publish({afterImageData,beforeImageData,dirtyRect: accumRect,layerId,tool,...(createdLayer ? { createdLayer } : {}),- };+ });+ if (published) {+ settled = true;+ } else {+ restore();+ }+ return published;},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex e0d6701db6..b64028f5f2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -45,13 +45,26 @@ export interface PixelEditPatch {after: ImageData;}-export interface PixelEditTransaction {- readonly layerId: string;- commitPatch(label: string, patch: PixelEditPatch): void;- commitStroke(event: StrokeCommittedEvent): void;+/**+ * An admitted live pixel edit. Its undo footprint is admitted before pixels change: `grow` admits more before the+ * edit expands, and a refusal means the caller must restore its pixels and cancel. `commit` records the+ * already-applied pixels as one undo step and reports whether it did; `cancel` ends it unrecorded.+ */+export interface StrokeEdit {+ grow(bytes: number): boolean;+ commit(event: StrokeCommittedEvent): boolean;cancel(): void;}+/**+ * A pixel edit that may first materialize its layer (control layers, raster images) in place. A `false` commit+ * leaves it open: the caller restores the pixels it touched, then cancels, which undoes the materialization.+ */+export interface PixelEditTransaction extends StrokeEdit {+ readonly layerId: string;+ commitPatch(label: string, patch: PixelEditPatch): boolean;+}+/*** Transient render-time transforms leave the mirror unchanged. Move sets position only; transform supplies full* values.@@ -139,8 +152,8 @@ export interface ToolContext {* reevaluate it.*/updateCursor(): void;- /** Emits a completed-stroke event to `engine.tools.onStrokeCommitted` subscribers. */- emitStrokeCommitted(event: StrokeCommittedEvent): void;+ /** Admits a live pixel edit on a paint layer; null when refused (the engine reports why). */+ beginStrokeEdit(initialBytes?: number): StrokeEdit | null;/** Bumps a layer's cache version (without marking it stale) after a direct paint, and recomposites. */notifyLayerPainted(layerId: string): void;commitSelection?(commit: SelectionCommit): void;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.tsindex 702805664c..18c52a6c71 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts@@ -162,7 +162,7 @@ const createHarness = (doc: CanvasDocumentContractV3, zoom = 1, float?: FloatingcreateLayerId: () => 'x',createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: vi.fn(),- emitStrokeCommitted: vi.fn(),+ beginStrokeEdit: () => null,getDocument: () => doc,getFloatingSelection: () => floatRef.current,invalidate: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.tsindex b948aec6d2..eb639d7c92 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.ts@@ -1,3 +1,4 @@+import type { GuardedMutationRefusal } from '@workbench/canvas-engine/capabilities';import type {CommitRasterFilterResult,ExportLayerPixelsResult,@@ -95,6 +96,17 @@ const sameGuard = (left: LayerExportGuard, right: LayerExportGuard): boolean =>const message = (error: unknown): string => (error instanceof Error ? error.message : String(error));+const FILTER_COMMIT_REFUSALS: Record<GuardedMutationRefusal, string> = {+ aborted: 'The filter was cancelled before it was applied.',+ busy: 'Another canvas edit is in progress. Try again when it finishes.',+ locked: 'The layer is locked. Unlock it to apply the filter.',+ missing: 'The layer is no longer in the canvas.',+ 'not-ready': 'The canvas is not ready to apply the filter yet.',+ 'over-budget': 'The filtered layer is too large to undo, so it was not applied.',+ stale: 'The layer changed while the filter ran. Process it again.',+ unsupported: 'This layer cannot take a filter result.',+};+export const createFilterOperationSession = (options: CreateFilterOperationSessionOptions): FilterOperationSession | null => {@@ -280,7 +292,7 @@ export const createFilterOperationSession = (}publish({...state,- error: result.status === 'failed' ? result.message : `Filter commit is ${result.status}.`,+ error: result.status === 'failed' ? result.message : FILTER_COMMIT_REFUSALS[result.status],status: 'error',});return result.status === 'locked' ? 'blocked' : 'stale';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.tsindex dae1f517ac..7cc0496aab 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts@@ -59,10 +59,10 @@ describe('layer restore through history on an interleaved document', () => {expect(engine.layers.commitPrepared('Delete', remove.edit).status).toBe('committed');expect(getDocumentLeaves(document()).some((layer) => layer.id === 'r0')).toBe(false);- engine.history.undo();+ expect(await engine.history.undo()).toBe('applied');expect(getDocumentLeaves(document()).find((layer) => layer.id === 'r0')).toEqual(r0);- expect(() => engine.history.undo()).not.toThrow();+ expect(await engine.history.undo()).toBe('applied');expect(haveSameStructure(document().stacks, original.stacks)).toBe(true);expect(document().selectedLayerId).toBe('r0');expect(engine.stores.canUndo.get()).toBe(false);@@ -87,14 +87,14 @@ describe('layer restore through history on an interleaved document', () => {expect(engine.layers.commitPrepared('Delete', remove.edit).status).toBe('committed');expect(getDocumentLeaves(document()).map((layer) => layer.id)).toEqual(['m1', 'r1']);- engine.history.undo();+ expect(await engine.history.undo()).toBe('applied');expect(getDocumentLeaves(document()).filter((layer) => layer.type === 'raster').map((layer) => layer.id)).toEqual([duplicateId, 'r0', 'r1']);- expect(() => engine.history.undo()).not.toThrow();+ expect(await engine.history.undo()).toBe('applied');expect(haveSameStructure(document().stacks, original.stacks)).toBe(true);expect(engine.stores.canUndo.get()).toBe(false);engine.lifecycle.dispose();@@ -126,10 +126,10 @@ describe('layer restore through history on an interleaved document', () => {expect(new Set([...copiedIds, ...getDocumentLeaves(original).map((layer) => layer.id)]).size).toBe(7);expect(outline()).toHaveLength(10);- engine.history.undo();+ expect(await engine.history.undo()).toBe('applied');expect(haveSameStructure(document().stacks, original.stacks)).toBe(true);expect(document().selectedLayerId).toBe('g');- engine.history.redo();+ expect(await engine.history.redo()).toBe('applied');expect(getDocumentIndex(document()).byId.get(copyId!)?.node).toMatchObject({ name: 'g copy' });engine.lifecycle.dispose();});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsxnew file mode 100644index 0000000000..60d0fe56b3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx@@ -0,0 +1,21 @@+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';++import { useMountEffect } from '@platform/react/useMountEffect';+import { useNotify } from '@workbench/useNotify';+import { reportStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { useTranslation } from 'react-i18next';++/** Explains edits the engine refused without a caller to report to, such as a stroke too large to undo. Keyed by engine. */+export const CanvasEditRefusalNotices = ({ engine }: { engine: Pick<CanvasEngineHandle, 'tools'> }) => {+ const notify = useNotify();+ const { t } = useTranslation();+ useMountEffect(() =>+ engine.tools.onEditRefused((status) =>+ // Elsewhere `busy` stays silent because its controls are disabled; a stroke can still meet it mid-gesture.+ status === 'busy'+ ? notify.error(t('widgets.canvas.structural.failed'), t('widgets.canvas.structural.busy'))+ : reportStructuralCommit({ status }, notify.error, t)+ )+ );+ return null;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex 08da4fb67d..6bd0d75073 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -1,8 +1,8 @@import type { Rect } from '@workbench/canvas-engine/api';+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { Project } from '@workbench/projectContracts';import type { WidgetViewProps } from '@workbench/widgetContracts';-/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { Box, HStack, Icon, Menu, Portal, Spinner, Stack, Text } from '@chakra-ui/react';import { useModifierHeld } from '@platform/react/useModifierHeld';@@ -12,6 +12,7 @@ import { Group } from '@platform/ui/Group';import { MenuContent } from '@platform/ui/Menu';import { Tooltip } from '@platform/ui/Tooltip';import { getCanvasEngine } from '@workbench/canvas-operations/api';+import { useCanvasEngine } from '@workbench/canvas-operations/react';import { useNotify } from '@workbench/useNotify';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';@@ -45,7 +46,6 @@ import {import { CANVAS_SNAP_TO_GRID_KEY, canvasSettingsEqual, resolveCanvasSettings } from './canvasSettings';import { useCanvasCanRedo, useCanvasCanUndo, useCanvasDocumentEditingLocked, useCanvasZoom } from './engineStoreHooks';import { computeFitBboxToLayers, computeFitBboxToMasks } from './fitBbox';-import { useCanvasEngine } from './useCanvasEngine';import { useCanvasGallerySave } from './useCanvasGallerySave';import { reportStructuralCommit } from './useStructuralCommit';import { formatZoomPercent, zoomMenuOptions } from './zoomOptions';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsxindex 6e0ed72ff5..be106f52fa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx@@ -1,5 +1,5 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop -- the container ref callback is intentionally re-created when `engine` changes, so a project switch detaches the old engine and attaches the new one. */-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react';import { Box } from '@chakra-ui/react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsxindex 8196787652..0489167f84 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx@@ -34,7 +34,7 @@ vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({}));vi.mock('@features/queue', () => ({ useQueueItemProgressImage: () => null }));vi.mock('./engineStoreHooks', () => ({ useCanvasOperation: () => null }));-vi.mock('./useCanvasEngine', () => ({ useCanvasEngine: () => harness.engine }));+vi.mock('@workbench/canvas-operations/react', () => ({ useCanvasEngine: () => harness.engine }));vi.mock('./useCanvasGallerySave', () => ({useCanvasGallerySave: () => ({ isSaving: false, save: () => undefined }),}));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 07dea3a8b7..3a4c120acf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -7,6 +7,7 @@ import { useQueueItemProgressImage } from '@features/queue/react';import { useMountEffect } from '@platform/react/useMountEffect';import { preloadCanvasInvocation } from '@workbench/activeInvocationSubmission';import { getCanvasImportNotice } from '@workbench/canvas-operations/api';+import { useCanvasEngine } from '@workbench/canvas-operations/react';import { getCanvasStagingSlots } from '@workbench/canvasStagingView';import { recordCanvasImportError } from '@workbench/image-actions/canvasImportError';import { readLayerPanelState } from '@workbench/layerPanelState';@@ -34,6 +35,7 @@ import {type CanvasContextMenuTarget,} from './canvasContextMenu';import { CanvasCreateFromBboxSubmenu } from './CanvasCreateFromBboxSubmenu';+import { CanvasEditRefusalNotices } from './CanvasEditRefusalNotices';import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';import { executeCanvasHotkeyCommand } from './canvasHotkeyCommands';import { resolveCanvasImageDrop } from './canvasImageDnd';@@ -57,10 +59,9 @@ import { StagingBar } from './StagingBar';import { selectStagedPreviewSource, stagedPreviewKey } from './stagingPreview';import { INLINE_EDIT_SELECTOR } from './surfaceFocus';import { ToolStrip } from './ToolStrip';-import { useCanvasEngine } from './useCanvasEngine';import { useCanvasGallerySave } from './useCanvasGallerySave';import { useCreateFromBbox } from './useCreateFromBbox';-import { reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';+import { reportLayerOperation, reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';const MissingFontsDialog = lazy(() =>import('./MissingFontsDialog').then((module) => ({ default: module.MissingFontsDialog }))@@ -267,7 +268,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {}const result = mountedEngine.selection.pasteImage(pixels);if (result.status !== 'created') {- notifications.add({ kind: 'error', title: t('widgets.canvas.clipboard.pasteFailed') });+ reportLayerOperation(result.status, notify.error, t);}})();});@@ -282,15 +283,20 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {/* eslint-disable react/preserve-manual-memoization -- imperative engine payload is mutable by design */const commitSelectedStagedImage = useCallback((continueStaging: boolean) => {- if (selectedSlot?.kind === 'candidate') {- engine?.layers.commitStagedImage({- candidate: selectedSlot.candidate,- continueStaging,- selectedImageIndex: stagingArea.selectedImageIndex,- });+ if (selectedSlot?.kind !== 'candidate' || !engine) {+ return;+ }+ const result = engine.layers.commitStagedImage({+ candidate: selectedSlot.candidate,+ continueStaging,+ selectedImageIndex: stagingArea.selectedImageIndex,+ });+ if (result.status !== 'committed' && result.status !== 'busy') {+ // A candidate that left staging is as stale as one that changed under the accept.+ reportLayerOperation(result.status === 'missing' ? 'stale' : result.status, notify.error, t);}},- [engine, selectedSlot, stagingArea.selectedImageIndex]+ [engine, notify, selectedSlot, stagingArea.selectedImageIndex, t]);/* eslint-enable react/preserve-manual-memoization */const acceptStagedImage = useCallback(() => commitSelectedStagedImage(false), [commitSelectedStagedImage]);@@ -375,6 +381,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {notifyLayerDuplicateFailed: () =>notifications.add({ kind: 'error', title: t('widgets.layers.actions.copyFailed') }),pasteFromClipboard,+ reportLayerOperation: (refusal) => reportLayerOperation(refusal, notify.error, t),reportPreparedCommit: (outcome) => reportPreparedCommit(outcome, notify.error, t),reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),resetActiveColors: colorCommands.resetPair,@@ -488,6 +495,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {w="full"><CanvasColorFeed engine={engine} />+ {engine ? <CanvasEditRefusalNotices key={projectId} engine={engine} /> : null}{engine && fontReferences.length > 0 ? (<Suspense fallback={null}><MissingFontsDialog key={projectId} engine={engine} groups={fontReferences} />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsxindex 7290a58390..678d032d91 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.tsx@@ -1,6 +1,6 @@import type { TextEditSession } from '@workbench/canvas-engine/api';/* oxlint-disable react-perf/jsx-no-new-object-as-prop -- the editable's style object is derived from the live session/viewport and intentionally recomputed each render. */-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent } from 'react';import { useNotify } from '@workbench/useNotify';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex 4bedd85785..3ca56977c7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@ -4,6 +4,8 @@ import type {CanvasInteractionState,CanvasLayerContract,CanvasNodeContract,+ MergeDownResult,+ NewRasterLayerResult,} from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -61,26 +63,27 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {}),},layers: {- clearMask: vi.fn(),+ clearMask: vi.fn(() => ({ status: 'committed' })),commitPrepared: vi.fn(() => ({ status: 'committed' as const })),commitStructural: vi.fn(),duplicateLayers: vi.fn(() =>Promise.resolve<- { status: 'duplicated'; duplicateIds: string[]; selectedLayerId: string } | { status: 'not-ready' }+ | { status: 'duplicated'; duplicateIds: string[]; selectedLayerId: string }+ | { status: 'not-ready' | 'over-budget' | 'stale' }>({duplicateIds: ['new-layer'],selectedLayerId: 'new-layer',status: 'duplicated',})),- mergeLayerDown: vi.fn(),+ mergeLayerDown: vi.fn((): MergeDownResult => 'merged'),nudgeSelectedLayer: vi.fn(() => ({ status: 'committed' as const })),},selection: {deselect: vi.fn(),eraseSelection: vi.fn(),invertSelection: vi.fn(),- liftSelectionToLayer: vi.fn(),+ liftSelectionToLayer: vi.fn((): NewRasterLayerResult => ({ layerId: 'lifted', status: 'created' })),selectAll: vi.fn(),},tools: { setTool: vi.fn(), stepBrushSize: vi.fn() },@@ -95,6 +98,7 @@ let pasteFromClipboard: Mock<() => void>;const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyContext => ({copySelection,dispatch,+ reportLayerOperation: vi.fn(),reportPreparedCommit: () => undefined,reportStructuralCommit: () => undefined,document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a'),@@ -330,19 +334,28 @@ describe('duplicate: lift vs whole layer', () => {expect(engine.layers.duplicateLayers).toHaveBeenCalledWith(['a', 'b']);});- it.each(['declines', 'throws'] as const)('reports when whole-layer duplication %s', async (failure) => {+ it('reports when whole-layer duplication throws', async () => {const engine = createEngine();- if (failure === 'declines') {- engine.layers.duplicateLayers.mockImplementation(() => Promise.resolve({ status: 'not-ready' }));- } else {- engine.layers.duplicateLayers.mockImplementation(() => Promise.reject(new Error('rejected')));- }+ engine.layers.duplicateLayers.mockImplementation(() => Promise.reject(new Error('rejected')));const notifyLayerDuplicateFailed = vi.fn();executeCanvasHotkeyCommand('canvas.duplicateLayer', contextOf({ engine, notifyLayerDuplicateFailed }));await vi.waitFor(() => expect(notifyLayerDuplicateFailed).toHaveBeenCalledOnce());});++ it.each(['not-ready', 'over-budget', 'stale'] as const)(+ 'explains a %s whole-layer duplication refusal',+ async (status) => {+ const engine = createEngine();+ engine.layers.duplicateLayers.mockImplementation(() => Promise.resolve({ status }));+ const reportLayerOperation = vi.fn();++ executeCanvasHotkeyCommand('canvas.duplicateLayer', contextOf({ engine, reportLayerOperation }));++ await vi.waitFor(() => expect(reportLayerOperation).toHaveBeenCalledExactlyOnceWith(status));+ }+ );});describe('clipboard', () => {@@ -467,6 +480,17 @@ describe('history, selection, and brush size', () => {it('resetSelected clears the selected layer mask', () => {expect(run('canvas.resetSelected').layers.clearMask).toHaveBeenCalledWith('a');});++ it('resetSelected explains a refused clear and stays silent when there is nothing to clear', () => {+ const engine = createEngine();+ const reportLayerOperation = vi.fn();+ engine.layers.clearMask.mockReturnValueOnce({ status: 'over-budget' }).mockReturnValueOnce({ status: 'nothing' });++ executeCanvasHotkeyCommand('canvas.resetSelected', contextOf({ engine, reportLayerOperation }));+ executeCanvasHotkeyCommand('canvas.resetSelected', contextOf({ engine, reportLayerOperation }));++ expect(reportLayerOperation).toHaveBeenCalledExactlyOnceWith('over-budget');+ });});describe('mergeDown', () => {@@ -484,6 +508,14 @@ describe('mergeDown', () => {const engine = run('canvas.mergeDown', { document: documentOf([rasterLayer('a')], null) });expect(engine.layers.mergeLayerDown).not.toHaveBeenCalled();});++ it('reports a merge the engine refused', () => {+ const engine = createEngine();+ engine.layers.mergeLayerDown.mockReturnValue('over-budget');+ const reportLayerOperation = vi.fn();+ executeCanvasHotkeyCommand('canvas.mergeDown', contextOf({ engine, reportLayerOperation }));+ expect(reportLayerOperation).toHaveBeenCalledExactlyOnceWith('over-budget');+ });});describe('toggleNonRasterLayers', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex 1ea314f97d..d7c8a0db9a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -14,7 +14,11 @@ import {isOverlayStack,} from '@workbench/canvas-engine/api';import { publishLayerPanelSelection } from '@workbench/layerPanelState';-import { commitPreparedEdit, type PreparedCommitOutcome } from '@workbench/widgets/canvas/useStructuralCommit';+import {+ commitPreparedEdit,+ type LayerOperationRefusal,+ type PreparedCommitOutcome,+} from '@workbench/widgets/canvas/useStructuralCommit';import {canGroupSelection,canUngroupSelection,@@ -63,6 +67,7 @@ export interface CanvasHotkeyContext {readonly notifyLayerDuplicateFailed: () => void;readonly reportStructuralCommit: (result: StructuralCommitResult) => void;readonly reportPreparedCommit: (outcome: PreparedCommitOutcome) => void;+ readonly reportLayerOperation: (refusal: LayerOperationRefusal) => void;readonly t: (key: string) => string;}@@ -176,7 +181,10 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC}} else if (commandId === 'canvas.resetSelected') {if (engine && selectedLayer) {- engine.layers.clearMask(selectedLayer.id);+ const result = engine.layers.clearMask(selectedLayer.id);+ if (result.status !== 'committed' && result.status !== 'nothing' && result.status !== 'busy') {+ ctx.reportLayerOperation(result.status);+ }}} else if (commandId === 'canvas.undo') {// Use engine pixel/structural history only; empty canvas history never falls back to project undo.@@ -252,7 +260,10 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC// With a live pixel selection, mod+J is "layer via copy" — it lifts just// the selected pixels. With none, it duplicates the whole layer.if (engine?.interaction.get('hasSelection')) {- engine.selection.liftSelectionToLayer();+ const result = engine.selection.liftSelectionToLayer();+ if (result.status !== 'created' && result.status !== 'empty') {+ ctx.reportLayerOperation(result.status);+ }} else if (engine && selected) {void engine.layers.duplicateLayers(ctx.selectedLayerIds)@@ -268,7 +279,11 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCif (result.status === 'busy') {return;}- ctx.notifyLayerDuplicateFailed();+ if (result.status === 'nothing') {+ ctx.notifyLayerDuplicateFailed();+ return;+ }+ ctx.reportLayerOperation(result.status);}).catch(() => {// The engine keeps rejected transactions atomic; route both rejection@@ -289,7 +304,10 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC} else if (commandId === 'canvas.mergeDown') {// Share canMergeLayerDown with the layer menu so shortcuts respect identical eligibility.if (engine && selectedLayer && canMergeLayerDown(document, selectedLayer.id, true)) {- engine.layers.mergeLayerDown(selectedLayer.id);+ const result = engine.layers.mergeLayerDown(selectedLayer.id);+ if (result !== 'merged') {+ ctx.reportLayerOperation(result);+ }}}};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsxindex 002eb0bb27..ac0f21c709 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx@@ -1,4 +1,4 @@-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { useEffect } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.tsindex 85ca0328b0..3f787222c8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts@@ -1,9 +1,8 @@import type { CanvasLayerContract, CanvasMaskFillContract } from '@workbench/canvas-engine/api';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { getDocumentLayer } from '@workbench/canvas-engine/api';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';-import { applyStructuralPreview } from '@workbench/widgets/layers/layerOps';+import { useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -48,7 +47,7 @@ const configFor = (layer: MaskLayer, fill: CanvasMaskFillContract) =>*/export const useMaskTintEditor = (engine: MaskTintEngine | null): MaskTintEditor | null => {const { t } = useTranslation();- const commitPrepared = usePreparedCommit(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const armedLayerId = useMaskTintTargetLayerId();const layer = useActiveProjectSelector((project): MaskLayer | null => {if (!armedLayerId || project.canvas.document.selectedLayerId !== armedLayerId) {@@ -105,7 +104,7 @@ export const useMaskTintEditor = (engine: MaskTintEngine | null): MaskTintEditorreturn;}if (- !applyStructuralPreview(engine, {+ !previewStructural({config: configFor(layer, { ...layer.mask.fill, color: hex }),id: layer.id,type: 'updateCanvasLayerConfig',@@ -119,7 +118,7 @@ export const useMaskTintEditor = (engine: MaskTintEngine | null): MaskTintEditorgestureRef.current.latestHex = hex;}},- [engine, layer]+ [previewStructural, layer]);const commit = useCallback((hex: string) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.tsindex 14e2aff6bb..d42f167820 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts@@ -135,12 +135,12 @@ export const useCanvasDocumentEditingLocked = (engine: CanvasCoreStoreCapability};/** Re-renders when any live layer cache gains, loses, or changes pixels. */-export const useCanvasRasterContentEpoch = (engine: CanvasCoreStoreCapability | null): number => {+export const useCanvasLayerPixelEpoch = (engine: CanvasCoreStoreCapability | null): number => {const subscribe = useCallback(- (listener: () => void) => engine?.interaction.subscribe('rasterContentEpoch', listener) ?? (() => undefined),+ (listener: () => void) => engine?.interaction.subscribe('layerPixelEpoch', listener) ?? (() => undefined),[engine]);- const getSnapshot = useCallback(() => engine?.interaction.get('rasterContentEpoch') ?? 0, [engine]);+ const getSnapshot = useCallback(() => engine?.interaction.get('layerPixelEpoch') ?? 0, [engine]);return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.tsindex ee06220d85..67d216f907 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts@@ -1,5 +1,5 @@+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { Project } from '@workbench/projectContracts';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { WorkbenchCanvasCommands, WorkbenchQueries } from '@workbench/workbenchStore';import { galleryImages } from '@features/gallery';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsxindex 0032844a05..b648af9c6a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx@@ -37,6 +37,7 @@ vi.mock('@workbench/widgets/canvas/engineStoreHooks', () => ({vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject.current!),}));+vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }) }));vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsxindex d6d9e70afd..cf63cbf866 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx@@ -5,7 +5,9 @@ import { HStack } from '@chakra-ui/react';import { Button, IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';import { isLeafPixelEditEligible, lookupDocumentLeaf } from '@workbench/canvas-engine/api';+import { useNotify } from '@workbench/useNotify';import { useCanvasHasSelection } from '@workbench/widgets/canvas/engineStoreHooks';+import { reportLayerOperation } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { SquareIcon, SquareMinusIcon, SquarePlusIcon, SquaresIntersectIcon } from 'lucide-react';import { useCallback } from 'react';@@ -113,6 +115,7 @@ const SelectionAction = ({*/export const SelectionActions = ({ engine }: ToolFormProps) => {const { t } = useTranslation();+ const notify = useNotify();const hasSelection = useCanvasHasSelection(engine);const canPaintTarget = useActiveProjectSelector((project) => {const { document } = project.canvas;@@ -123,7 +126,12 @@ export const SelectionActions = ({ engine }: ToolFormProps) => {const onErase = useCallback(() => engine.selection.eraseSelection(), [engine]);const onInvert = useCallback(() => engine.selection.invertSelection(), [engine]);const onDeselect = useCallback(() => engine.selection.deselect(), [engine]);- const onLiftToLayer = useCallback(() => engine.selection.liftSelectionToLayer(), [engine]);+ const onLiftToLayer = useCallback(() => {+ const result = engine.selection.liftSelectionToLayer();+ if (result.status !== 'created' && result.status !== 'empty') {+ reportLayerOperation(result.status, notify.error, t);+ }+ }, [engine, notify, t]);const needsSelection = hasSelection ? null : t('widgets.canvas.toolOptions.selectionNeedsSelection');const needsPaintTarget =needsSelection ?? (canPaintTarget ? null : t('widgets.canvas.toolOptions.selectionNeedsPaintLayer'));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.tsindex 6fce508916..cb332c18e8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts@@ -1,6 +1,6 @@import type { ToolId } from '@workbench/canvas-engine/api';import type { CanvasOperationState } from '@workbench/canvas-operations/api';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { ComponentType } from 'react';export type CanvasToolOptionsEngine = Pick<diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasEngine.tsdeleted file mode 100644index 1e65bf301c..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasEngine.ts+++ /dev/null@@ -1,2 +0,0 @@-/** Canvas widget compatibility seam; engine ownership lives in the Canvas operations interface. */-export { type CanvasEngineHandle, useCanvasEngine } from '@workbench/canvas-operations/react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.tsindex a1462c6390..2b242db503 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts@@ -1,4 +1,4 @@-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { invalidateGallery } from '@features/gallery/queries';import {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCreateFromBbox.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCreateFromBbox.tsindex 886b0275e1..f8eff914e5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCreateFromBbox.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCreateFromBbox.ts@@ -1,4 +1,4 @@-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { ensureModelsLoaded, useModelsSelector } from '@features/models';import { useMountEffect } from '@platform/react/useMountEffect';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.browser.test.tsxnew file mode 100644index 0000000000..6d4c1a4322--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.browser.test.tsx@@ -0,0 +1,141 @@+import type {+ CanvasEditRefusal,+ CanvasLayerPreviewMutation,+ PreparedDocumentEdit,+ StructuralPreviewSession,+} from '@workbench/canvas-engine/api';++import { act, createRef, type Ref, useImperativeHandle } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { CanvasEditRefusalNotices } from './CanvasEditRefusalNotices';+import { type CanvasPreviewEngine, type StructuralPreview, useStructuralPreview } from './useStructuralCommit';++const notify = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));+vi.mock('@workbench/useNotify', () => ({ useNotify: () => notify }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const cleanups: (() => void)[] = [];+afterEach(() => {+ for (const cleanup of cleanups.splice(0)) {+ cleanup();+ }+ vi.clearAllMocks();+});++const render = (element: React.ReactElement): void => {+ const host = document.createElement('div');+ document.body.append(host);+ const root = createRoot(host);+ act(() => root.render(element));+ cleanups.push(() => {+ act(() => root.unmount());+ host.remove();+ });+};++const opacity = (value: number): CanvasLayerPreviewMutation => ({+ id: 'layer',+ patch: { opacity: value },+ type: 'updateCanvasLayer',+});+const EDIT = { forward: opacity(0.5), inverse: opacity(1) } as unknown as PreparedDocumentEdit;++const createSession = (commitStatus: 'committed' | 'busy' = 'committed') => {+ const session = {+ apply: vi.fn(() => true),+ cancel: vi.fn(),+ commit: vi.fn(() => ({ status: commitStatus })),+ } satisfies StructuralPreviewSession;+ return session;+};++const createEngine = (session: StructuralPreviewSession, commitPrepared = vi.fn(() => ({ status: 'committed' }))) =>+ ({+ document: { model: () => ({}) },+ layers: { beginStructuralPreview: vi.fn(() => session), commitPrepared },+ }) as unknown as CanvasPreviewEngine & { layers: { commitPrepared: typeof commitPrepared } };++const PreviewProbe = ({ engine, ref }: { engine: CanvasPreviewEngine; ref: Ref<StructuralPreview> }) => {+ const preview = useStructuralPreview(engine);+ useImperativeHandle(ref, () => preview, [preview]);+ return null;+};++const renderPreview = (engine: CanvasPreviewEngine): StructuralPreview => {+ const ref = createRef<StructuralPreview>();+ render(<PreviewProbe ref={ref} engine={engine} />);+ return ref.current!;+};++/** An engine whose only capability is the refusal channel, and the emitter that drives it. */+const createRefusalEngine = () => {+ const listeners: ((refusal: CanvasEditRefusal) => void)[] = [];+ return {+ emit: (refusal: CanvasEditRefusal) => listeners.forEach((listener) => listener(refusal)),+ engine: {+ tools: {+ onEditRefused: (listener: (refusal: CanvasEditRefusal) => void) => {+ listeners.push(listener);+ return () => undefined;+ },+ },+ } as never,+ };+};++describe('useStructuralPreview', () => {+ it('records a previewed gesture through the session that previewed it', () => {+ const session = createSession();+ const engine = createEngine(session);+ const preview = renderPreview(engine);++ expect(preview.preview(opacity(0.7))).toBe(true);+ expect(preview.preview(opacity(0.5))).toBe(true);+ const outcome = preview.commit('Opacity', () => ({ edit: EDIT, status: 'prepared' }) as never);++ expect(engine.layers.beginStructuralPreview).toHaveBeenCalledOnce();+ expect(session.apply).toHaveBeenCalledTimes(2);+ expect(session.commit).toHaveBeenCalledWith('Opacity', EDIT);+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();+ expect(outcome).toEqual({ status: 'committed' });+ });++ it('commits as a plain prepared edit when another gesture took its session', () => {+ const engine = createEngine(createSession('busy'));+ const preview = renderPreview(engine);+ preview.preview(opacity(0.5));++ preview.commit('Opacity', () => ({ edit: EDIT, status: 'prepared' }) as never);+ expect(engine.layers.commitPrepared).toHaveBeenCalledWith('Opacity', EDIT);+ });++ it('cancels its session and reports when the edit cannot be prepared', () => {+ const session = createSession();+ const preview = renderPreview(createEngine(session));+ preview.preview(opacity(0.5));++ preview.commit('Opacity', () => ({ status: 'locked' }) as never);+ expect(session.cancel).toHaveBeenCalledOnce();+ expect(notify.error).toHaveBeenCalledWith(+ 'widgets.canvas.structural.failed',+ 'widgets.canvas.structural.refusedLocked'+ );+ });+});++describe('CanvasEditRefusalNotices', () => {+ it.each<[CanvasEditRefusal, string]>([+ ['over-budget', 'widgets.canvas.structural.overBudget'],+ ['busy', 'widgets.canvas.structural.busy'],+ ])('explains a %s refusal of an edit nobody else reports', (refusal, message) => {+ const { emit, engine } = createRefusalEngine();+ render(<CanvasEditRefusalNotices engine={engine} />);++ emit(refusal);+ expect(notify.error).toHaveBeenCalledWith('widgets.canvas.structural.failed', message);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.tsindex 48600a4495..4bfc2a8338 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts@@ -1,17 +1,62 @@import type {CanvasDocumentCapability,CanvasLayerCapability,+ CanvasLayerPreviewMutation,CanvasDocumentModel,DocumentRefusal,+ MaskEditResult,PrepareEditResult,StructuralCommitResult,+ StructuralPreviewSession,} from '@workbench/canvas-engine/api';import type { TFunction } from 'i18next';import { useNotify } from '@workbench/useNotify';-import { useCallback } from 'react';+import { useCallback, useRef } from 'react';import { useTranslation } from 'react-i18next';+/** Outcomes a layer pixel operation (merge down, rasterize, layer via copy) reports instead of applying. */+export type LayerOperationRefusal =+ | 'busy'+ | 'empty'+ | 'failed'+ | 'locked'+ | 'missing'+ | 'not-ready'+ | 'over-budget'+ | 'stale'+ | 'unsupported';++const LAYER_OPERATION_KEYS: Record<LayerOperationRefusal, string> = {+ busy: 'widgets.layers.actions.busy',+ empty: 'widgets.layers.actions.empty',+ failed: 'widgets.layers.actions.operationFailed',+ locked: 'widgets.layers.actions.locked',+ missing: 'widgets.layers.actions.missing',+ 'not-ready': 'widgets.layers.actions.notReady',+ 'over-budget': 'widgets.layers.actions.overBudget',+ stale: 'widgets.layers.actions.stale',+ unsupported: 'widgets.layers.actions.unsupported',+};++/** Explains a refused layer pixel operation; nothing changed in the document, pixels or history. */+export const reportLayerOperation = (+ refusal: LayerOperationRefusal,+ reportError: (title: string, message: string) => void,+ t: TFunction+): void => reportError(t('widgets.layers.actions.actionFailed'), t(LAYER_OPERATION_KEYS[refusal]));++/** Explains a refused mask clear or invert; `busy` and a mask with nothing to change stay silent. */+export const reportMaskEdit = (+ result: MaskEditResult,+ reportError: (title: string, message: string) => void,+ t: TFunction+): void => {+ if (result.status !== 'committed' && result.status !== 'busy' && result.status !== 'nothing') {+ reportLayerOperation(result.status, reportError, t);+ }+};+/*** Explains a refused structural edit. `busy` stays silent because an in-flight operation already* disables the controls that could reach here; every other refusal drops the edit and says so.@@ -32,6 +77,9 @@ export const reportStructuralCommit = (case 'not-ready':reportError(title, t('widgets.canvas.structural.notReady'));return;+ case 'over-budget':+ reportError(title, t('widgets.canvas.structural.overBudget'));+ return;case 'stale':reportError(title, t('widgets.canvas.structural.stale'));return;@@ -52,7 +100,6 @@ export const reportStructuralCommit = (}};-/** A widget-side structural commit that reports the refusals the user needs to hear about. *//** The engine surface a prepared edit needs: the document model and the transaction. */export interface CanvasPreparedEngine {readonly document: Pick<CanvasDocumentCapability, 'model'>;@@ -139,3 +186,73 @@ export const usePreparedCommit = (engine: CanvasPreparedEngine | null): Prepared[engine, notify, t]);};++export interface CanvasPreviewEngine extends CanvasPreparedEngine {+ readonly layers: Pick<CanvasLayerCapability, 'beginStructuralPreview' | 'commitPrepared'>;+}++export interface StructuralPreview {+ /** Previews `action` live, at most once per frame; false while edits are refused. */+ preview(action: CanvasLayerPreviewMutation): boolean;+ /** Records the gesture as one undo step from its baseline and reports any refusal. */+ commit: PreparedCommit;+ /** Ends the gesture unrecorded, returning the document to `restore`. */+ cancel(restore?: CanvasLayerPreviewMutation): void;+}++/** A live-preview gesture backed by one engine preview session, committed or cancelled as a whole. */+export const useStructuralPreview = (engine: CanvasPreviewEngine | null): StructuralPreview => {+ const notify = useNotify();+ const { t } = useTranslation();+ const sessionRef = useRef<StructuralPreviewSession | null>(null);++ const preview = useCallback(+ (action: CanvasLayerPreviewMutation): boolean => {+ if (!engine) {+ return false;+ }+ if (sessionRef.current?.apply(action)) {+ return true;+ }+ // No session yet, or a newer one or a commit ended it.+ sessionRef.current = engine.layers.beginStructuralPreview();+ return sessionRef.current?.apply(action) ?? false;+ },+ [engine]+ );++ const commit = useCallback<PreparedCommit>(+ (label, prepare) => {+ const session = sessionRef.current;+ sessionRef.current = null;+ const model = engine?.document.model() ?? null;+ let outcome: PreparedCommitOutcome;+ if (!engine || !model) {+ session?.cancel();+ outcome = { status: 'not-ready' };+ } else {+ const result = prepare(model);+ if (result.status === 'prepared') {+ const committed = session?.commit(label, result.edit);+ // A session another gesture ended commits like any prepared edit.+ outcome =+ committed && committed.status !== 'busy' ? committed : engine.layers.commitPrepared(label, result.edit);+ } else {+ session?.cancel();+ outcome = result.status === 'unchanged' ? result : { refusal: result, status: 'refused' };+ }+ }+ reportPreparedCommit(outcome, notify.error, t);+ return outcome;+ },+ [engine, notify, t]+ );++ const cancel = useCallback((restore?: CanvasLayerPreviewMutation): void => {+ const session = sessionRef.current;+ sessionRef.current = null;+ session?.cancel(restore);+ }, []);++ return { cancel, commit, preview };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsxindex be36d53395..bf3175ec92 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx@@ -93,7 +93,18 @@ const Harness = ({ entryId, owner = 'raster' }: { entryId: string; owner?: 'rast),},layers: {- applyStructuralPreview: apply,+ beginStructuralPreview: () => ({+ apply,+ cancel: (restore?: CanvasProjectMutation) => {+ if (restore) {+ apply(restore);+ }+ },+ commit: (_label: string, edit: PreparedDocumentEdit) => {+ commits.push(edit);+ return { status: apply(edit.forward) ? ('committed' as const) : ('dispatch-rejected' as const) };+ },+ }),commitPrepared: (_label: string, edit: PreparedDocumentEdit) => {commits.push(edit);return { status: apply(edit.forward) ? ('committed' as const) : ('dispatch-rejected' as const) };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsxindex 66ae92ee6c..cc8445d447 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.tsx@@ -11,7 +11,7 @@ import type { PointerEvent as ReactPointerEvent } from 'react';import { chakra, createListCollection, HStack, Stack, Text } from '@chakra-ui/react';import { Field, Select, Slider } from '@platform/ui';import { buildCurveLut } from '@workbench/canvas-engine/api';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -23,7 +23,6 @@ import {finishCurveDragResult,getCurveGridCoordinates,} from './curveEditorMath';-import { applyStructuralPreview } from './layerOps';/*** Edit adjustment subrows through whole-stack patch-config. Preview gestures live and commit once; tree rows own@@ -95,7 +94,7 @@ const AdjustmentEntryEditor = ({entry: CanvasAdjustmentEntry;layer: AdjustmentOwner;}) => {- const commitPrepared = usePreparedCommit(engine);+ const { cancel: cancelPreview, commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const { t } = useTranslation();const gestureBaselineRef = useRef<readonly CanvasAdjustmentEntry[] | null>(null);const configOf = useCallback(@@ -110,13 +109,13 @@ const AdjustmentEntryEditor = ({(next: CanvasAdjustmentEntry) => {const entries = layer.adjustments ?? [];gestureBaselineRef.current ??= entries;- applyStructuralPreview(engine, {+ previewStructural({config: configOf(entries.map((candidate) => (candidate.id === next.id ? next : candidate))),id: layer.id,type: 'updateCanvasLayerConfig',});},- [configOf, engine, layer.adjustments, layer.id]+ [configOf, previewStructural, layer.adjustments, layer.id]);const commitEntry = useCallback(@@ -142,13 +141,9 @@ const AdjustmentEntryEditor = ({const baseline = gestureBaselineRef.current;gestureBaselineRef.current = null;if (baseline) {- applyStructuralPreview(engine, {- config: configOf([...baseline]),- id: layer.id,- type: 'updateCanvasLayerConfig',- });+ cancelPreview({ config: configOf([...baseline]), id: layer.id, type: 'updateCanvasLayerConfig' });}- }, [configOf, engine, layer.id]);+ }, [cancelPreview, configOf, layer.id]);const handleScalarLive = useCallback((field: ScalarField, next: number) => patchLive({ ...entry, [field]: next } as CanvasAdjustmentEntry),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex 84559645f1..afac46ad9b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -30,13 +30,13 @@ import { useExternalStoreSelector } from '@platform/state/selectors';import { Button, Field, Select, Slider } from '@platform/ui';import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { getCompatibleControlModels } from './controlModelOptions';import { LayerFilterOperationButton } from './LayerFilterOperationButton';-import { applyStructuralPreview, CONTROL_ADAPTER_DEFAULTS, CONTROL_WEIGHT_BOUNDS } from './layerOps';+import { CONTROL_ADAPTER_DEFAULTS, CONTROL_WEIGHT_BOUNDS } from './layerOps';import { runLayerFilterOperation } from './layerPropertiesOperation';import { useSelectedMainModel } from './useSelectedMainModel';@@ -89,7 +89,7 @@ const contributingControlLayers = (export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ControlLayerSettingsProps) => {const { t } = useTranslation();- const commitPrepared = usePreparedCommit(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const models = useModelsSelector((snapshot) => snapshot.models);const mainModel = useSelectedMainModel();const base = mainModel?.base ?? null;@@ -221,7 +221,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contreturn;}if (- !applyStructuralPreview(engine, {+ !previewStructural({config: { adapter: { weight: next }, layerType: 'control' },id: layer.id,type: 'updateCanvasLayerConfig',@@ -233,7 +233,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ContweightBeforeRef.current = adapter.weight;}},- [adapter.weight, engine, layer.id]+ [adapter.weight, previewStructural, layer.id]);const handleWeightChangeEnd = useCallback(({ value }: SliderValueChangeDetails) => {@@ -268,7 +268,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contreturn;}if (- !applyStructuralPreview(engine, {+ !previewStructural({config: { adapter: { beginEndStepPct: [value[0]!, value[1]!] }, layerType: 'control' },id: layer.id,type: 'updateCanvasLayerConfig',@@ -280,7 +280,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ContrangeBeforeRef.current = adapter.beginEndStepPct;}},- [adapter.beginEndStepPct, engine, layer.id]+ [adapter.beginEndStepPct, previewStructural, layer.id]);const handleRangeChangeEnd = useCallback(({ value }: SliderValueChangeDetails) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.browser.test.tsxindex 9795a98ec3..6a2e8c4501 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.browser.test.tsx@@ -67,7 +67,18 @@ const Harness = () => {),},layers: {- applyStructuralPreview: apply,+ beginStructuralPreview: () => ({+ apply,+ cancel: (restore?: CanvasProjectMutation) => {+ if (restore) {+ apply(restore);+ }+ },+ commit: (label: string, edit: PreparedDocumentEdit) => {+ commits.push({ edit, label });+ return { status: apply(edit.forward) ? ('committed' as const) : ('dispatch-rejected' as const) };+ },+ }),commitPrepared: (label: string, edit: PreparedDocumentEdit) => {commits.push({ edit, label });return { status: apply(edit.forward) ? ('committed' as const) : ('dispatch-rejected' as const) };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsxindex b43e0ecf9e..1036382fc3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx@@ -4,15 +4,18 @@ import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps'import { createListCollection, HStack, Stack } from '@chakra-ui/react';import { Button, ColorPicker, Field, IconButton, Select, Tooltip } from '@platform/ui';+import { useNotify } from '@workbench/useNotify';import { armMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';import { type ColorSamplerEngine, useColorSampler } from '@workbench/widgets/canvas/useColorSampler';-import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import {+ type CanvasPreparedEngine,+ reportMaskEdit,+ useStructuralPreview,+} from '@workbench/widgets/canvas/useStructuralCommit';import { PaletteIcon } from 'lucide-react';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { applyStructuralPreview } from './layerOps';-/** The six mask fill styles, matching `CanvasMaskFillContract['style']` / legacy `zFillStyle`. */const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = ['solid',@@ -34,7 +37,7 @@ interface InpaintMaskSettingsProps {*/export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps) => {const { t } = useTranslation();- const commitPrepared = usePreparedCommit(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const sampleColor = useColorSampler(engine);const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);@@ -68,7 +71,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)const handleColorChange = useCallback((hex: string) => {if (- !applyStructuralPreview(engine, {+ !previewStructural({config: { layerType: 'inpaint_mask', mask: { fill: { ...fill, color: hex } } },id: layer.id,type: 'updateCanvasLayerConfig',@@ -80,7 +83,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)fillBeforeRef.current = fill;}},- [engine, fill, layer.id]+ [previewStructural, fill, layer.id]);const handleArmTint = useCallback(() => armMaskTintTarget(layer.id), [layer.id]);@@ -103,9 +106,12 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)[commitFill, fill]);+ const notify = useNotify();const handleInvert = useCallback(() => {- engine?.layers.invertMask(layer.id);- }, [engine, layer.id]);+ if (engine) {+ reportMaskEdit(engine.layers.invertMask(layer.id), notify.error, t);+ }+ }, [engine, layer.id, notify, t]);const styleValue = useMemo(() => [fill.style], [fill.style]);const colorAria = t('widgets.layers.maskFill.color');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsxindex 500dde75b4..b8821295d7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx@@ -1,13 +1,13 @@import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';import type { CanvasBlendMode, CanvasDocumentContractV3, CanvasNodeContract } from '@workbench/canvas-engine/api';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { createListCollection, Flex, HStack, NumberInput } from '@chakra-ui/react';import { Select } from '@platform/ui';import { getDocumentIndex, isGroupNode } from '@workbench/canvas-engine/api';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';-import { applyStructuralPreview, CANVAS_BLEND_MODES } from '@workbench/widgets/layers/layerOps';+import { usePreparedCommit, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';+import { CANVAS_BLEND_MODES } from '@workbench/widgets/layers/layerOps';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -119,7 +119,7 @@ const OpacityRow = ({engine: LayerBlendRowEngine | null;layer: CanvasNodeContract | null;}) => {- const commitPrepared = usePreparedCommit(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const { t } = useTranslation();// Capture original opacity once and track latest writes outside render closures so same-event commits record// current values.@@ -156,7 +156,7 @@ const OpacityRow = ({}const next = clamp01(valueAsNumber / 100);if (- !applyStructuralPreview(engine, {+ !previewStructural({id: layer.id,patch: { opacity: next },type: 'updateCanvasLayer',@@ -170,7 +170,7 @@ const OpacityRow = ({pendingRef.current.latest = next;}},- [commitPending, engine, layer]+ [commitPending, previewStructural, layer]);// Commit on spinner release, arrow/page-key release, Enter, or typed-value blur.diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 583bd6059e..daf760424b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -10,8 +10,8 @@ import type {LayerStackMoveKind,RegionalGuidanceReferenceImage,} from '@workbench/canvas-engine/api';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { LucideIcon } from 'lucide-react';import type { ComponentProps, Dispatch, ReactNode } from 'react';@@ -39,10 +39,10 @@ import { useNotify } from '@workbench/useNotify';import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';import {useCanvasDocumentEditingLocked,- useCanvasRasterContentEpoch,+ useCanvasLayerPixelEpoch,useLayerThumbnailVersion,} from '@workbench/widgets/canvas/engineStoreHooks';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { reportLayerOperation, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import {ArrowRightLeftIcon,@@ -147,6 +147,7 @@ type LayerActionErrorStatus =| 'busy'| 'disabled'| 'empty'+ | 'failed'| 'locked'| 'missing'| 'not-ready'@@ -158,10 +159,11 @@ const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {busy: 'widgets.layers.actions.busy',disabled: 'widgets.layers.actions.disabled',empty: 'widgets.layers.actions.empty',+ failed: 'widgets.layers.actions.operationFailed',locked: 'widgets.layers.actions.locked',missing: 'widgets.layers.actions.missing','not-ready': 'widgets.layers.actions.notReady',- 'over-budget': 'widgets.layers.actions.notReady',+ 'over-budget': 'widgets.layers.actions.overBudget',unsupported: 'widgets.layers.actions.unsupported',};@@ -281,7 +283,7 @@ const LayerMenu = ({const canGroup = canGroupSelection(engine?.document.model() ?? null, actionTargets({ layer, selectedIds }));// Un-memoized on purpose, like `canGroup`: it reads live raster content// (`hasExportableLayerContent`), which the content epoch re-renders for.- useCanvasRasterContentEpoch(engine);+ useCanvasLayerPixelEpoch(engine);const mergeModel = engine?.document.model() ?? null;const mergeTargets = actionTargets({ layer, selectedIds });const canMerge =@@ -359,6 +361,10 @@ const LayerMenu = ({if (result.status === 'busy') {return;}+ if (result.status !== 'nothing') {+ reportLayerOperation(result.status, notify.error, t);+ return;+ }} catch {// Report rejected transactions in the menu; the document remains unchanged.}@@ -392,19 +398,31 @@ const LayerMenu = ({notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.groupActions.mergeNotReady'));} else if (result === 'over-budget') {notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.groupActions.mergeOverBudget'));+ } else if (result === 'failed') {+ notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.operationFailed'));}});}, [engine, layer, notify, selectedIds, t]);const handleMerge = useCallback(() => {- // Pixel work: engine-only, and not recorded on the undo history.- engine?.layers.mergeLayerDown(layer.id);- }, [engine, layer.id]);+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ const result = engine.layers.mergeLayerDown(layer.id);+ if (result !== 'merged') {+ throw makeStatusError(result);+ }+ }, [engine, layer.id, makeStatusError]);const handleRasterize = useCallback(() => {- // Rasterization records one undoable entry restoring the original parametric source.- engine?.layers.rasterizeLayer(layer.id);- }, [engine, layer.id]);+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ const result = engine.layers.rasterizeLayer(layer.id);+ if (result !== 'rasterized') {+ throw makeStatusError(result);+ }+ }, [engine, layer.id, makeStatusError]);const addCopy = useCallback((copied: CanvasLayerContract | null, label: string) => {@@ -646,10 +664,11 @@ const LayerMenu = ({if (!engine) {throw makeStatusError('not-ready');}- if ((await engine.layers.copyLayerToRaster(layer.id)) === null) {- throw new Error(t('widgets.layers.actions.copyFailed'));+ const result = await engine.layers.copyLayerToRaster(layer.id);+ if (result.status !== 'copied') {+ throw makeStatusError(result.status);}- }, [addCopy, engine, getActionLabel, layer, makeStatusError, t]);+ }, [addCopy, engine, getActionLabel, layer, makeStatusError]);const handleCopyToControl = useCallback(() => {if (layer.type === 'raster') {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsxindex 26146e1cf6..f9cf6b661b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationButton.tsx@@ -1,6 +1,6 @@import type { CanvasControlLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';import type { CanvasOperationCapability } from '@workbench/canvas-operations/api';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { Box } from '@chakra-ui/react';import { Button, Tooltip } from '@platform/ui';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsxindex 1ca43c3863..30cb1a5d88 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx@@ -5,7 +5,7 @@ import type {LayerStackKind,LayerStackMoveKind,} from '@workbench/canvas-engine/api';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { LucideIcon } from 'lucide-react';import type { ComponentProps } from 'react';@@ -14,7 +14,7 @@ import { MenuActionItem, MenuContent, RenameDialog } from '@platform/ui';import { collectSubtree, getDocumentIndex, isOverlayStack } from '@workbench/canvas-engine/api';import { publishLayerPanelSelection, useLayerPanelState } from '@workbench/layerPanelState';import { useNotify } from '@workbench/useNotify';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { reportLayerOperation, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';import {ArrowDownIcon,@@ -159,6 +159,10 @@ export const LayerGroupContextMenu = ({if (result.status === 'busy') {return;}+ if (result.status !== 'nothing') {+ reportLayerOperation(result.status, notify.error, t);+ return;+ }} catch {// The engine leaves the document unchanged on a rejected transaction.}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsxindex 5e89c093b8..789bff39ae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx@@ -5,12 +5,10 @@ import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps'import { createListCollection, HStack, Stack, Text } from '@chakra-ui/react';import { ColorPicker, Field, Select } from '@platform/ui';import { type ColorSamplerEngine, useColorSampler } from '@workbench/widgets/canvas/useColorSampler';-import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { type CanvasPreparedEngine, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { applyStructuralPreview } from './layerOps';-const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = ['solid','grid',@@ -30,7 +28,7 @@ interface LayerRegionSettingsProps {/** The regenerate region's dedicated Properties editor: its overlay fill color and style. */export const LayerRegionSettings = ({ engine, layer }: LayerRegionSettingsProps) => {const { t } = useTranslation();- const commitPrepared = usePreparedCommit(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const sampleColor = useColorSampler(engine);const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);const region = layer.inpaint;@@ -69,7 +67,7 @@ export const LayerRegionSettings = ({ engine, layer }: LayerRegionSettingsProps)return;}if (- !applyStructuralPreview(engine, {+ !previewStructural({config: {inpaint: { ...region, fill: { ...region.fill, color: hex } },layerType: 'raster',@@ -82,7 +80,7 @@ export const LayerRegionSettings = ({ engine, layer }: LayerRegionSettingsProps)}fillBeforeRef.current ??= region.fill;},- [engine, layer.id, region]+ [previewStructural, layer.id, region]);const handleColorChangeEnd = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsxindex 79e4a184b7..0b03a3a085 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx@@ -1,6 +1,6 @@import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { Dispatch } from 'react';import { getDocumentLeaves, getDocumentNode } from '@workbench/canvas-engine/api';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsxindex a989ec554b..b40d854294 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx@@ -1,8 +1,8 @@import type { CollisionDetection, DragEndEvent, DragMoveEvent, DragOverEvent, DragStartEvent } from '@dnd-kit/core';import type { CanvasDocumentContractV3, DocumentCommand, LayerStackKind } from '@workbench/canvas-engine/api';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { LayerPanelState, LayerSelectionModifiers } from '@workbench/layerPanelState';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { Dispatch, FocusEvent, KeyboardEvent, ReactNode } from 'react';import { Box, Text } from '@chakra-ui/react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsxindex 791b74a9b0..6fb1da41ae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx@@ -3,10 +3,10 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';import { Flex, Icon, Stack, Text } from '@chakra-ui/react';import { SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui/SegmentTabs';import { getDocumentIndex } from '@workbench/canvas-engine/api';+import { useCanvasEngine } from '@workbench/canvas-operations/react';import { setLayerPanelFilter, useLayerPanelState } from '@workbench/layerPanelState';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';-import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';import { LayersIcon } from 'lucide-react';import { useCallback, useEffect, useMemo, useState, type MouseEvent } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsxindex 8793f60664..5a74aac563 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.tsx@@ -4,12 +4,10 @@ import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps'import { Stack, Text } from '@chakra-ui/react';import { Field, Slider } from '@platform/ui';-import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { type CanvasPreparedEngine, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { applyStructuralPreview } from './layerOps';-/** Edit modifier magnitude here with one commit per gesture; tree rows own enabling and removal. */type MaskModifierKind = 'mask-noise' | 'mask-denoise';@@ -36,7 +34,7 @@ export const MaskModifierSettings = ({layer: CanvasInpaintMaskLayerContract;}) => {const { t } = useTranslation();- const commitPrepared = usePreparedCommit(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const field = FIELD_OF[kind];const modifier = layer[field];const beforeRef = useRef<typeof modifier | null>(null);@@ -51,11 +49,11 @@ export const MaskModifierSettings = ({layerType: 'inpaint_mask',[field]: field === 'noise' ? { ...modifier, level: next } : { ...modifier, limit: next },} as const;- if (applyStructuralPreview(engine, { config, id: layer.id, type: 'updateCanvasLayerConfig' })) {+ if (previewStructural({ config, id: layer.id, type: 'updateCanvasLayerConfig' })) {beforeRef.current ??= modifier;}},- [engine, field, layer.id, modifier]+ [previewStructural, field, layer.id, modifier]);const handleChangeEnd = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 756a6073a6..80e299e0a6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -15,14 +15,18 @@ import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilitiesimport { useExternalStoreSelector } from '@platform/state/selectors';import { Button, ColorPicker, Field, Select, Tooltip } from '@platform/ui';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { useNotify } from '@workbench/useNotify';import { armMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';import { type ColorSamplerEngine, useColorSampler } from '@workbench/widgets/canvas/useColorSampler';-import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import {+ type CanvasPreparedEngine,+ reportMaskEdit,+ useStructuralPreview,+} from '@workbench/widgets/canvas/useStructuralCommit';import { PaletteIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { applyStructuralPreview } from './layerOps';import { useSelectedModelBase } from './useSelectedModelBase';/** The regional-guidance fields patchable via `updateCanvasLayerConfig`. */@@ -58,7 +62,7 @@ interface RegionalGuidanceSettingsProps {*/export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {const { t } = useTranslation();- const commitPrepared = usePreparedCommit(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const sampleColor = useColorSampler(engine);const base = useSelectedModelBase();const showSyntaxHighlighting = useWorkbenchPreferenceSelector(@@ -177,7 +181,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst handleColorChange = useCallback((hex: string) => {if (- !applyStructuralPreview(engine, {+ !previewStructural({config: { layerType: 'regional_guidance', mask: { fill: { ...fill, color: hex } } },id: layer.id,type: 'updateCanvasLayerConfig',@@ -189,7 +193,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettfillBeforeRef.current = fill;}},- [engine, fill, layer.id]+ [previewStructural, fill, layer.id]);const handleArmTint = useCallback(() => armMaskTintTarget(layer.id), [layer.id]);@@ -212,9 +216,12 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett[commitFill, fill]);+ const notify = useNotify();const handleInvert = useCallback(() => {- engine?.layers.invertMask(layer.id);- }, [engine, layer.id]);+ if (engine) {+ reportMaskEdit(engine.layers.invertMask(layer.id), notify.error, t);+ }+ }, [engine, layer.id, notify, t]);const styleValue = useMemo(() => [fill.style], [fill.style]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsxindex 946aa1d8c4..018017d390 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx@@ -169,7 +169,7 @@ const FAILURE_KEYS: Record<Exclude<RunLayerWorkflowResult['status'], 'completed'locked: 'widgets.layers.runWorkflow.locked',missing: 'widgets.layers.runWorkflow.missing','not-ready': 'widgets.layers.runWorkflow.notReady',- 'over-budget': 'widgets.layers.runWorkflow.notReady',+ 'over-budget': 'widgets.layers.runWorkflow.overBudget',stale: 'widgets.layers.runWorkflow.stale',unsupported: 'widgets.layers.runWorkflow.unsupported',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex 4242dd3921..a4d5b32f88 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -6,11 +6,9 @@ import type {import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import {- applyStructuralPreview,- type CanvasStructuralEngine,canConvertRasterControl,canMergeLayerDown,convertRasterToControl,@@ -180,22 +178,6 @@ describe('canMergeLayerDown', () => {});});-describe('applyStructuralPreview', () => {- const action = { id: 'layer', patch: { opacity: 0.5 }, type: 'updateCanvasLayer' } as const;-- it('routes a live document edit through the engine guard', () => {- const applyPreview = vi.fn(() => false);- const engine = { layers: { applyStructuralPreview: applyPreview } } as unknown as CanvasStructuralEngine;-- expect(applyStructuralPreview(engine, action)).toBe(false);- expect(applyPreview).toHaveBeenCalledWith(action);- });-- it('refuses a live edit without an engine', () => {- expect(applyStructuralPreview(null, action)).toBe(false);- });-});-describe('createInpaintMaskLayer', () => {it('builds an empty inpaint mask with the legacy-default diagonal fill', () => {const layer = createInpaintMaskLayer('Inpaint Mask 1', 'm1');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 927a56ffc8..dce37c1628 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -12,8 +12,6 @@ import type {CanvasMaskFillContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,- CanvasLayerPreviewMutation,- CanvasStructuralEngine,RegionalGuidanceReferenceImage,Rect,} from '@workbench/canvas-engine/api';@@ -578,9 +576,3 @@ export const convertRasterControlLayer = (/** Whether the layers panel may offer merge-down for `layerId`; merging is pixel work, so it needs an engine. */export const canMergeLayerDown = (document: CanvasDocumentContractV3, layerId: string, hasEngine: boolean): boolean =>hasEngine && mergeDownEligibility(document, layerId).status === 'eligible';--/** Applies a guarded live edit without recording history until the interaction ends. */-export const applyStructuralPreview = (- engine: CanvasStructuralEngine | null,- action: CanvasLayerPreviewMutation-): boolean => engine?.layers.applyStructuralPreview(action) ?? false;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsxindex e128d9ec23..34651f7750 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx@@ -19,6 +19,7 @@ import { HsvWheelPicker } from '@platform/ui/HsvWheelPicker';import { Scrollable } from '@platform/ui/Scrollable';import { Tooltip } from '@platform/ui/Tooltip';import { getDocumentLayer } from '@workbench/canvas-engine/api';+import { useCanvasEngine } from '@workbench/canvas-operations/react';import { armMaskTintTarget, clearMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';import {useActiveColorCommands,@@ -27,7 +28,6 @@ import {} from '@workbench/widgets/canvas/color-system/useActiveColors';import { useMaskTintEditor, type MaskTintEditor } from '@workbench/widgets/canvas/color-system/useMaskTintEditor';import { FormNumberField } from '@workbench/widgets/canvas/tool-presentation/FormControls';-import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { ArrowLeftRightIcon, CircleIcon, PipetteIcon, RotateCcwIcon, SquareIcon } from 'lucide-react';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsxindex e2d3f61aeb..5601e8dadd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx@@ -2,8 +2,8 @@ import { chakra, Flex, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { IconButton } from '@platform/ui/Button';import { Scrollable } from '@platform/ui/Scrollable';import { Tooltip } from '@platform/ui/Tooltip';+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';import { useCanvasCanRedo, useCanvasCanUndo, useCanvasHistoryEpoch } from '@workbench/widgets/canvas/engineStoreHooks';-import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { Redo2Icon, Undo2Icon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsxindex 04bc380032..7c722183b9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx@@ -88,7 +88,7 @@ vi.mock('@workbench/WorkbenchContext', async () => {vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({useCanvasProjectMutationDispatch: () => () => true,}));-vi.mock('@workbench/widgets/canvas/useCanvasEngine', () => ({ useCanvasEngine: () => harness.engine }));+vi.mock('@workbench/canvas-operations/react', () => ({ useCanvasEngine: () => harness.engine }));import { SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui/SegmentTabs';import { clearMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsxindex d1e22961e9..38a63fc2fa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx@@ -1,9 +1,9 @@import type { CanvasDocumentContractV3, CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/api';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { Stack, Switch, Text } from '@chakra-ui/react';import { getDocumentNode } from '@workbench/canvas-engine/api';-import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';+import { useCanvasEngine } from '@workbench/canvas-operations/react';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { AdjustmentSettings } from '@workbench/widgets/layers/AdjustmentSettings';import { ControlLayerSettings } from '@workbench/widgets/layers/ControlLayerSettings';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsxindex bfdadec477..14b138b8ac 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx@@ -1,8 +1,8 @@import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from 'react';import { Box, chakra, Flex } from '@chakra-ui/react';-import { useCanvasRasterContentEpoch } from '@workbench/widgets/canvas/engineStoreHooks';-import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';+import { useCanvasLayerPixelEpoch } from '@workbench/widgets/canvas/engineStoreHooks';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -56,7 +56,7 @@ const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {const drag = useRef<AbortController | null>(null);const [hostSize, setHostSize] = useState<{ width: number; height: number }>({ height: 0, width: 0 });- const contentEpoch = useCanvasRasterContentEpoch(engine);+ const pixelEpoch = useCanvasLayerPixelEpoch(engine);const stacks = useActiveProjectSelector((project) => project.canvas.document.stacks);const docWidth = useActiveProjectSelector((project) => project.canvas.document.width);const docHeight = useActiveProjectSelector((project) => project.canvas.document.height);@@ -143,7 +143,7 @@ const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {}, []);useEffect(() => {scheduleRedraw();- }, [contentEpoch, stacks, frame, scheduleRedraw]);+ }, [pixelEpoch, stacks, frame, scheduleRedraw]);// Throttle DOM outline updates and let CSS interpolate between them.useEffect(() => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsxindex 8b266264b5..d6d8363e92 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx@@ -1,5 +1,6 @@import { Flex, Stack } from '@chakra-ui/react';import { Scrollable } from '@platform/ui/Scrollable';+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';import { useCanvasActiveTool, useCanvasOperation } from '@workbench/widgets/canvas/engineStoreHooks';import { PropertyGroup } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';@@ -7,7 +8,6 @@ import {OPERATION_PRESENTATION_ADAPTERS,TOOL_PRESENTATION_ADAPTERS,} from '@workbench/widgets/canvas/tool-presentation/toolAdapters';-import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useLayoutEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsxindex e667ebe0dc..41fa2d0ff2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx@@ -6,6 +6,7 @@ import { formatHexColor, normalizeHex, parseHexColor } from '@platform/ui/color'import { DEFAULT_COLOR_SWATCHES, recordRecentColor, useRecentColors } from '@platform/ui/colorPickerStore';import { Scrollable } from '@platform/ui/Scrollable';import { Tooltip } from '@platform/ui/Tooltip';+import { useCanvasEngine } from '@workbench/canvas-operations/react';import { MAX_COLOR_PALETTE_SIZE } from '@workbench/widgets/canvas/color-system/colorPair';import {useActiveColorCommands,@@ -14,7 +15,6 @@ import {useColorPalette,} from '@workbench/widgets/canvas/color-system/useActiveColors';import { useMaskTintEditor } from '@workbench/widgets/canvas/color-system/useMaskTintEditor';-import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';import { PlusIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsxindex bfede2167d..486480b030 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsx@@ -4,11 +4,11 @@ import { Flex, Stack, Text } from '@chakra-ui/react';import { Button } from '@platform/ui/Button';import { Scrollable } from '@platform/ui/Scrollable';import { getDocumentNode, lookupDocumentLeaf } from '@workbench/canvas-engine/api';+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';import { useCanvasHasFloatingSelection, useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';import { clampScalePercent, round2, wrapDegrees } from '@workbench/widgets/canvas/tool-options/geometryForm';import { FormNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/FormControls';import { PropertyControlRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';-import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback } from 'react';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.tsindex 39dea1ff59..2210fb3d2c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts@@ -2,8 +2,8 @@ import type { CanvasNodeContract } from '@workbench/canvas-engine/api';import { useModelsSelector } from '@features/models';import { getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/api';+import { useCanvasEngine } from '@workbench/canvas-operations/react';import { setLayerGroupExpanded } from '@workbench/layerPanelState';-import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';import { nextLayerName } from '@workbench/workbenchState';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsxindex 8a082c8d0e..6cde36f9a2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx@@ -1,5 +1,5 @@+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { WidgetCommandContribution, WidgetHotkeyContribution } from '@workbench/widgetContracts';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { act, createElement, type ReactElement } from 'react';import { createRoot, type Root } from 'react-dom/client';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.tsindex d7ba0b7f1c..7a94d57ff3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts@@ -1,5 +1,5 @@+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { WidgetCommandApi, WidgetHotkeyApi } from '@workbench/widgetContracts';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { useEffect, useEffectEvent } from 'react';import { useTranslation } from 'react-i18next';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.tsindex 0102e1da00..336782ed0e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts@@ -1,8 +1,8 @@-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { toaster } from '@platform/ui';import { publishLayerPanelSelection } from '@workbench/layerPanelState';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { reportLayerOperation, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -53,6 +53,14 @@ export const useLayerSelectionCommands = (if (result?.status === 'busy') {return;}+ if (result && result.status !== 'nothing') {+ reportLayerOperation(+ result.status,+ (title, description) => toaster.create({ description, title, type: 'warning' }),+ t+ );+ return;+ }} catch {// Reducer rejection is failure-atomic; surface the same actionable result as a refusal.}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.tsindex 86a755c3a0..3043bf1d3c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts@@ -1,5 +1,5 @@import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { LucideIcon } from 'lucide-react';import { toaster } from '@platform/ui';@@ -98,6 +98,8 @@ export const useLayerStackActions = (toaster.create({ title: t('widgets.layers.groupActions.mergeNotReady'), type: 'warning' });} else if (result === 'over-budget') {toaster.create({ title: t('widgets.layers.groupActions.mergeOverBudget'), type: 'warning' });+ } else if (result === 'failed') {+ toaster.create({ title: t('widgets.layers.actions.operationFailed'), type: 'error' });}});},