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(webv2): support expanded generation policies
joshistoastc25b33742ab9
diff --git a/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.tsnew file mode 100644index 0000000000..30c68c6301--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.ts@@ -0,0 +1,454 @@+import { describe, expect, it } from 'vitest';++import type {+ ComponentModelConfig,+ GenerateModelConfig,+ GenerateSettings,+ LoraModelConfig,+ MainModelConfig,+ VaeModelConfig,+} from './types';++import {+ BASE_GENERATION,+ coerceSchedulerForGraph,+ getComponentSectionPolicy,+ getAutoFlux2ComponentSourceModel,+ getDefaultGenerateSettings,+ getGenerationDimensions,+ getGenerationModelAvailabilityReasons,+ getGenerationModelPolicy,+ getGenerationValidationReasons,+ getPromptPolicy,+ getSettingsWithCompatibleModelSelections,+ isSupportedGenerateModel,+ SUPPORTED_GENERATE_BASES,+} from './baseGenerationPolicies';++const createModel = (base: string, overrides: Partial<MainModelConfig> = {}): MainModelConfig => ({+ base,+ key: `${base}-model`,+ name: `${base} model`,+ type: 'main',+ ...overrides,+});++const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({+ ...getDefaultGenerateSettings(model),+ seed: 1,+ shouldRandomizeSeed: false,+ ...overrides,+});++const t5Encoder: ComponentModelConfig = { base: 'any', key: 't5', name: 'T5 Encoder', type: 't5_encoder' };+const clipEmbed: ComponentModelConfig = { base: 'any', key: 'clip', name: 'CLIP Embed', type: 'clip_embed' };+const qwenVlEncoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen-vl',+ name: 'Qwen VL Encoder',+ type: 'qwen_vl_encoder',+};+const qwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3',+ name: 'Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_8b',+};+const animaQwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'anima-qwen3',+ name: 'Anima Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_06b',+};+const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+const flux2Vae: VaeModelConfig = { base: 'flux2', key: 'flux2-vae', name: 'FLUX.2 VAE', type: 'vae' };+const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };+const sdxlVae: VaeModelConfig = { base: 'sdxl', key: 'sdxl-vae', name: 'SDXL VAE', type: 'vae' };+const sd1Lora: LoraModelConfig = { base: 'sd-1', key: 'sd1-lora', name: 'SD 1 LoRA', type: 'lora' };+const sdxlLora: LoraModelConfig = { base: 'sdxl', key: 'sdxl-lora', name: 'SDXL LoRA', type: 'lora' };+const externalModel: GenerateModelConfig = {+ base: 'external',+ capabilities: { modes: ['txt2img'], supports_negative_prompt: false, supports_seed: false },+ format: 'external_api',+ key: 'external-model',+ name: 'External Model',+ provider_id: 'openai',+ type: 'external_image_generator',+};++describe('BASE_GENERATION', () => {+ it('matches expected dimensions per base', () => {+ expect(getGenerationDimensions(createModel('sd-1'))).toMatchObject({ grid: 8, optimal: 512 });+ expect(getGenerationDimensions(createModel('sdxl'))).toMatchObject({ grid: 8, optimal: 1024 });+ expect(getGenerationDimensions(createModel('flux2'))).toMatchObject({ grid: 16, optimal: 1024 });+ expect(getGenerationDimensions(createModel('cogview4'))).toMatchObject({ grid: 32, optimal: 1024 });+ });++ it('matches expected defaults per base', () => {+ expect(getDefaultGenerateSettings(createModel('sdxl'))).toMatchObject({+ steps: 30,+ cfgScale: 7,+ scheduler: 'euler_a',+ width: 1024,+ height: 1024,+ });+ expect(getDefaultGenerateSettings(createModel('flux'))).toMatchObject({+ steps: 4,+ cfgScale: 4,+ scheduler: 'euler',+ });+ expect(getDefaultGenerateSettings(createModel('flux2'))).toMatchObject({+ steps: 4,+ cfgScale: 1,+ scheduler: 'euler',+ });+ expect(getDefaultGenerateSettings(createModel('qwen-image'))).toMatchObject({+ steps: 40,+ cfgScale: 4,+ scheduler: 'euler_a',+ });+ expect(getDefaultGenerateSettings(createModel('z-image'))).toMatchObject({+ steps: 8,+ cfgScale: 1,+ scheduler: 'euler',+ });+ });++ it('matches expected scheduler sets per base', () => {+ const flux = createModel('flux');+ const zbase = createModel('z-image', { variant: 'zbase' });+ const anima = createModel('anima');++ expect(+ getGenerationModelPolicy(createModel('sdxl'), createSettings(createModel('sdxl'))).scheduler.options.map(+ (option) => option.value+ )+ ).toContain('euler_a');+ expect(+ getGenerationModelPolicy(flux, createSettings(flux)).scheduler.options.map((option) => option.value)+ ).toEqual(['euler', 'heun', 'lcm']);+ expect(+ getGenerationModelPolicy(zbase, createSettings(zbase)).scheduler.options.map((option) => option.value)+ ).toEqual(['euler', 'heun']);+ expect(+ getGenerationModelPolicy(anima, createSettings(anima)).scheduler.options.map((option) => option.value)+ ).toEqual(['euler', 'heun', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde', 'lcm']);+ expect(coerceSchedulerForGraph(zbase, 'lcm')).toBe('euler');+ });++ it('matches expected prompt policy per base', () => {+ expect(getPromptPolicy(createModel('flux'), { cfgScale: 4 })).toMatchObject({+ negativeVisible: false,+ negativeUsedInGraph: false,+ });+ expect(getPromptPolicy(createModel('sdxl'), { cfgScale: 1 })).toMatchObject({+ negativeVisible: true,+ negativeUsedInGraph: true,+ });+ expect(getPromptPolicy(createModel('qwen-image'), { cfgScale: 1 })).toMatchObject({+ negativeVisible: true,+ negativeUsedInGraph: false,+ });+ expect(getPromptPolicy(createModel('qwen-image'), { cfgScale: 2 })).toMatchObject({+ negativeVisible: true,+ negativeUsedInGraph: true,+ negativeHelpText: 'Used only when CFG is greater than 1.',+ });+ expect(getPromptPolicy(externalModel, { cfgScale: 7 })).toMatchObject({+ negativeVisible: false,+ negativeUsedInGraph: false,+ });+ expect(+ getPromptPolicy({ ...externalModel, capabilities: { supports_negative_prompt: true } }, { cfgScale: 7 })+ ).toMatchObject({ negativeVisible: true, negativeUsedInGraph: true });+ });++ it('matches expected UI availability per base', () => {+ expect(getGenerationModelPolicy(createModel('sd-1'), createSettings(createModel('sd-1'))).ui).toMatchObject({+ clipSkipMax: 12,+ cfgRescaleVisible: true,+ schedulerVisible: true,+ });+ expect(getGenerationModelPolicy(createModel('sd-2'), createSettings(createModel('sd-2'))).ui).toMatchObject({+ clipSkipMax: 24,+ cfgRescaleVisible: true,+ });+ expect(getGenerationModelPolicy(createModel('flux'), createSettings(createModel('flux'))).ui).toMatchObject({+ guidanceLabel: 'Guidance',+ schedulerVisible: true,+ clipSkipMax: null,+ });+ expect(getGenerationModelPolicy(createModel('sd-3'), createSettings(createModel('sd-3'))).ui).toMatchObject({+ schedulerVisible: false,+ sdVaeVisible: false,+ });+ expect(+ getGenerationModelPolicy(createModel('qwen-image'), createSettings(createModel('qwen-image'))).ui.schedulerVisible+ ).toBe(false);+ expect(getGenerationModelPolicy(externalModel, createSettings(externalModel)).ui.seedVisible).toBe(false);+ expect(+ getGenerationModelPolicy(+ { ...externalModel, capabilities: { supports_seed: true } },+ createSettings(externalModel)+ ).ui.seedVisible+ ).toBe(true);+ });++ it('has generation config for every graph builder base', () => {+ expect(SUPPORTED_GENERATE_BASES).toEqual([+ 'sd-1',+ 'sd-2',+ 'sdxl',+ 'sd-3',+ 'flux',+ 'flux2',+ 'cogview4',+ 'qwen-image',+ 'z-image',+ 'anima',+ ]);+ });++ it('does not mark display-only bases as generatable', () => {+ expect(isSupportedGenerateModel(createModel('sdxl-refiner'))).toBe(false);+ expect(isSupportedGenerateModel(createModel('unknown'))).toBe(false);+ expect(isSupportedGenerateModel(createModel('made-up'))).toBe(false);+ expect(BASE_GENERATION).not.toHaveProperty('external');+ });+});++describe('component policies', () => {+ it('validates FLUX T5, CLIP embed, and VAE requirements', () => {+ const model = createModel('flux');++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a T5 Encoder for FLUX models.',+ 'Generate needs a CLIP Embed model for FLUX models.',+ 'Generate needs a VAE for FLUX models.',+ ]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae })+ )+ ).toEqual([]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, {+ clipEmbedModel: t5Encoder,+ t5EncoderModel: clipEmbed,+ vae: fluxVae,+ })+ )+ ).toEqual(['Generate needs a T5 Encoder for FLUX models.', 'Generate needs a CLIP Embed model for FLUX models.']);+ });++ it('rejects unsupported FLUX dev_fill variant', () => {+ const model = createModel('flux', { variant: 'dev_fill' });++ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae })+ )+ ).toEqual(['FLUX Fill models do not support text-to-image generation.']);+ });++ it('validates FLUX.2 Qwen3 and VAE requirements and allows bundled alternatives', () => {+ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });+ const source = createModel('flux2', { format: 'diffusers', variant: 'klein_9b' });+ const incompatibleSource = createModel('flux2', {+ format: 'diffusers',+ key: 'flux2-4b-source',+ variant: 'klein_4b',+ });++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.',+ 'Generate needs a VAE for non-Diffusers FLUX.2 models.',+ ]);+ expect(getGenerationValidationReasons(model, createSettings(model, { componentSourceModel: source }))).toEqual([]);+ expect(+ getGenerationValidationReasons(model, createSettings(model, { componentSourceModel: incompatibleSource }))+ ).toEqual(['Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.']);+ expect(+ getGenerationValidationReasons(model, createSettings(model, { qwen3EncoderModel: qwen3Encoder, vae: flux2Vae }))+ ).toEqual([]);+ });++ it('keeps FLUX.2 component source hidden and auto-selects installed Diffusers sources', () => {+ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });+ const source = createModel('flux2', { format: 'diffusers', variant: 'klein_9b' });+ const incompatibleSource = createModel('flux2', {+ format: 'diffusers',+ key: 'flux2-4b-source',+ variant: 'klein_4b',+ });+ const settings = createSettings(model);++ expect(getComponentSectionPolicy(model, settings).slots.map((slot) => slot.key)).toEqual([+ 'qwen3EncoderModel',+ 'vae',+ ]);+ expect(getAutoFlux2ComponentSourceModel(model, settings, [incompatibleSource, source])?.key).toBe(source.key);+ expect(+ getAutoFlux2ComponentSourceModel(model, { ...settings, qwen3EncoderModel: qwen3Encoder }, [incompatibleSource])+ ?.key+ ).toBe(incompatibleSource.key);+ });++ it('validates Qwen Image Qwen-VL and VAE requirements', () => {+ const model = createModel('qwen-image', { format: 'checkpoint' });++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen VL Encoder for non-Diffusers Qwen Image models.',+ 'Generate needs a VAE for non-Diffusers Qwen Image models.',+ ]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { qwenVLEncoderModel: qwenVlEncoder, vae: qwenImageVae })+ )+ ).toEqual([]);+ });++ it('validates Z-Image non-anima Qwen3 and flux VAE requirements', () => {+ const model = createModel('z-image', { format: 'checkpoint' });++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen3 Encoder for Z-Image models.',+ 'Generate needs a VAE for Z-Image models.',+ ]);+ expect(+ getGenerationValidationReasons(model, createSettings(model, { qwen3EncoderModel: qwen3Encoder, vae: fluxVae }))+ ).toEqual([]);+ });++ it('validates Anima Qwen3 and allowed VAE bases', () => {+ const model = createModel('anima');++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen3 Encoder for Anima models.',+ 'Generate needs a VAE for Anima models.',+ ]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { qwen3EncoderModel: animaQwen3Encoder, vae: qwenImageVae })+ )+ ).toEqual([]);+ });++ it('validates dimensions against bounds and model-family grid', () => {+ const model = createModel('flux2');++ expect(getGenerationValidationReasons(model, createSettings(model, { width: 0 }))).toContain(+ 'Generate width must be between 64 and 4096.'+ );+ expect(getGenerationValidationReasons(model, createSettings(model, { height: 4104 }))).toContain(+ 'Generate height must be between 64 and 4096.'+ );+ expect(getGenerationValidationReasons(model, createSettings(model, { height: 888 }))).toContain(+ 'Generate height must be a multiple of 16.'+ );+ });++ it('rejects external image generators without a registered invocation node', () => {+ const model: GenerateModelConfig = {+ base: 'external',+ capabilities: { modes: ['txt2img'] },+ format: 'external_api',+ key: 'external-unknown',+ name: 'Unknown External Provider',+ provider_id: 'future-provider',+ type: 'external_image_generator',+ };++ expect(getGenerationValidationReasons(model, createSettings(model))).toContain(+ "No invocation node registered for external provider 'future-provider'."+ );+ });++ it('renders no component slots for bases without extra requirements', () => {+ expect(getComponentSectionPolicy(createModel('sdxl'), createSettings(createModel('sdxl'))).slots).toEqual([]);+ expect(getComponentSectionPolicy(createModel('cogview4'), createSettings(createModel('cogview4'))).slots).toEqual(+ []+ );+ });++ it('clears incompatible selections when the selected model changes', () => {+ const model = createModel('sdxl');+ const settings = createSettings(createModel('sd-1'), {+ cfgRescaleMultiplier: 0.5,+ clipSkip: 2,+ loras: [+ { isEnabled: true, model: sd1Lora, weight: 1 },+ { isEnabled: true, model: sdxlLora, weight: 1 },+ ],+ seamlessXAxis: true,+ t5EncoderModel: t5Encoder,+ vae: sdxlVae,+ });++ const result = getSettingsWithCompatibleModelSelections(settings, model);++ expect(result.settings.modelKey).toBe(model.key);+ expect(result.settings.loras.map((lora) => lora.model.key)).toEqual(['sdxl-lora']);+ expect(result.settings.vae).toEqual(sdxlVae);+ expect(result.settings.t5EncoderModel).toBeNull();+ expect(result.settings.clipSkip).toBe(0);+ expect(result.settings.cfgRescaleMultiplier).toBe(0);+ expect(result.settings.seamlessXAxis).toBe(true);+ expect(result.clearedLabels).toEqual(['LoRAs', 'T5 Encoder', 'CLIP skip', 'CFG rescale']);+ });++ it('reconciles dimensions to the new model grid when the selected model changes', () => {+ const model = createModel('cogview4');+ const settings = createSettings(createModel('sdxl'), { height: 520, width: 520 });+ const result = getSettingsWithCompatibleModelSelections(settings, model);++ expect(result.settings.width).toBe(512);+ expect(result.settings.height).toBe(512);+ expect(result.clearedLabels).toContain('Dimensions');+ });++ it('reports selected model records that disappeared from the backend model list', () => {+ const model = createModel('flux');+ const settings = createSettings(model, {+ clipEmbedModel: clipEmbed,+ loras: [{ isEnabled: true, model: sd1Lora, weight: 1 }],+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ });++ expect(getGenerationModelAvailabilityReasons(model, settings, [model as never, t5Encoder as never])).toEqual([+ 'CLIP Embed "CLIP Embed" is no longer installed.',+ 'VAE "FLUX VAE" is no longer installed.',+ 'LoRA "SD 1 LoRA" is no longer installed.',+ ]);+ });++ it('clears same-base FLUX.2 component selections that do not match the new variant', () => {+ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });+ const incompatibleQwen3: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3-4b',+ name: 'Qwen3 4B Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_4b',+ };+ const settings = createSettings(createModel('flux2', { format: 'gguf_quantized', variant: 'klein_4b' }), {+ qwen3EncoderModel: incompatibleQwen3,+ vae: flux2Vae,+ });++ const result = getSettingsWithCompatibleModelSelections(settings, model);++ expect(result.settings.qwen3EncoderModel).toBeNull();+ expect(result.settings.vae).toEqual(flux2Vae);+ expect(result.clearedLabels).toEqual(['Qwen3 Encoder']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.tsnew file mode 100644index 0000000000..36d8aad0a6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.ts@@ -0,0 +1,1071 @@+import type { KnownModelBase } from '@workbench/models/baseIdentity';+import type { ModelConfig, ModelTaxonomyType } from '@workbench/models/types';++import type { GenerateModelConfig, GenerateSettings, MainModelConfig, VaePrecision } from './types';++import {+ getCompatibleDiffusersComponentSource,+ isAnimaQwen3Encoder,+ isAnimaVae,+ isClipVariant,+ isDiffusersMainForBase,+ isFlux2DiffusersSourceForModel,+ isFlux2Qwen3EncoderForModel,+ isNonAnimaQwen3Encoder,+ isVaeForBases,+ type GenerateComponentFilter,+} from './componentCompatibility';+import {+ clampDimension,+ deriveAspectRatioId,+ isLoraCompatibleWithModel,+ MAX_DIMENSION,+ MIN_DIMENSION,+ SEED_MAX,+} from './settings';++// Generation policy registry keyed by model base. Display identity stays in @workbench/models/baseIdentity;+// graph topology stays explicit in graph.ts.++export interface SchedulerOption {+ value: string;+ label: string;+}++export type SchedulerSetId = 'standard' | 'flow' | 'flow-no-lcm' | 'anima';++export type NegativePromptUsage = 'always' | 'cfg-gated' | 'never';++export type GuidanceLabel = 'CFG' | 'Guidance';++export interface BaseGenerationConfig {+ dimensions: {+ grid: number;+ optimalSide: number;+ };+ defaults: {+ steps: number;+ cfgScale: number;+ scheduler: string;+ };+ schedulerSet: SchedulerSetId;+ schedulerAppliesToGraph: boolean;+ guidanceLabel: GuidanceLabel;+ negativePrompt: {+ visible: boolean;+ usage: NegativePromptUsage;+ };+ ui: {+ sdVaeOverride: boolean;+ vaePrecision: boolean;+ seamless: boolean;+ cfgRescale: boolean;+ clipSkipMax?: number;+ };+}++type GenerateDefaultSettings =+ | {+ scheduler?: string | null;+ steps?: number | null;+ cfg_scale?: number | null;+ guidance?: number | null;+ cfg_rescale_multiplier?: number | null;+ width?: number | null;+ height?: number | null;+ vae?: string | null;+ vae_precision?: string | null;+ }+ | null+ | undefined;++export const SCHEDULER_OPTIONS: SchedulerOption[] = [+ { label: 'DDIM', value: 'ddim' },+ { label: 'DDPM', value: 'ddpm' },+ { label: 'DEIS', value: 'deis' },+ { label: 'DEIS Karras', value: 'deis_k' },+ { label: 'DPM++ 2S', value: 'dpmpp_2s' },+ { label: 'DPM++ 2S Karras', value: 'dpmpp_2s_k' },+ { label: 'DPM++ 2M', value: 'dpmpp_2m' },+ { label: 'DPM++ 2M Karras', value: 'dpmpp_2m_k' },+ { label: 'DPM++ 2M SDE', value: 'dpmpp_2m_sde' },+ { label: 'DPM++ 2M SDE Karras', value: 'dpmpp_2m_sde_k' },+ { label: 'DPM++ 3M', value: 'dpmpp_3m' },+ { label: 'DPM++ 3M Karras', value: 'dpmpp_3m_k' },+ { label: 'DPM++ SDE', value: 'dpmpp_sde' },+ { label: 'DPM++ SDE Karras', value: 'dpmpp_sde_k' },+ { label: 'ER-SDE', value: 'er_sde' },+ { label: 'Euler', value: 'euler' },+ { label: 'Euler Karras', value: 'euler_k' },+ { label: 'Euler Ancestral', value: 'euler_a' },+ { label: 'Heun', value: 'heun' },+ { label: 'Heun Karras', value: 'heun_k' },+ { label: 'KDPM 2', value: 'kdpm_2' },+ { label: 'KDPM 2 Karras', value: 'kdpm_2_k' },+ { label: 'KDPM 2 Ancestral', value: 'kdpm_2_a' },+ { label: 'KDPM 2 Ancestral Karras', value: 'kdpm_2_a_k' },+ { label: 'LCM', value: 'lcm' },+ { label: 'LMS', value: 'lms' },+ { label: 'LMS Karras', value: 'lms_k' },+ { label: 'PNDM', value: 'pndm' },+ { label: 'TCD', value: 'tcd' },+ { label: 'UniPC', value: 'unipc' },+ { label: 'UniPC Karras', value: 'unipc_k' },+];++export const FLOW_SCHEDULER_OPTIONS: SchedulerOption[] = [+ { label: 'Euler', value: 'euler' },+ { label: 'Heun (2nd order)', value: 'heun' },+ { label: 'LCM', value: 'lcm' },+];++export const FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM: SchedulerOption[] = [+ { label: 'Euler', value: 'euler' },+ { label: 'Heun (2nd order)', value: 'heun' },+];++export const ANIMA_SCHEDULER_OPTIONS: SchedulerOption[] = [+ { label: 'Euler', value: 'euler' },+ { label: 'Heun (2nd order)', value: 'heun' },+ { label: 'DPM++ 2M', value: 'dpmpp_2m' },+ { label: 'DPM++ 2M SDE', value: 'dpmpp_2m_sde' },+ { label: 'ER-SDE', value: 'er_sde' },+ { label: 'LCM', value: 'lcm' },+];++const KNOWN_SCHEDULERS = new Set(SCHEDULER_OPTIONS.map((option) => option.value));+const FLOW_SCHEDULERS = new Set(FLOW_SCHEDULER_OPTIONS.map((option) => option.value));+const FLOW_SCHEDULERS_WITHOUT_LCM = new Set(FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM.map((option) => option.value));+const ANIMA_SCHEDULERS = new Set(ANIMA_SCHEDULER_OPTIONS.map((option) => option.value));++export const isKnownScheduler = (value: string): boolean => KNOWN_SCHEDULERS.has(value);++export const BASE_GENERATION = {+ 'sd-1': {+ dimensions: { grid: 8, optimalSide: 512 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: true, vaePrecision: true, seamless: true, cfgRescale: true, clipSkipMax: 12 },+ },+ 'sd-2': {+ dimensions: { grid: 8, optimalSide: 512 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: true, vaePrecision: true, seamless: true, cfgRescale: true, clipSkipMax: 24 },+ },+ sdxl: {+ dimensions: { grid: 8, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: true, vaePrecision: true, seamless: true, cfgRescale: false },+ },+ 'sd-3': {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ flux: {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 4, cfgScale: 4, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'Guidance',+ negativePrompt: { visible: false, usage: 'never' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ flux2: {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 4, cfgScale: 1, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'Guidance',+ negativePrompt: { visible: false, usage: 'never' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ cogview4: {+ dimensions: { grid: 32, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ 'qwen-image': {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 40, cfgScale: 4, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'cfg-gated' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ 'z-image': {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 8, cfgScale: 1, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'cfg-gated' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ anima: {+ dimensions: { grid: 8, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 4, scheduler: 'euler' },+ schedulerSet: 'anima',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'cfg-gated' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+} as const satisfies Partial<Record<KnownModelBase, BaseGenerationConfig>>;++export type SupportedGenerateBase = keyof typeof BASE_GENERATION;++export const SUPPORTED_GENERATE_BASES = Object.keys(BASE_GENERATION) as SupportedGenerateBase[];++export interface GenerationModelPolicy {+ isSupported: boolean;+ dimensions: {+ grid: number;+ min: number;+ max: number;+ optimal: number;+ };+ defaults: {+ steps: number;+ cfgScale: number;+ cfgRescaleMultiplier: number;+ scheduler: string;+ vaePrecision: VaePrecision;+ };+ scheduler: {+ options: readonly SchedulerOption[];+ defaultValue: string;+ appliesToGraph: boolean;+ coerceForGraph: (value: string) => string;+ };+ prompt: {+ negativeVisible: boolean;+ negativeUsedInGraph: boolean;+ negativeHelpText?: string;+ };+ ui: {+ guidanceLabel: GuidanceLabel;+ schedulerVisible: boolean;+ clipSkipMax: number | null;+ cfgRescaleVisible: boolean;+ seamlessVisible: boolean;+ sdVaeVisible: boolean;+ vaePrecisionVisible: boolean;+ seedVisible: boolean;+ };+}++const FALLBACK_GENERATION_CONFIG: BaseGenerationConfig = {+ dimensions: { grid: 8, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'never' },+ ui: { sdVaeOverride: false, vaePrecision: false, seamless: false, cfgRescale: false },+};++// Fallbacks keep UI selectors crash-safe; isSupportedGenerateModel() still blocks invocation.+const getBaseGenerationConfig = (+ model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined+): BaseGenerationConfig => {+ if (!model || model.type === 'external_image_generator') {+ return FALLBACK_GENERATION_CONFIG;+ }++ return (BASE_GENERATION as Partial<Record<string, BaseGenerationConfig>>)[model.base] ?? FALLBACK_GENERATION_CONFIG;+};++const getNumber = (value: number | null | undefined, fallback: number): number =>+ Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;++export const getGenerationDimensions = (model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined) => {+ const config = getBaseGenerationConfig(model);++ return {+ grid: config.dimensions.grid,+ min: MIN_DIMENSION,+ max: MAX_DIMENSION,+ optimal: config.dimensions.optimalSide,+ };+};++export const getGenerationDefaults = (model: GenerateModelConfig | undefined) => {+ const config = getBaseGenerationConfig(model);+ const defaults = model?.default_settings as GenerateDefaultSettings;++ return {+ cfgRescaleMultiplier: getNumber(defaults?.cfg_rescale_multiplier, 0),+ cfgScale: getNumber(defaults?.cfg_scale ?? defaults?.guidance, config.defaults.cfgScale),+ scheduler: defaults?.scheduler ?? config.defaults.scheduler,+ steps: Math.max(1, Math.round(getNumber(defaults?.steps, config.defaults.steps))),+ vaePrecision: defaults?.vae_precision === 'fp16' ? ('fp16' as const) : ('fp32' as const),+ };+};++export const getSchedulerOptions = (+ model:+ | (Pick<GenerateModelConfig, 'base' | 'type' | 'variant'> & Partial<Pick<MainModelConfig, 'format'>>)+ | undefined,+ currentValue?: string+): readonly SchedulerOption[] => {+ const config = getBaseGenerationConfig(model);+ const options = (() => {+ if (model?.base === 'z-image' && model.variant === 'zbase') {+ return FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM;+ }++ switch (config.schedulerSet) {+ case 'flow':+ return FLOW_SCHEDULER_OPTIONS;+ case 'flow-no-lcm':+ return FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM;+ case 'anima':+ return ANIMA_SCHEDULER_OPTIONS;+ case 'standard':+ return SCHEDULER_OPTIONS;+ }+ })();++ // Keep persisted/metadata scheduler values visible until the user picks a supported option.+ return currentValue && !options.some((option) => option.value === currentValue)+ ? [{ label: currentValue, value: currentValue }, ...options]+ : options;+};++export const coerceSchedulerForGraph = (+ model:+ | (Pick<GenerateModelConfig, 'base' | 'type' | 'variant'> & Partial<Pick<MainModelConfig, 'format'>>)+ | undefined,+ scheduler: string+): string => {+ const config = getBaseGenerationConfig(model);++ // Some graph builders ignore scheduler entirely; coerce to stable metadata/defaults instead of leaking stale UI state.+ if (!config.schedulerAppliesToGraph) {+ return config.defaults.scheduler;+ }++ if (model?.base === 'z-image' && model.variant === 'zbase') {+ return FLOW_SCHEDULERS_WITHOUT_LCM.has(scheduler) ? scheduler : 'euler';+ }++ switch (config.schedulerSet) {+ case 'flow':+ return FLOW_SCHEDULERS.has(scheduler) ? scheduler : 'euler';+ case 'flow-no-lcm':+ return FLOW_SCHEDULERS_WITHOUT_LCM.has(scheduler) ? scheduler : 'euler';+ case 'anima':+ return ANIMA_SCHEDULERS.has(scheduler) ? scheduler : 'euler';+ case 'standard':+ return KNOWN_SCHEDULERS.has(scheduler) ? scheduler : config.defaults.scheduler;+ }+};++export const getPromptPolicy = (+ model: GenerateModelConfig | undefined,+ settings: Pick<GenerateSettings, 'cfgScale'>+) => {+ if (model?.type === 'external_image_generator') {+ const supportsNegativePrompt = model.capabilities?.supports_negative_prompt === true;++ return {+ negativeVisible: supportsNegativePrompt,+ negativeUsedInGraph: supportsNegativePrompt,+ };+ }++ const config = getBaseGenerationConfig(model);+ // Visibility controls the textarea; usage controls whether the graph wires negative conditioning.+ const negativeUsedInGraph =+ config.negativePrompt.usage === 'always' || (config.negativePrompt.usage === 'cfg-gated' && settings.cfgScale > 1);++ return {+ negativeVisible: config.negativePrompt.visible,+ negativeUsedInGraph,+ ...(config.negativePrompt.usage === 'cfg-gated'+ ? { negativeHelpText: 'Used only when CFG is greater than 1.' }+ : {}),+ };+};++export const getGenerationUiPolicy = (+ model: GenerateModelConfig | undefined,+ _settings: Pick<GenerateSettings, 'cfgScale'>+) => {+ const config = getBaseGenerationConfig(model);+ const seedVisible = model?.type === 'external_image_generator' ? model.capabilities?.supports_seed === true : true;++ return {+ guidanceLabel: config.guidanceLabel,+ schedulerVisible: config.schedulerAppliesToGraph,+ clipSkipMax: config.ui.clipSkipMax ?? null,+ cfgRescaleVisible: config.ui.cfgRescale,+ seamlessVisible: config.ui.seamless,+ sdVaeVisible: config.ui.sdVaeOverride,+ vaePrecisionVisible: config.ui.vaePrecision,+ seedVisible,+ };+};++export const isSupportedGenerateModel = <T extends { base: string; type: string }>(+ model: T+): model is T & GenerateModelConfig =>+ (model.type === 'main' && model.base in BASE_GENERATION) ||+ (model.type === 'external_image_generator' && model.base === 'external');++export const isGenerateModelSelectable = <T extends ModelConfig>(model: T): boolean => isSupportedGenerateModel(model);++export const EXTERNAL_PROVIDER_NODE_TYPES: Record<string, string> = {+ alibabacloud: 'alibabacloud_image_generation',+ gemini: 'gemini_image_generation',+ openai: 'openai_image_generation',+ seedream: 'seedream_image_generation',+};++export const getExternalProviderNodeType = (providerId: unknown): string | null =>+ typeof providerId === 'string' ? (EXTERNAL_PROVIDER_NODE_TYPES[providerId] ?? null) : null;++export const getGenerationModelPolicy = (+ model: GenerateModelConfig | undefined,+ settings: GenerateSettings+): GenerationModelPolicy => {+ const config = getBaseGenerationConfig(model);+ const dimensions = getGenerationDimensions(model);+ const defaults = getGenerationDefaults(model);++ return {+ isSupported: model ? isSupportedGenerateModel(model) : false,+ dimensions,+ defaults,+ scheduler: {+ options: getSchedulerOptions(model, settings.scheduler),+ defaultValue: defaults.scheduler,+ appliesToGraph: config.schedulerAppliesToGraph,+ coerceForGraph: (value: string) => coerceSchedulerForGraph(model, value),+ },+ prompt: getPromptPolicy(model, settings),+ ui: getGenerationUiPolicy(model, settings),+ };+};++export const getDefaultGenerateSettings = (model?: GenerateModelConfig): GenerateSettings => {+ const defaults = getGenerationDefaults(model);+ const dimensions = getGenerationDimensions(model);+ const defaultSettings = model?.default_settings as GenerateDefaultSettings;+ const width = clampDimension(getNumber(defaultSettings?.width, dimensions.optimal), dimensions.grid);+ const height = clampDimension(getNumber(defaultSettings?.height, dimensions.optimal), dimensions.grid);++ return {+ aspectRatioId: deriveAspectRatioId(width, height),+ aspectRatioIsLocked: false,+ aspectRatioValue: height > 0 ? width / height : 1,+ batchCount: 1,+ cfgRescaleMultiplier: defaults.cfgRescaleMultiplier,+ cfgScale: defaults.cfgScale,+ clipSkip: 0,+ clipEmbedModel: null,+ clipGEmbedModel: null,+ clipLEmbedModel: null,+ componentSourceModel: null,+ height,+ loras: [],+ modelKey: model?.key ?? '',+ negativePrompt: '',+ positivePrompt: '',+ qwen3EncoderModel: null,+ qwenVLEncoderModel: null,+ scheduler: defaults.scheduler,+ seamlessXAxis: false,+ seamlessYAxis: false,+ seed: Math.floor(Math.random() * SEED_MAX),+ shouldRandomizeSeed: true,+ steps: defaults.steps,+ t5EncoderModel: null,+ vae: null,+ vaePrecision: defaults.vaePrecision,+ width,+ };+};++export const getSettingsWithModelDefaults = (+ settings: GenerateSettings,+ model: GenerateModelConfig+): GenerateSettings => {+ const modelDefaults = getDefaultGenerateSettings(model);++ return {+ ...settings,+ aspectRatioId: modelDefaults.aspectRatioId,+ aspectRatioIsLocked: false,+ aspectRatioValue: modelDefaults.aspectRatioValue,+ cfgRescaleMultiplier: modelDefaults.cfgRescaleMultiplier,+ cfgScale: modelDefaults.cfgScale,+ height: modelDefaults.height,+ loras: settings.loras.map((lora) =>+ isLoraCompatibleWithModel(lora.model, model) ? lora : { ...lora, isEnabled: false }+ ),+ modelKey: model.key,+ scheduler: modelDefaults.scheduler,+ steps: modelDefaults.steps,+ vae: null,+ vaePrecision: modelDefaults.vaePrecision,+ width: modelDefaults.width,+ };+};++export type GenerateComponentValueKey =+ | 't5EncoderModel'+ | 'clipEmbedModel'+ | 'clipLEmbedModel'+ | 'clipGEmbedModel'+ | 'qwen3EncoderModel'+ | 'qwenVLEncoderModel'+ | 'componentSourceModel'+ | 'vae';++export interface ComponentPolicyContext {+ model: GenerateModelConfig;+ settings: GenerateSettings;+ selectedComponents: Pick<GenerateSettings, GenerateComponentValueKey>;+}++export interface ComponentSlotPolicy {+ key: GenerateComponentValueKey;+ label: string;+ modelTypes: readonly ModelTaxonomyType[];+ valueKind: 'component' | 'vae' | 'main';+ helpText?: string;+ placeholder?: string;+ defaultOpen?: boolean;+ filter?: (candidate: ModelConfig, ctx: ComponentPolicyContext) => boolean;+ required?: (ctx: ComponentPolicyContext) => boolean;+ missingMessage?: string;+}++export interface ComponentSectionPolicy {+ defaultOpen: boolean;+ slots: readonly ComponentSlotPolicy[];+ validate: (ctx: ComponentPolicyContext) => string[];+}++export interface GenerateSettingsCompatibilityResult {+ settings: GenerateSettings;+ clearedLabels: string[];+}++const TYPE_CLIP_EMBED: ModelTaxonomyType[] = ['clip_embed'];+const TYPE_MAIN: ModelTaxonomyType[] = ['main'];+const TYPE_QWEN3: ModelTaxonomyType[] = ['qwen3_encoder'];+const TYPE_QWEN_VL: ModelTaxonomyType[] = ['qwen_vl_encoder'];+const TYPE_T5: ModelTaxonomyType[] = ['t5_encoder'];+const TYPE_VAE: ModelTaxonomyType[] = ['vae'];++const wrapFilter = (filter: GenerateComponentFilter) => (candidate: ModelConfig) => filter(candidate);++const slot = (policy: ComponentSlotPolicy): ComponentSlotPolicy => policy;++const componentSourceSlot = (+ filter: (candidate: ModelConfig, ctx: ComponentPolicyContext) => boolean,+ helpText: string+): ComponentSlotPolicy =>+ slot({+ key: 'componentSourceModel',+ label: 'Component source',+ modelTypes: TYPE_MAIN,+ valueKind: 'main',+ helpText,+ filter,+ });++const t5EncoderSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 't5EncoderModel',+ label: 'T5 Encoder',+ modelTypes: TYPE_T5,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 't5_encoder',+ });++const clipEmbedSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 'clipEmbedModel',+ label: 'CLIP Embed',+ modelTypes: TYPE_CLIP_EMBED,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 'clip_embed',+ });++const qwenVlEncoderSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 'qwenVLEncoderModel',+ label: 'Qwen VL Encoder',+ modelTypes: TYPE_QWEN_VL,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 'qwen_vl_encoder',+ });++const qwen3EncoderSlot = (helpText: string, filter?: GenerateComponentFilter): ComponentSlotPolicy =>+ slot({+ key: 'qwen3EncoderModel',+ label: 'Qwen3 Encoder',+ modelTypes: TYPE_QWEN3,+ valueKind: 'component',+ helpText,+ filter: filter+ ? (candidate) => candidate.type === 'qwen3_encoder' && filter(candidate)+ : (candidate) => candidate.type === 'qwen3_encoder',+ });++const clipVariantSlot = (+ key: 'clipLEmbedModel' | 'clipGEmbedModel',+ label: string,+ variant: string,+ helpText: string+) =>+ slot({+ key,+ label,+ modelTypes: TYPE_CLIP_EMBED,+ valueKind: 'component',+ helpText,+ filter: wrapFilter(isClipVariant(variant)),+ });++const vaeSlot = (helpText: string, filter: GenerateComponentFilter): ComponentSlotPolicy =>+ slot({ key: 'vae', label: 'VAE', modelTypes: TYPE_VAE, valueKind: 'vae', helpText, filter: wrapFilter(filter) });++const hasCompatibleComponentSource = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ Boolean(getCompatibleDiffusersComponentSource(ctx.model, ctx.settings.componentSourceModel));++type ComponentSourceCandidate = {+ base: string;+ key: string;+ name: string;+ type: string;+ format?: string;+ variant?: unknown;+};++const isFlux2DiffusersSource = (source: ComponentSourceCandidate | null | undefined): source is MainModelConfig =>+ Boolean(source && source.type === 'main' && source.base === 'flux2' && source.format === 'diffusers');++const hasFlux2DiffusersVaeSource = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ (ctx.model.format === 'diffusers' || isFlux2DiffusersSource(ctx.settings.componentSourceModel));++const hasFlux2DiffusersQwen3Source = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ (ctx.model.format === 'diffusers' ||+ Boolean(+ ctx.settings.componentSourceModel && isFlux2DiffusersSourceForModel(ctx.model)(ctx.settings.componentSourceModel)+ ));++export const getFlux2DiffusersComponentSource = (+ model: MainModelConfig,+ settings: GenerateSettings+): MainModelConfig | undefined => {+ const source = settings.componentSourceModel;++ if (!isFlux2DiffusersSource(source)) {+ return undefined;+ }++ if (settings.qwen3EncoderModel) {+ return source;+ }++ return isFlux2DiffusersSourceForModel(model)(source) ? source : undefined;+};++export const getAutoFlux2ComponentSourceModel = (+ model: GenerateModelConfig | undefined,+ settings: Pick<GenerateSettings, 'qwen3EncoderModel' | 'vae'>,+ models: readonly ComponentSourceCandidate[]+): MainModelConfig | null | undefined => {+ if (!model || model.type === 'external_image_generator' || model.base !== 'flux2') {+ return undefined;+ }++ if (model.format === 'diffusers' || (settings.qwen3EncoderModel && settings.vae)) {+ return null;+ }++ const diffusersModels = models.filter(isFlux2DiffusersSource);+ const variantMatch = diffusersModels.find(isFlux2DiffusersSourceForModel(model));++ if (!settings.qwen3EncoderModel && settings.vae) {+ return variantMatch ?? null;+ }++ return variantMatch ?? diffusersModels[0] ?? null;+};++// Split/quantized families can satisfy required encoder/VAE slots from a bundled Diffusers source.+const isBundledOrDiffusersSourceSatisfied = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ (ctx.model.format === 'diffusers' || hasCompatibleComponentSource(ctx));++// Slot validation is shared by invocation readiness and graph preflight so picker requirements cannot drift.+const validateSlots = (policy: Pick<ComponentSectionPolicy, 'slots'>, ctx: ComponentPolicyContext): string[] =>+ policy.slots.flatMap((slotPolicy) => {+ if (!slotPolicy.required?.(ctx)) {+ return [];+ }++ const value = ctx.selectedComponents[slotPolicy.key];+ const isValid = value && (!slotPolicy.filter || slotPolicy.filter(value as ModelConfig, ctx));++ return isValid ? [] : [slotPolicy.missingMessage ?? `Generate needs a ${slotPolicy.label} for this model.`];+ });++const createPolicy = (defaultOpen: boolean, slots: readonly ComponentSlotPolicy[]): ComponentSectionPolicy => ({+ defaultOpen,+ slots,+ validate: (ctx) => validateSlots({ slots }, ctx),+});++const EMPTY_COMPONENT_POLICY: ComponentSectionPolicy = createPolicy(false, []);++export const getComponentSectionPolicy = (+ model: GenerateModelConfig | undefined,+ _settings: GenerateSettings+): ComponentSectionPolicy => {+ if (!model || model.type === 'external_image_generator') {+ return EMPTY_COMPONENT_POLICY;+ }++ switch (model.base) {+ case 'flux':+ return {+ ...createPolicy(false, [+ {+ ...t5EncoderSlot('Required for FLUX.1 models.'),+ required: () => true,+ missingMessage: 'Generate needs a T5 Encoder for FLUX models.',+ },+ {+ ...clipEmbedSlot('Required for FLUX.1 models.'),+ required: () => true,+ missingMessage: 'Generate needs a CLIP Embed model for FLUX models.',+ },+ {+ ...vaeSlot('Required for FLUX.1 models.', isVaeForBases(['flux'])),+ required: () => true,+ missingMessage: 'Generate needs a VAE for FLUX models.',+ },+ ]),+ validate: (ctx) => [+ ...(ctx.model.type !== 'external_image_generator' && ctx.model.variant === 'dev_fill'+ ? ['FLUX Fill models do not support text-to-image generation.']+ : []),+ ...validateSlots(getComponentSectionPolicy(ctx.model, ctx.settings), ctx),+ ],+ };+ case 'flux2':+ return createPolicy(model.format !== 'diffusers', [+ {+ ...qwen3EncoderSlot('Optional override; otherwise a compatible installed FLUX.2 Diffusers model is used.'),+ filter: (candidate, ctx) =>+ ctx.model.type !== 'external_image_generator' && isFlux2Qwen3EncoderForModel(ctx.model)(candidate),+ required: (ctx) => !hasFlux2DiffusersQwen3Source(ctx),+ missingMessage: 'Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.',+ },+ {+ ...vaeSlot(+ 'Optional override; otherwise an installed FLUX.2 Diffusers model is used.',+ isVaeForBases(['flux2'])+ ),+ required: (ctx) => !hasFlux2DiffusersVaeSource(ctx),+ missingMessage: 'Generate needs a VAE for non-Diffusers FLUX.2 models.',+ },+ ]);+ case 'sd-3':+ return createPolicy(false, [+ t5EncoderSlot('Optional override; the main model is used when omitted.'),+ clipVariantSlot('clipLEmbedModel', 'CLIP L', 'large', 'Optional CLIP-L override.'),+ clipVariantSlot('clipGEmbedModel', 'CLIP G', 'gigantic', 'Optional CLIP-G override.'),+ vaeSlot('Optional VAE override.', isVaeForBases(['sd-3'])),+ ]);+ case 'qwen-image':+ return createPolicy(model.format !== 'diffusers', [+ componentSourceSlot(+ (candidate) => isDiffusersMainForBase('qwen-image')(candidate),+ 'For non-Diffusers Qwen Image models, select this or provide separate VAE and Qwen VL models.'+ ),+ {+ ...qwenVlEncoderSlot('Optional override, or required with a non-Diffusers model and no component source.'),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a Qwen VL Encoder for non-Diffusers Qwen Image models.',+ },+ {+ ...vaeSlot(+ 'Optional override, or required with a non-Diffusers model and no component source.',+ isVaeForBases(['qwen-image'])+ ),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a VAE for non-Diffusers Qwen Image models.',+ },+ ]);+ case 'z-image':+ return createPolicy(model.format !== 'diffusers', [+ componentSourceSlot(+ (candidate) => isDiffusersMainForBase('z-image')(candidate),+ 'Select a Diffusers Z-Image model to provide VAE and Qwen3 components.'+ ),+ {+ ...qwen3EncoderSlot('Required unless a Diffusers component source is available.', isNonAnimaQwen3Encoder),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a Qwen3 Encoder for Z-Image models.',+ },+ {+ ...vaeSlot('Required unless a Diffusers component source is available.', isVaeForBases(['flux'])),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a VAE for Z-Image models.',+ },+ ]);+ case 'anima':+ return createPolicy(true, [+ {+ ...qwen3EncoderSlot('Required for Anima models.', isAnimaQwen3Encoder),+ required: () => true,+ missingMessage: 'Generate needs a Qwen3 Encoder for Anima models.',+ },+ {+ ...vaeSlot('Required for Anima models. Qwen Image and FLUX VAEs are supported.', isAnimaVae),+ required: () => true,+ missingMessage: 'Generate needs a VAE for Anima models.',+ },+ ]);+ default:+ return EMPTY_COMPONENT_POLICY;+ }+};++const getComponentPolicyContext = (model: GenerateModelConfig, settings: GenerateSettings): ComponentPolicyContext => ({+ model,+ settings,+ selectedComponents: {+ clipEmbedModel: settings.clipEmbedModel,+ clipGEmbedModel: settings.clipGEmbedModel,+ clipLEmbedModel: settings.clipLEmbedModel,+ componentSourceModel: settings.componentSourceModel,+ qwen3EncoderModel: settings.qwen3EncoderModel,+ qwenVLEncoderModel: settings.qwenVLEncoderModel,+ t5EncoderModel: settings.t5EncoderModel,+ vae: settings.vae,+ },+});++const COMPONENT_SETTING_LABELS: Record<GenerateComponentValueKey, string> = {+ clipEmbedModel: 'CLIP Embed',+ clipGEmbedModel: 'CLIP G',+ clipLEmbedModel: 'CLIP L',+ qwen3EncoderModel: 'Qwen3 Encoder',+ qwenVLEncoderModel: 'Qwen VL Encoder',+ t5EncoderModel: 'T5 Encoder',+ vae: 'VAE',+ componentSourceModel: 'Component source',+};++const addClearedLabel = (labels: string[], label: string) => {+ if (!labels.includes(label)) {+ labels.push(label);+ }+};++const isSelectedComponentCompatible = (+ slotPolicy: ComponentSlotPolicy | undefined,+ model: GenerateModelConfig,+ settings: GenerateSettings,+ key: GenerateComponentValueKey+): boolean => {+ const value = settings[key];++ if (!value) {+ return true;+ }++ if (key === 'componentSourceModel' && model.type !== 'external_image_generator' && model.base === 'flux2') {+ return Boolean(getFlux2DiffusersComponentSource(model, settings));+ }++ if (!slotPolicy) {+ return false;+ }++ return !slotPolicy.filter || slotPolicy.filter(value as ModelConfig, getComponentPolicyContext(model, settings));+};++export const getSettingsWithCompatibleModelSelections = (+ settings: GenerateSettings,+ model: GenerateModelConfig+): GenerateSettingsCompatibilityResult => {+ const nextSettings: GenerateSettings = { ...settings, modelKey: model.key };+ const clearedLabels: string[] = [];+ const compatibleLoras = settings.loras.filter((lora) => isLoraCompatibleWithModel(lora.model, model));+ const dimensions = getGenerationDimensions(model);+ const width = clampDimension(nextSettings.width, dimensions.grid);+ const height = clampDimension(nextSettings.height, dimensions.grid);++ if (width !== nextSettings.width || height !== nextSettings.height) {+ nextSettings.width = width;+ nextSettings.height = height;+ nextSettings.aspectRatioId = deriveAspectRatioId(width, height);+ nextSettings.aspectRatioValue = height > 0 ? width / height : 1;+ addClearedLabel(clearedLabels, 'Dimensions');+ }++ if (compatibleLoras.length !== settings.loras.length) {+ nextSettings.loras = compatibleLoras;+ addClearedLabel(clearedLabels, 'LoRAs');+ }++ const policy = getComponentSectionPolicy(model, nextSettings);+ const slotsByKey = new Map(policy.slots.map((slotPolicy) => [slotPolicy.key, slotPolicy]));+ const uiPolicy = getGenerationUiPolicy(model, nextSettings);++ for (const key of Object.keys(COMPONENT_SETTING_LABELS) as GenerateComponentValueKey[]) {+ if (!nextSettings[key]) {+ continue;+ }++ if (key === 'vae' && !slotsByKey.has(key) && uiPolicy.sdVaeVisible && nextSettings.vae?.base === model.base) {+ continue;+ }++ if (!isSelectedComponentCompatible(slotsByKey.get(key), model, nextSettings, key)) {+ nextSettings[key] = null;+ addClearedLabel(clearedLabels, COMPONENT_SETTING_LABELS[key]);+ }+ }++ if (!uiPolicy.clipSkipMax && nextSettings.clipSkip !== 0) {+ nextSettings.clipSkip = 0;+ addClearedLabel(clearedLabels, 'CLIP skip');+ } else if (uiPolicy.clipSkipMax && nextSettings.clipSkip > uiPolicy.clipSkipMax) {+ nextSettings.clipSkip = uiPolicy.clipSkipMax;+ addClearedLabel(clearedLabels, 'CLIP skip');+ }++ if (!uiPolicy.cfgRescaleVisible && nextSettings.cfgRescaleMultiplier !== 0) {+ nextSettings.cfgRescaleMultiplier = 0;+ addClearedLabel(clearedLabels, 'CFG rescale');+ }++ if (!uiPolicy.seamlessVisible && (nextSettings.seamlessXAxis || nextSettings.seamlessYAxis)) {+ nextSettings.seamlessXAxis = false;+ nextSettings.seamlessYAxis = false;+ addClearedLabel(clearedLabels, 'Seamless tiling');+ }++ if (!uiPolicy.vaePrecisionVisible) {+ const defaultVaePrecision = getGenerationDefaults(model).vaePrecision;++ if (nextSettings.vaePrecision !== defaultVaePrecision) {+ nextSettings.vaePrecision = defaultVaePrecision;+ addClearedLabel(clearedLabels, 'VAE precision');+ }+ }++ return { settings: nextSettings, clearedLabels };+};++const hasModelKey = (models: readonly ModelConfig[], key: string, type?: string): boolean =>+ models.some((model) => model.key === key && (!type || model.type === type));++export const getGenerationModelAvailabilityReasons = (+ model: GenerateModelConfig,+ settings: GenerateSettings,+ models: readonly ModelConfig[]+): string[] => {+ const reasons: string[] = [];++ if (!hasModelKey(models, model.key, model.type)) {+ reasons.push(`Selected model "${model.name}" is no longer installed.`);+ }++ for (const key of Object.keys(COMPONENT_SETTING_LABELS) as GenerateComponentValueKey[]) {+ const value = settings[key];++ if (value && !hasModelKey(models, value.key, value.type)) {+ reasons.push(`${COMPONENT_SETTING_LABELS[key]} "${value.name}" is no longer installed.`);+ }+ }++ for (const lora of settings.loras) {+ if (!hasModelKey(models, lora.model.key, 'lora')) {+ reasons.push(`LoRA "${lora.model.name}" is no longer installed.`);+ }+ }++ return reasons;+};++const getDimensionValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {+ const reasons: string[] = [];+ const dimensions = getGenerationDimensions(model);++ if (!Number.isFinite(settings.width) || settings.width < dimensions.min || settings.width > dimensions.max) {+ reasons.push(`Generate width must be between ${dimensions.min} and ${dimensions.max}.`);+ } else if (settings.width % dimensions.grid !== 0) {+ reasons.push(`Generate width must be a multiple of ${dimensions.grid}.`);+ }++ if (!Number.isFinite(settings.height) || settings.height < dimensions.min || settings.height > dimensions.max) {+ reasons.push(`Generate height must be between ${dimensions.min} and ${dimensions.max}.`);+ } else if (settings.height % dimensions.grid !== 0) {+ reasons.push(`Generate height must be a multiple of ${dimensions.grid}.`);+ }++ return reasons;+};++export const getGenerationValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {+ if (!isSupportedGenerateModel(model)) {+ return ['Generate needs a supported model before it can be invoked.'];+ }++ const reasons = getDimensionValidationReasons(model, settings);++ if (model.type === 'external_image_generator') {+ if (model.capabilities?.modes && !model.capabilities.modes.includes('txt2img')) {+ reasons.push(`${model.name} does not support text-to-image generation.`);+ }++ if (!getExternalProviderNodeType(model.provider_id)) {+ reasons.push(`No invocation node registered for external provider '${model.provider_id ?? ''}'.`);+ }++ return reasons;+ }++ const componentPolicy = getComponentSectionPolicy(model, settings);+ reasons.push(...componentPolicy.validate(getComponentPolicyContext(model, settings)));++ return reasons;+};diff --git a/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.test.ts b/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.test.tsnew file mode 100644index 0000000000..3ffa2e0587--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest';++import type { ComponentModelConfig, GenerateModelConfig } from './types';++import {+ getCompatibleSelectedComponentKey,+ isAnimaQwen3Encoder,+ isAnimaVae,+ isFlux2DiffusersSourceForModel,+ isFlux2Qwen3EncoderForModel,+ isNonAnimaQwen3Encoder,+ isVaeCompatibleWithGenerateModel,+ type GenerateComponentCandidate,+} from './componentCompatibility';++const flux2Model = (variant: string): GenerateModelConfig => ({+ base: 'flux2',+ key: `flux2-${variant}`,+ name: `FLUX.2 ${variant}`,+ type: 'main',+ variant,+});++const candidate = (overrides: Partial<GenerateComponentCandidate>): GenerateComponentCandidate => ({+ base: 'any',+ type: 'qwen3_encoder',+ ...overrides,+});++describe('Generate component compatibility', () => {+ it('separates Anima Qwen3 0.6B encoders from other Qwen3 encoders', () => {+ const qwen06b = candidate({ variant: 'qwen3_06b' });+ const qwen4b = candidate({ variant: 'qwen3_4b' });++ expect(isAnimaQwen3Encoder(qwen06b)).toBe(true);+ expect(isAnimaQwen3Encoder(qwen4b)).toBe(false);+ expect(isNonAnimaQwen3Encoder(qwen06b)).toBe(false);+ expect(isNonAnimaQwen3Encoder(qwen4b)).toBe(true);+ });++ it('matches FLUX.2 Klein models to compatible Qwen3 encoder variants', () => {+ const filter = isFlux2Qwen3EncoderForModel(flux2Model('klein_9b'));++ expect(filter(candidate({ variant: 'qwen3_8b' }))).toBe(true);+ expect(filter(candidate({ variant: 'qwen3_4b' }))).toBe(false);+ expect(filter(candidate({ variant: 'qwen3_06b' }))).toBe(false);+ });++ it('matches FLUX.2 component sources by shared Qwen3 encoder variant', () => {+ const filter = isFlux2DiffusersSourceForModel(flux2Model('klein_9b'));++ expect(filter(candidate({ base: 'flux2', format: 'diffusers', type: 'main', variant: 'klein_9b_base' }))).toBe(+ true+ );+ expect(filter(candidate({ base: 'flux2', format: 'diffusers', type: 'main', variant: 'klein_4b' }))).toBe(false);+ expect(filter(candidate({ base: 'flux2', format: 'checkpoint', type: 'main', variant: 'klein_9b' }))).toBe(false);+ expect(filter(candidate({ base: 'flux2', format: 'diffusers', type: 'main' }))).toBe(false);+ });++ it('allows only backend-supported Anima VAE families', () => {+ expect(isAnimaVae(candidate({ base: 'anima', type: 'vae' }))).toBe(true);+ expect(isAnimaVae(candidate({ base: 'qwen-image', type: 'vae' }))).toBe(true);+ expect(isAnimaVae(candidate({ base: 'flux', type: 'vae' }))).toBe(true);+ expect(isAnimaVae(candidate({ base: 'sdxl', type: 'vae' }))).toBe(false);+ });++ it('centralizes generate VAE compatibility for cross-base families', () => {+ const vae = (base: string) => ({ base, key: `${base}-vae`, name: `${base} VAE`, type: 'vae' as const });++ expect(isVaeCompatibleWithGenerateModel(flux2Model('klein_9b'), vae('flux2'))).toBe(true);+ expect(isVaeCompatibleWithGenerateModel(flux2Model('klein_9b'), vae('flux'))).toBe(false);+ expect(+ isVaeCompatibleWithGenerateModel({ base: 'z-image', key: 'z-image', name: 'Z-Image', type: 'main' }, vae('flux'))+ ).toBe(true);+ expect(+ isVaeCompatibleWithGenerateModel({ base: 'anima', key: 'anima', name: 'Anima', type: 'main' }, vae('qwen-image'))+ ).toBe(true);+ });++ it('hides a stale selected component when it no longer passes the picker filter', () => {+ const staleVae: ComponentModelConfig = { base: 'sdxl', key: 'sdxl-vae', name: 'SDXL VAE', type: 'vae' };++ expect(getCompatibleSelectedComponentKey(staleVae, isAnimaVae)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.ts b/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.tsnew file mode 100644index 0000000000..3542a5fdcd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/componentCompatibility.ts@@ -0,0 +1,118 @@+import type { ComponentModelConfig, GenerateModelConfig, VaeModelConfig } from './types';++export type GenerateComponentCandidate = {+ base: string;+ format?: string;+ key?: string;+ type: string;+ variant?: unknown;+};++export type GenerateComponentFilter = (model: GenerateComponentCandidate) => boolean;++export const KLEIN_TO_QWEN3_VARIANT: Record<string, string> = {+ klein_4b: 'qwen3_4b',+ klein_4b_base: 'qwen3_4b',+ klein_9b: 'qwen3_8b',+ klein_9b_base: 'qwen3_8b',+};++export const getCompatibleSelectedComponentKey = (+ value: ComponentModelConfig | null,+ filter?: GenerateComponentFilter+): string | null => (value && (!filter || filter(value)) ? value.key : null);++export const isDiffusersMainForBase =+ (base: string): GenerateComponentFilter =>+ (model) =>+ model.type === 'main' && model.base === base && model.format === 'diffusers';++export const isVaeForBases =+ (bases: readonly string[]): GenerateComponentFilter =>+ (model) =>+ model.type === 'vae' && (bases.length === 0 || bases.includes(model.base));++export const isClipVariant =+ (variant: string): GenerateComponentFilter =>+ (model) =>+ model.type === 'clip_embed' && model.variant === variant;++export const isAnimaQwen3Encoder: GenerateComponentFilter = (model) =>+ model.type === 'qwen3_encoder' && model.variant === 'qwen3_06b';++export const isNonAnimaQwen3Encoder: GenerateComponentFilter = (model) =>+ model.type === 'qwen3_encoder' && model.variant !== 'qwen3_06b';++export const isFlux2Qwen3EncoderForModel = (selectedModel: GenerateModelConfig): GenerateComponentFilter => {+ const requiredVariant =+ typeof selectedModel.variant === 'string' ? KLEIN_TO_QWEN3_VARIANT[selectedModel.variant] : null;++ return (model) => {+ if (!isNonAnimaQwen3Encoder(model)) {+ return false;+ }++ return requiredVariant ? model.variant === requiredVariant : true;+ };+};++export const isFlux2DiffusersSourceForModel = (selectedModel: GenerateModelConfig): GenerateComponentFilter => {+ const selectedVariant = typeof selectedModel.variant === 'string' ? selectedModel.variant : null;+ const requiredVariant = selectedVariant ? KLEIN_TO_QWEN3_VARIANT[selectedVariant] : null;++ return (model) => {+ if (!isDiffusersMainForBase('flux2')(model)) {+ return false;+ }++ if (!requiredVariant) {+ return true;+ }++ const sourceVariant = typeof model.variant === 'string' ? model.variant : null;++ return sourceVariant ? KLEIN_TO_QWEN3_VARIANT[sourceVariant] === requiredVariant : false;+ };+};++export const isCompatibleDiffusersComponentSourceForModel = (+ selectedModel: GenerateModelConfig,+ source: GenerateComponentCandidate+): boolean => {+ if (selectedModel.type === 'external_image_generator') {+ return false;+ }++ if (selectedModel.base === 'flux2') {+ return isFlux2DiffusersSourceForModel(selectedModel)(source);+ }++ return isDiffusersMainForBase(selectedModel.base)(source);+};++export const getCompatibleDiffusersComponentSource = <T extends GenerateComponentCandidate>(+ selectedModel: GenerateModelConfig,+ source: T | null | undefined+): T | undefined =>+ source && isCompatibleDiffusersComponentSourceForModel(selectedModel, source) ? source : undefined;++export const isAnimaVae = isVaeForBases(['anima', 'qwen-image', 'flux']);++export const isVaeCompatibleWithGenerateModel = (model: GenerateModelConfig, vae: VaeModelConfig): boolean => {+ if (model.type === 'external_image_generator') {+ return false;+ }++ switch (model.base) {+ case 'anima':+ return isAnimaVae(vae);+ case 'z-image':+ return isVaeForBases(['flux'])(vae);+ case 'qwen-image':+ return isVaeForBases(['qwen-image'])(vae);+ case 'flux2':+ return isVaeForBases(['flux2'])(vae);+ default:+ return vae.type === 'vae' && vae.base === model.base;+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.test.tsindex 6030e16d56..0cfe5e214b 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts@@ -1,31 +1,125 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import type { GenerateSettings, MainModelConfig, VaeModelConfig } from './types';+import type {+ ComponentModelConfig,+ GenerateModelConfig,+ GenerateSettings,+ LoraModelConfig,+ MainModelConfig,+ VaeModelConfig,+} from './types';-import { compileGenerateGraph, generateSeedSequence, getDefaultGenerateSettings, resolveGenerateSeed } from './graph';+import { getDefaultGenerateSettings, isSupportedGenerateModel } from './baseGenerationPolicies';+import { compileGenerateGraph, generateSeedSequence, resolveGenerateSeed } from './graph';const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };+const sd3Model: MainModelConfig = { base: 'sd-3', key: 'sd3-model', name: 'SD3', type: 'main' };+const fluxModel: MainModelConfig = { base: 'flux', key: 'flux-model', name: 'FLUX dev', type: 'main' };+const flux2Model: MainModelConfig = {+ base: 'flux2',+ format: 'diffusers',+ key: 'flux2-model',+ name: 'FLUX.2',+ type: 'main',+};+const flux2Klein9bModel: MainModelConfig = {+ base: 'flux2',+ format: 'gguf_quantized',+ key: 'flux2-klein-9b',+ name: 'FLUX.2 Klein 9B',+ type: 'main',+ variant: 'klein_9b',+};+const incompatibleFlux2Source: MainModelConfig = {+ base: 'flux2',+ format: 'diffusers',+ key: 'flux2-klein-4b-source',+ name: 'FLUX.2 Klein 4B Source',+ type: 'main',+ variant: 'klein_4b',+};+const cogView4Model: MainModelConfig = { base: 'cogview4', key: 'cog-model', name: 'CogView4', type: 'main' };+const qwenImageModel: MainModelConfig = {+ base: 'qwen-image',+ format: 'diffusers',+ key: 'qwen-model',+ name: 'Qwen Image',+ type: 'main',+};+const zImageModel: MainModelConfig = {+ base: 'z-image',+ format: 'diffusers',+ key: 'z-model',+ name: 'Z-Image',+ type: 'main',+};+const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };+const externalModel: GenerateModelConfig = {+ base: 'external',+ capabilities: { modes: ['txt2img'], supports_seed: true },+ format: 'external_api',+ key: 'external-model',+ name: 'OpenAI Image',+ provider_id: 'openai',+ type: 'external_image_generator',+};+const sd1Lora: LoraModelConfig = { base: 'sd-1', key: 'sd1-lora', name: 'SD 1.5 LoRA', type: 'lora' };+const sd2Lora: LoraModelConfig = { base: 'sd-2', key: 'sd2-lora', name: 'SD 2 LoRA', type: 'lora' };+const sdxlLora: LoraModelConfig = { base: 'sdxl', key: 'sdxl-lora', name: 'SDXL LoRA', type: 'lora' };+const fluxLora: LoraModelConfig = { base: 'flux', key: 'flux-lora', name: 'FLUX LoRA', type: 'lora' };const vae: VaeModelConfig = { base: 'sd-1', key: 'vae-model', name: 'Custom VAE', type: 'vae' };+const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+const flux2Vae: VaeModelConfig = { base: 'flux2', key: 'flux2-vae', name: 'FLUX.2 VAE', type: 'vae' };+const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };+const t5Encoder: ComponentModelConfig = { base: 'any', key: 't5', name: 'T5 Encoder', type: 't5_encoder' };+const clipEmbed: ComponentModelConfig = { base: 'any', key: 'clip', name: 'CLIP Embed', type: 'clip_embed' };+const qwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3',+ name: 'Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_06b',+};-const createSettings = (model: MainModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({+const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({...getDefaultGenerateSettings(model),seed: 1,shouldRandomizeSeed: false,...overrides,});-const compile = (model: MainModelConfig, overrides: Partial<GenerateSettings> = {}) =>+const compile = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}) =>compileGenerateGraph(createSettings(model, overrides), model, 'gallery', { useCpuNoise: true }).backendGraph;const getEdge = (graph: ReturnType<typeof compile>, targetNodeId: string, targetField: string) =>graph.edges.find((edge) => edge.destination.node_id === targetNodeId && edge.destination.field === targetField);+const getNodeByType = (graph: ReturnType<typeof compile>, type: string) =>+ Object.values(graph.nodes).find((node) => node.type === type);+afterEach(() => {vi.restoreAllMocks();});describe('compileGenerateGraph', () => {+ it('recognizes the legacy-supported generate model families', () => {+ expect(+ [+ sd1Model,+ sdxlModel,+ sd3Model,+ fluxModel,+ flux2Model,+ cogView4Model,+ qwenImageModel,+ zImageModel,+ animaModel,+ externalModel,+ ].every(isSupportedGenerateModel)+ ).toBe(true);+ });+it('builds a plain txt2img graph without optional nodes', () => {const graph = compile(sd1Model);@@ -36,6 +130,14 @@ describe('compileGenerateGraph', () => {expect(graph.nodes.canvas_output?.fp32).toBe(true);});+ it('coerces invalid SD schedulers before graph submission', () => {+ const graph = compile(sd1Model, { scheduler: 'not-a-scheduler' });+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(graph.nodes.denoise_latents?.scheduler).toBe('euler_a');+ expect(metadata?.scheduler).toBe('euler_a');+ });+it('wires CLIP skip into the SD1 conditioning chain', () => {const graph = compile(sd1Model, { clipSkip: 2 });@@ -65,6 +167,134 @@ describe('compileGenerateGraph', () => {expect(mismatched.nodes.vae_loader).toBeUndefined();expect(getEdge(mismatched, 'canvas_output', 'vae')?.source.node_id).toBe('model_loader');});++ it('routes SD LoRAs through the UNet and CLIP conditioning chain', () => {+ const graph = compile(sd1Model, {+ loras: [{ isEnabled: true, model: sd1Lora, weight: 0.5 }],+ });+ const loraLoader = getNodeByType(graph, 'lora_collection_loader');+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(loraLoader).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'pos_cond', 'clip')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'neg_cond', 'clip')?.source.node_id).toBe(loraLoader?.id);+ expect(metadata?.loras).toEqual([+ { model: { base: 'sd-1', key: 'sd1-lora', name: 'SD 1.5 LoRA', type: 'lora' }, weight: 0.5 },+ ]);+ });++ it('routes SDXL LoRAs through both CLIP encoders', () => {+ const graph = compile(sdxlModel, {+ loras: [{ isEnabled: true, model: sdxlLora, weight: 0.65 }],+ });+ const loraLoader = getNodeByType(graph, 'sdxl_lora_collection_loader');++ expect(loraLoader).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'pos_cond', 'clip')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'pos_cond', 'clip2')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'neg_cond', 'clip2')?.source.node_id).toBe(loraLoader?.id);+ });++ it('ignores disabled and incompatible LoRAs', () => {+ const graph = compile(sd1Model, {+ loras: [+ { isEnabled: true, model: sd2Lora, weight: 1 },+ { isEnabled: false, model: sd1Lora, weight: 1 },+ ],+ });+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(getNodeByType(graph, 'lora_collection_loader')).toBeUndefined();+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe('model_loader');+ expect(metadata?.loras).toBeUndefined();+ });++ it('builds a FLUX graph with required components and FLUX LoRAs', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ loras: [{ isEnabled: true, model: fluxLora, weight: 0.8 }],+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ });+ const loraLoader = getNodeByType(graph, 'flux_lora_collection_loader');++ expect(graph.nodes.model_loader?.type).toBe('flux_model_loader');+ expect(graph.nodes.model_loader?.t5_encoder_model).toEqual(t5Encoder);+ expect(graph.nodes.model_loader?.clip_embed_model).toEqual(clipEmbed);+ expect(graph.nodes.denoise_latents?.type).toBe('flux_denoise');+ expect(graph.nodes.canvas_output?.type).toBe('flux_vae_decode');+ expect(loraLoader).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'transformer')?.source.node_id).toBe(loraLoader?.id);+ });++ it('fails early when required FLUX components are missing', () => {+ expect(() => compile(fluxModel)).toThrow('Generate needs a T5 Encoder for FLUX models.');+ });++ it('builds modern Diffusers-family graphs without separate component overrides', () => {+ expect(compile(sd3Model).nodes.model_loader?.type).toBe('sd3_model_loader');+ expect(compile(flux2Model).nodes.model_loader?.type).toBe('flux2_klein_model_loader');+ expect(compile(cogView4Model).nodes.model_loader?.type).toBe('cogview4_model_loader');+ expect(compile(qwenImageModel).nodes.model_loader?.type).toBe('qwen_image_model_loader');+ expect(compile(zImageModel).nodes.model_loader?.type).toBe('z_image_model_loader');+ });++ it('does not enable FLUX.2 CFG without negative conditioning', () => {+ const graph = compile(flux2Model, { cfgScale: 4 });++ expect(graph.nodes.denoise_latents?.cfg_scale).toBe(1);+ expect(getEdge(graph, 'denoise_latents', 'negative_text_conditioning')).toBeUndefined();+ });++ it('rejects a stale incompatible FLUX.2 component source when Qwen3 is missing', () => {+ expect(() => compile(flux2Klein9bModel, { componentSourceModel: incompatibleFlux2Source, vae: flux2Vae })).toThrow(+ 'Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.'+ );+ });++ it('rejects dimensions that are not on the selected model family grid', () => {+ expect(() => compile(flux2Model, { height: 888 })).toThrow('Generate height must be a multiple of 16.');+ });++ it('builds an Anima graph with required components', () => {+ expect(() => compile(animaModel)).toThrow('Generate needs a Qwen3 Encoder for Anima models.');++ const graph = compile(animaModel, { qwen3EncoderModel: qwen3Encoder, vae: qwenImageVae });++ expect(graph.nodes.model_loader?.type).toBe('anima_model_loader');+ expect(graph.nodes.model_loader?.qwen3_encoder_model).toEqual(qwen3Encoder);+ expect(graph.nodes.model_loader?.vae_model).toEqual(qwenImageVae);+ expect(graph.nodes.canvas_output?.type).toBe('anima_l2i');+ });++ it('builds an external provider graph', () => {+ const graph = compile(externalModel);++ expect(graph.nodes.canvas_output?.type).toBe('openai_image_generation');+ expect(graph.nodes.canvas_output?.model).toEqual(externalModel);+ expect(getEdge(graph, 'canvas_output', 'prompt')?.source.node_id).toBe('positive_prompt');+ expect(getEdge(graph, 'canvas_output', 'seed')?.source.node_id).toBe('seed');+ });++ it('does not wire unsupported external provider seed or negative prompt inputs', () => {+ const graph = compile({ ...externalModel, capabilities: { modes: ['txt2img'] } });++ expect(getEdge(graph, 'canvas_output', 'prompt')?.source.node_id).toBe('positive_prompt');+ expect(getEdge(graph, 'canvas_output', 'seed')).toBeUndefined();+ expect(getEdge(graph, 'canvas_output', 'negative_prompt')).toBeUndefined();+ });++ it('wires external negative prompt only when the provider advertises support', () => {+ const graph = compile({+ ...externalModel,+ capabilities: { modes: ['txt2img'], supports_negative_prompt: true, supports_seed: false },+ });++ expect(getEdge(graph, 'canvas_output', 'negative_prompt')?.source.node_id).toBe('negative_prompt');+ expect(getEdge(graph, 'canvas_output', 'seed')).toBeUndefined();+ });});describe('generate seeds', () => {diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.tsindex a12f613ec3..f0dfe018c1 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graph.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.ts@@ -6,74 +6,38 @@ import type {ResultDestination,} from '@workbench/types';-import type { CompiledGenerateGraph, GenerateSettings, MainModelConfig, SupportedGenerateBase } from './types';--import { clampDimension, deriveAspectRatioId, getOptimalDimension, SEED_MAX } from './settings';+import type {+ CompiledGenerateGraph,+ ComponentModelConfig,+ GenerateLora,+ GenerateModelConfig,+ GenerateSettings,+ MainModelConfig,+} from './types';++import {+ coerceSchedulerForGraph,+ getExternalProviderNodeType,+ getFlux2DiffusersComponentSource,+ getGenerationDimensions,+ getGenerationValidationReasons,+ type SupportedGenerateBase,+} from './baseGenerationPolicies';+import {+ getCompatibleDiffusersComponentSource,+ isAnimaQwen3Encoder,+ isAnimaVae,+ isFlux2Qwen3EncoderForModel,+ isNonAnimaQwen3Encoder,+ isVaeForBases,+} from './componentCompatibility';+import { isLoraCompatibleWithModel, SEED_MAX } from './settings';const now = (): string => new Date().toISOString();const createId = (prefix: string): string =>`${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;-const getNumber = (value: number | null | undefined, fallback: number): number =>- Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;--export const isSupportedGenerateModel = <T extends { base: string; type: string }>(- model: T-): model is T & { base: SupportedGenerateBase; type: 'main' } =>- model.type === 'main' && (model.base === 'sdxl' || model.base === 'sd-1' || model.base === 'sd-2');--export const getDefaultGenerateSettings = (model?: MainModelConfig): GenerateSettings => {- const defaults = model?.default_settings;- const optimalDimension = getOptimalDimension(model?.base ?? 'sdxl');- const width = clampDimension(getNumber(defaults?.width, optimalDimension));- const height = clampDimension(getNumber(defaults?.height, optimalDimension));-- return {- aspectRatioId: deriveAspectRatioId(width, height),- aspectRatioIsLocked: false,- aspectRatioValue: height > 0 ? width / height : 1,- batchCount: 1,- cfgRescaleMultiplier: getNumber(defaults?.cfg_rescale_multiplier, 0),- cfgScale: getNumber(defaults?.cfg_scale, 7),- clipSkip: 0,- height,- modelKey: model?.key ?? '',- negativePrompt: '',- positivePrompt: '',- scheduler: defaults?.scheduler ?? 'euler_a',- seamlessXAxis: false,- seamlessYAxis: false,- seed: Math.floor(Math.random() * SEED_MAX),- shouldRandomizeSeed: true,- steps: Math.max(1, Math.round(getNumber(defaults?.steps, 30))),- vae: null,- vaePrecision: defaults?.vae_precision === 'fp16' ? 'fp16' : 'fp32',- width,- };-};--export const getSettingsWithModelDefaults = (settings: GenerateSettings, model: MainModelConfig): GenerateSettings => {- const modelDefaults = getDefaultGenerateSettings(model);-- return {- ...settings,- aspectRatioId: modelDefaults.aspectRatioId,- aspectRatioIsLocked: false,- aspectRatioValue: modelDefaults.aspectRatioValue,- cfgRescaleMultiplier: modelDefaults.cfgRescaleMultiplier,- cfgScale: modelDefaults.cfgScale,- height: modelDefaults.height,- modelKey: model.key,- scheduler: modelDefaults.scheduler,- steps: modelDefaults.steps,- // VAE overrides are base-specific; the widget re-resolves the model's default VAE after a switch.- vae: null,- vaePrecision: modelDefaults.vaePrecision,- width: modelDefaults.width,- };-};-const addNode = <T extends BackendInvocationContract>(graph: BackendGraphContract, node: T): T => {graph.nodes[node.id] = {is_intermediate: true,@@ -100,35 +64,145 @@ const addEdge = (return edge;};+const getActiveCompatibleLoras = (settings: GenerateSettings, model: GenerateModelConfig): GenerateLora[] =>+ settings.loras.filter((lora) => lora.isEnabled && isLoraCompatibleWithModel(lora.model, model));++const toModelIdentifier = (+ model: { base: string; key: string; name: string; type: string } & Record<string, unknown>+) => ({+ base: model.base,+ key: model.key,+ name: model.name,+ type: model.type,+ ...(typeof model.hash === 'string' ? { hash: model.hash } : {}),+ ...(typeof model.submodel_type === 'string' ? { submodel_type: model.submodel_type } : {}),+});++const getCompatibleComponentSource = (+ settings: GenerateSettings,+ model: MainModelConfig+): MainModelConfig | undefined => getCompatibleDiffusersComponentSource(model, settings.componentSourceModel);++const getCompatibleVae = (settings: GenerateSettings, bases: readonly string[]) =>+ settings.vae && isVaeForBases(bases)(settings.vae) ? settings.vae : null;++const getDiffusersSource = (settings: GenerateSettings, model: MainModelConfig): MainModelConfig | undefined =>+ getCompatibleComponentSource(settings, model) ?? (model.format === 'diffusers' ? model : undefined);++const requireComponent = <T extends ComponentModelConfig | null>(value: T, label: string): NonNullable<T> => {+ if (!value) {+ throw new Error(`${label} is required for this model family.`);+ }++ return value;+};++const addLoraSelectors = (+ graph: BackendGraphContract,+ loras: GenerateLora[],+ loaderType: string+): BackendInvocationContract => {+ const collector = addNode(graph, { id: createId('lora_collector'), type: 'collect' });+ const loader = addNode(graph, { id: createId(loaderType), type: loaderType });++ addEdge(graph, collector, 'collection', loader, 'loras');++ for (const lora of loras) {+ const selector = addNode(graph, {+ id: createId('lora_selector'),+ lora: toModelIdentifier(lora.model),+ type: 'lora_selector',+ weight: lora.weight,+ });++ addEdge(graph, selector, 'lora', collector, 'item');+ }++ return loader;+};++const addLoraCollectionLoader = (+ graph: BackendGraphContract,+ loras: GenerateLora[],+ model: GenerateModelConfig,+ sources: {+ clip: BackendInvocationContract;+ clip2?: BackendInvocationContract;+ unet: BackendInvocationContract;+ }+): BackendInvocationContract => {+ const loaderType = model.base === 'sdxl' ? 'sdxl_lora_collection_loader' : 'lora_collection_loader';+ const loader = addLoraSelectors(graph, loras, loaderType);++ addEdge(graph, sources.unet, 'unet', loader, 'unet');+ addEdge(graph, sources.clip, 'clip', loader, 'clip');++ if (sources.clip2) {+ addEdge(graph, sources.clip2, 'clip2', loader, 'clip2');+ }++ return loader;+};++const addTransformerLoraCollectionLoader = (+ graph: BackendGraphContract,+ loras: GenerateLora[],+ loaderType: string,+ modelLoader: BackendInvocationContract,+ fields: string[]+): BackendInvocationContract => {+ const loader = addLoraSelectors(graph, loras, loaderType);++ for (const field of fields) {+ addEdge(graph, modelLoader, field, loader, field);+ }++ return loader;+};+const addMetadata = (graph: BackendGraphContract,outputNode: BackendInvocationContract,settings: GenerateSettings,- model: MainModelConfig,- generationMode: string,- projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+ model: GenerateModelConfig,+ generationMode: string | null,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>,+ extras: Record<string, unknown> = {}) => {+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);const metadata = addNode(graph, {cfg_scale: settings.cfgScale,cfg_rescale_multiplier: settings.cfgRescaleMultiplier,- generation_mode: generationMode,+ ...(generationMode ? { generation_mode: generationMode } : {}),height: settings.height,id: createId('core_metadata'),model,rand_device: projectSettings.useCpuNoise ? 'cpu' : 'cuda',- scheduler: settings.scheduler,+ scheduler,seamless_x: settings.seamlessXAxis,seamless_y: settings.seamlessYAxis,steps: settings.steps,type: 'core_metadata',vae: settings.vae ?? undefined,width: settings.width,+ ...extras,+ ...(activeLoras.length+ ? {+ loras: activeLoras.map((lora) => ({+ model: toModelIdentifier(lora.model),+ weight: lora.weight,+ })),+ }+ : {}),...(model.base === 'sdxl' ? {} : { clip_skip: settings.clipSkip }),});addEdge(graph, graph.nodes.seed, 'value', metadata, 'seed');addEdge(graph, graph.nodes.positive_prompt, 'value', metadata, 'positive_prompt');- addEdge(graph, graph.nodes.negative_prompt, 'value', metadata, 'negative_prompt');+ if (graph.nodes.negative_prompt) {+ addEdge(graph, graph.nodes.negative_prompt, 'value', metadata, 'negative_prompt');+ }addEdge(graph, metadata, 'metadata', outputNode, 'metadata');};@@ -141,6 +215,8 @@ const buildSDGraph = (const graph: BackendGraphContract = { edges: [], id: createId(`${model.base}_graph`), nodes: {} };const modelLoaderType = model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader';const compelType = model.base === 'sdxl' ? 'sdxl_compel_prompt' : 'compel';+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);const positivePrompt = addNode(graph, { id: 'positive_prompt', type: 'string' });const negativePrompt = addNode(graph, { id: 'negative_prompt', type: 'string' });@@ -163,7 +239,7 @@ const buildSDGraph = (denoising_end: 1,denoising_start: 0,id: 'denoise_latents',- scheduler: settings.scheduler,+ scheduler,steps: settings.steps,type: 'denoise_latents',});@@ -188,12 +264,12 @@ const buildSDGraph = (type: 'seamless',}): null;+ let unetSource: BackendInvocationContract = seamless ?? modelLoader;+ let clipSource: BackendInvocationContract = modelLoader;+ let clip2Source: BackendInvocationContract | undefined;if (model.base === 'sdxl') {- addEdge(graph, modelLoader, 'clip', posCond, 'clip');- addEdge(graph, modelLoader, 'clip2', posCond, 'clip2');- addEdge(graph, modelLoader, 'clip', negCond, 'clip');- addEdge(graph, modelLoader, 'clip2', negCond, 'clip2');+ clip2Source = modelLoader;addEdge(graph, positivePrompt, 'value', posCond, 'prompt');addEdge(graph, positivePrompt, 'value', posCond, 'style');addEdge(graph, negativePrompt, 'value', negCond, 'prompt');@@ -202,12 +278,33 @@ const buildSDGraph = (const clipSkip = addNode(graph, { id: 'clip_skip', skipped_layers: settings.clipSkip, type: 'clip_skip' });addEdge(graph, modelLoader, 'clip', clipSkip, 'clip');- addEdge(graph, clipSkip, 'clip', posCond, 'clip');- addEdge(graph, clipSkip, 'clip', negCond, 'clip');+ clipSource = clipSkip;addEdge(graph, positivePrompt, 'value', posCond, 'prompt');addEdge(graph, negativePrompt, 'value', negCond, 'prompt');}+ if (activeLoras.length > 0) {+ const loraLoader = addLoraCollectionLoader(graph, activeLoras, model, {+ clip: clipSource,+ clip2: clip2Source,+ unet: unetSource,+ });++ unetSource = loraLoader;+ clipSource = loraLoader;+ clip2Source = model.base === 'sdxl' ? loraLoader : undefined;+ }++ if (model.base === 'sdxl') {+ addEdge(graph, clipSource, 'clip', posCond, 'clip');+ addEdge(graph, clip2Source ?? modelLoader, 'clip2', posCond, 'clip2');+ addEdge(graph, clipSource, 'clip', negCond, 'clip');+ addEdge(graph, clip2Source ?? modelLoader, 'clip2', negCond, 'clip2');+ } else {+ addEdge(graph, clipSource, 'clip', posCond, 'clip');+ addEdge(graph, clipSource, 'clip', negCond, 'clip');+ }+addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');@@ -219,19 +316,545 @@ const buildSDGraph = (if (seamless) {addEdge(graph, modelLoader, 'unet', seamless, 'unet');addEdge(graph, vaeLoader ?? modelLoader, 'vae', seamless, 'vae');- addEdge(graph, seamless, 'unet', denoise, 'unet');- } else {- addEdge(graph, modelLoader, 'unet', denoise, 'unet');}+ addEdge(graph, unetSource, 'unet', denoise, 'unet');addEdge(graph, noise, 'noise', denoise, 'noise');addEdge(graph, denoise, 'latents', output, 'latents');addEdge(graph, seamless ?? vaeLoader ?? modelLoader, 'vae', output, 'vae');- addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings);+ addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings, {+ scheduler,+ });++ return graph;+};++const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({+ negativePrompt: addNode(graph, { id: 'negative_prompt', type: 'string' }),+ positivePrompt: addNode(graph, { id: 'positive_prompt', type: 'string' }),+ seed: addNode(graph, { id: 'seed', type: 'integer' }),+});++const addImageOutputNode = (graph: BackendGraphContract, type: string, outputIsIntermediate: boolean) =>+ addNode(graph, { id: 'canvas_output', is_intermediate: outputIsIntermediate, type, use_cache: false });++const buildSD3Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ const graph: BackendGraphContract = { edges: [], id: createId('sd3_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const modelLoader = addNode(graph, {+ clip_g_model: settings.clipGEmbedModel ?? undefined,+ clip_l_model: settings.clipLEmbedModel ?? undefined,+ id: 'model_loader',+ model,+ t5_encoder_model: settings.t5EncoderModel ?? undefined,+ type: 'sd3_model_loader',+ vae_model: settings.vae ?? undefined,+ });+ const posCond = addNode(graph, { id: 'pos_cond', type: 'sd3_text_encoder' });+ const negCond = addNode(graph, { id: 'neg_cond', type: 'sd3_text_encoder' });+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ denoising_end: 1,+ denoising_start: 0,+ height: settings.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'sd3_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'sd3_l2i', outputIsIntermediate);++ addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'clip_l', posCond, 'clip_l');+ addEdge(graph, modelLoader, 'clip_l', negCond, 'clip_l');+ addEdge(graph, modelLoader, 'clip_g', posCond, 'clip_g');+ addEdge(graph, modelLoader, 'clip_g', negCond, 'clip_g');+ addEdge(graph, modelLoader, 't5_encoder', posCond, 't5_encoder');+ addEdge(graph, modelLoader, 't5_encoder', negCond, 't5_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'sd3_txt2img', projectSettings, {+ scheduler: undefined,+ vae: settings.vae ?? undefined,+ });++ return graph;+};++const buildFluxGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ if (model.variant === 'dev_fill') {+ throw new Error('FLUX Fill models do not support text-to-image generation.');+ }++ const graph: BackendGraphContract = { edges: [], id: createId('flux_graph'), nodes: {} };+ const { positivePrompt } = addPromptAndSeedNodes(graph);+ const t5EncoderModel = requireComponent(settings.t5EncoderModel, 'T5 Encoder');+ const clipEmbedModel = requireComponent(settings.clipEmbedModel, 'CLIP Embed');+ const vaeModel = requireComponent(getCompatibleVae(settings, ['flux']), 'FLUX VAE');+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const modelLoader = addNode(graph, {+ clip_embed_model: clipEmbedModel,+ id: 'model_loader',+ model,+ t5_encoder_model: t5EncoderModel,+ type: 'flux_model_loader',+ vae_model: vaeModel,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'flux_lora_collection_loader', modelLoader, [+ 'transformer',+ 'clip',+ 't5_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'flux_text_encoder' });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const denoise = addNode(graph, {+ denoising_end: 1,+ denoising_start: 0,+ guidance: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ num_steps: settings.steps,+ scheduler,+ type: 'flux_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'flux_vae_decode', outputIsIntermediate);++ addEdge(graph, loraSource, 'clip', posCond, 'clip');+ addEdge(graph, loraSource, 't5_encoder', posCond, 't5_encoder');+ addEdge(graph, modelLoader, 'max_seq_len', posCond, 't5_max_seq_len');+ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'vae', denoise, 'controlnet_vae');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');+ addEdge(graph, graph.nodes.seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'flux_txt2img', projectSettings, {+ clip_embed_model: clipEmbedModel,+ guidance: settings.cfgScale,+ scheduler,+ t5_encoder: t5EncoderModel,+ vae: vaeModel,+ });++ return graph;+};++const buildFlux2Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ const sourceModel = getFlux2DiffusersComponentSource(model, settings);+ const hasBundledComponents = model.format === 'diffusers' || sourceModel;+ const qwen3EncoderModel =+ settings.qwen3EncoderModel && isFlux2Qwen3EncoderForModel(model)(settings.qwen3EncoderModel)+ ? settings.qwen3EncoderModel+ : null;+ const vaeModel = getCompatibleVae(settings, ['flux2']);++ if (!hasBundledComponents && (!vaeModel || !qwen3EncoderModel)) {+ throw new Error('FLUX.2 non-Diffusers models require a VAE and Qwen3 Encoder, or a Diffusers component source.');+ }++ const graph: BackendGraphContract = { edges: [], id: createId('flux2_graph'), nodes: {} };+ const { positivePrompt } = addPromptAndSeedNodes(graph);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const modelLoader = addNode(graph, {+ id: 'model_loader',+ model,+ qwen3_encoder_model: qwen3EncoderModel ?? undefined,+ qwen3_source_model: sourceModel,+ type: 'flux2_klein_model_loader',+ vae_model: vaeModel ?? undefined,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'flux2_klein_lora_collection_loader', modelLoader, [+ 'transformer',+ 'qwen3_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'flux2_klein_text_encoder' });+ const denoise = addNode(graph, {+ cfg_scale: 1,+ denoising_end: 1,+ denoising_start: 0,+ guidance: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ num_steps: settings.steps,+ scheduler,+ type: 'flux2_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'flux2_vae_decode', outputIsIntermediate);++ addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');+ addEdge(graph, modelLoader, 'max_seq_len', posCond, 'max_seq_len');+ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'vae', denoise, 'vae');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_text_conditioning');+ addEdge(graph, graph.nodes.seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'flux2_txt2img', projectSettings, {+ qwen3_encoder: qwen3EncoderModel ?? undefined,+ qwen3_source: sourceModel,+ scheduler,+ vae: vaeModel ?? undefined,+ });++ return graph;+};++const buildCogView4Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ const graph: BackendGraphContract = { edges: [], id: createId('cogview4_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const modelLoader = addNode(graph, { id: 'model_loader', model, type: 'cogview4_model_loader' });+ const posCond = addNode(graph, { id: 'pos_cond', type: 'cogview4_text_encoder' });+ const negCond = addNode(graph, { id: 'neg_cond', type: 'cogview4_text_encoder' });+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'cogview4_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'cogview4_l2i', outputIsIntermediate);++ addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'glm_encoder', posCond, 'glm_encoder');+ addEdge(graph, modelLoader, 'glm_encoder', negCond, 'glm_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'cogview4_txt2img', projectSettings, { scheduler: undefined });++ return graph;+};++const buildQwenImageGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ const sourceModel = getCompatibleComponentSource(settings, model);+ const hasBundledComponents = model.format === 'diffusers' || sourceModel;+ const vaeModel = getCompatibleVae(settings, ['qwen-image']);++ if (!hasBundledComponents && (!vaeModel || !settings.qwenVLEncoderModel)) {+ throw new Error(+ 'Qwen Image non-Diffusers models require a VAE and Qwen VL Encoder, or a Diffusers component source.'+ );+ }++ const graph: BackendGraphContract = { edges: [], id: createId('qwen_image_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const useCfg = settings.cfgScale > 1;+ const modelLoader = addNode(graph, {+ component_source: sourceModel,+ id: 'model_loader',+ model,+ qwen_vl_encoder_model: settings.qwenVLEncoderModel ?? undefined,+ type: 'qwen_image_model_loader',+ vae_model: vaeModel ?? undefined,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'qwen_image_lora_collection_loader', modelLoader, [+ 'transformer',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'qwen_image_text_encoder' });+ const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'qwen_image_text_encoder' }) : null;+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'qwen_image_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'qwen_image_l2i', outputIsIntermediate);++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'qwen_vl_encoder', posCond, 'qwen_vl_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');++ if (negCond) {+ addEdge(graph, modelLoader, 'qwen_vl_encoder', negCond, 'qwen_vl_encoder');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ }++ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'qwen_image_txt2img', projectSettings, {+ qwen_image_component_source: sourceModel,+ qwen_image_qwen_vl_encoder: settings.qwenVLEncoderModel ?? undefined,+ qwen_image_vae: vaeModel ?? undefined,+ scheduler: undefined,+ });++ return graph;+};++const buildZImageGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ const sourceModel = getDiffusersSource(settings, model);+ const qwen3EncoderModel =+ settings.qwen3EncoderModel && isNonAnimaQwen3Encoder(settings.qwen3EncoderModel)+ ? settings.qwen3EncoderModel+ : null;+ const vaeModel = getCompatibleVae(settings, ['flux']);++ if (!sourceModel && (!vaeModel || !qwen3EncoderModel)) {+ throw new Error('Z-Image models require a VAE and Qwen3 Encoder, or a Diffusers component source.');+ }++ const graph: BackendGraphContract = { edges: [], id: createId('z_image_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const useCfg = settings.cfgScale > 1;+ const modelLoader = addNode(graph, {+ id: 'model_loader',+ model,+ qwen3_encoder_model: qwen3EncoderModel ?? undefined,+ qwen3_source_model: sourceModel,+ type: 'z_image_model_loader',+ vae_model: vaeModel ?? undefined,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'z_image_lora_collection_loader', modelLoader, [+ 'transformer',+ 'qwen3_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'z_image_text_encoder' });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'z_image_text_encoder' }) : null;+ const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;+ const denoise = addNode(graph, {+ denoising_end: 1,+ denoising_start: 0,+ guidance_scale: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ scheduler,+ steps: settings.steps,+ type: 'z_image_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'z_image_l2i', outputIsIntermediate);++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');+ addEdge(graph, modelLoader, 'vae', denoise, 'vae');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');++ if (negCond && negCondCollect) {+ addEdge(graph, loraSource, 'qwen3_encoder', negCond, 'qwen3_encoder');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ }++ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'z_image_txt2img', projectSettings, {+ qwen3_encoder: qwen3EncoderModel ?? undefined,+ qwen3_source: sourceModel,+ scheduler,+ vae: vaeModel ?? undefined,+ });++ return graph;+};++const buildAnimaGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ const vaeModel = requireComponent(settings.vae && isAnimaVae(settings.vae) ? settings.vae : null, 'Anima VAE');+ const qwen3EncoderModel = requireComponent(+ settings.qwen3EncoderModel && isAnimaQwen3Encoder(settings.qwen3EncoderModel) ? settings.qwen3EncoderModel : null,+ 'Qwen3 Encoder'+ );+ const graph: BackendGraphContract = { edges: [], id: createId('anima_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const useCfg = settings.cfgScale > 1;+ const modelLoader = addNode(graph, {+ id: 'model_loader',+ model,+ qwen3_encoder_model: qwen3EncoderModel,+ type: 'anima_model_loader',+ vae_model: vaeModel,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'anima_lora_collection_loader', modelLoader, [+ 'transformer',+ 'qwen3_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'anima_text_encoder' });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'anima_text_encoder' }) : null;+ const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;+ const denoise = addNode(graph, {+ denoising_end: 1,+ denoising_start: 0,+ guidance_scale: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ scheduler,+ steps: settings.steps,+ type: 'anima_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'anima_l2i', outputIsIntermediate);++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');++ if (negCond && negCondCollect) {+ addEdge(graph, loraSource, 'qwen3_encoder', negCond, 'qwen3_encoder');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ }++ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'anima_txt2img', projectSettings, {+ qwen3_encoder: qwen3EncoderModel,+ scheduler,+ vae: vaeModel,+ });++ return graph;+};++const buildExternalGraph = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): BackendGraphContract => {+ if (model.type !== 'external_image_generator') {+ throw new Error('Selected model is not an external image generator.');+ }++ if (model.capabilities?.modes && !model.capabilities.modes.includes('txt2img')) {+ throw new Error(`${model.name} does not support text-to-image generation.`);+ }++ const providerId = typeof model.provider_id === 'string' ? model.provider_id : '';+ const nodeType = getExternalProviderNodeType(providerId);++ if (!nodeType) {+ throw new Error(`No invocation node registered for external provider '${providerId}'.`);+ }++ const graph: BackendGraphContract = { edges: [], id: createId('external_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const output = addNode(graph, {+ height: settings.height,+ id: 'canvas_output',+ image_size: null,+ is_intermediate: outputIsIntermediate,+ mode: 'txt2img',+ model,+ num_images: 1,+ type: nodeType,+ use_cache: false,+ width: settings.width,+ });++ addEdge(graph, positivePrompt, 'value', output, 'prompt');+ if (model.capabilities?.supports_negative_prompt === true) {+ addEdge(graph, negativePrompt, 'value', output, 'negative_prompt');+ }++ if (model.capabilities?.supports_seed === true) {+ addEdge(graph, seed, 'value', output, 'seed');+ }+ addMetadata(graph, output, settings, model, null, projectSettings, { scheduler: undefined });return graph;};+type GenerateGraphBuilder = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+) => BackendGraphContract;++const GRAPH_BUILDERS = {+ 'sd-1': buildSDGraph,+ 'sd-2': buildSDGraph,+ sdxl: buildSDGraph,+ 'sd-3': buildSD3Graph,+ flux: buildFluxGraph,+ flux2: buildFlux2Graph,+ cogview4: buildCogView4Graph,+ 'qwen-image': buildQwenImageGraph,+ 'z-image': buildZImageGraph,+ anima: buildAnimaGraph,+} satisfies Record<SupportedGenerateBase, GenerateGraphBuilder>;+const toGraphContract = (backendGraph: BackendGraphContract, label: string) => ({backendGraph,edges: backendGraph.edges.map((edge, index) => ({@@ -250,15 +873,32 @@ const toGraphContract = (backendGraph: BackendGraphContract, label: string) => (export const compileGenerateGraph = (settings: GenerateSettings,- model: MainModelConfig,+ model: GenerateModelConfig,destination: ResultDestination,projectSettings: Pick<ProjectSettings, 'useCpuNoise'>): CompiledGenerateGraph => {- if (!isSupportedGenerateModel(model)) {- throw new Error(`${model.base} generation is not wired into the V7 Generate widget yet.`);+ const validationReasons = getGenerationValidationReasons(model, settings);++ if (validationReasons.length > 0) {+ throw new Error(validationReasons[0]);}- const backendGraph = buildSDGraph(settings, model, destination === 'canvas', projectSettings);+ const outputIsIntermediate = destination === 'canvas';+ const backendGraph = (() => {+ if (model.type === 'external_image_generator') {+ return buildExternalGraph(settings, model, outputIsIntermediate, projectSettings);+ }++ const builder = GRAPH_BUILDERS[model.base as SupportedGenerateBase];++ if (!builder) {+ const dimensionGrid = getGenerationDimensions(model).grid;++ throw new Error(`${model.name} dimensions must be multiples of ${dimensionGrid}.`);+ }++ return builder(settings, model, outputIsIntermediate, projectSettings);+ })();return {backendGraph,diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts b/invokeai/frontend/webv2/src/workbench/generation/settings.test.tsindex 99a21b2adc..c9d86bc3eb 100644--- a/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts@@ -1,6 +1,28 @@import { describe, expect, it } from 'vitest';-import { calculateNewSize, deriveAspectRatioId, isGenerateSettings, normalizeGenerateSettings } from './settings';+import type {+ ComponentModelConfig,+ GenerateLora,+ GenerateWidgetValues,+ LoraModelConfig,+ MainModelConfig,+ VaeModelConfig,+} from './types';++import { getGenerationDimensions } from './baseGenerationPolicies';+import {+ calculateNewSize,+ clampDimension,+ cloneGenerateWidgetValues,+ deriveAspectRatioId,+ getDefaultLoraWeight,+ getModelDefaultVae,+ isLoraCompatibleWithModel,+ isGenerateSettings,+ normalizeGenerateSettings,+ syncGenerateWidgetValuesWithModels,+ syncGenerateLorasWithModels,+} from './settings';/** The persisted widget-value shape from before aspect ratio / VAE / seamless / CLIP skip landed. */const legacyStoredValues = {@@ -29,6 +51,7 @@ describe('normalizeGenerateSettings', () => {expect(normalized?.aspectRatioId).toBe('2:3');expect(normalized?.aspectRatioIsLocked).toBe(false);expect(normalized?.clipSkip).toBe(0);+ expect(normalized?.loras).toEqual([]);expect(normalized?.seamlessXAxis).toBe(false);expect(normalized?.vae).toBeNull();expect(normalized?.vaePrecision).toBe('fp32');@@ -46,14 +69,150 @@ describe('normalizeGenerateSettings', () => {const normalized = normalizeGenerateSettings({...legacyStoredValues,aspectRatioId: 'bogus',+ loras: [{ isEnabled: true, model: { key: 'k', name: 'n', type: 'main' }, weight: 1 }],vae: { key: 'k', name: 'n', type: 'main' },vaePrecision: 'fp64',});expect(normalized?.aspectRatioId).toBe('2:3');+ expect(normalized?.loras).toEqual([]);expect(normalized?.vae).toBeNull();expect(normalized?.vaePrecision).toBe('fp32');});++ it('drops malformed persisted model identifiers missing a base', () => {+ const normalized = normalizeGenerateSettings({+ ...legacyStoredValues,+ loras: [{ isEnabled: true, model: { key: 'lora', name: 'LoRA', type: 'lora' }, weight: 1 }],+ qwen3EncoderModel: { key: 'qwen3', name: 'Qwen3', type: 'qwen3_encoder' },+ vae: { key: 'vae', name: 'VAE', type: 'vae' },+ });++ expect(normalized?.loras).toEqual([]);+ expect(normalized?.qwen3EncoderModel).toBeNull();+ expect(normalized?.vae).toBeNull();+ });+});++describe('Generate widget value snapshots', () => {+ const model: MainModelConfig = { base: 'flux2', key: 'model', name: 'Old Model', type: 'main' };+ const component: ComponentModelConfig = { base: 'any', key: 'qwen3', name: 'Old Qwen3', type: 'qwen3_encoder' };+ const vae: VaeModelConfig = { base: 'flux2', key: 'vae', name: 'Old VAE', type: 'vae' };+ const lora: LoraModelConfig = { base: 'flux2', key: 'lora', name: 'Old LoRA', type: 'lora' };+ const values: GenerateWidgetValues = {+ ...(normalizeGenerateSettings(legacyStoredValues) as NonNullable<ReturnType<typeof normalizeGenerateSettings>>),+ clipEmbedModel: { base: 'any', key: 'clip', name: 'CLIP', type: 'clip_embed' },+ componentSourceModel: model,+ loras: [{ isEnabled: true, model: lora, weight: 0.5 }],+ model,+ modelKey: model.key,+ qwen3EncoderModel: component,+ vae,+ };++ it('deep-clones every nested model selection', () => {+ const clone = cloneGenerateWidgetValues(values);++ expect(clone).toEqual(values);+ expect(clone.model).not.toBe(values.model);+ expect(clone.componentSourceModel).not.toBe(values.componentSourceModel);+ expect(clone.qwen3EncoderModel).not.toBe(values.qwen3EncoderModel);+ expect(clone.vae).not.toBe(values.vae);+ expect(clone.loras[0]).not.toBe(values.loras[0]);+ expect(clone.loras[0]?.model).not.toBe(values.loras[0]?.model);+ });++ it('uses current backend model records for same-key stored selections', () => {+ const currentModel = { ...model, format: 'diffusers' as const, name: 'Current Model' };+ const currentComponent = { ...component, name: 'Current Qwen3' };+ const currentVae = { ...vae, name: 'Current VAE' };+ const currentLora = { ...lora, name: 'Current LoRA' };+ const synced = syncGenerateWidgetValuesWithModels(values, [+ currentModel,+ currentComponent,+ currentVae,+ currentLora,+ ]);++ expect(synced.model).toBe(currentModel);+ expect(synced.componentSourceModel).toBe(currentModel);+ expect(synced.qwen3EncoderModel).toBe(currentComponent);+ expect(synced.vae).toBe(currentVae);+ expect(synced.loras[0]?.model).toBe(currentLora);+ });++ it('does not resync cloned current model snapshots by reference alone', () => {+ const currentModel = { ...model, format: 'diffusers' as const, name: 'Current Model' };+ const currentComponent = { ...component, name: 'Current Qwen3' };+ const currentVae = { ...vae, name: 'Current VAE' };+ const currentLora = { ...lora, name: 'Current LoRA' };+ const currentValues = {+ ...values,+ componentSourceModel: currentModel,+ loras: [{ isEnabled: true, model: currentLora, weight: 0.5 }],+ model: currentModel,+ qwen3EncoderModel: currentComponent,+ vae: currentVae,+ };+ const clonedValues = cloneGenerateWidgetValues(currentValues);+ const synced = syncGenerateWidgetValuesWithModels(clonedValues, [+ currentModel,+ currentComponent,+ currentVae,+ currentLora,+ ]);++ expect(synced).toBe(clonedValues);+ });+});++describe('LoRA settings helpers', () => {+ it('uses current model records when reading selected LoRA defaults', () => {+ const staleModel: LoraModelConfig = {+ base: 'sdxl',+ default_settings: { weight: 0.75 },+ key: 'lora-key',+ name: 'Old LoRA Name',+ type: 'lora',+ };+ const currentModel: LoraModelConfig = {+ ...staleModel,+ default_settings: { weight: 1.25 },+ name: 'Updated LoRA Name',+ trigger_phrases: ['updated trigger'],+ };+ const selectedLora: GenerateLora = { isEnabled: true, model: staleModel, weight: 0.5 };++ const [syncedLora] = syncGenerateLorasWithModels([selectedLora], [currentModel]);++ expect(syncedLora?.model).toBe(currentModel);+ expect(syncedLora?.weight).toBe(0.5);+ expect(getDefaultLoraWeight(syncedLora!.model)).toBe(1.25);+ });++ it('allows FLUX LoRAs for FLUX.2 while preserving FLUX.2 variant checks', () => {+ const flux2Model: MainModelConfig = { base: 'flux2', key: 'flux2', name: 'FLUX.2', type: 'main' };++ expect(isLoraCompatibleWithModel({ base: 'flux' }, flux2Model)).toBe(true);+ expect(+ isLoraCompatibleWithModel({ base: 'flux2', variant: 'klein_4b' }, { ...flux2Model, variant: 'klein_9b' })+ ).toBe(false);+ });+});++describe('model defaults', () => {+ it('uses shared VAE compatibility for cross-base default VAEs', () => {+ const zImageModel: MainModelConfig = {+ base: 'z-image',+ default_settings: { vae: 'flux-vae' },+ key: 'z-image',+ name: 'Z-Image',+ type: 'main',+ };+ const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };++ expect(getModelDefaultVae(zImageModel, [fluxVae])).toBe(fluxVae);+ });});describe('dimension helpers', () => {@@ -75,4 +234,13 @@ describe('dimension helpers', () => {expect(wide.height % 8).toBe(0);expect(wide.width / wide.height).toBeCloseTo(16 / 9, 1);});++ it('uses larger dimension grids for model families that require them', () => {+ expect(getGenerationDimensions({ base: 'sdxl', type: 'main' }).grid).toBe(8);+ expect(getGenerationDimensions({ base: 'anima', type: 'main' }).grid).toBe(8);+ expect(getGenerationDimensions({ base: 'flux2', type: 'main' }).grid).toBe(16);+ expect(getGenerationDimensions({ base: 'qwen-image', type: 'main' }).grid).toBe(16);+ expect(getGenerationDimensions({ base: 'cogview4', type: 'main' }).grid).toBe(32);+ expect(clampDimension(888, getGenerationDimensions({ base: 'flux2', type: 'main' }).grid)).toBe(896);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.ts b/invokeai/frontend/webv2/src/workbench/generation/settings.tsindex 8b2138c0ab..2d18015690 100644--- a/invokeai/frontend/webv2/src/workbench/generation/settings.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/settings.ts@@ -1,51 +1,17 @@import type {AspectRatioId,+ ComponentModelConfig,+ GenerateLora,+ GenerateModelConfig,GenerateSettings,GenerateWidgetValues,+ LoraModelConfig,MainModelConfig,- SupportedGenerateBase,VaeModelConfig,VaePrecision,} from './types';-/** Schedulers accepted by the backend `denoise_latents` invocation. */-export const SCHEDULER_OPTIONS: { value: string; label: string }[] = [- { label: 'DDIM', value: 'ddim' },- { label: 'DDPM', value: 'ddpm' },- { label: 'DEIS', value: 'deis' },- { label: 'DEIS Karras', value: 'deis_k' },- { label: 'DPM++ 2S', value: 'dpmpp_2s' },- { label: 'DPM++ 2S Karras', value: 'dpmpp_2s_k' },- { label: 'DPM++ 2M', value: 'dpmpp_2m' },- { label: 'DPM++ 2M Karras', value: 'dpmpp_2m_k' },- { label: 'DPM++ 2M SDE', value: 'dpmpp_2m_sde' },- { label: 'DPM++ 2M SDE Karras', value: 'dpmpp_2m_sde_k' },- { label: 'DPM++ 3M', value: 'dpmpp_3m' },- { label: 'DPM++ 3M Karras', value: 'dpmpp_3m_k' },- { label: 'DPM++ SDE', value: 'dpmpp_sde' },- { label: 'DPM++ SDE Karras', value: 'dpmpp_sde_k' },- { label: 'ER-SDE', value: 'er_sde' },- { label: 'Euler', value: 'euler' },- { label: 'Euler Karras', value: 'euler_k' },- { label: 'Euler Ancestral', value: 'euler_a' },- { label: 'Heun', value: 'heun' },- { label: 'Heun Karras', value: 'heun_k' },- { label: 'KDPM 2', value: 'kdpm_2' },- { label: 'KDPM 2 Karras', value: 'kdpm_2_k' },- { label: 'KDPM 2 Ancestral', value: 'kdpm_2_a' },- { label: 'KDPM 2 Ancestral Karras', value: 'kdpm_2_a_k' },- { label: 'LCM', value: 'lcm' },- { label: 'LMS', value: 'lms' },- { label: 'LMS Karras', value: 'lms_k' },- { label: 'PNDM', value: 'pndm' },- { label: 'TCD', value: 'tcd' },- { label: 'UniPC', value: 'unipc' },- { label: 'UniPC Karras', value: 'unipc_k' },-];--const KNOWN_SCHEDULERS = new Set(SCHEDULER_OPTIONS.map((option) => option.value));--export const isKnownScheduler = (value: string): boolean => KNOWN_SCHEDULERS.has(value);+import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';/** Preset ratios, with the preset to switch to when dimensions are swapped. */export const ASPECT_RATIO_MAP: Record<Exclude<AspectRatioId, 'Free'>, { ratio: number; inverseId: AspectRatioId }> = {@@ -82,30 +48,33 @@ export const ASPECT_RATIO_OPTIONS: AspectRatioId[] = [export const isAspectRatioId = (value: unknown): value is AspectRatioId =>value === 'Free' || (typeof value === 'string' && value in ASPECT_RATIO_MAP);-/** SD-family models generate at multiples of 8 pixels. */export const DIMENSION_GRID = 8;export const MIN_DIMENSION = 64;export const MAX_DIMENSION = 4096;export const SEED_MAX = 4_294_967_295;-/** Max skippable CLIP layers per base (mirrors the legacy CLIP_SKIP map). */-export const CLIP_SKIP_MAX: Record<SupportedGenerateBase, number> = {- 'sd-1': 12,- 'sd-2': 24,- sdxl: 24,+export const DEFAULT_LORA_WEIGHT_CONFIG = {+ coarseStep: 0.05,+ initial: 0.75,+ numberInputMax: 10,+ numberInputMin: -10,+ sliderMax: 2,+ sliderMin: -1,};-export const getOptimalDimension = (base: string): number => (base === 'sd-1' || base === 'sd-2' ? 512 : 1024);--export const clampDimension = (value: number): number =>- Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, Math.round(value / DIMENSION_GRID) * DIMENSION_GRID));+export const clampDimension = (value: number, grid = DIMENSION_GRID): number =>+ Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, Math.round(value / grid) * grid));/** Fit a width/height of the given ratio into approximately the given pixel area, snapped to the grid. */-export const calculateNewSize = (ratio: number, area: number): { width: number; height: number } => {+export const calculateNewSize = (+ ratio: number,+ area: number,+ grid = DIMENSION_GRID+): { width: number; height: number } => {const exactWidth = Math.sqrt(area * ratio);- return { height: clampDimension(exactWidth / ratio), width: clampDimension(exactWidth) };+ return { height: clampDimension(exactWidth / ratio, grid), width: clampDimension(exactWidth, grid) };};/** Best-matching preset for existing dimensions, falling back to Free. */@@ -131,13 +100,212 @@ const hasFiniteNumber = (record: Record<string, unknown>, key: string): booleantypeof record[key] === 'number' && Number.isFinite(record[key]);export const isMainModelConfig = (value: unknown): value is MainModelConfig =>- isRecord(value) && typeof value.key === 'string' && typeof value.name === 'string' && value.type === 'main';+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ value.type === 'main';++export const isExternalImageGeneratorModelConfig = (value: unknown): value is GenerateModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ value.base === 'external' &&+ value.type === 'external_image_generator';++export const isGenerateModelConfig = (value: unknown): value is GenerateModelConfig =>+ isMainModelConfig(value) || isExternalImageGeneratorModelConfig(value);++export const isModelIdentifierConfig = (value: unknown): value is ComponentModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ typeof value.type === 'string';export const isVaeModelConfig = (value: unknown): value is VaeModelConfig =>- isRecord(value) && typeof value.key === 'string' && typeof value.name === 'string' && value.type === 'vae';+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ value.type === 'vae';++export const isLoraModelConfig = (value: unknown): value is LoraModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ value.type === 'lora';++const getModelIdentifierOrNull = (value: unknown): ComponentModelConfig | null =>+ isModelIdentifierConfig(value) ? value : null;++const getMainModelOrNull = (value: unknown): MainModelConfig | null => (isMainModelConfig(value) ? value : null);const isVaePrecision = (value: unknown): value is VaePrecision => value === 'fp16' || value === 'fp32';+const isGenerateLora = (value: unknown): value is GenerateLora =>+ isRecord(value) &&+ isLoraModelConfig(value.model) &&+ hasFiniteNumber(value, 'weight') &&+ typeof value.isEnabled === 'boolean';++export const getDefaultLoraWeight = (model: LoraModelConfig): number => {+ const weight = model.default_settings?.weight;++ return Number.isFinite(weight) && weight !== null && weight !== undefined+ ? weight+ : DEFAULT_LORA_WEIGHT_CONFIG.initial;+};++const areModelSnapshotsEqual = (a: unknown, b: unknown): boolean => {+ if (a === b) {+ return true;+ }++ try {+ return JSON.stringify(a) === JSON.stringify(b);+ } catch {+ return false;+ }+};++export const syncGenerateLorasWithModels = (loras: GenerateLora[], models: readonly unknown[]): GenerateLora[] => {+ const modelsByKey = new Map<string, LoraModelConfig>();++ for (const model of models) {+ if (isLoraModelConfig(model)) {+ modelsByKey.set(model.key, model);+ }+ }++ let didSync = false;+ const syncedLoras = loras.map((lora) => {+ const currentModel = modelsByKey.get(lora.model.key);++ if (!currentModel || areModelSnapshotsEqual(currentModel, lora.model)) {+ return lora;+ }++ didSync = true;+ return { ...lora, model: currentModel };+ });++ return didSync ? syncedLoras : loras;+};++const syncModelIdentifierWithModels = <T extends ComponentModelConfig | null>(+ value: T,+ modelsByKey: Map<string, unknown>+): T => {+ if (!value) {+ return value;+ }++ const currentModel = modelsByKey.get(value.key);++ return isModelIdentifierConfig(currentModel) && !areModelSnapshotsEqual(currentModel, value)+ ? (currentModel as T)+ : value;+};++export const getModelDefaultVae = (+ model: GenerateModelConfig,+ vaeModels: readonly VaeModelConfig[]+): VaeModelConfig | null => {+ const defaultVaeKey = (model.default_settings as { vae?: string | null } | null | undefined)?.vae;++ return defaultVaeKey+ ? (vaeModels.find((vae) => vae.key === defaultVaeKey && isVaeCompatibleWithGenerateModel(model, vae)) ?? null)+ : null;+};++export const cloneGenerateWidgetValues = (+ values: GenerateWidgetValues+): GenerateWidgetValues & Record<string, unknown> => ({+ ...values,+ clipEmbedModel: values.clipEmbedModel ? { ...values.clipEmbedModel } : null,+ clipGEmbedModel: values.clipGEmbedModel ? { ...values.clipGEmbedModel } : null,+ clipLEmbedModel: values.clipLEmbedModel ? { ...values.clipLEmbedModel } : null,+ componentSourceModel: values.componentSourceModel ? { ...values.componentSourceModel } : null,+ loras: values.loras.map((lora) => ({ ...lora, model: { ...lora.model } })),+ model: { ...values.model },+ qwen3EncoderModel: values.qwen3EncoderModel ? { ...values.qwen3EncoderModel } : null,+ qwenVLEncoderModel: values.qwenVLEncoderModel ? { ...values.qwenVLEncoderModel } : null,+ t5EncoderModel: values.t5EncoderModel ? { ...values.t5EncoderModel } : null,+ vae: values.vae ? { ...values.vae } : null,+});++export const syncGenerateWidgetValuesWithModels = (+ values: GenerateWidgetValues,+ models: readonly unknown[]+): GenerateWidgetValues => {+ const modelsByKey = new Map<string, unknown>();++ for (const model of models) {+ if (isModelIdentifierConfig(model)) {+ modelsByKey.set(model.key, model);+ }+ }++ const currentModel = modelsByKey.get(values.model.key);+ const model =+ isGenerateModelConfig(currentModel) && !areModelSnapshotsEqual(currentModel, values.model)+ ? currentModel+ : values.model;+ const vae = syncModelIdentifierWithModels(values.vae, modelsByKey);+ const componentSourceModel = syncModelIdentifierWithModels(values.componentSourceModel, modelsByKey);+ const nextValues: GenerateWidgetValues = {+ ...values,+ clipEmbedModel: syncModelIdentifierWithModels(values.clipEmbedModel, modelsByKey),+ clipGEmbedModel: syncModelIdentifierWithModels(values.clipGEmbedModel, modelsByKey),+ clipLEmbedModel: syncModelIdentifierWithModels(values.clipLEmbedModel, modelsByKey),+ componentSourceModel: isMainModelConfig(componentSourceModel) ? componentSourceModel : values.componentSourceModel,+ loras: syncGenerateLorasWithModels(values.loras, models),+ model,+ modelKey: model.key,+ qwen3EncoderModel: syncModelIdentifierWithModels(values.qwen3EncoderModel, modelsByKey),+ qwenVLEncoderModel: syncModelIdentifierWithModels(values.qwenVLEncoderModel, modelsByKey),+ t5EncoderModel: syncModelIdentifierWithModels(values.t5EncoderModel, modelsByKey),+ vae: isVaeModelConfig(vae) ? vae : values.vae,+ };++ return nextValues.model === values.model &&+ nextValues.loras === values.loras &&+ nextValues.vae === values.vae &&+ nextValues.t5EncoderModel === values.t5EncoderModel &&+ nextValues.clipEmbedModel === values.clipEmbedModel &&+ nextValues.clipLEmbedModel === values.clipLEmbedModel &&+ nextValues.clipGEmbedModel === values.clipGEmbedModel &&+ nextValues.qwen3EncoderModel === values.qwen3EncoderModel &&+ nextValues.qwenVLEncoderModel === values.qwenVLEncoderModel &&+ nextValues.componentSourceModel === values.componentSourceModel &&+ nextValues.modelKey === values.modelKey+ ? values+ : nextValues;+};++export const isLoraCompatibleWithModel = (+ loraModel: Pick<LoraModelConfig, 'base' | 'variant'>,+ mainModel: Pick<GenerateModelConfig, 'base' | 'variant'>+): boolean => {+ if (mainModel.base === 'flux2') {+ if (loraModel.base !== 'flux2' && loraModel.base !== 'flux') {+ return false;+ }++ return (+ loraModel.base === 'flux' || !mainModel.variant || !loraModel.variant || loraModel.variant === mainModel.variant+ );+ }++ if (loraModel.base !== mainModel.base) {+ return false;+ }++ return true;+};+/*** Validate stored widget values and fill in fields that older persisted* projects predate. The core fields must be present and well-typed; newer@@ -180,6 +348,7 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | ncfgScale: values.cfgScale as number,clipSkip: hasFiniteNumber(values, 'clipSkip') ? (values.clipSkip as number) : 0,height,+ loras: Array.isArray(values.loras) ? values.loras.filter(isGenerateLora) : [],modelKey: values.modelKey as string,negativePrompt: values.negativePrompt as string,positivePrompt: values.positivePrompt as string,@@ -191,6 +360,13 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | nsteps: values.steps as number,vae: isVaeModelConfig(values.vae) ? values.vae : null,vaePrecision: isVaePrecision(values.vaePrecision) ? values.vaePrecision : 'fp32',+ t5EncoderModel: getModelIdentifierOrNull(values.t5EncoderModel),+ clipEmbedModel: getModelIdentifierOrNull(values.clipEmbedModel),+ clipLEmbedModel: getModelIdentifierOrNull(values.clipLEmbedModel),+ clipGEmbedModel: getModelIdentifierOrNull(values.clipGEmbedModel),+ qwen3EncoderModel: getModelIdentifierOrNull(values.qwen3EncoderModel),+ qwenVLEncoderModel: getModelIdentifierOrNull(values.qwenVLEncoderModel),+ componentSourceModel: getMainModelOrNull(values.componentSourceModel),width,};};@@ -198,7 +374,7 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | nexport const normalizeGenerateWidgetValues = (values: unknown): GenerateWidgetValues | null => {const settings = normalizeGenerateSettings(values);- if (!settings || !isRecord(values) || !isMainModelConfig(values.model)) {+ if (!settings || !isRecord(values) || !isGenerateModelConfig(values.model)) {return null;}@@ -218,12 +394,21 @@ export const isGenerateSettings = (values: unknown): values is GenerateSettingstypeof values.aspectRatioIsLocked === 'boolean' &&hasFiniteNumber(values, 'aspectRatioValue') &&hasFiniteNumber(values, 'clipSkip') &&+ Array.isArray(values.loras) &&+ values.loras.every(isGenerateLora) &&typeof values.seamlessXAxis === 'boolean' &&typeof values.seamlessYAxis === 'boolean' &&isVaePrecision(values.vaePrecision) &&- (values.vae === null || isVaeModelConfig(values.vae))+ (values.vae === null || isVaeModelConfig(values.vae)) &&+ (values.t5EncoderModel === null || isModelIdentifierConfig(values.t5EncoderModel)) &&+ (values.clipEmbedModel === null || isModelIdentifierConfig(values.clipEmbedModel)) &&+ (values.clipLEmbedModel === null || isModelIdentifierConfig(values.clipLEmbedModel)) &&+ (values.clipGEmbedModel === null || isModelIdentifierConfig(values.clipGEmbedModel)) &&+ (values.qwen3EncoderModel === null || isModelIdentifierConfig(values.qwen3EncoderModel)) &&+ (values.qwenVLEncoderModel === null || isModelIdentifierConfig(values.qwenVLEncoderModel)) &&+ (values.componentSourceModel === null || isMainModelConfig(values.componentSourceModel)));};export const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues =>- isGenerateSettings(values) && isMainModelConfig((values as unknown as Record<string, unknown>).model);+ isGenerateSettings(values) && isGenerateModelConfig((values as unknown as Record<string, unknown>).model);diff --git a/invokeai/frontend/webv2/src/workbench/generation/types.ts b/invokeai/frontend/webv2/src/workbench/generation/types.tsindex 329189e241..36dc7201dc 100644--- a/invokeai/frontend/webv2/src/workbench/generation/types.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/types.ts@@ -1,34 +1,72 @@import type { BackendGraphContract, GeneratedImageContract, GraphContract, ResultDestination } from '@workbench/types';-export type SupportedGenerateBase = 'sd-1' | 'sd-2' | 'sdxl';--export type MainModelConfig = {+export type ModelIdentifierConfig = {key: string;name: string;base: string;- type: 'main';+ type: string;format?: string;+ variant?: string | null;+ hash?: string;+ submodel_type?: string;+ [key: string]: unknown;+};++export type MainModelConfig = ModelIdentifierConfig & {+ type: 'main';default_settings?: {scheduler?: string | null;steps?: number | null;cfg_scale?: number | null;+ guidance?: number | null;cfg_rescale_multiplier?: number | null;width?: number | null;height?: number | null;vae?: string | null;vae_precision?: string | null;} | null;- [key: string]: unknown;};-export type VaeModelConfig = {- key: string;- name: string;- base: string;+export type ExternalImageGeneratorModelConfig = ModelIdentifierConfig & {+ base: 'external';+ type: 'external_image_generator';+ format: 'external_api';+ provider_id?: string;+ capabilities?: {+ modes?: string[];+ supports_seed?: boolean;+ supports_negative_prompt?: boolean;+ } | null;+ default_settings?: {+ width?: number | null;+ height?: number | null;+ num_images?: number | null;+ } | null;+};++export type GenerateModelConfig = MainModelConfig | ExternalImageGeneratorModelConfig;++export type ComponentModelConfig = ModelIdentifierConfig;++export type VaeModelConfig = ModelIdentifierConfig & {type: 'vae';- [key: string]: unknown;};+export type LoraModelConfig = ModelIdentifierConfig & {+ type: 'lora';+ trigger_phrases?: string[] | null;+ default_settings?: {+ weight?: number | null;+ } | null;+ variant?: string | null;+};++export interface GenerateLora {+ isEnabled: boolean;+ model: LoraModelConfig;+ weight: number;+}+export type VaePrecision = 'fp16' | 'fp32';export type AspectRatioId =@@ -72,10 +110,19 @@ export interface GenerateSettings {/** Optional VAE override; null uses the VAE bundled with the main model. */vae: VaeModelConfig | null;vaePrecision: VaePrecision;+ loras: GenerateLora[];+ t5EncoderModel: ComponentModelConfig | null;+ clipEmbedModel: ComponentModelConfig | null;+ clipLEmbedModel: ComponentModelConfig | null;+ clipGEmbedModel: ComponentModelConfig | null;+ qwen3EncoderModel: ComponentModelConfig | null;+ qwenVLEncoderModel: ComponentModelConfig | null;+ /** Optional Diffusers main model used as a component source for split/quantized model families. */+ componentSourceModel: MainModelConfig | null;}export interface GenerateWidgetValues extends GenerateSettings {- model: MainModelConfig;+ model: GenerateModelConfig;}export interface CompiledGenerateGraph {