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 paint cache persistence

joshistoast67e8a6a02444
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 e0609578d7..efc8dbd37d 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
@@ -35,6 +35,10 @@ const drainUntil = async (predicate: () => boolean, maxTicks = 50): Promise<void
interface HarnessOptions {
encodeSurface?: (surface: RasterSurface) => Promise<Blob>;
+ getLayerSurface?: (
+ surface: RasterSurface,
+ offset: { x: number; y: number }
+ ) => { surface: RasterSurface; offset: { x: number; y: number } } | null;
hashBlob?: (blob: Blob) => Promise<string>;
uploadImage?: (blob: Blob) => Promise<CanvasImageUploadResult>;
maxUploadAttempts?: number;
@@ -81,7 +85,7 @@ const createHarness = (options: HarnessOptions = {}) => {
? { getAuthoritativeLayerSource: options.getAuthoritativeLayerSource }
: {}),
getLayerSource: () => source,
- getLayerSurface: () => ({ offset, surface }),
+ getLayerSurface: () => (options.getLayerSurface ? options.getLayerSurface(surface, offset) : { offset, surface }),
// Deterministic content hash: the encoded blob's own text.
hashBlob: options.hashBlob ?? ((blob) => blob.text()),
maxUploadAttempts: options.maxUploadAttempts ?? 3,
@@ -1201,6 +1205,25 @@ describe('truthful extent: trimming and clearing', () => {
h.store.dispose();
});
+ 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') });
+
+ h.store.markLayerDirty(LAYER);
+ await h.store.flushPendingUploads();
+ const applied = (h.dispatch.mock.calls[0][0] as { source: { bitmap: CanvasImageRef } }).source.bitmap;
+ expect(h.store.isSelfEcho(LAYER, { bitmap: applied, type: 'paint' })).toBe(true);
+
+ erased = true;
+ h.setSource({ bitmap: null, type: 'paint' });
+ h.store.markLayerDirty(LAYER);
+ await h.store.flushPendingUploads();
+
+ expect(h.store.isSelfEcho(LAYER, { bitmap: applied, type: 'paint' })).toBe(false);
+ expect(h.dispatch).toHaveBeenCalledTimes(1);
+ h.store.dispose();
+ });
+
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') });
@@ -1234,6 +1257,86 @@ describe('truthful extent: trimming and clearing', () => {
h.store.dispose();
});
+ it('retries a rejected clear after the trim has already collapsed the cache', async () => {
+ let cacheEmpty = false;
+ let clearAttempts = 0;
+ const h = createHarness({
+ clearBitmap: () => {
+ clearAttempts += 1;
+ return clearAttempts === 2;
+ },
+ getLayerSurface: (surface, offset) => (cacheEmpty ? null : { offset, surface }),
+ trimLayerPixels: () => {
+ if (cacheEmpty) {
+ return 'kept';
+ }
+ cacheEmpty = true;
+ return 'emptied';
+ },
+ });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
+ await expect(h.store.flushPendingUploads()).resolves.toBeUndefined();
+
+ expect(h.clearBitmap).toHaveBeenCalledTimes(2);
+ expect(h.encodeSurface).not.toHaveBeenCalled();
+ expect(h.uploadImage).not.toHaveBeenCalled();
+ h.store.dispose();
+ });
+
+ it('cancels a pending clear when a new stroke restores visible pixels', 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');
+
+ cacheEmpty = false;
+ h.store.markLayerDirty(LAYER);
+ 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();
+ const h = createHarness({
+ onError,
+ trimLayerPixels: () => {
+ throw error;
+ },
+ });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
+
+ expect(h.trimLayerPixels).toHaveBeenCalledTimes(2);
+ expect(onError).toHaveBeenCalledTimes(2);
+ expect(onError).toHaveBeenNthCalledWith(1, error, LAYER);
+ expect(h.encodeSurface).not.toHaveBeenCalled();
+ h.store.dispose();
+ });
+
it('treats a throwing clear that nevertheless landed as success', async () => {
let cleared = false;
const onError = vi.fn();
@@ -1256,12 +1359,19 @@ describe('truthful extent: trimming and clearing', () => {
h.store.dispose();
});
- it('flushes normally for a deferred trim, byte-identically to an unwired store', async () => {
- const h = createHarness({ trimLayerPixels: () => 'deferred' });
+ it('defers persistence without uploading an untrimmed surface, then retries when ready', async () => {
+ let busy = true;
+ const h = createHarness({ trimLayerPixels: () => (busy ? 'deferred' : 'kept') });
h.store.markLayerDirty(LAYER);
- await vi.advanceTimersByTimeAsync(1500);
- await h.store.flushPendingUploads();
+ 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(h.uploadImage).toHaveBeenCalledTimes(1);
expect(h.dispatch).toHaveBeenCalledTimes(1);
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 d191d84ad4..8c92e75bf7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -127,7 +127,9 @@ 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. Absent ⇒ `'kept'` ⇒ no trimming.
+ * 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.
+ * Absent ⇒ `'kept'` ⇒ no trimming.
*/
trimLayerPixels?(layerId: string): PaintCacheTrim;
/**
@@ -231,11 +233,12 @@ 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 exhausted upload retries — the barrier must not
- * retry it again within the same {@link flushPendingUploads} call (anti-spin).
- * A stroke landing after a failure flips this back to `'stroke'`.
+ * 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'`.
*/
- const dirtyReason = new Map<string, 'failure' | 'stroke'>();
+ const dirtyReason = new Map<string, 'deferred' | 'failure' | 'stroke'>();
/** Active debounce timers, keyed by layer id. */
const debounceTimers = new Map<string, number>();
/** The in-flight flush op per layer (at most one), used by the barrier and to serialize. */
@@ -244,6 +247,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
const hashToImage = new Map<string, CanvasImageUploadResult>();
/** Layer id → the image name most recently dispatched by this store (self-echo guard). */
const lastApplied = new Map<string, string>();
+ /** Empty-cache clears that have not yet been accepted by the document. */
+ const pendingClears = new Set<string>();
/**
* Per-layer generation used only while invalidated work is still in flight.
* Idle ids are removed so ordinary layer deletion cannot accumulate permanent
@@ -346,18 +351,20 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
* throughout, so no generation re-check is needed before the dispatch.
*/
const clearLayerBitmap = (layerId: string, requeueFailure: (error: unknown) => void): void => {
+ // Drop the self-echo entry on every path: the trim established that the live
+ // cache no longer matches the last bitmap this store dispatched, including
+ // when the document has already independently reached `bitmap: null`.
+ lastApplied.delete(layerId);
// Redundant-dispatch skip against GROUND TRUTH, not `lastApplied` — see the header.
const sourceNow = deps.getLayerSource(layerId);
if (!sourceNow || sourceNow.type !== 'paint') {
+ pendingClears.delete(layerId);
return;
}
if (!sourceNow.bitmap) {
+ pendingClears.delete(layerId);
return;
}
- // Drop the self-echo entry: leaving the old name would make a later undo that
- // legitimately re-dispatches it look like our own echo, skipping the cache
- // invalidation and leaving an empty cache pointing at a real bitmap.
- lastApplied.delete(layerId);
let accepted: boolean;
try {
accepted = deps.clearBitmap
@@ -372,6 +379,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// As on the upload path: a dispatch that threw after the reducer committed
// still landed, so it must not be requeued.
if (authoritativeSource?.type === 'paint' && !authoritativeSource.bitmap) {
+ pendingClears.delete(layerId);
return;
}
if (authoritativeSource !== null) {
@@ -382,6 +390,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
if (accepted !== true && deps.getLayerSource(layerId) !== null) {
dirty.add(layerId);
dirtyReason.set(layerId, 'failure');
+ } else {
+ pendingClears.delete(layerId);
}
};
@@ -416,13 +426,30 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// would break the compositor's cache-rect-equals-content-rect invariant.
const sourceAtEntry = deps.getLayerSource(layerId);
if (!sourceAtEntry || sourceAtEntry.type !== 'paint') {
+ pendingClears.delete(layerId);
dirty.delete(layerId);
clearTimer(layerId);
return;
}
// Truthful extent (see the header). `getLayerSurface` below re-reads the cache,
// so it picks up the trimmed surface and origin with no further work.
- if (deps.trimLayerPixels?.(layerId) === 'emptied') {
+ let trimResult: PaintCacheTrim = 'kept';
+ try {
+ trimResult = deps.trimLayerPixels?.(layerId) ?? 'kept';
+ } catch (error) {
+ requeueFailure(error);
+ return;
+ }
+ if (trimResult === 'emptied') {
+ pendingClears.add(layerId);
+ }
+ if (trimResult === 'deferred') {
+ dirty.add(layerId);
+ dirtyReason.set(layerId, 'deferred');
+ clearTimer(layerId);
+ return;
+ }
+ if (pendingClears.has(layerId)) {
dirty.delete(layerId);
clearTimer(layerId);
clearLayerBitmap(layerId, requeueFailure);
@@ -607,6 +634,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
if (disposed) {
return;
}
+ pendingClears.delete(layerId);
dirty.add(layerId);
dirtyReason.set(layerId, 'stroke');
if (!isSuspended(layerId)) {
@@ -668,6 +696,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
dirty.delete(layerId);
dirtyReason.delete(layerId);
lastApplied.delete(layerId);
+ pendingClears.delete(layerId);
clearTimer(layerId);
};
@@ -679,13 +708,12 @@ 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 within this barrier call
- // is not retried again this call — only a fresh stroke re-enters the loop
- // for it — so a persistently failing upload still can't spin the barrier
- // forever.
- const failedThisBarrier = new Set<string>();
+ // 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.
+ const blockedThisBarrier = new Set<string>();
for (let iteration = 0; iteration < MAX_BARRIER_ITERATIONS; iteration += 1) {
- const toFlush = Array.from(dirty).filter((layerId) => !failedThisBarrier.has(layerId) && !isSuspended(layerId));
+ const toFlush = Array.from(dirty).filter((layerId) => !blockedThisBarrier.has(layerId) && !isSuspended(layerId));
for (const layerId of toFlush) {
clearTimer(layerId);
void runFlush(layerId);
@@ -696,18 +724,18 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
await waitForSuspensionChange();
continue;
}
- const failedLayerIds = Array.from(failedThisBarrier).filter(
- (layerId) => dirty.has(layerId) && dirtyReason.get(layerId) === 'failure'
+ const unpersistedLayerIds = Array.from(blockedThisBarrier).filter(
+ (layerId) => dirty.has(layerId) && dirtyReason.get(layerId) !== 'stroke'
);
- if (failedLayerIds.length > 0) {
- throw new BitmapPersistenceError(failedLayerIds);
+ if (unpersistedLayerIds.length > 0) {
+ throw new BitmapPersistenceError(unpersistedLayerIds);
}
return;
}
await Promise.all(ops);
for (const layerId of toFlush) {
- if (dirty.has(layerId) && dirtyReason.get(layerId) === 'failure') {
- failedThisBarrier.add(layerId);
+ if (dirty.has(layerId) && dirtyReason.get(layerId) !== 'stroke') {
+ blockedThisBarrier.add(layerId);
}
}
}
@@ -738,6 +766,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
debounceTimers.clear();
dirty.clear();
dirtyReason.clear();
+ pendingClears.clear();
suspensions.clear();
notifySuspensionWaiters();
// The self-echo map is per-(old)document; a reused layer id in the new
@@ -753,6 +782,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
debounceTimers.clear();
dirty.clear();
dirtyReason.clear();
+ pendingClears.clear();
suspensions.clear();
notifySuspensionWaiters();
inFlight.clear();
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 4bf3b17c83..d0e80b906b 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
@@ -241,10 +241,8 @@ const pointerAt = (x: number, y: number, buttons = 1): Partial<PointerEvent> =>
}) as Partial<PointerEvent>;
/**
- * `readbackAlpha` declares that the stub's surfaces report pixels — required by any
- * test that drives persistence through the engine's own bitmap store, since the
- * paint-cache trim reads alpha to decide whether a layer still has content. See
- * `StubRasterBackendOptions`.
+ * `readbackAlpha` overrides the stub's opaque readback when a test needs to model
+ * transparent pixels explicitly. See `StubRasterBackendOptions`.
*/
const setupEngine = (doc: CanvasDocumentContractV2, options: { readbackAlpha?: number } = {}) => {
const raf = createControllableRaf();
@@ -262,7 +260,7 @@ const setupEngine = (doc: CanvasDocumentContractV2, options: { readbackAlpha?: n
const reactive = createReactiveStore(doc);
const engine = createCanvasEngine({
- backend: createTestStubRasterBackend({ readbackAlpha: options.readbackAlpha ?? 0 }),
+ backend: createTestStubRasterBackend(options),
imageResolver: () => Promise.resolve(new Blob()),
projectId: 'p1',
store: reactive.store,
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 58ab4a550a..9c9a3a2569 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -12626,6 +12626,108 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',
uploadImage.mockRestore();
});
+ it('defers paint-cache trimming while a guarded canvas operation owns the layer', async () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal(
+ 'Path2D',
+ class FakePath2D {
+ closePath() {}
+ lineTo() {}
+ moveTo() {}
+ quadraticCurveTo() {}
+ }
+ );
+ const reducer = createReducerBackedStore(paintDoc());
+ const uploadImage = vi
+ .spyOn(canvasApplicationPort, 'uploadImage')
+ .mockResolvedValue({ height: 40, imageName: 'persisted-after-operation.png', width: 60 });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend({ readbackAlpha: 255 }),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: reducer.projectId,
+ store: reducer.store,
+ });
+ const overlay = createInputCanvas();
+ engine.surface.attach(createInputCanvas().element, overlay.element);
+ engine.tools.setTool('brush');
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+
+ overlay.fire('pointerdown', pointerAt(20, 20));
+ overlay.fire('pointermove', pointerAt(40, 40));
+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));
+ 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');
+ expect(uploadImage).not.toHaveBeenCalled();
+ expect(getCanvasOperations(engine).controller.getSnapshot()).toMatchObject({ status: 'active' });
+
+ getCanvasOperations(engine).cancelFilterOperation();
+ await expect(engine.lifecycle.flushPendingUploads()).resolves.toBeUndefined();
+ expect(uploadImage).toHaveBeenCalledOnce();
+
+ engine.lifecycle.dispose();
+ uploadImage.mockRestore();
+ });
+
+ it('defers paint-cache trimming while a raster snapshot pins the layer', async () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal(
+ 'Path2D',
+ class FakePath2D {
+ closePath() {}
+ lineTo() {}
+ moveTo() {}
+ quadraticCurveTo() {}
+ }
+ );
+ const reducer = createReducerBackedStore(paintDoc());
+ const uploadImage = vi
+ .spyOn(canvasApplicationPort, 'uploadImage')
+ .mockResolvedValue({ height: 40, imageName: 'persisted-after-snapshot.png', width: 60 });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend({ readbackAlpha: 255 }),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: reducer.projectId,
+ store: reducer.store,
+ });
+ const overlay = createInputCanvas();
+ engine.surface.attach(createInputCanvas().element, overlay.element);
+ engine.tools.setTool('brush');
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+
+ overlay.fire('pointerdown', pointerAt(20, 20));
+ overlay.fire('pointermove', pointerAt(40, 40));
+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));
+ const documentSnapshot = engine.document.captureSnapshot();
+ if (!documentSnapshot) {
+ throw new Error('expected a document snapshot');
+ }
+ 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') {
+ captured.snapshot.release();
+ }
+ await expect(engine.lifecycle.flushPendingUploads()).resolves.toBeUndefined();
+ expect(uploadImage).toHaveBeenCalledOnce();
+
+ engine.lifecycle.dispose();
+ uploadImage.mockRestore();
+ });
+
it('keeps an unflushed paint layer’s pixels on a transform/opacity-only change (no re-rasterize)', async () => {
const { engine, paintCache, raf, resolver, setDocument } = await paintOneStroke();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index f1ddabdca6..a220d62b8d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -568,6 +568,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
if (pipeline.isGestureActive()) {
return true;
}
+ if (stores.documentEditingLocked.get() || rasterController.memory.isPinned(layerId)) {
+ return true;
+ }
if (stores.transformSession.get()?.layerId === layerId || stores.textEditSession.get()?.layerId === layerId) {
return true;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts
index a34e585ed5..d3c0ef52f0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts
@@ -11,7 +11,7 @@ import { describe, expect, it, vi } from 'vitest';
* case and the guard matrix. Real cropping is asserted in the browser suite.
*/
const harness = (options: { busy?: boolean } = {}) => {
- const store = createLayerCacheStore(createTestStubRasterBackend());
+ const store = createLayerCacheStore(createTestStubRasterBackend({ readbackAlpha: 0 }));
const isLayerBusy = vi.fn(() => options.busy ?? false);
return { deps: { isLayerBusy, layers: store }, isLayerBusy, store };
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts
index a54ceeed98..16d7a1a0ff 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts
@@ -6,8 +6,9 @@
* is what the move outline, the transform frame and fit-to-content read. So a fully
* erased layer kept a draggable rectangle around nothing.
*
- * Runs from the debounced persistence flush, which already reads the whole surface
- * to encode it, so the alpha scan never touches the paint hot path.
+ * Runs from the debounced persistence flush, so its synchronous full-surface alpha
+ * readback never touches the paint hot path. The readback is distinct from the
+ * asynchronous PNG encode and its cost scales with the cache extent.
*
* Zero React, zero import-time side effects.
*/
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.ts
index 24b973e8d6..ff5bbab857 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.test.ts
@@ -36,14 +36,17 @@ describe('createTestStubRasterBackend', () => {
expect(surface.callLog[2]).toEqual({ op: 'setTransform', args: [1, 0, 0, 1, 5, 5] });
});
- it('getImageData returns a correctly-sized, zeroed buffer by default', () => {
+ it('getImageData reports opaque pixels by default so integration tests persist rendered surfaces', () => {
const backend = createTestStubRasterBackend();
const surface = backend.createSurface(4, 3);
const imageData = surface.ctx.getImageData(0, 0, 4, 3);
expect(imageData.width).toBe(4);
expect(imageData.height).toBe(3);
expect(imageData.data.length).toBe(4 * 3 * 4);
- expect(Array.from(imageData.data).every((v) => v === 0)).toBe(true);
+ const alphas = [...imageData.data].filter((_, index) => index % 4 === 3);
+ const colors = [...imageData.data].filter((_, index) => index % 4 !== 3);
+ expect(alphas.every((value) => value === 255)).toBe(true);
+ expect(colors.every((value) => value === 0)).toBe(true);
});
it('readbackAlpha fills the alpha channel only, leaving RGB zeroed', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts
index 30486cdc1e..c143316cb0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts
@@ -41,13 +41,12 @@ export interface StubRasterBackend extends RasterBackend {
/** Options for {@link createTestStubRasterBackend}. */
export interface StubRasterBackendOptions {
/**
- * The alpha every pixel of a synthetic readback reports (default `0`).
+ * The alpha every pixel of a synthetic readback reports (default `255`).
*
* A transparent readback MEANS something: the paint-cache trim reads alpha to
* decide whether a layer still has content, and clears one that has none. A test
- * driving persistence through the engine's OWN bitmap store must therefore declare
- * `readbackAlpha: 255`, or no upload will happen. Tests that inject their own
- * bitmap store are unaffected.
+ * driving an explicitly empty-cache path must therefore declare
+ * `readbackAlpha: 0`; ordinary engine-integration tests default to visible pixels.
*/
readbackAlpha?: number;
}
@@ -177,7 +176,7 @@ class StubRasterSurfaceImpl implements StubRasterSurface {
width: number;
height: number;
- constructor(width: number, height: number, readbackAlpha = 0) {
+ constructor(width: number, height: number, readbackAlpha = 255) {
this.width = width;
this.height = height;
this.canvas = { height, width } as unknown as OffscreenCanvas | HTMLCanvasElement;
@@ -213,7 +212,7 @@ export const createTestStubRasterBackend = (options: StubRasterBackendOptions =
return Promise.resolve({ close: () => {}, height: 0, width: 0 } as unknown as ImageBitmap);
},
createSurface: (width: number, height: number): StubRasterSurface =>
- new StubRasterSurfaceImpl(width, height, options.readbackAlpha ?? 0),
+ new StubRasterSurfaceImpl(width, height, options.readbackAlpha ?? 255),
// Deterministic fake blob keyed on the surface size, so encode calls are
// reproducible in node without touching a real canvas.
encodeSurface: (surface: RasterSurface, type = 'image/png'): Promise<Blob> =>