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
feat(canvas): scale before processing
Josh Corbett4e748234a4b0
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 4968c2c36e..15f5576d50 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2076,6 +2076,19 @@"resetToModelDefault": "Reset to model default","savePresetAction": "Save","savePresetTitle": "Save preset",+ "scaleBeforeProcessing": "Scale before processing",+ "scalingOptions": {+ "height": "Height",+ "method": "Scale method",+ "methods": {+ "auto": "Auto",+ "manual": "Manual",+ "none": "Off"+ },+ "processingAtFrame": "Generates at the generation size; nothing to resize.",+ "processingSize": "Generates at {{width}}x{{height}}, then resizes back to the generation size.",+ "width": "Width"+ },"searchPresets": "Search presets","secondsPerRun": "~{{value}}s/run","sizePreviewHandle": "Drag to resize the generation size",diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex 95af060607..da6b8578e5 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -19,6 +19,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[],generation: ['canvasGraph',+ 'canvasProcessingSize','components','contracts','graph',diff --git a/invokeai/frontend/webv2/src/features/generation/canvasProcessingSize.ts b/invokeai/frontend/webv2/src/features/generation/canvasProcessingSize.tsnew file mode 100644index 0000000000..7c39bbdf78--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/canvasProcessingSize.ts@@ -0,0 +1,7 @@+/**+ * The canvas processing-size policy, on its own lazy interface: its only+ * consumers (the canvas graph compiler and the Generate form's canvas+ * section) load on demand, so it must not ride the eager `graph` entry into+ * the initial editor graph.+ */+export { resolveCanvasProcessingSize } from './core/canvas/canvasProcessingSize';diff --git a/invokeai/frontend/webv2/src/features/generation/contracts.ts b/invokeai/frontend/webv2/src/features/generation/contracts.tsindex 491ecd432f..7dff1a82ce 100644--- a/invokeai/frontend/webv2/src/features/generation/contracts.ts+++ b/invokeai/frontend/webv2/src/features/generation/contracts.ts@@ -1,2 +1,3 @@export type * from './core/contracts';export type * from './core/types';+export type { CanvasScaleMethod, CanvasScalingSettings } from './core/canvas/types';diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.tsnew file mode 100644index 0000000000..f4df68a7a5--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts@@ -0,0 +1,83 @@+import type { GenerateModelConfig } from '@features/generation/core/types';++import { describe, expect, it } from 'vitest';++import { resolveCanvasProcessingSize } from './canvasProcessingSize';++const sd1 = { base: 'sd-1', type: 'main' } as GenerateModelConfig;+const sdxl = { base: 'sdxl', type: 'main' } as GenerateModelConfig;++describe('resolveCanvasProcessingSize', () => {+ it('keeps the bbox on the model grid when scaling is off or unset', () => {+ expect(resolveCanvasProcessingSize(sd1, 'off', { height: 300, width: 500 }, undefined)).toEqual({+ height: 304,+ width: 504,+ });+ expect(+ resolveCanvasProcessingSize(sd1, 'off', { height: 300, width: 500 }, { height: 64, method: 'none', width: 64 })+ ).toEqual({ height: 304, width: 504 });+ });++ it('grows a small bbox along its aspect ratio until it covers the optimal area', () => {+ // SD 1.x is trained at 512²: a 256×128 region processes at 2:1 with ≥ 512² pixels.+ const size = resolveCanvasProcessingSize(+ sd1,+ 'off',+ { height: 128, width: 256 },+ { height: null, method: 'auto', width: null }+ );+ expect(size.width / size.height).toBeCloseTo(2, 1);+ expect(size.width * size.height).toBeGreaterThanOrEqual(512 * 512);+ expect(size).toEqual({ height: 368, width: 728 });+ });++ it('sends a square bbox straight to the optimal square', () => {+ expect(+ resolveCanvasProcessingSize(+ sdxl,+ 'off',+ { height: 200, width: 200 },+ { height: null, method: 'auto', width: null }+ )+ ).toEqual({ height: 1024, width: 1024 });+ });++ it('leaves an SDXL training resolution alone in either orientation', () => {+ const auto = { height: null, method: 'auto', width: null } as const;+ expect(resolveCanvasProcessingSize(sdxl, 'off', { height: 1216, width: 832 }, auto)).toEqual({+ height: 1216,+ width: 832,+ });+ expect(resolveCanvasProcessingSize(sdxl, 'off', { height: 832, width: 1216 }, auto)).toEqual({+ height: 832,+ width: 1216,+ });+ // The same size on another base is below its optimal area and still grows.+ expect(resolveCanvasProcessingSize(sd1, 'off', { height: 1216, width: 832 }, auto)).toEqual({+ height: 1216,+ width: 832,+ });+ });++ it('never shrinks a bbox that already covers the optimal area', () => {+ expect(+ resolveCanvasProcessingSize(+ sd1,+ 'off',+ { height: 1024, width: 1536 },+ { height: null, method: 'auto', width: null }+ )+ ).toEqual({ height: 1024, width: 1536 });+ });++ it('uses the manual size snapped to the grid, falling back to the bbox side by side', () => {+ expect(+ resolveCanvasProcessingSize(+ sd1,+ 'off',+ { height: 300, width: 500 },+ { height: null, method: 'manual', width: 777 }+ )+ ).toEqual({ height: 304, width: 776 });+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.tsnew file mode 100644index 0000000000..3803df6411--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts@@ -0,0 +1,102 @@+/**+ * The size a canvas generation is denoised at, before the result is resized+ * back to the exact bbox footprint. Legacy's "Scale Before Processing":+ * `none` keeps the bbox (snapped to the model grid), `auto` grows a small bbox+ * along its aspect ratio until it reaches the model's optimal pixel area, and+ * `manual` uses the user's own size. Pure data; no React, no transport.+ */++import type { GenerateModelConfig, PidMode } from '@features/generation/core/types';++import { getGenerationDimensions } from '@features/generation/core/baseGenerationPolicies';+import { clampDimension, MAX_DIMENSION } from '@features/generation/core/settings';++import type { CanvasScalingSettings } from './types';++export interface CanvasSize {+ width: number;+ height: number;+}++const snap = (value: number, grid: number): number => Math.max(grid, Math.round(value / grid) * grid);++/** SDXL's trained resolutions (either orientation): already optimal, so auto scaling leaves them alone. */+const SDXL_TRAINING_DIMENSIONS: readonly (readonly [number, number])[] = [+ [512, 2048],+ [512, 1984],+ [512, 1920],+ [512, 1856],+ [576, 1792],+ [576, 1728],+ [576, 1664],+ [640, 1600],+ [640, 1536],+ [704, 1472],+ [704, 1408],+ [704, 1344],+ [768, 1344],+ [768, 1280],+ [832, 1216],+ [832, 1152],+ [896, 1152],+ [896, 1088],+ [960, 1088],+ [960, 1024],+ [1024, 1024],+];++const isSdxlTrainingSize = (base: string, { height, width }: CanvasSize): boolean =>+ base === 'sdxl' &&+ SDXL_TRAINING_DIMENSIONS.some(([a, b]) => (a === width && b === height) || (a === height && b === width));++/**+ * Grows `size` in grid steps along its aspect ratio until it covers the+ * optimal area; a bbox already at or above that area is left alone.+ */+const growToOptimalArea = (size: CanvasSize, optimal: number, grid: number): CanvasSize => {+ const width = snap(size.width, grid);+ const height = snap(size.height, grid);+ const targetArea = optimal * optimal;+ if (width * height >= targetArea) {+ return { height, width };+ }+ if (width === height) {+ return { height: optimal, width: optimal };+ }+ const ratio = width / height;+ const scaled = { height, width };+ let longest = optimal - grid;+ while (scaled.width * scaled.height < targetArea && longest < MAX_DIMENSION) {+ longest += grid;+ if (ratio > 1) {+ scaled.width = longest;+ scaled.height = snap(longest / ratio, grid);+ } else {+ scaled.height = longest;+ scaled.width = snap(longest * ratio, grid);+ }+ }+ return scaled;+};++export const resolveCanvasProcessingSize = (+ model: Pick<GenerateModelConfig, 'base' | 'type'>,+ pidMode: PidMode,+ bbox: CanvasSize,+ scaling: CanvasScalingSettings | undefined+): CanvasSize => {+ const { grid, optimal } = getGenerationDimensions(model, pidMode);+ switch (scaling?.method) {+ case 'auto': {+ const grown = isSdxlTrainingSize(model.base, bbox) ? bbox : growToOptimalArea(bbox, optimal, grid);+ return { height: clampDimension(grown.height, grid), width: clampDimension(grown.width, grid) };+ }+ case 'manual':+ return {+ height: clampDimension(scaling.height ?? bbox.height, grid),+ width: clampDimension(scaling.width ?? bbox.width, grid),+ };+ default:+ return { height: clampDimension(bbox.height, grid), width: clampDimension(bbox.width, grid) };+ }+};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 e7317a5eb7..9652519d24 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@@ -12,7 +12,7 @@ import { describe, expect, it } from 'vitest';import type { ControlLayerGraphInput } from './addControlLayers';import type { RegionalGuidanceInput } from './addRegionalGuidance';-import type { CanvasCompileMode, CanvasCompositingSettings, Rect } from './types';+import type { CanvasCompileMode, CanvasCompositingSettings, CanvasScalingSettings, Rect } from './types';import { compileCanvasGraph } from './compileCanvasGraph';@@ -118,6 +118,7 @@ const compile = (maskImageName?: string | null;noiseMaskImageName?: string | null;compositing?: Partial<CanvasCompositingSettings>;+ scaling?: CanvasScalingSettings;strength?: number;destination?: 'canvas' | 'gallery';outputOnlyMaskedRegions?: boolean;@@ -136,6 +137,7 @@ const compile = (},controlLayers: overrides.controlLayers,regionalGuidance: overrides.regionalGuidance,+ scaling: overrides.scaling,destination: overrides.destination ?? 'canvas',maskImageName:'maskImageName' in overrides ? overrides.maskImageName : mode === 'inpaint' ? 'canvas-mask.png' : null,@@ -495,6 +497,52 @@ describe('compileCanvasGraph', () => {expect(backendGraph.nodes.canvas_output?.type).toBe('l2i');});+ it('denoises a small txt2img bbox at the optimal area when scaling is automatic', () => {+ // SD 1.x: grid 8, optimal 512. 2:1 grows to 728×368 (720×360 is just under 512²).+ const { backendGraph } = compile(sd1Model, 'txt2img', {+ bbox: { height: 128, width: 256, x: 0, y: 0 },+ scaling: { height: null, method: 'auto', width: null },+ });++ expect(backendGraph.nodes.noise).toMatchObject({ height: 368, width: 728 });+ expect(backendGraph.nodes.canvas_output).toMatchObject({ height: 128, type: 'img_resize', width: 256 });+ });++ it('scales an img2img source up to the optimal area for processing when scaling is automatic', () => {+ // FLUX.2: grid 16, optimal 1024. 2:1 grows to 1456×736 (1440×720 is just under 1024²).+ const { backendGraph } = compile(flux2Model, 'img2img', {+ bbox: { height: 256, width: 512, x: 0, y: 0 },+ scaling: { height: null, method: 'auto', width: null },+ });++ expect(backendGraph.nodes.canvas_resize_initial_to_processing).toMatchObject({+ height: 736,+ type: 'img_resize',+ width: 1456,+ });+ expect(backendGraph.nodes.canvas_output).toMatchObject({ height: 256, type: 'img_resize', width: 512 });+ });++ it('processes at the manual size and restores the bbox footprint', () => {+ const { backendGraph } = compile(flux2Model, 'img2img', {+ bbox: { height: 512, width: 512, x: 0, y: 0 },+ scaling: { height: 768, method: 'manual', width: 1024 },+ });++ expect(backendGraph.nodes.canvas_resize_initial_to_processing).toMatchObject({ height: 768, width: 1024 });+ expect(backendGraph.nodes.canvas_output).toMatchObject({ height: 512, type: 'img_resize', width: 512 });+ });++ it('leaves an on-grid bbox alone when scaling is off', () => {+ const { backendGraph } = compile(flux2Model, 'img2img', {+ bbox: { height: 512, width: 512, x: 0, y: 0 },+ scaling: { height: 768, method: 'none', width: 1024 },+ });++ expect(backendGraph.nodes.canvas_resize_initial_to_processing).toBeUndefined();+ expect(backendGraph.nodes.canvas_output?.type).not.toBe('img_resize');+ });+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 },diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex edd61731ad..d2790d0841 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -29,15 +29,11 @@ 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 {- getGenerationDimensions,- getGenerationValidationReasons,-} from '@features/generation/core/baseGenerationPolicies';+import { 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,@@ -48,6 +44,7 @@ import type {import { addControlLayers } from './addControlLayers';import { addRegionalGuidance, isRegionalGuidanceSupportedForBase } from './addRegionalGuidance';+import { type CanvasSize, resolveCanvasProcessingSize } from './canvasProcessingSize';/*** The backend image-to-latents (encode) node type per supported base. sd-1 /@@ -98,28 +95,6 @@ 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;@@ -697,7 +672,7 @@ const graftOutpaint = (*/export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanvasGraph => {const { bbox, compositeImageName, destination, mode, model, projectSettings, strength } = input;- const processingSize = getCanvasProcessingSize(model, input.settings, bbox);+ const processingSize = resolveCanvasProcessingSize(model, input.settings.pidMode, bbox, input.scaling);const settings = withProcessingDimensions(input.settings, processingSize);const validationReasons = [...getCanvasValidationReasons(input), ...getGenerationValidationReasons(model, settings)];diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.tsindex 895ef60b0a..abd8bea034 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts@@ -19,6 +19,16 @@ export interface Rect {export type CanvasInfillMethod = 'patchmatch' | 'lama' | 'cv2' | 'color' | 'tile';export type CanvasCoherenceMode = 'Gaussian Blur' | 'Box Blur' | 'Staged';+/** Legacy "Scale Before Processing": how the bbox maps to the size the model denoises at. */+export type CanvasScaleMethod = 'none' | 'auto' | 'manual';++export interface CanvasScalingSettings {+ method: CanvasScaleMethod;+ /** The manual processing size; a null side falls back to the bbox's. */+ width: number | null;+ height: number | null;+}+export interface CanvasCompositingSettings {infillMethod: CanvasInfillMethod;infillTileSize: number;@@ -75,6 +85,8 @@ export interface CompileCanvasGraphInput {strength: number;/** Resolved infill / coherence / mask-blur knobs and output-compositing policy. */compositing: CanvasCompositingSettings;+ /** Processing-size policy; absent means the bbox snapped to the model grid. */+ scaling?: CanvasScalingSettings;/*** Valid, already-resolved control layers (each with its own uploaded composite* image name). The executor filters + composites these; the compiler onlydiff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.tsindex 8deccd72bc..d432f6462c 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts@@ -7,9 +7,9 @@* canvas footprint, including off-grid sizes. Resizing the bbox (tool gesture,* the frame form, 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)+ * and the result back to the bbox. The optional "Scale before processing"+ * policy (`resolveCanvasProcessingSize`) applies only at submit and never+ * touches the dimensions synced here. 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.*diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.tsindex df540234b1..19a41d58dc 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts@@ -183,6 +183,7 @@ const dispatchResolvedInvocation = async (owner,positivePrompts,projectId: project.id,+ canvasValues: getProjectWidgetValues(project, 'canvas'),projectSettings: project.settings,strength: readCanvasDenoisingStrength(getProjectWidgetValues(project, 'canvas')),});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsxnew file mode 100644index 0000000000..29182f9894--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx@@ -0,0 +1,196 @@+/**+ * Canvas "Scale before processing" for the generate widget: whether the bbox+ * is denoised at its own size, grown to the model's optimal area, or at a+ * manual size, with the result always resized back to the bbox. Persisted in+ * the canvas widget's values next to the denoising strength; read back by+ * `prepareCanvasInvocation` and threaded into the pure graph compiler.+ */++import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';+import type { CanvasScaleMethod, PidMode } from '@features/generation/contracts';+import type { Project } from '@workbench/projectContracts';++import { Badge, createListCollection, HStack, NumberInput, Stack, Text } from '@chakra-ui/react';+import { resolveCanvasProcessingSize } from '@features/generation/canvasProcessingSize';+import { GenerationSettingsSection } from '@features/generation/components';+import { clampDimension, getGenerationDimensions } from '@features/generation/settings';+import { Field, Select } from '@platform/ui';+import {+ CANVAS_SCALE_METHODS,+ CANVAS_SCALING_KEYS,+ readCanvasScaling,+} from '@workbench/widgets/canvas/invoke/canvasScaling';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;++const selectCanvasValues = (project: Project): Record<string, unknown> => getProjectWidgetValues(project, 'canvas');++/** The generate model's base/type and PiD mode decide the grid and optimal area the policy works in. */+const selectProcessingContext = (project: Project) => {+ const generate = getProjectWidgetValues(project, 'generate') as {+ model?: { base?: string; type?: string } | null;+ pidMode?: PidMode;+ };+ const model = generate.model;+ return {+ bbox: project.canvas.document.bbox,+ model: model && typeof model.base === 'string' ? { base: model.base, type: model.type ?? 'main' } : null,+ pidMode: generate.pidMode ?? 'off',+ };+};++const processingContextEqual = (+ a: ReturnType<typeof selectProcessingContext>,+ b: ReturnType<typeof selectProcessingContext>+): boolean =>+ a.bbox.width === b.bbox.width &&+ a.bbox.height === b.bbox.height &&+ a.model?.base === b.model?.base &&+ a.model?.type === b.model?.type &&+ a.pidMode === b.pidMode;++export const GenerateCanvasScalingSection = () => {+ const { t } = useTranslation();+ const { widgets } = useWorkbenchCommands();+ const values = useActiveProjectSelector(selectCanvasValues);+ const scaling = useMemo(() => readCanvasScaling(values), [values]);+ const context = useActiveProjectSelector(selectProcessingContext, processingContextEqual);+ const model = context.model as Parameters<typeof resolveCanvasProcessingSize>[0] | null;+ const dimensions = getGenerationDimensions(model ?? undefined, context.pidMode);+ const processingSize = useMemo(+ () => (model ? resolveCanvasProcessingSize(model, context.pidMode, context.bbox, scaling) : null),+ [context, model, scaling]+ );+ const resizes =+ processingSize !== null &&+ (processingSize.width !== context.bbox.width || processingSize.height !== context.bbox.height);++ const opt = useCallback((key: string) => t(`widgets.generate.scalingOptions.${key}`), [t]);+ const patch = useCallback((partial: Record<string, unknown>) => widgets.patchValues('canvas', partial), [widgets]);++ const methodCollection = useMemo(+ () =>+ createListCollection({+ items: CANVAS_SCALE_METHODS.map((method) => ({ label: opt(`methods.${method}`), value: method })),+ }),+ [opt]+ );+ const methodValue = useMemo(() => [scaling.method], [scaling.method]);+ const handleMethodChange = useCallback(+ ({ value }: SelectValueChangeDetails) => {+ const method = value[0] as CanvasScaleMethod | undefined;+ if (!method) {+ return;+ }+ // Manual starts from the size the frame processes at today, so both+ // sides are pinned and a later frame resize cannot move one of them.+ const seed =+ method === 'manual' && processingSize+ ? {+ [CANVAS_SCALING_KEYS.height]: scaling.height ?? processingSize.height,+ [CANVAS_SCALING_KEYS.width]: scaling.width ?? processingSize.width,+ }+ : {};+ patch({ ...seed, [CANVAS_SCALING_KEYS.method]: method });+ },+ [patch, processingSize, scaling.height, scaling.width]+ );+ const snap = useCallback((value: number) => clampDimension(value, dimensions.grid), [dimensions.grid]);+ // Typing needs the raw digits to land; the size snaps to the grid on commit+ // (Enter / blur), and the compiler clamps whatever is persisted meanwhile.+ const sideHandlers = useCallback(+ (key: string) => ({+ onValueChange: ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {+ if (Number.isFinite(valueAsNumber)) {+ patch({ [key]: valueAsNumber });+ }+ },+ onValueCommit: ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {+ if (Number.isFinite(valueAsNumber)) {+ patch({ [key]: snap(valueAsNumber) });+ }+ },+ }),+ [patch, snap]+ );+ const widthHandlers = useMemo(() => sideHandlers(CANVAS_SCALING_KEYS.width), [sideHandlers]);+ const heightHandlers = useMemo(() => sideHandlers(CANVAS_SCALING_KEYS.height), [sideHandlers]);++ const badges = useMemo(+ () => (+ <Badge size="xs">+ {scaling.method === 'none' || !processingSize+ ? opt(`methods.${scaling.method}`)+ : `${processingSize.width}x${processingSize.height}`}+ </Badge>+ ),+ [opt, processingSize, scaling.method]+ );++ return (+ <GenerationSettingsSection+ badges={badges}+ defaultOpen={false}+ label={t('widgets.generate.scaleBeforeProcessing')}+ sectionId="canvas-scaling"+ >+ <Stack gap="2" p="2">+ <Field label={opt('method')}>+ <Select+ aria-label={opt('method')}+ collection={methodCollection}+ positioning={SELECT_POSITIONING}+ size="xs"+ value={methodValue}+ valueText={opt(`methods.${scaling.method}`)}+ onValueChange={handleMethodChange}+ />+ </Field>+ {scaling.method === 'manual' ? (+ <HStack gap="2">+ <Field label={opt('width')}>+ <NumberInput.Root+ max={dimensions.max}+ min={dimensions.min}+ size="xs"+ step={dimensions.grid}+ value={String(scaling.width ?? context.bbox.width)}+ {...widthHandlers}+ >+ <NumberInput.Control />+ <NumberInput.Input aria-label={opt('width')} />+ </NumberInput.Root>+ </Field>+ <Field label={opt('height')}>+ <NumberInput.Root+ max={dimensions.max}+ min={dimensions.min}+ size="xs"+ step={dimensions.grid}+ value={String(scaling.height ?? context.bbox.height)}+ {...heightHandlers}+ >+ <NumberInput.Control />+ <NumberInput.Input aria-label={opt('height')} />+ </NumberInput.Root>+ </Field>+ </HStack>+ ) : null}+ {scaling.method !== 'none' && processingSize ? (+ <Text color="fg.muted" fontSize="2xs">+ {resizes+ ? t('widgets.generate.scalingOptions.processingSize', {+ height: processingSize.height,+ width: processingSize.width,+ })+ : t('widgets.generate.scalingOptions.processingAtFrame')}+ </Text>+ ) : null}+ </Stack>+ </GenerationSettingsSection>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasSections.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasSections.tsxindex e10e69aca1..dcbe2dbc5b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasSections.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasSections.tsx@@ -1,10 +1,12 @@import { GenerateCanvasCompositingSection } from './GenerateCanvasCompositingSection';+import { GenerateCanvasScalingSection } from './GenerateCanvasScalingSection';import { GenerateDenoisingStrength } from './GenerateDenoisingStrength';-/** The Generate form's canvas-only sections: denoising strength, then compositing. */+/** The Generate form's canvas-only sections: denoising strength, scale before processing, then compositing. */export const GenerateCanvasSections = () => (<><GenerateDenoisingStrength />+ <GenerateCanvasScalingSection /><GenerateCanvasCompositingSection /></>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.test.tsnew file mode 100644index 0000000000..86d555fdd9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { readCanvasScaling } from './canvasScaling';++describe('readCanvasScaling', () => {+ it('defaults to no scaling with no manual size', () => {+ expect(readCanvasScaling(undefined)).toEqual({ height: null, method: 'none', width: null });+ expect(readCanvasScaling({ scaleMethod: 'bigger', scaledWidth: -5, scaledHeight: 'tall' })).toEqual({+ height: null,+ method: 'none',+ width: null,+ });+ });++ it('reads a persisted manual size as whole pixels', () => {+ expect(readCanvasScaling({ scaleMethod: 'manual', scaledWidth: 768.4, scaledHeight: 512 })).toEqual({+ height: 512,+ method: 'manual',+ width: 768,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.tsnew file mode 100644index 0000000000..96bfd850fc--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasScaling.ts@@ -0,0 +1,34 @@+/**+ * Canvas "Scale before processing": persisted in the canvas widget's own+ * `state.values` like the denoising strength, read back with defaults by the+ * invoke orchestrator and threaded into the pure graph compiler. `none` keeps+ * today's behaviour (the bbox snapped to the model grid).+ */++import type { CanvasScaleMethod, CanvasScalingSettings } from '@features/generation/contracts';++export const CANVAS_SCALING_KEYS = {+ height: 'scaledHeight',+ method: 'scaleMethod',+ width: 'scaledWidth',+} as const;++export const CANVAS_SCALE_METHODS: readonly CanvasScaleMethod[] = ['none', 'auto', 'manual'];++/** No scaling: the bbox is processed as-is (snapped to the model grid). */+export const DEFAULT_CANVAS_SCALING: CanvasScalingSettings = { height: null, method: 'none', width: null };++const isScaleMethod = (value: unknown): value is CanvasScaleMethod =>+ CANVAS_SCALE_METHODS.includes(value as CanvasScaleMethod);++const readSide = (value: unknown): number | null =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : null;++export const readCanvasScaling = (values: Record<string, unknown> | undefined): CanvasScalingSettings => {+ const method = values?.[CANVAS_SCALING_KEYS.method];+ return {+ height: readSide(values?.[CANVAS_SCALING_KEYS.height]),+ method: isScaleMethod(method) ? method : 'none',+ width: readSide(values?.[CANVAS_SCALING_KEYS.width]),+ };+};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 09409c224b..fb94dba24b 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@@ -31,6 +31,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { RunCanvasInvocationDeps } from './prepareCanvasInvocation';import { DEFAULT_CANVAS_COMPOSITING } from './canvasCompositing';+import { DEFAULT_CANVAS_SCALING } from './canvasScaling';import {prepareCanvasInvocation,resolveRegionalReferenceImages,@@ -147,6 +148,7 @@ interface HarnessOptions {dispatch?: ReturnType<typeof vi.fn<(action: WorkbenchAction) => void>>;models?: RunCanvasInvocationDeps['models'];outputOnlyMaskedRegions?: boolean;+ scaling?: RunCanvasInvocationDeps['scaling'];}const makeHarness = (options: HarnessOptions = {}): Harness => {@@ -260,6 +262,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {outputOnlyMaskedRegions: options.outputOnlyMaskedRegions ?? true,},destination: options.destination ?? 'canvas',+ scaling: options.scaling ?? DEFAULT_CANVAS_SCALING,commands: {generation: {submitCanvas: (payload) => dispatch({ ...payload, type: 'submitCanvasInvocationSnapshot' }),@@ -352,6 +355,7 @@ describe('prepareCanvasInvocation generation-device boundary', () => {generateValues: harness.deps.generateValues,models: harness.deps.models,projectId: harness.deps.projectId,+ canvasValues: { scaleMethod: 'manual', scaledHeight: 768, scaledWidth: 1024 },projectSettings: { useCpuNoise: false },strength: harness.deps.strength,});@@ -405,6 +409,17 @@ describe('runCanvasInvocation', () => {expect(harness.dedupe.byKey.size).toBeGreaterThan(0);});+ it('denoises at the persisted manual processing size and restores the bbox', async () => {+ const harness = makeHarness({ scaling: { height: 768, method: 'manual', width: 1024 } });++ await runCanvasInvocation(harness.deps);++ const nodes = harness.submittedGraphs()[0]!.graph.backendGraph!.nodes;+ expect(nodes.noise).toMatchObject({ height: 768, width: 1024 });+ expect(nodes.canvas_resize_initial_to_processing).toMatchObject({ height: 768, width: 1024 });+ expect(nodes.canvas_output).toMatchObject({ type: 'img_resize' });+ });+it('reuses committed composite uploads on a later successful invocation', async () => {const harness = makeHarness();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex f832c08f66..44cb7086c3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -30,7 +30,7 @@* shallower user-facing guard from the instant the command begins.*/-import type { GenerateModelConfig } from '@features/generation/contracts';+import type { CanvasScalingSettings, GenerateModelConfig } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import type {CanvasControlLayerContract,@@ -70,6 +70,8 @@ import {type CanvasCompositingSettings,} from '@workbench/widgets/canvas/invoke/canvasCompositing';+import { readCanvasScaling } from './canvasScaling';+/** Title on every canvas-invoke failure notice. */export const CANVAS_INVOKE_ERROR_TITLE = 'Canvas generation failed';@@ -121,6 +123,8 @@ export interface RunCanvasInvocationDeps {strength: number;/** Persisted compositing settings (infill / coherence / mask blur / output policy), defaulted + clamped. */compositing: CanvasCompositingSettings;+ /** Persisted "scale before processing" policy, defaulted. */+ scaling: CanvasScalingSettings;commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;/** Localizes a control-layer rejection; defaults to the English validation sentence. */formatControlLayerError?: (code: ControlValidationReason, layerName: string) => string;@@ -389,6 +393,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): PromisprojectSettings: deps.projectSettings,randDevice: deps.randDevice,regionalGuidance: regions.toGraphInputs(composites.regionalMaskImages),+ scaling: deps.scaling,settings,strength: deps.strength,});@@ -447,6 +452,11 @@ export interface PrepareCanvasInvocationArgs {/** Expanded positive prompts, resolved by the caller before submitting. */positivePrompts?: string[];projectSettings: Pick<ProjectSettings, 'useCpuNoise'>;+ /**+ * The canvas widget's persisted values. The scaling policy is read here, in+ * the lazily loaded orchestrator, so its reader stays out of the eager submit path.+ */+ canvasValues?: Record<string, unknown>;strength: number;signal?: AbortSignal;/**@@ -494,6 +504,7 @@ export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs)projectSettings: args.projectSettings,randDevice: resolveRandDeviceMetadata(args.projectSettings.useCpuNoise, getGenerationDevicesSnapshot().options),signal,+ scaling: readCanvasScaling(args.canvasValues),strength: args.strength,});};