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): give mutating controllers one edit-concurrency interface
Josh Corbett4c5fe119c3f0
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex f429fa2736..97d561d45d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -9,8 +9,10 @@ import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { NewRasterLayerResult } from './controllers/newRasterLayerController';+import type { CanvasCommandRefusal } from './document/commandRefusal';import type { FlatLayerInsertionAnchor } from './document/insertionAnchors';import type { LayerStackKind } from './document/layerStacks';+import type { CanvasTransactionOutcome, SubsetOf } from './editConcurrency';import type { CanvasEditGate } from './editGate';import type {BboxToolOptions,@@ -41,20 +43,16 @@ export interface LayerExportGuard {}/**- * Why a guarded layer mutation declined to touch the document. Every commit- * that captures a permit, does async work, then re-checks before publishing- * reports refusal with exactly these reasons — one shared vocabulary so callers- * can handle them uniformly and new commits can't invent near-miss variants.- *- * `busy` — another edit owns the document, or a gesture started mid-flight.- * `stale` — the guarded pixels no longer match the live layer.- * `aborted` — the caller's signal fired.- *- * This union still mixes runtime outcomes with document refusals (`missing`,- * `locked`, `unsupported`); structural commits use the transaction-only- * {@link StructuralCommitResult} instead.+ * Why a guarded layer mutation declined to touch the document: the transaction+ * outcomes a permit-guarded commit can hit (`busy` — another edit owns the+ * document or a gesture started mid-flight; `stale` — the guarded pixels no+ * longer match the live layer; `aborted` — the caller's signal fired) plus the+ * command refusals its target can raise. Structural commits use the+ * transaction-only {@link StructuralCommitResult}.*/-export type GuardedMutationRefusal = 'aborted' | 'busy' | 'locked' | 'missing' | 'stale' | 'unsupported';+export type GuardedMutationRefusal =+ | SubsetOf<CanvasTransactionOutcome, 'aborted' | 'busy' | 'stale'>+ | SubsetOf<CanvasCommandRefusal, 'locked' | 'missing' | 'unsupported'>;export type CommitRasterFilterResult =| { status: 'committed'; layerId: string }@@ -160,7 +158,12 @@ export interface CanvasDocumentSnapshot {readonly documentGeneration: number;}-export type PsdExportResult = 'exported' | 'nothing' | 'too-large' | 'not-ready' | 'over-budget' | 'stale' | 'aborted';+export type PsdExportResult =+ | 'exported'+ | 'nothing'+ | 'too-large'+ | 'over-budget'+ | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'stale' | 'aborted'>;export interface CanvasPsdExportCapability {exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;@@ -189,7 +192,12 @@ export interface CanvasHistoryCapability {clearHistory(): void;}-export type LayerThumbnailRequestResult = 'ready' | 'stale' | 'error' | 'missing' | 'unsupported' | 'over-budget';+export type LayerThumbnailRequestResult =+ | 'ready'+ | 'error'+ | 'over-budget'+ | SubsetOf<CanvasTransactionOutcome, 'stale'>+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>;export interface CanvasPreviewCapability {drawLayerThumbnail(layerId: string, target: HTMLCanvasElement, maxSize: number): boolean;@@ -225,7 +233,14 @@ export type ExportBakedLayerPixelsOptions = Omit<ExportLayerPixelsOptions, 'applexport type ExportBakedLayerBlobResult =| { status: 'ok'; blob: Blob; rect: Rect; guard: LayerExportGuard }- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'aborted' };+ | {+ status:+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>+ | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'aborted'>+ | 'disabled'+ | 'empty'+ | 'over-budget';+ };export interface CanvasSelectionCapability {deselect(): void;@@ -271,8 +286,8 @@ export type ReplaceSelectionFromImageResult =*/export type StructuralCommitResult =| { status: 'committed' }- | { status: 'busy' | 'gesture-active' | 'not-ready' | 'dispatch-rejected' }- | { status: 'stale'; expectedRevision: number; actualRevision: number }+ | { status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'gesture-active' | 'not-ready'> | 'dispatch-rejected' }+ | { status: SubsetOf<CanvasTransactionOutcome, 'stale'>; expectedRevision: number; actualRevision: number }| { status: 'postcondition-failed'; recovered: 'reverted' | 'reverted-unmirrored' | 'unreverted' };export interface StructuralCommitOptions {@@ -310,7 +325,7 @@ export interface CommitStagedImageOptions {export type CommitStagedImageResult =| { status: 'committed'; layerId: string }- | { status: 'busy' | 'stale' | 'missing' };+ | { status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'stale'> | SubsetOf<CanvasCommandRefusal, 'missing'> };export type GeneratedImageTarget = 'replace' | 'copy-raster' | 'copy-control';@@ -359,17 +374,36 @@ export interface FilterPreviewInput {* refused, `'busy'` when another edit owns the document, and `'nothing'` when* fewer than two eligible rasters have content.*/-export type MergeVisibleResult = 'merged' | 'not-ready' | 'over-budget' | 'busy' | 'nothing';+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: 'busy' | 'nothing' | 'not-ready' | 'over-budget' | 'stale' };-export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty';+ | { 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: 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty' };+ | {+ status:+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>+ | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'busy'>+ | 'empty';+ };export type CropLayerResult =| { status: 'cropped' }- | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'busy' }+ | {+ status:+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'locked' | 'unsupported'>+ | SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'busy'>+ | 'empty'+ | 'over-budget';+ }| { status: 'failed'; message: string };export interface CanvasDiagnosticsCapability {clearCaches(): Promise<void>;@@ -459,7 +493,7 @@ export interface CanvasEnginePreviewCapability extends CanvasPreviewCapability {layerId: string,input: FilterPreviewInput,guard: LayerExportGuard- ): Promise<'shown' | 'missing' | 'stale'>;+ ): Promise<'shown' | SubsetOf<CanvasCommandRefusal, 'missing'> | SubsetOf<CanvasTransactionOutcome, 'stale'>>;setStagedPreview(input: StagedPreviewInput | null): 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 ce9c1df62a..19f2ee4722 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts@@ -2,6 +2,7 @@ import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { FlatLayerInsertionAnchor } 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';@@ -18,14 +19,12 @@ type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };-export interface BooleanMergeControllerOptions<Permit> {+export interface BooleanMergeControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly backend: RasterBackend;readonly history: History;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly capturePermit: () => Permit | null;- readonly isPermitCurrent: (permit: Permit) => boolean;- readonly isGestureActive: () => boolean;readonly endBurst: () => void;readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;@@ -49,14 +48,14 @@ const modes: Record<BooleanRasterOperation, GlobalCompositeOperation> = {};/** Owns guarded two-layer boolean compositing and atomic stack history. */-export class BooleanMergeController<Permit> {+export class BooleanMergeController {private disposed = false;- constructor(private readonly deps: BooleanMergeControllerOptions<Permit>) {}+ constructor(private readonly deps: BooleanMergeControllerOptions) {}async merge(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult> {- const permit = this.deps.capturePermit();- if (this.disposed || !permit || this.deps.isGestureActive()) {+ const permit = this.deps.concurrency.capturePermit();+ if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {return 'busy';}this.deps.endBurst();@@ -93,7 +92,7 @@ export class BooleanMergeController<Permit> {const [upperPixels, belowPixels] = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return 'busy';}if (upperPixels.status !== 'ok' || belowPixels.status !== 'ok') {@@ -111,14 +110,14 @@ export class BooleanMergeController<Permit> {return 'empty';}if (- !this.deps.isPermitCurrent(permit) ||- this.deps.isGestureActive() ||+ !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.isPermitCurrent(permit) ? 'not-ready' : 'busy';+ return this.deps.concurrency.isPermitCurrent(permit) ? 'not-ready' : 'busy';}const liveDocument = this.deps.getDocument();const liveIndex = liveDocument?.layers.findIndex((layer) => layer.id === upperLayerId) ?? -1;@@ -183,7 +182,7 @@ export class BooleanMergeController<Permit> {);this.deps.installPrepared(prepared);};- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return 'busy';}apply();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.tsindex b8a6099206..c286f003c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts@@ -2,6 +2,7 @@ import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { FlatLayerInsertionAnchor } 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';@@ -12,13 +13,11 @@ type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };-export interface CopyLayerControllerOptions<Permit> {+export interface CopyLayerControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly history: History;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly capturePermit: () => Permit | null;- readonly isPermitCurrent: (permit: Permit) => boolean;- readonly isGestureActive: () => boolean;readonly endBurst: () => void;readonly exportBaked: (layerId: string) => Promise<ExportResult>;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;@@ -34,13 +33,13 @@ export interface CopyLayerControllerOptions<Permit> {}/** Owns guarded baked copies into new raster paint layers. */-export class CopyLayerController<Permit> {+export class CopyLayerController {private disposed = false;- constructor(private readonly deps: CopyLayerControllerOptions<Permit>) {}+ constructor(private readonly deps: CopyLayerControllerOptions) {}async copyToRaster(layerId: string): Promise<string | null> {- const permit = this.deps.capturePermit();- if (this.disposed || !permit || this.deps.isGestureActive()) {+ const permit = this.deps.concurrency.capturePermit();+ if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {return null;}this.deps.endBurst();@@ -54,10 +53,14 @@ export class CopyLayerController<Permit> {return null;}try {- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return null;}- if (this.deps.isGestureActive() || !this.deps.isGuardCurrent(baked.guard) || baked.guard.layer !== sourceLayer) {+ if (+ this.deps.concurrency.isGestureActive() ||+ !this.deps.isGuardCurrent(baked.guard) ||+ baked.guard.layer !== sourceLayer+ ) {return null;}const liveDocument = this.deps.getDocument();@@ -96,7 +99,7 @@ export class CopyLayerController<Permit> {);this.deps.installPrepared(prepared);};- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return null;}apply();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.tsindex f454f37d1b..294365e205 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts@@ -4,6 +4,7 @@ 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';@@ -27,14 +28,12 @@ interface PixelSnapshot {rect: Rect;}-export interface CropLayerControllerOptions<Permit> {+export interface CropLayerControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly backend: RasterBackend;readonly history: History;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly capturePermit: () => Permit | null;- readonly isPermitCurrent: (permit: Permit) => boolean;- readonly isGestureActive: () => boolean;readonly endBurst: () => void;readonly isSupportedSource: (source: CanvasLayerSourceContract) => boolean;readonly exportBaked: (layerId: string) => Promise<ExportResult>;@@ -54,13 +53,13 @@ export interface CropLayerControllerOptions<Permit> {}/** Owns guarded crop-to-bbox conversion and replayable pixel snapshots. */-export class CropLayerController<Permit> {+export class CropLayerController {private disposed = false;- constructor(private readonly deps: CropLayerControllerOptions<Permit>) {}+ constructor(private readonly deps: CropLayerControllerOptions) {}async crop(layerId: string): Promise<CropLayerResult> {- const permit = this.deps.capturePermit();- if (this.disposed || !permit || this.deps.isGestureActive()) {+ const permit = this.deps.concurrency.capturePermit();+ if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {return { status: 'busy' };}this.deps.endBurst();@@ -82,7 +81,7 @@ export class CropLayerController<Permit> {return { status: exported.status === 'disabled' ? 'not-ready' : exported.status };}try {- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return { status: 'busy' };}const liveDocument = this.deps.getDocument();@@ -90,7 +89,7 @@ export class CropLayerController<Permit> {if (!liveDocument || !liveLayer) {return { status: 'missing' };}- if (!this.deps.isPermitCurrent(permit) || this.deps.isGestureActive()) {+ if (!this.deps.concurrency.isPermitCurrent(permit) || this.deps.concurrency.isGestureActive()) {return { status: 'busy' };}if (liveLayer.isLocked) {@@ -146,7 +145,7 @@ export class CropLayerController<Permit> {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.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return { status: 'busy' };}publish(after, prepared);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 6ff5e139c9..f815f3e84f 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@@ -1,6 +1,7 @@import type { SelectionState, SelectionStateDeps } from '@workbench/canvas-engine/selection/selectionState';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 { EditingController } from './editingController';@@ -81,12 +82,10 @@ const createFloatingSelectionOptions = () => ({});const createSelectionImageOptions = () => ({- capturePermit: () => null,+ concurrency: createTestEditConcurrency({ capturePermit: () => null, isPermitCurrent: () => false }),decodeImage: vi.fn(),getDocument: () => null,- isGestureActive: () => false,isGuardCurrent: () => false,- isPermitCurrent: () => false,});describe('EditingController', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.tsindex f05ee81030..06d7cbfc2c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts@@ -14,7 +14,7 @@ import { SelectionPixelController, type SelectionPixelControllerOptions } from 'import { TextEditingController, type TextEditingControllerOptions } from './textEditingController';import { TransformEditingController, type TransformEditingControllerOptions } from './transformEditingController';-export interface EditingControllerOptions<Permit = unknown, Owner = symbol> {+export interface EditingControllerOptions {readonly selection: SelectionStateDeps;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly createSelectionState?: (deps: SelectionStateDeps) => SelectionState;@@ -22,24 +22,24 @@ export interface EditingControllerOptions<Permit = unknown, Owner = symbol> {readonly text: TextEditingControllerOptions;readonly transform: TransformEditingControllerOptions;readonly selectionPixels: Omit<SelectionPixelControllerOptions, 'selection'>;- readonly selectionImage: Omit<SelectionImageControllerOptions<Permit, Owner>, 'selection'>;+ readonly selectionImage: Omit<SelectionImageControllerOptions, 'selection'>;readonly floatingSelection: Omit<FloatingSelectionControllerOptions, 'selection'>;}/** Owns transient editing state whose lifetime follows one engine instance. */-export class EditingController<Permit = unknown, Owner = symbol> {+export class EditingController {readonly selection: SelectionState;readonly edits: CanvasEditGate;readonly text: TextEditingController;readonly transform: TransformEditingController;readonly selectionPixels: SelectionPixelController;- readonly selectionImage: SelectionImageController<Permit, Owner>;+ readonly selectionImage: SelectionImageController;readonly floatingSelection: FloatingSelectionController;private readonly editGate: CanvasEditGateController;private readonly getDocument: () => CanvasDocumentContractV2 | null;private disposed = false;- constructor(options: EditingControllerOptions<Permit, Owner>) {+ constructor(options: EditingControllerOptions) {this.selection = (options.createSelectionState ?? createSelectionState)(options.selection);this.getDocument = options.getDocument;this.editGate = (options.createEditGate ?? createCanvasEditGate)();@@ -47,7 +47,7 @@ export class EditingController<Permit = unknown, Owner = symbol> {this.text = new TextEditingController(options.text);this.transform = new TransformEditingController(options.transform);this.selectionPixels = new SelectionPixelController({ ...options.selectionPixels, selection: this.selection });- this.selectionImage = new SelectionImageController<Permit, Owner>({+ this.selectionImage = new SelectionImageController({...options.selectionImage,selection: this.selection,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.tsindex 6e8cdaab60..72ef1fe965 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts@@ -3,6 +3,7 @@ import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/cimport type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { FlatLayerInsertionAnchor } 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 { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';@@ -27,7 +28,8 @@ type ExportResult =| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' };-export interface ExtractMaskedAreaControllerOptions<Permit> {+export interface ExtractMaskedAreaControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly backend: RasterBackend;readonly layers: LayerCacheStore;readonly derived: DerivedSurfaceCache;@@ -35,9 +37,6 @@ export interface ExtractMaskedAreaControllerOptions<Permit> {readonly history: History;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly capturePermit: () => Permit | null;- readonly isPermitCurrent: (permit: Permit) => boolean;- readonly isGestureActive: () => boolean;readonly endBurst: () => void;readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => boolean;readonly hasExportableContent: (layerId: string) => boolean;@@ -58,13 +57,13 @@ export interface ExtractMaskedAreaControllerOptions<Permit> {}/** Owns guarded extraction of raster content through an inpaint mask. */-export class ExtractMaskedAreaController<Permit> {+export class ExtractMaskedAreaController {private disposed = false;- constructor(private readonly deps: ExtractMaskedAreaControllerOptions<Permit>) {}+ constructor(private readonly deps: ExtractMaskedAreaControllerOptions) {}async extract(maskLayerId: string): Promise<ExtractMaskedAreaResult> {- const permit = this.deps.capturePermit();- if (this.disposed || !permit || this.deps.isGestureActive()) {+ const permit = this.deps.concurrency.capturePermit();+ if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {return { status: 'busy' };}this.deps.endBurst();@@ -116,7 +115,7 @@ export class ExtractMaskedAreaController<Permit> {const [maskPixels, ...contributorPixels] = settled.map((result) => (result as PromiseFulfilledResult<ExportResult>).value);- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return { status: 'busy' };}if (maskPixels.status !== 'ok') {@@ -125,7 +124,7 @@ export class ExtractMaskedAreaController<Permit> {if (contributorPixels.some((pixels) => pixels.status !== 'ok')) {return { status: contributorPixels.some((pixels) => pixels.status === 'not-ready') ? 'not-ready' : 'empty' };}- if (this.deps.isGestureActive()) {+ if (this.deps.concurrency.isGestureActive()) {return { status: 'busy' };}if (maskPixels.guard.layer !== mask || !this.deps.isGuardCurrent(maskPixels.guard)) {@@ -217,7 +216,7 @@ export class ExtractMaskedAreaController<Permit> {);this.deps.installPrepared(prepared);};- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return { status: 'busy' };}apply();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 dde0d73362..942387cfb7 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,6 +1,7 @@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';@@ -79,7 +80,7 @@ describe('LayerController', () => {};const booleanMerge = {backend: {} as never,- capturePermit: () => null,+ concurrency: createTestEditConcurrency({ capturePermit: () => null }),createLayerId: () => 'result',captureInsertionAnchor: createTestInsertionAnchorCapture('p'),dispatchPrepared: vi.fn(),@@ -90,14 +91,12 @@ describe('LayerController', () => {history: {} as never,installPrepared: vi.fn(),isCacheReady: () => true,- isGestureActive: () => false,isGuardCurrent: () => true,- isPermitCurrent: () => true,preparePixels: vi.fn(),};const extractMaskedArea = {backend: {} as never,- capturePermit: () => null,+ concurrency: createTestEditConcurrency({ capturePermit: () => null }),createLayerId: () => 'result',captureInsertionAnchor: createTestInsertionAnchorCapture('p'),derived: {} as never,@@ -113,9 +112,7 @@ describe('LayerController', () => {history: {} as never,installPrepared: vi.fn(),isCacheReady: () => true,- isGestureActive: () => false,isGuardCurrent: () => true,- isPermitCurrent: () => true,layers: {} as never,preparePixels: vi.fn(),rasterize: vi.fn(),@@ -123,7 +120,7 @@ describe('LayerController', () => {const crop = {backend: {} as never,captureCache: vi.fn(),- capturePermit: () => null,+ concurrency: createTestEditConcurrency({ capturePermit: () => null }),discardPersisted: vi.fn(),dispatchPrepared: vi.fn(),endBurst: vi.fn(),@@ -132,14 +129,12 @@ describe('LayerController', () => {getReducerDocument: () => null,history: {} as never,installPrepared: vi.fn(),- isGestureActive: () => false,isGuardCurrent: () => true,- isPermitCurrent: () => true,isSupportedSource: () => true,preparePixels: vi.fn(),};const copy = {- capturePermit: () => null,+ concurrency: createTestEditConcurrency({ capturePermit: () => null }),createLayerId: () => 'copy',captureInsertionAnchor: createTestInsertionAnchorCapture('p'),dispatchPrepared: vi.fn(),@@ -149,14 +144,12 @@ describe('LayerController', () => {getReducerDocument: () => null,history: {} as never,installPrepared: vi.fn(),- isGestureActive: () => false,isGuardCurrent: () => true,- isPermitCurrent: () => true,preparePixels: vi.fn(),};const newRasterLayer = {backend: {} as never,- capturePermit: () => null,+ concurrency: createTestEditConcurrency({ capturePermit: () => null }),createLayerId: () => 'new',captureInsertionAnchor: createTestInsertionAnchorCapture('p'),dispatchPrepared: vi.fn(),@@ -165,8 +158,6 @@ describe('LayerController', () => {getReducerDocument: () => null,history: {} as never,installPrepared: vi.fn(),- isGestureActive: () => false,- isPermitCurrent: () => true,layers: {} as never,preparePixels: vi.fn(),selection: {} as never,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.tsindex 5b2eeaa8b0..d124f7a209 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts@@ -13,7 +13,7 @@ import { NewRasterLayerController, type NewRasterLayerControllerOptions } from 'import { RasterizeLayerController, type RasterizeLayerControllerOptions } from './rasterizeLayerController';import { ThumbnailController, type ThumbnailControllerOptions } from './thumbnailController';-export type LayerControllerDeps<Permit> = Omit<+export type LayerControllerDeps = Omit<CanvasLayerCapability,'applyStructuralPreview' | 'canCommitStructural' | 'commitStagedImage' | 'commitStructural' | 'invertMask'> &@@ -23,15 +23,15 @@ export type LayerControllerDeps<Permit> = Omit<structural: StructuralLayerController;rasterize: RasterizeLayerControllerOptions;merge: MergeLayerControllerOptions;- booleanMerge: BooleanMergeControllerOptions<Permit>;- extractMaskedArea: ExtractMaskedAreaControllerOptions<Permit>;- crop: CropLayerControllerOptions<Permit>;- copy: CopyLayerControllerOptions<Permit>;- newRasterLayer: NewRasterLayerControllerOptions<Permit>;+ booleanMerge: BooleanMergeControllerOptions;+ extractMaskedArea: ExtractMaskedAreaControllerOptions;+ crop: CropLayerControllerOptions;+ copy: CopyLayerControllerOptions;+ newRasterLayer: NewRasterLayerControllerOptions;};/** Public layer-operation boundary. Implementations are injected by the composition root. */-export class LayerController<Permit> {+export class LayerController {readonly layers: Omit<CanvasLayerCapability, 'commitStagedImage'>;readonly previews: CanvasPreviewCapability;readonly mask: MaskLayerController;@@ -39,14 +39,14 @@ export class LayerController<Permit> {readonly structural: StructuralLayerController;readonly rasterize: RasterizeLayerController;readonly merge: MergeLayerController;- readonly booleanMerge: BooleanMergeController<Permit>;- readonly extractMaskedArea: ExtractMaskedAreaController<Permit>;- readonly crop: CropLayerController<Permit>;- readonly copy: CopyLayerController<Permit>;- readonly newRasterLayer: NewRasterLayerController<Permit>;+ readonly booleanMerge: BooleanMergeController;+ readonly extractMaskedArea: ExtractMaskedAreaController;+ readonly crop: CropLayerController;+ readonly copy: CopyLayerController;+ readonly newRasterLayer: NewRasterLayerController;private disposed = false;- constructor(deps: LayerControllerDeps<Permit>) {+ constructor(deps: LayerControllerDeps) {this.mask = new MaskLayerController(deps.mask);this.thumbnail = new ThumbnailController(deps.thumbnail);this.structural = deps.structural;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.tsindex 27f4f4815b..c6f1b0915f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts@@ -3,6 +3,7 @@ import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/cimport type { RasterMemoryReservationResult } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';import type { FlatLayerInsertionAnchor } 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';@@ -30,9 +31,8 @@ type DuplicateRasterPreparationResult =| { readonly status: 'ready'; readonly layer: CanvasLayerContract }| { readonly status: 'not-ready' | 'over-budget' };-export interface LayerMutationControllerOptions<Permit> {- readonly canEdit: () => boolean;- readonly capturePermit: () => Permit | null;+export interface LayerMutationControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;readonly createLayerId: () => string;@@ -54,8 +54,6 @@ export interface LayerMutationControllerOptions<Permit> {readonly history: History;readonly hasPendingPixelWork: (layerId: string) => boolean;readonly installPrepared: (prepared: PreparedLayerCacheReplacement, persist?: boolean) => void;- readonly isGestureActive: () => boolean;- readonly isPermitCurrent: (permit: Permit) => boolean;readonly needsPixelPersistence: (layer: CanvasLayerContract) => boolean;readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;readonly publishSelectedLayerIds: (primaryId: string | null, selectedIds: readonly string[]) => void;@@ -68,15 +66,15 @@ export interface LayerMutationControllerOptions<Permit> {}/** Owns failure-atomic copy and cross-type conversion mutations. */-export class LayerMutationController<Permit> {+export class LayerMutationController {private duplicateInFlight = false;- constructor(private readonly options: LayerMutationControllerOptions<Permit>) {}+ constructor(private readonly options: LayerMutationControllerOptions) {}async duplicate(layerIds: readonly string[]): Promise<DuplicateLayersResult> {const o = this.options;- const permit = o.capturePermit();- if (this.duplicateInFlight || !permit || !o.canEdit() || o.isGestureActive()) {+ const permit = o.concurrency.capturePermit();+ if (this.duplicateInFlight || !permit || !o.concurrency.canEdit() || o.concurrency.isGestureActive()) {return { status: 'busy' };}const document = o.getDocument();@@ -109,7 +107,7 @@ export class LayerMutationController<Permit> {return { status: 'stale' };}}- if (!o.isPermitCurrent(permit) || o.isGestureActive() || o.getDocument() !== document) {+ if (!o.concurrency.isPermitCurrent(permit) || o.concurrency.isGestureActive() || o.getDocument() !== document) {return { status: 'stale' };}return this.commitDuplicate(layerIds);@@ -121,7 +119,7 @@ export class LayerMutationController<Permit> {private commitDuplicate(layerIds: readonly string[]): DuplicateLayersResult {const o = this.options;- if (!o.canEdit() || o.isGestureActive()) {+ if (!o.concurrency.canEdit() || o.concurrency.isGestureActive()) {return { status: 'busy' };}o.endBurst();@@ -334,7 +332,7 @@ export class LayerMutationController<Permit> {copy(label: string, sourceLayerId: string, layer: CanvasLayerContract, anchor: FlatLayerInsertionAnchor): boolean {const o = this.options;- if (!o.canEdit() || o.isGestureActive()) {+ if (!o.concurrency.canEdit() || o.concurrency.isGestureActive()) {return false;}o.endBurst();@@ -395,7 +393,12 @@ export class LayerMutationController<Permit> {convert(label: string, expected: CanvasLayerContract, after: CanvasLayerContract): boolean {const o = this.options;- if (!o.canEdit() || o.isGestureActive() || expected.id !== after.id || expected.type === after.type) {+ if (+ !o.concurrency.canEdit() ||+ o.concurrency.isGestureActive() ||+ expected.id !== after.id ||+ expected.type === after.type+ ) {return false;}o.endBurst();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.tsindex 5f28db862b..f8b29416fd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts@@ -6,6 +6,7 @@ import type {import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';import type { FlatLayerInsertionAnchor } 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';@@ -24,9 +25,9 @@ export type {MaskImageResultTarget,} from '@workbench/canvas-engine/capabilities';-export interface MaskResultControllerOptions<Owner = symbol> {- readonly canEdit: (owner?: Owner) => boolean;+export interface MaskResultControllerOptions {readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;+ readonly concurrency: CanvasEditConcurrency;readonly createLayerId: () => string;readonly dispatchPrepared: (action: CanvasProjectMutation,@@ -37,17 +38,16 @@ export interface MaskResultControllerOptions<Owner = symbol> {readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;readonly history: History;- readonly isGestureActive: () => boolean;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;}/** Converts a guarded object-selection result into a structural mask layer. */-export class MaskResultController<Owner = symbol> {- constructor(private readonly options: MaskResultControllerOptions<Owner>) {}+export class MaskResultController {+ constructor(private readonly options: MaskResultControllerOptions) {}- commit(options: CommitMaskImageResultOptions, owner?: Owner): Promise<CommitMaskImageResult> {+ commit(options: CommitMaskImageResultOptions, owner?: symbol): Promise<CommitMaskImageResult> {const o = this.options;- if (!o.canEdit(owner)) {+ if (!o.concurrency.canEdit(owner)) {return Promise.resolve({ status: 'busy' });}if (options.signal?.aborted) {@@ -67,7 +67,7 @@ export class MaskResultController<Owner = symbol> {if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {return Promise.resolve({ status: 'unsupported' });}- if (o.isGestureActive()) {+ if (o.concurrency.isGestureActive()) {return Promise.resolve({ status: 'busy' });}if (!o.isGuardCurrent(options.guard)) {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 9426613de0..821db0ad42 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@@ -66,6 +66,13 @@ const createHarness = (overrides: Partial<CanvasMutationContextDeps> = {}) => {describe('createCanvasMutationContext', () => {describe('document edit permits', () => {+ it('exposes the engine project id on the concurrency surface', () => {+ const { context } = createHarness();++ expect(context.projectId).toBe('p1');+ expect(context.getEditRevision()).toBe(0);+ });+it('captures a permit while unlocked and keeps it current until the lock transitions', () => {const { context } = createHarness();const permit = context.capturePermit();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.tsindex e27eb4a801..d26732d57f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts@@ -3,6 +3,7 @@ import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { FlatLayerInsertionAnchor } 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 { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';@@ -11,37 +12,20 @@ import type { Rect } from '@workbench/canvas-engine/types';import { captureInsertionAnchor, captureRestoreAnchor } from '@workbench/canvas-engine/document/insertionAnchors';-/**- * 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.+ * document-mutation protocol (the edit-concurrency surface, 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 {+export interface CanvasMutationContext extends CanvasEditConcurrency {readonly history: History;getDocument(): CanvasDocumentContractV2 | null;getReducerDocument(): CanvasDocumentContractV2 | null;- /** Counts reducer document identities; a captured value is stale once any edit lands. */- getEditRevision(): number;/** Where a new `stack` layer lands: above `aboveId` when it belongs to the stack, else the stack top. */captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor;/** The anchor that restores `layerId` between its current same-stack neighbours; null when absent. */captureRestoreAnchor(layerId: string): FlatLayerInsertionAnchor | null;- canEdit(owner?: symbol): boolean;- capturePermit(owner?: symbol): DocumentEditPermit | null;- isPermitCurrent(permit: DocumentEditPermit): boolean;isGuardCurrent(guard: LayerExportGuard): boolean;dispatch(action: CanvasProjectMutation, origin?: WorkbenchActionOrigin): boolean;dispatchPrepared(@@ -53,7 +37,6 @@ export interface CanvasMutationContext {preparePixels(layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement;installPrepared(prepared: PreparedLayerCacheReplacement, persist?: boolean): void;endBurst(): void;- isGestureActive(): boolean;createLayerId(): string;}@@ -213,6 +196,7 @@ export const createCanvasMutationContext = (isGestureActive: () => deps.isGestureActive(),isGuardCurrent: (guard) => deps.isGuardCurrent(guard),isPermitCurrent,+ projectId: deps.projectId,preparePixels: (layerId, rect, pixels) => deps.preparePixels(layerId, rect, pixels),};};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 d6fcef68a9..ffc8dedf7a 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@@ -3,12 +3,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 { insertLayersAtAnchor } 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';@@ -55,7 +57,7 @@ interface HarnessOptions {selectedLayerId?: string | null;maskRect?: Rect | null;cacheRect?: Rect;- permit?: object | null;+ permit?: DocumentEditPermit | null;gestureActive?: boolean;}@@ -84,7 +86,10 @@ const createHarness = (options: HarnessOptions = {}) => {const controller = new NewRasterLayerController({backend,captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.layers ?? []),- capturePermit: () => (options.permit === undefined ? {} : options.permit),+ concurrency: createTestEditConcurrency({+ capturePermit: () => (options.permit === undefined ? { epoch: 0 } : options.permit),+ isGestureActive: () => options.gestureActive === true,+ }),createLayerId: () => `new-${(nextId += 1)}`,dispatchPrepared: (action) => {dispatched.push(action);@@ -106,8 +111,6 @@ const createHarness = (options: HarnessOptions = {}) => {getReducerDocument: () => document,history,installPrepared: installed,- isGestureActive: () => options.gestureActive === true,- isPermitCurrent: () => true,layers: layerCache,preparePixels: (layerId, rect) => ({ layerId, rect }) as never,selection,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.tsindex 5c333c9eb4..c56ce69de1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts@@ -1,6 +1,12 @@import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';import type { FlatLayerInsertionAnchor } 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 { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';import type { LayerCacheStore, PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';@@ -12,18 +18,18 @@ import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/matimport { liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';-export type NewRasterLayerResult = { status: 'created'; layerId: string } | { status: 'busy' | 'empty' | 'missing' };+export type NewRasterLayerResult =+ | { status: 'created'; layerId: string }+ | { status: SubsetOf<CanvasTransactionOutcome, 'busy'> | SubsetOf<CanvasCommandRefusal, 'missing'> | 'empty' };-export interface NewRasterLayerControllerOptions<Permit> {+export interface NewRasterLayerControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly backend: RasterBackend;readonly layers: LayerCacheStore;readonly selection: SelectionState;readonly history: History;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly getReducerDocument: () => CanvasDocumentContractV2 | null;- readonly capturePermit: () => Permit | null;- readonly isPermitCurrent: (permit: Permit) => boolean;- readonly isGestureActive: () => boolean;readonly endBurst: () => void;readonly createLayerId: () => string;readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;@@ -50,18 +56,18 @@ export interface NewRasterLayerControllerOptions<Permit> {* The new layer is inserted directly above the active one, which is where the* user is looking, and becomes the selection.*/-export class NewRasterLayerController<Permit> {+export class NewRasterLayerController {private disposed = false;- constructor(private readonly deps: NewRasterLayerControllerOptions<Permit>) {}+ 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.*/insert(rect: Rect, pixels: RasterSurface, name: string, label: string): NewRasterLayerResult {- const permit = this.deps.capturePermit();- if (this.disposed || !permit || this.deps.isGestureActive()) {+ const permit = this.deps.concurrency.capturePermit();+ if (this.disposed || !permit || this.deps.concurrency.isGestureActive()) {return { status: 'busy' };}const document = this.deps.getDocument();@@ -112,7 +118,7 @@ export class NewRasterLayerController<Permit> {this.deps.installPrepared(prepared);};- if (!this.deps.isPermitCurrent(permit)) {+ if (!this.deps.concurrency.isPermitCurrent(permit)) {return { status: 'busy' };}apply();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.tsindex ae02f85c6f..b7f075d73d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionImageController.ts@@ -1,11 +1,12 @@import type { LayerExportGuard, ReplaceSelectionFromImageResult } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV2, CanvasImageRef } from '@workbench/canvas-engine/contracts';import type { DecodeImageResult } from '@workbench/canvas-engine/controllers/rasterController';+import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { Rect } from '@workbench/canvas-engine/types';-export interface SelectionImageControllerOptions<Permit, Owner = symbol> {- readonly capturePermit: (owner?: Owner) => Permit | null;+export interface SelectionImageControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly decodeImage: (image: CanvasImageRef,@@ -16,24 +17,22 @@ export interface SelectionImageControllerOptions<Permit, Owner = symbol> {validateDecoded?: (width: number, height: number) => void;}) => Promise<DecodeImageResult>;- readonly isGestureActive: () => boolean;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;- readonly isPermitCurrent: (permit: Permit) => boolean;readonly selection: SelectionState;}/** Decodes guarded application results into the transient selection mask. */-export class SelectionImageController<Permit, Owner = symbol> {- constructor(private readonly options: SelectionImageControllerOptions<Permit, Owner>) {}+export class SelectionImageController {+ constructor(private readonly options: SelectionImageControllerOptions) {}async replace(guard: LayerExportGuard,image: CanvasImageRef,rect: Rect,signal?: AbortSignal,- owner?: Owner+ owner?: symbol): Promise<ReplaceSelectionFromImageResult> {- const permit = this.options.capturePermit(owner);+ const permit = this.options.concurrency.capturePermit(owner);if (!permit) {return { status: 'busy' };}@@ -42,7 +41,7 @@ export class SelectionImageController<Permit, Owner = symbol> {}try {const decoded = await this.options.decodeImage(image, {- isCurrent: () => this.options.isPermitCurrent(permit),+ isCurrent: () => this.options.concurrency.isPermitCurrent(permit),signal,});if (decoded.status !== 'ok') {@@ -63,7 +62,7 @@ export class SelectionImageController<Permit, Owner = symbol> {if (layer.type !== 'raster' && layer.type !== 'control') {return { status: 'unsupported' };}- if (!this.options.isPermitCurrent(permit) || this.options.isGestureActive()) {+ if (!this.options.concurrency.isPermitCurrent(permit) || this.options.concurrency.isGestureActive()) {return { status: 'busy' };}if (!this.options.isGuardCurrent(guard)) {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 f21d4a4b1f..849208a0c3 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@@ -3,6 +3,7 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { insertLayersAtAnchor } 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 { describe, expect, it, vi } from 'vitest';@@ -92,7 +93,7 @@ describe('StagedResultController', () => {);const controller = new StagedResultController({captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- capturePermit: () => ({ epoch: 1 }),+ concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),createEventId: () => 'event-1',createLayerId: () => 'layer-1',dispatchPrepared,@@ -100,8 +101,6 @@ describe('StagedResultController', () => {getCanvasState: () => reducerCanvas,getDocument: () => mirrorDocument,history,- isGestureActive: () => false,- isPermitCurrent: () => true,now: () => '2026-07-16T01:00:00.000Z',});@@ -131,7 +130,7 @@ describe('StagedResultController', () => {const history = createHistory();const controller = new StagedResultController({captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- capturePermit: () => ({ epoch: 1 }),+ concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),createEventId: () => 'event-1',createLayerId: () => 'layer-1',dispatchPrepared: () => {@@ -141,8 +140,6 @@ describe('StagedResultController', () => {getCanvasState: () => canvas,getDocument: () => canvas.document,history,- isGestureActive: () => false,- isPermitCurrent: () => true,now: () => '2026-07-16T01:00:00.000Z',});@@ -162,7 +159,11 @@ describe('StagedResultController', () => {const history = createHistory();const controller = new StagedResultController({captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- capturePermit: () => permit,+ concurrency: createTestEditConcurrency({+ capturePermit: () => permit,+ isGestureActive: () => gestureActive,+ isPermitCurrent: () => permitCurrent,+ }),createEventId: () => 'event-1',createLayerId: () => 'layer-1',dispatchPrepared,@@ -170,8 +171,6 @@ describe('StagedResultController', () => {getCanvasState: () => canvas,getDocument: () => canvas.document,history,- isGestureActive: () => gestureActive,- isPermitCurrent: () => permitCurrent,now: () => '2026-07-16T01:00:00.000Z',});@@ -185,7 +184,7 @@ describe('StagedResultController', () => {const history = createHistory();const controller = new StagedResultController({captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- capturePermit: () => ({ epoch: 1 }),+ concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),createEventId: () => 'event-1',createLayerId: () => 'layer-1',dispatchPrepared: () => {@@ -195,8 +194,6 @@ describe('StagedResultController', () => {getCanvasState: () => canvas,getDocument: () => canvas.document,history,- isGestureActive: () => false,- isPermitCurrent: () => true,now: () => '2026-07-16T01:00:00.000Z',});@@ -214,7 +211,7 @@ describe('StagedResultController', () => {expect(history.canRedo()).toBe(true);const controller = new StagedResultController({captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- capturePermit: () => ({ epoch: 1 }),+ concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),createEventId: () => 'event-1',createLayerId: () => 'layer-1',dispatchPrepared: (mutation, reducerAccepted, mirrorAccepted) => {@@ -244,8 +241,6 @@ describe('StagedResultController', () => {getCanvasState: () => reducerCanvas,getDocument: () => mirrorDocument,history,- isGestureActive: () => false,- isPermitCurrent: () => true,now: () => '2026-07-16T01:00:00.000Z',});@@ -265,7 +260,7 @@ describe('StagedResultController', () => {const history = createHistory();const controller = new StagedResultController({captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- capturePermit: () => ({ epoch: 1 }),+ concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),createEventId: () => 'event-1',createLayerId: () => 'layer-1',dispatchPrepared,@@ -273,8 +268,6 @@ describe('StagedResultController', () => {getCanvasState: () => canvas,getDocument: () => canvas?.document ?? null,history,- isGestureActive: () => false,- isPermitCurrent: () => true,now: () => '2026-07-16T01:00:00.000Z',});@@ -289,7 +282,7 @@ describe('StagedResultController', () => {const history = createHistory();const controller = new StagedResultController({captureInsertionAnchor: createTestInsertionAnchorCapture('p'),- capturePermit: () => ({ epoch: 1 }),+ concurrency: createTestEditConcurrency({ capturePermit: () => ({ epoch: 1 }) }),createEventId: () => 'event-1',createLayerId: () => 'layer-1',dispatchPrepared,@@ -297,8 +290,6 @@ describe('StagedResultController', () => {getCanvasState: () => canvas,getDocument: () => canvas.document,history,- isGestureActive: () => false,- isPermitCurrent: () => true,now: () => '2026-07-16T01:00:00.000Z',});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.tsindex eec3d35988..918b476c39 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts@@ -7,6 +7,7 @@ import type {} from '@workbench/canvas-engine/contracts';import type { FlatLayerInsertionAnchor } 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';@@ -15,8 +16,8 @@ import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertioimport { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';import { getCanvasStagingCandidateFingerprint } from '@workbench/canvasStagingView';-export interface StagedResultControllerOptions<Permit, Owner = symbol> {- readonly capturePermit: (owner?: Owner) => Permit | null;+export interface StagedResultControllerOptions {+ readonly concurrency: CanvasEditConcurrency;readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;readonly createEventId: () => string;readonly createLayerId: () => string;@@ -30,8 +31,6 @@ export interface StagedResultControllerOptions<Permit, Owner = symbol> {readonly getCanvasState: () => CanvasStateContractV2 | null;readonly getDocument: () => CanvasDocumentContractV2 | null;readonly history: History;- readonly isGestureActive: () => boolean;- readonly isPermitCurrent: (permit: Permit) => boolean;readonly now: () => string;}@@ -64,18 +63,18 @@ const createLayer = (};/** Owns guarded, project-bound acceptance of staged canvas results. */-export class StagedResultController<Permit, Owner = symbol> {+export class StagedResultController {private disposed = false;- constructor(private readonly options: StagedResultControllerOptions<Permit, Owner>) {}+ constructor(private readonly options: StagedResultControllerOptions) {}- commit(options: CommitStagedImageOptions, owner?: Owner): CommitStagedImageResult {+ commit(options: CommitStagedImageOptions, owner?: symbol): CommitStagedImageResult {const o = this.options;if (this.disposed) {return { status: 'missing' };}- const permit = o.capturePermit(owner);- if (!permit || o.isGestureActive()) {+ const permit = o.concurrency.capturePermit(owner);+ if (!permit || o.concurrency.isGestureActive()) {return { status: 'busy' };}const canvas = o.getCanvasState();@@ -90,7 +89,7 @@ export class StagedResultController<Permit, Owner = symbol> {) {return { status: 'missing' };}- if (!o.isPermitCurrent(permit) || o.isGestureActive()) {+ if (!o.concurrency.isPermitCurrent(permit) || o.concurrency.isGestureActive()) {return { status: 'busy' };}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/commandRefusal.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/commandRefusal.tsnew file mode 100644index 0000000000..7cc0f0c451--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/commandRefusal.ts@@ -0,0 +1,5 @@+/**+ * Why the document model refuses a command regardless of runtime state. Runtime transaction+ * outcomes live in `canvas-engine/editConcurrency.ts`; this vocabulary must never depend on them.+ */+export type CanvasCommandRefusal = 'missing' | 'locked' | 'invalid-target' | 'wrong-type' | 'unsupported';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.testStub.tsnew file mode 100644index 0000000000..23945b7a37--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.testStub.ts@@ -0,0 +1,11 @@+import type { CanvasEditConcurrency } from './editConcurrency';++export const createTestEditConcurrency = (overrides: Partial<CanvasEditConcurrency> = {}): CanvasEditConcurrency => ({+ canEdit: () => true,+ capturePermit: () => ({ epoch: 0 }),+ getEditRevision: () => 0,+ isGestureActive: () => false,+ isPermitCurrent: () => true,+ projectId: 'p',+ ...overrides,+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.tsnew file mode 100644index 0000000000..68835db0c0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editConcurrency.ts@@ -0,0 +1,54 @@+/**+ * The canvas edit-concurrency model. Controllers that capture permits receive+ * {@link CanvasEditConcurrency} as their mutation context; synchronous guards+ * read `canEdit` and `isGestureActive` from the same context. The engine keeps+ * four mechanisms behind it.+ *+ * Leases (`editGate.ts`, exposed as the engine's edit capability): at most one+ * exclusive canvas operation per engine (today `filter` and `select-object`).+ * A lease is acquired for an identity, carries an abort signal, and is+ * invalidated when the document is replaced, when the project changes, and on+ * any contract or pixel change to its own layer. The editing controller owns+ * the gate and hands it to canvas operations.+ *+ * Permits ({@link DocumentEditPermit}): a claim on the editing-lock epoch. A+ * commit captures one before async work and re-checks it before publishing;+ * every lock transition bumps the epoch, and the lock owner bypasses the lock.+ *+ * Gesture guard: structural commits, pixel commits and history replay refuse+ * while a pointer gesture owns the surface. Tools commit through their own+ * stroke path; the floating selection is guarded when it is lifted, not when+ * it is baked back.+ *+ * Project identity and edit revision: insertion anchors carry the engine's+ * project id and the edit revision they were captured at; export guards carry+ * the project id, the layer reference, its cache version and the document+ * generation they observed; structural commit options carry an expected+ * revision. The reducer refuses another project's anchor; a structural commit+ * refuses a mismatched revision as `stale`.+ *+ * {@link CanvasTransactionOutcome} is what the runtime reports when a+ * transaction could not run. The document model reports command refusals with+ * its own vocabulary (`canvas-engine/document/commandRefusal.ts`), which never+ * depends on runtime concepts; a runtime result type may list both, naming+ * each member through {@link SubsetOf} so a near-miss variant cannot compile.+ */+export interface CanvasEditConcurrency {+ readonly projectId: string;+ canEdit(owner?: symbol): boolean;+ capturePermit(owner?: symbol): DocumentEditPermit | null;+ isPermitCurrent(permit: DocumentEditPermit): boolean;+ isGestureActive(): boolean;+ /** Counts reducer document identities; a captured value is stale once any edit lands. */+ getEditRevision(): number;+}++export interface DocumentEditPermit {+ readonly epoch: number;+ readonly owner?: symbol;+}++export type CanvasTransactionOutcome = 'busy' | 'gesture-active' | 'stale' | 'aborted' | 'not-ready';++/** 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/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 534b67c25e..7532b4330a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -97,7 +97,6 @@ import { MaskResultController } from '@workbench/canvas-engine/controllers/maskRimport {createCanvasMutationContext,type CanvasMutationContext,- type DocumentEditPermit,} from '@workbench/canvas-engine/controllers/mutationContext';import { PersistenceController } from '@workbench/canvas-engine/controllers/persistenceController';import { PsdExportController } from '@workbench/canvas-engine/controllers/psdExportController';@@ -856,6 +855,27 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}};+ const documentEditOwner = Symbol('canvas-operation-document-edit-owner');+ // Later-defined engine values are passed as thunks: the context never+ // invokes them during construction.+ const mutationContext = createCanvasMutationContext({+ commitEdit: (intent) => mutationPort.commitEdit(intent),+ createLayerId,+ projectId,+ dispatch: (action, origin) => dispatchCanvasMutation(action, origin),+ 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(),+ subscribeReducer: (listener) => mutationPort.subscribe(listener),+ });const captureInsertionAnchor: CanvasMutationContext['captureInsertionAnchor'] = (stack, aboveId) =>mutationContext.captureInsertionAnchor(stack, aboveId);const editingController = new EditingController({@@ -901,12 +921,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCrequestRasterization: (layerId) => scheduleLayerRasterization([layerId]),},selectionImage: {- capturePermit: (owner) => captureDocumentEditPermit(owner),+ concurrency: mutationContext,decodeImage: (image, options) => rasterController.decodeImage(image, options),getDocument: () => mirror.getDocument(),- isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: (guard) => isLayerExportGuardCurrent(guard),- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),},text: {canEdit: () => canEditDocument(),@@ -1155,27 +1173,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCtrackPublishedLayerImage: (layer) => rasterController.trackPublishedLayerImage(layer),});- const documentEditOwner = Symbol('canvas-operation-document-edit-owner');- // Later-defined engine values (mirror, pipeline, prepared-cache helpers) are- // passed as thunks: the context never invokes them during construction.- const mutationContext = createCanvasMutationContext({- commitEdit: (intent) => mutationPort.commitEdit(intent),- createLayerId,- projectId,- dispatch: (action, origin) => dispatchCanvasMutation(action, origin),- 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(),- subscribeReducer: (listener) => mutationPort.subscribe(listener),- });structuralController = new StructuralLayerController({ctx: mutationContext,getSelectedLayerIds: resolveSelectedLayerIds,@@ -1201,8 +1198,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn result;};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 rasterExportController = new RasterExportController({backend,@@ -2244,11 +2239,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCrenderableSourceOf(layer)?.type === 'paint';const layerMutationController = new LayerMutationController({- canEdit: () => canEditDocument(),captureInsertionAnchor,- capturePermit: () => captureDocumentEditPermit(),captureCache: captureLayerCache,createLayerId,+ concurrency: mutationContext,discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),@@ -2260,8 +2254,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreChasPendingPixelWork: (layerId) => bitmapStore.hasPendingWork(layerId),history,installPrepared: installGeneratedPaintCache,- isGestureActive: () => pipeline.isGestureActive(),- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),needsPixelPersistence: layerNeedsPixelPersistence,preparePixels: prepareGeneratedPaintCache,prepareDuplicateRasterSource: prepareLayerRasterCache,@@ -2288,15 +2280,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst replaceSelectionFromImage = editingController.selectionImage.replace.bind(editingController.selectionImage);const maskResultController = new MaskResultController({- canEdit: (owner) => canEditDocument(owner),captureInsertionAnchor,+ concurrency: mutationContext,createLayerId,dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),getDocument: () => mirror.getDocument(),getReducerDocument,history,- isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,});const commitMaskImageResult = maskResultController.commit.bind(maskResultController);@@ -2326,16 +2317,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst stagedResultController = new StagedResultController({captureInsertionAnchor,- capturePermit: (owner) => captureDocumentEditPermit(owner),createEventId,createLayerId,+ concurrency: mutationContext,dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),getCanvasState: () => mutationPort.getCanvasState(),getDocument: () => mirror.getDocument(),history,- isGestureActive: () => pipeline.isGestureActive(),- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),now: () => new Date().toISOString(),});const commitStagedImage = stagedResultController.commit.bind(stagedResultController);@@ -2705,8 +2694,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbooleanMerge: {backend,captureInsertionAnchor,- capturePermit: () => captureDocumentEditPermit(),createLayerId,+ concurrency: mutationContext,dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId),@@ -2715,15 +2704,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreChistory,installPrepared: (prepared) => installGeneratedPaintCache(prepared),isCacheReady: isLayerCacheReadyForOp,- isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),preparePixels: prepareGeneratedPaintCache,},crop: {backend,captureCache: captureLayerCache,- capturePermit: () => captureDocumentEditPermit(),+ concurrency: mutationContext,discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),@@ -2732,16 +2719,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetReducerDocument,history,installPrepared: (prepared) => installGeneratedPaintCache(prepared),- isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),isSupportedSource: isSupportedExportSource,preparePixels: prepareGeneratedPaintCache,},copy: {captureInsertionAnchor,- capturePermit: () => captureDocumentEditPermit(),createLayerId,+ concurrency: mutationContext,dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId, { includeDisabled: true }),@@ -2749,16 +2734,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetReducerDocument,history,installPrepared: (prepared) => installGeneratedPaintCache(prepared),- isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),preparePixels: prepareGeneratedPaintCache,},extractMaskedArea: {backend,captureInsertionAnchor,- capturePermit: () => captureDocumentEditPermit(),createLayerId,+ concurrency: mutationContext,derived: derivedSurfaceCache,diagnostics,dispatchPrepared: dispatchPreparedMutation,@@ -2772,9 +2755,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreChistory,installPrepared: (prepared) => installGeneratedPaintCache(prepared),isCacheReady: isLayerCacheReadyForOp,- isGestureActive: () => pipeline.isGestureActive(),isGuardCurrent: isLayerExportGuardCurrent,- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),layers: layerCache,preparePixels: prepareGeneratedPaintCache,rasterize: (layerId) => rasterizeLayerPixelsForStructural(layerId),@@ -2783,16 +2764,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCnewRasterLayer: {backend,captureInsertionAnchor,- capturePermit: () => captureDocumentEditPermit(),createLayerId,+ concurrency: mutationContext,dispatchPrepared: dispatchPreparedMutation,endBurst: () => endNudgeBurst(),getDocument: () => mirror.getDocument(),getReducerDocument,history,installPrepared: (prepared) => installGeneratedPaintCache(prepared),- isGestureActive: () => pipeline.isGestureActive(),- isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit),layers: layerCache,preparePixels: prepareGeneratedPaintCache,selection: editingController.selection,