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 layer export guards from the engine
joshistoast73ea014d9cf8
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex c1c5c0724b..0e20e71b06 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -193,6 +193,7 @@ import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';import { createBitmapStore, type BitmapStore } from './document/bitmapStore';import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';+import { createLayerExportGuards, isDeeplyEqual, isSupportedExportSource } from './layerExportGuards';import { createPreviewPublisher } from './previewPublisher';import { createSelectObjectBridge } from './selectObjectBridge';import { createStrokeCommit } from './strokeCommit';@@ -234,35 +235,6 @@ const createCleanupAccumulator = (): { run: (step: () => void) => void; throwIfF};};-/** Structural equality for JSON-safe canvas contracts (including synthetic mask paint sources). */-const isDeeplyEqual = (left: unknown, right: unknown): boolean => {- if (Object.is(left, right)) {- return true;- }- if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) {- return false;- }- if (Array.isArray(left) || Array.isArray(right)) {- return (- Array.isArray(left) &&- Array.isArray(right) &&- left.length === right.length &&- left.every((value, index) => isDeeplyEqual(value, right[index]))- );- }- const leftRecord = left as Record<string, unknown>;- const rightRecord = right as Record<string, unknown>;- const leftKeys = Object.keys(leftRecord);- const rightKeys = Object.keys(rightRecord);- return (- leftKeys.length === rightKeys.length &&- leftKeys.every(- (key) =>- Object.prototype.hasOwnProperty.call(rightRecord, key) && isDeeplyEqual(leftRecord[key], rightRecord[key])- )- );-};-export interface CanvasEngineErrorReport {area: 'canvas-engine';context: { error: string; layerId: string };@@ -1017,24 +989,21 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCstore: layerCache,});- const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean => {- if (source.type === 'shape') {- return source.kind !== 'polygon';- }- return true;- };-- const isCurrentRasterizationJob = (layer: CanvasLayerContract): boolean => {- const job = rasterController.getRasterizationJob(layer.id);- const source = renderableSourceOf(layer);- return (- !!job &&- !!source &&- job.version === layerCache.version(layer.id) &&- job.documentGeneration === rasterController.getDocumentGeneration() &&- isDeeplyEqual(job.source, source)- );- };+ const {+ captureCurrentLayerExportGuard,+ captureLayerExportGuard,+ hasExportableLayerContent,+ isCurrentRasterizationJob,+ isLayerExportGuardCurrent,+ } = createLayerExportGuards({+ getDocument: () => mirror.getDocument(),+ getDocumentGeneration: () => rasterController.getDocumentGeneration(),+ getRasterizationJob: (layerId) => rasterController.getRasterizationJob(layerId),+ hasCanvasState: () => mutationPort.getCanvasState() !== null,+ isDisposed: () => disposed,+ layerCache,+ projectId,+ });/*** Starts (or joins) an isolated rasterization. Pixels land in a scratch@@ -1195,49 +1164,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCreturn promise;};- const captureLayerExportGuard = (layer: CanvasLayerContract, entry: LayerCacheEntry): LayerExportGuard => ({- cacheVersion: entry.version,- documentGeneration: rasterController.getDocumentGeneration(),- layer,- layerId: layer.id,- projectId,- });-- const isLayerExportGuardCurrent = (guard: LayerExportGuard): boolean => {- if (- disposed ||- guard.projectId !== projectId ||- mutationPort.getCanvasState() === null ||- guard.documentGeneration !== rasterController.getDocumentGeneration()- ) {- return false;- }- const document = mirror.getDocument();- const liveLayer = document?.layers.find((candidate) => candidate.id === guard.layerId);- const entry = layerCache.get(guard.layerId);- return !!entry && liveLayer === guard.layer && entry.version === guard.cacheVersion;- };-- const captureCurrentLayerExportGuard = (layerId: string): LayerExportGuard | null => {- const document = mirror.getDocument();- const layer = document?.layers.find((candidate) => candidate.id === layerId);- const source = layer ? renderableSourceOf(layer) : null;- const entry = layerCache.get(layerId);- if (- !layer ||- !source ||- !isSupportedExportSource(source) ||- !entry ||- entry.stale ||- isCurrentRasterizationJob(layer) ||- isEmpty(entry.rect)- ) {- return null;- }- const guard = captureLayerExportGuard(layer, entry);- return isLayerExportGuardCurrent(guard) ? guard : null;- };-const documentEditOwner = Symbol('canvas-operation-document-edit-owner');// Later-defined engine values (mirror, pipeline, prepared-cache helpers) are// passed as thunks: the context never invokes them during construction.@@ -1287,29 +1213,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}};- const hasExportableLayerContent = (layerId: string): boolean => {- const doc = mirror.getDocument();- const layer = doc?.layers.find((candidate) => candidate.id === layerId);- if (!doc || !layer) {- return false;- }- const source = renderableSourceOf(layer);- if (!source || !isSupportedExportSource(source)) {- return false;- }- if (!isEmpty(getSourceContentRect(layer, doc))) {- return true;- }- // Only paint-backed layers (including masks through renderableSourceOf) can- // have real pixels beyond their persisted source rect. The live cache must- // describe the current source revision and must not be mid-rasterization.- if (source.type !== 'paint') {- return false;- }- const entry = layerCache.get(layerId);- return !!entry && !entry.stale && !isCurrentRasterizationJob(layer) && !isEmpty(entry.rect);- };-const rasterExportController = new RasterExportController({backend,captureGuard: captureLayerExportGuard,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.test.tsnew file mode 100644index 0000000000..d453d6c03e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.test.ts@@ -0,0 +1,250 @@+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';+import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';+import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';++import { beforeEach, describe, expect, it } from 'vitest';++import {+ createLayerExportGuards,+ isDeeplyEqual,+ isSupportedExportSource,+ type CreateLayerExportGuardsDeps,+ type LayerExportGuards,+} from './layerExportGuards';++const imageSource = (imageName = 'a.png'): CanvasLayerSourceContract =>+ ({ image: { height: 4, imageName, width: 4 }, type: 'image' }) as CanvasLayerSourceContract;++const layerOf = (source: CanvasLayerSourceContract, id = 'layer-1'): CanvasLayerContract =>+ ({ id, isEnabled: true, isLocked: false, name: id, source, type: 'raster' }) as CanvasLayerContract;++const entryOf = (overrides: Partial<LayerCacheEntry> = {}): LayerCacheEntry =>+ ({+ layerId: 'layer-1',+ rect: { height: 4, width: 4, x: 0, y: 0 },+ stale: false,+ version: 7,+ ...overrides,+ }) as LayerCacheEntry;++/** A cache store backed by one entry, which is all any guard reads. */+const cacheOf = (entry: LayerCacheEntry | undefined): LayerCacheStore =>+ ({+ get: (id: string) => (id === entry?.layerId ? entry : undefined),+ version: (id: string) => (id === entry?.layerId ? entry.version : 0),+ }) as unknown as LayerCacheStore;++let layer: CanvasLayerContract;+let entry: LayerCacheEntry;+let generation: number;+let job: RasterizationJob | undefined;+let disposed: boolean;+let canvasState: boolean;++const build = (overrides: Partial<CreateLayerExportGuardsDeps> = {}): LayerExportGuards =>+ createLayerExportGuards({+ getDocument: () => ({ height: 64, layers: [layer], width: 64 }) as CanvasDocumentContractV2,+ getDocumentGeneration: () => generation,+ getRasterizationJob: () => job,+ hasCanvasState: () => canvasState,+ isDisposed: () => disposed,+ layerCache: cacheOf(entry),+ projectId: 'project-1',+ ...overrides,+ });++beforeEach(() => {+ layer = layerOf(imageSource());+ entry = entryOf();+ generation = 3;+ job = undefined;+ disposed = false;+ canvasState = true;+});++describe('isSupportedExportSource', () => {+ it.each([+ ['image', imageSource(), true],+ ['rect shape', { height: 4, kind: 'rect', type: 'shape', width: 4 } as CanvasLayerSourceContract, true],+ ['polygon shape', { kind: 'polygon', points: [], type: 'shape' } as unknown as CanvasLayerSourceContract, false],+ ])('reports %s as %s', (_label, source, expected) => {+ expect(isSupportedExportSource(source)).toBe(expected);+ });+});++describe('isDeeplyEqual', () => {+ it('compares nested contract shapes structurally, not by identity', () => {+ expect(isDeeplyEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] })).toBe(true);+ expect(isDeeplyEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 3 }] })).toBe(false);+ });++ it('does not treat an object as equal to a superset of itself', () => {+ expect(isDeeplyEqual({ a: 1 }, { a: 1, b: 2 })).toBe(false);+ expect(isDeeplyEqual({ a: 1, b: 2 }, { a: 1 })).toBe(false);+ });++ it('distinguishes an array from a plain object with the same keys', () => {+ expect(isDeeplyEqual([1, 2], { 0: 1, 1: 2 })).toBe(false);+ });+});++describe('isCurrentRasterizationJob', () => {+ const jobFor = (overrides: Partial<RasterizationJob> = {}): RasterizationJob =>+ ({ documentGeneration: 3, source: imageSource(), version: 7, ...overrides }) as RasterizationJob;++ it('is false with no job in flight', () => {+ expect(build().isCurrentRasterizationJob(layer)).toBe(false);+ });++ it('is true when the job matches the layers source, cache version and generation', () => {+ job = jobFor();+ expect(build().isCurrentRasterizationJob(layer)).toBe(true);+ });++ it.each([+ ['the cache version has moved on', () => (job = jobFor({ version: 6 }))],+ ['the document generation has moved on', () => (job = jobFor({ documentGeneration: 2 }))],+ ['the source has been edited since the job started', () => (job = jobFor({ source: imageSource('other.png') }))],+ ])('is false once %s', (_label, arrange) => {+ arrange();+ expect(build().isCurrentRasterizationJob(layer)).toBe(false);+ });+});++describe('isLayerExportGuardCurrent', () => {+ const capture = (guards: LayerExportGuards = build()) => guards.captureLayerExportGuard(layer, entry);++ it('accepts a guard nothing has invalidated', () => {+ const guards = build();+ expect(guards.isLayerExportGuardCurrent(capture(guards))).toBe(true);+ });++ it('stamps the guard from the caller-supplied entry and the live generation', () => {+ expect(capture()).toMatchObject({+ cacheVersion: 7,+ documentGeneration: 3,+ layerId: 'layer-1',+ projectId: 'project-1',+ });+ });++ it.each([+ ['the engine has been disposed', () => (disposed = true)],+ ['the canvas state has been torn down', () => (canvasState = false)],+ ['the document generation has advanced', () => (generation = 4)],+ ['the cache entry has been re-versioned', () => (entry = entryOf({ version: 8 }))],+ ['the cache entry is gone', () => (entry = entryOf({ layerId: 'other' }))],+ ])('rejects a guard once %s', (_label, invalidate) => {+ const guard = capture();+ invalidate();+ expect(build().isLayerExportGuardCurrent(guard)).toBe(false);+ });++ it('rejects a guard whose layer object was replaced, even with identical fields', () => {+ const guard = capture();+ layer = layerOf(imageSource());+ expect(build().isLayerExportGuardCurrent(guard)).toBe(false);+ });++ it('rejects a guard stamped by a different project', () => {+ const guard = capture();+ expect(build({ projectId: 'project-2' }).isLayerExportGuardCurrent(guard)).toBe(false);+ });+});++describe('captureCurrentLayerExportGuard', () => {+ it('stamps a guard for a layer whose cached pixels are trustworthy', () => {+ expect(build().captureCurrentLayerExportGuard('layer-1')).toMatchObject({ cacheVersion: 7, layerId: 'layer-1' });+ });++ it.each([+ ['the layer is not in the document', () => 'missing-layer'],+ [+ 'the cache entry is stale',+ () => {+ entry = entryOf({ stale: true });+ return 'layer-1';+ },+ ],+ [+ 'the cached content rect is empty',+ () => {+ entry = entryOf({ rect: { height: 0, width: 0, x: 0, y: 0 } });+ return 'layer-1';+ },+ ],+ [+ 'a rasterization for the current source is still running',+ () => {+ job = { documentGeneration: 3, source: imageSource(), version: 7 } as RasterizationJob;+ return 'layer-1';+ },+ ],+ [+ 'the source has no rasterizer',+ () => {+ layer = layerOf({ kind: 'polygon', type: 'shape' } as unknown as CanvasLayerSourceContract);+ return 'layer-1';+ },+ ],+ ])('refuses when %s', (_label, arrange) => {+ const layerId = arrange();+ expect(build().captureCurrentLayerExportGuard(layerId)).toBeNull();+ });++ it('refuses when the entry exists but the guard it would stamp is already invalid', () => {+ // A torn-down canvas state fails the currency re-check the capture ends with.+ canvasState = false;+ expect(build().captureCurrentLayerExportGuard('layer-1')).toBeNull();+ });+});++describe('hasExportableLayerContent', () => {+ it('is true for a source whose declared content rect is non-empty', () => {+ expect(build().hasExportableLayerContent('layer-1')).toBe(true);+ });++ it('is false for a layer the document does not hold', () => {+ expect(build().hasExportableLayerContent('missing-layer')).toBe(false);+ });++ it('is false for a source with no rasterizer, however much it is cached', () => {+ layer = layerOf({ kind: 'polygon', type: 'shape' } as unknown as CanvasLayerSourceContract);+ expect(build().hasExportableLayerContent('layer-1')).toBe(false);+ });++ describe('a paint layer with nothing persisted', () => {+ beforeEach(() => {+ layer = layerOf({ bitmap: null, type: 'paint' } as unknown as CanvasLayerSourceContract);+ });++ it('is true when the live cache holds unflushed strokes', () => {+ expect(build().hasExportableLayerContent('layer-1')).toBe(true);+ });++ it.each([+ ['the cache is stale', () => (entry = entryOf({ stale: true }))],+ ['the cache is empty', () => (entry = entryOf({ rect: { height: 0, width: 0, x: 0, y: 0 } }))],+ [+ 'those pixels are still being rasterized',+ () =>+ (job = { documentGeneration: 3, source: { bitmap: null, type: 'paint' }, version: 7 } as RasterizationJob),+ ],+ ])('is false when %s', (_label, arrange) => {+ arrange();+ expect(build().hasExportableLayerContent('layer-1')).toBe(false);+ });+ });++ it('is false for a non-paint source with an empty content rect, cache notwithstanding', () => {+ // Only paint can hold pixels beyond its persisted rect, so the live cache is+ // not consulted here — this layer has a fresh, non-empty one and still fails.+ layer = layerOf({ image: { height: 0, imageName: 'a.png', width: 0 }, type: 'image' } as CanvasLayerSourceContract);+ expect(entry.stale).toBe(false);+ expect(build().hasExportableLayerContent('layer-1')).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.tsnew file mode 100644index 0000000000..6ad89cf6f2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts@@ -0,0 +1,171 @@+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';+import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';+import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';++import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';+import { isEmpty } from '@workbench/canvas-engine/math/rect';++/** Structural equality for JSON-safe canvas contracts (including synthetic mask paint sources). */+export const isDeeplyEqual = (left: unknown, right: unknown): boolean => {+ if (Object.is(left, right)) {+ return true;+ }+ if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) {+ return false;+ }+ if (Array.isArray(left) || Array.isArray(right)) {+ return (+ Array.isArray(left) &&+ Array.isArray(right) &&+ left.length === right.length &&+ left.every((value, index) => isDeeplyEqual(value, right[index]))+ );+ }+ const leftRecord = left as Record<string, unknown>;+ const rightRecord = right as Record<string, unknown>;+ const leftKeys = Object.keys(leftRecord);+ const rightKeys = Object.keys(rightRecord);+ return (+ leftKeys.length === rightKeys.length &&+ leftKeys.every(+ (key) =>+ Object.prototype.hasOwnProperty.call(rightRecord, key) && isDeeplyEqual(leftRecord[key], rightRecord[key])+ )+ );+};++/** Polygon shapes have no raster path, so they can never back an export. */+export const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean => {+ if (source.type === 'shape') {+ return source.kind !== 'polygon';+ }+ return true;+};++export interface CreateLayerExportGuardsDeps {+ readonly projectId: string;+ readonly layerCache: LayerCacheStore;+ readonly isDisposed: () => boolean;+ readonly hasCanvasState: () => boolean;+ readonly getDocumentGeneration: () => number;+ readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly getRasterizationJob: (layerId: string) => RasterizationJob | undefined;+}++export interface LayerExportGuards {+ /** True while a rasterization for this layer's *current* source and cache version is running. */+ isCurrentRasterizationJob(layer: CanvasLayerContract): boolean;+ /** Stamps a guard from a layer and cache entry the caller already holds. */+ captureLayerExportGuard(layer: CanvasLayerContract, entry: LayerCacheEntry): LayerExportGuard;+ /** True when everything the guard was stamped against is still exactly as it was. */+ isLayerExportGuardCurrent(guard: LayerExportGuard): boolean;+ /** Stamps a guard for a layer, or `null` if its pixels are not trustworthy right now. */+ captureCurrentLayerExportGuard(layerId: string): LayerExportGuard | null;+ /** True when the layer has pixels an export would actually find. */+ hasExportableLayerContent(layerId: string): boolean;+}++/**+ * The engine's answer to "are this layer's cached pixels trustworthy right now?"+ *+ * Every async commit in the engine — filter, generation, SAM, merge, export —+ * captures a guard before it starts and re-checks it before it publishes. The+ * guard is deliberately identity-based: it holds the layer *object* the caller+ * saw, so any mutation that replaces the contract invalidates it even when the+ * id and the pixels are unchanged. Cache version, document generation and+ * project id cover the rest, and disposal or a torn-down canvas state+ * invalidates everything at once.+ */+export const createLayerExportGuards = (deps: CreateLayerExportGuardsDeps): LayerExportGuards => {+ const { layerCache } = deps;++ const isCurrentRasterizationJob = (layer: CanvasLayerContract): boolean => {+ const job = deps.getRasterizationJob(layer.id);+ const source = renderableSourceOf(layer);+ return (+ !!job &&+ !!source &&+ job.version === layerCache.version(layer.id) &&+ job.documentGeneration === deps.getDocumentGeneration() &&+ isDeeplyEqual(job.source, source)+ );+ };++ const captureLayerExportGuard = (layer: CanvasLayerContract, entry: LayerCacheEntry): LayerExportGuard => ({+ cacheVersion: entry.version,+ documentGeneration: deps.getDocumentGeneration(),+ layer,+ layerId: layer.id,+ projectId: deps.projectId,+ });++ const isLayerExportGuardCurrent = (guard: LayerExportGuard): boolean => {+ if (+ deps.isDisposed() ||+ guard.projectId !== deps.projectId ||+ !deps.hasCanvasState() ||+ guard.documentGeneration !== deps.getDocumentGeneration()+ ) {+ return false;+ }+ const document = deps.getDocument();+ const liveLayer = document?.layers.find((candidate) => candidate.id === guard.layerId);+ const entry = layerCache.get(guard.layerId);+ return !!entry && liveLayer === guard.layer && entry.version === guard.cacheVersion;+ };++ return {+ captureCurrentLayerExportGuard: (layerId) => {+ const document = deps.getDocument();+ const layer = document?.layers.find((candidate) => candidate.id === layerId);+ const source = layer ? renderableSourceOf(layer) : null;+ const entry = layerCache.get(layerId);+ if (+ !layer ||+ !source ||+ !isSupportedExportSource(source) ||+ !entry ||+ entry.stale ||+ isCurrentRasterizationJob(layer) ||+ isEmpty(entry.rect)+ ) {+ return null;+ }+ const guard = captureLayerExportGuard(layer, entry);+ return isLayerExportGuardCurrent(guard) ? guard : null;+ },++ captureLayerExportGuard,++ hasExportableLayerContent: (layerId) => {+ const doc = deps.getDocument();+ const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ if (!doc || !layer) {+ return false;+ }+ const source = renderableSourceOf(layer);+ if (!source || !isSupportedExportSource(source)) {+ return false;+ }+ if (!isEmpty(getSourceContentRect(layer, doc))) {+ return true;+ }+ // Only paint-backed layers (including masks through renderableSourceOf) can+ // have real pixels beyond their persisted source rect. The live cache must+ // describe the current source revision and must not be mid-rasterization.+ if (source.type !== 'paint') {+ return false;+ }+ const entry = layerCache.get(layerId);+ return !!entry && !entry.stale && !isCurrentRasterizationJob(layer) && !isEmpty(entry.rect);+ },++ isCurrentRasterizationJob,+ isLayerExportGuardCurrent,+ };+};