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
fix(canvas): normalize off-grid bbox processing
Josh Corbett1cc51f8a1519
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex 599ff4bcb5..271b5c9bb0 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@ -461,12 +461,120 @@ describe('compileCanvasGraph', () => {);});- it('rejects off-grid bbox dimensions', () => {- expect(() => compile(flux2Model, 'txt2img', { bbox: { height: 888, width: 1024, x: 0, y: 0 } })).toThrow(- 'Generate height must be a multiple of 16.'+ it('rejects fractional bbox dimensions before emitting backend resize fields', () => {+ expect(() => compile(flux2Model, 'txt2img', { bbox: { height: 888, width: 1024.5, x: 0, y: 0 } })).toThrow(+ 'Canvas bounding box dimensions must be whole pixels.');});+ it('processes an off-grid bbox on the model grid and resizes the output back to the bbox', () => {+ const { backendGraph } = compile(flux2Model, 'txt2img', {+ bbox: { height: 888, width: 1025, x: 0, y: 0 },+ });++ expect(backendGraph.nodes.denoise_latents).toMatchObject({ height: 896, width: 1024 });+ expect(backendGraph.nodes.canvas_output).toMatchObject({+ height: 888,+ type: 'img_resize',+ width: 1025,+ });+ expect(getEdge(backendGraph, 'canvas_output', 'image')?.source.node_id).toBe('canvas_processing_output');+ expect(getNodeByType(backendGraph, 'core_metadata')).toMatchObject({ height: 888, width: 1025 });+ expect(getEdge(backendGraph, 'canvas_output', 'metadata')?.source.node_id).toBe(+ getNodeByType(backendGraph, 'core_metadata')?.id+ );+ });++ it('does not silently upscale a small grid-valid bbox to the model optimal area', () => {+ const { backendGraph } = compile(sd1Model, 'txt2img', {+ bbox: { height: 64, width: 64, x: 0, y: 0 },+ });++ expect(backendGraph.nodes.noise).toMatchObject({ height: 64, width: 64 });+ expect(backendGraph.nodes.canvas_processing_output).toBeUndefined();+ expect(backendGraph.nodes.canvas_output?.type).toBe('l2i');+ });++ it('resizes an off-grid img2img source before processing and restores the bbox footprint', () => {+ const { backendGraph } = compile(flux2Model, 'img2img', {+ bbox: { height: 888, width: 1025, x: 0, y: 0 },+ });++ expect(backendGraph.nodes.canvas_resize_initial_to_processing).toMatchObject({+ height: 896,+ type: 'img_resize',+ width: 1024,+ });+ expect(getEdge(backendGraph, 'canvas_i2l', 'image')?.source.node_id).toBe('canvas_resize_initial_to_processing');+ expect(backendGraph.nodes.canvas_output).toMatchObject({ height: 888, type: 'img_resize', width: 1025 });+ });++ it('resizes off-grid inpaint inputs for processing, then composites at the exact bbox size', () => {+ const { backendGraph } = compile(flux2Model, 'inpaint', {+ bbox: { height: 888, width: 1025, x: 0, y: 0 },+ });++ expect(backendGraph.nodes.canvas_resize_initial_to_processing).toMatchObject({ height: 896, width: 1024 });+ expect(backendGraph.nodes.canvas_resize_mask_to_processing).toMatchObject({ height: 896, width: 1024 });+ expect(backendGraph.nodes.canvas_resize_generated_to_bbox).toMatchObject({ height: 888, width: 1025 });+ expect(backendGraph.nodes.canvas_resize_output_mask_to_bbox).toMatchObject({ height: 888, width: 1025 });+ expect(getEdge(backendGraph, 'canvas_output', 'layer_upper')?.source.node_id).toBe(+ 'canvas_resize_generated_to_bbox'+ );+ expect(getEdge(backendGraph, 'canvas_output', 'mask')?.source.node_id).toBe('canvas_resize_output_mask_to_bbox');+ });++ it('resizes the combined off-grid outpaint mask for processing, then composites at the bbox size', () => {+ const { backendGraph } = compile(flux2Model, 'outpaint', {+ bbox: { height: 888, width: 1025, x: 0, y: 0 },+ });++ expect(backendGraph.nodes.canvas_resize_initial_to_processing).toMatchObject({ height: 896, width: 1024 });+ expect(backendGraph.nodes.canvas_resize_outpaint_mask_to_processing).toMatchObject({+ height: 896,+ width: 1024,+ });+ expect(backendGraph.nodes.canvas_resize_generated_to_bbox).toMatchObject({ height: 888, width: 1025 });+ expect(backendGraph.nodes.canvas_resize_output_mask_to_bbox).toMatchObject({ height: 888, width: 1025 });+ });++ it.each(['inpaint', 'outpaint'] as const)(+ 'resizes an off-grid %s noise mask before applying it to the processing image',+ (mode) => {+ const { backendGraph } = compile(flux2Model, mode, {+ bbox: { height: 888, width: 1025, x: 0, y: 0 },+ noiseMaskImageName: 'noise-mask.png',+ });++ expect(backendGraph.nodes.canvas_resize_noise_mask_to_processing).toMatchObject({+ height: 896,+ image: { image_name: 'noise-mask.png' },+ type: 'img_resize',+ width: 1024,+ });+ expect(getEdge(backendGraph, 'add_inpaint_noise', 'mask')?.source.node_id).toBe(+ 'canvas_resize_noise_mask_to_processing'+ );+ expect(getEdge(backendGraph, 'add_inpaint_noise', 'image')?.source.node_id).toBe(+ mode === 'inpaint' ? 'canvas_resize_initial_to_processing' : 'infill'+ );+ }+ );++ it('keeps an off-grid masked-only output transparent at the exact bbox size', () => {+ const { backendGraph } = compile(flux2Model, 'inpaint', {+ bbox: { height: 888, width: 1025, x: 0, y: 0 },+ outputOnlyMaskedRegions: true,+ });++ expect(backendGraph.nodes.canvas_output).toMatchObject({+ invert_mask: true,+ type: 'apply_mask_to_image',+ });+ expect(getEdge(backendGraph, 'canvas_output', 'image')?.source.node_id).toBe('canvas_resize_generated_to_bbox');+ expect(getEdge(backendGraph, 'canvas_output', 'mask')?.source.node_id).toBe('canvas_resize_output_mask_to_bbox');+ });+it('surfaces missing-component validation for the bbox-sized settings', () => {// FLUX with no component overrides fails the shared generate validation.expect(() =>diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex 9687c6b28a..e9b0b11652 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -11,7 +11,9 @@** 1. Build the base txt2img graph via `GRAPH_BUILDERS[model.base]` with the* canvas destination (`outputIsIntermediate = true`) and a settings copy whose- * width/height are the bbox size (builders read dims from settings).+ * width/height are snapped to the model's processing grid. The bbox remains+ * the exact final canvas footprint; off-grid inputs are resized before+ * processing and outputs are resized back before staging or saving.* 2. For `img2img`, add a base-appropriate image-to-latents encode node fed by* the composite image + the graph's VAE source, wire its latents into* `denoise_latents.latents`, and set `denoising_start = 1 - strength`.@@ -27,11 +29,15 @@ import type { SupportedGenerateBase } from '@features/generation/core/baseGeneraimport type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { getGenerationValidationReasons } from '@features/generation/core/baseGenerationPolicies';+import {+ getGenerationDimensions,+ getGenerationValidationReasons,+} from '@features/generation/core/baseGenerationPolicies';import { GRAPH_BUILDERS } from '@features/generation/core/graph';import { addEdge, addNode, toGraphContract } from '@features/generation/core/graphBuilder';import { addKrea2ConditioningEnhancers } from '@features/generation/core/krea2Conditioning';import { getIsPidSupportedBase } from '@features/generation/core/pid';+import { clampDimension } from '@features/generation/core/settings';import type {CanvasCompositingSettings,@@ -92,6 +98,31 @@ const canvasDenoisingStart = (model: GenerateModelConfig, strength: number): num/** True for the image-referencing modes (everything but pure txt2img). */const isImageMode = (mode: CompileCanvasGraphInput['mode']): boolean => mode !== 'txt2img';+interface CanvasSize {+ width: number;+ height: number;+}++const getCanvasProcessingSize = (+ model: GenerateModelConfig,+ settings: GenerateSettings,+ bbox: CompileCanvasGraphInput['bbox']+): CanvasSize => {+ const { grid } = getGenerationDimensions(model, settings.pidMode);++ // Normalize only the model's hard dimension constraints. Legacy canvas also+ // had an optional "Scale Before Processing" policy that upscaled small bboxes+ // to the model's optimal pixel area; webv2 keeps Generate dimensions+ // user-controlled and must not silently add that compute/quality policy here.+ return {+ height: clampDimension(bbox.height, grid),+ width: clampDimension(bbox.width, grid),+ };+};++const sizesMatch = (left: CanvasSize, right: CanvasSize): boolean =>+ left.width === right.width && left.height === right.height;+/** Canvas-specific validation reasons layered on top of the shared generate ones. */const getCanvasValidationReasons = (input: CompileCanvasGraphInput): string[] => {const { bbox, compositeImageName, maskImageName, mode, model, strength } = input;@@ -112,6 +143,8 @@ const getCanvasValidationReasons = (input: CompileCanvasGraphInput): string[] =>if (!Number.isFinite(bbox.width) || !Number.isFinite(bbox.height) || bbox.width <= 0 || bbox.height <= 0) {reasons.push('Canvas bounding box must have a positive area.');+ } else if (!Number.isInteger(bbox.width) || !Number.isInteger(bbox.height)) {+ reasons.push('Canvas bounding box dimensions must be whole pixels.');}if (isImageMode(mode)) {@@ -133,11 +166,11 @@ const getCanvasValidationReasons = (input: CompileCanvasGraphInput): string[] =>return reasons;};-/** The settings a base builder sees: identical to the widget's, but sized to the bbox. */-const withBboxDimensions = (settings: GenerateSettings, bbox: CompileCanvasGraphInput['bbox']): GenerateSettings => ({+/** The settings a base builder sees: identical to the widget's, but sized to the model-valid processing frame. */+const withProcessingDimensions = (settings: GenerateSettings, processingSize: CanvasSize): GenerateSettings => ({...settings,- height: bbox.height,- width: bbox.width,+ height: processingSize.height,+ width: processingSize.width,});/** Locates the node + field feeding a decode/denoise input edge (e.g. `canvas_output.vae`). */@@ -186,6 +219,47 @@ const renameNode = (graph: BackendGraphContract, oldId: string, newId: string):return node;};+/** Resizes a model-grid processing output back to the bbox's exact final footprint. */+const resizeCanvasOutputToBbox = (+ graph: BackendGraphContract,+ bbox: CompileCanvasGraphInput['bbox'],+ processingSize: CanvasSize,+ destination: CompileCanvasGraphInput['destination']+): void => {+ if (sizesMatch(bbox, processingSize)) {+ return;+ }++ const processingOutput = renameNode(graph, 'canvas_output', 'canvas_processing_output');+ processingOutput.is_intermediate = true;++ const output = addNode(graph, {+ height: bbox.height,+ id: 'canvas_output',+ is_intermediate: destination === 'canvas',+ type: 'img_resize',+ use_cache: false,+ width: bbox.width,+ });+ addEdge(graph, processingOutput, 'image', output, 'image');++ const metadataEdge = graph.edges.find(+ (edge) => edge.destination.node_id === processingOutput.id && edge.destination.field === 'metadata'+ );+ if (metadataEdge) {+ metadataEdge.destination.node_id = output.id;+ }+};++/** Keeps saved-image metadata aligned to the bbox footprint, not the internal processing size. */+const setCanvasMetadataDimensions = (graph: BackendGraphContract, bbox: CompileCanvasGraphInput['bbox']): void => {+ const metadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');+ if (metadata) {+ metadata.width = bbox.width;+ metadata.height = bbox.height;+ }+};+/** Sets the metadata `generation_mode` variant + strength (legacy parity). */const setMetadataMode = (graph: BackendGraphContract, mode: string, strength: number): void => {const metadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');@@ -214,6 +288,21 @@ const addEncodeNode = (...(isSdI2l(i2lType) ? { fp32: settings.vaePrecision === 'fp32' } : {}),});+const addInputResizeNode = (+ graph: BackendGraphContract,+ id: string,+ imageName: string,+ processingSize: CanvasSize+): BackendInvocationContract =>+ addNode(graph, {+ height: processingSize.height,+ id,+ image: { image_name: imageName },+ is_intermediate: true,+ type: 'img_resize',+ width: processingSize.width,+ });+/** Resolves the encode node type for a supported base (throws otherwise). */const requireI2lType = (model: GenerateModelConfig): string => {if (model.type === 'external_image_generator') {@@ -241,12 +330,20 @@ const graftImageToImage = (model: GenerateModelConfig,settings: GenerateSettings,compositeImageName: string,- strength: number+ strength: number,+ bbox: CompileCanvasGraphInput['bbox'],+ processingSize: CanvasSize): void => {const i2lType = requireI2lType(model);const denoise = requireDenoise(graph);const vaeSource = requireVaeSource(graph);- const encode = addEncodeNode(graph, i2lType, settings, compositeImageName);+ const needsResize = !sizesMatch(bbox, processingSize);+ const encode = addEncodeNode(graph, i2lType, settings, needsResize ? null : compositeImageName);++ if (needsResize) {+ const resize = addInputResizeNode(graph, 'canvas_resize_initial_to_processing', compositeImageName, processingSize);+ addEdge(graph, resize, 'image', encode, 'image');+ }addEdge(graph, vaeSource.node, vaeSource.field, encode, 'vae');addEdge(graph, encode, 'latents', denoise, 'latents');@@ -303,12 +400,16 @@ const graftMaskTail = (initialImageName: string;compositing: CanvasCompositingSettings;destination: CompileCanvasGraphInput['destination'];+ bbox: CompileCanvasGraphInput['bbox'];+ processingSize: CanvasSize;+ gradientImageEdge?: { node: BackendInvocationContract; field: string };/** Either a fixed mask image field or an edge-fed source node. */gradientMaskImage?: { image_name: string };gradientMaskEdge?: { node: BackendInvocationContract; field: string };}): void => {const { compositing, denoise, destination, i2lType, initialImageName, settings, vaeSource } = args;+ const needsResize = !sizesMatch(args.bbox, args.processingSize);// Demote the base decode to an intermediate `canvas_l2i`; the final mask or// composite node claims `canvas_output`.@@ -320,7 +421,7 @@ const graftMaskTail = (edge_radius: compositing.coherenceEdgeSize,fp32: isSdI2l(i2lType) ? settings.vaePrecision === 'fp32' : false,id: 'create_gradient_mask',- image: { image_name: initialImageName },+ ...(args.gradientImageEdge ? {} : { image: { image_name: initialImageName } }),minimum_denoise: compositing.coherenceMinDenoise,type: 'create_gradient_mask',...(args.gradientMaskImage ? { mask: args.gradientMaskImage } : {}),@@ -329,6 +430,9 @@ const graftMaskTail = (if (args.gradientMaskEdge) {addEdge(graph, args.gradientMaskEdge.node, args.gradientMaskEdge.field, gradientMask, 'mask');}+ if (args.gradientImageEdge) {+ addEdge(graph, args.gradientImageEdge.node, args.gradientImageEdge.field, gradientMask, 'image');+ }addEdge(graph, vaeSource.node, vaeSource.field, gradientMask, 'vae');// The optional UNet edge only applies to SD-family models (legacy `isMainModelWithoutUnet`).const unetSource = findEdgeSource(graph, 'denoise_latents', 'unet');@@ -344,6 +448,28 @@ const graftMaskTail = (});addEdge(graph, gradientMask, 'expanded_mask_area', expandMask, 'mask');+ let generatedImageSource: BackendInvocationContract = l2i;+ let outputMaskSource: BackendInvocationContract = expandMask;++ if (needsResize) {+ generatedImageSource = addNode(graph, {+ height: args.bbox.height,+ id: 'canvas_resize_generated_to_bbox',+ is_intermediate: true,+ type: 'img_resize',+ width: args.bbox.width,+ });+ outputMaskSource = addNode(graph, {+ height: args.bbox.height,+ id: 'canvas_resize_output_mask_to_bbox',+ is_intermediate: true,+ type: 'img_resize',+ width: args.bbox.width,+ });+ addEdge(graph, l2i, 'image', generatedImageSource, 'image');+ addEdge(graph, expandMask, 'image', outputMaskSource, 'image');+ }+const output = compositing.outputOnlyMaskedRegions? addNode(graph, {id: 'canvas_output',@@ -359,8 +485,8 @@ const graftMaskTail = (type: 'invokeai_img_blend',use_cache: false,});- addEdge(graph, l2i, 'image', output, compositing.outputOnlyMaskedRegions ? 'image' : 'layer_upper');- addEdge(graph, expandMask, 'image', output, 'mask');+ addEdge(graph, generatedImageSource, 'image', output, compositing.outputOnlyMaskedRegions ? 'image' : 'layer_upper');+ addEdge(graph, outputMaskSource, 'image', output, 'mask');// The base builder wired core_metadata → the decode's `metadata`; `renameNode`// followed it onto the (now intermediate) canvas_l2i. Re-point it to the final@@ -379,7 +505,8 @@ const addNoiseBeforeEncode = (graph: BackendGraphContract,imageName: string,noiseMaskImageName: string | null | undefined,- imageSourceNode: BackendInvocationContract | null+ imageSourceNode: BackendInvocationContract | null,+ noiseMaskSourceNode: BackendInvocationContract | null = null): { imageField?: { image_name: string }; edgeFrom?: BackendInvocationContract } => {if (!noiseMaskImageName) {// No noise mask: encode reads the (infilled) initial image directly.@@ -389,7 +516,7 @@ const addNoiseBeforeEncode = (amount: 1.0,id: 'add_inpaint_noise',...(imageSourceNode ? {} : { image: { image_name: imageName } }),- mask: { image_name: noiseMaskImageName },+ ...(noiseMaskSourceNode ? {} : { mask: { image_name: noiseMaskImageName } }),noise_color: true,noise_type: 'gaussian',type: 'img_noise',@@ -398,6 +525,9 @@ const addNoiseBeforeEncode = (if (imageSourceNode) {addEdge(graph, imageSourceNode, 'image', noise, 'image');}+ if (noiseMaskSourceNode) {+ addEdge(graph, noiseMaskSourceNode, 'image', noise, 'mask');+ }return { edgeFrom: noise };};@@ -405,7 +535,8 @@ const addNoiseBeforeEncode = (const graftInpaint = (graph: BackendGraphContract,input: CompileCanvasGraphInput,- compositing: CanvasCompositingSettings+ compositing: CanvasCompositingSettings,+ processingSize: CanvasSize): void => {const { model } = input;const i2lType = requireI2lType(model);@@ -414,12 +545,30 @@ const graftInpaint = (const initialImageName = input.compositeImageName as string;const maskImageName = input.maskImageName as string;const strength = input.strength;+ const needsResize = !sizesMatch(input.bbox, processingSize);denoise.denoising_start = canvasDenoisingStart(model, strength);denoise.denoising_end = 1;+ const initialResize = needsResize+ ? addInputResizeNode(graph, 'canvas_resize_initial_to_processing', initialImageName, processingSize)+ : null;+ const maskResize = needsResize+ ? addInputResizeNode(graph, 'canvas_resize_mask_to_processing', maskImageName, processingSize)+ : null;+ const noiseMaskResize =+ needsResize && input.noiseMaskImageName+ ? addInputResizeNode(graph, 'canvas_resize_noise_mask_to_processing', input.noiseMaskImageName, processingSize)+ : null;+const encode = addEncodeNode(graph, i2lType, input.settings, null);- const noiseResult = addNoiseBeforeEncode(graph, initialImageName, input.noiseMaskImageName, null);+ const noiseResult = addNoiseBeforeEncode(+ graph,+ initialImageName,+ input.noiseMaskImageName,+ initialResize,+ noiseMaskResize+ );if (noiseResult.edgeFrom) {addEdge(graph, noiseResult.edgeFrom, 'image', encode, 'image');} else if (noiseResult.imageField) {@@ -429,13 +578,18 @@ const graftInpaint = (addEdge(graph, encode, 'latents', denoise, 'latents');graftMaskTail(graph, {+ bbox: input.bbox,compositing,denoise,destination: input.destination,- gradientMaskImage: { image_name: maskImageName },+ ...(initialResize ? { gradientImageEdge: { field: 'image', node: initialResize } } : {}),+ ...(maskResize+ ? { gradientMaskEdge: { field: 'image', node: maskResize } }+ : { gradientMaskImage: { image_name: maskImageName } }),i2lType,initialImageName,model,+ processingSize,settings: input.settings,vaeSource,});@@ -447,7 +601,8 @@ const graftInpaint = (const graftOutpaint = (graph: BackendGraphContract,input: CompileCanvasGraphInput,- compositing: CanvasCompositingSettings+ compositing: CanvasCompositingSettings,+ processingSize: CanvasSize): void => {const { model } = input;const i2lType = requireI2lType(model);@@ -455,13 +610,21 @@ const graftOutpaint = (const vaeSource = requireVaeSource(graph);const initialImageName = input.compositeImageName as string;const strength = input.strength;+ const needsResize = !sizesMatch(input.bbox, processingSize);denoise.denoising_start = canvasDenoisingStart(model, strength);denoise.denoising_end = 1;// Infill the transparent region before encode (legacy `getInfill`).const infill = addInfillNode(graph, compositing.infillMethod, compositing);- infill.image = { image_name: initialImageName };+ const initialResize = needsResize+ ? addInputResizeNode(graph, 'canvas_resize_initial_to_processing', initialImageName, processingSize)+ : null;+ if (initialResize) {+ addEdge(graph, initialResize, 'image', infill, 'image');+ } else {+ infill.image = { image_name: initialImageName };+ }// Derive a mask from the initial image alpha (transparent → generate), combined// with the inpaint mask when one exists.@@ -484,8 +647,25 @@ const graftOutpaint = (gradientMaskEdge = { field: 'image', node: alphaToMask };}+ if (needsResize) {+ const maskResize = addNode(graph, {+ height: processingSize.height,+ id: 'canvas_resize_outpaint_mask_to_processing',+ is_intermediate: true,+ type: 'img_resize',+ width: processingSize.width,+ });+ addEdge(graph, gradientMaskEdge.node, gradientMaskEdge.field, maskResize, 'image');+ gradientMaskEdge = { field: 'image', node: maskResize };+ }++ const noiseMaskResize =+ needsResize && input.noiseMaskImageName+ ? addInputResizeNode(graph, 'canvas_resize_noise_mask_to_processing', input.noiseMaskImageName, processingSize)+ : null;+const encode = addEncodeNode(graph, i2lType, input.settings, null);- const noiseResult = addNoiseBeforeEncode(graph, initialImageName, input.noiseMaskImageName, infill);+ const noiseResult = addNoiseBeforeEncode(graph, initialImageName, input.noiseMaskImageName, infill, noiseMaskResize);if (noiseResult.edgeFrom) {addEdge(graph, noiseResult.edgeFrom, 'image', encode, 'image');}@@ -493,13 +673,16 @@ const graftOutpaint = (addEdge(graph, encode, 'latents', denoise, 'latents');graftMaskTail(graph, {+ bbox: input.bbox,compositing,denoise,destination: input.destination,+ ...(needsResize ? { gradientImageEdge: { field: 'image', node: infill } } : {}),gradientMaskEdge,i2lType,initialImageName,model,+ processingSize,settings: input.settings,vaeSource,});@@ -514,7 +697,8 @@ const graftOutpaint = (*/export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanvasGraph => {const { bbox, compositeImageName, destination, mode, model, projectSettings, strength } = input;- const settings = withBboxDimensions(input.settings, bbox);+ const processingSize = getCanvasProcessingSize(model, input.settings, bbox);+ const settings = withProcessingDimensions(input.settings, processingSize);const validationReasons = [...getCanvasValidationReasons(input), ...getGenerationValidationReasons(model, settings)];@@ -540,11 +724,11 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv// Validation above guarantees the composite/mask images required per mode.if (mode === 'img2img') {- graftImageToImage(backendGraph, model, settings, compositeImageName as string, strength);+ graftImageToImage(backendGraph, model, settings, compositeImageName as string, strength, bbox, processingSize);} else if (mode === 'inpaint') {- graftInpaint(backendGraph, input, compositing);+ graftInpaint(backendGraph, input, compositing, processingSize);} else if (mode === 'outpaint') {- graftOutpaint(backendGraph, input, compositing);+ graftOutpaint(backendGraph, input, compositing, processingSize);}// Control layers apply in every mode (legacy allows control with all). The@@ -586,6 +770,11 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv});}+ if (mode === 'txt2img' || mode === 'img2img') {+ resizeCanvasOutputToBbox(backendGraph, bbox, processingSize, destination);+ }+ setCanvasMetadataDimensions(backendGraph, bbox);+return {backendGraph,graph: toGraphContract(backendGraph, `${model.name} ${mode}`),diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.tsindex eff7c34ea0..70518efc3b 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts@@ -15,11 +15,12 @@ const dispatchCanvas = (store: ReturnType<typeof createWorkbenchStore>, mutationstore.commands.canvas.apply(store.getState().activeProjectId, mutation);};-const snapshot = (bboxW: number, bboxH: number, dimsW: number, dimsH: number): CanvasDimsSnapshot => ({+const snapshot = (bboxW: number, bboxH: number, dimsW: number, dimsH: number, grid = 8): CanvasDimsSnapshot => ({bboxHeight: bboxH,bboxWidth: bboxW,dimsHeight: dimsH,dimsWidth: dimsW,+ grid,});describe('reconcileCanvasDims (pure)', () => {@@ -120,21 +121,38 @@ describe('reconcileCanvasDims (pure)', () => {bbox: bbox(512, 512),dims: { height: 100, width: 100 },grid: 16,- prev: snapshot(512, 512, 512, 512),+ prev: snapshot(512, 512, 512, 512, 16),});expect(result).toEqual({ bbox: { height: 96, width: 96, x: 0, y: 0 }, kind: 'set-bbox' });});- it('clamps a sub-grid dimension up to the grid minimum', () => {+ it('clamps a tiny dimension up to the shared generation minimum', () => {const result = reconcileCanvasDims({bbox: bbox(512, 512),dims: { height: 1, width: 1 },grid: 16,- prev: snapshot(512, 512, 512, 512),+ prev: snapshot(512, 512, 512, 512, 16),+ });++ expect(result).toEqual({ bbox: { height: 64, width: 64, x: 0, y: 0 }, kind: 'set-bbox' });+ });++ it('clamps an oversized bbox to the shared processing maximum without changing its footprint', () => {+ const result = reconcileCanvasDims({+ bbox: bbox(5000, 6000),+ dims: { height: 512, width: 512 },+ grid: 16,+ prev: snapshot(512, 512, 512, 512, 16),});- expect(result).toEqual({ bbox: { height: 16, width: 16, x: 0, y: 0 }, kind: 'set-bbox' });+ expect(result).toEqual({+ aspectRatioId: 'Free',+ aspectRatioValue: 5 / 6,+ height: 4096,+ kind: 'patch-dims',+ width: 4096,+ });});it('no-ops the dims->bbox direction when the snapped size already matches the bbox', () => {@@ -142,7 +160,7 @@ describe('reconcileCanvasDims (pure)', () => {bbox: bbox(96, 96),dims: { height: 100, width: 100 },grid: 16,- prev: snapshot(96, 96, 96, 96),+ prev: snapshot(96, 96, 96, 96, 16),});expect(result).toEqual({ kind: 'none' });@@ -195,6 +213,7 @@ describe('reconcileCanvasDims (pure)', () => {});const model: MainModelConfig = { base: 'sdxl', key: 'test-model', name: 'Test Model', type: 'main' };+const flux2Model: MainModelConfig = { base: 'flux2', key: 'test-flux2-model', name: 'Test FLUX.2 Model', type: 'main' };const getActiveGenerate = (state: WorkbenchState) => {const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);@@ -266,6 +285,32 @@ describe('createCanvasDimsSync (wiring)', () => {sync.dispose();});+ it('snaps an off-grid bbox and generation dimensions to the active model grid', () => {+ const { getSyncDispatches, store, sync } = setupCanvasStore();++ dispatchCanvas(store, { bbox: { height: 503, width: 501, x: 32, y: 48 }, type: 'setCanvasBbox' });++ const { bbox: nextBbox, values } = getActiveGenerate(store.getState());+ expect(nextBbox).toEqual({ height: 503, width: 501, x: 32, y: 48 });+ expect(values.width).toBe(504);+ expect(values.height).toBe(504);+ expect(getSyncDispatches()).toBe(1);+ sync.dispose();+ });++ it('re-snaps an agreed bbox and dimensions when the model changes to a stricter grid', () => {+ const { store, sync } = setupCanvasStore();++ dispatchCanvas(store, { bbox: { height: 504, width: 504, x: 32, y: 48 }, type: 'setCanvasBbox' });+ store.commands.generation.patchSettings({ model: flux2Model, modelKey: flux2Model.key });++ const { bbox: nextBbox, values } = getActiveGenerate(store.getState());+ expect(nextBbox).toEqual({ height: 504, width: 504, x: 32, y: 48 });+ expect(values.width).toBe(512);+ expect(values.height).toBe(512);+ sync.dispose();+ });+it('a bbox-driven ratio is what a subsequent constrained width edit uses (not the pre-drag ratio)', () => {const { store, sync } = setupCanvasStore();@@ -314,15 +359,14 @@ describe('createCanvasDimsSync (wiring)', () => {const before = getSyncDispatches();// 501 is not a multiple of the sdxl grid (8): dims -> bbox must snap it,- // and the bbox -> dims echo from that snapped bbox must not re-trigger- // another round of reconciliation (the snapped bbox and the still-501-wide- // dims disagree by construction, but the sync's re-entrancy guard must- // still hold the total dispatch count for this one external change to 1).+ // then write the valid value back to the dimensions. The re-entrancy guard+ // must keep those two bounded system writes from echoing indefinitely.store.commands.generation.patchSettings({ width: 501 });- const { bbox: nextBbox } = getActiveGenerate(store.getState());+ const { bbox: nextBbox, values } = getActiveGenerate(store.getState());expect(nextBbox.width).toBe(504); // snapped up to the nearest multiple of 8- expect(getSyncDispatches() - before).toBe(1);+ expect(values.width).toBe(504);+ expect(getSyncDispatches() - before).toBe(2);sync.dispose();});diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.tsindex 1946c3400e..8f7c210ab3 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts@@ -1,12 +1,17 @@/*** Two-way sync between a project's canvas generation frame (`canvas.document.bbox`)- * and its generate-widget dimensions (`width` / `height` / `aspectRatioId`).+ * and its model-valid generate-widget processing dimensions (`width` / `height` /+ * `aspectRatioId`).*- * Legacy parity: while a project is invoking into the canvas, the generation- * frame IS the generation size. Resizing the bbox (tool gesture, BboxOptions,- * undo/redo) drives the generate width/height; editing the generate dimensions- * (or picking an aspect preset) resizes the bbox in place (top-left anchored).- * Position-only bbox moves never touch the dimensions.+ * Legacy-compatible geometry: the generation frame remains the exact final+ * canvas footprint, including off-grid sizes. Resizing the bbox (tool gesture,+ * BboxOptions, undo/redo) drives width/height snapped to the selected model's+ * hard processing grid; the canvas graph resizes inputs to that processing size+ * and the result back to the bbox. Unlike legacy's optional "Scale Before+ * Processing" policy, this does not silently upscale small bboxes to an optimal+ * pixel area. Editing the generate dimensions (or picking an aspect preset)+ * still resizes the bbox in place (top-left anchored). Position-only bbox moves+ * never touch the dimensions.** The module is two parts:* - {@link reconcileCanvasDims}: a pure, unit-tested reconcile that decides which@@ -30,7 +35,7 @@ import type { AspectRatioId } from '@features/generation/contracts';import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/api';import type { WorkbenchState } from '@workbench/projectContracts';-import { deriveAspectRatioId } from '@features/generation/settings';+import { clampDimension, deriveAspectRatioId } from '@features/generation/settings';import type { WorkbenchCommands } from './workbenchStore';@@ -45,6 +50,7 @@ export interface CanvasDimsSnapshot {bboxHeight: number;dimsWidth: number;dimsHeight: number;+ grid: number;}export interface CanvasDimsReconcileInput {@@ -61,31 +67,26 @@ export interface CanvasDimsReconcileInput {export type CanvasDimsReconcileResult =| { kind: 'none' }/**- * Write the bbox size onto the generate dims (bbox wins), re-deriving the- * aspect id *and* the numeric aspect ratio. Both are re-derived from the bbox- * unconditionally (even when the form's ratio is locked to a preset) so the- * id, the numeric ratio, and the dims stay mutually consistent after the- * patch — a locked preset does not veto the bbox, which remains authoritative.+ * Write a model-grid processing size onto the generate dims (bbox wins),+ * retaining the exact bbox ratio in the aspect controls. Both aspect values+ * are re-derived from the bbox unconditionally (even when the form's ratio is+ * locked to a preset) so a locked preset does not veto the bbox, which remains+ * authoritative.*/| { kind: 'patch-dims'; width: number; height: number; aspectRatioId: AspectRatioId; aspectRatioValue: number }/** Resize the bbox to the (grid-snapped) generate dims, keeping its top-left position. */| { kind: 'set-bbox'; bbox: Bbox };-const snapToGrid = (value: number, grid: number): number => {- const step = grid > 0 ? grid : 1;- return Math.max(step, Math.round(value / step) * step);-};-/*** Decide which direction of the bbox <-> dims sync to apply.** - No bbox (not in canvas mode) -> `none`.- * - Bbox and dims already agree -> `none` (the primary loop guard).+ * - A grid-valid bbox and dims that already agree -> `none` (the primary loop guard).* - Otherwise the side that changed since `prev` wins; the bbox is authoritative- * when both (or neither, on first run) changed, matching "the frame is the- * generation size". Bbox -> dims writes the exact bbox size and re-derives the- * aspect id. Dims -> bbox snaps to the grid and only emits when the snapped- * size actually differs from the live bbox.+ * when both (or neither, on first run) changed. Bbox -> dims writes the nearest+ * model-grid processing size while preserving the exact bbox footprint and+ * aspect. Dims -> bbox snaps to the grid and only emits when the snapped size+ * actually differs from the live bbox.*/export const reconcileCanvasDims = ({bbox,@@ -97,27 +98,33 @@ export const reconcileCanvasDims = ({return { kind: 'none' };}- if (bbox.width === dims.width && bbox.height === dims.height) {+ const bboxIsOnGrid = bbox.width % grid === 0 && bbox.height % grid === 0;+ const gridChanged = prev !== null && prev.grid !== grid;++ if (bboxIsOnGrid && !gridChanged && bbox.width === dims.width && bbox.height === dims.height) {return { kind: 'none' };}- const bboxChanged = !prev || prev.bboxWidth !== bbox.width || prev.bboxHeight !== bbox.height;+ const bboxChanged = !prev || gridChanged || prev.bboxWidth !== bbox.width || prev.bboxHeight !== bbox.height;if (bboxChanged) {+ const width = clampDimension(bbox.width, grid);+ const height = clampDimension(bbox.height, grid);+return {aspectRatioId: deriveAspectRatioId(bbox.width, bbox.height),aspectRatioValue: bbox.height > 0 ? bbox.width / bbox.height : 1,- height: bbox.height,+ height,kind: 'patch-dims',- width: bbox.width,+ width,};}const dimsChanged = !prev || prev.dimsWidth !== dims.width || prev.dimsHeight !== dims.height;if (dimsChanged) {- const width = snapToGrid(dims.width, grid);- const height = snapToGrid(dims.height, grid);+ const width = clampDimension(dims.width, grid);+ const height = clampDimension(dims.height, grid);if (width === bbox.width && height === bbox.height) {return { kind: 'none' };@@ -209,7 +216,7 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSyncswitch (result.kind) {case 'none': {- prev = { bboxHeight: bbox.height, bboxWidth: bbox.width, dimsHeight: height, dimsWidth: width };+ prev = { bboxHeight: bbox.height, bboxWidth: bbox.width, dimsHeight: height, dimsWidth: width, grid };return;}case 'patch-dims': {@@ -218,6 +225,7 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSyncbboxWidth: bbox.width,dimsHeight: result.height,dimsWidth: result.width,+ grid,};isSyncing = true;try {@@ -240,12 +248,25 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSyncprev = {bboxHeight: result.bbox.height,bboxWidth: result.bbox.width,- dimsHeight: height,- dimsWidth: width,+ dimsHeight: result.bbox.height,+ dimsWidth: result.bbox.width,+ grid,};isSyncing = true;try {store.commands.canvas.apply(project.id, { bbox: result.bbox, type: 'setCanvasBbox' }, 'system');+ if (width !== result.bbox.width || height !== result.bbox.height) {+ store.commands.generation.patchSettings(+ {+ aspectRatioId: deriveAspectRatioId(result.bbox.width, result.bbox.height),+ aspectRatioValue: result.bbox.width / result.bbox.height,+ height: result.bbox.height,+ width: result.bbox.width,+ },+ project.id,+ 'system'+ );+ }} finally {isSyncing = false;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.tsindex 85212707e7..0197e3fd3a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts@@ -3,8 +3,8 @@ import { describe, expect, it } from 'vitest';import { DEFAULT_MODEL_GRID, gridSizeForModelBase } from './bboxGrid';describe('gridSizeForModelBase', () => {- it('maps flux-family and sd-3 bases to a 16px grid', () => {- for (const base of ['flux', 'flux2', 'sd-3', 'qwen-image', 'z-image']) {+ it('maps every 16px generation base to a 16px canvas grid', () => {+ for (const base of ['flux', 'flux2', 'sd-3', 'qwen-image', 'z-image', 'ideogram-4', 'krea-2', 'wan']) {expect(gridSizeForModelBase(base)).toBe(16);}});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.tsindex fd01aabc8e..3b68b1e874 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts@@ -1,30 +1,16 @@/*** Maps a model base to the bbox snapping grid size (document px), mirroring the- * legacy `getGridSize` rule: generation dimensions must land on a base-specific- * multiple. React reads the active generate model's base and feeds the result- * into `engine.viewport.setBboxGrid`; the engine itself stays model-agnostic.+ * generation core's model policy: generation dimensions must land on a+ * base-specific multiple. React reads the active generate model's base and+ * feeds the result into `engine.viewport.setBboxGrid`; the engine itself stays+ * model-agnostic.*/+import { getGenerationDimensions } from '@features/generation/settings';+/** Default grid when no model is selected (or an unknown base). */-export const DEFAULT_MODEL_GRID = 8;+export const DEFAULT_MODEL_GRID = getGenerationDimensions(undefined).grid;-/**- * The bbox grid size for a model base:- * - `cogview4` → 32- * - `flux` / `flux2` / `sd-3` / `qwen-image` / `z-image` → 16- * - everything else (sd-1/sd-2/sdxl/anima/unknown) → 8- */-export const gridSizeForModelBase = (base: string | null | undefined): number => {- switch (base) {- case 'cogview4':- return 32;- case 'flux':- case 'flux2':- case 'sd-3':- case 'qwen-image':- case 'z-image':- return 16;- default:- return DEFAULT_MODEL_GRID;- }-};+/** The bbox grid for a model base, or the shared 8px fallback for unknown/empty bases. */+export const gridSizeForModelBase = (base: string | null | undefined): number =>+ base ? getGenerationDimensions({ base, type: 'main' }).grid : DEFAULT_MODEL_GRID;