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 layer rasterization from the engine
joshistoast909f83c682d6
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex e45bb48179..6bc3b31011 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -120,7 +120,7 @@ import {} from '@workbench/canvas-engine/controllers/mutationContext';import { PersistenceController } from '@workbench/canvas-engine/controllers/persistenceController';import { PsdExportController } from '@workbench/canvas-engine/controllers/psdExportController';-import { RasterController, type RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';+import { RasterController } from '@workbench/canvas-engine/controllers/rasterController';import {RasterExportController,type ExportLayerPixelsResult,@@ -157,7 +157,6 @@ import { createMaskPatternTile } from '@workbench/canvas-engine/render/maskFill'import { renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';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 { textFontString } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';import { enforceSurfaceBudget } from '@workbench/canvas-engine/render/surfaceBudget';import { getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';import {@@ -195,6 +194,7 @@ 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 { createLayerRasterizer } from './layerRasterizer';import { createPreviewPublisher } from './previewPublisher';import { createRasterSnapshotCapture } from './rasterSnapshotCapture';import { createSelectObjectBridge } from './selectObjectBridge';@@ -1019,164 +1019,31 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCprojectId,});- /**- * Starts (or joins) an isolated rasterization. Pixels land in a scratch- * surface and are copied into the live cache only while this exact job still- * describes the current layer source, cache version, and document.- */- const getOrStartLayerRasterization = (- layer: CanvasLayerContract,- document: CanvasDocumentContractV2,- signal?: AbortSignal- ): Promise<'published' | 'stale' | 'error' | 'aborted'> => {- if (signal?.aborted) {- return Promise.resolve('aborted');- }- if (disposed || mutationPort.getCanvasState() === null) {- return Promise.resolve('stale');- }- const liveSource = renderableSourceOf(layer);- if (!liveSource || !isSupportedExportSource(liveSource)) {- return Promise.resolve('stale');- }-- const contentRect = getSourceContentRect(layer, document);- const entry = layerCache.getOrCreateRect(layer.id, contentRect);- const version = entry.version;- const documentGeneration = rasterController.getDocumentGeneration();- const source = structuredClone(liveSource);- const existing = rasterController.getRasterizationJob(layer.id);- if (- existing &&- existing.version === version &&- existing.documentGeneration === documentGeneration &&- isDeeplyEqual(existing.source, source)- ) {- if (!signal) {- return existing.promise;- }- const abort = (): void => {- existing.abortedByCaller = true;- existing.controller.abort(signal.reason);- };- signal.addEventListener('abort', abort, { once: true });- return existing.promise.finally(() => signal.removeEventListener('abort', abort));- }- cancelLayerRasterization(layer.id);-- if (source.type === 'text') {- fontLoader.ensure(textFontString(source), () => {- const currentDocument = mirror.getDocument();- const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layer.id);- if (- disposed ||- mutationPort.getCanvasState() === null ||- !currentLayer ||- rasterController.getDocumentGeneration() !== documentGeneration ||- layerCache.version(layer.id) !== version ||- !isDeeplyEqual(renderableSourceOf(currentLayer), source)- ) {- return;- }- invalidateLayerCache(layer.id);- scheduler.invalidate({ layers: [layer.id] });- });- }-- const scratch = backend.createSurface(contentRect.width, contentRect.height);- const controller = new AbortController();- let settleJob!: (result: 'published' | 'stale' | 'error' | 'aborted') => void;- const promise = new Promise<'published' | 'stale' | 'error' | 'aborted'>((resolve) => {- settleJob = resolve;- });- const job: RasterizationJob = {- controller,- documentGeneration,- promise,- source,- version,- };- const abort = (): void => {- job.abortedByCaller = true;- controller.abort(signal?.reason);- };- signal?.addEventListener('abort', abort, { once: true });- rasterController.installRasterizationJob(layer.id, job);- let published = false;- void (async () => {- try {- const result = await rasterizeSource(source, rasterizeDeps(document, controller.signal), scratch);- const currentDocument = mirror.getDocument();- const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layer.id);- const currentEntry = layerCache.get(layer.id);- if (- disposed ||- mutationPort.getCanvasState() === null ||- rasterController.getRasterizationJob(layer.id) !== job ||- rasterController.getDocumentGeneration() !== documentGeneration ||- !currentLayer ||- !currentEntry ||- currentEntry.version !== version ||- !isDeeplyEqual(renderableSourceOf(currentLayer), source)- ) {- return 'stale';- }-- if (currentEntry.surface.width !== result.rect.width || currentEntry.surface.height !== result.rect.height) {- currentEntry.surface.resize(result.rect.width, result.rect.height);- }- const ctx = currentEntry.surface.ctx;- ctx.setTransform(1, 0, 0, 1, 0, 0);- ctx.clearRect(0, 0, result.rect.width, result.rect.height);- if (!isEmpty(result.rect)) {- ctx.drawImage(result.surface.canvas, 0, 0);- }- currentEntry.rect = { ...result.rect };- const publishedEntry = layerCache.publishPixels(layer.id);- if (!publishedEntry) {- return 'stale';- }- trackPublishedLayerImage(currentLayer);- published = true;- stores.thumbnailVersion.set(layer.id, publishedEntry.version);- stores.thumbnailStatus.set(layer.id, 'ready');- scheduler.invalidate({ layers: [layer.id] });- return 'published';- } catch (error) {- if (job.abortedByCaller) {- return 'aborted';- }- const currentDocument = mirror.getDocument();- const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layer.id);- if (- disposed ||- mutationPort.getCanvasState() === null ||- rasterController.getRasterizationJob(layer.id) !== job ||- rasterController.getDocumentGeneration() !== documentGeneration ||- !currentLayer ||- layerCache.version(layer.id) !== version ||- !isDeeplyEqual(renderableSourceOf(currentLayer), source)- ) {- return 'stale';- }- stores.thumbnailStatus.set(layer.id, 'error');- try {- reportError('Layer thumbnail rasterization failed', layer.id, error);- } catch {- // Diagnostics must not turn a handled thumbnail failure into a rejection.- }- return 'error';- } finally {- signal?.removeEventListener('abort', abort);- rasterController.finishRasterizationJob(layer.id, job);- const imageName = sourceImageName(source);- if (!published && imageName) {- releaseBitmapIfUnreferenced(imageName);- }- }- })().then(settleJob, () => settleJob('stale'));- return promise;- };+ const { getOrStartLayerRasterization } = createLayerRasterizer({+ createSurface: (width, height) => backend.createSurface(width, height),+ fontLoader,+ getDocument: () => mirror.getDocument(),+ hasCanvasState: () => mutationPort.getCanvasState() !== null,+ invalidateLayerCache,+ invalidateLayerRender: (layerId) => scheduler.invalidate({ layers: [layerId] }),+ isDisposed: () => disposed,+ jobs: {+ cancel: cancelLayerRasterization,+ finish: (layerId, job) => rasterController.finishRasterizationJob(layerId, job),+ get: (layerId) => rasterController.getRasterizationJob(layerId),+ getDocumentGeneration: () => rasterController.getDocumentGeneration(),+ install: (layerId, job) => rasterController.installRasterizationJob(layerId, job),+ },+ layerCache,+ rasterize: (source, document, scratch, signal) => rasterizeSource(source, rasterizeDeps(document, signal), scratch),+ releaseBitmapIfUnreferenced: (imageName) => rasterController.releaseBitmapIfUnreferenced(imageName),+ reportError,+ thumbnails: {+ setStatus: (layerId, status) => stores.thumbnailStatus.set(layerId, status),+ setVersion: (layerId, version) => stores.thumbnailVersion.set(layerId, version),+ },+ trackPublishedLayerImage: (layer) => rasterController.trackPublishedLayerImage(layer),+ });const documentEditOwner = Symbol('canvas-operation-document-edit-owner');// Later-defined engine values (mirror, pipeline, prepared-cache helpers) are@@ -1318,8 +1185,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst releaseBitmapIfUnreferenced = (imageName: string): void =>rasterController.releaseBitmapIfUnreferenced(imageName);- const trackPublishedLayerImage = (layer: CanvasLayerContract): void =>- rasterController.trackPublishedLayerImage(layer);const dropLayer = (layerId: string): void => {// Generation-cancel persistence before the id can be restored by undo/redo.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.tsnew file mode 100644index 0000000000..e63092e63a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts@@ -0,0 +1,392 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';+import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';++import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createLayerRasterizer, type CreateLayerRasterizerDeps } from './layerRasterizer';++const surface = (width = 4, height = 4): RasterSurface =>+ ({+ canvas: {},+ ctx: { clearRect: vi.fn(), drawImage: vi.fn(), setTransform: vi.fn() },+ height,+ resize: vi.fn(),+ width,+ }) as unknown as RasterSurface;++const rasterLayer = (overrides: Record<string, unknown> = {}): CanvasLayerContract =>+ ({+ id: 'layer-1',+ isEnabled: true,+ isLocked: false,+ name: 'Layer 1',+ source: { image: { height: 4, imageName: 'a.png', width: 4 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ ...overrides,+ }) as unknown as CanvasLayerContract;++const textLayer = (): CanvasLayerContract =>+ rasterLayer({+ source: {+ color: '#fff',+ content: 'hello',+ fontFamily: 'Inter',+ fontSize: 12,+ fontStyle: 'normal',+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ });++const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 =>+ ({ height: 64, layers, width: 64 }) as unknown as CanvasDocumentContractV2;++interface Harness {+ deps: CreateLayerRasterizerDeps;+ entry: LayerCacheEntry;+ installed: Map<string, RasterizationJob>;+ documentGeneration: { value: number };+ document: { value: CanvasDocumentContractV2 };+ state: { disposed: boolean; hasCanvas: boolean };+ rasterize: ReturnType<typeof vi.fn>;+ fontReady: (() => void) | null;+ spies: {+ cancel: ReturnType<typeof vi.fn>;+ invalidateLayerCache: ReturnType<typeof vi.fn>;+ invalidateLayerRender: ReturnType<typeof vi.fn>;+ releaseBitmapIfUnreferenced: ReturnType<typeof vi.fn>;+ reportError: ReturnType<typeof vi.fn>;+ setStatus: ReturnType<typeof vi.fn>;+ setVersion: ReturnType<typeof vi.fn>;+ trackPublishedLayerImage: ReturnType<typeof vi.fn>;+ };+}++let harness: Harness;++const makeHarness = (overrides: Partial<CreateLayerRasterizerDeps> = {}): Harness => {+ const entry = {+ layerId: 'layer-1',+ rect: { height: 4, width: 4, x: 0, y: 0 },+ surface: surface(),+ version: 3,+ } as unknown as LayerCacheEntry;+ const installed = new Map<string, RasterizationJob>();+ const documentGeneration = { value: 7 };+ const document = { value: documentOf([rasterLayer()]) };+ const state = { disposed: false, hasCanvas: true };+ const rasterize = vi.fn(() => Promise.resolve({ rect: { height: 4, width: 4, x: 0, y: 0 }, surface: surface() }));+ const spies = {+ cancel: vi.fn(),+ invalidateLayerCache: vi.fn(),+ invalidateLayerRender: vi.fn(),+ releaseBitmapIfUnreferenced: vi.fn(),+ reportError: vi.fn(),+ setStatus: vi.fn(),+ setVersion: vi.fn(),+ trackPublishedLayerImage: vi.fn(),+ };+ const result: Harness = {+ document,+ documentGeneration,+ entry,+ fontReady: null,+ installed,+ rasterize,+ spies,+ state,+ deps: {+ createSurface: (width, height) => surface(width, height),+ fontLoader: {+ ensure: (_font, onReady) => {+ result.fontReady = onReady;+ },+ },+ getDocument: () => document.value,+ hasCanvasState: () => state.hasCanvas,+ invalidateLayerCache: spies.invalidateLayerCache,+ invalidateLayerRender: spies.invalidateLayerRender,+ isDisposed: () => state.disposed,+ jobs: {+ cancel: spies.cancel,+ finish: (layerId, job) => {+ if (installed.get(layerId) === job) {+ installed.delete(layerId);+ }+ },+ get: (layerId) => installed.get(layerId),+ getDocumentGeneration: () => documentGeneration.value,+ install: (layerId, job) => installed.set(layerId, job),+ },+ layerCache: {+ get: vi.fn(() => entry),+ getOrCreateRect: vi.fn(() => entry),+ publishPixels: vi.fn(() => ({ ...entry, version: entry.version + 1 })),+ version: vi.fn(() => entry.version),+ } as unknown as CreateLayerRasterizerDeps['layerCache'],+ rasterize: rasterize as unknown as CreateLayerRasterizerDeps['rasterize'],+ releaseBitmapIfUnreferenced: spies.releaseBitmapIfUnreferenced,+ reportError: spies.reportError,+ thumbnails: { setStatus: spies.setStatus, setVersion: spies.setVersion },+ trackPublishedLayerImage: spies.trackPublishedLayerImage,+ ...overrides,+ },+ };+ return result;+};++beforeEach(() => {+ harness = makeHarness();+});++const start = (layer = rasterLayer(), signal?: AbortSignal) =>+ createLayerRasterizer(harness.deps).getOrStartLayerRasterization(layer, harness.document.value, signal);++describe('refusals before any work', () => {+ it('reports aborted for an already-aborted signal', async () => {+ const controller = new AbortController();+ controller.abort();+ await expect(start(rasterLayer(), controller.signal)).resolves.toBe('aborted');+ expect(harness.rasterize).not.toHaveBeenCalled();+ });++ it.each([+ ['the engine is disposed', (h: Harness) => (h.state.disposed = true)],+ ['there is no canvas state', (h: Harness) => (h.state.hasCanvas = false)],+ ])('reports stale when %s', async (_label, mutate) => {+ mutate(harness);+ await expect(start()).resolves.toBe('stale');+ expect(harness.rasterize).not.toHaveBeenCalled();+ });++ it('reports stale for a source it cannot rasterize', async () => {+ await expect(start(rasterLayer({ source: { kind: 'polygon', points: [], type: 'shape' } }))).resolves.toBe('stale');+ });+});++describe('job reuse', () => {+ it('joins an in-flight job describing the same source, version and generation', async () => {+ const rasterizer = createLayerRasterizer(harness.deps);+ const first = rasterizer.getOrStartLayerRasterization(rasterLayer(), harness.document.value);+ const second = rasterizer.getOrStartLayerRasterization(rasterLayer(), harness.document.value);+ expect(second).toBe(first);+ expect(harness.rasterize).toHaveBeenCalledTimes(1);+ await first;+ });++ it.each([+ ['the cache version moved', (h: Harness) => ((h.entry as { version: number }).version = 99)],+ ['the document generation moved', (h: Harness) => (h.documentGeneration.value += 1)],+ ])('restarts rather than joining once %s', async (_label, mutate) => {+ const rasterizer = createLayerRasterizer(harness.deps);+ const first = rasterizer.getOrStartLayerRasterization(rasterLayer(), harness.document.value);+ mutate(harness);+ const second = rasterizer.getOrStartLayerRasterization(rasterLayer(), harness.document.value);+ expect(second).not.toBe(first);+ expect(harness.spies.cancel).toHaveBeenCalledWith('layer-1');+ await Promise.all([first, second]);+ });++ it('restarts when the source changed by value even though nothing else did', async () => {+ const rasterizer = createLayerRasterizer(harness.deps);+ const first = rasterizer.getOrStartLayerRasterization(rasterLayer(), harness.document.value);+ const edited = rasterLayer({ source: { image: { height: 4, imageName: 'b.png', width: 4 }, type: 'image' } });+ const second = rasterizer.getOrStartLayerRasterization(edited, harness.document.value);+ expect(second).not.toBe(first);+ await Promise.all([first, second]);+ });++ it('cancels the shared job when a joining caller aborts, and unhooks its listener', async () => {+ const rasterizer = createLayerRasterizer(harness.deps);+ const first = rasterizer.getOrStartLayerRasterization(rasterLayer(), harness.document.value);+ const controller = new AbortController();+ const removeSpy = vi.spyOn(controller.signal, 'removeEventListener');+ const joined = rasterizer.getOrStartLayerRasterization(rasterLayer(), harness.document.value, controller.signal);+ const job = harness.installed.get('layer-1')!;+ controller.abort();+ expect(job.abortedByCaller).toBe(true);+ await Promise.all([first, joined]);+ expect(removeSpy).toHaveBeenCalled();+ });+});++describe('publishing', () => {+ it('writes the pixels, publishes, and reports the layer ready', async () => {+ await expect(start()).resolves.toBe('published');+ expect(harness.spies.trackPublishedLayerImage).toHaveBeenCalled();+ expect(harness.spies.setVersion).toHaveBeenCalledWith('layer-1', 4);+ expect(harness.spies.setStatus).toHaveBeenCalledWith('layer-1', 'ready');+ expect(harness.spies.invalidateLayerRender).toHaveBeenCalledWith('layer-1');+ });++ it('keeps the decoded bitmap it published', async () => {+ await start();+ expect(harness.spies.releaseBitmapIfUnreferenced).not.toHaveBeenCalled();+ });++ it('resizes the cache surface when the raster came back a different size', async () => {+ harness.rasterize.mockResolvedValue({ rect: { height: 8, width: 8, x: 0, y: 0 }, surface: surface(8, 8) });+ await start();+ expect(harness.entry.surface.resize).toHaveBeenCalledWith(8, 8);+ });++ it('clears but does not draw an empty result', async () => {+ harness.rasterize.mockResolvedValue({ rect: { height: 0, width: 0, x: 0, y: 0 }, surface: surface(0, 0) });+ await expect(start()).resolves.toBe('published');+ expect(harness.entry.surface.ctx.drawImage).not.toHaveBeenCalled();+ expect(harness.entry.surface.ctx.clearRect).toHaveBeenCalled();+ });++ it('copies the result rect rather than aliasing it', async () => {+ const rect = { height: 4, width: 4, x: 1, y: 2 };+ harness.rasterize.mockResolvedValue({ rect, surface: surface() });+ await start();+ expect(harness.entry.rect).toEqual(rect);+ expect(harness.entry.rect).not.toBe(rect);+ });++ it('reports stale when the cache refuses to publish', async () => {+ (harness.deps.layerCache.publishPixels as ReturnType<typeof vi.fn>).mockReturnValue(undefined);+ await expect(start()).resolves.toBe('stale');+ expect(harness.spies.setStatus).not.toHaveBeenCalled();+ });+});++describe('a result that no longer describes the live layer', () => {+ it.each([+ ['the engine was disposed', (h: Harness) => (h.state.disposed = true)],+ ['the canvas state went away', (h: Harness) => (h.state.hasCanvas = false)],+ ['the document generation moved', (h: Harness) => (h.documentGeneration.value += 1)],+ ['the layer was deleted', (h: Harness) => (h.document.value = documentOf([]))],+ [+ 'the layer source was edited',+ (h: Harness) =>+ (h.document.value = documentOf([+ rasterLayer({ source: { image: { height: 4, imageName: 'b.png', width: 4 }, type: 'image' } }),+ ])),+ ],+ [+ 'the cache entry was dropped',+ (h: Harness) => (h.deps.layerCache.get as ReturnType<typeof vi.fn>).mockReturnValue(undefined),+ ],+ [+ 'the cache version moved under it',+ (h: Harness) => (h.deps.layerCache.get as ReturnType<typeof vi.fn>).mockReturnValue({ ...h.entry, version: 99 }),+ ],+ ])('is dropped as stale once %s', async (_label, mutate) => {+ harness.rasterize.mockImplementation(() => {+ mutate(harness);+ return Promise.resolve({ rect: { height: 4, width: 4, x: 0, y: 0 }, surface: surface() });+ });+ await expect(start()).resolves.toBe('stale');+ expect(harness.spies.setVersion).not.toHaveBeenCalled();+ });++ it('is dropped as stale when a newer job replaced it', async () => {+ harness.rasterize.mockImplementation(() => {+ harness.installed.set('layer-1', { version: 999 } as unknown as RasterizationJob);+ return Promise.resolve({ rect: { height: 4, width: 4, x: 0, y: 0 }, surface: surface() });+ });+ await expect(start()).resolves.toBe('stale');+ });++ it('releases the bitmap it pulled in but never published', async () => {+ harness.rasterize.mockImplementation(() => {+ harness.state.disposed = true;+ return Promise.resolve({ rect: { height: 4, width: 4, x: 0, y: 0 }, surface: surface() });+ });+ await start();+ expect(harness.spies.releaseBitmapIfUnreferenced).toHaveBeenCalledWith('a.png');+ });+});++describe('failure', () => {+ it('marks the layer errored and reports it', async () => {+ harness.rasterize.mockRejectedValue(new Error('decode failed'));+ await expect(start()).resolves.toBe('error');+ expect(harness.spies.setStatus).toHaveBeenCalledWith('layer-1', 'error');+ expect(harness.spies.reportError).toHaveBeenCalledWith(+ 'Layer thumbnail rasterization failed',+ 'layer-1',+ expect.any(Error)+ );+ });++ it('still reports error when diagnostics itself throws', async () => {+ harness.rasterize.mockRejectedValue(new Error('decode failed'));+ harness.spies.reportError.mockImplementation(() => {+ throw new Error('diagnostics is down');+ });+ await expect(start()).resolves.toBe('error');+ });++ it('stays quiet about a failure whose layer has already moved on', async () => {+ harness.rasterize.mockImplementation(() => {+ harness.document.value = documentOf([]);+ return Promise.reject(new Error('decode failed'));+ });+ await expect(start()).resolves.toBe('stale');+ expect(harness.spies.reportError).not.toHaveBeenCalled();+ expect(harness.spies.setStatus).not.toHaveBeenCalled();+ });++ it.each([+ [+ 'the cache version moved on',+ (h: Harness) => (h.deps.layerCache.version as ReturnType<typeof vi.fn>).mockReturnValue(99),+ ],+ [+ 'the layer source was edited',+ (h: Harness) =>+ (h.document.value = documentOf([+ rasterLayer({ source: { image: { height: 4, imageName: 'b.png', width: 4 }, type: 'image' } }),+ ])),+ ],+ ])('stays quiet about a failure once %s', async (_label, mutate) => {+ harness.rasterize.mockImplementation(() => {+ mutate(harness);+ return Promise.reject(new Error('decode failed'));+ });+ await expect(start()).resolves.toBe('stale');+ expect(harness.spies.reportError).not.toHaveBeenCalled();+ expect(harness.spies.setStatus).not.toHaveBeenCalled();+ });++ it('reports aborted, not error, when the caller cancelled', async () => {+ const controller = new AbortController();+ harness.rasterize.mockImplementation(() => {+ controller.abort();+ return Promise.reject(new Error('aborted'));+ });+ await expect(start(rasterLayer(), controller.signal)).resolves.toBe('aborted');+ expect(harness.spies.reportError).not.toHaveBeenCalled();+ });+});++describe('text sources', () => {+ it('re-invalidates once the real font arrives', async () => {+ harness.document.value = documentOf([textLayer()]);+ await start(textLayer());+ expect(harness.fontReady).toBeTypeOf('function');+ harness.fontReady?.();+ expect(harness.spies.invalidateLayerCache).toHaveBeenCalledWith('layer-1');+ expect(harness.spies.invalidateLayerRender).toHaveBeenCalledWith('layer-1');+ });++ it('does not re-invalidate when the font arrives after the layer moved on', async () => {+ harness.document.value = documentOf([textLayer()]);+ await start(textLayer());+ harness.document.value = documentOf([]);+ harness.fontReady?.();+ expect(harness.spies.invalidateLayerCache).not.toHaveBeenCalled();+ });++ it('does not wait on fonts for a non-text source', async () => {+ await start();+ expect(harness.fontReady).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.tsnew file mode 100644index 0000000000..5a7ee9f604--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts@@ -0,0 +1,253 @@+import type {+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasLayerSourceContract,+} from '@workbench/canvas-engine/contracts';+import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';+import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { RasterizeResult } from '@workbench/canvas-engine/render/rasterizers';++import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';+import { isDeeplyEqual, isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';+import { isEmpty } from '@workbench/canvas-engine/math/rect';+import { textFontString } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';++/** How a rasterization ended: pixels landed, the world moved, it threw, or it was cancelled. */+export type LayerRasterizationOutcome = 'published' | 'stale' | 'error' | 'aborted';++/** The image a source references, whose decoded bitmap the job holds a reference to. */+const sourceImageName = (source: CanvasLayerSourceContract): string | null => {+ if (source.type === 'image') {+ return source.image.imageName;+ }+ if (source.type === 'paint') {+ return source.bitmap?.imageName ?? null;+ }+ return null;+};++/** The registry of in-flight rasterizations, keyed by layer. */+export interface RasterizationJobRegistry {+ getDocumentGeneration(): number;+ get(layerId: string): RasterizationJob | undefined;+ install(layerId: string, job: RasterizationJob): void;+ finish(layerId: string, job: RasterizationJob): void;+ cancel(layerId: string): void;+}++export interface CreateLayerRasterizerDeps {+ readonly layerCache: LayerCacheStore;+ readonly jobs: RasterizationJobRegistry;+ readonly thumbnails: {+ setVersion(layerId: string, version: number): void;+ setStatus(layerId: string, status: 'ready' | 'error'): void;+ };+ readonly fontLoader: { ensure(font: string, onReady: () => void): void };+ readonly createSurface: (width: number, height: number) => RasterSurface;+ readonly rasterize: (+ source: CanvasLayerSourceContract,+ document: CanvasDocumentContractV2,+ scratch: RasterSurface,+ signal: AbortSignal+ ) => Promise<RasterizeResult>;+ readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly hasCanvasState: () => boolean;+ readonly isDisposed: () => boolean;+ readonly invalidateLayerCache: (layerId: string) => void;+ readonly invalidateLayerRender: (layerId: string) => void;+ readonly trackPublishedLayerImage: (layer: CanvasLayerContract) => void;+ readonly releaseBitmapIfUnreferenced: (imageName: string) => void;+ readonly reportError: (message: 'Layer thumbnail rasterization failed', layerId: string, error: unknown) => void;+}++export interface LayerRasterizer {+ /**+ * Starts — or joins — the rasterization of one layer, resolving with how it+ * ended. Safe to call every frame: a job that already describes the same+ * source, cache version and document generation is shared, not restarted.+ */+ getOrStartLayerRasterization(+ layer: CanvasLayerContract,+ document: CanvasDocumentContractV2,+ signal?: AbortSignal+ ): Promise<LayerRasterizationOutcome>;+}++/**+ * Rasterizes a layer's source into its cache.+ *+ * Rasterizing is slow and the document is live, so a job never draws straight+ * into the cache: pixels land in a scratch surface, and are copied across only+ * if the job still describes the world it started in — same source (compared by+ * value, since a reducer pass replaces objects wholesale), same cache version,+ * same document generation, same job still installed, engine not disposed. Any+ * of those moving means the result describes a layer that no longer exists in+ * that form, and it is dropped as `'stale'` rather than published over whatever+ * replaced it.+ *+ * The same check appears three times and is deliberately not shared. The+ * post-success one holds the cache entry it is about to write to, so it can+ * distinguish a deleted cache from a fresh one at version 0 — the two are+ * indistinguishable through `version()` alone. The font-load one runs before+ * any job is installed, so it has no job identity to compare.+ *+ * Text is the one source that can rasterize correctly and still be wrong: the+ * font may not have loaded yet. Rather than block, it rasterizes with whatever+ * is available and re-invalidates once the real font arrives.+ */+export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasterizer => {+ const { jobs, layerCache } = deps;++ const getOrStartLayerRasterization = (+ layer: CanvasLayerContract,+ document: CanvasDocumentContractV2,+ signal?: AbortSignal+ ): Promise<LayerRasterizationOutcome> => {+ if (signal?.aborted) {+ return Promise.resolve('aborted');+ }+ if (deps.isDisposed() || !deps.hasCanvasState()) {+ return Promise.resolve('stale');+ }+ const liveSource = renderableSourceOf(layer);+ if (!liveSource || !isSupportedExportSource(liveSource)) {+ return Promise.resolve('stale');+ }++ const contentRect = getSourceContentRect(layer, document);+ const entry = layerCache.getOrCreateRect(layer.id, contentRect);+ const version = entry.version;+ const documentGeneration = jobs.getDocumentGeneration();+ const source = structuredClone(liveSource);+ const existing = jobs.get(layer.id);+ if (+ existing &&+ existing.version === version &&+ existing.documentGeneration === documentGeneration &&+ isDeeplyEqual(existing.source, source)+ ) {+ if (!signal) {+ return existing.promise;+ }+ // Joining with a signal must be able to cancel the shared job, but the+ // listener has to come off again or a long-lived signal accumulates them.+ const abort = (): void => {+ existing.abortedByCaller = true;+ existing.controller.abort(signal.reason);+ };+ signal.addEventListener('abort', abort, { once: true });+ return existing.promise.finally(() => signal.removeEventListener('abort', abort));+ }+ jobs.cancel(layer.id);++ if (source.type === 'text') {+ deps.fontLoader.ensure(textFontString(source), () => {+ const currentLayer = deps.getDocument()?.layers.find((candidate) => candidate.id === layer.id);+ if (+ deps.isDisposed() ||+ !deps.hasCanvasState() ||+ !currentLayer ||+ jobs.getDocumentGeneration() !== documentGeneration ||+ layerCache.version(layer.id) !== version ||+ !isDeeplyEqual(renderableSourceOf(currentLayer), source)+ ) {+ return;+ }+ deps.invalidateLayerCache(layer.id);+ deps.invalidateLayerRender(layer.id);+ });+ }++ const scratch = deps.createSurface(contentRect.width, contentRect.height);+ const controller = new AbortController();+ let settleJob!: (result: LayerRasterizationOutcome) => void;+ const promise = new Promise<LayerRasterizationOutcome>((resolve) => {+ settleJob = resolve;+ });+ const job: RasterizationJob = { controller, documentGeneration, promise, source, version };+ const abort = (): void => {+ job.abortedByCaller = true;+ controller.abort(signal?.reason);+ };+ signal?.addEventListener('abort', abort, { once: true });+ jobs.install(layer.id, job);+ let published = false;+ void (async () => {+ try {+ const result = await deps.rasterize(source, document, scratch, controller.signal);+ const currentLayer = deps.getDocument()?.layers.find((candidate) => candidate.id === layer.id);+ const currentEntry = layerCache.get(layer.id);+ if (+ deps.isDisposed() ||+ !deps.hasCanvasState() ||+ jobs.get(layer.id) !== job ||+ jobs.getDocumentGeneration() !== documentGeneration ||+ !currentLayer ||+ !currentEntry ||+ currentEntry.version !== version ||+ !isDeeplyEqual(renderableSourceOf(currentLayer), source)+ ) {+ return 'stale';+ }++ if (currentEntry.surface.width !== result.rect.width || currentEntry.surface.height !== result.rect.height) {+ currentEntry.surface.resize(result.rect.width, result.rect.height);+ }+ const ctx = currentEntry.surface.ctx;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, result.rect.width, result.rect.height);+ if (!isEmpty(result.rect)) {+ ctx.drawImage(result.surface.canvas, 0, 0);+ }+ currentEntry.rect = { ...result.rect };+ const publishedEntry = layerCache.publishPixels(layer.id);+ if (!publishedEntry) {+ return 'stale';+ }+ deps.trackPublishedLayerImage(currentLayer);+ published = true;+ deps.thumbnails.setVersion(layer.id, publishedEntry.version);+ deps.thumbnails.setStatus(layer.id, 'ready');+ deps.invalidateLayerRender(layer.id);+ return 'published';+ } catch (error) {+ if (job.abortedByCaller) {+ return 'aborted';+ }+ const currentLayer = deps.getDocument()?.layers.find((candidate) => candidate.id === layer.id);+ if (+ deps.isDisposed() ||+ !deps.hasCanvasState() ||+ jobs.get(layer.id) !== job ||+ jobs.getDocumentGeneration() !== documentGeneration ||+ !currentLayer ||+ layerCache.version(layer.id) !== version ||+ !isDeeplyEqual(renderableSourceOf(currentLayer), source)+ ) {+ // The failure describes a layer that has already moved on; reporting it+ // would surface an error about work nobody is waiting for.+ return 'stale';+ }+ deps.thumbnails.setStatus(layer.id, 'error');+ try {+ deps.reportError('Layer thumbnail rasterization failed', layer.id, error);+ } catch {+ // Diagnostics must not turn a handled thumbnail failure into a rejection.+ }+ return 'error';+ } finally {+ signal?.removeEventListener('abort', abort);+ jobs.finish(layer.id, job);+ // A job that did not publish still holds the decoded bitmap it pulled in.+ const imageName = sourceImageName(source);+ if (!published && imageName) {+ deps.releaseBitmapIfUnreferenced(imageName);+ }+ }+ })().then(settleJob, () => settleJob('stale'));+ return promise;+ };++ return { getOrStartLayerRasterization };+};