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(canvas): collapse composite generation transaction into one deep call
joshistoast23b8bf2efe2d
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.tsindex fe3655675d..634b58ad72 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts@@ -1,7 +1,5 @@export type {CanvasOperationActionResult,- CanvasCompositeTransaction,- CanvasCompositeTransactionResult,CanvasOperationCapability,CanvasOperationMutationResult,CanvasOperationState,@@ -29,22 +27,17 @@ export type {export { getCanvasOperations } from './operationAccess';export { getCanvasEngine } from './engineRegistry';export { saveCanvasToGallery, type CanvasGallerySaveRegion } from './saveCanvasToGallery';-export { computeCompositeContentBounds } from './compositeForGeneration';export {- getBaseRasterContentBounds,- getCompositeLayerBounds,- planBaseRasterComposite,- planComposites,- planControlComposites,- planRegionalMaskComposites,-} from './generationCompositePlan';-export type {- CompositeEntry,- CompositeLayerRef,- CompositeMaskLayerRef,- CompositePlan,- Rect,-} from './generationContracts';+ composeForGeneration,+ type ComposeForGenerationOptions,+ type ComposeForGenerationResult,+ type GenerationCompositeExecutorDeps,+ type GenerationCompositeHost,+ type GenerationCompositeMode,+ type GenerationComposites,+ type GenerationModeFacts,+} from './generationComposite';+export { createCompositeDedupeCache, type CompositeDedupeCache } from './compositeForGeneration';export {CONTROL_FILTERS,buildFilterGraph,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.tsindex 959c417efc..cce66e9fc8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts@@ -1,7 +1,5 @@import type {CommitGeneratedImageResult,- CanvasDocumentSnapshot,- CanvasStateContractV2,LayerExportGuard,ReplaceSelectionFromImageResult,} from '@workbench/canvas-engine/api';@@ -16,11 +14,9 @@ import type { ExportBakedLayerBlobResult, ExportLayerPixelsResult } from '@workbimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type {- CompositeEntryResult,- CompositeResult,- MaskCompositeResult,-} from '@workbench/canvas-operations/compositeForGeneration';-import type { CompositeEntry, CompositePlan } from '@workbench/canvas-operations/generationContracts';+ ComposeForGenerationOptions,+ ComposeForGenerationResult,+} from '@workbench/canvas-operations/generationComposite';import type {FilterCommitTarget,FilterOperationSessionState,@@ -61,11 +57,8 @@ export interface SelectObjectSessionUpdate {/** Intent-oriented application operations attached to one Canvas engine. */export interface CanvasOperationCapability {- captureCompositeTransaction(- snapshot: CanvasDocumentSnapshot,- layerIds: readonly string[],- options: { signal: AbortSignal }- ): Promise<CanvasCompositeTransactionResult>;+ /** Runs the complete canvas → generation composite pipeline (see `composeForGeneration`). */+ composeForGeneration(options: ComposeForGenerationOptions): Promise<ComposeForGenerationResult>;uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;getOperationState(): CanvasOperationState;subscribeOperation(listener: () => void): () => void;@@ -95,21 +88,6 @@ export interface CanvasOperationCapability {cancelSelectObjectSession(): void;}-/** Opaque generation transaction; pixels, surfaces, caches, and reservations remain Canvas-owned. */-export interface CanvasCompositeTransaction {- readonly canvas: CanvasStateContractV2;- executePlan(plan: CompositePlan): Promise<CompositeResult>;- executeControl(entry: CompositeEntry): Promise<CompositeEntryResult>;- executeMask(entry: CompositeEntry): Promise<MaskCompositeResult>;- executeRegionalMask(entry: CompositeEntry): Promise<CompositeEntryResult>;- commit(): void;- release(): void;-}--export type CanvasCompositeTransactionResult =- | { status: 'ok'; transaction: CanvasCompositeTransaction }- | { status: 'stale' | 'aborted' | 'not-ready' | 'over-budget' };-/** Private composition shape; mutable stores and controller never cross the Canvas interface. */export interface CanvasOperationImplementation extends CanvasOperationCapability {readonly controller: CanvasOperationController;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.tsindex b83fb976d4..14b8321c1e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts@@ -3,17 +3,13 @@ import type {CanvasEngineOptions as CoreCanvasEngineOptions,} from '@workbench/canvas-engine/engine';import type { CanvasUtilityGraphResult } from '@workbench/canvas-operations/contracts';+import type { GenerationCompositeHost } from '@workbench/canvas-operations/generationComposite';import type { BackendGraphContract } from '@workbench/graphContracts';import { createCanvasEngine as createCanvasEngineCore } from '@workbench/canvas-engine/engine';import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';-import {- createBoundedCompositeDedupeCache,- executeCompositePlan,- executeControlComposite,- executeMaskComposite,- executeRegionalMaskComposite,-} from '@workbench/canvas-operations/compositeForGeneration';+import { createBoundedCompositeDedupeCache } from '@workbench/canvas-operations/compositeForGeneration';+import { composeForGeneration } from '@workbench/canvas-operations/generationComposite';import type { CanvasOperationCapability, CanvasOperationImplementation } from './contracts';@@ -204,52 +200,20 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =syncSamInteraction();const compositeDedupe = createBoundedCompositeDedupeCache();+ const generationCompositeHost: GenerationCompositeHost = {+ captureDocumentSnapshot: () => core.document.captureSnapshot(),+ captureRasterSnapshot: (snapshot, layerIds, captureOptions) =>+ core.exports.captureRasterSnapshot(snapshot, layerIds, captureOptions),+ dedupe: compositeDedupe,+ getCompositeExecutorDeps: () => core.exports.getCompositeExecutorDeps(),+ };const operations: CanvasOperationImplementation = {applySelectObjectSession: selectObjectCoordinator.apply,cancelFilterOperation: filterCoordinator.cancel,cancelSelectObjectSession: selectObjectCoordinator.cancel,- captureCompositeTransaction: async (snapshot, layerIds, captureOptions) => {- const capture = await core.exports.captureRasterSnapshot(snapshot, layerIds, captureOptions);- if (capture.status !== 'ok') {- return capture;- }- const rasterSnapshot = capture.snapshot;- const transactionDedupe = {- byHash: new Map(compositeDedupe.byHash),- byKey: new Map(compositeDedupe.byKey),- };- const deps = {- ...core.exports.getCompositeExecutorDeps(),- dedupe: transactionDedupe,- getLayerSurface: (layerId: string) => {- const detached = rasterSnapshot.layerSurfaces.get(layerId);- return detached- ? Promise.resolve(detached)- : Promise.reject(new Error(`Canvas raster snapshot is missing layer ${layerId}.`));- },- };- return {- status: 'ok',- transaction: {- canvas: rasterSnapshot.canvas,- commit: () => {- for (const [key, value] of transactionDedupe.byHash) {- compositeDedupe.byHash.set(key, value);- }- for (const [key, value] of transactionDedupe.byKey) {- compositeDedupe.byKey.set(key, value);- }- },- executeControl: (entry) => executeControlComposite(entry, deps),- executeMask: (entry) => executeMaskComposite(entry, deps),- executePlan: (plan) => executeCompositePlan(plan, deps),- executeRegionalMask: (entry) => executeRegionalMaskComposite(entry, deps),- release: rasterSnapshot.release,- },- };- },commitFilterOperation: filterCoordinator.commit,+ composeForGeneration: (composeOptions) => composeForGeneration(generationCompositeHost, composeOptions),controller,getFilterSessionState: stores.filterSession.get,getOperationState: controller.getSnapshot,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.tsnew file mode 100644index 0000000000..6fb8347bfd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.test.ts@@ -0,0 +1,454 @@+import type {+ CanvasControlLayerContract,+ CanvasDocumentContractV2,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+ CanvasStateContractV2,+} from '@workbench/canvas-engine/contracts';+import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';+import type { Rect } from '@workbench/canvas-engine/types';++import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { describe, expect, it, vi } from 'vitest';++import type { ComposeForGenerationOptions, GenerationCompositeHost, GenerationModeFacts } from './generationComposite';++import { createCompositeDedupeCache } from './compositeForGeneration';+import { composeForGeneration } from './generationComposite';++const rasterLayer = (id: string, size = 64): CanvasRasterLayerContractV2 => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { image: { height: size, imageName: `${id}.png`, width: size }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+});++const controlLayer = (id: string): CanvasControlLayerContract => ({+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 0.75 },+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { image: { height: 64, imageName: `${id}.png`, width: 64 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: true,+});++const regionalLayer = (id: string): CanvasLayerContract => ({+ autoNegative: false,+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: { height: 64, imageName: `${id}-bmp`, width: 64 }, fill: { color: '#ff0000', style: 'solid' } },+ name: id,+ negativePrompt: null,+ opacity: 1,+ positivePrompt: 'region',+ referenceImages: [],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+});++const inpaintMaskLayer = (id: string, noiseLevel?: number): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: { height: 64, imageName: `${id}-bmp`, width: 64 }, fill: { color: '#ff0000', style: 'solid' } },+ name: id,+ ...(noiseLevel !== undefined ? { noiseLevel } : {}),+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+});++const makeDoc = (layers: CanvasLayerContract[], size = 64): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: size, width: size, x: 0, y: 0 },+ height: size,+ layers,+ selectedLayerId: null,+ version: 2,+ width: size,+});++const makeCanvas = (document: CanvasDocumentContractV2): CanvasStateContractV2 => ({+ document: structuredClone(document),+ documentRevision: 0,+ snapshots: [],+ stagingArea: {+ areThumbnailsVisible: true,+ autoSwitchMode: 'off',+ isVisible: false,+ pendingImageIds: [],+ pendingImages: [],+ selectedImageIndex: 0,+ },+ version: 2,+});++/** Uniform-alpha ImageData (255 = fully opaque → bboxFullyCovered true). */+const uniformImageData = (width: number, height: number, alpha: number): ImageData => {+ const data = new Uint8ClampedArray(Math.max(1, width) * Math.max(1, height) * 4);+ for (let i = 3; i < data.length; i += 4) {+ data[i] = alpha;+ }+ return { colorSpace: 'srgb', data, height, width } as unknown as ImageData;+};++interface HostHarness {+ host: GenerationCompositeHost;+ uploadImage: ReturnType<typeof vi.fn>;+ release: ReturnType<typeof vi.fn>;+ /** Ordered log of `upload:<name>` entries (tests may push their own markers). */+ events: string[];+ /** Layer ids requested from the raster snapshot, in request order. */+ surfaceIds: string[];+}++interface HostOptions {+ alpha?: number;+ uploadImage?: (blob: Blob) => Promise<CanvasImageUploadResult>;+}++/**+ * Assembles a fake {@link GenerationCompositeHost} mirroring the widget invoke+ * harness: the raster test stub for surfaces, a counting uploader, a spy-able+ * release, and a per-call-unique hash so every distinct composite entry uploads+ * (plan-key dedupe still reuses across calls).+ */+const makeHost = (document: CanvasDocumentContractV2, options: HostOptions = {}): HostHarness => {+ const stub = createTestStubRasterBackend();+ const events: string[] = [];+ const surfaceIds: string[] = [];+ const alpha = options.alpha ?? 255;+ const release = vi.fn();+ const dedupe = createCompositeDedupeCache();++ let uploadCounter = 0;+ const uploadImage = vi.fn(+ options.uploadImage ??+ ((blob: Blob): Promise<CanvasImageUploadResult> => {+ void blob;+ uploadCounter += 1;+ events.push(`upload:composite-${uploadCounter}.png`);+ return Promise.resolve({ height: 64, imageName: `composite-${uploadCounter}.png`, width: 64 });+ })+ );++ let hashCounter = 0;+ const layerSurfaces = new Map<string, RasterSurface>();++ const host: GenerationCompositeHost = {+ captureDocumentSnapshot: () => ({ canvas: makeCanvas(document), documentGeneration: 0 }),+ captureRasterSnapshot: (documentSnapshot, layerIds) => {+ const detached = new Map<string, { rect: Rect; surface: RasterSurface }>();+ for (const layerId of layerIds) {+ surfaceIds.push(layerId);+ let surface = layerSurfaces.get(layerId);+ if (!surface) {+ surface = stub.createSurface(64, 64);+ layerSurfaces.set(layerId, surface);+ }+ detached.set(layerId, { rect: { height: 64, width: 64, x: 0, y: 0 }, surface });+ }+ return Promise.resolve({+ snapshot: {+ canvas: documentSnapshot.canvas,+ documentGeneration: documentSnapshot.documentGeneration,+ emptyLayerIds: new Set<string>(),+ layerSurfaces: detached,+ release,+ },+ status: 'ok',+ });+ },+ dedupe,+ getCompositeExecutorDeps: () => ({+ backend: {+ createSurface: (w: number, h: number): RasterSurface => stub.createSurface(w, h),+ encodeSurface: (surface: RasterSurface): Promise<Blob> => stub.encodeSurface(surface),+ },+ // Unique per call: byHash never collapses distinct entries (the stub+ // encodes size-only blobs), so upload counts stay per-entry; cross-call+ // reuse goes through the plan-key cache.+ hashBlob: () => {+ hashCounter += 1;+ return Promise.resolve(`hash-${hashCounter}`);+ },+ readImageData: (_surface, rect) => uniformImageData(rect.width, rect.height, alpha),+ uploadImage: uploadImage as (blob: Blob) => Promise<CanvasImageUploadResult>,+ }),+ };++ return { events, host, release, surfaceIds, uploadImage };+};++const compose = (host: GenerationCompositeHost, overrides: Partial<ComposeForGenerationOptions> = {}) =>+ composeForGeneration(host, {+ detectMode: () => 'img2img',+ signal: new AbortController().signal,+ ...overrides,+ });++describe('composeForGeneration', () => {+ it('returns no-document when the host has no active document', async () => {+ const harness = makeHost(makeDoc([rasterLayer('layer-a')]));+ harness.host.captureDocumentSnapshot = () => null;++ const result = await compose(harness.host);++ expect(result).toEqual({ status: 'no-document' });+ expect(harness.uploadImage).not.toHaveBeenCalled();+ expect(harness.release).not.toHaveBeenCalled();+ });++ it.each(['stale', 'aborted', 'not-ready', 'over-budget'] as const)(+ 'passes the raster-capture %s status through without compositing',+ async (status) => {+ const harness = makeHost(makeDoc([rasterLayer('layer-a')]));+ harness.host.captureRasterSnapshot = vi.fn(() => Promise.resolve({ status }));+ const detectMode = vi.fn(() => 'img2img' as const);++ const result = await compose(harness.host, { detectMode });++ expect(result).toEqual({ status });+ expect(detectMode).not.toHaveBeenCalled();+ expect(harness.uploadImage).not.toHaveBeenCalled();+ expect(harness.host.dedupe.byKey.size).toBe(0);+ expect(harness.host.dedupe.byHash.size).toBe(0);+ }+ );++ it('forwards the abort signal to raster capture', async () => {+ const harness = makeHost(makeDoc([rasterLayer('layer-a')]));+ const captureRasterSnapshot = vi.fn(() => Promise.resolve({ status: 'aborted' as const }));+ harness.host.captureRasterSnapshot = captureRasterSnapshot;+ const controller = new AbortController();++ await compose(harness.host, { signal: controller.signal });++ expect(captureRasterSnapshot).toHaveBeenCalledWith(+ expect.any(Object),+ ['layer-a'],+ expect.objectContaining({ signal: controller.signal })+ );+ });++ it('resolves txt2img from the bounds pre-pass: no base upload, detectMode never consulted, controls and regionals still composited', async () => {+ // No raster layers → no content bounds → txt2img without executing the base+ // plan; control + regional composites are mode-independent and still run.+ const harness = makeHost(makeDoc([controlLayer('control-a'), regionalLayer('region-a')]));+ const detectMode = vi.fn(() => 'img2img' as const);++ const result = await compose(harness.host, { detectMode });++ expect(detectMode).not.toHaveBeenCalled();+ expect(result.status).toBe('ok');+ if (result.status !== 'ok') {+ return;+ }+ expect(result.composites.mode).toBe('txt2img');+ expect(result.composites.baseImageName).toBeNull();+ expect(result.composites.maskImageName).toBeNull();+ expect(result.composites.noiseMaskImageName).toBeNull();+ expect(result.composites.controlImages).toEqual([{ imageName: 'composite-1.png', layerId: 'control-a' }]);+ expect(result.composites.regionalMaskImages).toEqual([{ imageName: 'composite-2.png', layerId: 'region-a' }]);+ expect(harness.uploadImage).toHaveBeenCalledTimes(2);+ });++ it('consults detectMode exactly once with the composite facts when content overlaps the bbox', async () => {+ const harness = makeHost(makeDoc([rasterLayer('base')]));+ const detectMode = vi.fn(() => 'img2img' as const);++ const result = await compose(harness.host, { detectMode });++ expect(detectMode).toHaveBeenCalledTimes(1);+ expect(detectMode).toHaveBeenCalledWith({+ bbox: { height: 64, width: 64, x: 0, y: 0 },+ bboxFullyCovered: true,+ contentBounds: { height: 64, width: 64, x: 0, y: 0 },+ hasActiveInpaintMask: false,+ });+ expect(result.status).toBe('ok');+ if (result.status !== 'ok') {+ return;+ }+ expect(result.composites.mode).toBe('img2img');+ expect(result.composites.baseImageName).toBe('composite-1.png');+ expect(result.composites.canvas.document.layers[0]?.id).toBe('base');+ expect(result.composites.bbox).toEqual({ height: 64, width: 64, x: 0, y: 0 });+ });++ it('executes the inpaint mask before consulting detectMode and reports its coverage', async () => {+ const harness = makeHost(makeDoc([rasterLayer('base'), inpaintMaskLayer('mask')]));+ const detectMode = vi.fn((facts: GenerationModeFacts) => {+ harness.events.push('detectMode');+ return facts.hasActiveInpaintMask ? ('inpaint' as const) : ('img2img' as const);+ });++ const result = await compose(harness.host, { detectMode });++ // Base upload, then the inpaint-mask upload, then (and only then) the mode+ // strategy — the mask's coverage is one of its inputs.+ expect(harness.events).toEqual(['upload:composite-1.png', 'upload:composite-2.png', 'detectMode']);+ expect(detectMode).toHaveBeenCalledWith(expect.objectContaining({ hasActiveInpaintMask: true }));+ expect(result.status).toBe('ok');+ if (result.status !== 'ok') {+ return;+ }+ expect(result.composites.mode).toBe('inpaint');+ expect(result.composites.maskImageName).toBe('composite-2.png');+ });++ it.each([+ { expectedMask: null, expectedNoise: null, expectedUploads: 2, mode: 'img2img' as const },+ { expectedMask: 'composite-2.png', expectedNoise: 'composite-3.png', expectedUploads: 3, mode: 'inpaint' as const },+ {+ expectedMask: 'composite-2.png',+ expectedNoise: 'composite-3.png',+ expectedUploads: 3,+ mode: 'outpaint' as const,+ },+ ])(+ 'composites the noise mask only for inpaint/outpaint ($mode)',+ async ({ expectedMask, expectedNoise, expectedUploads, mode }) => {+ // The inpaint mask defines a noiseLevel, so the plan carries a noise-mask+ // entry — it must execute only when the resolved mode consumes it.+ const harness = makeHost(makeDoc([rasterLayer('base'), inpaintMaskLayer('mask', 0.5)]));++ const result = await compose(harness.host, { detectMode: () => mode });++ expect(result.status).toBe('ok');+ if (result.status !== 'ok') {+ return;+ }+ expect(result.composites.mode).toBe(mode);+ expect(result.composites.maskImageName).toBe(expectedMask);+ expect(result.composites.noiseMaskImageName).toBe(expectedNoise);+ expect(harness.uploadImage).toHaveBeenCalledTimes(expectedUploads);+ }+ );++ it('skips a control layer the predicate rejects, with no upload for it', async () => {+ const harness = makeHost(makeDoc([controlLayer('control-a'), controlLayer('control-b')]));++ const result = await compose(harness.host, {+ shouldCompositeControlLayer: (layer) => layer.id !== 'control-a',+ });++ expect(result.status).toBe('ok');+ if (result.status !== 'ok') {+ return;+ }+ expect(result.composites.controlImages).toEqual([{ imageName: 'composite-1.png', layerId: 'control-b' }]);+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);+ });++ it('rethrows a control-predicate throw after releasing the snapshot, committing nothing', async () => {+ // A raster layer first, so the base composite has already uploaded (and+ // populated the operation-scoped cache) before the predicate aborts.+ const harness = makeHost(makeDoc([rasterLayer('base'), controlLayer('control-a')]));++ await expect(+ compose(harness.host, {+ shouldCompositeControlLayer: () => {+ throw new Error('[missing_model] Control layer "control-a" is invalid.');+ },+ })+ ).rejects.toThrow('[missing_model] Control layer "control-a" is invalid.');++ expect(harness.release).toHaveBeenCalledTimes(1);+ expect(harness.host.dedupe.byKey.size).toBe(0);+ expect(harness.host.dedupe.byHash.size).toBe(0);+ });++ it('silently skips a regional mask the predicate rejects, with no upload for it', async () => {+ const harness = makeHost(makeDoc([regionalLayer('region-a'), regionalLayer('region-b')]));++ const result = await compose(harness.host, {+ shouldCompositeRegionalMask: (layer) => layer.id !== 'region-a',+ });++ expect(result.status).toBe('ok');+ if (result.status !== 'ok') {+ return;+ }+ expect(result.composites.regionalMaskImages).toEqual([{ imageName: 'composite-1.png', layerId: 'region-b' }]);+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);+ });++ it('calls the predicates in plan z-order (controls, then regionals)', async () => {+ const harness = makeHost(+ makeDoc([+ controlLayer('control-a'),+ regionalLayer('region-a'),+ controlLayer('control-b'),+ regionalLayer('region-b'),+ ])+ );+ const order: string[] = [];++ await compose(harness.host, {+ shouldCompositeControlLayer: (layer) => {+ order.push(`control:${layer.id}`);+ return true;+ },+ shouldCompositeRegionalMask: (layer) => {+ order.push(`regional:${layer.id}`);+ return true;+ },+ });++ expect(order).toEqual(['control:control-a', 'control:control-b', 'regional:region-a', 'regional:region-b']);+ });++ it('commits the dedupe cache on success so a second compose reuses every upload', async () => {+ const document = makeDoc([rasterLayer('base'), controlLayer('control-a')]);+ const harness = makeHost(document);++ const first = await compose(harness.host);+ expect(first.status).toBe('ok');+ const uploadsAfterFirst = harness.uploadImage.mock.calls.length;+ expect(uploadsAfterFirst).toBe(2);+ expect(harness.host.dedupe.byKey.size).toBeGreaterThan(0);++ const second = await compose(harness.host);+ expect(second.status).toBe('ok');+ expect(harness.uploadImage.mock.calls.length).toBe(uploadsAfterFirst);+ if (first.status === 'ok' && second.status === 'ok') {+ expect(second.composites.baseImageName).toBe(first.composites.baseImageName);+ expect(second.composites.controlImages).toEqual(first.composites.controlImages);+ }+ });++ it('releases the raster snapshot on success', async () => {+ const harness = makeHost(makeDoc([rasterLayer('base')]));++ await compose(harness.host);++ expect(harness.release).toHaveBeenCalledTimes(1);+ });++ it('releases the raster snapshot and commits nothing when an upload fails', async () => {+ const harness = makeHost(makeDoc([rasterLayer('base')]), {+ uploadImage: () => Promise.reject(new Error('upload exploded')),+ });++ await expect(compose(harness.host)).rejects.toThrow('upload exploded');++ expect(harness.release).toHaveBeenCalledTimes(1);+ expect(harness.host.dedupe.byKey.size).toBe(0);+ expect(harness.host.dedupe.byHash.size).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.tsnew file mode 100644index 0000000000..9cfd5e7a96--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts@@ -0,0 +1,307 @@+/**+ * The composite-generation operation: one deep call that turns the live canvas+ * into every uploaded image a canvas invoke needs.+ *+ * `composeForGeneration` owns the whole snapshot → plan → capture → composite+ * protocol that callers previously drove step by step through+ * `CanvasCompositeTransaction`: it captures the document snapshot, plans the+ * base / mask / control / regional composites, detaches the required layer+ * surfaces, runs a bounds-only pre-pass (content that does not overlap the bbox+ * is txt2img — no base composite, no upload, and the mode strategy is never+ * consulted), executes the base composite + grayscale masks + per-layer control+ * and regional-mask composites, and releases the raster snapshot in a `finally`+ * on both success and failure. Pixels, surfaces, dedupe caches, and memory+ * reservations never cross the seam.+ *+ * Caller-owned policy enters as three strategies on the options:+ * - `detectMode` maps composite facts to a generation mode. It is called at+ * most once, and only when raster content overlaps the bbox.+ * - `shouldCompositeControlLayer` vets each planned control layer in z-order:+ * `false` skips the layer (no upload); a **throw aborts the whole operation**+ * (the snapshot is released, no dedupe entry is committed, and the error is+ * rethrown to the caller).+ * - `shouldCompositeRegionalMask` vets each planned regional-guidance layer in+ * z-order: `false` silently skips the region (no upload).+ *+ * Semantic delta vs. the old transaction (documented, intentional): the dedupe+ * commit happens when every composite has succeeded, not after the caller+ * submits the graph. The cache only enables reuse of correctly uploaded+ * content-hashed intermediates, so committing at composite-success is not+ * product-visible — a later submit failure never invalidates the uploads.+ */++import type {+ CanvasControlLayerContract,+ CanvasDocumentSnapshot,+ CanvasRegionalGuidanceLayerContract,+ CanvasStateContractV2,+} from '@workbench/canvas-engine/api';+import type { CaptureRasterSnapshotResult } from '@workbench/canvas-engine/rasterTransactions';+import type { Rect } from '@workbench/canvas-engine/types';+import type {+ CompositeDedupeCache,+ ExecuteCompositePlanDeps,+} from '@workbench/canvas-operations/compositeForGeneration';++import { intersect } from '@workbench/canvas-engine/math/rect';+import {+ computeCompositeContentBounds,+ executeCompositePlan,+ executeControlComposite,+ executeMaskComposite,+ executeRegionalMaskComposite,+} from '@workbench/canvas-operations/compositeForGeneration';+import {+ planComposites,+ planControlComposites,+ planRegionalMaskComposites,+} from '@workbench/canvas-operations/generationCompositePlan';++/**+ * The generation mode a composite resolves to. Structural mirror of+ * generation's `CanvasGenerationMode` — canvas-operations must not import the+ * feature, and tsc guards drift in both directions at the caller's `detectMode`+ * wiring.+ */+export type GenerationCompositeMode = 'txt2img' | 'img2img' | 'inpaint' | 'outpaint';++/** The composite facts the caller's `detectMode` strategy decides from. */+export interface GenerationModeFacts {+ /** The generation bounding box, in document space. */+ bbox: Rect;+ /** Union of enabled raster content bounds in document space, or `null`. */+ contentBounds: Rect | null;+ /** Whether the composited bbox surface is fully opaque (no transparent holes). */+ bboxFullyCovered: boolean;+ /** Whether an enabled inpaint mask with masked (non-white) content exists. */+ hasActiveInpaintMask: boolean;+}++/** Caller-owned policy + cancellation for {@link composeForGeneration}. */+export interface ComposeForGenerationOptions {+ /** Cancels raster capture; a capture abort resolves as `{ status: 'aborted' }`. */+ signal: AbortSignal;+ /**+ * Maps composite facts to the generation mode. Called at most once, and only+ * when raster content overlaps the bbox (otherwise the mode is txt2img).+ */+ detectMode(facts: GenerationModeFacts): GenerationCompositeMode;+ /**+ * Vets one planned control layer (called in z-order). `false` skips it with+ * no upload; a throw aborts the whole operation (snapshot released, dedupe+ * uncommitted, error rethrown). Omitted → every planned layer composites.+ */+ shouldCompositeControlLayer?(layer: CanvasControlLayerContract): boolean;+ /**+ * Vets one planned regional-guidance layer (called in z-order). `false`+ * silently skips it with no upload. Omitted → every planned region composites.+ */+ shouldCompositeRegionalMask?(layer: CanvasRegionalGuidanceLayerContract): boolean;+}++/** The engine-side executor dependencies the host supplies (dedupe + surfaces are operation-owned). */+export type GenerationCompositeExecutorDeps = Omit<ExecuteCompositePlanDeps, 'dedupe' | 'getLayerSurface'>;++/**+ * The engine seam {@link composeForGeneration} runs against. Production wiring+ * lives in `createCanvasEngine`; tests assemble a fake host over+ * `render/raster.testStub` + a mock uploader.+ */+export interface GenerationCompositeHost {+ /** Captures the current document snapshot, or `null` without an active document. */+ captureDocumentSnapshot(): CanvasDocumentSnapshot | null;+ /** Detaches the listed layers' pixel surfaces for the snapshot (status on failure). */+ captureRasterSnapshot(+ snapshot: CanvasDocumentSnapshot,+ layerIds: readonly string[],+ options: { signal: AbortSignal }+ ): Promise<CaptureRasterSnapshotResult>;+ /** The engine's composite executor deps (backend, upload, reserve, ...). */+ getCompositeExecutorDeps(): GenerationCompositeExecutorDeps;+ /** Engine-scoped dedupe cache, merged into only after every composite succeeds. */+ dedupe: CompositeDedupeCache;+}++/** Everything a canvas invoke needs from the composite pipeline. */+export interface GenerationComposites {+ /** The frozen canvas state the composites were built from (for the enqueue snapshot). */+ canvas: CanvasStateContractV2;+ /** The generation bounding box of the frozen document. */+ bbox: Rect;+ /** The resolved generation mode. */+ mode: GenerationCompositeMode;+ /** The base composite's uploaded image, or `null` for txt2img. */+ baseImageName: string | null;+ /** The grayscale inpaint mask's uploaded image (inpaint/outpaint with mask content), or `null`. */+ maskImageName: string | null;+ /** The grayscale noise mask's uploaded image (inpaint/outpaint only), or `null`. */+ noiseMaskImageName: string | null;+ /** One uploaded image per accepted control layer, in z-order. */+ controlImages: { layerId: string; imageName: string }[];+ /** One uploaded alpha-mask image per accepted regional-guidance layer, in z-order. */+ regionalMaskImages: { layerId: string; imageName: string }[];+}++export type ComposeForGenerationResult =+ | { status: 'ok'; composites: GenerationComposites }+ | { status: 'no-document' | 'stale' | 'aborted' | 'not-ready' | 'over-budget' };++/**+ * Runs the complete canvas → generation composite pipeline against `host`.+ * Capture failures resolve as a status; execution failures (including a+ * control-predicate throw) release the raster snapshot and rethrow.+ */+export const composeForGeneration = async (+ host: GenerationCompositeHost,+ options: ComposeForGenerationOptions+): Promise<ComposeForGenerationResult> => {+ const documentSnapshot = host.captureDocumentSnapshot();+ if (!documentSnapshot) {+ return { status: 'no-document' };+ }+ const document = documentSnapshot.canvas.document;+ const bbox = document.bbox;++ const plan = planComposites(document, bbox);+ const controlPlan = planControlComposites(document, bbox);+ const regionalPlan = planRegionalMaskComposites(document, bbox);++ const requiredLayerIds = new Set<string>();+ for (const entry of [+ ...plan.entries,+ ...controlPlan.map((item) => item.entry),+ ...regionalPlan.map((item) => item.entry),+ ]) {+ for (const layer of entry.layers) {+ requiredLayerIds.add(layer.id);+ }+ for (const layer of entry.maskLayers ?? []) {+ requiredLayerIds.add(layer.id);+ }+ }++ const capture = await host.captureRasterSnapshot(documentSnapshot, [...requiredLayerIds], {+ signal: options.signal,+ });+ if (capture.status !== 'ok') {+ return capture;+ }+ const rasterSnapshot = capture.snapshot;++ // Operation-scoped dedupe: composites read/write a copy, merged back into the+ // host cache only after every composite succeeded (see the module doc).+ const operationDedupe: CompositeDedupeCache = {+ byHash: new Map(host.dedupe.byHash),+ byKey: new Map(host.dedupe.byKey),+ };+ const deps: ExecuteCompositePlanDeps = {+ ...host.getCompositeExecutorDeps(),+ dedupe: operationDedupe,+ getLayerSurface: (layerId) => {+ const detached = rasterSnapshot.layerSurfaces.get(layerId);+ return detached+ ? Promise.resolve(detached)+ : Promise.reject(new Error(`Canvas raster snapshot is missing layer ${layerId}.`));+ },+ };++ try {+ // Bounds-only pre-pass (pure geometry, no upload): content that does not+ // overlap the bbox is txt2img no matter the coverage. Also naturally skips a+ // zero-area bbox (`intersect` is null for empty rects). `intersect`'s strict+ // overlap matches generation's `rectsIntersect` (flush edges don't count).+ const contentBounds = computeCompositeContentBounds(plan);++ let mode: GenerationCompositeMode = 'txt2img';+ let baseImageName: string | null = null;+ let maskImageName: string | null = null;+ let noiseMaskImageName: string | null = null;++ if (contentBounds && intersect(contentBounds, bbox) !== null) {+ const result = await executeCompositePlan(plan, deps);+ baseImageName = result.base.imageName;++ // The grayscale denoise-limit mask (when enabled inpaint masks exist) both+ // decides inpaint-vs-img2img (its coverage) and feeds the graph — it must+ // execute BEFORE the mode strategy runs. Legacy parity: raster opaque ++ // mask has content → inpaint; else img2img.+ const maskEntry = plan.entries.find((entry) => entry.kind === 'inpaint-mask');+ const maskResult = maskEntry ? await executeMaskComposite(maskEntry, deps) : null;++ mode = options.detectMode({+ bbox,+ bboxFullyCovered: result.bboxFullyCovered,+ contentBounds: result.contentBounds,+ hasActiveInpaintMask: maskResult?.hasContent ?? false,+ });++ if (mode === 'inpaint' || mode === 'outpaint') {+ // A real (non-white) mask feeds create_gradient_mask; outpaint without one+ // derives its mask from the raster alpha (maskImageName stays null).+ maskImageName = maskResult?.hasContent ? maskResult.imageName : null;+ const noiseEntry = plan.entries.find((entry) => entry.kind === 'noise-mask');+ if (noiseEntry) {+ noiseMaskImageName = (await executeMaskComposite(noiseEntry, deps)).imageName;+ }+ }+ }++ const layerById = new Map(document.layers.map((layer) => [layer.id, layer]));++ // Control layers apply in every mode, independent of the base composite —+ // composite each accepted layer regardless of whether raster content+ // overlaps. Each layer is composited SEPARATELY (never blended).+ const controlImages: { layerId: string; imageName: string }[] = [];+ for (const { entry, layerId } of controlPlan) {+ const layer = layerById.get(layerId);+ if (!layer || layer.type !== 'control') {+ continue;+ }+ if (options.shouldCompositeControlLayer && !options.shouldCompositeControlLayer(layer)) {+ continue;+ }+ const result = await executeControlComposite(entry, deps);+ controlImages.push({ imageName: result.imageName, layerId });+ }++ // Regional guidance also applies in every mode — each accepted region's+ // mask is composited separately (its alpha feeds its own tensor).+ const regionalMaskImages: { layerId: string; imageName: string }[] = [];+ for (const { entry, layerId } of regionalPlan) {+ const layer = layerById.get(layerId);+ if (!layer || layer.type !== 'regional_guidance') {+ continue;+ }+ if (options.shouldCompositeRegionalMask && !options.shouldCompositeRegionalMask(layer)) {+ continue;+ }+ const result = await executeRegionalMaskComposite(entry, deps);+ regionalMaskImages.push({ imageName: result.imageName, layerId });+ }++ // Every composite succeeded: publish the operation's dedupe entries so the+ // next invoke reuses the uploads (see the module doc for the timing note).+ for (const [key, value] of operationDedupe.byHash) {+ host.dedupe.byHash.set(key, value);+ }+ for (const [key, value] of operationDedupe.byKey) {+ host.dedupe.byKey.set(key, value);+ }++ return {+ composites: {+ baseImageName,+ bbox,+ canvas: rasterSnapshot.canvas,+ controlImages,+ maskImageName,+ mode,+ noiseMaskImageName,+ regionalMaskImages,+ },+ status: 'ok',+ };+ } finally {+ rasterSnapshot.release();+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex c425f80b41..2fc9e1b4bb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -11,7 +11,6 @@ import type {import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';-import type { CanvasCompositeTransaction } from '@workbench/canvas-operations/api';import type { WorkbenchState } from '@workbench/projectContracts';import type { WorkbenchAction } from '@workbench/workbenchState.testing';import type { WorkbenchCommands } from '@workbench/workbenchStore';@@ -19,13 +18,11 @@ import type { WorkbenchCommands } from '@workbench/workbenchStore';import { getDefaultGenerateSettings } from '@features/generation/settings';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import {+ composeForGeneration,createCompositeDedupeCache,- executeCompositePlan,- executeControlComposite,- executeMaskComposite,- executeRegionalMaskComposite,- type ExecuteCompositePlanDeps,-} from '@workbench/canvas-operations/compositeForGeneration';+ type GenerationCompositeExecutorDeps,+ type GenerationCompositeHost,+} from '@workbench/canvas-operations/api';import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -94,7 +91,9 @@ interface Harness {surfaceIds: string[];releaseRasterSnapshot: ReturnType<typeof vi.fn>;dedupe: ReturnType<typeof createCompositeDedupeCache>;- executorDeps: Omit<ExecuteCompositePlanDeps, 'dedupe' | 'getLayerSurface'>;+ executorDeps: GenerationCompositeExecutorDeps;+ /** The fake engine seam the REAL `composeForGeneration` operation runs against. */+ host: GenerationCompositeHost;submittedGraphs: () => Extract<WorkbenchAction, { type: 'submitCanvasInvocationSnapshot' }>[];notices: () => { message?: string }[];}@@ -182,56 +181,43 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {version: 2,});- const executorDeps: Omit<ExecuteCompositePlanDeps, 'dedupe' | 'getLayerSurface'> = {+ const executorDeps: GenerationCompositeExecutorDeps = {backend,hashBlob: (blob: Blob) => blob.text(),readImageData: (_surface, rect) => uniformImageData(rect.width, rect.height, alpha),uploadImage: uploadImage as (blob: Blob) => Promise<CanvasImageUploadResult>,};- const deps: RunCanvasInvocationDeps = {+ // The fake engine seam behind the REAL `composeForGeneration` operation — the+ // same fakes the hand-rolled transaction used to wire (stub raster backend,+ // counting uploader, spy-able release, harness-scoped dedupe cache).+ const host: GenerationCompositeHost = {captureDocumentSnapshot: () => ({canvas: makeCanvas(options.document ?? makeDoc([rasterLayer('layer-a')])),documentGeneration: 0,}),- captureCompositeTransaction: async (documentSnapshot, layerIds) => {+ captureRasterSnapshot: async (documentSnapshot, layerIds) => {const layerSurfaces = new Map<string, { surface: RasterSurface; rect: Rect }>();for (const layerId of layerIds) {layerSurfaces.set(layerId, await getLayerSurface(layerId));}- const transactionDedupe = createCompositeDedupeCache();- for (const [key, value] of dedupe.byHash) {- transactionDedupe.byHash.set(key, value);- }- for (const [key, value] of dedupe.byKey) {- transactionDedupe.byKey.set(key, value);- }- const compositeDeps: ExecuteCompositePlanDeps = {- ...executorDeps,- dedupe: transactionDedupe,- getLayerSurface: (layerId) => {- const detached = layerSurfaces.get(layerId);- return detached ? Promise.resolve(detached) : Promise.reject(new Error(`Missing ${layerId}`));- },- };- const transaction: CanvasCompositeTransaction = {- canvas: documentSnapshot.canvas,- commit: () => {- for (const [key, value] of transactionDedupe.byHash) {- dedupe.byHash.set(key, value);- }- for (const [key, value] of transactionDedupe.byKey) {- dedupe.byKey.set(key, value);- }+ return {+ status: 'ok',+ snapshot: {+ canvas: documentSnapshot.canvas,+ documentGeneration: documentSnapshot.documentGeneration,+ emptyLayerIds: new Set<string>(),+ layerSurfaces,+ release: releaseRasterSnapshot,},- executeControl: (entry) => executeControlComposite(entry, compositeDeps),- executeMask: (entry) => executeMaskComposite(entry, compositeDeps),- executePlan: (plan) => executeCompositePlan(plan, compositeDeps),- executeRegionalMask: (entry) => executeRegionalMaskComposite(entry, compositeDeps),- release: releaseRasterSnapshot,};- return { status: 'ok', transaction };},+ dedupe,+ getCompositeExecutorDeps: () => executorDeps,+ };++ const deps: RunCanvasInvocationDeps = {+ composeForGeneration: (composeOptions) => composeForGeneration(host, composeOptions),compositing: DEFAULT_CANVAS_COMPOSITING,destination: options.destination ?? 'canvas',commands: {@@ -264,6 +250,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {executorDeps,events,flushPendingUploads,+ host,notices,releaseRasterSnapshot,submittedGraphs,@@ -436,7 +423,7 @@ describe('runCanvasInvocation', () => {}),});// Return the stale doc until the flush resolves, the fresh doc afterwards.- harness.deps.captureDocumentSnapshot = () => ({+ harness.host.captureDocumentSnapshot = () => ({canvas: {document: structuredClone(flushed ? postDoc : preDoc),documentRevision: 0,@@ -480,9 +467,9 @@ describe('runCanvasInvocation', () => {},documentGeneration: 0,};- Object.assign(harness.deps, {+ Object.assign(harness.host, {captureDocumentSnapshot: vi.fn(() => snapshot),- captureCompositeTransaction: vi.fn(() => Promise.resolve({ status: 'stale' as const })),+ captureRasterSnapshot: vi.fn(() => Promise.resolve({ status: 'stale' as const })),});await runCanvasInvocation(harness.deps);@@ -497,7 +484,7 @@ describe('runCanvasInvocation', () => {'does not submit when raster capture returns the typed %s outcome',async (status) => {const harness = makeHarness();- harness.deps.captureCompositeTransaction = vi.fn(() => Promise.resolve({ status }));+ harness.host.captureRasterSnapshot = vi.fn(() => Promise.resolve({ status }));await runCanvasInvocation(harness.deps);@@ -511,13 +498,14 @@ describe('runCanvasInvocation', () => {it('passes the orchestration AbortSignal into raster snapshot capture', async () => {const harness = makeHarness();const controller = new AbortController();- const captureCompositeTransaction = vi.fn(() => Promise.resolve({ status: 'aborted' as const }));- Object.assign(harness.deps, { captureCompositeTransaction, signal: controller.signal });+ const captureRasterSnapshot = vi.fn(() => Promise.resolve({ status: 'aborted' as const }));+ harness.host.captureRasterSnapshot = captureRasterSnapshot;+ harness.deps.signal = controller.signal;controller.abort(new DOMException('invoke cancelled', 'AbortError'));await runCanvasInvocation(harness.deps);- expect(captureCompositeTransaction).toHaveBeenCalledWith(+ expect(captureRasterSnapshot).toHaveBeenCalledWith(expect.any(Object),['layer-a'],expect.objectContaining({ signal: controller.signal })@@ -532,7 +520,7 @@ describe('runCanvasInvocation', () => {liveDocument = { ...liveDocument, bbox: { height: 96, width: 96, x: 303, y: 404 } };});const harness = makeHarness({ dispatch, document: liveDocument });- harness.deps.captureDocumentSnapshot = () => ({+ harness.host.captureDocumentSnapshot = () => ({canvas: {document: structuredClone(liveDocument),documentRevision: 4,@@ -549,11 +537,11 @@ describe('runCanvasInvocation', () => {},documentGeneration: 9,});- const captureCompositeTransaction = harness.deps.captureCompositeTransaction;- harness.deps.captureCompositeTransaction = async (snapshot, layerIds) => {- const result = await captureCompositeTransaction(snapshot, layerIds, { signal: harness.deps.signal });- // The transaction is fully detached at this boundary. Subsequent edits- // must not alter any composite/upload/compile/dispatch input.+ const captureRasterSnapshot = harness.host.captureRasterSnapshot;+ harness.host.captureRasterSnapshot = async (snapshot, layerIds, captureOptions) => {+ const result = await captureRasterSnapshot(snapshot, layerIds, captureOptions);+ // The composite inputs are fully detached at this boundary. Subsequent+ // edits must not alter any composite/upload/compile/dispatch input.liveDocument = {...liveDocument,bbox: { height: 64, width: 64, x: 101, y: 202 },@@ -578,7 +566,7 @@ describe('runCanvasInvocation', () => {async (boundary) => {let liveDocument = makeDoc([rasterLayer('layer-a')]);const harness = makeHarness({ document: liveDocument });- harness.deps.captureDocumentSnapshot = () => ({+ harness.host.captureDocumentSnapshot = () => ({canvas: {document: structuredClone(liveDocument),documentRevision: 2,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex 2d8f3d178e..06590e5398 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -2,20 +2,24 @@* Wires the canvas-generation pipeline into the Invoke button.** `prepareCanvasInvocation` is the thin command-layer entry: it resolves the- * active project's engine, scopes a per-engine dedupe cache, and delegates to- * the React-free {@link runCanvasInvocation} orchestrator. The orchestrator runs- * the whole flush → composite → mode-detect → compile → enqueue flow with every- * side-effecting dependency injected, so it is fully node-testable with fakes.+ * active project's engine and delegates to the React-free+ * {@link runCanvasInvocation} orchestrator. The orchestrator runs the whole+ * flush → compose → compile → enqueue flow with every side-effecting dependency+ * injected, so it is fully node-testable with fakes.** ## Flow (per the plan)- * 1. Resolve the engine + its live document (no engine/document → notice, abort).+ * 1. Resolve the engine (no engine → notice, abort) and normalize/sync the+ * generate values exactly as the generate path does.* 2. `flushPendingUploads()` — the paint-bitmap persistence barrier — so the- * composite reads the latest painted pixels.- * 3. Plan the composites, then run a **bounds-only pre-pass**: if enabled raster- * content does not overlap the bbox, the mode is txt2img regardless of- * coverage, so we skip the composite/encode/upload entirely (no useless base- * image). Only when content overlaps do we run the executor (which the- * image-referencing modes need) and detect img2img/outpaint from coverage.+ * composite reads the latest painted pixels. The composite operation+ * captures its document snapshot internally, AFTER this barrier, so it+ * plans from the post-flush document (fresh bitmap refs, fresh bbox).+ * 3. `composeForGeneration` — Canvas's one deep composite call — produces+ * every uploaded image (base / masks / controls / regionals) plus the+ * resolved mode. This module supplies the policy: `detectCanvasMode` as the+ * mode strategy, control validation as a throwing predicate (an invalid+ * enabled nonempty control layer blocks the invoke), and regional-guidance+ * rejection as a silent-skip predicate.* 4. Compile the base-appropriate graph and dispatch it to canvas staging.* 5. Any failure (validation throw, upload error, unsupported mode) records a* notice — the app never gets stuck.@@ -27,10 +31,11 @@import type { GenerateModelConfig } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import type {- CanvasDocumentSnapshot,- CanvasDocumentContractV2,+ CanvasControlLayerContract,+ CanvasRegionalGuidanceLayerContract,RegionalGuidanceReferenceImage,} from '@workbench/canvas-engine/api';+import type { ComposeForGenerationOptions, ComposeForGenerationResult } from '@workbench/canvas-operations/api';import type { ResultDestination } from '@workbench/invocationContracts';import type { WorkbenchNotificationKind } from '@workbench/projectContracts';import type { ProjectSettings } from '@workbench/settings/contracts';@@ -42,7 +47,6 @@ import {getControlValidationReason,getRegionalGuidanceRejectionReason,isRegionalGuidanceSupportedForBase,- rectsIntersect,type CanvasCompileMode,type ControlLayerGraphInput,type RegionalGuidanceInput,@@ -50,16 +54,7 @@ import {} from '@features/generation/canvas';import { resolveGenerateSeed } from '@features/generation/graph';import { normalizeGenerateWidgetValues, syncGenerateWidgetValuesWithModels } from '@features/generation/settings';-import {- computeCompositeContentBounds,- getCanvasEngine,- getCanvasOperations,- type CanvasCompositeTransaction,- type CanvasCompositeTransactionResult,- planComposites,- planControlComposites,- planRegionalMaskComposites,-} from '@workbench/canvas-operations/api';+import { getCanvasEngine, getCanvasOperations } from '@workbench/canvas-operations/api';import {DEFAULT_CANVAS_COMPOSITING,type CanvasCompositingSettings,@@ -78,15 +73,12 @@ export interface RunCanvasInvocationDeps {* snapshot's destination, so a Canvas source can target the Gallery.*/destination: ResultDestination;- /** Captures the exact post-flush canvas contract used by immutable invocation transactions. */- captureDocumentSnapshot: () => CanvasDocumentSnapshot | null;- /** Detaches every layer surface required by the transaction's complete composite plan. */- captureCompositeTransaction: (- snapshot: CanvasDocumentSnapshot,- layerIds: readonly string[],- options: { signal: AbortSignal }- ) => Promise<CanvasCompositeTransactionResult>;- /** Cancels cache preparation and detachment for this invocation transaction. */+ /**+ * Canvas's composite-generation operation: snapshot → plan → capture →+ * composite → upload, releasing pixel resources on both success and failure.+ */+ composeForGeneration: (options: ComposeForGenerationOptions) => Promise<ComposeForGenerationResult>;+ /** Cancels raster capture for this invocation. */signal: AbortSignal;/** Paint-bitmap persistence barrier, awaited before compositing. */flushPendingUploads: () => Promise<void>;@@ -114,76 +106,70 @@ const recordNotice = (};/**- * Composites + resolves the enabled control layers into graph inputs. Each- * content-bearing control layer is composited SEPARATELY (never blended) and its- * adapter model resolved from the loaded models. Enabled nonempty invalid layers- * throw a shared reason code and block invocation; content-less control layers- * are already excluded by `planControlComposites` and remain harmless.+ * Control-layer policy + metadata side-channel for the composite operation.+ * `shouldComposite` validates each enabled content-bearing control layer in+ * z-order and resolves its adapter model from the loaded models: an invalid+ * layer throws a shared reason code and blocks the invocation (content-less+ * control layers are already excluded by the operation's plan and remain+ * harmless). `toGraphInputs` joins the composited image names back with the+ * recorded adapter/model metadata.*/-const collectControlLayerInputs = async (- document: CanvasDocumentContractV2,- bbox: { x: number; y: number; width: number; height: number },+const createControlLayerCollector = (model: GenerateModelConfig,- models: readonly ModelConfig[] | undefined,- transaction: Pick<CanvasCompositeTransaction, 'executeControl'>-): Promise<ControlLayerGraphInput[]> => {- const composites = planControlComposites(document, bbox);- if (composites.length === 0) {- return [];- }-- const layerById = new Map(document.layers.map((layer) => [layer.id, layer]));- const inputs: ControlLayerGraphInput[] = [];+ models: readonly ModelConfig[] | undefined+): {+ shouldComposite(layer: CanvasControlLayerContract): boolean;+ toGraphInputs(images: readonly { layerId: string; imageName: string }[]): ControlLayerGraphInput[];+} => {+ const metadata = new Map<string, Omit<ControlLayerGraphInput, 'imageName'>>();let controlLoraCount = 0;let zImageControlCount = 0;- for (const { entry, layerId } of composites) {- const layer = layerById.get(layerId);- if (!layer || layer.type !== 'control') {- continue;- }-- const { adapter } = layer;- const resolved = adapter.model ? models?.find((candidate) => candidate.key === adapter.model) : undefined;- const rejection = getControlValidationReason({- adapterModel: resolved ? { base: resolved.base, type: resolved.type } : null,- beginEndStepPct: adapter.beginEndStepPct,- controlLoraIndex: adapter.kind === 'control_lora' ? controlLoraCount : 0,- kind: adapter.kind,- mainBase: model.base,- mainVariant: model.variant ?? undefined,- weight: adapter.weight,- zImageControlIndex: adapter.kind === 'z_image_control' ? zImageControlCount : 0,- });- if (rejection || !resolved) {- throw new Error(`[${rejection ?? 'missing_model'}] Control layer "${layer.name}" is invalid.`);- }- if (adapter.kind === 'control_lora') {- controlLoraCount += 1;- }- if (adapter.kind === 'z_image_control') {- zImageControlCount += 1;- }-- const result = await transaction.executeControl(entry);- inputs.push({- beginEndStepPct: adapter.beginEndStepPct,- controlMode: adapter.controlMode,- id: layerId,- imageName: result.imageName,- kind: adapter.kind,- model: {- base: resolved.base,- key: resolved.key,- name: resolved.name,- type: resolved.type,- ...(typeof resolved.hash === 'string' ? { hash: resolved.hash } : {}),- },- weight: adapter.weight,- });- }-- return inputs;+ return {+ shouldComposite: (layer) => {+ const { adapter } = layer;+ const resolved = adapter.model ? models?.find((candidate) => candidate.key === adapter.model) : undefined;+ const rejection = getControlValidationReason({+ adapterModel: resolved ? { base: resolved.base, type: resolved.type } : null,+ beginEndStepPct: adapter.beginEndStepPct,+ controlLoraIndex: adapter.kind === 'control_lora' ? controlLoraCount : 0,+ kind: adapter.kind,+ mainBase: model.base,+ mainVariant: model.variant ?? undefined,+ weight: adapter.weight,+ zImageControlIndex: adapter.kind === 'z_image_control' ? zImageControlCount : 0,+ });+ if (rejection || !resolved) {+ throw new Error(`[${rejection ?? 'missing_model'}] Control layer "${layer.name}" is invalid.`);+ }+ if (adapter.kind === 'control_lora') {+ controlLoraCount += 1;+ }+ if (adapter.kind === 'z_image_control') {+ zImageControlCount += 1;+ }+ metadata.set(layer.id, {+ beginEndStepPct: adapter.beginEndStepPct,+ controlMode: adapter.controlMode,+ id: layer.id,+ kind: adapter.kind,+ model: {+ base: resolved.base,+ key: resolved.key,+ name: resolved.name,+ type: resolved.type,+ ...(typeof resolved.hash === 'string' ? { hash: resolved.hash } : {}),+ },+ weight: adapter.weight,+ });+ return true;+ },+ toGraphInputs: (images) =>+ images.flatMap(({ imageName, layerId }) => {+ const meta = metadata.get(layerId);+ return meta ? [{ ...meta, imageName }] : [];+ }),+ };};/** FLUX Redux image-influence → backend redux settings (mirrors `graph.ts` FLUX_REDUX_INFLUENCE). */@@ -249,61 +235,54 @@ export const resolveRegionalReferenceImages = (};/**- * Composites + resolves the enabled regional-guidance regions into graph inputs.- * Each region with mask content is composited SEPARATELY (its alpha feeds its own- * `alpha_mask_to_tensor`); regions invalid for the base (unsupported base, empty,- * FLUX + negative/autoNegative) are skipped silently, mirroring legacy. Regions- * whose prompts + reference images are all empty are also skipped.+ * Regional-guidance policy + metadata side-channel for the composite operation.+ * `shouldComposite` resolves each region's reference images and rejects regions+ * invalid for the base (unsupported base, FLUX + negative/autoNegative, all+ * prompts + references empty) with a SILENT skip, mirroring legacy.+ * `toGraphInputs` joins the composited mask image names back with the recorded+ * prompt/reference metadata.*/-const collectRegionalGuidanceInputs = async (- document: CanvasDocumentContractV2,- bbox: { x: number; y: number; width: number; height: number },- model: GenerateModelConfig,- transaction: Pick<CanvasCompositeTransaction, 'executeRegionalMask'>-): Promise<RegionalGuidanceInput[]> => {- if (!isRegionalGuidanceSupportedForBase(model.base)) {- return [];- }- const composites = planRegionalMaskComposites(document, bbox);- if (composites.length === 0) {- return [];- }-- const layerById = new Map(document.layers.map((layer) => [layer.id, layer]));- const inputs: RegionalGuidanceInput[] = [];-- for (const { entry, layerId } of composites) {- const layer = layerById.get(layerId);- if (!layer || layer.type !== 'regional_guidance') {- continue;- }-- const referenceImages = resolveRegionalReferenceImages(layer, model.base);- const rejection = getRegionalGuidanceRejectionReason({- autoNegative: layer.autoNegative,- hasContent: true,- layerName: layer.name,- mainBase: model.base,- negativePrompt: layer.negativePrompt,- positivePrompt: layer.positivePrompt,- referenceImageCount: referenceImages.length,- });- if (rejection) {- continue;- }-- const result = await transaction.executeRegionalMask(entry);- inputs.push({- autoNegative: layer.autoNegative,- id: layerId,- maskImageName: result.imageName,- negativePrompt: layer.negativePrompt,- positivePrompt: layer.positivePrompt,- referenceImages,- });- }-- return inputs;+const createRegionalGuidanceCollector = (+ model: GenerateModelConfig+): {+ shouldComposite(layer: CanvasRegionalGuidanceLayerContract): boolean;+ toGraphInputs(images: readonly { layerId: string; imageName: string }[]): RegionalGuidanceInput[];+} => {+ const metadata = new Map<string, Omit<RegionalGuidanceInput, 'maskImageName'>>();++ return {+ shouldComposite: (layer) => {+ if (!isRegionalGuidanceSupportedForBase(model.base)) {+ return false;+ }+ const referenceImages = resolveRegionalReferenceImages(layer, model.base);+ const rejection = getRegionalGuidanceRejectionReason({+ autoNegative: layer.autoNegative,+ hasContent: true,+ layerName: layer.name,+ mainBase: model.base,+ negativePrompt: layer.negativePrompt,+ positivePrompt: layer.positivePrompt,+ referenceImageCount: referenceImages.length,+ });+ if (rejection) {+ return false;+ }+ metadata.set(layer.id, {+ autoNegative: layer.autoNegative,+ id: layer.id,+ negativePrompt: layer.negativePrompt,+ positivePrompt: layer.positivePrompt,+ referenceImages,+ });+ return true;+ },+ toGraphInputs: (images) =>+ images.flatMap(({ imageName, layerId }) => {+ const meta = metadata.get(layerId);+ return meta ? [{ ...meta, maskImageName: imageName }] : [];+ }),+ };};/**@@ -321,7 +300,6 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis}inFlight.add(projectId);- let transaction: CanvasCompositeTransaction | null = null;try {const values = normalizeGenerateWidgetValues(deps.generateValues);if (!values) {@@ -336,114 +314,52 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promisconst model: GenerateModelConfig = settings.model;// Persist any pending paint bitmaps BEFORE compositing from their pixels.+ // The composite operation captures its document snapshot internally — after+ // this barrier — so it plans from the post-flush document: the flush+ // dispatches `updateCanvasLayerSource` for each just-persisted paint layer,+ // and a pre-flush snapshot would still reference `paint:empty`/stale bitmap+ // names (silent dedupe cache misses) and a possibly-moved bbox.await deps.flushPendingUploads();- // Re-read the document AFTER the flush barrier: the flush dispatches- // `updateCanvasLayerSource` for each just-persisted paint layer, so the- // pre-flush snapshot still references `paint:empty`/stale bitmap names. Plan,- // composite, and compile from the post-flush document so the dedupe keys are- // built from the persisted refs (silent cache misses otherwise) and so the- // empty-paint-layer filter (see `planComposites`) sees the real `bitmap`.- // The bbox can also move during a slow flush; take it from the fresh snapshot.- const documentSnapshot = deps.captureDocumentSnapshot();- if (!documentSnapshot) {- recordNotice(commands.notifications, 'error', 'The canvas has no active document to generate from.');- return;- }- const postFlushDocument = documentSnapshot.canvas.document;- const bbox = postFlushDocument.bbox;-- const plan = planComposites(postFlushDocument, bbox);- const controlPlan = planControlComposites(postFlushDocument, bbox);- const regionalPlan = planRegionalMaskComposites(postFlushDocument, bbox);-- const requiredLayerIds = new Set<string>();- for (const entry of [- ...plan.entries,- ...controlPlan.map((item) => item.entry),- ...regionalPlan.map((item) => item.entry),- ]) {- for (const layer of entry.layers) {- requiredLayerIds.add(layer.id);- }- for (const layer of entry.maskLayers ?? []) {- requiredLayerIds.add(layer.id);- }- }- const capture = await deps.captureCompositeTransaction(documentSnapshot, [...requiredLayerIds], {+ const controls = createControlLayerCollector(model, deps.models);+ const regions = createRegionalGuidanceCollector(model);+ const composed = await deps.composeForGeneration({+ // Mode-union drift guard: `detectCanvasMode`'s facts/mode types must stay+ // structurally identical to canvas-operations' `GenerationModeFacts` /+ // `GenerationCompositeMode` — tsc fails here on drift in either direction.+ detectMode: (facts) => detectCanvasMode(facts),+ shouldCompositeControlLayer: controls.shouldComposite,+ shouldCompositeRegionalMask: regions.shouldComposite,signal: deps.signal,});- if (capture.status !== 'ok') {+ if (composed.status !== 'ok') {recordNotice(commands.notifications,'error',- capture.status === 'stale'- ? 'The canvas changed while generation was being prepared. Please invoke again.'- : `The canvas could not be captured for generation (${capture.status}).`+ composed.status === 'no-document'+ ? 'The canvas has no active document to generate from.'+ : composed.status === 'stale'+ ? 'The canvas changed while generation was being prepared. Please invoke again.'+ : `The canvas could not be captured for generation (${composed.status}).`);return;}- transaction = capture.transaction;- const canvasSnapshot = transaction.canvas;- // Bounds-only pre-pass (pure geometry, no upload): content that does not- // overlap the bbox is txt2img no matter the coverage. Also naturally skips a- // zero-area bbox (rectsIntersect is false), which validation rejects anyway.- const contentBounds = computeCompositeContentBounds(plan);-- let mode: CanvasCompileMode = 'txt2img';- let compositeImageName: string | null = null;- let maskImageName: string | null = null;- let noiseMaskImageName: string | null = null;-- if (contentBounds && rectsIntersect(contentBounds, bbox)) {- const result = await transaction.executePlan(plan);- compositeImageName = result.base.imageName;-- // The grayscale denoise-limit mask (when enabled inpaint masks exist) both- // decides inpaint-vs-img2img (its coverage) and feeds the graph. Legacy- // parity: raster opaque + mask has content → inpaint; else img2img.- const maskEntry = plan.entries.find((entry) => entry.kind === 'inpaint-mask');- const maskResult = maskEntry ? await transaction.executeMask(maskEntry) : null;-- const detected = detectCanvasMode({- bbox,- bboxFullyCovered: result.bboxFullyCovered,- contentBounds: result.contentBounds,- hasActiveInpaintMask: maskResult?.hasContent ?? false,- });- mode = detected;-- if (detected === 'inpaint' || detected === 'outpaint') {- // A real (non-white) mask feeds create_gradient_mask; outpaint without one- // derives its mask from the raster alpha (maskImageName stays null).- maskImageName = maskResult?.hasContent ? maskResult.imageName : null;- const noiseEntry = plan.entries.find((entry) => entry.kind === 'noise-mask');- if (noiseEntry) {- noiseMaskImageName = (await transaction.executeMask(noiseEntry)).imageName;- }- }- }-- // Control layers apply in every mode, independent of the base composite —- // composite + resolve them regardless of whether raster content overlaps.- const controlLayers = await collectControlLayerInputs(postFlushDocument, bbox, model, deps.models, transaction);-- // Regional guidance also applies in every mode, independent of the base- // composite — composite + resolve each region regardless of raster overlap.- const regionalGuidance = await collectRegionalGuidanceInputs(postFlushDocument, bbox, model, transaction);+ const { composites } = composed;+ // The other half of the mode-union drift guard (see `detectMode` above).+ const mode: CanvasCompileMode = composites.mode;const compiled = compileCanvasGraph({- bbox,- compositeImageName,+ bbox: composites.bbox,+ compositeImageName: composites.baseImageName,compositing: deps.compositing,- controlLayers,+ controlLayers: controls.toGraphInputs(composites.controlImages),destination: deps.destination,- maskImageName,+ maskImageName: composites.maskImageName,mode,model,- noiseMaskImageName,+ noiseMaskImageName: composites.noiseMaskImageName,projectSettings: deps.projectSettings,- regionalGuidance,+ regionalGuidance: regions.toGraphInputs(composites.regionalMaskImages),settings,strength: deps.strength,});@@ -458,14 +374,12 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promisvalues: settings,},graph: compiled.graph,- canvas: canvasSnapshot,+ canvas: composites.canvas,projectId,});- transaction.commit();} catch (error) {recordNotice(commands.notifications, 'error', error instanceof Error ? error.message : String(error));} finally {- transaction?.release();inFlight.delete(projectId);}};@@ -507,9 +421,7 @@ export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs)compositing: args.compositing ?? DEFAULT_CANVAS_COMPOSITING,destination: args.destination,commands: args.commands,- captureDocumentSnapshot: () => engine.document.captureSnapshot(),- captureCompositeTransaction: (snapshot, layerIds, options) =>- operations.captureCompositeTransaction(snapshot, layerIds, options),+ composeForGeneration: (composeOptions) => operations.composeForGeneration(composeOptions),flushPendingUploads: () => engine.lifecycle.flushPendingUploads(),generateValues: args.generateValues,inFlight: inFlightProjects,