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(generate): restore tuning defaults on recall and keep watermarked masks transparent
Josh Corbett7cbad900d36b
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdxindex 03786dc249..a682e1011b 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx@@ -144,4 +144,6 @@ Decoder Qwen-Image (2K to 4K)* decoders (including an int8 build of the latter)The **Prompt - Qwen Image** node also has a **Quantization** option (`none`, `int8`, `nf4`) thatquantizes the Qwen2.5-VL encoder on load to reduce its VRAM use. The Generate panel offers the same choice-as **Encoder quantization** under **Advanced**, applied to both prompt encoders.+as **Encoder quantization** under **Advanced**, applied to both prompt encoders. The saving has a cost: a+quantized encoder cannot stay in the model cache, so it is loaded from disk for every prompt it encodes, twice+per generation when CFG is above 1. Leave it at `none` if the bf16 encoder fits.diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdxindex 4cc49c7bcf..b6d8339c38 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx@@ -50,9 +50,10 @@ The **Seed** sets the starting noise for the image. The same model, prompt, seedSome families add their own controls to the Render section:* **DyPE** (FLUX.1) — position extrapolation for sizes above the 1024px training resolution. **Auto** turns it on above 1536px, **Area** by image area and **4K optimized** is a fixed tuning; **Manual** exposes the **scale (λs)** and **exponent (λt)**.-* **Shift** (Z-Image, Qwen Image) — an override for the sampling schedule's timestep shift. Left on auto, the model derives it from the image size; Lightning LoRAs are trained for `3`.+* **Shift** (Z-Image, Qwen Image) — an override for the sampling schedule's timestep shift, from 0.1 to 10. Left on auto, the model derives it from the image size; Qwen Image's Lightning LoRAs are trained for `3`.* **Seed variance** (Krea-2, Z-Image) — perturbs the prompt conditioning so nearby seeds give more varied images; **Variance strength** and **Randomized channels** set how much.-* **Conditioning rebalance** (Krea-2) and **CFG (Low)** (Wan) — see the model's page under Local Models.+* **Conditioning rebalance** (Krea-2) — see [Krea-2](/users-guide/models/local-models/krea-2/).+* **Low-noise guidance** (Wan) — guidance for the low-noise expert; left unset, it reuses the main guidance.### Negative prompt@@ -69,10 +70,10 @@ The **Advanced** section appears for models with extra options, and its header c* **HiDiffusion** — improves structure at large sizes for SD 1.5 and SDXL; see [HiDiffusion](/users-guide/image-generation/advanced-topics/hidiffusion/).* **Color compensation** — SDXL only.* **PiD Decode** — decodes the image at up to four times its size; see [PiD Super-Resolution Decode](/users-guide/image-generation/advanced-topics/pid-decode/).-* **Encoder quantization** — Qwen Image only; quantizes the Qwen VL text encoder to 8-bit or 4-bit on load to save VRAM.+* **Encoder quantization** — Qwen Image only; quantizes the Qwen VL text encoder to 8-bit or 4-bit on load to save VRAM. A quantized encoder cannot stay in the model cache, so it is loaded from disk on every generation, twice when CFG is above 1.* **Seamless tiling** — makes the image tile along the X axis, the Y axis, or both.-Two output filters live in **Settings** under **Project** rather than in the panel, because they apply to every image the project generates: the **NSFW checker** blurs images it flags as explicit, and the **Invisible watermark** stamps every saved image. Both are off by default.+Two output filters live in **Settings** under **Project** rather than in the panel, because they apply to every image the project's Generate panel and Canvas produce: the **NSFW checker** blurs images it flags as explicit, and the **Invisible watermark** stamps every saved image. Both are off by default. Upscale results, workflow runs and images from external models are not filtered.### Resetting to defaultsdiff --git a/invokeai/backend/image_util/invisible_watermark.py b/invokeai/backend/image_util/invisible_watermark.pyindex 95c483848c..a7af517439 100644--- a/invokeai/backend/image_util/invisible_watermark.py+++ b/invokeai/backend/image_util/invisible_watermark.py@@ -24,7 +24,11 @@ class InvisibleWatermark:encoder = WatermarkEncoder()encoder.set_watermark("bytes", watermark_text.encode("utf-8"))bgr_encoded = encoder.encode(bgr, "dwtDct")- return Image.fromarray(cv2.cvtColor(bgr_encoded, cv2.COLOR_BGR2RGB)).convert("RGBA")+ watermarked = Image.fromarray(cv2.cvtColor(bgr_encoded, cv2.COLOR_BGR2RGB))+ # The watermark lives in the color channels. Carry the source alpha over, so a masked Canvas result keeps+ # its transparent surround instead of becoming an opaque rectangle; an image without alpha stays opaque.+ watermarked.putalpha(image.convert("RGBA").getchannel("A"))+ return watermarked@classmethoddef decode_watermark(cls, image: Image.Image, length: int = 8) -> str:diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex e6852840f3..a7733a2860 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -869,7 +869,8 @@"encoderQuantization": {"heading": "Encoder Quantization","paragraphs": [- "Quantizes the Qwen2.5-VL text encoder on load to reduce VRAM use. 4-bit (nf4) saves the most memory; 8-bit (int8) is a middle ground. None keeps the bf16 weights."+ "Quantizes the Qwen2.5-VL text encoder on load to reduce VRAM use. 4-bit (nf4) saves the most memory; 8-bit (int8) is a middle ground. None keeps the bf16 weights.",+ "A quantized encoder cannot stay in the model cache, so it is loaded from disk on every generation, twice when CFG is above 1. None keeps the cached encoder and loads it once."]},"styleStrength": {@@ -882,7 +883,7 @@"heading": "Timestep Shift","paragraphs": ["Overrides the sigma-schedule shift. Left on auto the model derives it from the image size, which is recommended.",- "Lightning LoRAs are trained for a fixed shift of 3. Lower values spend more steps at low noise; higher values at high noise."+ "Qwen Image Lightning LoRAs are trained for a fixed shift of 3. Lower values spend more steps at low noise; higher values at high noise."]},"imageInfluence": {@@ -1965,11 +1966,11 @@},"useNsfwChecker": {"label": "NSFW checker",- "description": "Blur generated images the checker flags as explicit before they are saved."+ "description": "Blur Generate and Canvas results the checker flags as explicit before they are saved."},"useWatermark": {"label": "Invisible watermark",- "description": "Stamp an invisible watermark into every generated image."+ "description": "Stamp an invisible watermark into every Generate and Canvas result."},"confirmImageDeletion": {"label": "Confirm image deletion",@@ -2496,10 +2497,6 @@"krea2RebalanceWeights": "Per-tap weights","krea2RebalanceWeightsHelp": "{{count}} comma-separated numbers, one per tap.","krea2RebalanceWeightsInvalid": "Enter exactly {{count}} comma-separated numbers.",- "krea2SeedVariance": "Seed variance",- "krea2SeedVarianceHelp": "Perturbs conditioning so nearby seeds diverge more.",- "krea2SeedVarianceRandomize": "Randomized channels",- "krea2SeedVarianceStrength": "Variance strength","dypePreset": "DyPE","dypePresetOff": "Off","dypePresetManual": "Manual",@@ -2509,13 +2506,18 @@"dypeScale": "DyPE scale (λs)","dypeExponent": "DyPE exponent (λt)","encoderQuantization": "Encoder quantization",- "encoderQuantizationHelp": "Quantizes the Qwen VL encoder on load to save VRAM.",+ "encoderQuantizationHelp": "Quantizes the Qwen VL encoder on load to save VRAM, but reloads it from disk for every generation.","encoderQuantizationNone": "None (bf16)","encoderQuantizationInt8": "8-bit (int8)","encoderQuantizationNf4": "4-bit (nf4)","styleStrength": "Style strength","timestepShift": "Shift",- "timestepShiftHelp": "Auto derives the schedule shift from the image size; Lightning LoRAs expect 3.",+ "timestepShiftHelp": "Auto derives the schedule shift from the image size.",+ "qwenImageShiftHelp": "Auto derives the schedule shift from the image size; Lightning LoRAs expect 3.",+ "seedVariance": "Seed variance",+ "seedVarianceHelp": "Perturbs conditioning so nearby seeds diverge more.",+ "seedVarianceRandomize": "Randomized channels",+ "seedVarianceStrength": "Variance strength","llmTaskGenerating": "Generating","llmTaskLoadingModel": "Loading model","llmTaskProgress": "LLM task progress",diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.jsonindex f5c4355639..9ac9888b19 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json@@ -407,12 +407,6 @@"image_name": "canvas-composite.png"}},- "canvas_l2i": {- "is_intermediate": true,- "use_cache": false,- "id": "canvas_l2i",- "type": "anima_l2i"- },"create_gradient_mask": {"is_intermediate": true,"use_cache": true,@@ -436,14 +430,20 @@"id": "expand_mask","type": "expand_mask_with_fade"},+ "canvas_l2i": {+ "is_intermediate": true,+ "use_cache": false,+ "id": "canvas_l2i",+ "type": "anima_l2i"+ },"canvas_output": {"is_intermediate": true,"use_cache": false,- "id": "canvas_output","layer_base": {"image_name": "canvas-composite.png"},- "type": "invokeai_img_blend"+ "type": "invokeai_img_blend",+ "id": "canvas_output"},"anima_lllite_sketch-layer": {"is_intermediate": true,diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.jsonindex bffd6bf8da..cdaa0677e8 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json@@ -562,7 +562,8 @@1],"dype_preset": [- "manual"+ "manual",+ "off"],"dype_scale": [3diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex 49b935961d..49164b02a0 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -971,7 +971,7 @@ describe('component policies', () => {expect(getDefaultReferenceImageConfig(krea2, [sdxlIpAdapter], referenceImage)).toEqual({image: referenceImage,styleStrength: 1,- type: 'krea2_style_reference_image',+ type: 'krea2_reference_image',});const fromSdxl = getGenerateModelSelectionResult({@@ -1000,7 +1000,7 @@ describe('component policies', () => {{id: 'ref-1',isEnabled: true,- config: { image: referenceImage, styleStrength: 1, type: 'krea2_style_reference_image' },+ config: { image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' },},]);@@ -1009,7 +1009,7 @@ describe('component policies', () => {{id: 'style',isEnabled: true,- config: { image: referenceImage, styleStrength: 1, type: 'krea2_style_reference_image' },+ config: { image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' },},],});@@ -1020,6 +1020,58 @@ describe('component policies', () => {]);});+ it('switches off the enabled references a newly selected model has no room for, keeping every reference', () => {+ const krea2 = createModel('krea-2', { format: 'diffusers' });+ const ipAdapter = (id: string, isEnabled: boolean) => ({+ id,+ isEnabled,+ config: {+ beginEndStepPct: [0, 1] as [number, number],+ clipVisionModel: 'ViT-H' as const,+ image: {+ ...referenceImage,+ original: { image: { ...referenceImage.original.image, image_name: `${id}.png` } },+ },+ method: 'style' as const,+ model: sdxlIpAdapter,+ type: 'ip_adapter' as const,+ weight: 1,+ },+ });++ const result = getGenerateModelSelectionResult({+ currentValues: createSettings(createModel('sdxl'), {+ referenceImages: [ipAdapter('bypassed', false), ipAdapter('used', true), ipAdapter('extra', true)],+ }),+ model: krea2,+ models: [sdxlIpAdapter],+ });++ // The first enabled reference is the one that keeps running, not the first in the list.+ expect(+ result.settings.referenceImages.map(({ config, id, isEnabled }) => ({ id, isEnabled, type: config.type }))+ ).toEqual([+ { id: 'bypassed', isEnabled: false, type: 'krea2_reference_image' },+ { id: 'used', isEnabled: true, type: 'krea2_reference_image' },+ { id: 'extra', isEnabled: false, type: 'krea2_reference_image' },+ ]);+ expect(result.clearedLabels).toContain('Reference Images');+ expect(getGenerationValidationReasons(krea2, result.settings)).toEqual([]);+ });++ it('names a limit of one reference in the singular', () => {+ const krea2 = createModel('krea-2', { format: 'diffusers' });+ const style = (id: string) => ({+ id,+ isEnabled: true,+ config: { image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' as const },+ });++ expect(+ getGenerationValidationReasons(krea2, createSettings(krea2, { referenceImages: [style('a'), style('b')] }))+ ).toContain(`Generate supports at most 1 reference image for ${krea2.name}.`);+ });+it('reports reference image support per model', () => {expect(isReferenceImageSupported(createModel('sdxl'))).toBe(true);expect(isReferenceImageSupported(createModel('cogview4'))).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 4dcaa8999a..1bb3ddaa51 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -1287,7 +1287,7 @@ export const getDefaultReferenceImageConfig = (}if (modelBase === 'krea-2') {- return { image, styleStrength: DEFAULT_KREA2_STYLE_STRENGTH, type: 'krea2_style_reference_image' };+ return { image, styleStrength: DEFAULT_KREA2_STYLE_STRENGTH, type: 'krea2_reference_image' };}if (isFluxKontextModel(model)) {@@ -1319,7 +1319,7 @@ const getReferenceImageConfigSupported = (return model.type !== 'external_image_generator' && model.base === 'flux2';case 'qwen_image_reference_image':return model.type !== 'external_image_generator' && model.base === 'qwen-image' && model.variant === 'edit';- case 'krea2_style_reference_image':+ case 'krea2_reference_image':return model.type !== 'external_image_generator' && model.base === 'krea-2';case 'flux_kontext_reference_image':return isFluxKontextModel(model);@@ -1406,7 +1406,22 @@ const getSettingsWithCompatibleModelSelections = (addClearedLabel(clearedLabels, 'LoRAs');}- const compatibleReferenceImages = getCompatibleReferenceImages(settings.referenceImages, model, models);+ // Enabled references beyond the new family's limit are switched off rather than deleted: Invoke is not left+ // blocked, the first enabled ones keep running, and switching back can turn the rest on again.+ const retargetedReferenceImages = getCompatibleReferenceImages(settings.referenceImages, model, models);+ const maxReferenceImages = getMaxReferenceImages(model);+ let enabledKept = 0;+ const compatibleReferenceImages =+ retargetedReferenceImages.filter((referenceImage) => referenceImage.isEnabled).length > maxReferenceImages+ ? retargetedReferenceImages.map((referenceImage) => {+ if (!referenceImage.isEnabled) {+ return referenceImage;+ }++ enabledKept += 1;+ return enabledKept > maxReferenceImages ? { ...referenceImage, isEnabled: false } : referenceImage;+ })+ : retargetedReferenceImages;if (compatibleReferenceImages !== settings.referenceImages) {nextSettings.referenceImages = compatibleReferenceImages;@@ -1597,7 +1612,9 @@ const getReferenceImageValidationReasons = (model: GenerateModelConfig, settingsconst maxReferenceImages = getMaxReferenceImages(model);if (isReferenceImageSupported(model) && enabled.length > maxReferenceImages) {- reasons.push(`Generate supports at most ${maxReferenceImages} reference images for ${model.name}.`);+ reasons.push(+ `Generate supports at most ${maxReferenceImages} reference image${maxReferenceImages === 1 ? '' : 's'} for ${model.name}.`+ );}enabled.forEach((referenceImage, index) => {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 09a5791e61..54a798691a 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@@ -80,7 +80,7 @@ const qwen3Encoder: ComponentModelConfig = {variant: 'qwen3_06b',};-const PROJECT_SETTINGS: GenerationProjectSettings = { useCpuNoise: true };+const PROJECT_SETTINGS: GenerationProjectSettings = { useCpuNoise: true, useNsfwChecker: false, useWatermark: false };const settingsFor = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({...getDefaultGenerateSettings(model),@@ -1127,7 +1127,7 @@ describe('compileCanvasGraph — output filters', () => {projectSettings: { useNsfwChecker: true, useWatermark: true },});- expect(backendGraph.nodes.canvas_decode).toMatchObject({ is_intermediate: true, type: 'img_resize' });+ expect(backendGraph.nodes.canvas_unfiltered_output).toMatchObject({ is_intermediate: true, type: 'img_resize' });expect(backendGraph.nodes.canvas_img_nsfw?.type).toBe('img_nsfw');expect(backendGraph.nodes.canvas_output).toMatchObject({ is_intermediate: false, type: 'img_watermark' });expect(metadataTarget(backendGraph)).toBe('canvas_output');@@ -1136,13 +1136,13 @@ describe('compileCanvasGraph — output filters', () => {it('filters the composited inpaint result rather than the decode behind it', () => {const { backendGraph } = compile(sd1Model, 'inpaint', { projectSettings: { useNsfwChecker: true } });- expect(backendGraph.nodes.canvas_decode?.type).toBe('invokeai_img_blend');+ expect(backendGraph.nodes.canvas_unfiltered_output?.type).toBe('invokeai_img_blend');expect(backendGraph.nodes.canvas_output).toMatchObject({ is_intermediate: true, type: 'img_nsfw' });expect(backendGraph.edges.find((edge) => edge.destination.node_id === 'canvas_output' && edge.destination.field === 'image')?.source.node_id- ).toBe('canvas_decode');+ ).toBe('canvas_unfiltered_output');expect(metadataTarget(backendGraph)).toBe('canvas_output');});@@ -1152,14 +1152,14 @@ describe('compileCanvasGraph — output filters', () => {projectSettings: { useWatermark: true },});- expect(backendGraph.nodes.canvas_decode?.type).toBe('invokeai_img_blend');+ expect(backendGraph.nodes.canvas_unfiltered_output?.type).toBe('invokeai_img_blend');expect(backendGraph.nodes.canvas_img_nsfw).toBeUndefined();expect(backendGraph.nodes.canvas_output).toMatchObject({ is_intermediate: true, type: 'img_watermark' });expect(backendGraph.edges.find((edge) => edge.destination.node_id === 'canvas_output' && edge.destination.field === 'image')?.source.node_id- ).toBe('canvas_decode');+ ).toBe('canvas_unfiltered_output');expect(metadataTarget(backendGraph)).toBe('canvas_output');});@@ -1169,7 +1169,7 @@ describe('compileCanvasGraph — output filters', () => {projectSettings: { useNsfwChecker: false, useWatermark: false },});- expect(backendGraph.nodes.canvas_decode).toBeUndefined();+ expect(backendGraph.nodes.canvas_unfiltered_output).toBeUndefined();expect(getNodeByType(backendGraph, 'img_nsfw')).toBeUndefined();expect(getNodeByType(backendGraph, 'img_watermark')).toBeUndefined();}@@ -1187,7 +1187,7 @@ describe('compileCanvasGraph — Krea-2 style reference', () => {config: {image: { original: { image: { height: 512, image_name: 'style.png', width: 512 } } },styleStrength: 1.2,- type: 'krea2_style_reference_image',+ type: 'krea2_reference_image',},id: 'style',isEnabled: true,diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex b29ff3ea52..1f7cf4da4b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -13,7 +13,7 @@ import {addEdge,addNode,addOutputPostprocessors,- renameNode,+ replaceCanvasOutput,toGraphContract,} from '@features/generation/core/graphBuilder';import { addKrea2ConditioningEnhancers } from '@features/generation/core/krea2Conditioning';@@ -143,25 +143,14 @@ const resizeCanvasOutputToBbox = (return;}- const processingOutput = renameNode(graph, 'canvas_output', 'canvas_processing_output');- processingOutput.is_intermediate = true;-- const output = addNode(graph, {+ const { output, retired } = replaceCanvasOutput(graph, 'canvas_processing_output', {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;- }+ addEdge(graph, retired, 'image', output, 'image');};/** Keeps saved-image metadata aligned to the bbox footprint, not the internal processing size. */@@ -319,9 +308,11 @@ const graftMaskTail = (const { compositing, denoise, destination, i2lType, initialImageName, settings, vaeSource } = args;const needsResize = !sizesMatch(args.bbox, args.processingSize);- // The final output owns canvas_output; the base decoder becomes intermediate.- const l2i = renameNode(graph, 'canvas_output', 'canvas_l2i');- l2i.is_intermediate = true;+ // The base decoder, until the composited output below takes over canvas_output from it.+ const l2i = graph.nodes.canvas_output;+ if (!l2i) {+ throw new Error('Canvas generation could not find the base graph output.');+ }const gradientMask = addNode(graph, {coherence_mode: compositing.coherenceMode,@@ -377,31 +368,25 @@ const graftMaskTail = (addEdge(graph, expandMask, 'image', outputMaskSource, 'image');}- const output = compositing.outputOnlyMaskedRegions- ? addNode(graph, {- id: 'canvas_output',- invert_mask: true,- is_intermediate: destination === 'canvas',- type: 'apply_mask_to_image',- use_cache: false,- })- : addNode(graph, {- id: 'canvas_output',- is_intermediate: destination === 'canvas',- layer_base: { image_name: initialImageName },- type: 'invokeai_img_blend',- use_cache: false,- });+ const { output } = replaceCanvasOutput(+ graph,+ 'canvas_l2i',+ compositing.outputOnlyMaskedRegions+ ? {+ invert_mask: true,+ is_intermediate: destination === 'canvas',+ type: 'apply_mask_to_image',+ use_cache: false,+ }+ : {+ is_intermediate: destination === 'canvas',+ layer_base: { image_name: initialImageName },+ type: 'invokeai_img_blend',+ use_cache: false,+ }+ );addEdge(graph, generatedImageSource, 'image', output, compositing.outputOnlyMaskedRegions ? 'image' : 'layer_upper');addEdge(graph, outputMaskSource, 'image', output, 'mask');-- // Move metadata to the final saved output after renaming.- const metadataEdge = graph.edges.find(- (edge) => edge.destination.node_id === 'canvas_l2i' && edge.destination.field === 'metadata'- );- if (metadataEdge) {- metadataEdge.destination.node_id = 'canvas_output';- }};/** Optionally inserts an `img_noise` node before encode; returns the node feeding `i2l.image`. */diff --git a/invokeai/frontend/webv2/src/features/generation/core/contracts.ts b/invokeai/frontend/webv2/src/features/generation/core/contracts.tsindex 27c890d711..072ac8f152 100644--- a/invokeai/frontend/webv2/src/features/generation/core/contracts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/contracts.ts@@ -4,10 +4,12 @@ export type ResultDestination = 'canvas' | 'gallery';export interface GenerationProjectSettings {useCpuNoise: boolean;- /** Blur images the NSFW checker flags before they are saved. Omitted means off. */- useNsfwChecker?: boolean;- /** Stamp an invisible watermark into every saved image. Omitted means off. */- useWatermark?: boolean;+ // The Generate and Canvas output filters are required so that a caller passing its settings structurally breaks+ // the build when it renames one, instead of silently turning a safety filter off.+ /** Blur images the NSFW checker flags before they are saved. */+ useNsfwChecker: boolean;+ /** Stamp an invisible watermark into every saved image. */+ useWatermark: boolean;}export interface PromptHistoryItem {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex 2891dc7871..729e3680e3 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -13,7 +13,6 @@ import type {import { getDefaultGenerateSettings, isSupportedGenerateModel } from './baseGenerationPolicies';import { compileGenerateGraph, resolveGenerateSeed } from './graph';import { generateGraphCases, satisfiedSettingsFor } from './graphCoverage.testing';-import { stabilizeBackendGraphIds } from './previewGraph';const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };@@ -156,7 +155,11 @@ const refImage = {};const compile = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}) =>- compileGenerateGraph(createSettings(model, overrides), model, 'gallery', { useCpuNoise: true }).backendGraph;+ compileGenerateGraph(createSettings(model, overrides), model, 'gallery', {+ useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,+ }).backendGraph;const getEdge = (graph: ReturnType<typeof compile>, targetNodeId: string, targetField: string) =>graph.edges.find((edge) => edge.destination.node_id === targetNodeId && edge.destination.field === targetField);@@ -204,7 +207,7 @@ describe('compileGenerateGraph', () => {createSettings(sd1Model),sd1Model,'gallery',- { useCpuNoise: false },+ { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },'xpu').backendGraph;@@ -1300,17 +1303,19 @@ describe('model-family tuning', () => {variant: 'krea2_turbo',};const styleReference = (styleStrength: number, isEnabled = true, id = 'style-ref') => ({- config: { image: refImage, styleStrength, type: 'krea2_style_reference_image' as const },+ config: { image: refImage, styleStrength, type: 'krea2_reference_image' as const },id,isEnabled,});- it('sends no DyPE fields while the preset is off, so the FLUX denoise node stays as it was', () => {+ it('sends no DyPE fields while the preset is off, but records off so recall can restore it', () => {const graph = compile(fluxModel, fluxComponents);+ const metadata = getNodeByType(graph, 'core_metadata');expect(graph.nodes.denoise_latents).not.toHaveProperty('dype_preset');expect(graph.nodes.denoise_latents).not.toHaveProperty('dype_scale');- expect(getNodeByType(graph, 'core_metadata')).not.toHaveProperty('dype_preset');+ expect(metadata).toMatchObject({ dype_preset: 'off' });+ expect(metadata).not.toHaveProperty('dype_scale');});it('sends only the DyPE preset for the derived presets, and scale and exponent under manual', () => {@@ -1427,7 +1432,7 @@ describe('model-family tuning', () => {};const graph = compile(krea2Model, {referenceImages: [- { config: { image: cropped, styleStrength: 1, type: 'krea2_style_reference_image' }, id: 'r', isEnabled: true },+ { config: { image: cropped, styleStrength: 1, type: 'krea2_reference_image' }, id: 'r', isEnabled: true },],});@@ -1444,60 +1449,46 @@ describe('model-family tuning', () => {});describe('output filters', () => {- /** The graph without its minted ids, so two compilations of one recipe compare equal. */- const structure = (graph: ReturnType<typeof compile>) => stabilizeBackendGraphIds(graph);-- // The committed node-type contract (`__snapshots__/generateGraphNodeTypes.json`, checked against the backend- // registry) is the guard on what a default recipe emits; this only pins that the filter switches themselves are- // inert at their defaults. Metadata does record the new tuning keys at defaults (`z_image_shift: 'auto'` etc.),- // as legacy did.- it.each(generateGraphCases)(- '$label emits no filter nodes and the same structure whether the filter settings are omitted or off',- ({ base, shape }) => {- const { model, settings } = satisfiedSettingsFor(base, shape);- const plain = compileGenerateGraph(settings, model, 'gallery', { useCpuNoise: true }).backendGraph;- const explicit = compileGenerateGraph(settings, model, 'gallery', {- useCpuNoise: true,- useNsfwChecker: false,- useWatermark: false,- }).backendGraph;-- expect(structure(explicit)).toEqual(structure(plain));- expect(Object.values(plain.nodes).some((node) => node.type === 'img_nsfw' || node.type === 'img_watermark')).toBe(- false- );- }- );-it.each(generateGraphCases)('$label chains the checker and watermark after its decode', ({ base, shape }) => {const { model, settings } = satisfiedSettingsFor(base, shape);- const plain = compileGenerateGraph(settings, model, 'gallery', { useCpuNoise: true }).backendGraph;+ const plain = compileGenerateGraph(settings, model, 'gallery', {+ useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,+ }).backendGraph;const graph = compileGenerateGraph(settings, model, 'canvas', {useCpuNoise: true,useNsfwChecker: true,useWatermark: true,}).backendGraph;- // The decode that used to be the output now feeds the checker, and only the watermark is the result.- expect(graph.nodes.canvas_decode?.type).toBe(plain.nodes.canvas_output?.type);- expect(graph.nodes.canvas_decode?.is_intermediate).toBe(true);+ expect(Object.values(plain.nodes).some((node) => node.type === 'img_nsfw' || node.type === 'img_watermark')).toBe(+ false+ );+ // The image that used to be the output now feeds the checker, and only the watermark is the result.+ expect(graph.nodes.canvas_unfiltered_output?.type).toBe(plain.nodes.canvas_output?.type);+ expect(graph.nodes.canvas_unfiltered_output?.is_intermediate).toBe(true);expect(graph.nodes.canvas_img_nsfw).toMatchObject({ is_intermediate: true, type: 'img_nsfw', use_cache: false });expect(graph.nodes.canvas_output).toMatchObject({ is_intermediate: true, type: 'img_watermark', use_cache: false });- expect(getEdge(graph, 'canvas_img_nsfw', 'image')?.source).toEqual({ field: 'image', node_id: 'canvas_decode' });+ expect(getEdge(graph, 'canvas_img_nsfw', 'image')?.source).toEqual({+ field: 'image',+ node_id: 'canvas_unfiltered_output',+ });expect(getEdge(graph, 'canvas_output', 'image')?.source).toEqual({ field: 'image', node_id: 'canvas_img_nsfw' });expect(getEdge(graph, 'canvas_output', 'metadata')?.source.node_id).toBe(getNodeByType(graph, 'core_metadata')?.id);- expect(getEdge(graph, 'canvas_decode', 'metadata')).toBeUndefined();+ expect(getEdge(graph, 'canvas_unfiltered_output', 'metadata')).toBeUndefined();});it('runs a single filter as the durable output itself', () => {const graph = compileGenerateGraph(createSettings(sd1Model), sd1Model, 'gallery', {useCpuNoise: true,+ useNsfwChecker: false,useWatermark: true,}).backendGraph;expect(graph.nodes.canvas_img_nsfw).toBeUndefined();expect(graph.nodes.canvas_output).toMatchObject({ is_intermediate: false, type: 'img_watermark' });- expect(getEdge(graph, 'canvas_output', 'image')?.source.node_id).toBe('canvas_decode');+ expect(getEdge(graph, 'canvas_output', 'image')?.source.node_id).toBe('canvas_unfiltered_output');});it('keeps the filters after a PiD decode, which already ends on the output node', () => {@@ -1510,10 +1501,10 @@ describe('output filters', () => {}),sdxlModel,'gallery',- { useCpuNoise: true, useNsfwChecker: true }+ { useCpuNoise: true, useNsfwChecker: true, useWatermark: false }).backendGraph;- expect(graph.nodes.canvas_decode?.type).toBe('sdxl_pid_decode');+ expect(graph.nodes.canvas_unfiltered_output?.type).toBe('sdxl_pid_decode');expect(graph.nodes.canvas_output?.type).toBe('img_nsfw');});diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex ce6676db7b..509ad3aba0 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -697,6 +697,8 @@ const buildFluxGraph = (clip_embed_model: clipEmbedModel ?? undefined,guidance: settings.cfgScale,...dype,+ // Recorded even when off, so recall can restore it over a preset the panel has since turned on.+ dype_preset: settings.fluxDypePreset,scheduler,t5_encoder: t5EncoderModel ?? undefined,vae: vaeModel ?? undefined,@@ -1324,7 +1326,7 @@ const buildKrea2Graph = (addEdge(graph, seed, 'value', denoise, 'seed');addEdge(graph, denoise, 'latents', output, 'latents');// Shared-KV reference attention takes exactly one reference; zero strength is a full bypass, so it is not run.- const styleReference = getEnabledReferenceImages(settings, 'krea2_style_reference_image').find(+ const styleReference = getEnabledReferenceImages(settings, 'krea2_reference_image').find((referenceImage) => referenceImage.config.styleStrength > 0);if (styleReference?.config.image) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.tsindex b75d82b86f..163d568b08 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts@@ -42,7 +42,7 @@ export const addEdge = (};/** Rename every matching node ID and edge reference. */-export const renameNode = (graph: BackendGraphContract, oldId: string, newId: string): BackendInvocationContract => {+const renameNode = (graph: BackendGraphContract, oldId: string, newId: string): BackendInvocationContract => {const node = graph.nodes[oldId];if (!node) {throw new Error(`Could not find the "${oldId}" node to rename.`);@@ -62,9 +62,32 @@ export const renameNode = (graph: BackendGraphContract, oldId: string, newId: st};/**- * Chains the project's optional output filters after the image the graph ends on. The last filter takes over- * `canvas_output` with its durability flag and metadata edge, so result hydration and the saved record stay on the- * node that actually emits the final image; the decode behind it becomes intermediate.+ * Makes `output` the graph's `canvas_output`, the node result hydration follows. The node that held the id is renamed+ * to `retiredId` and made intermediate, and its metadata edge moves to `output` so the saved record stays on the node+ * that emits the final image. Edges into `output` are the caller's; the retired node keeps its edges under its new id.+ */+export const replaceCanvasOutput = (+ graph: BackendGraphContract,+ retiredId: string,+ output: { type: string; [key: string]: unknown }+): { output: BackendInvocationContract; retired: BackendInvocationContract } => {+ const retired = renameNode(graph, 'canvas_output', retiredId);+ retired.is_intermediate = true;++ const next = addNode(graph, { ...output, id: 'canvas_output' });+ const metadataEdge = graph.edges.find(+ (edge) => edge.destination.node_id === retiredId && edge.destination.field === 'metadata'+ );+ if (metadataEdge) {+ metadataEdge.destination.node_id = next.id;+ }++ return { output: next, retired };+};++/**+ * Chains the project's optional output filters after the image the graph ends on. Each filter in turn takes over+ * `canvas_output`, so the last one is the durable result and the unfiltered image becomes intermediate.*/export const addOutputPostprocessors = (graph: BackendGraphContract,@@ -75,33 +98,17 @@ export const addOutputPostprocessors = (...(projectSettings.useNsfwChecker ? ['img_nsfw'] : []),...(projectSettings.useWatermark ? ['img_watermark'] : []),];+ let retiredId = 'canvas_unfiltered_output';- if (filters.length === 0) {- return;- }-- const decode = renameNode(graph, 'canvas_output', 'canvas_decode');- decode.is_intermediate = true;- let source = decode;-- filters.forEach((type, index) => {- const isLast = index === filters.length - 1;- const filter = addNode(graph, {- id: isLast ? 'canvas_output' : `canvas_${type}`,- is_intermediate: isLast ? outputIsIntermediate : true,+ for (const type of filters) {+ const { output, retired } = replaceCanvasOutput(graph, retiredId, {+ is_intermediate: outputIsIntermediate,type,use_cache: false,});- addEdge(graph, source, 'image', filter, 'image');- source = filter;- });-- const metadataEdge = graph.edges.find(- (edge) => edge.destination.node_id === decode.id && edge.destination.field === 'metadata'- );- if (metadataEdge) {- metadataEdge.destination.node_id = source.id;+ addEdge(graph, retired, 'image', output, 'image');+ retiredId = `canvas_${type}`;}};diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.tsindex f2dde241af..468e6b7478 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts@@ -32,7 +32,10 @@ const compileForShape = (): { filled: GenerateComponentValueKey[]; graph: BackendGraphContract } => {const { filled, model, projectSettings, settings } = tuned? tunedSettingsFor(base, shape)- : { ...satisfiedSettingsFor(base, shape), projectSettings: { useCpuNoise: true } };+ : {+ ...satisfiedSettingsFor(base, shape),+ projectSettings: { useCpuNoise: true, useNsfwChecker: false, useWatermark: false },+ };// Assert every requirement before compilation for complete diagnostics.expect(getGenerationValidationReasons(model, settings), `${base}/${shape.label} is not satisfiable`).toEqual([]);@@ -99,6 +102,8 @@ describe('generate graph coverage', () => {for (const vae of offered.values()) {const { backendGraph } = compileGenerateGraph({ ...settings, vae: vae as VaeModelConfig }, model, 'gallery', {useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,});// Metadata records the selection whether or not the builder used it, so it does not count.const sent = Object.values(backendGraph.nodes).some(@@ -138,7 +143,7 @@ describe('generate graph coverage', () => {},model,'gallery',- { useCpuNoise: true }+ { useCpuNoise: true, useNsfwChecker: false, useWatermark: false });const nodes = Object.values(backendGraph.nodes);const loaded = nodesdiff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.tsindex 9749759163..81e4ec21c2 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts@@ -233,7 +233,7 @@ export const tunedSettingsFor = (base: SupportedGenerateBase, shape: ModelShape)base === 'krea-2'? [{- config: { image, styleStrength: 1, type: 'krea2_style_reference_image' as const },+ config: { image, styleStrength: 1, type: 'krea2_reference_image' as const },id: 'style',isEnabled: true,},diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.tsindex 1439961cd1..8858477edb 100644--- a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts@@ -49,7 +49,12 @@ afterEach(resetArchitectureCapabilities);describe('compileGeneratePreviewGraph', () => {it('compiles a ready graph with deterministic node ids across repeated compiles', () => {- const input = { destination: 'gallery' as const, models, storedValues, projectSettings: { useCpuNoise: false } };+ const input = {+ destination: 'gallery' as const,+ models,+ storedValues,+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },+ };const first = compileGeneratePreviewGraph(input);const second = compileGeneratePreviewGraph(input);@@ -75,7 +80,7 @@ describe('compileGeneratePreviewGraph', () => {destination: 'gallery',models,storedValues,- projectSettings: { useCpuNoise: false },+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },});if (result.status !== 'ready') {@@ -92,7 +97,7 @@ describe('compileGeneratePreviewGraph', () => {destination: 'gallery',models,storedValues,- projectSettings: { useCpuNoise: false },+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },});if (result.status !== 'ready') {@@ -114,7 +119,7 @@ describe('compileGeneratePreviewGraph', () => {destination: 'gallery',models,storedValues: badValues,- projectSettings: { useCpuNoise: false },+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },});expect(result.status).toBe('invalid');@@ -129,7 +134,7 @@ describe('compileGeneratePreviewGraph', () => {destination: 'gallery',models: [],storedValues,- projectSettings: { useCpuNoise: false },+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },});expect(result.status).toBe('invalid');@@ -140,7 +145,7 @@ describe('compileGeneratePreviewGraph', () => {destination: 'gallery' as const,models,storedValues: undefined,- projectSettings: { useCpuNoise: false },+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },};const first = compileGeneratePreviewGraph(input);const second = compileGeneratePreviewGraph(input);diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex cf20295ee6..d7e40ecbb5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@ -323,14 +323,14 @@ describe('normalizeGenerateSettings', () => {const normalized = normalizeGenerateSettings({...legacyStoredValues,referenceImages: [- { config: { image, type: 'krea2_style_reference_image' }, id: 'defaulted', isEnabled: true },- { config: { image, styleStrength: 7, type: 'krea2_style_reference_image' }, id: 'bounded', isEnabled: true },+ { config: { image, type: 'krea2_reference_image' }, id: 'defaulted', isEnabled: true },+ { config: { image, styleStrength: 7, type: 'krea2_reference_image' }, id: 'bounded', isEnabled: true },],});expect(normalized?.referenceImages.map((referenceImage) => referenceImage.config)).toEqual([- { image, styleStrength: 1, type: 'krea2_style_reference_image' },- { image, styleStrength: 2, type: 'krea2_style_reference_image' },+ { image, styleStrength: 1, type: 'krea2_reference_image' },+ { image, styleStrength: 2, type: 'krea2_reference_image' },]);expect(normalized && isGenerateSettings(normalized)).toBe(true);});diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex 0aaad447d2..7061d150c8 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -218,8 +218,12 @@ export const DEFAULT_FLUX_DYPE_SCALE = 2;export const MAX_FLUX_DYPE_SCALE = 8;export const DEFAULT_FLUX_DYPE_EXPONENT = 2;export const MAX_FLUX_DYPE_EXPONENT = 1000;-/** Z-Image and Qwen-Image `shift` are `ge=0`; 3 is the Lightning value and the auto-derived one at one megapixel. */+/**+ * 3 is the Lightning value and the auto-derived one at one megapixel. The nodes accept 0, but Qwen-Image takes its log+ * and fails the queue item, and Z-Image's schedule collapses, so the override starts above it.+ */export const DEFAULT_TIMESTEP_SHIFT = 3;+export const MIN_TIMESTEP_SHIFT = 0.1;export const MAX_TIMESTEP_SHIFT = 10;/** `z_image_seed_variance_enhancer`: strength `le=2`, randomize percent `ge=1, le=100`. */export const DEFAULT_ZIMAGE_SEED_VARIANCE_STRENGTH = 0.1;@@ -243,7 +247,9 @@ export const isQwenImageEncoderQuantization = (value: unknown): value is QwenIma* fixed ones.*/const getTimestepShift = (value: unknown): number | null =>- typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= MAX_TIMESTEP_SHIFT ? value : null;+ typeof value === 'number' && Number.isFinite(value) && value >= MIN_TIMESTEP_SHIFT && value <= MAX_TIMESTEP_SHIFT+ ? value+ : null;const getOptionalNumber = (value: unknown): number | null =>typeof value === 'number' && Number.isFinite(value) ? value : null;@@ -272,7 +278,7 @@ const REFERENCE_IMAGE_CONFIG_TYPES = new Set(['flux_kontext_reference_image','flux_redux','ip_adapter',- 'krea2_style_reference_image',+ 'krea2_reference_image','qwen_image_reference_image',]);@@ -312,7 +318,7 @@ const normalizeReferenceImageConfig = (value: unknown): GenerateReferenceImageCoreturn { image, type: value.type };case 'flux_kontext_reference_image':return { image, model: getMainModelOrNull(value.model), type: value.type };- case 'krea2_style_reference_image':+ case 'krea2_reference_image':return {image,styleStrength: getClampedNumber(@@ -379,7 +385,7 @@ const cloneReferenceImageConfig = (config: GenerateReferenceImageConfig): Generaswitch (config.type) {case 'external_reference_image':case 'flux2_reference_image':- case 'krea2_style_reference_image':+ case 'krea2_reference_image':case 'qwen_image_reference_image':return { ...config, image: config.image ? cloneCroppableImage(config.image) : null };case 'flux_kontext_reference_image':@@ -547,7 +553,7 @@ const syncReferenceImageConfigWithModels = (}case 'external_reference_image':case 'flux2_reference_image':- case 'krea2_style_reference_image':+ case 'krea2_reference_image':case 'qwen_image_reference_image':return config;}diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex b104a66e82..0073ad199b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -141,7 +141,7 @@ export type GenerateReferenceImageConfig =| { type: 'flux2_reference_image'; image: GenerateReferenceImageAsset | null }| { type: 'qwen_image_reference_image'; image: GenerateReferenceImageAsset | null }/** Krea-2 training-free style transfer: no adapter model, a single reference, `styleStrength` 0–2 (0 bypasses). */- | { type: 'krea2_style_reference_image'; image: GenerateReferenceImageAsset | null; styleStrength: number }+ | { type: 'krea2_reference_image'; image: GenerateReferenceImageAsset | null; styleStrength: number }| { type: 'external_reference_image'; image: GenerateReferenceImageAsset | null };export interface GenerateReferenceImage {diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 000a14d518..db6ad11635 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -30,6 +30,7 @@ export {MIN_NEGATIVE_PROMPT_HEIGHT_PX,MIN_HIDIFFUSION_T1_RATIO,MIN_POSITIVE_PROMPT_HEIGHT_PX,+ MIN_TIMESTEP_SHIFT,MIN_ZIMAGE_SEED_VARIANCE_RANDOMIZE_PERCENT,normalizeGenerateSettings,normalizeGenerateWidgetValues,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsxindex f63972e633..79ae3ab772 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx@@ -12,6 +12,7 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';import type { CanvasDenoisingStrengthProps } from './GenerationUiContext';@@ -83,13 +84,14 @@ void i18n.use(initReactI18next).init({dypePresetManual: 'Manual',dypePresetOff: 'Off',dypeScale: 'DyPE scale (λs)',- krea2SeedVariance: 'Seed variance',- krea2SeedVarianceHelp: 'Perturbs conditioning so nearby seeds diverge more.',- krea2SeedVarianceRandomize: 'Randomized channels',- krea2SeedVarianceStrength: 'Variance strength',+ seedVariance: 'Seed variance',+ seedVarianceHelp: 'Perturbs conditioning so nearby seeds diverge more.',+ seedVarianceRandomize: 'Randomized channels',+ seedVarianceStrength: 'Variance strength',override: 'Override',timestepShift: 'Shift',- timestepShiftHelp: 'Auto derives the schedule shift from the image size; Lightning LoRAs expect 3.',+ qwenImageShiftHelp: 'Auto derives the schedule shift from the image size; Lightning LoRAs expect 3.',+ timestepShiftHelp: 'Auto derives the schedule shift from the image size.',recentSeeds: 'Recent seeds',render: 'Render',scheduler: 'Scheduler',@@ -513,4 +515,42 @@ describe('GenerateRenderSection model-family tuning', () => {await render(sd1Model);expect(switchNamed('Override')).toBeNull();});++ it('keeps the shift override while a typed value passes outside its bounds', async () => {+ const onCommit = await render(zImageModel, { zImageShift: 3 });+ const input = () => host?.querySelector<HTMLInputElement>('input[aria-label="Shift"]');++ await settle(() => input()?.select());+ await act(() => userEvent.keyboard('0.5'));++ // "0" and "0." on the way to 0.5 are below the minimum, and committing them would read as auto.+ expect(onCommit.mock.calls.map(([patch]) => patch.zImageShift)).not.toContain(0);+ expect(onCommit).toHaveBeenLastCalledWith({ zImageShift: 0.5 });++ onCommit.mockClear();+ await settle(() => input()?.select());+ await act(() => userEvent.keyboard('12'));++ // "1" is in bounds; "12" is above the maximum and would read as auto too.+ expect(onCommit.mock.calls.map(([patch]) => patch.zImageShift)).toEqual([1]);+ });++ it('commits Z-Image seed variance to the Z-Image settings', async () => {+ const onCommit = await render(zImageModel);++ await settle(() => switchNamed('Seed variance')?.querySelector<HTMLElement>('[data-part="control"]')?.click());+ expect(onCommit).toHaveBeenCalledWith({ zImageSeedVarianceEnabled: true });++ await settle(() => root?.unmount());+ const onEnabledCommit = await render(zImageModel, {+ zImageSeedVarianceEnabled: true,+ zImageSeedVarianceRandomizePercent: 50,+ zImageSeedVarianceStrength: 0.1,+ });+ await pressOnSlider('Variance strength', 'ArrowRight');+ await pressOnSlider('Randomized channels', 'ArrowRight');++ expect(onEnabledCommit).toHaveBeenCalledWith({ zImageSeedVarianceStrength: expect.closeTo(0.15) });+ expect(onEnabledCommit).toHaveBeenCalledWith({ zImageSeedVarianceRandomizePercent: 51 });+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsxindex ca584b172f..cf17080fc6 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx@@ -34,6 +34,7 @@ import {MAX_KREA2_SEED_VARIANCE_STRENGTH,MAX_TIMESTEP_SHIFT,MAX_ZIMAGE_SEED_VARIANCE_STRENGTH,+ MIN_TIMESTEP_SHIFT,MIN_ZIMAGE_SEED_VARIANCE_RANDOMIZE_PERCENT,} from '@features/generation/core/settings';import { useExternalStoreSelector } from '@platform/state/selectors';@@ -282,12 +283,12 @@ const SeedVarianceFields = ({return (<><Field- helpText={t('widgets.generate.krea2SeedVarianceHelp')}- label={t('widgets.generate.krea2SeedVariance')}+ helpText={t('widgets.generate.seedVarianceHelp')}+ label={t('widgets.generate.seedVariance')}labelEnd={<GenerateToggleSwitchchecked={enabled}- label={t('widgets.generate.krea2SeedVariance')}+ label={t('widgets.generate.seedVariance')}onCheckedChange={(checked) => onChange({ enabled: checked })}/>}@@ -297,7 +298,7 @@ const SeedVarianceFields = ({{enabled ? (<><ScrubberField- label={t('widgets.generate.krea2SeedVarianceStrength')}+ label={t('widgets.generate.seedVarianceStrength')}max={maxStrength}min={0}step={0.05}@@ -306,7 +307,7 @@ const SeedVarianceFields = ({/><ScrubberFieldformatValue={formatPercent}- label={t('widgets.generate.krea2SeedVarianceRandomize')}+ label={t('widgets.generate.seedVarianceRandomize')}max={100}min={minRandomizePercent}step={1}@@ -420,20 +421,18 @@ const FluxDypeFields = ({ onCommit, settings }: RenderFieldsProps) => {/** Null lets the denoise node derive the shift from the image size; the override starts at the Lightning value. */const TimestepShiftField = ({+ helpText,onChange,shift,}: {+ helpText: string;shift: number | null;onChange: (shift: number | null) => void;}) => {const { t } = useTranslation();return (- <Field- helpText={t('widgets.generate.timestepShiftHelp')}- hint="timestepShift"- label={t('widgets.generate.timestepShift')}- >+ <Field helpText={helpText} hint="timestepShift" label={t('widgets.generate.timestepShift')}><GenerateToggleSwitchchecked={shift !== null}label={t('widgets.generate.override')}@@ -447,10 +446,16 @@ const TimestepShiftField = ({max={TIMESTEP_SHIFT_SLIDER_MAX}min={TIMESTEP_SHIFT_SLIDER_MIN}numberInputMax={MAX_TIMESTEP_SHIFT}- numberInputMin={0}+ numberInputMin={MIN_TIMESTEP_SHIFT}step={0.1}value={shift}- onChange={onChange}+ // The input reports each keystroke, so typing 0.5 passes through 0. Settings read a shift outside its+ // bounds as auto, which would drop the override mid-edit; the input clamps it on blur instead.+ onChange={(next) => {+ if (next >= MIN_TIMESTEP_SHIFT && next <= MAX_TIMESTEP_SHIFT) {+ onChange(next);+ }+ }}/>) : null}</Field>@@ -600,10 +605,15 @@ export const GenerateRenderSection = ({) : null}{familyBase === 'wan' ? <WanLowNoiseGuidanceField settings={settings} onCommit={onCommit} /> : null}{familyBase === 'z-image' ? (- <TimestepShiftField shift={settings.zImageShift} onChange={(zImageShift) => onCommit({ zImageShift })} />+ <TimestepShiftField+ helpText={t('widgets.generate.timestepShiftHelp')}+ shift={settings.zImageShift}+ onChange={(zImageShift) => onCommit({ zImageShift })}+ />) : null}{familyBase === 'qwen-image' ? (<TimestepShiftField+ helpText={t('widgets.generate.qwenImageShiftHelp')}shift={settings.qwenImageShift}onChange={(qwenImageShift) => onCommit({ qwenImageShift })}/>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsxindex 682a004571..fb89a3e164 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx@@ -154,7 +154,7 @@ const ReferenceImageCardBase = ({{formatWeight(config.weight)}</Text></>- ) : config.type === 'krea2_style_reference_image' ? (+ ) : config.type === 'krea2_reference_image' ? (<>{' · '}{t('widgets.generate.styleStrength')}{' '}@@ -272,7 +272,7 @@ const ReferenceImageCardBase = ({selectedBase={selectedBase}onConfigChange={changeConfig}/>- ) : config.type === 'krea2_style_reference_image' ? (+ ) : config.type === 'krea2_reference_image' ? (<Krea2StyleReferenceControls config={config} disabled={!isEnabled} onChange={changeConfig} />) : null}</Stack>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsxindex a8e9a53f3a..c963445f3f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx@@ -383,7 +383,7 @@ export const FluxReduxControls = <T extends { imageInfluence: FluxReduxImageInflconst STYLE_STRENGTH_MARKS = [DEFAULT_KREA2_STYLE_STRENGTH];/** Krea-2 style transfer has one knob; 0 bypasses the reference entirely. */-export const Krea2StyleReferenceControls = <T extends { styleStrength: number; type: 'krea2_style_reference_image' }>({+export const Krea2StyleReferenceControls = <T extends { styleStrength: number; type: 'krea2_reference_image' }>({config,disabled,onChange,diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex 8d606cbaac..f0cebe4aea 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -91,11 +91,14 @@ export const getZImageTileControlValues = (structure: number) => ({endStepPercent: 0.75 + structure * 0.025,});+/** Upscale runs no output filters, so only the noise device reaches its graph. */+type UpscaleProjectSettings = Pick<GenerationProjectSettings, 'useCpuNoise'>;+const addUpscaleMetadata = (graph: BackendGraphContract,{ frame, output }: UpscalePathResult,settings: UpscaleWidgetValues,- projectSettings: GenerationProjectSettings,+ projectSettings: UpscaleProjectSettings,randDevice: string): void => {if (!settings.model || !settings.upscaleModel || !settings.inputImage) {@@ -159,7 +162,7 @@ interface UpscalePathContext {/** The encoders this main model reads. A field it has no slot for is null here, whatever the widget holds. */components: ReturnType<typeof activeUpscaleComponents>;destination: ResultDestination;- projectSettings: GenerationProjectSettings;+ projectSettings: UpscaleProjectSettings;positivePrompt: BackendInvocationContract;negativePrompt: BackendInvocationContract;seed: BackendInvocationContract;@@ -677,7 +680,7 @@ const UPSCALE_PATH_BUILDERS = {export const compileUpscaleGraph = (settings: UpscaleWidgetValues,destination: ResultDestination,- projectSettings: GenerationProjectSettings,+ projectSettings: UpscaleProjectSettings,randDevice = projectSettings.useCpuNoise ? 'cpu' : 'cuda'): CompiledUpscaleGraph => {const reasons = getUpscaleValidationReasons(settings);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex fda6f07bb2..6fc1fab762 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -1081,7 +1081,11 @@ describe('image recall', () => {Object.values(backendGraph.nodes).filter((node) => node.type === 'lora_selector').map((node) => [(node.lora as { key: string }).key, node.weight]);- const generated = compileGenerateGraph(generatedWith, model, 'gallery', { useCpuNoise: true }).backendGraph;+ const generated = compileGenerateGraph(generatedWith, model, 'gallery', {+ useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,+ }).backendGraph;const result = buildImageRecallSettings({currentValues: createValues({ loras: [{ isEnabled: true, model: staleLora, weight: 0.9 }], model: sd1Model }),image,@@ -1091,7 +1095,11 @@ describe('image recall', () => {supportedModels: [model],vaeModels: [],});- const recalled = compileGenerateGraph(result!.values, result!.values.model, 'gallery', { useCpuNoise: true });+ const recalled = compileGenerateGraph(result!.values, result!.values.model, 'gallery', {+ useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,+ });expect(loraWeights(recalled.backendGraph)).toEqual([[grainLora.key, -0.4],@@ -1193,9 +1201,14 @@ describe('model-family tuning recall', () => {const fluxModel: MainModelConfig = { base: 'flux', key: 'flux-model', name: 'FLUX', type: 'main' };const zImageModel: MainModelConfig = { base: 'z-image', key: 'z-model', name: 'Z-Image', type: 'main' };const qwenModel: MainModelConfig = { base: 'qwen-image', key: 'qwen-model', name: 'Qwen', type: 'main' };- const recall = (metadata: Record<string, unknown>, model: MainModelConfig, kind: ImageRecallKind = 'all') =>+ const recall = (+ metadata: Record<string, unknown>,+ model: MainModelConfig,+ kind: ImageRecallKind = 'all',+ current: Partial<GenerateWidgetValues> = {}+ ) =>buildImageRecallSettings({- currentValues: createValues(),+ currentValues: createValues(current),image,kind,metadata: { model: { key: model.key }, ...metadata },@@ -1221,7 +1234,7 @@ describe('model-family tuning recall', () => {},zImageModel);- const auto = recall({ z_image_shift: 'auto' }, zImageModel);+ const auto = recall({ z_image_shift: 'auto' }, zImageModel, 'all', { zImageShift: 4 });expect(fixed?.values).toMatchObject({zImageSeedVarianceEnabled: true,@@ -1233,6 +1246,13 @@ describe('model-family tuning recall', () => {expect(auto?.fields).toContain('modelTuning');});+ it('does not count tuning the recall leaves as it was', () => {+ const unchanged = recall({ dype_preset: 'off', generation_mode: 'flux_txt2img', seed: 7 }, fluxModel);++ expect(unchanged?.values.fluxDypePreset).toBe('off');+ expect(unchanged?.fields).not.toContain('modelTuning');+ });+it('restores the Qwen-Image shift and encoder quantization', () => {const result = recall({ qwen_image_quantization: 'nf4', qwen_image_shift: 3 }, qwenModel);@@ -1249,6 +1269,108 @@ describe('model-family tuning recall', () => {expect(outOfRange?.values).toMatchObject({ fluxDypePreset: 'off', fluxDypeScale: 2 });});+ describe('over tuning the panel has since changed', () => {+ const changedTuning = {+ fluxDypePreset: '4k',+ qwenImageEncoderQuantization: 'nf4',+ qwenImageShift: 5,+ zImageSeedVarianceEnabled: true,+ zImageShift: 5,+ } as const;+ const recallOverChanged = (metadata: Record<string, unknown>, model: MainModelConfig) =>+ buildImageRecallSettings({+ currentValues: createValues(changedTuning),+ image,+ kind: 'all',+ metadata,+ models: [],+ supportedModels: [model],+ vaeModels: [],+ })?.values;+ const record = (model: MainModelConfig, extra: Record<string, unknown> = {}) => ({+ generation_mode: `${model.base}_txt2img`,+ model: { base: model.base, key: model.key, name: model.name, type: 'main' },+ ...extra,+ });++ it('restores the defaults a record of the same family leaves out', () => {+ expect(recallOverChanged(record(fluxModel), fluxModel)?.fluxDypePreset).toBe('off');+ expect(recallOverChanged(record(zImageModel), zImageModel)).toMatchObject({+ zImageSeedVarianceEnabled: false,+ zImageShift: null,+ });+ expect(recallOverChanged(record(qwenModel), qwenModel)).toMatchObject({+ qwenImageEncoderQuantization: 'none',+ qwenImageShift: null,+ });+ });++ it('reads the legacy null shift as auto', () => {+ expect(recallOverChanged(record(qwenModel, { qwen_image_shift: null }), qwenModel)?.qwenImageShift).toBeNull();+ });++ it('keeps the current tuning when the record is not a generation of that family', () => {+ const { generation_mode: _mode, ...withoutMode } = record(fluxModel);+ const otherFamily = record(fluxModel, {+ model: { base: 'sdxl', key: fluxModel.key, name: 'SDXL', type: 'main' },+ });++ expect(recallOverChanged(withoutMode, fluxModel)?.fluxDypePreset).toBe('4k');+ expect(recallOverChanged(otherFamily, fluxModel)?.fluxDypePreset).toBe('4k');+ });++ // What a graph records must bring the panel back to that recipe from either direction. A switch the graph stops+ // recording still passes here, since recall reads a missing key as the default; graph.test.ts pins that FLUX+ // records DyPE off.+ const tunedBases = generateGraphCases.filter(({ base }) => ['flux', 'qwen-image', 'z-image'].includes(base));+ const defaultTuning = {+ fluxDypePreset: 'off',+ qwenImageEncoderQuantization: 'none',+ qwenImageShift: null,+ zImageSeedVarianceEnabled: false,+ zImageShift: null,+ } as const;+ const roundTrip = ({ base, shape }: (typeof generateGraphCases)[number], recorded: object, current: object) => {+ const { model, settings } = fullyFilledSettingsFor(base, shape);+ const graph = compileGenerateGraph({ ...settings, ...recorded }, model, 'gallery', {+ useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,+ }).backendGraph;+ const values = buildImageRecallSettings({+ currentValues: createValues({ ...current, model }),+ image,+ kind: 'all',+ metadata: Object.values(graph.nodes).find((node) => node.type === 'core_metadata'),+ models: [],+ supportedModels: [model],+ vaeModels: [],+ })?.values;+ const keys = {+ flux: ['fluxDypePreset'],+ 'qwen-image': ['qwenImageEncoderQuantization', 'qwenImageShift'],+ 'z-image': ['zImageSeedVarianceEnabled', 'zImageShift'],+ }[base as 'flux' | 'qwen-image' | 'z-image'] as (keyof typeof defaultTuning)[];++ return {+ expected: Object.fromEntries(keys.map((key) => [key, (recorded as typeof defaultTuning)[key]])),+ restored: Object.fromEntries(keys.map((key) => [key, values?.[key]])),+ };+ };++ it.each(tunedBases)('$label restores its default tuning over changed settings', (graphCase) => {+ const { expected, restored } = roundTrip(graphCase, defaultTuning, changedTuning);++ expect(restored).toEqual(expected);+ });++ it.each(tunedBases)('$label restores its changed tuning over the defaults', (graphCase) => {+ const { expected, restored } = roundTrip(graphCase, changedTuning, defaultTuning);++ expect(restored).toEqual(expected);+ });+ });+it('offers recall for an image whose only recallable delta is its tuning', () => {const capabilities = getImageRecallCapabilities({currentValues: createValues({ model: fluxModel }),@@ -1276,7 +1398,7 @@ describe('model-family tuning recall', () => {config: {image: { original: { image: { height: 512, image_name: 'style.png', width: 512 } } },styleStrength: 1.4,- type: 'krea2_style_reference_image',+ type: 'krea2_reference_image',},id: 'style',isEnabled: true,@@ -1293,7 +1415,7 @@ describe('model-family tuning recall', () => {config: {image: { original: { image: { height: 512, image_name: 'style.png', width: 512 } } },styleStrength: 1.4,- type: 'krea2_style_reference_image',+ type: 'krea2_reference_image',},id: 'style',isEnabled: true,@@ -1314,7 +1436,7 @@ describe('Krea-2 style reference without an image', () => {model: { key: krea2Model.key },ref_images: [{- config: { image: null, styleStrength: 1.4, type: 'krea2_style_reference_image' },+ config: { image: null, styleStrength: 1.4, type: 'krea2_reference_image' },id: 'style',isEnabled: true,},@@ -1335,7 +1457,11 @@ describe('Krea-2 style reference without an image', () => {/** Remix from the metadata a fully filled graph records, starting from SDXL defaults. */const remixRoundTrip = ({ base, shape }: (typeof generateGraphCases)[number]) => {const { filled, model, settings } = fullyFilledSettingsFor(base, shape);- const graph = compileGenerateGraph(settings, model, 'gallery', { useCpuNoise: true }).backendGraph;+ const graph = compileGenerateGraph(settings, model, 'gallery', {+ useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,+ }).backendGraph;const recordedMetadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');const serializedMetadata = JSON.stringify(recordedMetadata);// A slot the graph leaves unused (e.g. a bundled model's) is not recorded, so there is nothing to restore.diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex a8d424fe06..74fb71fd4b 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -37,6 +37,7 @@ import {MAX_TIMESTEP_SHIFT,MAX_ZIMAGE_SEED_VARIANCE_STRENGTH,MIN_HIDIFFUSION_T1_RATIO,+ MIN_TIMESTEP_SHIFT,MIN_ZIMAGE_SEED_VARIANCE_RANDOMIZE_PERCENT,normalizeReferenceImages,} from '@features/generation/settings';@@ -427,50 +428,77 @@ const getMetadataKrea2Rebalance = (const hasKrea2Rebalance = (metadata: unknown, model: GenerateModelConfig | undefined): boolean =>Object.keys(getMetadataKrea2Rebalance(metadata, model)).length > 0;+/**+ * Generation graphs stamp `generation_mode` and record what ran, so on such a record a missing list or switch means+ * none or the node default. Other records that name a model, such as canvas saves, never record concepts or tuning.+ */+const isGenerationRecord = (metadata: unknown): boolean => getString(metadata, 'generation_mode') !== null;+const getBoundedNumber = (metadata: unknown, key: string, min: number, max: number): number | null => {const value = getNumber(metadata, key);return value !== null && value >= min && value <= max ? value : null;};-/** The graphs record `'auto'` for a shift they let the node derive; a number is an explicit override. */-const getTimestepShiftPatch = (metadata: unknown, key: string): number | null | undefined => {- if (getString(metadata, key) === 'auto') {- return null;+/**+ * A recorded shift: `'auto'` (webv2) or `null` (legacy) for one the node derived, a number for an override.+ * Undefined when the key is missing or holds something else.+ */+const getRecordedTimestepShift = (metadata: unknown, key: string): number | null | undefined => {+ if (!isRecord(metadata) || !(key in metadata)) {+ return undefined;}- const shift = getBoundedNumber(metadata, key, 0, MAX_TIMESTEP_SHIFT);+ if (metadata[key] === null || metadata[key] === 'auto') {+ return null;+ }- return shift === null ? undefined : shift;+ return getBoundedNumber(metadata, key, MIN_TIMESTEP_SHIFT, MAX_TIMESTEP_SHIFT) ?? undefined;};/*** Per-family tuning the graphs record under their own keys. Gated on the model recall settles on, since each* setting only reaches that family's denoise or encoder nodes.+ *+ * A generation record of that same family that leaves a switch out ran the node's default: webv2 recorded no tuning+ * before the panel offered it. Restoring the default there means a preset turned on since does not survive recall.+ * Values that only matter while a switch is on (DyPE scale, variance strength) stay as they are when missing.*/const getMetadataModelTuning = (metadata: unknown,model: GenerateModelConfig | undefined): Partial<GenerateWidgetValues> => {- if (!model || model.type !== 'main') {+ if (!model || model.type !== 'main' || !isRecord(metadata)) {return {};}+ const recordsFamily = isGenerationRecord(metadata) && getRecord(metadata, 'model')?.base === model.base;+ const recordedOrDefault = <T>(key: string, recorded: T | undefined, fallback: T): T | undefined =>+ recorded !== undefined ? recorded : recordsFamily && !(key in metadata) ? fallback : undefined;+if (model.base === 'flux') {- const preset = isRecord(metadata) ? metadata.dype_preset : undefined;+ const preset = recordedOrDefault(+ 'dype_preset',+ isFluxDypePreset(metadata.dype_preset) ? metadata.dype_preset : undefined,+ 'off'+ );const scale = getBoundedNumber(metadata, 'dype_scale', 0, MAX_FLUX_DYPE_SCALE);const exponent = getBoundedNumber(metadata, 'dype_exponent', 0, MAX_FLUX_DYPE_EXPONENT);return {- ...(isFluxDypePreset(preset) ? { fluxDypePreset: preset } : {}),+ ...(preset === undefined ? {} : { fluxDypePreset: preset }),...(scale === null ? {} : { fluxDypeScale: scale }),...(exponent === null ? {} : { fluxDypeExponent: exponent }),};}if (model.base === 'z-image') {- const shift = getTimestepShiftPatch(metadata, 'z_image_shift');- const enabled = getBoolean(metadata, 'z_image_seed_variance_enabled');+ const shift = recordedOrDefault('z_image_shift', getRecordedTimestepShift(metadata, 'z_image_shift'), null);+ const enabled = recordedOrDefault(+ 'z_image_seed_variance_enabled',+ getBoolean(metadata, 'z_image_seed_variance_enabled') ?? undefined,+ false+ );const strength = getBoundedNumber(metadata, 'z_image_seed_variance_strength', 0, MAX_ZIMAGE_SEED_VARIANCE_STRENGTH);const randomizePercent = getBoundedNumber(metadata,@@ -481,19 +509,23 @@ const getMetadataModelTuning = (return {...(shift === undefined ? {} : { zImageShift: shift }),- ...(enabled === null ? {} : { zImageSeedVarianceEnabled: enabled }),+ ...(enabled === undefined ? {} : { zImageSeedVarianceEnabled: enabled }),...(strength === null ? {} : { zImageSeedVarianceStrength: strength }),...(randomizePercent === null ? {} : { zImageSeedVarianceRandomizePercent: randomizePercent }),};}if (model.base === 'qwen-image') {- const shift = getTimestepShiftPatch(metadata, 'qwen_image_shift');- const quantization = isRecord(metadata) ? metadata.qwen_image_quantization : undefined;+ const shift = recordedOrDefault('qwen_image_shift', getRecordedTimestepShift(metadata, 'qwen_image_shift'), null);+ const quantization = recordedOrDefault(+ 'qwen_image_quantization',+ isQwenImageEncoderQuantization(metadata.qwen_image_quantization) ? metadata.qwen_image_quantization : undefined,+ 'none'+ );return {...(shift === undefined ? {} : { qwenImageShift: shift }),- ...(isQwenImageEncoderQuantization(quantization) ? { qwenImageEncoderQuantization: quantization } : {}),+ ...(quantization === undefined ? {} : { qwenImageEncoderQuantization: quantization }),};}@@ -626,12 +658,6 @@ const resolveRecordedLora = (return matches.length > 1 ? 'ambiguous' : (matches[0] ?? null);};-/**- * Generation graphs stamp `generation_mode` and omit `loras` when no concept was active, so on such a record a- * missing list means "none". Other records that name a model, such as canvas saves, never record concepts.- */-const isGenerationRecord = (metadata: unknown): boolean => getString(metadata, 'generation_mode') !== null;-interface ConceptRecall {/** The concept list to apply, or null when the metadata says nothing reliable about concepts. */loras: GenerateLora[] | null;@@ -892,7 +918,8 @@ export const buildImageRecallSettings = ({const tuningPatch = getMetadataModelTuning(metadata, values.model);- if (Object.keys(tuningPatch).length > 0) {+ // A same-family record always restores its switches, so only count the field when one actually changes.+ if (Object.entries(tuningPatch).some(([key, value]) => values[key as keyof GenerateWidgetValues] !== value)) {values = { ...values, ...tuningPatch };fields.push('modelTuning');}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 d157fd3f2f..2b2aaf5dd4 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@@ -281,7 +281,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {inFlight: options.inFlight ?? new Set<string>(),models: options.models,projectId: options.projectId ?? 'project-1',- projectSettings: { useCpuNoise: true },+ projectSettings: { useCpuNoise: true, useNsfwChecker: false, useWatermark: false },signal: new AbortController().signal,strength: options.strength ?? 0.75,};@@ -364,7 +364,7 @@ describe('prepareCanvasInvocation generation-device boundary', () => {models: harness.deps.models,projectId: harness.deps.projectId,canvasValues: { scaleMethod: 'manual', scaledHeight: 768, scaledWidth: 1024 },- projectSettings: { useCpuNoise: false },+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },strength: harness.deps.strength,});@@ -392,7 +392,7 @@ describe('prepareCanvasInvocation generation-device boundary', () => {generateValues: harness.deps.generateValues,models: harness.deps.models,projectId: harness.deps.projectId,- projectSettings: { useCpuNoise: false },+ projectSettings: { useCpuNoise: false, useNsfwChecker: false, useWatermark: false },strength: harness.deps.strength,});diff --git a/tests/backend/image_util/test_invisible_watermark.py b/tests/backend/image_util/test_invisible_watermark.pynew file mode 100644index 0000000000..8010f98b9d--- /dev/null+++ b/tests/backend/image_util/test_invisible_watermark.py@@ -0,0 +1,34 @@+import numpy as np+from PIL import Image++from invokeai.backend.image_util.invisible_watermark import InvisibleWatermark+++def _textured_rgb(size: int = 512) -> np.ndarray:+ """A smooth gradient with some texture: enough detail for the DWT-DCT watermark to embed and decode."""+ y, x = np.mgrid[0:size, 0:size]+ rgb = np.stack([(x * 255) // size, (y * 255) // size, ((x + y) * 127) // size], axis=-1)+ noise = np.random.default_rng(0).integers(0, 32, size=rgb.shape)+ return np.clip(rgb + noise, 0, 255).astype(np.uint8)+++def test_watermarking_keeps_the_transparent_surround_of_a_masked_result():+ rgb = _textured_rgb()+ alpha = np.zeros(rgb.shape[:2], dtype=np.uint8)+ alpha[128:384, 128:384] = 255+ image = Image.fromarray(np.dstack([rgb, alpha]), mode="RGBA")++ watermarked = InvisibleWatermark.add_watermark(image, "InvokeAI")++ assert watermarked.mode == "RGBA"+ assert np.array_equal(np.array(watermarked.getchannel("A")), alpha)+ assert InvisibleWatermark.decode_watermark(watermarked, length=8) == "InvokeAI"+++def test_watermarking_an_image_without_alpha_returns_it_opaque():+ image = Image.fromarray(_textured_rgb(), mode="RGB")++ watermarked = InvisibleWatermark.add_watermark(image, "InvokeAI")++ assert watermarked.mode == "RGBA"+ assert np.all(np.array(watermarked.getchannel("A")) == 255)