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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(webv2): extract the per-layer change decision from the mirror
joshistoast2b81d79a925d
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.tsnew file mode 100644index 0000000000..c81cbf790e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.test.ts@@ -0,0 +1,150 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';++import { getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';+import { describe, expect, it, vi } from 'vitest';++import { decideLayerChange, type LayerChangeInput } from './layerChangeDecision';++const layerOf = (overrides: Record<string, unknown> = {}): CanvasLayerContract =>+ ({+ id: 'a',+ isEnabled: true,+ name: 'a',+ opacity: 1,+ source: { image: { height: 8, imageName: 'a.png', width: 8 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ ...overrides,+ }) as unknown as CanvasLayerContract;++const decide = (overrides: Partial<LayerChangeInput> = {}) =>+ decideLayerChange({+ currentThumbnailKey: undefined,+ currentThumbnailVersion: undefined,+ hasTextEditSession: false,+ hasTransformSession: false,+ isSelfEcho: () => false,+ layer: layerOf(),+ previousImageName: undefined,+ sourceChanged: false,+ ...overrides,+ });++describe('a layer that is gone', () => {+ it('is reported removed', () => {+ expect(decide({ layer: undefined }).kind).toBe('removed');+ });++ it('releases the image it referenced', () => {+ expect(decide({ layer: undefined, previousImageName: 'old.png' })).toMatchObject({+ releaseImageName: 'old.png',+ });+ });++ it('releases nothing when it referenced no image', () => {+ expect(decide({ layer: undefined })).toMatchObject({ releaseImageName: null });+ });++ it.each([+ ['transform', { hasTransformSession: true }, 'cancelTransformSession'],+ ['text-edit', { hasTextEditSession: true }, 'cancelTextEditSession'],+ ])('tears down an open %s session belonging to it', (_label, session, field) => {+ // A session outlives individual gestures, so it can outlive its own layer —+ // deleted from the layers panel, or undone — and must not be left pointing+ // at an id that no longer exists.+ expect(decide({ layer: undefined, ...session })).toMatchObject({ [field]: true });+ });++ it('leaves a session belonging to another layer alone', () => {+ expect(decide({ layer: undefined })).toMatchObject({+ cancelTextEditSession: false,+ cancelTransformSession: false,+ });+ });++ it('is removed even when its source also changed', () => {+ expect(decide({ layer: undefined, sourceChanged: true }).kind).toBe('removed');+ });+});++describe('a change that left the source alone', () => {+ it('never invalidates the cache', () => {+ // Invalidating here is wasteful for an image layer and destructive for an+ // unflushed paint layer, whose `bitmap: null` source rasterizes to a cleared+ // surface and would wipe strokes still only in the cache.+ expect(decide().kind).toBe('appearance-only');+ });++ it('records nothing when the layer looks exactly as it did', () => {+ const layer = layerOf();+ const decision = decide({ currentThumbnailKey: getLayerThumbnailDisplayKey(layer), layer });+ expect(decision).toEqual({ kind: 'appearance-only', thumbnailDisplay: null });+ });++ it('re-keys the thumbnail when the layer looks different', () => {+ const layer = layerOf({ opacity: 0.5 });+ const decision = decide({ currentThumbnailKey: 'stale-key', layer });+ expect(decision).toMatchObject({+ thumbnailDisplay: { key: getLayerThumbnailDisplayKey(layer) },+ });+ });++ it('tokens the first appearance change negative so it cannot collide with a cache version', () => {+ // Cache versions are positive; a negative token can never be mistaken for+ // one and suppress the redraw that follows the next publication.+ expect(decide({ currentThumbnailKey: 'stale-key' })).toMatchObject({+ thumbnailDisplay: { version: -1 },+ });+ });++ it('steps further negative on each subsequent appearance change', () => {+ expect(decide({ currentThumbnailKey: 'stale-key', currentThumbnailVersion: -3 })).toMatchObject({+ thumbnailDisplay: { version: -4 },+ });+ });++ it('starts a fresh negative token when the recorded version is a real cache version', () => {+ expect(decide({ currentThumbnailKey: 'stale-key', currentThumbnailVersion: 7 })).toMatchObject({+ thumbnailDisplay: { version: -1 },+ });+ });++ it('never asks whether the change was a self-echo', () => {+ const isSelfEcho = vi.fn(() => false);+ decide({ currentThumbnailKey: 'stale-key', isSelfEcho });+ expect(isSelfEcho).not.toHaveBeenCalled();+ });+});++describe('a genuine source swap', () => {+ it('invalidates the cache so the new source is rasterized', () => {+ expect(decide({ sourceChanged: true })).toMatchObject({ invalidateCache: true, kind: 'source-changed' });+ });++ it('does not invalidate the bitmap store’s own echo', () => {+ // The cache already holds exactly those pixels; re-rasterizing would refetch+ // them and risk a flicker.+ expect(decide({ isSelfEcho: () => true, sourceChanged: true })).toMatchObject({ invalidateCache: false });+ });++ it('re-keys the thumbnail without a display token', () => {+ const layer = layerOf({ source: { image: { height: 8, imageName: 'b.png', width: 8 }, type: 'image' } });+ const decision = decide({ layer, sourceChanged: true });+ expect(decision).toMatchObject({ thumbnailKey: getLayerThumbnailDisplayKey(layer) });+ });++ it('releases the image it previously referenced, echo or not', () => {+ expect(decide({ previousImageName: 'old.png', sourceChanged: true })).toMatchObject({+ releaseImageName: 'old.png',+ });+ expect(decide({ isSelfEcho: () => true, previousImageName: 'old.png', sourceChanged: true })).toMatchObject({+ releaseImageName: 'old.png',+ });+ });++ it('re-keys the thumbnail even for an echo it will not re-rasterize', () => {+ expect(decide({ isSelfEcho: () => true, sourceChanged: true })).toMatchObject({+ thumbnailKey: expect.any(String),+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.tsnew file mode 100644index 0000000000..1d8e55e9b2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerChangeDecision.ts@@ -0,0 +1,105 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';++import { getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';++/** The display token given to a thumbnail whose appearance changed without its pixels. */+const FIRST_DISPLAY_TOKEN = -1;++export interface LayerChangeInput {+ /** The layer as it now stands, or `undefined` when it is no longer in the document. */+ readonly layer: CanvasLayerContract | undefined;+ /** Whether the mirror reported this layer's SOURCE reference as changed. */+ readonly sourceChanged: boolean;+ /** The image this layer referenced before the change, if any. */+ readonly previousImageName: string | null | undefined;+ /** The display key recorded for this layer's last-rendered thumbnail. */+ readonly currentThumbnailKey: string | undefined;+ /** The version recorded for this layer's thumbnail, if any. */+ readonly currentThumbnailVersion: number | undefined;+ /** Whether an open transform session belongs to this layer. */+ readonly hasTransformSession: boolean;+ /** Whether an open text-edit session belongs to this layer. */+ readonly hasTextEditSession: boolean;+ /**+ * Whether this source swap is the bitmap store's own echo. Lazy because it is+ * only ever asked on the source-changed path, and answering costs a lookup.+ */+ readonly isSelfEcho: () => boolean;+}++export type LayerChangeDecision =+ | {+ readonly kind: 'removed';+ readonly releaseImageName: string | null;+ readonly cancelTransformSession: boolean;+ readonly cancelTextEditSession: boolean;+ }+ | {+ readonly kind: 'appearance-only';+ /** The new display key and the token to record, or `null` when it did not change. */+ readonly thumbnailDisplay: { key: string; version: number } | null;+ }+ | {+ readonly kind: 'source-changed';+ readonly thumbnailKey: string;+ readonly releaseImageName: string | null;+ /** `false` when the swap is the bitmap store's own echo, whose pixels the cache already holds. */+ readonly invalidateCache: boolean;+ };++/**+ * What has to happen to one layer's engine-side state after the document+ * changed it. Pure: the caller performs the effects in loop order.+ *+ * The three outcomes are genuinely different, and conflating them has real+ * costs. A prop or transform change — opacity, blend, lock, visibility, rename,+ * nudge — replaces the layer object while leaving its SOURCE reference intact,+ * so the rasterized pixels remain valid. Invalidating there would be wasteful+ * for an image layer and *destructive* for an unflushed paint layer, whose+ * `bitmap: null` source rasterizes to a cleared surface and would wipe strokes+ * that live only in the cache until their debounced upload lands. The+ * compositor applies transform, opacity and blend at draw time, so a recomposite+ * is all such a change needs.+ *+ * A genuine source swap does invalidate — unless it is the echo of a write the+ * bitmap store just made, where the cache already holds exactly those pixels and+ * re-rasterizing would re-fetch them and risk a flicker.+ */+export const decideLayerChange = (input: LayerChangeInput): LayerChangeDecision => {+ const { layer, previousImageName } = input;+ const releaseImageName = previousImageName ?? null;++ if (!layer) {+ return {+ cancelTextEditSession: input.hasTextEditSession,+ cancelTransformSession: input.hasTransformSession,+ kind: 'removed',+ releaseImageName,+ };+ }++ if (!input.sourceChanged) {+ const key = getLayerThumbnailDisplayKey(layer);+ if (key === input.currentThumbnailKey) {+ return { kind: 'appearance-only', thumbnailDisplay: null };+ }+ // Cache versions are positive, so a negative display token can never collide+ // with the next cache publication and suppress its redraw. Each further+ // appearance change steps further negative rather than resetting.+ const current = input.currentThumbnailVersion;+ return {+ kind: 'appearance-only',+ thumbnailDisplay: {+ key,+ version: current !== undefined && current < 0 ? current - 1 : FIRST_DISPLAY_TOKEN,+ },+ };+ }++ return {+ invalidateCache: !input.isSelfEcho(),+ kind: 'source-changed',+ releaseImageName,+ thumbnailKey: getLayerThumbnailDisplayKey(layer),+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 3d21576d29..60e92bbb63 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -176,6 +176,7 @@ import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';import { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';+import { decideLayerChange } from './document/layerChangeDecision';import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';import { createLayerExportGuards, isDeeplyEqual, isSupportedExportSource } from './layerExportGuards';import { createLayerRasterizer } from './layerRasterizer';@@ -1349,7 +1350,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCfor (const id of ids) {cleanup.run(() => editingController.invalidateLayer(id));}- const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);const sourceChanged = new Set(sourceChangedIds);const previousImageNames = new Map(ids.map((id) => [id, rasterController.getMirroredImage(id)]));for (const id of ids) {@@ -1371,13 +1371,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst session = stores.transformSession.get();const textSession = stores.textEditSession.get();for (const id of ids) {- const layer = doc?.layers.find((candidate) => candidate.id === id);- if (!present.has(id)) {+ const decision = decideLayerChange({+ currentThumbnailKey: rasterController.getThumbnailKey(id),+ currentThumbnailVersion: stores.thumbnailVersion.get(id),+ hasTextEditSession: textSession?.layerId === id,+ hasTransformSession: session?.layerId === id,+ isSelfEcho: () => bitmapStore.isSelfEcho(id, getLayerSourceById(id)),+ layer: doc?.layers.find((candidate) => candidate.id === id),+ previousImageName: previousImageNames.get(id),+ sourceChanged: sourceChanged.has(id),+ });+ if (decision.kind === 'removed') {+ const { releaseImageName } = decision;rasterController.deleteThumbnailKey(id);cleanup.run(() => dropLayer(id));- const previousImageName = previousImageNames.get(id);- if (previousImageName) {- cleanup.run(() => releaseBitmapIfUnreferenced(previousImageName));+ if (releaseImageName) {+ cleanup.run(() => releaseBitmapIfUnreferenced(releaseImageName));}// A control-filter preview (session + decoded surface) belongs to a// specific layer; a layer removed out from under an in-flight or@@ -1386,12 +1395,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// token bumped, or a late-resolving decode — or a later undo that// restores this same id — would repopulate a stale preview.cleanup.run(() => clearFilterPreview(id));- if (session && session.layerId === id) {+ if (decision.cancelTransformSession) {cleanup.run(cancelTransform);}- // An edit-mode text session whose layer was deleted out from under it- // (layers panel, or undo of the add) is torn down the same way.- if (textSession && textSession.layerId === id) {+ if (decision.cancelTextEditSession) {cleanup.run(cancelTextEdit);}continue;@@ -1400,49 +1407,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCif (preview && !isLayerExportGuardCurrent(preview.guard)) {cleanup.run(() => clearFilterPreview(id));}- if (!sourceChanged.has(id)) {- if (layer) {- const displayKey = getLayerThumbnailDisplayKey(layer);- if (rasterController.getThumbnailKey(id) !== displayKey) {- rasterController.setThumbnailKey(id, displayKey);- const currentVersion = stores.thumbnailVersion.get(id);- // Cache versions are positive. Negative display tokens cannot- // collide with the next cache publication and suppress its redraw.- stores.thumbnailVersion.set(- id,- currentVersion !== undefined && currentVersion < 0 ? currentVersion - 1 : -1- );- }+ if (decision.kind === 'appearance-only') {+ if (decision.thumbnailDisplay) {+ rasterController.setThumbnailKey(id, decision.thumbnailDisplay.key);+ stores.thumbnailVersion.set(id, decision.thumbnailDisplay.version);}- // Prop/transform-only change (opacity, blend, lock, visibility,- // rename, nudge): the layer object was replaced but its SOURCE- // reference is unchanged, so the rasterized pixels are still valid.- // Invalidating here would be wasteful for an image layer and- // *destructive* for an unflushed paint layer — a `bitmap: null` paint- // source rasterizes to a CLEARED surface, wiping strokes that live- // only in the cache until their debounced upload lands. The compositor- // applies transform/opacity/blend at draw time, so the scheduled- // recomposite below is all a prop change needs.continue;}- // The layer's source genuinely changed (image swap, or a paint-bitmap- // swap from undo/import). Self-echo guard: skip when it's the exact- // paint-bitmap ref the bitmap store just applied — the cache already- // holds those pixels, so re-rasterizing would needlessly re-fetch and- // could flicker. Any other swap invalidates → re-rasterizes.- if (layer) {- rasterController.setThumbnailKey(id, getLayerThumbnailDisplayKey(layer));- }+ const { releaseImageName } = decision;+ rasterController.setThumbnailKey(id, decision.thumbnailKey);cleanup.run(() => rasterController.untrackLayerImage(id));- const previousImageName = previousImageNames.get(id);- if (previousImageName) {- cleanup.run(() => releaseBitmapIfUnreferenced(previousImageName));+ if (releaseImageName) {+ cleanup.run(() => releaseBitmapIfUnreferenced(releaseImageName));}- const source = getLayerSourceById(id);- if (bitmapStore.isSelfEcho(id, source)) {- continue;+ if (decision.invalidateCache) {+ cleanup.run(() => invalidateLayerCache(id));}- cleanup.run(() => invalidateLayerCache(id));}cleanup.run(() => scheduler.invalidate({ layers: ids }));cleanup.throwIfFailed();