Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(architectures): serve only what webv2 reads, and per-variant Wan VAEs
Alexander Eichhornbe92d1819b9e
diff --git a/invokeai/backend/architectures/__init__.py b/invokeai/backend/architectures/__init__.pyindex 0ea730afa1..97ad2985f4 100644--- a/invokeai/backend/architectures/__init__.py+++ b/invokeai/backend/architectures/__init__.py@@ -9,7 +9,6 @@ from invokeai.backend.architectures import facets as facets # noqa: F401 (impofrom invokeai.backend.architectures.capabilities import (ArchitectureCapabilities,ArchitectureFeatures,- ArchitectureModality,NegativePromptPolicy,architecture_capabilities,)@@ -61,7 +60,6 @@ from invokeai.backend.architectures.registry import (__all__ = ["ArchitectureCapabilities","ArchitectureFeatures",- "ArchitectureModality","NegativePromptPolicy","architecture_capabilities","ArchitectureError",diff --git a/invokeai/backend/architectures/capabilities.py b/invokeai/backend/architectures/capabilities.pyindex e75f4a755c..8ff60dc67f 100644--- a/invokeai/backend/architectures/capabilities.py+++ b/invokeai/backend/architectures/capabilities.py@@ -13,6 +13,10 @@ fields on a schema webv2 already consumes.Also deliberately not a computed field on `AnyModelConfig`: that would add these fields to all 115config schemas and risk them being persisted into model records.+Only what a client reads is served. The registry knows more -- the modes an architecture generates+in, its metadata prefix, its latent compression -- and those stay backend facts until a client has+a use for them: a field nobody reads is a contract nobody checks, and it goes stale unnoticed.+The models here are response-only and stay open. `extra="forbid"` on one would reject nothing atruntime -- nothing parses these -- and only stamp `additionalProperties: false` into `openapi.json`,which turns every field this table grows into a breaking change for a strictly-validating client.@@ -27,8 +31,6 @@ from invokeai.backend.architectures.facets.features import (NegativePromptUsage,SchedulerSet,)-from invokeai.backend.architectures.facets.latent_space import LatentSpaceFacet-from invokeai.backend.architectures.facets.modality import GenerationModeKind, ModalityFacetfrom invokeai.backend.architectures.facets.vae import VaeFacetfrom invokeai.backend.architectures.registry import generative_bases, get, requirefrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings@@ -42,16 +44,6 @@ class NegativePromptPolicy(BaseModel):)-class ArchitectureModality(BaseModel):- """What this architecture can produce, and what it calls it in image metadata."""-- modes: list[GenerationModeKind] = Field(description="Sorted. Empty means it generates nothing on its own.")- metadata_slug: str | None = Field(- default=None,- description="Prefix its mode strings carry in image metadata; null means unprefixed.",- )--class ArchitectureFeatures(BaseModel):"""What a UI may offer for this architecture."""@@ -59,7 +51,6 @@ class ArchitectureFeatures(BaseModel):dimension_grid: int = Field(description="Width and height must be a multiple of this. A variant row may carry its own.")- spatial_compression: int = Field(description="How much smaller a latent is than the image, per side.")guidance_label: str = Field(description="What to call the guidance slider: 'CFG' or 'Guidance'.")guidance_min: float = Field(description="Lowest guidance value the denoise node accepts; a smaller one fails at enqueue."@@ -79,7 +70,9 @@ class ArchitectureFeatures(BaseModel):description="If set, reference images are only accepted for models of this variant.",)supports_regional_guidance: bool = False- regional_negative: bool = False+ regional_negative: bool = Field(+ default=False, description="Whether a region's negative prompt is masked, rather than applied globally."+ )clip_skip_max: int | None = Nonesupports_seamless: bool = Falsesupports_cfg_rescale: bool = False@@ -102,7 +95,8 @@ class ArchitectureVae(BaseModel):"""Which VAEs an architecture's decode accepts, beyond its own base.Served because the clients keep their own copy of this and it drifts: widening a backend list- without the picker leaves a VAE that loads but cannot be chosen.+ without the picker leaves a VAE that loads but cannot be chosen. A variant row carries its own+ list where its decoder differs -- Wan TI2V-5B takes the 48-channel VAE, A14B the 16-channel one."""accepted: list[VaeAcceptance]@@ -116,7 +110,6 @@ class ArchitectureCapabilities(BaseModel):default=None,description="Null for the architecture's own row. A variant row overrides it.",)- modality: ArchitectureModalityfeatures: ArchitectureFeaturesdefaults: MainModelDefaultSettings | None = Field(default=None, description="Recommended generation parameters, if the architecture has any."@@ -126,19 +119,13 @@ class ArchitectureCapabilities(BaseModel):)-def _features_of(- facet: FeaturesFacet, latent_space: LatentSpaceFacet, variant: AnyVariant | None = None-) -> ArchitectureFeatures:- # Resolved per row, not once per architecture: Wan TI2V-5B denoises in the 48-channel Wan2.2- # space at 16x where A14B is 16 channels at 8x, and a client joining on `(base, variant)`- # would otherwise read its base's compression.+def _features_of(facet: FeaturesFacet, variant: AnyVariant | None = None) -> ArchitectureFeatures:return ArchitectureFeatures(negative_prompt=NegativePromptPolicy(visible=facet.negative_prompt.visible,usage=facet.negative_prompt.usage,),dimension_grid=facet.resolve_dimension_grid(variant),- spatial_compression=latent_space.resolve_variant(variant).spatial_compression,guidance_label=facet.guidance_label,guidance_min=facet.guidance_min,guidance_max=facet.guidance_max,@@ -158,14 +145,26 @@ def _features_of()+def _vae_of(facet: VaeFacet | None, variant: AnyVariant | None = None) -> ArchitectureVae | None:+ # Optional: most architectures accept only their own base, which needs no row.+ if facet is None:+ return None+ return ArchitectureVae(+ accepted=[+ VaeAcceptance(base=c.base, latent_channels=c.latent_channels)+ for c in sorted(facet.resolve(variant), key=lambda c: (c.base.value, c.latent_channels or 0))+ ]+ )++def architecture_capabilities() -> list[ArchitectureCapabilities]:"""Every row, base rows first, then the variant rows that override them.- A variant gets its own row only where something actually differs: its recommended parameters- (`DefaultSettingsFacet.by_variant`) or its dimension grid- (`FeaturesFacet.dimension_grid_by_variant`). Those two mappings are the whole rule — a row is- emitted for the union of their keys, and every row is rendered in full, so a client never has to- know which fields a variant row is allowed to omit.+ A variant gets its own row only where something served actually differs: its recommended+ parameters (`DefaultSettingsFacet.by_variant`), its dimension grid+ (`FeaturesFacet.dimension_grid_by_variant`) or the VAEs it decodes with (`VaeFacet.by_variant`).+ Those mappings are the whole rule — a row is emitted for the union of their keys, and every row+ is rendered in full, so a client never has to know which fields a variant row is allowed to omit.Differences too small to have earned a mapping are expressed on the base row instead, by`features.reference_images_require_variant`; Qwen-Image is the only one.@@ -174,40 +173,26 @@ def architecture_capabilities() -> list[ArchitectureCapabilities]:"""rows: list[ArchitectureCapabilities] = []for base in sorted(generative_bases(), key=lambda b: b.value):- # All four are REQUIRED, so `validate()` has already refused to start without them.+ # Both are REQUIRED, so `validate()` has already refused to start without them.# `require()` rather than `assert`: this is an API path, and `python -O` drops asserts.- modality = require(base, ModalityFacet)features = require(base, FeaturesFacet)- latent_space = require(base, LatentSpaceFacet)defaults = require(base, DefaultSettingsFacet)-- rendered = ArchitectureModality(modes=sorted(modality.modes), metadata_slug=modality.metadata_slug)+ vae_facet = get(base, VaeFacet)base_defaults = defaults.resolve()- # Optional: most architectures accept only their own base, which needs no row.- vae_facet = get(base, VaeFacet)- rendered_vae = (- ArchitectureVae(- accepted=[- VaeAcceptance(base=c.base, latent_channels=c.latent_channels)- for c in sorted(vae_facet.accepted, key=lambda c: (c.base.value, c.latent_channels or 0))- ]- )- if vae_facet is not None- else None- )rows.append(ArchitectureCapabilities(base=base,- modality=rendered,- features=_features_of(features, latent_space),+ features=_features_of(features),defaults=base_defaults,- vae=rendered_vae,+ vae=_vae_of(vae_facet),))differing = (- set(defaults.by_variant) | set(features.dimension_grid_by_variant) | set(latent_space.by_variant)+ set(defaults.by_variant)+ | set(features.dimension_grid_by_variant)+ | set(vae_facet.by_variant if vae_facet is not None else ())) - {None}for variant in sorted(differing):rows.append(@@ -216,10 +201,9 @@ def architecture_capabilities() -> list[ArchitectureCapabilities]:# `.value`, not `str()`: these are `str`-mixin enums, and `str()` on one yields# "FluxVariantType.DevFill" rather than the "dev_fill" a client stores and sends.variant=variant.value,- modality=rendered,- features=_features_of(features, latent_space, variant),+ features=_features_of(features, variant),defaults=defaults.by_variant.get(variant, base_defaults),- vae=rendered_vae,+ vae=_vae_of(vae_facet, variant),))return rowsdiff --git a/invokeai/backend/architectures/defs/wan.py b/invokeai/backend/architectures/defs/wan.pyindex 252d520ae7..b9b3907f6e 100644--- a/invokeai/backend/architectures/defs/wan.py+++ b/invokeai/backend/architectures/defs/wan.py@@ -53,16 +53,12 @@ register(guidance_min=1.0,scheduler_set="flow",),+ # A14B uses the 16-channel Wan 2.1 VAE; TI2V-5B needs the 48-channel Wan2.2-VAE, and+ # `wan_model_loader` rejects either the other way round. Both are registered under `wan`, so+ # the channel count is the only thing that tells them apart.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),- }- )+ frozenset({VaeCompatibility(BaseModelType.Wan, latent_channels=16)}),+ by_variant={WanVariantType.TI2V_5B: frozenset({VaeCompatibility(BaseModelType.Wan, latent_channels=48)})},),# The one architecture whose LoRAs carry a different variant enum from its mains. They are not# interchangeable: an A14B LoRA (inner_dim=5120) against a TI2V-5B main (3072) crashes in thediff --git a/invokeai/backend/architectures/facets/vae.py b/invokeai/backend/architectures/facets/vae.pyindex 0c6219cb7e..fea5b0b896 100644--- a/invokeai/backend/architectures/facets/vae.py+++ b/invokeai/backend/architectures/facets/vae.py@@ -10,14 +10,19 @@ Nor is it derivable from the VAE's `base` alone. The same physical file is registensors -- and a `wan` VAE may be either the 16-channel Wan 2.1 file (the same family again) orTI2V-5B's 48-channel Wan2.2-VAE, which fits nothing else. `VAE_Checkpoint_Wan_Config` alreadyrecords `latent_channels`; this facet is what finally reads it.++Nor, for Wan, is it a property of the architecture: A14B decodes with the 16-channel VAE and+TI2V-5B with the 48-channel one, and `wan_model_loader` rejects the other pairing. `by_variant`+says so, the same way `FeaturesFacet.dimension_grid_by_variant` does for the grid."""-from dataclasses import dataclass+from collections.abc import Mapping+from dataclasses import dataclass, fieldfrom typing import ClassVarfrom invokeai.backend.architectures.facet import Facetfrom invokeai.backend.architectures.registry import get-from invokeai.backend.model_manager.taxonomy import BaseModelType+from invokeai.backend.model_manager.taxonomy import AnyVariant, BaseModelType@dataclass(frozen=True)@@ -53,19 +58,52 @@ class VaeFacet(Facet):REQUIRED: ClassVar[bool] = Falseaccepted: 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)+ """What the architecture accepts, and what any variant not named in `by_variant` accepts."""++ by_variant: Mapping[AnyVariant, frozenset[VaeCompatibility]] = field(default_factory=dict)+ """A variant whose decoder is a different one. Replaces `accepted` for that variant, never extends it."""++ def __post_init__(self) -> None:+ if None in self.by_variant:+ raise ValueError(+ "VaeFacet.by_variant has a None key. `accepted` is the answer for every variant not "+ "named here, so a None key would never be read."+ )++ empty = sorted(+ str(getattr(variant, "value", variant)) for variant, entries in self.by_variant.items() if not entries+ )+ if not self.accepted or empty:+ raise ValueError(+ f"VaeFacet accepts no VAE at all for {', '.join(empty) or 'the architecture itself'}. The picker "+ "would offer nothing and a model that needs a VAE could never generate."+ )++ def resolve(self, variant: AnyVariant | None = None) -> frozenset[VaeCompatibility]:+ if variant is None:+ return self.accepted+ return self.by_variant.get(variant, self.accepted)++ def accepts(+ self, vae_base: BaseModelType, vae_latent_channels: int | None = None, variant: AnyVariant | None = None+ ) -> bool:+ return any(entry.matches(vae_base, vae_latent_channels) for entry in self.resolve(variant))@propertydef 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)+ """The bases alone, across every variant, for comparing against a loader's `ui_model_base` --+ one loader serves all variants and cannot express a channel constraint."""+ entries = self.accepted.union(*self.by_variant.values())+ return frozenset(entry.base for entry in entries)-def accepts_vae(base: BaseModelType, vae_base: BaseModelType, vae_latent_channels: int | None = None) -> bool:- """Whether `base` can decode with this VAE.+def accepts_vae(+ base: BaseModelType,+ vae_base: BaseModelType,+ vae_latent_channels: int | None = None,+ variant: AnyVariant | None = None,+) -> bool:+ """Whether a model of `base` (and `variant`, where it matters) can decode with this VAE.Architectures that declare no `VaeFacet` accept only their own base -- the SD family andanything whose loader has no VAE input at all.@@ -75,4 +113,4 @@ def accepts_vae(base: BaseModelType, vae_base: BaseModelType, vae_latent_channelif facet is None:return vae_base == base- return facet.accepts(vae_base, vae_latent_channels)+ return facet.accepts(vae_base, vae_latent_channels, variant)diff --git a/invokeai/backend/model_manager/load/model_loaders/vae.py b/invokeai/backend/model_manager/load/model_loaders/vae.pyindex 7dd8554094..3317006697 100644--- a/invokeai/backend/model_manager/load/model_loaders/vae.py+++ b/invokeai/backend/model_manager/load/model_loaders/vae.py@@ -407,10 +407,11 @@ class VAELoader(GenericDiffusersLoader):sd = _read_checkpoint(config.path)- if self._torch_dtype is not None:- for k in list(sd.keys()):- if sd[k].is_floating_point():- sd[k] = sd[k].to(self._torch_dtype)+ # The same autoencoder as the Wan-family layout above, so the same precision policy.+ dtype = _wan_family_dtype(self._torch_dtype)+ for k in list(sd.keys()):+ if sd[k].is_floating_point():+ sd[k] = sd[k].to(dtype)new_sd_size = sum(t.nelement() * t.element_size() for t in sd.values())self._ram_cache.make_room(new_sd_size)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex c147c282e9..6482ab2e0d 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -17799,9 +17799,6 @@"title": "Variant","description": "Null for the architecture's own row. A variant row overrides it."},- "modality": {- "$ref": "#/components/schemas/ArchitectureModality"- },"features": {"$ref": "#/components/schemas/ArchitectureFeatures"},@@ -17829,7 +17826,7 @@}},"type": "object",- "required": ["base", "modality", "features"],+ "required": ["base", "features"],"title": "ArchitectureCapabilities","description": "One row of the table."},@@ -17843,11 +17840,6 @@"title": "Dimension Grid","description": "Width and height must be a multiple of this. A variant row may carry its own."},- "spatial_compression": {- "type": "integer",- "title": "Spatial Compression",- "description": "How much smaller a latent is than the image, per side."- },"guidance_label": {"type": "string","title": "Guidance Label",@@ -17922,6 +17914,7 @@"regional_negative": {"type": "boolean","title": "Regional Negative",+ "description": "Whether a region's negative prompt is masked, rather than applied globally.","default": false},"clip_skip_max": {@@ -17962,51 +17955,10 @@}},"type": "object",- "required": ["negative_prompt", "dimension_grid", "spatial_compression", "guidance_label", "guidance_min"],+ "required": ["negative_prompt", "dimension_grid", "guidance_label", "guidance_min"],"title": "ArchitectureFeatures","description": "What a UI may offer for this architecture."},- "ArchitectureModality": {- "properties": {- "modes": {- "items": {- "type": "string",- "enum": [- "txt2img",- "img2img",- "inpaint",- "outpaint",- "t2v",- "i2v",- "lf2v",- "flf2v",- "interpolate",- "extend_video",- "ref2v"- ]- },- "type": "array",- "title": "Modes",- "description": "Sorted. Empty means it generates nothing on its own."- },- "metadata_slug": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "title": "Metadata Slug",- "description": "Prefix its mode strings carry in image metadata; null means unprefixed."- }- },- "type": "object",- "required": ["modes"],- "title": "ArchitectureModality",- "description": "What this architecture can produce, and what it calls it in image metadata."- },"ArchitectureVae": {"properties": {"accepted": {@@ -18020,7 +17972,7 @@"type": "object","required": ["accepted"],"title": "ArchitectureVae",- "description": "Which VAEs an architecture's decode accepts, beyond its own base.\n\nServed because the clients keep their own copy of this and it drifts: widening a backend list\nwithout the picker leaves a VAE that loads but cannot be chosen."+ "description": "Which VAEs an architecture's decode accepts, beyond its own base.\n\nServed because the clients keep their own copy of this and it drifts: widening a backend list\nwithout the picker leaves a VAE that loads but cannot be chosen. A variant row carries its own\nlist where its decoder differs -- Wan TI2V-5B takes the 48-channel VAE, A14B the 16-channel one."},"BaseMetadata": {"properties": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex b07fa4f00d..9fbe6e7e16 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -5171,7 +5171,6 @@ export type components = {* @description Null for the architecture's own row. A variant row overrides it.*/variant?: string | null;- modality: components["schemas"]["ArchitectureModality"];features: components["schemas"]["ArchitectureFeatures"];/** @description Recommended generation parameters, if the architecture has any. */defaults?: components["schemas"]["MainModelDefaultSettings"] | null;@@ -5189,11 +5188,6 @@ export type components = {* @description Width and height must be a multiple of this. A variant row may carry its own.*/dimension_grid: number;- /**- * Spatial Compression- * @description How much smaller a latent is than the image, per side.- */- spatial_compression: number;/*** Guidance Label* @description What to call the guidance slider: 'CFG' or 'Guidance'.@@ -5241,6 +5235,7 @@ export type components = {supports_regional_guidance?: boolean;/*** Regional Negative+ * @description Whether a region's negative prompt is masked, rather than applied globally.* @default false*/regional_negative?: boolean;@@ -5272,28 +5267,13 @@ export type components = {*/vae_precision?: boolean;};- /**- * ArchitectureModality- * @description What this architecture can produce, and what it calls it in image metadata.- */- ArchitectureModality: {- /**- * Modes- * @description Sorted. Empty means it generates nothing on its own.- */- modes: ("txt2img" | "img2img" | "inpaint" | "outpaint" | "t2v" | "i2v" | "lf2v" | "flf2v" | "interpolate" | "extend_video" | "ref2v")[];- /**- * Metadata Slug- * @description Prefix its mode strings carry in image metadata; null means unprefixed.- */- metadata_slug?: string | null;- };/*** ArchitectureVae* @description Which VAEs an architecture's decode accepts, beyond its own base.** Served because the clients keep their own copy of this and it drifts: widening a backend list- * without the picker leaves a VAE that loads but cannot be chosen.+ * without the picker leaves a VAE that loads but cannot be chosen. A variant row carries its own+ * list where its decoder differs -- Wan TI2V-5B takes the 48-channel VAE, A14B the 16-channel one.*/ArchitectureVae: {/** Accepted */diff --git a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.jsonindex 5f69255a09..0f85d1e155 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json@@ -2,22 +2,12 @@{"base": "anima","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "anima"- },"features": {"negative_prompt": {"visible": true,"usage": "cfg-gated"},"dimension_grid": 8,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 1.0,"guidance_max": null,@@ -68,22 +58,12 @@{"base": "cogview4","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "cogview4"- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 32,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -119,19 +99,12 @@{"base": "ernie-image","variant": null,- "modality": {- "modes": [- "txt2img"- ],- "metadata_slug": "ernie_image"- },"features": {"negative_prompt": {"visible": true,"usage": "cfg-gated"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 1.0,"guidance_max": null,@@ -167,22 +140,12 @@{"base": "flux","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "flux"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": null,@@ -221,22 +184,12 @@{"base": "flux","variant": "dev_fill",- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "flux"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": null,@@ -275,22 +228,12 @@{"base": "flux","variant": "schnell",- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "flux"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": null,@@ -329,22 +272,12 @@{"base": "flux2","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "flux2"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": 20.0,@@ -380,22 +313,12 @@{"base": "flux2","variant": "dev",- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "flux2"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": 20.0,@@ -431,22 +354,12 @@{"base": "flux2","variant": "klein_4b_base",- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "flux2"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": 20.0,@@ -482,22 +395,12 @@{"base": "flux2","variant": "klein_9b_base",- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "flux2"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": 20.0,@@ -533,19 +436,12 @@{"base": "ideogram-4","variant": null,- "modality": {- "modes": [- "txt2img"- ],- "metadata_slug": "ideogram4"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": null,@@ -581,22 +477,12 @@{"base": "krea-2","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "krea2"- },"features": {"negative_prompt": {"visible": true,"usage": "cfg-gated"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -643,22 +529,12 @@{"base": "krea-2","variant": "krea2_base",- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "krea2"- },"features": {"negative_prompt": {"visible": true,"usage": "cfg-gated"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -705,25 +581,12 @@{"base": "minimax-h3","variant": null,- "modality": {- "modes": [- "extend_video",- "flf2v",- "i2v",- "lf2v",- "ref2v",- "t2v",- "txt2img"- ],- "metadata_slug": "minimax_h3"- },"features": {"negative_prompt": {"visible": false,"usage": "never"},"dimension_grid": 32,- "spatial_compression": 16,"guidance_label": "Guidance","guidance_min": 0.0,"guidance_max": null,@@ -759,22 +622,12 @@{"base": "qwen-image","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "qwen_image"- },"features": {"negative_prompt": {"visible": true,"usage": "cfg-gated"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -821,22 +674,12 @@{"base": "sd-1","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": null- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 8,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -875,22 +718,12 @@{"base": "sd-2","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": null- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 8,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -926,22 +759,12 @@{"base": "sd-3","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "sd3"- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -977,22 +800,12 @@{"base": "sdxl","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "sdxl"- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 8,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -1031,17 +844,12 @@{"base": "sdxl-refiner","variant": null,- "modality": {- "modes": [],- "metadata_slug": null- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 8,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 0.0,"guidance_max": null,@@ -1077,26 +885,12 @@{"base": "wan","variant": null,- "modality": {- "modes": [- "extend_video",- "i2v",- "img2img",- "inpaint",- "interpolate",- "outpaint",- "t2v",- "txt2img"- ],- "metadata_slug": "wan"- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "Guidance","guidance_min": 1.0,"guidance_max": null,@@ -1132,10 +926,6 @@{"base": "wan","latent_channels": 16- },- {- "base": "wan",- "latent_channels": 48}]}@@ -1143,26 +933,12 @@{"base": "wan","variant": "ti2v_5b",- "modality": {- "modes": [- "extend_video",- "i2v",- "img2img",- "inpaint",- "interpolate",- "outpaint",- "t2v",- "txt2img"- ],- "metadata_slug": "wan"- },"features": {"negative_prompt": {"visible": true,"usage": "always"},"dimension_grid": 32,- "spatial_compression": 16,"guidance_label": "Guidance","guidance_min": 1.0,"guidance_max": null,@@ -1195,10 +971,6 @@},"vae": {"accepted": [- {- "base": "wan",- "latent_channels": 16- },{"base": "wan","latent_channels": 48@@ -1209,22 +981,12 @@{"base": "z-image","variant": null,- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "z_image"- },"features": {"negative_prompt": {"visible": true,"usage": "cfg-gated"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 1.0,"guidance_max": null,@@ -1269,22 +1031,12 @@{"base": "z-image","variant": "zbase",- "modality": {- "modes": [- "img2img",- "inpaint",- "outpaint",- "txt2img"- ],- "metadata_slug": "z_image"- },"features": {"negative_prompt": {"visible": true,"usage": "cfg-gated"},"dimension_grid": 16,- "spatial_compression": 8,"guidance_label": "CFG","guidance_min": 1.0,"guidance_max": null,diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.tsindex 9bfdbf5f23..c746b6ca45 100644--- a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts@@ -24,14 +24,9 @@ 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 & {});/** The floor the denoise node enforces on the guidance field; `0` where it enforces none. */guidance_min: number;@@ -68,7 +63,8 @@ export interface ArchitectureCapabilitiesRow {/*** Which VAEs this architecture's decode accepts beyond its own base, or null where it accepts* only its own. `latent_channels` is null unless the base ships VAEs of more than one width;- * today only `wan` does, and its two are different decoders.+ * today only `wan` does, and its two are different decoders -- which is why the `ti2v_5b` row+ * carries its own list.*/vae: {accepted: { base: string; latent_channels: number | null }[];diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex eea8651c4f..5e92501478 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -947,6 +947,40 @@ describe('component policies', () => {).toBe(5);});+ it('validates the reference image count against the served limit, not a local default', () => {+ // Every image base serves 5 today, which is also the old local default -- so a table that serves+ // a different number is the only way to tell "reads the table" from "happens to agree with it".+ setArchitectureCapabilities(+ architectureCapabilitiesFixture.map((row) =>+ row.base === 'sdxl' ? { ...row, features: { ...row.features, max_reference_images: 2 } } : row+ )+ );+ const model = createModel('sdxl');+ const ipAdapterReference = (index: number) => ({+ config: {+ beginEndStepPct: [0, 1] as [number, number],+ clipVisionModel: 'ViT-H' as const,+ image: referenceImage,+ method: 'full' as const,+ model: sdxlIpAdapter,+ type: 'ip_adapter' as const,+ weight: 1,+ },+ id: `ref-${index}`,+ isEnabled: true,+ });+ const countReasons = (count: number) =>+ getGenerationValidationReasons(+ model,+ createSettings(model, {+ referenceImages: Array.from({ length: count }, (_, index) => ipAdapterReference(index)),+ })+ ).filter((reason) => reason.startsWith('Generate supports at most'));++ expect(countReasons(2)).toEqual([]);+ expect(countReasons(3)).toEqual(['Generate supports at most 2 reference images for sdxl model.']);+ });+it('rejects unsupported reference image configs for the selected model', () => {const model = createModel('sd-3');diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 2932d77b8c..d61f50a46d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -954,7 +954,7 @@ const getBaseComponentSectionPolicy = (}// The graph builder sends a VAE by `isVaeCompatibleWithGenerateModel`, which reads the same row.- const isAcceptedVae = isVaeAcceptedByBase(model.base);+ const isAcceptedVae = isVaeAcceptedByBase(model.base, model.variant);switch (model.base) {case 'flux':@@ -1601,12 +1601,11 @@ const getPidValidationReasons = (model: GenerateModelConfig, settings: GenerateSconst getReferenceImageValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {const reasons: string[] = [];const enabled = settings.referenceImages.filter((referenceImage) => referenceImage.isEnabled);- const maxReferenceImages =- model.type === 'external_image_generator' && typeof model.capabilities?.max_reference_images === 'number'- ? model.capabilities.max_reference_images- : DEFAULT_REFERENCE_IMAGE_LIMIT;+ // The limit the reference-image panel enforces, so validation cannot pass what the panel refuses.+ // A model without reference images is reported per image below rather than as "at most 0".+ const maxReferenceImages = getMaxReferenceImages(model);- if (enabled.length > maxReferenceImages) {+ if (isReferenceImageSupported(model) && enabled.length > maxReferenceImages) {reasons.push(`Generate supports at most ${maxReferenceImages} reference images for ${model.name}.`);}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 2c282513e7..edcfd0e54c 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@@ -192,18 +192,6 @@ describe('isRegionalGuidanceSupportedForBase', () => {});describe('the support matrix and the served capabilities', () => {- // The graph builder decides regional negatives from the matrix while the layer settings UI asks- // the backend. They agreed when this merge landed only because the facets were corrected for- // sd-2, z-image and anima; nothing else keeps them from drifting apart again.- it('answer regional negatives identically for every base the matrix covers', () => {- for (const row of architectureCapabilitiesFixture) {- const support = getRegionalGuidanceSupport(row.base);- if (support !== null) {- expect(support.negativePrompt, row.base).toBe(row.features.regional_negative);- }- }- });-// isRegionalGuidanceSupportedForBase asserts `base is RegionalGuidanceBase` from the backend's// answer, and getRegionalGuidanceSupport then indexes the matrix on that assertion. A base the// backend declares supported but the matrix has no row for would hand callers an undefined typeddiff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tsindex 534c922526..ba2ead1170 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts@@ -30,20 +30,22 @@ export interface RegionalGuidanceSupport {}/**- * Mirrors the backend: `compel` / `sdxl_compel_prompt` + `denoise_latents` mask both- * prompt polarities; FLUX / FLUX.2 / Krea-2 / Z-Image / Anima denoisers mask positive- * conditioning only (Z-Image and Anima accept negative lists but discard their masks,- * so a "regional" negative there would silently act globally and is rejected instead).+ * The graph half of the support matrix: what a region's reference images become, and what to call+ * the base. Whether a region's negative is masked is the backend's answer (`regional_negative`), not+ * this table's -- see {@link getRegionalGuidanceSupport}.*/-const REGIONAL_GUIDANCE_SUPPORT: Record<RegionalGuidanceBase, RegionalGuidanceSupport> = {- 'sd-1': { autoNegative: true, label: 'SD 1.x', negativePrompt: true, referenceImages: 'ip_adapter' },- 'sd-2': { autoNegative: true, label: 'SD 2.x', negativePrompt: true, referenceImages: 'ip_adapter' },- sdxl: { autoNegative: true, label: 'SDXL', negativePrompt: true, referenceImages: 'ip_adapter' },- flux: { autoNegative: false, label: 'FLUX', negativePrompt: false, referenceImages: 'flux_redux' },- flux2: { autoNegative: false, label: 'FLUX.2', negativePrompt: false, referenceImages: null },- 'krea-2': { autoNegative: false, label: 'Krea-2', negativePrompt: false, referenceImages: null },- 'z-image': { autoNegative: false, label: 'Z-Image', negativePrompt: false, referenceImages: null },- anima: { autoNegative: false, label: 'Anima', negativePrompt: false, referenceImages: null },+const REGIONAL_GUIDANCE_SUPPORT: Record<+ RegionalGuidanceBase,+ Pick<RegionalGuidanceSupport, 'label' | 'referenceImages'>+> = {+ 'sd-1': { label: 'SD 1.x', referenceImages: 'ip_adapter' },+ 'sd-2': { label: 'SD 2.x', referenceImages: 'ip_adapter' },+ sdxl: { label: 'SDXL', referenceImages: 'ip_adapter' },+ flux: { label: 'FLUX', referenceImages: 'flux_redux' },+ flux2: { label: 'FLUX.2', referenceImages: null },+ 'krea-2': { label: 'Krea-2', referenceImages: null },+ 'z-image': { label: 'Z-Image', referenceImages: null },+ anima: { label: 'Anima', referenceImages: null },};/**@@ -62,13 +64,23 @@ export const isRegionalGuidanceSupportedForBase = (base: string): base is Region(getArchitectureFeatures(base)?.supports_regional_guidance ?? false) && base in REGIONAL_GUIDANCE_SUPPORT;/**- * The per-base support matrix, or `null` for a base with no regional path.+ * What a base's regions honour, or `null` for a base with no regional path.*- * The *answer* comes from the capability table; the row it selects is graph knowledge (which node- * kind a region's reference images become), which the backend has no say in.+ * Negatives come from the capability table: the SD family's `compel` path masks both polarities,+ * while the FLUX / FLUX.2 / Krea-2 / Z-Image / Anima denoisers mask positive conditioning only --+ * Z-Image and Anima accept a negative list but discard its masks, so a "regional" negative there+ * would act globally. Auto-negative re-encodes the positive prompt as a masked negative, so it needs+ * the same path. The rest of the row is graph knowledge the backend has no say in.*/-export const getRegionalGuidanceSupport = (base: string | null): RegionalGuidanceSupport | null =>- base !== null && isRegionalGuidanceSupportedForBase(base) ? REGIONAL_GUIDANCE_SUPPORT[base] : null;+export const getRegionalGuidanceSupport = (base: string | null): RegionalGuidanceSupport | null => {+ if (base === null || !isRegionalGuidanceSupportedForBase(base)) {+ return null;+ }++ const negative = getArchitectureFeatures(base)?.regional_negative ?? false;++ return { ...REGIONAL_GUIDANCE_SUPPORT[base], autoNegative: negative, negativePrompt: negative };+};/** A resolved reference-image (component) model identifier — the backend model field shape. */export interface RegionalReferenceModel {@@ -264,7 +276,10 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegthrow new Error('addRegionalGuidance: base graph is missing the positive conditioning collector.');}const negCondCollect = graph.nodes[NEG_COND_COLLECT_ID] ?? null;- const support = REGIONAL_GUIDANCE_SUPPORT[base];+ const support = getRegionalGuidanceSupport(base);+ if (!support) {+ throw new Error(`addRegionalGuidance: ${base} has no regional guidance path.`);+ }let ipAdapterCollector: BackendInvocationContract | null = null;let fluxReduxCollector: BackendInvocationContract | null = null;diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.tsindex 17f89e3e36..3ee7d4da4a 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.test.ts@@ -83,4 +83,20 @@ describe('resolveCanvasProcessingSize', () => {)).toEqual({ height: 304, width: 776 });});++ it('snaps on the grid the model variant declares, not the one its base declares', () => {+ // Wan TI2V-5B takes multiples of 32 where A14B takes 16. 720 is on the one grid and not the+ // other, so a caller that drops the variant shows a size the graph then re-snaps.+ const bbox = { height: 720, width: 1280 };+ const a14b = { base: 'wan', type: 'main' } as GenerateModelConfig;+ const ti2v = { base: 'wan', type: 'main', variant: 'ti2v_5b' } as GenerateModelConfig;++ expect(resolveCanvasProcessingSize(a14b, 'off', bbox, undefined)).toEqual(bbox);++ const size = resolveCanvasProcessingSize(ti2v, 'off', bbox, undefined);++ expect(size.width).toBe(1280);+ expect(size.height % 32).toBe(0);+ expect(size.height).not.toBe(720);+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.tsindex 3803df6411..ed42aa9e37 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/canvasProcessingSize.ts@@ -80,7 +80,9 @@ const growToOptimalArea = (size: CanvasSize, optimal: number, grid: number): Can};export const resolveCanvasProcessingSize = (- model: Pick<GenerateModelConfig, 'base' | 'type'>,+ // The variant participates: Wan TI2V-5B snaps to 32 where A14B snaps to 16, and a caller that+ // dropped it would show one processing size while the graph compiles another.+ model: Pick<GenerateModelConfig, 'base' | 'type'> & { variant?: unknown },pidMode: PidMode,bbox: CanvasSize,scaling: CanvasScalingSettings | undefineddiff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.tsindex 30beb70935..66256db94f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts@@ -18,7 +18,6 @@ import {isSelfContainedSDNQPipeline,isVaeAcceptedByBase,isVaeCompatibleWithGenerateModel,- isVaeForBases,type GenerateComponentCandidate,} from './componentCompatibility';@@ -187,28 +186,40 @@ describe('Generate component compatibility', () => {expect(getCompatibleSelectedComponentKey(staleVae, isVaeAcceptedByBase('anima'))).toBeNull();});-});--const vae = (base: string) => ({ base, type: 'vae' }) as Parameters<ReturnType<typeof isVaeForBases>>[0];--describe('isVaeForBases', () => {- it('matches a VAE whose base is listed', () => {- expect(isVaeForBases(['flux'])(vae('flux'))).toBe(true);- expect(isVaeForBases(['flux'])(vae('sdxl'))).toBe(false);- });- it('an empty base list matches nothing (no all-pass escape hatch)', () => {- expect(isVaeForBases([])(vae('flux'))).toBe(false);- });+ it('offers each Wan variant only the VAE width its decode accepts', () => {+ // `wan_model_loader` refuses a 48-channel VAE for A14B and a 16-channel one for TI2V-5B. The+ // served base row used to accept both widths for every variant, so both pickers offered a VAE+ // that failed at enqueue.+ const wanMain = (variant: string) =>+ ({ base: 'wan', key: `wan-${variant}`, name: `Wan ${variant}`, type: 'main', variant }) as GenerateModelConfig;+ const wanVae = (latentChannels: number) =>+ ({+ base: 'wan',+ key: `wan-vae-${latentChannels}`,+ latent_channels: latentChannels,+ name: 'Wan VAE',+ type: 'vae',+ }) as VaeModelConfig;- it('never matches a non-vae model', () => {- expect(isVaeForBases(['flux'])({ base: 'flux', type: 'main' } as never)).toBe(false);+ expect(isVaeCompatibleWithGenerateModel(wanMain('i2v_a14b'), wanVae(16))).toBe(true);+ expect(isVaeCompatibleWithGenerateModel(wanMain('i2v_a14b'), wanVae(48))).toBe(false);+ expect(isVaeCompatibleWithGenerateModel(wanMain('ti2v_5b'), wanVae(48))).toBe(true);+ expect(isVaeCompatibleWithGenerateModel(wanMain('ti2v_5b'), wanVae(16))).toBe(false);});});describe('the VAE filters and the backend declarations', () => {- const mainOf = (base: string) =>- ({ base, key: `${base}-main`, name: base, type: 'main' as const }) as unknown as GenerateModelConfig;+ // With the row's variant: a variant row states what *that* variant accepts, which for Wan TI2V-5B+ // is a different VAE from the one its base row names.+ const mainOf = (base: string, variant: string | null = null) =>+ ({+ base,+ key: `${base}-main`,+ name: base,+ type: 'main' as const,+ ...(variant === null ? {} : { variant }),+ }) as unknown as GenerateModelConfig;const vaeOf = (base: string, latentChannels?: number) =>({@@ -237,7 +248,7 @@ describe('the VAE filters and the backend declarations', () => {expect(// Only wan distinguishes VAEs by latent width; the others leave it null.isVaeCompatibleWithGenerateModel(- mainOf(row.base),+ mainOf(row.base, row.variant),vaeOf(accepted.base, accepted.latent_channels ?? undefined)),`${row.base} should accept a VAE registered under ${accepted.base}`@@ -261,7 +272,7 @@ describe('the VAE filters and the backend declarations', () => {continue;}expect(- isVaeCompatibleWithGenerateModel(mainOf(row.base), vaeOf(base)),+ isVaeCompatibleWithGenerateModel(mainOf(row.base, row.variant), vaeOf(base)),`${row.base} should refuse a VAE registered under ${base}`).toBe(false);}@@ -277,7 +288,7 @@ describe('the VAE filters and the backend declarations', () => {continue;}expect(- isVaeCompatibleWithGenerateModel(mainOf(row.base), vaeOf(entry.base, otherWidth)),+ isVaeCompatibleWithGenerateModel(mainOf(row.base, row.variant), vaeOf(entry.base, otherWidth)),`${row.base} should refuse a ${otherWidth}-channel ${entry.base} VAE`).toBe(false);}diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.tsindex 4cda7785b6..19ba42b397 100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts@@ -64,11 +64,6 @@ export const isDiffusersMainForBase =(model) =>model.type === 'main' && model.base === base && model.format === 'diffusers';-export const isVaeForBases =- (bases: readonly string[]): GenerateComponentFilter =>- (model) =>- model.type === 'vae' && bases.length > 0 && bases.includes(model.base);-export const isClipVariant =(variant: string): GenerateComponentFilter =>(model) =>@@ -156,12 +151,13 @@ export const getCompatibleDiffusersComponentSource = <T extends GenerateComponen* table, or no row for this base, nothing is offered. Choosing a VAE the graph then rejects is* worse than an empty picker that fills in as soon as the table lands.*/-const acceptsVae = (base: string, model: GenerateComponentCandidate): boolean => {+const acceptsVae = (base: string, model: GenerateComponentCandidate, variant?: unknown): boolean => {if (model.type !== 'vae') {return false;}- const row = getArchitectureCapabilityRow(base);+ // With the variant: Wan A14B and TI2V-5B decode with different VAEs, and only the variant row says so.+ const row = getArchitectureCapabilityRow(base, variant);if (!row) {return false;@@ -181,13 +177,13 @@ const acceptsVae = (base: string, model: GenerateComponentCandidate): boolean =>};export const isVaeAcceptedByBase =- (base: string): GenerateComponentFilter =>+ (base: string, variant?: unknown): GenerateComponentFilter =>(model) =>- acceptsVae(base, model);+ acceptsVae(base, model, variant);/*** The one VAE rule for a Generate model. The component picker and its validation filter with- * `isVaeAcceptedByBase(model.base)` and the graph builder with this, so a VAE the user can select is+ * `isVaeAcceptedByBase(model.base, model.variant)` and the graph builder with this, so a VAE the user can select is* always one the graph sends -- the served row decides for both, including cross-base families such* as a Qwen-Image VAE installed under `anima`.*/@@ -196,5 +192,5 @@ export const isVaeCompatibleWithGenerateModel = (model: GenerateModelConfig, vaereturn false;}- return acceptsVae(model.base, vae);+ return acceptsVae(model.base, vae, model.variant);};diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 9443e895cf..987ecd2d34 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -49,6 +49,7 @@ export {getMaxReferenceImages,getPromptHistoryRecallPatch,getSettingsWithModelDefaults,+ isArchitectureDescribed,isKnownScheduler,isReferenceImageSupported,isSupportedGenerateModel,@@ -63,8 +64,8 @@ export {export {getCompatibleDiffusersComponentSource,isDiffusersMainForBase,+ isVaeAcceptedByBase,isVaeCompatibleWithGenerateModel,- isVaeForBases,} from './core/componentCompatibility';export {isValidKrea2RebalanceWeights,diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.tsindex e6cc2607b9..383ad6e61f 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts@@ -1,5 +1,6 @@import type { GenerationModelCatalogItem, MainModelConfig } from '@features/generation/contracts';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';import { describe, expect, it } from 'vitest';import type { VideoSettings } from './types';@@ -775,6 +776,29 @@ describe('component section policy', () => {expect(forTi2v.slot?.filter?.(vaeUnknown, forTi2v.ctx)).toBe(true);});+ it('agrees with the served Wan rows on which VAE width each variant takes', () => {+ // The rule is written out rather than read from the table, because this surface syncs its stored+ // VAE before the table arrives. This keeps the copy honest: a Wan variant or VAE width added to+ // the backend changes the served rows, and fails here until the rule follows.+ const wanRows = architectureCapabilitiesFixture.filter((row) => row.base === 'wan');++ expect(wanRows.map((row) => row.variant)).toContain('ti2v_5b');++ for (const row of wanRows) {+ const model = wanModel(row.variant ?? 'i2v_a14b');+ const settings = settingsFor(model);+ const ctx = { model, selectedComponents: settings, settings };+ const slot = getVideoComponentSectionPolicy(model, settings).slots.find((s) => s.key === 'vae');++ for (const width of [16, 48]) {+ const vae = { base: 'wan', key: `vae${width}`, latent_channels: width, name: `Wan VAE ${width}`, type: 'vae' };+ const served = row.vae?.accepted.some((entry) => entry.base === 'wan' && entry.latent_channels === width);++ expect(slot?.filter?.(vae, ctx), `${row.variant ?? 'base row'}, ${width} channels`).toBe(served ?? false);+ }+ }+ });+it('a cross-family component source covers the encoder but not the VAE', () => {// TI2V-5B main with an A14B Diffusers source: UMT5 is shared (encoder// satisfied) but the VAE is family-bound, so a VAE is still required.diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.tsindex 731b40ba13..b324caad13 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts@@ -11,7 +11,6 @@ import {isDiffusersMainForBase,isLoraCompatibleWithModel,isLoraModelConfig,- isVaeForBases,isWanLoraTargetingMain,SEED_MAX,} from '@features/generation/settings';@@ -1042,8 +1041,12 @@ const isWanLowNoiseExpertCandidate = (candidate: ModelConfig, ctx: VideoComponen// wan_model_loader validates the standalone VAE's latent channels against the// main: TI2V-5B needs the 48-channel Wan 2.2 VAE, A14B the 16-channel Wan 2.1// VAE. A config without the field (open union) stays allowed.+//+// The served (wan, variant) rows say the same thing, but this surface does not+// wait for the capability table: reading it here would drop a stored VAE during+// the widget sync that runs before the table arrives, and persist the loss.const isWanVaeForMain = (candidate: ModelConfig, ctx: VideoComponentPolicyContext): boolean => {- if (!isVaeForBases(['wan'])(candidate)) {+ if (candidate.type !== 'vae' || candidate.base !== 'wan') {return false;}diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.tsindex 0e9800211b..7aed36d9bd 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts@@ -439,3 +439,6 @@ export const useInvocationTemplatesSelector = store.useSelector;/** Imperative read for the workbench reducer and route validation. */export const getInvocationTemplatesSnapshot = (): InvocationTemplatesSnapshot => store.getSnapshot();++/** For readers that combine this store with another one; a single-store reader uses the selector. */+export const subscribeInvocationTemplates = store.subscribe;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex 01fa7988ea..ab38ac6eea 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -736,6 +736,33 @@ describe('importGalleryImagesToCanvas', () => {});});+describe('importGalleryImagesToCanvas with a table that does not describe the architecture', () => {+ it('refuses a resized import rather than uploading at fallback dimensions for that model', async () => {+ // A backend build that has no row for the project's architecture answers with the same fallback+ // 1024 / grid 8 for that one model as a missing table does for all of them, and the upload is+ // just as irreversible.+ const { project, state } = withProject((value) => setModel(value, 'sd-1'));+ const fetchImage = vi.fn<typeof fetch>();+ const uploadImage = vi.fn<typeof uploadCanvasImage>();++ setArchitectureCapabilities(architectureCapabilitiesFixture.filter((row) => row.base !== 'sd-1'));+ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: () => undefined,+ engine: engine(project.id),+ fetchImage,+ ...queriesFor(() => state),+ images: [image('wide.png', 1600, 900)],+ project,+ uploadImage,+ });++ expect(result).toEqual({ status: 'capabilities-unavailable' });+ expect(fetchImage).not.toHaveBeenCalled();+ expect(uploadImage).not.toHaveBeenCalled();+ });+});+describe('importGalleryImagesToCanvas before the capability table arrives', () => {it('refuses a resized import rather than uploading at fallback dimensions', async () => {// The resize target is the model's native size and grid, and this is the one import path whosediff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.tsindex 72db5ab407..9be6abcad6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts@@ -9,6 +9,7 @@ import { getArchitectureCapabilitiesSnapshot } from '@features/generation/runtimimport {calculateNewSize,getGenerationDimensions,+ isArchitectureDescribed,normalizeGenerateWidgetValues,} from '@features/generation/settings';import { getModelsSnapshot } from '@features/models';@@ -282,8 +283,14 @@ export const importGalleryImagesToCanvas = async (options: {// whose mistake is irreversible: the resized asset is uploaded to the server and becomes a// layer. Without the table `getGenerationDimensions` answers 1024 / grid 8 for every// architecture, so an SD-1 project would upload four times the area it asked for and a- // CogView 4 project an off-grid layer. Refuse instead, the way the Invoke gate does.- if (getArchitectureCapabilitiesSnapshot().revision === 0) {+ // CogView 4 project an off-grid layer. Refuse instead, the way the Invoke gate does -- also+ // when the table is there but has no row for the selected architecture, which is the same+ // fallback answer for that one model.+ const targetModel = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'))?.model;+ if (+ getArchitectureCapabilitiesSnapshot().revision === 0 ||+ (targetModel !== undefined && !isArchitectureDescribed(targetModel))+ ) {return { status: 'capabilities-unavailable' };}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsxindex d1769e1d42..2695deac41 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx@@ -14,6 +14,32 @@ import { afterEach, describe, expect, it, vi } from 'vitest';const harness = vi.hoisted(() => ({ project: null as unknown }));+// A controllable stand-in for the node-template store, so a test can decide which of the two stores+// the route depends on finishes loading last.+const templates = vi.hoisted(() => {+ type Snapshot = { error: string | null; status: string; templates: Record<string, unknown> };+ const loading: Snapshot = { error: null, status: 'loading', templates: {} };+ const listeners = new Set<() => void>();+ let snapshot = loading;++ return {+ get: () => snapshot,+ reset: () => {+ snapshot = loading;+ },+ set: (next: Snapshot) => {+ snapshot = next;+ listeners.forEach((listener) => listener());+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+});+vi.mock('@features/generation/react', () => ({useDynamicPrompts: () => ({ count: 1, error: null, isDynamic: false, isError: false, isLoading: false, prompts: [] }),}));@@ -23,6 +49,11 @@ vi.mock('@features/models', () => ({// an input React Compiler memoises the route on, and re-resolve it by accident.useModelsSelector: (selector: (snapshot: unknown) => unknown) => selector(modelsSnapshot),}));+vi.mock('@features/workflow/react', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getInvocationTemplatesSnapshot: () => templates.get(),+ subscribeInvocationTemplates: templates.subscribe,+}));vi.mock('@workbench/activeInvocationSubmission', () => ({ submitActiveInvocation: () => Promise.resolve() }));vi.mock('@workbench/canvasInvocationPreparation', () => ({ useIsCanvasInvocationPreparing: () => false }));vi.mock('@workbench/WorkbenchContext', () => ({@@ -41,7 +72,10 @@ import { useInvocationState } from './useInvocationState';const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };const modelsSnapshot = { models: [sdxlModel], status: 'loaded' };-const buildProject = (): Project => {+const activeProject = (state: ReturnType<typeof createInitialWorkbenchState>): Project =>+ state.projects.find((candidate) => candidate.id === state.activeProjectId)!;++const buildGenerateProject = (): Project => {// The table is needed to derive a *valid* saved project; the point of the test is what happens// when the app is restarted and that project is reopened before the table comes back.setArchitectureCapabilities(architectureCapabilitiesFixture);@@ -53,8 +87,7 @@ const buildProject = (): Project => {};resetArchitectureCapabilities();- const state = workbenchReducer(createInitialWorkbenchState(), { type: 'setGenerateSettings', values });- return state.projects.find((candidate) => candidate.id === state.activeProjectId)!;+ return activeProject(workbenchReducer(createInitialWorkbenchState(), { type: 'setGenerateSettings', values }));};(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -64,6 +97,16 @@ let root: Root | null = null;const Probe = (): ReactNode => <span data-testid="reasons">{useInvocationState().blockingReasons.join(' | ')}</span>;+const renderProbe = async (project: Project) => {+ harness.project = project;+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(<Probe />);+ });+};+const blockingReasons = (): string => host?.querySelector('[data-testid="reasons"]')?.textContent ?? '';afterEach(async () => {@@ -72,17 +115,12 @@ afterEach(async () => {host = null;root = null;resetArchitectureCapabilities();+ templates.reset();});describe('useInvocationState and the architecture capability table', () => {it('stops blocking Invoke as soon as a retried load succeeds', async () => {- harness.project = buildProject();- host = document.createElement('div');- document.body.append(host);- root = createRoot(host);- await act(() => {- root?.render(<Probe />);- });+ await renderProbe(buildGenerateProject());expect(blockingReasons()).toBe('Model capabilities are not available. Generation is blocked until they load; if this persists, retry from the Generate panel.'@@ -97,3 +135,24 @@ describe('useInvocationState and the architecture capability table', () => {expect(blockingReasons()).toBe('');});});++describe('useInvocationState and the workflow node templates', () => {+ it('re-resolves a workflow route when the templates finish loading after the capability table', async () => {+ // The capability table is already there, so its snapshot never changes again. A route cached on+ // that snapshot alone kept "still loading" after the templates arrived.+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ await renderProbe(+ activeProject(+ workbenchReducer(createInitialWorkbenchState(), { sourceId: 'workflow', type: 'setInvocationSource' })+ )+ );++ expect(blockingReasons()).toContain('Node definitions are still loading.');++ await act(() => {+ templates.set({ error: null, status: 'loaded', templates: {} });+ });++ expect(blockingReasons()).not.toContain('Node definitions are still loading.');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsindex 2ee13358aa..0ced0b464d 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -12,7 +12,7 @@ import {sanitizeDynamicPromptsConfig,} from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';-import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { getInvocationTemplatesSnapshot, subscribeInvocationTemplates } from '@features/workflow/react';import { localizeForLoopValidationReason } from '@features/workflow/utility';import { useMountEffect } from '@platform/react/useMountEffect';import { useExternalStoreSelector } from '@platform/state/selectors';@@ -35,6 +35,40 @@ import { useTranslation } from 'react-i18next';const selectInvocationRouteInput = createInvocationRouteInputSelector();+/**+ * Route resolution reads two stores imperatively: the capability table (Generate validation fails+ * closed without it) and the invocation templates (workflow readiness). The selector that resolves+ * the route is only re-run when its snapshot changes, so the snapshot has to change with either --+ * a templates load that lands after the table would otherwise leave "Node definitions are still+ * loading." on Invoke until an unrelated edit.+ */+const subscribeRouteSources = (listener: () => void): (() => void) => {+ const unsubscribeCapabilities = subscribeArchitectureCapabilities(listener);+ const unsubscribeTemplates = subscribeInvocationTemplates(listener);++ return () => {+ unsubscribeCapabilities();+ unsubscribeTemplates();+ };+};++let routeSources: {+ capabilities: ReturnType<typeof getArchitectureCapabilitiesSnapshot>;+ templates: ReturnType<typeof getInvocationTemplatesSnapshot>;+} | null = null;++/** Referentially stable until one of the two stores publishes a new snapshot. */+const getRouteSourcesSnapshot = () => {+ const capabilities = getArchitectureCapabilitiesSnapshot();+ const templates = getInvocationTemplatesSnapshot();++ if (routeSources?.capabilities !== capabilities || routeSources.templates !== templates) {+ routeSources = { capabilities, templates };+ }++ return routeSources;+};+const areTypeIdSetsEqual = (left: ReadonlySet<WidgetTypeId>, right: ReadonlySet<WidgetTypeId>): boolean =>left.size === right.size && [...left].every((typeId) => right.has(typeId));@@ -82,21 +116,18 @@ export const useInvocationState = (): InvocationState => {const isCanvasPreparing = useIsCanvasInvocationPreparing(routeInput.projectId);const isPreparing = invocation.sourceId === 'canvas' && isCanvasPreparing;- // Project-graph route validation reads the invocation templates imperatively;- // subscribing here keeps the resolved route live while they load.- useInvocationTemplatesSelector((snapshot) => snapshot.status);useMountEffect(() => {void ensureModelsLoaded();});- // `getGenerationValidationReasons` fails closed while the capability table is absent, so a load- // that only succeeds on retry has to reach Invoke on its own. The route is resolved inside the- // store's selector, like `useModelGridSize`: the table is core module state, so to React Compiler a- // bare call is a pure function of these arguments and stays memoised -- Invoke would remain blocked- // until an unrelated edit changed one of them.+ // `getGenerationValidationReasons` fails closed while the capability table is absent, and workflow+ // readiness while the node templates are, so either load -- including one that only succeeds on+ // retry -- has to reach Invoke on its own. The route is resolved inside the stores' selector, like+ // `useModelGridSize`: both are module state, so to React Compiler a bare call is a pure function of+ // these arguments and stays memoised until an unrelated edit changes one of them.const resolvedRoute = useExternalStoreSelector(- subscribeArchitectureCapabilities,- getArchitectureCapabilitiesSnapshot,+ subscribeRouteSources,+ getRouteSourcesSnapshot,useCallback(() => resolveInvocationRouteInput(routeInput, 'global', invocation, availabilityModels),[availabilityModels, invocation, routeInput]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.browser.test.tsxnew file mode 100644index 0000000000..25bce55914--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.browser.test.tsx@@ -0,0 +1,104 @@+import { ChakraProvider } from '@chakra-ui/react';+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { applyThemeToRoot } from '@theme/applyTheme';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++// A project with a Wan TI2V-5B model and a manual 1280x720 processing size. Stable identities, so only+// the capability table's arrival can change what the section computes.+const harness = vi.hoisted(() => ({+ commands: { widgets: { patchValues: () => undefined } },+ project: {+ canvas: { document: { bbox: { height: 720, width: 1280, x: 0, y: 0 } } },+ values: {+ canvas: { scaleMethod: 'manual', scaledHeight: 720, scaledWidth: 1280 },+ generate: {+ model: { base: 'wan', key: 'wan-ti2v', name: 'Wan 2.2 TI2V-5B', type: 'main', variant: 'ti2v_5b' },+ pidMode: 'off',+ },+ } as Record<string, Record<string, unknown>>,+ },+ sectionPreferences: { sectionsOpen: {}, setSectionOpen: () => undefined },+}));++vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: (selector: (project: unknown) => unknown) => selector(harness.project),+ useWorkbenchCommands: () => harness.commands,+}));+vi.mock('@workbench/widgetState', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getProjectWidgetValues: (project: typeof harness.project, widgetId: string) => project.values[widgetId] ?? {},+}));+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useGenerationUi: () => ({ sectionPreferences: harness.sectionPreferences }),+}));++import { GenerateCanvasScalingSection } from './GenerateCanvasScalingSection';++const i18n = createInstance();+void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++const render = async () => {+ applyThemeToRoot('classic');+ host = document.createElement('div');+ host.style.width = '320px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <GenerateCanvasScalingSection />+ </ChakraProvider>+ </I18nextProvider>+ );+ });+};++/** The processing size the section's badge shows, as `[width, height]`. */+const shownSize = (): [number, number] | null => {+ const match = /(\d+)x(\d+)/.exec(host?.textContent ?? '');+ return match ? [Number(match[1]), Number(match[2])] : null;+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ resetArchitectureCapabilities();+});++describe('GenerateCanvasScalingSection', () => {+ it('shows the size the graph will generate at, on the grid the model variant declares', async () => {+ // Before the table the fallback grid is 8, and 720 sits on it.+ await render();+ expect(shownSize()).toEqual([1280, 720]);++ // TI2V-5B takes multiples of 32; its base row says 16, on which 720 would still sit. The section+ // used to drop the variant and to latch its first answer, and either kept showing 1280x720 while+ // `compileCanvasGraph` generated at a different height.+ await act(() => {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ });++ const [width, height] = shownSize() ?? [0, 0];+ expect(width).toBe(1280);+ expect(height % 32).toBe(0);+ expect(height).not.toBe(720);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsxindex 29182f9894..44276d76e5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasScalingSection.tsx@@ -13,7 +13,9 @@ import type { Project } from '@workbench/projectContracts';import { Badge, createListCollection, HStack, NumberInput, Stack, Text } from '@chakra-ui/react';import { resolveCanvasProcessingSize } from '@features/generation/canvasProcessingSize';import { GenerationSettingsSection } from '@features/generation/components';+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';import { clampDimension, getGenerationDimensions } from '@features/generation/settings';+import { useExternalStoreSelector } from '@platform/state/selectors';import { Field, Select } from '@platform/ui';import {CANVAS_SCALE_METHODS,@@ -29,28 +31,39 @@ const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as conconst selectCanvasValues = (project: Project): Record<string, unknown> => getProjectWidgetValues(project, 'canvas');-/** The generate model's base/type and PiD mode decide the grid and optimal area the policy works in. */+/**+ * The generate model's base, type and variant, and the PiD mode, decide the grid and optimal area the+ * policy works in -- the same model `compileCanvasGraph` compiles with, variant included, or the size+ * shown here is not the size that is generated.+ */const selectProcessingContext = (project: Project) => {const generate = getProjectWidgetValues(project, 'generate') as {- model?: { base?: string; type?: string } | null;+ model?: { base?: string; type?: string; variant?: unknown } | null;pidMode?: PidMode;};const model = generate.model;return {bbox: project.canvas.document.bbox,- model: model && typeof model.base === 'string' ? { base: model.base, type: model.type ?? 'main' } : null,+ model:+ model && typeof model.base === 'string'+ ? {+ base: model.base,+ type: model.type ?? 'main',+ variant: typeof model.variant === 'string' ? model.variant : null,+ }+ : null,pidMode: generate.pidMode ?? 'off',};};-const processingContextEqual = (- a: ReturnType<typeof selectProcessingContext>,- b: ReturnType<typeof selectProcessingContext>-): boolean =>+type ProcessingContext = ReturnType<typeof selectProcessingContext>;++const processingContextEqual = (a: ProcessingContext, b: ProcessingContext): boolean =>a.bbox.width === b.bbox.width &&a.bbox.height === b.bbox.height &&a.model?.base === b.model?.base &&a.model?.type === b.model?.type &&+ a.model?.variant === b.model?.variant &&a.pidMode === b.pidMode;export const GenerateCanvasScalingSection = () => {@@ -59,11 +72,19 @@ export const GenerateCanvasScalingSection = () => {const values = useActiveProjectSelector(selectCanvasValues);const scaling = useMemo(() => readCanvasScaling(values), [values]);const context = useActiveProjectSelector(selectProcessingContext, processingContextEqual);- const model = context.model as Parameters<typeof resolveCanvasProcessingSize>[0] | null;- const dimensions = getGenerationDimensions(model ?? undefined, context.pidMode);- const processingSize = useMemo(- () => (model ? resolveCanvasProcessingSize(model, context.pidMode, context.bbox, scaling) : null),- [context, model, scaling]+ // Both answer from the capability table, so they are read inside the store's selector: to React+ // Compiler a bare call is a pure function of `context` and `scaling`, and would keep the fallback+ // grid 8 / optimal 1024 it answered before the table arrived.+ const { dimensions, processingSize } = useExternalStoreSelector(+ subscribeArchitectureCapabilities,+ getArchitectureCapabilitiesSnapshot,+ useCallback(() => {+ const model = context.model as Parameters<typeof resolveCanvasProcessingSize>[0] | null;+ return {+ dimensions: getGenerationDimensions(model ?? undefined, context.pidMode),+ processingSize: model ? resolveCanvasProcessingSize(model, context.pidMode, context.bbox, scaling) : null,+ };+ }, [context, scaling]));const resizes =processingSize !== null &&diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsxnew file mode 100644index 0000000000..80a5b792f9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx@@ -0,0 +1,101 @@+import type { CanvasControlLayerContract } from '@workbench/canvas-engine/api';++import { ChakraProvider } from '@chakra-ui/react';+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { applyThemeToRoot } from '@theme/applyTheme';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { ControlLayerSettings } from './ControlLayerSettings';++// Stable identities, as the real stores hand out, so only the table's arrival can re-read the policy.+const catalog = vi.hoisted(() => ({+ mainModel: { base: 'sd-1', key: 'sd1-main', name: 'SD 1.5', type: 'main' },+ models: [{ base: 'sd-1', key: 'sd1-controlnet', name: 'SD 1.5 ControlNet', type: 'controlnet' }],+}));++vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useModelsSelector: (selector: (snapshot: { models: typeof catalog.models }) => unknown) =>+ selector({ models: catalog.models }),+}));+vi.mock('./useSelectedMainModel', () => ({ useSelectedMainModel: () => catalog.mainModel }));++const i18n = createInstance();+void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++const layer = {+ adapter: {+ beginEndStepPct: [0, 1],+ controlMode: 'balanced',+ kind: 'controlnet',+ model: 'sd1-controlnet',+ weight: 1,+ },+ filter: null,+ id: 'control-1',+ isEnabled: true,+ isLocked: false,+ name: 'Control 1',+ opacity: 1,+ type: 'control',+ withTransparencyEffect: false,+} as unknown as CanvasControlLayerContract;++const ignoreOperationStarted = (): void => undefined;++const render = async () => {+ applyThemeToRoot('classic');+ host = document.createElement('div');+ host.style.width = '260px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <ControlLayerSettings engine={null} layer={layer} onOperationStarted={ignoreOperationStarted} />+ </ChakraProvider>+ </I18nextProvider>+ );+ });+};++/** The kind Select renders a hidden native select, so its offered kinds are readable without opening it. */+const offersKind = (kind: string) => host!.querySelector(`option[value="${kind}"]`) !== null;++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ resetArchitectureCapabilities();+});++describe('ControlLayerSettings and the capability table', () => {+ it('offers the adapter kinds once a retried load succeeds, without remounting', async () => {+ // Without the table every kind reads as unsupported. The list used to be memoised on the base+ // alone, so it stayed empty after the table arrived until the model changed or the panel remounted.+ await render();+ expect(offersKind('controlnet')).toBe(false);++ await act(() => {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ });++ expect(offersKind('controlnet')).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex ac2ef8df78..53ceb65c7d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -18,7 +18,9 @@ import {isControlKindSupportedForBase,type ControlAdapterKind,} from '@features/generation/graph';+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';import { useModelsSelector } from '@features/models';+import { useExternalStoreSelector } from '@platform/state/selectors';import { Field, Select, Slider } from '@platform/ui';import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';@@ -108,13 +110,19 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont);// Adapter kinds supported by the selected base. Z-Image Control is only shown- // when a compatible Z-Image main model is selected.- const kindOptions = useMemo(- () =>- CONTROL_ADAPTER_KINDS.filter((kind) =>- base ? isControlKindSupportedForBase(base, kind) : kind !== 'z_image_control'- ),- [base]+ // when a compatible Z-Image main model is selected. Read inside the store's+ // selector: the answer comes from the capability table, and a call memoised on+ // `base` alone keeps the empty list it gave before a retried load succeeded.+ const kindOptions = useExternalStoreSelector(+ subscribeArchitectureCapabilities,+ getArchitectureCapabilitiesSnapshot,+ useCallback(+ () =>+ CONTROL_ADAPTER_KINDS.filter((kind) =>+ base ? isControlKindSupportedForBase(base, kind) : kind !== 'z_image_control'+ ),+ [base]+ ));const kindCollection = useMemo(() =>@@ -313,19 +321,36 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contconst contributing = engine? (lookupDocumentLeaf(engine.document.model()?.document, layer.id)?.contributionEnabled ?? false): layer.isEnabled;- const validationReason =- contributing && mainModel- ? getControlValidationReason({- adapterModel: adapterModel ? { base: adapterModel.base, type: adapterModel.type } : null,- beginEndStepPct: adapter.beginEndStepPct,- controlLoraIndex: Math.max(0, controlLoraIndex),- kind: adapter.kind,- mainBase: mainModel.base,- mainVariant: mainModel.variant ?? undefined,- weight: adapter.weight,- zImageControlIndex: Math.max(0, zImageControlIndex),- })- : null;+ // Same reason as `kindOptions`: validation asks the capability table whether the kind is supported.+ const validationReason = useExternalStoreSelector(+ subscribeArchitectureCapabilities,+ getArchitectureCapabilitiesSnapshot,+ useCallback(+ () =>+ contributing && mainModel+ ? getControlValidationReason({+ adapterModel: adapterModel ? { base: adapterModel.base, type: adapterModel.type } : null,+ beginEndStepPct: adapter.beginEndStepPct,+ controlLoraIndex: Math.max(0, controlLoraIndex),+ kind: adapter.kind,+ mainBase: mainModel.base,+ mainVariant: mainModel.variant ?? undefined,+ weight: adapter.weight,+ zImageControlIndex: Math.max(0, zImageControlIndex),+ })+ : null,+ [+ adapter.beginEndStepPct,+ adapter.kind,+ adapter.weight,+ adapterModel,+ contributing,+ controlLoraIndex,+ mainModel,+ zImageControlIndex,+ ]+ )+ );// Content-dependent problems only matter once the layer has pixels, but a// missing model deserves the warning even on a fresh empty layer.const visibleValidationReason =diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsxnew file mode 100644index 0000000000..8291888e2f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.browser.test.tsx@@ -0,0 +1,96 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';++import { ChakraProvider } from '@chakra-ui/react';+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { applyThemeToRoot } from '@theme/applyTheme';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { ControlLayerWarningIcon } from './ControlLayerWarningIcon';++// Stable identities, as the real stores hand out: a fresh array or model per render would change an+// input React Compiler memoises on, and re-read the table by accident rather than by subscription.+const catalog = vi.hoisted(() => ({+ mainModel: { base: 'sd-1', key: 'sd1-main', name: 'SD 1.5', type: 'main' },+ models: [{ base: 'sd-1', key: 'sd1-controlnet', name: 'SD 1.5 ControlNet', type: 'controlnet' }],+}));++vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useModelsSelector: (selector: (snapshot: { models: typeof catalog.models }) => unknown) =>+ selector({ models: catalog.models }),+}));+vi.mock('./useSelectedMainModel', () => ({ useSelectedMainModel: () => catalog.mainModel }));++const i18n = createInstance();+void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++const layer = {+ adapter: {+ beginEndStepPct: [0, 1],+ controlMode: 'balanced',+ kind: 'controlnet',+ model: 'sd1-controlnet',+ weight: 1,+ },+ id: 'control-1',+ isEnabled: true,+ isLocked: false,+ name: 'Control 1',+ opacity: 1,+ type: 'control',+} as unknown as CanvasLayerContract;++const render = async () => {+ applyThemeToRoot('classic');+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <ControlLayerWarningIcon layer={layer} />+ </ChakraProvider>+ </I18nextProvider>+ );+ });+};++const warning = () => host!.querySelector('[aria-label="widgets.layers.control.needsAttention"]');++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ resetArchitectureCapabilities();+});++describe('ControlLayerWarningIcon and the capability table', () => {+ it('drops the "unsupported adapter" warning once a retried load succeeds, without remounting', async () => {+ // Without the table every adapter kind reads as unsupported. The row used to keep that answer+ // until the layer or model changed, so a healthy SD-1 ControlNet layer stayed flagged.+ await render();+ expect(warning()).not.toBeNull();++ await act(() => {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ });++ expect(warning()).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsxindex 3fb61cacfa..3fbd3e0c68 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx@@ -1,10 +1,13 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import { Icon } from '@chakra-ui/react';+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';import { useModelsSelector } from '@features/models';+import { useExternalStoreSelector } from '@platform/state/selectors';import { Tooltip } from '@platform/ui';import { getControlLayerAttentionReason } from '@workbench/controlLayerChecks';import { TriangleAlertIcon } from 'lucide-react';+import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useSelectedMainModel } from './useSelectedMainModel';@@ -25,11 +28,21 @@ export const ControlLayerWarningIcon = ({const { t } = useTranslation();const models = useModelsSelector((snapshot) => snapshot.models);const mainModel = useSelectedMainModel();+ // Read inside the store's selector: whether the adapter kind is supported comes from the capability+ // table, and a call memoised on the layer and model would keep flagging "unsupported adapter" after a+ // retried load succeeded, until something unrelated re-rendered the row.+ const reason = useExternalStoreSelector(+ subscribeArchitectureCapabilities,+ getArchitectureCapabilitiesSnapshot,+ useCallback(+ () =>+ layer.type === 'control' && contributing && mainModel+ ? getControlLayerAttentionReason(layer, mainModel.base, models)+ : null,+ [contributing, layer, mainModel, models]+ )+ );- if (layer.type !== 'control' || !contributing || !mainModel) {- return null;- }- const reason = getControlLayerAttentionReason(layer, mainModel.base, models);if (!reason) {return null;}diff --git a/tests/backend/architectures/test_dimension_grid.py b/tests/backend/architectures/test_dimension_grid.pyindex e1884fd0e9..a9ba5ec847 100644--- a/tests/backend/architectures/test_dimension_grid.py+++ b/tests/backend/architectures/test_dimension_grid.py@@ -94,7 +94,8 @@ def test_no_variant_row_repeats_its_base_row() -> None:redundant = [f"{r.base.value}/{r.variant}"for r in architecture_capabilities()- if r.variant is not None and (r.features, r.defaults) == (by_base[r.base].features, by_base[r.base].defaults)+ if r.variant is not None+ and (r.features, r.defaults, r.vae) == (by_base[r.base].features, by_base[r.base].defaults, by_base[r.base].vae)]assert redundant == []@@ -108,8 +109,8 @@ def test_every_variant_row_is_rendered_in_full() -> None:if row.variant is None:continuebase_row = by_base[row.base]- assert row.modality == base_row.modalityassert (row.defaults is None) == (base_row.defaults is None), row.base.value+ assert (row.vae is None) == (base_row.vae is None), row.base.valuedef test_the_variant_rows_of_a_base_stay_sorted() -> None:@@ -120,19 +121,6 @@ def test_the_variant_rows_of_a_base_stay_sorted() -> None:assert variants == sorted(variants), base.value-def test_a_variant_row_reports_the_compression_of_the_space_it_denoises_in() -> None:- """The grid and the compression are two facts about the same space, and a row that got one- from the variant and the other from the base would be internally inconsistent. TI2V-5B- compresses 16x per side; A14B, and the base row, 8x."""- rows = {(r.base.value, r.variant): r for r in architecture_capabilities()}-- wan_base = rows[("wan", None)]- wan_ti2v = rows[("wan", "ti2v_5b")]-- assert (wan_base.features.dimension_grid, wan_base.features.spatial_compression) == (16, 8)- assert (wan_ti2v.features.dimension_grid, wan_ti2v.features.spatial_compression) == (32, 16)--def test_resolving_a_space_by_variant_agrees_with_resolving_it_by_sample() -> None:"""Two ways to the same answer: generation has a tensor, the served table has a model record.If they disagreed, a preview and the size the client was told would describe different spaces."""diff --git a/tests/backend/architectures/test_features.py b/tests/backend/architectures/test_features.pyindex 8b9075e854..3ab0ea20f9 100644--- a/tests/backend/architectures/test_features.py+++ b/tests/backend/architectures/test_features.py@@ -97,9 +97,9 @@ def test_reference_images_and_the_one_variant_condition() -> None:def test_regional_guidance_and_its_negative_subset() -> None:- """Transcribed from `REGIONAL_GUIDANCE_SUPPORT` in webv2's `addRegionalGuidance.ts`, which is- the only place these two facts live today -- neither field is served in a form the frontend- fixture pins, so nothing else cross-checks them.+ """Both are served, and webv2 builds its regional graph from them: `supports_regional_guidance`+ decides whether a region reaches the graph at all, `regional_negative` whether its negative+ prompt and auto-negative do. A wrong declaration here is a region silently applied globally.Regional negative prompts are a strict subset: only the SD family's `compel` /`sdxl_compel_prompt` path masks both prompt polarities. The FLUX / FLUX.2 / Krea-2 / Z-Image /diff --git a/tests/backend/architectures/test_vae.py b/tests/backend/architectures/test_vae.pyindex 58e0be0ece..ebfaa37e97 100644--- a/tests/backend/architectures/test_vae.py+++ b/tests/backend/architectures/test_vae.py@@ -10,11 +10,11 @@ import pytestfrom invokeai.app.invocations.baseinvocation import InvocationRegistryfrom invokeai.app.services.shared.graph import Graph # noqa: F401 -- imports every invocation-from invokeai.backend.architectures import generative_bases, get+from invokeai.backend.architectures import architecture_capabilities, generative_bases, getfrom invokeai.backend.architectures.facets.latent_space import LatentSpace, LatentSpaceFacetfrom invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacet, accepts_vaefrom invokeai.backend.architectures.registry import require-from invokeai.backend.model_manager.taxonomy import BaseModelType+from invokeai.backend.model_manager.taxonomy import BaseModelType, WanVariantType# 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.@@ -152,26 +152,61 @@ def test_every_accepted_vae_shares_the_architectures_latent_space() -> None:continueown = require(base, LatentSpaceFacet)- own_spaces = (own.primary, *own.alternates)-- for entry in sorted(facet.accepted, key=_sort_key):- space = _declared_latent_space(entry.base, entry.latent_channels)- if space is None:- violations.append(- f"{base.value} accepts {entry.base.value} at {entry.latent_channels} channels, "- f"but {entry.base.value} declares no such latent space"- )- elif space not in own_spaces:- violations.append(- f"{base.value} denoises in {own.primary.channels}ch/"- f"{own.primary.spatial_compression}x but accepts a {entry.base.value} VAE, "- f"whose latent space is a different basis of {space.channels}ch/"- f"{space.spatial_compression}x"- )++ # Per variant, against the one space that variant denoises in -- not against any space the+ # architecture declares. Against the union, Wan A14B accepting TI2V-5B's 48-channel VAE+ # passed, and `wan_model_loader` rejects exactly that pairing.+ for variant in (None, *facet.by_variant):+ expected = own.resolve_variant(variant)+ label = base.value if variant is None else f"{base.value}/{variant.value}"++ for entry in sorted(facet.resolve(variant), key=_sort_key):+ space = _declared_latent_space(entry.base, entry.latent_channels)+ if space is None:+ violations.append(+ f"{label} accepts {entry.base.value} at {entry.latent_channels} channels, "+ f"but {entry.base.value} declares no such latent space"+ )+ elif space != expected:+ violations.append(+ f"{label} denoises in {expected.channels}ch/{expected.spatial_compression}x but "+ f"accepts a {entry.base.value} VAE, whose latent space is a different basis of "+ f"{space.channels}ch/{space.spatial_compression}x"+ )assert violations == []+def test_wan_offers_each_variant_only_the_vae_its_decode_accepts() -> None:+ """`wan_model_loader` and `wan_l2i` refuse a 48-channel VAE for A14B and a 16-channel one for+ TI2V-5B. The served rows said both widths were fine for both, so the variant row stated a+ pairing that fails at enqueue -- the one fact `latent_channels` is on the contract for."""+ assert accepts_vae(BaseModelType.Wan, BaseModelType.Wan, 16) is True+ assert accepts_vae(BaseModelType.Wan, BaseModelType.Wan, 48) is False+ assert accepts_vae(BaseModelType.Wan, BaseModelType.Wan, 48, WanVariantType.TI2V_5B) is True+ assert accepts_vae(BaseModelType.Wan, BaseModelType.Wan, 16, WanVariantType.TI2V_5B) is False++ served = {+ row.variant: [(a.base, a.latent_channels) for a in row.vae.accepted]+ for row in architecture_capabilities()+ if row.base is BaseModelType.Wan and row.vae is not None+ }+ assert served == {None: [(BaseModelType.Wan, 16)], "ti2v_5b": [(BaseModelType.Wan, 48)]}+++def test_a_variant_mapping_that_is_never_read_or_accepts_nothing_is_refused_at_declaration() -> None:+ """An empty set is served as `accepted: []` and leaves the picker with nothing to offer for that+ variant, with nothing pointing at the facet; a None key is dead weight `resolve` never reads."""+ wan16 = frozenset({VaeCompatibility(BaseModelType.Wan, latent_channels=16)})++ with pytest.raises(ValueError, match="None key"):+ VaeFacet(wan16, by_variant={None: wan16}) # type: ignore[dict-item]+ with pytest.raises(ValueError, match="ti2v_5b"):+ VaeFacet(wan16, by_variant={WanVariantType.TI2V_5B: frozenset()})+ with pytest.raises(ValueError, match="no VAE at all"):+ VaeFacet(frozenset())++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 thatalready for every architecture without one.@@ -184,8 +219,10 @@ def test_the_facet_is_only_declared_where_it_says_something_new() -> None:facet = get(base, VaeFacet)if facet is None:continue+ # Across every variant: a channel constraint that lives only in `by_variant` still says something.+ entries = facet.accepted.union(*facet.by_variant.values())says_nothing_new = facet.accepted_bases == frozenset({base}) and all(- entry.latent_channels is None for entry in facet.accepted+ entry.latent_channels is None for entry in entries)if says_nothing_new:redundant.append(base.value)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.pyindex b9d2c3ca5f..4b7b6c99d4 100644--- a/tests/backend/model_manager/load/test_qwen_image_vae_layout.py+++ b/tests/backend/model_manager/load/test_qwen_image_vae_layout.py@@ -217,7 +217,9 @@ def test_the_diffusers_layout_still_loads_directly() -> None:result = _loader()._load_qwen_image_vae(_config())wan.assert_not_called()- qwen.return_value.load_state_dict.assert_called_once()+ (loaded,), _ = qwen.return_value.load_state_dict.call_args+ # The same autoencoder as the converted layout, so float16 is raised the same way.+ assert {tensor.dtype for tensor in loaded.values()} == {torch.bfloat16}assert result is qwen.return_value