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): trim erased paint layers so they stop reporting phantom content

joshistoast5a00e6bd5d9d
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 fa6c2f13c8..f471614c76 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
@@ -1,5 +1,6 @@
import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';
import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';
+import type { PaintCacheTrim } from '@workbench/canvas-engine/render/paintCacheTrim';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
@@ -41,6 +42,10 @@ interface HarnessOptions {
/** The layer-local content-rect origin the surface sits at (default 0,0). */
offset?: { x: number; y: number };
sleep?: (ms: number) => Promise<void>;
+ /** Absent ⇒ the seam is not wired at all, i.e. no trimming (the default). */
+ trimLayerPixels?: (layerId: string) => PaintCacheTrim;
+ clearBitmap?: (layerId: string) => boolean;
+ getAuthoritativeLayerSource?: (layerId: string) => CanvasLayerSourceContract | null;
}
/** The default source: a plain paint layer, matching every pre-existing test's assumption. */
@@ -64,11 +69,18 @@ const createHarness = (options: HarnessOptions = {}) => {
Promise.resolve({ height: 10, imageName: `img-${uploadSeq++}`, width: 10 })
);
const dispatch = vi.fn((_action: CanvasProjectMutation) => true);
+ const clearBitmap = options.clearBitmap ? vi.fn(options.clearBitmap) : undefined;
+ const trimLayerPixels = options.trimLayerPixels ? vi.fn(options.trimLayerPixels) : undefined;
const store = createBitmapStore({
debounceMs: 1500,
dispatch,
encodeSurface,
+ ...(clearBitmap ? { clearBitmap } : {}),
+ ...(trimLayerPixels ? { trimLayerPixels } : {}),
+ ...(options.getAuthoritativeLayerSource
+ ? { getAuthoritativeLayerSource: options.getAuthoritativeLayerSource }
+ : {}),
getLayerSource: () => source,
getLayerSurface: () => ({ offset, surface }),
// Deterministic content hash: the encoded blob's own text.
@@ -82,8 +94,10 @@ const createHarness = (options: HarnessOptions = {}) => {
});
return {
+ clearBitmap,
dispatch,
encodeSurface,
+ trimLayerPixels,
setEncoded: (value: string) => {
encoded = value;
},
@@ -1134,3 +1148,160 @@ describe('createBitmapStore', () => {
});
});
});
+
+describe('truthful extent: trimming and clearing', () => {
+ /** A paint source already pointing at an uploaded bitmap. */
+ const withBitmap: CanvasLayerSourceContract = {
+ bitmap: { contentHash: 'h', height: 10, imageName: 'img-old', width: 10 },
+ offset: { x: 0, y: 0 },
+ type: 'paint',
+ };
+
+ it('clears the ref instead of uploading when the trim finds no visible pixels', async () => {
+ const h = createHarness({ trimLayerPixels: () => 'emptied' });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ // A transparent PNG must never be encoded, hashed or uploaded.
+ expect(h.encodeSurface).not.toHaveBeenCalled();
+ expect(h.uploadImage).not.toHaveBeenCalled();
+ expect(h.dispatch).toHaveBeenCalledTimes(1);
+ expect(h.dispatch.mock.calls[0][0]).toEqual({
+ id: LAYER,
+ source: { bitmap: null, type: 'paint' },
+ type: 'updateCanvasLayerSource',
+ });
+ h.store.dispose();
+ });
+
+ it('prefers the injected clearBitmap seam over the default dispatch', async () => {
+ const h = createHarness({ clearBitmap: () => true, trimLayerPixels: () => 'emptied' });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ expect(h.clearBitmap).toHaveBeenCalledWith(LAYER);
+ expect(h.dispatch).not.toHaveBeenCalled();
+ h.store.dispose();
+ });
+
+ it('does not dispatch when the document already holds no bitmap', async () => {
+ const h = createHarness({ trimLayerPixels: () => 'emptied' });
+ // Default source is `{ bitmap: null }` — the clear would be a no-op.
+
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ expect(h.dispatch).not.toHaveBeenCalled();
+ 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') });
+
+ // First flush establishes `lastApplied` for the uploaded image.
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ 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);
+
+ // Now the layer is erased and the trim empties it.
+ erased = true;
+ h.setSource({ bitmap: applied, offset: { x: 0, y: 0 }, type: 'paint' });
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ expect(h.store.isSelfEcho(LAYER, { bitmap: applied, type: 'paint' })).toBe(false);
+ h.store.dispose();
+ });
+
+ it('requeues as a failure when the clear is rejected', async () => {
+ const onError = vi.fn();
+ const h = createHarness({ clearBitmap: () => false, onError, trimLayerPixels: () => 'emptied' });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await expect(h.store.flushPendingUploads()).rejects.toThrow('Canvas pixel persistence failed');
+ h.store.dispose();
+ });
+
+ it('treats a throwing clear that nevertheless landed as success', async () => {
+ let cleared = false;
+ const onError = vi.fn();
+ const h = createHarness({
+ clearBitmap: () => {
+ cleared = true;
+ throw new Error('mirror notified synchronously and threw');
+ },
+ getAuthoritativeLayerSource: () => (cleared ? { bitmap: null, type: 'paint' } : withBitmap),
+ onError,
+ trimLayerPixels: () => 'emptied',
+ });
+ h.setSource(withBitmap);
+
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ expect(onError).not.toHaveBeenCalled();
+ h.store.dispose();
+ });
+
+ it('flushes normally for a deferred trim, byte-identically to an unwired store', async () => {
+ const h = createHarness({ trimLayerPixels: () => 'deferred' });
+
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ expect(h.uploadImage).toHaveBeenCalledTimes(1);
+ expect(h.dispatch).toHaveBeenCalledTimes(1);
+ h.store.dispose();
+ });
+
+ it('persists the POST-trim offset, proving the surface is re-read after trimming', async () => {
+ // The trim shrinks the cache, moving its origin; the flush must carry the new
+ // origin, not the one the cache had when the layer was marked dirty.
+ const h = createHarness({
+ offset: { x: 10, y: 10 },
+ trimLayerPixels: () => {
+ h.setOffset({ x: 34, y: 41 });
+ return 'trimmed';
+ },
+ });
+
+ h.store.markLayerDirty(LAYER);
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ expect(h.dispatch.mock.calls[0][0]).toMatchObject({
+ source: { offset: { x: 34, y: 41 }, type: 'paint' },
+ });
+ h.store.dispose();
+ });
+
+ it('never trims a layer whose source has converted away from paint', async () => {
+ const h = createHarness({ trimLayerPixels: () => 'emptied' });
+ h.store.markLayerDirty(LAYER);
+ h.setSource({ height: 10, kind: 'rect', fill: '#fff', stroke: null, strokeWidth: 0, type: 'shape', width: 10 });
+
+ await vi.advanceTimersByTimeAsync(1500);
+ await h.store.flushPendingUploads();
+
+ // Trimming a cache that now backs a parametric render would break the
+ // compositor's rect invariant, so the source guard must come first.
+ expect(h.trimLayerPixels).not.toHaveBeenCalled();
+ expect(h.dispatch).not.toHaveBeenCalled();
+ 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 20a8e510c2..81e7aab6c8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -41,6 +41,15 @@
* references (the redo lands on `{ bitmap: null }`); comparing against that
* stale memory would suppress the re-dispatch forever. Comparing against
* the document itself self-heals regardless of how it drifted.
+ * - **Truthful extent**: the persisted bitmap's DIMENSIONS are what the document
+ * reports as the layer's content rect, and that rect is what draws the move
+ * outline, frames the transform tool and drives fit-to-content. The cache only
+ * ever grows (chunk-padded strokes; the eraser grows it too), so persisting it
+ * verbatim would report a full-size rectangle for a layer whose pixels have all
+ * been erased. Each flush therefore trims the cache to its visible pixels first
+ * ({@link BitmapStoreDeps.trimLayerPixels}), and a layer left with none is
+ * cleared to `{ bitmap: null }` instead of uploading a transparent PNG — the
+ * same state a brand-new layer has.
*
* Every side-effecting dependency (encode, upload, hash, dispatch, timers) is
* injectable, so this runs in node tests with fakes. Zero React.
@@ -49,6 +58,7 @@
import type { CanvasImageRef, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';
import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { PaintCacheTrim } from '@workbench/canvas-engine/render/paintCacheTrim';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
/** Default idle window before a dirty layer is flushed. */
@@ -117,6 +127,28 @@ export interface BitmapStoreDeps {
* dispatch (used by the store's own tests, which only exercise paint layers).
*/
dispatchBitmap?(layerId: string, bitmap: CanvasImageRef, offset: { x: number; y: number }): boolean;
+ /**
+ * Trims a layer's cache back to its visible pixels before the extent is
+ * persisted, reporting what it did. See the **Truthful extent** invariant above.
+ *
+ * Called once per flush, immediately after the source-type guard and BEFORE
+ * `getLayerSurface`, so the surface and offset this flush goes on to read are
+ * already the trimmed ones. Absent ⇒ `'kept'` ⇒ no trimming, which is why the
+ * store's own tests are unaffected by this seam.
+ */
+ trimLayerPixels?(layerId: string): PaintCacheTrim;
+ /**
+ * Clears a layer's persisted bitmap reference (`bitmap: null`), for a layer the
+ * trim found to have no visible pixels. Returns whether the intended layer
+ * accepted it, exactly like {@link dispatchBitmap}. Absent ⇒ the default
+ * paint-source dispatch.
+ *
+ * Separate from `dispatchBitmap` rather than widening it to a nullable ref: the
+ * engine's implementation genuinely differs (there is no offset to carry, and a
+ * mask must clear `mask.bitmap` while preserving its `fill`), and the non-null
+ * contract stays intact for every existing caller.
+ */
+ clearBitmap?(layerId: string): boolean;
/** Content-hashes a blob (defaults to SHA-256 hex via `crypto.subtle`). */
hashBlob?(blob: Blob): Promise<string>;
/** Idle debounce window in ms (default {@link DEFAULT_DEBOUNCE_MS}). */
@@ -153,6 +185,11 @@ export interface BitmapStore {
* applied to `layerId` — i.e. the engine is seeing its own dispatch round-trip
* and must NOT re-rasterize/invalidate the cache (the pixels already match).
* A different bitmap (undo/import) returns `false` and re-rasterizes as usual.
+ *
+ * A CLEAR (`bitmap: null`) is deliberately never an echo: it has no image name,
+ * so the engine invalidates and re-rasterizes, and rasterizing a bitmap-less
+ * paint source collapses the cache to a zero rect — which is exactly the
+ * reconciliation a cleared layer needs.
*/
isSelfEcho(layerId: string, source: CanvasLayerSourceContract | null): boolean;
/**
@@ -317,6 +354,58 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
throw lastError ?? new Error('Canvas image upload failed');
};
+ /**
+ * Clears a layer's persisted bitmap ref, for a layer the trim found to hold no
+ * visible pixels. Synchronous throughout — there is nothing to encode or upload —
+ * so no generation re-check is needed between the decision and the dispatch.
+ *
+ * `requeueFailure` is passed in rather than re-derived so the "requeue before
+ * notifying" ordering rule lives in exactly one place.
+ */
+ const clearLayerBitmap = (layerId: string, requeueFailure: (error: unknown) => void): void => {
+ // Redundant-dispatch skip, against GROUND TRUTH rather than `lastApplied`, for
+ // the reason the module header gives: the document already holding no bitmap is
+ // the only thing that makes this dispatch a genuine no-op.
+ const sourceNow = deps.getLayerSource(layerId);
+ if (!sourceNow || sourceNow.type !== 'paint') {
+ return;
+ }
+ if (!sourceNow.bitmap) {
+ return;
+ }
+ // Drop the self-echo entry rather than recording one. A null ref has no image
+ // name to echo, and leaving the old name behind would make a later undo that
+ // legitimately re-dispatches that same name look like this store's 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
+ ? deps.clearBitmap(layerId)
+ : deps.dispatch({
+ id: layerId,
+ source: { bitmap: null, type: 'paint' },
+ type: 'updateCanvasLayerSource',
+ });
+ } catch (error) {
+ const authoritativeSource = (deps.getAuthoritativeLayerSource ?? deps.getLayerSource)(layerId);
+ // Same swap-on-success recovery as the upload path: a dispatch that threw
+ // after the reducer committed still landed, and must not be requeued.
+ if (authoritativeSource?.type === 'paint' && !authoritativeSource.bitmap) {
+ return;
+ }
+ if (authoritativeSource !== null) {
+ requeueFailure(error);
+ }
+ return;
+ }
+ if (accepted !== true && deps.getLayerSource(layerId) !== null) {
+ dirty.add(layerId);
+ dirtyReason.set(layerId, 'failure');
+ }
+ };
+
/** Encodes → hashes → dedupes/uploads → swaps the layer's ref, once. */
const flushLayer = async (layerId: string): Promise<void> => {
const generationAtEntry = layerGenerations.get(layerId) ?? 0;
@@ -336,6 +425,35 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// Keep the bounded retry state intact when an observer itself fails.
}
};
+ // Source-type guard (see `getLayerSource` doc): the dirty mark may predate
+ // a conversion away from `paint` (rasterize → undo is the motivating case,
+ // but any convert-back qualifies). The cache surface survives a source swap,
+ // so without this check we'd encode and dispatch a `paint` source over a layer
+ // that is no longer paint at all. Drop the pending flush entirely: nothing
+ // about this dirty mark is still valid, and a future genuine paint stroke will
+ // re-mark it if the layer ever becomes a paint layer again.
+ //
+ // This runs BEFORE the trim as well as before the encode: trimming a cache
+ // that now backs a PARAMETRIC render would break the compositor's invariant
+ // that the cache rect equals the source's content rect.
+ const sourceAtEntry = deps.getLayerSource(layerId);
+ if (!sourceAtEntry || sourceAtEntry.type !== 'paint') {
+ dirty.delete(layerId);
+ clearTimer(layerId);
+ return;
+ }
+ // Truthful extent (see the module header): shrink the cache to its visible
+ // pixels before anything reads its extent. `getLayerSurface` below re-reads the
+ // cache, so it picks up the trimmed surface and origin with no further work.
+ if (deps.trimLayerPixels?.(layerId) === 'emptied') {
+ // No visible pixels: clear the ref rather than upload a transparent PNG whose
+ // dimensions would keep reporting a phantom content rect. Nothing on this
+ // path awaits, so the generation cannot move underneath it.
+ dirty.delete(layerId);
+ clearTimer(layerId);
+ clearLayerBitmap(layerId, requeueFailure);
+ return;
+ }
const placed = deps.getLayerSurface(layerId);
if (!placed) {
// Layer or its cache is gone (or empty); nothing to persist.
@@ -348,20 +466,6 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// growth during the async encode window re-marks the layer (its stroke marks
// it dirty), so a follow-up flush re-converges with the current rect + offset.
const { offset, surface } = placed;
- // Source-type guard (see `getLayerSource` doc): the dirty mark may predate
- // a conversion away from `paint` (rasterize → undo is the motivating case,
- // but any convert-back qualifies). The cache surface still resolves above
- // — a source swap doesn't clear it — so without this check we'd encode and
- // dispatch a `paint` source over a layer that is no longer paint at all.
- // Drop the pending flush entirely: nothing about this dirty mark is still
- // valid, and a future genuine paint stroke will re-mark it if the layer
- // ever becomes a paint layer again.
- const sourceAtEntry = deps.getLayerSource(layerId);
- if (!sourceAtEntry || sourceAtEntry.type !== 'paint') {
- dirty.delete(layerId);
- clearTimer(layerId);
- return;
- }
// Consume the dirty flag up front; a failure re-adds it below. A stroke that
// lands mid-flush re-marks the layer, so the finally handler re-schedules.
dirty.delete(layerId);
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 74c2f05e11..4bf3b17c83 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
@@ -240,7 +240,13 @@ const pointerAt = (x: number, y: number, buttons = 1): Partial<PointerEvent> =>
timeStamp: 0,
}) as Partial<PointerEvent>;
-const setupEngine = (doc: CanvasDocumentContractV2) => {
+/**
+ * `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`.
+ */
+const setupEngine = (doc: CanvasDocumentContractV2, options: { readbackAlpha?: number } = {}) => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
@@ -256,7 +262,7 @@ const setupEngine = (doc: CanvasDocumentContractV2) => {
const reactive = createReactiveStore(doc);
const engine = createCanvasEngine({
- backend: createTestStubRasterBackend(),
+ backend: createTestStubRasterBackend({ readbackAlpha: options.readbackAlpha ?? 0 }),
imageResolver: () => Promise.resolve(new Blob()),
projectId: 'p1',
store: reactive.store,
@@ -328,7 +334,7 @@ describe('inpaint mask painting', () => {
});
it('persists the mask via updateCanvasLayerConfig (bitmap + offset) after a stroke flush', async () => {
- const { dispatch, engine, overlay } = setupEngine(maskDoc());
+ const { dispatch, engine, overlay } = setupEngine(maskDoc(), { readbackAlpha: 255 });
engine.tools.setTool('brush');
overlay.fire('pointerdown', pointerAt(20, 20));
overlay.fire('pointermove', pointerAt(50, 50));
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 b9fd0ceccb..58ab4a550a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -12580,7 +12580,8 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',
.spyOn(canvasApplicationPort, 'uploadImage')
.mockResolvedValue({ height: 40, imageName: 'persisted-before-mirror-refresh.png', width: 60 });
const engine = createCanvasEngine({
- backend: createTestStubRasterBackend(),
+ // The trim reads alpha to decide a layer still has content; declare it does.
+ backend: createTestStubRasterBackend({ readbackAlpha: 255 }),
imageResolver: () => Promise.resolve(new Blob()),
projectId: reducer.projectId,
reportError,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 04e2a38361..8d4db5933f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -123,6 +123,7 @@ import { createCheckerboardTile } from '@workbench/canvas-engine/render/composit
import { createFontLoader, domFontLoadApi } from '@workbench/canvas-engine/render/fontLoader';
import { createMaskPatternTile } from '@workbench/canvas-engine/render/maskFill';
import { renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';
+import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCacheTrim';
import { createDomRasterBackend, type RasterBackend, type RasterSurface } from '@workbench/canvas-engine/render/raster';
import { rasterizeSource, type ImageResolver, type RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';
import { getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';
@@ -526,6 +527,69 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return false;
};
+ /**
+ * Clears a layer's persisted bitmap, for a layer the paint-cache trim found to
+ * hold no visible pixels. The counterpart to {@link dispatchLayerBitmap}, routed
+ * the same way per layer type — and the resulting source is byte-identical to the
+ * one a brand-new layer is created with, so an emptied layer is indistinguishable
+ * from a fresh one to everything downstream (content rect, move outline, transform
+ * eligibility, fit-to-content).
+ *
+ * Deliberately NOT recorded as a self-echo: the engine should invalidate and
+ * re-rasterize, because rasterizing a bitmap-less paint source is what collapses
+ * the cache to a zero rect.
+ */
+ const clearLayerBitmap = (layerId: string): boolean => {
+ const doc = mirror.getDocument();
+ const layer = doc?.layers.find((candidate) => candidate.id === layerId);
+ if (!layer) {
+ return false;
+ }
+ if (layer.type === 'raster' || layer.type === 'control') {
+ return mutationPort.dispatch(
+ { id: layerId, source: { bitmap: null, type: 'paint' }, type: 'updateCanvasLayerSource' },
+ 'system'
+ );
+ } else if (layer.type === 'inpaint_mask' || layer.type === 'regional_guidance') {
+ // `patchLayerConfig` shallow-merges, so the mask's `fill` survives.
+ return mutationPort.dispatch(
+ {
+ config: { layerType: layer.type, mask: { bitmap: null, offset: { x: 0, y: 0 } } },
+ id: layerId,
+ type: 'updateCanvasLayerConfig',
+ },
+ 'system'
+ );
+ }
+ return false;
+ };
+
+ /**
+ * True while something other than persistence owns or frames a layer's pixels, so
+ * the paint-cache trim must defer rather than move the extent underneath it.
+ *
+ * ANY new session kind that reads or frames a layer's cache rect must be added
+ * here. The transform session is the non-obvious one: its frame geometry and its
+ * bake are both expressed relative to this rect, so shrinking mid-session would
+ * make the frame jump and Apply would bake against a rect the user never framed.
+ */
+ const isLayerBusyForTrim = (layerId: string): boolean => {
+ if (pipeline.isGestureActive()) {
+ return true;
+ }
+ if (stores.transformSession.get()?.layerId === layerId || stores.textEditSession.get()?.layerId === layerId) {
+ return true;
+ }
+ if (floatingSelection.get()?.layerId === layerId) {
+ return true;
+ }
+ if (controlPixelController?.isOpenFor([layerId])) {
+ return true;
+ }
+ const layer = mirror.getDocument()?.layers.find((candidate) => candidate.id === layerId);
+ return !!layer && isCurrentRasterizationJob(layer);
+ };
+
// Paint persistence: debounced PNG encode → SHA-256 dedupe → upload → a single
// swap-on-success `updateCanvasLayerSource` (paint) / `updateCanvasLayerConfig`
// (mask). Wired to committed strokes below.
@@ -533,8 +597,21 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
opts.bitmapStore ??
createBitmapStore({
dispatch: (action) => mutationPort.dispatch(action, 'system'),
+ clearBitmap: (layerId) => clearLayerBitmap(layerId),
dispatchBitmap: (layerId, bitmap, offset) => dispatchLayerBitmap(layerId, bitmap, offset),
encodeSurface: (surface) => backend.encodeSurface(surface),
+ trimLayerPixels: (layerId) => {
+ const result = trimPaintCacheToAlpha({ isLayerBusy: isLayerBusyForTrim, layers: layerCache }, layerId);
+ if (result === 'emptied' || result === 'trimmed') {
+ // The adjusted/mask-fill surfaces are keyed on the old extent, and the
+ // thumbnail and composite both need the new one. Both are synchronous, so
+ // they land before the clear dispatch below — cache and contract are never
+ // inconsistent across a rendered frame.
+ deleteDerivedSurfaces(layerId);
+ notifyLayerPainted(layerId);
+ }
+ return result;
+ },
getAuthoritativeLayerSource: getAuthoritativeLayerSourceById,
getLayerSource: getLayerSourceById,
getLayerSurface: (layerId) => {
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
new file mode 100644
index 0000000000..efda7bef9c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.test.ts
@@ -0,0 +1,128 @@
+import type { AlphaPixels } from '@workbench/canvas-engine/render/alphaBounds';
+
+import { isEmpty } from '@workbench/canvas-engine/math/rect';
+import { alphaBounds, hasVisiblePixels } from '@workbench/canvas-engine/render/alphaBounds';
+import { describe, expect, it } from 'vitest';
+
+/** A transparent RGBA buffer of the given size. */
+const buffer = (width: number, height: number): AlphaPixels & { data: Uint8ClampedArray } => ({
+ data: new Uint8ClampedArray(Math.max(0, width * height * 4)),
+ height,
+ width,
+});
+
+/** Sets one pixel's alpha (and, unless told otherwise, leaves RGB at zero). */
+const setAlpha = (pixels: AlphaPixels, x: number, y: number, alpha: number): void => {
+ pixels.data[(y * pixels.width + x) * 4 + 3] = alpha;
+};
+
+describe('alphaBounds', () => {
+ it('returns an empty rect for a fully transparent buffer', () => {
+ expect(isEmpty(alphaBounds(buffer(10, 10)))).toBe(true);
+ });
+
+ it('returns a 1x1 rect at a single opaque pixel', () => {
+ const pixels = buffer(10, 10);
+ setAlpha(pixels, 3, 5, 255);
+ expect(alphaBounds(pixels)).toEqual({ height: 1, width: 1, x: 3, y: 5 });
+ });
+
+ it('returns the bounding box of a ring, not the ring itself', () => {
+ const pixels = buffer(8, 8);
+ for (let i = 2; i <= 5; i += 1) {
+ setAlpha(pixels, i, 2, 255);
+ setAlpha(pixels, i, 5, 255);
+ setAlpha(pixels, 2, i, 255);
+ setAlpha(pixels, 5, i, 255);
+ }
+ expect(alphaBounds(pixels)).toEqual({ height: 4, width: 4, x: 2, y: 2 });
+ });
+
+ it('returns the bounding box of an L-shape spanning both extremes', () => {
+ const pixels = buffer(6, 6);
+ setAlpha(pixels, 0, 5, 255);
+ setAlpha(pixels, 5, 5, 255);
+ setAlpha(pixels, 0, 0, 255);
+ expect(alphaBounds(pixels)).toEqual({ height: 6, width: 6, x: 0, y: 0 });
+ });
+
+ it('treats alpha 1 as content', () => {
+ const pixels = buffer(4, 4);
+ setAlpha(pixels, 1, 2, 1);
+ expect(alphaBounds(pixels)).toEqual({ height: 1, width: 1, x: 1, y: 2 });
+ });
+
+ it('reads only the alpha channel — opaque RGB with alpha 0 is empty', () => {
+ const pixels = buffer(4, 4);
+ for (let index = 0; index < pixels.data.length; index += 4) {
+ pixels.data[index] = 255;
+ pixels.data[index + 1] = 255;
+ pixels.data[index + 2] = 255;
+ }
+ expect(isEmpty(alphaBounds(pixels))).toBe(true);
+ });
+
+ it('returns the whole buffer when every pixel is opaque', () => {
+ const pixels = buffer(5, 3);
+ pixels.data.fill(255);
+ expect(alphaBounds(pixels)).toEqual({ height: 3, width: 5, x: 0, y: 0 });
+ });
+
+ it('finds the rightmost pixel even when a later row is narrower', () => {
+ // Exercises the inward-from-the-right scan: row 0 sets the running maxX, and
+ // row 1 must not be able to lower it, while row 2 must be able to raise it.
+ const pixels = buffer(10, 3);
+ setAlpha(pixels, 1, 0, 255);
+ setAlpha(pixels, 6, 0, 255);
+ setAlpha(pixels, 4, 1, 255);
+ setAlpha(pixels, 9, 2, 255);
+ expect(alphaBounds(pixels)).toEqual({ height: 3, width: 9, x: 1, y: 0 });
+ });
+
+ it('finds a row whose only pixel sits exactly at the running maxX', () => {
+ const pixels = buffer(8, 2);
+ setAlpha(pixels, 5, 0, 255);
+ setAlpha(pixels, 5, 1, 255);
+ expect(alphaBounds(pixels)).toEqual({ height: 2, width: 1, x: 5, y: 0 });
+ });
+
+ it('returns an empty rect for non-positive dimensions', () => {
+ expect(isEmpty(alphaBounds(buffer(0, 0)))).toBe(true);
+ 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('ignores bytes beyond width * height * 4', () => {
+ const pixels: AlphaPixels = { data: new Uint8ClampedArray(4 * 4 * 4 + 64), height: 4, width: 4 };
+ pixels.data.fill(255, 4 * 4 * 4);
+ expect(isEmpty(alphaBounds(pixels))).toBe(true);
+ });
+});
+
+describe('hasVisiblePixels', () => {
+ it('agrees with alphaBounds emptiness across representative buffers', () => {
+ const single = buffer(6, 6);
+ 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 },
+ ];
+ for (const pixels of cases) {
+ expect(hasVisiblePixels(pixels)).toBe(!isEmpty(alphaBounds(pixels)));
+ }
+ });
+
+ it('finds alpha in the final pixel', () => {
+ const pixels = buffer(4, 4);
+ setAlpha(pixels, 3, 3, 1);
+ expect(hasVisiblePixels(pixels)).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts
new file mode 100644
index 0000000000..950a32d589
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts
@@ -0,0 +1,124 @@
+/**
+ * Alpha-derived content bounds for an RGBA pixel buffer.
+ *
+ * A layer's content rect is otherwise pure geometry — a paint source reports its
+ * persisted bitmap's dimensions, and the raster cache only ever GROWS (the stroke
+ * chunk-pads its extent, and the eraser grows it too). So a layer whose pixels
+ * have all been erased still describes a full-size rectangle, and every consumer
+ * of that rectangle — the move outline, the transform frame, fit-to-content —
+ * frames a region holding nothing. These functions are the pixel-side answer:
+ * where the visible pixels ACTUALLY are.
+ *
+ * ANY non-zero alpha counts as content, matching the selection state's mask test
+ * (`selection/selectionState.ts`) rather than the mask outline's solidity
+ * threshold. A higher threshold would silently discard faint pixels a user
+ * deliberately painted, which is a worse failure than an outline that lingers
+ * around near-invisible content.
+ *
+ * Zero React, zero import-time side effects.
+ */
+
+import type { Rect } from '@workbench/canvas-engine/types';
+
+/**
+ * An RGBA pixel buffer. Only the ALPHA channel is read, and only the first
+ * `width * height * 4` bytes. `ImageData` satisfies this structurally, so callers
+ * can pass a readback directly and tests can pass a plain literal — no canvas
+ * required.
+ */
+export interface AlphaPixels {
+ readonly data: Uint8ClampedArray;
+ readonly height: number;
+ readonly width: number;
+}
+
+/** The all-zero rect returned for a buffer with no visible pixels. */
+const EMPTY_RECT: Rect = { height: 0, width: 0, x: 0, y: 0 };
+
+/**
+ * True when the buffer is too small to describe `width * height` RGBA pixels —
+ * a partially-populated readback is never trusted to prove emptiness.
+ */
+const isUnreadable = (pixels: AlphaPixels): boolean =>
+ pixels.width <= 0 || pixels.height <= 0 || pixels.data.length < pixels.width * pixels.height * 4;
+
+/**
+ * True when any pixel in `pixels` has non-zero alpha.
+ *
+ * Early-exits on the first hit, so this is strictly cheaper than
+ * {@link alphaBounds} when only the yes/no answer is needed. An unreadable buffer
+ * reports `false` — it describes no pixels, so it has no visible ones.
+ */
+export const hasVisiblePixels = (pixels: AlphaPixels): boolean => {
+ if (isUnreadable(pixels)) {
+ return false;
+ }
+ const { data } = pixels;
+ const end = pixels.width * pixels.height * 4;
+ for (let index = 3; index < end; index += 4) {
+ if (data[index] !== 0) {
+ return true;
+ }
+ }
+ return false;
+};
+
+/**
+ * The tight bounds of the non-transparent pixels in `pixels`, expressed in the
+ * BUFFER's own pixel coordinates (origin at its top-left) — the caller translates
+ * into layer-local space by its surface origin.
+ *
+ * Returns an EMPTY rect when every pixel has alpha 0, so `math/rect`'s `isEmpty`
+ * is the emptiness test. The result is always inclusive of both edges: a single
+ * opaque pixel yields a 1x1 rect at that pixel.
+ *
+ * Rows are scanned edge-inward, skipping the span already known to be inside the
+ * running horizontal bounds — so a fully-covered buffer costs roughly two probes
+ * per row rather than a full pass.
+ */
+export const alphaBounds = (pixels: AlphaPixels): Rect => {
+ if (isUnreadable(pixels)) {
+ return EMPTY_RECT;
+ }
+ const { data, height, width } = pixels;
+ let minX = width;
+ let minY = -1;
+ let maxX = -1;
+ let maxY = -1;
+ for (let y = 0; y < height; y += 1) {
+ const rowStart = y * width * 4 + 3;
+ let rowMinX = -1;
+ for (let x = 0; x < width; x += 1) {
+ if (data[rowStart + x * 4] !== 0) {
+ rowMinX = x;
+ break;
+ }
+ }
+ if (rowMinX === -1) {
+ continue;
+ }
+ let rowMaxX = rowMinX;
+ // Everything between the running bounds is already accounted for, so only
+ // scan inward from the right edge down to whichever is further right.
+ for (let x = width - 1; x > Math.max(rowMinX, maxX); x -= 1) {
+ if (data[rowStart + x * 4] !== 0) {
+ rowMaxX = x;
+ break;
+ }
+ }
+ if (rowMinX < minX) {
+ minX = rowMinX;
+ }
+ if (rowMaxX > maxX) {
+ maxX = rowMaxX;
+ }
+ if (minY === -1) {
+ minY = y;
+ }
+ maxY = y;
+ }
+ if (maxY === -1) {
+ return EMPTY_RECT;
+ }
+ return { height: maxY - minY + 1, width: maxX - minX + 1, x: minX, y: minY };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts
index 9313b8323a..6e9f3640a0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts
@@ -301,6 +301,114 @@ describe('growToRect (paint caches grow with strokes)', () => {
});
});
+describe('shrinkToRect (paint caches trim back to their visible pixels)', () => {
+ /** A published 40x40 cache at (10,10) — the shape a chunk-padded stroke leaves. */
+ const published = () => {
+ const store = createLayerCacheStore(createTestStubRasterBackend());
+ const entry = store.growToRect('L', { height: 40, width: 40, x: 10, y: 10 });
+ store.publishPixels('L');
+ return { entry, store };
+ };
+
+ it('returns undefined for a layer with no cache', () => {
+ const store = createLayerCacheStore(createTestStubRasterBackend());
+ expect(store.shrinkToRect('missing', { height: 1, width: 1, x: 0, y: 0 })).toBeUndefined();
+ });
+
+ it('crops to the target rect with a NEGATIVE blit offset, preserving surface identity', () => {
+ const { entry, store } = published();
+ const trimmed = store.shrinkToRect('L', { height: 10, width: 10, x: 25, y: 30 });
+
+ expect(trimmed).toBe(entry);
+ expect(trimmed?.rect).toEqual({ height: 10, width: 10, x: 25, y: 30 });
+ expect(trimmed?.surface).toBe(entry.surface);
+ // Old origin (10,10) minus new origin (25,30) = (-15,-20): `drawImage` clips
+ // everything outside the smaller surface, so the crop is one GPU blit.
+ const log = (entry.surface as StubRasterSurface).callLog;
+ expect(log.filter((e) => e.op === 'resizePreserving').map((e) => e.args)).toEqual([[10, 10, -15, -20]]);
+ expect(log.map((e) => e.op)).not.toContain('getImageData');
+ expect(log.map((e) => e.op)).not.toContain('putImageData');
+ });
+
+ it('collapses to a zero-rect surface via resize (not a blit) for an empty target', () => {
+ const { entry, store } = published();
+ const emptied = store.shrinkToRect('L', { height: 0, width: 0, x: 0, y: 0 });
+
+ expect(emptied?.rect).toEqual({ height: 0, width: 0, x: 10, y: 10 });
+ expect(emptied?.surface.width).toBe(0);
+ expect(emptied?.surface.height).toBe(0);
+ const resizes = (entry.surface as StubRasterSurface).callLog.filter((e) => e.op === 'resize');
+ expect(resizes.map((e) => e.args)).toEqual([[0, 0]]);
+ });
+
+ it('keeps the ENTRY alive when collapsed, so an undo can re-grow into it', () => {
+ const { store } = published();
+ store.shrinkToRect('L', { height: 0, width: 0, x: 0, y: 0 });
+
+ // `applyImagePatch` gates undo on the entry existing, not on it having extent.
+ expect(store.peek('L')).toBeDefined();
+ const regrown = store.growToRect('L', { height: 8, width: 8, x: 12, y: 14 });
+ expect(regrown.rect).toEqual({ height: 8, width: 8, x: 12, y: 14 });
+ });
+
+ it('CLAMPS a request reaching outside the extent and never grows the cache', () => {
+ const { store } = published();
+ const clamped = store.shrinkToRect('L', { height: 400, width: 400, x: -100, y: -100 });
+ // Intersection with [10,50)² is the whole current extent → a no-op.
+ expect(clamped?.rect).toEqual({ height: 40, width: 40, x: 10, y: 10 });
+
+ const partial = store.shrinkToRect('L', { height: 100, width: 100, x: 30, y: 30 });
+ expect(partial?.rect).toEqual({ height: 20, width: 20, x: 30, y: 30 });
+ });
+
+ it('is a no-op — no resize, no version bump, no notify — when the rect already matches', () => {
+ const onVersionChange = vi.fn();
+ const store = createLayerCacheStore(createTestStubRasterBackend(), { onVersionChange });
+ const entry = store.growToRect('L', { height: 40, width: 40, x: 10, y: 10 });
+ store.publishPixels('L');
+ onVersionChange.mockClear();
+ const versionBefore = entry.version;
+ const logLength = (entry.surface as StubRasterSurface).callLog.length;
+
+ const again = store.shrinkToRect('L', { height: 40, width: 40, x: 10, y: 10 });
+ expect(again).toBe(entry);
+ expect(again?.version).toBe(versionBefore);
+ expect((entry.surface as StubRasterSurface).callLog.length).toBe(logLength);
+ expect(onVersionChange).not.toHaveBeenCalled();
+ });
+
+ it('bumps the version even when no pixels were ever published', () => {
+ // Unlike `growToRect`, which bumps only for published pixels: a shrink DESTROYS
+ // pixels, so an in-flight rasterization job must be invalidated regardless.
+ const onVersionChange = vi.fn();
+ const store = createLayerCacheStore(createTestStubRasterBackend(), { onVersionChange });
+ const entry = store.getOrCreateRect('L', { height: 40, width: 40, x: 0, y: 0 });
+ expect(entry.hasPublishedPixels).toBe(false);
+ const versionBefore = entry.version;
+
+ store.shrinkToRect('L', { height: 10, width: 10, x: 0, y: 0 });
+ expect(entry.version).toBe(versionBefore + 1);
+ expect(onVersionChange).toHaveBeenCalledWith('L');
+ });
+
+ it('leaves stale and hasPublishedPixels untouched — the surviving pixels are still fresh', () => {
+ const { entry, store } = published();
+ store.shrinkToRect('L', { height: 10, width: 10, x: 10, y: 10 });
+ expect(entry.stale).toBe(false);
+ expect(entry.hasPublishedPixels).toBe(true);
+ });
+
+ it('drops the damage trail, since every recorded surface-local rect is now void', () => {
+ const { entry, store } = published();
+ const version = entry.version;
+ store.publishPixels('L', { height: 4, width: 4, x: 0, y: 0 });
+ expect(store.damageSince('L', version)).not.toBeNull();
+
+ store.shrinkToRect('L', { height: 10, width: 10, x: 20, y: 20 });
+ expect(store.damageSince('L', version)).toBeNull();
+ });
+});
+
describe('damageSince', () => {
const seeded = () => {
const store = createLayerCacheStore(createTestStubRasterBackend());
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts
index 0f7da28823..39d084e35e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts
@@ -14,7 +14,7 @@
import type { Rect } from '@workbench/canvas-engine/types';
-import { union } from '@workbench/canvas-engine/math/rect';
+import { intersect, isEmpty, union } from '@workbench/canvas-engine/math/rect';
import type { RasterBackend, RasterSurface } from './raster';
@@ -110,6 +110,28 @@ export interface LayerCacheStore {
* when absent. Returns the entry.
*/
growToRect(layerId: string, rect: Rect): LayerCacheEntry;
+ /**
+ * SHRINKS a layer's cache to `rect` in layer-local space — the mirror of
+ * {@link growToRect}. `rect` is INTERSECTED with the current extent, so this can
+ * never grow a cache. Pixels inside the retained rect are preserved at their new
+ * offset; everything outside is dropped. An EMPTY `rect` collapses the cache to a
+ * zero-rect surface, the extent a brand-new or fully-erased paint layer has.
+ *
+ * Bumps the version and notifies UNCONDITIONALLY, unlike `growToRect`, which does
+ * so only when the entry had published pixels. Growth preserves everything the old
+ * version described; a shrink DESTROYS pixels, so every version-keyed dependent
+ * must be invalidated — in particular an in-flight rasterization job, which drops
+ * itself when the entry's version has moved and would otherwise resize the trimmed
+ * surface back up and redraw over it.
+ *
+ * The entry is MUTATED, never deleted: `applyImagePatch` gates undo on the entry
+ * existing, so a collapsed cache must still be able to receive restored pixels
+ * through `growToRect`.
+ *
+ * A no-op returning the entry when `rect` already equals the current extent, and
+ * `undefined` when the layer has no cache.
+ */
+ shrinkToRect(layerId: string, rect: Rect): LayerCacheEntry | undefined;
/** Clones `pixels` into a detached replacement without mutating the live cache. */
prepareReplacement(layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement;
/** Publishes a detached replacement without allocating, resizing, or drawing. */
@@ -343,6 +365,45 @@ export const createLayerCacheStore = (
return existing;
};
+ const shrinkToRect = (layerId: string, rect: Rect): LayerCacheEntry | undefined => {
+ const existing = entries.get(layerId);
+ if (!existing) {
+ return undefined;
+ }
+ const cur = existing.rect;
+ const requested: Rect = {
+ height: Math.max(0, Math.round(rect.height)),
+ width: Math.max(0, Math.round(rect.width)),
+ x: Math.round(rect.x),
+ y: Math.round(rect.y),
+ };
+ // Intersect rather than adopt: a shrink must never be able to grow a cache, so
+ // a request reaching outside the current extent is clamped back into it.
+ const clamped = isEmpty(cur) || isEmpty(requested) ? null : intersect(cur, requested);
+ const newRect: Rect = clamped ?? { height: 0, width: 0, x: cur.x, y: cur.y };
+ if (newRect.x === cur.x && newRect.y === cur.y && newRect.width === cur.width && newRect.height === cur.height) {
+ touch(existing);
+ return existing;
+ }
+ // The surface origin moves with the trimmed rect, so every surface-local rect
+ // recorded so far is void — same reasoning as `growToRect`.
+ damageTrails.delete(layerId);
+ const surface = existing.surface;
+ if (isEmpty(newRect)) {
+ surface.resize(0, 0);
+ } else {
+ // A negative blit offset is exactly how a crop is expressed: `drawImage`
+ // clips whatever falls outside the smaller surface, so the retained window
+ // lands at the new origin in one GPU blit with no CPU round trip.
+ surface.resizePreserving(newRect.width, newRect.height, cur.x - newRect.x, cur.y - newRect.y);
+ }
+ existing.rect = newRect;
+ touch(existing);
+ existing.version += 1;
+ notifyVersionChange(layerId);
+ return existing;
+ };
+
const prepareReplacement = (layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement => {
const normalizedRect: Rect = {
height: Math.max(0, Math.round(rect.height)),
@@ -496,6 +557,7 @@ export const createLayerCacheStore = (
peek,
prepareReplacement,
publishPixels,
+ shrinkToRect,
version,
};
};
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
new file mode 100644
index 0000000000..97d1b7c3d3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.test.ts
@@ -0,0 +1,114 @@
+import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';
+
+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCacheTrim';
+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
+import { describe, expect, it, vi } from 'vitest';
+
+/**
+ * A real cache store on the stub backend. The stub's `getImageData` invents a
+ * ZEROED readback, so every published surface reads as fully transparent here —
+ * which is exactly the `emptied` case, and makes this the natural home for the
+ * guard matrix. Cropping to real pixel bounds is asserted in the browser suite.
+ */
+const harness = (options: { busy?: boolean } = {}) => {
+ const store = createLayerCacheStore(createTestStubRasterBackend());
+ const isLayerBusy = vi.fn(() => options.busy ?? false);
+ return { deps: { isLayerBusy, layers: store }, isLayerBusy, store };
+};
+
+/** A published 40x40 cache at (10,10) — the shape a chunk-padded stroke leaves. */
+const publish = (store: ReturnType<typeof createLayerCacheStore>) => {
+ const entry = store.growToRect('L', { height: 40, width: 40, x: 10, y: 10 });
+ store.publishPixels('L');
+ return entry;
+};
+
+describe('trimPaintCacheToAlpha', () => {
+ it('keeps a layer with no cache at all', () => {
+ const { deps, isLayerBusy } = harness();
+ expect(trimPaintCacheToAlpha(deps, 'missing')).toBe('kept');
+ expect(isLayerBusy).not.toHaveBeenCalled();
+ });
+
+ it('keeps an already-empty cache without probing pixels', () => {
+ const { deps, store } = harness();
+ const entry = store.getOrCreateRect('L', { height: 0, width: 0, x: 0, y: 0 });
+ entry.stale = false;
+
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('kept');
+ expect((entry.surface as StubRasterSurface).callLog.map((e) => e.op)).not.toContain('getImageData');
+ });
+
+ it('DEFERS while pixels have never been published — the pre-rasterize window', () => {
+ // The layer rasterizer sizes the entry from the persisted content rect before
+ // its async decode fills it. Scanning here would clear a valid bitmap on load.
+ const { deps, store } = harness();
+ const entry = store.getOrCreateRect('L', { height: 40, width: 40, x: 0, y: 0 });
+ entry.stale = false;
+ expect(entry.hasPublishedPixels).toBe(false);
+
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('deferred');
+ expect(entry.rect).toEqual({ height: 40, width: 40, x: 0, y: 0 });
+ expect((entry.surface as StubRasterSurface).callLog.map((e) => e.op)).not.toContain('getImageData');
+ });
+
+ it('DEFERS while the cache is stale', () => {
+ const { deps, store } = harness();
+ const entry = publish(store);
+ entry.stale = true;
+
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('deferred');
+ expect(entry.rect).toEqual({ height: 40, width: 40, x: 10, y: 10 });
+ });
+
+ it('DEFERS while the layer is busy, without reading pixels', () => {
+ const { deps, isLayerBusy, store } = harness({ busy: true });
+ const entry = publish(store);
+
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('deferred');
+ expect(isLayerBusy).toHaveBeenCalledWith('L');
+ expect(entry.rect).toEqual({ height: 40, width: 40, x: 10, y: 10 });
+ expect((entry.surface as StubRasterSurface).callLog.map((e) => e.op)).not.toContain('getImageData');
+ });
+
+ it('EMPTIES a published cache holding no visible alpha, collapsing it to a zero rect', () => {
+ const { deps, store } = harness();
+ const entry = publish(store);
+
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('emptied');
+ expect(entry.rect).toEqual({ height: 0, width: 0, x: 10, y: 10 });
+ expect(entry.surface.width).toBe(0);
+ expect(entry.surface.height).toBe(0);
+ expect((entry.surface as StubRasterSurface).callLog.filter((e) => e.op === 'resize').map((e) => e.args)).toEqual([
+ [0, 0],
+ ]);
+ });
+
+ it('leaves the ENTRY alive after emptying, so an undo can re-grow into it', () => {
+ const { deps, store } = harness();
+ publish(store);
+
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('emptied');
+ // `applyImagePatch` gates undo on the entry existing, not on it having extent.
+ expect(store.peek('L')).toBeDefined();
+ });
+
+ it('reads the cache RECT, not the whole surface, when probing', () => {
+ const { deps, store } = harness();
+ const entry = publish(store);
+ store.shrinkToRect('L', { height: 12, width: 20, x: 15, y: 18 });
+
+ trimPaintCacheToAlpha(deps, 'L');
+ const reads = (entry.surface as StubRasterSurface).callLog.filter((e) => e.op === 'getImageData');
+ expect(reads.map((e) => e.args)).toEqual([[0, 0, 20, 12]]);
+ });
+
+ it('is idempotent — a second pass over an emptied cache keeps it', () => {
+ const { deps, store } = harness();
+ publish(store);
+
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('emptied');
+ expect(trimPaintCacheToAlpha(deps, 'L')).toBe('kept');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts
new file mode 100644
index 0000000000..180fbc3fa3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts
@@ -0,0 +1,88 @@
+/**
+ * Trims a paint layer's raster cache back to the pixels it can actually show.
+ *
+ * The cache only ever GROWS: a stroke chunk-pads its extent so a long drag
+ * reallocates once per chunk crossed rather than once per pointer batch, and the
+ * eraser grows it on the same path even though `destination-out` can only remove
+ * alpha. Nothing ever shrank it, so the extent recorded the high-water mark of
+ * everywhere the user's pointer had been — and persistence baked that extent into
+ * the layer's bitmap dimensions, which is what the move outline, the transform
+ * frame and fit-to-content all read. A fully erased layer therefore kept a
+ * full-size, draggable, transformable rectangle around nothing.
+ *
+ * This is the convergence step. It runs from the debounced persistence flush,
+ * which already reads the whole surface to encode it, so the alpha scan is
+ * proportionally cheap and never touches the paint hot path.
+ *
+ * Every guard below is load-bearing; see {@link trimPaintCacheToAlpha}.
+ *
+ * Zero React, zero import-time side effects.
+ */
+
+import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+
+import { isEmpty } from '@workbench/canvas-engine/math/rect';
+import { alphaBounds } from '@workbench/canvas-engine/render/alphaBounds';
+
+/**
+ * What a trim attempt did.
+ *
+ * - `deferred` — something else owns or frames these pixels right now; try later.
+ * - `emptied` — no visible pixels at all; the cache is now zero-rect.
+ * - `kept` — nothing to do (already tight, or no cache to trim).
+ * - `trimmed` — the cache was cropped to a smaller extent.
+ */
+export type PaintCacheTrim = 'deferred' | 'emptied' | 'kept' | 'trimmed';
+
+export interface TrimPaintCacheDeps {
+ readonly layers: LayerCacheStore;
+ /**
+ * True while something other than persistence owns or frames this layer's
+ * pixels. Supplied by the engine so this module stays free of engine knowledge.
+ */
+ readonly isLayerBusy: (layerId: string) => boolean;
+}
+
+/**
+ * Shrinks `layerId`'s cache to the bounds of its non-transparent pixels, or
+ * collapses it to a zero rect when it has none.
+ *
+ * The guards, and why each one matters:
+ *
+ * - Reads through `peek`, not `get`: a persistence-side probe must not reorder the
+ * LRU and make an unrelated layer the next eviction candidate.
+ * - `!hasPublishedPixels || stale` defers. This is the correctness guard, not an
+ * optimization: the layer rasterizer creates the cache entry sized to the
+ * persisted content rect BEFORE its async decode fills it, so a scan in that
+ * window would read a blank surface and conclude a perfectly good bitmap was
+ * empty — clearing it on every document load.
+ * - `isLayerBusy` defers for an open gesture, transform/text session, floating
+ * selection or in-flight rasterization. A transform frame in particular is
+ * expressed relative to this rect, so shrinking underneath it would make the
+ * frame jump and Apply would bake against a rect the user never framed.
+ */
+export const trimPaintCacheToAlpha = (deps: TrimPaintCacheDeps, layerId: string): PaintCacheTrim => {
+ const entry = deps.layers.peek(layerId);
+ if (!entry || isEmpty(entry.rect)) {
+ return 'kept';
+ }
+ if (!entry.hasPublishedPixels || entry.stale || deps.isLayerBusy(layerId)) {
+ return 'deferred';
+ }
+ const bounds = alphaBounds(entry.surface.ctx.getImageData(0, 0, entry.rect.width, entry.rect.height));
+ if (isEmpty(bounds)) {
+ deps.layers.shrinkToRect(layerId, { height: 0, width: 0, x: entry.rect.x, y: entry.rect.y });
+ return 'emptied';
+ }
+ if (bounds.width === entry.rect.width && bounds.height === entry.rect.height) {
+ return 'kept';
+ }
+ // `bounds` is in surface coordinates; the cache rect is layer-local.
+ deps.layers.shrinkToRect(layerId, {
+ height: bounds.height,
+ width: bounds.width,
+ x: entry.rect.x + bounds.x,
+ y: entry.rect.y + bounds.y,
+ });
+ return 'trimmed';
+};
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 cbc1d62a1a..24b973e8d6 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,7 +36,7 @@ describe('createTestStubRasterBackend', () => {
expect(surface.callLog[2]).toEqual({ op: 'setTransform', args: [1, 0, 0, 1, 5, 5] });
});
- it('getImageData returns a correctly-sized, zeroed buffer', () => {
+ it('getImageData returns a correctly-sized, zeroed buffer by default', () => {
const backend = createTestStubRasterBackend();
const surface = backend.createSurface(4, 3);
const imageData = surface.ctx.getImageData(0, 0, 4, 3);
@@ -46,6 +46,23 @@ describe('createTestStubRasterBackend', () => {
expect(Array.from(imageData.data).every((v) => v === 0)).toBe(true);
});
+ it('readbackAlpha fills the alpha channel only, leaving RGB zeroed', () => {
+ // The contract anything inferring content FROM pixels depends on: a stub
+ // surface reports pixels only when the test declares that it has them.
+ const backend = createTestStubRasterBackend({ readbackAlpha: 255 });
+ const imageData = backend.createSurface(2, 2).ctx.getImageData(0, 0, 2, 2);
+ const alphas = [...imageData.data].filter((_, index) => index % 4 === 3);
+ const colors = [...imageData.data].filter((_, index) => index % 4 !== 3);
+ expect(alphas).toEqual([255, 255, 255, 255]);
+ expect(colors.every((value) => value === 0)).toBe(true);
+ });
+
+ it('readbackAlpha also applies to createImageData', () => {
+ const backend = createTestStubRasterBackend({ readbackAlpha: 7 });
+ const imageData = backend.createSurface(1, 1).ctx.createImageData(1, 1);
+ expect(imageData.data[3]).toBe(7);
+ });
+
it('putImageData is recorded in the call log', () => {
const backend = createTestStubRasterBackend();
const surface = backend.createSurface(2, 2);
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 dff337fd5b..59006236ec 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
@@ -15,6 +15,11 @@
* `{ op: 'set', args: [prop, value] }` entry, so tests can assert that
* opacity/blend/style state was applied in order. Extend the method table in
* `createStubCtx` below as later tasks need more of the API surface.
+ *
+ * Readbacks are INVENTED, since the stub holds no pixels: `getImageData` returns a
+ * correctly-sized buffer whose alpha is {@link StubRasterBackendOptions.readbackAlpha}
+ * (transparent by default). Anything that infers content FROM pixels must therefore
+ * be tested either against a declared `readbackAlpha` or in the browser suite.
*/
import type { RasterBackend, RasterSurface } from './raster';
@@ -35,8 +40,30 @@ export interface StubRasterBackend extends RasterBackend {
createSurface(width: number, height: number): StubRasterSurface;
}
-const createStubImageData = (width: number, height: number): ImageData => {
+/** Options for {@link createTestStubRasterBackend}. */
+export interface StubRasterBackendOptions {
+ /**
+ * The alpha every pixel of a synthetic readback reports (default `0`).
+ *
+ * The stub holds no pixels, so a `getImageData` result is invented — and a fully
+ * transparent readback now MEANS something: the paint-cache trim reads a layer's
+ * alpha to decide whether it still has visible content, and a layer with none is
+ * cleared rather than persisted. A test that drives paint or mask persistence
+ * through the engine's OWN bitmap store must therefore declare that its layer has
+ * pixels (`readbackAlpha: 255`), or the trim will correctly conclude it is empty
+ * and no upload will happen. Tests that inject their own bitmap store are
+ * unaffected.
+ */
+ readbackAlpha?: number;
+}
+
+const createStubImageData = (width: number, height: number, alpha = 0): ImageData => {
const data = new Uint8ClampedArray(Math.max(0, width) * Math.max(0, height) * 4);
+ if (alpha !== 0) {
+ for (let index = 3; index < data.length; index += 4) {
+ data[index] = alpha;
+ }
+ }
return { colorSpace: 'srgb', data, height, width } as unknown as ImageData;
};
@@ -54,7 +81,10 @@ const fontSizeFromShorthand = (font: unknown): number => {
return match ? parseFloat(match[1] ?? '10') : 10;
};
-const createStubCtx = (callLog: RasterCallLogEntry[]): OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D => {
+const createStubCtx = (
+ callLog: RasterCallLogEntry[],
+ readbackAlpha: number
+): OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D => {
const log = (op: string, args: unknown[]): void => {
callLog.push({ args, op });
};
@@ -103,7 +133,7 @@ const createStubCtx = (callLog: RasterCallLogEntry[]): OffscreenCanvasRenderingC
createImageData: (...args: unknown[]) => {
const [width, height] = args as [number, number];
log('createImageData', [width, height]);
- return createStubImageData(width, height);
+ return createStubImageData(width, height, readbackAlpha);
},
drawImage: (...args: unknown[]) => log('drawImage', args),
ellipse: (...args: unknown[]) => log('ellipse', args),
@@ -112,7 +142,7 @@ const createStubCtx = (callLog: RasterCallLogEntry[]): OffscreenCanvasRenderingC
getImageData: (...args: unknown[]) => {
const [sx, sy, sw, sh] = args as [number, number, number, number];
log('getImageData', [sx, sy, sw, sh]);
- return createStubImageData(sw, sh);
+ return createStubImageData(sw, sh, readbackAlpha);
},
lineTo: (...args: unknown[]) => log('lineTo', args),
moveTo: (...args: unknown[]) => log('moveTo', args),
@@ -152,11 +182,11 @@ class StubRasterSurfaceImpl implements StubRasterSurface {
width: number;
height: number;
- constructor(width: number, height: number) {
+ constructor(width: number, height: number, readbackAlpha = 0) {
this.width = width;
this.height = height;
this.canvas = { height, width } as unknown as OffscreenCanvas | HTMLCanvasElement;
- this.ctx = createStubCtx(this.callLog);
+ this.ctx = createStubCtx(this.callLog, readbackAlpha);
}
resize(w: number, h: number): void {
@@ -182,12 +212,13 @@ class StubRasterSurfaceImpl implements StubRasterSurface {
* Creates a `RasterBackend` whose surfaces are backed by a fake, node-safe
* 2D context that records draw calls instead of executing them.
*/
-export const createTestStubRasterBackend = (): StubRasterBackend => ({
+export const createTestStubRasterBackend = (options: StubRasterBackendOptions = {}): StubRasterBackend => ({
createImageBitmap: (source: ImageBitmapSource): Promise<ImageBitmap> => {
void source;
return Promise.resolve({ close: () => {}, height: 0, width: 0 } as unknown as ImageBitmap);
},
- createSurface: (width: number, height: number): StubRasterSurface => new StubRasterSurfaceImpl(width, height),
+ createSurface: (width: number, height: number): StubRasterSurface =>
+ new StubRasterSurfaceImpl(width, height, options.readbackAlpha ?? 0),
// 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> =>