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(webv2): harden canvas persistence and control filters

Josh Corbett0787c66f4b11
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index ba230b3f89..12877830c6 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2514,6 +2514,7 @@
"mlsd_detection": "MLSD",
"normal_map": "Normal map",
"pidi_edge_detection": "PiDiNet",
+ "scribble_edge_detection": "Scribble",
"spandrel_filter": "Spandrel"
},
"invalidLayer": "Control layer \"{{name}}\": {{reason}}",
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 14078dfbbc..99c9993a2f 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
@@ -1508,9 +1508,10 @@ describe('truthful extent: trimming and clearing', () => {
offset: { x: 0, y: 0 },
type: 'paint',
};
+ const noSurface = (): null => null;
it('clears the ref instead of uploading when the trim finds no visible pixels', async () => {
- const h = createHarness({ trimLayerPixels: () => 'emptied' });
+ const h = createHarness({ getLayerSurface: noSurface, trimLayerPixels: () => 'emptied' });
h.setSource(withBitmap);
h.store.markLayerDirty(LAYER);
@@ -1530,7 +1531,7 @@ describe('truthful extent: trimming and clearing', () => {
});
it('prefers the injected clearBitmap seam over the default dispatch', async () => {
- const h = createHarness({ clearBitmap: () => true, trimLayerPixels: () => 'emptied' });
+ const h = createHarness({ clearBitmap: () => true, getLayerSurface: noSurface, trimLayerPixels: () => 'emptied' });
h.setSource(withBitmap);
h.store.markLayerDirty(LAYER);
@@ -1543,7 +1544,7 @@ describe('truthful extent: trimming and clearing', () => {
});
it('does not dispatch when the document already holds no bitmap', async () => {
- const h = createHarness({ trimLayerPixels: () => 'emptied' });
+ const h = createHarness({ getLayerSurface: noSurface, trimLayerPixels: () => 'emptied' });
// Default source is `{ bitmap: null }` — the clear would be a no-op.
h.store.markLayerDirty(LAYER);
@@ -1556,7 +1557,10 @@ describe('truthful extent: trimming and clearing', () => {
it('drops a stale self-echo entry when the document already holds no bitmap', async () => {
let erased = false;
- const h = createHarness({ trimLayerPixels: () => (erased ? 'emptied' : 'kept') });
+ const h = createHarness({
+ getLayerSurface: (surface, offset) => (erased ? null : { offset, surface }),
+ trimLayerPixels: () => (erased ? 'emptied' : 'kept'),
+ });
h.store.markLayerDirty(LAYER);
await h.store.flushPendingUploads();
@@ -1575,7 +1579,10 @@ describe('truthful extent: trimming and clearing', () => {
it('drops the self-echo entry, so a later undo re-dispatching the old name is not mistaken for an echo', async () => {
let erased = false;
- const h = createHarness({ trimLayerPixels: () => (erased ? 'emptied' : 'kept') });
+ const h = createHarness({
+ getLayerSurface: (surface, offset) => (erased ? null : { offset, surface }),
+ trimLayerPixels: () => (erased ? 'emptied' : 'kept'),
+ });
// First flush establishes `lastApplied` for the uploaded image.
h.store.markLayerDirty(LAYER);
@@ -1597,7 +1604,12 @@ describe('truthful extent: trimming and clearing', () => {
it('requeues as a failure when the clear is rejected', async () => {
const onError = vi.fn();
- const h = createHarness({ clearBitmap: () => false, onError, trimLayerPixels: () => 'emptied' });
+ const h = createHarness({
+ clearBitmap: () => false,
+ getLayerSurface: noSurface,
+ onError,
+ trimLayerPixels: () => 'emptied',
+ });
h.setSource(withBitmap);
h.store.markLayerDirty(LAYER);
@@ -1664,6 +1676,69 @@ describe('truthful extent: trimming and clearing', () => {
h.store.dispose();
});
+ it('cancels a pending clear when visible pixels are restored without a new dirty mark', async () => {
+ let cacheEmpty = false;
+ let trimmedOnce = false;
+ const h = createHarness({
+ clearBitmap: () => false,
+ getLayerSurface: (surface, offset) => (cacheEmpty ? null : { offset, surface }),
+ trimLayerPixels: () => {
+ if (!trimmedOnce) {
+ trimmedOnce = true;
+ cacheEmpty = true;
+ return 'emptied';
+ }
+ return 'kept';
+ },
+ });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
+
+ // A cache re-rasterization may restore pixels without going through
+ // markLayerDirty(). The pending clear must respect the fresh trim/surface
+ // verdict instead of deleting those visible pixels from the document.
+ cacheEmpty = false;
+ await expect(h.store.flushPendingUploads()).resolves.toBeUndefined();
+
+ expect(h.clearBitmap).toHaveBeenCalledOnce();
+ expect(h.uploadImage).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
+ it('lets a surface restored during trim cancel a pending clear in the same flush', async () => {
+ let cacheEmpty = true;
+ let primedPendingClear = false;
+ let restoreDuringTrim = false;
+ const h = createHarness({
+ clearBitmap: () => false,
+ getLayerSurface: (surface, offset) => (cacheEmpty ? null : { offset, surface }),
+ trimLayerPixels: () => {
+ if (!primedPendingClear) {
+ primedPendingClear = true;
+ return 'emptied';
+ }
+ if (restoreDuringTrim) {
+ cacheEmpty = false;
+ return 'emptied';
+ }
+ return 'kept';
+ },
+ });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
+
+ restoreDuringTrim = true;
+ await expect(h.store.flushPendingUploads()).resolves.toBeUndefined();
+
+ expect(h.clearBitmap).toHaveBeenCalledOnce();
+ expect(h.uploadImage).toHaveBeenCalledOnce();
+ h.store.dispose();
+ });
+
it('reports a throwing trim as a typed persistence failure and keeps it retryable', async () => {
const error = new Error('alpha readback failed');
const onError = vi.fn();
@@ -1710,20 +1785,19 @@ describe('truthful extent: trimming and clearing', () => {
h.store.dispose();
});
- it('defers persistence without uploading an untrimmed surface, then retries when ready', async () => {
+ it('waits through a transient trim deferral without reporting persistence failure', async () => {
let busy = true;
- const h = createHarness({ trimLayerPixels: () => (busy ? 'deferred' : 'kept') });
+ const sleep = vi.fn(() => {
+ busy = false;
+ return Promise.resolve();
+ });
+ const h = createHarness({ sleep, trimLayerPixels: () => (busy ? 'deferred' : 'kept') });
h.store.markLayerDirty(LAYER);
- await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
-
- expect(h.encodeSurface).not.toHaveBeenCalled();
- expect(h.uploadImage).not.toHaveBeenCalled();
- expect(h.dispatch).not.toHaveBeenCalled();
-
- busy = false;
await expect(h.store.flushPendingUploads()).resolves.toBeUndefined();
+ expect(sleep).toHaveBeenCalled();
+ expect(h.trimLayerPixels).toHaveBeenCalledTimes(2);
expect(h.uploadImage).toHaveBeenCalledTimes(1);
expect(h.dispatch).toHaveBeenCalledTimes(1);
h.store.dispose();
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 515a419bff..c12e7be263 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -51,6 +51,8 @@ export const DEFAULT_DEDUPE_CAP = 64;
export const DEFAULT_FAILURE_BACKOFF_MS = [2000, 5000, 15000, 30000] as const;
/** Consecutive ambient failures before the circuit opens (no more auto-retries). */
export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
+/** Short barrier poll while another canvas operation transiently owns pixels. */
+export const DEFAULT_DEFERRED_RETRY_MS = 50;
export class BitmapPersistenceError extends Error {
readonly layerIds: readonly string[];
@@ -113,7 +115,7 @@ export interface BitmapStoreDeps {
* Trims a layer's cache to its visible pixels (see **Truthful extent** above).
* Called after the source-type guard and BEFORE `getLayerSurface`, so this flush
* reads the trimmed surface and offset. A `'deferred'` result leaves the layer
- * dirty without encoding; a barrier reports that it could not persist the layer.
+ * dirty without encoding; a barrier waits and retries until ownership is released.
* Absent ⇒ `'kept'` ⇒ no trimming.
*/
trimLayerPixels?(layerId: string): PaintCacheTrim;
@@ -234,9 +236,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
* Why a layer is currently in `dirty`: `'stroke'` means a new paint stroke
* (re)marked it — worth retrying inside a barrier call; `'failure'` means
* its last flush attempt failed, and `'deferred'` means another operation still
- * owns the pixels. Neither is retried again within the same
- * {@link flushPendingUploads} call (anti-spin). A new stroke flips either back
- * to `'stroke'`.
+ * owns the pixels. Failures are not retried again within the same
+ * {@link flushPendingUploads} call (anti-spin); deferrals are polled until the
+ * owner releases the pixels. A new stroke flips either back to `'stroke'`.
*/
const dirtyReason = new Map<string, 'deferred' | 'failure' | 'stroke'>();
/** Active debounce timers, keyed by layer id. */
@@ -492,13 +494,19 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
clearTimer(layerId);
return;
}
- if (pendingClears.has(layerId)) {
+ const placed = deps.getLayerSurface(layerId);
+ if (pendingClears.has(layerId) && !placed) {
dirty.delete(layerId);
clearTimer(layerId);
clearLayerBitmap(layerId, requeueFailure);
return;
}
- const placed = deps.getLayerSurface(layerId);
+ if (pendingClears.has(layerId)) {
+ // A failed clear may outlive the empty cache that requested it. A later
+ // rasterization can restore visible pixels without calling markLayerDirty,
+ // so the fresh surface verdict wins over the stale clear intent.
+ pendingClears.delete(layerId);
+ }
if (!placed) {
// Layer or its cache is gone (or empty); nothing to persist.
dirty.delete(layerId);
@@ -768,9 +776,10 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// then await the in-flight ops — looping so a layer re-dirtied by a NEW
// stroke that lands while its upload is in flight gets a follow-up flush
// before the barrier resolves (the "document points at the latest painted
- // pixels" guarantee). A layer whose flush FAILED or DEFERRED within this
- // barrier call is not retried again this call, so neither a persistent error
- // nor an operation that still owns the pixels can spin the barrier forever.
+ // pixels" guarantee). A layer whose flush FAILED within this barrier call is
+ // not retried again this call. A transient DEFERRED layer is different: the
+ // barrier polls until the operation owning its pixels releases them, matching
+ // suspension semantics instead of surfacing a false persistence failure.
const blockedThisBarrier = new Set<string>();
for (let iteration = 0; iteration < MAX_BARRIER_ITERATIONS; iteration += 1) {
const toFlush = Array.from(dirty).filter((layerId) => !blockedThisBarrier.has(layerId) && !isSuspended(layerId));
@@ -793,11 +802,17 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
return;
}
await Promise.all(ops);
+ let deferredThisRound = false;
for (const layerId of toFlush) {
- if (dirty.has(layerId) && dirtyReason.get(layerId) !== 'stroke') {
+ if (dirty.has(layerId) && dirtyReason.get(layerId) === 'failure') {
blockedThisBarrier.add(layerId);
+ } else if (dirty.has(layerId) && dirtyReason.get(layerId) === 'deferred') {
+ deferredThisRound = true;
}
}
+ if (deferredThisRound) {
+ await sleep(DEFAULT_DEFERRED_RETRY_MS);
+ }
}
throw new Error('Canvas pixel persistence barrier exceeded its iteration limit.');
};
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 3a1b063366..22bafef53c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -11995,6 +11995,7 @@ describe('guarded filter previews', () => {
}
expect(engine.stores.documentEditingLocked.get()).toBe(true);
+ expect(engine.stores.documentEditingLayerId.get()).toBe('L');
engine.history.undo();
expect(
engine.layers.applyStructuralPreview({ id: 'L', patch: { opacity: 0.2 }, type: 'updateCanvasLayer' })
@@ -12026,6 +12027,7 @@ describe('guarded filter previews', () => {
operation?.cancel();
}
expect(engine.stores.documentEditingLocked.get()).toBe(false);
+ expect(engine.stores.documentEditingLayerId.get()).toBeNull();
engine.history.undo();
expect(engine.document.getDocument()!.layers[0]?.name).toBe('L');
engine.lifecycle.dispose();
@@ -12662,19 +12664,24 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',
expect(getCanvasOperations(engine).startFilterOperation('paint1')).toBe('started');
expect(getCanvasOperations(engine).setFilterOperationAutoProcess(false)).toBe('updated');
- await expect(engine.lifecycle.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
+ let barrierSettled = false;
+ const barrier = engine.lifecycle.flushPendingUploads().then(() => {
+ barrierSettled = true;
+ });
+ await flushMicrotasks();
+ expect(barrierSettled).toBe(false);
expect(uploadImage).not.toHaveBeenCalled();
expect(getCanvasOperations(engine).controller.getSnapshot()).toMatchObject({ status: 'active' });
getCanvasOperations(engine).cancelFilterOperation();
- await expect(engine.lifecycle.flushPendingUploads()).resolves.toBeUndefined();
+ await expect(barrier).resolves.toBeUndefined();
expect(uploadImage).toHaveBeenCalledOnce();
engine.lifecycle.dispose();
uploadImage.mockRestore();
});
- it('defers paint-cache trimming while a raster snapshot pins the layer', async () => {
+ it('persists once a raster snapshot has detached the pixels it needs', async () => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
@@ -12713,9 +12720,6 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',
}
const capture = engine.exports.captureRasterSnapshot(documentSnapshot, ['paint1']);
- await expect(engine.lifecycle.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
- expect(uploadImage).not.toHaveBeenCalled();
-
const captured = await capture;
expect(captured.status).toBe('ok');
if (captured.status === 'ok') {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 9baa719894..dfc7c28e37 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -415,6 +415,40 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
let lifecycleState: 'active' | 'cooling' | 'cool' | 'disposed' = 'active';
let lifecycleGeneration = 0;
let cooldownPromise: Promise<'cooled' | 'dirty'> | null = null;
+ const trimPinCounts = new Map<string, number>();
+ const trimPinsByGeneration = new Map<number, Set<{ release(): void }>>();
+ const pinLayerForTrim = (layerId: string, generation: number): { release(): void } => {
+ trimPinCounts.set(layerId, (trimPinCounts.get(layerId) ?? 0) + 1);
+ let released = false;
+ const lease = {
+ release: (): void => {
+ if (released) {
+ return;
+ }
+ released = true;
+ const count = trimPinCounts.get(layerId) ?? 0;
+ if (count <= 1) {
+ trimPinCounts.delete(layerId);
+ } else {
+ trimPinCounts.set(layerId, count - 1);
+ }
+ const generationPins = trimPinsByGeneration.get(generation);
+ generationPins?.delete(lease);
+ if (generationPins?.size === 0) {
+ trimPinsByGeneration.delete(generation);
+ }
+ },
+ };
+ const generationPins = trimPinsByGeneration.get(generation) ?? new Set<{ release(): void }>();
+ generationPins.add(lease);
+ trimPinsByGeneration.set(generation, generationPins);
+ return lease;
+ };
+ const releaseTrimPinGeneration = (generation: number): void => {
+ for (const lease of trimPinsByGeneration.get(generation) ?? []) {
+ lease.release();
+ }
+ };
// The brush/eraser cursor ring, drawn on the overlay (set by the active tool).
let overlayCursor: OverlayCursor | null = null;
@@ -568,7 +602,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
if (pipeline.isGestureActive()) {
return true;
}
- if (stores.documentEditingLocked.get() || rasterController.memory.isPinned(layerId)) {
+ if (stores.documentEditingLayerId.get() === layerId || (trimPinCounts.get(layerId) ?? 0) > 0) {
return true;
}
if (stores.transformSession.get()?.layerId === layerId || stores.textEditSession.get()?.layerId === layerId) {
@@ -1757,7 +1791,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// resets the pointer pipeline so a held space/alt temp tool doesn't strand
// when the window loses focus mid-hold.
const kickPendingFlush = (): void => {
- void persistenceController.flush();
+ // Lifecycle events cannot await this best-effort flush. Real persistence
+ // failures are already reported through BitmapStore.onError; consume the
+ // rejection so pagehide/visibilitychange never creates an unhandled promise.
+ void persistenceController.flush().catch(() => undefined);
};
const onPageHide = (): void => {
kickPendingFlush();
@@ -1807,6 +1844,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return;
}
rasterController.memory.releaseGeneration(lifecycleGeneration);
+ releaseTrimPinGeneration(lifecycleGeneration);
lifecycleGeneration += 1;
lifecycleState = 'active';
editingController.activate();
@@ -1825,6 +1863,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
psdExportController.cancel();
rasterController.memory.releaseGeneration(lifecycleGeneration);
+ releaseTrimPinGeneration(lifecycleGeneration);
lifecycleGeneration += 1;
const generation = lifecycleGeneration;
lifecycleState = 'cooling';
@@ -2133,6 +2172,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
isDisposed: () => disposed,
isGuardCurrent: isLayerExportGuardCurrent,
memory: rasterController.memory,
+ pinForTrim: pinLayerForTrim,
rasterizeLayerPixels,
syncMemoryBaselines,
});
@@ -2282,6 +2322,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
disposed = true;
releaseActiveSnapshots();
rasterController.memory.releaseGeneration(lifecycleGeneration);
+ releaseTrimPinGeneration(lifecycleGeneration);
lifecycleGeneration += 1;
lifecycleState = 'disposed';
const cleanup = createCleanupAccumulator();
@@ -2435,7 +2476,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
snapshot.documentGeneration === rasterController.getDocumentGeneration() &&
snapshot.lifecycleGeneration === lifecycleGeneration,
pin: (layerIds) => {
- const leases = layerIds.map((layerId) => rasterController.memory.pinOperation(layerId));
+ const leases = layerIds.map((layerId) => ({
+ memory: rasterController.memory.pinOperation(layerId),
+ trim: pinLayerForTrim(layerId, lifecycleGeneration),
+ }));
let released = false;
return {
release: () => {
@@ -2444,7 +2488,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
released = true;
for (const lease of leases) {
- lease.release();
+ lease.memory.release();
+ lease.trim.release();
}
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 916d3e8e35..7f92ac1ff4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -549,6 +549,8 @@ export interface EngineStores {
snapToGrid: ScalarStore<boolean>;
/** Whether an engine-owned operation currently excludes ordinary document edits. */
documentEditingLocked: ScalarStore<boolean>;
+ /** The layer targeted by that operation, or null when no operation is active. */
+ documentEditingLayerId: ScalarStore<string | null>;
}
const brushOptionsEqual = (a: BrushOptions, b: BrushOptions): boolean =>
@@ -671,6 +673,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
checkerColors: createScalarStore<CheckerColors>({ ...DEFAULT_CHECKER_COLORS }, checkerColorsEqual),
cursor: createScalarStore<string>('default'),
eraserOptions: createScalarStore<EraserOptions>({ ...DEFAULT_ERASER_OPTIONS }, eraserOptionsEqual),
+ documentEditingLayerId: createScalarStore<string | null>(null),
documentEditingLocked: createScalarStore<boolean>(false),
hasFloatingSelection: createScalarStore<boolean>(false),
hasSelection: createScalarStore<boolean>(false),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
index 7250ed778d..8cab99fa4b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
@@ -143,6 +143,33 @@ describe('isDocumentSnapshotCurrent', () => {
});
describe('captureRasterSnapshot', () => {
+ it('holds and releases the purpose-built trim guard around live pixel capture', async () => {
+ let resolveRasterize!: (result: ExportLayerPixelsResult) => void;
+ const rasterizeLayerPixels = vi.fn(
+ () =>
+ new Promise<ExportLayerPixelsResult>((resolve) => {
+ resolveRasterize = resolve;
+ })
+ );
+ const releaseTrimPin = vi.fn();
+ const pinForTrim = vi.fn(() => ({ release: releaseTrimPin }));
+ const guarded = makeHarness({ pinForTrim, rasterizeLayerPixels });
+ const capture = createRasterSnapshotCapture(guarded.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+
+ const pending = capture.captureRasterSnapshot(snapshot, ['a']);
+ expect(pinForTrim).toHaveBeenCalledWith('a', 0);
+ expect(releaseTrimPin).not.toHaveBeenCalled();
+
+ const pixels = okPixels('a');
+ if (pixels.status === 'ok') {
+ guarded.currentGuards.add(pixels.guard);
+ }
+ resolveRasterize(pixels);
+ await expect(pending).resolves.toMatchObject({ status: 'ok' });
+ expect(releaseTrimPin).toHaveBeenCalledOnce();
+ });
+
it('detaches a surface per layer and reports the empty ones separately', async () => {
harness.state.canvas = canvasState(['a', 'b']);
harness.rasterize.mockImplementation((layerId: string) => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
index 5b68741919..41293b76fb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
@@ -47,6 +47,8 @@ export interface CreateRasterSnapshotCaptureDeps {
layerId: string,
options: { includeDisabled?: boolean; signal?: AbortSignal }
) => Promise<ExportLayerPixelsResult>;
+ /** Guards paint-cache trimming while snapshot capture reads live layer pixels. */
+ readonly pinForTrim?: (layerId: string, generation: number) => { release(): void };
}
export interface RasterSnapshotCapture {
@@ -146,6 +148,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
}
const reservationLeases: { release(): void }[] = [reservation.lease];
const pinLeases = uniqueLayerIds.map((layerId) => memory.pin(layerId, captureLifecycleGeneration));
+ const trimPinLeases = uniqueLayerIds.map((layerId) => deps.pinForTrim?.(layerId, captureLifecycleGeneration));
const layerSurfaces = new Map<string, { rect: Rect; surface: RasterSurface }>();
const emptyLayerIds = new Set<string>();
const capturedGuards: LayerExportGuard[] = [];
@@ -243,6 +246,9 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
for (const lease of pinLeases) {
lease.release();
}
+ for (const lease of trimPinLeases) {
+ lease?.release();
+ }
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts
index efda7bef9c..b18580e672 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts
@@ -91,8 +91,10 @@ describe('alphaBounds', () => {
expect(isEmpty(alphaBounds({ data: new Uint8ClampedArray(0), height: 4, width: -1 }))).toBe(true);
});
- it('returns an empty rect when the buffer is too short to describe its dimensions', () => {
- expect(isEmpty(alphaBounds({ data: new Uint8ClampedArray(4 * 4 * 4 - 1), height: 4, width: 4 }))).toBe(true);
+ it('rejects a buffer too short to describe its dimensions', () => {
+ expect(() => alphaBounds({ data: new Uint8ClampedArray(4 * 4 * 4 - 1), height: 4, width: 4 })).toThrow(
+ 'RGBA pixel buffer is shorter than its dimensions require.'
+ );
});
it('ignores bytes beyond width * height * 4', () => {
@@ -108,13 +110,7 @@ describe('hasVisiblePixels', () => {
setAlpha(single, 5, 0, 1);
const opaque = buffer(3, 3);
opaque.data.fill(255);
- const cases: AlphaPixels[] = [
- buffer(6, 6),
- single,
- opaque,
- buffer(0, 0),
- { data: new Uint8ClampedArray(4 * 4 * 4 - 1), height: 4, width: 4 },
- ];
+ const cases: AlphaPixels[] = [buffer(6, 6), single, opaque, buffer(0, 0)];
for (const pixels of cases) {
expect(hasVisiblePixels(pixels)).toBe(!isEmpty(alphaBounds(pixels)));
}
@@ -125,4 +121,10 @@ describe('hasVisiblePixels', () => {
setAlpha(pixels, 3, 3, 1);
expect(hasVisiblePixels(pixels)).toBe(true);
});
+
+ it('rejects a buffer too short to prove that it has no visible pixels', () => {
+ expect(() => hasVisiblePixels({ data: new Uint8ClampedArray(4 * 4 * 4 - 1), height: 4, width: 4 })).toThrow(
+ 'RGBA pixel buffer is shorter than its dimensions require.'
+ );
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts
index c0d839b83c..f76cba09df 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts
@@ -23,15 +23,21 @@ export interface AlphaPixels {
const EMPTY_RECT: Rect = { height: 0, width: 0, x: 0, y: 0 };
-/** Too small to describe `width * height` pixels — never trusted to prove emptiness. */
-const isUnreadable = (pixels: AlphaPixels): boolean =>
- pixels.width <= 0 || pixels.height <= 0 || pixels.data.length < pixels.width * pixels.height * 4;
+const hasNonPositiveDimensions = (pixels: AlphaPixels): boolean => pixels.width <= 0 || pixels.height <= 0;
+
+/** Fail closed: incomplete readback must never be allowed to prove pixel emptiness. */
+const assertCompleteBuffer = (pixels: AlphaPixels): void => {
+ if (pixels.data.length < pixels.width * pixels.height * 4) {
+ throw new RangeError('RGBA pixel buffer is shorter than its dimensions require.');
+ }
+};
/** True when any pixel has non-zero alpha. Early-exits, so cheaper than {@link alphaBounds}. */
export const hasVisiblePixels = (pixels: AlphaPixels): boolean => {
- if (isUnreadable(pixels)) {
+ if (hasNonPositiveDimensions(pixels)) {
return false;
}
+ assertCompleteBuffer(pixels);
const { data } = pixels;
const end = pixels.width * pixels.height * 4;
for (let index = 3; index < end; index += 4) {
@@ -48,9 +54,10 @@ export const hasVisiblePixels = (pixels: AlphaPixels): boolean => {
* Edge-inclusive: one opaque pixel yields a 1x1 rect.
*/
export const alphaBounds = (pixels: AlphaPixels): Rect => {
- if (isUnreadable(pixels)) {
+ if (hasNonPositiveDimensions(pixels)) {
return EMPTY_RECT;
}
+ assertCompleteBuffer(pixels);
const { data, height, width } = pixels;
let minX = width;
let minY = -1;
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 01f4c21fb2..ba33bd8848 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
@@ -586,14 +586,16 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no
expect(h.layers.peek(h.createdIds[0]!)).toBeDefined();
});
- it('omits the reselect when nothing was selected to begin with', () => {
+ it('restores a null selection when nothing was selected to begin with', () => {
const h = clipped(makeDoc([paintLayer('p1')], null));
const brush = createBrushTool();
down(brush, h.ctx, pointer(80, 80));
up(brush, h.ctx, pointer(80, 80));
- expect(kinds(h)).toEqual(['addCanvasLayer', 'removeCanvasLayers']);
+ expect(kinds(h)).toEqual(['addCanvasLayer', 'removeCanvasLayers', 'setCanvasSelectedLayer']);
+ const reselect = h.dispatched[2]!;
+ expect(reselect.type === 'setCanvasSelectedLayer' && reselect.id).toBeNull();
});
it('keeps the layer when the stroke DOES commit pixels', () => {
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 e9204115ed..ffbad90b5e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -162,9 +162,7 @@ const resolveTarget = (ctx: ToolContext): PaintTarget | null => {
ctx.dispatch({ ids: [layerId], type: 'removeCanvasLayers' });
// The reducer's nearest-neighbour fallback would otherwise select whatever sits
// at the top, not what the user had selected when the gesture began.
- if (previousSelectedLayerId !== null) {
- ctx.dispatch({ id: previousSelectedLayerId, type: 'setCanvasSelectedLayer' });
- }
+ ctx.dispatch({ id: previousSelectedLayerId, type: 'setCanvasSelectedLayer' });
},
commit: (event) => ctx.emitStrokeCommitted(event),
createdLayer: { index: 0, layer },
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
index 1a112c7a5f..f55ac6e500 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
@@ -168,8 +168,11 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =
},
});
- const syncEditingLock = (): void =>
- core.stores.documentEditingLocked.set(controller.getSnapshot().status === 'active');
+ const syncEditingLock = (): void => {
+ const operation = controller.getSnapshot();
+ core.stores.documentEditingLocked.set(operation.status === 'active');
+ core.stores.documentEditingLayerId.set(operation.status === 'active' ? operation.identity.layerId : null);
+ };
const unsubscribeEditingLock = controller.subscribe(syncEditingLock);
const syncSamInteraction = (): void => {
const session = stores.samSession.get();
@@ -277,6 +280,7 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =
filterCoordinator.dispose();
selectObjectCoordinator.dispose();
controller.dispose();
+ core.stores.documentEditingLayerId.set(null);
core.stores.documentEditingLocked.set(false);
host.setSamInteraction(null);
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.test.ts
index c49f809fac..cc368657ee 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.test.ts
@@ -21,6 +21,7 @@ const EXPECTED_DEFAULTS: Record<string, Record<string, unknown>> = {
hed_edge_detection: { scribble: false },
mlsd_detection: { score_threshold: 0.1, distance_threshold: 20 },
pidi_edge_detection: { quantize_edges: false, scribble: false },
+ scribble_edge_detection: {},
content_shuffle: { scale_factor: 256 },
mediapipe_face_detection: { max_faces: 1, min_confidence: 0.5 },
color_map: { tile_size: 64 },
@@ -42,10 +43,10 @@ const SPANDREL_MODEL = {
};
describe('CONTROL_FILTERS registry', () => {
- it('contains exactly all sixteen legacy filter types', () => {
+ it('contains the legacy filters plus the Scribble preset', () => {
const types = CONTROL_FILTERS.map((definition) => definition.type);
- expect(types).toHaveLength(16);
- expect(new Set(types).size).toBe(16);
+ expect(types).toHaveLength(17);
+ expect(new Set(types).size).toBe(17);
expect(types).toEqual(EXPECTED_TYPES);
});
@@ -144,7 +145,7 @@ describe('buildFilterGraph', () => {
it('builds the direct legacy filter nodes with default params', () => {
const directTypes = EXPECTED_TYPES.filter(
- (type) => !['adjust_image', 'spandrel_filter', 'img_blur', 'img_noise'].includes(type)
+ (type) => !['adjust_image', 'spandrel_filter', 'img_blur', 'img_noise', 'scribble_edge_detection'].includes(type)
);
for (const type of directTypes) {
const { graph, outputNodeId } = buildFilterGraph(type, imageName);
@@ -171,6 +172,63 @@ describe('buildFilterGraph', () => {
}
});
+ it('builds Scribble as a discoverable HED scribble-mode preset', () => {
+ const { graph, outputNodeId } = buildFilterGraph('scribble_edge_detection', imageName);
+
+ expect(graph.nodes[FILTER_NODE_ID]).toMatchObject({
+ image: { image_name: imageName },
+ scribble: true,
+ type: 'hed_edge_detection',
+ });
+ expect(outputNodeId).toBe(FILTER_NODE_ID);
+ });
+
+ it('flattens transparent control inputs over white before processing and reapplies their alpha', () => {
+ const { graph, outputNodeId } = buildFilterGraph('canny_edge_detection', imageName, undefined, {
+ height: 80,
+ preserveTransparency: true,
+ width: 120,
+ });
+
+ expect(graph.nodes.control_filter_background).toMatchObject({
+ color: { a: 255, b: 255, g: 255, r: 255 },
+ height: 80,
+ type: 'blank_image',
+ width: 120,
+ });
+ expect(graph.nodes.control_filter_flatten).toMatchObject({
+ crop: true,
+ image: { image_name: imageName },
+ type: 'img_paste',
+ });
+ expect(graph.nodes.control_filter_source_alpha).toMatchObject({
+ image: { image_name: imageName },
+ type: 'tomask',
+ });
+ expect(graph.nodes.control_filter_restore_alpha).toMatchObject({
+ is_intermediate: true,
+ type: 'apply_mask_to_image',
+ });
+ expect(graph.nodes[FILTER_NODE_ID]).not.toHaveProperty('image');
+ expect(graph.edges).toEqual(
+ expect.arrayContaining([
+ {
+ destination: { field: 'image', node_id: FILTER_NODE_ID },
+ source: { field: 'image', node_id: 'control_filter_flatten' },
+ },
+ {
+ destination: { field: 'image', node_id: 'control_filter_restore_alpha' },
+ source: { field: 'image', node_id: FILTER_NODE_ID },
+ },
+ {
+ destination: { field: 'mask', node_id: 'control_filter_restore_alpha' },
+ source: { field: 'image', node_id: 'control_filter_source_alpha' },
+ },
+ ])
+ );
+ expect(outputNodeId).toBe('control_filter_restore_alpha');
+ });
+
it('builds adjust_image as offset or channel multiply', () => {
const offset = buildFilterGraph('adjust_image', imageName).graph.nodes[FILTER_NODE_ID] as Record<string, unknown>;
expect(offset).toMatchObject({
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts
index e301b0d920..2c4b138a67 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterGraphs.ts
@@ -29,8 +29,10 @@ export type FilterParamSpec =
/** One filter's identity, defaults, and node-arg projection. */
export interface FilterDefinition {
- /** The filter id (equals the backend node `type`). */
+ /** The persisted/UI filter id. */
type: string;
+ /** Backend node type when this definition is a named preset. */
+ nodeType?: string;
/** Ordered parameter specs (also the default-settings source). */
params: readonly FilterParamSpec[];
}
@@ -46,8 +48,9 @@ export const buildFilterDefaults = (definition: FilterDefinition): Record<string
/**
* The supported filters, in the legacy display order of the required set
- * (`features/controlLayers/store/filters.ts`). Each id equals its backend node
- * `type`; params carry legacy defaults + ranges.
+ * (`features/controlLayers/store/filters.ts`), plus named presets that improve
+ * discoverability. Params carry legacy defaults + ranges; a preset may project
+ * its UI id to a different backend node type.
*/
export const CONTROL_FILTERS: readonly FilterDefinition[] = [
{
@@ -103,6 +106,11 @@ export const CONTROL_FILTERS: readonly FilterDefinition[] = [
],
type: 'pidi_edge_detection',
},
+ {
+ nodeType: 'hed_edge_detection',
+ params: [],
+ type: 'scribble_edge_detection',
+ },
{
params: [{ default: 256, integer: true, key: 'scale_factor', kind: 'number', max: 4096, min: 0, step: 1 }],
type: 'content_shuffle',
@@ -306,7 +314,8 @@ export interface FilterGraphResult {
export const buildFilterGraph = (
filterType: string,
imageName: string,
- settings?: Record<string, unknown>
+ settings?: Record<string, unknown>,
+ input?: { height: number; preserveTransparency?: boolean; width: number }
): FilterGraphResult => {
const definition = FILTERS_BY_TYPE.get(filterType);
if (!definition) {
@@ -318,7 +327,7 @@ export const buildFilterGraph = (
id: FILTER_NODE_ID,
image: { image_name: imageName },
is_intermediate: true,
- type: definition.type,
+ type: definition.nodeType ?? definition.type,
use_cache: true,
...resolved,
};
@@ -335,7 +344,9 @@ export const buildFilterGraph = (
});
};
- if (filterType === 'adjust_image') {
+ if (filterType === 'scribble_edge_detection') {
+ graph.nodes[FILTER_NODE_ID] = { ...node, scribble: true };
+ } else if (filterType === 'adjust_image') {
const { channel, scale_values: scaleValues, value } = resolved;
graph.nodes[FILTER_NODE_ID] = scaleValues
? {
@@ -414,6 +425,59 @@ export const buildFilterGraph = (
edge('control_filter_seed', 'value', FILTER_NODE_ID, 'seed');
}
+ const canRestoreSourceAlpha =
+ input?.preserveTransparency === true &&
+ filterType !== 'adjust_image' &&
+ filterType !== 'img_blur' &&
+ filterType !== 'spandrel_filter';
+ if (canRestoreSourceAlpha) {
+ // Most control preprocessors convert RGBA to RGB. Transparent erased pixels
+ // then become black, producing an opaque black region (and false boundary
+ // edges). Composite over white before processing, then restore the source
+ // alpha so the processed control retains the user's erased holes.
+ delete graph.nodes[FILTER_NODE_ID]!.image;
+ graph.nodes.control_filter_background = {
+ color: { a: 255, b: 255, g: 255, r: 255 },
+ height: input.height,
+ id: 'control_filter_background',
+ is_intermediate: true,
+ mode: 'RGBA',
+ type: 'blank_image',
+ use_cache: true,
+ width: input.width,
+ };
+ graph.nodes.control_filter_flatten = {
+ crop: true,
+ id: 'control_filter_flatten',
+ image: { image_name: imageName },
+ is_intermediate: true,
+ type: 'img_paste',
+ use_cache: true,
+ x: 0,
+ y: 0,
+ };
+ graph.nodes.control_filter_source_alpha = {
+ id: 'control_filter_source_alpha',
+ image: { image_name: imageName },
+ invert: false,
+ is_intermediate: true,
+ type: 'tomask',
+ use_cache: true,
+ };
+ graph.nodes.control_filter_restore_alpha = {
+ id: 'control_filter_restore_alpha',
+ invert_mask: false,
+ is_intermediate: true,
+ type: 'apply_mask_to_image',
+ use_cache: true,
+ };
+ edge('control_filter_background', 'image', 'control_filter_flatten', 'base_image');
+ edge('control_filter_flatten', 'image', FILTER_NODE_ID, 'image');
+ edge(FILTER_NODE_ID, 'image', 'control_filter_restore_alpha', 'image');
+ edge('control_filter_source_alpha', 'image', 'control_filter_restore_alpha', 'mask');
+ return { graph, outputNodeId: 'control_filter_restore_alpha' };
+ }
+
return {
graph,
outputNodeId: FILTER_NODE_ID,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.test.ts
index 1f3708a09c..1fda67f996 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.test.ts
@@ -99,11 +99,15 @@ describe('runLayerFilter', () => {
calls.push('run');
expect(graph.nodes.control_filter).toMatchObject({
high_threshold: 200,
- image: { image_name: 'input' },
low_threshold: 100,
type: 'canny_edge_detection',
});
- expect(outputNodeId).toBe('control_filter');
+ expect(graph.nodes.control_filter_flatten).toMatchObject({
+ image: { image_name: 'input' },
+ type: 'img_paste',
+ });
+ expect(graph.nodes.control_filter_restore_alpha).toMatchObject({ type: 'apply_mask_to_image' });
+ expect(outputNodeId).toBe('control_filter_restore_alpha');
expect(receivedSignal).toBe(signal);
return Promise.resolve({ height: 60, imageName: 'output', width: 80 });
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.ts
index 3796e5c924..7c3e8eacb0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerFilterRunner.ts
@@ -70,7 +70,11 @@ export const runLayerFilter = async (options: RunLayerFilterOptions): Promise<La
throwIfAborted(options.signal);
const uploaded = await options.deps.uploadIntermediate(blob, options.signal);
throwIfAborted(options.signal);
- const built = buildFilterGraph(options.filterType, uploaded.imageName, options.settings);
+ const built = buildFilterGraph(options.filterType, uploaded.imageName, options.settings, {
+ height: options.input.rect.height,
+ preserveTransparency: true,
+ width: options.input.rect.width,
+ });
const output = await options.deps.runFilterGraph({
graph: built.graph,
outputNodeId: built.outputNodeId,