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 control paint commits failure atomic

joshistoast5bce614099d2
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
index dc0ec9903c..50c94f0d8a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts
@@ -452,6 +452,35 @@ describe('createBitmapStore', () => {
h.store.dispose();
});
+ it('ignores a stale suspension release after reset reuses the same layer id', async () => {
+ const h = createHarness();
+ const releaseOldDocument = h.store.suspendLayer(LAYER);
+
+ h.store.reset();
+
+ const releaseNewDocument = h.store.suspendLayer(LAYER);
+ h.store.markLayerDirty(LAYER);
+ const barrier = h.store.flushPendingUploads();
+ let settled = false;
+ void barrier.then(() => {
+ settled = true;
+ });
+
+ releaseOldDocument();
+ await vi.advanceTimersByTimeAsync(3000);
+ await Promise.resolve();
+
+ expect(settled).toBe(false);
+ expect(h.encodeSurface).not.toHaveBeenCalled();
+
+ releaseNewDocument();
+ await barrier;
+
+ expect(h.encodeSurface).toHaveBeenCalledOnce();
+ expect(h.dispatch).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
it.each(['reset', 'dispose'] as const)('%s settles barriers waiting on suspended dirty work', async (ending) => {
const h = createHarness();
h.store.markLayerDirty(LAYER);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
index 92bd2d67c6..7e6dc81043 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -217,13 +217,13 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
* tombstones for the lifetime of the engine.
*/
const layerGenerations = new Map<string, number>();
- /** Active nested persistence-suspension lease count per layer. */
- const suspensionCounts = new Map<string, number>();
+ /** Active nested persistence-suspension generation per layer. */
+ const suspensions = new Map<string, { count: number; token: symbol }>();
/** Barriers waiting for a suspended dirty layer to resume or be reset/disposed. */
const suspensionWaiters = new Set<() => void>();
let disposed = false;
- const isSuspended = (layerId: string): boolean => (suspensionCounts.get(layerId) ?? 0) > 0;
+ const isSuspended = (layerId: string): boolean => (suspensions.get(layerId)?.count ?? 0) > 0;
const notifySuspensionWaiters = (): void => {
const waiters = [...suspensionWaiters];
suspensionWaiters.clear();
@@ -501,8 +501,10 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
if (disposed) {
return () => undefined;
}
- const count = suspensionCounts.get(layerId) ?? 0;
- suspensionCounts.set(layerId, count + 1);
+ const currentSuspension = suspensions.get(layerId);
+ const count = currentSuspension?.count ?? 0;
+ const token = currentSuspension?.token ?? Symbol(layerId);
+ suspensions.set(layerId, { count: count + 1, token });
if (count === 0) {
const hadPendingWork = dirty.has(layerId) || debounceTimers.has(layerId) || inFlight.has(layerId);
clearTimer(layerId);
@@ -521,14 +523,17 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
return;
}
released = true;
- const current = suspensionCounts.get(layerId) ?? 0;
- if (current <= 1) {
- suspensionCounts.delete(layerId);
+ const current = suspensions.get(layerId);
+ if (!current || current.token !== token) {
+ return;
+ }
+ if (current.count <= 1) {
+ suspensions.delete(layerId);
if (dirty.has(layerId) && !disposed) {
scheduleFlush(layerId);
}
} else {
- suspensionCounts.set(layerId, current - 1);
+ suspensions.set(layerId, { count: current.count - 1, token });
}
notifySuspensionWaiters();
};
@@ -609,7 +614,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
debounceTimers.clear();
dirty.clear();
dirtyReason.clear();
- suspensionCounts.clear();
+ suspensions.clear();
notifySuspensionWaiters();
// The self-echo map is per-(old)document; a reused layer id in the new
// document must not inherit it. `hashToImage` is content-addressed and kept.
@@ -624,7 +629,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
debounceTimers.clear();
dirty.clear();
dirtyReason.clear();
- suspensionCounts.clear();
+ suspensions.clear();
notifySuspensionWaiters();
inFlight.clear();
hashToImage.clear();
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 1d3dee4717..5771db5dc2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -1,3 +1,5 @@
+import type * as ImagePatchModule from '@workbench/canvas-engine/history/imagePatch';
+import type * as LayerSnapshotModule from '@workbench/canvas-engine/history/layerSnapshot';
import type * as AdjustedSurfaceCacheModule from '@workbench/canvas-engine/render/adjustedSurfaceCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type {
@@ -35,6 +37,12 @@ import { createCanvasEngine } from './engine';
// factory wraps the real implementation, preserving all behaviour.
const adjustedSurfaceCacheDeletes = vi.hoisted(() => [] as string[]);
const adjustedSurfaceCacheGets = vi.hoisted(() => [] as string[]);
+const adjustedSurfaceCacheDeleteFaults = vi.hoisted(() => new Set<string>());
+const historyPreparationFaults = vi.hoisted(() => ({
+ imagePatch: false,
+ imagePatchBefore: null as ImageData | null,
+ layerSnapshot: false,
+}));
vi.mock('@workbench/canvas-engine/render/adjustedSurfaceCache', async (importOriginal) => {
const actual = await importOriginal<typeof AdjustedSurfaceCacheModule>();
@@ -46,6 +54,9 @@ vi.mock('@workbench/canvas-engine/render/adjustedSurfaceCache', async (importOri
...cache,
delete: (layerId: string) => {
adjustedSurfaceCacheDeletes.push(layerId);
+ if (adjustedSurfaceCacheDeleteFaults.has(layerId)) {
+ throw new Error('adjusted surface cache delete failed');
+ }
cache.delete(layerId);
},
get: (...args: Parameters<typeof cache.get>) => {
@@ -57,6 +68,33 @@ vi.mock('@workbench/canvas-engine/render/adjustedSurfaceCache', async (importOri
};
});
+vi.mock('./history/imagePatch', async (importOriginal) => {
+ const actual = await importOriginal<typeof ImagePatchModule>();
+ return {
+ ...actual,
+ createImagePatchEntry: (...args: Parameters<typeof actual.createImagePatchEntry>) => {
+ historyPreparationFaults.imagePatchBefore = args[0].before;
+ if (historyPreparationFaults.imagePatch) {
+ throw new Error('image patch preparation failed');
+ }
+ return actual.createImagePatchEntry(...args);
+ },
+ };
+});
+
+vi.mock('./history/layerSnapshot', async (importOriginal) => {
+ const actual = await importOriginal<typeof LayerSnapshotModule>();
+ return {
+ ...actual,
+ createLayerSnapshotEntry: (...args: Parameters<typeof actual.createLayerSnapshotEntry>) => {
+ if (historyPreparationFaults.layerSnapshot) {
+ throw new Error('layer snapshot preparation failed');
+ }
+ return actual.createLayerSnapshotEntry(...args);
+ },
+ };
+});
+
const rasterLayer = (id: string, opts: { imageName?: string; opacity?: number } = {}): CanvasLayerContract => ({
blendMode: 'normal',
id,
@@ -455,6 +493,10 @@ const flushMicrotasks = (): Promise<void> =>
});
afterEach(() => {
+ adjustedSurfaceCacheDeleteFaults.clear();
+ historyPreparationFaults.imagePatch = false;
+ historyPreparationFaults.imagePatchBefore = null;
+ historyPreparationFaults.layerSnapshot = false;
vi.unstubAllGlobals();
});
@@ -2211,6 +2253,33 @@ describe('engine-owned control pixel editing', () => {
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());
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(20, 20));
+ h.overlay.fire('pointermove', pointerAt(40, 40));
+ historyPreparationFaults.imagePatch = true;
+
+ expect(() => h.overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }))).toThrow(
+ 'image patch preparation failed'
+ );
+
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ 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);
+ }
+ h.engine.dispose();
+ });
+
it('materializes an image control plus brush stroke as one reversible edit', async () => {
const h = createControlPaintHarness({
source: { image: { height: 10, imageName: 'control-image', width: 20 }, type: 'image' },
@@ -2251,6 +2320,70 @@ describe('engine-owned control pixel editing', () => {
h.engine.dispose();
});
+ it('restores a materialized control when layer-snapshot history preparation fails', async () => {
+ const h = createControlPaintHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 20 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 7, y: 11 },
+ });
+ await h.publishInitialCache();
+ const before = structuredClone(h.engine.getDocument());
+ const beforeCache = await snapshotLayerCache(h.engine, 'control');
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(20, 20));
+ h.overlay.fire('pointermove', pointerAt(25, 25));
+ historyPreparationFaults.layerSnapshot = true;
+
+ expect(() => h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }))).toThrow(
+ 'layer snapshot preparation failed'
+ );
+
+ expect(h.engine.getDocument()).toEqual(before);
+ const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });
+ expect(restored.status).toBe('ok');
+ if (restored.status === 'ok') {
+ expect(restored.surface).toBe(beforeCache.surface);
+ expect(restored.rect).toEqual(beforeCache.rect);
+ expect(restored.guard.cacheVersion).toBe(beforeCache.version);
+ }
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ expect(h.strokes).toHaveLength(0);
+ h.engine.dispose();
+ });
+
+ it('releases materialized persistence and edit ownership when rollback cleanup throws', async () => {
+ const h = createControlPaintHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 20 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 7, y: 11 },
+ });
+ await h.publishInitialCache();
+ const before = structuredClone(h.engine.getDocument());
+ h.engine.setTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(20, 20));
+ h.overlay.fire('pointermove', pointerAt(25, 25));
+ historyPreparationFaults.layerSnapshot = true;
+ adjustedSurfaceCacheDeleteFaults.add('control');
+
+ expect(() => h.overlay.fire('pointerup', pointerAt(25, 25, { buttons: 0 }))).toThrow(
+ 'adjusted surface cache delete failed'
+ );
+
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.strokes).toHaveLength(0);
+
+ historyPreparationFaults.layerSnapshot = false;
+ adjustedSurfaceCacheDeleteFaults.clear();
+ h.overlay.fire('pointerdown', pointerAt(30, 30));
+ expect(h.bitmapStore.suspendLayer).toHaveBeenCalledTimes(2);
+ h.overlay.fire('pointercancel', pointerAt(30, 30, { buttons: 0 }));
+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledTimes(2);
+ h.engine.dispose();
+ });
+
it.each(['eraser', 'brush'] as const)(
'rolls back a prepared image control when a %s gesture is cancelled',
async (tool) => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index a110cbb523..6fdf88fdf4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -4080,6 +4080,14 @@ 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 commitPatch = (label: string, patch: PixelEditPatch): boolean => {
if (closed || openControlPixelEdit !== owner) {
return false;
@@ -4094,30 +4102,32 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
currentLayer !== layer
) {
close();
- 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] });
- }
+ restorePatch(patch);
return false;
}
close();
- endNudgeBurst();
- notifyLayerPainted(layerId);
- bitmapStore.markLayerDirty(layerId);
- if (!history.isApplying()) {
- history.push(
- createImagePatchEntry({
+ let historyEntry: HistoryEntry | null = null;
+ try {
+ if (!history.isApplying()) {
+ historyEntry = createImagePatchEntry({
after: patch.after,
apply: applyImagePatch,
before: patch.before,
label,
layerId,
rect: patch.rect,
- })
- );
+ });
+ }
+ } catch (error) {
+ restorePatch(patch);
+ throw error;
+ }
+ endNudgeBurst();
+ if (historyEntry) {
+ history.push(historyEntry);
}
+ notifyLayerPainted(layerId);
+ bitmapStore.markLayerDirty(layerId);
return true;
};
const transaction: ControlPixelEditTransaction = {
@@ -4201,24 +4211,37 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
rect: beforeRect,
};
const restoreOriginal = (): void => {
- if (originalCache) {
- const current = layerCache.get(layerId);
- if (current) {
- current.hasPublishedPixels = originalCache.hasPublishedPixels;
- current.lastUsed = originalCache.lastUsed;
- current.rect = { ...originalCache.rect };
- current.stale = originalCache.stale;
- current.surface = originalCache.surface;
- current.version = originalCache.version;
+ try {
+ if (originalCache) {
+ const current = layerCache.get(layerId);
+ if (current) {
+ current.hasPublishedPixels = originalCache.hasPublishedPixels;
+ current.lastUsed = originalCache.lastUsed;
+ current.rect = { ...originalCache.rect };
+ current.stale = originalCache.stale;
+ current.surface = originalCache.surface;
+ current.version = originalCache.version;
+ }
+ } else {
+ layerCache.delete(layerId);
+ }
+ } finally {
+ try {
+ adjustedSurfaceCache.delete(layerId);
+ } finally {
+ transformOverrides.delete(layerId);
+ scheduler.invalidate({ layers: [layerId], overlay: true });
}
- } else {
- layerCache.delete(layerId);
}
- adjustedSurfaceCache.delete(layerId);
- transformOverrides.delete(layerId);
- scheduler.invalidate({ layers: [layerId], overlay: true });
};
const releasePersistence = bitmapStore.suspendLayer(layerId);
+ const restoreAndRelease = (): void => {
+ try {
+ restoreOriginal();
+ } finally {
+ releasePersistence();
+ }
+ };
try {
const previewEntry = originalEntry ?? layerCache.getOrCreateRect(layerId, prepared.rect);
previewEntry.surface = prepared.surface;
@@ -4230,8 +4253,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
transformOverrides.set(layerId, { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
scheduler.invalidate({ layers: [layerId], overlay: true });
} catch {
- restoreOriginal();
- releasePersistence();
+ restoreAndRelease();
return null;
}
@@ -4249,8 +4271,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (!close()) {
return;
}
- restoreOriginal();
- releasePersistence();
+ restoreAndRelease();
};
const commit = (label: string, event?: StrokeCommittedEvent): void => {
if (!close()) {
@@ -4268,12 +4289,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
!edited ||
(event && event.layerId !== layerId)
) {
- restoreOriginal();
- releasePersistence();
+ restoreAndRelease();
return;
}
let afterPixels: ImageData | null = null;
let after: LayerPixelSnapshot;
+ let historyEntry: HistoryEntry | null = null;
try {
if (!isEmpty(edited.rect)) {
afterPixels = edited.surface.ctx.getImageData(0, 0, edited.rect.width, edited.rect.height);
@@ -4284,24 +4305,26 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
pixels: afterPixels,
rect: { ...edited.rect },
};
+ if (!history.isApplying()) {
+ historyEntry = createLayerSnapshotEntry({ after, apply: applyControlLayerSnapshot, before, label });
+ }
dispatchPreparedMutation(
{ layer: materialized, layerId, type: 'replaceCanvasLayer' },
() => documentHasLayerContract(getReducerDocument(), materialized),
() => documentHasLayerContract(mirror.getDocument(), materialized)
);
} catch (error) {
- restoreOriginal();
- releasePersistence();
+ restoreAndRelease();
throw error;
}
transformOverrides.delete(layerId);
endNudgeBurst();
try {
+ if (historyEntry) {
+ history.push(historyEntry);
+ }
notifyLayerPainted(layerId);
bitmapStore.markLayerDirty(layerId);
- if (!history.isApplying()) {
- history.push(createLayerSnapshotEntry({ after, apply: applyControlLayerSnapshot, before, label }));
- }
} finally {
releasePersistence();
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
index 16a68580ef..719e7009b9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
@@ -286,6 +286,89 @@ describe('paint tool: target resolution', () => {
expect(transaction.commitStroke).not.toHaveBeenCalled();
});
+ it('aborts the control transaction and releases the gesture after pointer-move painting fails', () => {
+ const transaction = controlTransaction();
+ const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);
+ const brush = createBrushTool();
+ down(brush, h.ctx, pointer(10, 10));
+ const drawImage = vi.spyOn(cacheSurface(h, 'control').ctx, 'drawImage').mockImplementation(() => {
+ throw new Error('move paint failed');
+ });
+
+ expect(() => move(brush, h.ctx, pointer(20, 20), [pointer(20, 20)])).toThrow('move paint failed');
+
+ expect(transaction.cancel).toHaveBeenCalledOnce();
+ expect(transaction.commitStroke).not.toHaveBeenCalled();
+ expect(h.dispatched).toHaveLength(0);
+ expect(h.painted).toHaveLength(0);
+ expect(h.strokes).toHaveLength(0);
+
+ drawImage.mockRestore();
+ down(brush, h.ctx, pointer(30, 30));
+ expect(h.beginControlPixelEdit).toHaveBeenCalledTimes(2);
+ });
+
+ it('aborts the control transaction and releases the gesture after stroke finalization fails', () => {
+ const transaction = controlTransaction();
+ const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);
+ const brush = createBrushTool();
+ down(brush, h.ctx, pointer(10, 10));
+ const getImageData = vi.spyOn(cacheSurface(h, 'control').ctx, 'getImageData').mockImplementation(() => {
+ throw new Error('stroke finalization failed');
+ });
+
+ expect(() => up(brush, h.ctx, pointer(10, 10, { buttons: 0 }))).toThrow('stroke finalization failed');
+
+ expect(transaction.cancel).toHaveBeenCalledOnce();
+ expect(transaction.commitStroke).not.toHaveBeenCalled();
+ expect(h.dispatched).toHaveLength(0);
+ expect(h.painted).toHaveLength(0);
+ expect(h.strokes).toHaveLength(0);
+
+ getImageData.mockRestore();
+ down(brush, h.ctx, pointer(30, 30));
+ expect(h.beginControlPixelEdit).toHaveBeenCalledTimes(2);
+ });
+
+ it('still cancels the control transaction and releases the gesture when pixel restoration fails', () => {
+ const transaction = controlTransaction();
+ const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);
+ const brush = createBrushTool();
+ down(brush, h.ctx, pointer(10, 10));
+ const putImageData = vi.spyOn(cacheSurface(h, 'control').ctx, 'putImageData').mockImplementation(() => {
+ throw new Error('pixel restoration failed');
+ });
+
+ expect(() => cancel(brush, h.ctx)).toThrow('pixel restoration failed');
+
+ expect(transaction.cancel).toHaveBeenCalledOnce();
+ expect(transaction.commitStroke).not.toHaveBeenCalled();
+ expect(h.dispatched).toHaveLength(0);
+ expect(h.painted).toHaveLength(0);
+ expect(h.strokes).toHaveLength(0);
+
+ putImageData.mockRestore();
+ down(brush, h.ctx, pointer(30, 30));
+ expect(h.beginControlPixelEdit).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not roll back an accepted stroke when transaction publication throws', () => {
+ const transaction = controlTransaction();
+ vi.mocked(transaction.commitStroke).mockImplementation(() => {
+ throw new Error('listener publication failed');
+ });
+ const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);
+ const brush = createBrushTool();
+ down(brush, h.ctx, pointer(10, 10));
+
+ expect(() => up(brush, h.ctx, pointer(10, 10, { buttons: 0 }))).toThrow('listener publication failed');
+
+ expect(transaction.commitStroke).toHaveBeenCalledOnce();
+ expect(transaction.cancel).not.toHaveBeenCalled();
+ down(brush, h.ctx, pointer(30, 30));
+ expect(h.beginControlPixelEdit).toHaveBeenCalledTimes(2);
+ });
+
it('does not fall through to raster auto-create when control preparation is rejected', () => {
const h = createHarness(makeDoc([controlImageLayer('control')], 'control'), null);
const brush = createBrushTool();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index 3b0ccee773..fddfc19887 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -173,23 +173,36 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
target = null;
};
+ const abortSession = (): void => {
+ const activeSession = session;
+ const activeTarget = target;
+ try {
+ activeSession?.cancel();
+ } finally {
+ try {
+ activeTarget?.cancel();
+ } finally {
+ endSession();
+ }
+ }
+ };
+
return {
cursor: () => 'crosshair',
id: spec.id,
onDeactivate: (ctx, opts) => {
- if (session && target && !opts?.temporary) {
- session.cancel();
- target.cancel();
- endSession();
+ try {
+ if ((session || target) && !opts?.temporary) {
+ abortSession();
+ }
+ } finally {
+ ctx.setOverlayCursor(null);
+ ctx.invalidate({ overlay: true });
}
- ctx.setOverlayCursor(null);
- ctx.invalidate({ overlay: true });
},
onPointerCancel: () => {
- if (session && target) {
- session.cancel();
- target.cancel();
- endSession();
+ if (session || target) {
+ abortSession();
}
},
onPointerDown: (ctx, input) => {
@@ -228,29 +241,37 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
});
session.addPoints([input]);
} catch {
- session?.cancel();
- target.cancel();
- endSession();
+ abortSession();
}
},
onPointerMove: (ctx, input, batch) => {
updateCursorRing(ctx, input);
if (session) {
- session.addPoints(batch);
+ try {
+ session.addPoints(batch);
+ } catch (error) {
+ abortSession();
+ throw error;
+ }
}
},
onPointerUp: (ctx, input) => {
updateCursorRing(ctx, input);
if (session && target) {
+ const activeSession = session;
+ const activeTarget = target;
+ let event: StrokeCommittedEvent | null;
try {
- const event = session.commit();
- if (event) {
- target.commit(event);
- } else {
- target.cancel();
- }
- } finally {
- endSession();
+ event = activeSession.commit();
+ } catch (error) {
+ abortSession();
+ throw error;
+ }
+ endSession();
+ if (event) {
+ activeTarget.commit(event);
+ } else {
+ activeTarget.cancel();
}
}
},