Skip to content

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.

fix(canvas): make raster structural history failure-atomic

joshistoast0a1773088c89
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.ts
index a94d39afd2..300fec6be6 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
@@ -12,6 +12,7 @@ import type { CanvasDocumentContractV2, CanvasStateContractV2, WorkbenchState }
import type { WorkbenchAction } from '@workbench/workbenchState';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { EngineStore } from './engine';
@@ -91,6 +92,30 @@ const createReactiveStore = (document: CanvasDocumentContractV2) => {
};
};
+const createReducerBackedStore = (document: CanvasDocumentContractV2) => {
+ let state = createInitialWorkbenchState();
+ const projectId = state.activeProjectId;
+ 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 {
+ projectId,
+ store: {
+ dispatch,
+ getState: () => state,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ } as EngineStore,
+ };
+};
+
const createControllableRaf = () => {
let nextHandle = 1;
const callbacks = new Map<number, FrameRequestCallback>();
@@ -373,12 +398,12 @@ describe('mask invert', () => {
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'raster',
});
- const reactive = createReactiveStore(doc);
+ const reducer = createReducerBackedStore(doc);
const engine = createCanvasEngine({
backend: createTestStubRasterBackend(),
imageResolver: () => Promise.resolve(new Blob()),
- projectId: 'p1',
- store: reactive.store,
+ projectId: reducer.projectId,
+ store: reducer.store,
});
const overlay = createInputCanvas();
const screen = createInputCanvas();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index e548366e7f..d9250df5bd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -286,6 +286,92 @@ const createRecordingRasterBackend = (): RecordingRasterBackend => {
const recordingBitmap = (id: string): ImageBitmap =>
({ __recordingId: `bitmap-${id}`, close: vi.fn(), height: 10, width: 10 }) as unknown as ImageBitmap;
+/** One-shot allocation/draw faults, armed after a deterministic number of successful calls. */
+const createStructuralFaultBackend = () => {
+ const base = createTestStubRasterBackend();
+ let allocationCountdown: number | null = null;
+ let drawCountdown: number | null = null;
+ const backend: StubRasterBackend = {
+ ...base,
+ createSurface: (width, height) => {
+ if (allocationCountdown !== null) {
+ if (allocationCountdown === 0) {
+ allocationCountdown = null;
+ throw new Error('structural cache allocation failed');
+ }
+ allocationCountdown -= 1;
+ }
+ const surface = base.createSurface(width, height);
+ const ctx = new Proxy(surface.ctx, {
+ get: (target, property, receiver) => {
+ const value = Reflect.get(target, property, receiver);
+ if (property !== 'drawImage' || typeof value !== 'function') {
+ return value;
+ }
+ return (...args: unknown[]) => {
+ if (drawCountdown !== null) {
+ if (drawCountdown === 0) {
+ drawCountdown = null;
+ throw new Error('structural cache draw failed');
+ }
+ drawCountdown -= 1;
+ }
+ return Reflect.apply(value, target, args);
+ };
+ },
+ });
+ Object.defineProperty(surface, 'ctx', { value: ctx });
+ return surface;
+ },
+ };
+
+ return {
+ armAllocation: (successfulCreates: number) => {
+ allocationCountdown = successfulCreates;
+ },
+ armDraw: (successfulDraws: number) => {
+ drawCountdown = successfulDraws;
+ },
+ backend,
+ };
+};
+
+interface LayerCacheTestSnapshot {
+ calls: RasterCallLogEntry[];
+ rect: { height: number; width: number; x: number; y: number };
+ surface: RasterSurface;
+ version: number;
+}
+
+const snapshotLayerCache = async (engine: ReturnType<typeof createCanvasEngine>, layerId: string) => {
+ const exported = await engine.exportLayerPixels(layerId, { includeDisabled: true });
+ if (exported.status !== 'ok') {
+ throw new Error(`Expected a ready cache for ${layerId}, got ${exported.status}`);
+ }
+ return {
+ calls: structuredClone((exported.surface as StubRasterSurface).callLog),
+ rect: { ...exported.rect },
+ surface: exported.surface,
+ version: exported.guard.cacheVersion,
+ } satisfies LayerCacheTestSnapshot;
+};
+
+const expectLayerCacheExact = async (
+ engine: ReturnType<typeof createCanvasEngine>,
+ layerId: string,
+ expectedSnapshot: LayerCacheTestSnapshot
+): Promise<void> => {
+ const actual = await engine.exportLayerPixels(layerId, { includeDisabled: true });
+ expect(actual.status).toBe('ok');
+ if (actual.status !== 'ok') {
+ return;
+ }
+ expect(actual.surface).toBe(expectedSnapshot.surface);
+ expect(actual.rect).toEqual(expectedSnapshot.rect);
+ expect(actual.guard.cacheVersion).toBe(expectedSnapshot.version);
+ expect((actual.surface as StubRasterSurface).callLog).toEqual(expectedSnapshot.calls);
+};
+
/** Recursively follows recording-surface draw edges to a bitmap/surface id. */
const drawGraphContains = (
surface: StubRasterSurface,
@@ -1246,7 +1332,7 @@ describe('createCanvasEngine', () => {
it('copyLayerToRaster adds a baked paint copy directly above the source layer', async () => {
const doc = { ...makeDoc(), layers: [rasterLayer('top'), rasterLayer('a')] };
- const { store } = createFakeStore(doc);
+ const { projectId, store } = createReducerBackedStore(doc);
const dispatch = store.dispatch as Mock;
const base = createTestStubRasterBackend();
const surfaces: StubRasterSurface[] = [];
@@ -1260,25 +1346,26 @@ describe('createCanvasEngine', () => {
},
},
imageResolver: () => Promise.resolve(new Blob()),
- projectId: 'p1',
+ projectId,
store,
});
const newId = await engine.copyLayerToRaster('a');
expect(newId).toMatch(/^layer-/);
- const add = dispatch.mock.calls
+ const mutation = dispatch.mock.calls
.map((call) => call[0] as WorkbenchAction)
- .find((action) => action.type === 'addCanvasLayer');
- expect(add).toBeDefined();
- if (add?.type === 'addCanvasLayer' && add.layer.type === 'raster') {
- expect(add.index).toBe(1);
- expect(add.layer.id).toBe(newId);
- expect(add.layer.name).toBe('a copy');
- expect(add.layer.source).toEqual({ bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' });
- expect(add.layer.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
+ .find((action) => action.type === 'applyCanvasLayerStackMutation');
+ expect(mutation).toBeDefined();
+ const added = mutation?.type === 'applyCanvasLayerStackMutation' ? mutation.add : undefined;
+ if (added?.layer.type === 'raster') {
+ expect(added.index).toBe(1);
+ expect(added.layer.id).toBe(newId);
+ expect(added.layer.name).toBe('a copy');
+ expect(added.layer.source).toEqual({ bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' });
+ expect(added.layer.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
} else {
- throw new Error('expected addCanvasLayer with raster copy');
+ throw new Error('expected atomic layer-stack mutation with raster copy');
}
expect(
surfaces.some(
@@ -1331,7 +1418,7 @@ describe('createCanvasEngine', () => {
engine.dispose();
});
- it('copyLayerToRaster redo cache failure cannot be retried into a duplicate layer id', async () => {
+ it('copyLayerToRaster redo cache failure leaves the copy absent and retryable', async () => {
const { projectId, store } = createReducerBackedStore(makeDoc());
const base = createTestStubRasterBackend();
let failNextAllocation = false;
@@ -1359,14 +1446,14 @@ describe('createCanvasEngine', () => {
failNextAllocation = true;
expect(() => engine.redo()).toThrow('copy replay allocation failed');
- // The reducer add already landed before cache allocation failed. Legacy
- // history therefore consumes redo and exposes undo; replaying redo again
- // must be a no-op rather than inserting the same structural id twice.
+ expect(engine.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(0);
+ expect(engine.stores.canUndo.get()).toBe(false);
+ expect(engine.stores.canRedo.get()).toBe(true);
+
+ engine.redo();
expect(engine.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(1);
expect(engine.stores.canUndo.get()).toBe(true);
expect(engine.stores.canRedo.get()).toBe(false);
- expect(() => engine.redo()).not.toThrow();
- expect(engine.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(1);
engine.undo();
expect(engine.getDocument()!.layers.filter((layer) => layer.id === newId)).toHaveLength(0);
@@ -3189,6 +3276,599 @@ const createReducerBackedStore = (
};
};
+describe('structural raster publication failure atomicity', () => {
+ const sentinelLayer = (): CanvasLayerContract => ({
+ ...rasterLayer('selection-sentinel'),
+ isEnabled: false,
+ });
+
+ const createFaultHarness = (document: CanvasDocumentContractV2) => {
+ const faults = createStructuralFaultBackend();
+ const bitmapStore = createSpyBitmapStore();
+ const reducer = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: faults.backend,
+ bitmapStore,
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: reducer.projectId,
+ store: reducer.store,
+ });
+ return { ...reducer, bitmapStore, engine, faults };
+ };
+
+ type StructuralFault = 'allocation' | 'draw';
+ const structuralFaults = ['allocation', 'draw'] as const satisfies readonly StructuralFault[];
+ const armStructuralFault = (
+ faults: ReturnType<typeof createStructuralFaultBackend>,
+ failure: StructuralFault,
+ countdowns: Record<StructuralFault, number>
+ ): void => {
+ if (failure === 'allocation') {
+ faults.armAllocation(countdowns.allocation);
+ } else {
+ faults.armDraw(countdowns.draw);
+ }
+ };
+ const structuralFaultMessage = (failure: StructuralFault): string => `structural cache ${failure} failed`;
+
+ const expectInitialFailureExact = (
+ harness: ReturnType<typeof createFaultHarness>,
+ expectedDocument: CanvasDocumentContractV2
+ ): void => {
+ expect(harness.engine.getDocument()).toBe(expectedDocument);
+ expect(harness.engine.getDocument()).toEqual(expectedDocument);
+ expect(harness.engine.getDocument()!.selectedLayerId).toBe('selection-sentinel');
+ expect(harness.store.dispatch).not.toHaveBeenCalled();
+ expect(harness.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(harness.bitmapStore.discardLayer).not.toHaveBeenCalled();
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(false);
+ };
+
+ it.each(structuralFaults)(
+ 'crop keeps document, cache, selection, and history exact when final cache %s fails',
+ async (failure) => {
+ const source = rasterLayer('crop-source');
+ const document: CanvasDocumentContractV2 = {
+ ...makeDoc(),
+ bbox: { height: 7, width: 6, x: 2, y: 3 },
+ layers: [source, sentinelLayer()],
+ selectedLayerId: 'selection-sentinel',
+ };
+ const harness = createFaultHarness(document);
+ const sourceCache = await snapshotLayerCache(harness.engine, source.id);
+ const expectedDocument = harness.engine.getDocument()!;
+ (harness.store.dispatch as Mock).mockClear();
+ harness.bitmapStore.markLayerDirty.mockClear();
+ armStructuralFault(harness.faults, failure, { allocation: 3, draw: 3 });
+
+ await expect(harness.engine.cropLayerToBbox(source.id)).resolves.toEqual({
+ message: structuralFaultMessage(failure),
+ status: 'failed',
+ });
+
+ expectInitialFailureExact(harness, expectedDocument);
+ await expectLayerCacheExact(harness.engine, source.id, sourceCache);
+ harness.engine.dispose();
+ }
+ );
+
+ it.each(structuralFaults)(
+ 'commitLayerCopy keeps document, cache, selection, and history exact when final cache %s fails',
+ async (failure) => {
+ const source = rasterLayer('copy-source');
+ const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };
+ const harness = createFaultHarness(document);
+ const sourceCache = await snapshotLayerCache(harness.engine, source.id);
+ const expectedDocument = harness.engine.getDocument()!;
+ const copy = { ...structuredClone(source), id: 'copy-result', name: 'Copy result' };
+ (harness.store.dispatch as Mock).mockClear();
+ harness.bitmapStore.markLayerDirty.mockClear();
+ armStructuralFault(harness.faults, failure, { allocation: 1, draw: 1 });
+
+ expect(() => harness.engine.commitLayerCopy('Copy layer', source.id, copy, 0)).toThrow(
+ structuralFaultMessage(failure)
+ );
+
+ expectInitialFailureExact(harness, expectedDocument);
+ expect(harness.engine.getDocument()!.layers.some((layer) => layer.id === copy.id)).toBe(false);
+ await expectLayerCacheExact(harness.engine, source.id, sourceCache);
+ harness.engine.dispose();
+ }
+ );
+
+ it.each(structuralFaults)(
+ 'commitLayerConversion keeps document, cache, selection, and history exact when final cache %s fails',
+ async (failure) => {
+ const source = rasterLayer('conversion-source');
+ const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };
+ const harness = createFaultHarness(document);
+ const sourceCache = await snapshotLayerCache(harness.engine, source.id);
+ const expectedDocument = harness.engine.getDocument()!;
+ const live = harness.engine.getDocument()!.layers.find((layer) => layer.id === source.id)!;
+ if (live.type !== 'raster') {
+ throw new Error('expected a raster conversion source');
+ }
+ const converted: CanvasLayerContract = {
+ ...structuredClone(live),
+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },
+ type: 'control',
+ withTransparencyEffect: false,
+ };
+ (harness.store.dispatch as Mock).mockClear();
+ harness.bitmapStore.markLayerDirty.mockClear();
+ armStructuralFault(harness.faults, failure, { allocation: 1, draw: 1 });
+
+ expect(() => harness.engine.commitLayerConversion('Convert layer', live, converted)).toThrow(
+ structuralFaultMessage(failure)
+ );
+
+ expectInitialFailureExact(harness, expectedDocument);
+ await expectLayerCacheExact(harness.engine, source.id, sourceCache);
+ harness.engine.dispose();
+ }
+ );
+
+ it.each(structuralFaults)(
+ 'copyLayerToRaster keeps document, cache, selection, and history exact when final cache %s fails',
+ async (failure) => {
+ const source = rasterLayer('raster-copy-source');
+ const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };
+ const harness = createFaultHarness(document);
+ const sourceCache = await snapshotLayerCache(harness.engine, source.id);
+ const expectedDocument = harness.engine.getDocument()!;
+ (harness.store.dispatch as Mock).mockClear();
+ harness.bitmapStore.markLayerDirty.mockClear();
+ armStructuralFault(harness.faults, failure, { allocation: 1, draw: 1 });
+
+ await expect(harness.engine.copyLayerToRaster(source.id)).rejects.toThrow(structuralFaultMessage(failure));
+
+ expectInitialFailureExact(harness, expectedDocument);
+ await expectLayerCacheExact(harness.engine, source.id, sourceCache);
+ harness.engine.dispose();
+ }
+ );
+
+ it.each(structuralFaults)(
+ 'boolean merge keeps document, source caches, selection, and history exact when final cache %s fails',
+ async (failure) => {
+ const pair = twoPaintDoc();
+ const document = {
+ ...pair,
+ layers: [...pair.layers, sentinelLayer()],
+ selectedLayerId: 'selection-sentinel',
+ };
+ const harness = createFaultHarness(document);
+ const upperCache = await snapshotLayerCache(harness.engine, 'upper');
+ const belowCache = await snapshotLayerCache(harness.engine, 'below');
+ const expectedDocument = harness.engine.getDocument()!;
+ (harness.store.dispatch as Mock).mockClear();
+ harness.bitmapStore.markLayerDirty.mockClear();
+ armStructuralFault(harness.faults, failure, { allocation: 3, draw: 4 });
+
+ await expect(harness.engine.booleanMergeRasterLayers('upper', 'intersect')).rejects.toThrow(
+ structuralFaultMessage(failure)
+ );
+
+ expectInitialFailureExact(harness, expectedDocument);
+ await expectLayerCacheExact(harness.engine, 'upper', upperCache);
+ await expectLayerCacheExact(harness.engine, 'below', belowCache);
+ harness.engine.dispose();
+ }
+ );
+
+ it.each(structuralFaults)(
+ 'masked extraction keeps document, source caches, selection, and history exact when final cache %s fails',
+ async (failure) => {
+ const pair = twoPaintDoc();
+ const mask: CanvasInpaintMaskLayerContract = {
+ ...maskLayer('atomic-mask'),
+ mask: {
+ bitmap: { height: 20, imageName: 'atomic-mask-bitmap', width: 20 },
+ fill: { color: '#e07575', style: 'diagonal' },
+ offset: { x: 15, y: 25 },
+ },
+ };
+ const document = {
+ ...pair,
+ layers: [mask, ...pair.layers, sentinelLayer()],
+ selectedLayerId: 'selection-sentinel',
+ };
+ const harness = createFaultHarness(document);
+ const maskCache = await snapshotLayerCache(harness.engine, mask.id);
+ const upperCache = await snapshotLayerCache(harness.engine, 'upper');
+ const belowCache = await snapshotLayerCache(harness.engine, 'below');
+ const expectedDocument = harness.engine.getDocument()!;
+ (harness.store.dispatch as Mock).mockClear();
+ harness.bitmapStore.markLayerDirty.mockClear();
+ armStructuralFault(harness.faults, failure, { allocation: 2, draw: 4 });
+
+ await expect(harness.engine.extractMaskedArea(mask.id)).rejects.toThrow(structuralFaultMessage(failure));
+
+ expectInitialFailureExact(harness, expectedDocument);
+ await expectLayerCacheExact(harness.engine, mask.id, maskCache);
+ await expectLayerCacheExact(harness.engine, 'upper', upperCache);
+ await expectLayerCacheExact(harness.engine, 'below', belowCache);
+ harness.engine.dispose();
+ }
+ );
+
+ const createCropReplayHarness = async () => {
+ const source = rasterLayer('crop-replay-source');
+ const document: CanvasDocumentContractV2 = {
+ ...makeDoc(),
+ bbox: { height: 7, width: 6, x: 2, y: 3 },
+ layers: [source, sentinelLayer()],
+ selectedLayerId: 'selection-sentinel',
+ };
+ const harness = createFaultHarness(document);
+ await snapshotLayerCache(harness.engine, source.id);
+ await expect(harness.engine.cropLayerToBbox(source.id)).resolves.toEqual({ status: 'cropped' });
+ return { ...harness, originalDocument: document, source };
+ };
+
+ it.each(structuralFaults)(
+ 'crop undo cache-%s failure leaves the committed state exact and retryable',
+ async (failure) => {
+ const harness = await createCropReplayHarness();
+ const committedDocument = harness.engine.getDocument()!;
+ const committedCache = await snapshotLayerCache(harness.engine, harness.source.id);
+ armStructuralFault(harness.faults, failure, { allocation: 0, draw: 0 });
+
+ expect(() => harness.engine.undo()).toThrow(structuralFaultMessage(failure));
+
+ expect(harness.engine.getDocument()).toBe(committedDocument);
+ expect(harness.engine.getDocument()).toEqual(committedDocument);
+ expect(harness.engine.stores.canUndo.get()).toBe(true);
+ expect(harness.engine.stores.canRedo.get()).toBe(false);
+ await expectLayerCacheExact(harness.engine, harness.source.id, committedCache);
+ harness.engine.undo();
+ expect(harness.engine.getDocument()).toEqual(harness.originalDocument);
+ harness.engine.dispose();
+ }
+ );
+
+ it.each(structuralFaults)(
+ 'crop redo cache-%s failure leaves the restored state exact and retryable',
+ async (failure) => {
+ const harness = await createCropReplayHarness();
+ const committedDocument = structuredClone(harness.engine.getDocument()!);
+ harness.engine.undo();
+ const restoredDocument = harness.engine.getDocument()!;
+ const restoredCache = await snapshotLayerCache(harness.engine, harness.source.id);
+ armStructuralFault(harness.faults, failure, { allocation: 0, draw: 0 });
+
+ expect(() => harness.engine.redo()).toThrow(structuralFaultMessage(failure));
+
+ expect(harness.engine.getDocument()).toBe(restoredDocument);
+ expect(harness.engine.getDocument()).toEqual(harness.originalDocument);
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(true);
+ await expectLayerCacheExact(harness.engine, harness.source.id, restoredCache);
+ harness.engine.redo();
+ expect(harness.engine.getDocument()).toEqual(committedDocument);
+ harness.engine.dispose();
+ }
+ );
+
+ it('commitLayerCopy redo cache-draw failure leaves the restored state exact and retryable', async () => {
+ const source = rasterLayer('copy-replay-source');
+ const copy = { ...structuredClone(source), id: 'copy-replay-result', name: 'Copy replay result' };
+ const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };
+ const harness = createFaultHarness(document);
+ const originalCache = await snapshotLayerCache(harness.engine, source.id);
+ const originalDocument = harness.engine.getDocument()!;
+ expect(harness.engine.commitLayerCopy('Copy layer', source.id, copy, 0)).toBe(true);
+ const committedDocument = structuredClone(harness.engine.getDocument()!);
+ harness.engine.undo();
+ const restoredDocument = harness.engine.getDocument()!;
+ harness.faults.armDraw(0);
+
+ expect(() => harness.engine.redo()).toThrow('structural cache draw failed');
+
+ expect(harness.engine.getDocument()).toBe(restoredDocument);
+ expect(harness.engine.getDocument()).toEqual(originalDocument);
+ expect(harness.engine.getDocument()!.layers.some((layer) => layer.id === copy.id)).toBe(false);
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(true);
+ await expectLayerCacheExact(harness.engine, source.id, originalCache);
+ harness.engine.redo();
+ expect(harness.engine.getDocument()).toEqual(committedDocument);
+ expect(harness.engine.getDocument()!.layers.filter((layer) => layer.id === copy.id)).toHaveLength(1);
+ harness.engine.dispose();
+ });
+
+ it('commitLayerConversion keeps failed undo and redo cache preparation exact and retryable', async () => {
+ const source = rasterLayer('conversion-replay-source');
+ const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };
+ const harness = createFaultHarness(document);
+ await snapshotLayerCache(harness.engine, source.id);
+ const originalDocument = harness.engine.getDocument()!;
+ const live = originalDocument.layers.find((layer) => layer.id === source.id)!;
+ if (live.type !== 'raster') {
+ throw new Error('expected a raster conversion source');
+ }
+ const converted: CanvasLayerContract = {
+ ...structuredClone(live),
+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },
+ type: 'control',
+ withTransparencyEffect: false,
+ };
+ expect(harness.engine.commitLayerConversion('Convert layer', live, converted)).toBe(true);
+ const committedDocument = harness.engine.getDocument()!;
+ const committedCache = await snapshotLayerCache(harness.engine, source.id);
+ harness.faults.armDraw(0);
+
+ expect(() => harness.engine.undo()).toThrow('structural cache draw failed');
+
+ expect(harness.engine.getDocument()).toBe(committedDocument);
+ expect(harness.engine.stores.canUndo.get()).toBe(true);
+ expect(harness.engine.stores.canRedo.get()).toBe(false);
+ await expectLayerCacheExact(harness.engine, source.id, committedCache);
+ harness.engine.undo();
+ expect(harness.engine.getDocument()).toEqual(originalDocument);
+ const restoredDocument = harness.engine.getDocument()!;
+ const restoredCache = await snapshotLayerCache(harness.engine, source.id);
+ harness.faults.armAllocation(0);
+
+ expect(() => harness.engine.redo()).toThrow('structural cache allocation failed');
+
+ expect(harness.engine.getDocument()).toBe(restoredDocument);
+ expect(harness.engine.getDocument()).toEqual(originalDocument);
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(true);
+ await expectLayerCacheExact(harness.engine, source.id, restoredCache);
+ harness.engine.redo();
+ expect(harness.engine.getDocument()).toEqual(committedDocument);
+ harness.engine.dispose();
+ });
+
+ it('boolean redo cache-draw failure leaves sources, selection, and history exact and retryable', async () => {
+ const pair = twoPaintDoc();
+ const document = {
+ ...pair,
+ layers: [...pair.layers, sentinelLayer()],
+ selectedLayerId: 'selection-sentinel',
+ };
+ const harness = createFaultHarness(document);
+ const upperCache = await snapshotLayerCache(harness.engine, 'upper');
+ const belowCache = await snapshotLayerCache(harness.engine, 'below');
+ const originalDocument = harness.engine.getDocument()!;
+ await expect(harness.engine.booleanMergeRasterLayers('upper', 'exclude')).resolves.toBe('merged');
+ const committedDocument = structuredClone(harness.engine.getDocument()!);
+ const resultId = harness.engine.getDocument()!.selectedLayerId!;
+ harness.engine.undo();
+ const restoredDocument = harness.engine.getDocument()!;
+ harness.faults.armDraw(0);
+
+ expect(() => harness.engine.redo()).toThrow('structural cache draw failed');
+
+ expect(harness.engine.getDocument()).toBe(restoredDocument);
+ expect(harness.engine.getDocument()).toEqual(originalDocument);
+ expect(harness.engine.getDocument()!.layers.some((layer) => layer.id === resultId)).toBe(false);
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(true);
+ await expectLayerCacheExact(harness.engine, 'upper', upperCache);
+ await expectLayerCacheExact(harness.engine, 'below', belowCache);
+ harness.engine.redo();
+ expect(harness.engine.getDocument()).toEqual(committedDocument);
+ harness.engine.dispose();
+ });
+
+ it('masked extraction redo cache-draw failure leaves sources, selection, and history exact and retryable', async () => {
+ const pair = twoPaintDoc();
+ const mask: CanvasInpaintMaskLayerContract = {
+ ...maskLayer('extract-replay-mask'),
+ mask: {
+ bitmap: { height: 20, imageName: 'extract-replay-mask-bitmap', width: 20 },
+ fill: { color: '#e07575', style: 'diagonal' },
+ offset: { x: 15, y: 25 },
+ },
+ };
+ const document = {
+ ...pair,
+ layers: [mask, ...pair.layers, sentinelLayer()],
+ selectedLayerId: 'selection-sentinel',
+ };
+ const harness = createFaultHarness(document);
+ const maskCache = await snapshotLayerCache(harness.engine, mask.id);
+ const upperCache = await snapshotLayerCache(harness.engine, 'upper');
+ const belowCache = await snapshotLayerCache(harness.engine, 'below');
+ const originalDocument = harness.engine.getDocument()!;
+ const extracted = await harness.engine.extractMaskedArea(mask.id);
+ expect(extracted.status).toBe('extracted');
+ if (extracted.status !== 'extracted') {
+ throw new Error('expected masked extraction');
+ }
+ const committedDocument = structuredClone(harness.engine.getDocument()!);
+ harness.engine.undo();
+ const restoredDocument = harness.engine.getDocument()!;
+ harness.faults.armDraw(0);
+
+ expect(() => harness.engine.redo()).toThrow('structural cache draw failed');
+
+ expect(harness.engine.getDocument()).toBe(restoredDocument);
+ expect(harness.engine.getDocument()).toEqual(originalDocument);
+ expect(harness.engine.getDocument()!.layers.some((layer) => layer.id === extracted.layerId)).toBe(false);
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(true);
+ await expectLayerCacheExact(harness.engine, mask.id, maskCache);
+ await expectLayerCacheExact(harness.engine, 'upper', upperCache);
+ await expectLayerCacheExact(harness.engine, 'below', belowCache);
+ harness.engine.redo();
+ expect(harness.engine.getDocument()).toEqual(committedDocument);
+ harness.engine.dispose();
+ });
+
+ it('copyLayerToRaster undo restores the exact prior selection', async () => {
+ const source = rasterLayer('selection-copy-source');
+ const document = { ...makeDoc(), layers: [source, sentinelLayer()], selectedLayerId: 'selection-sentinel' };
+ const harness = createFaultHarness(document);
+ const originalDocument = harness.engine.getDocument()!;
+ const copiedId = await harness.engine.copyLayerToRaster(source.id);
+ expect(copiedId).not.toBeNull();
+
+ harness.engine.undo();
+
+ expect(harness.engine.getDocument()).toEqual(originalDocument);
+ expect(harness.engine.getDocument()!.selectedLayerId).toBe('selection-sentinel');
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(true);
+ harness.engine.dispose();
+ });
+
+ it('keeps a reducer-rejected copy undo retryable until its prior selection exists again', async () => {
+ const source = rasterLayer('rejected-undo-source');
+ const sentinel = sentinelLayer();
+ const document = { ...makeDoc(), layers: [source, sentinel], selectedLayerId: sentinel.id };
+ const harness = createFaultHarness(document);
+ const copiedId = await harness.engine.copyLayerToRaster(source.id);
+ expect(copiedId).not.toBeNull();
+
+ harness.store.dispatch({ ids: [sentinel.id], type: 'removeCanvasLayers' });
+ expect(harness.engine.getDocument()!.layers.some((layer) => layer.id === copiedId)).toBe(true);
+
+ expect(() => harness.engine.undo()).toThrow('Canvas document mutation was rejected');
+ expect(harness.engine.getDocument()!.layers.some((layer) => layer.id === copiedId)).toBe(true);
+ expect(harness.engine.stores.canUndo.get()).toBe(true);
+ expect(harness.engine.stores.canRedo.get()).toBe(false);
+
+ harness.store.dispatch({ layer: sentinel, type: 'addCanvasLayer' });
+ expect(() => harness.engine.undo()).not.toThrow();
+ expect(harness.engine.getDocument()!.layers.some((layer) => layer.id === copiedId)).toBe(false);
+ expect(harness.engine.getDocument()!.selectedLayerId).toBe(sentinel.id);
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ expect(harness.engine.stores.canRedo.get()).toBe(true);
+ harness.engine.dispose();
+ });
+
+ it('rejects prepared structural publication before dispatch when this engine project is inactive', () => {
+ const source = rasterLayer('inactive-source');
+ const document = { ...makeDoc(), layers: [source], selectedLayerId: source.id };
+ const harness = createFaultHarness(document);
+ const liveSource = harness.engine.getDocument()!.layers[0]!;
+ const copy = { ...structuredClone(source), id: 'inactive-copy' };
+ harness.store.dispatch({ type: 'createProject' });
+ const otherProjectId = harness.store.getState().activeProjectId;
+ const otherBefore = structuredClone(
+ harness.store.getState().projects.find((project) => project.id === otherProjectId)!.canvas.document
+ );
+ (harness.store.dispatch as Mock).mockClear();
+
+ expect(() => harness.engine.commitLayerCopy('Copy layer', liveSource.id, copy, 0)).toThrow(
+ 'Canvas project is not active'
+ );
+
+ expect(harness.store.dispatch).not.toHaveBeenCalled();
+ expect(harness.store.getState().projects.find((project) => project.id === otherProjectId)!.canvas.document).toEqual(
+ otherBefore
+ );
+ expect(harness.engine.getDocument()).toEqual(document);
+ expect(harness.engine.stores.canUndo.get()).toBe(false);
+ harness.engine.dispose();
+ });
+
+ it('crop generation-cancels a deferred pre-crop upload before publishing the new paint incarnation', async () => {
+ const source: CanvasRasterLayerContractV2 = {
+ ...(rasterLayer('crop-persistence-source') as CanvasRasterLayerContractV2),
+ source: {
+ bitmap: { height: 10, imageName: 'before-crop-paint', width: 10 },
+ offset: { x: 0, y: 0 },
+ type: 'paint',
+ },
+ };
+ const document: CanvasDocumentContractV2 = {
+ ...makeDoc(),
+ bbox: { height: 7, width: 6, x: 2, y: 3 },
+ layers: [source, sentinelLayer()],
+ selectedLayerId: 'selection-sentinel',
+ };
+ const reducer = createReducerBackedStore(document);
+ const staleUpload = createDeferred<{ height: number; imageName: string; width: number }>();
+ let uploadCount = 0;
+ const uploadImage = vi.fn(() => {
+ uploadCount += 1;
+ return uploadCount === 1
+ ? staleUpload.promise
+ : Promise.resolve({ height: 7, imageName: 'cropped-paint', width: 6 });
+ });
+ let placed: { offset: { x: number; y: number }; surface: RasterSurface } | null = null;
+ const bitmapStore = createBitmapStore({
+ debounceMs: 1500,
+ dispatch: reducer.store.dispatch,
+ encodeSurface: (surface) =>
+ Promise.resolve(new Blob([`${surface.width}x${surface.height}`], { type: 'image/png' })),
+ getLayerSource: (layerId) => {
+ const layer = reducer.store
+ .getState()
+ .projects.find((project) => project.id === reducer.projectId)
+ ?.canvas.document.layers.find((candidate) => candidate.id === layerId);
+ return layer?.type === 'raster' || layer?.type === 'control' ? layer.source : null;
+ },
+ getLayerSurface: () => placed,
+ hashBlob: (blob) => blob.text(),
+ maxUploadAttempts: 1,
+ retryDelaysMs: [],
+ sleep: () => Promise.resolve(),
+ uploadImage,
+ });
+ const discardLayer = vi.spyOn(bitmapStore, 'discardLayer');
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore,
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: reducer.projectId,
+ store: reducer.store,
+ });
+ const before = await snapshotLayerCache(engine, source.id);
+ placed = { offset: { x: before.rect.x, y: before.rect.y }, surface: before.surface };
+ bitmapStore.markLayerDirty(source.id);
+ const barrier = bitmapStore.flushPendingUploads();
+ for (let tick = 0; tick < 50 && uploadImage.mock.calls.length === 0; tick += 1) {
+ await Promise.resolve();
+ }
+ expect(uploadImage).toHaveBeenCalledOnce();
+
+ await expect(engine.cropLayerToBbox(source.id)).resolves.toEqual({ status: 'cropped' });
+ const croppedCache = await snapshotLayerCache(engine, source.id);
+ placed = {
+ offset: { x: croppedCache.rect.x, y: croppedCache.rect.y },
+ surface: croppedCache.surface,
+ };
+ staleUpload.resolve({ height: 10, imageName: 'stale-pre-crop-paint', width: 10 });
+ await barrier;
+
+ const bitmapUpdates = (reducer.store.dispatch as Mock).mock.calls
+ .map((call) => call[0] as WorkbenchAction)
+ .filter((action) => action.type === 'updateCanvasLayerSource' && action.id === source.id);
+ expect(discardLayer).toHaveBeenCalledWith(source.id);
+ expect(bitmapUpdates).toHaveLength(1);
+ expect(bitmapUpdates).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ source: { bitmap: expect.objectContaining({ imageName: 'stale-pre-crop-paint' }) } }),
+ ])
+ );
+ expect(bitmapUpdates[0]).toMatchObject({
+ source: {
+ bitmap: { height: 7, imageName: 'cropped-paint', width: 6 },
+ offset: { x: 2, y: 3 },
+ type: 'paint',
+ },
+ });
+ expect(engine.getDocument()!.selectedLayerId).toBe('selection-sentinel');
+ expect(engine.getDocument()!.layers.find((layer) => layer.id === source.id)).toMatchObject({
+ source: {
+ bitmap: { height: 7, imageName: 'cropped-paint', width: 6 },
+ offset: { x: 2, y: 3 },
+ type: 'paint',
+ },
+ });
+ expect(engine.stores.canUndo.get()).toBe(true);
+ await expectLayerCacheExact(engine, source.id, croppedCache);
+ engine.dispose();
+ });
+});
+
describe('mergeVisibleRasterLayers', () => {
/** [upper raster, mask, lower raster] — the interleaved case round 1 no-oped. */
const interleavedDoc = (): CanvasDocumentContractV2 => {
@@ -4922,12 +5602,32 @@ describe('commitRasterFilterResult', () => {
it('passes the exact cancellation signal into durable-image resolution', async () => {
const resolver = vi.fn((_imageName: string, _signal?: AbortSignal) => Promise.resolve(new Blob()));
- const harness = await createGuardHarness(resolver);
+ const layer = filterLayer();
+ const reducer = createReducerBackedStore(filterDoc([layer]));
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: resolver,
+ projectId: reducer.projectId,
+ store: reducer.store,
+ });
+ const exported = await engine.exportLayerPixels(layer.id);
+ if (exported.status !== 'ok') {
+ throw new Error('expected a filterable export');
+ }
const controller = new AbortController();
- await expect(harness.commit(controller.signal)).resolves.toMatchObject({ status: 'committed' });
+ await expect(
+ engine.commitRasterFilterResult({
+ guard: exported.guard,
+ image: durableImage,
+ mode: 'replace',
+ rect: exported.rect,
+ signal: controller.signal,
+ })
+ ).resolves.toMatchObject({ status: 'committed' });
expect(resolver).toHaveBeenCalledWith(durableImage.imageName, controller.signal);
- harness.engine.dispose();
+ engine.dispose();
});
it('maps an abort rejection from durable-image resolution to aborted without mutation', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index db25e23b0e..52f9858967 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1609,12 +1609,32 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
}
+ const publishSnapshot = (
+ contract: CanvasLayerContract,
+ prepared: ReturnType<LayerCacheStore['prepareReplacement']>
+ ): void => {
+ dispatchPreparedMutation(
+ { layer: contract, layerId, type: 'replaceCanvasLayer' },
+ () => getReducerDocument()?.layers.find((candidate) => candidate.id === layerId) === contract,
+ () => mirror.getDocument()?.layers.find((candidate) => candidate.id === layerId) === contract
+ );
+ // A crop creates a new live-paint incarnation for the same layer id.
+ // Invalidate any pending or in-flight upload from the outgoing pixels
+ // before publishing and dirtying the replacement cache.
+ try {
+ bitmapStore.discardLayer(layerId);
+ } catch {
+ // Persistence bookkeeping is ancillary after reducer acceptance.
+ }
+ installGeneratedPaintCache(prepared);
+ };
const applySnapshot = (contract: CanvasLayerContract, snapshot: { pixels: RasterSurface; rect: Rect }): void => {
- store.dispatch({ layer: contract, layerId, type: 'replaceCanvasLayer' });
- seedGeneratedPaintCache(layerId, snapshot.rect, snapshot.pixels);
+ const prepared = prepareGeneratedPaintCache(layerId, snapshot.rect, snapshot.pixels);
+ publishSnapshot(contract, prepared);
};
const afterPixels = { pixels: cropped, rect: cropRect };
- applySnapshot(after, afterPixels);
+ const preparedAfter = prepareGeneratedPaintCache(layerId, afterPixels.rect, afterPixels.pixels);
+ publishSnapshot(after, preparedAfter);
history.push({
bytes:
beforePixels.rect.width * beforePixels.rect.height * 4 +
@@ -1622,6 +1642,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
256,
label: 'Crop layer to bbox',
redo: () => applySnapshot(after, afterPixels),
+ replayFailureAtomic: true,
undo: () => applySnapshot(before, beforePixels),
});
return { status: 'cropped' };
@@ -1666,16 +1687,46 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'raster',
};
+ const selectedLayerId = liveDocument.selectedLayerId;
const apply = (): void => {
- store.dispatch({ index: sourceIndex, layer, type: 'addCanvasLayer' });
- seedGeneratedPaintCache(newId, baked.rect, baked.surface);
+ const prepared = prepareGeneratedPaintCache(newId, baked.rect, baked.surface);
+ dispatchPreparedMutation(
+ {
+ add: { index: sourceIndex, layer },
+ enabledUpdates: [],
+ selectedLayerId: newId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ getReducerDocument()?.selectedLayerId === newId &&
+ getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,
+ () =>
+ mirror.getDocument()?.selectedLayerId === newId &&
+ mirror.getDocument()?.layers.some((candidate) => candidate === layer) === true
+ );
+ installGeneratedPaintCache(prepared);
};
apply();
history.push({
bytes: baked.rect.width * baked.rect.height * 4 + 256,
label: 'Copy layer to raster',
redo: apply,
- undo: () => store.dispatch({ ids: [newId], type: 'removeCanvasLayers' }),
+ replayFailureAtomic: true,
+ undo: () =>
+ dispatchPreparedMutation(
+ {
+ enabledUpdates: [],
+ removeIds: [newId],
+ selectedLayerId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ getReducerDocument()?.selectedLayerId === selectedLayerId &&
+ getReducerDocument()?.layers.some((candidate) => candidate.id === newId) === false,
+ () =>
+ mirror.getDocument()?.selectedLayerId === selectedLayerId &&
+ mirror.getDocument()?.layers.some((candidate) => candidate.id === newId) === false
+ ),
});
return newId;
};
@@ -2607,11 +2658,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
};
- const seedGeneratedPaintCache = (layerId: string, rect: Rect, pixels: RasterSurface, persist = true): void => {
- const prepared = prepareGeneratedPaintCache(layerId, rect, pixels);
- installGeneratedPaintCache(prepared, persist);
- };
-
const getReducerDocument = (): CanvasDocumentContractV2 | null =>
store.getState().projects.find((project) => project.id === projectId)?.canvas.document ?? null;
@@ -2620,6 +2666,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
isApplied: () => boolean,
isMirrored: () => boolean
): void => {
+ if (store.getState().activeProjectId !== projectId) {
+ throw new Error('Canvas project is not active');
+ }
try {
store.dispatch(action);
} catch (error) {
@@ -2644,9 +2693,39 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (!isMirrored()) {
throw error;
}
+ return;
+ }
+
+ // A reducer may reject a guarded transaction by returning the unchanged
+ // state without throwing. Do not install its prepared cache or consume a
+ // failure-atomic history entry unless the authoritative postcondition
+ // actually landed.
+ if (!isApplied()) {
+ throw new Error('Canvas document mutation was rejected');
+ }
+ if (!isMirrored()) {
+ try {
+ mirror.refresh();
+ } catch (refreshError) {
+ if (!isMirrored()) {
+ throw refreshError;
+ }
+ }
+ if (!isMirrored()) {
+ throw new Error('Canvas document mutation was not mirrored');
+ }
}
};
+ /** Conversion reducers clone contracts, so their publication postcondition compares by value. */
+ const documentHasLayerContract = (
+ document: CanvasDocumentContractV2 | null,
+ expected: CanvasLayerContract
+ ): boolean => {
+ const current = document?.layers.find((candidate) => candidate.id === expected.id);
+ return current !== undefined && isDeeplyEqual(current, expected);
+ };
+
const captureLayerCache = (
layer: CanvasLayerContract,
doc: CanvasDocumentContractV2
@@ -2685,10 +2764,25 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (captured === 'not-ready') {
return false;
}
+ const selectedLayerId = doc.selectedLayerId;
const apply = (): void => {
- store.dispatch({ index, layer, type: 'addCanvasLayer' });
- if (captured) {
- seedGeneratedPaintCache(layer.id, captured.rect, captured.pixels, layerNeedsPixelPersistence(layer));
+ const prepared = captured ? prepareGeneratedPaintCache(layer.id, captured.rect, captured.pixels) : null;
+ dispatchPreparedMutation(
+ {
+ add: { index, layer },
+ enabledUpdates: [],
+ selectedLayerId: layer.id,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ getReducerDocument()?.selectedLayerId === layer.id &&
+ getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,
+ () =>
+ mirror.getDocument()?.selectedLayerId === layer.id &&
+ mirror.getDocument()?.layers.some((candidate) => candidate === layer) === true
+ );
+ if (prepared) {
+ installGeneratedPaintCache(prepared, layerNeedsPixelPersistence(layer));
}
};
apply();
@@ -2696,7 +2790,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
bytes: captured ? captured.rect.width * captured.rect.height * 4 + 256 : 256,
label,
redo: apply,
- undo: () => store.dispatch({ ids: [layer.id], type: 'removeCanvasLayers' }),
+ replayFailureAtomic: true,
+ undo: () =>
+ dispatchPreparedMutation(
+ {
+ enabledUpdates: [],
+ removeIds: [layer.id],
+ selectedLayerId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ getReducerDocument()?.selectedLayerId === selectedLayerId &&
+ getReducerDocument()?.layers.some((candidate) => candidate.id === layer.id) === false,
+ () =>
+ mirror.getDocument()?.selectedLayerId === selectedLayerId &&
+ mirror.getDocument()?.layers.some((candidate) => candidate.id === layer.id) === false
+ ),
});
return true;
};
@@ -2726,9 +2835,21 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return false;
}
const apply = (layer: CanvasLayerContract): void => {
- store.dispatch({ id: layer.id, layer, targetType: layer.type, type: 'convertCanvasLayer' });
- if (captured) {
- seedGeneratedPaintCache(layer.id, captured.rect, captured.pixels, layerNeedsPixelPersistence(layer));
+ const prepared = captured ? prepareGeneratedPaintCache(layer.id, captured.rect, captured.pixels) : null;
+ dispatchPreparedMutation(
+ { id: layer.id, layer, targetType: layer.type, type: 'convertCanvasLayer' },
+ () => documentHasLayerContract(getReducerDocument(), layer),
+ () => documentHasLayerContract(mirror.getDocument(), layer)
+ );
+ // Conversion republishes a cache incarnation under the same layer id.
+ // Cancel persistence from the outgoing contract before exposing it.
+ try {
+ bitmapStore.discardLayer(layer.id);
+ } catch {
+ // Persistence bookkeeping is ancillary after reducer acceptance.
+ }
+ if (prepared) {
+ installGeneratedPaintCache(prepared, layerNeedsPixelPersistence(layer));
}
};
const before = structuredClone(current);
@@ -2737,6 +2858,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
bytes: captured ? captured.rect.width * captured.rect.height * 4 + 256 : 256,
label,
redo: () => apply(after),
+ replayFailureAtomic: true,
undo: () => apply(before),
});
return true;
@@ -3381,10 +3503,41 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
{ id: below.id, isEnabled: below.isEnabled },
];
const disabled = originalEnabled.map(({ id }) => ({ id, isEnabled: false }));
+ const selectedLayerId = liveDocument.selectedLayerId;
+ const hasEnabledState = (
+ document: CanvasDocumentContractV2 | null,
+ updates: readonly { id: string; isEnabled: boolean }[]
+ ): boolean =>
+ updates.every(
+ (update) => document?.layers.find((candidate) => candidate.id === update.id)?.isEnabled === update.isEnabled
+ );
const apply = (): void => {
- store.dispatch({ index: liveUpperIndex, layer: resultLayer, type: 'addCanvasLayer' });
- seedGeneratedPaintCache(resultId, resultRect, resultPixels);
- store.dispatch({ type: 'setCanvasLayersEnabled', updates: disabled });
+ const prepared = prepareGeneratedPaintCache(resultId, resultRect, resultPixels);
+ dispatchPreparedMutation(
+ {
+ add: { index: liveUpperIndex, layer: resultLayer },
+ enabledUpdates: disabled,
+ selectedLayerId: resultId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () => {
+ const document = getReducerDocument();
+ return (
+ document?.selectedLayerId === resultId &&
+ document.layers.some((candidate) => candidate === resultLayer) &&
+ hasEnabledState(document, disabled)
+ );
+ },
+ () => {
+ const document = mirror.getDocument();
+ return (
+ document?.selectedLayerId === resultId &&
+ document.layers.some((candidate) => candidate === resultLayer) &&
+ hasEnabledState(document, disabled)
+ );
+ }
+ );
+ installGeneratedPaintCache(prepared);
};
apply();
@@ -3392,10 +3545,32 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
bytes: resultRect.width * resultRect.height * 4 + 256,
label: `Boolean ${operation}`,
redo: apply,
- undo: () => {
- store.dispatch({ ids: [resultId], type: 'removeCanvasLayers' });
- store.dispatch({ type: 'setCanvasLayersEnabled', updates: originalEnabled });
- },
+ replayFailureAtomic: true,
+ undo: () =>
+ dispatchPreparedMutation(
+ {
+ enabledUpdates: originalEnabled,
+ removeIds: [resultId],
+ selectedLayerId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () => {
+ const document = getReducerDocument();
+ return (
+ document?.selectedLayerId === selectedLayerId &&
+ document.layers.some((candidate) => candidate.id === resultId) === false &&
+ hasEnabledState(document, originalEnabled)
+ );
+ },
+ () => {
+ const document = mirror.getDocument();
+ return (
+ document?.selectedLayerId === selectedLayerId &&
+ document.layers.some((candidate) => candidate.id === resultId) === false &&
+ hasEnabledState(document, originalEnabled)
+ );
+ }
+ ),
});
return 'merged';
};
@@ -3520,9 +3695,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'raster',
};
+ const selectedLayerId = liveDocument.selectedLayerId;
const apply = (): void => {
- store.dispatch({ index: maskIndex, layer: resultLayer, type: 'addCanvasLayer' });
- seedGeneratedPaintCache(resultId, resultRect, resultPixels);
+ const prepared = prepareGeneratedPaintCache(resultId, resultRect, resultPixels);
+ dispatchPreparedMutation(
+ {
+ add: { index: maskIndex, layer: resultLayer },
+ enabledUpdates: [],
+ selectedLayerId: resultId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ getReducerDocument()?.selectedLayerId === resultId &&
+ getReducerDocument()?.layers.some((candidate) => candidate === resultLayer) === true,
+ () =>
+ mirror.getDocument()?.selectedLayerId === resultId &&
+ mirror.getDocument()?.layers.some((candidate) => candidate === resultLayer) === true
+ );
+ installGeneratedPaintCache(prepared);
};
apply();
@@ -3530,7 +3720,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
bytes: resultRect.width * resultRect.height * 4 + 256,
label: 'Extract masked area',
redo: apply,
- undo: () => store.dispatch({ ids: [resultId], type: 'removeCanvasLayers' }),
+ replayFailureAtomic: true,
+ undo: () =>
+ dispatchPreparedMutation(
+ {
+ enabledUpdates: [],
+ removeIds: [resultId],
+ selectedLayerId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ getReducerDocument()?.selectedLayerId === selectedLayerId &&
+ getReducerDocument()?.layers.some((candidate) => candidate.id === resultId) === false,
+ () =>
+ mirror.getDocument()?.selectedLayerId === selectedLayerId &&
+ mirror.getDocument()?.layers.some((candidate) => candidate.id === resultId) === false
+ ),
});
return { layerId: resultId, status: 'extracted' };
};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index b7950a738b..846a3901c1 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -18,7 +18,7 @@ import { getCanvasStagingSlots } from './canvasStagingView';
import { MAX_PROMPT_HISTORY } from './generation/promptHistory';
import { DEFAULT_PROJECT_SETTINGS } from './settings/store';
import { getProjectWidgetValues } from './widgetState';
-import { createInitialWorkbenchState, nextLayerName, workbenchReducer } from './workbenchState';
+import { createInitialWorkbenchState, nextLayerName, type WorkbenchAction, workbenchReducer } from './workbenchState';
const model: MainModelConfig = {
base: 'sdxl',
@@ -1863,6 +1863,118 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
expect(getCanvas(next).document).toBe(before);
});
+ it('applies and reverses a layer stack mutation atomically while preserving unrelated layer identity', () => {
+ const upper = createRasterLayer('upper');
+ const below = createRasterLayer('below');
+ const unrelated = { ...createRasterLayer('unrelated'), isEnabled: false };
+ const result = createRasterLayer('result');
+ const initial = workbenchReducer(withCanvasLayers(createInitialWorkbenchState(), [unrelated, upper, below]), {
+ id: unrelated.id,
+ type: 'setCanvasSelectedLayer',
+ });
+ const unrelatedBefore = getCanvas(initial).document.layers[0];
+
+ const applied = workbenchReducer(initial, {
+ add: { index: 1, layer: result },
+ enabledUpdates: [
+ { id: upper.id, isEnabled: false },
+ { id: below.id, isEnabled: false },
+ ],
+ selectedLayerId: result.id,
+ type: 'applyCanvasLayerStackMutation',
+ });
+
+ expect(applied).toBeDefined();
+ expect(getCanvas(applied).document.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([
+ ['unrelated', false],
+ ['result', true],
+ ['upper', false],
+ ['below', false],
+ ]);
+ expect(getCanvas(applied).document.selectedLayerId).toBe(result.id);
+ expect(getCanvas(applied).document.layers[0]).toBe(unrelatedBefore);
+
+ const reverted = workbenchReducer(applied, {
+ enabledUpdates: [
+ { id: upper.id, isEnabled: true },
+ { id: below.id, isEnabled: true },
+ ],
+ removeIds: [result.id],
+ selectedLayerId: unrelated.id,
+ type: 'applyCanvasLayerStackMutation',
+ });
+
+ expect(getCanvas(reverted).document.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([
+ ['unrelated', false],
+ ['upper', true],
+ ['below', true],
+ ]);
+ expect(getCanvas(reverted).document.selectedLayerId).toBe(unrelated.id);
+ expect(getCanvas(reverted).document.layers[0]).toBe(unrelatedBefore);
+ });
+
+ it('rejects an invalid layer stack mutation without applying any valid fields', () => {
+ const initial = workbenchReducer(
+ withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]),
+ { id: 'b', type: 'setCanvasSelectedLayer' }
+ );
+ const invalidActions = [
+ {
+ add: { index: 0, layer: createRasterLayer('a') },
+ enabledUpdates: [{ id: 'b', isEnabled: false }],
+ selectedLayerId: 'b',
+ type: 'applyCanvasLayerStackMutation',
+ },
+ {
+ enabledUpdates: [{ id: 'a', isEnabled: false }],
+ removeIds: ['missing'],
+ selectedLayerId: 'b',
+ type: 'applyCanvasLayerStackMutation',
+ },
+ {
+ enabledUpdates: [{ id: 'missing', isEnabled: false }],
+ selectedLayerId: 'b',
+ type: 'applyCanvasLayerStackMutation',
+ },
+ {
+ enabledUpdates: [],
+ selectedLayerId: 'missing',
+ type: 'applyCanvasLayerStackMutation',
+ },
+ {
+ enabledUpdates: [{ id: 'a', isEnabled: false }],
+ removeIds: ['a'],
+ selectedLayerId: 'b',
+ type: 'applyCanvasLayerStackMutation',
+ },
+ {
+ add: { index: 0, layer: createRasterLayer('c') },
+ enabledUpdates: [],
+ removeIds: ['a'],
+ selectedLayerId: 'b',
+ type: 'applyCanvasLayerStackMutation',
+ },
+ ] satisfies WorkbenchAction[];
+
+ for (const action of invalidActions) {
+ expect(workbenchReducer(initial, action)).toBe(initial);
+ }
+ });
+
+ it('preserves the layers array for a selection-only layer stack mutation', () => {
+ const initial = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);
+ const before = getCanvas(initial).document.layers;
+
+ const next = workbenchReducer(initial, {
+ enabledUpdates: [],
+ selectedLayerId: 'b',
+ type: 'applyCanvasLayerStackMutation',
+ });
+
+ expect(getCanvas(next).document.layers).toBe(before);
+ expect(getCanvas(next).document.selectedLayerId).toBe('b');
+ });
+
it('duplicates a layer above its source with a copy name and selects the duplicate', () => {
let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index fc06592d17..dc682eeb0b 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -237,6 +237,13 @@ type WorkbenchAction =
| { type: 'acceptStagedImage' }
| { type: 'clearCanvasStaging' }
| { type: 'addCanvasLayer'; layer: CanvasLayerContract; index?: number }
+ | {
+ type: 'applyCanvasLayerStackMutation';
+ add?: { index: number; layer: CanvasLayerContract };
+ removeIds?: readonly string[];
+ enabledUpdates: readonly { id: string; isEnabled: boolean }[];
+ selectedLayerId: string | null;
+ }
| { type: 'removeCanvasLayers'; ids: string[] }
| { type: 'duplicateCanvasLayer'; sourceId: string; newId: string }
| { type: 'reorderCanvasLayers'; orderedIds: string[] }
@@ -809,6 +816,67 @@ const setCanvasLayersEnabledInDocument = (
return changed ? { ...document, layers } : document;
};
+const applyCanvasLayerStackMutationToDocument = (
+ document: CanvasDocumentContractV2,
+ action: Extract<WorkbenchAction, { type: 'applyCanvasLayerStackMutation' }>
+): CanvasDocumentContractV2 => {
+ const currentIds = new Set(document.layers.map((layer) => layer.id));
+ if (action.add && ((action.removeIds?.length ?? 0) > 0 || currentIds.has(action.add.layer.id))) {
+ return document;
+ }
+
+ const removeIds = new Set(action.removeIds ?? []);
+ if ([...removeIds].some((id) => !currentIds.has(id))) {
+ return document;
+ }
+
+ const projectedIds = new Set(currentIds);
+ for (const id of removeIds) {
+ projectedIds.delete(id);
+ }
+ if (action.add) {
+ projectedIds.add(action.add.layer.id);
+ }
+ if (
+ action.enabledUpdates.some((update) => !projectedIds.has(update.id)) ||
+ (action.selectedLayerId !== null && !projectedIds.has(action.selectedLayerId))
+ ) {
+ return document;
+ }
+
+ let layers = document.layers;
+ let changed = false;
+ if (action.add) {
+ const insertIndex = Math.min(Math.max(0, Math.round(action.add.index)), layers.length);
+ layers = [...layers.slice(0, insertIndex), action.add.layer, ...layers.slice(insertIndex)];
+ changed = true;
+ }
+ if (removeIds.size > 0) {
+ layers = layers.filter((layer) => !removeIds.has(layer.id));
+ changed = true;
+ }
+
+ const enabledById = new Map(action.enabledUpdates.map((update) => [update.id, update.isEnabled]));
+ let enabledChanged = false;
+ const updatedLayers = layers.map((layer) => {
+ const isEnabled = enabledById.get(layer.id);
+ if (isEnabled === undefined || isEnabled === layer.isEnabled) {
+ return layer;
+ }
+ enabledChanged = true;
+ return { ...layer, isEnabled };
+ });
+ if (enabledChanged) {
+ layers = updatedLayers;
+ changed = true;
+ }
+
+ if (document.selectedLayerId !== action.selectedLayerId) {
+ changed = true;
+ }
+ return changed ? { ...document, layers, selectedLayerId: action.selectedLayerId } : document;
+};
+
/** After removing the selected layer, selects the nearest surviving layer below it, else above it, else null. */
const selectNearestRemainingLayerId = (
previousLayers: CanvasLayers,
@@ -3161,6 +3229,11 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
updateCanvasDocument(project, (document) => addCanvasLayerToDocument(document, action.layer, action.index))
);
}
+ case 'applyCanvasLayerStackMutation': {
+ return updateActiveProject(state, (project) =>
+ updateCanvasDocument(project, (document) => applyCanvasLayerStackMutationToDocument(document, action))
+ );
+ }
case 'removeCanvasLayers': {
return updateActiveProject(state, (project) =>
updateCanvasDocument(project, (document) => removeCanvasLayersFromDocument(document, action.ids))