Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(canvas): harden layer raster operations
joshistoastdfe719b45865
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex e75b406761..acd6222307 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1143,8 +1143,11 @@"convertToInpaintMask": "Convert to inpaint mask","convertToRaster": "Convert to raster layer","convertToRegionalGuidance": "Convert to regional guidance",+ "cropBusy": "Finish the current canvas action before cropping this layer.","cropFailed": "The layer could not be cropped.","cropLayerToBbox": "Crop layer to bbox",+ "cropUnsupported": "This layer cannot be cropped.",+ "cropped": "Layer cropped to bbox.","cutaway": "Cutaway with layer below","cutout": "Cutout with layer below","delete": "Delete layer",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.tsindex c25608805d..a94d39afd2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts@@ -63,13 +63,19 @@ const maskDoc = (): CanvasDocumentContractV2 => ({});const createReactiveStore = (document: CanvasDocumentContractV2) => {- let state = { projects: [{ canvas: makeCanvas(document), id: 'p1' }] } as unknown as WorkbenchState;+ let state = {+ activeProjectId: 'p1',+ projects: [{ canvas: makeCanvas(document), id: 'p1' }],+ } as unknown as WorkbenchState;const listeners = new Set<() => void>();const dispatch = vi.fn<(action: WorkbenchAction) => void>();return {dispatch,setDocument: (next: CanvasDocumentContractV2, revision = 0) => {- state = { projects: [{ canvas: makeCanvas(next, revision), id: 'p1' }] } as unknown as WorkbenchState;+ state = {+ activeProjectId: 'p1',+ projects: [{ canvas: makeCanvas(next, revision), id: 'p1' }],+ } as unknown as WorkbenchState;for (const listener of listeners) {listener();}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 7ecc1a7e9e..da083e87aa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -92,7 +92,10 @@ const makeCanvas = (document: CanvasDocumentContractV2, documentRevision = 0): Cconst createFakeStore = (document: CanvasDocumentContractV2): { store: EngineStore; unsubscribe: ReturnType<typeof vi.fn> } => {- const state = { projects: [{ canvas: makeCanvas(document), id: 'p1' }] } as unknown as WorkbenchState;+ const state = {+ activeProjectId: 'p1',+ projects: [{ canvas: makeCanvas(document), id: 'p1' }],+ } as unknown as WorkbenchState;const unsubscribe = vi.fn();return {store: {@@ -129,21 +132,35 @@ const createEngine = () => {const createReactiveStore = (document: CanvasDocumentContractV2): {+ setActiveProjectId: (projectId: string) => void;setDocument: (next: CanvasDocumentContractV2, documentRevision?: number) => void;store: EngineStore;} => {let revision = 0;- let state = { projects: [{ canvas: makeCanvas(document), id: 'p1' }] } as unknown as WorkbenchState;+ let activeProjectId = 'p1';+ let state = {+ activeProjectId,+ projects: [{ canvas: makeCanvas(document), id: 'p1' }],+ } as unknown as WorkbenchState;const listeners = new Set<() => void>();+ const notify = (): void => {+ for (const listener of listeners) {+ listener();+ }+ };return {+ setActiveProjectId: (projectId) => {+ activeProjectId = projectId;+ state = { ...state, activeProjectId };+ notify();+ },setDocument: (next, documentRevision = revision) => {revision = documentRevision;state = {+ activeProjectId,projects: [{ canvas: makeCanvas(next, documentRevision), id: 'p1' }],} as unknown as WorkbenchState;- for (const listener of listeners) {- listener();- }+ notify();},store: {dispatch: vi.fn(),@@ -228,6 +245,44 @@ const createDeferred = <T>(): { promise: Promise<T>; resolve: (value: T) => voidreturn { promise, resolve };};+type RecordingRasterBackend = StubRasterBackend & {+ drawSourcesFor(surface: StubRasterSurface): string[];+ surfaceById(id: string): StubRasterSurface | undefined;+ surfaceId(surface: StubRasterSurface): string;+};++/**+ * Stateful raster backend for publication-race tests. Every scratch/cache+ * surface gets a stable id, as do the fake bitmaps supplied by each test. This+ * lets a test distinguish a decode drawn into an isolated scratch surface from+ * a scratch surface published into the live cache without exposing cache+ * internals from the production engine.+ */+const createRecordingRasterBackend = (): RecordingRasterBackend => {+ const base = createTestStubRasterBackend();+ let nextSurfaceId = 1;+ const surfaces = new Map<string, StubRasterSurface>();+ return {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ const id = `surface-${nextSurfaceId++}`;+ Object.assign(surface.canvas, { __recordingId: id });+ surfaces.set(id, surface);+ return surface;+ },+ drawSourcesFor: (surface) =>+ surface.callLog+ .filter((entry) => entry.op === 'drawImage')+ .map((entry) => (entry.args[0] as { __recordingId?: string }).__recordingId ?? 'unknown'),+ surfaceById: (id) => surfaces.get(id),+ surfaceId: (surface) => (surface.canvas as unknown as { __recordingId: string }).__recordingId,+ };+};++const recordingBitmap = (id: string): ImageBitmap =>+ ({ __recordingId: `bitmap-${id}`, close: vi.fn(), height: 10, width: 10 }) as unknown as ImageBitmap;+/** Flushes pending microtasks (promise chains) without depending on fake timers. */const flushMicrotasks = (): Promise<void> =>new Promise((resolve) => {@@ -283,15 +338,16 @@ describe('createCanvasEngine', () => {engine.dispose();});- it('exportLayerPixels refuses a layer while its cache is already rasterizing', async () => {+ it('exportLayerPixels shares the scheduled rasterization already running for the same source', async () => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);const pendingResolve = createDeferred<Blob>();+ const imageResolver = vi.fn(() => pendingResolve.promise);const { store } = createReactiveStore(makeDoc());const engine = createCanvasEngine({backend: createTestStubRasterBackend(),- imageResolver: () => pendingResolve.promise,+ imageResolver,projectId: 'p1',store,});@@ -301,10 +357,203 @@ describe('createCanvasEngine', () => {engine.attach(screen.element, overlay.element);raf.flush();- expect(await engine.exportLayerPixels('a')).toEqual({ status: 'not-ready' });+ const exported = engine.exportLayerPixels('a');+ expect(imageResolver).toHaveBeenCalledTimes(1);pendingResolve.resolve(new Blob());+ expect((await exported).status).toBe('ok');+ engine.dispose();+ });++ it('does not publish an older rasterization after a newer source wins', async () => {+ const first = createDeferred<Blob>();+ const second = createDeferred<Blob>();+ const blobA = new Blob(['A']);+ const blobB = new Blob(['B']);+ const bitmapA = recordingBitmap('A');+ const bitmapB = recordingBitmap('B');+ const backend = createRecordingRasterBackend();+ backend.createImageBitmap = vi.fn((blob) => Promise.resolve(blob === blobA ? bitmapA : bitmapB));+ const imageResolver = vi.fn((imageName: string) => (imageName === 'A' ? first.promise : second.promise));+ const document = { ...makeDoc(), layers: [rasterLayer('L', { imageName: 'A' })] };+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({ backend, imageResolver, projectId: 'p1', store });++ const exportA = engine.exportLayerPixels('L');+ setDocument({ ...document, layers: [rasterLayer('L', { imageName: 'B' })] });+ const exportB = engine.exportLayerPixels('L');++ second.resolve(blobB);+ const resultB = await exportB;+ expect(resultB.status).toBe('ok');+ if (resultB.status !== 'ok') {+ throw new Error('newer rasterization did not publish');+ }+ const publicationAfterB = backend.drawSourcesFor(resultB.surface as StubRasterSurface);++ first.resolve(blobA);+ expect(await exportA).toEqual({ status: 'not-ready' });+ expect(backend.drawSourcesFor(resultB.surface as StubRasterSurface)).toEqual(publicationAfterB);+ engine.dispose();+ });++ it('does not publish a rasterization from a replaced document that reuses the layer id', async () => {+ const first = createDeferred<Blob>();+ const second = createDeferred<Blob>();+ const blobA = new Blob(['document-A']);+ const blobB = new Blob(['document-B']);+ const backend = createRecordingRasterBackend();+ backend.createImageBitmap = vi.fn((blob) =>+ Promise.resolve(blob === blobA ? recordingBitmap('document-A') : recordingBitmap('document-B'))+ );+ const imageResolver = vi.fn((imageName: string) => (imageName === 'A' ? first.promise : second.promise));+ const document = { ...makeDoc(), layers: [rasterLayer('L', { imageName: 'A' })] };+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({ backend, imageResolver, projectId: 'p1', store });++ const oldExport = engine.exportLayerPixels('L');+ setDocument({ ...document, layers: [rasterLayer('L', { imageName: 'B' })] }, 1);+ const newExport = engine.exportLayerPixels('L');++ second.resolve(blobB);+ const newResult = await newExport;+ expect(newResult.status).toBe('ok');+ if (newResult.status !== 'ok') {+ throw new Error('replacement rasterization did not publish');+ }+ const publicationAfterReplacement = backend.drawSourcesFor(newResult.surface as StubRasterSurface);++ first.resolve(blobA);+ expect(await oldExport).toEqual({ status: 'not-ready' });+ expect(backend.drawSourcesFor(newResult.surface as StubRasterSurface)).toEqual(publicationAfterReplacement);+ engine.dispose();+ });++ it('shares one rasterization between concurrent exports of the same version', async () => {+ const blob = new Blob(['shared']);+ const imageResolver = vi.fn(() => Promise.resolve(blob));+ const { store } = createFakeStore({ ...makeDoc(), layers: [rasterLayer('L')] });+ const engine = createCanvasEngine({+ backend: createRecordingRasterBackend(),+ imageResolver,+ projectId: 'p1',+ store,+ });++ const [a, b] = await Promise.all([engine.exportLayerPixels('L'), engine.exportLayerPixels('L')]);++ expect(imageResolver).toHaveBeenCalledTimes(1);+ expect(a.status).toBe('ok');+ expect(b.status).toBe('ok');+ engine.dispose();+ });++ it('does not return a default export when the layer becomes disabled during rasterization', async () => {+ const pending = createDeferred<Blob>();+ const layer = rasterLayer('L');+ const document = { ...makeDoc(), layers: [layer] };+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => pending.promise,+ projectId: 'p1',+ store,+ });++ const exported = engine.exportLayerPixels('L');+ setDocument({ ...document, layers: [{ ...layer, isEnabled: false }] });+ pending.resolve(new Blob());++ expect(await exported).toEqual({ status: 'disabled' });+ engine.dispose();+ });++ it('publishes an empty paint cache without drawing a zero-sized scratch canvas', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const empty = { ...rasterLayer('empty'), source: { bitmap: null, type: 'paint' } as const };+ const { store } = createReactiveStore({ ...makeDoc(), layers: [empty] });+ const base = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];+ const engine = createCanvasEngine({+ backend: {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ },+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();++ engine.attach(screen.element, overlay.element);+ raf.flush();await flushMicrotasks();++ const zeroSizedDraws = surfaces.flatMap((surface) =>+ surface.callLog.filter((entry) => {+ if (entry.op !== 'drawImage') {+ return false;+ }+ const source = entry.args[0] as { height?: number; width?: number };+ return source.width === 0 || source.height === 0;+ })+ );+ expect(zeroSizedDraws).toEqual([]);+ expect(await engine.exportLayerPixels('empty')).toEqual({ status: 'empty' });+ engine.dispose();+ });++ it('retries a same-version rasterization after a one-time synchronous rasterizer failure', async () => {+ const shape: CanvasLayerSourceContract = {+ fill: '#fff',+ height: 10,+ kind: 'rect',+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 10,+ };+ const layer = { ...rasterLayer('shape'), source: shape };+ const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });+ const base = createTestStubRasterBackend();+ let shouldThrow = true;+ const engine = createCanvasEngine({+ backend: {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ const ctx = new Proxy(surface.ctx, {+ get(target, property, receiver) {+ if (property === 'fill') {+ return (...args: unknown[]) => {+ if (shouldThrow) {+ shouldThrow = false;+ throw new Error('one-time fill failure');+ }+ return Reflect.apply(target.fill, target, args);+ };+ }+ return Reflect.get(target, property, receiver);+ },+ });+ Object.defineProperty(surface, 'ctx', { value: ctx });+ return surface;+ },+ },+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });++ expect(await engine.exportLayerPixels('shape')).toEqual({ status: 'not-ready' });+ expect((await engine.exportLayerPixels('shape')).status).toBe('ok');engine.dispose();});@@ -375,99 +624,518 @@ describe('createCanvasEngine', () => {const result = await engine.exportBakedLayerBlob('a');- expect(result.status).toBe('ok');- if (result.status === 'ok') {- expect(result.rect).toEqual({ height: 10, width: 10, x: 0, y: 0 });- expect(result.blob.type).toBe('image/png');- expect(await result.blob.text()).toBe('stub-surface-10x10');- }+ expect(result.status).toBe('ok');+ if (result.status === 'ok') {+ expect(result.rect).toEqual({ height: 10, width: 10, x: 0, y: 0 });+ expect(result.blob.type).toBe('image/png');+ expect(await result.blob.text()).toBe('stub-surface-10x10');+ }+ engine.dispose();+ });++ it('returns a current LayerExportGuard from local, baked-pixel, and baked-blob exports', async () => {+ const { doc, engine } = createEngine();++ const local = await engine.exportLayerPixels('a');+ const baked = await engine.exportBakedLayerPixels('a');+ const blob = await engine.exportBakedLayerBlob('a');++ expect(local.status).toBe('ok');+ expect(baked.status).toBe('ok');+ expect(blob.status).toBe('ok');+ if (local.status !== 'ok' || baked.status !== 'ok' || blob.status !== 'ok') {+ throw new Error('expected successful exports');+ }+ for (const result of [local, baked, blob]) {+ expect(result.guard).toMatchObject({ layer: doc.layers[0], layerId: 'a', projectId: 'p1' });+ expect(engine.isLayerExportGuardCurrent(result.guard)).toBe(true);+ }+ engine.dispose();+ });++ it('invalidates a LayerExportGuard when the immutable layer contract changes', async () => {+ const document = makeDoc();+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const exported = await engine.exportLayerPixels('a');+ expect(exported.status).toBe('ok');+ if (exported.status !== 'ok') {+ throw new Error('expected successful export');+ }++ setDocument({ ...document, layers: [{ ...document.layers[0]!, opacity: 0.5 }] });++ expect(engine.isLayerExportGuardCurrent(exported.guard)).toBe(false);+ engine.dispose();+ });++ it('invalidates a LayerExportGuard when the document is replaced with the same layer object', async () => {+ const document = makeDoc();+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const exported = await engine.exportLayerPixels('a');+ expect(exported.status).toBe('ok');+ if (exported.status !== 'ok') {+ throw new Error('expected successful export');+ }++ setDocument({ ...document, layers: document.layers }, 1);++ expect(engine.isLayerExportGuardCurrent(exported.guard)).toBe(false);+ engine.dispose();+ });++ it('invalidates a LayerExportGuard when another project becomes active', async () => {+ const document = makeDoc();+ const { setActiveProjectId, store } = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const exported = await engine.exportLayerPixels('a');+ expect(exported.status).toBe('ok');+ if (exported.status !== 'ok') {+ throw new Error('expected successful export');+ }++ setActiveProjectId('p2');++ expect(engine.isLayerExportGuardCurrent(exported.guard)).toBe(false);+ engine.dispose();+ });++ it('does not return an encoded layer blob after its export guard becomes stale', async () => {+ const encoded = createDeferred<Blob>();+ const base = createTestStubRasterBackend();+ const encodeSurface = vi.fn(() => encoded.promise);+ const document = makeDoc();+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: { ...base, encodeSurface },+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });++ const pending = engine.exportBakedLayerBlob('a');+ await vi.waitFor(() => expect(encodeSurface).toHaveBeenCalledOnce());+ setDocument({ ...document, layers: [{ ...document.layers[0]!, opacity: 0.5 }] });+ encoded.resolve(new Blob(['stale'], { type: 'image/png' }));++ expect(await pending).toEqual({ status: 'not-ready' });+ engine.dispose();+ });++ it('invalidates a LayerExportGuard when live cache pixels are edited', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal('Path2D', class FakePath2D {});+ const document = paintDoc();+ const layer = document.layers[0];+ if (!layer || layer.type !== 'raster') {+ throw new Error('expected paint layer');+ }+ const persisted: CanvasDocumentContractV2 = {+ ...document,+ layers: [+ {+ ...layer,+ source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' },+ },+ ],+ };+ const { projectId, store } = createReducerBackedStore(persisted);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const overlay = createInputCanvas();+ const screen = createInputCanvas();+ engine.attach(screen.element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ const exported = await engine.exportLayerPixels(layer.id);+ expect(exported.status).toBe('ok');+ if (exported.status !== 'ok') {+ throw new Error('expected successful export');+ }++ engine.setTool('brush');+ overlay.fire('pointerdown', pointerAt(5, 5));+ overlay.fire('pointermove', pointerAt(10, 10));+ overlay.fire('pointerup', pointerAt(10, 10, { buttons: 0 }));++ expect(engine.isLayerExportGuardCurrent(exported.guard)).toBe(false);+ engine.dispose();+ });++ it('cropLayerToBbox crops only the bbox overlap and restores exact contracts/cache snapshots on undo/redo', async () => {+ const layer = {+ ...rasterLayer('a'),+ adjustments: { brightness: 0.2, contrast: -0.1, saturation: 0.3 },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 5, y: 5 },+ };+ const document = { ...makeDoc(), bbox: { height: 8, width: 10, x: 8, y: 2 }, layers: [layer] };+ const { projectId, store } = createReducerBackedStore(document);+ const backend = createRecordingRasterBackend();+ const bitmapStore = createSpyBitmapStore();+ const engine = createCanvasEngine({+ backend,+ bitmapStore,+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const beforeContract = structuredClone(engine.getDocument()!.layers[0]!);+ const beforeExport = await engine.exportLayerPixels('a');+ expect(beforeExport.status).toBe('ok');+ if (beforeExport.status !== 'ok') {+ throw new Error('expected original cache pixels');+ }+ const thumbnailListener = vi.fn();+ engine.stores.thumbnailVersion.subscribeKey('a', thumbnailListener);+ bitmapStore.markLayerDirty.mockClear();++ expect(await engine.cropLayerToBbox('a')).toEqual({ status: 'cropped' });++ const afterContract = engine.getDocument()!.layers[0]!;+ expect(afterContract).toEqual({+ blendMode: 'normal',+ id: 'a',+ isEnabled: true,+ isLocked: false,+ name: 'a',+ opacity: 1,+ source: { bitmap: null, offset: { x: 8, y: 5 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ });+ expect('adjustments' in afterContract).toBe(false);+ expect(bitmapStore.markLayerDirty).toHaveBeenCalledTimes(1);+ expect(thumbnailListener).toHaveBeenCalledTimes(1);+ const forwardExport = await engine.exportLayerPixels('a');+ expect(forwardExport.status).toBe('ok');+ if (forwardExport.status !== 'ok') {+ throw new Error('expected cropped cache pixels');+ }+ expect(forwardExport.rect).toEqual({ height: 5, width: 7, x: 8, y: 5 });+ const forwardSources = backend.drawSourcesFor(forwardExport.surface as StubRasterSurface);++ engine.undo();+ expect(engine.getDocument()!.layers[0]).toEqual(beforeContract);+ expect(bitmapStore.markLayerDirty).toHaveBeenCalledTimes(2);+ expect(thumbnailListener).toHaveBeenCalledTimes(2);+ const undoExport = await engine.exportLayerPixels('a');+ expect(undoExport.status).toBe('ok');+ if (undoExport.status !== 'ok') {+ throw new Error('expected restored cache pixels');+ }+ const undoSources = backend.drawSourcesFor(undoExport.surface as StubRasterSurface);+ const beforeSnapshot = backend.surfaceById(undoSources.at(-1)!);+ expect(beforeSnapshot).toBeDefined();+ expect(backend.drawSourcesFor(beforeSnapshot!)).toContain(+ backend.surfaceId(beforeExport.surface as StubRasterSurface)+ );++ engine.redo();+ expect(engine.getDocument()!.layers[0]).toEqual(afterContract);+ expect(bitmapStore.markLayerDirty).toHaveBeenCalledTimes(3);+ expect(thumbnailListener).toHaveBeenCalledTimes(3);+ const redoExport = await engine.exportLayerPixels('a');+ expect(redoExport.status).toBe('ok');+ if (redoExport.status !== 'ok') {+ throw new Error('expected redone cache pixels');+ }+ expect(backend.drawSourcesFor(redoExport.surface as StubRasterSurface)).toEqual(forwardSources);+ engine.dispose();+ });++ it('cropLayerToBbox preserves control adapter settings while removing the baked filter', async () => {+ const control: CanvasLayerContract = {+ adapter: {+ beginEndStepPct: [0.1, 0.9],+ controlMode: 'more_control',+ kind: 'controlnet',+ model: 'm',+ weight: 0.7,+ },+ blendMode: 'screen',+ filter: { settings: { low: 10 }, type: 'canny' },+ id: 'control',+ isEnabled: true,+ isLocked: false,+ name: 'Control',+ opacity: 0.6,+ source: { image: { height: 10, imageName: 'control', width: 10 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: true,+ };+ const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [control] };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(await engine.cropLayerToBbox('control')).toEqual({ status: 'cropped' });+ const cropped = engine.getDocument()!.layers[0];+ expect(cropped).toMatchObject({+ adapter: control.adapter,+ source: { bitmap: null, offset: { x: 2, y: 3 }, type: 'paint' },+ type: 'control',+ withTransparencyEffect: true,+ });+ expect(cropped && 'filter' in cropped).toBe(false);+ engine.dispose();+ });++ it('cropLayerToBbox preserves mask fill/noise/denoise configuration while replacing pixels and offset', async () => {+ const layer: CanvasInpaintMaskLayerContract = {+ ...maskLayer('mask'),+ denoiseLimit: 0.45,+ mask: {+ bitmap: { height: 10, imageName: 'mask-img', width: 10 },+ fill: { color: '#123456', style: 'crosshatch' },+ offset: { x: 0, y: 0 },+ },+ noiseLevel: 0.25,+ };+ const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [layer] };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(await engine.cropLayerToBbox('mask')).toEqual({ status: 'cropped' });+ expect(engine.getDocument()!.layers[0]).toMatchObject({+ denoiseLimit: 0.45,+ mask: { bitmap: null, fill: layer.mask.fill, offset: { x: 2, y: 3 } },+ noiseLevel: 0.25,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ });+ engine.dispose();+ });++ it('cropLayerToBbox preserves regional prompts and reference images while replacing mask pixels', async () => {+ const layer: CanvasLayerContract = {+ autoNegative: false,+ blendMode: 'normal',+ id: 'region',+ isEnabled: true,+ isLocked: false,+ mask: {+ bitmap: { height: 10, imageName: 'region-mask', width: 10 },+ fill: { color: '#abcdef', style: 'vertical' },+ },+ name: 'Region',+ negativePrompt: 'negative',+ opacity: 0.8,+ positivePrompt: 'positive',+ referenceImages: [{ config: { image: null, type: 'flux2_reference_image' }, id: 'reference', isEnabled: true }],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+ };+ const document = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [layer] };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(await engine.cropLayerToBbox('region')).toEqual({ status: 'cropped' });+ expect(engine.getDocument()!.layers[0]).toMatchObject({+ autoNegative: false,+ mask: { bitmap: null, fill: layer.mask.fill, offset: { x: 2, y: 3 } },+ negativePrompt: 'negative',+ positivePrompt: 'positive',+ referenceImages: layer.referenceImages,+ type: 'regional_guidance',+ });+ engine.dispose();+ });++ it('cropLayerToBbox returns empty without mutation when the layer and bbox do not overlap', async () => {+ const document = { ...makeDoc(), bbox: { height: 5, width: 5, x: 50, y: 50 } };+ const { projectId, store } = createReducerBackedStore(document);+ const bitmapStore = createSpyBitmapStore();+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore,+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const before = engine.getDocument();++ expect(await engine.cropLayerToBbox('a')).toEqual({ status: 'empty' });+ expect(engine.getDocument()).toBe(before);+ expect(engine.stores.canUndo.get()).toBe(false);+ expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ engine.dispose();+ });++ it('cropLayerToBbox reports missing, locked, unsupported, and not-ready layers explicitly', async () => {+ const polygon: CanvasLayerSourceContract = {+ fill: '#000',+ height: 10,+ kind: 'polygon',+ points: [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 5, y: 10 },+ ],+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 10,+ };+ const layers = [+ { ...rasterLayer('locked'), isLocked: true },+ { ...rasterLayer('polygon'), source: polygon },+ rasterLayer('pending'),+ ];+ const document = { ...makeDoc(), layers };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.reject(new Error('decode failed')),+ projectId,+ store,+ });++ expect(await engine.cropLayerToBbox('missing')).toEqual({ status: 'missing' });+ expect(await engine.cropLayerToBbox('locked')).toEqual({ status: 'locked' });+ expect(await engine.cropLayerToBbox('polygon')).toEqual({ status: 'unsupported' });+ expect(await engine.cropLayerToBbox('pending')).toEqual({ status: 'not-ready' });engine.dispose();});- it('cropLayerToBbox replaces a raster/control source with bbox-sized paint pixels at identity', async () => {- const doc = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 } };- const { store } = createFakeStore(doc);- const dispatch = store.dispatch as Mock;- const base = createTestStubRasterBackend();- const surfaces: StubRasterSurface[] = [];+ it('cropLayerToBbox returns not-ready without mutation when the source changes during rasterization', async () => {+ const pending = createDeferred<Blob>();+ const document = { ...makeDoc(), layers: [rasterLayer('a', { imageName: 'A' })] };+ const { setDocument, store } = createReactiveStore(document);+ const bitmapStore = createSpyBitmapStore();const engine = createCanvasEngine({- backend: {- ...base,- createSurface: (width, height) => {- const surface = base.createSurface(width, height);- surfaces.push(surface);- return surface;- },- },- imageResolver: () => Promise.resolve(new Blob()),+ backend: createTestStubRasterBackend(),+ bitmapStore,+ imageResolver: () => pending.promise,projectId: 'p1',store,});- expect(await engine.cropLayerToBbox('a')).toBe(true);+ const crop = engine.cropLayerToBbox('a');+ setDocument({ ...document, layers: [rasterLayer('a', { imageName: 'B' })] });+ pending.resolve(new Blob());- expect(dispatch.mock.calls.map((call) => call[0])).toEqual(- expect.arrayContaining([- { id: 'a', source: { bitmap: null, offset: { x: 2, y: 3 }, type: 'paint' }, type: 'updateCanvasLayerSource' },- {- id: 'a',- patch: { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 } },- type: 'updateCanvasLayer',- },- ])- );- const cropped = surfaces.find((surface) => surface.width === 6 && surface.height === 7);- expect(cropped?.callLog.some((entry) => entry.op === 'drawImage')).toBe(true);+ expect(await crop).toEqual({ status: 'not-ready' });+ expect(store.dispatch).not.toHaveBeenCalled();+ expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();engine.dispose();});- it('cropLayerToBbox replaces a mask bitmap while preserving mask fill', async () => {- const layer: CanvasInpaintMaskLayerContract = {- ...maskLayer('mask'),- mask: { bitmap: { height: 10, imageName: 'mask-img', width: 10 }, fill: { color: '#e07575', style: 'diagonal' } },+ it('cropLayerToBbox reports busy during an open gesture', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal('Path2D', class FakePath2D {});+ const paint = {+ ...rasterLayer('paint'),+ source: { bitmap: { height: 10, imageName: 'paint', width: 10 }, type: 'paint' as const },};- const doc = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [layer] };- const { store } = createFakeStore(doc);- const dispatch = store.dispatch as Mock;- const engine = createCanvasEngine({+ const busyHarness = createReducerBackedStore({ ...makeDoc(), layers: [paint], selectedLayerId: 'paint' });+ const busyEngine = createCanvasEngine({backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),imageResolver: () => Promise.resolve(new Blob()),- projectId: 'p1',- store,+ projectId: busyHarness.projectId,+ store: busyHarness.store,});+ const overlay = createInputCanvas();+ const screen = createInputCanvas();+ busyEngine.attach(screen.element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ busyEngine.setTool('brush');+ overlay.fire('pointerdown', pointerAt(2, 2));+ expect(await busyEngine.cropLayerToBbox('paint')).toEqual({ status: 'busy' });+ overlay.fire('pointerup', pointerAt(2, 2, { buttons: 0 }));+ busyEngine.dispose();+ });- expect(await engine.cropLayerToBbox('mask')).toBe(true);-- expect(dispatch.mock.calls.map((call) => call[0])).toEqual(- expect.arrayContaining([- {- config: { layerType: 'inpaint_mask', mask: { bitmap: null, offset: { x: 2, y: 3 } } },- id: 'mask',- type: 'updateCanvasLayerConfig',- },- {- id: 'mask',- patch: { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 } },- type: 'updateCanvasLayer',+ it('cropLayerToBbox reports failed for unexpected raster errors', async () => {+ const base = createTestStubRasterBackend();+ const failedHarness = createReducerBackedStore({+ ...makeDoc(),+ bbox: { height: 7, width: 6, x: 2, y: 3 },+ });+ const failedEngine = createCanvasEngine({+ backend: {+ ...base,+ createSurface: (width, height) => {+ if (width === 6 && height === 7) {+ throw new Error('crop allocation failed');+ }+ return base.createSurface(width, height);},- ])- );- engine.dispose();+ },+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: failedHarness.projectId,+ store: failedHarness.store,+ });+ expect(await failedEngine.cropLayerToBbox('a')).toEqual({+ message: 'crop allocation failed',+ status: 'failed',+ });+ failedEngine.dispose();});- it('cropLayerToBbox refuses locked layers', async () => {- const doc = { ...makeDoc(), layers: [{ ...rasterLayer('a'), isLocked: true }] };- const { store } = createFakeStore(doc);- const dispatch = store.dispatch as Mock;+ it('copyLayerToRaster does not mutate another project after its export resolves', async () => {+ const pending = createDeferred<Blob>();+ const document = makeDoc();+ const { setActiveProjectId, store } = createReactiveStore(document);const engine = createCanvasEngine({backend: createTestStubRasterBackend(),- imageResolver: () => Promise.resolve(new Blob()),+ imageResolver: () => pending.promise,projectId: 'p1',store,});- expect(await engine.cropLayerToBbox('a')).toBe(false);- expect(dispatch).not.toHaveBeenCalled();+ const copy = engine.copyLayerToRaster('a');+ setActiveProjectId('p2');+ pending.resolve(new Blob());++ expect(await copy).toBeNull();+ expect(store.dispatch).not.toHaveBeenCalled();engine.dispose();});@@ -887,40 +1555,27 @@ describe('ensureLayerCaches: edit-during-rasterize race', () => {// An edit lands mid-flight: same layer id, new object reference, new source.setDocument({ ...doc, layers: [rasterLayer('a', { imageName: 'a-v2' })] });- // A frame runs while the first rasterize is still in flight: the in-flight- // guard must prevent a second dispatch here.- raf.flush();- expect(resolver).toHaveBeenCalledTimes(1);-- // The first (now-stale) rasterize resolves with the OLD pixels.- deferreds.get('a')!.resolve(new Blob());- await flushMicrotasks();-- // Its resolution scheduled a follow-up frame; running it must re-dispatch a- // rasterize for the layer, this time picking up the newest source.+ // A frame runs while the first rasterize is still in flight. The source no+ // longer matches that job, so a fresh isolated job starts immediately.raf.flush();expect(resolver).toHaveBeenCalledTimes(2);expect(resolver).toHaveBeenNthCalledWith(2, 'a-v2');- // Critical assertion: the stale completion must NOT have notified thumbnail- // subscribers. If it did, subscribers would have redrawn from the surface- // while it still held the OLD pixels (the fresh rasterize hasn't finished- // yet), and -- because the store's `set` is equality-guarded -- the later,- // real notification for the fresh pixels would be silently swallowed since- // it lands on the same version number the stale completion already wrote.- expect(thumbnailListener).not.toHaveBeenCalled();-- // Resolve the second (fresh) rasterize so nothing is left in flight.+ // The newer rasterize wins and publishes while the old decode is pending.deferreds.get('a-v2')!.resolve(new Blob());await flushMicrotasks();raf.flush();-- // Now that fresh pixels have actually landed, subscribers must be notified- // exactly once -- not zero times (swallowed by the equality guard) and not- // twice (which would imply the stale completion also fired).expect(thumbnailListener).toHaveBeenCalledTimes(1);expect(engine.stores.thumbnailVersion.get('a')).toBe(1);+ // The older decode resolves afterwards. It may finish its isolated scratch+ // draw, but it must neither publish nor notify subscribers.+ deferreds.get('a')!.resolve(new Blob());+ await flushMicrotasks();+ raf.flush();+ expect(thumbnailListener).toHaveBeenCalledTimes(1);+ expect(resolver).toHaveBeenCalledTimes(2);+unsubscribe();engine.dispose();});@@ -1960,6 +2615,33 @@ describe('boolean raster operations', () => {engine.dispose();});+ it('does not publish a boolean merge into another active project after awaiting exports', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const { setActiveProjectId, store } = createReactiveStore(twoPaintDoc());+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();+ engine.attach(screen.element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ (store.dispatch as Mock).mockClear();++ const merge = engine.booleanMergeRasterLayers('upper', 'intersect');+ setActiveProjectId('p2');++ expect(await merge).toBe('not-ready');+ expect(store.dispatch).not.toHaveBeenCalled();+ engine.dispose();+ });+it('refuses the operation until both raster caches are ready', async () => {const { engine, raf } = setup();raf.flush();@@ -2120,6 +2802,170 @@ describe('extract masked canvas area', () => {engine.dispose();});+ it('extracts enabled raster layers but never control layers', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const raster = rasterLayer('raster');+ const control: CanvasLayerContract = {+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'normal',+ id: 'control',+ isEnabled: true,+ isLocked: false,+ name: 'Control',+ opacity: 1,+ source: { image: { height: 10, imageName: 'control', width: 10 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: false,+ };+ const mask: CanvasInpaintMaskLayerContract = {+ ...maskLayer('mask'),+ mask: {+ ...maskLayer('mask').mask,+ bitmap: { height: 10, imageName: 'mask', width: 10 },+ },+ };+ const document = { ...makeDoc(), layers: [mask, raster, control], selectedLayerId: 'mask' };+ const { projectId, store } = createReducerBackedStore(document);+ const base = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];+ const engine = createCanvasEngine({+ backend: {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ },+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();+ engine.attach(screen.element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ const rasterExport = await engine.exportLayerPixels(raster.id);+ const controlExport = await engine.exportLayerPixels(control.id);+ expect(rasterExport.status).toBe('ok');+ expect(controlExport.status).toBe('ok');+ if (rasterExport.status !== 'ok' || controlExport.status !== 'ok') {+ throw new Error('fixture layers did not rasterize');+ }++ expect((await engine.extractMaskedArea(mask.id)).status).toBe('extracted');++ const extractedPixels = surfaces.find((surface) =>+ surface.callLog.some(+ (entry) =>+ entry.op === 'set' && entry.args[0] === 'globalCompositeOperation' && entry.args[1] === 'destination-in'+ )+ );+ const compositeSources = extractedPixels?.callLog+ .filter((entry) => entry.op === 'drawImage')+ .map((entry) => entry.args[0]);+ expect(compositeSources).toContain(rasterExport.surface.canvas);+ expect(compositeSources).not.toContain(controlExport.surface.canvas);+ engine.dispose();+ });++ it('skips enabled raster layers that have no persisted or live pixels', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const document = maskedDoc();+ const blank: CanvasRasterLayerContractV2 = {+ blendMode: 'normal',+ id: 'blank',+ isEnabled: true,+ isLocked: false,+ name: 'Blank',+ opacity: 1,+ source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ };+ document.layers.splice(2, 0, blank);+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();+ engine.attach(screen.element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();++ expect((await engine.extractMaskedArea('mask')).status).toBe('extracted');+ engine.dispose();+ });++ it('does not extract stale contributor pixels after a source change during await', async () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const document = maskedDoc();+ const { setDocument, store } = createReactiveStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();+ engine.attach(screen.element, overlay.element);+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ (store.dispatch as Mock).mockClear();++ const extraction = engine.extractMaskedArea('mask');+ setDocument({+ ...document,+ layers: document.layers.map((layer) =>+ layer.id === 'upper' && layer.type === 'raster'+ ? {+ ...layer,+ source: {+ bitmap: { height: 40, imageName: 'upper-v2', width: 40 },+ offset: { x: 0, y: 0 },+ type: 'paint',+ },+ }+ : layer+ ),+ });++ expect(await extraction).toEqual({ status: 'not-ready' });+ expect(store.dispatch).not.toHaveBeenCalled();+ engine.dispose();+ });++ it('refuses extraction from a locked mask', async () => {+ const document = maskedDoc();+ document.layers[0] = { ...document.layers[0]!, isLocked: true };+ const { projectId, store } = createReducerBackedStore(document);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(await engine.extractMaskedArea('mask')).toEqual({ status: 'unsupported' });+ engine.dispose();+ });+it('refuses extraction until the mask and contributor caches are ready', async () => {const { engine, raf } = setup();raf.flush();@@ -2167,20 +3013,24 @@ describe('extract masked canvas area', () => {* mirror re-reads between steps — the no-op mock store cannot exercise a* multi-step fold.*/-const createReducerBackedStore = (document: CanvasDocumentContractV2): { projectId: string; store: EngineStore } => {+const createReducerBackedStore = (+ document: CanvasDocumentContractV2+): { dispatch: Mock<(action: WorkbenchAction) => void>; projectId: string; store: EngineStore } => {let state = createInitialWorkbenchState();const projectId = state.projects[0]!.id;state = workbenchReducer(state, { document, type: 'replaceCanvasDocument' });const listeners = new Set<() => void>();+ const dispatch = vi.fn((action: WorkbenchAction) => {+ state = workbenchReducer(state, action);+ for (const listener of listeners) {+ listener();+ }+ });return {+ dispatch,projectId,store: {- dispatch: (action) => {- state = workbenchReducer(state, action);- for (const listener of listeners) {- listener();- }- },+ dispatch,getState: () => state,subscribe: (listener) => {listeners.add(listener);@@ -3570,6 +4420,61 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',engine.dispose();});+ it('commitLayerConversion requires the caller to hold the immutable live layer object', async () => {+ const { dispatch, projectId, store } = createReducerBackedStore(makeDoc());+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ expect((await engine.exportLayerPixels('a')).status).toBe('ok');+ const live = engine.getDocument()!.layers[0]!;+ if (live.type !== 'raster') {+ throw new Error('expected raster layer');+ }+ const converted: CanvasLayerContract = {+ ...live,+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ type: 'control',+ withTransparencyEffect: false,+ };+ dispatch.mockClear();++ expect(engine.commitLayerConversion('Convert', structuredClone(live), converted)).toBe(false);+ expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'convertCanvasLayer' }));+ expect(engine.getDocument()!.layers[0]!.type).toBe('raster');+ engine.dispose();+ });++ it('commitLayerConversion refuses conversion when the live layer is locked', async () => {+ const { dispatch, projectId, store } = createReducerBackedStore(makeDoc());+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ expect((await engine.exportLayerPixels('a')).status).toBe('ok');+ const expectedUnlocked = engine.getDocument()!.layers[0]!;+ if (expectedUnlocked.type !== 'raster') {+ throw new Error('expected raster layer');+ }+ const converted: CanvasLayerContract = {+ ...expectedUnlocked,+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ type: 'control',+ withTransparencyEffect: false,+ };+ dispatch({ id: expectedUnlocked.id, patch: { isLocked: true }, type: 'updateCanvasLayer' });+ dispatch.mockClear();++ expect(engine.commitLayerConversion('Convert', expectedUnlocked, converted)).toBe(false);+ expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'convertCanvasLayer' }));+ expect(engine.getDocument()!.layers[0]).toMatchObject({ isLocked: true, type: 'raster' });+ engine.dispose();+ });+it('flushing after a prop-only change persists the painted (non-blank) surface', async () => {const { bitmapStore, engine, paintCache, raf, setDocument } = await paintOneStroke();const clearsBefore = fullClearCount(paintCache);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 7682a364f2..4fbda50287 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -138,6 +138,11 @@ export type ExtractMaskedAreaResult =| { status: 'extracted'; layerId: string }| { status: 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty' };+export type CropLayerResult =+ | { status: 'cropped' }+ | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | 'not-ready' | 'busy' }+ | { status: 'failed'; message: string };+/*** Result of {@link CanvasEngine.exportRasterLayersToPsd}: `'exported'` on* success, `'nothing'` when there are no raster layers with content, `'too-large'`@@ -151,8 +156,17 @@ export interface ExportLayerPixelsOptions {includeDisabled?: boolean;}+/** Opaque snapshot identity carried through async layer operations. */+export interface LayerExportGuard {+ readonly projectId: string;+ readonly layerId: string;+ readonly layer: CanvasLayerContract;+ readonly cacheVersion: number;+ readonly documentGeneration: number;+}+export type ExportLayerPixelsResult =- | { status: 'ok'; surface: RasterSurface; rect: Rect }+ | { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' };export interface ExportBakedLayerPixelsOptions extends ExportLayerPixelsOptions {@@ -163,9 +177,45 @@ export interface ExportBakedLayerPixelsOptions extends ExportLayerPixelsOptionsexport type ExportBakedLayerPixelsResult = ExportLayerPixelsResult;export type ExportBakedLayerBlobResult =- | { status: 'ok'; blob: Blob; rect: Rect }+ | { status: 'ok'; blob: Blob; rect: Rect; guard: LayerExportGuard }| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' };+interface RasterizationJob {+ version: number;+ documentGeneration: number;+ source: CanvasLayerSourceContract;+ promise: Promise<'published' | 'stale'>;+}++/** Structural equality for JSON-safe canvas contracts (including synthetic mask paint sources). */+const isDeeplyEqual = (left: unknown, right: unknown): boolean => {+ if (Object.is(left, right)) {+ return true;+ }+ if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) {+ return false;+ }+ if (Array.isArray(left) || Array.isArray(right)) {+ return (+ Array.isArray(left) &&+ Array.isArray(right) &&+ left.length === right.length &&+ left.every((value, index) => isDeeplyEqual(value, right[index]))+ );+ }+ const leftRecord = left as Record<string, unknown>;+ const rightRecord = right as Record<string, unknown>;+ const leftKeys = Object.keys(leftRecord);+ const rightKeys = Object.keys(rightRecord);+ return (+ leftKeys.length === rightKeys.length &&+ leftKeys.every(+ (key) =>+ Object.prototype.hasOwnProperty.call(rightRecord, key) && isDeeplyEqual(leftRecord[key], rightRecord[key])+ )+ );+};+/** The minimal workbench store the engine depends on. */export interface EngineStore {getState(): WorkbenchState;@@ -281,7 +331,7 @@ export interface CanvasEngine {* The complete change is one engine-history entry.*/booleanMergeRasterLayers(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult>;- /** Extracts the enabled raster/control composite through one inpaint mask. */+ /** Extracts the enabled raster-layer composite through one inpaint mask. */extractMaskedArea(maskLayerId: string): Promise<ExtractMaskedAreaResult>;/*** Folds ALL visible mergeable raster layers together (the raster group-header@@ -319,8 +369,8 @@ export interface CanvasEngine {/*** Ensures one layer's pixels are rasterized in the shared layer cache and returns* the cache surface plus its layer-local content rect. Read-only: no dispatches,- * no history entry, no document mutation. Returns `not-ready` rather than racing- * an already in-flight rasterize, so callers never export stale/blank pixels.+ * no history entry, no document mutation. Joins an equivalent in-flight+ * rasterization and returns `not-ready` only when that work becomes stale or fails.*/exportLayerPixels(layerId: string, options?: ExportLayerPixelsOptions): Promise<ExportLayerPixelsResult>;/**@@ -334,12 +384,14 @@ export interface CanvasEngine {): Promise<ExportBakedLayerPixelsResult>;/** Encodes {@link exportBakedLayerPixels} as a PNG blob for save/copy/upload actions. */exportBakedLayerBlob(layerId: string, options?: ExportBakedLayerPixelsOptions): Promise<ExportBakedLayerBlobResult>;+ /** True only while the exact exported layer/cache/document/project snapshot remains live. */+ isLayerExportGuardCurrent(guard: LayerExportGuard): boolean;/**- * Destructively crops a layer to the current bbox: bakes transform/adjustments- * into bbox-sized paint/mask pixels, resets transform to identity, and persists- * through the normal bitmap-store path. A no-op for locked/missing/unsupported layers.+ * Destructively crops a layer to its overlap with the current bbox, baking its+ * transform/adjustments into content-sized paint/mask pixels. The full layer+ * contract and cache snapshot are restored by one undoable history entry.*/- cropLayerToBbox(layerId: string): Promise<boolean>;+ cropLayerToBbox(layerId: string): Promise<CropLayerResult>;/** Creates a new raster paint layer above `layerId` from that layer's baked pixels. */copyLayerToRaster(layerId: string): Promise<string | null>;/**@@ -362,8 +414,8 @@ export interface CanvasEngine {commitStructural(label: string, forward: WorkbenchAction, inverse: WorkbenchAction): void;/** Adds a contract-built layer while preserving the source layer's live cache pixels. */commitLayerCopy(label: string, sourceLayerId: string, layer: CanvasLayerContract, index: number): boolean;- /** Converts a layer contract in place while preserving its live cache pixels through undo/redo. */- commitLayerConversion(label: string, before: CanvasLayerContract, after: CanvasLayerContract): boolean;+ /** Converts the expected immutable live layer while preserving its cache pixels through undo/redo. */+ commitLayerConversion(label: string, expectedLiveLayer: CanvasLayerContract, after: CanvasLayerContract): boolean;/*** Updates the active transform session's live transform (a numeric options-bar* edit). Refreshes the preview; no dispatch until Apply. A no-op with no session.@@ -616,8 +668,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {/** Layer id → decoded image name, so removed layers can release their bitmaps. */const trackedImageNames = new Map<string, string>();- /** Layer ids with an in-flight rasterization, to avoid re-triggering each frame. */- const inFlight = new Set<string>();+ /** The newest isolated rasterization job for each layer id. */+ const layerRasterizationJobs = new Map<string, RasterizationJob>();+ /** Invalidates jobs and export guards across wholesale document replacement. */+ let rasterDocumentGeneration = 0;let screenSurface: RasterSurface | null = null;let overlaySurface: RasterSurface | null = null;@@ -1015,6 +1069,150 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {store: layerCache,});+ const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean => {+ if (source.type === 'shape') {+ return source.kind !== 'polygon';+ }+ return true;+ };++ const isCurrentRasterizationJob = (layer: CanvasLayerContract): boolean => {+ const job = layerRasterizationJobs.get(layer.id);+ const source = renderableSourceOf(layer);+ return (+ !!job &&+ !!source &&+ job.version === layerCache.version(layer.id) &&+ job.documentGeneration === rasterDocumentGeneration &&+ isDeeplyEqual(job.source, source)+ );+ };++ /**+ * Starts (or joins) an isolated rasterization. Pixels land in a scratch+ * surface and are copied into the live cache only while this exact job still+ * describes the current layer source, cache version, and document.+ */+ const getOrStartLayerRasterization = (+ layer: CanvasLayerContract,+ document: CanvasDocumentContractV2+ ): Promise<'published' | 'stale'> => {+ const liveSource = renderableSourceOf(layer);+ if (!liveSource || !isSupportedExportSource(liveSource)) {+ return Promise.resolve('stale');+ }++ const contentRect = getSourceContentRect(layer, document);+ const entry = layerCache.getOrCreateRect(layer.id, contentRect);+ const version = entry.version;+ const documentGeneration = rasterDocumentGeneration;+ const source = structuredClone(liveSource);+ const existing = layerRasterizationJobs.get(layer.id);+ if (+ existing &&+ existing.version === version &&+ existing.documentGeneration === documentGeneration &&+ isDeeplyEqual(existing.source, source)+ ) {+ return existing.promise;+ }++ if (source.type === 'text') {+ fontLoader.ensure(textFontString(source), () => {+ const currentDocument = mirror.getDocument();+ const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layer.id);+ if (+ disposed ||+ !currentLayer ||+ rasterDocumentGeneration !== documentGeneration ||+ layerCache.version(layer.id) !== version ||+ !isDeeplyEqual(renderableSourceOf(currentLayer), source)+ ) {+ return;+ }+ layerCache.invalidate(layer.id);+ scheduler.invalidate({ layers: [layer.id] });+ });+ }++ const scratch = backend.createSurface(contentRect.width, contentRect.height);+ let settleJob!: (result: 'published' | 'stale') => void;+ const promise = new Promise<'published' | 'stale'>((resolve) => {+ settleJob = resolve;+ });+ const job: RasterizationJob = {+ documentGeneration,+ promise,+ source,+ version,+ };+ layerRasterizationJobs.set(layer.id, job);+ void (async () => {+ try {+ const result = await rasterizeSource(source, rasterizeDeps(document), scratch);+ const currentDocument = mirror.getDocument();+ const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layer.id);+ const currentEntry = layerCache.get(layer.id);+ if (+ disposed ||+ layerRasterizationJobs.get(layer.id) !== job ||+ rasterDocumentGeneration !== documentGeneration ||+ !currentLayer ||+ !currentEntry ||+ currentEntry.version !== version ||+ !isDeeplyEqual(renderableSourceOf(currentLayer), source)+ ) {+ return 'stale';+ }++ if (currentEntry.surface.width !== result.rect.width || currentEntry.surface.height !== result.rect.height) {+ currentEntry.surface.resize(result.rect.width, result.rect.height);+ }+ const ctx = currentEntry.surface.ctx;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, result.rect.width, result.rect.height);+ if (!isEmpty(result.rect)) {+ ctx.drawImage(result.surface.canvas, 0, 0);+ }+ currentEntry.rect = { ...result.rect };+ currentEntry.stale = false;+ stores.thumbnailVersion.set(layer.id, currentEntry.version);+ scheduler.invalidate({ layers: [layer.id] });+ return 'published';+ } catch {+ return 'stale';+ } finally {+ if (layerRasterizationJobs.get(layer.id) === job) {+ layerRasterizationJobs.delete(layer.id);+ }+ }+ })().then(settleJob, () => settleJob('stale'));+ return promise;+ };++ const captureLayerExportGuard = (layer: CanvasLayerContract, entry: LayerCacheEntry): LayerExportGuard => ({+ cacheVersion: entry.version,+ documentGeneration: rasterDocumentGeneration,+ layer,+ layerId: layer.id,+ projectId,+ });++ const isLayerExportGuardCurrent = (guard: LayerExportGuard): boolean => {+ if (+ disposed ||+ guard.projectId !== projectId ||+ store.getState().activeProjectId !== projectId ||+ guard.documentGeneration !== rasterDocumentGeneration+ ) {+ return false;+ }+ const document = mirror.getDocument();+ const liveLayer = document?.layers.find((candidate) => candidate.id === guard.layerId);+ const entry = layerCache.get(guard.layerId);+ return !!entry && liveLayer === guard.layer && entry.version === guard.cacheVersion;+ };+const ensureLayerCaches = (doc: CanvasDocumentContractV2): void => {for (const layer of doc.layers) {// The layer's rasterizable source: a raster/control `source`, or a mask@@ -1038,64 +1236,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// here — that would destroy those pixels. The rasterizer (below, guarded by// `stale`) owns sizing the surface + placing its content rect.const entry = layerCache.getOrCreateRect(layer.id, getSourceContentRect(layer, doc));- if (!entry.stale || inFlight.has(layer.id)) {+ if (!entry.stale) {continue;}- inFlight.add(layer.id);- // Capture the cache's version before dispatching: if another- // invalidation bumps it while this rasterize is in flight, the pixels- // we're about to produce are already stale by the time they land, and- // must not clear `stale` — otherwise the newest edit would be dropped- // until some unrelated invalidation happens to re-trigger a rasterize.- const dispatchedVersion = layerCache.version(layer.id);- // Text metrics depend on the font actually being available. This rasterize- // draws with whatever `measureText` reports now (a fallback if a web font- // is still loading); when the font resolves, re-rasterize — unless a newer- // edit already bumped the version (a stale resolve must not clobber it).- if (source.type === 'text') {- fontLoader.ensure(textFontString(source), () => {- if (disposed || layerCache.version(layer.id) !== dispatchedVersion) {- return;- }- layerCache.invalidate(layer.id);- scheduler.invalidate({ layers: [layer.id] });- });- }- rasterizeSource(source, rasterizeDeps(doc), entry.surface)- .then((result) => {- inFlight.delete(layer.id);- const current = layerCache.get(layer.id);- if (current && layerCache.version(layer.id) === dispatchedVersion) {- current.stale = false;- // Adopt the placed content rect the rasterizer produced (the surface- // was resized in place, so its identity is unchanged).- current.rect = result.rect;- // Only bump the thumbnail version when the pixels that just- // landed are actually the current ones. A stale (superseded)- // completion must not touch `thumbnailVersion`: since the- // equality-guarded store only notifies on change, a stale- // completion setting the same version the fresh completion will- // later compute would suppress that later notification, leaving- // thumbnail subscribers stuck on pre-edit pixels indefinitely.- stores.thumbnailVersion.set(layer.id, layerCache.version(layer.id));- }- // If the version moved on, `current.stale` is left `true` (set by- // the intervening `invalidate`), so the next scheduled frame's- // `ensureLayerCaches` pass re-dispatches a fresh rasterize.- scheduler.invalidate({ layers: [layer.id] });- })- .catch(() => {- inFlight.delete(layer.id);- });- }- };-- const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean => {- if (source.type === 'shape') {- return source.kind !== 'polygon';+ void getOrStartLayerRasterization(layer, doc);}- return true;};const hasExportableLayerContent = (layerId: string): boolean => {@@ -1118,7 +1264,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return false;}const entry = layerCache.get(layerId);- return !!entry && !entry.stale && !inFlight.has(layerId) && !isEmpty(entry.rect);+ return !!entry && !entry.stale && !isCurrentRasterizationJob(layer) && !isEmpty(entry.rect);};const rasterizeLayerPixels = async (@@ -1141,24 +1287,47 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return { status: 'unsupported' };}const liveEntry = layerCache.get(layerId);- if (liveEntry && !liveEntry.stale && !inFlight.has(layer.id) && !isEmpty(liveEntry.rect)) {- return { rect: liveEntry.rect, status: 'ok', surface: liveEntry.surface };+ if (liveEntry && !liveEntry.stale && !isCurrentRasterizationJob(layer) && !isEmpty(liveEntry.rect)) {+ return {+ guard: captureLayerExportGuard(layer, liveEntry),+ rect: liveEntry.rect,+ status: 'ok',+ surface: liveEntry.surface,+ };}const contentRect = getSourceContentRect(layer, doc);if (isEmpty(contentRect)) {return { status: 'empty' };}- if (inFlight.has(layer.id)) {+ const rasterized = await getOrStartLayerRasterization(layer, doc);+ if (rasterized !== 'published') {return { status: 'not-ready' };}- const entry = layerCache.getOrCreateRect(layerId, contentRect);- if (entry.stale) {- const result = await rasterizeSource(source, rasterizeDeps(doc), entry.surface);- entry.rect = result.rect;- entry.stale = false;- stores.thumbnailVersion.set(layer.id, layerCache.version(layer.id));+ const currentDocument = mirror.getDocument();+ const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layerId);+ const entry = layerCache.get(layerId);+ if (!currentLayer || !entry || entry.stale) {+ return { status: 'not-ready' };+ }+ const currentSource = renderableSourceOf(currentLayer);+ if (!currentSource) {+ return { status: 'missing' };+ }+ if (!options.includeDisabled && !currentLayer.isEnabled) {+ return { status: 'disabled' };+ }+ if (!isSupportedExportSource(currentSource)) {+ return { status: 'unsupported' };+ }+ if (isEmpty(entry.rect)) {+ return { status: 'empty' };}- return { rect: entry.rect, status: 'ok', surface: entry.surface };+ return {+ guard: captureLayerExportGuard(currentLayer, entry),+ rect: entry.rect,+ status: 'ok',+ surface: entry.surface,+ };};const exportBakedLayerPixels = async (@@ -1169,11 +1338,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (raw.status !== 'ok') {return raw;}- const doc = mirror.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === layerId);- if (!doc || !layer) {- return { status: 'missing' };- }+ const layer = raw.guard.layer;const matrix = fromTRS({ x: layer.transform.x, y: layer.transform.y },@@ -1199,7 +1364,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {ctx.putImageData(imageData, 0, 0);}- return { rect: worldRect, status: 'ok', surface };+ return { guard: raw.guard, rect: worldRect, status: 'ok', surface };};const exportBakedLayerBlob = async (@@ -1210,71 +1375,120 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (result.status !== 'ok') {return result;}- return { blob: await backend.encodeSurface(result.surface, 'image/png'), rect: result.rect, status: 'ok' };+ const blob = await backend.encodeSurface(result.surface, 'image/png');+ if (!isLayerExportGuardCurrent(result.guard)) {+ return { status: 'not-ready' };+ }+ return { blob, guard: result.guard, rect: result.rect, status: 'ok' };};- const cropLayerToBbox = async (layerId: string): Promise<boolean> => {+ const cropLayerToBbox = async (layerId: string): Promise<CropLayerResult> => {if (pipeline.isGestureActive()) {- return false;+ return { status: 'busy' };}endNudgeBurst();- const doc = mirror.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === layerId);- if (!doc || !layer || layer.isLocked) {- return false;+ const document = mirror.getDocument();+ const layer = document?.layers.find((candidate) => candidate.id === layerId);+ if (!document || !layer) {+ return { status: 'missing' };}- const cropRect = roundOut(doc.bbox);- if (isEmpty(cropRect)) {- return false;+ if (layer.isLocked) {+ return { status: 'locked' };}-- const baked = await exportBakedLayerPixels(layerId, { includeDisabled: true });- if (baked.status !== 'ok') {- return false;+ const source = renderableSourceOf(layer);+ if (!source || !isSupportedExportSource(source)) {+ return { status: 'unsupported' };}- const cropped = backend.createSurface(cropRect.width, cropRect.height);- const cctx = cropped.ctx;- cctx.setTransform(1, 0, 0, 1, 0, 0);- cctx.clearRect(0, 0, cropRect.width, cropRect.height);- cctx.drawImage(baked.surface.canvas, baked.rect.x - cropRect.x, baked.rect.y - cropRect.y);+ try {+ const exported = await exportBakedLayerPixels(layerId, { includeDisabled: true });+ if (exported.status !== 'ok') {+ switch (exported.status) {+ case 'missing':+ case 'unsupported':+ case 'empty':+ case 'not-ready':+ return { status: exported.status };+ case 'disabled':+ return { status: 'not-ready' };+ }+ }- const identity = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };- if (layer.type === 'raster' || layer.type === 'control') {- store.dispatch({- id: layerId,- source: { bitmap: null, offset: { x: cropRect.x, y: cropRect.y }, type: 'paint' },- type: 'updateCanvasLayerSource',- });- if (layer.type === 'raster' && layer.adjustments) {- store.dispatch({- config: { adjustments: undefined, layerType: 'raster' },- id: layerId,- type: 'updateCanvasLayerConfig',- });- } else if (layer.type === 'control' && layer.filter) {- store.dispatch({- config: { filter: undefined, layerType: 'control' },- id: layerId,- type: 'updateCanvasLayerConfig',- });+ const liveDocument = mirror.getDocument();+ const liveLayer = liveDocument?.layers.find((candidate) => candidate.id === layerId);+ if (!liveDocument || !liveLayer) {+ return { status: 'missing' };}- } else {- store.dispatch({- config: { layerType: layer.type, mask: { bitmap: null, offset: { x: cropRect.x, y: cropRect.y } } },- id: layerId,- type: 'updateCanvasLayerConfig',+ if (pipeline.isGestureActive()) {+ return { status: 'busy' };+ }+ if (liveLayer.isLocked) {+ return { status: 'locked' };+ }+ if (!isLayerExportGuardCurrent(exported.guard)) {+ return { status: 'not-ready' };+ }+ const liveSource = renderableSourceOf(liveLayer);+ if (!liveSource || !isSupportedExportSource(liveSource)) {+ return { status: 'unsupported' };+ }++ const overlap = intersect(exported.rect, roundOut(liveDocument.bbox));+ if (!overlap) {+ return { status: 'empty' };+ }+ const cropRect = roundOut(overlap);+ if (isEmpty(cropRect)) {+ return { status: 'empty' };+ }++ const beforePixels = captureLayerCache(liveLayer, liveDocument);+ if (!beforePixels || beforePixels === 'not-ready') {+ return { status: 'not-ready' };+ }+ const before = structuredClone(liveLayer);+ const cropped = backend.createSurface(cropRect.width, cropRect.height);+ const cctx = cropped.ctx;+ cctx.setTransform(1, 0, 0, 1, 0, 0);+ cctx.clearRect(0, 0, cropRect.width, cropRect.height);+ cctx.drawImage(exported.surface.canvas, exported.rect.x - cropRect.x, exported.rect.y - cropRect.y);++ const identity = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };+ const paintSource = { bitmap: null, offset: { x: cropRect.x, y: cropRect.y }, type: 'paint' } as const;+ let after: CanvasLayerContract;+ if (before.type === 'raster') {+ const { adjustments: _adjustments, ...rest } = before;+ after = { ...rest, source: paintSource, transform: identity };+ } else if (before.type === 'control') {+ const { filter: _filter, ...rest } = before;+ after = { ...rest, source: paintSource, transform: identity };+ } else {+ after = {+ ...before,+ mask: { ...before.mask, bitmap: null, offset: { x: cropRect.x, y: cropRect.y } },+ transform: identity,+ };+ }++ const applySnapshot = (contract: CanvasLayerContract, snapshot: { pixels: RasterSurface; rect: Rect }): void => {+ store.dispatch({ layer: contract, layerId, type: 'replaceCanvasLayer' });+ seedGeneratedPaintCache(layerId, snapshot.rect, snapshot.pixels);+ };+ const afterPixels = { pixels: cropped, rect: cropRect };+ applySnapshot(after, afterPixels);+ history.push({+ bytes:+ beforePixels.rect.width * beforePixels.rect.height * 4 ++ afterPixels.rect.width * afterPixels.rect.height * 4 ++ 256,+ label: 'Crop layer to bbox',+ redo: () => applySnapshot(after, afterPixels),+ undo: () => applySnapshot(before, beforePixels),});+ return { status: 'cropped' };+ } catch (error) {+ return { message: error instanceof Error ? error.message : String(error), status: 'failed' };}- store.dispatch({ id: layerId, patch: { transform: identity }, type: 'updateCanvasLayer' });-- layerCache.delete(layerId);- const target = layerCache.getOrCreateRect(layerId, cropRect);- target.surface.ctx.drawImage(cropped.canvas, 0, 0);- target.stale = false;- notifyLayerPainted(layerId);- bitmapStore.markLayerDirty(layerId);- return true;};const copyLayerToRaster = async (layerId: string): Promise<string | null> => {@@ -1287,14 +1501,19 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (!doc || !sourceLayer) {return null;}- const sourceIndex = doc.layers.findIndex((layer) => layer.id === layerId);- if (sourceIndex < 0) {- return null;- }const baked = await exportBakedLayerPixels(layerId, { includeDisabled: true });if (baked.status !== 'ok') {return null;}+ if (pipeline.isGestureActive() || !isLayerExportGuardCurrent(baked.guard) || baked.guard.layer !== sourceLayer) {+ return null;+ }+ const liveDocument = mirror.getDocument();+ const liveSourceLayer = liveDocument?.layers.find((layer) => layer.id === layerId);+ const sourceIndex = liveDocument?.layers.findIndex((layer) => layer.id === layerId) ?? -1;+ if (!liveDocument || liveSourceLayer !== sourceLayer || sourceIndex < 0) {+ return null;+ }const newId = createLayerId();const layer: CanvasLayerContract = {@@ -1354,9 +1573,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {};const dropLayer = (layerId: string): void => {+ layerRasterizationJobs.delete(layerId);layerCache.delete(layerId);adjustedSurfaceCache.delete(layerId);- inFlight.delete(layerId);stores.thumbnailVersion.delete(layerId);const imageName = trackedImageNames.get(layerId);trackedImageNames.delete(layerId);@@ -1640,6 +1859,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// is active the document must recomposite to reposition it with the bbox.onBboxChanged: () => scheduler.invalidate(stagedPreview ? { all: true } : { overlay: true }),onDocumentReplaced: () => {+ rasterDocumentGeneration += 1;+ layerRasterizationJobs.clear();// A wholesale document swap — project switch, dims/background change, or a// snapshot restore that changes dims — invalidates the pixel history: its// entries reference layers/pixels that no longer describe the live document.@@ -2069,7 +2290,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {* cache: the surface then holds blank/old pixels, so the op would bake garbage* AND the in-flight `rasterizeSource` completion would later redraw over the* op's result. Such a layer is safe only once its cache exists and is neither- * stale (re-rasterize pending) nor mid-decode (`inFlight`).+ * stale (re-rasterize pending) nor in its current decode job.** A layer with NO persisted content is always safe: its cache — whether a fresh* live paint (unflushed stroke) or a genuinely empty 0×0 stale entry — already@@ -2080,7 +2301,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return true;}const entry = layerCache.get(layer.id);- return !!entry && !entry.stale && !inFlight.has(layer.id);+ return !!entry && !entry.stale && !isCurrentRasterizationJob(layer);};const booleanCompositeModes: Record<BooleanRasterOperation, GlobalCompositeOperation> = {@@ -2110,7 +2331,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (!entry || isEmpty(entry.rect)) {return null;}- if (inFlight.has(layer.id) || (entry.stale && !isEmpty(getSourceContentRect(layer, doc)))) {+ if (isCurrentRasterizationJob(layer) || (entry.stale && !isEmpty(getSourceContentRect(layer, doc)))) {return 'not-ready';}const pixels = backend.createSurface(entry.rect.width, entry.rect.height);@@ -2156,14 +2377,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return true;};- const commitLayerConversion = (label: string, before: CanvasLayerContract, after: CanvasLayerContract): boolean => {- if (pipeline.isGestureActive() || before.id !== after.id || before.type === after.type) {+ const commitLayerConversion = (+ label: string,+ expectedLiveLayer: CanvasLayerContract,+ after: CanvasLayerContract+ ): boolean => {+ if (pipeline.isGestureActive() || expectedLiveLayer.id !== after.id || expectedLiveLayer.type === after.type) {return false;}endNudgeBurst();const doc = mirror.getDocument();- const current = doc?.layers.find((candidate) => candidate.id === before.id);- if (!doc || !current || current.type !== before.type) {+ const current = doc?.layers.find((candidate) => candidate.id === expectedLiveLayer.id);+ if (+ !doc ||+ !current ||+ current !== expectedLiveLayer ||+ current.isLocked ||+ current.type !== expectedLiveLayer.type+ ) {return false;}const captured = captureLayerCache(current, doc);@@ -2176,6 +2407,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {seedGeneratedPaintCache(layer.id, captured.rect, captured.pixels, layerNeedsPixelPersistence(layer));}};+ const before = structuredClone(current);apply(after);history.push({bytes: captured ? captured.rect.width * captured.rect.height * 4 + 256 : 256,@@ -2222,8 +2454,37 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (upperPixels.status === 'not-ready' || belowPixels.status === 'not-ready') {return 'not-ready';}+ if (+ upperPixels.status === 'disabled' ||+ upperPixels.status === 'unsupported' ||+ belowPixels.status === 'disabled' ||+ belowPixels.status === 'unsupported'+ ) {+ return 'unsupported';+ }return 'empty';}+ if (pipeline.isGestureActive()) {+ return 'busy';+ }+ if (+ upperPixels.guard.layer !== upper ||+ belowPixels.guard.layer !== below ||+ !isLayerExportGuardCurrent(upperPixels.guard) ||+ !isLayerExportGuardCurrent(belowPixels.guard)+ ) {+ return 'not-ready';+ }+ const liveDocument = mirror.getDocument();+ const liveUpperIndex = liveDocument?.layers.findIndex((layer) => layer.id === upperLayerId) ?? -1;+ const liveUpper = liveDocument?.layers[liveUpperIndex];+ const liveBelow = liveDocument?.layers[liveUpperIndex + 1];+ if (!liveDocument || liveUpper !== upper || liveBelow !== below) {+ return 'not-ready';+ }+ if (!isMergeableRasterLayer(liveUpper) || !isMergeableRasterLayer(liveBelow)) {+ return 'unsupported';+ }const resultRect = roundOut(union(upperPixels.rect, belowPixels.rect));if (isEmpty(resultRect)) {@@ -2258,7 +2519,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {];const disabled = originalEnabled.map(({ id }) => ({ id, isEnabled: false }));const apply = (): void => {- store.dispatch({ index: upperIndex, layer: resultLayer, type: 'addCanvasLayer' });+ store.dispatch({ index: liveUpperIndex, layer: resultLayer, type: 'addCanvasLayer' });seedGeneratedPaintCache(resultId, resultRect, resultPixels);store.dispatch({ type: 'setCanvasLayersEnabled', updates: disabled });};@@ -2293,12 +2554,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (!maskLayer || maskLayer.type !== 'inpaint_mask') {return { status: 'unsupported' };}- const liveMask = layerCache.get(maskLayerId);- if (isEmpty(getSourceContentRect(maskLayer, doc)) && (!liveMask || isEmpty(liveMask.rect))) {+ if (maskLayer.isLocked) {+ return { status: 'unsupported' };+ }+ const liveMaskCache = layerCache.get(maskLayerId);+ if (isEmpty(getSourceContentRect(maskLayer, doc)) && (!liveMaskCache || isEmpty(liveMaskCache.rect))) {return { status: 'empty' };}const contributors = doc.layers.filter(- (layer) => layer.isEnabled && (layer.type === 'raster' || layer.type === 'control')+ (layer) => layer.isEnabled && layer.type === 'raster' && hasExportableLayerContent(layer.id));if (contributors.length === 0) {return { status: 'empty' };@@ -2307,10 +2571,56 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return { status: 'not-ready' };}- const maskPixels = await exportBakedLayerPixels(maskLayerId, { includeDisabled: true });+ const [maskPixels, contributorPixels] = await Promise.all([+ exportBakedLayerPixels(maskLayerId, { includeDisabled: true }),+ Promise.all(contributors.map((layer) => rasterizeLayerPixels(layer.id))),+ ]);if (maskPixels.status !== 'ok') {return { status: maskPixels.status === 'not-ready' ? 'not-ready' : 'empty' };}+ if (contributorPixels.some((pixels) => pixels.status !== 'ok')) {+ return {+ status: contributorPixels.some((pixels) => pixels.status === 'not-ready') ? 'not-ready' : 'empty',+ };+ }+ if (pipeline.isGestureActive()) {+ return { status: 'busy' };+ }+ if (maskPixels.guard.layer !== maskLayer || !isLayerExportGuardCurrent(maskPixels.guard)) {+ return { status: 'not-ready' };+ }+ const liveDocument = mirror.getDocument();+ const liveMaskIndex = liveDocument?.layers.findIndex((layer) => layer.id === maskLayerId) ?? -1;+ const currentMask = liveDocument?.layers[liveMaskIndex];+ if (!liveDocument || !currentMask) {+ return { status: 'missing' };+ }+ if (currentMask !== maskLayer) {+ return { status: currentMask.type === 'inpaint_mask' && currentMask.isLocked ? 'unsupported' : 'not-ready' };+ }+ const liveContributors = liveDocument.layers.filter(+ (layer) => layer.isEnabled && layer.type === 'raster' && hasExportableLayerContent(layer.id)+ );+ if (+ liveMaskIndex !== maskIndex ||+ liveContributors.length !== contributors.length ||+ liveContributors.some((layer, index) => layer !== contributors[index])+ ) {+ return { status: 'not-ready' };+ }+ for (let index = 0; index < contributorPixels.length; index += 1) {+ const pixels = contributorPixels[index];+ const contributor = contributors[index];+ if (+ !pixels ||+ pixels.status !== 'ok' ||+ !contributor ||+ pixels.guard.layer !== contributor ||+ !isLayerExportGuardCurrent(pixels.guard)+ ) {+ return { status: 'not-ready' };+ }+ }const resultRect = maskPixels.rect;if (isEmpty(resultRect)) {return { status: 'empty' };@@ -2602,7 +2912,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (rasterLayers.length === 0) {return 'nothing';}- // Readiness pre-flight: a layer whose cache is MID-DECODE (`inFlight`) would+ // Readiness pre-flight: a layer whose cache is in its current decode job would// bake blank/old pixels, so refuse the whole export (nothing partial). A// layer with no live cache entry is safe — the executor rasterizes it fresh// and synchronously. Transform/stroke sessions in progress export the current@@ -2611,7 +2921,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (isEmpty(getSourceContentRect(layer, doc))) {continue;}- if (inFlight.has(layer.id)) {+ if (isCurrentRasterizationJob(layer)) {return 'not-ready';}}@@ -3603,7 +3913,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {layerCache.dispose();adjustedSurfaceCache.dispose();trackedImageNames.clear();- inFlight.clear();+ layerRasterizationJobs.clear();strokeListeners.clear();};@@ -3722,6 +4032,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {hasExportableLayerContent,invertMask,invertSelection,+ isLayerExportGuardCurrent,mergeLayerDown,mergeVisibleRasterLayers,openTextCreate,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex fa9c13bea1..bb4b7b55a5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -90,6 +90,10 @@ const PANEL_POSITIONING: MenuPositioning = { placement: 'bottom-end' };const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));+const assertNever = (value: never): never => {+ throw new Error(`Unhandled layer action result: ${String(value)}`);+};+type LayerActionErrorStatus = 'busy' | 'disabled' | 'empty' | 'locked' | 'missing' | 'not-ready' | 'unsupported';const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {@@ -334,12 +338,16 @@ const LayerMenu = ({if (!converted) {throw makeStatusError('unsupported');}- // Convert in place, preserving the pixel source + id. The inverse restores- // the layer verbatim (adapter/filter config and all).- const original = structuredClone(layer);if (engine) {- engine.commitLayerConversion(label, original, converted);+ // Pass the immutable live object: the engine rejects stale menu actions+ // by identity and clones the inverse contract internally.+ if (!engine.commitLayerConversion(label, layer, converted)) {+ throw makeStatusError('not-ready');+ }} else {+ // Convert in place, preserving the pixel source + id. The inverse restores+ // the layer verbatim (adapter/filter config and all).+ const original = structuredClone(layer);applyStructural(engine,dispatch,@@ -413,10 +421,26 @@ const LayerMenu = ({if (!engine) {throw makeStatusError('not-ready');}- if (!(await engine.cropLayerToBbox(layer.id))) {- throw new Error(t('widgets.layers.actions.cropFailed'));+ const result = await engine.cropLayerToBbox(layer.id);+ switch (result.status) {+ case 'cropped':+ notify.success(t('widgets.layers.actions.cropped'));+ return;+ case 'missing':+ case 'locked':+ case 'empty':+ case 'not-ready':+ throw makeStatusError(result.status);+ case 'busy':+ throw new Error(t('widgets.layers.actions.cropBusy'));+ case 'unsupported':+ throw new Error(t('widgets.layers.actions.cropUnsupported'));+ case 'failed':+ throw new Error(`${t('widgets.layers.actions.cropFailed')} ${result.message}`);+ default:+ return assertNever(result);}- }, [engine, layer.id, makeStatusError, t]);+ }, [engine, layer.id, makeStatusError, notify, t]);const handleExtractMaskedArea = useCallback(async () => {if (!engine) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex b36ee2cea3..f92d69ca94 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -164,7 +164,10 @@ describe('layer context action registry', () => {'widgets.layers.actions.empty','widgets.layers.actions.disabled','widgets.layers.actions.copyFailed',+ 'widgets.layers.actions.cropBusy','widgets.layers.actions.cropFailed',+ 'widgets.layers.actions.cropUnsupported',+ 'widgets.layers.actions.cropped',];for (const key of keys) {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 85cf5e739b..1a54dceab7 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1829,6 +1829,60 @@ describe('workbenchReducer canvas v2 layer reducers', () => {expect(getCanvas(updated).document.layers.find((layer) => layer.id === 'b')).toBe(originalLayerB);});+ it('replaces one complete layer contract in place and no-ops when the id is missing', () => {+ const state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('a'),+ createRasterLayer('b'),+ createRasterLayer('c'),+ ]);+ const beforeDocument = getCanvas(state).document;+ const replacement: CanvasControlLayerContract = {+ adapter: {+ beginEndStepPct: [0.2, 0.8],+ controlMode: 'more_control',+ kind: 'control_lora',+ model: 'control-model',+ weight: 0.65,+ },+ blendMode: 'multiply',+ filter: { settings: { radius: 3 }, type: 'canny' },+ id: 'b',+ isEnabled: false,+ isLocked: true,+ name: 'Complete replacement',+ opacity: 0.4,+ source: {+ bitmap: { contentHash: 'hash', height: 23, imageName: 'replacement.png', width: 17 },+ offset: { x: -4, y: 9 },+ type: 'paint',+ },+ transform: { rotation: 0.75, scaleX: -2, scaleY: 3, x: 12, y: -8 },+ type: 'control',+ withTransparencyEffect: true,+ };++ const replaced = workbenchReducer(state, {+ layer: replacement,+ layerId: 'b',+ type: 'replaceCanvasLayer',+ });+ const afterLayers = getCanvas(replaced).document.layers;++ expect(afterLayers.map((layer) => layer.id)).toEqual(['a', 'b', 'c']);+ expect(afterLayers[1]).toBe(replacement);+ expect(afterLayers[1]).toEqual(replacement);+ expect(afterLayers[0]).toBe(beforeDocument.layers[0]);+ expect(afterLayers[2]).toBe(beforeDocument.layers[2]);++ const missing = workbenchReducer(replaced, {+ layer: replacement,+ layerId: 'missing',+ type: 'replaceCanvasLayer',+ });+ expect(missing).toBe(replaced);+ expect(getCanvas(missing).document).toBe(getCanvas(replaced).document);+ });+it('swaps a raster/control layer source but ignores mask-only layer types', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);const newSource = { image: { height: 10, imageName: 'swapped.png', width: 10 }, type: 'image' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 1c6537c463..05c9f8d819 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -240,6 +240,7 @@ type WorkbenchAction =| { type: 'duplicateCanvasLayer'; sourceId: string; newId: string }| { type: 'reorderCanvasLayers'; orderedIds: string[] }| { type: 'updateCanvasLayer'; id: string; patch: CanvasLayerBasePatch }+ | { type: 'replaceCanvasLayer'; layerId: string; layer: CanvasLayerContract }| { type: 'setCanvasLayersEnabled'; updates: readonly { id: string; isEnabled: boolean }[] }| { type: 'updateCanvasLayerSource'; id: string; source: CanvasLayerSourceContract }| { type: 'updateCanvasLayerConfig'; id: string; config: CanvasLayerConfigPatch }@@ -3138,6 +3139,11 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)));}+ case 'replaceCanvasLayer': {+ return updateActiveProject(state, (project) =>+ updateCanvasDocument(project, (document) => mapCanvasLayer(document, action.layerId, () => action.layer))+ );+ }case 'setCanvasLayersEnabled': {return updateActiveProject(state, (project) =>updateCanvasDocument(project, (document) => setCanvasLayersEnabledInDocument(document, action.updates))