Skip to content

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.

feat(architectures): close the review findings on the served model policy

Alexander Eichhorn303e28177809
diff --git a/.gitattributes b/.gitattributes
index 8d2e4d195a..eaada5155b 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -10,6 +10,20 @@ docker/** text eol=lf
#
# Only the working copy changes: these files are already stored with LF (`* text=auto` normalizes on
# commit), so nothing in history is rewritten.
+#
+# It is not automatic on an existing checkout, and nothing warns you. Git applies `eol=lf` when it
+# writes a file, and a pull only writes files whose content changed -- so a CRLF working tree
+# becomes a mixed one: the files this revision touched are LF, the thousands it did not stay CRLF,
+# and `format:check` keeps failing, now on files nobody edited. Rewrite the rest once, from the
+# repository root, with nothing you want to keep uncommitted (this discards working-copy changes;
+# `git stash` first if you have any):
+#
+# git rm --cached -r .
+# git reset --hard
+#
+# `rm --cached` empties the index without touching disk; `reset --hard` then rewrites both from
+# HEAD, which is the only step that applies these rules to files whose content did not change.
+# `git status` is clean afterwards on a checkout that was already converted.
invokeai/frontend/**/*.ts text eol=lf
invokeai/frontend/**/*.tsx text eol=lf
invokeai/frontend/**/*.mts text eol=lf
diff --git a/invokeai/app/invocations/anima/anima_model_loader.py b/invokeai/app/invocations/anima/anima_model_loader.py
index c84a6d0cf6..29cd7e532a 100644
--- a/invokeai/app/invocations/anima/anima_model_loader.py
+++ b/invokeai/app/invocations/anima/anima_model_loader.py
@@ -39,7 +39,7 @@ class AnimaModelLoaderInvocation(BaseInvocation):
Anima uses:
- Transformer: Cosmos Predict2 DiT + LLM Adapter (from single-file checkpoint)
- Qwen3 Encoder: Qwen3 0.6B (standalone single-file)
- - VAE: AutoencoderKLQwenImage / Wan 2.1 VAE (standalone single-file or FLUX VAE)
+ - VAE: AutoencoderKLQwenImage / Wan 2.1 VAE (standalone single-file)
The T5-XXL tokenizer needed for LLM Adapter token IDs is bundled in the package,
so no T5-XXL encoder model needs to be installed.
@@ -54,17 +54,16 @@ class AnimaModelLoaderInvocation(BaseInvocation):
)
vae_model: ModelIdentifierField = InputField(
- description="Standalone VAE model. Anima uses a Wan 2.1 / QwenImage VAE (16-channel). "
- "A FLUX VAE can also be used as a compatible fallback.",
+ description="Standalone VAE model. Anima uses a Wan 2.1 / QwenImage VAE (16-channel).",
input=Input.Direct,
- # `anima_l2i` accepts AutoencoderKLWan or FluxAutoEncoder. The Wan-family file is the same
- # checkpoint whichever of the three bases it was installed under; declaring nothing here
- # offered every VAE ever installed, including ones that cannot decode an Anima latent.
+ # The same Wan-family checkpoint whichever of the three bases it was installed under.
+ # Declaring nothing here offered every VAE ever installed. A FLUX VAE is *not* among
+ # them: it shares the channel count but not the basis, so `anima_l2i` decodes it
+ # without error into noise -- 6.10 dB PSNR against the Wan decode, measured.
ui_model_base=[
BaseModelType.Anima,
BaseModelType.QwenImage,
BaseModelType.Wan,
- BaseModelType.Flux,
],
ui_model_type=ModelType.VAE,
title="VAE",
diff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.py
index 55fe3e94c0..202f31f1de 100644
--- a/invokeai/backend/architectures/defs/anima.py
+++ b/invokeai/backend/architectures/defs/anima.py
@@ -32,13 +32,17 @@ register(
VaeFacet(
frozenset(
{
- # `anima_l2i` accepts AutoencoderKLWan or FluxAutoEncoder, each with its own
- # decode path. The Wan-family file is registered under whichever base it was
- # installed for -- all three point at the same 194-tensor checkpoint.
+ # The Wan 2.1 VAE, registered under whichever base it was installed for -- all
+ # three point at the same 194-tensor checkpoint.
+ #
+ # Not FLUX. `anima_l2i` takes a FluxAutoEncoder without raising, but that branch
+ # skips the Wan denormalisation and decodes a WAN21_16 latent in FLUX's basis:
+ # measured against the Anima VAE on real weights, 6.10 dB PSNR, 0.93 MAE, a
+ # magenta moire in place of the subject. Accepting it is a silent corruption, not
+ # a fallback. See `tests/backend/architectures/test_vae.py`.
VaeCompatibility(BaseModelType.Anima),
VaeCompatibility(BaseModelType.QwenImage),
VaeCompatibility(BaseModelType.Wan, latent_channels=16),
- VaeCompatibility(BaseModelType.Flux),
}
)
),
diff --git a/invokeai/backend/model_manager/load/model_loaders/vae.py b/invokeai/backend/model_manager/load/model_loaders/vae.py
index d58a98f9d4..003c5112ad 100644
--- a/invokeai/backend/model_manager/load/model_loaders/vae.py
+++ b/invokeai/backend/model_manager/load/model_loaders/vae.py
@@ -37,6 +37,29 @@ def _is_sdnq_vae_folder(path: Path) -> bool:
return is_sdnq_folder(path)
+_QWEN_IMAGE_LAYOUT_MARKER = "decoder.conv_in.weight"
+"""Present only in the diffusers export of the Qwen-Image VAE."""
+
+_WAN_LAYOUT_MARKER = "decoder.middle.0.residual.0.gamma"
+"""Present only in the original Wan-family layout.
+
+The same key diffusers' own `infer_diffusers_model_type` keys the Wan VAE off, so a file carrying
+it is one `convert_wan_vae_to_diffusers` knows how to read.
+"""
+
+
+def _checkpoint_keys(path: str | Path) -> set[str]:
+ """The tensor names in a safetensors file, read from its header alone.
+
+ Layout is decided before anything is loaded, so the file is read once, by whichever branch
+ actually needs the tensors.
+ """
+ from safetensors import safe_open
+
+ with safe_open(path, framework="pt", device="cpu") as f:
+ return set(f.keys())
+
+
# Architectural defaults for the Wan 2.2-VAE (TI2V-5B). Verbatim from the
# vae/config.json shipped with Wan-AI/Wan2.2-TI2V-5B-Diffusers — only the
# values that differ from diffusers' AutoencoderKLWan defaults are listed.
@@ -176,15 +199,10 @@ class VAELoader(GenericDiffusersLoader):
submodel_type: Optional[SubModelType] = None,
) -> AnyModel:
if isinstance(config, VAE_Checkpoint_Anima_Config):
- from diffusers.models.autoencoders import AutoencoderKLWan
-
- from invokeai.backend.wan.rocm_causal_conv3d import patch_wan_causal_conv3d_for_rocm
-
- patch_wan_causal_conv3d_for_rocm()
- return AutoencoderKLWan.from_single_file(
- config.path,
- torch_dtype=self._torch_dtype,
- )
+ # `VAE_Checkpoint_Anima_Config` matches on the original Wan-family layout, which is what
+ # `_load_wan_family_vae` reads -- the same checkpoint the community `qwen-image`
+ # redistribution carries.
+ return self._load_wan_family_vae(config.path)
elif isinstance(config, VAE_Checkpoint_Wan_Config):
return self._load_wan_vae(config)
elif isinstance(config, VAE_Diffusers_Wan_Config):
@@ -276,34 +294,88 @@ class VAELoader(GenericDiffusersLoader):
local_files_only=True,
)
+ def _load_wan_family_vae(self, path: str) -> AnyModel:
+ """Load the 16-channel Wan 2.1 VAE from a single file in its original (non-diffusers) layout.
+
+ Two registrations reach this: `VAE_Checkpoint_Anima_Config`, and the community `qwen-image`
+ redistribution of the same 194-tensor checkpoint.
+
+ Converts and constructs rather than calling `AutoencoderKLWan.from_single_file`, which would
+ fetch `Wan-AI/Wan2.1-T2V-14B-Diffusers::vae/config.json` over HTTP at load time and then
+ load non-strictly. The fetched config is a strict subset of diffusers' `AutoencoderKLWan`
+ defaults with identical values, so `z_dim=16` builds the same 194-tensor module.
+
+ A key the conversion did not produce is the failure that matters: `from_single_file` leaves
+ that parameter on the meta device and the model only fails at the first decode, so it is
+ checked here instead. Keys the module has no use for are not an error -- a redistribution
+ may carry extras -- but they are worth a line in the log.
+
+ Forces bfloat16 for the same reason as `_load_wan_vae` and `_load_wan_vae_diffusers` -- fp16
+ is unstable on the Wan VAE, and the default `precision: auto` resolves to float16 on CUDA.
+ """
+ import accelerate
+ import torch
+ from diffusers.loaders.single_file_utils import convert_wan_vae_to_diffusers
+ from diffusers.models.autoencoders import AutoencoderKLWan
+ from safetensors.torch import load_file
+
+ from invokeai.backend.wan.rocm_causal_conv3d import patch_wan_causal_conv3d_for_rocm
+
+ patch_wan_causal_conv3d_for_rocm()
+
+ sd = convert_wan_vae_to_diffusers(load_file(path))
+ for k in list(sd.keys()):
+ if sd[k].is_floating_point():
+ sd[k] = sd[k].to(torch.bfloat16)
+
+ self._ram_cache.make_room(sum(t.nelement() * t.element_size() for t in sd.values()))
+
+ with accelerate.init_empty_weights():
+ model = AutoencoderKLWan(z_dim=16)
+
+ missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)
+ if missing:
+ raise ValueError(
+ f"{path} does not convert to a complete Wan 2.1 VAE: {len(missing)} tensors are "
+ f"missing, starting with {sorted(missing)[:5]}."
+ )
+ if unexpected:
+ self._logger.warning(f"{path} carries {len(unexpected)} tensors the Wan 2.1 VAE does not use.")
+
+ model.eval()
+ return model
+
def _load_qwen_image_vae(self, config: VAE_Checkpoint_QwenImage_Config) -> AnyModel:
"""Load a Qwen Image VAE from a single safetensors file.
- Two layouts reach this method. Files exported from the Qwen-Image repo carry the diffusers
- state-dict keys (`decoder.conv_in.weight`, ...) and are loaded directly, because
- `AutoencoderKLQwenImage` registers no single-file conversion in diffusers.
+ Two layouts reach this method, and each is recognised by a key it must carry. Files exported
+ from the Qwen-Image repo carry the diffusers state-dict keys and are loaded directly,
+ because `AutoencoderKLQwenImage` registers no single-file conversion in diffusers. Community
+ redistributions carry the original Wan-family layout, which needs converting; loading those
+ into `AutoencoderKLQwenImage` with `strict=True` failed with 194 missing keys, which made a
+ VAE unusable purely because of the base it happened to be probed as.
- Community redistributions carry the original layout instead (`decoder.conv1.weight`, ...),
- which needs converting. Those files are the 16-channel Wan-family VAE -- architecturally the
- same autoencoder -- so `AutoencoderKLWan.from_single_file` reads them, and the identical
- checkpoint installed under `anima` already takes that path. Loading them into
- `AutoencoderKLQwenImage` with `strict=True` failed with 194 missing keys, which made a VAE
- unusable purely because of the base it happened to be probed as.
+ Both tests are positive. "Not the diffusers layout, therefore Wan" sent anything else --
+ a truncated download, an unrelated autoencoder -- into a conversion that silently produces
+ nothing the module recognises, where identification's own `strict=True` used to raise.
"""
import accelerate
from diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLQwenImage
from safetensors.torch import load_file
- sd = load_file(config.path)
+ keys = _checkpoint_keys(config.path)
- if "decoder.conv_in.weight" not in sd:
- from diffusers.models.autoencoders import AutoencoderKLWan
+ if _WAN_LAYOUT_MARKER in keys:
+ return self._load_wan_family_vae(config.path)
- from invokeai.backend.wan.rocm_causal_conv3d import patch_wan_causal_conv3d_for_rocm
+ if _QWEN_IMAGE_LAYOUT_MARKER not in keys:
+ raise ValueError(
+ f"{config.path} is not a Qwen-Image VAE in either known layout: it carries neither "
+ f"`{_QWEN_IMAGE_LAYOUT_MARKER}` (the diffusers export) nor `{_WAN_LAYOUT_MARKER}` "
+ f"(the original Wan-family layout)."
+ )
- del sd
- patch_wan_causal_conv3d_for_rocm()
- return AutoencoderKLWan.from_single_file(config.path, torch_dtype=self._torch_dtype)
+ sd = load_file(config.path)
if self._torch_dtype is not None:
for k in list(sd.keys()):
diff --git a/invokeai/frontend/webv2/.oxfmtrc.json b/invokeai/frontend/webv2/.oxfmtrc.json
index d53c375361..515c343a56 100644
--- a/invokeai/frontend/webv2/.oxfmtrc.json
+++ b/invokeai/frontend/webv2/.oxfmtrc.json
@@ -8,7 +8,8 @@
"dist/**",
"node_modules/**",
"stats.html",
- "src/features/generation/core/__snapshots__/generateGraphNodeTypes.json"
+ "src/features/generation/core/__snapshots__/generateGraphNodeTypes.json",
+ "src/features/generation/core/__fixtures__/architectureCapabilities.json"
],
"printWidth": 120,
"semi": true,
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 24ad0ce824..a9e5f1596b 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2700,6 +2700,7 @@
"hideStagingThumbnails": "Hide staging thumbnails",
"import": {
"blocked": "Finish the current canvas operation before adding images.",
+ "capabilitiesUnavailable": "The resize target depends on model capabilities, which haven't loaded yet. Try again in a moment.",
"control": "Control Layer",
"dropControl": "Add as Control Layer",
"dropInpaintMask": "Add as Inpaint Mask",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 62185fa0fd..8df4b63230 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -53,6 +53,18 @@ const ARCHITECTURE_CAPABILITIES = JSON.parse(
)
);
+/**
+ * Fault switches, orthogonal to the workload profiles.
+ *
+ * The Generate panel gates its entire form on `GET /api/v2/models/capabilities`, so its outage,
+ * retry and recovery states are unreachable while that route always succeeds. `POST /__faults`
+ * (`{"capabilities": "error" | "empty" | "ok"}`, also accepted as a query parameter) makes the
+ * route fail for the rest of the session; `POST /__reset` clears the faults with the state.
+ */
+const CAPABILITY_FAULTS = new Set(['ok', 'error', 'empty']);
+
+const createFaults = () => ({ capabilities: 'ok' });
+
const MOCK_USER_ID = 'fixture-user';
const clone = (value) => structuredClone(value);
@@ -629,6 +641,7 @@ const parseByteRange = (value, size) => {
export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
const initialProfile = assertMockBackendProfileName(profile);
let state = createState(initialProfile);
+ let faults = createFaults();
const server = createServer(async (request, response) => {
const url = new URL(request.url, `http://127.0.0.1:${String(port)}`);
@@ -651,6 +664,8 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(400, { detail: error instanceof Error ? error.message : String(error) });
}
+ faults = createFaults();
+
const collisions = [...url.searchParams.getAll('collide'), ...(body.collide ?? [])]
.flatMap((value) => String(value).split(','))
.map((value) => value.trim())
@@ -663,6 +678,23 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, { ok: true, ...getProfileInfo(state) });
}
+ if (path === '/__faults') {
+ if (method === 'POST') {
+ const body = await readJsonBody(request);
+ const requested = url.searchParams.get('capabilities') ?? body.capabilities;
+
+ if (requested !== undefined && requested !== null) {
+ if (!CAPABILITY_FAULTS.has(requested)) {
+ return json(400, { detail: `Unknown capabilities fault: ${String(requested)}` });
+ }
+
+ faults.capabilities = requested;
+ }
+ }
+
+ return json(200, { ok: true, faults: { ...faults } });
+ }
+
if (method === 'GET' && path === '/openapi.json') {
return json(200, state.openApiDocument);
}
@@ -949,7 +981,11 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, []);
}
if (method === 'GET' && path === '/api/v2/models/capabilities') {
- return json(200, ARCHITECTURE_CAPABILITIES);
+ if (faults.capabilities === 'error') {
+ return json(500, { detail: 'Fixture capability outage.' });
+ }
+
+ return json(200, faults.capabilities === 'empty' ? [] : ARCHITECTURE_CAPABILITIES);
}
if (method === 'GET' && path === '/api/v2/models/starter_models') {
return json(200, STARTER_MODELS_RESPONSE);
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index 6a60bac838..16706c53bd 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -171,6 +171,20 @@ describe('dependency policy rules', () => {
expect(checkDependency('features/queue/core/policy.ts', '@platform/state/selectorCore')).toEqual([]);
});
+ it('treats test-support modules as non-production and keeps production out of them', () => {
+ expect(isProductionSourcePath('features/generation/core/architectureCapabilities.testing.ts')).toBe(false);
+ expect(isProductionSourcePath('platform/ui/Button.type-test.tsx')).toBe(false);
+ expect(isProductionSourcePath('features/generation/ui/GenerateWidgetView.browser.test.tsx')).toBe(false);
+ expect(isProductionSourcePath('features/generation/core/architectureCapabilities.ts')).toBe(true);
+ // The helper imports a test runner and a 1000-row fixture, and Core is bundled by every route.
+ expect(
+ checkDependency('features/generation/ui/GenerateWidgetView.tsx', '../core/architectureCapabilities.testing')
+ ).toContainEqual(expect.objectContaining({ rule: 'test-support-isolation' }));
+ expect(checkDependency('features/generation/core/settings.test.ts', './architectureCapabilities.testing')).toEqual(
+ []
+ );
+ });
+
it('rejects the retired global Workbench contract hub', () => {
expect(checkDependency('workbench/shell/View.tsx', '@workbench/types')).toContainEqual(
expect.objectContaining({ rule: 'retired-contract-hub' })
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
index f8af40478c..799844ef6d 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
@@ -186,9 +186,18 @@ const DOCUMENT_MODEL_DEPENDENCY_MODULES = [
'workbench/canvas-engine/document/selectionRepair',
];
-/** Production sources: everything the architecture rules scan; tests, type tests and stories are not. */
-export const isProductionSourcePath = (path: string): boolean =>
- !/\.(?:test|browser\.test|type-test|stories)\.[^.]+$/.test(path);
+/**
+ * Test-support suffixes, matched with or without a file extension so the same predicate classifies
+ * both a source path and a resolved (extensionless) import target.
+ */
+const TEST_SUPPORT_SUFFIX = /\.(?:test|type-test|testing|stories)(?:\.[^.]+)?$/;
+
+/**
+ * Production sources: everything the architecture rules scan. Tests, type tests, stories and the
+ * `.testing` helpers they share are not -- those import test runners and fixtures, so a production
+ * module reaching one pulls both into every bundle that route touches.
+ */
+export const isProductionSourcePath = (path: string): boolean => !TEST_SUPPORT_SUFFIX.test(path);
/** The pure document model may only reach pure document facts, math, and contracts. */
const isDocumentModelDependency = (target: string | null): boolean =>
@@ -224,6 +233,10 @@ export const checkDependency = (source: string, specifier: string): DependencyVi
return violations;
}
+ if (isProductionSourcePath(sourcePath) && !isProductionSourcePath(target)) {
+ add('test-support-isolation');
+ }
+
const sourceOwner = getModuleOwner(sourcePath);
const targetOwner = getModuleOwner(target);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
index 2be96eaa17..dfd6ee4f4c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
@@ -3,7 +3,12 @@
"base": "anima",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "anima"
},
"features": {
@@ -47,10 +52,6 @@
"base": "anima",
"latent_channels": null
},
- {
- "base": "flux",
- "latent_channels": null
- },
{
"base": "qwen-image",
"latent_channels": null
@@ -66,7 +67,12 @@
"base": "cogview4",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "cogview4"
},
"features": {
@@ -110,7 +116,9 @@
"base": "ernie-image",
"variant": null,
"modality": {
- "modes": ["txt2img"],
+ "modes": [
+ "txt2img"
+ ],
"metadata_slug": "ernie_image"
},
"features": {
@@ -154,7 +162,12 @@
"base": "flux",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "flux"
},
"features": {
@@ -167,7 +180,10 @@
"guidance_label": "Guidance",
"scheduler_set": "flow",
"scheduler_applies_to_graph": true,
- "control_kinds": ["control_lora", "controlnet"],
+ "control_kinds": [
+ "control_lora",
+ "controlnet"
+ ],
"max_reference_images": 5,
"reference_images_require_variant": null,
"supports_regional_guidance": true,
@@ -198,7 +214,12 @@
"base": "flux",
"variant": "dev_fill",
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "flux"
},
"features": {
@@ -211,7 +232,10 @@
"guidance_label": "Guidance",
"scheduler_set": "flow",
"scheduler_applies_to_graph": true,
- "control_kinds": ["control_lora", "controlnet"],
+ "control_kinds": [
+ "control_lora",
+ "controlnet"
+ ],
"max_reference_images": 5,
"reference_images_require_variant": null,
"supports_regional_guidance": true,
@@ -242,7 +266,12 @@
"base": "flux",
"variant": "schnell",
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "flux"
},
"features": {
@@ -255,7 +284,10 @@
"guidance_label": "Guidance",
"scheduler_set": "flow",
"scheduler_applies_to_graph": true,
- "control_kinds": ["control_lora", "controlnet"],
+ "control_kinds": [
+ "control_lora",
+ "controlnet"
+ ],
"max_reference_images": 5,
"reference_images_require_variant": null,
"supports_regional_guidance": true,
@@ -286,7 +318,12 @@
"base": "flux2",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "flux2"
},
"features": {
@@ -330,7 +367,12 @@
"base": "flux2",
"variant": "dev",
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "flux2"
},
"features": {
@@ -374,7 +416,12 @@
"base": "flux2",
"variant": "klein_4b_base",
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "flux2"
},
"features": {
@@ -418,7 +465,12 @@
"base": "flux2",
"variant": "klein_9b_base",
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "flux2"
},
"features": {
@@ -462,7 +514,9 @@
"base": "ideogram-4",
"variant": null,
"modality": {
- "modes": ["txt2img"],
+ "modes": [
+ "txt2img"
+ ],
"metadata_slug": "ideogram4"
},
"features": {
@@ -506,7 +560,12 @@
"base": "krea-2",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "krea2"
},
"features": {
@@ -561,7 +620,12 @@
"base": "krea-2",
"variant": "krea2_base",
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "krea2"
},
"features": {
@@ -616,7 +680,15 @@
"base": "minimax-h3",
"variant": null,
"modality": {
- "modes": ["extend_video", "flf2v", "i2v", "lf2v", "ref2v", "t2v", "txt2img"],
+ "modes": [
+ "extend_video",
+ "flf2v",
+ "i2v",
+ "lf2v",
+ "ref2v",
+ "t2v",
+ "txt2img"
+ ],
"metadata_slug": "minimax_h3"
},
"features": {
@@ -660,7 +732,12 @@
"base": "qwen-image",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "qwen_image"
},
"features": {
@@ -715,7 +792,12 @@
"base": "sd-1",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": null
},
"features": {
@@ -728,7 +810,10 @@
"guidance_label": "CFG",
"scheduler_set": "standard",
"scheduler_applies_to_graph": true,
- "control_kinds": ["controlnet", "t2i_adapter"],
+ "control_kinds": [
+ "controlnet",
+ "t2i_adapter"
+ ],
"max_reference_images": 5,
"reference_images_require_variant": null,
"supports_regional_guidance": true,
@@ -759,7 +844,12 @@
"base": "sd-2",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": null
},
"features": {
@@ -803,7 +893,12 @@
"base": "sd-3",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "sd3"
},
"features": {
@@ -847,7 +942,12 @@
"base": "sdxl",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "sdxl"
},
"features": {
@@ -860,7 +960,10 @@
"guidance_label": "CFG",
"scheduler_set": "standard",
"scheduler_applies_to_graph": true,
- "control_kinds": ["controlnet", "t2i_adapter"],
+ "control_kinds": [
+ "controlnet",
+ "t2i_adapter"
+ ],
"max_reference_images": 5,
"reference_images_require_variant": null,
"supports_regional_guidance": true,
@@ -935,7 +1038,16 @@
"base": "wan",
"variant": null,
"modality": {
- "modes": ["extend_video", "i2v", "img2img", "inpaint", "interpolate", "outpaint", "t2v", "txt2img"],
+ "modes": [
+ "extend_video",
+ "i2v",
+ "img2img",
+ "inpaint",
+ "interpolate",
+ "outpaint",
+ "t2v",
+ "txt2img"
+ ],
"metadata_slug": "wan"
},
"features": {
@@ -990,7 +1102,16 @@
"base": "wan",
"variant": "ti2v_5b",
"modality": {
- "modes": ["extend_video", "i2v", "img2img", "inpaint", "interpolate", "outpaint", "t2v", "txt2img"],
+ "modes": [
+ "extend_video",
+ "i2v",
+ "img2img",
+ "inpaint",
+ "interpolate",
+ "outpaint",
+ "t2v",
+ "txt2img"
+ ],
"metadata_slug": "wan"
},
"features": {
@@ -1045,7 +1166,12 @@
"base": "z-image",
"variant": null,
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "z_image"
},
"features": {
@@ -1058,7 +1184,9 @@
"guidance_label": "CFG",
"scheduler_set": "flow",
"scheduler_applies_to_graph": true,
- "control_kinds": ["z_image_control"],
+ "control_kinds": [
+ "z_image_control"
+ ],
"max_reference_images": 0,
"reference_images_require_variant": null,
"supports_regional_guidance": true,
@@ -1096,7 +1224,12 @@
"base": "z-image",
"variant": "zbase",
"modality": {
- "modes": ["img2img", "inpaint", "outpaint", "txt2img"],
+ "modes": [
+ "img2img",
+ "inpaint",
+ "outpaint",
+ "txt2img"
+ ],
"metadata_slug": "z_image"
},
"features": {
@@ -1109,7 +1242,9 @@
"guidance_label": "CFG",
"scheduler_set": "flow",
"scheduler_applies_to_graph": true,
- "control_kinds": ["z_image_control"],
+ "control_kinds": [
+ "z_image_control"
+ ],
"max_reference_images": 0,
"reference_images_require_variant": null,
"supports_regional_guidance": true,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts
index 4a9f4ce640..fb4d700878 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.test.ts
@@ -11,10 +11,12 @@ import { afterEach, describe, expect, it } from 'vitest';
import fixture from './__fixtures__/architectureCapabilities.json';
import {
type ArchitectureCapabilitiesRow,
+ getArchitectureCapabilitiesRevision,
getArchitectureCapabilityRow,
getArchitectureFeatures,
getArchitectureGenerationConfig,
hasArchitectureCapabilities,
+ onArchitectureCapabilitiesChanged,
resetArchitectureCapabilities,
setArchitectureCapabilities,
toBaseGenerationConfig,
@@ -139,3 +141,45 @@ describe('the registry', () => {
expect(getArchitectureFeatures('sd-1')).toBeUndefined();
});
});
+
+describe('publishing the table', () => {
+ it('stays empty when a malformed row makes the mapping throw', () => {
+ // The wire type is applied by an unchecked `as` in the api module, so a row the backend never
+ // meant to serve is reachable. Publishing the rows before mapping them left the registry
+ // saying "loaded" over an empty config map: the widget would show the load error while every
+ // fail-closed gate elsewhere opened onto fallback policy for every architecture.
+ const malformed = [...rows, { base: 'broken', variant: null } as unknown as ArchitectureCapabilitiesRow];
+
+ expect(() => setArchitectureCapabilities(malformed)).toThrow();
+ expect(hasArchitectureCapabilities()).toBe(false);
+ expect(getArchitectureCapabilitiesRevision()).toBe(0);
+ expect(getArchitectureGenerationConfig('sd-1')).toBeUndefined();
+ });
+
+ it('keeps the previous table intact when a later push is malformed', () => {
+ setArchitectureCapabilities(rows);
+ const revision = getArchitectureCapabilitiesRevision();
+
+ expect(() =>
+ setArchitectureCapabilities([{ base: 'broken', variant: null } as unknown as ArchitectureCapabilitiesRow])
+ ).toThrow();
+ expect(getArchitectureCapabilitiesRevision()).toBe(revision);
+ expect(getArchitectureGenerationConfig('sd-1')?.defaults.steps).toBe(30);
+ });
+
+ it('notifies subscribers when the table is replaced or dropped', () => {
+ // The single subscription contract behind every imperative reader: renders, the bbox grid, the
+ // Invoke gate and the bbox <-> dims sync all re-read on this.
+ const seen: number[] = [];
+ const unsubscribe = onArchitectureCapabilitiesChanged(() => seen.push(getArchitectureCapabilitiesRevision()));
+
+ setArchitectureCapabilities(rows);
+ resetArchitectureCapabilities();
+ // Already empty: nothing changed, so nothing is announced.
+ resetArchitectureCapabilities();
+ unsubscribe();
+ setArchitectureCapabilities(rows);
+
+ expect(seen).toEqual([1, 0]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts
index 5f57adc376..f75a94aaa4 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/architectureCapabilities.ts
@@ -15,6 +15,8 @@
* from here -- the same shape `configureHttpAuth` uses in `platform/transport/http.ts`.
*/
+import { createListenerChannel } from '@platform/state/externalStoreCore';
+
import type { BaseGenerationConfig, GuidanceLabel, NegativePromptUsage, SchedulerSetId } from './generationConfig';
/** A capabilities row exactly as the backend serialises it. snake_case, unions kept open. */
@@ -139,20 +141,52 @@ const key = (base: string, variant: string | null): string => `${base}\u0000${va
let rows: readonly ArchitectureCapabilitiesRow[] | null = null;
let byKey = new Map<string, ArchitectureCapabilitiesRow>();
let configByKey = new Map<string, BaseGenerationConfig>();
+let revision = 0;
+
+/**
+ * Fires whenever the table below is replaced or dropped.
+ *
+ * Everything here is synchronous module state, read during render and at enqueue time from all over
+ * the app. Without a change signal a reader that answered before the table arrived keeps its
+ * fallback answer for the rest of the session -- it has nothing to re-read on. `data/` mirrors this
+ * into its snapshot, so React and non-React readers subscribe to one signal.
+ */
+const channel = createListenerChannel();
+
+/** Subscribe to table replacements. Returns an unsubscribe function. */
+export const onArchitectureCapabilitiesChanged = channel.subscribe;
+
+/** Identity of the table currently held; `0` while there is none. */
+export const getArchitectureCapabilitiesRevision = (): number => revision;
/** Called by `data/` once the table has been fetched. */
export const setArchitectureCapabilities = (next: readonly ArchitectureCapabilitiesRow[]): void => {
- rows = next;
- byKey = new Map(next.map((row) => [key(row.base, row.variant), row]));
+ // Built into locals, then swapped in one step. Assigning `rows` first would publish a table that
+ // `hasArchitectureCapabilities` reports as present while the rows are still being mapped: a
+ // malformed row's throw would then leave every fail-closed gate open over an empty config map,
+ // so the widget would show the load error while the canvas and topbar used fallback policy.
+ const nextByKey = new Map(next.map((row) => [key(row.base, row.variant), row]));
// Memoised so policy accessors stay O(1) and hand back referentially stable objects.
- configByKey = new Map(next.map((row) => [key(row.base, row.variant), toBaseGenerationConfig(row)]));
+ const nextConfigByKey = new Map(next.map((row) => [key(row.base, row.variant), toBaseGenerationConfig(row)]));
+
+ rows = next;
+ byKey = nextByKey;
+ configByKey = nextConfigByKey;
+ revision += 1;
+ channel.notify();
};
/** Drop the table. The store calls this on account change; tests call it to isolate. */
export const resetArchitectureCapabilities = (): void => {
+ if (rows === null) {
+ return;
+ }
+
rows = null;
byKey = new Map();
configByKey = new Map();
+ revision = 0;
+ channel.notify();
};
export const hasArchitectureCapabilities = (): boolean => rows !== null;
@@ -186,5 +220,7 @@ export const getArchitectureGenerationConfig = (base: string, variant?: unknown)
* `features` block onto every variant row of an architecture, so asking per variant would suggest
* a precision that is not there.
*/
-export const getArchitectureFeatures = (base: string): ArchitectureCapabilitiesRow['features'] | undefined =>
- byKey.get(key(base, null))?.features;
+export const getArchitectureFeatures = (
+ base: string,
+ variant?: unknown
+): ArchitectureCapabilitiesRow['features'] | undefined => getArchitectureCapabilityRow(base, variant)?.features;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
index 17de282230..02b2c4a3bc 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
@@ -1297,3 +1297,58 @@ describe('without the capability table', () => {
expect(getGenerationValidationReasons(model, settings)[0] ?? '').not.toMatch(/capabilities/i);
});
});
+
+describe('with a table that omits this architecture', () => {
+ /**
+ * A served table is not the same as a described architecture. `isSupportedGenerateModel` answers
+ * from a static list of bases webv2 can build a graph for; a backend build that does not serve a
+ * row for one of them used to fall straight through to `FALLBACK_GENERATION_CONFIG` -- grid 8,
+ * 30 steps, CFG 7, euler_a -- and compile. Reference images already failed closed on a missing
+ * row; the rest of policy does now too.
+ */
+ const withoutBase = (base: string) => architectureCapabilitiesFixture.filter((row) => row.base !== base);
+
+ it('blocks a supported base the backend did not describe', () => {
+ const model = createModel('cogview4');
+ const settings = createSettings(model);
+
+ setArchitectureCapabilities(withoutBase('cogview4'));
+
+ expect(getGenerationValidationReasons(model, settings)).toEqual([
+ 'The backend does not describe the cogview4 architecture, so it cannot be generated with.',
+ ]);
+ });
+
+ it('leaves the architectures it did describe alone', () => {
+ const model = createModel('sdxl');
+
+ setArchitectureCapabilities(withoutBase('cogview4'));
+
+ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([]);
+ });
+
+ it('never asks the table about an external generator, which has no architecture row', () => {
+ setArchitectureCapabilities(withoutBase('cogview4'));
+
+ expect(getGenerationValidationReasons(externalModel, createSettings(externalModel))).toEqual([]);
+ });
+});
+
+describe('getGenerationDimensions and the variant it dispatches on', () => {
+ it('answers from the variant row when one differs, which its parameter type now admits', () => {
+ // `getBaseGenerationConfig` prefers a variant row and `optimalSide` comes from that row's
+ // default canvas, so the answer is variant-specific -- but the signature used to accept only
+ // `{ base, type }`, so a caller that built one of those type-checked and silently got the
+ // architecture's row. Every served variant declares 1024x1024 today, so the divergence has to
+ // be constructed to be observed at all.
+ const schnell = architectureCapabilitiesFixture.find((row) => row.base === 'flux' && row.variant === 'schnell')!;
+
+ setArchitectureCapabilities([
+ ...architectureCapabilitiesFixture.filter((row) => row !== schnell),
+ { ...schnell, defaults: { ...schnell.defaults!, height: 512, width: 512 } },
+ ]);
+
+ expect(getGenerationDimensions({ base: 'flux', type: 'main', variant: 'schnell' }).optimal).toBe(512);
+ expect(getGenerationDimensions({ base: 'flux', type: 'main' }).optimal).toBe(1024);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index fe8d652e5f..3219883d55 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -218,8 +218,9 @@ const FALLBACK_GENERATION_CONFIG: BaseGenerationConfig = {
*
* The variant matters: FLUX Schnell wants 4 steps where dev wants 28, and the endpoint answers per
* variant where they differ. Falling back keeps UI selectors crash-safe for external generators and
- * for an architecture the backend does not know; `isSupportedGenerateModel` still blocks invocation,
- * and `resolveGenerateWidgetValues` refuses to resolve at all until the table has arrived.
+ * for an architecture the backend does not know. It is not a licence to generate with fallback
+ * policy: `isArchitectureDescribed` is what blocks invocation for a supported base the served table
+ * omits, and `resolveGenerateWidgetValues` will not even select such a model.
*/
const getBaseGenerationConfig = (
model: (Pick<GenerateModelConfig, 'base' | 'type'> & { variant?: unknown }) | undefined
@@ -235,11 +236,26 @@ const getBaseGenerationConfig = (
* The pixel grid generation dimensions must land on, or `null` if the backend has no row for this
* architecture.
*
+ * Variant-dependent: Wan A14B enforces multiples of 16 on its denoise node, TI2V-5B multiples of
+ * 32 in the reference-image encoder. Passing the variant is how the canvas offers a size that
+ * survives enqueue; omitting it falls back to the architecture's own row.
+ *
* `null` rather than a default so callers keep owning their own "nothing selected" behaviour --
* the canvas has a different sensible answer there than a generation graph does.
*/
-export const getDimensionGridForBase = (base: string): number | null =>
- getArchitectureFeatures(base)?.dimension_grid ?? null;
+export const getDimensionGrid = (base: string, variant?: unknown): number | null =>
+ getArchitectureFeatures(base, variant)?.dimension_grid ?? null;
+
+/**
+ * Whether the served table actually describes this model's architecture.
+ *
+ * `isSupportedGenerateModel` answers from a static list of bases webv2 can build a graph for, which
+ * says nothing about whether the *backend* described that base in this build. Generating on a base
+ * the table omits would silently use `FALLBACK_GENERATION_CONFIG` -- grid 8, 30 steps, CFG 7 -- for
+ * an architecture whose denoise node may enforce something else entirely.
+ */
+export const isArchitectureDescribed = (model: Pick<GenerateModelConfig, 'base' | 'type'>): boolean =>
+ model.type === 'external_image_generator' || getArchitectureFeatures(model.base) !== undefined;
const getNumber = (value: number | null | undefined, fallback: number): number =>
Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;
@@ -253,7 +269,10 @@ const getNumber = (value: number | null | undefined, fallback: number): number =
* optimal side becomes PiD's 2048 rather than the model's 1024.
*/
export const getGenerationDimensions = (
- model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined,
+ // `variant` participates: `getBaseGenerationConfig` prefers a variant row where the backend
+ // answers differently, and `optimalSide` comes from that row's default canvas. Optional because
+ // an architecture always has its own row; omitting it asks for the architecture's answer.
+ model: (Pick<GenerateModelConfig, 'base' | 'type'> & { variant?: unknown }) | undefined,
pidMode: PidMode = 'off'
) => {
const config = getBaseGenerationConfig(model);
@@ -1629,6 +1648,13 @@ export const getGenerationValidationReasons = (model: GenerateModelConfig, setti
return ['Generate needs a supported model before it can be invoked.'];
}
+ // A loaded table is not the same as a described architecture: a base inside `SUPPORTED_GENERATE_BASES`
+ // that this backend build does not serve a row for would otherwise compile against the fallback
+ // config. Reference images already fail closed this way; so does everything else now.
+ if (!isArchitectureDescribed(model)) {
+ return [`The backend does not describe the ${model.base} architecture, so it cannot be generated with.`];
+ }
+
const reasons = [
...getDimensionValidationReasons(model, settings),
...getReferenceImageValidationReasons(model, settings),
diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts
index b5e063f7f5..75cdf5a65a 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts
@@ -1,3 +1,4 @@
+import { resetArchitectureCapabilities } from '@features/generation/core/architectureCapabilities';
import {
seedArchitectureCapabilities,
architectureCapabilitiesFixture,
@@ -145,10 +146,27 @@ describe('Generate component compatibility', () => {
it('allows only backend-supported Anima VAE families', () => {
expect(isAnimaVae(candidate({ base: 'anima', type: 'vae' }))).toBe(true);
expect(isAnimaVae(candidate({ base: 'qwen-image', type: 'vae' }))).toBe(true);
- expect(isAnimaVae(candidate({ base: 'flux', type: 'vae' }))).toBe(true);
+ expect(isAnimaVae(candidate({ base: 'wan', latent_channels: 16, type: 'vae' }))).toBe(true);
+ expect(isAnimaVae(candidate({ base: 'wan', latent_channels: 48, type: 'vae' }))).toBe(false);
+ // A FLUX VAE decodes an Anima latent without raising and returns a magenta smear.
+ expect(isAnimaVae(candidate({ base: 'flux', type: 'vae' }))).toBe(false);
expect(isAnimaVae(candidate({ base: 'sdxl', type: 'vae' }))).toBe(false);
});
+ it('offers no VAE at all before the capability table has loaded', () => {
+ resetArchitectureCapabilities();
+
+ expect(isAnimaVae(candidate({ base: 'anima', type: 'vae' }))).toBe(false);
+ expect(
+ isVaeCompatibleWithGenerateModel({ base: 'sdxl', key: 'sdxl', name: 'SDXL', type: 'main' }, {
+ base: 'sdxl',
+ key: 'sdxl-vae',
+ name: 'SDXL VAE',
+ type: 'vae',
+ } as VaeModelConfig)
+ ).toBe(false);
+ });
+
it('centralizes generate VAE compatibility for cross-base families', () => {
const vae = (base: string) => ({ base, key: `${base}-vae`, name: `${base} VAE`, type: 'vae' as const });
@@ -187,40 +205,84 @@ describe('isVaeForBases', () => {
});
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;
+
+ const vaeOf = (base: string, latentChannels?: number) =>
+ ({
+ base,
+ key: `${base}-vae`,
+ name: `${base} vae`,
+ type: 'vae' as const,
+ ...(latentChannels === undefined ? {} : { latent_channels: latentChannels }),
+ }) as unknown as VaeModelConfig;
+
+ const ALL_BASES = [...new Set(architectureCapabilitiesFixture.map((row) => row.base))];
+
/**
- * webv2 keeps its own copy of which VAE bases a model accepts, and the backend now declares the
- * same fact in `VaeFacet`. Two copies drift: this PR widened qwen-image to accept the anima
+ * webv2 kept its own copy of which VAE bases a model accepts, and the backend declares the same
+ * fact in `VaeFacet`. Two copies drift: this PR widened qwen-image to accept the anima
* registration and the picker kept refusing it, so a VAE the backend would have loaded could not
- * be selected. Binding the filter to the served table is what makes the next widening show up
- * here instead of in a user's model list.
+ * be selected. Reading the served table is what makes the next widening show up here instead of
+ * in a user's model list.
*/
it('accepts every VAE base the backend declares for that architecture', () => {
const declared = architectureCapabilitiesFixture.filter((row) => row.vae);
expect(declared.length).toBeGreaterThan(0);
for (const row of declared) {
- const model = {
- base: row.base,
- key: `${row.base}-main`,
- name: row.base,
- type: 'main' as const,
- } as unknown as GenerateModelConfig;
-
for (const accepted of row.vae!.accepted) {
- const vae = {
- base: accepted.base,
- key: `${accepted.base}-vae`,
- name: `${accepted.base} vae`,
- type: 'vae' as const,
- // Only wan distinguishes VAEs by latent width; the others leave it null.
- ...(accepted.latent_channels === null ? {} : { latent_channels: accepted.latent_channels }),
- } as unknown as VaeModelConfig;
-
expect(
- isVaeCompatibleWithGenerateModel(model, vae),
+ // Only wan distinguishes VAEs by latent width; the others leave it null.
+ isVaeCompatibleWithGenerateModel(
+ mainOf(row.base),
+ vaeOf(accepted.base, accepted.latent_channels ?? undefined)
+ ),
`${row.base} should accept a VAE registered under ${accepted.base}`
).toBe(true);
}
}
});
+
+ /**
+ * The half a one-directional check cannot see. This PR's headline VAE bug was a *narrowing* —
+ * Klein silently losing `flux` — and a filter that returned `true` for everything would satisfy
+ * the loop above while offering VAEs that decode to noise.
+ */
+ it('rejects every VAE base the backend does not declare for that architecture', () => {
+ for (const row of architectureCapabilitiesFixture) {
+ const accepted = row.vae?.accepted ?? [{ base: row.base, latent_channels: null }];
+ const acceptedBases = new Set(accepted.map((entry) => entry.base));
+
+ for (const base of ALL_BASES) {
+ if (acceptedBases.has(base)) {
+ continue;
+ }
+ expect(
+ isVaeCompatibleWithGenerateModel(mainOf(row.base), vaeOf(base)),
+ `${row.base} should refuse a VAE registered under ${base}`
+ ).toBe(false);
+ }
+
+ // A width constraint is a real constraint: wan ships a 16- and a 48-channel VAE under one
+ // base, and only one of them belongs to the family an architecture decodes with.
+ for (const entry of accepted) {
+ if (entry.latent_channels === null) {
+ continue;
+ }
+ const otherWidth = entry.latent_channels === 16 ? 48 : 16;
+ if (accepted.some((other) => other.base === entry.base && other.latent_channels === otherWidth)) {
+ continue;
+ }
+ expect(
+ isVaeCompatibleWithGenerateModel(mainOf(row.base), vaeOf(entry.base, otherWidth)),
+ `${row.base} should refuse a ${otherWidth}-channel ${entry.base} VAE`
+ ).toBe(false);
+ }
+ }
+ });
+
+ it('refuses an architecture the table says nothing about', () => {
+ expect(isVaeCompatibleWithGenerateModel(mainOf('not-an-architecture'), vaeOf('not-an-architecture'))).toBe(false);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts
index fdb9a7300a..4afea0d410 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts
@@ -1,5 +1,7 @@
import type { ComponentModelConfig, GenerateModelConfig, VaeModelConfig } from './types';
+import { getArchitectureCapabilityRow } from './architectureCapabilities';
+
export type GenerateComponentCandidate = {
base: string;
format?: string;
@@ -142,50 +144,68 @@ export const getCompatibleDiffusersComponentSource = <T extends GenerateComponen
source && isCompatibleDiffusersComponentSourceForModel(selectedModel, source) ? source : undefined;
/**
- * Anima's decode takes an `AutoencoderKLWan` or a `FluxAutoEncoder`, and the Wan-family file is the
- * same 194-tensor checkpoint whichever base it was installed under — see the `VaeFacet` in
- * `architectures/defs/anima.py`, which is where this list is declared. The 48-channel Wan VAE is a
- * different decoder, so the width is part of the condition rather than the base alone.
+ * Whether an architecture's decode accepts this VAE, as the backend declares it.
+ *
+ * The single reader of `vae.accepted` from the served capability table — the same `VaeFacet` the
+ * loaders and `accepts_vae()` read in `architectures/defs/<base>.py`. Which VAE families a base can
+ * decode used to be hand-written here as a `switch` over literal base lists, and that copy drifted:
+ * it offered Anima a FLUX VAE, which decodes a WAN21_16 latent in FLUX's basis and returns a
+ * magenta smear rather than an error (6.10 dB PSNR, measured).
+ *
+ * Fail closed, like `resolveGenerateWidgetValues` and `getGenerationValidationReasons`: with no
+ * 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.
*/
-export const isAnimaVae: GenerateComponentFilter = (model) =>
- model.type === 'vae' &&
- (['anima', 'qwen-image', 'flux'].includes(model.base) || (model.base === 'wan' && model.latent_channels === 16));
+const acceptsVae = (base: string, model: GenerateComponentCandidate): boolean => {
+ if (model.type !== 'vae') {
+ return false;
+ }
+
+ const row = getArchitectureCapabilityRow(base);
+
+ if (!row) {
+ return false;
+ }
+
+ // A null `vae` block is the backend saying "its own base, no constraints" — what `accepts_vae`
+ // answers for an architecture that declares no facet. It is a declaration, not a missing one.
+ if (!row.vae) {
+ return model.base === base;
+ }
+
+ return row.vae.accepted.some(
+ (accepted) =>
+ accepted.base === model.base &&
+ (accepted.latent_channels === null || model.latent_channels === accepted.latent_channels)
+ );
+};
+
+export const isVaeAcceptedByBase =
+ (base: string): GenerateComponentFilter =>
+ (model) =>
+ acceptsVae(base, model);
/**
- * Krea-2 decodes with the Qwen-Image VAE (16-channel), which is why its graph reuses
- * `qwen_image_l2i`. `anima` is accepted alongside `qwen-image` because the same physical VAE
- * is registered under either base depending on which family it was installed for — matching
- * `krea2_model_loader`'s own `ui_model_base=[QwenImage, Anima]`. Restricting this to
- * `qwen-image` hides a working VAE that the backend would have accepted.
+ * Anima's decode takes the 16-channel Wan 2.1 VAE, which is the same 194-tensor checkpoint
+ * whichever of three bases it was installed under. The 48-channel Wan VAE is a different decoder,
+ * which is why the served row constrains the width as well as the base.
*/
+export const isAnimaVae: GenerateComponentFilter = isVaeAcceptedByBase('anima');
+
+/** Qwen-Image's VAE, wherever it is registered from. */
+export const isQwenImageFamilyVae: GenerateComponentFilter = isVaeAcceptedByBase('qwen-image');
+
/**
- * Qwen-Image's VAE, wherever it is registered from.
- *
- * The same weights ship registered under either base, which is why the backend's `VaeFacet` for
- * qwen-image accepts both — see `architectures/defs/qwen_image.py`. Krea-2 decodes with this VAE
- * too, so it shares the predicate rather than keeping a second list that can drift from it.
+ * Krea-2 decodes with the Qwen-Image VAE, which is why its graph reuses `qwen_image_l2i`. It reads
+ * its own row rather than aliasing Qwen-Image's: they agree today, and the point of reading the
+ * table is that neither has to stay in step with the other by hand.
*/
-export const isQwenImageFamilyVae = isVaeForBases(['qwen-image', 'anima']);
-
-export const isKrea2Vae = isQwenImageFamilyVae;
+export const isKrea2Vae: GenerateComponentFilter = isVaeAcceptedByBase('krea-2');
export const isVaeCompatibleWithGenerateModel = (model: GenerateModelConfig, vae: VaeModelConfig): boolean => {
if (model.type === 'external_image_generator') {
return false;
}
- switch (model.base) {
- case 'anima':
- return isAnimaVae(vae);
- case 'z-image':
- return isVaeForBases(['flux'])(vae);
- case 'qwen-image':
- return isQwenImageFamilyVae(vae);
- case 'krea-2':
- return isKrea2Vae(vae);
- case 'flux2':
- return isVaeForBases(['flux2'])(vae);
- default:
- return vae.type === 'vae' && vae.base === model.base;
- }
+ return acceptsVae(model.base, vae);
};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts
index fc55038830..8350f9bfeb 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts
@@ -215,3 +215,29 @@ describe('without the backend capability table', () => {
expect(resolveGenerateWidgetValues({ models: [model], storedValues: {} })).toBeNull();
});
});
+
+describe('resolveGenerateWidgetValues and an architecture the table omits', () => {
+ const rows = capabilitiesFixture as ArchitectureCapabilitiesRow[];
+
+ it('will not select a model whose architecture the backend did not describe', () => {
+ // The resolver's patch is persisted. Selecting a model with no row would write the fallback's
+ // grid, optimal size, step count and scheduler into the project file -- the same reason the
+ // whole resolver waits for the table in the first place, one level finer.
+ setArchitectureCapabilities(rows.filter((row) => row.base !== 'cogview4'));
+
+ expect(
+ resolveGenerateWidgetValues({ models: [createModel('cogview', { base: 'cogview4' })], storedValues: undefined })
+ ).toBeNull();
+ });
+
+ it('falls back to a described model rather than blocking the whole catalog', () => {
+ setArchitectureCapabilities(rows.filter((row) => row.base !== 'cogview4'));
+
+ const resolved = resolveGenerateWidgetValues({
+ models: [createModel('cogview', { base: 'cogview4' }), createModel('sdxl-model')],
+ storedValues: { modelKey: 'cogview' },
+ });
+
+ expect(resolved?.values.modelKey).toBe('sdxl-model');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts
index c7488e0718..08e67b2584 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts
@@ -8,6 +8,7 @@ import type { GenerateWidgetValues } from './types';
import {
getAutoFlux2ComponentSourceModel,
getDefaultGenerateSettings,
+ isArchitectureDescribed,
isSupportedGenerateModel,
} from './baseGenerationPolicies';
import { syncPromptTemplateWithCatalog } from './promptTemplates';
@@ -76,7 +77,11 @@ export const resolveGenerateWidgetValues = ({
return null;
}
- const supportedModels = models.filter(isSupportedGenerateModel);
+ // Described, not merely supported: `getDefaultGenerateSettings` below reads the architecture's
+ // grid, optimal size, steps and scheduler, and this resolver's patch is persisted. Selecting a
+ // base the served table omits would write `FALLBACK_GENERATION_CONFIG` into the project file --
+ // the same reason the whole resolver waits for the table in the first place.
+ const supportedModels = models.filter(isSupportedGenerateModel).filter(isArchitectureDescribed);
if (supportedModels.length === 0) {
return null;
diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts
index 4054955b06..86e8853caf 100644
--- a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.test.ts
@@ -23,7 +23,7 @@ describe('architecture capabilities store', () => {
expect(registry.hasArchitectureCapabilities()).toBe(false);
await store.refreshArchitectureCapabilities();
- expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: null, status: 'loaded' });
+ expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: null, revision: 1, status: 'loaded' });
expect(registry.getArchitectureGenerationConfig('sd-1')?.defaults.steps).toBe(30);
});
@@ -45,7 +45,7 @@ describe('architecture capabilities store', () => {
await store.refreshArchitectureCapabilities();
- expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: 'outage', status: 'error' });
+ expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: 'outage', revision: 0, status: 'error' });
expect(registry.hasArchitectureCapabilities()).toBe(false);
});
@@ -80,7 +80,69 @@ describe('architecture capabilities store', () => {
lifecycle.accountLifecycle.invalidate();
- expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: null, status: 'idle' });
+ expect(store.getArchitectureCapabilitiesSnapshot()).toEqual({ error: null, revision: 0, status: 'idle' });
expect(registry.hasArchitectureCapabilities()).toBe(false);
});
+
+ it('publishes the registry rather than its own request state', async () => {
+ // The subscription contract for every imperative policy reader. It has to follow the registry,
+ // not this store's fetch: `status` would miss a table that arrived by any other route, and a
+ // reader gated on it would keep answering from the fallback config.
+ api.getArchitectureCapabilities.mockResolvedValue(rows);
+ const store = await import('./architectureCapabilitiesStore');
+ const registry = await import('@features/generation/core/architectureCapabilities');
+ const seen: number[] = [];
+ const unsubscribe = store.subscribeArchitectureCapabilities(() =>
+ seen.push(store.getArchitectureCapabilitiesSnapshot().revision)
+ );
+
+ registry.setArchitectureCapabilities(rows as never);
+ expect(store.getArchitectureCapabilitiesSnapshot().revision).toBe(1);
+
+ registry.resetArchitectureCapabilities();
+ unsubscribe();
+
+ expect(seen).toContain(1);
+ expect(store.getArchitectureCapabilitiesSnapshot().revision).toBe(0);
+ });
+
+ it('reloads the table for the account that replaces the one it was cleared for', async () => {
+ // The boot kick lives in a mount effect that does not re-run, and the long-lived subscribers
+ // (the bbox <-> dims sync, the topbar) never re-subscribe. Without this re-arm a table cleared
+ // on an account change would stay `idle` forever and every gate would stay closed.
+ api.getArchitectureCapabilities.mockResolvedValue(rows);
+ const lifecycle = await import('@platform/state/accountLifecycle');
+ const store = await import('./architectureCapabilitiesStore');
+ const registry = await import('@features/generation/core/architectureCapabilities');
+
+ store.ensureArchitectureCapabilitiesLoaded();
+ await store.refreshArchitectureCapabilities();
+ expect(registry.hasArchitectureCapabilities()).toBe(true);
+
+ lifecycle.accountLifecycle.activate('account-2');
+ expect(registry.hasArchitectureCapabilities()).toBe(false);
+
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(store.getArchitectureCapabilitiesSnapshot().status).toBe('loaded');
+ expect(registry.hasArchitectureCapabilities()).toBe(true);
+
+ lifecycle.accountLifecycle.invalidate();
+ });
+
+ it('does not fetch for a signed-out lifetime', async () => {
+ api.getArchitectureCapabilities.mockResolvedValue(rows);
+ const lifecycle = await import('@platform/state/accountLifecycle');
+ const store = await import('./architectureCapabilitiesStore');
+
+ store.ensureArchitectureCapabilitiesLoaded();
+ await store.refreshArchitectureCapabilities();
+ api.getArchitectureCapabilities.mockClear();
+
+ lifecycle.accountLifecycle.invalidate();
+
+ await Promise.resolve();
+ expect(api.getArchitectureCapabilities).not.toHaveBeenCalled();
+ expect(store.getArchitectureCapabilitiesSnapshot().status).toBe('idle');
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts
index 46a52be338..958ab54c33 100644
--- a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts
+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts
@@ -1,4 +1,6 @@
import {
+ getArchitectureCapabilitiesRevision,
+ onArchitectureCapabilitiesChanged,
resetArchitectureCapabilities,
setArchitectureCapabilities,
} from '@features/generation/core/architectureCapabilities';
@@ -27,20 +29,46 @@ import { getArchitectureCapabilities } from './architectureCapabilitiesApi';
export interface ArchitectureCapabilitiesSnapshot {
status: 'idle' | 'loading' | 'loaded' | 'error';
error: string | null;
+ /**
+ * Identity of the table in the core registry; `0` while there is none.
+ *
+ * This is the whole subscription contract for the many readers that call the synchronous policy
+ * accessors during render or at enqueue time: subscribe to this, and re-read when it changes.
+ * `status` cannot serve that purpose -- it describes this store's request, not the registry, and
+ * a reader gated on it would miss a table seeded by anything but a fetch.
+ */
+ revision: number;
}
-const EMPTY_SNAPSHOT: ArchitectureCapabilitiesSnapshot = { error: null, status: 'idle' };
+const EMPTY_SNAPSHOT: ArchitectureCapabilitiesSnapshot = { error: null, revision: 0, status: 'idle' };
const store = createExternalStore<ArchitectureCapabilitiesSnapshot>(EMPTY_SNAPSHOT);
+// The registry is the authority; this store publishes it. Mirroring here rather than alongside each
+// write means every path that fills or drops the table reaches subscribers, including tests that
+// seed it directly.
+onArchitectureCapabilitiesChanged(() => store.patchSnapshot({ revision: getArchitectureCapabilitiesRevision() }));
+
const refreshFlight = createTrailingSingleFlight();
+/** Whether anything in this session has asked for the table; see the account-change re-arm below. */
+let isRequested = false;
+
registerAccountOwnedResource({
clear: () => {
refreshFlight.reset();
- store.setSnapshot(EMPTY_SNAPSHOT);
// The registry is module state outside this store, so clearing the snapshot alone would leave
- // the previous account's table readable behind a status that says nothing is loaded.
+ // the previous account's table readable behind a status that says nothing is loaded. Dropped
+ // before the snapshot, so no subscriber is ever woken to read the old table at revision 0.
resetArchitectureCapabilities();
+ store.setSnapshot(EMPTY_SNAPSHOT);
+
+ // `activate` rotates the scope *before* clearing, so the incoming account is already current
+ // here. Re-arm rather than wait to be asked again: the app kicks the fetch once, at boot, from
+ // a mount effect that does not re-run, and the long-lived subscribers below never re-subscribe.
+ // A boot-time load that raced sign-in was aborted by that rotation; this is what replaces it.
+ if (isRequested && captureAccountScope().accountId !== null) {
+ void refreshArchitectureCapabilities();
+ }
},
name: 'architecture-capabilities',
});
@@ -73,6 +101,8 @@ export const refreshArchitectureCapabilities = (): Promise<void> =>
/** Fetch on first use or retry after an error, so one failed load never sticks. */
export const ensureArchitectureCapabilitiesLoaded = (): void => {
+ isRequested = true;
+
const { status } = store.getSnapshot();
if (status === 'idle' || status === 'error') {
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index d9bd1caa50..9443e895cf 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -41,7 +41,7 @@ export {
getDefaultGenerateSettings,
getDefaultReferenceImageConfig,
getGenerateModelSelectionResult,
- getDimensionGridForBase,
+ getDimensionGrid,
getGenerationDimensions,
getGenerationModelAvailabilityReasons,
getGenerationUiPolicy,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx
new file mode 100644
index 0000000000..200b62582c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.browser.test.tsx
@@ -0,0 +1,203 @@
+import type { GenerationModelCatalogItem } from '@features/generation/contracts';
+import type { ArchitectureCapabilitiesRow } from '@features/generation/core/architectureCapabilities';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
+import { ensureArchitectureCapabilitiesLoaded } from '@features/generation/data/architectureCapabilitiesStore';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GenerateWidgetView } from './GenerateWidgetView';
+import { GenerationUiProvider, type GenerationUiAdapter } from './GenerationUiContext';
+
+vi.mock('react-i18next', () => {
+ const messages: Record<string, string> = {
+ 'widgets.generate.capabilitiesLoadFailed': 'Could not load model capabilities from the backend.',
+ 'widgets.generate.loadingCapabilities': 'Loading model capabilities…',
+ 'widgets.generate.retry': 'Retry',
+ };
+
+ return { useTranslation: () => ({ t: (key: string) => messages[key] ?? key }) };
+});
+
+/**
+ * The form has its own suite; what this view owns is the capability gate and the values it hands
+ * down, so the stub reports exactly those two.
+ */
+vi.mock('./GenerateSettingsForm', () => ({
+ GenerateSettingsForm: ({
+ selectedModel,
+ settings,
+ }: {
+ selectedModel?: { key: string };
+ settings: { positivePrompt: string };
+ }) => (
+ <div data-testid="generate-form">{`model:${selectedModel?.key ?? 'none'} prompt:${settings.positivePrompt}`}</div>
+ ),
+}));
+
+const getArchitectureCapabilities = vi.fn<() => Promise<ArchitectureCapabilitiesRow[]>>();
+
+/** A request still in flight: the fetch neither resolves nor rejects while the assertions run. */
+const pendingRequest = (): Promise<ArchitectureCapabilitiesRow[]> =>
+ new Promise(() => {
+ // Intentionally never settles.
+ });
+
+vi.mock('@features/generation/data/architectureCapabilitiesApi', () => ({
+ getArchitectureCapabilities: () => getArchitectureCapabilities(),
+}));
+
+const OTHER_MODEL: GenerationModelCatalogItem = {
+ base: 'sdxl',
+ key: 'other-sdxl',
+ name: 'Other SDXL',
+ type: 'main',
+} as GenerationModelCatalogItem;
+
+const STORED_MODEL: GenerationModelCatalogItem = {
+ base: 'sdxl',
+ key: 'stored-sdxl',
+ name: 'Stored SDXL',
+ type: 'main',
+} as GenerationModelCatalogItem;
+
+/**
+ * Catalog and stored values are pinned module constants on purpose: the project store hands the
+ * view the same references on every render, which is what let a resolve attempted before the
+ * capability table arrived stay cached after the retry that fixed it.
+ */
+const CATALOG: readonly GenerationModelCatalogItem[] = [OTHER_MODEL, STORED_MODEL];
+
+const STORED_VALUES = {
+ cfgRescaleMultiplier: 0,
+ cfgScale: 7.5,
+ height: 1024,
+ modelKey: STORED_MODEL.key,
+ negativePrompt: '',
+ positivePrompt: 'a saved prompt',
+ scheduler: 'euler',
+ seed: 7,
+ shouldRandomizeSeed: false,
+ steps: 30,
+ width: 1024,
+};
+
+const patchGenerateSettings = vi.fn();
+
+const buildAdapter = (): GenerationUiAdapter =>
+ ({
+ models: { catalog: CATALOG, error: null, status: 'loaded' },
+ project: { activeProjectId: 'project-1', generateValues: STORED_VALUES },
+ settings: { patchGenerateSettings },
+ }) as unknown as GenerationUiAdapter;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const settle = async (run: () => void = () => undefined) => {
+ await act(async () => {
+ run();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 0);
+ });
+ });
+};
+
+const renderView = () =>
+ settle(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <GenerationUiProvider adapter={buildAdapter()}>
+ <GenerateWidgetView />
+ </GenerationUiProvider>
+ </ChakraProvider>
+ )
+ );
+
+const retryButton = (): HTMLButtonElement => {
+ const button = [...document.querySelectorAll('button')].find((candidate) => candidate.textContent === 'Retry');
+
+ if (!button) {
+ throw new Error('the retry button did not render');
+ }
+
+ return button;
+};
+
+const formStub = (): HTMLElement | null => document.querySelector('[data-testid="generate-form"]');
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ getArchitectureCapabilities.mockReset();
+ patchGenerateSettings.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ // Returns the capability store and the core registry to their unloaded state between tests.
+ accountLifecycle.invalidate();
+});
+
+describe('GenerateWidgetView capability gate', () => {
+ it('announces the wait for the capability table instead of rendering the form', async () => {
+ getArchitectureCapabilities.mockReturnValue(pendingRequest());
+
+ await renderView();
+ await settle(ensureArchitectureCapabilitiesLoaded);
+
+ const region = document.querySelector('[role="status"]');
+
+ expect(region?.getAttribute('aria-busy')).toBe('true');
+ expect(region?.getAttribute('aria-live')).toBe('polite');
+ expect(region?.textContent).toContain('Loading model capabilities');
+ expect(formStub()).toBeNull();
+ });
+
+ it('restores the project model once a retry loads the table', async () => {
+ getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));
+
+ await renderView();
+ await settle(ensureArchitectureCapabilitiesLoaded);
+
+ const alert = document.querySelector('[role="alert"]');
+
+ expect(alert?.textContent).toContain('Fixture capability outage.');
+ expect(formStub()).toBeNull();
+
+ getArchitectureCapabilities.mockResolvedValueOnce(architectureCapabilitiesFixture);
+
+ await settle(() => retryButton().click());
+
+ // The stored selection, not the catalog's first entry, and the project's own prompt.
+ expect(formStub()?.textContent).toBe('model:stored-sdxl prompt:a saved prompt');
+ });
+
+ it('keeps focus on the retry button while its own retry is in flight', async () => {
+ getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));
+
+ await renderView();
+ await settle(ensureArchitectureCapabilitiesLoaded);
+
+ getArchitectureCapabilities.mockReturnValue(pendingRequest());
+
+ await settle(() => {
+ retryButton().focus();
+ retryButton().click();
+ });
+
+ expect(document.activeElement).toBe(retryButton());
+ expect(retryButton().getAttribute('aria-busy')).toBe('true');
+ expect(retryButton().disabled).toBe(false);
+ expect(document.querySelector('[role="alert"]')?.getAttribute('aria-busy')).toBe('true');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
index 2966ec246e..b3d64b0e2c 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
@@ -1,7 +1,7 @@
import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';
import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';
-import { Stack, Text } from '@chakra-ui/react';
+import { HStack, Spinner, Stack, Text } from '@chakra-ui/react';
import { getDefaultGenerateSettings, isSupportedGenerateModel } from '@features/generation/core/baseGenerationPolicies';
import { isLoraModelConfig, normalizeGenerateSettings } from '@features/generation/core/settings';
import {
@@ -10,7 +10,7 @@ import {
} from '@features/generation/data/architectureCapabilitiesStore';
import { resolveGenerateWidgetValues } from '@features/generation/settings';
import { Button } from '@platform/ui/Button';
-import { useCallback, useMemo } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getGenerateFormCommitPatch } from './generateFormViewModel';
@@ -22,6 +22,7 @@ export const GenerateWidgetView = () => {
const ui = useGenerationUi();
const capabilitiesStatus = useArchitectureCapabilitiesSelector((snapshot) => snapshot.status);
const capabilitiesError = useArchitectureCapabilitiesSelector((snapshot) => snapshot.error);
+ const [hasRequestedRetry, setHasRequestedRetry] = useState(false);
const projectId = ui.project.activeProjectId;
const storedValues = ui.project.generateValues;
const error = ui.models.error;
@@ -33,10 +34,29 @@ export const GenerateWidgetView = () => {
() => models.filter((model): model is ModelConfig & LoraModelConfig => isLoraModelConfig(model)),
[models]
);
- const resolved = useMemo(() => resolveGenerateWidgetValues({ models, storedValues }), [models, storedValues]);
+ // The resolver reads the architecture table from the core registry and fails closed while it is
+ // absent, so the load status is a real input here: without it a resolve attempted before the
+ // table arrives would be cached as `null` and survive the retry that fixed it, leaving a saved
+ // project with an empty model picker.
+ const resolved = useMemo(
+ () => (capabilitiesStatus === 'loaded' ? resolveGenerateWidgetValues({ models, storedValues }) : null),
+ [capabilitiesStatus, models, storedValues]
+ );
const settings =
resolved?.values ?? normalizeGenerateSettings(storedValues) ?? getDefaultGenerateSettings(supportedModels[0]);
const selectedModel = resolved?.values.model;
+ // The click flips the status to `loading` synchronously. Keeping the failure surface mounted for
+ // the retry it started is what keeps the button -- and the user's focus -- in place.
+ const isRetrying = hasRequestedRetry && capabilitiesStatus === 'loading';
+
+ const retryCapabilities = useCallback(() => {
+ if (isRetrying) {
+ return;
+ }
+
+ setHasRequestedRetry(true);
+ ensureArchitectureCapabilitiesLoaded();
+ }, [isRetrying]);
const commitSettings = useCallback(
(nextSettings: GenerateSettings) => {
@@ -70,23 +90,44 @@ export const GenerateWidgetView = () => {
// own -- and a single keystroke would commit them. App boot kicks the fetch, so this is one round
// trip in practice.
if (capabilitiesStatus !== 'loaded') {
- return (
- <Stack gap="1.5" p="1">
- {capabilitiesStatus === 'error' ? (
- <>
- <Text color="fg.error" fontSize="2xs">
- {capabilitiesError ?? t('widgets.generate.capabilitiesLoadFailed')}
- </Text>
- <Button size="xs" variant="outline" onClick={ensureArchitectureCapabilitiesLoaded}>
- {t('widgets.generate.retry')}
- </Button>
- </>
- ) : (
- <Text color="fg.subtle" fontSize="2xs">
- {t('widgets.generate.loadingCapabilities')}
+ if (capabilitiesStatus === 'error' || isRetrying) {
+ return (
+ <Stack aria-busy={isRetrying} aria-live="polite" gap="2" justify="center" minH="8rem" p="1" role="alert">
+ <Text color="fg.error" fontSize="2xs" textWrap="pretty">
+ {capabilitiesError ?? t('widgets.generate.capabilitiesLoadFailed')}
</Text>
- )}
- </Stack>
+ {/* `aria-disabled` rather than `disabled`: a disabled button drops the focus it holds. */}
+ <Button
+ alignSelf="flex-start"
+ aria-busy={isRetrying}
+ aria-disabled={isRetrying}
+ size="xs"
+ variant="outline"
+ onClick={retryCapabilities}
+ >
+ {isRetrying ? <Spinner size="xs" /> : null}
+ {t('widgets.generate.retry')}
+ </Button>
+ </Stack>
+ );
+ }
+
+ return (
+ <HStack
+ align="center"
+ aria-atomic="true"
+ aria-busy="true"
+ aria-live="polite"
+ color="fg.muted"
+ gap="1.5"
+ justify="center"
+ minH="8rem"
+ p="1"
+ role="status"
+ >
+ <Spinner size="xs" />
+ <Text fontSize="2xs">{t('widgets.generate.loadingCapabilities')}</Text>
+ </HStack>
);
}
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
index 1e4df878e0..b3833a4d7e 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
@@ -1,6 +1,7 @@
import type { GenerateLora, VaeModelConfig } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
import { describe, expect, it } from 'vitest';
import {
@@ -13,6 +14,9 @@ import {
UPSCALE_PRESETS,
} from './settings';
+// VAE compatibility is served by the backend now, and the accessor fails closed without it.
+seedArchitectureCapabilities();
+
const model = (key: string, type: string, base: string, name = key): ModelConfig => ({
base,
file_size: 1,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.ts
index e7951b20c3..a127daa00e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.test.ts
@@ -49,4 +49,13 @@ describe('getCanvasImportNotice', () => {
] as const)('maps %s to the expected localized notice', (status, kind, titleKey) => {
expect(getCanvasImportNotice({ status })).toEqual({ kind, titleKey });
});
+
+ it('tells a blocked import apart from one waiting on model capabilities', () => {
+ // Both are informational and both stop the import, but only one is something the user can
+ // act on. Sharing a message sent people looking for a canvas operation they never started.
+ expect(getCanvasImportNotice({ status: 'blocked' }).titleKey).toBe('widgets.canvas.import.blocked');
+ expect(getCanvasImportNotice({ status: 'capabilities-unavailable' }).titleKey).toBe(
+ 'widgets.canvas.import.capabilitiesUnavailable'
+ );
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.ts
index 81b7cff372..f617274adf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/canvasImportNotice.ts
@@ -4,6 +4,7 @@ export interface CanvasImportNotice {
kind: 'error' | 'info' | 'success';
titleKey:
| 'widgets.canvas.import.blocked'
+ | 'widgets.canvas.import.capabilitiesUnavailable'
| 'widgets.canvas.import.empty'
| 'widgets.canvas.import.partial'
| 'widgets.canvas.import.staleDocument'
@@ -37,6 +38,8 @@ export const getCanvasImportNotice = (result: ImportGalleryImagesResult): Canvas
};
case 'blocked':
return { kind: 'info', titleKey: 'widgets.canvas.import.blocked' };
+ case 'capabilities-unavailable':
+ return { kind: 'info', titleKey: 'widgets.canvas.import.capabilitiesUnavailable' };
case 'empty':
return { kind: 'info', titleKey: 'widgets.canvas.import.empty' };
case 'stale-document':
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
index adc5913de1..639e13f699 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
@@ -107,12 +107,19 @@ export const createFromBbox = async (options: {
if (imported.status === 'imported') {
return { destination, layerIds: imported.layerIds, status: 'created' };
}
- if (imported.status === 'empty') {
- // Unreachable: exactly one image is always passed. Kept for exhaustiveness.
- return { status: 'blocked' };
+ switch (imported.status) {
+ case 'blocked':
+ case 'stale-document':
+ case 'stale-project':
+ return { status: imported.status };
+ case 'empty':
+ // Unreachable: exactly one image is always passed. Kept for exhaustiveness.
+ return { status: 'blocked' };
+ case 'capabilities-unavailable':
+ // Unreachable: only 'control-resized' consults the capability table, and this flow never
+ // asks for it -- CreateFromBboxLayerDestination excludes that destination.
+ return { status: 'blocked' };
}
-
- return imported;
} catch (error) {
if (!isAccountScopeCurrent(owner)) {
return { status: 'stale' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
index 75f9e21d78..01fa7988ea 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -6,7 +6,14 @@ import type { uploadCanvasImage } from '@workbench/canvas-operations/backend/can
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import {
+ resetArchitectureCapabilities,
+ setArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
@@ -619,6 +626,10 @@ describe('importGalleryImagesToCanvas', () => {
it('does not upload an old account image after local preprocessing crosses an account switch', async () => {
accountLifecycle.activate('user-a');
+ // Activating an account drops the capability table with the rest of the previous account's
+ // state; the app reloads it for the incoming one. Resized imports are refused without it, and
+ // this test is about the account fence, not that gate.
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
const { project, state } = withProject();
let resolveFetch: ((response: Response) => void) | undefined;
const fetchImage = vi.fn<typeof fetch>(
@@ -724,3 +735,49 @@ describe('importGalleryImagesToCanvas', () => {
});
});
});
+
+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 whose
+ // mistake cannot be taken back: the asset is uploaded and becomes a layer. With no table every
+ // architecture reads as 1024 / grid 8, so an SD-1 project would upload four times the area it
+ // asked for. Nothing re-derives it afterwards.
+ const { project, state } = withProject((value) => setModel(value, 'sd-1'));
+ const fetchImage = vi.fn<typeof fetch>();
+ const uploadImage = vi.fn<typeof uploadCanvasImage>();
+
+ resetArchitectureCapabilities();
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ applyCanvasMutation: () => undefined,
+ engine: engine(project.id),
+ fetchImage,
+ ...queriesFor(() => state),
+ images: [image('wide.png', 1600, 900)],
+ project,
+ uploadImage,
+ });
+
+ // Its own status, not 'blocked' -- that one tells the user to finish an operation they
+ // did not start, and gives them nothing to act on.
+ expect(result).toEqual({ status: 'capabilities-unavailable' });
+ expect(fetchImage).not.toHaveBeenCalled();
+ expect(uploadImage).not.toHaveBeenCalled();
+ });
+
+ it('still imports destinations that do not depend on the architecture', async () => {
+ const { project, state } = withProject((value) => setModel(value, 'sd-1'));
+
+ resetArchitectureCapabilities();
+ const result = await importGalleryImagesToCanvas({
+ destination: 'raster',
+ applyCanvasMutation: () => undefined,
+ engine: engine(project.id),
+ ...queriesFor(() => state),
+ images: [image('wide.png', 1600, 900)],
+ project,
+ });
+
+ expect(result.status).toBe('imported');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
index 15fe07f9bf..72db5ab407 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
@@ -5,6 +5,7 @@ import type { CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engi
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project } from '@workbench/projectContracts';
+import { getArchitectureCapabilitiesSnapshot } from '@features/generation/runtime';
import {
calculateNewSize,
getGenerationDimensions,
@@ -48,7 +49,7 @@ export type GalleryCanvasImportDestination =
export type ImportGalleryImagesResult =
| { status: 'imported'; layerIds: string[]; failedImageNames: string[] }
- | { status: 'blocked' | 'empty' | 'stale-document' | 'stale-project' };
+ | { status: 'blocked' | 'capabilities-unavailable' | 'empty' | 'stale-document' | 'stale-project' };
interface BuildLayerContext {
bbox: Project['canvas']['document']['bbox'];
@@ -277,6 +278,15 @@ export const importGalleryImagesToCanvas = async (options: {
let layerImages: readonly LayerImage[] = images;
let failedImageNames: string[] = [];
if (destination === 'control-resized') {
+ // The resize target is the model's native size and grid, and this is the one import path
+ // 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) {
+ return { status: 'capabilities-unavailable' };
+ }
+
const resized = await resizeImages(images, project, fetchImage, uploadImage, owner.signal);
assertAccountScopeCurrent(owner);
diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts
index 1b30708e77..5956f75d72 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts
@@ -1,15 +1,20 @@
import type { MainModelConfig } from '@features/generation/contracts';
import type { WorkbenchState } from '@workbench/projectContracts';
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
-import { describe, expect, it } from 'vitest';
+import {
+ resetArchitectureCapabilities,
+ setArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
+import { afterEach, describe, expect, it } from 'vitest';
import type { CanvasProjectMutation } from './canvasProjectMutations';
import { type CanvasDimsSnapshot, createCanvasDimsSync, reconcileCanvasDims } from './canvasDimsSync';
import { getProjectWidgetValues } from './widgetState';
-
-seedArchitectureCapabilities();
import { createWorkbenchStore } from './workbenchStore';
const bbox = (width: number, height: number, x = 0, y = 0) => ({ height, width, x, y });
@@ -262,6 +267,8 @@ const setupCanvasStore = () => {
};
describe('createCanvasDimsSync (wiring)', () => {
+ seedArchitectureCapabilities();
+
it('does not dispatch on mount when bbox and dims already agree', () => {
const { getSyncDispatches, sync } = setupCanvasStore();
@@ -442,3 +449,77 @@ describe('createCanvasDimsSync (wiring)', () => {
sync.dispose();
});
});
+
+describe('createCanvasDimsSync before the capability table arrives', () => {
+ afterEach(resetArchitectureCapabilities);
+
+ const wanModel: MainModelConfig = { base: 'wan', key: 'test-wan-model', name: 'Test Wan Model', type: 'main' };
+
+ /** A saved canvas project whose frame is 8-aligned but not on Wan's 16px grid. */
+ const setupWanProject = () => {
+ const store = createWorkbenchStore();
+
+ store.commands.generation.setSource('canvas');
+ store.commands.generation.patchSettings({
+ height: 1024,
+ model: wanModel,
+ modelKey: wanModel.key,
+ width: 1024,
+ });
+ dispatchCanvas(store, { bbox: { height: 1032, width: 1032, x: 0, y: 0 }, type: 'setCanvasBbox' });
+
+ let syncDispatches = 0;
+ const countingStore = {
+ commands: {
+ canvas: store.commands.canvas,
+ generation: {
+ ...store.commands.generation,
+ patchSettings: (...args: Parameters<typeof store.commands.generation.patchSettings>) => {
+ syncDispatches += 1;
+ store.commands.generation.patchSettings(...args);
+ },
+ },
+ },
+ getState: store.getState,
+ subscribe: store.subscribe,
+ };
+
+ return { getSyncDispatches: () => syncDispatches, store, sync: createCanvasDimsSync(countingStore) };
+ };
+
+ it('writes nothing into the project while the architecture has no answer', () => {
+ // Reopening a saved canvas project: `prev` is null, so the bbox wins and the dims are patched
+ // and persisted. With no table the grid reads as 8, which is a real answer for SDXL and a guess
+ // for Wan -- and Wan's denoise node rejects anything but multiples of 16.
+ const { getSyncDispatches, store, sync } = setupWanProject();
+
+ expect(getSyncDispatches()).toBe(0);
+ expect(getActiveGenerate(store.getState()).values.width).toBe(1024);
+ sync.dispose();
+ });
+
+ it('reconciles as soon as the table lands, with no other change to the project', () => {
+ // The gap this closes: nothing else moves when the table arrives -- the widget's own resolver
+ // produces no patch for an already-consistent project -- so this listener has to hear about the
+ // table itself or the wrong dimensions stay persisted.
+ const { getSyncDispatches, store, sync } = setupWanProject();
+
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+
+ // The 1032px frame snapped onto Wan's declared 16px grid, not the fallback's 8.
+ const { values } = getActiveGenerate(store.getState());
+ expect(values.width).toBe(1040);
+ expect(values.height).toBe(1040);
+ expect(getSyncDispatches()).toBe(1);
+ sync.dispose();
+ });
+
+ it('stops listening to the table once disposed', () => {
+ const { getSyncDispatches, sync } = setupWanProject();
+
+ sync.dispose();
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+
+ expect(getSyncDispatches()).toBe(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts
index d432f6462c..0942ea667f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts
@@ -18,7 +18,10 @@
* side (if any) to write, given the current bbox, the current committed
* generate dims, the snapping grid, and the last-synced snapshot.
* - {@link createCanvasDimsSync}: a thin `store.subscribe` wiring that feeds the
- * reconcile from workbench state and dispatches the resulting action.
+ * reconcile from workbench state and dispatches the resulting action. It also
+ * subscribes to the architecture capability table, because the grid is
+ * generation policy that arrives over the network rather than workbench state,
+ * and both directions of this sync are persisted.
*
* Loop safety: the reconcile short-circuits to `none` whenever the bbox and dims
* already agree, so applying either direction is a fixed point. The wiring also
@@ -35,11 +38,12 @@ import type { AspectRatioId } from '@features/generation/contracts';
import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/api';
import type { WorkbenchState } from '@workbench/projectContracts';
+import { subscribeArchitectureCapabilities } from '@features/generation/runtime';
import { clampDimension, deriveAspectRatioId } from '@features/generation/settings';
import type { WorkbenchCommands } from './workbenchStore';
-import { gridSizeForModelBase } from './widgets/canvas/bboxGrid';
+import { resolveModelGrid } from './widgets/canvas/bboxGrid';
import { getProjectWidgetValues } from './widgetState';
type Bbox = CanvasDocumentContractV3['bbox'];
@@ -175,6 +179,15 @@ const readModelBase = (values: Record<string, unknown>): string | null => {
: null;
};
+// The grid is variant-dependent -- Wan TI2V-5B enforces 32 where A14B enforces 16 -- and this
+// path persists what it reconciles, so it has to ask with the variant.
+const readModelVariant = (values: Record<string, unknown>): string | null => {
+ const model = values.model;
+ return model && typeof model === 'object' && typeof (model as { variant?: unknown }).variant === 'string'
+ ? (model as { variant: string }).variant
+ : null;
+};
+
/**
* Wire the bbox <-> generate-dims reconcile onto a workbench store. Subscribes
* immediately; dispatches `patchGenerateSettings` / `setCanvasBbox` as the
@@ -224,7 +237,17 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSync
}
const bbox = project.canvas.document.bbox;
- const grid = gridSizeForModelBase(readModelBase(generateValues));
+ const grid = resolveModelGrid(readModelBase(generateValues), readModelVariant(generateValues));
+
+ // Nothing is written until the backend has answered for this architecture. Both writes below
+ // are `patchSettings` / `setCanvasBbox` on the project, so reconciling against a fallback grid
+ // would *persist* an off-grid width/height for a base whose denoise node rejects it -- and the
+ // capability subscription below is what brings this listener back once the answer lands.
+ if (grid === null) {
+ prev = null;
+ return;
+ }
+
const result = reconcileCanvasDims({ bbox, dims: { height, width }, grid, prev });
const projectId = project.id;
@@ -261,10 +284,19 @@ export const createCanvasDimsSync = (store: CanvasDimsSyncStore): CanvasDimsSync
}
};
- const unsubscribe = store.subscribe(handleChange);
+ const unsubscribeStore = store.subscribe(handleChange);
+ // The grid is generation policy, not workbench state, and it arrives over the network after this
+ // runtime is constructed. A project that is already consistent produces no workbench-store change
+ // when the table lands, so without this the gate above would never be re-entered.
+ const unsubscribeCapabilities = subscribeArchitectureCapabilities(handleChange);
// Seed from the current state so an already-canvas project reconciles on mount.
handleChange();
- return { dispose: unsubscribe };
+ return {
+ dispose: () => {
+ unsubscribeStore();
+ unsubscribeCapabilities();
+ },
+ };
};
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.tsx
new file mode 100644
index 0000000000..111212fc82
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx
@@ -0,0 +1,94 @@
+import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';
+import type { Project } from '@workbench/projectContracts';
+import type { ReactNode } from 'react';
+
+import {
+ resetArchitectureCapabilities,
+ setArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
+import { getDefaultGenerateSettings } from '@features/generation/settings';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const harness = vi.hoisted(() => ({ project: null as unknown }));
+
+vi.mock('@features/generation/react', () => ({
+ useDynamicPrompts: () => ({ count: 1, error: null, isDynamic: false, isError: false, isLoading: false, prompts: [] }),
+}));
+vi.mock('@features/models', () => ({
+ ensureModelsLoaded: () => Promise.resolve(),
+ useModelsSelector: (selector: (snapshot: unknown) => unknown) => selector({ models: [sdxlModel], status: 'loaded' }),
+}));
+vi.mock('@workbench/activeInvocationSubmission', () => ({ submitActiveInvocation: () => Promise.resolve() }));
+vi.mock('@workbench/canvasInvocationPreparation', () => ({ useIsCanvasInvocationPreparing: () => false }));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project as Project),
+ useWorkbenchCommands: () => ({}),
+ useWorkbenchQueries: () => ({}),
+ useWorkbenchSelector: (selector: (snapshot: unknown) => unknown) =>
+ selector({ backendConnection: { status: 'connected' } }),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
+
+import { useInvocationState } from './useInvocationState';
+
+const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };
+
+const buildProject = (): 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);
+ const values: GenerateWidgetValues = {
+ ...getDefaultGenerateSettings(sdxlModel),
+ model: sdxlModel,
+ modelKey: sdxlModel.key,
+ positivePrompt: 'a landscape',
+ };
+ resetArchitectureCapabilities();
+
+ const state = workbenchReducer(createInitialWorkbenchState(), { type: 'setGenerateSettings', values });
+ return state.projects.find((candidate) => candidate.id === state.activeProjectId)!;
+};
+
+(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 Probe = (): ReactNode => <span data-testid="reasons">{useInvocationState().blockingReasons.join(' | ')}</span>;
+
+const blockingReasons = (): string => host?.querySelector('[data-testid="reasons"]')?.textContent ?? '';
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ resetArchitectureCapabilities();
+});
+
+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 />);
+ });
+
+ expect(blockingReasons()).toBe('Model capabilities have not loaded yet. Generation is blocked until they arrive.');
+
+ // The retry button in the Generate widget, succeeding. Nothing else about the project changes,
+ // so the route resolution has to be driven by the table's arrival alone.
+ await act(() => {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ });
+
+ expect(blockingReasons()).toBe('');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
index 2fd6a2f6e4..5a3f2ddd71 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
@@ -1,9 +1,11 @@
import type { DynamicPromptsExpansion } from '@features/generation/react';
+import type { ArchitectureCapabilitiesSnapshot } from '@features/generation/runtime';
import type { GraphWidgetSource } from '@workbench/graphWidgets';
import type { InvocationRoute, ResultDestination } from '@workbench/invocationContracts';
import type { WidgetTypeId } from '@workbench/widgetContracts';
import { useDynamicPrompts } from '@features/generation/react';
+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';
import {
getEffectivePrompts,
normalizeGenerateSettings,
@@ -14,6 +16,7 @@ import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { useInvocationTemplatesSelector } from '@features/workflow/react';
import { localizeForLoopValidationReason } from '@features/workflow/utility';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { useExternalStoreSelector } from '@platform/state/selectors';
import { submitActiveInvocation } from '@workbench/activeInvocationSubmission';
import { useIsCanvasInvocationPreparing } from '@workbench/canvasInvocationPreparation';
import { getPlacedWidgetTypeIds, getVisibleWidgetTypeIds, graphWidgetSources } from '@workbench/graphWidgets';
@@ -32,6 +35,8 @@ import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
const selectInvocationRouteInput = createInvocationRouteInputSelector();
+const selectCapabilitiesRevision = (snapshot: ArchitectureCapabilitiesSnapshot): number => snapshot.revision;
+
const areTypeIdSetsEqual = (left: ReadonlySet<WidgetTypeId>, right: ReadonlySet<WidgetTypeId>): boolean =>
left.size === right.size && [...left].every((typeId) => right.has(typeId));
@@ -82,6 +87,14 @@ export const useInvocationState = (): InvocationState => {
// Project-graph route validation reads the invocation templates imperatively;
// subscribing here keeps the resolved route live while they load.
useInvocationTemplatesSelector((snapshot) => snapshot.status);
+ // Same shape, for the architecture capability table: `getGenerationValidationReasons` fails closed
+ // while it is absent, so a load that only succeeds on retry has to reach Invoke on its own rather
+ // than waiting for the next unrelated edit to re-render this hook.
+ useExternalStoreSelector(
+ subscribeArchitectureCapabilities,
+ getArchitectureCapabilitiesSnapshot,
+ selectCapabilitiesRevision
+ );
useMountEffect(() => {
void ensureModelsLoaded();
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
index bdee5f4047..b3adf13080 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
@@ -35,7 +35,7 @@ import { useTranslation } from 'react-i18next';
import type { CanvasHeaderCommandContext } from './canvasHeaderCommands';
import type { ResolvedCanvasSettings } from './canvasSettings';
-import { gridSizeForModelBase } from './bboxGrid';
+import { useModelGridSize } from './bboxGrid';
import {
applyFitBbox,
confirmNewCanvas as confirmNewCanvasDocument,
@@ -68,6 +68,11 @@ const selectModelBase = (project: Project): string | null => {
return typeof values?.model?.base === 'string' ? values.model.base : null;
};
+const selectModelVariant = (project: Project): string | null => {
+ const values = getProjectWidgetValues(project, 'generate') as { model?: { variant?: unknown } } | undefined;
+ return typeof values?.model?.variant === 'string' ? values.model.variant : null;
+};
+
/**
* Canvas widget header actions, in legacy toolbar order: the zoom-percent menu, a
* reset-view (fit content to view) button, fit-bbox-to-layers / fit-bbox-to-masks,
@@ -99,6 +104,7 @@ const CanvasHeaderActionsInner = ({
const { isSaving, save: saveToGallery } = useCanvasGallerySave(engine);
const document = useActiveProjectSelector((project) => project.canvas.document);
const modelBase = useActiveProjectSelector(selectModelBase);
+ const modelVariant = useActiveProjectSelector(selectModelVariant);
const settings = useActiveProjectSelector(selectCanvasSettings, canvasSettingsEqual);
const [isNewCanvasOpen, setIsNewCanvasOpen] = useState(false);
@@ -112,7 +118,8 @@ const CanvasHeaderActionsInner = ({
const setZoom = (value: number) => zoomAtViewportCentre(engine, value);
// Fit-bbox honors the snap-to-grid setting: snapping off ⇒ grid 1 (a plain round).
- const gridSize = settings[CANVAS_SNAP_TO_GRID_KEY] ? gridSizeForModelBase(modelBase) : 1;
+ const modelGrid = useModelGridSize(modelBase, modelVariant);
+ const gridSize = settings[CANVAS_SNAP_TO_GRID_KEY] ? modelGrid : 1;
const fitLayersRect = useMemo(() => computeFitBboxToLayers(document, gridSize), [document, gridSize]);
const fitMasksRect = useMemo(() => computeFitBboxToMasks(document, gridSize), [document, gridSize]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index f4dae466dc..bf885532a1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -25,7 +25,7 @@ import {
import { lazy, Suspense, useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { gridSizeForModelBase } from './bboxGrid';
+import { useModelGridSize } from './bboxGrid';
import { CanvasBottomOverlay } from './CanvasBottomOverlay';
import { copyBlobToClipboard, decodeImageBlob, readClipboardImage } from './canvasClipboard';
import {
@@ -108,15 +108,21 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
// shared per-layer menu or the global menu at the pointer.
const [contextMenuTarget, setContextMenuTarget] = useState<CanvasContextMenuTarget | null>(null);
const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);
- // The bbox tool snaps to a model-dependent grid; the engine is model-agnostic,
- // so read the active generate model's base and feed the grid size in.
+ // The bbox tool snaps to a model-dependent grid; the engine is model-agnostic, so read the
+ // active generate model and feed the grid size in. Two primitive selectors rather than one
+ // object, so the subscription compares by value.
const modelBase = useActiveProjectSelector((project) => {
const values = getProjectWidgetValues(project, 'generate') as { model?: { base?: unknown } } | undefined;
return typeof values?.model?.base === 'string' ? values.model.base : null;
});
+ const modelVariant = useActiveProjectSelector((project) => {
+ const values = getProjectWidgetValues(project, 'generate') as { model?: { variant?: unknown } } | undefined;
+ return typeof values?.model?.variant === 'string' ? values.model.variant : null;
+ });
+ const bboxGrid = useModelGridSize(modelBase, modelVariant);
useEffect(() => {
- engine?.viewport.setBboxGrid(gridSizeForModelBase(modelBase));
- }, [engine, modelBase]);
+ engine?.viewport.setBboxGrid(bboxGrid);
+ }, [bboxGrid, engine]);
// Canvas view settings (checkerboard / grid / invert-scroll) persist in the
// canvas widget's per-project values; the engine only reads its stores, so
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.browser.test.tsx
new file mode 100644
index 0000000000..c70f0f907e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.browser.test.tsx
@@ -0,0 +1,65 @@
+import {
+ resetArchitectureCapabilities,
+ setArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { useModelGridSize } from './bboxGrid';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+/** Stands in for the canvas widget's `engine.viewport.setBboxGrid` feed and the header's fit-bbox. */
+const GridProbe = ({ base }: { base: string }) => <span data-testid="grid">{useModelGridSize(base)}</span>;
+
+const render = async (base: string): Promise<void> => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => {
+ root?.render(<GridProbe base={base} />);
+ });
+};
+
+const grid = (): string | null | undefined => host?.querySelector('[data-testid="grid"]')?.textContent;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ resetArchitectureCapabilities();
+});
+
+describe('useModelGridSize', () => {
+ it('re-reads the grid when the capability table lands after mount', async () => {
+ // The real sequence for a saved project: the base is restored from disk and never changes, so
+ // an effect keyed on it alone never re-runs. Wan's denoise node enforces multiples of 16; the
+ // canvas used to keep snapping at 8 for the rest of the session.
+ await render('wan');
+ expect(grid()).toBe('8');
+
+ await act(() => {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ });
+
+ expect(grid()).toBe('16');
+ });
+
+ it('drops back to the default when the table is dropped on an account change', async () => {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ await render('cogview4');
+ expect(grid()).toBe('32');
+
+ await act(() => {
+ resetArchitectureCapabilities();
+ });
+
+ expect(grid()).toBe('8');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts
index e4ab0e0705..5d1a6f3535 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts
@@ -1,11 +1,18 @@
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
-import { describe, expect, it } from 'vitest';
+import {
+ resetArchitectureCapabilities,
+ setArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { DEFAULT_MODEL_GRID, gridSizeForModelBase } from './bboxGrid';
-
-seedArchitectureCapabilities();
+import { DEFAULT_MODEL_GRID, gridSizeForModelBase, resolveModelGrid } from './bboxGrid';
describe('gridSizeForModelBase', () => {
+ seedArchitectureCapabilities();
+
it('reads the grid the architecture declares', () => {
// The same number the denoise node enforces through `multiple_of` on width/height.
for (const base of ['flux', 'flux2', 'sd-3', 'qwen-image', 'z-image', 'ernie-image']) {
@@ -34,3 +41,60 @@ describe('gridSizeForModelBase', () => {
expect(DEFAULT_MODEL_GRID).toBe(8);
});
});
+
+describe('resolveModelGrid before the capability table arrives', () => {
+ // Deliberately unseeded. Every case above runs with the table present, which is the state the
+ // app reaches a round trip *after* boot -- and a project reopened before then is exactly where
+ // the grid used to latch at 8 for the session.
+
+ it('reports the grid as unknown rather than as 8', () => {
+ // The distinction a writer needs: 8 is a real answer for SDXL and a guess for Wan, and only
+ // one of the two may be persisted into a project file.
+ expect(resolveModelGrid('wan')).toBeNull();
+ expect(resolveModelGrid('cogview4')).toBeNull();
+ expect(resolveModelGrid('sdxl')).toBeNull();
+ });
+
+ it('still answers for "no model selected", which the backend has no say in', () => {
+ expect(resolveModelGrid(null)).toBe(DEFAULT_MODEL_GRID);
+ expect(resolveModelGrid(undefined)).toBe(DEFAULT_MODEL_GRID);
+ });
+
+ it('keeps the default for readers that must show something', () => {
+ expect(gridSizeForModelBase('wan')).toBe(DEFAULT_MODEL_GRID);
+ });
+});
+
+describe('the grid a variant declares', () => {
+ // Wan is the architecture whose grid is not a property of the base: A14B enforces multiples of
+ // 16 on its denoise node, TI2V-5B multiples of 32 in the reference-image encoder. The backend
+ // publishes that as a variant row; the canvas has to join on `(base, variant)` or it offers a
+ // size the run rejects after the model is already loaded -- 1280x720 is the obvious one, both
+ // multiples of 16, and 720 % 32 === 16.
+ //
+ // Seeded with a hand-built override rather than the committed fixture, so this states the rule
+ // rather than whatever number that fixture happens to carry.
+ beforeEach(() => {
+ setArchitectureCapabilities(
+ architectureCapabilitiesFixture.map((row) =>
+ row.base === 'wan' && row.variant === 'ti2v_5b'
+ ? { ...row, features: { ...row.features, dimension_grid: 32 } }
+ : row
+ )
+ );
+ });
+
+ afterEach(() => {
+ resetArchitectureCapabilities();
+ });
+
+ it('prefers the variant row over the architecture row', () => {
+ expect(gridSizeForModelBase('wan', 'ti2v_5b')).toBe(32);
+ expect(gridSizeForModelBase('wan')).toBe(16);
+ });
+
+ it('falls back to the architecture row for a variant that declares nothing of its own', () => {
+ expect(gridSizeForModelBase('wan', 'a14b')).toBe(16);
+ expect(gridSizeForModelBase('sdxl', 'inpaint')).toBe(8);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts
index e090750227..53d093752b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.ts
@@ -8,12 +8,48 @@
* used to be a second, hand-maintained copy of that column -- and it had drifted, offering 8px
* steps for krea-2, wan and ideogram-4, all of which reject anything but multiples of 16 at
* enqueue time.
+ *
+ * Because the rule now arrives over the network, "the grid for this base" has a third answer
+ * besides a number and "no model": *not yet*. {@link resolveModelGrid} keeps that answer distinct
+ * so a writer (the bbox <-> dims sync, which persists) can wait while a reader (the tool's snap
+ * step) can pick a harmless default -- and {@link useModelGridSize} makes the reader re-read when
+ * the table lands instead of latching whatever it answered on the first render.
*/
-import { getDimensionGridForBase } from '@features/generation/settings';
+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';
+import { getDimensionGrid } from '@features/generation/settings';
+import { useExternalStoreSelector } from '@platform/state/selectors';
+import { useCallback } from 'react';
-/** Default grid when no model is selected, or the backend has no row for its architecture. */
+/** Default grid when no model is selected. */
export const DEFAULT_MODEL_GRID = 8;
-export const gridSizeForModelBase = (base: string | null | undefined): number =>
- (base ? getDimensionGridForBase(base) : null) ?? DEFAULT_MODEL_GRID;
+/**
+ * The grid the selected architecture declares, `DEFAULT_MODEL_GRID` when no model is selected, or
+ * `null` while the backend has not answered for that architecture.
+ */
+export const resolveModelGrid = (base: string | null | undefined, variant?: unknown): number | null =>
+ base ? getDimensionGrid(base, variant) : DEFAULT_MODEL_GRID;
+
+export const gridSizeForModelBase = (base: string | null | undefined, variant?: unknown): number =>
+ resolveModelGrid(base, variant) ?? DEFAULT_MODEL_GRID;
+
+/**
+ * The grid for `base`, re-read whenever the capability table changes.
+ *
+ * `base` comes from the persisted project and is therefore already final on the first render, so an
+ * effect keyed on it alone never re-runs: without this subscription a project reopened before the
+ * table arrives snaps at 8px for the whole session, on an architecture whose denoise node enforces
+ * 16 or 32.
+ *
+ * The read happens *inside* the selector rather than after a bare subscription call. The grid lives
+ * in the core registry, not in this snapshot, so to React Compiler a plain `gridSizeForModelBase(base)`
+ * in a component body is a pure function of `base` and is memoised for the component's lifetime --
+ * subscribing alongside it would re-render and hand back the cached 8 anyway.
+ */
+export const useModelGridSize = (base: string | null | undefined, variant?: string | null): number =>
+ useExternalStoreSelector(
+ subscribeArchitectureCapabilities,
+ getArchitectureCapabilitiesSnapshot,
+ useCallback(() => gridSizeForModelBase(base, variant), [base, variant])
+ );
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx
index 6411171da2..acd004de23 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx
@@ -2,19 +2,21 @@ import type { CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engi
import type { ComponentProps } from 'react';
import { ChakraProvider } from '@chakra-ui/react';
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { RegionalGuidanceSettings } from './RegionalGuidanceSettings';
-seedArchitectureCapabilities();
-
let selectedBase: string | null = null;
vi.mock('./useSelectedModelBase', () => ({ useSelectedModelBase: () => selectedBase }));
@@ -67,6 +69,7 @@ afterEach(async () => {
host?.remove();
host = null;
root = null;
+ resetArchitectureCapabilities();
});
const alerts = () => [...host!.querySelectorAll('[role="alert"]')].map((el) => el.textContent);
@@ -76,6 +79,10 @@ const hasAutoNegativeSwitch = () =>
Boolean(host!.textContent?.includes('widgets.layers.regionalGuidance.autoNegative'));
describe('RegionalGuidanceSettings per model base', () => {
+ beforeEach(() => {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ });
+
it('offers both prompt polarities on an SD base', async () => {
await render('sd-1', createLayer());
expect(alerts()).toEqual([]);
@@ -102,3 +109,39 @@ describe('RegionalGuidanceSettings per model base', () => {
expect(hasNegativeField()).toBe(true);
});
});
+
+describe('RegionalGuidanceSettings before the capability table arrives', () => {
+ it('does not accuse a supported model of lacking a regional path', async () => {
+ // `getRegionalGuidanceSupport` answers `null` for every base while the table is missing. The
+ // panel used to read that as "unsupported model" and say so in a role="alert" -- for SD-1,
+ // permanently if the load failed -- while rendering the very controls it called unavailable.
+ await render('sd-1', createLayer());
+
+ expect(alerts()).toEqual([]);
+ expect(hasNegativeField()).toBe(true);
+ expect(hasAutoNegativeSwitch()).toBe(true);
+ });
+
+ it('renders the real answer once the table lands, without remounting', async () => {
+ await render('sd-3', createLayer());
+ expect(alerts()).toEqual([]);
+
+ await act(() => {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ });
+
+ expect(alerts()).toEqual(['widgets.layers.regionalGuidance.unsupportedModel']);
+ });
+
+ it('hides the negative controls once the table says the base ignores them', async () => {
+ await render('anima', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));
+ expect(hasNegativeField()).toBe(true);
+
+ await act(() => {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ });
+
+ expect(hasNegativeField()).toBe(false);
+ expect(hasAutoNegativeSwitch()).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
index 3dac6344a7..532b0afaac 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
@@ -1,4 +1,5 @@
import type { SelectValueChangeDetails } from '@chakra-ui/react';
+import type { ArchitectureCapabilitiesSnapshot } from '@features/generation/runtime';
import type {
CanvasMaskContract,
CanvasMaskFillContract,
@@ -10,6 +11,8 @@ import type { ChangeEvent, FocusEvent } from 'react';
import { createListCollection, HStack, IconButton, Stack, Switch, Text } from '@chakra-ui/react';
import { PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generation/components';
import { getRegionalGuidanceSupport } from '@features/generation/graph';
+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';
+import { useExternalStoreSelector } from '@platform/state/selectors';
import { Button, ColorPicker, Field, Select, Tooltip } from '@platform/ui';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { armMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';
@@ -71,13 +74,33 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
const [negativePrompt, setNegativePrompt] = useState(layer.negativePrompt ?? '');
const fill = layer.mask.fill;
+ // `getRegionalGuidanceSupport` answers from the capability table, which arrives over the network,
+ // and it is read here through the store's selector rather than called in the component body: the
+ // table is module state, so to React Compiler a bare call is a pure function of `base` and would
+ // be memoised for the panel's lifetime.
+ //
+ // Until the table arrives it answers `null` for *every* base, so "this model has no regional
+ // path" has to stay distinct from "nobody has said yet" -- otherwise a perfectly supported SD-1
+ // model is accused of being unsupported, permanently if the load failed, while the very controls
+ // the alert calls unavailable render right underneath it.
+ const { hasCapabilities, support } = useExternalStoreSelector(
+ subscribeArchitectureCapabilities,
+ getArchitectureCapabilitiesSnapshot,
+ useCallback(
+ (snapshot: ArchitectureCapabilitiesSnapshot) => ({
+ hasCapabilities: snapshot.revision > 0,
+ support: getRegionalGuidanceSupport(base),
+ }),
+ [base]
+ )
+ );
// Negative controls are hidden on bases whose backend ignores regional negatives -- asked as "is
// this the FLUX family?" before, which got krea-2 wrong: it rendered a regional negative prompt
// and an Auto-Negative switch that `addRegionalGuidance` then discarded. The values stay on the
- // layer for other models. With no selected model every control is offered.
- const support = getRegionalGuidanceSupport(base);
- const showNegativeControls = support?.negativePrompt !== false;
- const unsupportedModel = base !== null && support === null;
+ // layer for other models. With no selected model, and until the table arrives, every control is
+ // offered.
+ const showNegativeControls = !hasCapabilities || support?.negativePrompt !== false;
+ const unsupportedModel = hasCapabilities && base !== null && support === null;
const commitConfig = useCallback(
(label: string, next: RegionalConfigPatch, before: RegionalConfigPatch) => {
diff --git a/tests/backend/architectures/test_capabilities_fixture.py b/tests/backend/architectures/test_capabilities_fixture.py
index 7219fae04e..d3dbe9df71 100644
--- a/tests/backend/architectures/test_capabilities_fixture.py
+++ b/tests/backend/architectures/test_capabilities_fixture.py
@@ -36,6 +36,12 @@ REGEN_HINT = (
f"and commit the result, so webv2's tests and mock backend see what this backend serves."
)
+# The fixture is written by `json.dumps(indent=2)` below, which oxfmt would reflow -- so following
+# the hint above would redden webv2's `format:check` on a file nobody hand-edited. It is listed in
+# `.oxfmtrc.json`'s `ignorePatterns` for that reason, alongside `generateGraphNodeTypes.json`, the
+# other generated cross-stack artifact. Machine-written files are not the formatter's to own; if
+# that entry is removed, this writer has to emit oxfmt's exact output instead.
+
def _rendered() -> list[dict[str, Any]]:
return [row.model_dump(mode="json") for row in architecture_capabilities()]
diff --git a/tests/backend/architectures/test_vae.py b/tests/backend/architectures/test_vae.py
index 79e75c1b1e..58e0be0ece 100644
--- a/tests/backend/architectures/test_vae.py
+++ b/tests/backend/architectures/test_vae.py
@@ -11,7 +11,9 @@ import pytest
from invokeai.app.invocations.baseinvocation import InvocationRegistry
from invokeai.app.services.shared.graph import Graph # noqa: F401 -- imports every invocation
from invokeai.backend.architectures import generative_bases, get
-from invokeai.backend.architectures.facets.vae import VaeFacet, accepts_vae
+from invokeai.backend.architectures.facets.latent_space import LatentSpace, LatentSpaceFacet
+from invokeai.backend.architectures.facets.vae import VaeCompatibility, VaeFacet, accepts_vae
+from invokeai.backend.architectures.registry import require
from invokeai.backend.model_manager.taxonomy import BaseModelType
# The loader that owns each architecture's VAE input. Architectures absent from this map take no
@@ -71,10 +73,9 @@ def test_flux2_no_longer_offers_a_vae_that_crashes() -> None:
assert accepts_vae(BaseModelType.Flux2, BaseModelType.Flux) is False
-def test_anima_accepts_both_families_it_actually_handles() -> None:
- """`anima_l2i` branches on `isinstance(vae, (AutoencoderKLWan, FluxAutoEncoder))`, each with its
- own working-memory estimate. The Wan-family file is registered under any of three bases."""
- for vae_base in (BaseModelType.Anima, BaseModelType.QwenImage, BaseModelType.Flux):
+def test_anima_accepts_the_wan_family_under_each_base_it_registers_as() -> None:
+ """One 194-tensor checkpoint, three registrations. All three decode the same latent."""
+ for vae_base in (BaseModelType.Anima, BaseModelType.QwenImage):
assert accepts_vae(BaseModelType.Anima, vae_base) is True, vae_base.value
assert accepts_vae(BaseModelType.Anima, BaseModelType.Wan, 16) is True
@@ -82,6 +83,25 @@ def test_anima_accepts_both_families_it_actually_handles() -> None:
assert accepts_vae(BaseModelType.Anima, BaseModelType.Wan, 48) is False
+def test_anima_no_longer_offers_a_flux_vae_that_decodes_to_noise() -> None:
+ """Anima denoises in WAN21_16; a FLUX VAE reads the same 16 channels in a different basis.
+
+ `anima_l2i` takes the `FluxAutoEncoder` branch without raising and without the Wan per-channel
+ denormalisation the `AutoencoderKLWan` branch applies, so nothing fails and nothing is logged.
+ Measured on real weights (`qwenImage_qwenImageVAE.safetensors` vs FLUX `ae.safetensors`,
+ 512x512, float32) by encoding an image with the Anima VAE and decoding that one latent down
+ both production branches:
+
+ Anima VAE vs original 46.18 dB PSNR, 0.0041 MAE, 0.327 max abs
+ FLUX VAE vs original 6.10 dB PSNR, 0.9325 MAE, 2.000 max abs
+
+ Per-channel means move from R +0.858 / G +0.804 / B +0.666 to R +0.156 / G -0.212 / B +0.111 --
+ a magenta, moire-patterned image in which the subject is barely discernible. It is not a
+ fallback, so it is not offered.
+ """
+ assert accepts_vae(BaseModelType.Anima, BaseModelType.Flux) is False
+
+
def test_an_architecture_without_the_facet_accepts_only_its_own_base() -> None:
assert accepts_vae(BaseModelType.StableDiffusionXL, BaseModelType.StableDiffusionXL) is True
assert accepts_vae(BaseModelType.StableDiffusionXL, BaseModelType.Flux) is False
@@ -96,6 +116,62 @@ def test_every_loader_with_a_vae_input_declares_its_bases(base: BaseModelType) -
)
+def _declared_latent_space(base: BaseModelType, latent_channels: int | None) -> LatentSpace | None:
+ """The space a VAE registered under `base` decodes, or None if `latent_channels` matches none.
+
+ `latent_channels` narrows only where the base has alternates -- today only `wan`, whose 48 is
+ TI2V-5B's Wan2.2-VAE. Everywhere else the base has exactly one space and the field is unused.
+ """
+ facet = require(base, LatentSpaceFacet)
+ if latent_channels is None:
+ return facet.primary
+ spaces = (facet.primary, *facet.alternates)
+ return next((space for space in spaces if space.channels == latent_channels), None)
+
+
+def test_every_accepted_vae_shares_the_architectures_latent_space() -> None:
+ """Compatibility is about the basis, not the channel count, and nothing else enforces that.
+
+ Eight architectures denoise in 16 channels at 8x and their VAEs are still not interchangeable:
+ WAN21_16 and FLUX_16 have different `rgb_factors` and only WAN21_16 carries an `rgb_bias`.
+ Anima declared `VaeCompatibility(Flux)` and `anima_l2i` decoded it without raising -- 6.10 dB
+ PSNR against the correct decode, measured on real weights; see
+ `test_anima_no_longer_offers_a_flux_vae_that_decodes_to_noise`.
+
+ There is no exception list. A new entry that fails this is a silently wrong decode, so the fix
+ is to drop the entry, not to name it here.
+ """
+
+ def _sort_key(entry: VaeCompatibility) -> tuple[str, int]:
+ return (entry.base.value, entry.latent_channels or 0)
+
+ violations = []
+ for base in generative_bases():
+ facet = get(base, VaeFacet)
+ if facet is None:
+ continue
+
+ own = 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"
+ )
+
+ assert violations == []
+
+
def test_the_facet_is_only_declared_where_it_says_something_new() -> None:
"""A facet repeating "its own base, no constraints" would be noise; `accepts_vae` says that
already for every architecture without one.
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.py
index 1494af2505..8774c3f5c1 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
@@ -2,25 +2,45 @@
Two layouts are in circulation for the same 16-channel autoencoder. Files exported from the
Qwen-Image repo carry diffusers keys (`decoder.conv_in.weight`); community redistributions carry the
-original layout (`decoder.conv1.weight`) and need converting.
+original Wan-family layout (`decoder.middle.0.residual.0.gamma`) and need converting.
Only the first was handled, with `strict=True`, so a redistributed file failed with 194 missing keys
--- while the byte-identical checkpoint installed under `anima` loaded fine, because that path uses
-`AutoencoderKLWan.from_single_file`, which converts. Whether a VAE worked came down to which base it
-happened to be probed as.
+-- while the byte-identical checkpoint installed under `anima` loaded fine, because that path
+converts. Whether a VAE worked came down to which base it happened to be probed as.
+
+Both branches are now keyed on a marker the layout must carry, and both registrations of the
+Wan-family file land in one loader, so the dtype and strictness policy cannot diverge between them.
"""
from unittest.mock import MagicMock, patch
+import pytest
import torch
+from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Anima_Config
from invokeai.backend.model_manager.load.model_loaders.vae import VAELoader
+# One key from each rule the Wan converter implements, so the assertion below is over a real
+# conversion rather than a renamed copy of its input.
+_ORIGINAL_LAYOUT = {
+ "conv1.weight": "quant_conv.weight",
+ "conv2.weight": "post_quant_conv.weight",
+ "encoder.conv1.weight": "encoder.conv_in.weight",
+ "encoder.downsamples.0.residual.0.gamma": "encoder.down_blocks.0.norm1.gamma",
+ "encoder.middle.1.to_qkv.weight": "encoder.mid_block.attentions.0.to_qkv.weight",
+ "decoder.conv1.weight": "decoder.conv_in.weight",
+ "decoder.middle.0.residual.0.gamma": "decoder.mid_block.resnets.0.norm1.gamma",
+ "decoder.upsamples.0.residual.0.gamma": "decoder.up_blocks.0.resnets.0.norm1.gamma",
+ "decoder.head.0.gamma": "decoder.norm_out.gamma",
+}
+
def _loader() -> VAELoader:
loader = VAELoader.__new__(VAELoader)
+ # float16 on CUDA is what `precision: auto` resolves to, and what the Wan VAE is unstable in.
loader._torch_dtype = torch.float16 # type: ignore[attr-defined]
loader._ram_cache = MagicMock() # type: ignore[attr-defined]
+ loader._logger = MagicMock() # type: ignore[attr-defined]
return loader
@@ -30,18 +50,72 @@ def _config(path: str = "vae.safetensors") -> MagicMock:
return config
-def test_the_original_layout_is_converted_rather_than_rejected() -> None:
- state_dict = {"decoder.conv1.weight": torch.zeros(1), "encoder.conv1.weight": torch.zeros(1)}
+def test_the_original_layout_is_converted_and_loaded_in_bfloat16() -> None:
+ """`from_single_file` would fetch the Wan config over HTTP at load time, and it would honour
+ `self._torch_dtype` -- float16 on a default CUDA install, the dtype `_load_wan_vae` and
+ `_load_wan_vae_diffusers` both refuse for this exact autoencoder."""
+ state_dict = {key: torch.zeros(2, dtype=torch.float32) for key in _ORIGINAL_LAYOUT}
with (
+ patch(
+ "invokeai.backend.model_manager.load.model_loaders.vae._checkpoint_keys",
+ return_value=set(state_dict),
+ ),
patch("safetensors.torch.load_file", return_value=state_dict),
+ patch("accelerate.init_empty_weights"),
patch("diffusers.models.autoencoders.AutoencoderKLWan") as wan,
patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),
):
- result = _loader()._load_qwen_image_vae(_config())
+ wan.return_value.load_state_dict.return_value = ([], [])
+ loader = _loader()
+ result = loader._load_qwen_image_vae(_config())
+
+ wan.from_single_file.assert_not_called()
+ wan.assert_called_once_with(z_dim=16)
+
+ (loaded,), kwargs = wan.return_value.load_state_dict.call_args
+ assert kwargs == {"strict": False, "assign": True}
+ assert set(loaded) == set(_ORIGINAL_LAYOUT.values())
+ assert {tensor.dtype for tensor in loaded.values()} == {torch.bfloat16}
+
+ loader._ram_cache.make_room.assert_called_once_with( # type: ignore[attr-defined]
+ sum(tensor.nelement() * tensor.element_size() for tensor in loaded.values())
+ )
+ assert result is wan.return_value
+
+
+def test_a_conversion_that_leaves_a_tensor_unset_is_an_error_not_a_warning() -> None:
+ """`from_single_file` loads with `strict=False` and reports only *unexpected* keys, so a tensor
+ the conversion never produced stays on the meta device and surfaces at the first decode --
+ after the model has loaded and generation has begun."""
+ state_dict = {key: torch.zeros(2, dtype=torch.float32) for key in _ORIGINAL_LAYOUT}
+
+ with (
+ patch(
+ "invokeai.backend.model_manager.load.model_loaders.vae._checkpoint_keys",
+ return_value=set(state_dict),
+ ),
+ patch("safetensors.torch.load_file", return_value=state_dict),
+ patch("accelerate.init_empty_weights"),
+ patch("diffusers.models.autoencoders.AutoencoderKLWan") as wan,
+ patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),
+ ):
+ wan.return_value.load_state_dict.return_value = (["decoder.conv_out.weight"], [])
+
+ with pytest.raises(ValueError, match="does not convert to a complete Wan 2.1 VAE"):
+ _loader()._load_qwen_image_vae(_config())
+
- wan.from_single_file.assert_called_once()
- assert result is wan.from_single_file.return_value
+def test_the_anima_registration_takes_the_same_path() -> None:
+ """The same checkpoint, registered for a different family. It used to be loaded by a separate
+ branch that passed `self._torch_dtype`, so `anima` and `qwen-image` disagreed about the dtype
+ of byte-identical weights."""
+ loader = _loader()
+ with patch.object(VAELoader, "_load_wan_family_vae") as load_wan_family:
+ result = loader._load_model(VAE_Checkpoint_Anima_Config.model_construct(path="anima-vae.safetensors"))
+
+ load_wan_family.assert_called_once_with("anima-vae.safetensors")
+ assert result is load_wan_family.return_value
def test_the_diffusers_layout_still_loads_directly() -> None:
@@ -49,6 +123,10 @@ def test_the_diffusers_layout_still_loads_directly() -> None:
state_dict = {"decoder.conv_in.weight": torch.zeros(1)}
with (
+ patch(
+ "invokeai.backend.model_manager.load.model_loaders.vae._checkpoint_keys",
+ return_value=set(state_dict),
+ ),
patch("safetensors.torch.load_file", return_value=state_dict),
patch("accelerate.init_empty_weights"),
patch("diffusers.models.autoencoders.autoencoder_kl_qwenimage.AutoencoderKLQwenImage") as qwen,
@@ -56,6 +134,32 @@ def test_the_diffusers_layout_still_loads_directly() -> None:
):
result = _loader()._load_qwen_image_vae(_config())
- wan.from_single_file.assert_not_called()
+ wan.assert_not_called()
qwen.return_value.load_state_dict.assert_called_once()
assert result is qwen.return_value
+
+
+def test_a_checkpoint_in_neither_layout_is_rejected() -> None:
+ """The discriminator used to be a negation, so this file was assumed to be the Wan layout.
+
+ `from_single_file` checks for keys it recognises, never for keys that are missing: an
+ unrecognised file falls through to `model_type = "v1"`, fetches SD 1.5's `vae/config.json`, and
+ returns an `AutoencoderKLWan` whose parameters are all still on the meta device -- a warning,
+ not an error, and a failure that surfaces at the first decode instead of at install time.
+ """
+ state_dict = {"first_stage_model.decoder.conv_in.weight": torch.zeros(1)}
+
+ with (
+ patch(
+ "invokeai.backend.model_manager.load.model_loaders.vae._checkpoint_keys",
+ return_value=set(state_dict),
+ ),
+ patch("safetensors.torch.load_file", return_value=state_dict) as load_file,
+ patch("diffusers.models.autoencoders.AutoencoderKLWan") as wan,
+ ):
+ with pytest.raises(ValueError, match="not a Qwen-Image VAE in either known layout"):
+ _loader()._load_qwen_image_vae(_config())
+
+ wan.assert_not_called()
+ wan.from_single_file.assert_not_called()
+ load_file.assert_not_called()