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(architectures): serve model policy from the backend, and read it in webv2
Alexander Eichhornc668917de454
diff --git a/invokeai/app/invocations/anima/anima_model_loader.py b/invokeai/app/invocations/anima/anima_model_loader.pyindex 0841f58bd9..c84a6d0cf6 100644--- a/invokeai/app/invocations/anima/anima_model_loader.py+++ b/invokeai/app/invocations/anima/anima_model_loader.py@@ -57,6 +57,15 @@ class AnimaModelLoaderInvocation(BaseInvocation):description="Standalone VAE model. Anima uses a Wan 2.1 / QwenImage VAE (16-channel). ""A FLUX VAE can also be used as a compatible fallback.",input=Input.Direct,+ # `anima_l2i` accepts AutoencoderKLWan or FluxAutoEncoder. The Wan-family file is the same+ # checkpoint whichever of the three bases it was installed under; declaring nothing here+ # offered every VAE ever installed, including ones that cannot decode an Anima latent.+ ui_model_base=[+ BaseModelType.Anima,+ BaseModelType.QwenImage,+ BaseModelType.Wan,+ BaseModelType.Flux,+ ],ui_model_type=ModelType.VAE,title="VAE",)diff --git a/invokeai/app/invocations/flux2/flux2_klein_model_loader.py b/invokeai/app/invocations/flux2/flux2_klein_model_loader.pyindex 3cb8363146..dffd55430a 100644--- a/invokeai/app/invocations/flux2/flux2_klein_model_loader.py+++ b/invokeai/app/invocations/flux2/flux2_klein_model_loader.py@@ -93,10 +93,13 @@ class Flux2KleinModelLoaderInvocation(BaseInvocation):vae_model: Optional[ModelIdentifierField] = InputField(default=None,- description="Standalone VAE model. Flux2 Klein uses the same VAE as FLUX (16-channel). "+ description="Standalone VAE model (AutoencoderKLFlux2, 32-channel). ""If not provided, VAE will be loaded from the Qwen3 Source model.",input=Input.Direct,- ui_model_base=[BaseModelType.Flux, BaseModelType.Flux2],+ # A FLUX VAE was offered here and does not work: it is the legacy `AutoEncoder` class with+ # a 16-channel latent space, and decoding a FLUX.2 latent with it raises+ # `AutoEncoder.decode() got an unexpected keyword argument 'return_dict'`.+ ui_model_base=BaseModelType.Flux2,ui_model_type=ModelType.VAE,title="VAE",)diff --git a/invokeai/app/invocations/qwen_image/qwen_image_model_loader.py b/invokeai/app/invocations/qwen_image/qwen_image_model_loader.pyindex b3e86d1bf4..86a18747c9 100644--- a/invokeai/app/invocations/qwen_image/qwen_image_model_loader.py+++ b/invokeai/app/invocations/qwen_image/qwen_image_model_loader.py@@ -65,7 +65,9 @@ class QwenImageModelLoaderInvocation(BaseInvocation):description="Standalone Qwen Image VAE model. ""If not provided, VAE will be loaded from the Component Source (or from the main model if it is Diffusers).",input=Input.Direct,- ui_model_base=BaseModelType.QwenImage,+ # The same 16-channel checkpoint is registered under either base depending on which+ # family it was installed for; krea2_model_loader already offers both.+ ui_model_base=[BaseModelType.QwenImage, BaseModelType.Anima],ui_model_type=ModelType.VAE,title="VAE",)diff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.pyindex 0953d44fb3..0a32883172 100644--- a/invokeai/backend/architectures/defs/anima.py+++ b/invokeai/backend/architectures/defs/anima.py@@ -5,6 +5,7 @@ from invokeai.backend.architectures.facets.default_settings import DefaultSettinfrom invokeai.backend.architectures.facets.features import FeaturesFacet, NegativePromptfrom invokeai.backend.architectures.facets.latent_space import WAN21_16, LatentSpaceFacetfrom invokeai.backend.architectures.facets.modality import ModalityFacet+from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.taxonomy import BaseModelType@@ -26,4 +27,17 @@ register(scheduler_set="anima",scheduler_applies_to_graph=True,),+ VaeFacet(+ frozenset(+ {+ # `anima_l2i` accepts AutoencoderKLWan or FluxAutoEncoder, each with its own+ # decode path. The Wan-family file is registered under whichever base it was+ # installed for -- all three point at the same 194-tensor checkpoint.+ VaeCompatibility(BaseModelType.Anima),+ VaeCompatibility(BaseModelType.QwenImage),+ VaeCompatibility(BaseModelType.Wan, latent_channels=16),+ VaeCompatibility(BaseModelType.Flux),+ }+ )+ ),)diff --git a/invokeai/backend/architectures/defs/krea_2.py b/invokeai/backend/architectures/defs/krea_2.pyindex 0b1987da6e..9417a282e3 100644--- a/invokeai/backend/architectures/defs/krea_2.py+++ b/invokeai/backend/architectures/defs/krea_2.py@@ -5,6 +5,7 @@ from invokeai.backend.architectures.facets.default_settings import DefaultSettinfrom invokeai.backend.architectures.facets.features import FeaturesFacet, NegativePromptfrom invokeai.backend.architectures.facets.latent_space import WAN21_16, LatentSpaceFacetfrom invokeai.backend.architectures.facets.modality import ModalityFacet+from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.taxonomy import BaseModelType, Krea2VariantType@@ -34,4 +35,14 @@ register(scheduler_set="flow",supports_regional_guidance=True,),+ VaeFacet(+ frozenset(+ {+ # Krea-2 decodes with the Qwen-Image VAE, which is why its graph reuses+ # `qwen_image_l2i`. The same file also appears registered as `anima`.+ VaeCompatibility(BaseModelType.QwenImage),+ VaeCompatibility(BaseModelType.Anima),+ }+ )+ ),)diff --git a/invokeai/backend/architectures/defs/qwen_image.py b/invokeai/backend/architectures/defs/qwen_image.pyindex c8ff84447a..f4def104bd 100644--- a/invokeai/backend/architectures/defs/qwen_image.py+++ b/invokeai/backend/architectures/defs/qwen_image.py@@ -5,6 +5,7 @@ from invokeai.backend.architectures.facets.default_settings import DefaultSettinfrom invokeai.backend.architectures.facets.features import FeaturesFacet, NegativePromptfrom invokeai.backend.architectures.facets.latent_space import WAN21_16, LatentSpaceFacetfrom invokeai.backend.architectures.facets.modality import ModalityFacet+from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.taxonomy import BaseModelType@@ -27,4 +28,12 @@ register(max_reference_images=5,reference_images_require_variant="edit",),+ VaeFacet(+ frozenset(+ {+ VaeCompatibility(BaseModelType.QwenImage),+ VaeCompatibility(BaseModelType.Anima),+ }+ )+ ),)diff --git a/invokeai/backend/architectures/defs/wan.py b/invokeai/backend/architectures/defs/wan.pyindex 86ef2864a6..fb9825510f 100644--- a/invokeai/backend/architectures/defs/wan.py+++ b/invokeai/backend/architectures/defs/wan.py@@ -5,6 +5,7 @@ from invokeai.backend.architectures.facets.default_settings import DefaultSettinfrom invokeai.backend.architectures.facets.features import FeaturesFacet, NegativePromptfrom invokeai.backend.architectures.facets.latent_space import WAN21_16, WAN22_48, LatentSpaceFacetfrom invokeai.backend.architectures.facets.modality import ModalityFacet+from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.taxonomy import BaseModelType, WanVariantType@@ -38,4 +39,15 @@ register(guidance_label="Guidance",scheduler_set="flow",),+ VaeFacet(+ frozenset(+ {+ # A14B uses the 16-channel Wan 2.1 VAE; TI2V-5B needs the 48-channel+ # Wan2.2-VAE. Both are registered under `wan`, so the channel count is the+ # only thing that tells them apart.+ VaeCompatibility(BaseModelType.Wan, latent_channels=16),+ VaeCompatibility(BaseModelType.Wan, latent_channels=48),+ }+ )+ ),)diff --git a/invokeai/backend/architectures/defs/z_image.py b/invokeai/backend/architectures/defs/z_image.pyindex 2029720336..877f7b9ee1 100644--- a/invokeai/backend/architectures/defs/z_image.py+++ b/invokeai/backend/architectures/defs/z_image.py@@ -5,6 +5,7 @@ from invokeai.backend.architectures.facets.default_settings import DefaultSettinfrom invokeai.backend.architectures.facets.features import FeaturesFacet, NegativePromptfrom invokeai.backend.architectures.facets.latent_space import FLUX_16, LatentSpaceFacetfrom invokeai.backend.architectures.facets.modality import ModalityFacet+from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacetfrom invokeai.backend.architectures.registry import registerfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ZImageVariantType@@ -34,4 +35,12 @@ register(scheduler_applies_to_graph=True,control_kinds=frozenset({"z_image_control"}),),+ VaeFacet(+ frozenset(+ {+ # Z-Image decodes with a FLUX-compatible VAE; `z_image_model_loader` says so.+ VaeCompatibility(BaseModelType.Flux),+ }+ )+ ),)diff --git a/invokeai/backend/architectures/facets/vae.py b/invokeai/backend/architectures/facets/vae.pynew file mode 100644index 0000000000..0c6219cb7e--- /dev/null+++ b/invokeai/backend/architectures/facets/vae.py@@ -0,0 +1,78 @@+"""Which VAEs an architecture can decode with.++Not derivable from the latent geometry. Eight architectures share a 16-channel space at 8x+compression, but their VAEs are not interchangeable: SD 3.5 and CogView 4 are 16-channel too and+belong to neither the Wan/Qwen family nor FLUX's. Compatibility is a fact about the decoder class,+so it is declared.++Nor is it derivable from the VAE's `base` alone. The same physical file is registered under+`anima` or `qwen-image` depending on which family it was installed for -- byte-identical, 194+tensors -- and a `wan` VAE may be either the 16-channel Wan 2.1 file (the same family again) or+TI2V-5B's 48-channel Wan2.2-VAE, which fits nothing else. `VAE_Checkpoint_Wan_Config` already+records `latent_channels`; this facet is what finally reads it.+"""++from dataclasses import dataclass+from typing import ClassVar++from invokeai.backend.architectures.facet import Facet+from invokeai.backend.architectures.registry import get+from invokeai.backend.model_manager.taxonomy import BaseModelType+++@dataclass(frozen=True)+class VaeCompatibility:+ """One VAE an architecture accepts, as a model record can be matched against it."""++ base: BaseModelType++ latent_channels: int | None = None+ """Required channel count, where the base alone is ambiguous.++ Only `wan` is: its VAEs carry `latent_channels` of 16 or 48 and only the 16-channel ones belong+ to the shared family. `None` means the base is unambiguous and the field is not consulted --+ which is also what happens for VAE configs that do not carry it.+ """++ def matches(self, vae_base: BaseModelType, vae_latent_channels: int | None = None) -> bool:+ if vae_base != self.base:+ return False+ if self.latent_channels is None:+ return True+ return vae_latent_channels == self.latent_channels+++@dataclass(frozen=True)+class VaeFacet(Facet):+ """The VAEs a model of this architecture can be paired with.++ Includes the architecture's own base wherever that is accepted, so the set is complete on its+ own and a consumer never has to add an implicit "or its own".+ """++ REQUIRED: ClassVar[bool] = False++ accepted: frozenset[VaeCompatibility]++ def accepts(self, vae_base: BaseModelType, vae_latent_channels: int | None = None) -> bool:+ return any(entry.matches(vae_base, vae_latent_channels) for entry in self.accepted)++ @property+ def accepted_bases(self) -> frozenset[BaseModelType]:+ """The bases alone, for the UI's first-pass filter and for comparing against a loader's+ `ui_model_base`, which cannot express a channel constraint."""+ return frozenset(entry.base for entry in self.accepted)+++def accepts_vae(base: BaseModelType, vae_base: BaseModelType, vae_latent_channels: int | None = None) -> bool:+ """Whether `base` can decode with this VAE.++ Architectures that declare no `VaeFacet` accept only their own base -- the SD family and+ anything whose loader has no VAE input at all.+ """+ facet = get(base, VaeFacet)++ if facet is None:+ return vae_base == base++ return facet.accepts(vae_base, vae_latent_channels)diff --git a/invokeai/backend/model_manager/load/model_loaders/vae.py b/invokeai/backend/model_manager/load/model_loaders/vae.pyindex 51497e725a..d58a98f9d4 100644--- a/invokeai/backend/model_manager/load/model_loaders/vae.py+++ b/invokeai/backend/model_manager/load/model_loaders/vae.py@@ -279,11 +279,16 @@ class VAELoader(GenericDiffusersLoader):def _load_qwen_image_vae(self, config: VAE_Checkpoint_QwenImage_Config) -> AnyModel:"""Load a Qwen Image VAE from a single safetensors file.- The Qwen Image VAE checkpoint is expected to be in the diffusers state-dict- layout (i.e. the same keys as `vae/diffusion_pytorch_model.safetensors` from- the Qwen-Image repo). `AutoencoderKLQwenImage` does not register a single-file- conversion in diffusers, so we instantiate the model with default config and- load the state dict directly.+ Two layouts reach this method. Files exported from the Qwen-Image repo carry the diffusers+ state-dict keys (`decoder.conv_in.weight`, ...) and are loaded directly, because+ `AutoencoderKLQwenImage` registers no single-file conversion in diffusers.++ Community redistributions carry the original layout instead (`decoder.conv1.weight`, ...),+ which needs converting. Those files are the 16-channel Wan-family VAE -- architecturally the+ same autoencoder -- so `AutoencoderKLWan.from_single_file` reads them, and the identical+ checkpoint installed under `anima` already takes that path. Loading them into+ `AutoencoderKLQwenImage` with `strict=True` failed with 194 missing keys, which made a VAE+ unusable purely because of the base it happened to be probed as."""import acceleratefrom diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLQwenImage@@ -291,6 +296,15 @@ class VAELoader(GenericDiffusersLoader):sd = load_file(config.path)+ if "decoder.conv_in.weight" not in sd:+ from diffusers.models.autoencoders import AutoencoderKLWan++ from invokeai.backend.wan.rocm_causal_conv3d import patch_wan_causal_conv3d_for_rocm++ del sd+ patch_wan_causal_conv3d_for_rocm()+ return AutoencoderKLWan.from_single_file(config.path, torch_dtype=self._torch_dtype)+if self._torch_dtype is not None:for k in list(sd.keys()):if sd[k].is_floating_point():diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex db241b746a..781e561524 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1487,6 +1487,7 @@"addPromptTrigger": "Add prompt trigger","advanced": "Advanced","aspectRatio": "Aspect ratio",+ "capabilitiesLoadFailed": "Could not load model capabilities from the backend.","cfgRescale": "CFG rescale","chooseModelToStart": "Choose a model to start","clearPromptTemplate": "Stop using this template",@@ -1664,6 +1665,7 @@"llmTaskGenerating": "Generating","llmTaskLoadingModel": "Loading model","llmTaskProgress": "LLM task progress",+ "loadingCapabilities": "Loading model capabilities…","loadingModels": "Loading backend models…","lockAspectRatio": "Lock aspect ratio","mainModel": "Main model",@@ -1701,6 +1703,7 @@"promptHistoryKeyboardHelp": "Alt+Up/Down switches between prompts while focused.","recentSeeds": "Recent seeds","resetToModelDefault": "Reset to model default",+ "retry": "Retry","savePreset": "Save as preset…","savePresetAction": "Save","savePresetTitle": "Save preset",diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 43911fea92..60970bd166 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -26,6 +26,16 @@ const TINY_PNG = Buffer.from();const FIXTURE_VIDEO = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.mp4'));const FIXTURE_VIDEO_POSTER = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.webp'));+// Served verbatim from the same file the backend pins in+// `tests/backend/architectures/test_capabilities_fixture.py`, so the journey tests exercise the+// payload the real route returns rather than a stand-in that can drift from it.+const ARCHITECTURE_CAPABILITIES = JSON.parse(+ readFileSync(+ resolve(import.meta.dirname, '../src/features/generation/core/__fixtures__/architectureCapabilities.json'),+ 'utf8'+ )+);+const MOCK_USER_ID = 'fixture-user';const clone = (value) => structuredClone(value);@@ -882,6 +892,9 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {if (method === 'GET' && path === '/api/v2/models/install') {return json(200, []);}+ if (method === 'GET' && path === '/api/v2/models/capabilities') {+ return json(200, ARCHITECTURE_CAPABILITIES);+ }if (method === 'GET' && path === '/api/v2/models/starter_models') {return json(200, STARTER_MODELS_RESPONSE);}diff --git a/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx b/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsxindex b9a5925fef..17acbabe22 100644--- a/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx+++ b/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx@@ -1,4 +1,10 @@-import { createGenerateWidgetSyncRuntime, type GenerateWidgetSyncProjectSnapshot } from '@features/generation/runtime';+import {+ createGenerateWidgetSyncRuntime,+ ensureArchitectureCapabilitiesLoaded,+ getArchitectureCapabilitiesSnapshot,+ subscribeArchitectureCapabilities,+ type GenerateWidgetSyncProjectSnapshot,+} from '@features/generation/runtime';import { ensureModelsLoaded, getModelsSnapshot, subscribeModels } from '@features/models';import { useMountEffect } from '@platform/react/useMountEffect';import { createProjectedExternalStore } from '@platform/state/projectedExternalStore';@@ -25,13 +31,21 @@ export const GenerateWidgetSyncRuntime = () => {select: (snapshot) => snapshot.models,source: { getSnapshot: getModelsSnapshot, subscribe: subscribeModels },});+ const capabilitiesLoaded = createProjectedExternalStore({+ select: (snapshot) => snapshot.status === 'loaded',+ source: { getSnapshot: getArchitectureCapabilitiesSnapshot, subscribe: subscribeArchitectureCapabilities },+ });const runtime = createGenerateWidgetSyncRuntime({+ capabilitiesLoaded,models,patchValues: store.commands.generation.patchSettings,project,queryClient,});+ // Kicked here, at app boot, so the gate's window is one round trip rather than "whenever the+ // Generate panel is first opened".+ ensureArchitectureCapabilitiesLoaded();void ensureModelsLoaded();return () => runtime.dispose();});diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.tsnew file mode 100644index 0000000000..4a9f4ce640--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts@@ -0,0 +1,141 @@+/**+ * The mapper, driven by the real response body.+ *+ * `__fixtures__/architectureCapabilities.json` is pinned against the backend by+ * `tests/backend/architectures/test_capabilities_fixture.py`, so these assertions are about the+ * payload the app actually receives rather than a hand-written stand-in.+ */++import { afterEach, describe, expect, it } from 'vitest';++import fixture from './__fixtures__/architectureCapabilities.json';+import {+ type ArchitectureCapabilitiesRow,+ getArchitectureCapabilityRow,+ getArchitectureFeatures,+ getArchitectureGenerationConfig,+ hasArchitectureCapabilities,+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+ toBaseGenerationConfig,+} from './architectureCapabilities';+import { SUPPORTED_GENERATE_BASES } from './supportedBases';++const rows = fixture as ArchitectureCapabilitiesRow[];+const row = (base: string, variant: string | null = null): ArchitectureCapabilitiesRow => {+ const found = rows.find((r) => r.base === base && r.variant === variant);+ if (!found) {+ throw new Error(`fixture has no row for ${base}/${variant}`);+ }+ return found;+};++afterEach(resetArchitectureCapabilities);++describe('the wire contract', () => {+ it('serves a base row for every architecture this build can generate with', () => {+ const served = new Set(rows.filter((r) => r.variant === null).map((r) => r.base));+ expect(SUPPORTED_GENERATE_BASES.filter((base) => !served.has(base))).toEqual([]);+ });+});++describe('toBaseGenerationConfig', () => {+ it('reads the guidance field for a guidance-labelled architecture', () => {+ // dev is FLUX's base row -- variant rows exist only where they differ. It records cfg_scale+ // 1.0 ("CFG off") alongside guidance 3.5, and buildFluxGraph wires this value into the node's+ // `guidance`. Preferring cfg_scale would generate at 1.0.+ expect(toBaseGenerationConfig(row('flux')).defaults.cfgScale).toBe(3.5);+ expect(toBaseGenerationConfig(row('flux', 'dev_fill')).defaults.cfgScale).toBe(30);+ });++ it('falls back to cfg_scale when a guidance-labelled architecture declares no guidance', () => {+ const schnell = toBaseGenerationConfig(row('flux', 'schnell'));+ expect(schnell.guidanceLabel).toBe('Guidance');+ expect(schnell.defaults.cfgScale).toBe(1);+ expect(schnell.defaults.steps).toBe(4);+ });++ it('reads cfg_scale for a CFG-labelled architecture', () => {+ const sdxl = toBaseGenerationConfig(row('sdxl'));+ expect(sdxl.guidanceLabel).toBe('CFG');+ expect(sdxl.defaults).toEqual({ steps: 30, cfgScale: 7, scheduler: 'euler_a' });+ });++ it('derives the optimal side from the declared area, not from width alone', () => {+ // Square today for every generatable architecture, so this is the identity -- but MiniMax H3+ // is 1344x768, so the area form is what keeps a non-square canvas from being squashed.+ expect(toBaseGenerationConfig(row('sd-1')).dimensions.optimalSide).toBe(512);+ expect(toBaseGenerationConfig(row('sd-2')).dimensions.optimalSide).toBe(768);+ expect(toBaseGenerationConfig(row('minimax-h3')).dimensions.optimalSide).toBe(1016); // sqrt(1344*768)+ });++ it('carries the feature flags across verbatim', () => {+ const sd1 = toBaseGenerationConfig(row('sd-1'));+ expect(sd1.dimensions.grid).toBe(8);+ expect(sd1.negativePrompt).toEqual({ visible: true, usage: 'always' });+ expect(sd1.ui).toEqual({+ sdVaeOverride: true,+ colorCompensation: false,+ vaePrecision: true,+ seamless: true,+ cfgRescale: true,+ clipSkipMax: 12,+ });+ });++ it('turns an absent clip-skip ceiling into undefined rather than null', () => {+ // Consumers branch on presence as well as falsiness.+ expect(toBaseGenerationConfig(row('flux')).ui.clipSkipMax).toBeUndefined();+ expect('clipSkipMax' in toBaseGenerationConfig(row('flux')).ui).toBe(true);+ });++ it('declares ERNIE-Image scheduler choice as reaching the graph', () => {+ // ernie_image_denoise builds its sampler from the `scheduler` field, so the dropdown is real.+ expect(toBaseGenerationConfig(row('ernie-image')).schedulerAppliesToGraph).toBe(true);+ });+});++describe('the registry', () => {+ it('is empty until the table is pushed in', () => {+ expect(hasArchitectureCapabilities()).toBe(false);+ expect(getArchitectureGenerationConfig('sd-1')).toBeUndefined();++ setArchitectureCapabilities(rows);++ expect(hasArchitectureCapabilities()).toBe(true);+ expect(getArchitectureGenerationConfig('sd-1')?.defaults.steps).toBe(30);+ });++ it('prefers a variant row and falls back to the architecture row', () => {+ setArchitectureCapabilities(rows);++ expect(getArchitectureGenerationConfig('flux', 'schnell')?.defaults.steps).toBe(4);+ expect(getArchitectureGenerationConfig('flux', 'dev')?.defaults.steps).toBe(28);+ // A variant with no row of its own, and no variant at all, both land on the base row.+ expect(getArchitectureGenerationConfig('flux', 'made-up')?.defaults.steps).toBe(28);+ expect(getArchitectureGenerationConfig('flux')?.defaults.steps).toBe(28);+ });++ it('returns features from the architecture row regardless of variant', () => {+ setArchitectureCapabilities(rows);++ expect(getArchitectureFeatures('sd-1')?.control_kinds).toEqual(['controlnet', 't2i_adapter']);+ expect(getArchitectureFeatures('z-image')?.control_kinds).toEqual(['z_image_control']);+ expect(getArchitectureFeatures('made-up')).toBeUndefined();+ });++ it('hands back stable objects so policy accessors can be used in render paths', () => {+ setArchitectureCapabilities(rows);++ expect(getArchitectureGenerationConfig('sdxl')).toBe(getArchitectureGenerationConfig('sdxl'));+ });++ it('forgets everything on reset', () => {+ setArchitectureCapabilities(rows);+ resetArchitectureCapabilities();++ expect(hasArchitectureCapabilities()).toBe(false);+ expect(getArchitectureCapabilityRow('sd-1')).toBeUndefined();+ expect(getArchitectureFeatures('sd-1')).toBeUndefined();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.testing.tsnew file mode 100644index 0000000000..c2dba58471--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.testing.ts@@ -0,0 +1,33 @@+/**+ * Seeds the architecture capability registry for tests.+ *+ * Generation policy comes from the backend now, and the resolver fails closed without it, so any+ * test that touches policy needs the table present -- the way it always is in a running app, where+ * app boot fetches it before the Generate widget renders.+ *+ * Explicit rather than a global setup file: a test that wants to observe the *unloaded* behaviour+ * should be able to see that it is unloaded.+ */++import { afterEach, beforeEach } from 'vitest';++import fixture from './__fixtures__/architectureCapabilities.json';+import {+ type ArchitectureCapabilitiesRow,+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from './architectureCapabilities';++/** The response body the backend actually serves, pinned by `test_capabilities_fixture.py`. */+export const architectureCapabilitiesFixture = fixture as ArchitectureCapabilitiesRow[];++/** Load the table before each test and drop it afterwards, so nothing leaks between files. */+export const useArchitectureCapabilitiesFixture = (): void => {+ beforeEach(() => {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ });++ afterEach(() => {+ resetArchitectureCapabilities();+ });+};diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.tsnew file mode 100644index 0000000000..f8de4942de--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts@@ -0,0 +1,182 @@+/**+ * What the backend says each architecture supports, and how it reaches generation policy.+ *+ * `GET /api/v2/models/capabilities` serves one row per architecture plus a row per variant that+ * answers differently -- the same table `invokeai/backend/architectures/defs/<base>.py` declares.+ * Adding an architecture to the backend should not mean editing a table here too.+ *+ * webv2 has no generated OpenAPI types, so the wire shape below is hand-written and unguarded by+ * the compiler. `tests/backend/architectures/test_capabilities_fixture.py` is what guards it: it+ * pins `__fixtures__/architectureCapabilities.json` against what the backend actually renders, and+ * that same fixture feeds these tests and the mock backend.+ *+ * This module is deliberately push-based. `feature-core-purity` forbids `core/` from importing+ * `data/` or transport, so the store calls `setArchitectureCapabilities` rather than being read+ * from here -- the same shape `configureHttpAuth` uses in `platform/transport/http.ts`.+ */++import type { BaseGenerationConfig, GuidanceLabel, NegativePromptUsage, SchedulerSetId } from './generationConfig';++/** A capabilities row exactly as the backend serialises it. snake_case, unions kept open. */+export interface ArchitectureCapabilitiesRow {+ base: string;+ /** Null for the architecture's own row. A variant row overrides it. */+ variant: string | null;+ modality: {+ modes: string[];+ metadata_slug: string | null;+ };+ features: {+ negative_prompt: { visible: boolean; usage: NegativePromptUsage };+ dimension_grid: number;+ spatial_compression: number;+ guidance_label: GuidanceLabel | (string & {});+ /** No `flow-no-lcm` here: that set is reached by a frontend-only variant rule, see below. */+ scheduler_set: SchedulerSetId | null;+ scheduler_applies_to_graph: boolean;+ control_kinds: string[];+ max_reference_images: number;+ reference_images_require_variant: string | null;+ supports_regional_guidance: boolean;+ regional_negative: boolean;+ clip_skip_max: number | null;+ supports_seamless: boolean;+ supports_cfg_rescale: boolean;+ sd_vae_override: boolean;+ color_compensation: boolean;+ vae_precision: boolean;+ };+ defaults: {+ vae: string | null;+ vae_precision: 'fp16' | 'fp32' | null;+ scheduler: string | null;+ steps: number | null;+ cfg_scale: number | null;+ cfg_rescale_multiplier: number | null;+ width: number | null;+ height: number | null;+ guidance: number | null;+ cpu_only: boolean | null;+ fp8_storage: boolean | null;+ } | null;+}++const FALLBACK_STEPS = 30;+const FALLBACK_CFG_SCALE = 7;+const FALLBACK_SCHEDULER = 'euler_a';+const FALLBACK_OPTIMAL_SIDE = 1024;++/**+ * The value the single guidance slider takes.+ *+ * There is one control, labelled from `guidance_label`, and two fields behind it. A+ * guidance-distilled architecture records `cfg_scale: 1.0` meaning "CFG off" *and* the guidance it+ * samples with, so reading `cfg_scale` first would present the off-switch as the setting.+ */+const guidanceValue = (defaults: NonNullable<ArchitectureCapabilitiesRow['defaults']>, label: GuidanceLabel): number =>+ (label === 'Guidance' ? defaults.guidance ?? defaults.cfg_scale : defaults.cfg_scale ?? defaults.guidance) ??+ FALLBACK_CFG_SCALE;++/**+ * The optimal canvas as a side length.+ *+ * `optimalSide` is squared back into an area by its consumers (`importGalleryImages` passes+ * `optimal ** 2` to `calculateNewSize`), so deriving it from the area rather than from `width`+ * alone survives an architecture whose default canvas is not square. Every architecture webv2+ * generates images with is square today; MiniMax H3 is 1344x768, which is why this is not just+ * `width`.+ */+const optimalSide = (defaults: NonNullable<ArchitectureCapabilitiesRow['defaults']>): number => {+ const { width, height } = defaults;+ if (width && height) {+ return Math.round(Math.sqrt(width * height));+ }+ return width ?? height ?? FALLBACK_OPTIMAL_SIDE;+};++/** Map one row onto the shape generation policy already speaks. Pure. */+export const toBaseGenerationConfig = (row: ArchitectureCapabilitiesRow): BaseGenerationConfig => {+ const { features } = row;+ const defaults = row.defaults;+ const guidanceLabel: GuidanceLabel = features.guidance_label === 'Guidance' ? 'Guidance' : 'CFG';++ return {+ dimensions: {+ grid: features.dimension_grid,+ optimalSide: defaults ? optimalSide(defaults) : FALLBACK_OPTIMAL_SIDE,+ },+ defaults: {+ steps: defaults?.steps ?? FALLBACK_STEPS,+ cfgScale: defaults ? guidanceValue(defaults, guidanceLabel) : FALLBACK_CFG_SCALE,+ scheduler: defaults?.scheduler ?? FALLBACK_SCHEDULER,+ },+ schedulerSet: features.scheduler_set ?? 'standard',+ schedulerAppliesToGraph: features.scheduler_applies_to_graph,+ guidanceLabel,+ negativePrompt: features.negative_prompt,+ ui: {+ sdVaeOverride: features.sd_vae_override,+ colorCompensation: features.color_compensation,+ vaePrecision: features.vae_precision,+ seamless: features.supports_seamless,+ cfgRescale: features.supports_cfg_rescale,+ // `undefined`, not `null`: consumers branch on falsiness and on presence.+ clipSkipMax: features.clip_skip_max ?? undefined,+ },+ };+};++const key = (base: string, variant: string | null): string => `${base}\u0000${variant ?? ''}`;++let rows: readonly ArchitectureCapabilitiesRow[] | null = null;+let byKey = new Map<string, ArchitectureCapabilitiesRow>();+let configByKey = new Map<string, BaseGenerationConfig>();++/** Called by `data/` once the table has been fetched. */+export const setArchitectureCapabilities = (next: readonly ArchitectureCapabilitiesRow[]): void => {+ rows = next;+ byKey = new Map(next.map((row) => [key(row.base, row.variant), row]));+ // Memoised so policy accessors stay O(1) and hand back referentially stable objects.+ configByKey = new Map(next.map((row) => [key(row.base, row.variant), toBaseGenerationConfig(row)]));+};++/** Drop the table. The store calls this on account change; tests call it to isolate. */+export const resetArchitectureCapabilities = (): void => {+ rows = null;+ byKey = new Map();+ configByKey = new Map();+};++export const hasArchitectureCapabilities = (): boolean => rows !== null;++/** `(base, variant)` if that variant answers differently, else the architecture's own row. */+export const getArchitectureCapabilityRow = (+ base: string,+ variant?: unknown+): ArchitectureCapabilitiesRow | undefined => {+ if (typeof variant === 'string' && variant.length > 0) {+ const exact = byKey.get(key(base, variant));+ if (exact) {+ return exact;+ }+ }+ return byKey.get(key(base, null));+};++export const getArchitectureGenerationConfig = (base: string, variant?: unknown): BaseGenerationConfig | undefined => {+ if (typeof variant === 'string' && variant.length > 0) {+ const exact = configByKey.get(key(base, variant));+ if (exact) {+ return exact;+ }+ }+ return configByKey.get(key(base, null));+};++/**+ * Feature flags for an architecture. Variant-independent by design: the backend copies one+ * `features` block onto every variant row of an architecture, so asking per variant would suggest+ * a precision that is not there.+ */+export const getArchitectureFeatures = (base: string): ArchitectureCapabilitiesRow['features'] | undefined =>+ byKey.get(key(base, null))?.features;diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex ed0eaf3bf5..ce52335345 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -10,7 +10,6 @@ import type {} from './types';import {- BASE_GENERATION,coerceSchedulerForGraph,getComponentSectionPolicy,getAutoFlux2ComponentSourceModel,@@ -27,6 +26,7 @@ import {isSupportedGenerateModel,SUPPORTED_GENERATE_BASES,} from './baseGenerationPolicies';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const createModel = (base: string, overrides: Partial<MainModelConfig> = {}): MainModelConfig => ({base,@@ -102,7 +102,9 @@ const externalModel: GenerateModelConfig = {type: 'external_image_generator',};-describe('BASE_GENERATION', () => {+useArchitectureCapabilitiesFixture();++describe('architecture policy, read from the backend capability table', () => {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 });@@ -111,6 +113,8 @@ describe('BASE_GENERATION', () => {});it('matches expected defaults per base', () => {+ // These now come from the architecture facets rather than a table maintained here, so several+ // moved to the values the model cards recommend. See the PR description for the full list.expect(getDefaultGenerateSettings(createModel('sdxl'))).toMatchObject({steps: 30,cfgScale: 7,@@ -118,9 +122,11 @@ describe('BASE_GENERATION', () => {width: 1024,height: 1024,});+ // FLUX's base row is dev: 28 steps at guidance 3.5. The old single row carried Schnell's step+ // count for every variant, which is what the variant rows below now express properly.expect(getDefaultGenerateSettings(createModel('flux'))).toMatchObject({- steps: 4,- cfgScale: 4,+ steps: 28,+ cfgScale: 3.5,scheduler: 'euler',});expect(getDefaultGenerateSettings(createModel('flux2'))).toMatchObject({@@ -133,13 +139,28 @@ describe('BASE_GENERATION', () => {cfgScale: 4,scheduler: 'euler_a',});+ // Tongyi-MAI/Z-Image-Turbo says num_inference_steps=9.expect(getDefaultGenerateSettings(createModel('z-image'))).toMatchObject({- steps: 8,+ steps: 9,cfgScale: 1,scheduler: 'euler',});});+ it('answers per variant where the architecture does', () => {+ // The gain the single-row table could not express: Schnell and dev want different step counts,+ // and Fill wants a guidance an order of magnitude higher.+ expect(getDefaultGenerateSettings(createModel('flux', { variant: 'schnell' }))).toMatchObject({ steps: 4 });+ expect(getDefaultGenerateSettings(createModel('flux', { variant: 'dev_fill' }))).toMatchObject({+ steps: 50,+ cfgScale: 30,+ });+ expect(getDefaultGenerateSettings(createModel('z-image', { variant: 'zbase' }))).toMatchObject({+ steps: 50,+ cfgScale: 4,+ });+ });+it('matches expected scheduler sets per base', () => {const flux = createModel('flux');const zbase = createModel('z-image', { variant: 'zbase' });@@ -233,30 +254,15 @@ describe('BASE_GENERATION', () => {).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',- 'ernie-image',- 'qwen-image',- 'z-image',- 'ideogram-4',- 'krea-2',- 'wan',- 'anima',- ]);- });+ // The ordered list of generatable bases is pinned in `supportedBases.test.ts`, which now owns it.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');+ // 'external' is the pseudo-base of external image generators; they are supported through+ // `type === 'external_image_generator'`, not by having an architecture row.+ expect(isSupportedGenerateModel(createModel('external'))).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 755796caf0..b233ea8263 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -5,6 +5,24 @@ import type {PromptHistoryItem,} from '@features/generation/core/contracts';+import {+ isSupportedGenerateBase,+ SUPPORTED_GENERATE_BASES,+ type SupportedGenerateBase,+} from '@features/generation/core/supportedBases';++import type {+ BaseGenerationConfig,+ GuidanceLabel,+ NegativePromptUsage,+ SchedulerSetId,+} from '@features/generation/core/generationConfig';++import {+ getArchitectureFeatures,+ getArchitectureGenerationConfig,+} from '@features/generation/core/architectureCapabilities';+import type {GenerateModelConfig,GenerateReferenceImage,@@ -71,38 +89,12 @@ export interface SchedulerOption {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;- colorCompensation: boolean;- vaePrecision: boolean;- seamless: boolean;- cfgRescale: boolean;- clipSkipMax?: number;- };-}+export type {+ BaseGenerationConfig,+ GuidanceLabel,+ NegativePromptUsage,+ SchedulerSetId,+} from '@features/generation/core/generationConfig';type GenerateDefaultSettings =| {@@ -180,166 +172,8 @@ const ANIMA_SCHEDULERS = new Set(ANIMA_SCHEDULER_OPTIONS.map((option) => option.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,- colorCompensation: false,- 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,- colorCompensation: false,- 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, colorCompensation: 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, colorCompensation: 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, colorCompensation: 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, colorCompensation: 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, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },- },- 'ernie-image': {- // ernie_image_denoise carries multiple_of=16 on width/height.- dimensions: { grid: 16, optimalSide: 1024 },- // The base model's numbers. ERNIE-Image-Turbo wants 8 steps at guidance 1.0, which arrives- // through the model's own default_settings rather than a second entry here: Turbo and the- // base model share an architecture and a config, so no variant discriminates them.- defaults: { steps: 50, cfgScale: 4, scheduler: 'euler' },- // ERNIE_IMAGE_SCHEDULER_MAP is euler/heun/lcm, and the denoise node takes the choice.- schedulerSet: 'flow',- schedulerAppliesToGraph: true,- guidanceLabel: 'CFG',- // negative_conditioning is 'required when guidance_scale != 1.0'.- negativePrompt: { visible: true, usage: 'cfg-gated' },- ui: { sdVaeOverride: false, colorCompensation: 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, colorCompensation: 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, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },- },- 'ideogram-4': {- // Enforced by ideogram4_denoise: width/height carry multipleOf=16.- dimensions: { grid: 16, optimalSide: 1024 },- // Steps and guidance come from the sampler preset unless explicitly overridden, so the- // shared step/CFG fields are inert here; the preset default is V4_QUALITY_48 (48 steps).- defaults: { steps: 48, cfgScale: 1, scheduler: 'euler' },- schedulerSet: 'flow',- schedulerAppliesToGraph: false,- guidanceLabel: 'Guidance',- negativePrompt: { visible: false, usage: 'never' },- ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },- },- 'krea-2': {- dimensions: { grid: 16, optimalSide: 1024 },- // Krea-2-Turbo's numbers. Krea-2-Raw wants ~28 steps at CFG ~4.5, which comes through the- // model's own default_settings rather than being hardcoded per variant here.- defaults: { steps: 8, cfgScale: 1, scheduler: 'euler' },- schedulerSet: 'flow',- schedulerAppliesToGraph: false,- guidanceLabel: 'CFG',- negativePrompt: { visible: true, usage: 'cfg-gated' },- ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },- },- wan: {- // Wan's transformer patch-embeds with stride 2 and un-patches by 2; combined with the VAE's- // 8x spatial scale, dimensions must be multiples of 16 or the scheduler step fails on a- // latents-vs-noise spatial mismatch.- dimensions: { grid: 16, optimalSide: 1024 },- defaults: { steps: 40, cfgScale: 4, scheduler: 'euler' },- schedulerSet: 'flow',- schedulerAppliesToGraph: false,- guidanceLabel: 'Guidance',- negativePrompt: { visible: true, usage: 'always' },- ui: { sdVaeOverride: false, colorCompensation: 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, colorCompensation: 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 { isSupportedGenerateBase, SUPPORTED_GENERATE_BASES, type SupportedGenerateBase };export interface GenerationModelPolicy {isSupported: boolean;@@ -391,17 +225,34 @@ const FALLBACK_GENERATION_CONFIG: BaseGenerationConfig = {ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },};-// Fallbacks keep UI selectors crash-safe; isSupportedGenerateModel() still blocks invocation.+/**+ * What the backend says about this model's architecture.+ *+ * The variant matters: FLUX Schnell wants 4 steps where dev wants 28, and the endpoint answers per+ * variant where they differ. Falling back keeps UI selectors crash-safe for external generators and+ * for an architecture the backend does not know; `isSupportedGenerateModel` still blocks invocation,+ * and `resolveGenerateWidgetValues` refuses to resolve at all until the table has arrived.+ */const getBaseGenerationConfig = (- model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined+ model: (Pick<GenerateModelConfig, 'base' | 'type'> & { variant?: unknown }) | 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;+ return getArchitectureGenerationConfig(model.base, model.variant) ?? FALLBACK_GENERATION_CONFIG;};+/**+ * The pixel grid generation dimensions must land on, or `null` if the backend has no row for this+ * architecture.+ *+ * `null` rather than a default so callers keep owning their own "nothing selected" behaviour --+ * the canvas has a different sensible answer there than a generation graph does.+ */+export const getDimensionGridForBase = (base: string): number | null =>+ getArchitectureFeatures(base)?.dimension_grid ?? null;+const getNumber = (value: number | null | undefined, fallback: number): number =>Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;@@ -579,7 +430,7 @@ export const getGenerationUiPolicy = (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 === 'main' && isSupportedGenerateBase(model.base)) ||(model.type === 'external_image_generator' && model.base === 'external');export const isGenerateModelSelectable = <T extends ModelConfig>(model: T): boolean => isSupportedGenerateModel(model);@@ -1349,11 +1200,18 @@ export const isReferenceImageSupported = (model: GenerateModelConfig | undefinedreturn model.capabilities?.supports_reference_images === true;}- if (model.base === 'qwen-image') {- return model.variant === 'edit';+ const features = getArchitectureFeatures(model.base);++ if (!features || features.max_reference_images <= 0) {+ return false;}- return ['flux', 'flux2', 'sd-1', 'sdxl'].includes(model.base);+ // Qwen-Image accepts reference images only as the `edit` variant -- the one feature the backend+ // qualifies by variant, which is why it says so on the architecture row rather than inventing a+ // variant row for it.+ return (+ features.reference_images_require_variant === null || model.variant === features.reference_images_require_variant+ );};export const getMaxReferenceImages = (model: GenerateModelConfig | undefined): number => {@@ -1365,7 +1223,7 @@ export const getMaxReferenceImages = (model: GenerateModelConfig | undefined): nreturn Math.max(0, model.capabilities.max_reference_images);}- return DEFAULT_REFERENCE_IMAGE_LIMIT;+ return getArchitectureFeatures(model.base)?.max_reference_images ?? DEFAULT_REFERENCE_IMAGE_LIMIT;};export const createReferenceImageId = (): string =>diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.tsindex 44b2289571..fe1e6fad21 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addControlLayers.test.ts@@ -13,6 +13,7 @@ import {getControlLayerRejectionReason,isControlKindSupportedForBase,} from './addControlLayers';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';// ---------------------------------------------------------------------------// Test helpers@@ -69,6 +70,8 @@ const edgesTo = (graph: TestGraph, nodeId: string, field: string) =>// 1. isControlKindSupportedForBase full matrix// ---------------------------------------------------------------------------+useArchitectureCapabilitiesFixture();+describe('isControlKindSupportedForBase', () => {it('controlnet is supported on sd-1, sdxl, flux only', () => {expect(isControlKindSupportedForBase('sd-1', 'controlnet')).toBe(true);diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.tsindex feaa093a2a..1b1bd25fa3 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts@@ -7,6 +7,7 @@ import {getRegionalGuidanceRejectionReason,isRegionalGuidanceSupportedForBase,} from './addRegionalGuidance';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';interface TestGraph {id: string;@@ -140,6 +141,8 @@ const hasEdge = (graph: TestGraph, s: string, sf: string, d: string, df: string)(e) => e.source.node_id === s && e.source.field === sf && e.destination.node_id === d && e.destination.field === df);+useArchitectureCapabilitiesFixture();+describe('isRegionalGuidanceSupportedForBase', () => {it('supports sd-1 / sdxl / flux / flux2 / krea-2 and nothing else', () => {expect(isRegionalGuidanceSupportedForBase('sd-1')).toBe(true);diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tsindex 65b0bf460c..6a9bdd9355 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts@@ -1,3 +1,5 @@+import { getArchitectureFeatures } from '@features/generation/core/architectureCapabilities';+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';import { addEdge, addNode } from '@features/generation/core/graphBuilder';@@ -13,12 +15,26 @@ const NEG_COND_COLLECT_ID = 'neg_cond_collect';/** The base models regional guidance supports. */export type RegionalGuidanceBase = 'sd-1' | 'sdxl' | 'flux' | 'flux2' | 'krea-2';-/** True when `base` supports regional guidance at all. */+/**+ * True when `base` supports regional guidance at all.+ *+ * The narrowing to `RegionalGuidanceBase` stays: everything below this point dispatches on the+ * literal to pick node types and field names, and that is graph knowledge the backend has no say+ * in. Only the *answer* comes from the capability table now.+ */export const isRegionalGuidanceSupportedForBase = (base: string): base is RegionalGuidanceBase =>- base === 'sd-1' || base === 'sdxl' || base === 'flux' || base === 'flux2' || base === 'krea-2';+ getArchitectureFeatures(base)?.supports_regional_guidance ?? false;++/**+ * Whether a base supports regional NEGATIVE prompts / autoNegative.+ *+ * Exported because the layer settings UI needs the same answer: it used to ask "is this the FLUX+ * family?" and got krea-2 wrong, rendering a negative-prompt field the graph builder discards.+ */+export const isRegionalNegativeSupportedForBase = (base: string): boolean =>+ getArchitectureFeatures(base)?.regional_negative ?? false;-/** Whether a base supports regional NEGATIVE prompts / autoNegative (SD family only). */-const supportsRegionalNegative = (base: RegionalGuidanceBase): boolean => base === 'sd-1' || base === 'sdxl';+const supportsRegionalNegative = (base: RegionalGuidanceBase): boolean => isRegionalNegativeSupportedForBase(base);/** A resolved reference-image (component) model identifier — the backend model field shape. */export interface RegionalReferenceModel {diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex 04ae26fe13..8012758a68 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@ -16,6 +16,7 @@ import type { CanvasCompileMode, CanvasCompositingSettings, Rect } from './typesimport { compileCanvasGraph } from './compileCanvasGraph';import { DEFAULT_CANVAS_COMPOSITING } from './types';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };@@ -250,6 +251,8 @@ const BASE_CASES: BaseCase[] = [},];+useArchitectureCapabilitiesFixture();+describe('compileCanvasGraph', () => {describe('txt2img per base', () => {it.each(BASE_CASES)(diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.test.tsindex f6ed3c8e6f..18ba7425d5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import { getControlValidationReason } from './controlValidation';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const valid = {adapterModel: { base: 'sd-1', type: 'controlnet' },@@ -12,6 +13,8 @@ const valid = {weight: 0.75,};+useArchitectureCapabilitiesFixture();+describe('getControlValidationReason', () => {it('returns stable reason codes for the validation matrix', () => {expect(getControlValidationReason(valid)).toBeNull();diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.tsindex 203379d241..cdad06de76 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/controlValidation.ts@@ -1,3 +1,5 @@+import { getArchitectureFeatures } from '@features/generation/core/architectureCapabilities';+export type ControlAdapterKind = 'controlnet' | 't2i_adapter' | 'control_lora' | 'z_image_control';export type ControlValidationReason =@@ -10,18 +12,15 @@ export type ControlValidationReason =| 'z_image_control_limit'| 'flux_fill_control_lora';-export const isControlKindSupportedForBase = (base: string, kind: ControlAdapterKind): boolean => {- if (kind === 'controlnet') {- return base === 'sd-1' || base === 'sdxl' || base === 'flux';- }- if (kind === 't2i_adapter') {- return base === 'sd-1' || base === 'sdxl';- }- if (kind === 'z_image_control') {- return base === 'z-image';- }- return base === 'flux';-};+/**+ * Which control adapters an architecture accepts, as the backend declares it.+ *+ * Only the base-to-kinds mapping comes from there. The limit rules further down -- one control+ * LoRA, one Z-Image control, and FLUX Fill rejecting control LoRAs entirely -- have no column in+ * the capability table and stay here.+ */+export const isControlKindSupportedForBase = (base: string, kind: ControlAdapterKind): boolean =>+ getArchitectureFeatures(base)?.control_kinds.includes(kind) ?? false;export const getControlValidationReason = (params: {adapterModel: { base: string; type: string } | null;diff --git a/invokeai/frontend/webv2/src/features/generation/core/generationConfig.ts b/invokeai/frontend/webv2/src/features/generation/core/generationConfig.tsnew file mode 100644index 0000000000..c1d92e02c4--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/generationConfig.ts@@ -0,0 +1,46 @@+/**+ * The shape generation policy speaks about an architecture.+ *+ * Split out of `baseGenerationPolicies.ts` so that `architectureCapabilities.ts` -- which maps the+ * backend's wire rows onto this shape -- and the policy accessors that consume it can both refer to+ * it without importing each other.+ */++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;+ /**+ * The side of the model's optimal square canvas. Consumers square it back into an area+ * (`importGalleryImages` passes `optimal ** 2` to `calculateNewSize`), so it is derived from+ * the declared area rather than from width alone.+ */+ optimalSide: number;+ };+ defaults: {+ steps: number;+ /** Whatever the single guidance slider shows -- CFG or distilled guidance, per `guidanceLabel`. */+ cfgScale: number;+ scheduler: string;+ };+ schedulerSet: SchedulerSetId;+ schedulerAppliesToGraph: boolean;+ guidanceLabel: GuidanceLabel;+ negativePrompt: {+ visible: boolean;+ usage: NegativePromptUsage;+ };+ ui: {+ sdVaeOverride: boolean;+ colorCompensation: boolean;+ vaePrecision: boolean;+ seamless: boolean;+ cfgRescale: boolean;+ clipSkipMax?: number;+ };+}diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex 2429462990..511460b000 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -11,6 +11,7 @@ import type {import { getDefaultGenerateSettings, isSupportedGenerateModel } from './baseGenerationPolicies';import { compileGenerateGraph, generateSeedSequence, resolveGenerateSeed } from './graph';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };@@ -158,6 +159,8 @@ afterEach(() => {vi.restoreAllMocks();});+useArchitectureCapabilitiesFixture();+describe('compileGenerateGraph', () => {it('recognizes the legacy-supported generate model families', () => {expect(diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.tsindex 9357826fda..3892fa78a5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts@@ -2,7 +2,7 @@* Every supported base compiles a graph — the systematic counterpart to `graph.test.ts`.** `graph.test.ts` asserts *what* individual families wire up, one hand-written case at a time. That- * leaves a base added to `BASE_GENERATION` and `GRAPH_BUILDERS` but never given a case silently+ * leaves a base added to `SUPPORTED_GENERATE_BASES` and `GRAPH_BUILDERS` but never given a case silently* untested. This file instead iterates `SUPPORTED_GENERATE_BASES`, so a new architecture is covered* the moment it is registered, and asserts the properties that hold for *all* of them: the* component policy is satisfiable, the builder runs, and the resulting graph is structurally sound.@@ -37,6 +37,7 @@ import {SUPPORTED_GENERATE_BASES,} from './baseGenerationPolicies';import { compileGenerateGraph, GRAPH_BUILDERS } from './graph';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';/*** Main-model shapes to compile per base.@@ -204,6 +205,8 @@ const cases = SUPPORTED_GENERATE_BASES.flatMap((base) =>shapesForBase(base).map((shape) => ({ base, label: `${base} / ${shape.label}`, shape })));+useArchitectureCapabilitiesFixture();+describe('generate graph coverage', () => {it('has a builder for every supported base and no builder for anything else', () => {expect(Object.keys(GRAPH_BUILDERS).sort()).toEqual([...SUPPORTED_GENERATE_BASES].sort());diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.tsindex 651e322737..15b3158595 100644--- a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts@@ -1,4 +1,12 @@-import { describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import capabilitiesFixture from './__fixtures__/architectureCapabilities.json';+import {+ type ArchitectureCapabilitiesRow,+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from './architectureCapabilities';+import type { GenerationModelCatalogItem } from './contracts';import type { GenerateLora, GenerateWidgetValues, LoraModelConfig, MainModelConfig } from './types';@@ -34,6 +42,14 @@ const storedValues = createGenerateValues({width: 1024,});+// The resolver fails closed without the backend's architecture table, so seed the registry with the+// same fixture the backend pins. Reset afterwards so registry state cannot leak between files.+beforeEach(() => {+ setArchitectureCapabilities(capabilitiesFixture as ArchitectureCapabilitiesRow[]);+});++afterEach(resetArchitectureCapabilities);+describe('compileGeneratePreviewGraph', () => {it('compiles a ready graph with deterministic node ids across repeated compiles', () => {const input = { destination: 'gallery' as const, models, storedValues, useCpuNoise: false };diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptHistory.test.ts b/invokeai/frontend/webv2/src/features/generation/core/promptHistory.test.tsindex 26c1942b50..622ac01cba 100644--- a/invokeai/frontend/webv2/src/features/generation/core/promptHistory.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/promptHistory.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import type { MainModelConfig } from './types';import { getDefaultGenerateSettings, getPromptHistoryRecallPatch } from './baseGenerationPolicies';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const createModel = (base: string): MainModelConfig => ({base,@@ -11,6 +12,8 @@ const createModel = (base: string): MainModelConfig => ({type: 'main',});+useArchitectureCapabilitiesFixture();+describe('getPromptHistoryRecallPatch', () => {it('clears an absent negative prompt when the selected model exposes it', () => {const model = createModel('sdxl');diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.tsindex 83f13ed44b..010e67103a 100644--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts@@ -1,4 +1,12 @@-import { describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import capabilitiesFixture from './__fixtures__/architectureCapabilities.json';+import {+ type ArchitectureCapabilitiesRow,+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from './architectureCapabilities';+import type { GenerateWidgetValues, MainModelConfig } from './types';@@ -26,6 +34,14 @@ const applySystemPatch = (systemPatch: Partial<GenerateWidgetValues>): Record<string, unknown> => ({ ...storedValues, ...systemPatch });+// The resolver fails closed without the backend's architecture table, so seed the registry with the+// same fixture the backend pins. Reset afterwards so registry state cannot leak between files.+beforeEach(() => {+ setArchitectureCapabilities(capabilitiesFixture as ArchitectureCapabilitiesRow[]);+});++afterEach(resetArchitectureCapabilities);+describe('resolveGenerateWidgetValues', () => {it('returns null when the catalog has no supported generation model', () => {expect(@@ -188,3 +204,16 @@ describe('resolveGenerateWidgetValues', () => {expect(second?.systemPatch).toBeNull();});});++describe('without the backend capability table', () => {+ it('resolves nothing rather than falling back to generic defaults', () => {+ // Its `systemPatch` is persisted into the project, so a fallback grid or step count would be+ // written to disk. Returning null is already how "no usable models" is signalled, and every+ // caller handles it.+ resetArchitectureCapabilities();++ const model: MainModelConfig = { base: 'sdxl', key: 'model', name: 'model', type: 'main' };++ expect(resolveGenerateWidgetValues({ models: [model], storedValues: {} })).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.tsindex fc8bd06ae4..772b119f99 100644--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts@@ -1,3 +1,5 @@+import { hasArchitectureCapabilities } from '@features/generation/core/architectureCapabilities';+import { areJsonValuesStructurallyEqual } from '@platform/core/json';import type { GenerationModelCatalogItem } from './contracts';@@ -68,6 +70,13 @@ export const resolveGenerateWidgetValues = ({promptTemplates,storedValues,}: ResolveGenerateWidgetValuesInput): ResolvedGenerateWidgetValues | null => {+ // Fail closed until the backend's architecture table has arrived. Resolving without it would+ // fall back to generic defaults -- and this resolver's `systemPatch` is *persisted* into the+ // project, so a fallback grid or step count would be written to disk rather than merely shown.+ if (!hasArchitectureCapabilities()) {+ return null;+ }+const supportedModels = models.filter(isSupportedGenerateModel);if (supportedModels.length === 0) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex 6b79407de2..9a872ae679 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@ -24,6 +24,7 @@ import {syncGenerateWidgetValuesWithModels,syncGenerateLorasWithModels,} from './settings';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';/** The persisted widget-value shape from before aspect ratio / VAE / seamless / CLIP skip landed. */const legacyStoredValues = {@@ -41,6 +42,8 @@ const legacyStoredValues = {width: 512,};+useArchitectureCapabilitiesFixture();+describe('normalizeGenerateSettings', () => {it('enforces template view mode only when a valid template remains', () => {const validTemplate = {diff --git a/invokeai/frontend/webv2/src/features/generation/core/supportedBases.test.ts b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.test.tsnew file mode 100644index 0000000000..aea901e553--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.test.ts@@ -0,0 +1,46 @@+/**+ * The list of architectures this build can generate images with.+ *+ * It used to be `Object.keys(BASE_GENERATION)`, so this assertion doubled as a check on that+ * table. With the policy data moving to the backend, the list stands on its own: it is the+ * frontend's half of the contract -- the architectures we have a graph builder for. The pin stays+ * because adding one must be a deliberate act that a reviewer sees.+ */++import { describe, expect, it } from 'vitest';++import { isSupportedGenerateBase, SUPPORTED_GENERATE_BASES } from './supportedBases';++describe('SUPPORTED_GENERATE_BASES', () => {+ it('is exactly the bases with a graph builder, in order', () => {+ expect(SUPPORTED_GENERATE_BASES).toEqual([+ 'sd-1',+ 'sd-2',+ 'sdxl',+ 'sd-3',+ 'flux',+ 'flux2',+ 'cogview4',+ 'ernie-image',+ 'qwen-image',+ 'z-image',+ 'ideogram-4',+ 'krea-2',+ 'wan',+ 'anima',+ ]);+ });++ it('excludes architectures the backend serves but this build cannot generate with', () => {+ // Both have capability rows on `/api/v2/models/capabilities`. Neither has an image graph+ // builder: the refiner is a second pass over an SDXL latent, and MiniMax H3 is video-only.+ expect(isSupportedGenerateBase('sdxl-refiner')).toBe(false);+ expect(isSupportedGenerateBase('minimax-h3')).toBe(false);+ });++ it('rejects unknown and non-architecture values', () => {+ expect(isSupportedGenerateBase('unknown')).toBe(false);+ expect(isSupportedGenerateBase('made-up')).toBe(false);+ expect(isSupportedGenerateBase('external')).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/supportedBases.ts b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.tsnew file mode 100644index 0000000000..6a46825ac5--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/supportedBases.ts@@ -0,0 +1,38 @@+/**+ * The architectures this build can compile an image-generation graph for.+ *+ * Frontend-owned on purpose, and the one thing in generation policy that cannot come from the+ * server: `GRAPH_BUILDERS` in `graph.ts` must have an entry for each of these, and the `satisfies`+ * there is what enforces it. The capabilities endpoint advertises more architectures than this --+ * `sdxl-refiner` is never run on its own, and `minimax-h3` is video-only with no image graph -- so+ * "the server knows about it" and "we can generate with it" are different questions.+ *+ * Previously derived as `keyof typeof BASE_GENERATION`, which tied the set to the key order of a+ * table that is about to be served from the backend. Written out here, adding an architecture stays+ * a deliberate act with a test that notices it.+ */++import type { KnownGenerationModelBase } from '@features/generation/core/contracts';++export const SUPPORTED_GENERATE_BASES = [+ 'sd-1',+ 'sd-2',+ 'sdxl',+ 'sd-3',+ 'flux',+ 'flux2',+ 'cogview4',+ 'ernie-image',+ 'qwen-image',+ 'z-image',+ 'ideogram-4',+ 'krea-2',+ 'wan',+ 'anima',+] as const satisfies readonly KnownGenerationModelBase[];++export type SupportedGenerateBase = (typeof SUPPORTED_GENERATE_BASES)[number];++const SUPPORTED = new Set<string>(SUPPORTED_GENERATE_BASES);++export const isSupportedGenerateBase = (base: string): base is SupportedGenerateBase => SUPPORTED.has(base);diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesApi.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesApi.tsnew file mode 100644index 0000000000..b6cdf30bab--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesApi.ts@@ -0,0 +1,15 @@+import type { ArchitectureCapabilitiesRow } from '@features/generation/core/architectureCapabilities';++import { apiFetchJson } from '@platform/transport/http';++/**+ * The architecture capability table.+ *+ * A static list -- the same for every install and every user -- describing what each model+ * architecture supports. Lives under the model-manager router because that is where architectures+ * are addressed, but it is not model-record data: nothing here depends on what is installed.+ */+const CAPABILITIES_PATH = '/api/v2/models/capabilities';++export const getArchitectureCapabilities = (signal?: AbortSignal): Promise<ArchitectureCapabilitiesRow[]> =>+ apiFetchJson<ArchitectureCapabilitiesRow[]>(CAPABILITIES_PATH, { signal });diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.tsnew file mode 100644index 0000000000..995698af20--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import fixture from '@features/generation/core/__fixtures__/architectureCapabilities.json';++const api = vi.hoisted(() => ({ getArchitectureCapabilities: vi.fn() }));++vi.mock('./architectureCapabilitiesApi', () => api);++const rows = fixture as unknown[];++describe('architecture capabilities store', () => {+ beforeEach(() => {+ vi.resetModules();+ api.getArchitectureCapabilities.mockReset();+ });++ it('fills the core registry rather than the snapshot', async () => {+ // The rows have exactly one home: policy accessors read them synchronously from all over the+ // app, including graph builders at enqueue time.+ api.getArchitectureCapabilities.mockResolvedValue(rows);+ const store = await import('./architectureCapabilitiesStore');+ const registry = await import('@features/generation/core/architectureCapabilities');++ expect(registry.hasArchitectureCapabilities()).toBe(false);+ await store.refreshArchitectureCapabilities();++ expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: null, status: 'loaded' });+ expect(registry.getArchitectureGenerationConfig('sd-1')?.defaults.steps).toBe(30);+ });++ it('dedupes concurrent refreshes', async () => {+ api.getArchitectureCapabilities.mockResolvedValue(rows);+ const store = await import('./architectureCapabilitiesStore');++ const first = store.refreshArchitectureCapabilities();+ expect(store.refreshArchitectureCapabilities()).toBe(first);+ await first;++ expect(store.getArchitectureCapabilitiesSnapshot().status).toBe('loaded');+ });++ it('reports a failure and leaves the registry empty', async () => {+ api.getArchitectureCapabilities.mockRejectedValue(new Error('outage'));+ const store = await import('./architectureCapabilitiesStore');+ const registry = await import('@features/generation/core/architectureCapabilities');++ await store.refreshArchitectureCapabilities();++ expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: 'outage', status: 'error' });+ expect(registry.hasArchitectureCapabilities()).toBe(false);+ });++ it('retries after an error but not after success', async () => {+ api.getArchitectureCapabilities.mockRejectedValueOnce(new Error('outage')).mockResolvedValue(rows);+ const store = await import('./architectureCapabilitiesStore');++ store.ensureArchitectureCapabilitiesLoaded();+ await Promise.resolve();+ await Promise.resolve();+ expect(store.getArchitectureCapabilitiesSnapshot().status).toBe('error');++ // One failed load must not stick...+ await store.refreshArchitectureCapabilities();+ expect(store.getArchitectureCapabilitiesSnapshot().status).toBe('loaded');++ // ...and a loaded table is never refetched: it is static per backend build.+ store.ensureArchitectureCapabilitiesLoaded();+ expect(api.getArchitectureCapabilities).toHaveBeenCalledTimes(2);+ });++ it('clears the registry as well as the snapshot when the account changes', async () => {+ // The addition to the starters-store template: the rows live outside this store, so clearing+ // only the snapshot would leave the previous account's table readable behind an idle status.+ api.getArchitectureCapabilities.mockResolvedValue(rows);+ const lifecycle = await import('@platform/state/accountLifecycle');+ const store = await import('./architectureCapabilitiesStore');+ const registry = await import('@features/generation/core/architectureCapabilities');++ await store.refreshArchitectureCapabilities();+ expect(registry.hasArchitectureCapabilities()).toBe(true);++ lifecycle.accountLifecycle.invalidate();++ expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: null, status: 'idle' });+ expect(registry.hasArchitectureCapabilities()).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.tsnew file mode 100644index 0000000000..46a52be338--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts@@ -0,0 +1,87 @@+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';+import {+ captureAccountScope,+ isAccountScopeCurrent,+ registerAccountOwnedResource,+} from '@platform/state/accountLifecycle';+import { createExternalStore } from '@platform/state/externalStore';+import { createTrailingSingleFlight } from '@platform/state/singleFlight';+import { getApiErrorMessage } from '@platform/transport/http';++import { getArchitectureCapabilities } from './architectureCapabilitiesApi';++/**+ * Load state for the architecture capability table.+ *+ * The rows themselves live in the core registry, not in this snapshot: generation policy is read+ * from synchronous accessors all over the app, including from graph builders at enqueue time, so+ * there must be exactly one place holding the table. This store owns only *whether* it is there.+ *+ * Fetched once. The table is static per backend build -- it is derived from+ * `invokeai/backend/architectures/defs/`, not from installed models -- so nothing revalidates it.+ */++export interface ArchitectureCapabilitiesSnapshot {+ status: 'idle' | 'loading' | 'loaded' | 'error';+ error: string | null;+}++const EMPTY_SNAPSHOT: ArchitectureCapabilitiesSnapshot = { error: null, status: 'idle' };+const store = createExternalStore<ArchitectureCapabilitiesSnapshot>(EMPTY_SNAPSHOT);++const refreshFlight = createTrailingSingleFlight();++registerAccountOwnedResource({+ clear: () => {+ refreshFlight.reset();+ store.setSnapshot(EMPTY_SNAPSHOT);+ // The registry is module state outside this store, so clearing the snapshot alone would leave+ // the previous account's table readable behind a status that says nothing is loaded.+ resetArchitectureCapabilities();+ },+ name: 'architecture-capabilities',+});++export const refreshArchitectureCapabilities = (): Promise<void> =>+ refreshFlight.run(() => {+ const owner = captureAccountScope();+ store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });++ return getArchitectureCapabilities(owner.signal)+ .then((rows) => {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ setArchitectureCapabilities(rows);+ store.patchSnapshot({ error: null, status: 'loaded' });+ })+ .catch((error: unknown) => {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ store.patchSnapshot({+ error: getApiErrorMessage(error, 'Failed to load model capabilities.'),+ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'error',+ });+ });+ });++/** Fetch on first use or retry after an error, so one failed load never sticks. */+export const ensureArchitectureCapabilitiesLoaded = (): void => {+ const { status } = store.getSnapshot();++ if (status === 'idle' || status === 'error') {+ void refreshArchitectureCapabilities();+ }+};++export const getArchitectureCapabilitiesSnapshot = (): ArchitectureCapabilitiesSnapshot => store.getSnapshot();++export const subscribeArchitectureCapabilities = store.subscribe;++export const useArchitectureCapabilitiesSelector = store.useSelector;diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.tsindex b83aab7726..f60ff01bde 100644--- a/invokeai/frontend/webv2/src/features/generation/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts@@ -29,6 +29,7 @@ export { getControlLayerRejectionReason, getControlValidationReasonMessage } froexport {getRegionalGuidanceRejectionReason,isRegionalGuidanceSupportedForBase,+ isRegionalNegativeSupportedForBase,type RegionalGuidanceInput,type RegionalReferenceImageInput,} from './core/canvas/addRegionalGuidance';diff --git a/invokeai/frontend/webv2/src/features/generation/runtime.test.ts b/invokeai/frontend/webv2/src/features/generation/runtime.test.tsindex 55ac91f82d..39accece84 100644--- a/invokeai/frontend/webv2/src/features/generation/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/runtime.test.ts@@ -2,9 +2,15 @@ import type { GenerationModelCatalogItem, GenerateWidgetValues, MainModelConfigimport type { PromptTemplateRecord } from '@features/generation/data/promptTemplates';import type * as GenerationQueries from '@features/generation/queries';+import capabilitiesFixture from '@features/generation/core/__fixtures__/architectureCapabilities.json';+import {+ type ArchitectureCapabilitiesRow,+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';import { getDefaultGenerateSettings } from '@features/generation/settings';import { QueryClient } from '@tanstack/react-query';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const templateQuery = vi.hoisted(() => ({queryFn: vi.fn<() => Promise<PromptTemplateRecord[]>>(),@@ -66,14 +72,17 @@ const createReadableStore = <Snapshot>(initialSnapshot: Snapshot) => {};const setup = ({+ capabilitiesLoaded: initialCapabilitiesLoaded = true,models: initialModels,project: initialProject,}: {+ capabilitiesLoaded?: boolean;models: readonly GenerationModelCatalogItem[];project: GenerateWidgetSyncProjectSnapshot;}) => {const models = createReadableStore(initialModels);const project = createReadableStore(initialProject);+ const capabilitiesLoaded = createReadableStore(initialCapabilitiesLoaded);const patches: Array<{origin: 'system';projectId: string;@@ -81,6 +90,7 @@ const setup = ({}> = [];const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });const deps: GenerateWidgetSyncRuntimeDeps = {+ capabilitiesLoaded,models,patchValues: (values, projectId, origin) => {patches.push({ origin, projectId, values });@@ -95,7 +105,7 @@ const setup = ({};const runtime = createGenerateWidgetSyncRuntime(deps);- return { models, patches, project, queryClient, runtime };+ return { capabilitiesLoaded, models, patches, project, queryClient, runtime };};beforeEach(() => {@@ -103,6 +113,14 @@ beforeEach(() => {templateQuery.queryFn.mockResolvedValue([]);});+// The resolver fails closed without the backend's architecture table, so seed the registry with the+// same fixture the backend pins. Reset afterwards so registry state cannot leak between files.+beforeEach(() => {+ setArchitectureCapabilities(capabilitiesFixture as ArchitectureCapabilitiesRow[]);+});++afterEach(resetArchitectureCapabilities);+describe('createGenerateWidgetSyncRuntime', () => {it('reconciles the newly active project after a project switch', () => {const model = createModel('model');@@ -239,3 +257,29 @@ describe('createGenerateWidgetSyncRuntime', () => {expect(patches).toHaveLength(0);});});++describe('the architecture-capabilities gate', () => {+ // reconcile() writes its result into the project via patchValues, so it must not run on fallback+ // policy: the values are persisted, not merely displayed. This is why the gate lives here and+ // not only in the widget -- the runtime reconciles at construction, before anything renders.+ it('writes nothing until the capability table has arrived', () => {+ const { capabilitiesLoaded, patches } = setup({+ capabilitiesLoaded: false,+ models: [createModel('model')],+ project: { id: 'project-1', values: {} },+ });++ expect(patches).toEqual([]);++ capabilitiesLoaded.setSnapshot(true);++ expect(patches.length).toBeGreaterThan(0);+ expect(patches[0]?.projectId).toBe('project-1');+ });++ it('reconciles at construction when the table is already there', () => {+ const { patches } = setup({ models: [createModel('model')], project: { id: 'project-1', values: {} } });++ expect(patches.length).toBeGreaterThan(0);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/runtime.ts b/invokeai/frontend/webv2/src/features/generation/runtime.tsindex 53f6aaefc9..25afb42e2c 100644--- a/invokeai/frontend/webv2/src/features/generation/runtime.ts+++ b/invokeai/frontend/webv2/src/features/generation/runtime.ts@@ -16,6 +16,14 @@ export interface GenerateWidgetSyncProjectSnapshot {}export interface GenerateWidgetSyncRuntimeDeps {+ /**+ * Whether the backend's architecture capability table has arrived.+ *+ * `reconcile` writes its result into the project, so it must not run on fallback policy: the+ * values would be persisted, not just displayed. Subscribed like the other read models so the+ * first reconcile happens as soon as the table lands.+ */+ capabilitiesLoaded: ReadonlyStore<boolean>;models: ReadonlyStore<readonly GenerationModelCatalogItem[]>;patchValues(values: Partial<GenerateWidgetValues>, projectId: string, origin: 'system'): void;project: ReadonlyStore<GenerateWidgetSyncProjectSnapshot>;@@ -42,7 +50,7 @@ export const createGenerateWidgetSyncRuntime = (deps: GenerateWidgetSyncRuntimeDlet isPromptTemplateQueryEnabled = false;const reconcile = (): void => {- if (isDisposed || isReconciling) {+ if (isDisposed || isReconciling || !deps.capabilitiesLoaded.getSnapshot()) {return;}@@ -78,6 +86,7 @@ export const createGenerateWidgetSyncRuntime = (deps: GenerateWidgetSyncRuntimeDconst unsubscribeProject = deps.project.subscribe(reconcile);const unsubscribeModels = deps.models.subscribe(reconcile);+ const unsubscribeCapabilities = deps.capabilitiesLoaded.subscribe(reconcile);const unsubscribePromptTemplates = promptTemplateObserver.subscribe(reconcile);reconcile();@@ -90,9 +99,17 @@ export const createGenerateWidgetSyncRuntime = (deps: GenerateWidgetSyncRuntimeDisDisposed = true;unsubscribePromptTemplates();+ unsubscribeCapabilities();unsubscribeModels();unsubscribeProject();promptTemplateObserver.destroy();},};};++export {+ ensureArchitectureCapabilitiesLoaded,+ getArchitectureCapabilitiesSnapshot,+ subscribeArchitectureCapabilities,+ type ArchitectureCapabilitiesSnapshot,+} from './data/architectureCapabilitiesStore';diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex ac78d1f31d..d9bd1caa50 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -41,6 +41,7 @@ export {getDefaultGenerateSettings,getDefaultReferenceImageConfig,getGenerateModelSelectionResult,+ getDimensionGridForBase,getGenerationDimensions,getGenerationModelAvailabilityReasons,getGenerationUiPolicy,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsxindex ce4cbc6e39..eaefc6b3ce 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx@@ -1,17 +1,27 @@import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';+import { Stack, Text } from '@chakra-ui/react';import { getDefaultGenerateSettings, isSupportedGenerateModel } from '@features/generation/core/baseGenerationPolicies';+import {+ ensureArchitectureCapabilitiesLoaded,+ useArchitectureCapabilitiesSelector,+} from '@features/generation/data/architectureCapabilitiesStore';import { isLoraModelConfig, normalizeGenerateSettings } from '@features/generation/core/settings';import { resolveGenerateWidgetValues } from '@features/generation/settings';+import { Button } from '@platform/ui/Button';import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';import { getGenerateFormCommitPatch } from './generateFormViewModel';import { GenerateSettingsForm } from './GenerateSettingsForm';import { useGenerationUi } from './GenerationUiContext';export const GenerateWidgetView = () => {+ const { t } = useTranslation();const ui = useGenerationUi();+ const capabilitiesStatus = useArchitectureCapabilitiesSelector((snapshot) => snapshot.status);+ const capabilitiesError = useArchitectureCapabilitiesSelector((snapshot) => snapshot.error);const projectId = ui.project.activeProjectId;const storedValues = ui.project.generateValues;const error = ui.models.error;@@ -55,6 +65,31 @@ export const GenerateWidgetView = () => {[projectId, ui]);+ // Every field below is prefilled from architecture policy and is editable, so rendering the form+ // before the backend's table arrives would offer generic fallbacks as if they were the model's+ // own -- and a single keystroke would commit them. App boot kicks the fetch, so this is one round+ // trip in practice.+ if (capabilitiesStatus !== 'loaded') {+ return (+ <Stack gap="1.5" p="1">+ {capabilitiesStatus === 'error' ? (+ <>+ <Text color="fg.error" fontSize="2xs">+ {capabilitiesError ?? t('widgets.generate.capabilitiesLoadFailed')}+ </Text>+ <Button size="xs" variant="outline" onClick={ensureArchitectureCapabilitiesLoaded}>+ {t('widgets.generate.retry')}+ </Button>+ </>+ ) : (+ <Text color="fg.subtle" fontSize="2xs">+ {t('widgets.generate.loadingCapabilities')}+ </Text>+ )}+ </Stack>+ );+ }+return (<GenerateSettingsFormisLoadingModels={status === 'idle' || status === 'loading'}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex fa1cf21f36..35251f2970 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -21,6 +21,7 @@ import { createInitialWorkbenchState, type WorkbenchAction } from '@workbench/woimport { describe, expect, it, vi } from 'vitest';import { importGalleryImagesToCanvas, type GalleryCanvasImportDestination } from './importGalleryImages';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const queriesFor = (getState: () => WorkbenchState) => ({getProject: (projectId: string) => getState().projects.find((project) => project.id === projectId) ?? null,@@ -213,6 +214,8 @@ const expectedLayer = (}};+useArchitectureCapabilitiesFixture();+describe('importGalleryImagesToCanvas', () => {it.each<Exclude<GalleryCanvasImportDestination, 'control-resized'>>(['raster',diff --git a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.ts b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.tsindex e6cd04d0d5..acf4a6b2c6 100644--- a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.ts+++ b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.ts@@ -8,6 +8,7 @@ import {getControlLayerAttentionReason,hasControlLayerContent,} from './controlLayerChecks';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const model = (key: string, base: string, type: string): ModelConfig => ({ base, key, name: key, type }) as ModelConfig;@@ -43,6 +44,8 @@ const controlLayer = (const sdxl = { base: 'sdxl' };const models = [model('sdxl-control', 'sdxl', 'controlnet'), model('sd1-control', 'sd-1', 'controlnet')];+useArchitectureCapabilitiesFixture();+describe('hasControlLayerContent', () => {it('matches the pipeline content gate', () => {expect(hasControlLayerContent(controlLayer('image'))).toBe(true);diff --git a/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.tsindex 887cfdf109..79450f6c20 100644--- a/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts@@ -9,6 +9,7 @@ import { getDefaultGenerateSettings } from '@features/generation/settings';import { describe, expect, it, vi } from 'vitest';import { recallProjectPromptHistoryItem, selectProjectGenerateModel } from './generationSettingsOrchestration';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const createModel = (base: string, key = `${base}-model`): GenerateModelConfig => ({base,@@ -27,6 +28,8 @@ const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSconst sdxlLora: LoraModelConfig = { base: 'sdxl', key: 'sdxl-lora', name: 'SDXL LoRA', type: 'lora' };const sdxlVae: VaeModelConfig = { base: 'sdxl', key: 'sdxl-vae', name: 'SDXL VAE', type: 'vae' };+useArchitectureCapabilitiesFixture();+describe('selectProjectGenerateModel', () => {it('atomically stores reconciled model settings and returns cleared labels', () => {const currentModel = createModel('sdxl');diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.tsindex bb2409d68e..6b892ae8ac 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts@@ -5,6 +5,7 @@ import { getDefaultGenerateSettings, getMaxReferenceImages } from '@features/genimport { describe, expect, it } from 'vitest';import { appendReferenceImage, type AppendReferenceImageResult } from './appendReferenceImage';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const sd1Model: MainModelConfig = {base: 'sd-1',@@ -25,6 +26,8 @@ const generateValuesFor = (referenceImages: unknown[] = []): Record<string, unknreferenceImages,});+useArchitectureCapabilitiesFixture();+describe('appendReferenceImage', () => {it('appends a reference image built from the flat upload result', () => {const result = appendReferenceImage({ generateValues: generateValuesFor(), image, models });diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.tsindex 4e0e831d67..4994778994 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts@@ -15,6 +15,7 @@ const galleryApi = vi.hoisted(() => ({vi.mock('@features/gallery', () => galleryApi);import { executeImageRecall } from './executeImageRecall';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const model = {base: 'sdxl',@@ -53,6 +54,8 @@ const createCommands = () => {return { add, commands, setSettings };};+useArchitectureCapabilitiesFixture();+describe('executeImageRecall', () => {beforeEach(() => {accountLifecycle.activate('test-account');diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex bee1b8a2fc..435fd95e41 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -9,6 +9,7 @@ import type {import { describe, expect, it } from 'vitest';import { buildImageRecallSettings, getImageRecallCapabilities } from './imageRecall';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };@@ -133,6 +134,8 @@ const metadata = {width: 513,};+useArchitectureCapabilitiesFixture();+describe('image recall', () => {it.each(['all', 'remix', 'prompts'] as const)('clears the active template and view mode when %s recalls prompt metadata',diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.tsindex 2fba396b8c..621f150d94 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts@@ -30,6 +30,7 @@ import {import { submitResolvedInvocation } from './invocationSubmit';import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';import { createWorkbenchStore } from './workbenchStore';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };const animaVae: VaeModelConfig = { base: 'qwen-image', key: 'anima-vae', name: 'Anima VAE', type: 'vae' };@@ -112,6 +113,8 @@ const getActiveProject = (values: GenerateWidgetValues) => {return project!;};+useArchitectureCapabilitiesFixture();+describe('resolveInvocationRoute', () => {it('invalidates Anima generation until required components are selected', () => {const missingComponentsRoute = resolveInvocationRoute(diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.tsindex 78476b0845..b7e4d812b7 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts@@ -13,6 +13,7 @@ import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbeimport { describe, expect, it } from 'vitest';import { buildGraphPreviewSource } from './graphPreviewSource';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const t = ((key: string) => key) as TFunction;@@ -56,6 +57,8 @@ const generateSurface = createGraphBearingSurface(generateWidgetManifest, 'left'const workflowSurface = createGraphBearingSurface(workflowWidgetManifest, 'left', 'Workflow')!;const canvasSurface = createGraphBearingSurface(canvasWidgetManifest, 'center', 'Canvas')!;+useArchitectureCapabilitiesFixture();+describe('buildGraphPreviewSource', () => {it('live-compiles the generate source and reports a seed notice when randomized', () => {const source = buildGraphPreviewSource({ models, project, surface: generateSurface, t, templates: idleTemplates });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.tsindex 85212707e7..3ccee56828 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts@@ -1,27 +1,37 @@import { describe, expect, it } from 'vitest';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { DEFAULT_MODEL_GRID, gridSizeForModelBase } from './bboxGrid';+useArchitectureCapabilitiesFixture();+describe('gridSizeForModelBase', () => {- it('maps flux-family and sd-3 bases to a 16px grid', () => {- for (const base of ['flux', 'flux2', 'sd-3', 'qwen-image', 'z-image']) {+ it('reads the grid the architecture declares', () => {+ // The same number the denoise node enforces through `multiple_of` on width/height.+ for (const base of ['flux', 'flux2', 'sd-3', 'qwen-image', 'z-image', 'ernie-image']) {expect(gridSizeForModelBase(base)).toBe(16);}- });- it('maps cogview4 to a 32px grid', () => {expect(gridSizeForModelBase('cogview4')).toBe(32);- });- it('maps sd/sdxl and unknown bases to the default 8px grid', () => {- for (const base of ['sd-1', 'sd-2', 'sdxl', 'anima', 'mystery-model']) {+ for (const base of ['sd-1', 'sd-2', 'sdxl', 'anima']) {expect(gridSizeForModelBase(base)).toBe(8);}});- it('falls back to the default grid for null/undefined', () => {+ it('no longer offers 8px steps for architectures that reject them', () => {+ // The drift this replaces: these three fell through to the default 8 here while their denoise+ // nodes carry multiple_of=16, so the canvas offered sizes that failed at enqueue time.+ for (const base of ['krea-2', 'wan', 'ideogram-4']) {+ expect(gridSizeForModelBase(base)).toBe(16);+ }+ });++ it('falls back to the default grid when there is no model or no row for its architecture', () => {expect(gridSizeForModelBase(null)).toBe(DEFAULT_MODEL_GRID);expect(gridSizeForModelBase(undefined)).toBe(DEFAULT_MODEL_GRID);+ expect(gridSizeForModelBase('mystery-model')).toBe(DEFAULT_MODEL_GRID);expect(DEFAULT_MODEL_GRID).toBe(8);});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.tsindex 7d0513024b..e090750227 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts@@ -1,31 +1,19 @@/**- * Maps a model base to the bbox snapping grid size (document px), mirroring the- * legacy `getGridSize` rule: generation dimensions must land on a base-specific- * multiple. React reads the active generate model's base and feeds the result- * into `engine.viewport.setBboxGrid`; the engine itself stays model-agnostic.+ * Maps a model base to the bbox snapping grid size (document px). React reads the active generate+ * model's base and feeds the result into `engine.viewport.setBboxGrid`; the engine itself stays+ * model-agnostic.+ *+ * The rule comes from the backend now, which is where it is enforced: each denoise node carries a+ * `multiple_of` on its width/height fields, and the architecture declares the same number. This+ * used to be a second, hand-maintained copy of that column -- and it had drifted, offering 8px+ * steps for krea-2, wan and ideogram-4, all of which reject anything but multiples of 16 at+ * enqueue time.*/-/** Default grid when no model is selected (or an unknown base). */+import { getDimensionGridForBase } from '@features/generation/settings';++/** Default grid when no model is selected, or the backend has no row for its architecture. */export const DEFAULT_MODEL_GRID = 8;-/**- * The bbox grid size for a model base:- * - `cogview4` → 32- * - `flux` / `flux2` / `sd-3` / `qwen-image` / `z-image` / `ernie-image` → 16- * - everything else (sd-1/sd-2/sdxl/anima/unknown) → 8- */-export const gridSizeForModelBase = (base: string | null | undefined): number => {- switch (base) {- case 'cogview4':- return 32;- case 'flux':- case 'flux2':- case 'sd-3':- case 'qwen-image':- case 'z-image':- case 'ernie-image':- return 16;- default:- return DEFAULT_MODEL_GRID;- }-};+export const gridSizeForModelBase = (base: string | null | undefined): number =>+ (base ? getDimensionGridForBase(base) : null) ?? DEFAULT_MODEL_GRID;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex ea33791a54..c1aee39a45 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -34,6 +34,7 @@ import {resolveRegionalReferenceImages,runCanvasInvocation,} from './prepareCanvasInvocation';+import { useArchitectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';const canvasBoundaryMocks = vi.hoisted(() => ({getCanvasEngine: vi.fn(),@@ -320,6 +321,8 @@ const controlLayer = (withTransparencyEffect: true,});+useArchitectureCapabilitiesFixture();+describe('prepareCanvasInvocation generation-device boundary', () => {beforeEach(() => {vi.restoreAllMocks();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 88fb24ee2f..01bc83a421 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -17,6 +17,7 @@ import { galleryImages, galleryTransfers } from '@features/gallery';import { invalidateGallery } from '@features/gallery/queries';import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';import { FluxReduxControls, PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generation/components';+import { isRegionalNegativeSupportedForBase } from '@features/generation/graph';import { useModelsSelector } from '@features/models';import {assertAccountScopeCurrent,@@ -108,10 +109,12 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst [negativePrompt, setNegativePrompt] = useState(layer.negativePrompt ?? '');const fill = layer.mask.fill;- const isFlux = base === 'flux';const isFlux2 = base === 'flux2';- const isFluxFamily = isFlux || isFlux2;- const showNegativeControls = !isFluxFamily || Boolean(layer.negativePrompt) || layer.autoNegative;+ // Asked as "is this the FLUX family?" before, which got krea-2 wrong: it rendered a regional+ // negative prompt and an Auto-Negative switch that `addRegionalGuidance` then discarded. The+ // graph builder and this control now read the same declaration.+ const supportsRegionalNegative = isRegionalNegativeSupportedForBase(base ?? '');+ const showNegativeControls = supportsRegionalNegative || Boolean(layer.negativePrompt) || layer.autoNegative;const showReferenceImages = !isFlux2 || layer.referenceImages.length > 0;const commitConfig = useCallback(diff --git a/tests/backend/architectures/test_vae.py b/tests/backend/architectures/test_vae.pynew file mode 100644index 0000000000..79e75c1b1e--- /dev/null+++ b/tests/backend/architectures/test_vae.py@@ -0,0 +1,117 @@+"""Which VAEs each architecture accepts, and that the loaders agree.++The facts here were duplicated three times before -- once per loader as `ui_model_base`, once in+webv2's VAE picker, once more in its related-models linker -- and all three disagreed. Anima's+loader declared nothing at all while its description named three families; FLUX.2 Klein's offered+FLUX VAEs that crash in `decode()`.+"""++import pytest++from invokeai.app.invocations.baseinvocation import InvocationRegistry+from invokeai.app.services.shared.graph import Graph # noqa: F401 -- imports every invocation+from invokeai.backend.architectures import generative_bases, get+from invokeai.backend.architectures.facets.vae import VaeFacet, accepts_vae+from invokeai.backend.model_manager.taxonomy import BaseModelType++# The loader that owns each architecture's VAE input. Architectures absent from this map take no+# standalone VAE: the SD family overrides it through model settings instead.+VAE_LOADER = {+ BaseModelType.Anima: "anima_model_loader",+ BaseModelType.Flux: "flux_model_loader",+ BaseModelType.Flux2: "flux2_klein_model_loader",+ BaseModelType.Krea2: "krea2_model_loader",+ BaseModelType.QwenImage: "qwen_image_model_loader",+ BaseModelType.StableDiffusion3: "sd3_model_loader",+ BaseModelType.Wan: "wan_model_loader",+ BaseModelType.ZImage: "z_image_model_loader",+}+++def _ui_model_bases() -> dict[str, list[str] | None]:+ out: dict[str, list[str] | None] = {}+ for cls in InvocationRegistry.get_invocation_classes():+ vae = cls.model_json_schema().get("properties", {}).get("vae_model")+ if vae is not None:+ out[cls.get_type()] = vae.get("ui_model_base")+ return out+++def test_the_declaration_and_the_loader_agree() -> None:+ """`ui_model_base` is what the UI filters on today; the facet is what it will filter on.++ While both exist they must say the same thing, or a model the graph accepts is hidden -- or+ worse, one it rejects is offered. `ui_model_base` cannot express a channel constraint, so the+ comparison is over bases; the channel rules are checked separately below.+ """+ ui_bases = _ui_model_bases()++ disagreements = []+ for base, node_type in sorted(VAE_LOADER.items(), key=lambda item: item[0].value):+ declared = ui_bases.get(node_type)+ if declared is None:+ continue # covered by test_every_loader_with_a_vae_input_declares_its_bases++ facet = get(base, VaeFacet)+ accepted = facet.accepted_bases if facet else frozenset({base})+ if {b.value for b in accepted} != set(declared):+ disagreements.append(+ f"{base.value}: facet accepts {sorted(b.value for b in accepted)}, "+ f"{node_type} offers {sorted(declared)}"+ )++ assert disagreements == []+++def test_flux2_no_longer_offers_a_vae_that_crashes() -> None:+ """Klein advertised FLUX VAEs. Decoding a FLUX.2 latent with one raises+ `AutoEncoder.decode() got an unexpected keyword argument 'return_dict'` -- the legacy FLUX+ `AutoEncoder` against a 32-channel latent. Verified by generating with it."""+ assert accepts_vae(BaseModelType.Flux2, BaseModelType.Flux2) is True+ assert accepts_vae(BaseModelType.Flux2, BaseModelType.Flux) is False+++def test_anima_accepts_both_families_it_actually_handles() -> None:+ """`anima_l2i` branches on `isinstance(vae, (AutoencoderKLWan, FluxAutoEncoder))`, each with its+ own working-memory estimate. The Wan-family file is registered under any of three bases."""+ for vae_base in (BaseModelType.Anima, BaseModelType.QwenImage, BaseModelType.Flux):+ assert accepts_vae(BaseModelType.Anima, vae_base) is True, vae_base.value++ assert accepts_vae(BaseModelType.Anima, BaseModelType.Wan, 16) is True+ # TI2V-5B's Wan2.2-VAE is the same class but a 48-channel latent space; it fits nothing else.+ assert accepts_vae(BaseModelType.Anima, BaseModelType.Wan, 48) is False+++def test_an_architecture_without_the_facet_accepts_only_its_own_base() -> None:+ assert accepts_vae(BaseModelType.StableDiffusionXL, BaseModelType.StableDiffusionXL) is True+ assert accepts_vae(BaseModelType.StableDiffusionXL, BaseModelType.Flux) is False++[email protected]("base", sorted(VAE_LOADER, key=lambda b: b.value))+def test_every_loader_with_a_vae_input_declares_its_bases(base: BaseModelType) -> None:+ """Anima's did not, so nothing constrained its picker and the two frontend copies drifted."""+ assert _ui_model_bases().get(VAE_LOADER[base]) is not None, (+ f"{VAE_LOADER[base]} takes a VAE but declares no `ui_model_base`, so the UI offers every "+ f"VAE ever installed. Declare it, and keep it in step with {base.value}'s VaeFacet."+ )+++def test_the_facet_is_only_declared_where_it_says_something_new() -> None:+ """A facet repeating "its own base, no constraints" would be noise; `accepts_vae` says that+ already for every architecture without one.++ Wan declares only its own base and is *not* redundant: it carries the channel split that tells+ A14B's 16-channel VAE from TI2V-5B's 48-channel one.+ """+ redundant = []+ for base in generative_bases():+ facet = get(base, VaeFacet)+ if facet is None:+ continue+ says_nothing_new = facet.accepted_bases == frozenset({base}) and all(+ entry.latent_channels is None for entry in facet.accepted+ )+ if says_nothing_new:+ redundant.append(base.value)++ assert redundant == []diff --git a/tests/backend/model_manager/load/test_qwen_image_vae_layout.py b/tests/backend/model_manager/load/test_qwen_image_vae_layout.pynew file mode 100644index 0000000000..1494af2505--- /dev/null+++ b/tests/backend/model_manager/load/test_qwen_image_vae_layout.py@@ -0,0 +1,61 @@+"""The Qwen-Image VAE loader picks its path from the checkpoint's key layout, not from its base.++Two layouts are in circulation for the same 16-channel autoencoder. Files exported from the+Qwen-Image repo carry diffusers keys (`decoder.conv_in.weight`); community redistributions carry the+original layout (`decoder.conv1.weight`) and need converting.++Only the first was handled, with `strict=True`, so a redistributed file failed with 194 missing keys+-- while the byte-identical checkpoint installed under `anima` loaded fine, because that path uses+`AutoencoderKLWan.from_single_file`, which converts. Whether a VAE worked came down to which base it+happened to be probed as.+"""++from unittest.mock import MagicMock, patch++import torch++from invokeai.backend.model_manager.load.model_loaders.vae import VAELoader+++def _loader() -> VAELoader:+ loader = VAELoader.__new__(VAELoader)+ loader._torch_dtype = torch.float16 # type: ignore[attr-defined]+ loader._ram_cache = MagicMock() # type: ignore[attr-defined]+ return loader+++def _config(path: str = "vae.safetensors") -> MagicMock:+ config = MagicMock()+ config.path = path+ return config+++def test_the_original_layout_is_converted_rather_than_rejected() -> None:+ state_dict = {"decoder.conv1.weight": torch.zeros(1), "encoder.conv1.weight": torch.zeros(1)}++ with (+ patch("safetensors.torch.load_file", return_value=state_dict),+ patch("diffusers.models.autoencoders.AutoencoderKLWan") as wan,+ patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),+ ):+ result = _loader()._load_qwen_image_vae(_config())++ wan.from_single_file.assert_called_once()+ assert result is wan.from_single_file.return_value+++def test_the_diffusers_layout_still_loads_directly() -> None:+ """`AutoencoderKLQwenImage` registers no single-file conversion, so this path stays."""+ state_dict = {"decoder.conv_in.weight": torch.zeros(1)}++ with (+ patch("safetensors.torch.load_file", return_value=state_dict),+ patch("accelerate.init_empty_weights"),+ patch("diffusers.models.autoencoders.autoencoder_kl_qwenimage.AutoencoderKLQwenImage") as qwen,+ patch("diffusers.models.autoencoders.AutoencoderKLWan") as wan,+ ):+ result = _loader()._load_qwen_image_vae(_config())++ wan.from_single_file.assert_not_called()+ qwen.return_value.load_state_dict.assert_called_once()+ assert result is qwen.return_value