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.

refactor(webv2): tighten comments on the paint-cache trim

joshistoast17b8fa3e0bdc
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 f471614c76..0016e5daeb 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
@@ -1165,7 +1165,7 @@ describe('truthful extent: trimming and clearing', () => {
await vi.advanceTimersByTimeAsync(1500);
await h.store.flushPendingUploads();
- // A transparent PNG must never be encoded, hashed or uploaded.
+ // A transparent PNG must never be encoded or uploaded.
expect(h.encodeSurface).not.toHaveBeenCalled();
expect(h.uploadImage).not.toHaveBeenCalled();
expect(h.dispatch).toHaveBeenCalledTimes(1);
@@ -1270,8 +1270,7 @@ describe('truthful extent: trimming and clearing', () => {
});
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.
+ // The trim moves the cache origin; the flush must carry the new one.
const h = createHarness({
offset: { x: 10, y: 10 },
trimLayerPixels: () => {
@@ -1298,8 +1297,7 @@ describe('truthful extent: trimming and clearing', () => {
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.
+ // Trimming a parametric-backed cache would break the compositor's rect invariant.
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 81e7aab6c8..d191d84ad4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts
@@ -41,15 +41,12 @@
* 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.
+ * - **Truthful extent**: the persisted bitmap's DIMENSIONS become the layer's
+ * content rect, which draws the move outline, frames the transform tool and
+ * drives fit-to-content. The cache only ever grows, so each flush first trims it
+ * to its visible pixels ({@link BitmapStoreDeps.trimLayerPixels}); a layer left
+ * with none is cleared to `{ bitmap: null }` rather than uploading a transparent
+ * PNG whose dimensions would keep reporting a phantom rect.
*
* Every side-effecting dependency (encode, upload, hash, dispatch, timers) is
* injectable, so this runs in node tests with fakes. Zero React.
@@ -128,25 +125,16 @@ export interface BitmapStoreDeps {
*/
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.
+ * 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.
*/
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.
+ * Clears a layer's bitmap ref, for a layer the trim found empty. Returns whether
+ * the layer accepted it, like {@link dispatchBitmap}. Kept separate from that
+ * rather than widening it to a nullable ref: there is no offset to carry, and a
+ * mask must clear `mask.bitmap` while preserving its `fill`.
*/
clearBitmap?(layerId: string): boolean;
/** Content-hashes a blob (defaults to SHA-256 hex via `crypto.subtle`). */
@@ -186,10 +174,9 @@ export interface BitmapStore {
* 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.
+ * A clear (`bitmap: null`) is deliberately never an echo: re-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;
/**
@@ -355,17 +342,11 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
};
/**
- * 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.
+ * Clears a layer's bitmap ref, for a layer the trim found empty. Synchronous
+ * throughout, so no generation re-check is needed before the dispatch.
*/
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.
+ // Redundant-dispatch skip against GROUND TRUTH, not `lastApplied` — see the header.
const sourceNow = deps.getLayerSource(layerId);
if (!sourceNow || sourceNow.type !== 'paint') {
return;
@@ -373,11 +354,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
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.
+ // 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 {
@@ -390,8 +369,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
});
} 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.
+ // 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) {
return;
}
@@ -433,22 +412,17 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {
// 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.
+ // Also before the TRIM: shrinking a cache that now backs a parametric render
+ // would break the compositor's cache-rect-equals-content-rect invariant.
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.
+ // 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') {
- // 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);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 8d4db5933f..f1ddabdca6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -528,16 +528,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
};
/**
- * 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.
+ * Clears a layer's persisted bitmap, for a layer the paint-cache trim found empty.
+ * The counterpart to {@link dispatchLayerBitmap}, routed the same way per layer
+ * type. The resulting source is byte-identical to a brand-new layer's, so an
+ * emptied layer is indistinguishable from a fresh one downstream.
*/
const clearLayerBitmap = (layerId: string): boolean => {
const doc = mirror.getDocument();
@@ -566,12 +560,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
/**
* 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.
+ * the paint-cache trim defers rather than moving the extent underneath it. ANY new
+ * session kind that reads a layer's cache rect belongs here — notably the transform
+ * session, whose frame and bake are both expressed relative to that rect.
*/
const isLayerBusyForTrim = (layerId: string): boolean => {
if (pipeline.isGestureActive()) {
@@ -603,10 +594,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
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.
+ // Derived surfaces are keyed on the old extent; both calls are synchronous,
+ // so they land before the clear dispatch and no frame sees a mismatch.
deleteDerivedSurfaces(layerId);
notifyLayerPainted(layerId);
}
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 950a32d589..c0d839b83c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/alphaBounds.ts
@@ -1,19 +1,10 @@
/**
- * Alpha-derived content bounds for an RGBA pixel buffer.
+ * Alpha-derived content bounds for an RGBA pixel buffer — where a layer's visible
+ * pixels actually are, as opposed to the geometric extent its cache grew to.
*
- * 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.
+ * ANY non-zero alpha counts as content (matching `selection/selectionState.ts`, not
+ * the mask outline's solidity threshold): a higher threshold would silently discard
+ * faint pixels the user painted.
*
* Zero React, zero import-time side effects.
*/
@@ -21,10 +12,8 @@
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.
+ * An RGBA pixel buffer; only the alpha channel is read. `ImageData` satisfies this
+ * structurally, so tests can pass a plain literal — no canvas required.
*/
export interface AlphaPixels {
readonly data: Uint8ClampedArray;
@@ -32,23 +21,13 @@ export interface AlphaPixels {
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.
- */
+/** 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;
-/**
- * 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.
- */
+/** True when any pixel has non-zero alpha. Early-exits, so cheaper than {@link alphaBounds}. */
export const hasVisiblePixels = (pixels: AlphaPixels): boolean => {
if (isUnreadable(pixels)) {
return false;
@@ -64,17 +43,9 @@ export const hasVisiblePixels = (pixels: AlphaPixels): boolean => {
};
/**
- * 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.
+ * Tight bounds of the non-transparent pixels, in the BUFFER's own coordinates (the
+ * caller translates by its surface origin). Empty rect when every pixel is alpha 0.
+ * Edge-inclusive: one opaque pixel yields a 1x1 rect.
*/
export const alphaBounds = (pixels: AlphaPixels): Rect => {
if (isUnreadable(pixels)) {
@@ -98,8 +69,7 @@ export const alphaBounds = (pixels: AlphaPixels): Rect => {
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.
+ // Only scan right of the running maxX; anything inside it is already covered.
for (let x = width - 1; x > Math.max(rowMinX, maxX); x -= 1) {
if (data[rowStart + x * 4] !== 0) {
rowMaxX = x;
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 6e9f3640a0..df7e7957d4 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
@@ -322,8 +322,7 @@ describe('shrinkToRect (paint caches trim back to their visible pixels)', () =>
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.
+ // Old origin (10,10) minus new origin (25,30) = (-15,-20), in 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');
@@ -345,7 +344,6 @@ describe('shrinkToRect (paint caches trim back to their visible pixels)', () =>
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 });
@@ -378,8 +376,7 @@ describe('shrinkToRect (paint caches trim back to their visible pixels)', () =>
});
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.
+ // A shrink destroys pixels, so an in-flight rasterization job must invalidate.
const onVersionChange = vi.fn();
const store = createLayerCacheStore(createTestStubRasterBackend(), { onVersionChange });
const entry = store.getOrCreateRect('L', { height: 40, width: 40, x: 0, y: 0 });
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 39d084e35e..0243b4e450 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts
@@ -111,25 +111,19 @@ export interface LayerCacheStore {
*/
growToRect(layerId: string, rect: Rect): LayerCacheEntry;
/**
- * SHRINKS a layer's cache to `rect` in layer-local space — the mirror of
+ * Shrinks a layer's cache to `rect` (layer-local) — 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.
+ * never grow a cache; retained pixels move to the new offset and the rest is
+ * dropped. An empty `rect` collapses the cache to a zero-rect surface.
*
- * 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.
+ * Bumps the version UNCONDITIONALLY, unlike `growToRect`: a shrink destroys pixels,
+ * so an in-flight rasterization job must invalidate itself rather than 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`.
+ * MUTATES the entry, never deletes it — `applyImagePatch` gates undo on the entry
+ * existing, so a collapsed cache must still accept restored pixels via `growToRect`.
*
- * A no-op returning the entry when `rect` already equals the current extent, and
- * `undefined` when the layer has no cache.
+ * No-op when `rect` already equals the extent; `undefined` when there is no cache.
*/
shrinkToRect(layerId: string, rect: Rect): LayerCacheEntry | undefined;
/** Clones `pixels` into a detached replacement without mutating the live cache. */
@@ -377,24 +371,21 @@ export const createLayerCacheStore = (
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.
+ // Intersect rather than adopt, so a request reaching outside is clamped inward.
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`.
+ // The origin moved, so recorded surface-local rects are void (as in `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.
+ // A negative offset IS the crop: `drawImage` clips what falls outside the
+ // smaller surface, so this is 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;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.ts
index 4a3c55dc70..306180268b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheShrink.browser.test.ts
@@ -5,14 +5,10 @@ import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
import { describe, expect, it } from 'vitest';
/**
- * `shrinkToRect` crops a cache by blitting the surviving window to a new origin
- * with a NEGATIVE `resizePreserving` offset, relying on `drawImage` to clip
- * everything that falls outside the smaller surface. That is real GPU work with a
- * real offset: a sign slip would keep the wrong pixels, and a blit that silently
- * did nothing would lose the layer's content entirely.
- *
- * The node tests can only assert the arguments, because the stub surface holds no
- * pixels. These assert the pixels — the counterpart to `layerCacheGrowth.browser`.
+ * `shrinkToRect` crops by blitting the surviving window with a NEGATIVE
+ * `resizePreserving` offset, letting `drawImage` clip the rest. A sign slip would
+ * keep the wrong pixels; a no-op blit would lose the layer entirely. The node tests
+ * assert the arguments — these assert the pixels.
*/
const START: Rect = { height: 200, width: 200, x: 100, y: 100 };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts
index d3416c6d34..a123376c74 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.browser.test.ts
@@ -7,14 +7,9 @@ import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
import { describe, expect, it } from 'vitest';
/**
- * The trim decides whether a layer still has content by reading its alpha, and it
- * crops the cache by blitting the surviving window to a new origin. Both are real
- * pixel work: the node stub invents a uniform readback and only records the blit's
- * arguments, so it can cover the guard matrix but not the actual verdict.
- *
- * These assert the pixels — including the `destination-out` erase that produced the
- * reported bug, and the premultiplied readback of a faint mark, which is exactly
- * where a threshold-based emptiness test would wrongly discard user content.
+ * The trim's verdict and its crop blit are both real pixel work, which the node stub
+ * (uniform invented readback, recorded-only blits) cannot exercise. These assert the
+ * pixels — including the `destination-out` erase that produced the reported bug.
*/
/** A published cache at a non-zero origin — the shape a chunk-padded stroke leaves. */
@@ -47,8 +42,7 @@ describe('trimPaintCacheToAlpha with real pixels', () => {
expect(trimPaintCacheToAlpha(deps, 'L')).toBe('trimmed');
expect(entry.rect).toEqual({ height: 10, width: 10, x: 150, y: 160 });
- // Derived-surface caches key on the surface OBJECT, so the crop must resize in
- // place rather than swap the surface out from under them.
+ // Derived-surface caches key on the surface OBJECT, so this must resize in place.
expect(entry.surface).toBe(surfaceBefore);
expect(entry.surface.width).toBe(10);
expect(entry.surface.height).toBe(10);
@@ -69,7 +63,6 @@ describe('trimPaintCacheToAlpha with real pixels', () => {
it('EMPTIES a cache erased with destination-out — the reported bug', () => {
const { deps, entry } = published();
mark(entry, 150, 150, 'rgb(10,120,240)');
- // Exactly what the eraser does: composite the stroke out of the cache.
entry.surface.ctx.globalCompositeOperation = 'destination-out';
entry.surface.ctx.fillStyle = 'rgb(0,0,0)';
entry.surface.ctx.fillRect(0, 0, entry.rect.width, entry.rect.height);
@@ -93,10 +86,7 @@ describe('trimPaintCacheToAlpha with real pixels', () => {
});
it('PRESERVES a barely-visible mark: strict-zero never discards faint user pixels', () => {
- // A soft eraser leaves `a_dst * (1 - a_src)` behind, and an antialiased edge
- // leaves a couple of units. Treating those as empty would silently delete
- // content, so the verdict is strict-zero — which only real premultiplied
- // readback can exercise.
+ // A soft eraser leaves `a_dst * (1 - a_src)`, and antialiased edges a few units.
const { deps, entry } = published();
mark(entry, 180, 180, 'rgba(40,180,220,0.02)');
const sampled = entry.surface.ctx.getImageData(185 - START.x, 185 - START.y, 1, 1).data;
@@ -118,9 +108,7 @@ describe('trimPaintCacheToAlpha with real pixels', () => {
});
it('converges: trim, undo-style repaint, trim again', () => {
- // The full round trip the engine performs — erase → flush empties → undo writes
- // pixels back → flush finds them again. Drift in either direction would show up
- // as a rect that never settles.
+ // Erase → flush empties → undo writes pixels back → flush finds them again.
const { deps, entry, store } = published();
mark(entry, 150, 150, 'rgb(255,255,255)');
expect(trimPaintCacheToAlpha(deps, 'L')).toBe('trimmed');
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 97d1b7c3d3..a34e585ed5 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
@@ -6,10 +6,9 @@ import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/ras
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.
+ * A real cache store on the stub backend, whose readback is zeroed — so every
+ * published surface reads as transparent, making this the home for the `emptied`
+ * case and the guard matrix. Real cropping is asserted in the browser suite.
*/
const harness = (options: { busy?: boolean } = {}) => {
const store = createLayerCacheStore(createTestStubRasterBackend());
@@ -41,8 +40,6 @@ describe('trimPaintCacheToAlpha', () => {
});
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;
@@ -90,7 +87,6 @@ describe('trimPaintCacheToAlpha', () => {
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();
});
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 180fbc3fa3..a54ceeed98 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/paintCacheTrim.ts
@@ -1,20 +1,13 @@
/**
* 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.
+ * The cache only ever grows (strokes chunk-pad their extent; the eraser grows it
+ * too), and persistence bakes that extent into the layer's bitmap dimensions — which
+ * is what the move outline, the transform frame and fit-to-content read. So a fully
+ * erased layer kept a draggable 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}.
+ * 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.
*
* Zero React, zero import-time side effects.
*/
@@ -25,47 +18,31 @@ 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.
+ * `deferred` — something else owns these pixels; retry later. `emptied` — none
+ * visible, cache now zero-rect. `kept` — already tight, or no cache. `trimmed` —
+ * cropped smaller.
*/
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.
- */
+ /** Injected 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.
+ * Shrinks `layerId`'s cache to its non-transparent bounds, or collapses it to a zero
+ * rect when it has none.
*/
export const trimPaintCacheToAlpha = (deps: TrimPaintCacheDeps, layerId: string): PaintCacheTrim => {
+ // `peek`, not `get`: a persistence-side probe must not reorder the LRU.
const entry = deps.layers.peek(layerId);
if (!entry || isEmpty(entry.rect)) {
return 'kept';
}
+ // The unpublished/stale guard is correctness, not thrift: the rasterizer sizes the
+ // entry from the persisted rect BEFORE its async decode fills it, so scanning there
+ // would read a blank surface and clear a good bitmap on every document load.
if (!entry.hasPublishedPixels || entry.stale || deps.isLayerBusy(layerId)) {
return 'deferred';
}
@@ -77,7 +54,7 @@ export const trimPaintCacheToAlpha = (deps: TrimPaintCacheDeps, layerId: string)
if (bounds.width === entry.rect.width && bounds.height === entry.rect.height) {
return 'kept';
}
- // `bounds` is in surface coordinates; the cache rect is layer-local.
+ // `bounds` is surface-local; the cache rect is layer-local.
deps.layers.shrinkToRect(layerId, {
height: bounds.height,
width: bounds.width,
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 59006236ec..30486cdc1e 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
@@ -17,9 +17,7 @@
* `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.
+ * correctly-sized buffer whose alpha is {@link StubRasterBackendOptions.readbackAlpha}.
*/
import type { RasterBackend, RasterSurface } from './raster';
@@ -45,14 +43,11 @@ 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.
+ * 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.
*/
readbackAlpha?: number;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts
index 33b8f44072..3c9534f498 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts
@@ -260,14 +260,11 @@ describe('live cache rect (freshly-painted, not-yet-flushed content)', () => {
describe('a layer erased to nothing behaves exactly like a brand-new one', () => {
/**
- * The reported bug: a layer whose pixels had all been erased kept a full-size
- * bitmap of transparent pixels, so it still drew a movable, transformable blue
- * outline around an empty region.
- *
- * The paint-cache trim now clears such a layer to `{ bitmap: null }` — the same
- * source a freshly-added layer is created with — so every affordance derived from
- * `hittableLayerRect` disappears. These pin that equivalence, since it is the
- * whole reason the fix works without touching the overlay or the tools.
+ * The reported bug: an erased layer kept a full-size transparent bitmap, so it still
+ * drew a movable, transformable outline around nothing. The paint-cache trim now
+ * clears it to `{ bitmap: null }` — a freshly-added layer's source — so every
+ * affordance derived from `hittableLayerRect` disappears. Pinning that equivalence
+ * is why the fix needs no change to the overlay or the tools.
*/
it('reports no hittable extent once its bitmap has been cleared', () => {
const erased = paintLayer('erased');
@@ -278,8 +275,6 @@ describe('a layer erased to nothing behaves exactly like a brand-new one', () =>
});
it('draws no move outline, even under a non-identity transform', () => {
- // Scale and rotation are exactly where a phantom rect is most visible, so the
- // suppression must not depend on the transform being trivial.
const erased: CanvasLayerContract = {
...paintLayer('erased'),
transform: { rotation: 0.6, scaleX: 2.5, scaleY: 1.75, x: 40, y: 25 },
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 1266311bda..01f4c21fb2 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
@@ -511,14 +511,12 @@ describe('mask strokes are forced opaque', () => {
describe('auto-created layer rollback (a gesture that commits nothing leaves no trace)', () => {
/**
- * The auto-create dispatch happens at pointer-DOWN, before any pixel exists, and
- * deliberately outside history — so a gesture that produces no dirty rect has to
- * roll the layer back itself, or it strands a layer the user cannot undo.
+ * The auto-create dispatch happens at pointer-DOWN, outside history, so a gesture
+ * producing no dirty rect must roll the layer back itself or strand it un-undoably.
*/
const clipped = (doc: CanvasDocumentContractV2) => {
const h = createHarness(doc);
- // Clip-to-bbox on, with the whole stroke outside the frame: every `paint()`
- // call bails, so `commit()` returns null.
+ // Clip-to-bbox on with the stroke outside the frame, so `commit()` returns null.
const ctx: ToolContext = { ...h.ctx, getStrokeClipRect: () => ({ height: 10, width: 10, x: 0, y: 0 }) };
return { ...h, ctx };
};
@@ -537,8 +535,7 @@ describe('auto-created layer rollback (a gesture that commits nothing leaves no
expect(kinds(h)).toEqual(['addCanvasLayer', 'removeCanvasLayers', 'setCanvasSelectedLayer']);
const removal = h.dispatched[1]!;
expect(removal.type === 'removeCanvasLayers' && removal.ids).toEqual([h.createdIds[0]]);
- // The reducer's nearest-neighbour fallback would have picked the top layer, not
- // the image layer the user actually had selected.
+ // The reducer's nearest-neighbour fallback would have picked the top layer.
const reselect = h.dispatched[2]!;
expect(reselect.type === 'setCanvasSelectedLayer' && reselect.id).toBe('img1');
});
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 8477b4ed90..e9204115ed 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -152,19 +152,16 @@ const resolveTarget = (ctx: ToolContext): PaintTarget | null => {
const entry = ctx.layers.getOrCreateRect(layerId, { height: 0, width: 0, x: 0, y: 0 });
entry.stale = false;
return {
- // This dispatch happens at pointer-DOWN, before a single pixel exists, and it
- // is deliberately outside history (the stroke's own composed entry owns the
- // create+paint pair). So it needs a real transactional rollback, like the
- // control branch above: a gesture that commits nothing must leave no trace.
- // Reachable whenever `strokeSession.commit()` returns null — every stroke
- // point clipped away by the generation frame or the pixel selection — and from
- // pointercancel, a tool switch mid-drag, or a throwing session construction.
+ // The dispatch above happens at pointer-DOWN, before any pixel exists, and sits
+ // outside history (the stroke's composed entry owns the create+paint pair), so it
+ // needs a real rollback like the control branch's. Reached whenever
+ // `strokeSession.commit()` returns null — every point clipped away by the
+ // generation frame or the selection — plus pointercancel and a mid-drag switch.
cancel: () => {
ctx.layers.delete(layerId);
ctx.dispatch({ ids: [layerId], type: 'removeCanvasLayers' });
- // Removing the top layer would otherwise leave the reducer's generic
- // "nearest remaining neighbour" fallback selecting whatever sits at the top,
- // not the layer the user actually had selected when the gesture began.
+ // 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' });
}