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): make control edit rollback exact
joshistoastae065f96eaa8
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.tsindex aeddc4a2a1..b23528e7f1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts@@ -1,6 +1,6 @@import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/types';-import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { createTestStubRasterBackend, type StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it } from 'vitest';import {@@ -90,7 +90,35 @@ describe('isLayerPixelEditEligible', () => {it.each([['raster paint', rasterPaint, true],- ['control', control(), true],+ ['paint control', control(), true],+ [+ 'image control',+ control({ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' } }),+ true,+ ],+ [+ 'rectangle control',+ control({+ source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },+ }),+ true,+ ],+ [+ 'polygon control',+ control({+ source: {+ fill: '#fff',+ height: 10,+ kind: 'polygon',+ points: [],+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 10,+ },+ }),+ false,+ ],['raster image',{ ...rasterPaint, source: { image: { height: 10, imageName: 'i', width: 10 }, type: 'image' } },@@ -122,18 +150,30 @@ describe('buildMaterializedControlLayer', () => {});describe('bakeControlPixelEditSurface', () => {- it('bakes source pixels through the transform into document-space bounds', () => {+ it('bakes offset source pixels through the complete translated, rotated, and scaled transform', () => {const backend = createTestStubRasterBackend();const source = backend.createSurface(10, 5);+ const sourceRect = { height: 5, width: 10, x: 5, y: -4 };const baked = bakeControlPixelEditSurface({backend,source,- sourceRect: { height: 5, width: 10, x: 0, y: 0 },- transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 7, y: 11 },+ sourceRect,+ transform: { rotation: Math.PI / 2, scaleX: 2, scaleY: 3, x: 7, y: 11 },});- expect(baked.rect).toEqual({ height: 15, width: 20, x: 7, y: 11 });- expect(baked.surface.width).toBe(20);- expect(baked.surface.height).toBe(15);+ expect(baked.rect).toEqual({ height: 20, width: 15, x: 4, y: 21 });+ expect(baked.surface.width).toBe(15);+ expect(baked.surface.height).toBe(20);+ expect((baked.surface as StubRasterSurface).callLog).toEqual([+ { args: [1, 0, 0, 1, 0, 0], op: 'setTransform' },+ { args: [0, 0, 15, 20], op: 'clearRect' },+ { args: ['imageSmoothingEnabled', true], op: 'set' },+ {+ args: [2 * Math.cos(Math.PI / 2), 2, -3, 3 * Math.cos(Math.PI / 2), 3, -10],+ op: 'setTransform',+ },+ { args: [source.canvas, sourceRect.x, sourceRect.y], op: 'drawImage' },+ { args: [1, 0, 0, 1, 0, 0], op: 'setTransform' },+ ]);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.tsindex e2c2d18cdb..8221c82e64 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts@@ -31,7 +31,7 @@ export const isLayerPixelEditEligible = (layer: CanvasLayerContract | undefined)!!layer &&!layer.isLocked &&layer.isEnabled &&- ((layer.type === 'raster' && layer.source.type === 'paint') || layer.type === 'control');+ ((layer.type === 'raster' && layer.source.type === 'paint') || (layer.type === 'control' && isRasterizable(layer)));export const decideControlPixelEdit = ({hasSourceContent,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 29b252e5e5..ac0b8312de 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -55,6 +55,7 @@ vi.mock('@workbench/canvas-engine/render/adjustedSurfaceCache', async (importOridelete: (layerId: string) => {adjustedSurfaceCacheDeletes.push(layerId);if (adjustedSurfaceCacheDeleteFaults.has(layerId)) {+ adjustedSurfaceCacheDeleteFaults.delete(layerId);throw new Error('adjusted surface cache delete failed');}cache.delete(layerId);@@ -492,6 +493,12 @@ const flushMicrotasks = (): Promise<void> =>setTimeout(resolve, 0);});+const drainMicrotasksUntil = async (predicate: () => boolean, maxTicks = 100): Promise<void> => {+ for (let tick = 0; tick < maxTicks && !predicate(); tick += 1) {+ await Promise.resolve();+ }+};+afterEach(() => {adjustedSurfaceCacheDeleteFaults.clear();historyPreparationFaults.imagePatch = false;@@ -2087,9 +2094,18 @@ type ControlPaintHarnessOverrides = Partial<Omit<CanvasControlLayerContract, 'sosource: CanvasControlLayerContract['source'];};+interface ControlPaintHarnessOptions {+ bitmapStoreFactory?: (deps: {+ backend: StubRasterBackend;+ projectId: string;+ store: EngineStore;+ }) => ReturnType<typeof createSpyBitmapStore>;+ pixelWrites?: { enabled: boolean };+}+const createControlPaintHarness = (overrides: ControlPaintHarnessOverrides,- selectionPixelWrites?: { enabled: boolean }+ options: ControlPaintHarnessOptions = {}) => {const raf = createControllableRaf();vi.stubGlobal('requestAnimationFrame', raf.requestFrame);@@ -2129,13 +2145,11 @@ const createControlPaintHarness = (};const { projectId, store } = createReducerBackedStore(document);const baseBackend = createTestStubRasterBackend();+ const pixelWrites = options.pixelWrites ?? { enabled: true };const backend: StubRasterBackend = {...baseBackend,createSurface: (width, height) => {const surface = baseBackend.createSurface(width, height);- if (!selectionPixelWrites) {- return surface;- }const originalCtx = surface.ctx;const ctx = new Proxy(originalCtx, {get(target, property, receiver) {@@ -2145,7 +2159,7 @@ const createControlPaintHarness = (}return (...args: unknown[]) => {const imageData = Reflect.apply(value, target, args) as ImageData;- if (selectionPixelWrites.enabled && imageData.data.length > 0) {+ if (pixelWrites.enabled && imageData.data.length > 0) {const drawCount = surface.callLog.filter((entry) => entry.op === 'drawImage').length;imageData.data[0] = drawCount % 256;}@@ -2157,7 +2171,7 @@ const createControlPaintHarness = (return surface;},};- const bitmapStore = createSpyBitmapStore();+ const bitmapStore = options.bitmapStoreFactory?.({ backend, projectId, store }) ?? createSpyBitmapStore();const engine = createCanvasEngine({backend,bitmapStore,@@ -2174,7 +2188,9 @@ const createControlPaintHarness = (return {backend,bitmapStore,+ document,engine,+ layer,overlay,publishInitialCache: async () => {raf.flush();@@ -2184,6 +2200,7 @@ const createControlPaintHarness = (},raf,screen,+ store,strokes,};};@@ -2191,7 +2208,7 @@ const createControlPaintHarness = (const createControlSelectionHarness = (overrides: ControlPaintHarnessOverrides) => {const selectionPixelWrites = { enabled: true };return {- ...createControlPaintHarness(overrides, selectionPixelWrites),+ ...createControlPaintHarness(overrides, { pixelWrites: selectionPixelWrites }),setSelectionPixelWrites: (enabled: boolean) => {selectionPixelWrites.enabled = enabled;},@@ -2218,6 +2235,59 @@ const createSpyBitmapStore = (): BitmapStore & {};};+const createRealControlPersistenceHarness = async (+ uploadImage: (blob: Blob) => Promise<{ height: number; imageName: string; width: number }>+) => {+ let placed: { offset: { x: number; y: number }; surface: RasterSurface } | null = null;+ const encodeSurface = vi.fn(() => Promise.resolve(new Blob(['control-pixels'], { type: 'image/png' })));+ const h = createControlPaintHarness(+ { source: { bitmap: { height: 10, imageName: 'control-paint', width: 10 }, type: 'paint' } },+ {+ bitmapStoreFactory: ({ projectId, store }) => {+ const real = createBitmapStore({+ debounceMs: 1500,+ dispatch: store.dispatch,+ encodeSurface,+ getLayerSource: (layerId) => {+ const layer = store+ .getState()+ .projects.find((project) => project.id === projectId)+ ?.canvas.document.layers.find((candidate) => candidate.id === layerId);+ return layer?.type === 'control' ? layer.source : null;+ },+ getLayerSurface: () => placed,+ hashBlob: (blob) => blob.text(),+ maxUploadAttempts: 1,+ retryDelaysMs: [],+ sleep: () => Promise.resolve(),+ uploadImage,+ });+ const releaseSuspendedLayer = vi.fn();+ return {+ ...real,+ markLayerDirty: vi.fn(real.markLayerDirty),+ releaseSuspendedLayer,+ reset: vi.fn(real.reset),+ suspendLayer: vi.fn((layerId: string) => {+ const release = real.suspendLayer(layerId);+ return () => {+ releaseSuspendedLayer();+ release();+ };+ }),+ };+ },+ }+ );+ await h.publishInitialCache();+ const exported = await h.engine.exportLayerPixels('control', { includeDisabled: true });+ if (exported.status !== 'ok') {+ throw new Error(`expected ready direct control cache, got ${exported.status}`);+ }+ placed = { offset: { x: exported.rect.x, y: exported.rect.y }, surface: exported.surface };+ return { ...h, encodeSurface };+};+/** A fake canvas that also lets a test fire pointer events at the engine's listeners. */const createInputCanvas = (width = 100,@@ -2289,14 +2359,198 @@ describe('engine-owned control pixel editing', () => {expect(h.strokes).toHaveLength(1);expect(h.strokes[0]!.layerId).toBe('control');expect(h.bitmapStore.markLayerDirty).toHaveBeenCalledWith('control');- expect(h.bitmapStore.suspendLayer).not.toHaveBeenCalled();+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledWith('control');+ expect(h.bitmapStore.markLayerDirty.mock.invocationCallOrder[0]).toBeLessThan(+ h.bitmapStore.releaseSuspendedLayer.mock.invocationCallOrder[0]!+ );expect(h.engine.stores.canUndo.get()).toBe(true);h.engine.dispose();});+ it('restores the exact direct cache after a cancelled stroke grows it and permits a subsequent edit', async () => {+ const h = createControlPaintHarness({+ source: { bitmap: { height: 10, imageName: 'control-paint', width: 10 }, type: 'paint' },+ });+ await h.publishInitialCache();+ const before = await snapshotLayerCache(h.engine, 'control');+ h.engine.setTool('brush');+ h.overlay.fire('pointerdown', pointerAt(80, 80));+ h.overlay.fire('pointermove', pointerAt(90, 90));+ h.overlay.fire('pointercancel', pointerAt(90, 90, { buttons: 0 }));++ const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });+ expect(restored.status).toBe('ok');+ if (restored.status === 'ok') {+ expect(restored.surface).toBe(before.surface);+ expect(restored.rect).toEqual(before.rect);+ expect(restored.guard.cacheVersion).toBe(before.version);+ const finalWrite = (restored.surface as StubRasterSurface).callLog+ .filter((entry) => entry.op === 'putImageData')+ .at(-1);+ expect(finalWrite?.args[0]).toMatchObject({ height: before.rect.height, width: before.rect.width });+ }+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);++ h.overlay.fire('pointerdown', pointerAt(20, 20));+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledTimes(2);+ h.overlay.fire('pointercancel', pointerAt(20, 20, { buttons: 0 }));+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledTimes(2);+ h.engine.dispose();+ });++ it.each(['brush', 'eraser'] as const)(+ 'treats a byte-identical direct %s stroke as an exact rollback',+ async (tool) => {+ const h = createControlPaintHarness(+ { source: { bitmap: { height: 10, imageName: 'control-paint', width: 10 }, type: 'paint' } },+ { pixelWrites: { enabled: false } }+ );+ await h.publishInitialCache();+ const before = await snapshotLayerCache(h.engine, 'control');+ h.engine.setTool(tool);+ h.overlay.fire('pointerdown', pointerAt(5, 5));+ h.overlay.fire('pointermove', pointerAt(8, 8));+ h.overlay.fire('pointerup', pointerAt(8, 8, { buttons: 0 }));++ const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });+ expect(restored.status).toBe('ok');+ if (restored.status === 'ok') {+ expect(restored.surface).toBe(before.surface);+ expect(restored.rect).toEqual(before.rect);+ expect(restored.guard.cacheVersion).toBe(before.version);+ }+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);+ h.engine.dispose();+ }+ );++ it('keeps a pending direct-control upload suspended through cancel, then resumes the preserved dirty work', async () => {+ const uploadImage = vi.fn(() => Promise.resolve({ height: 10, imageName: 'resumed-control', width: 10 }));+ const h = await createRealControlPersistenceHarness(uploadImage);+ vi.useFakeTimers();+ try {+ h.bitmapStore.markLayerDirty('control');+ h.engine.setTool('brush');+ h.overlay.fire('pointerdown', pointerAt(20, 20));+ h.overlay.fire('pointermove', pointerAt(30, 30));+ const barrier = h.bitmapStore.flushPendingUploads();+ let settled = false;+ void barrier.then(() => {+ settled = true;+ });++ await vi.advanceTimersByTimeAsync(3000);+ expect(settled).toBe(false);+ expect(h.encodeSurface).not.toHaveBeenCalled();+ expect(uploadImage).not.toHaveBeenCalled();++ h.overlay.fire('pointercancel', pointerAt(30, 30, { buttons: 0 }));+ await drainMicrotasksUntil(() => settled);++ expect(settled).toBe(true);+ expect(h.encodeSurface).toHaveBeenCalledOnce();+ expect(uploadImage).toHaveBeenCalledOnce();+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);+ h.engine.dispose();+ } finally {+ vi.useRealTimers();+ }+ });++ it('invalidates an in-flight direct-control upload on begin and releases the barrier after cancel', async () => {+ const uploads = [+ createDeferred<{ height: number; imageName: string; width: number }>(),+ createDeferred<{ height: number; imageName: string; width: number }>(),+ ];+ let uploadIndex = 0;+ const uploadImage = vi.fn(() => uploads[uploadIndex++]!.promise);+ const h = await createRealControlPersistenceHarness(uploadImage);+ h.bitmapStore.markLayerDirty('control');+ const barrier = h.bitmapStore.flushPendingUploads();+ for (let tick = 0; tick < 50 && uploadImage.mock.calls.length < 1; tick += 1) {+ await Promise.resolve();+ }+ expect(uploadImage).toHaveBeenCalledOnce();++ h.engine.setTool('brush');+ h.overlay.fire('pointerdown', pointerAt(20, 20));+ h.overlay.fire('pointermove', pointerAt(30, 30));+ let settled = false;+ void barrier.then(() => {+ settled = true;+ });+ uploads[0]!.resolve({ height: 10, imageName: 'obsolete-control', width: 10 });+ await Promise.resolve();+ await Promise.resolve();++ expect(settled).toBe(false);+ expect(uploadImage).toHaveBeenCalledOnce();++ h.overlay.fire('pointercancel', pointerAt(30, 30, { buttons: 0 }));+ for (let tick = 0; tick < 50 && uploadImage.mock.calls.length < 2; tick += 1) {+ await Promise.resolve();+ }+ expect(uploadImage).toHaveBeenCalledTimes(2);+ uploads[1]!.resolve({ height: 10, imageName: 'resumed-control', width: 10 });+ await drainMicrotasksUntil(() => settled);++ expect(settled).toBe(true);+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);+ h.engine.dispose();+ });++ it.each([+ ['image control', { source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' } }],+ [+ 'transformed empty control',+ {+ source: { bitmap: null, type: 'paint' },+ transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 7, y: 11 },+ },+ ],+ ] as const)('treats byte-identical brush and eraser strokes on a %s as rollback', async (_scenario, overrides) => {+ for (const tool of ['brush', 'eraser'] as const) {+ const h = createControlPaintHarness(overrides, { pixelWrites: { enabled: false } });+ if (overrides.source.type === 'image') {+ await h.publishInitialCache();+ }+ const beforeDocument = structuredClone(h.engine.getDocument());+ const beforeCache = await h.engine.exportLayerPixels('control', { includeDisabled: true });+ h.engine.setTool(tool);+ h.overlay.fire('pointerdown', pointerAt(5, 5));+ h.overlay.fire('pointermove', pointerAt(8, 8));+ h.overlay.fire('pointerup', pointerAt(8, 8, { buttons: 0 }));++ expect(h.engine.getDocument()).toEqual(beforeDocument);+ const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });+ expect(restored.status).toBe(beforeCache.status);+ if (restored.status === 'ok' && beforeCache.status === 'ok') {+ expect(restored.surface).toBe(beforeCache.surface);+ expect(restored.rect).toEqual(beforeCache.rect);+ expect(restored.guard.cacheVersion).toBe(beforeCache.guard.cacheVersion);+ }+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);+ h.engine.dispose();+ }+ });+it('restores a direct control stroke when image-patch history preparation fails', async () => {const h = createControlPaintHarness({ source: { bitmap: null, type: 'paint' } });const before = structuredClone(h.engine.getDocument());+ const beforeExport = await h.engine.exportLayerPixels('control', { includeDisabled: true });h.engine.setTool('brush');h.overlay.fire('pointerdown', pointerAt(20, 20));h.overlay.fire('pointermove', pointerAt(40, 40));@@ -2309,15 +2563,10 @@ describe('engine-owned control pixel editing', () => {expect(h.engine.getDocument()).toEqual(before);expect(h.engine.stores.canUndo.get()).toBe(false);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();expect(h.strokes).toHaveLength(0);const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });- expect(restored.status).toBe('ok');- if (restored.status === 'ok') {- const finalPixelWrite = (restored.surface as StubRasterSurface).callLog- .filter((entry) => entry.op === 'putImageData')- .at(-1);- expect(finalPixelWrite?.args[0]).toBe(historyPreparationFaults.imagePatchBefore);- }+ expect(restored.status).toBe(beforeExport.status);h.engine.dispose();});@@ -2500,6 +2749,99 @@ describe('engine-owned control pixel editing', () => {expect(h.engine.stores.canRedo.get()).toBe(false);h.engine.dispose();});++ it('finishes document-replacement cleanup after materialized gesture rollback throws', async () => {+ const h = createControlPaintHarness({+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },+ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 },+ });+ await h.publishInitialCache();+ h.engine.setTool('brush');+ h.overlay.fire('pointerdown', pointerAt(8, 8));+ h.overlay.fire('pointermove', pointerAt(12, 12));+ adjustedSurfaceCacheDeleteFaults.add('control');+ const replacement = { ...h.document, width: h.document.width + 1 };++ expect(() => h.store.dispatch({ document: replacement, type: 'replaceCanvasDocument' })).toThrow(+ 'adjusted surface cache delete failed'+ );++ expect(h.engine.getDocument()).toEqual(replacement);+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.bitmapStore.reset).toHaveBeenCalledOnce();+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);+ h.engine.dispose();+ });++ it('finishes affected-layer removal cleanup after direct gesture rollback throws', async () => {+ const h = createControlPaintHarness({+ source: { bitmap: { height: 10, imageName: 'control-paint', width: 10 }, type: 'paint' },+ });+ await h.publishInitialCache();+ h.engine.setTool('brush');+ h.overlay.fire('pointerdown', pointerAt(8, 8));+ h.overlay.fire('pointermove', pointerAt(12, 12));+ adjustedSurfaceCacheDeleteFaults.add('control');++ expect(() => h.store.dispatch({ ids: ['control'], type: 'removeCanvasLayers' })).toThrow(+ 'adjusted surface cache delete failed'+ );++ expect(h.engine.getDocument()!.layers).toHaveLength(0);+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.bitmapStore.discardLayer).toHaveBeenCalledWith('control');+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);+ h.engine.dispose();+ });++ it('finishes active-project cleanup after materialized gesture rollback throws', async () => {+ const h = createControlPaintHarness({+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },+ });+ await h.publishInitialCache();+ h.engine.setTool('brush');+ h.overlay.fire('pointerdown', pointerAt(8, 8));+ h.overlay.fire('pointermove', pointerAt(12, 12));+ adjustedSurfaceCacheDeleteFaults.add('control');++ expect(() => h.store.dispatch({ type: 'createProject' })).toThrow('adjusted surface cache delete failed');++ expect(h.store.getState().activeProjectId).not.toBe(h.store.getState().projects[0]!.id);+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.engine.stores.canUndo.get()).toBe(false);+ expect(h.strokes).toHaveLength(0);++ h.store.dispatch({ projectId: h.store.getState().projects[0]!.id, type: 'switchProject' });+ h.overlay.fire('pointerdown', pointerAt(20, 20));+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledTimes(2);+ h.overlay.fire('pointercancel', pointerAt(20, 20, { buttons: 0 }));+ h.engine.dispose();+ });++ it('finishes disposal after direct gesture rollback throws and remains idempotent', async () => {+ const h = createControlPaintHarness({+ source: { bitmap: { height: 10, imageName: 'control-paint', width: 10 }, type: 'paint' },+ });+ await h.publishInitialCache();+ h.engine.setTool('brush');+ h.overlay.fire('pointerdown', pointerAt(8, 8));+ h.overlay.fire('pointermove', pointerAt(12, 12));+ adjustedSurfaceCacheDeleteFaults.add('control');++ expect(() => h.engine.dispose()).toThrow('adjusted surface cache delete failed');++ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();+ expect(h.bitmapStore.dispose).toHaveBeenCalledOnce();+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(h.strokes).toHaveLength(0);+ expect(() => h.engine.dispose()).not.toThrow();+ expect(h.bitmapStore.dispose).toHaveBeenCalledOnce();+ });});describe('engine-owned history: stroke → undo → redo', () => {@@ -12539,7 +12881,8 @@ describe('engine selection: fill / erase', () => {expect(h.engine.getDocument()).toEqual(beforeDocument);expect(h.engine.stores.canUndo.get()).toBe(false);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();- expect(h.bitmapStore.suspendLayer).not.toHaveBeenCalled();+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledOnce();+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();expect(h.engine.stores.thumbnailVersion.get('control')).toBe(beforeThumbnailVersion);const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });expect(restored.status).toBe('ok');@@ -12572,7 +12915,8 @@ describe('engine selection: fill / erase', () => {expect(h.engine.getDocument()).toEqual(beforeDocument);expect(h.engine.stores.canUndo.get()).toBe(false);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();- expect(h.bitmapStore.suspendLayer).not.toHaveBeenCalled();+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledOnce();+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();expect(h.engine.stores.thumbnailVersion.get('control')).toBe(beforeThumbnailVersion);const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });expect(restored.status).toBe(beforeExport.status);@@ -12679,14 +13023,14 @@ describe('engine selection: fill / erase', () => {const beforeDocument = structuredClone(h.engine.getDocument());const beforeCache = await snapshotLayerCache(h.engine, 'control');const originalCtx = beforeCache.surface.ctx;- let capturedBefore: ImageData | null = null;+ const capturedReads: ImageData[] = [];const failingCtx = new Proxy(originalCtx, {get(target, property, receiver) {const value = Reflect.get(target, property, receiver);if (property === 'getImageData' && typeof value === 'function') {return (...args: unknown[]) => {const result = Reflect.apply(value, target, args) as ImageData;- capturedBefore = result;+ capturedReads.push(result);return result;};}@@ -12712,9 +13056,11 @@ describe('engine selection: fill / erase', () => {expect(h.engine.getDocument()).toEqual(beforeDocument);expect(h.engine.stores.canUndo.get()).toBe(false);expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();+ expect(capturedReads[0]).toMatchObject({ height: 10, width: 10 });+ expect(capturedReads.at(-1)).toMatchObject({ height: 5, width: 5 });expect((beforeCache.surface as StubRasterSurface).callLog.filter((entry) => entry.op === 'putImageData').at(-1)?.args[0]- ).toBe(capturedBefore);+ ).toBe(capturedReads[0]);Object.defineProperty(beforeCache.surface, 'ctx', { configurable: true, value: originalCtx });h.engine.fillSelection();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex f286339a61..e9a1cf02dc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -332,6 +332,29 @@ const isImageDataEqual = (left: ImageData, right: ImageData): boolean => {return true;};+/** Runs every teardown step, then rethrows the first failure after cleanup is terminal. */+const createCleanupAccumulator = (): { run: (step: () => void) => void; throwIfFailed: () => void } => {+ let firstError: unknown;+ let hasFailed = false;+ return {+ run: (step) => {+ try {+ step();+ } catch (error) {+ if (!hasFailed) {+ firstError = error;+ hasFailed = true;+ }+ }+ },+ throwIfFailed: () => {+ if (hasFailed) {+ throw firstError instanceof Error ? firstError : new Error(String(firstError));+ }+ },+ };+};+/** Structural equality for JSON-safe canvas contracts (including synthetic mask paint sources). */const isDeeplyEqual = (left: unknown, right: unknown): boolean => {if (Object.is(left, right)) {@@ -2482,14 +2505,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {scheduler.invalidate(stagedPreview && !stagedPreview.placement ? { all: true } : { overlay: true });},onDocumentReplaced: () => {- pipeline.cancelActiveGesture();- cancelOpenControlPixelEdit();- canvasOperations.invalidateDocument(projectId);- cancelSelectObjectSession();+ const cleanup = createCleanupAccumulator();+ cleanup.run(() => pipeline.cancelActiveGesture());+ cleanup.run(cancelOpenControlPixelEdit);+ cleanup.run(() => canvasOperations.invalidateDocument(projectId));+ cleanup.run(cancelSelectObjectSession);const previousImageNames = [...mirroredLayerImageNames.values()];rasterDocumentGeneration += 1;- cancelAllLayerRasterizations();- stores.thumbnailStatus.clear();+ cleanup.run(cancelAllLayerRasterizations);+ cleanup.run(() => stores.thumbnailStatus.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.@@ -2500,26 +2524,26 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// pipeline clears `gestureActive` and runs the tool's `onPointerCancel`, so// the tool drops its own transient state.// Defensive: a non-bbox active tool won't have cleared a lingering preview.- stores.bboxPreview.set(null);- history.clear();- endNudgeBurst();+ cleanup.run(() => stores.bboxPreview.set(null));+ cleanup.run(() => history.clear());+ cleanup.run(endNudgeBurst);// A transform session (which outlives individual gestures) belongs to the// outgoing document; tear it down alongside its preview override.- stores.transformSession.set(null);- transformOverrides.clear();+ cleanup.run(() => stores.transformSession.set(null));+ cleanup.run(() => transformOverrides.clear());// A text-edit session likewise belongs to the outgoing document; drop it.- stores.textEditSession.set(null);+ cleanup.run(() => stores.textEditSession.set(null));// A staged preview belongs to the outgoing document's bbox/candidates; a// wholesale swap (project switch, snapshot restore) invalidates it.- clearStagedPreview();+ cleanup.run(clearStagedPreview);// Per-layer control-filter previews likewise belong to the outgoing// document — a swap can reuse a layer id with different content, so// pruning only "missing" ids isn't enough; drop them all.- clearAllFilterPreviews();+ cleanup.run(clearAllFilterPreviews);// The selection is document-scoped interaction state: a swap drops it (and// any in-progress lasso preview), stopping the ants loop via onChange.- selection.clear();- stores.lassoPreview.set(null);+ cleanup.run(() => selection.clear());+ cleanup.run(() => stores.lassoPreview.set(null));const doc = mirror.getDocument();const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);mirroredLayerImageNames.clear();@@ -2535,9 +2559,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const trackedIds = Array.from(trackedImageNames.keys());for (const layerId of trackedIds) {if (!present.has(layerId)) {- dropLayer(layerId);+ cleanup.run(() => dropLayer(layerId));} else {- untrackLayerImage(layerId);+ cleanup.run(() => untrackLayerImage(layerId));}}// A wholesale replacement can reuse a layer id with a DIFFERENT source, so@@ -2546,32 +2570,34 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// reference happened to change — to force a re-rasterize from the new// source; a diff can't be trusted across a full swap.for (const layerId of present) {- invalidateLayerCache(layerId);+ cleanup.run(() => invalidateLayerCache(layerId));}for (const imageName of previousImageNames) {- releaseBitmapIfUnreferenced(imageName);+ cleanup.run(() => releaseBitmapIfUnreferenced(imageName));}// Persistence bookkeeping (the self-echo `lastApplied` map and pending// debounced flushes) described the OLD document. Drop it so a reused layer// id can't have its next legit persistence dispatch suppressed as a stale// self-echo.- bitmapStore.reset();- scheduler.invalidate({ all: true });+ cleanup.run(() => bitmapStore.reset());+ cleanup.run(() => scheduler.invalidate({ all: true }));+ cleanup.throwIfFailed();},onLayerOrderChanged: () => {scheduler.invalidate({ all: true });},onLayersChanged: (ids, sourceChangedIds) => {+ const cleanup = createCleanupAccumulator();if (openControlPixelEdit && ids.includes(openControlPixelEdit.layerId)) {- pipeline.cancelActiveGesture();- cancelOpenControlPixelEdit();+ cleanup.run(() => pipeline.cancelActiveGesture());+ cleanup.run(cancelOpenControlPixelEdit);}const doc = mirror.getDocument();for (const id of sourceChangedIds) {- canvasOperations.invalidateSource(projectId, id);+ cleanup.run(() => canvasOperations.invalidateSource(projectId, id));}for (const id of ids) {- canvasOperations.invalidateLayer(projectId, id);+ cleanup.run(() => canvasOperations.invalidateLayer(projectId, id));}const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);const sourceChanged = new Set(sourceChangedIds);@@ -2598,10 +2624,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const layer = doc?.layers.find((candidate) => candidate.id === id);if (!present.has(id)) {thumbnailDisplayKeys.delete(id);- dropLayer(id);+ cleanup.run(() => dropLayer(id));const previousImageName = previousImageNames.get(id);if (previousImageName) {- releaseBitmapIfUnreferenced(previousImageName);+ cleanup.run(() => releaseBitmapIfUnreferenced(previousImageName));}// A control-filter preview (session + decoded surface) belongs to a// specific layer; a layer removed out from under an in-flight or@@ -2609,20 +2635,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {// that removes it) must have its preview dropped and its decode// token bumped, or a late-resolving decode — or a later undo that// restores this same id — would repopulate a stale preview.- clearFilterPreview(id);+ cleanup.run(() => clearFilterPreview(id));if (session && session.layerId === id) {- cancelTransform();+ cleanup.run(cancelTransform);}// An edit-mode text session whose layer was deleted out from under it// (layers panel, or undo of the add) is torn down the same way.if (textSession && textSession.layerId === id) {- cancelTextEdit();+ cleanup.run(cancelTextEdit);}continue;}const preview = filterPreviews.get(id);if (preview && !isLayerExportGuardCurrent(preview.guard)) {- clearFilterPreview(id);+ cleanup.run(() => clearFilterPreview(id));}if (!sourceChanged.has(id)) {if (layer) {@@ -2657,18 +2683,19 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {if (layer) {thumbnailDisplayKeys.set(id, getLayerThumbnailDisplayKey(layer));}- untrackLayerImage(id);+ cleanup.run(() => untrackLayerImage(id));const previousImageName = previousImageNames.get(id);if (previousImageName) {- releaseBitmapIfUnreferenced(previousImageName);+ cleanup.run(() => releaseBitmapIfUnreferenced(previousImageName));}const source = getLayerSourceById(id);if (bitmapStore.isSelfEcho(id, source)) {continue;}- invalidateLayerCache(id);+ cleanup.run(() => invalidateLayerCache(id));}- scheduler.invalidate({ layers: ids });+ cleanup.run(() => scheduler.invalidate({ layers: ids }));+ cleanup.throwIfFailed();},onStagingChanged: () => scheduler.invalidate({ overlay: true }),});@@ -2688,20 +2715,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const unsubscribeProjectPreviewLifecycle = store.subscribe(() => {const activeProjectId = store.getState().activeProjectId;if (lastActiveProjectId === projectId && activeProjectId !== projectId) {- pipeline.cancelActiveGesture();- cancelOpenControlPixelEdit();- canvasOperations.invalidateProject(projectId);- cancelSelectObjectSession();+ const cleanup = createCleanupAccumulator();+ cleanup.run(() => pipeline.cancelActiveGesture());+ cleanup.run(cancelOpenControlPixelEdit);+ cleanup.run(() => canvasOperations.invalidateProject(projectId));+ cleanup.run(cancelSelectObjectSession);rasterDocumentGeneration += 1;- cancelAllLayerRasterizations();- stores.thumbnailStatus.clear();+ cleanup.run(cancelAllLayerRasterizations);+ cleanup.run(() => stores.thumbnailStatus.clear());const ids = new Set<string>(guardedFilterPreviewTokens.keys());for (const layerId of filterPreviews.keys()) {ids.add(layerId);}for (const layerId of ids) {- clearFilterPreview(layerId);+ cleanup.run(() => clearFilterPreview(layerId));}+ lastActiveProjectId = activeProjectId;+ cleanup.throwIfFailed();+ return;}lastActiveProjectId = activeProjectId;});@@ -4086,6 +4117,32 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {}if (decision.status === 'direct') {+ const originalEntry = layerCache.get(layerId);+ let originalPixels: ImageData | null = null;+ if (originalEntry && !isEmpty(originalEntry.rect)) {+ try {+ originalPixels = originalEntry.surface.ctx.getImageData(+ 0,+ 0,+ originalEntry.rect.width,+ originalEntry.rect.height+ );+ } catch {+ return null;+ }+ }+ const originalCache = originalEntry+ ? {+ hasPublishedPixels: originalEntry.hasPublishedPixels,+ lastUsed: originalEntry.lastUsed,+ pixels: originalPixels,+ rect: { ...originalEntry.rect },+ stale: originalEntry.stale,+ surface: originalEntry.surface,+ version: originalEntry.version,+ }+ : null;+ const releasePersistence = bitmapStore.suspendLayer(layerId);let closed = false;let owner: { cancel: () => void; layerId: string };const close = (): boolean => {@@ -4096,18 +4153,52 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {openControlPixelEdit = null;return true;};- const restorePatch = (patch: PixelEditPatch): void => {- const entry = layerCache.get(layerId);- if (entry) {- entry.surface.ctx.putImageData(patch.before, patch.rect.x - entry.rect.x, patch.rect.y - entry.rect.y);- adjustedSurfaceCache.delete(layerId);- scheduler.invalidate({ layers: [layerId] });+ const restoreOriginal = (): void => {+ try {+ if (!originalCache) {+ layerCache.delete(layerId);+ } else {+ originalCache.surface.resize(originalCache.rect.width, originalCache.rect.height);+ if (originalCache.pixels) {+ originalCache.surface.ctx.putImageData(originalCache.pixels, 0, 0);+ }+ const current = layerCache.get(layerId) ?? layerCache.getOrCreateRect(layerId, originalCache.rect);+ current.hasPublishedPixels = originalCache.hasPublishedPixels;+ current.lastUsed = originalCache.lastUsed;+ current.rect = { ...originalCache.rect };+ current.stale = originalCache.stale;+ current.surface = originalCache.surface;+ current.version = originalCache.version;+ }+ } finally {+ try {+ adjustedSurfaceCache.delete(layerId);+ } finally {+ scheduler.invalidate({ layers: [layerId] });+ }}};+ const restoreAndRelease = (): void => {+ try {+ restoreOriginal();+ } finally {+ releasePersistence();+ }+ };+ const cancel = (): void => {+ if (!close()) {+ return;+ }+ restoreAndRelease();+ };const commitPatch = (label: string, patch: PixelEditPatch): boolean => {if (closed || openControlPixelEdit !== owner) {return false;}+ if (isImageDataEqual(patch.before, patch.after)) {+ cancel();+ return false;+ }const currentDocument = mirror.getDocument();const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layerId);if (@@ -4117,8 +4208,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {currentDocument?.selectedLayerId !== layerId ||currentLayer !== layer) {- close();- restorePatch(patch);+ cancel();return false;}close();@@ -4135,21 +4225,23 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {});}} catch (error) {- restorePatch(patch);+ restoreAndRelease();throw error;}endNudgeBurst();- if (historyEntry) {- history.push(historyEntry);+ try {+ if (historyEntry) {+ history.push(historyEntry);+ }+ notifyLayerPainted(layerId);+ bitmapStore.markLayerDirty(layerId);+ } finally {+ releasePersistence();}- notifyLayerPainted(layerId);- bitmapStore.markLayerDirty(layerId);return true;};const transaction: ControlPixelEditTransaction = {- cancel: () => {- close();- },+ cancel,commitPatch: (label, patch) => {commitPatch(label, patch);},@@ -4174,7 +4266,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {},layerId,};- owner = { cancel: transaction.cancel, layerId };+ owner = { cancel, layerId };openControlPixelEdit = owner;return transaction;}@@ -4352,8 +4444,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {};const transaction: ControlPixelEditTransaction = {cancel,- commitPatch: (label) => commit(label),- commitStroke: (event) => commit(event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke', event),+ commitPatch: (label, patch) => {+ if (isImageDataEqual(patch.before, patch.after)) {+ cancel();+ return;+ }+ commit(label);+ },+ commitStroke: (event) => {+ if (isImageDataEqual(event.beforeImageData, event.afterImageData)) {+ cancel();+ return;+ }+ commit(event.tool === 'eraser' ? 'Eraser stroke' : 'Brush stroke', event);+ },layerId,};owner = { cancel, layerId };@@ -6902,46 +7006,48 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return;}disposed = true;- pipeline.cancelActiveGesture();- cancelOpenControlPixelEdit();- clearOwnedFilterSession();- clearOwnedSelectObjectSession();- canvasOperations.dispose();- cancelAllLayerRasterizations();- detach();+ const cleanup = createCleanupAccumulator();+ cleanup.run(() => pipeline.cancelActiveGesture());+ cleanup.run(cancelOpenControlPixelEdit);+ cleanup.run(clearOwnedFilterSession);+ cleanup.run(clearOwnedSelectObjectSession);+ cleanup.run(() => canvasOperations.dispose());+ cleanup.run(cancelAllLayerRasterizations);+ cleanup.run(detach);// Drop any open text-edit session (its layer belongs to a document this// engine no longer serves).- stores.textEditSession.set(null);+ cleanup.run(() => stores.textEditSession.set(null));// Drop any guarded filter previews outright — the engine is going away, so// there's no render loop left to invalidate for them.- filterPreviews.clear();- filterPreviewTokens.clear();- guardedFilterPreviewTokens.clear();- antsAnimator.stop();- selection.dispose();- activeTool()?.onDeactivate?.(toolContext);- unsubscribeViewport();- unsubscribeBrushOptions();- unsubscribeEraserOptions();- unsubscribeCheckerboard();- unsubscribeCheckerColors();- unsubscribeShowGrid();- unsubscribeBboxGrid();- unsubscribeShowBbox();- unsubscribeBboxOverlay();- unsubscribeRuleOfThirds();- unsubscribeHistory();- unsubscribeProjectPreviewLifecycle();- unsubscribeDocumentEditingLock();- history.clear();- bitmapStore.dispose();- mirror.dispose();- scheduler.dispose();- layerCache.dispose();- adjustedSurfaceCache.dispose();- trackedImageNames.clear();- stores.thumbnailStatus.clear();- strokeListeners.clear();+ cleanup.run(() => filterPreviews.clear());+ cleanup.run(() => filterPreviewTokens.clear());+ cleanup.run(() => guardedFilterPreviewTokens.clear());+ cleanup.run(() => antsAnimator.stop());+ cleanup.run(() => selection.dispose());+ cleanup.run(() => activeTool()?.onDeactivate?.(toolContext));+ cleanup.run(unsubscribeViewport);+ cleanup.run(unsubscribeBrushOptions);+ cleanup.run(unsubscribeEraserOptions);+ cleanup.run(unsubscribeCheckerboard);+ cleanup.run(unsubscribeCheckerColors);+ cleanup.run(unsubscribeShowGrid);+ cleanup.run(unsubscribeBboxGrid);+ cleanup.run(unsubscribeShowBbox);+ cleanup.run(unsubscribeBboxOverlay);+ cleanup.run(unsubscribeRuleOfThirds);+ cleanup.run(unsubscribeHistory);+ cleanup.run(unsubscribeProjectPreviewLifecycle);+ cleanup.run(unsubscribeDocumentEditingLock);+ cleanup.run(() => history.clear());+ cleanup.run(() => bitmapStore.dispose());+ cleanup.run(() => mirror.dispose());+ cleanup.run(() => scheduler.dispose());+ cleanup.run(() => layerCache.dispose());+ cleanup.run(() => adjustedSurfaceCache.dispose());+ cleanup.run(() => trackedImageNames.clear());+ cleanup.run(() => stores.thumbnailStatus.clear());+ cleanup.run(() => strokeListeners.clear());+ cleanup.throwIfFailed();};const onStrokeCommitted = (listener: (event: StrokeCommittedEvent) => void): (() => void) => {