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): extract shared mutation substrate for controllers
joshistoastb2b62739a544
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.tsindex 69efbdc377..723671fcd1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts@@ -1,6 +1,7 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';+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 type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -33,8 +34,8 @@ export interface BooleanMergeControllerOptions {expectedReducer: () => boolean,expectedMirror: () => boolean) => void;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => unknown;- readonly installPrepared: (prepared: unknown) => void;+ readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;+ readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;}const modes: Record<BooleanRasterOperation, GlobalCompositeOperation> = {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.tsindex 6275b9377a..06449516c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts@@ -1,6 +1,7 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';+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 type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -20,8 +21,8 @@ export interface CopyLayerControllerOptions {readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;readonly createLayerId: () => string;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => unknown;- readonly installPrepared: (prepared: unknown) => void;+ readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;+ readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;readonly dispatchPrepared: (action: CanvasProjectMutation,expectedReducer: () => boolean,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.tsindex b717754920..f7919a8840 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@ -5,6 +5,7 @@ import type {CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';import type { History } from '@workbench/canvas-engine/history/history';+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 type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -42,8 +43,8 @@ export interface CropLayerControllerOptions {layer: CanvasLayerContract,document: CanvasDocumentContractV2) => PixelSnapshot | null | 'not-ready';- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => unknown;- readonly installPrepared: (prepared: unknown) => void;+ readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;+ readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;readonly discardPersisted: (layerId: string) => void;readonly dispatchPrepared: (action: CanvasProjectMutation,@@ -128,7 +129,7 @@ export class CropLayerController {} else {after = { ...before, mask: { ...before.mask, bitmap: null, offset: paint.offset }, transform: identity };}- const publish = (contract: CanvasLayerContract, prepared: unknown): void => {+ const publish = (contract: CanvasLayerContract, prepared: PreparedLayerCacheReplacement): void => {this.deps.dispatchPrepared({ layer: contract, layerId, type: 'replaceCanvasLayer' },() => this.deps.getReducerDocument()?.layers.find((candidate) => candidate.id === layerId) === contract,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.tsindex 00ac84789c..13a64d36a3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts@@ -3,7 +3,11 @@ import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/cimport type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { History } from '@workbench/canvas-engine/history/history';import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';-import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type {+ LayerCacheEntry,+ LayerCacheStore,+ 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 type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -40,8 +44,8 @@ export interface ExtractMaskedAreaControllerOptions {readonly getAdjustedSurface: (layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null;readonly getMaskPattern: (style: string, color: string) => RasterSurface | null;readonly createLayerId: () => string;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => unknown;- readonly installPrepared: (prepared: unknown) => void;+ readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;+ readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;readonly dispatchPrepared: (action: CanvasProjectMutation,expectedReducer: () => boolean,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.tsindex 87e3a12428..7bdebffa69 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts@@ -1,8 +1,4 @@-import type {- CommitRasterFilterOptions,- CommitRasterFilterResult,- LayerExportGuard,-} from '@workbench/canvas-engine/capabilities';+import type { CommitRasterFilterOptions, CommitRasterFilterResult } from '@workbench/canvas-engine/capabilities';import type {CanvasDocumentContractV2,CanvasImageRef,@@ -11,15 +7,15 @@ import type {} from '@workbench/canvas-engine/contracts';import type { CapturedLayerCache } from '@workbench/canvas-engine/controllers/layerMutationController';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';-import type { History } from '@workbench/canvas-engine/history/history';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 type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { createControlLayer } from '@workbench/canvas-engine/document/layerFactories';import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';+import type { CanvasMutationContext } from './mutationContext';+export type {CommitRasterFilterOptions,CommitRasterFilterResult,@@ -27,10 +23,9 @@ export type {RasterFilterSettings,} from '@workbench/canvas-engine/capabilities';-export interface FilterResultControllerOptions<Permit, Owner = symbol> {+export interface FilterResultControllerOptions {readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;- readonly capturePermit: (owner?: Owner) => Permit | null;- readonly createLayerId: () => string;+ readonly ctx: CanvasMutationContext;readonly decodeImage: (image: CanvasImageRef,options: {@@ -41,31 +36,17 @@ export interface FilterResultControllerOptions<Permit, Owner = symbol> {}) => Promise<DecodeImageResult>;readonly discardPersisted: (layerId: string) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- reducerAccepted: () => boolean,- mirrorAccepted: () => boolean- ) => void;- readonly endBurst: () => void;- readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getMainModelBase: () => string | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly history: History;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;- readonly isGestureActive: () => boolean;- readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;- readonly isPermitCurrent: (permit: Permit) => boolean;readonly needsPixelPersistence: (layer: CanvasLayerContract) => boolean;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;}/** Publishes guarded filter results as replacements or independent copies. */-export class FilterResultController<Permit, Owner = symbol> {- constructor(private readonly options: FilterResultControllerOptions<Permit, Owner>) {}+export class FilterResultController {+ constructor(private readonly options: FilterResultControllerOptions) {}- async commit(options: CommitRasterFilterOptions, owner?: Owner): Promise<CommitRasterFilterResult> {+ async commit(options: CommitRasterFilterOptions, owner?: symbol): Promise<CommitRasterFilterResult> {const o = this.options;- const permit = o.capturePermit(owner);+ const permit = o.ctx.capturePermit(owner);if (!permit) {return { status: 'busy' };}@@ -74,7 +55,7 @@ export class FilterResultController<Permit, Owner = symbol> {}try {const decoded = await o.decodeImage(options.image, {- isCurrent: () => o.isPermitCurrent(permit),+ isCurrent: () => o.ctx.isPermitCurrent(permit),scaleToImage: false,signal: options.signal,validateDecoded: (width, height) => {@@ -94,7 +75,7 @@ export class FilterResultController<Permit, Owner = symbol> {return { status: decoded.status === 'aborted' ? 'aborted' : 'busy' };}const pixels = decoded.surface;- const document = o.getDocument();+ const document = o.ctx.getDocument();const liveLayer = document?.layers.find((candidate) => candidate.id === options.guard.layerId);if (!document || !liveLayer) {return { status: 'missing' };@@ -105,16 +86,16 @@ export class FilterResultController<Permit, Owner = symbol> {if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {return { status: 'unsupported' };}- if (!o.isPermitCurrent(permit) || o.isGestureActive()) {+ if (!o.ctx.isPermitCurrent(permit) || o.ctx.isGestureActive()) {return { status: 'busy' };}- if (!o.isGuardCurrent(options.guard)) {+ if (!o.ctx.isGuardCurrent(options.guard)) {return { status: 'stale' };}if (options.signal?.aborted) {return { status: 'aborted' };}- o.endBurst();+ 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;@@ -137,10 +118,10 @@ export class FilterResultController<Permit, Owner = symbol> {prepared: PreparedLayerCacheReplacement,publishOptions: { discardPersistence: boolean; persist: boolean }): void => {- o.dispatchPrepared(+ o.ctx.dispatchPrepared({ layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },- () => o.getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,- () => o.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract+ () => o.ctx.getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,+ () => o.ctx.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract);if (publishOptions.discardPersistence) {try {@@ -149,15 +130,15 @@ export class FilterResultController<Permit, Owner = symbol> {/* Ancillary after commit. */}}- o.installPrepared(prepared, publishOptions.persist);+ o.ctx.installPrepared(prepared, publishOptions.persist);};const apply = (contract: CanvasLayerContract,snapshot: { pixels: RasterSurface; rect: Rect },publishOptions: { discardPersistence: boolean; persist: boolean }- ): void => publish(contract, o.preparePixels(liveLayer.id, snapshot.rect, snapshot.pixels), publishOptions);- publish(after, o.preparePixels(liveLayer.id, rect, pixels), { discardPersistence: true, persist: false });- o.history.push({+ ): 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,label: 'Replace layer with filter result',redo: () => apply(after, afterPixels, { discardPersistence: true, persist: false }),@@ -172,7 +153,7 @@ export class FilterResultController<Permit, Owner = symbol> {return { status: 'missing' };}const selectedLayerId = document.selectedLayerId;- const layerId = o.createLayerId();+ const layerId = o.ctx.createLayerId();let copy: CanvasLayerContract;if (options.target === 'control') {const base =@@ -212,30 +193,30 @@ export class FilterResultController<Permit, Owner = symbol> {};}const apply = (): void => {- const prepared = o.preparePixels(layerId, rect, pixels);- o.dispatchPrepared(+ const prepared = o.ctx.preparePixels(layerId, rect, pixels);+ o.ctx.dispatchPrepared({ index: sourceIndex, layer: copy, type: 'addCanvasLayer' },- () => o.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,- () => o.getDocument()?.layers.some((candidate) => candidate === copy) === true+ () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,+ () => o.ctx.getDocument()?.layers.some((candidate) => candidate === copy) === true);- o.installPrepared(prepared, false);+ o.ctx.installPrepared(prepared, false);};apply();- o.history.push({+ o.ctx.history.push({bytes: rect.width * rect.height * 4 + 256,label: 'Copy layer filter result',redo: apply,replayFailureAtomic: true,undo: () => {- o.dispatchPrepared(+ o.ctx.dispatchPrepared({ id: selectedLayerId, type: 'setCanvasSelectedLayer' },- () => o.getReducerDocument()?.selectedLayerId === selectedLayerId,- () => o.getDocument()?.selectedLayerId === selectedLayerId+ () => o.ctx.getReducerDocument()?.selectedLayerId === selectedLayerId,+ () => o.ctx.getDocument()?.selectedLayerId === selectedLayerId);- o.dispatchPrepared(+ o.ctx.dispatchPrepared({ ids: [layerId], type: 'removeCanvasLayers' },- () => o.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,- () => o.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,+ () => o.ctx.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false);},});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.tsindex 5d9216c62d..85cffba686 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts@@ -1,55 +1,36 @@-import type {- CommitGeneratedImageOptions,- CommitGeneratedImageResult,- LayerExportGuard,-} from '@workbench/canvas-engine/capabilities';+import type { CommitGeneratedImageOptions, CommitGeneratedImageResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { CapturedLayerCache } from '@workbench/canvas-engine/controllers/layerMutationController';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';-import type { History } from '@workbench/canvas-engine/history/history';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 type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { createControlLayer, nextControlLayerName } from '@workbench/canvas-engine/document/layerFactories';-export interface GeneratedResultControllerOptions<Permit, Owner = symbol> {+import type { CanvasMutationContext } from './mutationContext';++export interface GeneratedResultControllerOptions {readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;- readonly capturePermit: (owner?: Owner) => Permit | null;readonly clearPreview: (layerId: string) => void;- readonly createLayerId: () => string;+ readonly ctx: CanvasMutationContext;readonly decodeImage: (image: CanvasImageRef,options: { signal?: AbortSignal; isCurrent?: () => boolean }) => Promise<DecodeImageResult>;readonly discardPersisted: (layerId: string) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- reducerAccepted: () => boolean,- mirrorAccepted: () => boolean- ) => void;- readonly endBurst: () => void;- readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getMainModelBase: () => string | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly history: History;- readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;- readonly isGestureActive: () => boolean;- readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;- readonly isPermitCurrent: (permit: Permit) => boolean;readonly needsPixelPersistence: (layer: CanvasLayerContract) => boolean;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;}/** Publishes guarded workflow/SAM images as replacements or copies. */-export class GeneratedResultController<Permit, Owner = symbol> {- constructor(private readonly options: GeneratedResultControllerOptions<Permit, Owner>) {}+export class GeneratedResultController {+ constructor(private readonly options: GeneratedResultControllerOptions) {}- async commit(options: CommitGeneratedImageOptions, owner?: Owner): Promise<CommitGeneratedImageResult> {+ async commit(options: CommitGeneratedImageOptions, owner?: symbol): Promise<CommitGeneratedImageResult> {const o = this.options;- const permit = o.capturePermit(owner);+ const permit = o.ctx.capturePermit(owner);if (!permit) {return { status: 'busy' };}@@ -59,10 +40,10 @@ export class GeneratedResultController<Permit, Owner = symbol> {const validate = ():| { document: CanvasDocumentContractV2; liveLayer: Extract<CanvasLayerContract, { type: 'raster' | 'control' }> }| { result: CommitGeneratedImageResult } => {- if (!o.isPermitCurrent(permit)) {+ if (!o.ctx.isPermitCurrent(permit)) {return { result: { status: 'busy' } };}- const document = o.getDocument();+ const document = o.ctx.getDocument();if (!document) {return { result: { status: 'missing' } };}@@ -76,17 +57,17 @@ export class GeneratedResultController<Permit, Owner = symbol> {if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {return { result: { status: 'unsupported' } };}- if (o.isGestureActive()) {+ if (o.ctx.isGestureActive()) {return { result: { status: 'busy' } };}- if (!o.isGuardCurrent(options.guard)) {+ if (!o.ctx.isGuardCurrent(options.guard)) {return { result: { status: 'stale' } };}return { document, liveLayer };};try {const decoded = await o.decodeImage(options.image, {- isCurrent: () => o.isPermitCurrent(permit),+ isCurrent: () => o.ctx.isPermitCurrent(permit),signal: options.signal,});if (decoded.status !== 'ok') {@@ -107,10 +88,10 @@ export class GeneratedResultController<Permit, Owner = symbol> {prepared: PreparedLayerCacheReplacement,publishOptions: { discardPersistence: boolean; persist: boolean }): void => {- o.dispatchPrepared(+ o.ctx.dispatchPrepared({ layer: contract, layerId: liveLayer.id, type: 'replaceCanvasLayer' },- () => o.getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,- () => o.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract+ () => o.ctx.getReducerDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract,+ () => o.ctx.getDocument()?.layers.find((candidate) => candidate.id === liveLayer.id) === contract);if (publishOptions.discardPersistence) {try {@@ -124,14 +105,14 @@ export class GeneratedResultController<Permit, Owner = symbol> {} catch {/* Transient preview is ancillary. */}- o.installPrepared(prepared, publishOptions.persist);+ o.ctx.installPrepared(prepared, publishOptions.persist);};const applySnapshot = (contract: CanvasLayerContract,snapshot: { pixels: RasterSurface; rect: Rect },publishOptions: { discardPersistence: boolean; persist: boolean }): void =>- publishSnapshot(contract, o.preparePixels(liveLayer.id, snapshot.rect, snapshot.pixels), publishOptions);+ 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') {@@ -149,7 +130,7 @@ export class GeneratedResultController<Permit, Owner = symbol> {after = { ...structuredClone(liveLayer), source, transform: identityTransform };}const afterPixels = { pixels: decoded.surface, rect };- const prepared = o.preparePixels(liveLayer.id, rect, decoded.surface);+ const prepared = o.ctx.preparePixels(liveLayer.id, rect, decoded.surface);if (options.signal?.aborted) {return { status: 'aborted' };}@@ -157,9 +138,9 @@ export class GeneratedResultController<Permit, Owner = symbol> {if ('result' in finalCheck) {return finalCheck.result;}- o.endBurst();+ o.ctx.endBurst();publishSnapshot(after, prepared, { discardPersistence: true, persist: false });- o.history.push({+ o.ctx.history.push({bytes: beforePixels.rect.width * beforePixels.rect.height * 4 + rect.width * rect.height * 4 + 256,label: options.historyLabel ?? 'Replace layer with workflow result',redo: () => applySnapshot(after, afterPixels, { discardPersistence: true, persist: false }),@@ -176,7 +157,7 @@ export class GeneratedResultController<Permit, Owner = symbol> {if (sourceIndex < 0) {return { status: 'missing' };}- const layerId = o.createLayerId();+ const layerId = o.ctx.createLayerId();const selectedLayerId = document.selectedLayerId;const copy: CanvasLayerContract =options.target === 'copy-control'@@ -201,15 +182,15 @@ export class GeneratedResultController<Permit, Owner = symbol> {type: 'raster',};const publishCopy = (prepared: PreparedLayerCacheReplacement): void => {- o.dispatchPrepared(+ o.ctx.dispatchPrepared({ index: sourceIndex, layer: copy, type: 'addCanvasLayer' },- () => o.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,- () => o.getDocument()?.layers.some((candidate) => candidate === copy) === true+ () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,+ () => o.ctx.getDocument()?.layers.some((candidate) => candidate === copy) === true);- o.installPrepared(prepared, false);+ o.ctx.installPrepared(prepared, false);};- const applyCopy = (): void => publishCopy(o.preparePixels(layerId, rect, decoded.surface));- const prepared = o.preparePixels(layerId, rect, decoded.surface);+ 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' };}@@ -217,9 +198,9 @@ export class GeneratedResultController<Permit, Owner = symbol> {if ('result' in finalCheck) {return finalCheck.result;}- o.endBurst();+ o.ctx.endBurst();publishCopy(prepared);- o.history.push({+ o.ctx.history.push({bytes: rect.width * rect.height * 4 + 256,label:options.target === 'copy-control'@@ -228,15 +209,15 @@ export class GeneratedResultController<Permit, Owner = symbol> {redo: applyCopy,replayFailureAtomic: true,undo: () => {- o.dispatchPrepared(+ o.ctx.dispatchPrepared({ id: selectedLayerId, type: 'setCanvasSelectedLayer' },- () => o.getReducerDocument()?.selectedLayerId === selectedLayerId,- () => o.getDocument()?.selectedLayerId === selectedLayerId+ () => o.ctx.getReducerDocument()?.selectedLayerId === selectedLayerId,+ () => o.ctx.getDocument()?.selectedLayerId === selectedLayerId);- o.dispatchPrepared(+ o.ctx.dispatchPrepared({ ids: [layerId], type: 'removeCanvasLayers' },- () => o.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,- () => o.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false+ () => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,+ () => o.ctx.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false);},});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 9ac7241f41..0c2546c6bf 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@@ -59,25 +59,13 @@ describe('LayerController', () => {const merge = {backend: {} as never,canEdit: () => true,- capturePermit: () => null,- createLayerId: () => 'merged',- dispatch: vi.fn(),- dispatchPrepared: vi.fn(),- endBurst: vi.fn(),+ ctx: {} as never,exportBaked: vi.fn(),- getDocument: () => null,- getReducerDocument: () => null,hasExportableContent: () => false,- history: {} as never,- installPrepared: vi.fn(),isCacheReady: () => true,- isGestureActive: () => false,- isGuardCurrent: () => true,- isPermitCurrent: () => true,layers: {} as never,markDirty: vi.fn(),notifyPainted: vi.fn(),- preparePixels: vi.fn(),};const booleanMerge = {backend: {} as never,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.tsindex dcab58d733..a48cf86ba8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts@@ -1,10 +1,8 @@import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';-import type { History } from '@workbench/canvas-engine/history/history';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';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';import { getMergeVisibleRasterLayers } from '@workbench/canvas-engine/document/mergeVisible';@@ -12,6 +10,8 @@ import { isMergeableRasterLayer } from '@workbench/canvas-engine/document/sourceimport { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { blendToComposite } from '@workbench/canvas-engine/render/compositor';+import type { CanvasMutationContext } from './mutationContext';+export type MergeVisibleResult = 'merged' | 'not-ready' | 'busy' | 'nothing';type ExportResult =@@ -20,28 +20,12 @@ type ExportResult =export interface MergeLayerControllerOptions {readonly backend: RasterBackend;- readonly history: History;+ readonly ctx: CanvasMutationContext;readonly layers: LayerCacheStore;- readonly getDocument: () => CanvasDocumentContractV2 | null;- readonly getReducerDocument: () => CanvasDocumentContractV2 | null;readonly canEdit: () => boolean;- readonly capturePermit: () => object | null;- readonly isPermitCurrent: (permit: object) => boolean;- readonly isGestureActive: () => boolean;readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => boolean;readonly hasExportableContent: (layerId: string) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;- readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;- readonly createLayerId: () => string;- readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => unknown;- readonly installPrepared: (prepared: unknown) => void;- readonly dispatchPrepared: (- action: CanvasProjectMutation,- expectedReducer: () => boolean,- expectedMirror: () => boolean- ) => void;- readonly endBurst: () => void;- readonly dispatch: (action: CanvasProjectMutation) => void;readonly notifyPainted: (layerId: string) => void;readonly markDirty: (layerId: string) => void;}@@ -53,11 +37,11 @@ export class MergeLayerController {constructor(private readonly deps: MergeLayerControllerOptions) {}mergeDown(upperLayerId: string): boolean {- if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {+ if (this.disposed || !this.deps.canEdit() || this.deps.ctx.isGestureActive()) {return false;}- this.deps.endBurst();- const document = this.deps.getDocument();+ this.deps.ctx.endBurst();+ const document = this.deps.ctx.getDocument();if (!document) {return false;}@@ -84,7 +68,7 @@ export class MergeLayerController {return false;}if (!belowHasContent && !upperHasContent) {- this.deps.dispatch({+ this.deps.ctx.dispatch({source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },type: 'mergeCanvasLayersDown',upperLayerId,@@ -121,7 +105,7 @@ export class MergeLayerController {context.globalAlpha = 1;context.globalCompositeOperation = 'source-over';}- this.deps.dispatch({+ this.deps.ctx.dispatch({source: { bitmap: null, offset: { x: mergedRect.x, y: mergedRect.y }, type: 'paint' },type: 'mergeCanvasLayersDown',upperLayerId,@@ -136,12 +120,12 @@ export class MergeLayerController {}async mergeVisible(): Promise<MergeVisibleResult> {- const permit = this.deps.capturePermit();- if (this.disposed || !permit || !this.deps.canEdit() || this.deps.isGestureActive()) {+ const permit = this.deps.ctx.capturePermit();+ if (this.disposed || !permit || !this.deps.canEdit() || this.deps.ctx.isGestureActive()) {return 'busy';}- this.deps.endBurst();- const document = this.deps.getDocument();+ this.deps.ctx.endBurst();+ const document = this.deps.ctx.getDocument();if (!document) {return 'nothing';}@@ -164,13 +148,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.isPermitCurrent(permit)) {+ if (!this.deps.ctx.isPermitCurrent(permit)) {return 'busy';}if (exports.some((result) => result.status !== 'ok')) {return 'not-ready';}- if (this.deps.isGestureActive()) {+ if (this.deps.ctx.isGestureActive()) {return 'busy';}for (let index = 0; index < exports.length; index += 1) {@@ -181,13 +165,13 @@ export class MergeLayerController {exported.status !== 'ok' ||!contributor ||exported.guard.layer !== contributor ||- !this.deps.isGuardCurrent(exported.guard)+ !this.deps.ctx.isGuardCurrent(exported.guard)) {return 'not-ready';}}- const liveDocument = this.deps.getDocument();+ const liveDocument = this.deps.ctx.getDocument();const liveContributors = liveDocument? getMergeVisibleRasterLayers(liveDocument.layers, this.deps.hasExportableContent): [];@@ -222,7 +206,7 @@ export class MergeLayerController {context.globalAlpha = 1;context.globalCompositeOperation = 'source-over';- const resultId = this.deps.createLayerId();+ const resultId = this.deps.ctx.createLayerId();const resultLayer: CanvasLayerContract = {blendMode: 'normal',id: resultId,@@ -238,37 +222,37 @@ export class MergeLayerController {const hasResult = (doc: CanvasDocumentContractV2 | null): boolean =>doc?.selectedLayerId === resultId && doc.layers[0] === resultLayer;const apply = (): void => {- const prepared = this.deps.preparePixels(resultId, rect, pixels);- this.deps.dispatchPrepared(+ const prepared = this.deps.ctx.preparePixels(resultId, rect, pixels);+ this.deps.ctx.dispatchPrepared({add: { index: 0, layers: [resultLayer] },enabledUpdates: [],selectedLayerId: resultId,type: 'applyCanvasLayerStackMutation',},- () => hasResult(this.deps.getReducerDocument()),- () => hasResult(this.deps.getDocument())+ () => hasResult(this.deps.ctx.getReducerDocument()),+ () => hasResult(this.deps.ctx.getDocument()));- this.deps.installPrepared(prepared);+ this.deps.ctx.installPrepared(prepared);};- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.ctx.isPermitCurrent(permit)) {return 'busy';}apply();- this.deps.history.push({+ this.deps.ctx.history.push({bytes: rect.width * rect.height * 4 + 256,label: 'Merge visible',redo: apply,replayFailureAtomic: true,undo: () =>- this.deps.dispatchPrepared(+ this.deps.ctx.dispatchPrepared({ enabledUpdates: [], removeIds: [resultId], selectedLayerId, type: 'applyCanvasLayerStackMutation' },() =>- this.deps.getReducerDocument()?.selectedLayerId === selectedLayerId &&- this.deps.getReducerDocument()?.layers.some((layer) => layer.id === resultId) === false,+ this.deps.ctx.getReducerDocument()?.selectedLayerId === selectedLayerId &&+ this.deps.ctx.getReducerDocument()?.layers.some((layer) => layer.id === resultId) === false,() =>- this.deps.getDocument()?.selectedLayerId === selectedLayerId &&- this.deps.getDocument()?.layers.some((layer) => layer.id === resultId) === false+ this.deps.ctx.getDocument()?.selectedLayerId === selectedLayerId &&+ this.deps.ctx.getDocument()?.layers.some((layer) => layer.id === resultId) === false),});return 'merged';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.tsnew file mode 100644index 0000000000..31c245f266--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts@@ -0,0 +1,270 @@+import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';++import { createHistory } from '@workbench/canvas-engine/history/history';+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;+ setLocked(next: boolean): void;+}++const createLockStore = (): LockStore => {+ let locked = false;+ const listeners: (() => void)[] = [];+ return {+ get: () => locked,+ setLocked: (next) => {+ locked = next;+ for (const listener of listeners.slice()) {+ listener();+ }+ },+ subscribe: (listener) => {+ listeners.push(listener);+ return () => {+ const index = listeners.indexOf(listener);+ if (index >= 0) {+ listeners.splice(index, 1);+ }+ };+ },+ };+};++const createHarness = (overrides: Partial<CanvasMutationContextDeps> = {}) => {+ const lock = createLockStore();+ const editOwner = Symbol('test-edit-owner');+ const deps: CanvasMutationContextDeps = {+ createLayerId: () => 'layer-new',+ dispatch: vi.fn(() => true),+ editOwner,+ editingLocked: lock,+ endBurst: () => undefined,+ getDocument: () => null,+ getReducerDocument: () => null,+ history: createHistory(),+ installPrepared: () => undefined,+ isGestureActive: () => false,+ isGuardCurrent: () => true,+ preparePixels: (layerId, rect) => ({ layerId, rect, surface: {} }) as PreparedLayerCacheReplacement,+ refreshMirror: vi.fn(),+ ...overrides,+ };+ const context = createCanvasMutationContext(deps);+ return { context, deps, editOwner, lock };+};++describe('createCanvasMutationContext', () => {+ describe('document edit permits', () => {+ it('captures a permit while unlocked and keeps it current until the lock transitions', () => {+ const { context } = createHarness();+ const permit = context.capturePermit();+ expect(permit).not.toBeNull();+ expect(context.canEdit()).toBe(true);+ expect(context.isPermitCurrent(permit!)).toBe(true);+ });++ it('refuses anonymous permits while locked but grants them to the edit owner', () => {+ const { context, editOwner, lock } = createHarness();+ lock.setLocked(true);+ expect(context.canEdit()).toBe(false);+ expect(context.capturePermit()).toBeNull();+ expect(context.capturePermit(Symbol('someone-else'))).toBeNull();+ expect(context.canEdit(editOwner)).toBe(true);+ expect(context.capturePermit(editOwner)).not.toBeNull();+ });++ it('invalidates an anonymous permit after the lock toggles on and back off', () => {+ const { context, lock } = createHarness();+ const permit = context.capturePermit()!;+ lock.setLocked(true);+ lock.setLocked(false);+ expect(context.canEdit()).toBe(true);+ expect(context.isPermitCurrent(permit)).toBe(false);+ });++ it('reports anonymous permits stale while the lock is held', () => {+ const { context, lock } = createHarness();+ const permit = context.capturePermit()!;+ lock.setLocked(true);+ expect(context.isPermitCurrent(permit)).toBe(false);+ });++ it('keeps an owner-held permit current across lock transitions', () => {+ const { context, editOwner, lock } = createHarness();+ const permit = context.capturePermit(editOwner)!;+ lock.setLocked(true);+ expect(context.isPermitCurrent(permit)).toBe(true);+ lock.setLocked(false);+ expect(context.isPermitCurrent(permit)).toBe(true);+ });+ });++ describe('dispatchPrepared', () => {+ it('throws when dispatch rejects the mutation and the reducer shows no postcondition', () => {+ const { context } = createHarness({ dispatch: () => false });+ expect(() =>+ context.dispatchPrepared(+ action,+ () => false,+ () => false+ )+ ).toThrow('Canvas document mutation was rejected');+ });++ 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;+ },+ });+ expect(() =>+ context.dispatchPrepared(+ action,+ () => false,+ () => true+ )+ ).toThrow(failure);+ });++ it('swallows a dispatch error when the mutation is applied and mirrored', () => {+ const failure = new Error('subscriber exploded');+ const refreshMirror = vi.fn();+ const { context } = createHarness({+ dispatch: () => {+ throw failure;+ },+ refreshMirror,+ });+ expect(() =>+ context.dispatchPrepared(+ action,+ () => true,+ () => true+ )+ ).not.toThrow();+ expect(refreshMirror).toHaveBeenCalledTimes(1);+ });++ 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;+ });+ const { context } = createHarness({+ dispatch: () => {+ throw failure;+ },+ refreshMirror,+ });+ expect(() =>+ context.dispatchPrepared(+ action,+ () => true,+ () => mirrored+ )+ ).not.toThrow();+ expect(refreshMirror).toHaveBeenCalledTimes(1);+ });++ it('rethrows the original dispatch error when the mirror never converges', () => {+ const failure = new Error('subscriber exploded');+ const refreshMirror = vi.fn();+ const { context } = createHarness({+ dispatch: () => {+ throw failure;+ },+ refreshMirror,+ });+ expect(() =>+ context.dispatchPrepared(+ action,+ () => true,+ () => false+ )+ ).toThrow(failure);+ expect(refreshMirror).toHaveBeenCalledTimes(1);+ });++ 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');+ });+ const { context } = createHarness({+ dispatch: () => {+ throw failure;+ },+ refreshMirror,+ });+ expect(() =>+ context.dispatchPrepared(+ action,+ () => true,+ () => mirrored+ )+ ).not.toThrow();+ });++ 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');+ });++ 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('accepts an unmirrored mutation once the mirror refresh converges', () => {+ let mirrored = false;+ const refreshMirror = vi.fn(() => {+ mirrored = true;+ });+ const { context } = createHarness({ refreshMirror });+ expect(() =>+ context.dispatchPrepared(+ action,+ () => true,+ () => mirrored+ )+ ).not.toThrow();+ expect(refreshMirror).toHaveBeenCalledTimes(1);+ });+ });++ describe('dispose', () => {+ it('stops tracking lock transitions so pre-dispose permits stay current', () => {+ const { context, lock } = createHarness();+ const permit = context.capturePermit()!;+ context.dispose();+ lock.setLocked(true);+ lock.setLocked(false);+ expect(context.isPermitCurrent(permit)).toBe(true);+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.tsnew file mode 100644index 0000000000..136c4afb9f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts@@ -0,0 +1,158 @@+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';+import type { History } from '@workbench/canvas-engine/history/history';+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 type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';++/**+ * A claim on the current document-edit epoch. Captured before an async+ * operation and re-checked ({@link CanvasMutationContext.isPermitCurrent})+ * before publishing its result: any editing-lock transition in between bumps+ * the epoch and invalidates outstanding permits. A permit captured with the+ * engine's own edit-owner symbol bypasses the lock (the lock holder may edit).+ */+export interface DocumentEditPermit {+ readonly epoch: number;+ readonly owner?: symbol;+}++/**+ * The shared mutation substrate handed to canvas controllers: the guarded+ * document-mutation protocol (edit permits, prepared-cache dispatch with+ * reducer/mirror postconditions, layer-cache replacement install), plus the+ * small set of engine services every mutating controller needs.+ */+export interface CanvasMutationContext {+ readonly history: History;+ getDocument(): CanvasDocumentContractV2 | null;+ getReducerDocument(): CanvasDocumentContractV2 | null;+ canEdit(owner?: symbol): boolean;+ capturePermit(owner?: symbol): DocumentEditPermit | null;+ isPermitCurrent(permit: DocumentEditPermit): boolean;+ isGuardCurrent(guard: LayerExportGuard): boolean;+ dispatch(action: CanvasProjectMutation): boolean;+ dispatchPrepared(action: CanvasProjectMutation, reducerAccepted: () => boolean, mirrorAccepted: () => boolean): void;+ preparePixels(layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement;+ installPrepared(prepared: PreparedLayerCacheReplacement, persist?: boolean): void;+ endBurst(): void;+ isGestureActive(): boolean;+ createLayerId(): string;+}++/** Engine-side wiring for {@link createCanvasMutationContext}. */+export interface CanvasMutationContextDeps {+ readonly history: History;+ readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getReducerDocument: () => CanvasDocumentContractV2 | null;+ readonly dispatch: (action: CanvasProjectMutation) => boolean;+ readonly refreshMirror: () => void;+ readonly editingLocked: { get(): boolean; subscribe(listener: () => void): () => void };+ readonly editOwner: symbol;+ 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 isGestureActive: () => boolean;+ readonly createLayerId: () => string;+}++/**+ * Creates the shared mutation substrate. Owns the document-edit permit epoch+ * machine (subscribed to the editing-lock store until {@link dispose}) and the+ * prepared-mutation dispatch postcondition protocol; everything else delegates+ * to the engine through `deps`.+ */+export const createCanvasMutationContext = (+ deps: CanvasMutationContextDeps+): CanvasMutationContext & { dispose(): void } => {+ let documentEditEpoch = 0;+ let documentEditingLocked = false;+ const syncDocumentEditingLock = (): void => {+ const nextLocked = deps.editingLocked.get();+ if (nextLocked !== documentEditingLocked) {+ documentEditingLocked = nextLocked;+ documentEditEpoch += 1;+ }+ };+ const unsubscribeDocumentEditingLock = deps.editingLocked.subscribe(syncDocumentEditingLock);+ const canEdit = (owner?: symbol): boolean => 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+ ): void => {+ try {+ if (!deps.dispatch(action)) {+ throw new Error('Canvas document mutation was rejected');+ }+ } catch (error) {+ // Store subscribers run after the reducer has accepted an action. A+ // faulty observer must not strand an applied document mutation before+ // its matching engine state and history are published. Preserve real+ // reducer/dispatch failures by swallowing only when the exact intended+ // postcondition is visible in the authoritative reducer state.+ if (!isApplied()) {+ throw error;+ }+ // Notification may have been interrupted before DocumentMirror's+ // subscriber ran. Reconcile it synchronously from authoritative state+ // before publishing follow-up state or history.+ try {+ deps.refreshMirror();+ } catch (refreshError) {+ if (!isMirrored()) {+ throw refreshError;+ }+ }+ if (!isMirrored()) {+ throw error;+ }+ return;+ }++ // 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');+ }+ if (!isMirrored()) {+ try {+ deps.refreshMirror();+ } catch (refreshError) {+ if (!isMirrored()) {+ throw refreshError;+ }+ }+ if (!isMirrored()) {+ throw new Error('Canvas document mutation was not mirrored');+ }+ }+ };++ return {+ canEdit,+ capturePermit,+ createLayerId: () => deps.createLayerId(),+ dispatch: (action) => deps.dispatch(action),+ dispatchPrepared,+ dispose: () => unsubscribeDocumentEditingLock(),+ endBurst: () => deps.endBurst(),+ getDocument: () => deps.getDocument(),+ getReducerDocument: () => deps.getReducerDocument(),+ history: deps.history,+ installPrepared: (prepared, persist) => deps.installPrepared(prepared, persist),+ isGestureActive: () => deps.isGestureActive(),+ isGuardCurrent: (guard) => deps.isGuardCurrent(guard),+ isPermitCurrent,+ preparePixels: (layerId, rect, pixels) => deps.preparePixels(layerId, rect, pixels),+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 5d69ff1779..24f76cb91b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -111,6 +111,10 @@ import {type CommitMaskImageResult,type CommitMaskImageResultOptions,} from '@workbench/canvas-engine/controllers/maskResultController';+import {+ createCanvasMutationContext,+ type DocumentEditPermit,+} from '@workbench/canvas-engine/controllers/mutationContext';import { PersistenceController } from '@workbench/canvas-engine/controllers/persistenceController';import { PsdExportController } from '@workbench/canvas-engine/controllers/psdExportController';import { RasterController, type RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';@@ -1273,23 +1277,26 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};const documentEditOwner = Symbol('canvas-operation-document-edit-owner');- type DocumentEditPermit = { epoch: number; owner?: symbol };- let documentEditEpoch = 0;- let documentEditingLocked = false;- const syncDocumentEditingLock = (): void => {- const nextLocked = stores.documentEditingLocked.get();- if (nextLocked !== documentEditingLocked) {- documentEditingLocked = nextLocked;- documentEditEpoch += 1;- }- };- const unsubscribeDocumentEditingLock = stores.documentEditingLocked.subscribe(syncDocumentEditingLock);- const canEditDocument = (owner?: symbol): boolean =>- owner === documentEditOwner || !stores.documentEditingLocked.get();- const captureDocumentEditPermit = (owner?: symbol): DocumentEditPermit | null =>- canEditDocument(owner) ? { epoch: documentEditEpoch, owner } : null;- const isDocumentEditPermitCurrent = (permit: DocumentEditPermit): boolean =>- permit.owner === documentEditOwner || (!stores.documentEditingLocked.get() && permit.epoch === documentEditEpoch);+ // Later-defined engine values (mirror, pipeline, prepared-cache helpers) are+ // passed as thunks: the context never invokes them during construction.+ const mutationContext = createCanvasMutationContext({+ createLayerId,+ dispatch: (action) => mutationPort.dispatch(action),+ editOwner: documentEditOwner,+ editingLocked: stores.documentEditingLocked,+ endBurst: () => endNudgeBurst(),+ getDocument: () => mirror.getDocument(),+ getReducerDocument: () => mutationPort.getCanvasState()?.document ?? null,+ history,+ installPrepared: (prepared, persist) => installGeneratedPaintCache(prepared, persist),+ isGestureActive: () => pipeline.isGestureActive(),+ isGuardCurrent: (guard) => isLayerExportGuardCurrent(guard),+ preparePixels: (layerId, rect, pixels) => prepareGeneratedPaintCache(layerId, rect, pixels),+ refreshMirror: () => mirror.refresh(),+ });+ const canEditDocument = (owner?: symbol): boolean => mutationContext.canEdit(owner);+ const captureDocumentEditPermit = (owner?: symbol): DocumentEditPermit | null => mutationContext.capturePermit(owner);+ const isDocumentEditPermitCurrent = (permit: DocumentEditPermit): boolean => mutationContext.isPermitCurrent(permit);const ensureLayerCaches = (doc: CanvasDocumentContractV2, activeFrameLayerIds: ReadonlySet<string>): void => {for (const layer of doc.layers) {@@ -2422,60 +2429,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn opts.getMainModelBase?.() ?? null;};- const dispatchPreparedMutation = (- action: CanvasProjectMutation,- isApplied: () => boolean,- isMirrored: () => boolean- ): void => {- try {- if (!mutationPort.dispatch(action)) {- throw new Error('Canvas document mutation was rejected');- }- } catch (error) {- // Store subscribers run after the reducer has accepted an action. A- // faulty observer must not strand an applied document mutation before- // its matching engine state and history are published. Preserve real- // reducer/dispatch failures by swallowing only when the exact intended- // postcondition is visible in the authoritative reducer state.- if (!isApplied()) {- throw error;- }- // Notification may have been interrupted before DocumentMirror's- // subscriber ran. Reconcile it synchronously from authoritative state- // before publishing follow-up state or history.- try {- mirror.refresh();- } catch (refreshError) {- if (!isMirrored()) {- throw refreshError;- }- }- if (!isMirrored()) {- throw error;- }- return;- }-- // 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');- }- if (!isMirrored()) {- try {- mirror.refresh();- } catch (refreshError) {- if (!isMirrored()) {- throw refreshError;- }- }- if (!isMirrored()) {- throw new Error('Canvas document mutation was not mirrored');- }- }- };+ const dispatchPreparedMutation = mutationContext.dispatchPrepared;/** Conversion reducers clone contracts, so their publication postcondition compares by value. */const documentHasLayerContract = (@@ -2580,44 +2534,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst filterResultController = new FilterResultController({captureCache: captureLayerCache,- capturePermit: (owner) => captureDocumentEditPermit(owner),- createLayerId,+ ctx: mutationContext,decodeImage: (image, options) => rasterController.decodeImage(image, options),discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),- getDocument: () => mirror.getDocument(),getMainModelBase,- getReducerDocument,- history,- installPrepared: installGeneratedPaintCache,- isGestureActive: () => pipeline.isGestureActive(),- isGuardCurrent: isLayerExportGuardCurrent,- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit as DocumentEditPermit),needsPixelPersistence: layerNeedsPixelPersistence,- preparePixels: prepareGeneratedPaintCache,});const commitRasterFilterResult = filterResultController.commit.bind(filterResultController);const generatedResultController = new GeneratedResultController({captureCache: captureLayerCache,- capturePermit: (owner) => captureDocumentEditPermit(owner),clearPreview: clearFilterPreview,- createLayerId,+ ctx: mutationContext,decodeImage: (image, options) => rasterController.decodeImage(image, options),discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),- getDocument: () => mirror.getDocument(),getMainModelBase,- getReducerDocument,- history,- installPrepared: installGeneratedPaintCache,- isGestureActive: () => pipeline.isGestureActive(),- isGuardCurrent: isLayerExportGuardCurrent,- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit as DocumentEditPermit),needsPixelPersistence: layerNeedsPixelPersistence,- preparePixels: prepareGeneratedPaintCache,});const commitGeneratedImageResult = generatedResultController.commit.bind(generatedResultController);@@ -2769,7 +2701,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(unsubscribeBboxOverlay);cleanup.run(unsubscribeRuleOfThirds);cleanup.run(unsubscribeProjectPreviewLifecycle);- cleanup.run(unsubscribeDocumentEditingLock);+ cleanup.run(() => mutationContext.dispose());cleanup.run(() => historyController.dispose());cleanup.run(() => persistenceController.dispose());cleanup.run(() => mirror.dispose());@@ -2926,8 +2858,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetDocument: () => mirror.getDocument(),getReducerDocument,history,- installPrepared: (prepared) =>- installGeneratedPaintCache(prepared as ReturnType<LayerCacheStore['prepareReplacement']>),+ installPrepared: (prepared) => installGeneratedPaintCache(prepared),isCacheReady: isLayerCacheReadyForOp,isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,@@ -2945,8 +2876,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetDocument: () => mirror.getDocument(),getReducerDocument,history,- installPrepared: (prepared) =>- installGeneratedPaintCache(prepared as ReturnType<LayerCacheStore['prepareReplacement']>),+ installPrepared: (prepared) => installGeneratedPaintCache(prepared),isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit as DocumentEditPermit),@@ -2962,8 +2892,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetDocument: () => mirror.getDocument(),getReducerDocument,history,- installPrepared: (prepared) =>- installGeneratedPaintCache(prepared as ReturnType<LayerCacheStore['prepareReplacement']>),+ installPrepared: (prepared) => installGeneratedPaintCache(prepared),isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit as DocumentEditPermit),@@ -2984,8 +2913,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetReducerDocument,hasExportableContent: hasExportableLayerContent,history,- installPrepared: (prepared) =>- installGeneratedPaintCache(prepared as ReturnType<LayerCacheStore['prepareReplacement']>),+ installPrepared: (prepared) => installGeneratedPaintCache(prepared),isCacheReady: isLayerCacheReadyForOp,isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,@@ -3014,26 +2942,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCmerge: {backend,canEdit: () => canEditDocument(),- capturePermit: () => captureDocumentEditPermit(),- createLayerId,- dispatch: (action) => mutationPort.dispatch(action),- dispatchPrepared: dispatchPreparedMutation,- endBurst: () => endNudgeBurst(),+ ctx: mutationContext,exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId),- getDocument: () => mirror.getDocument(),- getReducerDocument,hasExportableContent: hasExportableLayerContent,- history,- installPrepared: (prepared) =>- installGeneratedPaintCache(prepared as ReturnType<LayerCacheStore['prepareReplacement']>),isCacheReady: isLayerCacheReadyForOp,- isGestureActive: () => pipeline.isGestureActive(),- isGuardCurrent: isLayerExportGuardCurrent,- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit as DocumentEditPermit),layers: layerCache,markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),notifyPainted: notifyLayerPainted,- preparePixels: prepareGeneratedPaintCache,},rasterize: {backend,