Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(models): default component models per main model (#10263)
Alexander Eichhorn7b783591bcdd
diff --git a/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx b/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdxindex 967850327b..bc802581ae 100644--- a/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx@@ -146,6 +146,7 @@ Click a model in the library to open it. Its **⋯** menu, and right-clicking it| --- | --- | --- || Rename, describe, reclassify | **Edit** | Change the name, description, base, type, variant, format and **Source URL**. Changing the format reclassifies the model; invalid combinations are rejected. || Default settings | **Default Settings**, then **Save Defaults** (main models, LoRAs, control adapters) | Applied when the model is selected; a setting left off uses the app default. |+| Default components | **Default Components** in **Default Settings** (main models whose family takes components, such as text encoders or a component source) | Switching to the model in Generate or Canvas fills each empty or incompatible slot, and the default VAE, with the model's default; a component that already fits stays. **Apply model defaults** and **Reset everything to defaults** put them in place of your picks. A default whose model is not installed, whose file is missing or that no longer fits the slot is skipped and named, and your pick stays. Recalling an image restores the components it recorded. For an image Invoke generated, a component the image does not name is not filled from the defaults: your current pick stays, or the slot stays empty. Metadata that does not come from a generation, such as parameters pasted in, fills the slots it leaves out from the defaults of the model it sets. A project whose Generate settings are not set up yet takes the model's defaults only after the image has been read, and only if the image sets no model. || Trigger phrases | **Trigger Phrases** (main models, LoRAs, embeddings) | Offered in the prompt editor. || Cover image | Click the model's image | Shown in the library and pickers. PNG, JPEG or WebP. || Related models | **Related Models** | Linked models are suggested together elsewhere in the app. |@@ -159,7 +160,7 @@ Click a model in the library to open it. Its **⋯** menu, and right-clicking it**Source URL** records where a model came from, such as its Civitai or HuggingFace page, and shows as a link in the model's details. It doesn't affect loading or updates.:::caution[Re-identify resets settings]-Re-identify keeps the name, description, cover image, trigger phrases, install source and the CPU and FP8 storage choices. It resets the custom variant and the other default settings, and clears the **Source URL**: note it first. Re-identifying several models asks for confirmation first; the single-model action runs at once.+Re-identify keeps the name, description, cover image, trigger phrases, install source and the CPU and FP8 storage choices, and the default VAE and default components while the base stays the same. It resets the custom variant and the other default settings, and clears the **Source URL**: note it first. Re-identifying several models asks for confirmation first; the single-model action runs at once.Re-identify also recomputes the model's roles (see below). Changing a model's **Type** by hand in the edit form discards its roles; Re-identify restores them.:::diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdxindex bcaeb9db5f..6af0c5993b 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx@@ -109,8 +109,8 @@ Two output filters live in the Generate widget's settings (the cog in its headerEach model can have default settings, which you set in the Model Manager. The ↺ button in the Generate panel's title bar, **Reset settings**, opens a menu with two choices, each saying under its name what it would change, such as *Steps 30 → 8, CFG 7 → 1*:-* **Apply model defaults** applies only the values the model sets there: any of size, steps, CFG or guidance, scheduler, VAE, VAE precision and CFG rescale. A setting the model leaves unset keeps your value, so a model with no default size leaves your size alone; the menu lists what the model does not set. When the model sets only a width or only a height, that side is applied as if you typed it: a locked aspect ratio carries the other side along, an unlocked one leaves it. The choice is unavailable when the model's values already hold or the model sets no defaults, and it says which.-* **Reset everything to defaults** resets all of those settings: to the model's values where it sets them, and to Invoke's defaults for its family everywhere else, size included. Your VAE stays unless the model sets one; a reset that locks the aspect ratio says so (*Aspect ratio Free → 1:1*).+* **Apply model defaults** applies only the values the model sets there: any of size, steps, CFG or guidance, scheduler, VAE, default components, VAE precision and CFG rescale. A setting the model leaves unset keeps your value, so a model with no default size leaves your size alone; the menu lists what the model does not set. When the model sets only a width or only a height, that side is applied as if you typed it: a locked aspect ratio carries the other side along, an unlocked one leaves it. The choice is unavailable when the model's values already hold or the model sets no defaults, and it says which.+* **Reset everything to defaults** resets all of those settings: to the model's values where it sets them, and to Invoke's defaults for its family everywhere else, size included. Your VAE and components stay unless the model sets them; a reset that locks the aspect ratio says so (*Aspect ratio Free → 1:1*).A default VAE set to the model's own ("Default VAE" in the Model Manager) means the VAE bundled with the model, and either choice returns to it, except for families such as FLUX.1 whose VAE is a separate, required component. A VAE the model names but that is not installed, or does not fit the model, is never applied: both choices keep your VAE, and the menu says so. Recalling an image or parameters that switch to such a model uses the bundled VAE instead, so an image made with it is reproduced; only where a VAE is required and none is bundled does your VAE stay. Newly installed models come with their family's recommended values filled in as their default settings, size included, so **Apply model defaults** sets the size for them until you clear Width and Height under **Default Settings** in the Model Manager.diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 81fae12853..69aeb84da5 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -42,6 +42,7 @@ from invokeai.app.services.model_records import (ModelRecordOrderBy,UnknownModelException,)+from invokeai.app.services.model_records.missing_models import find_missing_modelsfrom invokeai.app.services.orphaned_models import CONVERSION_SCRATCH_DIRNAME, OrphanedModelInfofrom invokeai.app.services.shared.pagination import SQLiteDirectionfrom invokeai.app.util.path_safety import is_plain_filename@@ -372,14 +373,7 @@ def list_missing_models(current_user: CurrentUserOrDefault) -> ModelsList:record_store = ApiDependencies.invoker.services.model_manager.storemodels_path = ApiDependencies.invoker.services.configuration.models_path- missing_models: list[AnyModelConfig] = []- for model_config in record_store.all_models():- if model_config.base == BaseModelType.External or model_config.format == ModelFormat.ExternalApi:- continue- if not (models_path / model_config.path).resolve().exists():- missing_models.append(model_config)-- return ModelsList(models=missing_models)+ return ModelsList(models=find_missing_models(record_store.all_models(), models_path))@model_manager_router.get(diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.pyindex 1cc1c1b988..8137768469 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -58,6 +58,7 @@ from invokeai.app.services.model_install.model_install_common import (URLModelSource,)from invokeai.app.services.model_records import DuplicateModelException, ModelRecordServiceBase, UnknownModelException+from invokeai.app.services.model_records.missing_models import find_missing_modelsfrom invokeai.app.services.model_records.model_records_base import ModelRecordChangesfrom invokeai.app.util.no_replace import rename_noreplacefrom invokeai.app.util.path_safety import is_plain_filename@@ -91,7 +92,6 @@ from invokeai.backend.model_manager.metadata.metadata_base import (from invokeai.backend.model_manager.search import ModelSearchfrom invokeai.backend.model_manager.taxonomy import (BaseModelType,- ModelFormat,ModelRepoVariant,ModelSourceType,ModelType,@@ -1950,13 +1950,7 @@ class ModelInstallService(ModelInstallServiceBase):# --------------------------------------------------------------------------------------------def _scan_for_missing_models(self) -> list[AnyModelConfig]:"""Scan the models directory for missing models and return a list of them."""- missing_models: list[AnyModelConfig] = []- for model_config in self.record_store.all_models():- if model_config.base == BaseModelType.External or model_config.format == ModelFormat.ExternalApi:- continue- if not (self.app_config.models_path / model_config.path).resolve().exists():- missing_models.append(model_config)- return missing_models+ return find_missing_models(self.record_store.all_models(), self.app_config.models_path)def _register_orphaned_models(self) -> None:"""Scan the invoke-managed models directory for orphaned models and registers them.diff --git a/invokeai/app/services/model_manager/model_manager_default.py b/invokeai/app/services/model_manager/model_manager_default.pyindex 17363c5ed2..29a635bde0 100644--- a/invokeai/app/services/model_manager/model_manager_default.py+++ b/invokeai/app/services/model_manager/model_manager_default.py@@ -22,6 +22,7 @@ from invokeai.app.services.model_records.model_records_base import (ModelRecordChanges,ModelRecordServiceBase,)+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactoryfrom invokeai.backend.model_manager.configs.qwen3_5_encoder import Qwen35Encoder_Checkpoint_Configfrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache@@ -29,9 +30,16 @@ from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudgetfrom invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStorefrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.model_on_disk import ModelOnDisk+from invokeai.backend.model_manager.taxonomy import ModelTypefrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILogger+# Default settings a user chooses, which identification cannot derive and so must not replace on re-identify. The load+# preferences always carry over. The default VAE and component models name models of the base they were chosen for, so+# they carry over only while the base is unchanged. The rest are the architecture's recommendations.+_USER_CURATED_LOAD_SETTINGS = ("cpu_only", "fp8_storage")+_USER_CURATED_BASE_BOUND_SETTINGS = ("vae", "components")+class ModelManagerService(ModelManagerServiceBase):"""@@ -111,11 +119,22 @@ class ModelManagerService(ModelManagerServiceBase):identified.cpu_only = config.cpu_onlyprevious_settings = getattr(config, "default_settings", None)updated_settings = getattr(identified, "default_settings", None)- if previous_settings is not None and updated_settings is not None:+ if (+ updated_settings is None+ and isinstance(previous_settings, MainModelDefaultSettings)+ and identified.type == ModelType.Main+ ):+ # The probe has no recommendations for this config; the user's curated fields still carry over.+ updated_settings = MainModelDefaultSettings()+ elif updated_settings is not None:# The probe may hand back an architecture's shared defaults object; copy it before writing to it.updated_settings = deepcopy(updated_settings)+ if previous_settings is not None and updated_settings is not None:identified.default_settings = updated_settings- for field in ("cpu_only", "fp8_storage"):+ carried = _USER_CURATED_LOAD_SETTINGS+ if identified.base == config.base:+ carried += _USER_CURATED_BASE_BOUND_SETTINGS+ for field in carried:if hasattr(previous_settings, field) and hasattr(updated_settings, field):setattr(updated_settings, field, getattr(previous_settings, field))diff --git a/invokeai/app/services/model_records/missing_models.py b/invokeai/app/services/model_records/missing_models.pynew file mode 100644index 0000000000..34e09277e4--- /dev/null+++ b/invokeai/app/services/model_records/missing_models.py@@ -0,0 +1,24 @@+"""Which registered models have lost their files, by the one rule the Model Manager and the calibration share."""++from collections.abc import Iterable+from pathlib import Path++from invokeai.backend.model_manager.configs.factory import AnyModelConfig+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat+++def is_model_missing(config: AnyModelConfig, models_path: Path) -> bool:+ """Whether the files of a registered model are gone. External providers have none, so they are never missing."""+ if config.base == BaseModelType.External or config.format == ModelFormat.ExternalApi:+ return False+ try:+ return not (models_path / config.path).resolve().exists()+ except (OSError, RuntimeError):+ # An inaccessible directory (PermissionError) or a symlink loop (RuntimeError from resolve() before Python 3.13)+ # makes the files unusable, and must not stop the scan of the other models.+ return True+++def find_missing_models(configs: Iterable[AnyModelConfig], models_path: Path) -> list[AnyModelConfig]:+ """The registered models among `configs` whose files are gone, in order."""+ return [config for config in configs if is_model_missing(config, models_path)]diff --git a/invokeai/app/services/model_records/model_records_sql.py b/invokeai/app/services/model_records/model_records_sql.pyindex c8deb9c2f0..3b1d300769 100644--- a/invokeai/app/services/model_records/model_records_sql.py+++ b/invokeai/app/services/model_records/model_records_sql.py@@ -49,6 +49,7 @@ from invokeai.app.services.shared.database.queries import Queriesfrom invokeai.app.services.shared.database.queries.models import MAX_KEY_LENGTH, MAX_PATH_LENGTHfrom invokeai.app.services.shared.pagination import SQLiteDirectionfrom invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Config_Base+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.factory import (SINGLE_FILE_MODEL_SUFFIXES,AnyModelConfig,@@ -101,6 +102,25 @@ def _check_path_length(path: str) -> None:raise ValueError(f"A model's path can be at most {MAX_PATH_LENGTH} characters long")+def _changed_value(changes: ModelRecordChanges, field_name: str, record: AnyModelConfig) -> object:+ """The value `changes` sets for `field_name`.++ Main-model default settings that do not mention `components` leave the stored ones alone: a client that predates+ the field posts the whole settings object back and would otherwise erase them. An explicit `null` or empty map+ still clears them.+ """+ value = getattr(changes, field_name)+ stored = getattr(record, field_name, None)+ if (+ field_name == "default_settings"+ and isinstance(value, MainModelDefaultSettings)+ and isinstance(stored, MainModelDefaultSettings)+ and "components" not in value.model_fields_set+ ):+ return value.model_copy(update={"components": stored.components})+ return value++def _stored_json(config: AnyModelConfig) -> str:"""The JSON a record is stored as. Empty roles are left out: a config with `extra="forbid"` would make an olderbuild, which has no `roles` field, drop the record."""@@ -179,7 +199,7 @@ class ModelRecordServiceSQL(ModelRecordServiceBase):# 2. Apply the changes to the dictfor field_name in changes.model_fields_set:- record_as_dict[field_name] = getattr(changes, field_name)+ record_as_dict[field_name] = _changed_value(changes, field_name, original)# 3. Attempt to create a new model config from the updated dict.#@@ -220,7 +240,7 @@ class ModelRecordServiceSQL(ModelRecordServiceBase):# We are not allowing the model config class to change, so we can just update the existing instance in# place. If the changes are invalid for the existing class, an exception will be raised by pydantic.for field_name in changes.model_fields_set:- setattr(record, field_name, getattr(changes, field_name))+ setattr(record, field_name, _changed_value(changes, field_name, record))# If we get this far, the updated model config is valid, so we can save it to the database.if "path" in changes.model_fields_set:diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.pyindex e67acf6666..01df4f433f 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py@@ -21,6 +21,7 @@ import torchfrom invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocationfrom invokeai.app.invocations.fields import WithBoardfrom invokeai.app.services.model_records import UnknownModelException+from invokeai.app.services.model_records.missing_models import is_model_missingfrom invokeai.app.services.session_queue.session_queue_common import (DEFAULT_QUEUE_ID,QUEUE_ITEM_STATUS,@@ -97,6 +98,7 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibrationStoreRead,)from invokeai.app.util.misc import uuid_string+from invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.load.load_default import resolve_submodel_pathfrom invokeai.backend.model_manager.taxonomy import SubModelTypefrom invokeai.backend.quantization.sdnq.detection import is_sdnq_folder@@ -531,6 +533,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):untiled_decode_reservation: Callable[[str, int, int, str, torch.device], int] = _untiled_decode_reservation,device_memory: Optional[Callable[[torch.device], DeviceMemory]] = None,vae_dtypes: Callable[[torch.device, Path], VaeDtypes] = _vae_dtypes,+ is_model_missing: Callable[[AnyModelConfig, Path], bool] = is_model_missing,) -> None:self._store = storeself._generation_devices = generation_devices@@ -539,6 +542,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):self._untiled_decode_reservation = untiled_decode_reservationself._device_memory = device_memory or self._cache_memoryself._vae_dtypes = vae_dtypes+ self._is_model_missing = is_model_missing# A card's class cannot change while the process runs; reading it touches the driver.self._device_classes: dict[str, DeviceClass] = {}# Which file holds a run, so admitting an item and recording its windows do not scan every file.@@ -1736,7 +1740,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):specs = import_estimator_modules()return build_plan(target,- store.all_models(),+ self._available_models(),device_class=self._device_class(device) if device is not None else None,unavailable=unavailable,platform=platform_for(device) if device is not None else None,@@ -1749,6 +1753,16 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):force_tiled_decode=self._services.configuration.force_tiled_decode,)+ def _available_models(self) -> list[AnyModelConfig]:+ """The registered models whose files are on disk: Generate skips the others as default components and as+ fallbacks, so a plan that counted them (a Z-Image source whose directory is gone) would size another graph."""+ models_path = self._services.configuration.models_path+ return [+ model+ for model in self._services.model_manager.store.all_models()+ if not self._is_model_missing(model, models_path)+ ]+def _vae_dtypes_on(self, device: Optional[torch.device]) -> VaeDtypes:"""What the VAE loaders choose on `device`, by default the one models load onto."""return self._vae_dtypes(device or TorchDevice.choose_torch_device(), self._services.configuration.models_path)@@ -1857,7 +1871,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):target,self._services.configuration.precision,self._vae_dtypes_on(self._present_device(class_id)),- store.all_models(),+ self._available_models(),),name_of=name_of,held_back=held_back,diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.pyindex 6e29c8fca7..974de4a6fd 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py@@ -362,9 +362,26 @@ def _text_encoder_reason(main: ModelConfig, models: Sequence[ModelConfig]) -> st)+def default_component_source(model: ModelConfig, models: Sequence[ModelConfig]) -> Optional[ModelConfig]:+ """The Z-Image pipeline a main model's default components name as its `component_source`, which Generate fills the+ slot with when the model is selected (`getModelDefaultComponents`): an installed pipeline that brings its own VAE+ (`ships_its_vae`). A self-contained pipeline is offered the slot too, and the model loader node takes a source's+ VAE over its own. FLUX.2 picks its source on its own (`vae_source`), so a stored one is not read."""+ if not _is_main(model) or model.base != BaseModelType.ZImage:+ return None+ key = getattr(getattr(model, "default_settings", None), "components", None)+ key = key.get("component_source") if isinstance(key, Mapping) else None+ if not key:+ return None+ return next(+ (source for source in models if source.key == key and source.base == model.base and ships_its_vae(source)), None+ )++def vae_source(model: ModelConfig, models: Sequence[ModelConfig]) -> Optional[ModelConfig]:"""The pipeline whose own VAE decodes a main model's generations while its `vae` slot is empty: the model itself- (`ships_its_vae`), or for another FLUX.2 model the component source Generate then picks on its own and its graph+ (`ships_its_vae`), the Z-Image pipeline its default components name (`default_component_source`), or for another+ FLUX.2 model the component source Generate then picks on its own and its graphkeeps, whose VAE the FLUX.2 model loader node takes: among the installed pipelines that loader takes componentsfrom (`_flux2_sources`), the first fitting one, else the first one (`getAutoFlux2ComponentSourceModel`), which thegraph keeps only beside a standalone text encoder. Generate lists the models in the order the server does, which is@@ -373,6 +390,8 @@ def vae_source(model: ModelConfig, models: Sequence[ModelConfig]) -> Optional[Mo(`_needs_gpu_vae`)."""if default_vae(model, models) is not None:return None+ if (source := default_component_source(model, models)) is not None:+ return sourceif ships_its_vae(model):return modelif not _is_main(model) or model.base != BaseModelType.Flux2:diff --git a/invokeai/backend/model_manager/configs/default_settings.py b/invokeai/backend/model_manager/configs/default_settings.pyindex f5800919d1..80c0b45fc8 100644--- a/invokeai/backend/model_manager/configs/default_settings.py+++ b/invokeai/backend/model_manager/configs/default_settings.py@@ -10,14 +10,18 @@ the registry which imports the defs which import the facet, and the cycle closeshalf-initialized module."""+import refrom typing import Literal-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, field_validatorfrom invokeai.backend.stable_diffusion.schedulers.schedulers import SCHEDULER_NAME_VALUESDEFAULTS_PRECISION = Literal["fp16", "fp32"]+_COMPONENT_SLOT_PATTERN = re.compile(r"^[a-z0-9_]+$")+MAX_DEFAULT_COMPONENTS = 16+class MainModelDefaultSettings(BaseModel):vae: str | None = Field(default=None, description="Default VAE for this model (model key)")@@ -37,4 +41,36 @@ class MainModelDefaultSettings(BaseModel):description="Store weights in FP8 to reduce VRAM usage (~50% savings). Weights are cast to compute dtype during inference.",)+ components: dict[str, str] | None = Field(+ default=None,+ # Left out of a dump while unset: an older server forbids unknown fields, so a record that carries the key+ # even as null would be skipped by it.+ exclude_if=lambda value: value is None,+ description=(+ "Default component models for this main model, keyed by the component slot name Generate reads, "+ "e.g. `t5_encoder`, `qwen3_encoder` or `component_source` (the component source of Qwen Image, Wan and "+ "similar families, which graphs record under their own metadata names); values are model keys. The default "+ "VAE lives in `vae`."+ ),+ )+model_config = ConfigDict(extra="forbid")++ @field_validator("components")+ @classmethod+ def _validate_components(cls, components: dict[str, str] | None) -> dict[str, str] | None:+ # Keys are not checked against installed models, like `vae`: a model removed later leaves a dangling key that+ # the client ignores. Only the shape is bounded, since the map is stored with every record.+ if not components:+ # An empty map stores nothing, like null, so clients see one representation of "no defaults".+ return None+ if len(components) > MAX_DEFAULT_COMPONENTS:+ raise ValueError(f"at most {MAX_DEFAULT_COMPONENTS} default components are allowed, got {len(components)}")+ for slot, model_key in components.items():+ if slot == "vae":+ raise ValueError("the default VAE is set with the `vae` field, not as a component")+ if not _COMPONENT_SLOT_PATTERN.fullmatch(slot):+ raise ValueError(f"component slot {slot!r} must be snake_case (lowercase letters, digits, underscores)")+ if not model_key.strip():+ raise ValueError(f"component {slot!r} needs a model key")+ return componentsdiff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 115d5abf3f..60fb886125 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -79328,6 +79328,21 @@],"title": "Fp8 Storage","description": "Store weights in FP8 to reduce VRAM usage (~50% savings). Weights are cast to compute dtype during inference."+ },+ "components": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Components",+ "description": "Default component models for this main model, keyed by the component slot name Generate reads, e.g. `t5_encoder`, `qwen3_encoder` or `component_source` (the component source of Qwen Image, Wan and similar families, which graphs record under their own metadata names); values are model keys. The default VAE lives in `vae`."}},"additionalProperties": false,diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 531e7fea64..92c1bc31a2 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -32826,6 +32826,13 @@ export type components = {* @description Store weights in FP8 to reduce VRAM usage (~50% savings). Weights are cast to compute dtype during inference.*/fp8_storage?: boolean | null;+ /**+ * Components+ * @description Default component models for this main model, keyed by the component slot name Generate reads, e.g. `t5_encoder`, `qwen3_encoder` or `component_source` (the component source of Qwen Image, Wan and similar families, which graphs record under their own metadata names); values are model keys. The default VAE lives in `vae`.+ */+ components?: {+ [key: string]: string;+ } | null;};/*** Main Model - SD1.5, SD2diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex 6fc83d2a9c..7c85219365 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -37,7 +37,7 @@ Ownership follows invariants, not the first caller:- Authentication: `app/main.tsx` hands it to Platform transport before React mounts. Identity owns the credential and every policy about it. Platform captures it once per request and reports that request's outcome.- Platform socket publishes raw events and connection transitions. Queue and other domains interpret them.- Lifecycle-specific production composition stays explicit at its natural root: authenticated socket in `app/router.tsx`, editor runtimes in `app/WorkbenchApp.tsx`, feature UI providers in `app/workbenchPorts.tsx`, lazy editor bridges beside their lazy entry modules. App builds the production Queue runtime from Queue, Workbench, Gallery, Workflow adapters.- - The authenticated layout in `app/router.tsx` supplies the account's Models UI port (capabilities, preferences, Generation's scheduler rules), which the Launchpad Model Manager reads and the editor's adapter narrows with its active project. It lives there because a new module would join the Launchpad's startup graph; the scheduler rules load on demand from a lazy module.+ - The authenticated layout in `app/router.tsx` supplies the account's Models UI port (capabilities, preferences, Generation's rules for a model's default settings), which the Launchpad Model Manager reads and the editor's adapter narrows with its active project. It lives there because a new module would join the Launchpad's startup graph; those rules (scheduler choices, component slots) load on demand from a lazy module.- The authenticated route applies the account's startup destination preference (`app/startupRedirect.ts`) once per page load. Only opening the bare URL is a launch (not a deep link, reload or history return); its first authenticated arrival at Home may redirect to the editor, and later visits to Home never do. While a launch decides or opens, the splash offers "Stay on the Launchpad". A launch that redirects into the editor leaves a mark in the account's browser storage (`workbench/launchpad/startupLaunch.ts`), naming the project it opened; any editor render clears it, whichever page or tab rendered, and so does deleting that project. If the mark survives to the next launch (the editor failed to load or crashed first), that one launch stays on the Launchpad with a notice instead of reopening the same work.- Signed-out arrivals go to `/login`; an expired session carries `returnTo`, the in-app path it was on, and a sign-in by the same account, on this page or followed from another tab, returns there (any other account starts at Home). Following another tab's sign-in to a different account shows "Switching account…", then lands on Home. Addresses no route answers open Home, and Launchpad managers the account may not use open Projects, each with a notice (never on a hover preload).- Controlled Chakra props stay synchronized when React Activity reconnects a retained section: Zag's watchers reconcile values changed while hidden without replaying unchanged ones, so a confirmation completed while hidden stays closed. `ConfirmDialog.browser.test.tsx` and the production workbench keep-alive scroll/zoom journey cover it; rerun both when upgrading Zag or Chakra.diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex a86d2ae61d..6df101103a 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -2,15 +2,15 @@"build": {"launchpad": {"baseline": {- "brotliBytes": 827521,+ "brotliBytes": 828036,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 826297,+ "gzipBytes": 826764,"imageRawBytes": 44398,- "initialRawBytes": 2143904,+ "initialRawBytes": 2144774,"largestAssetRawBytes": 770754,"otherAssetRawBytes": 0,- "ownedRawBytes": 116635,+ "ownedRawBytes": 117308,"requestCount": 34,"scriptRequestCount": 18,"sourceOwners": [@@ -364,15 +364,15 @@},"editor": {"baseline": {- "brotliBytes": 1302629,+ "brotliBytes": 1305696,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 1294831,+ "gzipBytes": 1297890,"imageRawBytes": 44398,- "initialRawBytes": 3611751,+ "initialRawBytes": 3620562,"largestAssetRawBytes": 770754,"otherAssetRawBytes": 0,- "ownedRawBytes": 177699,+ "ownedRawBytes": 177610,"requestCount": 70,"scriptRequestCount": 54,"sourceOwners": [@@ -576,6 +576,7 @@"source:src/features/generation/core/canvas/controlValidation.ts","source:src/features/generation/core/catalogSearch.ts","source:src/features/generation/core/componentCompatibility.ts",+ "source:src/features/generation/core/componentDefaults.ts","source:src/features/generation/core/conditioningRebalance.ts","source:src/features/generation/core/dimensionLimits.ts","source:src/features/generation/core/dynamicPrompts.ts",@@ -1189,7 +1190,7 @@"source": "src/app/WorkbenchApp.tsx"}},- "capturedAt": "2026-11-19",+ "capturedAt": "2026-11-20","developmentInvalidation": {"platformUiBarrel": {"specifier": "@platform/ui",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 8f54890881..5d7f5ff51d 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -30,11 +30,11 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 28,- "scriptRawBytes": 1971379,+ "scriptRawBytes": 1973080,"scriptRequestCount": 24,- "totalRawBytes": 2332599+ "totalRawBytes": 2336135},"routeReadyMedianMs": 270.59999999962747,"scriptSourceOwnerSet": "launchpad-static",@@ -68,11 +68,11 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 28,- "scriptRawBytes": 1971379,+ "scriptRawBytes": 1973080,"scriptRequestCount": 24,- "totalRawBytes": 2332599+ "totalRawBytes": 2336135},"routeReadyMedianMs": 293.09999999962747,"scriptSourceOwnerSet": "launchpad-static",@@ -106,11 +106,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 84,- "scriptRawBytes": 4732676,+ "scriptRawBytes": 4748784,"scriptRequestCount": 79,- "totalRawBytes": 5138294+ "totalRawBytes": 5156237},"routeReadyMedianMs": 468.5,"scriptSourceOwnerSet": "editor-minimal-static",@@ -144,11 +144,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 84,- "scriptRawBytes": 4732676,+ "scriptRawBytes": 4748784,"scriptRequestCount": 79,- "totalRawBytes": 5138294+ "totalRawBytes": 5156237},"routeReadyMedianMs": 464.59999999962747,"scriptSourceOwnerSet": "editor-minimal-static",@@ -159,12 +159,12 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 354198,+ "largestAssetRawBytes": 354247,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 620754,+ "scriptRawBytes": 620765,"scriptRequestCount": 7,- "totalRawBytes": 620754+ "totalRawBytes": 620765},"domContentLoadedMedianMs": 133.89999999850988,"id": "editor-canvas",@@ -182,11 +182,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 91,- "scriptRawBytes": 5353430,+ "scriptRawBytes": 5369549,"scriptRequestCount": 86,- "totalRawBytes": 5759048+ "totalRawBytes": 5777002},"routeReadyMedianMs": 1293.800000000745,"scriptSourceOwnerSet": "editor-canvas-static",@@ -197,12 +197,12 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 354198,+ "largestAssetRawBytes": 354247,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 620754,+ "scriptRawBytes": 620765,"scriptRequestCount": 7,- "totalRawBytes": 620754+ "totalRawBytes": 620765},"domContentLoadedMedianMs": 133.90000000037253,"id": "editor-canvas",@@ -220,11 +220,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 91,- "scriptRawBytes": 5353430,+ "scriptRawBytes": 5369549,"scriptRequestCount": 86,- "totalRawBytes": 5759048+ "totalRawBytes": 5777002},"routeReadyMedianMs": 1294.300000000745,"scriptSourceOwnerSet": "editor-canvas-static",@@ -235,12 +235,12 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 221147,+ "largestAssetRawBytes": 221153,"otherRawBytes": 0,"requestCount": 6,- "scriptRawBytes": 442639,+ "scriptRawBytes": 442649,"scriptRequestCount": 5,- "totalRawBytes": 458052+ "totalRawBytes": 458062},"domContentLoadedMedianMs": 133.40000000037253,"id": "editor-workflow",@@ -258,11 +258,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 90,- "scriptRawBytes": 5175315,+ "scriptRawBytes": 5191433,"scriptRequestCount": 84,- "totalRawBytes": 5596346+ "totalRawBytes": 5614299},"routeReadyMedianMs": 1276.699999999255,"scriptSourceOwnerSet": "editor-workflow-static",@@ -273,12 +273,12 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 221147,+ "largestAssetRawBytes": 221153,"otherRawBytes": 0,"requestCount": 6,- "scriptRawBytes": 442639,+ "scriptRawBytes": 442649,"scriptRequestCount": 5,- "totalRawBytes": 458052+ "totalRawBytes": 458062},"domContentLoadedMedianMs": 132.30000000074506,"id": "editor-workflow",@@ -296,11 +296,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 90,- "scriptRawBytes": 5175315,+ "scriptRawBytes": 5191433,"scriptRequestCount": 84,- "totalRawBytes": 5596346+ "totalRawBytes": 5614299},"routeReadyMedianMs": 1363.5999999996275,"scriptSourceOwnerSet": "editor-workflow-static",@@ -334,11 +334,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 84,- "scriptRawBytes": 4732676,+ "scriptRawBytes": 4748784,"scriptRequestCount": 79,- "totalRawBytes": 5138294+ "totalRawBytes": 5156237},"routeReadyMedianMs": 1494.300000000745,"scriptSourceOwnerSet": "editor-minimal-static",@@ -372,11 +372,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 770754,- "otherRawBytes": 335397,+ "otherRawBytes": 337232,"requestCount": 84,- "scriptRawBytes": 4732676,+ "scriptRawBytes": 4748784,"scriptRequestCount": 79,- "totalRawBytes": 5138294+ "totalRawBytes": 5156237},"routeReadyMedianMs": 1513.5,"scriptSourceOwnerSet": "editor-minimal-static",@@ -1012,6 +1012,7 @@"source:src/features/generation/core/canvas/controlValidation.ts","source:src/features/generation/core/catalogSearch.ts","source:src/features/generation/core/componentCompatibility.ts",+ "source:src/features/generation/core/componentDefaults.ts","source:src/features/generation/core/conceptList.ts","source:src/features/generation/core/conditioningRebalance.ts","source:src/features/generation/core/dimensionLimits.ts",@@ -2194,6 +2195,7 @@"source:src/features/generation/core/canvas/controlValidation.ts","source:src/features/generation/core/catalogSearch.ts","source:src/features/generation/core/componentCompatibility.ts",+ "source:src/features/generation/core/componentDefaults.ts","source:src/features/generation/core/conceptList.ts","source:src/features/generation/core/conditioningRebalance.ts","source:src/features/generation/core/dimensionLimits.ts",@@ -3547,6 +3549,7 @@"source:src/features/generation/core/canvas/controlValidation.ts","source:src/features/generation/core/catalogSearch.ts","source:src/features/generation/core/componentCompatibility.ts",+ "source:src/features/generation/core/componentDefaults.ts","source:src/features/generation/core/conceptList.ts","source:src/features/generation/core/conditioningRebalance.ts","source:src/features/generation/core/dimensionLimits.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex dd2b23c524..1e85de7ae4 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1527,6 +1527,10 @@"weightMin": "Weight Min","width": "Width"},+ "defaultComponents": "Default Components",+ "defaultComponentsHelp": "Filled in when you switch to this model; a component that already fits stays. Apply model defaults and Reset everything to defaults use them over your picks.",+ "defaultComponentsNone": "No default",+ "missingModelKey": "Missing model: {{key}}","defaultSettings": "Default Settings","defaultVae": "Default VAE","defaultSettingsHelp": "Applied automatically when this model is selected. Off = use the app default.",@@ -3546,10 +3550,13 @@"modelDefaultsChange": "{{setting}} {{from}} → {{to}}","modelDefaultsUnset": "Left as is, not set for this model: {{settings}}","modelDefaultsApplyHint": "{{changes}}. Left as is, not set for this model: {{settings}}",- "modelDefaultsVaeMissing": "The model's VAE is not installed or does not fit it, so your VAE stays.",- "modelDefaultsWithVaeMissing": "{{hint}}. The model's VAE is not installed or does not fit it, so your VAE stays.",- "modelDefaultsOnlyVaeMissing": "{{name}} sets only a VAE, which is not installed or does not fit it, so your VAE stays.",- "modelDefaultsAppliedExceptVae": "Already using {{name}}'s defaults, except its VAE, which is not installed or does not fit it, so your VAE stays.",+ "modelDefaultsMissingNote_one": "{{list}} is missing, not installed or does not fit this model, so no default is applied for it.",+ "modelDefaultsMissingNote_other": "{{list}} are missing, not installed or do not fit this model, so no default is applied for them.",+ "modelDefaultsWithMissingNote": "{{hint}}. {{note}}",+ "modelDefaultsOnlyMissing_one": "{{name}} sets only {{list}}, which is missing, not installed or does not fit it, so nothing is applied.",+ "modelDefaultsOnlyMissing_other": "{{name}} sets only {{list}}, which are missing, not installed or do not fit it, so nothing is applied.",+ "modelDefaultsAppliedExceptMissing_one": "Already using {{name}}'s defaults, except {{list}}, which is missing, not installed or does not fit it.",+ "modelDefaultsAppliedExceptMissing_other": "Already using {{name}}'s defaults, except {{list}}, which are missing, not installed or do not fit it.","modelDefaultsNoneSet": "{{name}} has no default settings of its own. Add them in the Model Manager.","modelDefaultsAlreadyApplied": "Already using {{name}}'s defaults.","resetSettings": "Reset settings",diff --git a/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx b/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsxindex 4afe85dfd3..bec4d11960 100644--- a/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx@@ -82,6 +82,7 @@ const settingsModel = (overrides: Partial<DefaultSettingsModel>): DefaultSettingdefault_settings: null,format: 'checkpoint',key: 'model-key',+ name: 'Model',type: 'main',variant: null,...overrides,@@ -164,7 +165,7 @@ describe('Account Models port on the Launchpad', () => {// The rules are a lazy chunk (the reader and the Generation modules it imports); load it up front so the first test// is not timing a cold transform. Importing it starts nothing: the section's load does.beforeAll(async () => {- await import('./modelSchedulerPolicyReader');+ await import('./modelDefaultsRulesReader');});it('loads Generate’s rules on demand and offers its Anima schedulers once the table arrives', async () => {diff --git a/invokeai/frontend/webv2/src/app/VideoModelPicker.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoModelPicker.browser.test.tsxindex 3a8125fdfe..54fe015aae 100644--- a/invokeai/frontend/webv2/src/app/VideoModelPicker.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/VideoModelPicker.browser.test.tsx@@ -4,7 +4,7 @@ import type { VideoUiAdapter } from '@features/video/ui/VideoUiContext';import { ChakraProvider } from '@chakra-ui/react';import { seedArchitectureCapabilities } from '@features/models/core/architectureCapabilities.testing';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';-import { ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { createDefaultVideoWidgetValues } from '@features/video';import { VideoModelField } from '@features/video/ui/VideoModelField';import { VideoUiProvider } from '@features/video/ui/VideoUiContext';@@ -44,7 +44,7 @@ const modelsAdapter = {installInPlace: true,isProjectActive: () => true,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,};diff --git a/invokeai/frontend/webv2/src/app/graphExport.test.ts b/invokeai/frontend/webv2/src/app/graphExport.test.tsindex cb1b1cd64c..4afcef720e 100644--- a/invokeai/frontend/webv2/src/app/graphExport.test.ts+++ b/invokeai/frontend/webv2/src/app/graphExport.test.ts@@ -138,6 +138,27 @@ describe('graph export', () => {});});+ it('takes the default component the way Generate does: not while its files are missing', () => {+ const zImage = { ...sdxlCase('z-image'), model_key: 'z-image-gguf' };+ const withDefault = (flagged: boolean, missingFirst = false) => {+ const models = MODELS.map((entry) =>+ entry.key === 'z-image-gguf'+ ? { ...entry, default_settings: { components: { qwen3_encoder: 'qwen3-4b-gguf' } } }+ : entry.key === 'qwen3-4b-gguf'+ ? { ...entry, ...(flagged ? { is_missing: true } : {}) }+ : entry+ );+ const missing = models.find((entry) => entry.key === 'qwen3-4b-gguf')!;++ return missingFirst ? [missing, ...models.filter((entry) => entry !== missing)] : models;+ };++ expect(exportOne(zImage, withDefault(false)).components.qwen3EncoderModel).toBe('qwen3-4b-gguf');+ // Whichever comes first in the catalog, the required-slot fallback skips the missing encoder too.+ expect(exportOne(zImage, withDefault(true)).components.qwen3EncoderModel).toBe('qwen3-4b');+ expect(exportOne(zImage, withDefault(true, true)).components.qwen3EncoderModel).toBe('qwen3-4b');+ });+it('fills required components from the installed models and keeps explicit picks', () => {const zImage = { ...sdxlCase('z-image'), model_key: 'z-image-gguf' };@@ -149,6 +170,51 @@ describe('graph export', () => {});});+ it('rejects a Vision Tower beside a safetensors encoder whatever order the picks are listed in', () => {+ // The model's default components set a GGUF encoder and its tower; the case asks for a safetensors encoder.+ const krea2Models = [+ ...MODELS,+ model('k2-gguf', 'krea-2', 'main', {+ default_settings: { components: { qwen3_vl_encoder: 'k2-encoder-gguf', qwen3_vl_vision_tower: 'k2-mmproj' } },+ format: 'gguf_quantized',+ variant: 'krea2_base',+ }),+ model('k2-encoder-gguf', 'any', 'qwen3_vl_encoder', { format: 'gguf_quantized', variant: 'qwen3_vl_4b' }),+ model('k2-encoder-st', 'any', 'qwen3_vl_encoder', { format: 'checkpoint', variant: 'qwen3_vl_4b' }),+ model('k2-mmproj', 'any', 'qwen3_vl_vision_tower', { format: 'gguf_quantized', variant: 'qwen3_vl_4b' }),+ model('k2-vae', 'qwen-image', 'vae', { format: 'checkpoint' }),+ ];+ const exportWith = (components: Record<string, string>) =>+ exportGraphs(request([sdxlCase('k2', { components, model_key: 'k2-gguf' })], krea2Models)).cases[0];+ const encoderFirst = { qwen3VLEncoderModel: 'k2-encoder-st', qwen3VLVisionTowerModel: 'k2-mmproj', vae: 'k2-vae' };+ const towerFirst = { qwen3VLVisionTowerModel: 'k2-mmproj', qwen3VLEncoderModel: 'k2-encoder-st', vae: 'k2-vae' };++ expect(errorOf(exportWith(encoderFirst))).toMatch(/Unknown component slot .{1,4}qwen3VLVisionTowerModel/);+ expect(errorOf(exportWith(towerFirst))).toMatch(/Unknown component slot .{1,4}qwen3VLVisionTowerModel/);+ });++ it('drops an inherited Vision Tower whose slot an encoder override closes', () => {+ const krea2Models = [+ ...MODELS,+ model('k2-gguf', 'krea-2', 'main', {+ default_settings: { components: { qwen3_vl_encoder: 'k2-encoder-gguf', qwen3_vl_vision_tower: 'k2-mmproj' } },+ format: 'gguf_quantized',+ variant: 'krea2_base',+ }),+ model('k2-encoder-gguf', 'any', 'qwen3_vl_encoder', { format: 'gguf_quantized', variant: 'qwen3_vl_4b' }),+ model('k2-encoder-st', 'any', 'qwen3_vl_encoder', { format: 'checkpoint', variant: 'qwen3_vl_4b' }),+ model('k2-mmproj', 'any', 'qwen3_vl_vision_tower', { format: 'gguf_quantized', variant: 'qwen3_vl_4b' }),+ model('k2-vae', 'qwen-image', 'vae', { format: 'checkpoint' }),+ ];+ const { batch, components } = exportOne(+ sdxlCase('k2', { components: { qwen3VLEncoderModel: 'k2-encoder-st', vae: 'k2-vae' }, model_key: 'k2-gguf' }),+ krea2Models+ );++ expect(components).toEqual({ qwen3VLEncoderModel: 'k2-encoder-st', vae: 'k2-vae' });+ expect(batch.graph.nodes.model_loader?.qwen3_vl_vision_tower_model).toBeUndefined();+ });+it.each(generateGraphCases)('compiles $label from exactly the components it needs', ({ base, shape }) => {const {filled,@@ -193,6 +259,22 @@ describe('graph export', () => {expect(response.cases.find((result) => result.id === 'ok')).toHaveProperty('batch');});+ it('refuses a case that names a model whose files are gone like one that is not installed', () => {+ const models = MODELS.map((entry) =>+ entry.key === 'sdxl' || entry.key === 'sdxl-lora' ? { ...entry, is_missing: true } : entry+ );+ const [mainGone] = exportGraphs(request([sdxlCase('main-gone')], models)).cases;+ const [loraGone] = exportGraphs(+ request(+ [sdxlCase('lora-gone', { loras: [{ key: 'sdxl-lora', weight: 1 }] })],+ MODELS.map((entry) => (entry.key === 'sdxl-lora' ? { ...entry, is_missing: true } : entry))+ )+ ).cases;++ expect(errorOf(mainGone!)).toBe('model_key "sdxl" is not a selectable main model. Choices: z-image-gguf.');+ expect(errorOf(loraGone!)).toContain('"sdxl-lora" is not an installed LoRA');+ });+it('exports identical requests identically, with stable node ids', () => {const cases = [sdxlCase('t2i', { loras: [{ key: 'sdxl-lora', weight: 1 }], reference_images: ['reference.png'] }),diff --git a/invokeai/frontend/webv2/src/app/modelDefaultsRulesReader.test.ts b/invokeai/frontend/webv2/src/app/modelDefaultsRulesReader.test.tsnew file mode 100644index 0000000000..2aa39747b3--- /dev/null+++ b/invokeai/frontend/webv2/src/app/modelDefaultsRulesReader.test.ts@@ -0,0 +1,69 @@+import type { ModelDefaultsRulesState } from '@features/models';++import { seedArchitectureCapabilities } from '@features/models/core/architectureCapabilities.testing';+import { describe, expect, it, vi } from 'vitest';++import { startModelDefaultsRulesReader } from './modelDefaultsRulesReader';++// The served table is seeded directly; the store that fetches it is the one thing stood in for.+vi.mock('@features/models/architecturesStore', () => ({+ ensureArchitectureCapabilitiesLoaded: () => Promise.resolve(),+ getArchitectureCapabilitiesSnapshot: () => ({ revision: 1, status: 'loaded' }),+ subscribeArchitectureCapabilities: () => () => undefined,+}));++seedArchitectureCapabilities();++const vae = (base: string, latent_channels = 32) => ({+ base,+ key: `${base}-vae`,+ latent_channels,+ name: base,+ type: 'vae',+});+const model = (base: string) => ({ base, format: 'checkpoint', key: base, name: base }) as never;++const readReadyState = (): Extract<ModelDefaultsRulesState, { status: 'ready' }> => {+ const published: ModelDefaultsRulesState[] = [];++ startModelDefaultsRulesReader((next) => published.push(next));+ const state = published.at(-1);++ if (state?.status !== 'ready') {+ throw new Error('the rules did not become ready');+ }++ return state;+};++describe('whether Generate loads a default VAE', () => {+ it('is no for a self-contained FLUX.1 SDNQ pipeline, whose own VAE always decodes, and yes for other models', () => {+ const { usesDefaultVae } = readReadyState();+ const pipeline = { text_encoder: {}, text_encoder_2: {}, tokenizer: {}, tokenizer_2: {}, transformer: {}, vae: {} };++ expect(+ usesDefaultVae({+ base: 'flux',+ format: 'sdnq_quantized',+ key: 'flux',+ name: 'flux',+ submodels: pipeline,+ } as never)+ ).toBe(false);+ expect(usesDefaultVae(model('flux'))).toBe(true);+ expect(usesDefaultVae(model('sdxl'))).toBe(true);+ });+});++describe('the default VAE rule the Model Manager reads', () => {+ it("follows the served architecture rows, so a model takes the other base's VAE its row accepts", () => {+ const { acceptsDefaultVae } = readReadyState();++ // MOSS-Image decodes with the FLUX.2 VAE; SDXL's is not among its accepted ones.+ expect(acceptsDefaultVae(model('moss-image'), vae('flux2') as never)).toBe(true);+ expect(acceptsDefaultVae(model('moss-image'), vae('sdxl', 4) as never)).toBe(false);+ // A row that declares no VAE facet accepts its own base only.+ expect(acceptsDefaultVae(model('sdxl'), vae('sdxl', 4) as never)).toBe(true);+ expect(acceptsDefaultVae(model('sdxl'), vae('flux2') as never)).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/app/modelSchedulerPolicyReader.ts b/invokeai/frontend/webv2/src/app/modelDefaultsRulesReader.tssimilarity index 51%rename from invokeai/frontend/webv2/src/app/modelSchedulerPolicyReader.tsrename to invokeai/frontend/webv2/src/app/modelDefaultsRulesReader.tsindex f076c01347..d81e0c8517 100644--- a/invokeai/frontend/webv2/src/app/modelSchedulerPolicyReader.ts+++ b/invokeai/frontend/webv2/src/app/modelDefaultsRulesReader.ts@@ -1,7 +1,20 @@-import type { SchedulerPolicyReader, SchedulerPolicyState } from '@features/models';+import type {+ DefaultComponentPruner,+ DefaultComponentSlotReader,+ ModelDefaultsRulesState,+ SchedulerPolicyReader,+} from '@features/models';import type { ArchitectureCapabilitiesSnapshot } from '@features/models/architecturesStore';-import { getDefaultGenerateSettings, getGenerationUiPolicy, getSchedulerOptions } from '@features/generation/settings';+import {+ getDefaultComponentSlotPolicies,+ getDefaultGenerateSettings,+ getGenerationUiPolicy,+ getSchedulerOptions,+ isDefaultVaeLoaded,+ isVaeCompatibleWithGenerateModel,+ pruneClosedDefaultComponents,+} from '@features/generation/settings';import {ensureArchitectureCapabilitiesLoaded,getArchitectureCapabilitiesSnapshot,@@ -21,9 +34,30 @@ const readSchedulerPolicy: SchedulerPolicyReader = (model, currentValue) => {};};-const toPolicyState = (snapshot: ArchitectureCapabilitiesSnapshot): SchedulerPolicyState => {+const readDefaultComponentSlots: DefaultComponentSlotReader = (model, components, catalog) =>+ getDefaultComponentSlotPolicies(+ { ...model, default_settings: { components }, type: 'main' } as GenerateMainModel,+ catalog+ );++const readPrunedDefaultComponents: DefaultComponentPruner = (model, components, catalog) =>+ pruneClosedDefaultComponents(+ { ...model, default_settings: { components }, type: 'main' } as GenerateMainModel,+ catalog+ );++const toPolicyState = (snapshot: ArchitectureCapabilitiesSnapshot): ModelDefaultsRulesState => {if (snapshot.status === 'loaded' && snapshot.revision > 0) {- return { read: (model, currentValue) => readSchedulerPolicy(model, currentValue), status: 'ready' };+ return {+ acceptsDefaultVae: (model, candidate) =>+ isVaeCompatibleWithGenerateModel({ ...model, type: 'main' } as GenerateMainModel, candidate as never),+ usesDefaultVae: (model) =>+ isDefaultVaeLoaded({ ...model, default_settings: null, type: 'main' } as GenerateMainModel),+ pruneComponents: (model, components, catalog) => readPrunedDefaultComponents(model, components, catalog),+ read: (model, currentValue) => readSchedulerPolicy(model, currentValue),+ readComponentSlots: (model, components, catalog) => readDefaultComponentSlots(model, components, catalog),+ status: 'ready',+ };}return snapshot.status === 'error' ? { status: 'unavailable' } : { status: 'loading' };};@@ -32,7 +66,7 @@ const toPolicyState = (snapshot: ArchitectureCapabilitiesSnapshot): SchedulerPol* Publishes the rules' state now and whenever the architecture table's status or revision changes, with a new reader* per revision so memoized callers recompute. Lives for the page, like the table's own store.*/-export const startSchedulerPolicyReader = (publish: (state: SchedulerPolicyState) => void): void => {+export const startModelDefaultsRulesReader = (publish: (state: ModelDefaultsRulesState) => void): void => {let published: Pick<ArchitectureCapabilitiesSnapshot, 'revision' | 'status'> | null = null;const sync = () => {const snapshot = getArchitectureCapabilitiesSnapshot();@@ -47,4 +81,4 @@ export const startSchedulerPolicyReader = (publish: (state: SchedulerPolicyState};/** Joins or starts the table's load; it never rejects (see `ensureArchitectureCapabilitiesLoaded`). */-export const ensureSchedulerRulesLoaded = (): Promise<void> => ensureArchitectureCapabilitiesLoaded();+export const ensureDefaultsRulesLoaded = (): Promise<void> => ensureArchitectureCapabilitiesLoaded();diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsxindex 0cd0da42a9..8b642377d5 100644--- a/invokeai/frontend/webv2/src/app/router.tsx+++ b/invokeai/frontend/webv2/src/app/router.tsx@@ -21,8 +21,8 @@ import {ModelsUiProvider,type CalibrationGraphCompiler,type ModelsUiAdapter,- type SchedulerPolicySource,- type SchedulerPolicyState,+ type ModelDefaultsRulesSource,+ type ModelDefaultsRulesState,} from '@features/models';import { createLogger } from '@platform/logging/logger';import { captureAccountScope } from '@platform/state/accountLifecycle';@@ -60,7 +60,7 @@ import i18next from 'i18next';import { Fragment, useCallback, useMemo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import type * as SchedulerRules from './modelSchedulerPolicyReader';+import type * as DefaultsRulesModule from './modelDefaultsRulesReader';import { RouterErrorScreen } from './RouterErrorScreen';import { SocketHubRuntime } from './SocketHubRuntime';@@ -86,40 +86,40 @@ const RouterError = ({ error, reset }: ErrorComponentProps) => {const rootRoute = createRootRoute({ component: Outlet, errorComponent: RouterError });-const SCHEDULER_RULES_LOADING: SchedulerPolicyState = { status: 'loading' };-const SCHEDULER_RULES_UNAVAILABLE: SchedulerPolicyState = { status: 'unavailable' };-let schedulerPolicyState: SchedulerPolicyState = SCHEDULER_RULES_LOADING;-let schedulerRules: Promise<typeof SchedulerRules> | null = null;-const schedulerPolicyChannel = createListenerChannel();+const DEFAULTS_RULES_LOADING: ModelDefaultsRulesState = { status: 'loading' };+const DEFAULTS_RULES_UNAVAILABLE: ModelDefaultsRulesState = { status: 'unavailable' };+let defaultsRulesState: ModelDefaultsRulesState = DEFAULTS_RULES_LOADING;+let defaultsRulesModule: Promise<typeof DefaultsRulesModule> | null = null;+const defaultsRulesChannel = createListenerChannel();-const publishSchedulerPolicy = (next: SchedulerPolicyState): void => {- schedulerPolicyState = next;- schedulerPolicyChannel.notify();+const publishDefaultsRules = (next: ModelDefaultsRulesState): void => {+ defaultsRulesState = next;+ defaultsRulesChannel.notify();};-/** Generation's rules and Models' architecture table arrive with the first Default settings section, not at startup. */-const schedulerPolicySource: SchedulerPolicySource = {- getSnapshot: () => schedulerPolicyState,+/** The defaults rules and Models' architecture table arrive with the first Default settings section, not at startup. */+const defaultsRulesSource: ModelDefaultsRulesSource = {+ getSnapshot: () => defaultsRulesState,load: () => {- if (!schedulerRules) {- if (schedulerPolicyState.status === 'unavailable') {- publishSchedulerPolicy(SCHEDULER_RULES_LOADING);+ if (!defaultsRulesModule) {+ if (defaultsRulesState.status === 'unavailable') {+ publishDefaultsRules(DEFAULTS_RULES_LOADING);}- schedulerRules = import('./modelSchedulerPolicyReader').then((rules) => {- rules.startSchedulerPolicyReader(publishSchedulerPolicy);+ defaultsRulesModule = import('./modelDefaultsRulesReader').then((rules) => {+ rules.startModelDefaultsRulesReader(publishDefaultsRules);return rules;});}// Asked on every load: it retries a failed table, and an account change clears the table.- schedulerRules- .then((rules) => rules.ensureSchedulerRulesLoaded())+ defaultsRulesModule+ .then((rules) => rules.ensureDefaultsRulesLoaded()).catch(() => {// The rules' chunk failed to load; the next load (Retry, or another section) imports it again.- schedulerRules = null;- publishSchedulerPolicy(SCHEDULER_RULES_UNAVAILABLE);+ defaultsRulesModule = null;+ publishDefaultsRules(DEFAULTS_RULES_UNAVAILABLE);});},- subscribe: schedulerPolicyChannel.subscribe,+ subscribe: defaultsRulesChannel.subscribe,};const setInstallInPlace = (installInPlace: boolean) => void patchWorkbenchPreferences({ installInPlace });@@ -141,7 +141,7 @@ export const AccountModelsUiProvider = ({ children }: { children: ReactNode }) =installInPlace,isProjectActive: NO_ACTIVE_PROJECT,managerProjectId: null,- schedulerPolicy: schedulerPolicySource,+ defaultsRules: defaultsRulesSource,setInstallInPlace,}),[canManageModels, enableModelDescriptions, galleryValues, installInPlace]diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex 73511515a7..cf0176143d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -20,9 +20,12 @@ import type {import {addReferenceImages,+ getAutoFlux2ComponentSourceModel,+ pickFallbackGenerateModel,coerceSchedulerForGraph,getComponentPolicyContext,getComponentSectionPolicy,+ getDefaultComponentSlotPolicies,getDefaultGenerateSettings,getGenerateModelSelectionResult,getGenerationDimensions,@@ -31,6 +34,9 @@ import {getGenerationValidationIssues,getGenerationValidationReasons,getCompatibleReferenceImages,+ getModelDefaultComponents,+ getModelDefaultFills,+ pruneClosedDefaultComponents,getReferenceImageRoom,getReferenceImageUnavailableReason,getPromptPolicy,@@ -271,6 +277,16 @@ describe('architecture policy, read from the backend capability table', () => {expect(isGenerateModelSelectable(createModel('ideogram-4', { format: 'diffusers' }))).toBe(true);expect(isGenerateModelSelectable(createModel('wan', { variant: 'a14b' }))).toBe(true);});++ it('starts on a selectable main model whose files are present, never on a standalone branch', () => {+ const gone = { ...createModel('sdxl', { key: 'gone' }), is_missing: true } as MainModelConfig;+ const sdxl = createModel('sdxl', { key: 'sdxl-ok' });++ expect(pickFallbackGenerateModel([gone, unconditional, sdxl])).toBe(sdxl);+ // All unusable by file: the first selectable one, not the branch.+ expect(pickFallbackGenerateModel([unconditional, gone])).toBe(gone);+ expect(pickFallbackGenerateModel([unconditional])).toBeUndefined();+ });});});@@ -352,6 +368,26 @@ describe('component policies', () => {).toEqual([]);});+ it('picks no FLUX.2 component source whose files are missing, whatever the catalog order', () => {+ const klein = createModel('flux2', { format: 'checkpoint', key: 'klein-single', variant: 'klein_9b' });+ const pipeline = (key: string, missing: boolean) => ({+ ...createModel('flux2', { format: 'diffusers', key, name: key, variant: 'klein_9b' }),+ ...(missing ? { is_missing: true } : {}),+ });+ const gone = pipeline('pipeline-gone', true);+ const working = pipeline('pipeline-ok', false);+ const pick = (models: unknown[]) =>+ getAutoFlux2ComponentSourceModel(+ klein,+ { mistralEncoderModel: null, qwen3EncoderModel: null, vae: null },+ models as never+ );++ expect(pick([gone, working])?.key).toBe('pipeline-ok');+ expect(pick([working, gone])?.key).toBe('pipeline-ok');+ expect(pick([gone])).toBeNull();+ });+describe('FLUX.2 [dev] component sources', () => {const model = createModel('flux2', { format: 'gguf_quantized', variant: 'dev' });const completePipeline = { text_encoder: {}, tokenizer: {}, transformer: {}, vae: {} };@@ -1363,6 +1399,15 @@ describe('Anima IP-Adapter references', () => {isEnabled: true,});+ it('retargets an adapter-less reference only when a present IP-Adapter could take it', () => {+ const empty = { ...animaReference('ref-1'), config: { ...animaReference('ref-1').config, model: null } };+ const missing = { ...animaIpAdapter, is_missing: true } as ComponentModelConfig;+ const referenceImages = [empty];++ expect(getCompatibleReferenceImages(referenceImages, animaQwen3, [missing])).toBe(referenceImages);+ expect(getCompatibleReferenceImages(referenceImages, animaQwen3, [animaIpAdapter])).not.toBe(referenceImages);+ });+it('accepts four references sharing one Anima IP-Adapter and rejects a fifth', () => {const reasons = (count: number) =>getGenerationValidationReasons(@@ -1627,3 +1672,494 @@ describe('isModelFromRepo', () => {expect(isModelFromRepo(null, REPO)).toBe(false);});});++describe("a main model's default components", () => {+ const withDefaults = (base: string, components: Record<string, string>, overrides: Partial<MainModelConfig> = {}) =>+ createModel(base, {+ default_settings: { components },+ format: 'checkpoint',+ key: `${base}-with-defaults`,+ ...overrides,+ });+ const switchTo = (model: GenerateModelConfig, models: unknown[], currentValues?: GenerateSettings) =>+ getGenerateModelSelectionResult({+ currentValues: currentValues ?? createSettings(createModel('sd-1')),+ model,+ models: models as ComponentModelConfig[],+ });+ const otherT5: ComponentModelConfig = { base: 'any', key: 't5-other', name: 'Other T5', type: 't5_encoder' };++ it('fills the empty slots on a switch without counting them as a loss', () => {+ const model = withDefaults('flux', { clip_embed_model: clipEmbed.key, t5_encoder: t5Encoder.key });+ const result = switchTo(model, [t5Encoder, clipEmbed]);++ expect(result.settings.t5EncoderModel).toBe(t5Encoder);+ expect(result.settings.clipEmbedModel).toBe(clipEmbed);+ expect(result.changes).toEqual([]);+ expect(isLossyModelSwitch(result)).toBe(false);+ });++ it('offers a Text LLM that serves as the encoder through a role in the Model Manager', () => {+ const model = createModel('z-image', { format: 'checkpoint' });+ const llm = {+ base: 'any',+ format: 'checkpoint',+ key: 'qwen3-llm',+ name: 'Qwen3 4B',+ roles: [{ type: 'qwen3_encoder', variant: 'qwen3_4b' }],+ type: 'text_llm',+ } as unknown as ComponentModelConfig;+ const slot = getDefaultComponentSlotPolicies(model, [llm]).find(+ (candidate) => candidate.persistenceKey === 'qwen3_encoder'+ );++ expect(slot?.filter(llm)).toBe(true);+ });++ it('takes no default whose files are missing on a switch, and replaces a pick that went missing', () => {+ const model = withDefaults('flux', { t5_encoder: t5Encoder.key });+ const missingT5 = { ...t5Encoder, is_missing: true };+ const picked = createSettings(createModel('sd-1'), { t5EncoderModel: otherT5 });++ expect(switchTo(model, [missingT5]).settings.t5EncoderModel).toBeNull();+ expect(switchTo(model, [missingT5, otherT5], picked).settings.t5EncoderModel).toBe(otherT5);+ expect(switchTo(model, [t5Encoder, { ...otherT5, is_missing: true }], picked).settings.t5EncoderModel).toBe(+ t5Encoder+ );+ });++ it('keeps a selection that already fits the new model', () => {+ const model = withDefaults('flux', { t5_encoder: t5Encoder.key });+ const current = createSettings(createModel('flux', { key: 'flux-other' }), { t5EncoderModel: otherT5 });++ expect(switchTo(model, [t5Encoder, otherT5], current).settings.t5EncoderModel).toBe(otherT5);+ });++ it('fills a slot the switch cleared as incompatible, and still reports the loss', () => {+ const model = withDefaults('flux', { t5_encoder: t5Encoder.key });+ // A Qwen VL encoder fits no FLUX slot, so a stale one is cleared; the T5 default is not what it held.+ const current = createSettings(createModel('qwen-image', { format: 'diffusers' }), {+ qwenVLEncoderModel: qwenVlEncoder,+ });+ const result = switchTo(model, [t5Encoder, qwenVlEncoder], current);++ expect(result.settings.qwenVLEncoderModel).toBeNull();+ expect(result.settings.t5EncoderModel).toBe(t5Encoder);+ expect(isLossyModelSwitch(result)).toBe(true);+ });++ it('skips unknown slot names, models that are not installed and models the slot rejects', () => {+ const model = withDefaults('flux', {+ clip_embed_model: t5Encoder.key,+ not_a_slot: clipEmbed.key,+ t5_encoder: 'uninstalled',+ });+ const { settings } = switchTo(model, [t5Encoder, clipEmbed]);++ expect(settings.t5EncoderModel).toBeNull();+ expect(settings.clipEmbedModel).toBeNull();+ });++ it('changes nothing when the model is selected again', () => {+ const model = withDefaults('flux', { t5_encoder: t5Encoder.key });+ const current = createSettings(model);++ expect(switchTo(model, [t5Encoder], current).settings.t5EncoderModel).toBeNull();+ });++ it('skips the FLUX.2 component source, which the family offers no slot for and picks automatically', () => {+ const source = createModel('flux2', { format: 'diffusers', key: 'klein-a', variant: 'klein_9b' });+ const model = createModel('flux2', {+ default_settings: { components: { component_source: source.key } },+ format: 'gguf_quantized',+ key: 'klein-default',+ variant: 'klein_9b',+ });++ expect(getModelDefaultComponents(model, createSettings(model), [source] as ComponentModelConfig[])).toEqual({});+ });++ it('opens a dependent slot once the slot it hangs on is filled, whatever order they are stored in', () => {+ const encoder = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'qwen3-vl-8b-gguf',+ name: 'Qwen3-VL 8B',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ };+ const tower = { ...encoder, key: 'mmproj', name: 'mmproj', type: 'qwen3_vl_vision_tower' };+ const model = withDefaults('qwen-image-2-1', { qwen3_vl_vision_tower: tower.key, qwen3_vl_encoder: encoder.key });+ const current = createSettings(model);++ expect(getModelDefaultComponents(model, current, [tower, encoder] as ComponentModelConfig[])).toEqual({+ qwen3VLEncoderModel: encoder,+ qwen3VLVisionTowerModel: tower,+ });+ // Without the encoder default the tower has no slot to fill.+ expect(+ getModelDefaultComponents(withDefaults('qwen-image-2-1', { qwen3_vl_vision_tower: tower.key }), current, [+ tower,+ ] as ComponentModelConfig[])+ ).toEqual({});+ // The component list the Model Manager offers follows the same rule.+ const offered = (components: Record<string, string>) =>+ getDefaultComponentSlotPolicies(withDefaults('qwen-image-2-1', components), [+ encoder,+ tower,+ ] as ComponentModelConfig[]).map((slot) => slot.persistenceKey);++ expect(offered({})).not.toContain('qwen3_vl_vision_tower');+ expect(offered({ qwen3_vl_encoder: encoder.key })).toContain('qwen3_vl_vision_tower');+ });++ it('does not keep a selection that is no longer installed over the default of the new model', () => {+ const model = withDefaults('flux', { t5_encoder: t5Encoder.key });+ const removed = createSettings(createModel('flux', { key: 'flux-other' }), { t5EncoderModel: otherT5 });++ expect(switchTo(model, [t5Encoder], removed).settings.t5EncoderModel).toBe(t5Encoder);+ });++ it('clears a vision tower whose slot a reset to the default encoder closes', () => {+ const gguf = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'encoder-gguf',+ name: 'GGUF encoder',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ };+ const checkpoint = { ...gguf, format: 'checkpoint', key: 'encoder-st', name: 'Checkpoint encoder' };+ const tower = { ...gguf, key: 'mmproj', name: 'mmproj', type: 'qwen3_vl_vision_tower' };+ const model = withDefaults('qwen-image-2-1', { qwen3_vl_encoder: checkpoint.key });+ const current = createSettings(model, {+ qwen3VLEncoderModel: gguf as ComponentModelConfig,+ qwen3VLVisionTowerModel: tower as ComponentModelConfig,+ });+ const models = [gguf, checkpoint, tower] as ComponentModelConfig[];++ expect(getModelDefaultComponents(model, current, models, { replace: true })).toEqual({+ qwen3VLEncoderModel: checkpoint,+ qwen3VLVisionTowerModel: null,+ });+ // A fitting selection that stays closes nothing.+ expect(getModelDefaultComponents(model, current, models)).toEqual({});+ });++ it('offers and fills no encoder default for a self-contained FLUX.1 SDNQ pipeline, whose graph loads its own', () => {+ const pipeline = { text_encoder: {}, text_encoder_2: {}, tokenizer: {}, tokenizer_2: {}, transformer: {}, vae: {} };+ const components = { clip_embed_model: clipEmbed.key, t5_encoder: t5Encoder.key };+ const sdnq = withDefaults('flux', components, { format: 'sdnq_quantized', submodels: pipeline } as never);+ const standalone = withDefaults('flux', components);+ const installed = [t5Encoder, clipEmbed] as ComponentModelConfig[];+ const offered = (model: GenerateModelConfig) =>+ getDefaultComponentSlotPolicies(model, installed).map((slot) => slot.persistenceKey);++ expect(offered(standalone)).toEqual(expect.arrayContaining(['t5_encoder', 'clip_embed_model']));+ expect(offered(sdnq)).not.toContain('t5_encoder');+ expect(offered(sdnq)).not.toContain('clip_embed_model');+ expect(getModelDefaultComponents(sdnq, createSettings(sdnq), installed)).toEqual({});+ });++ it.each([+ ['ideogram-4', 'ideogram4_unconditional_model'],+ ['wan', 'component_source'],+ ['qwen-image', 'component_source'],+ ])('offers and fills no %s default for the %s a Diffusers pipeline never loads', (base, persistenceKey) => {+ const main = (key: string, format: string) =>+ ({+ base,+ format,+ key,+ name: key,+ type: 'main',+ ...(base === 'wan' ? { variant: 't2v_a14b' } : {}),+ }) as MainModelConfig;+ const other = main('other', 'diffusers');+ const installed = [other] as ComponentModelConfig[];+ const offered = (model: GenerateModelConfig) =>+ getDefaultComponentSlotPolicies(model, installed).map((slot) => slot.persistenceKey);+ const diffusers = {+ ...main('pipeline', 'diffusers'),+ default_settings: { components: { [persistenceKey]: 'other' } },+ };+ const singleFile = { ...main('single-file', 'gguf_quantized'), default_settings: diffusers.default_settings };++ expect(offered(singleFile)).toContain(persistenceKey);+ expect(offered(diffusers)).not.toContain(persistenceKey);+ expect(getModelDefaultComponents(diffusers, createSettings(diffusers), installed)).toEqual({});+ });++ it('prunes a stored vision tower once the encoder it hangs on is gone, or no longer opens it', () => {+ const gguf = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'encoder-gguf',+ name: 'GGUF encoder',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ };+ const checkpoint = { ...gguf, format: 'checkpoint', key: 'encoder-st', name: 'Checkpoint encoder' };+ const tower = { ...gguf, key: 'mmproj', name: 'mmproj', type: 'qwen3_vl_vision_tower' };+ const installed = [gguf, checkpoint, tower] as ComponentModelConfig[];+ const prune = (components: Record<string, string>) =>+ pruneClosedDefaultComponents(withDefaults('qwen-image-2-1', components), installed);++ expect(prune({ qwen3_vl_encoder: gguf.key, qwen3_vl_vision_tower: tower.key })).toEqual({+ qwen3_vl_encoder: gguf.key,+ qwen3_vl_vision_tower: tower.key,+ });+ // Cleared encoder; replaced by one with no tower slot.+ expect(prune({ qwen3_vl_vision_tower: tower.key })).toEqual({});+ expect(prune({ qwen3_vl_encoder: checkpoint.key, qwen3_vl_vision_tower: tower.key })).toEqual({+ qwen3_vl_encoder: checkpoint.key,+ });+ // An encoder that is no longer installed is the user's to see and clear first; keys of unknown slots stay.+ expect(prune({ qwen3_vl_encoder: 'deleted', qwen3_vl_vision_tower: tower.key, unknown_slot: 'x' })).toEqual({+ qwen3_vl_encoder: 'deleted',+ qwen3_vl_vision_tower: tower.key,+ unknown_slot: 'x',+ });+ });++ describe('dependent slots are judged against the final settings', () => {+ const gguf = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'encoder-gguf',+ name: 'GGUF encoder',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ };+ const checkpoint = { ...gguf, format: 'checkpoint', key: 'encoder-st', name: 'Checkpoint encoder' };+ const tower = { ...gguf, key: 'mmproj', name: 'mmproj', type: 'qwen3_vl_vision_tower' };+ const installed = [gguf, checkpoint, tower] as ComponentModelConfig[];++ it.each([+ ['tower before encoder', { qwen3_vl_vision_tower: tower.key, qwen3_vl_encoder: checkpoint.key }],+ ['encoder before tower', { qwen3_vl_encoder: checkpoint.key, qwen3_vl_vision_tower: tower.key }],+ ])('leaves no hidden tower whatever the stored order (%s)', (_name, components) => {+ const model = withDefaults('qwen-image-2-1', components);+ const current = createSettings(model, {+ qwen3VLEncoderModel: gguf as ComponentModelConfig,+ qwen3VLVisionTowerModel: tower as ComponentModelConfig,+ });++ expect(getModelDefaultComponents(model, current, installed, { replace: true })).toEqual({+ qwen3VLEncoderModel: checkpoint,+ qwen3VLVisionTowerModel: null,+ });+ });+ });++ describe('the Wan low-noise expert', () => {+ const wan = (key: string, extra: Record<string, unknown> = {}) =>+ createModel('wan', { format: 'gguf_quantized', key, name: key, variant: 't2v_a14b', ...extra } as never);+ const high = wan('high');+ const low = wan('low');+ const offered = (model: GenerateModelConfig, models: unknown[]) =>+ getDefaultComponentSlotPolicies(model, models as ComponentModelConfig[]).find(+ (slot) => slot.persistenceKey === 'wan_transformer_low_noise'+ );++ it('accepts only a different single-file expert of the same variant for a single-file A14B model', () => {+ const slot = offered(high, [high, low])!;++ expect(slot.filter(low as never)).toBe(true);+ expect(slot.filter(wan('low-st', { format: 'checkpoint' }) as never)).toBe(true);+ expect(slot.filter(high as never)).toBe(false);+ expect(slot.filter(wan('pipeline', { format: 'diffusers' }) as never)).toBe(false);+ expect(slot.filter(wan('other-variant', { variant: 'i2v_a14b' }) as never)).toBe(false);+ });++ it("refuses two experts the loader's tags name for the same role, and accepts untagged ones", () => {+ const tagged = (key: string, expert: string) => wan(key, { expert });+ const slotOf = (main: GenerateModelConfig) => offered(main, [main])!;++ expect(slotOf(tagged('high-a', 'high')).filter(tagged('high-b', 'high') as never)).toBe(false);+ expect(slotOf(tagged('low-a', 'low')).filter(tagged('low-b', 'low') as never)).toBe(false);+ expect(slotOf(tagged('high-a', 'high')).filter(tagged('low-b', 'low') as never)).toBe(true);+ expect(slotOf(tagged('none-a', 'none')).filter(tagged('none-b', 'none') as never)).toBe(true);+ expect(slotOf(tagged('high-a', 'high')).filter(wan('untagged') as never)).toBe(true);+ });++ it('reports a saved expert the loader would reject, which the picker no longer lists', () => {+ const pipeline = wan('pipeline', { format: 'diffusers' });+ const reasons = (expert: unknown) =>+ getGenerationValidationReasons(+ high,+ createSettings(high, { componentSourceModel: pipeline, wanLowNoiseModel: expert as never })+ );++ expect(reasons(null)).toEqual([]);+ expect(reasons(low)).toEqual([]);+ expect(reasons(pipeline)).toEqual([+ 'The selected low-noise expert is not a different single-file model of this variant. Select one or clear it.',+ ]);+ });++ it('lets a Diffusers component source supply the VAE only when its VAE width fits the model', () => {+ const a14bPipeline = wan('a14b-pipeline', { format: 'diffusers' });+ const smallPipeline = wan('small-pipeline', { format: 'diffusers', variant: 'ti2v_5b' });+ const wanVae = {+ base: 'wan',+ key: 'wan-vae-16',+ latent_channels: 16,+ name: 'Wan VAE',+ type: 'vae',+ } as VaeModelConfig;+ const reasons = (source: unknown, vae: VaeModelConfig | null = null) =>+ getGenerationValidationReasons(+ high,+ createSettings(high, { componentSourceModel: source as never, vae, wanT5EncoderModel: null })+ );++ expect(reasons(a14bPipeline)).toEqual([]);+ // The source still supplies the text encoder beside a VAE that fits.+ expect(reasons(smallPipeline, wanVae)).toEqual([]);+ expect(reasons(smallPipeline)).toEqual([+ 'Generate needs a VAE for Wan models: a component source supplies one only when it is the same variant family.',+ ]);+ });++ it('is no default of a Diffusers or TI2V-5B model, whose loader ignores or reads the pair itself', () => {+ expect(offered(wan('pipeline', { format: 'diffusers' }), [low])).toBeUndefined();+ expect(offered(wan('small', { variant: 'ti2v_5b' }), [low])).toBeUndefined();+ });++ it('offers no slot to a model whose loader never reads it, and a switch clears a stale pick', () => {+ const pipeline = wan('pipeline', { format: 'diffusers' });+ const slotKeys = (model: GenerateModelConfig) =>+ getComponentSectionPolicy(model, createSettings(model)).slots.map((candidate) => candidate.key);++ expect(slotKeys(high)).toContain('wanLowNoiseModel');+ expect(slotKeys(pipeline)).not.toContain('wanLowNoiseModel');+ expect(slotKeys(wan('small', { variant: 'ti2v_5b' }))).not.toContain('wanLowNoiseModel');++ const current = createSettings(high, { wanLowNoiseModel: low });+ const result = getGenerateModelSelectionResult({+ currentValues: current,+ model: pipeline,+ models: [high, low, pipeline] as ComponentModelConfig[],+ });++ expect(result.settings.wanLowNoiseModel).toBeNull();+ });++ it('judges a kept expert by the catalog record, so a valid default replaces one reclassified since', () => {+ const model = withDefaults('wan', { wan_transformer_low_noise: low.key }, {+ format: 'gguf_quantized',+ key: high.key,+ variant: 't2v_a14b',+ } as never);+ // The project saved this pick while it was still a T2V expert; the catalog has since reclassified it.+ const old = wan('old');+ const reclassified = wan('old', { variant: 'i2v_a14b' });+ const saved = createSettings(model, { wanLowNoiseModel: old as never });++ expect(getModelDefaultComponents(model, saved, [model, low, reclassified] as never)).toEqual({+ wanLowNoiseModel: low,+ });+ // Still a T2V expert in the catalog: it stays.+ expect(getModelDefaultComponents(model, saved, [model, low, old] as never)).toEqual({});+ });++ it('skips a stored default the loader would reject', () => {+ const model = withDefaults('wan', { wan_transformer_low_noise: high.key }, {+ format: 'gguf_quantized',+ key: high.key,+ variant: 't2v_a14b',+ } as never);++ expect(getModelDefaultComponents(model, createSettings(model), [model, low] as never)).toEqual({});+ });+ });++ describe('the default VAE', () => {+ it('fills an empty VAE of a family with a VAE slot', () => {+ const model = createModel('flux', { default_settings: { vae: fluxVae.key }, format: 'checkpoint' });++ expect(switchTo(model, [fluxVae]).settings.vae).toBe(fluxVae);+ });++ it('fills the FLUX.2 VAE a single-file MOSS-Image takes as its default', () => {+ const model = createModel('moss-image', { default_settings: { vae: flux2Vae.key }, format: 'checkpoint' });++ expect(isComponentCompatibleWithModel(model, createSettings(model), 'vae', flux2Vae)).toBe(true);+ expect(switchTo(model, [flux2Vae]).settings.vae).toBe(flux2Vae);+ // SDXL's VAE is not among the ones MOSS-Image accepts.+ expect(+ switchTo(createModel('moss-image', { default_settings: { vae: sdxlVae.key }, format: 'checkpoint' }), [sdxlVae])+ .settings.vae+ ).toBeNull();+ });++ it('replaces a VAE of another family, as left behind by a fallback from an unsupported model', () => {+ const model = createModel('flux', { default_settings: { vae: fluxVae.key }, format: 'checkpoint' });+ const stale = createSettings(createModel('sdxl'), { vae: sdxlVae });++ expect(getModelDefaultFills(model, stale, [fluxVae, sdxlVae]).vae).toBe(fluxVae);+ });++ it('judges a kept VAE by the catalog record, so a default replaces one reclassified since', () => {+ const defaultVae: VaeModelConfig = { base: 'flux', key: 'flux-vae-default', name: 'FLUX VAE 2', type: 'vae' };+ const model = createModel('flux', { default_settings: { vae: defaultVae.key }, format: 'checkpoint' });+ // The project saved the pick as a FLUX VAE; the catalog now classifies the same key as SD3's.+ const saved = createSettings(model, { vae: fluxVae });+ const reclassified: VaeModelConfig = { ...fluxVae, base: 'sd-3' };++ expect(getModelDefaultFills(model, saved, [defaultVae, reclassified]).vae).toBe(defaultVae);+ expect(getModelDefaultFills(model, saved, [defaultVae, fluxVae]).vae).toBeUndefined();+ });++ it('fills no VAE for a self-contained FLUX.1 SDNQ pipeline, whose graph decodes with its own', () => {+ const pipeline = {+ text_encoder: {},+ text_encoder_2: {},+ tokenizer: {},+ tokenizer_2: {},+ transformer: {},+ vae: {},+ };+ const model = createModel('flux', {+ default_settings: { vae: fluxVae.key },+ format: 'sdnq_quantized',+ submodels: pipeline,+ } as never);++ expect(switchTo(model, [fluxVae]).settings.vae).toBeNull();+ });++ it('keeps an installed VAE that fits when the model defaults to the bundled one', () => {+ const model = createModel('sdxl', { default_settings: { vae: 'default' } });+ const chosen = createSettings(createModel('sdxl', { key: 'sdxl-other' }), { vae: sdxlVae });++ expect(switchTo(model, [sdxlVae], chosen).settings.vae).toBe(sdxlVae);+ });++ it('clears a VAE that is gone when the model defaults to the bundled one', () => {+ const model = createModel('sdxl', { default_settings: { vae: 'default' } });+ const gone = createSettings(createModel('sdxl', { key: 'sdxl-other' }), { vae: sdxlVae });++ expect(switchTo(model, [], gone).settings.vae).toBeNull();+ });++ it('fills the SD VAE picker, and leaves a VAE the user chose', () => {+ const model = createModel('sdxl', { default_settings: { vae: sdxlVae.key } });+ const chosen: VaeModelConfig = { ...sdxlVae, key: 'chosen', name: 'Chosen' };+ const current = createSettings(createModel('sdxl', { key: 'sdxl-other' }), { vae: chosen });++ expect(switchTo(model, [sdxlVae]).settings.vae).toBe(sdxlVae);+ expect(switchTo(model, [sdxlVae, chosen], current).settings.vae).toBe(chosen);+ });++ it('leaves the bundled VAE for the "default" sentinel, and skips a VAE of another base', () => {+ expect(+ switchTo(createModel('sdxl', { default_settings: { vae: 'default' } }), [sdxlVae]).settings.vae+ ).toBeNull();+ expect(+ switchTo(createModel('sdxl', { default_settings: { vae: fluxVae.key } }), [fluxVae]).settings.vae+ ).toBeNull();+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 1aedfddd5e..09180664a6 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -17,6 +17,7 @@ import { SEED_MAX } from '@platform/core/seed';import type {ExpandPromptSuggestion,+ ComponentModelConfig,ExternalGenerationMode,GenerateLora,GenerateModelConfig,@@ -53,13 +54,17 @@ import {isIdeogram4UnconditionalBranch,isMossImageQwen35Encoder,isQwen3Vl4bEncoder,+ doesWanSourceSupplyVae,+ hasWanLowNoiseSlot,isSelfContainedSDNQFlux1Pipeline,isVaeAcceptedByBase,+ isWanLowNoiseExpertFor,isVaeCompatibleWithGenerateModel,isZImageQwen3Encoder,servesAsType,type GenerateComponentFilter,} from './componentCompatibility';+import { DEFAULT_COMPONENT_SLOTS, type DefaultComponentSlot, getDefaultComponentSlot } from './componentDefaults';import { MAX_DIMENSION, MIN_DIMENSION } from './dimensionLimits';import { DEFAULT_DYNAMIC_PROMPTS_SETTINGS } from './dynamicPrompts';import {@@ -119,6 +124,9 @@ import {isGenerateSettings,isLoraCompatibleWithModel,isSameInstalledModel,+ isMainModelConfig,+ isModelIdentifierConfig,+ isVaeModelConfig,isValidKrea2RebalanceWeights,isValidMossImageSkipLayers,KREA2_REBALANCE_WEIGHT_COUNT,@@ -493,6 +501,19 @@ export const isSupportedGenerateModel = <T extends { base: string; type: stringexport const isGenerateModelSelectable = <T extends ModelConfig>(model: T): model is T & GenerateModelConfig =>isSupportedGenerateModel(model) && !isIdeogram4UnconditionalBranch(model);+/**+ * The model a fresh project starts on, or the Generate form falls back to when none is chosen: the first one Generate+ * can select as a main model (so no standalone Ideogram 4 branch) whose files are present, else the first. Where a+ * model is stored or chosen, that one stays.+ */+export const pickFallbackGenerateModel = <T extends ModelConfig>(+ models: readonly T[]+): (T & GenerateModelConfig) | undefined => {+ const selectable = models.filter(isGenerateModelSelectable);++ return selectable.find((model) => !model.is_missing) ?? selectable[0];+};+export const getPromptHistoryRecallPatch = ({item,models,@@ -689,6 +710,13 @@ export const resolveModelDefaultVae = (return { kind: 'none' };}+ // A graph that loads no VAE pick (a self-contained pipeline's own decodes) takes no default either.+ const vaeSlot = getComponentSectionPolicy(model, settings).slots.find((slotPolicy) => slotPolicy.key === 'vae');++ if (vaeSlot?.neverLoaded?.(getComponentPolicyContext(model, settings))) {+ return { kind: 'none' };+ }+const hasBundledVae = !isVaeComponentRequired(model, settings);if (key === '' || key === 'default') {@@ -696,7 +724,7 @@ export const resolveModelDefaultVae = (}const vae = vaeModels.find(- (candidate) => candidate.key === key && isVaeCompatibleWithGenerateModel(model, candidate)+ (candidate) => candidate.key === key && !candidate.is_missing && isVaeCompatibleWithGenerateModel(model, candidate));return vae ? { kind: 'apply', vae } : { kind: 'missing', hasBundledVae };@@ -759,6 +787,11 @@ export interface ComponentSlotPolicy {required?: (ctx: ComponentPolicyContext) => boolean;/** False while the slot's switch is off: nothing loads a kept selection, so an uninstalled one does not block. */inUse?: (ctx: ComponentPolicyContext) => boolean;+ /**+ * The model's graph loads no pick for the slot whatever the switches (a self-contained pipeline takes its bundled+ * components), so a default stored for it would do nothing and the Model Manager does not offer it.+ */+ neverLoaded?: (ctx: ComponentPolicyContext) => boolean;missingMessage?: string;/** Reported even when optional, so a saved unusable selection blocks Invoke by name instead of silently dropping. */incompatibleMessage?: string;@@ -980,7 +1013,11 @@ const wanLowNoiseSlot = (helpText: string): ComponentSlotPolicy =>modelTypes: TYPE_MAIN,valueKind: 'main',helpText,- filter: (candidate) => candidate.type === 'main' && candidate.base === 'wan',+ // The loader pairs a single-file A14B model with a different single-file expert of its variant.+ filter: (candidate, ctx) =>+ ctx.model.type !== 'external_image_generator' && isWanLowNoiseExpertFor(ctx.model)(candidate),+ incompatibleMessage:+ 'The selected low-noise expert is not a different single-file model of this variant. Select one or clear it.',});const ideogram4UnconditionalSlot = (helpText: string): ComponentSlotPolicy =>@@ -1042,6 +1079,7 @@ const hasCompatibleComponentSource = (ctx: ComponentPolicyContext): boolean =>type ComponentSourceCandidate = {base: string;+ is_missing?: boolean;key: string;name: string;type: string;@@ -1102,7 +1140,8 @@ export const getAutoFlux2ComponentSourceModel = (return null;}- const pipelines = models.filter(isFlux2SourceFor(model));+ // A registered pipeline whose files are gone is listed but cannot be loaded.+ const pipelines = models.filter((candidate) => !candidate.is_missing).filter(isFlux2SourceFor(model));const encoderSource = pipelines.find(isFlux2EncoderSourceForModel(model));if (!encoderModel && settings.vae) {@@ -1118,6 +1157,15 @@ const isBundledOrDiffusersSourceSatisfied = (ctx: ComponentPolicyContext): boolectx.model.type !== 'external_image_generator' &&(isBundledMainForBase(ctx.model.base)(ctx.model) || hasCompatibleComponentSource(ctx));+/** A Diffusers pipeline loads its own components, so the loader reads no component source or second transformer. */+const isDiffusersPipeline = (ctx: ComponentPolicyContext): boolean => ctx.model.format === 'diffusers';++/** Whether a Diffusers component source of a single-file Wan model supplies the VAE: the loader needs its width to fit. */+const hasWanSourceVae = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ hasCompatibleComponentSource(ctx) &&+ doesWanSourceSupplyVae(ctx.model, ctx.settings.componentSourceModel!);+/** Shared by the picker, invocation readiness and graph preflight so their requirements cannot drift. */export const getComponentSlotIssue = (slotPolicy: ComponentSlotPolicy, ctx: ComponentPolicyContext): string | null => {const value = ctx.selectedComponents[slotPolicy.key];@@ -1134,6 +1182,10 @@ export const getComponentSlotIssue = (slotPolicy: ComponentSlotPolicy, ctx: Compreturn isValid ? null : (slotPolicy.missingMessage ?? `Generate needs a ${slotPolicy.label} for this model.`);};+/** A self-contained SDNQ FLUX.1 pipeline always loads its own encoders and VAE (`buildFluxGraph` sends none). */+const hasBundledFlux1Components = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' && isSelfContainedSDNQFlux1Pipeline(ctx.model);+const createPolicy = (defaultOpen: boolean, slots: readonly ComponentSlotPolicy[]): ComponentSectionPolicy => ({defaultOpen,slots,@@ -1158,17 +1210,20 @@ const getBaseComponentSectionPolicy = (...createPolicy(!isSelfContainedSDNQFlux1Pipeline(model), [{...t5EncoderSlot('Required for FLUX.1 models.'),- required: (ctx) => !isSelfContainedSDNQFlux1Pipeline(ctx.model),+ neverLoaded: hasBundledFlux1Components,+ required: (ctx) => !hasBundledFlux1Components(ctx),missingMessage: 'Generate needs a T5 Encoder for FLUX models.',},{...clipEmbedSlot('Required for FLUX.1 models.'),- required: (ctx) => !isSelfContainedSDNQFlux1Pipeline(ctx.model),+ neverLoaded: hasBundledFlux1Components,+ required: (ctx) => !hasBundledFlux1Components(ctx),missingMessage: 'Generate needs a CLIP Embed model for FLUX models.',},{...vaeSlot('Required for FLUX.1 models.', isAcceptedVae),- required: (ctx) => !isSelfContainedSDNQFlux1Pipeline(ctx.model),+ neverLoaded: hasBundledFlux1Components,+ required: (ctx) => !hasBundledFlux1Components(ctx),missingMessage: 'Generate needs a VAE for FLUX models.',},]),@@ -1274,10 +1329,13 @@ const getBaseComponentSectionPolicy = (}case 'qwen-image':return createPolicy(model.format !== 'diffusers', [- componentSourceSlot(- (candidate) => isDiffusersMainForBase('qwen-image')(candidate),- 'For non-Diffusers Qwen Image models, select this or provide separate VAE and Qwen VL models.'- ),+ {+ ...componentSourceSlot(+ (candidate) => isDiffusersMainForBase('qwen-image')(candidate),+ 'For non-Diffusers Qwen Image models, select this or provide separate VAE and Qwen VL models.'+ ),+ neverLoaded: isDiffusersPipeline,+ },{...qwenVlEncoderSlot('Optional override, or required with a non-Diffusers model and no component source.'),required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),@@ -1444,6 +1502,7 @@ const getBaseComponentSectionPolicy = ('The second transformer branch. Required for single-file Ideogram 4 models, which hold ' +'only the conditional branch.'),+ neverLoaded: isDiffusersPipeline,required: (ctx) => ctx.model.format !== 'diffusers',missingMessage: 'Generate needs the unconditional transformer for single-file Ideogram 4 models.',},@@ -1468,21 +1527,29 @@ const getBaseComponentSectionPolicy = (]);case 'wan':return createPolicy(model.format !== 'diffusers', [- componentSourceSlot(- (candidate) => isDiffusersMainForBase('wan')(candidate),- 'Select a Diffusers Wan model to provide VAE and text-encoder components.'- ),{- ...vaeSlot('Required unless a Diffusers component source is available.', isAcceptedVae),- required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),- missingMessage: 'Generate needs a VAE for Wan models.',+ ...componentSourceSlot(+ (candidate) => isDiffusersMainForBase('wan')(candidate),+ 'Select a Diffusers Wan model to provide VAE and text-encoder components. Its VAE is used only when it ' ++ 'is a TI2V-5B pipeline for a TI2V-5B model, or an A14B one for an A14B model.'+ ),+ neverLoaded: isDiffusersPipeline,+ },+ {+ ...vaeSlot('Required unless a matching Diffusers component source is available.', isAcceptedVae),+ required: (ctx) => !(isBundledMainForBase('wan')(ctx.model) || hasWanSourceVae(ctx)),+ missingMessage:+ 'Generate needs a VAE for Wan models: a component source supplies one only when it is the same variant family.',},{...wanT5EncoderSlot('Required unless a Diffusers component source is available.'),required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),missingMessage: 'Generate needs a Wan T5 Encoder for Wan models.',},- wanLowNoiseSlot('Optional second A14B expert. Without it the high-noise expert runs the whole schedule.'),+ // Only a single-file A14B model reads it; the loader ignores it for the others, so it is not offered there.+ ...(hasWanLowNoiseSlot(model)+ ? [wanLowNoiseSlot('Optional second A14B expert. Without it the high-noise expert runs the whole schedule.')]+ : []),]);case 'anima':return createPolicy(true, [@@ -1624,7 +1691,322 @@ export const isComponentCompatibleWithModel = (return isSelectedComponentCompatible(slotPolicy, model, nextSettings, key);};-type ReferenceModelCandidate = { base: string; key: string; name: string; type: string };+export type ModelDefaultComponents = Partial<Pick<GenerateSettings, DefaultComponentSlot['setting']>>;++/**+ * `settings` with each component pick replaced by the catalog's record of it, where it is installed: a copy saved with+ * the project keeps the variant or base the pick had when it was made, which the catalog may have reclassified since.+ */+const withCatalogRecords = (settings: GenerateSettings, models: readonly ModelConfig[]): GenerateSettings => {+ const current: Record<string, unknown> = { ...settings };++ for (const setting of GENERATE_COMPONENT_VALUE_KEYS) {+ const picked = settings[setting];+ const installed = picked ? models.find((candidate) => candidate.key === picked.key && !candidate.is_missing) : null;++ if (installed) {+ current[setting] = installed;+ }+ }++ return current as unknown as GenerateSettings;+};++/** Registered and loadable: a model whose files moved is listed (`is_missing`) but a default cannot take it. */+const isInstalled = (models: readonly ModelConfig[], selected: { key: string }): boolean =>+ models.some((installed) => installed.key === selected.key && !installed.is_missing);++const isSlotOffered = (model: GenerateModelConfig, settings: GenerateSettings, setting: GenerateComponentValueKey) =>+ getComponentSectionPolicy(model, settings).slots.some((slotPolicy) => slotPolicy.key === setting);++/** Whether a default for the slot can take effect: the family offers it and the graph loads what it holds. */+const isSlotLoaded = (model: GenerateModelConfig, settings: GenerateSettings, setting: GenerateComponentValueKey) => {+ const context = getComponentPolicyContext(model, settings);++ return getComponentSectionPolicy(model, settings).slots.some(+ (slotPolicy) => slotPolicy.key === setting && !slotPolicy.neverLoaded?.(context)+ );+};++/**+ * The default components the model stores for slots it offers that Apply cannot take: the model is not installed, or+ * it does not fit the slot (an encoder reclassified to another size). Judged beside the defaults that are taken (a+ * vision tower is offered once its encoder default is).+ */+export const getMissingDefaultComponents = (+ model: GenerateModelConfig,+ models: readonly ModelConfig[]+): DefaultComponentSlot['setting'][] => {+ const stored = (model.default_settings as { components?: Record<string, string> | null } | null | undefined)+ ?.components;+ const defaults = getDefaultGenerateSettings(model);+ const taken = getModelDefaultComponents(model, defaults, models);+ const settings = { ...defaults, ...taken };+ const context = getComponentPolicyContext(model, settings);+ const loaded = new Set(+ getComponentSectionPolicy(model, settings)+ .slots.filter((slotPolicy) => !slotPolicy.neverLoaded?.(context))+ .map((slotPolicy) => slotPolicy.key)+ );++ return Object.entries(stored ?? {}).flatMap(([persistenceKey, modelKey]) => {+ const slot = getDefaultComponentSlot(persistenceKey);++ return slot && loaded.has(slot.setting) && taken[slot.setting]?.key !== modelKey ? [slot.setting] : [];+ });+};++/** Whether a generation with `model` loads the VAE it is given, so a default VAE for it can take effect. */+export const isDefaultVaeLoaded = (model: GenerateModelConfig): boolean => {+ const settings = getDefaultGenerateSettings(model);+ const vaeSlot = getComponentSectionPolicy(model, settings).slots.find((slotPolicy) => slotPolicy.key === 'vae');++ return !vaeSlot?.neverLoaded?.(getComponentPolicyContext(model, settings));+};++/** The selections of `before` whose slot is offered there but not in `after`: they stay hidden and unloaded. */+export const getClosedComponentSettings = (+ model: GenerateModelConfig,+ before: GenerateSettings,+ after: GenerateSettings+): GenerateComponentValueKey[] =>+ GENERATE_COMPONENT_VALUE_KEYS.filter(+ (setting) => before[setting] && isSlotOffered(model, before, setting) && !isSlotOffered(model, after, setting)+ );++/**+ * The model's default components that fill a slot of `settings`: one that is empty, or whose selection is not+ * installed or does not fit `model`. A selection that fits stays, unless `replace` (a reset to the model's defaults)+ * takes the default over it. Defaults naming an unknown slot, a model that is not installed or one the slot rejects are+ * skipped. A slot that depends on another (the vision tower follows a GGUF encoder) is judged beside the defaults+ * already taken, whatever order they are stored in, and a selection whose slot a taken default closes is cleared+ * (`null`), so no hidden pick is left to block or leak into a later choice.+ */+export const getModelDefaultComponents = (+ model: GenerateModelConfig,+ settings: GenerateSettings,+ models: readonly ModelConfig[],+ { replace = false }: { replace?: boolean } = {}+): ModelDefaultComponents => {+ const stored = (model.default_settings as { components?: Record<string, string> | null } | null | undefined)+ ?.components;+ const patch: Partial<Record<DefaultComponentSlot['setting'], ComponentModelConfig>> = {};+ const fresh = withCatalogRecords(settings, models);+ let next = fresh;+ let pending = Object.entries(stored ?? {}).flatMap(([persistenceKey, modelKey]) => {+ const slot = getDefaultComponentSlot(persistenceKey);+ const candidate = models.find((installed) => installed.key === modelKey && !installed.is_missing);++ return slot && candidate && (slot.isMainModel ? isMainModelConfig(candidate) : isModelIdentifierConfig(candidate))+ ? [{ candidate, setting: slot.setting }]+ : [];+ });+ let progressed = true;++ while (progressed && pending.length > 0) {+ progressed = false;+ pending = pending.filter(({ candidate, setting }) => {+ const picked = next[setting];++ if (+ !replace &&+ picked &&+ isInstalled(models, picked) &&+ isComponentCompatibleWithModel(model, next, setting, picked as ModelConfig)+ ) {+ return false;+ }++ // Only a slot the family offers (the Model Manager lists the same ones); a dependent slot waits for the one it+ // hangs on.+ if (!isSlotLoaded(model, next, setting) || !isComponentCompatibleWithModel(model, next, setting, candidate)) {+ return true;+ }++ patch[setting] = candidate;+ next = { ...next, [setting]: candidate };+ progressed = true;+ return false;+ });+ }++ // A default taken beside a pick that a later default replaced (a tower before the encoder that closes it) is judged+ // again in the final settings, so the order they are stored in cannot change the result.+ for (let settled = false; !settled;) {+ settled = true;++ for (const setting of Object.keys(patch) as DefaultComponentSlot['setting'][]) {+ if (+ !isSlotLoaded(model, next, setting) ||+ !isComponentCompatibleWithModel(model, next, setting, patch[setting]!)+ ) {+ delete patch[setting];+ next = { ...next, [setting]: fresh[setting] };+ settled = false;+ }+ }+ }++ const cleared: ModelDefaultComponents = {};++ for (const setting of getClosedComponentSettings(model, fresh, next)) {+ if (setting !== 'vae' && !(setting in patch)) {+ cleared[setting as DefaultComponentSlot['setting']] = null;+ }+ }++ // A slot that holds a main model only took a main model above.+ return { ...cleared, ...patch } as ModelDefaultComponents;+};++/** A component slot Generate offers `model`, as the Model Manager lists it among the model's default components. */+export interface DefaultComponentSlotPolicy {+ helpText?: string;+ filter: (candidate: ModelConfig) => boolean;+ label: string;+ modelTypes: readonly ModelTaxonomyType[];+ persistenceKey: string;+}++/**+ * The slots Generate offers a model for its family, given the default components it stores: resolved like a model+ * switch resolves them, so a slot that depends on another opens once that one is set. The VAE has its own default.+ */+export const getDefaultComponentSlotPolicies = (+ model: GenerateModelConfig,+ models: readonly ModelConfig[]+): DefaultComponentSlotPolicy[] => {+ const defaults = getDefaultGenerateSettings(model);+ const settings = { ...defaults, ...getModelDefaultComponents(model, defaults, models) };+ const context = getComponentPolicyContext(model, settings);++ return getComponentSectionPolicy(model, settings).slots.flatMap((slot) => {+ if (slot.neverLoaded?.(context)) {+ return [];+ }++ const persistenceKey = DEFAULT_COMPONENT_SLOTS.find(({ setting }) => setting === slot.key)?.persistenceKey;++ return persistenceKey+ ? [+ {+ filter: (candidate) =>+ (slot.modelTypes as readonly string[]).some((type) => servesAsType(candidate, type)) &&+ (!slot.filter || slot.filter(candidate, context)),+ helpText: slot.helpText,+ label: slot.label,+ modelTypes: slot.modelTypes,+ persistenceKey,+ },+ ]+ : [];+ });+};++/**+ * The default components `model` stores, less the ones whose slot an edit closed: a dependent slot (the vision tower)+ * goes with the pick it hangs on when that is cleared, or when the pick still installed no longer opens it (a+ * safetensors encoder for a GGUF one). Keys this client has no slot for stay, as do the dependents of a pick that is+ * no longer installed, which the user sees and clears first.+ */+export const pruneClosedDefaultComponents = (+ model: GenerateModelConfig,+ models: readonly ModelConfig[]+): Record<string, string> => {+ const stored = (model.default_settings as { components?: Record<string, string> | null } | null | undefined)+ ?.components;+ const components = { ...stored };+ const offered = new Set(getDefaultComponentSlotPolicies(model, models).map((slot) => slot.persistenceKey));++ for (const key of Object.keys(components)) {+ const parent = getDefaultComponentSlot(key)?.dependsOn;+ const parentKey = parent === undefined ? undefined : components[parent];++ if (+ parent !== undefined &&+ (parentKey === undefined || (isInstalled(models, { key: parentKey }) && !offered.has(key)))+ ) {+ delete components[key];+ }+ }++ return components;+};++/** `model` without the stored defaults of the `held` slots, which the caller keeps as they are, empty ones included. */+const withoutDefaultsOf = (+ model: GenerateModelConfig,+ held: readonly (DefaultComponentSlot['setting'] | 'vae')[]+): GenerateModelConfig => {+ if (held.length === 0 || model.type === 'external_image_generator') {+ return model;+ }++ const stored = model.default_settings as { components?: Record<string, string> | null; vae?: string | null } | null;+ const heldKeys = new Set(+ DEFAULT_COMPONENT_SLOTS.filter(({ setting }) => held.includes(setting)).map(({ persistenceKey }) => persistenceKey)+ );+ const components = Object.fromEntries(Object.entries(stored?.components ?? {}).filter(([key]) => !heldKeys.has(key)));++ return {+ ...model,+ default_settings: {+ ...stored,+ components,+ ...(held.includes('vae') ? { vae: null } : {}),+ },+ } as GenerateModelConfig;+};++/**+ * What a model's defaults fill into the slots of `settings` that are empty: its default components, and its default+ * VAE where the model has a VAE picker the VAE fits. A selection that fits stays.+ */+export const getModelDefaultFills = (+ fillModel: GenerateModelConfig,+ settings: GenerateSettings,+ models: readonly ModelConfig[],+ { held = [] }: { held?: readonly (DefaultComponentSlot['setting'] | 'vae')[] } = {}+): Partial<GenerateSettings> => {+ const model = withoutDefaultsOf(fillModel, held);+ const components = getModelDefaultComponents(model, settings, models);+ const current = withCatalogRecords(settings, models);+ const filled = { ...current, ...components };+ const hasVaeSlot = isSlotOffered(model, filled, 'vae');+ const fitsVae = (vae: VaeModelConfig) =>+ hasVaeSlot+ ? isComponentCompatibleWithModel(model, filled, 'vae', vae)+ : getGenerationUiPolicy(model).sdVaeVisible && isVaeCompatibleWithGenerateModel(model, vae);++ // A VAE that is installed and fits stays; one left over from another family (a fallback from an unsupported model)+ // gives way to the default.+ if (current.vae && isInstalled(models, current.vae) && fitsVae(current.vae)) {+ return components;+ }++ const defaultVae = resolveModelDefaultVae(model, filled, models.filter(isVaeModelConfig));++ if (defaultVae.kind !== 'apply') {+ return components;+ }++ // The bundled VAE (`null`) is what an empty slot already uses, and what a pick that is gone gives way to.+ if (defaultVae.vae === null) {+ return settings.vae ? { ...components, vae: null } : components;+ }++ return fitsVae(defaultVae.vae) ? { ...components, vae: defaultVae.vae } : components;+};++/** The IP-Adapter a reference image takes by default for `base`: the first one whose files are present. */+const findDefaultIpAdapter = <T extends ReferenceModelCandidate>(+ models: readonly T[],+ base: string | undefined+): T | null =>+ models.find((candidate) => candidate.type === 'ip_adapter' && candidate.base === base && !candidate.is_missing) ??+ null;++type ReferenceModelCandidate = { base: string; is_missing?: boolean; key: string; name: string; type: string };// FLUX.1 Kontext starter sources from invokeai/backend/model_manager/starter_models/flux.py.const FLUX_KONTEXT_REPOS = [@@ -1841,8 +2223,7 @@ const getFamilyDefaultReferenceImageConfig = (return { image, type: 'qwen_image_2_1_reference_image' };}- const adapterModel =- models.find((candidate) => candidate.type === 'ip_adapter' && candidate.base === modelBase) ?? null;+ const adapterModel = findDefaultIpAdapter(models, modelBase);return {beginEndStepPct: [0, 1],@@ -2022,10 +2403,7 @@ const needsStrengthOnlyRetarget = (return true;}- return (- config.model === null &&- models.some((candidate) => candidate.type === 'ip_adapter' && candidate.base === model.base)- );+ return config.model === null && findDefaultIpAdapter(models, model.base) !== null;};/** Drops unsupported, retargets incompatible ones, keeping image/enabled state. No changes return the same array. */@@ -2192,7 +2570,7 @@ export const addReferenceImages = (request: ReferenceImageAddRequest): Referenceconst getSettingsWithCompatibleModelSelections = (settings: GenerateSettings,model: GenerateModelConfig,- models: readonly ReferenceModelCandidate[],+ models: readonly ModelConfig[],isCanvasFrame: boolean): GenerateModelSelectionResult => {const nextSettings: GenerateSettings = { ...settings, modelKey: model.key };@@ -2322,6 +2700,12 @@ const getSettingsWithCompatibleModelSelections = (}}+ // The new model's defaults fill the slots left empty, which the confirmation does not count as a loss. A pick that+ // fits stays, and picking the same model again changes nothing.+ if (settings.modelKey !== model.key) {+ Object.assign(nextSettings, getModelDefaultFills(model, nextSettings, models));+ }+// Clamp and report during selection; validation remains the backstop for other write paths.const clampedGuidance = clampGuidance(nextSettings.cfgScale, getBaseGenerationConfig(model).guidance);@@ -2397,10 +2781,17 @@ export const getGenerateModelSelectionResult = ({model: GenerateModelConfig;models: readonly ModelConfig[];}): GenerateModelSelectionResult => {- const currentSettings = isGenerateSettings(currentValues)- ? currentValues- : (normalizeGenerateSettings(currentValues) ?? getDefaultGenerateSettings(model));- const result = getSettingsWithCompatibleModelSelections(currentSettings, model, models, isCanvasFrame);+ const stored = isGenerateSettings(currentValues) ? currentValues : normalizeGenerateSettings(currentValues);+ const computed = getSettingsWithCompatibleModelSelections(+ stored ?? getDefaultGenerateSettings(model),+ model,+ models,+ isCanvasFrame+ );+ // Nothing chosen before (an initial model): the model's defaults fill in as they do on a switch.+ const result = stored+ ? computed+ : { ...computed, settings: { ...computed.settings, ...getModelDefaultFills(model, computed.settings, models) } };const componentSourceModel = getAutoFlux2ComponentSourceModel(model, result.settings, models);if (componentSourceModel === undefined || componentSourceModel?.key === result.settings.componentSourceModel?.key) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.tsindex f386c9d392..07b6847ac4 100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts@@ -48,6 +48,44 @@ const hasSubmodels = (model: GenerateComponentCandidate, required: readonly striexport const isSelfContainedSDNQPipeline = (model: GenerateComponentCandidate): boolean =>hasSubmodels(model, SDNQ_PIPELINE_COMPONENTS);+const WAN_SINGLE_FILE_FORMATS: readonly (string | undefined)[] = ['gguf_quantized', 'checkpoint'];++/** Whether the Wan loader reads a low-noise expert beside `model`: a single-file A14B model, not TI2V-5B. */+export const hasWanLowNoiseSlot = (model: GenerateModelConfig): boolean =>+ model.type === 'main' &&+ model.base === 'wan' &&+ WAN_SINGLE_FILE_FORMATS.includes(model.format) &&+ model.variant !== 'ti2v_5b';++const isSameWanExpertTag = (first: unknown, second: unknown): boolean =>+ (first === 'high' || first === 'low') && first === second;++/** The probe's filename tag of a single-file Wan expert; `none` or absent when the name says nothing. */+const getWanExpertTag = (model: object): unknown => (model as { expert?: unknown }).expert;++/**+ * What `wan_model_loader` accepts as the low-noise expert of `model`: another single-file Wan model of the same+ * variant, never the main model itself, no Diffusers pipeline, and not tagged for the role `model` is tagged for.+ */+export const isWanLowNoiseExpertFor =+ (model: GenerateModelConfig): GenerateComponentFilter =>+ (candidate) =>+ hasWanLowNoiseSlot(model) &&+ candidate.type === 'main' &&+ candidate.base === 'wan' &&+ candidate.key !== (model as { key?: string }).key &&+ WAN_SINGLE_FILE_FORMATS.includes(candidate.format) &&+ (candidate.variant ?? null) === (model.variant ?? null) &&+ !isSameWanExpertTag(getWanExpertTag(model), getWanExpertTag(candidate));++/**+ * Whether the Wan loader takes the VAE from a Diffusers `source` beside `model`: TI2V-5B decodes with the 48-channel+ * VAE and the A14B variants with the 16-channel one, so both must be on the same side. The source may still supply just+ * the text encoder beside a standalone VAE.+ */+export const doesWanSourceSupplyVae = (model: GenerateModelConfig, source: GenerateComponentCandidate): boolean =>+ (model.variant === 'ti2v_5b') === (source.variant === 'ti2v_5b');+export const isSelfContainedSDNQFlux1Pipeline = (model: GenerateComponentCandidate): boolean =>hasSubmodels(model, SDNQ_FLUX1_COMPONENTS);diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentDefaults.ts b/invokeai/frontend/webv2/src/features/generation/core/componentDefaults.tsnew file mode 100644index 0000000000..0c317e54df--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/componentDefaults.ts@@ -0,0 +1,45 @@+import type { GenerateComponentValueKey } from './baseGenerationPolicies';++/** A component slot a main model can store a default model for. */+export interface DefaultComponentSlot {+ /** The settings key the picker fills. */+ setting: Exclude<GenerateComponentValueKey, 'vae'>;+ /**+ * The slot's name in `default_settings.components`; one canonical name per slot, `^[a-z0-9_]+$` like the backend+ * requires. Generation metadata records the slot under the same name, except the component source, which each+ * family records under its own name. The VAE has its own `default_settings.vae`.+ */+ persistenceKey: string;+ /** The slot holds a main model (a component source or second transformer), not an encoder. */+ isMainModel?: true;+ /** The slot only exists beside a pick of this slot (the vision tower follows a GGUF encoder); one without goes too. */+ dependsOn?: string;+}++/**+ * The one table pairing slots with their persistence key. Recall reads the same keys from image metadata, so the+ * stored defaults and the recorded components cannot drift apart.+ */+export const DEFAULT_COMPONENT_SLOTS: readonly DefaultComponentSlot[] = [+ { persistenceKey: 'anima_inpaint_adapter', setting: 'animaInpaintAdapterModel' },+ { persistenceKey: 'clip_embed_model', setting: 'clipEmbedModel' },+ { persistenceKey: 'clip_g_model', setting: 'clipGEmbedModel' },+ { persistenceKey: 'clip_l_model', setting: 'clipLEmbedModel' },+ { isMainModel: true, persistenceKey: 'component_source', setting: 'componentSourceModel' },+ { persistenceKey: 'flux3_prompt_upsampler', setting: 'flux3PromptUpsamplerModel' },+ { persistenceKey: 'gemma2_encoder', setting: 'gemma2EncoderModel' },+ { isMainModel: true, persistenceKey: 'ideogram4_unconditional_model', setting: 'ideogram4UnconditionalModel' },+ { persistenceKey: 'mistral_encoder', setting: 'mistralEncoderModel' },+ { persistenceKey: 'pid_decoder', setting: 'pidDecoderModel' },+ { persistenceKey: 'qwen3_5_encoder', setting: 'qwen35EncoderModel' },+ { persistenceKey: 'qwen3_encoder', setting: 'qwen3EncoderModel' },+ { persistenceKey: 'qwen3_vl_encoder', setting: 'qwen3VLEncoderModel' },+ { dependsOn: 'qwen3_vl_encoder', persistenceKey: 'qwen3_vl_vision_tower', setting: 'qwen3VLVisionTowerModel' },+ { persistenceKey: 'qwen_image_qwen_vl_encoder', setting: 'qwenVLEncoderModel' },+ { persistenceKey: 't5_encoder', setting: 't5EncoderModel' },+ { isMainModel: true, persistenceKey: 'wan_transformer_low_noise', setting: 'wanLowNoiseModel' },+ { persistenceKey: 'wan_t5_encoder_model', setting: 'wanT5EncoderModel' },+];++export const getDefaultComponentSlot = (persistenceKey: string): DefaultComponentSlot | undefined =>+ DEFAULT_COMPONENT_SLOTS.find((slot) => slot.persistenceKey === persistenceKey);diff --git a/invokeai/frontend/webv2/src/features/generation/core/contracts.ts b/invokeai/frontend/webv2/src/features/generation/core/contracts.tsindex 6691f8ca44..73eb04caa0 100644--- a/invokeai/frontend/webv2/src/features/generation/core/contracts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/contracts.ts@@ -95,6 +95,8 @@ export interface GenerationModelCatalogItem {variant?: string | null;roles?: readonly ModelRole[];hash?: string;+ /** Registered, but its files are gone: listed in the library, never loadable. */+ is_missing?: boolean;submodel_type?: string;trigger_phrases?: string[] | null;default_settings?: {@@ -107,6 +109,7 @@ export interface GenerationModelCatalogItem {height?: number | null;vae?: string | null;vae_precision?: string | null;+ components?: Record<string, string> | null;weight?: number | null;} | null;[key: string]: unknown;diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex fcfdbc4079..9a3e2c36ac 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -931,6 +931,42 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {expect(getNodeByType(graph, 'wan_l2v')).toBeUndefined();});+ it('passes the optional Wan low-noise expert to a single-file A14B model, and to no other', () => {+ const wanHigh: MainModelConfig = {+ base: 'wan',+ format: 'gguf_quantized',+ key: 'wan-high',+ name: 'Wan high noise',+ type: 'main',+ variant: 't2v_a14b',+ };+ const wanLow: MainModelConfig = { ...wanHigh, key: 'wan-low-gguf', name: 'Wan low noise' };+ // The loader takes the VAE of a component source only beside the same variant family.+ const source = {+ componentSourceModel: { ...wanDiffusers, key: 'wan-a14b-diffusers', variant: 't2v_a14b' } as const,+ };++ // Omit undefined optional fields instead of serializing null.+ expect(compile(wanHigh, source).nodes.model_loader?.transformer_low_noise_model).toBeUndefined();+ expect(compile(wanHigh, { ...source, wanLowNoiseModel: wanLow }).nodes.model_loader).toMatchObject({+ transformer_low_noise_model: wanLow,+ });+ // The loader ignores it for a Diffusers or TI2V-5B model, so a stale pick never reaches the graph.+ const wanLowNoise: MainModelConfig = {+ ...wanDiffusers,+ key: 'wan-low',+ name: 'Wan low noise',+ variant: 'i2v_a14b',+ };+ const stale = compile(wanDiffusers, { wanLowNoiseModel: wanLowNoise });++ expect(stale.nodes.model_loader?.transformer_low_noise_model).toBeUndefined();+ // A project saved before the picker listed single-file experts only can hold a Diffusers pipeline for an A14B+ // model: Generate names it instead of sending what the loader rejects.+ expect(() => compile(wanHigh, { ...source, wanLowNoiseModel: wanLowNoise })).toThrow(/low-noise expert/);+ expect(JSON.stringify(stale)).not.toContain('wan_transformer_low_noise');+ });+it('routes Wan LoRAs through the transformer only, leaving the text encoder unpatched', () => {const a14bLora: LoraModelConfig = {base: 'wan',diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex 073eab8f68..086503e5d3 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -45,6 +45,7 @@ import {isMossImageQwen35Encoder,isQwen3Vl4bEncoder,isVisionTextLlm,+ hasWanLowNoiseSlot,isSelfContainedSDNQFlux1Pipeline,isVaeCompatibleWithGenerateModel,isZImageQwen3Encoder,@@ -2099,6 +2100,8 @@ const buildWanGraph = (const sourceModel = getDiffusersSource(settings, model);const vaeModel = getCompatibleVae(settings, model);const wanT5EncoderModel = settings.wanT5EncoderModel;+ // The loader reads the second expert only for a single-file A14B model, so a stale pick never reaches the graph.+ const lowNoiseModel = hasWanLowNoiseSlot(model) ? settings.wanLowNoiseModel : null;if (!sourceModel && (!vaeModel || !wanT5EncoderModel)) {throw new Error('Wan models require a VAE and Wan T5 Encoder, or a Diffusers component source.');@@ -2112,7 +2115,7 @@ const buildWanGraph = (id: 'model_loader',model,// The second A14B expert. Omitted, the high-noise expert covers the whole schedule.- transformer_low_noise_model: settings.wanLowNoiseModel ?? undefined,+ transformer_low_noise_model: lowNoiseModel ?? undefined,type: 'wan_model_loader',vae_model: vaeModel ?? undefined,wan_t5_encoder_model: wanT5EncoderModel ?? undefined,@@ -2150,7 +2153,7 @@ const buildWanGraph = (wan_component_source: sourceModel,wan_guidance_scale_low_noise: settings.wanGuidanceScaleLowNoise ?? null,wan_t5_encoder_model: wanT5EncoderModel ?? undefined,- wan_transformer_low_noise: settings.wanLowNoiseModel ?? undefined,+ wan_transformer_low_noise: lowNoiseModel ?? undefined,});return {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts b/invokeai/frontend/webv2/src/features/generation/core/graphExport.tsindex 1ac40aa92e..966dddcb8c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts@@ -19,9 +19,11 @@ import {coerceSchedulerForGraph,GENERATE_COMPONENT_VALUE_KEYS,getComponentPolicyContext,+ getClosedComponentSettings,getComponentSectionPolicy,getDefaultGenerateSettings,getGenerateModelSelectionResult,+ getModelDefaultComponents,getSchedulerOptions,isArchitectureDescribed,isGenerateModelSelectable,@@ -139,16 +141,21 @@ const getSelectableModel = (key: string, models: readonly ModelConfig[]): Generareturn model;};-/** Selecting the model, then its default VAE by recall's policy (`getRecallDefaultVae`); otherwise the selection's. */+/**+ * Selecting the model, then its default components and its default VAE by recall's policy (`getRecallDefaultVae`);+ * otherwise the selection's VAE.+ */const getModelDefaultValues = (model: GenerateModelConfig, models: readonly ModelConfig[]): GenerateWidgetValues => {const { settings } = getGenerateModelSelectionResult({currentValues: getDefaultGenerateSettings(model),model,models,});- const vae = getRecallDefaultVae(resolveModelDefaultVae(model, settings, models.filter(isVaeModelConfig)));+ // Components first: a default component source can bundle the VAE the default VAE then falls back to.+ const withComponents = { ...settings, ...getModelDefaultComponents(model, settings, models, { replace: true }) };+ const vae = getRecallDefaultVae(resolveModelDefaultVae(model, withComponents, models.filter(isVaeModelConfig)));- return { ...settings, model, vae: vae === undefined ? settings.vae : vae };+ return { ...withComponents, model, vae: vae === undefined ? withComponents.vae : vae };};const withCaseValues = (values: GenerateWidgetValues, input: GraphExportCase): GenerateWidgetValues => ({@@ -196,6 +203,38 @@ const toSlotValue = (slot: ComponentSlotPolicy, model: ModelConfig): ComponentMo}};+/** The slot a pick of `slotKey` fills and the installed model it names, or the error that tells why it cannot. */+const resolveComponentPick = (+ values: GenerateWidgetValues,+ slotKey: string,+ modelKey: string,+ models: readonly ModelConfig[]+): { slot: ComponentSlotPolicy; value: ComponentModelConfig } => {+ const { slots } = getComponentSectionPolicy(values.model, values);+ const slot = slots.find((candidate) => candidate.key === slotKey);++ if (!slot) {+ const validSlots = listKeys(slots.map((candidate) => candidate.key));++ throw new Error(`Unknown component slot "${slotKey}" for ${values.model.name}. Valid slots: ${validSlots}.`);+ }++ const ctx = getComponentPolicyContext(values.model, values);+ const fitting = models.filter((candidate) => fitsSlot(slot, candidate, ctx));+ const pick = fitting.find((candidate) => candidate.key === modelKey);+ const value = pick ? toSlotValue(slot, pick) : null;++ if (!value) {+ const problem = models.some((candidate) => candidate.key === modelKey)+ ? `"${modelKey}" cannot be the ${slot.label} of ${values.model.name}`+ : `model key "${modelKey}" is not installed`;++ throw new Error(`components.${slotKey}: ${problem}. Choices: ${listModelKeys(fitting)}.`);+ }++ return { slot, value };+};+const withComponentPicks = (values: GenerateWidgetValues,picks: GraphExportCase['components'],@@ -213,31 +252,21 @@ const withComponentPicks = (pending.findIndex(([key]) => slots.some((candidate) => candidate.key === key)));const [slotKey, modelKey] = pending.splice(index, 1)[0]!;- const slot = slots.find((candidate) => candidate.key === slotKey);-- if (!slot) {- const validSlots = listKeys(slots.map((candidate) => candidate.key));-- throw new Error(`Unknown component slot "${slotKey}" for ${values.model.name}. Valid slots: ${validSlots}.`);- }-- const ctx = getComponentPolicyContext(next.model, next);- const fitting = models.filter((candidate) => fitsSlot(slot, candidate, ctx));- const pick = fitting.find((candidate) => candidate.key === modelKey);- const value = pick ? toSlotValue(slot, pick) : null;-- if (!value) {- const problem = models.some((candidate) => candidate.key === modelKey)- ? `"${modelKey}" cannot be the ${slot.label} of ${values.model.name}`- : `model key "${modelKey}" is not installed`;-- throw new Error(`components.${slotKey}: ${problem}. Choices: ${listModelKeys(fitting)}.`);- }+ const { slot, value } = resolveComponentPick(next, slotKey, modelKey, models);next = { ...next, [slot.key]: value };}- return next;+ // A later pick can close the slot of an earlier one (a safetensors encoder after the default GGUF encoder's tower),+ // so the picks are judged together, in the settings they all lead to.+ for (const [slotKey, modelKey] of Object.entries(picks)) {+ resolveComponentPick(next, slotKey, modelKey, models);+ }++ // Inherited picks whose slot a pick closed go too, as the model switch clears them: the graph never loads them.+ const closed = getClosedComponentSettings(values.model, values, next);++ return closed.length === 0 ? next : { ...next, ...Object.fromEntries(closed.map((key) => [key, null])) };};/** Pick the first installed model for the first required slot that is unfilled; null when none can be filled. */@@ -447,7 +476,9 @@ export const compileGraphExportCase = (): CompiledGraphExportCase => {assertModeInputs(input);- const { models } = env;+ // A registered model whose files are gone is listed but cannot be loaded: the case sees the usable ones only, as+ // Generate's pickers do, and a case that names a missing one fails like one that names an unknown model.+ const models = env.models.filter((candidate) => !candidate.is_missing);let values = withCaseValues(getModelDefaultValues(getSelectableModel(input.modelKey, models), models), input);values = withSettingsOverrides(values, input.settings);values = withComponentPicks(values, input.components, models);diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.tsindex b6a4107284..1f70188001 100644--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts@@ -9,7 +9,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import type { GenerateWidgetValues, MainModelConfig } from './types';-import { getDefaultGenerateSettings } from './baseGenerationPolicies';+import { getDefaultGenerateSettings, getGenerateModelSelectionResult } from './baseGenerationPolicies';import { resolveGenerateWidgetValues } from './resolveGenerateWidgetValues';const createModel = (key: string, overrides: Partial<MainModelConfig> = {}): MainModelConfig => ({@@ -87,6 +87,19 @@ describe('resolveGenerateWidgetValues', () => {expect(result?.systemPatch).not.toHaveProperty('batchCount');});+ it('starts on the first model whose files are present, and on the first one when none are', () => {+ const gone = createModel('gone', { is_missing: true } as Partial<MainModelConfig>);+ const present = createModel('present');+ const alsoGone = createModel('also-gone', { is_missing: true } as Partial<MainModelConfig>);++ expect(resolveGenerateWidgetValues({ models: [gone, present], storedValues: {} })?.values.modelKey).toBe('present');+ expect(resolveGenerateWidgetValues({ models: [gone, alsoGone], storedValues: {} })?.values.modelKey).toBe('gone');+ // A model the project chose stays, whatever its files.+ expect(+ resolveGenerateWidgetValues({ models: [present, gone], storedValues: createValues(gone) })?.values.modelKey+ ).toBe('gone');+ });+it('reads dynamic prompts as on for a project saved before the toggle, without writing the flag in', () => {const model = createModel('current');const { dynamicPromptsEnabled: _absent, ...storedValues } = createValues(model);@@ -360,3 +373,39 @@ describe('resolveGenerateWidgetValues and an architecture the table omits', () =expect(resolved?.values.modelKey).toBe('sdxl-model');});});++describe('default components through the resolver', () => {+ const t5 = { base: 'any', key: 't5-default', name: 'T5', type: 't5_encoder' };+ const withDefaults = createModel('flux-default', {+ base: 'flux',+ default_settings: { components: { t5_encoder: t5.key } },+ format: 'checkpoint',+ });+ const plain = createModel('sdxl-plain');+ const catalog = [plain, withDefaults, t5];++ it('keeps the components a model switch filled in', () => {+ const { settings } = getGenerateModelSelectionResult({+ currentValues: createValues(plain),+ model: withDefaults,+ models: catalog,+ });+ const stored = { ...settings, model: withDefaults };++ expect(settings.t5EncoderModel).toEqual(t5);+ expect(resolveGenerateWidgetValues({ models: catalog, storedValues: stored })?.values.t5EncoderModel).toEqual(t5);+ });++ it('applies them to the initial model only, never to an ordinary resolve', () => {+ const initial = resolveGenerateWidgetValues({ models: [withDefaults, t5], storedValues: {} });++ expect(initial?.values.model.key).toBe(withDefaults.key);+ expect(initial?.values.t5EncoderModel).toEqual(t5);++ const cleared = { ...initial!.values, t5EncoderModel: null };++ expect(+ resolveGenerateWidgetValues({ models: [withDefaults, t5], storedValues: cleared })?.values.t5EncoderModel+ ).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.tsindex 038f3e0b44..dd49524449 100644--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.ts@@ -8,8 +8,10 @@ import type { GenerateWidgetValues } from './types';import {getAutoFlux2ComponentSourceModel,getDefaultGenerateSettings,+ getModelDefaultFills,isArchitectureDescribed,isGenerateModelSelectable,+ pickFallbackGenerateModel,} from './baseGenerationPolicies';import { syncPromptTemplateWithCatalog } from './promptTemplates';import {@@ -92,7 +94,7 @@ export const resolveGenerateWidgetValues = ({// picks another or it returns. Reinstalling gives it a new key but the same file hash, so it is found again by hash// (and its type, base and variant). Only values with no runnable choice (first run, an unknown family) take the// default.- const selectedModel =+ const chosenModel =supportedModels.find((model) => model.key === normalizedSettings?.modelKey) ??(storedModel ? supportedModels.find((model) => isSameModelFile(model, storedModel)) : undefined) ??(storedModel &&@@ -100,7 +102,8 @@ export const resolveGenerateWidgetValues = ({isGenerateModelSelectable(storedModel) &&isArchitectureDescribed(storedModel)? storedModel- : supportedModels[0]!);+ : undefined);+ const selectedModel = chosenModel ?? pickFallbackGenerateModel(supportedModels)!;const canReuseStoredValues =isGenerateWidgetValues(storedValues) && normalizedWidgetValues?.batchCount === storedValues.batchCount;const baseValues: GenerateWidgetValues = canReuseStoredValues@@ -116,6 +119,11 @@ export const resolveGenerateWidgetValues = ({values = { ...values, model: selectedModel, modelKey: selectedModel.key };}+ // Only the initial choice takes the model's default components and VAE; an ordinary resolve leaves them as chosen.+ if (chosenModel === undefined) {+ values = { ...values, ...getModelDefaultFills(selectedModel, values, models) };+ }+if (promptTemplates !== undefined) {const promptTemplate = syncPromptTemplateWithCatalog(values.promptTemplate, promptTemplates);diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex 8a0bce0293..ac49ce1403 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -13,6 +13,8 @@ export type ModelIdentifierConfig = {variant?: string | null;roles?: readonly ModelRole[];hash?: string;+ /** Registered, but its files are gone: listed in the library, never loadable. */+ is_missing?: boolean;submodel_type?: string;[key: string]: unknown;};@@ -29,6 +31,7 @@ export type MainModelConfig = ModelIdentifierConfig & {height?: number | null;vae?: string | null;vae_precision?: string | null;+ components?: Record<string, string> | null;} | null;};diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex d66a5e1164..04b832eb10 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -56,7 +56,12 @@ export {getCompatibleReferenceImages,getDefaultGenerateSettings,addReferenceImages,+ getDefaultComponentSlotPolicies,+ isDefaultVaeLoaded,+ pruneClosedDefaultComponents,getGenerateModelSelectionResult,+ getModelDefaultComponents,+ getModelDefaultFills,isComponentCompatibleWithModel,getDimensionGrid,getGenerationDimensions,@@ -71,6 +76,7 @@ export {resolveModelDefaultVae,isArchitectureDescribed,isGenerateModelSelectable,+ pickFallbackGenerateModel,isKnownScheduler,isLossyModelSwitch,isSupportedGenerateModel,@@ -90,6 +96,7 @@ export {type GenerationIssue,type GenerationIssueFix,} from './core/generationIssues';+export { DEFAULT_COMPONENT_SLOTS, type DefaultComponentSlot } from './core/componentDefaults';export {describeExternalCanvasRefusal,GEMINI_TEMPERATURE_MAX,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsxindex 68944ebf7f..98eff4a660 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsx@@ -73,7 +73,10 @@ const turbo: MainModelConfig = {type: 'main',};-const render = async (model: MainModelConfig) => {+const render = async (+ model: MainModelConfig,+ { catalog = [model], settings = {} }: { catalog?: readonly unknown[]; settings?: Record<string, unknown> } = {}+) => {const values = createExternalStoreCore<Record<string, unknown>>({...getDefaultGenerateSettings(model),aspectRatioId: 'Free',@@ -84,12 +87,13 @@ const render = async (model: MainModelConfig) => {positivePrompt: 'a lighthouse',steps: 30,width: 1216,+ ...settings,});const patchGenerateSettings = vi.fn((patch: Record<string, unknown>) => values.patchSnapshot(patch));const undoable = vi.fn();const adapter = {generateValues: values,- models: { catalog: [model], getBaseLabel: () => 'SDXL' },+ models: { catalog, getBaseLabel: () => 'SDXL' },notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn(), undoable },presets: { includePrompts: true, presets: [], remove: vi.fn(), rename: vi.fn(), save: vi.fn() },project: { activeProjectId: 'project-1' },@@ -258,7 +262,7 @@ describe('GenerateHeaderActions', () => {.element(item('Apply model defaults')).toHaveAccessibleDescription('Steps 30 → 8. Left as is, not set for this model: Size, CFG, Scheduler, and VAE precision. ' +- "The model's VAE is not installed or does not fit it, so your VAE stays."+ 'VAE is missing, not installed or does not fit this model, so no default is applied for it.');});@@ -271,7 +275,7 @@ describe('GenerateHeaderActions', () => {.element(item('Apply model defaults')).toHaveAccessibleDescription('Left as is, not set for this model: Size, Steps, CFG, Scheduler, and VAE precision ' +- 'VAE only sets only a VAE, which is not installed or does not fit it, so your VAE stays.'+ 'VAE only sets only VAE, which is missing, not installed or does not fit it, so nothing is applied.');});@@ -284,11 +288,37 @@ describe('GenerateHeaderActions', () => {.element(item('Apply model defaults')).toHaveAccessibleDescription('Left as is, not set for this model: Size, CFG, Scheduler, and VAE precision ' +- "Already using Steps only's defaults, except its VAE, which is not installed or does not fit it, so your " +- 'VAE stays.'+ "Already using Steps only's defaults, except VAE, which is missing, not installed or does not fit it.");});+ it('keeps a working encoder when the saved default encoder is registered but its file is missing', async () => {+ const t5 = (key: string, name: string) => ({ base: 'any', key, name, type: 't5_encoder' });+ const saved = { ...t5('saved-t5', 'Moved T5'), is_missing: true };+ const working = t5('working-t5', 'Working T5');+ const flux: MainModelConfig = {+ base: 'flux',+ default_settings: { components: { t5_encoder: saved.key } },+ format: 'checkpoint',+ key: 'flux',+ name: 'FLUX',+ type: 'main',+ };+ const { patchGenerateSettings } = await render(flux, {+ catalog: [flux, saved, working],+ settings: { t5EncoderModel: working },+ });++ await openMenu();+ await expect.element(item('Apply model defaults')).toHaveAttribute('aria-disabled', 'true');+ await expect+ .element(item('Apply model defaults'))+ .toHaveAccessibleDescription(expect.stringContaining('T5 Encoder'));+ await act(() => (item('Apply model defaults').element() as HTMLElement).click());++ expect(patchGenerateSettings).not.toHaveBeenCalled();+ });+it('offers no apply, saying why, for a model with no defaults of its own', async () => {const { patchGenerateSettings } = await render({ ...turbo, default_settings: null, name: 'Plain SDXL' });diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateResetMenuItems.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateResetMenuItems.tsxindex 7655da3ca2..2d7d359b96 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateResetMenuItems.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateResetMenuItems.tsx@@ -1,9 +1,7 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';-import type { GenerateModelConfig, GenerateSettings, VaeModelConfig } from '@features/generation/core/types';+import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';import { MenuActionItem } from '@platform/ui/Menu';-import { useMemo } from 'react';import { useTranslation } from 'react-i18next';import { flushGenerateDrafts } from './generateDraftRegistry';@@ -11,6 +9,7 @@ import { offerGenerateUndo } from './generateUndo';import { useGenerateValues, useGenerationUi } from './GenerationUiContext';import {describeChanges,+ describeMissingComponents,describeUnset,getApplyModelDefaultsPlan,getChangedSettings,@@ -38,10 +37,6 @@ export const GenerateResetMenuItems = ({const ui = useGenerationUi();const models = ui.models.catalog;const projectId = ui.project.activeProjectId;- const vaeModels = useMemo(- () => models.filter((model): model is ModelConfig & VaeModelConfig => model.type === 'vae'),- [models]- );const items = useGenerateValues((values): { apply: MenuItemState; reset: MenuItemState } | null => {const resolved = resolve(values);@@ -52,7 +47,7 @@ export const GenerateResetMenuItems = ({const { selectedModel, settings } = resolved;const name = selectedModel.name;- const plan = getApplyModelDefaultsPlan(settings, selectedModel, vaeModels);+ const plan = getApplyModelDefaultsPlan(settings, selectedModel, models);const applyChanges = describeChanges(plan.changed,settings,@@ -61,28 +56,39 @@ export const GenerateResetMenuItems = ({t,locale);+ // One list of the defaults the model stores that cannot apply (not installed, or the VAE does not fit), so the+ // wording tells each once, whether or not the slot holds a pick.+ const missing = [...(plan.isVaeMissing ? (['vae'] as const) : []), ...plan.missingComponents];+ const missingList = describeMissingComponents(missing, selectedModel, { ...settings, ...plan.patch }, t, locale);+ const hasMissing = missing.length > 0;// A model that sets nothing leaves everything as it is; its reason says so without listing it all.- const setsNothing = plan.defined.length === 0 && !plan.isVaeMissing;+ const setsNothing = plan.defined.length === 0 && !hasMissing;const unset = setsNothing ? null : describeUnset(plan.unset, selectedModel, t, locale);- // A VAE the model sets but that cannot apply is no unset setting: it gets its own sentence.- const withVaeNote = (hint: string | undefined) =>- !plan.isVaeMissing- ? hint- : hint- ? t('widgets.generate.modelDefaultsWithVaeMissing', { hint })- : t('widgets.generate.modelDefaultsVaeMissing');- const resetAfter = { ...settings, ...getModelDefaultsPatch(settings, selectedModel, vaeModels) };+ const withMissingNote = (hint: string | undefined) => {+ if (!hasMissing) {+ return hint;+ }++ const note = t('widgets.generate.modelDefaultsMissingNote', { count: missing.length, list: missingList });++ return hint ? t('widgets.generate.modelDefaultsWithMissingNote', { hint, note }) : note;+ };+ const resetAfter = { ...settings, ...getModelDefaultsPatch(settings, selectedModel, models) };const resetChanged = getChangedSettings(settings, resetAfter, selectedModel);const applyUnavailableReason = setsNothing? t('widgets.generate.modelDefaultsNoneSet', { name }): plan.changed.length > 0? undefined- : !plan.isVaeMissing+ : !hasMissing? t('widgets.generate.modelDefaultsAlreadyApplied', { name }): plan.defined.length === 0- ? t('widgets.generate.modelDefaultsOnlyVaeMissing', { name })- : t('widgets.generate.modelDefaultsAppliedExceptVae', { name });+ ? t('widgets.generate.modelDefaultsOnlyMissing', { count: missing.length, list: missingList, name })+ : t('widgets.generate.modelDefaultsAppliedExceptMissing', {+ count: missing.length,+ list: missingList,+ name,+ });const applyHint =applyChanges && unset? t('widgets.generate.modelDefaultsApplyHint', { changes: applyChanges, settings: unset })@@ -90,14 +96,14 @@ export const GenerateResetMenuItems = ({return {apply: {- // An unavailable item's reason already tells a missing VAE; the hint tells it only once.- hint: applyUnavailableReason ? applyHint : withVaeNote(applyHint),+ // An unavailable item's reason already names what is missing; the hint names it only once.+ hint: applyUnavailableReason ? applyHint : withMissingNote(applyHint),unavailableReason: applyUnavailableReason,},reset: {hint:resetChanged.length > 0- ? withVaeNote(describeChanges(resetChanged, settings, resetAfter, selectedModel, t, locale))+ ? withMissingNote(describeChanges(resetChanged, settings, resetAfter, selectedModel, t, locale)): t('widgets.generate.resetEverythingToDefaultsHint'),unavailableReason: resetChanged.length === 0 ? t('widgets.generate.resetEverythingAlreadyDone') : undefined,},@@ -153,12 +159,12 @@ export const GenerateResetMenuItems = ({const applyModelDefaults = () =>commitReset(- (settings, model) => getApplyModelDefaultsPlan(settings, model, vaeModels).patch,+ (settings, model) => getApplyModelDefaultsPlan(settings, model, models).patch,(model) => t('widgets.generate.applyModelDefaultsDone', { name: model.name }));const resetEverything = () =>commitReset(- (settings, model) => getModelDefaultsPatch(settings, model, vaeModels),+ (settings, model) => getModelDefaultsPatch(settings, model, models),() => t('widgets.generate.resetEverythingToDefaultsDone'));diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsxindex 1de6af740a..0575e3dbe9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx@@ -4,6 +4,7 @@ import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@feimport {getDefaultGenerateSettings,isGenerateModelSelectable,+ pickFallbackGenerateModel,} from '@features/generation/core/baseGenerationPolicies';import { isLoraModelConfig, normalizeGenerateSettings } from '@features/generation/core/settings';import { resolveGenerateWidgetValues } from '@features/generation/settings';@@ -39,7 +40,9 @@ export const GenerateWidgetView = ({ instance }: { instance?: { id: string } })[capabilitiesStatus, models, storedValues]);const settings =- resolved?.values ?? normalizeGenerateSettings(storedValues) ?? getDefaultGenerateSettings(supportedModels[0]);+ resolved?.values ??+ normalizeGenerateSettings(storedValues) ??+ getDefaultGenerateSettings(pickFallbackGenerateModel(supportedModels));const selectedModel = resolved?.values.model;const gateLabels = useMemo(() => ({diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.test.tsindex 97e5e8f103..ae9d97b611 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.test.ts@@ -1,4 +1,9 @@-import type { GenerateSettings, MainModelConfig, VaeModelConfig } from '@features/generation/core/types';+import type {+ ComponentModelConfig,+ GenerateSettings,+ MainModelConfig,+ VaeModelConfig,+} from '@features/generation/core/types';import type { TFunction } from 'i18next';import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';@@ -8,6 +13,7 @@ import { beforeAll, describe, expect, it } from 'vitest';import {describeChanges,+ describeMissingComponents,describeUnset,getApplyModelDefaultsPlan,getChangedSettings,@@ -247,3 +253,136 @@ describe('describeChanges', () => {);});});++describe('default components', () => {+ const t5 = (key: string): ComponentModelConfig => ({ base: 'any', key, name: key, type: 't5_encoder' });+ const clip: ComponentModelConfig = { base: 'any', key: 'clip', name: 'CLIP', type: 'clip_embed', variant: 'large' };+ const defaultT5 = t5('t5-default');+ const flux: MainModelConfig = {+ base: 'flux',+ default_settings: { components: { clip_embed_model: 'missing', t5_encoder: defaultT5.key } },+ format: 'checkpoint',+ key: 'flux-model',+ name: 'FLUX',+ type: 'main',+ };+ const catalog = [defaultT5, t5('t5-mine'), clip];+ const settings = { ...getDefaultGenerateSettings(flux), clipEmbedModel: clip, t5EncoderModel: t5('t5-mine') };++ it("applies the model's default component over the selection and tells it by the slot's name", () => {+ const plan = getApplyModelDefaultsPlan(settings, flux, catalog);++ expect(plan.patch).toEqual({ t5EncoderModel: defaultT5 });+ expect(plan.defined).toEqual(['t5EncoderModel']);+ expect(describeChanges(plan.changed, settings, after(settings, plan.patch), flux, t, 'en')).toBe(+ 'T5 Encoder t5-mine → t5-default'+ );+ // Once the default holds, there is nothing left to apply, but the model still sets something.+ const applied = getApplyModelDefaultsPlan(after(settings, plan.patch), flux, catalog);++ expect(applied.patch).toEqual({});+ expect(applied.defined).toEqual(['t5EncoderModel']);+ });++ it('resets to the default component and keeps a slot whose default is not installed', () => {+ const patch = getModelDefaultsPatch(settings, flux, catalog);++ expect(patch.t5EncoderModel).toBe(defaultT5);+ // The CLIP default names a model that is not installed, so the current selection is not touched.+ expect(patch).not.toHaveProperty('clipEmbedModel');+ expect(getChangedSettings(settings, after(settings, patch), flux)).toContain('t5EncoderModel');+ });++ it('clears the vision tower when the reset encoder closes its slot, and does not count that as a default', () => {+ const encoder = (key: string, format: string): ComponentModelConfig => ({+ base: 'any',+ format,+ key,+ name: key,+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ });+ const gguf = encoder('encoder-gguf', 'gguf_quantized');+ const checkpoint = encoder('encoder-st', 'checkpoint');+ const tower: ComponentModelConfig = { ...gguf, key: 'mmproj', name: 'mmproj', type: 'qwen3_vl_vision_tower' };+ const model: MainModelConfig = {+ base: 'qwen-image-2-1',+ default_settings: { components: { qwen3_vl_encoder: checkpoint.key } },+ format: 'gguf_quantized',+ key: 'q21',+ name: 'Qwen-Image-2.1',+ type: 'main',+ };+ const current = { ...getDefaultGenerateSettings(model), qwen3VLEncoderModel: gguf, qwen3VLVisionTowerModel: tower };+ const installed = [gguf, checkpoint, tower];+ const patch = getModelDefaultsPatch(current, model, installed);+ const plan = getApplyModelDefaultsPlan(current, model, installed);++ expect(patch).toMatchObject({ qwen3VLEncoderModel: checkpoint, qwen3VLVisionTowerModel: null });+ expect(plan.patch).toEqual({ qwen3VLEncoderModel: checkpoint, qwen3VLVisionTowerModel: null });+ expect(plan.defined).toEqual(['qwen3VLEncoderModel']);+ });++ it('names a default component that is no longer installed instead of reporting no defaults', () => {+ const model: MainModelConfig = { ...flux, default_settings: { components: { t5_encoder: 'uninstalled' } } };+ const plan = getApplyModelDefaultsPlan(settings, model, catalog);++ expect(plan.patch).toEqual({});+ expect(plan.defined).toEqual([]);+ expect(plan.missingComponents).toEqual(['t5EncoderModel']);+ expect(describeMissingComponents(plan.missingComponents, model, settings, t, 'en')).toBe('T5 Encoder');+ expect(getApplyModelDefaultsPlan(settings, flux, catalog).missingComponents).toEqual(['clipEmbedModel']);+ });++ it('names a default encoder that is installed but no longer fits, instead of reporting no defaults', () => {+ // An 8B encoder stored as the default, then reclassified as 4B: Qwen-Image-2.1 conditions on the 8B one.+ const encoder: ComponentModelConfig = {+ base: 'any',+ format: 'checkpoint',+ key: 'reclassified',+ name: 'Reclassified encoder',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_4b',+ };+ const model: MainModelConfig = {+ base: 'qwen-image-2-1',+ default_settings: { components: { qwen3_vl_encoder: encoder.key } },+ format: 'gguf_quantized',+ key: 'q21',+ name: 'Qwen-Image-2.1',+ type: 'main',+ };+ const current = getDefaultGenerateSettings(model);+ const plan = getApplyModelDefaultsPlan(current, model, [encoder]);++ expect(plan.patch).toEqual({});+ expect(plan.defined).toEqual([]);+ expect(plan.missingComponents).toEqual(['qwen3VLEncoderModel']);+ });++ it('names a missing vision tower beside its installed encoder, and lists a missing VAE with the components', () => {+ const encoder: ComponentModelConfig = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'encoder-gguf',+ name: 'GGUF encoder',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ };+ const model: MainModelConfig = {+ base: 'qwen-image-2-1',+ default_settings: { components: { qwen3_vl_encoder: encoder.key, qwen3_vl_vision_tower: 'gone' } },+ format: 'gguf_quantized',+ key: 'q21',+ name: 'Qwen-Image-2.1',+ type: 'main',+ };+ const current = getDefaultGenerateSettings(model);+ const plan = getApplyModelDefaultsPlan(current, model, [encoder]);++ expect(plan.missingComponents).toEqual(['qwen3VLVisionTowerModel']);+ expect(+ describeMissingComponents(['vae', ...plan.missingComponents], model, after(current, plan.patch), t, 'en')+ ).toBe('VAE and Vision Tower');+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.ts b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.tsindex 7bcb38cab8..4c8425c683 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.ts@@ -1,16 +1,26 @@-import type { GenerateModelConfig, GenerateSettings, VaeModelConfig } from '@features/generation/core/types';+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';+import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';import type { TFunction } from 'i18next';import { formatAspectRatio } from '@features/generation/core/aspectRatioPresets';import {getDefaultGenerateSettings,+ getComponentSectionPolicy,getGenerationDimensions,getGenerationUiPolicy,+ getMissingDefaultComponents,+ getModelDefaultComponents,getSchedulerOptions,getSettingsWithModelDefaults,resolveModelDefaultVae,} from '@features/generation/core/baseGenerationPolicies';-import { clampDimension, getActiveAspectRatio, isAspectRatioLocked } from '@features/generation/core/settings';+import { DEFAULT_COMPONENT_SLOTS, type DefaultComponentSlot } from '@features/generation/core/componentDefaults';+import {+ clampDimension,+ getActiveAspectRatio,+ isAspectRatioLocked,+ isVaeModelConfig,+} from '@features/generation/core/settings';import {doesModelSetDefault,@@ -22,10 +32,18 @@ import {// The Generate reset menu's plan and wording. Only that menu reads them, and it loads with the menu, off the editor's// startup; the fields' reset labels read `modelDefaultSettings`.-/** What a reset is described by: the settings, plus the aspect ratio lock a size change can set or release. */-export type DescribedSetting = ModelDefaultSetting | 'aspectRatio';+/** A component slot a main model can store a default model for. */+type ComponentSetting = DefaultComponentSlot['setting'];++/** What a reset is described by: the settings, the aspect ratio lock a size change can set or release, components. */+export type DescribedSetting = ModelDefaultSetting | 'aspectRatio' | ComponentSetting;++const COMPONENT_SETTINGS: readonly ComponentSetting[] = DEFAULT_COMPONENT_SLOTS.map(({ setting }) => setting);-/** In the order the form shows them: Size, then Render, then Advanced. */+const isComponentSetting = (setting: DescribedSetting): setting is ComponentSetting =>+ (COMPONENT_SETTINGS as readonly DescribedSetting[]).includes(setting);++/** In the order the form shows them: Size, then Render, then Components, then Advanced. */const DESCRIBED_SETTINGS: readonly DescribedSetting[] = ['size','aspectRatio',@@ -33,12 +51,20 @@ const DESCRIBED_SETTINGS: readonly DescribedSetting[] = ['cfgScale','scheduler','vae',+ ...COMPONENT_SETTINGS,'vaePrecision','cfgRescaleMultiplier',];-/** Whether the form shows the setting for this family, so a value its graph ignores is neither applied nor told. */+/**+ * Whether the form shows the setting for this family, so a value its graph ignores is neither applied nor told. A+ * component changes only to a default for a slot the family offers, so its change is always told.+ */const isShown = (setting: DescribedSetting, model: GenerateModelConfig): boolean => {+ if (isComponentSetting(setting)) {+ return true;+ }+const policy = getGenerationUiPolicy(model);switch (setting) {@@ -95,7 +121,9 @@ const isSettingChanged = (setting: DescribedSetting, before: GenerateSettings, acase 'vae':return (before.vae?.key ?? null) !== (after.vae?.key ?? null);default:- return !Object.is(before[setting], after[setting]);+ return isComponentSetting(setting)+ ? (before[setting]?.key ?? null) !== (after[setting]?.key ?? null)+ : !Object.is(before[setting], after[setting]);}};@@ -114,32 +142,53 @@ export interface ApplyModelDefaultsPlan {/** Only the settings that change; empty when the model's defaults already hold. */patch: Partial<GenerateSettings>;changed: readonly DescribedSetting[];- /** Shown settings the model sets a default for, changed or not. */- defined: readonly ModelDefaultSetting[];+ /** Shown settings and component slots the model sets a usable default for, changed or not. */+ defined: readonly (ModelDefaultSetting | ComponentSetting)[];/** Shown settings the model sets no default for, which applying leaves as they are. */unset: readonly ModelDefaultSetting[];/** The model names a VAE that is not installed or does not fit; the user's VAE stays. */isVaeMissing: boolean;+ /** Default components the model stores that are not installed; the user's picks stay. */+ missingComponents: readonly ComponentSetting[];}/*** Apply model defaults: only the values the model's own defaults set, as the legacy "Use default settings" did. A- * setting the model leaves unset keeps its value, and a set one that already matches is left out of the patch.+ * setting the model leaves unset keeps its value, and a set one that already matches is left out of the patch. A+ * default component replaces the slot's selection; one that is not installed or does not fit is skipped, and the+ * slots the model stores no default for are not listed as unset.*/export const getApplyModelDefaultsPlan = (settings: GenerateSettings,model: GenerateModelConfig,- vaeModels: readonly VaeModelConfig[]+ models: readonly ModelConfig[]): ApplyModelDefaultsPlan => {const defaults = getDefaultGenerateSettings(model);- const defaultVae = resolveModelDefaultVae(model, settings, vaeModels);+ const components = getModelDefaultComponents(model, settings, models, { replace: true });+ const withComponents = { ...settings, ...components };+ // A default component source can bundle the VAE, so the VAE is judged beside the default components.+ const defaultVae = resolveModelDefaultVae(model, withComponents, models.filter(isVaeModelConfig));// Where the VAE has no field of its own, a default the model sets is still applied and told.const isVaeShown = getGenerationUiPolicy(model).sdVaeVisible || defaultVae.kind !== 'none';const patch: Partial<GenerateSettings> = {};- const defined: ModelDefaultSetting[] = [];+ const defined: (ModelDefaultSetting | ComponentSetting)[] = [];const unset: ModelDefaultSetting[] = [];for (const setting of DESCRIBED_SETTINGS) {+ if (isComponentSetting(setting)) {+ // A cleared slot (`null`: the default encoder closed it) is no default of the model's, only a change.+ if (setting in components) {+ if (components[setting]) {+ defined.push(setting);+ }++ if (isSettingChanged(setting, settings, withComponents)) {+ Object.assign(patch, { [setting]: components[setting] });+ }+ }+ continue;+ }+if (setting === 'aspectRatio' || !isShown(setting, model) || (setting === 'vae' && !isVaeShown)) {continue;}@@ -171,22 +220,29 @@ export const getApplyModelDefaultsPlan = (changed: getChangedSettings(settings, { ...settings, ...patch }, model),defined,isVaeMissing: defaultVae.kind === 'missing',+ missingComponents: getMissingDefaultComponents(model, models),patch,unset,};};/**- * Settings with every model-governed value reset: the model's where it sets one, the base's otherwise. The VAE changes- * only to one the model's defaults can apply; otherwise the user's stays, since the base has no VAE to return to.+ * Settings with every model-governed value reset: the model's where it sets one, the base's otherwise. The VAE and+ * each component change only to a default the model can apply; otherwise the user's stays, since the base has none+ * to return to.*/export const getModelDefaultSettings = (settings: GenerateSettings,model: GenerateModelConfig,- vaeModels: readonly VaeModelConfig[]+ models: readonly ModelConfig[]): GenerateSettings => {- const nextSettings = getSettingsWithModelDefaults(settings, model);- const defaultVae = resolveModelDefaultVae(model, settings, vaeModels);+ const withDefaults = getSettingsWithModelDefaults(settings, model);+ // Components first: a default component source can bundle the VAE.+ const nextSettings = {+ ...withDefaults,+ ...getModelDefaultComponents(model, withDefaults, models, { replace: true }),+ };+ const defaultVae = resolveModelDefaultVae(model, nextSettings, models.filter(isVaeModelConfig));// The menu's policy for a default VAE that cannot apply: the user's VAE stays, and the menu says so.return defaultVae.kind === 'apply' ? { ...nextSettings, vae: defaultVae.vae } : nextSettings;@@ -214,20 +270,44 @@ const MODEL_DEFAULT_VALUE_KEYS = [export const getModelDefaultsPatch = (settings: GenerateSettings,model: GenerateModelConfig,- vaeModels: readonly VaeModelConfig[]+ models: readonly ModelConfig[]): Partial<GenerateSettings> => {- const defaults = getModelDefaultSettings(settings, model, vaeModels);+ const defaults = getModelDefaultSettings(settings, model, models);const patch: Partial<GenerateSettings> = { vae: defaults.vae };for (const key of MODEL_DEFAULT_VALUE_KEYS) {(patch as Record<string, unknown>)[key] = defaults[key];}+ // Only the component slots a default changes; the others keep their selection untouched.+ for (const setting of COMPONENT_SETTINGS) {+ if (defaults[setting] !== settings[setting]) {+ Object.assign(patch, { [setting]: defaults[setting] });+ }+ }+return patch;};+/**+ * A component slot's name as the Components section shows it. A slot can depend on another (the vision tower on a GGUF+ * encoder), so it is looked up beside the settings the change leads to.+ */+const getComponentLabel = (+ setting: ComponentSetting,+ model: GenerateModelConfig,+ settings: GenerateSettings,+ t: TFunction+): string =>+ getComponentSectionPolicy(model, settings).slots.find((slot) => slot.key === setting)?.label ??+ t('widgets.generate.components');+/** The setting's name as its field shows it: CFG or Guidance per family. */-const getSettingLabel = (setting: DescribedSetting, model: GenerateModelConfig, t: TFunction): string => {+const getSettingLabel = (+ setting: Exclude<DescribedSetting, ComponentSetting>,+ model: GenerateModelConfig,+ t: TFunction+): string => {switch (setting) {case 'aspectRatio':return t('widgets.generate.aspectRatio');@@ -276,7 +356,7 @@ const formatSettingValue = (return settings.vaePrecision.toUpperCase();// Exactly as the fields show them, so two values that differ there never read the same here.default:- return String(settings[setting]);+ return isComponentSetting(setting) ? (settings[setting]?.name ?? t('common.none')) : String(settings[setting]);}};@@ -307,7 +387,9 @@ export const describeChanges = (changed.map((setting) =>t('widgets.generate.modelDefaultsChange', {from: formatSettingValue(setting, before, model, t, locale),- setting: getSettingLabel(setting, model, t),+ setting: isComponentSetting(setting)+ ? getComponentLabel(setting, model, after, t)+ : getSettingLabel(setting, model, t),to: formatSettingValue(setting, after, model, t, locale),})),@@ -315,6 +397,22 @@ export const describeChanges = ('unit');+/** The defaults that cannot apply (a VAE or components) as one list, named as their fields are. */+export const describeMissingComponents = (+ missing: readonly (ComponentSetting | 'vae')[],+ model: GenerateModelConfig,+ settings: GenerateSettings,+ t: TFunction,+ locale: string | undefined+): string =>+ formatList(+ missing.map((setting) =>+ setting === 'vae' ? getSettingLabel(setting, model, t) : getComponentLabel(setting, model, settings, t)+ ),+ locale,+ 'conjunction'+ );+/** The settings Apply leaves as they are because the model sets no default, as one list; null for none. */export const describeUnset = (unset: readonly ModelDefaultSetting[],diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.test.tsindex 51c59b20b5..0b4d2022e9 100644--- a/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts@@ -91,6 +91,36 @@ describe('mainDefaultSettingsSchema', () => {});});+describe('mainDefaultSettingsSchema default components', () => {+ const parse = (components: Record<string, string> | null) =>+ mainDefaultSettingsSchema.safeParse({+ cfgRescaleMultiplier: null,+ cfgScale: null,+ components,+ guidance: null,+ height: null,+ scheduler: null,+ steps: null,+ vae: null,+ vaePrecision: null,+ width: null,+ });++ it('accepts slot names with a model key each, or none', () => {+ expect(parse({ qwen3_5_encoder: 'key-1', t5_encoder: 'key-2' }).success).toBe(true);+ expect(parse(null).success).toBe(true);+ });++ it.each([+ ['the VAE, which has its own field', { vae: 'key' }],+ ['a slot name outside a-z, 0-9 and _', { 'T5-Encoder': 'key' }],+ ['a blank model key', { t5_encoder: ' ' }],+ ['more than sixteen entries', Object.fromEntries(Array.from({ length: 17 }, (_, index) => [`slot_${index}`, 'k']))],+ ])('rejects %s', (_label, components) => {+ expect(parse(components).success).toBe(false);+ });+});+describe('canonicalLocalPath', () => {it.each([['C:\\Users\\Me\\x.safetensors', 'c:/users/me/x.safetensors'],diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.tsindex 5dcb0b86c4..eb976d5b70 100644--- a/invokeai/frontend/webv2/src/features/models/core/schemas.ts+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.ts@@ -23,10 +23,25 @@ const optionalBoundedNumber = (min: number, max: number, label: string) =>.max(max, `${label} must be at most ${max}.`).nullable();+/** Mirrors the backend's rules for `default_settings.components`: the VAE has its own field. */+const MAX_DEFAULT_COMPONENTS = 16;+const defaultComponentsSchema = z+ .record(+ z.string().regex(/^[a-z0-9_]+$/, 'A component slot name may only hold a-z, 0-9 and _.'),+ trimmed.min(1, 'Choose a model or clear the component.')+ )+ .refine((components) => !('vae' in components), 'Set the VAE in its own field.')+ .refine(+ (components) => Object.keys(components).length <= MAX_DEFAULT_COMPONENTS,+ `At most ${MAX_DEFAULT_COMPONENTS} default components are allowed.`+ );+/** Null means inherit the app default and corresponds to an unchecked field toggle. */export const mainDefaultSettingsSchema = z.object({cfgRescaleMultiplier: optionalBoundedNumber(0, 0.99, 'CFG rescale multiplier'),cfgScale: optionalBoundedNumber(1, 200, 'CFG scale'),+ // Model keys by slot; null or unset stores none.+ components: defaultComponentsSchema.nullish(),// Record validation permits guidance >=1 without an architecture ceiling; generation owns guidance_max. Accept FLUX// Fill's stored default of 30.guidance: optionalBoundedNumber(1, 200, 'Guidance'),diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tsindex 96c8e0e959..95a2e1e9b8 100644--- a/invokeai/frontend/webv2/src/features/models/core/types.ts+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts@@ -109,6 +109,8 @@ export interface MainModelDefaultSettings {height?: number | null;guidance?: number | null;fp8_storage?: boolean | null;+ /** Default component models by slot name (`generation/core/componentDefaults`), each a model key; null when none. */+ components?: Record<string, string> | null;}export interface LoraModelDefaultSettings {@@ -188,6 +190,8 @@ export interface ModelConfig {type: ModelTaxonomyType;format: ModelFileFormat;variant?: string | null;+ /** Set by the library on a registered model whose files are gone; the backend never sends it. */+ is_missing?: boolean;/** Other types these files serve as. The backend always sends it; older fixtures may omit it. */roles?: ModelRole[];prediction_type?: PredictionType | null;diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.tsindex e6022baa89..6c3c63c621 100644--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts@@ -45,6 +45,45 @@ describe('models store loading', () => {expect(api.listModels).toHaveBeenCalledTimes(2);});+ it('reads the library fresh with file availability, and lists every model present when detection fails', async () => {+ const a = { base: 'sdxl', key: 'a', name: 'A', type: 'main' };+ const b = { base: 'sdxl', key: 'b', name: 'B', type: 'main' };+ const { listModelsWithAvailability } = await import('./modelsStore');++ api.listModels.mockResolvedValueOnce([a, b]);+ api.listMissingModels.mockResolvedValueOnce([b]);+ await expect(listModelsWithAvailability()).resolves.toEqual([a, { ...b, is_missing: true }]);++ api.listModels.mockResolvedValueOnce([a, b]);+ api.listMissingModels.mockRejectedValueOnce(new Error('down'));+ await expect(listModelsWithAvailability()).resolves.toEqual([a, b]);+ });++ it('flags a registered model whose files are gone on its catalog entry', async () => {+ const a = { base: 'sdxl', key: 'a', name: 'A', type: 'main' };+ const b = { base: 'sdxl', key: 'b', name: 'B', type: 'main' };+ api.listModels.mockResolvedValueOnce([a, b]);+ api.listMissingModels.mockResolvedValueOnce([b]);+ const store = await import('./modelsStore');++ await store.refreshModels();++ expect(store.getModelsSnapshot().models).toEqual([a, { ...b, is_missing: true }]);+ expect(store.getModelsSnapshot().modelsByKey.get('b')).toMatchObject({ is_missing: true });+ });++ it('keeps a missing model flagged when a server response replaces its record', async () => {+ const b = { base: 'sdxl', key: 'b', name: 'B', type: 'main' };+ api.listModels.mockResolvedValueOnce([b]);+ api.listMissingModels.mockResolvedValueOnce([b]);+ const store = await import('./modelsStore');++ await store.refreshModels();+ store.replaceModelInStore({ ...b, name: 'Renamed' } as ModelConfig);++ expect(store.getModelsSnapshot().modelsByKey.get('b')).toMatchObject({ is_missing: true, name: 'Renamed' });+ });+it('keeps the by-key index in lockstep with every models write', async () => {api.listModels.mockResolvedValueOnce([{ base: 'sdxl', key: 'a', name: 'A', type: 'main' },diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.tsindex 5c9a6fa8e8..49a94b2030 100644--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts@@ -63,6 +63,22 @@ registerAccountOwnedResource({});/** Re-fetch the library; concurrent calls share one request, and a call made mid-flight queues one trailing rerun. */+// Flagged on the entry itself, so every consumer of the catalog sees it, not only the library views.+const withMissingFlags = (models: ModelConfig[], missingKeys: ReadonlySet<string>): ModelConfig[] =>+ missingKeys.size > 0+ ? models.map((model) => (missingKeys.has(model.key) ? { ...model, is_missing: true } : model))+ : models;++/**+ * A fresh read of the library, not this tab's snapshot, with current file availability on each entry as the snapshot+ * has it. Detection is best-effort: a failed missing-file lookup lists every model as present.+ */+export const listModelsWithAvailability = async (signal?: AbortSignal): Promise<ModelConfig[]> => {+ const [models, missing] = await Promise.all([listModels(signal), listMissingModels(signal).catch(() => [])]);++ return withMissingFlags(models, new Set(missing.map((model) => model.key)));+};+export const refreshModels = (owner: AccountScope = captureAccountScope()): Promise<void> =>refreshFlight.run(() => {const generation = mutationGeneration;@@ -85,11 +101,13 @@ export const refreshModels = (owner: AccountScope = captureAccountScope()): Promreturn;}+ const missingKeys =+ missingModels.length > 0 ? new Set(missingModels.map((model) => model.key)) : EMPTY_MISSING_KEYS;+store.patchSnapshot({- ...withModels(models),+ ...withModels(withMissingFlags(models, missingKeys)),error: null,- missingModelKeys:- missingModels.length > 0 ? new Set(missingModels.map((model) => model.key)) : EMPTY_MISSING_KEYS,+ missingModelKeys: missingKeys,modelsDir,status: 'loaded',});@@ -127,12 +145,16 @@ export const getModelsSnapshot = (): ModelsSnapshot => store.getSnapshot();/** Read-only subscription for App-owned cross-feature runtimes. */export const subscribeModels = (listener: () => void): (() => void) => store.subscribe(listener);-/** Patch one model in place after a successful update/convert. */+/**+ * Patch one model in place after a successful update/convert. A server record carries no file availability, so the+ * model keeps the missing flag the last refresh gave it; whoever moves its files refreshes the library afterwards.+ */export const replaceModelInStore = (model: ModelConfig): void => {mutationGeneration += 1;- store.patchSnapshot(- withModels(store.getSnapshot().models.map((existing) => (existing.key === model.key ? model : existing)))- );+ const { missingModelKeys, models } = store.getSnapshot();+ const flagged = missingModelKeys.has(model.key) ? { ...model, is_missing: true } : model;++ store.patchSnapshot(withModels(models.map((existing) => (existing.key === model.key ? flagged : existing))));};/** Apply a narrow optimistic model patch without replacing unrelated server fields. */diff --git a/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.test.ts b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.test.tsindex d5dd58b804..dcb17233a7 100644--- a/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.test.ts+++ b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.test.ts@@ -48,6 +48,7 @@ const library = vi.hoisted(() => ({ models: [] as unknown[] }));vi.mock('./api', async (importOriginal) => ({...(await importOriginal<typeof ModelsApi>()),+ listMissingModels: () => Promise.resolve([]),listModels: () => Promise.resolve(library.models),}));diff --git a/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.ts b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.tsindex d2cd8ae1b0..7962f40a5c 100644--- a/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.ts+++ b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.ts@@ -27,7 +27,7 @@ import { createExternalStore } from '@platform/state/externalStore';import { ApiError, getApiErrorCode, getApiErrorMessage, sleep } from '@platform/transport/http';import { socketHub } from '@platform/transport/socketHub';-import { listModels } from './api';+import { listModelsWithAvailability } from './modelsStore';import {acknowledgeCalibrationEnqueue,calibrateWorkingMemory,@@ -171,8 +171,8 @@ export const compileWorkingMemoryPlan = async (const compileSignal = signal ? AbortSignal.any([owner.signal, signal]) : owner.signal;compileSignal.throwIfAborted();- // Not this tab's models store: another tab may have changed a record. Records only, without missing-file stats.- const records = listModels(compileSignal);+ // Not this tab's models store: another tab may have changed a record. Records with current file availability.+ const records = listModelsWithAvailability(compileSignal);// The compiler awaits the records only once it has loaded; until then a failed read must not count as unhandled.void records.catch(() => undefined);diff --git a/invokeai/frontend/webv2/src/features/models/index.ts b/invokeai/frontend/webv2/src/features/models/index.tsindex 21c3a5251e..3fa2222242 100644--- a/invokeai/frontend/webv2/src/features/models/index.ts+++ b/invokeai/frontend/webv2/src/features/models/index.ts@@ -41,9 +41,13 @@ export {useModelsUi,useOpenAddModelsSearch,useOpenModelInManager,+ type DefaultComponentPruner,+ type DefaultComponentSlotModel,+ type DefaultComponentSlotPolicy,+ type DefaultComponentSlotReader,type ModelSchedulerPolicy,type ModelsUiAdapter,type SchedulerPolicyReader,- type SchedulerPolicySource,- type SchedulerPolicyState,+ type ModelDefaultsRulesSource,+ type ModelDefaultsRulesState,} from './ui/ModelsUiContext';diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsxindex d5e72e88dc..b15ff51ca9 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsx@@ -2,12 +2,7 @@ import { accountLifecycle } from '@platform/state/accountLifecycle';import { renderToStaticMarkup } from 'react-dom/server';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import {- ModelsUiProvider,- NO_SCHEDULER_POLICY,- useOpenAddModelsSearch,- useOpenModelInManager,-} from './ModelsUiContext';+import { ModelsUiProvider, NO_DEFAULTS_RULES, useOpenAddModelsSearch, useOpenModelInManager } from './ModelsUiContext';import { getModelsUiSnapshotForTests } from './uiStore';const { navigate, router } = vi.hoisted(() => ({@@ -24,7 +19,7 @@ const adapter = {installInPlace: true,isProjectActive: (projectId: string) => activeProjectId === projectId,managerProjectId: 'project-a',- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,};diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsxindex baa8e33f32..2aa2fed8c3 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx@@ -1,4 +1,4 @@-import type { ModelConfig } from '@features/models/core/types';+import type { ModelConfig, ModelTaxonomyType } from '@features/models/core/types';import type { CalibrationGraphCompiler } from '@features/models/core/workingMemory';import type { ResolvedValues } from '@platform/core/resolvedValues';import type { ReactNode } from 'react';@@ -27,27 +27,73 @@ export type SchedulerPolicyModel = Pick<ModelConfig, 'base' | 'format' | 'varianexport type SchedulerPolicyReader = (model: SchedulerPolicyModel, currentValue: string | null) => ModelSchedulerPolicy;+/** What Generate's component rules read of the main model: its architecture, and the bundle a self-contained one holds. */+export type DefaultComponentSlotModel = Pick<ModelConfig, 'base' | 'format' | 'key' | 'name' | 'submodels' | 'variant'>;++/** One component slot of a main model's family that the model can store a default for. */+export interface DefaultComponentSlotPolicy {+ /** The slot's name in `default_settings.components`. */+ persistenceKey: string;+ label: string;+ /** Generate's help for the slot. */+ helpText?: string;+ modelTypes: readonly ModelTaxonomyType[];+ /** Whether `candidate` may fill the slot, beside the other default components stored. */+ filter: (candidate: ModelConfig) => boolean;+}+/**- * Generate's scheduler rules: `loading` until the rules and the architecture table they read arrive, `unavailable` when- * either failed, and `ready` with a reader that is replaced whenever the table changes.+ * The slots Generate offers `model`, given the default components stored so far (a slot can depend on another: the+ * vision tower appears only beside a GGUF Qwen3-VL encoder). `catalog` resolves the stored model keys; the VAE has+ * its own default and is not listed.*/-export type SchedulerPolicyState =+export type DefaultComponentSlotReader = (+ model: DefaultComponentSlotModel,+ components: Readonly<Record<string, string>>,+ catalog: readonly ModelConfig[]+) => readonly DefaultComponentSlotPolicy[];++/**+ * `components` less the keys whose slot an edit closed (the vision tower once its encoder is cleared or replaced by one+ * that has none), so no hidden default is left behind. Keys of slots this client does not know stay.+ */+export type DefaultComponentPruner = (+ model: DefaultComponentSlotModel,+ components: Readonly<Record<string, string>>,+ catalog: readonly ModelConfig[]+) => Record<string, string>;++/**+ * Generate's rules for a main model's defaults (the scheduler and the component slots): `loading` until the rules and+ * the architecture table they read arrive, `unavailable` when either failed, and `ready` with readers that are+ * replaced whenever the table changes.+ */+export type ModelDefaultsRulesState =| { status: 'loading' }| { status: 'unavailable' }- | { read: SchedulerPolicyReader; status: 'ready' };--/** Generate's scheduler rules, loaded on first use so the Model Manager carries no Generation code at startup. */-export interface SchedulerPolicySource {- getSnapshot: () => SchedulerPolicyState;+ | {+ /** Whether Generate accepts `candidate` as the VAE of `model`, which may be of another base (MOSS-Image takes FLUX.2's). */+ acceptsDefaultVae: (model: DefaultComponentSlotModel, candidate: ModelConfig) => boolean;+ pruneComponents: DefaultComponentPruner;+ /** Whether Generate loads a VAE picked for `model`; a self-contained pipeline decodes with its own. */+ usesDefaultVae: (model: DefaultComponentSlotModel) => boolean;+ read: SchedulerPolicyReader;+ readComponentSlots: DefaultComponentSlotReader;+ status: 'ready';+ };++/** Generate's rules for main-model defaults, loaded on first use so the Model Manager carries no Generation code at startup. */+export interface ModelDefaultsRulesSource {+ getSnapshot: () => ModelDefaultsRulesState;/** Starts loading the rules and the table, or retries after a failure; joins a load already running. */load: () => void;subscribe: (listener: () => void) => () => void;}-const SCHEDULER_POLICY_UNAVAILABLE: SchedulerPolicyState = { status: 'unavailable' };+const DEFAULTS_RULES_UNAVAILABLE: ModelDefaultsRulesState = { status: 'unavailable' };/** For surfaces composed without Generation, such as isolated tests: the rules never arrive. */-export const NO_SCHEDULER_POLICY: SchedulerPolicySource = {- getSnapshot: () => SCHEDULER_POLICY_UNAVAILABLE,+export const NO_DEFAULTS_RULES: ModelDefaultsRulesSource = {+ getSnapshot: () => DEFAULTS_RULES_UNAVAILABLE,load: () => undefined,subscribe: () => () => undefined,};@@ -63,7 +109,7 @@ export interface ModelsUiAdapter {installInPlace: boolean;isProjectActive: (projectId: string) => boolean;managerProjectId: string | null;- schedulerPolicy: SchedulerPolicySource;+ defaultsRules: ModelDefaultsRulesSource;setInstallInPlace: (installInPlace: boolean) => void;}@@ -73,7 +119,7 @@ const DEFAULT_MODELS_UI_ADAPTER: ModelsUiAdapter = {installInPlace: true,isProjectActive: () => false,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,};diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsxindex 286e64551a..3fa495450d 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx@@ -4,7 +4,7 @@ import type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';import { scanFolderForModels } from '@features/models/data/api';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';-import { type ModelsUiAdapter, ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { type ModelsUiAdapter, ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { getModelsUiSnapshotForTests, setAddModelsQuery, updateModelsUi } from '@features/models/ui/uiStore';import { createExternalStore } from '@platform/state/externalStore';import { ApiError } from '@platform/transport/http';@@ -92,7 +92,7 @@ const WithAccountPreferences = ({ children }: { children: ReactNode }) => {installInPlace,isProjectActive: () => true,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace,}),[installInPlace]diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsxindex 6478d72969..6d234d9e84 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx@@ -3,7 +3,7 @@ import type { ModelConfig } from '@features/models';import { ChakraProvider } from '@chakra-ui/react';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';import { setRelationshipsSnapshotForTests } from '@features/models/data/relationshipsStore';-import { ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { Field } from '@platform/ui/Field';import { system } from '@theme/system';import { act } from 'react';@@ -48,7 +48,7 @@ const MODELS_UI_ADAPTER = {installInPlace: true,isProjectActive: () => true,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,};const MAIN_MODEL_TYPES: ['main'] = ['main'];diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsxindex f8aaa08fd2..0c4b09345d 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx@@ -105,6 +105,7 @@ export const ModelSelect = ({installAction = false,invalid,isClearable = false,+ missingLabel,modelTypes,onChange,onOpen,@@ -130,6 +131,11 @@ export const ModelSelect = ({installAction?: boolean;invalid?: boolean;isClearable?: boolean;+ /**+ * Shown instead of the placeholder when `value` names a model the library does not hold (deleted since it was+ * saved), so a broken selection reads differently from an empty one; it stays clearable.+ */+ missingLabel?: string;modelTypes: readonly ModelTaxonomyType[];onChange: (model: ModelConfig | null) => void;/** Called as the picker opens, e.g. to load what `filter` reads. */@@ -271,6 +277,9 @@ export const ModelSelect = ({onPickerClose?.();};const canClear = isClearable && Boolean(value);+ // A model whose files are gone is listed but cannot be used: where a label is given, it shows that instead.+ const missingText =+ value && loadStatus === 'loaded' && (!selectedModel || selectedModel.is_missing) ? missingLabel : undefined;const renderOption = useCallback((model: ModelConfig, state: PickerOptionState) => (@@ -354,19 +363,21 @@ export const ModelSelect = ({}}>{insideLabel ? <FieldInsideLabel label={insideLabel} /> : null}- {selectedModel ? (+ {selectedModel && !missingText ? (<ModelButtonContent id={valueTextId} isEndAligned={Boolean(insideLabel)} model={selectedModel} />) : (<Textas="span"id={valueTextId}- color="fg.muted"+ color={missingText ? 'fg.warning' : 'fg.muted'}flex={insideLabel ? '1' : undefined}minW="0"textAlign={insideLabel ? 'end' : undefined}+ title={missingText}truncate>- {isEmpty ? emptyMessage : (placeholder ?? t('models.scopeSelect', { scope: scopeLabel }))}+ {missingText ??+ (isEmpty ? emptyMessage : (placeholder ?? t('models.scopeSelect', { scope: scopeLabel })))}</Text>)}{canClear || isEmpty ? null : <Icon as={ChevronDownIcon} boxSize="3" flexShrink={0} />}diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.browser.test.tsxindex 49fb169dc2..9cdc05cc61 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.browser.test.tsx@@ -1,7 +1,18 @@+import type { ModelConfig, ModelTaxonomyType } from '@features/models/core/types';import type * as ModelsApi from '@features/models/data/api';+import type {+ DefaultComponentPruner,+ DefaultComponentSlotPolicy,+ DefaultComponentSlotReader,+ ModelDefaultsRulesSource,+ ModelDefaultsRulesState,+ ModelsUiAdapter,+} from '@features/models/ui/ModelsUiContext';import { ChakraProvider } from '@chakra-ui/react';import { getFp8StorageSupportSnapshot } from '@features/models/data/fp8StorageSupportStore';+import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';+import { ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';import { act } from 'react';@@ -200,3 +211,418 @@ describe('DefaultSettingsSection FP8 Storage row', () => {expect(api.getFp8StorageSupport).toHaveBeenCalledTimes(1);});});++describe('DefaultSettingsSection default components', () => {+ let host: HTMLDivElement;+ let root: Root;++ const component = (key: string, name: string, type: string) => ({ base: 'any', key, name, type }) as ModelConfig;+ const catalog = [+ component('t5-a', 'T5 A', 't5_encoder'),+ component('t5-b', 'T5 B', 't5_encoder'),+ component('qwen3-a', 'Qwen3 A', 'qwen3_encoder'),+ component('tower-a', 'Tower A', 'qwen3_vl_vision_tower'),+ { ...component('flux2-vae', 'FLUX.2 VAE', 'vae'), base: 'flux2' },+ { ...component('sdxl-vae', 'SDXL VAE', 'vae'), base: 'sdxl' },+ { ...component('moss-vae', 'MOSS VAE', 'vae'), base: 'moss-image' },+ ];+ // The `vae.accepted` bases of the served rows these tests read: MOSS-Image decodes with FLUX.2's VAE as well as+ // its own; a row without the facet accepts its own base only. The real rule is covered beside the reader.+ const ACCEPTED_VAE_BASES: Record<string, string[]> = { 'moss-image': ['flux2', 'moss-image'] };+ const acceptsDefaultVae: Extract<ModelDefaultsRulesState, { status: 'ready' }>['acceptsDefaultVae'] = (+ model,+ candidate+ ) => (ACCEPTED_VAE_BASES[String(model.base)] ?? [String(model.base)]).includes(String(candidate.base));+ const slot = (persistenceKey: string, label: string, type: string): DefaultComponentSlotPolicy => ({+ filter: (candidate) => candidate.type === type,+ label,+ modelTypes: [type as ModelTaxonomyType],+ persistenceKey,+ });+ // Generation's rules are the app's to supply; this stands in for them with a family whose vision tower is offered+ // only beside a Qwen3 encoder, and whose PiD decoder has no installed model.+ const readComponentSlots: DefaultComponentSlotReader = (_model, components) => [+ slot('t5_encoder', 'T5 Encoder', 't5_encoder'),+ slot('qwen3_vl_encoder', 'Qwen3 Encoder', 'qwen3_encoder'),+ ...(components.qwen3_vl_encoder ? [slot('qwen3_vl_vision_tower', 'Vision Tower', 'qwen3_vl_vision_tower')] : []),+ slot('pid_decoder', 'PiD Decoder', 'pid_decoder'),+ ];+ // The tower goes with the encoder it hangs on, as Generate's rules prune it.+ const pruneComponents: DefaultComponentPruner = (_model, components) =>+ Object.fromEntries(+ Object.entries(components).filter(([key]) => key !== 'qwen3_vl_vision_tower' || components.qwen3_vl_encoder)+ );+ const readyState: ModelDefaultsRulesState = {+ acceptsDefaultVae,+ pruneComponents,+ usesDefaultVae: (model) => model.format !== 'sdnq_quantized',+ read: () => ({ appliesToGraph: false, defaultValue: 'euler', options: [] }),+ readComponentSlots,+ status: 'ready',+ };+ /** A rules source whose state a test moves, as the lazy loader does. */+ const createSource = (initial: ModelDefaultsRulesState) => {+ let state = initial;+ const listeners = new Set<() => void>();+ const source: ModelDefaultsRulesSource = {+ getSnapshot: () => state,+ load: () => undefined,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };++ return {+ set: (next: ModelDefaultsRulesState) => {+ state = next;+ listeners.forEach((listener) => listener());+ },+ source,+ };+ };+ const adapterFor = (source: ModelDefaultsRulesSource): ModelsUiAdapter => ({+ canManageModels: true,+ defaultsRules: source,+ enableModelDescriptions: true,+ installInPlace: true,+ isProjectActive: () => true,+ managerProjectId: null,+ setInstallInPlace: () => undefined,+ });+ const readyAdapter = adapterFor(createSource(readyState).source);+ const unavailableAdapter = adapterFor(NO_DEFAULTS_RULES);++ const render = async (model: DefaultSettingsModel, uiAdapter: ModelsUiAdapter = readyAdapter) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <ModelsUiProvider adapter={uiAdapter}>+ <DefaultSettingsSection model={model} onError={vi.fn()} onSaved={vi.fn()} />+ </ModelsUiProvider>+ </ChakraProvider>+ );+ });+ await act(async () => {+ await Promise.resolve();+ });+ };++ /** The picker's trigger, found from the slot's label. */+ const pickerOf = (label: string): HTMLElement => {+ let node: HTMLElement | null =+ [...host.querySelectorAll<HTMLElement>('label, span, p')].find((candidate) => candidate.textContent === label) ??+ null;++ while (node && !node.querySelector('[aria-haspopup="listbox"]')) {+ node = node.parentElement;+ }++ return node!.querySelector<HTMLElement>('[aria-haspopup="listbox"]')!;+ };+ const choose = async (label: string, name: string) => {+ await act(() => pickerOf(label).click());+ await expect.poll(() => document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);+ await act(() =>+ [...document.querySelectorAll<HTMLElement>('[role="option"]')]+ .find((option) => option.textContent?.includes(name))!+ .click()+ );+ };+ const clear = (label: string) =>+ act(() => {+ let node: HTMLElement | null = pickerOf(label);++ while (node && !node.querySelector('[aria-label="models.clearSelectedModel"]')) {+ node = node.parentElement;+ }+ node!.querySelector<HTMLElement>('[aria-label="models.clearSelectedModel"]')!.click();+ });+ const saveButton = () =>+ [...host.querySelectorAll('button')].find((candidate) => candidate.textContent === 'models.saveDefaults')!;+ const save = async () => {+ await act(async () => {+ saveButton().click();+ await Promise.resolve();+ });+ };+ const savedDefaults = () => api.updateModel.mock.calls[0]?.[1]?.default_settings;++ beforeEach(() => {+ api.getFp8StorageSupport.mockReset();+ api.getFp8StorageSupport.mockResolvedValue([]);+ api.updateModel.mockReset();+ api.updateModel.mockImplementation((_key, body) => Promise.resolve({ ...settingsModel({}), ...body }));+ accountLifecycle.activate('default-components-test', ':user:default-components-test');+ setModelsSnapshotForTests({ error: null, models: catalog, status: 'loaded' });+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ document.querySelectorAll('[data-scope="popover"]').forEach((element) => element.remove());+ setModelsSnapshotForTests({ error: null, models: [], status: 'idle' });+ accountLifecycle.invalidate();+ });++ it('offers a picker for each component slot with a candidate and saves the choice under its slot name', async () => {+ await render(settingsModel({}));++ expect(labels(host)).toEqual(expect.arrayContaining(['T5 Encoder', 'Qwen3 Encoder']));+ // Nothing installed fills the PiD decoder, so it stays out of the way.+ expect(labels(host)).not.toContain('PiD Decoder');++ await choose('T5 Encoder', 'T5 B');+ await save();++ expect(savedDefaults()).toMatchObject({ components: { t5_encoder: 't5-b' } });+ });++ it('keeps a slot that holds a value, even one nothing installed can fill, so it can be cleared', async () => {+ await render(settingsModel({ default_settings: { components: { pid_decoder: 'gone' } } }));+ await clear('PiD Decoder');+ await save();++ expect(savedDefaults().components).toBeNull();+ });++ describe('a default whose file is missing', () => {+ const gone = { ...component('t5-gone', 'T5 Gone', 't5_encoder'), is_missing: true } as ModelConfig;++ beforeEach(() => {+ setModelsSnapshotForTests({ error: null, models: [...catalog, gone], status: 'loaded' });+ });++ it('is not offered as a new choice', async () => {+ await render(settingsModel({}));+ await act(() => pickerOf('T5 Encoder').click());+ await expect.poll(() => document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);++ const options = [...document.querySelectorAll('[role="option"]')].map((option) => option.textContent ?? '');++ expect(options.some((text) => text.includes('T5 A'))).toBe(true);+ expect(options.some((text) => text.includes('T5 Gone'))).toBe(false);+ });++ it('leaves a slot out when only missing models could fill it', async () => {+ setModelsSnapshotForTests({+ error: null,+ models: [...catalog.filter((candidate) => candidate.type !== 't5_encoder'), gone],+ status: 'loaded',+ });+ await render(settingsModel({}));++ expect(labels(host)).not.toContain('T5 Encoder');+ });++ it('is labelled by its name when it is the saved one, and can be cleared', async () => {+ await render(settingsModel({ default_settings: { components: { t5_encoder: gone.key } } }));++ expect(pickerOf('T5 Encoder').textContent).toContain('models.missingModelKey:T5 Gone');++ await clear('T5 Encoder');+ await save();++ expect(savedDefaults()).toHaveProperty('components', null);+ });+ });++ it("judges the slots by the catalog's record of the model, not the fields this section projects", async () => {+ const read = vi.fn(readComponentSlots);+ const main = { ...component('model-key', 'Main', 'main'), base: 'wan', expert: 'high' } as unknown as ModelConfig;+ setModelsSnapshotForTests({ error: null, models: [...catalog, main], status: 'loaded' });++ await render(+ settingsModel({ base: 'wan' }),+ adapterFor(createSource({ ...readyState, readComponentSlots: read }).source)+ );++ expect(read).toHaveBeenCalled();+ expect(read.mock.calls.at(-1)![0]).toMatchObject({ expert: 'high' });+ });++ describe('clearing a slot', () => {+ it('removes it from the stored map and keeps the others', async () => {+ await render(+ settingsModel({ default_settings: { components: { qwen3_vl_encoder: 'qwen3-a', t5_encoder: 't5-a' } } })+ );+ await clear('T5 Encoder');+ await save();++ expect(savedDefaults().components).toEqual({ qwen3_vl_encoder: 'qwen3-a' });+ });++ it('stores no map once the last slot is cleared', async () => {+ await render(settingsModel({ default_settings: { components: { t5_encoder: 't5-a' } } }));+ await clear('T5 Encoder');+ await save();++ expect(savedDefaults().components).toBeNull();+ });++ it('says a stored component that is no longer installed is missing, with its key, and clears it', async () => {+ await render(settingsModel({ default_settings: { components: { t5_encoder: 'deleted-t5' } } }));++ expect(host.textContent).toContain('models.missingModelKey:deleted-t5');++ await clear('T5 Encoder');+ await save();++ expect(savedDefaults()).toHaveProperty('components', null);+ });++ it('takes the dependent slot of a missing encoder along when the encoder is cleared', async () => {+ await render(+ settingsModel({+ default_settings: { components: { qwen3_vl_encoder: 'deleted-encoder', qwen3_vl_vision_tower: 'tower-a' } },+ })+ );+ await clear('Qwen3 Encoder');+ await save();++ expect(savedDefaults()).toHaveProperty('components', null);+ });++ it('takes a dependent slot along when the slot it hangs on is cleared', async () => {+ await render(+ settingsModel({+ default_settings: { components: { qwen3_vl_encoder: 'qwen3-a', qwen3_vl_vision_tower: 'tower-a' } },+ })+ );+ expect(labels(host)).toContain('Vision Tower');++ await clear('Qwen3 Encoder');+ await save();++ expect(savedDefaults().components).toBeNull();+ });+ });++ it('keeps a stored key for a slot this version does not offer through an unrelated edit', async () => {+ // Deliberate: another version or client may know slots this one does not, and an edit elsewhere must not drop them.+ await render(settingsModel({ default_settings: { components: { t5_encoder: 't5-a', unknown_slot: 'x' } } }));+ await choose('T5 Encoder', 'T5 B');+ await save();++ expect(savedDefaults().components).toEqual({ t5_encoder: 't5-b', unknown_slot: 'x' });+ });++ it('is clean again when the choice is put back to the saved one', async () => {+ await render(settingsModel({ default_settings: { components: { t5_encoder: 't5-a' } } }));+ expect(saveButton().disabled).toBe(true);++ await choose('T5 Encoder', 'T5 B');+ expect(saveButton().disabled).toBe(false);++ await choose('T5 Encoder', 'T5 A');+ expect(saveButton().disabled).toBe(true);+ });++ it('is clean after a save', async () => {+ await render(settingsModel({}));+ await choose('T5 Encoder', 'T5 B');+ await save();++ expect(api.updateModel).toHaveBeenCalledTimes(1);+ expect(saveButton().disabled).toBe(true);+ });++ it('shows no group while the rules are unavailable, and still saves the stored components with other edits', async () => {+ await render(settingsModel({ default_settings: { components: { t5_encoder: 't5-a' } } }), unavailableAdapter);++ expect(labels(host)).not.toContain('models.defaultComponents');++ const stepsSwitch = [...host.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')].find((input) =>+ input.closest('div')?.textContent?.includes('models.defaultFields.steps')+ );+ await act(async () => {+ stepsSwitch!.click();+ await Promise.resolve();+ });+ await save();++ expect(savedDefaults()).toMatchObject({ components: { t5_encoder: 't5-a' }, steps: 30 });+ });++ it('shows the pickers once the rules arrive', async () => {+ const rules = createSource({ status: 'unavailable' });++ await render(settingsModel({}), adapterFor(rules.source));+ expect(labels(host)).not.toContain('T5 Encoder');++ await act(() => rules.set(readyState));++ expect(labels(host)).toContain('T5 Encoder');+ });++ describe('the default VAE picker', () => {+ const mossModel = settingsModel({ base: 'moss-image', default_settings: { vae: 'default' } });+ const offeredVaes = async () => {+ await act(() => pickerOf('models.defaultFields.vae').click());+ await expect.poll(() => document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);++ return [...document.querySelectorAll('[role="option"]')].map((option) => option.textContent ?? '');+ };++ it('offers the VAEs Generate accepts for the model, whatever their base, and not the ones it rejects', async () => {+ await render(mossModel);+ const offered = (await offeredVaes()).join('|');++ expect(offered).toContain('FLUX.2 VAE');+ expect(offered).toContain('MOSS VAE');+ expect(offered).not.toContain('SDXL VAE');+ });++ it('offers no replacement until the rules arrive, while the stored VAE stays visible and clearable', async () => {+ await render(settingsModel({ base: 'moss-image', default_settings: { vae: 'moss-vae' } }), unavailableAdapter);++ expect(host.textContent).toContain('MOSS VAE');+ expect((await offeredVaes()).join('|')).not.toContain('FLUX.2 VAE');+ await act(() => document.body.click());+ await clear('models.defaultFields.vae');+ await save();++ expect(savedDefaults().vae).toBe('default');+ });++ it('offers no default VAE for a model whose graph decodes with its own VAE', async () => {+ await render(settingsModel({ base: 'flux', default_settings: { vae: 'flux2-vae' }, format: 'sdnq_quantized' }));++ expect(labels(host)).not.toContain('models.defaultFields.vae');+ expect(labels(host)).toContain('models.defaultFields.steps');+ });++ it('does not offer a VAE whose files are missing, and names a stored one by its name', async () => {+ const goneVae = { ...component('gone-vae', 'Gone VAE', 'vae'), base: 'flux2', is_missing: true } as ModelConfig;+ setModelsSnapshotForTests({ error: null, models: [...catalog, goneVae], status: 'loaded' });++ await render(mossModel);+ expect((await offeredVaes()).join('|')).not.toContain('Gone VAE');++ await act(() => root.unmount());+ host.remove();+ await render(settingsModel({ base: 'moss-image', default_settings: { vae: goneVae.key } }));+ expect(host.textContent).toContain('models.missingModelKey:Gone VAE');+ });++ it('says a stored VAE that is no longer installed is missing, with its key', async () => {+ await render(settingsModel({ base: 'moss-image', default_settings: { vae: 'deleted-vae' } }));++ expect(host.textContent).toContain('models.missingModelKey:deleted-vae');+ });++ it('keeps a stored default VAE the rule no longer accepts, so it can be cleared', async () => {+ await render(settingsModel({ base: 'moss-image', default_settings: { vae: 'sdxl-vae' } }));++ expect(host.textContent).toContain('SDXL VAE');+ await clear('models.defaultFields.vae');+ await save();++ expect(savedDefaults().vae).toBe('default');+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsxindex 95b26d6ec6..79e78976c6 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx@@ -1,15 +1,16 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { AnyModelDefaultSettings } from '@features/models/core/types';-import type { SchedulerPolicyState } from '@features/models/ui/ModelsUiContext';+import type { AnyModelDefaultSettings, ModelConfig } from '@features/models/core/types';+import type { DefaultComponentSlotPolicy, ModelDefaultsRulesState } from '@features/models/ui/ModelsUiContext';import { createListCollection, Grid, HStack, Icon, NumberInput, Stack, Switch, Text } from '@chakra-ui/react';+import { hasModelPickerCandidates } from '@features/models/core/library';import { updateModel } from '@features/models/data/api';import {ensureFp8StorageSupportLoaded,isFp8StorageSupported,useFp8StorageSupportSelector,} from '@features/models/data/fp8StorageSupportStore';-import { replaceModelInStore } from '@features/models/data/modelsStore';+import { replaceModelInStore, useModelsSelector } from '@features/models/data/modelsStore';import { ModelSelect } from '@features/models/ui/components/ModelSelect';import {applyModelDraftFields,@@ -28,6 +29,7 @@ import { useMountEffect } from '@platform/react/useMountEffect';import { useScopedAction } from '@platform/react/useScopedAction';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';import { Button, Combobox, FieldLabel, Panel, Select } from '@platform/ui';+import { Field } from '@platform/ui/Field';import { MoveHorizontalIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState, useSyncExternalStore } from 'react';import { useTranslation } from 'react-i18next';@@ -43,14 +45,17 @@ import { DraftConflictNotice, UnsavedChangesLabel } from './ModelDraftNotices';*/const EMPTY_SETTINGS: AnyModelDefaultSettings = {};+const EMPTY_COMPONENTS: Readonly<Record<string, string>> = {};+const EMPTY_CATALOG: readonly ModelConfig[] = [];+const EMPTY_SLOTS: readonly DefaultComponentSlotPolicy[] = [];const selectDefaultsDraft = (draft: ModelDraft | undefined) => draft?.defaults;interface FieldControlProps {+ /** Generate's VAE rule for the edited model; absent until the rules arrive. */+ acceptsVae: ((candidate: ModelConfig) => boolean) | null;control: DefaultSettingsControl;disabled: boolean;label: string;- /** Base of the model being edited, for same-base model pickers. */- modelBase: string;/** Key of the model being edited; its links rank the model pickers. */modelKey: string;setValue: (value: unknown) => void;@@ -61,8 +66,33 @@ interface FieldControlProps {const buildCollection = (options: readonly string[]) =>createListCollection({ items: options.map((option) => ({ label: option, value: option })) });-const FieldControl = ({ control, disabled, label, modelBase, modelKey, setValue, value }: FieldControlProps) => {+/** Names a stored default whose file is gone (or which is no longer registered), so the user can replace or clear it. */+const useMissingModelLabel = () => {const { t } = useTranslation();+ const modelsByKey = useModelsSelector((snapshot) => snapshot.modelsByKey);++ return useCallback(+ (storedKey: string | undefined) =>+ t('models.missingModelKey', {+ key: storedKey === undefined ? '' : (modelsByKey.get(storedKey)?.name ?? storedKey),+ }),+ [modelsByKey, t]+ );+};++const FieldControl = ({ acceptsVae, control, disabled, label, modelKey, setValue, value }: FieldControlProps) => {+ const { t } = useTranslation();+ const getMissingLabel = useMissingModelLabel();+ const storedKey = typeof value === 'string' && value !== 'default' ? value : null;+ // A model whose files are gone is never a new choice: the default would be skipped when it applies.+ const vaeFilter = useCallback(+ (candidate: ModelConfig) =>+ !candidate.is_missing &&+ (control.kind !== 'model' ||+ !control.generateVaeRule ||+ (acceptsVae ? acceptsVae(candidate) : storedKey === null || candidate.key === storedKey)),+ [acceptsVae, control, storedKey]+ );const selectCollection = useMemo(() => (control.kind === 'select' ? buildCollection(control.options) : null),[control]@@ -139,18 +169,23 @@ const FieldControl = ({ control, disabled, label, modelBase, modelKey, setValue,}if (control.kind === 'model') {+ const isRulesPending = control.generateVaeRule && !acceptsVae;+return (<ModelSelect- disabled={disabled}- filter={(candidate) => !control.sameBase || String(candidate.base) === modelBase}+ // Until Generate's rules arrive no replacement is offered, since the model's own base is not always the+ // base its VAE must have: the picker is off, and a stored VAE stays visible and clearable.+ disabled={disabled || (isRulesPending && storedKey === null)}+ filter={vaeFilter}isClearable+ missingLabel={storedKey ? getMissingLabel(storedKey) : undefined}modelTypes={control.modelTypes}placeholder={t(control.placeholderKey)}relatedTo={modelKey}showManagerButton={false}size="lg"- // The 'default' sentinel renders as the placeholder: the toggle is on but no specific model is pinned.- value={typeof value === 'string' && value !== 'default' ? value : null}+ // The default sentinel renders as the placeholder: the toggle is on but no specific model is pinned.+ value={storedKey}onChange={(selected) => setValue(selected ? selected.key : 'default')}/>);@@ -176,42 +211,42 @@ export const DefaultSettingsSection = ({});const fp8StorageSupported = useFp8StorageSupportSelector((snapshot) => isFp8StorageSupported(snapshot, model));// Generate's scheduler rules load with the section, as the FP8 answer does; the row shows disabled until they do.- const { schedulerPolicy: schedulerPolicySource } = useModelsUi();+ const { defaultsRules: defaultsRulesSource } = useModelsUi();useMountEffect(() => {- schedulerPolicySource.load();+ defaultsRulesSource.load();});- const schedulerPolicyState = useSyncExternalStore(- schedulerPolicySource.subscribe,- schedulerPolicySource.getSnapshot,- schedulerPolicySource.getSnapshot+ const defaultsRulesState = useSyncExternalStore(+ defaultsRulesSource.subscribe,+ defaultsRulesSource.getSnapshot,+ defaultsRulesSource.getSnapshot);const schedulerRules = useMemo((): SchedulerFieldRules | null => {if (model.type !== 'main') {return null;}- return schedulerPolicyState.status === 'ready'- ? schedulerPolicyState.read(model, model.default_settings?.scheduler ?? null)- : schedulerPolicyState.status;- }, [model, schedulerPolicyState]);+ return defaultsRulesState.status === 'ready'+ ? defaultsRulesState.read(model, model.default_settings?.scheduler ?? null)+ : defaultsRulesState.status;+ }, [model, defaultsRulesState]);// The failure a retry started from. The retry is over once the rules arrive or a new failure replaces it, so a later// ordinary load (another account, say) shows the plain loading text rather than "Retrying…".- const [retriedFailure, setRetriedFailure] = useState<SchedulerPolicyState | null>(null);+ const [retriedFailure, setRetriedFailure] = useState<ModelDefaultsRulesState | null>(null);if (retriedFailure &&- (schedulerPolicyState.status === 'ready' ||- (schedulerPolicyState.status === 'unavailable' && schedulerPolicyState !== retriedFailure))+ (defaultsRulesState.status === 'ready' ||+ (defaultsRulesState.status === 'unavailable' && defaultsRulesState !== retriedFailure))) {setRetriedFailure(null);}- const isRetryingSchedulerRules = retriedFailure !== null;+ const isRetryingDefaultsRules = retriedFailure !== null;const schedulerSwitchRef = useRef<HTMLInputElement | null>(null);const headingRef = useRef<HTMLDivElement | null>(null);- const retrySchedulerRules = () => {- if (schedulerPolicyState.status !== 'unavailable') {+ const retryDefaultsRules = () => {+ if (defaultsRulesState.status !== 'unavailable') {return;}- setRetriedFailure(schedulerPolicyState);- schedulerPolicySource.load();+ setRetriedFailure(defaultsRulesState);+ defaultsRulesSource.load();};// When a retry succeeds the Retry button leaves with the note; hand the focus it held to the scheduler row, or to the// section heading when the base ignores the scheduler and the whole row left with it.@@ -230,9 +265,22 @@ export const DefaultSettingsSection = ({});};}, []);+ const acceptsVae = useMemo(+ () =>+ defaultsRulesState.status === 'ready'+ ? (candidate: ModelConfig) => defaultsRulesState.acceptsDefaultVae(model, candidate)+ : null,+ [defaultsRulesState, model]+ );+ // A model whose graph loads no VAE of its own pick (a self-contained pipeline) has no default VAE to set.+ const hidesVae =+ model.type === 'main' && defaultsRulesState.status === 'ready' && !defaultsRulesState.usesDefaultVae(model);const fields = useMemo(- () => getFieldsForModel(model, fp8StorageSupported, schedulerRules),- [fp8StorageSupported, model, schedulerRules]+ () =>+ getFieldsForModel(model, fp8StorageSupported, schedulerRules).filter(+ (field) => !(hidesVae && field.key === 'vae')+ ),+ [fp8StorageSupported, hidesVae, model, schedulerRules]);const saved = model.default_settings ?? EMPTY_SETTINGS;const draft = useModelDraft(model.key, selectDefaultsDraft);@@ -248,6 +296,66 @@ export const DefaultSettingsSection = ({setError(null);};+ // The component slots of the model's family, which depend on the components chosen so far. Only a main model has+ // any, so the others do not follow the catalog.+ const isMain = model.type === 'main';+ const catalog = useModelsSelector((snapshot) => (isMain ? snapshot.models : EMPTY_CATALOG));+ const isCatalogLoaded = useModelsSelector((snapshot) => snapshot.status === 'loaded');+ const storedComponents = settings.components ?? EMPTY_COMPONENTS;+ // Generate's component rules read more of the model than the fields projected for this section (a Wan expert tag,+ // say), so they judge the catalog's own record.+ const catalogModel = useMemo(+ () => catalog.find((candidate) => candidate.key === model.key) ?? model,+ [catalog, model]+ );+ const componentSlots = useMemo(+ () =>+ isMain && defaultsRulesState.status === 'ready'+ ? defaultsRulesState.readComponentSlots(catalogModel, storedComponents, catalog)+ : null,+ [catalog, catalogModel, defaultsRulesState, isMain, storedComponents]+ );+ // The group shows once the rules are ready. A slot nothing installed can fill stays out of the way, unless it holds+ // a value (even a dangling one), which must stay clearable. The status of the rules is the scheduler row's to show.+ // A model whose files are gone is never a new choice, nor a reason to show a slot: the default would be skipped.+ const visibleComponentSlots = useMemo(+ () =>+ (componentSlots ?? EMPTY_SLOTS)+ .map((slot) => ({+ ...slot,+ filter: (candidate: ModelConfig) => !candidate.is_missing && slot.filter(candidate),+ }))+ .filter(+ (slot) =>+ storedComponents[slot.persistenceKey] !== undefined ||+ !isCatalogLoaded ||+ hasModelPickerCandidates(catalog, { filter: slot.filter, modelTypes: slot.modelTypes })+ ),+ [catalog, componentSlots, isCatalogLoaded, storedComponents]+ );+ const getMissingLabel = useMissingModelLabel();++ // An empty map is stored as null, which the backend and the draft read as "no defaults".+ const setComponent = (persistenceKey: string, modelKey: string | null) => {+ if (defaultsRulesState.status !== 'ready') {+ return;+ }++ const next = { ...storedComponents };++ if (modelKey) {+ next[persistenceKey] = modelKey;+ } else {+ delete next[persistenceKey];+ }++ // A slot this change closes (the vision tower once its encoder is cleared, even a missing one) leaves no hidden+ // default behind; a key for a slot this client does not know stays, since another version or client may.+ const kept = defaultsRulesState.pruneComponents(catalogModel, next, catalog);++ setFieldValue('components', Object.keys(kept).length > 0 ? kept : null);+ };+const handleReset = () => {discardModelDraft(model.key, 'defaults');setError(null);@@ -343,13 +451,13 @@ export const DefaultSettingsSection = ({control={field.control}disabled={!isEnabled || field.pending !== undefined}label={t(field.labelKey)}- modelBase={String(model.base)}+ acceptsVae={acceptsVae}modelKey={model.key}setValue={(nextValue) => setFieldValue(field.key, nextValue)}value={isEnabled ? value : field.defaultValue}/>) : null}- {field.pending === 'unavailable' || (field.pending === 'loading' && isRetryingSchedulerRules) ? (+ {field.pending === 'unavailable' || (field.pending === 'loading' && isRetryingDefaultsRules) ? (// One Retry button across the failure and the retry's load, so the focus it holds stays put.<HStack gap="2" justify="space-between" role={field.pending === 'unavailable' ? 'alert' : 'status'}><Text color={field.pending === 'unavailable' ? 'fg.warning' : 'fg.subtle'} fontSize="xs">@@ -364,7 +472,7 @@ export const DefaultSettingsSection = ({aria-disabled={field.pending === 'loading'}size="xs"variant="outline"- onClick={retrySchedulerRules}+ onClick={retryDefaultsRules}>{field.pending === 'loading' ? t('models.schedulerListRetrying') : t('common.retry')}</Button>@@ -382,6 +490,37 @@ export const DefaultSettingsSection = ({);})}</Grid>+ {visibleComponentSlots.length > 0 ? (+ <Stack gap="2">+ <Stack gap="0.5">+ <FieldLabel>{t('models.defaultComponents')}</FieldLabel>+ <Text color="fg.subtle" fontSize="xs">+ {t('models.defaultComponentsHelp')}+ </Text>+ </Stack>+ <Grid gap="2.5" templateColumns="repeat(auto-fill, minmax(13rem, 1fr))">+ {visibleComponentSlots.map((slot) => (+ <Panel key={slot.persistenceKey} gap="2" p="2.5" tone="surface">+ <Field helpText={slot.helpText} label={slot.label}>+ <ModelSelect+ filter={slot.filter}+ id={`default-component-${slot.persistenceKey}`}+ isClearable+ missingLabel={getMissingLabel(storedComponents[slot.persistenceKey])}+ modelTypes={slot.modelTypes}+ placeholder={t('models.defaultComponentsNone')}+ relatedTo={model.key}+ showManagerButton={false}+ size="lg"+ value={storedComponents[slot.persistenceKey] ?? null}+ onChange={(selected) => setComponent(slot.persistenceKey, selected?.key ?? null)}+ />+ </Field>+ </Panel>+ ))}+ </Grid>+ </Stack>+ ) : null}</Stack>);};diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.browser.test.tsxindex a95218b825..4f428404da 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.browser.test.tsx@@ -2,7 +2,7 @@ import type { ModelConfig } from '@features/models/core/types';import { ChakraProvider } from '@chakra-ui/react';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';-import { type ModelsUiAdapter, ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { type ModelsUiAdapter, ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';import { act } from 'react';@@ -70,7 +70,7 @@ const MANAGER: ModelsUiAdapter = {installInPlace: true,isProjectActive: () => false,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,};diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxindex e88664aec5..e181aa36b8 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx@@ -144,13 +144,15 @@ const selectDefaultSettingsModel = (snapshot: ModelsSnapshot, modelKey: string):// `base` and `format` are projected too: together with the type they are the loader key the backend answers the FP8// Storage question on, and all three parts change the answer. `variant` joins them for Generate's scheduler rules,- // which differ by variant within a base.+ // which differ by variant within a base; `name` and `submodels` join them for its component rules.return model? {base: model.base,default_settings: model.default_settings,format: model.format,key: model.key,+ name: model.name,+ submodels: model.submodels,type: model.type,variant: model.variant,}diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsxindex 4f4b523bc8..753f12d0a1 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx@@ -5,7 +5,7 @@ import { ChakraProvider } from '@chakra-ui/react';import { architectureCapabilitiesFixture } from '@features/models/core/architectureCapabilities.testing';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';import { setRelationshipsSnapshotForTests } from '@features/models/data/relationshipsStore';-import { ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';import { system } from '@theme/system';@@ -60,7 +60,7 @@ const MODELS_UI_ADAPTER = {installInPlace: true,isProjectActive: () => true,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,};const SECTION_MODEL = { base: 'flux', key: 'flux-main', type: 'main' } as const;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tableDemand.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tableDemand.browser.test.tsxindex 47e0d97623..46216fa296 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tableDemand.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tableDemand.browser.test.tsx@@ -9,7 +9,7 @@ import type { ArchitectureCapabilitiesRow } from '@features/models/architecturesimport { ChakraProvider } from '@chakra-ui/react';import { getArchitectureCapabilitiesSnapshot } from '@features/models/data/architectureCapabilitiesStore';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';-import { ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';import { act } from 'react';@@ -49,7 +49,7 @@ const MODELS_UI_ADAPTER = {installInPlace: true,isProjectActive: () => true,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,};const SECTION_MODEL = { base: 'flux', key: 'flux-main', type: 'main' } as const;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsxindex d2ff535b4f..7dd8cd984d 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx@@ -4,7 +4,7 @@ import type { ModelConfig } from '@features/models/core/types';import { Input, Portal, Stack, Text } from '@chakra-ui/react';import { modelPathSchema } from '@features/models/core/schemas';import { updateModel } from '@features/models/data/api';-import { replaceModelInStore } from '@features/models/data/modelsStore';+import { refreshModels, replaceModelInStore } from '@features/models/data/modelsStore';import { useNotify } from '@features/models/ui/useModelsNotify';import { useScopedAction } from '@platform/react/useScopedAction';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';@@ -47,6 +47,8 @@ export const UpdatePathDialog = ({assertAccountScopeCurrent(owner);replaceModelInStore(updated);+ // The new path may or may not hold the files: the library checks again.+ void refreshModels();notify.success(t('models.pathUpdated'), model.name);onClose();},diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.tsindex e01ac07fb3..f76f80e37b 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts@@ -6,7 +6,7 @@ import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '@features/export type DefaultSettingsModel = Pick<ModelConfig,- 'base' | 'default_settings' | 'format' | 'key' | 'type' | 'variant'+ 'base' | 'default_settings' | 'format' | 'key' | 'name' | 'submodels' | 'type' | 'variant'>;const CONTROL_ADAPTER_TYPES = new Set(['controlnet', 't2i_adapter', 'control_lora']);@@ -38,8 +38,11 @@ export type DefaultSettingsControl =| {kind: 'model';modelTypes: readonly ModelTaxonomyType[];- /** Restrict candidates to the edited model's base. */- sameBase: boolean;+ /**+ * Candidates are the VAEs Generate accepts for the edited model, which can be of another base. Until Generate's+ * rules arrive none is offered, though a stored one stays visible and clearable.+ */+ generateVaeRule: boolean;/** Placeholder shown for the backend's 'default' sentinel. */placeholderKey: string;};@@ -72,7 +75,7 @@ const FP8_STORAGE_FIELD: FieldSpec = {};const VAE_FIELD: FieldSpec = {- control: { kind: 'model', modelTypes: ['vae'], placeholderKey: 'models.defaultVae', sameBase: true },+ control: { kind: 'model', modelTypes: ['vae'], generateVaeRule: true, placeholderKey: 'models.defaultVae' },// The backend sentinel for "the compatible default VAE" — what legacy writes when the toggle is on but no specific// model is picked.defaultValue: 'default',@@ -227,6 +230,7 @@ export const validateDefaults = (const result = mainDefaultSettingsSchema.safeParse({cfgRescaleMultiplier: settings.cfg_rescale_multiplier ?? null,cfgScale: settings.cfg_scale ?? null,+ components: settings.components ?? null,guidance: settings.guidance ?? null,height: settings.height ?? null,scheduler: settings.scheduler ?? null,diff --git a/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.attentionLoad.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.attentionLoad.browser.test.tsxindex 96fbe28f73..a5ce73195f 100644--- a/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.attentionLoad.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.attentionLoad.browser.test.tsx@@ -77,7 +77,7 @@ const ADAPTER: ModelsUiAdapter = {installInPlace: true,isProjectActive: () => false,managerProjectId: null,- schedulerPolicy: {+ defaultsRules: {getSnapshot: () => ({ status: 'loading' }),load: () => undefined,subscribe: () => () => undefined,diff --git a/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.browser.test.tsxindex 0b8df2935b..eea6248d38 100644--- a/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/launchpad/ModelsNotice.browser.test.tsx@@ -84,7 +84,7 @@ const adapter = (canManageModels: boolean): ModelsUiAdapter => ({installInPlace: true,isProjectActive: () => false,managerProjectId: null,- schedulerPolicy: {+ defaultsRules: {getSnapshot: () => ({ status: 'loading' }),load: () => undefined,subscribe: () => () => undefined,diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsxindex 764be26a73..25a51871e2 100644--- a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx@@ -2,7 +2,7 @@ import type { ModelConfig } from '@features/models/core/types';import { ChakraProvider } from '@chakra-ui/react';import { getModelsSnapshot, setModelsSnapshotForTests } from '@features/models/data/modelsStore';-import { type ModelsUiAdapter, ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { type ModelsUiAdapter, ModelsUiProvider, NO_DEFAULTS_RULES } from '@features/models/ui/ModelsUiContext';import { openModelDetail } from '@features/models/ui/uiStore';import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';@@ -63,7 +63,7 @@ describe('models DetailPane for a model installed before the probe recorded a fainstallInPlace: true,isProjectActive: () => true,managerProjectId: null,- schedulerPolicy: NO_SCHEDULER_POLICY,+ defaultsRules: NO_DEFAULTS_RULES,setInstallInPlace: () => undefined,});let host: HTMLDivElement;diff --git a/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.test.ts b/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.test.tsindex cbfec55692..b9003cbe63 100644--- a/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.test.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.test.ts@@ -67,6 +67,16 @@ describe('model drafts store', () => {expect(getModelDraft('m')).toBeUndefined();});+ it('compares default components by content, so a map edited back to the saved one is no edit', () => {+ const saved = { components: { t5_encoder: 'a' } };++ recordModelDraftFields('m', 'defaults', { components: { t5_encoder: 'b' } }, saved);+ expect(getModelDraft('m')?.defaults).toBeDefined();++ recordModelDraftFields('m', 'defaults', { components: { t5_encoder: 'a' } }, saved);+ expect(getModelDraft('m')).toBeUndefined();+ });+it('rebases untouched fields onto the server and flags only edited fields the server changed differently', () => {const draft = { baseline: { name: 'Server' }, fields: { name: 'Mine' } };diff --git a/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.ts b/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.tsindex 3ada55f759..02d4975f5d 100644--- a/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/modelDraftsStore.ts@@ -5,7 +5,7 @@ import { toExternalModelValues } from '@features/models/core/externalModelFieldsimport { getModelsSnapshot, subscribeModels } from '@features/models/data/modelsStore';import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createKeyedTransientStore } from '@platform/state/externalStore';-import { useExternalStoreSelector, type EqualityFn } from '@platform/state/selectors';+import { shallowEqual, useExternalStoreSelector, type EqualityFn } from '@platform/state/selectors';import { useCallback } from 'react';/** Unsaved model-detail edits per model, in memory for the account's lifetime in this tab, saves in flight included. */@@ -70,8 +70,9 @@ const SERVER_VALUES: Record<ModelDraftSurface, (model: ModelConfig) => object> =const FIELD_SURFACES = ['identity', 'defaults', 'external'] as const satisfies readonly ModelDraftSurface[];-// Unset and null are the same "no value" to the backend and to every form here.-const isSameValue = (left: unknown, right: unknown): boolean => Object.is(left ?? null, right ?? null);+// Unset and null are the same "no value" to the backend and to every form here. Shallow, so an edited map of default+// components (model keys by slot) that is back to the saved one stops being an edit.+const isSameValue = (left: unknown, right: unknown): boolean => shallowEqual(left ?? null, right ?? null);export const hasDraftFields = (draft: ModelFieldsDraft | undefined): boolean =>draft !== undefined && Object.keys(draft.fields).length > 0;diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.tsindex df737c8703..5781b5a637 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts@@ -25,7 +25,7 @@ export const appendReferenceImage = ({models: ModelConfig[];}): AppendReferenceImageResult => {const supportedModels = models.filter(isSupportedGenerateModel);- const currentValues = getCurrentGenerateValues({ generateValues, supportedModels });+ const currentValues = getCurrentGenerateValues({ generateValues, models, supportedModels });if (!currentValues) {return { status: 'unsupported' };diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.tsindex cfd2c59ddb..7ea6cbde93 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts@@ -1,10 +1,11 @@import type { GalleryImage } from '@features/gallery';import type * as GalleryBackendModule from '@features/gallery/data/backend';-import type { GenerateModelConfig } from '@features/generation/contracts';+import type { GenerateModelConfig, GenerateWidgetValues } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import type { WorkbenchCommands } from '@workbench/workbenchStore';import type { TFunction } from 'i18next';+import { getDefaultGenerateSettings } from '@features/generation/settings';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';import { QueryClient } from '@tanstack/react-query';@@ -487,6 +488,7 @@ describe('executeImageRecall', () => {// Initialised while the table is present, so only the recall itself is gated.const generateValues = getCurrentGenerateValues({generateValues: { modelKey: model.key },+ models: [model as GenerateModelConfig],supportedModels: [model as GenerateModelConfig],});@@ -818,6 +820,233 @@ describe('executeImageRecall', () => {expect(oldCommands.setSettings).not.toHaveBeenCalled();expect(oldCommands.add).not.toHaveBeenCalled();});++ describe('in a fresh project whose model stores default components', () => {+ const q21 = {+ base: 'qwen-image-2-1',+ default_settings: { components: { qwen3_vl_encoder: 'q21-encoder' } },+ format: 'diffusers',+ key: 'q21-main',+ name: 'Qwen-Image-2.1',+ type: 'main',+ variant: 'qwen_image_21_base',+ } as unknown as ModelConfig;+ const encoder = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'q21-encoder',+ name: 'External encoder',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ } as unknown as ModelConfig;+ const recallValues = async (+ kind: 'prompts' | 'remix',+ metadata: Record<string, unknown>,+ main: ModelConfig = q21,+ installed: ModelConfig[] = [q21, encoder]+ ) => {+ // The metadata is cached per image: each recall reads its own.+ queryClient.clear();+ const { commands, setSettings } = createCommands();++ galleryApi.galleryImages.metadata.mockResolvedValue(metadata);+ await executeImageRecall({+ queryClient,+ t,+ commands,+ // Never initialised: nothing but a model key, so the values are synthesised.+ getGenerateValues: () => ({ modelKey: main.key }),+ image,+ kind,+ models: installed,+ projectId: 'project-1',+ });++ return setSettings.mock.calls[0]![0] as GenerateWidgetValues;+ };+ const recallInto = async (kind: 'prompts' | 'remix', metadata: Record<string, unknown>) =>+ (await recallValues(kind, metadata)).qwen3VLEncoderModel;++ it('lets a remix of an image made with the bundled encoder keep the bundled one', async () => {+ await expect(+ recallInto('remix', { generation_mode: 'txt2img', model: { key: q21.key }, positive_prompt: 'bundled' })+ ).resolves.toBeNull();+ });++ it('keeps a component the image records as empty cleared, though the image names no model', async () => {+ await expect(recallInto('remix', { positive_prompt: 'no model', qwen3_vl_encoder: null })).resolves.toBeNull();+ });++ it('keeps a component source recorded as empty under its alias cleared', async () => {+ const source = {+ base: 'wan',+ format: 'diffusers',+ key: 'wan-source',+ name: 'Wan pipeline',+ type: 'main',+ variant: 't2v_a14b',+ } as unknown as ModelConfig;+ const wan = {+ base: 'wan',+ default_settings: { components: { component_source: source.key } },+ format: 'gguf_quantized',+ key: 'wan-main',+ name: 'Wan',+ type: 'main',+ variant: 't2v_a14b',+ } as unknown as ModelConfig;+ const installed = [wan, source];++ const filled = await recallValues('prompts', { positive_prompt: 'p' }, wan, installed);+ expect(filled.componentSourceModel?.key).toBe(source.key);++ const cleared = await recallValues('remix', { positive_prompt: 'p', wan_component_source: null }, wan, installed);+ expect(cleared.componentSourceModel).toBeNull();+ });++ it('fills the default for a slot whose recorded pick recall rejected', async () => {+ const qwen = (key: string, variant: string) =>+ ({+ base: 'any',+ format: 'checkpoint',+ key,+ name: key,+ type: 'qwen3_encoder',+ variant,+ }) as unknown as ModelConfig;+ const small = qwen('enc-06b', 'qwen3_06b');+ const fitting = qwen('enc-4b', 'qwen3_4b');+ const zImage = {+ base: 'z-image',+ default_settings: { components: { qwen3_encoder: fitting.key } },+ format: 'checkpoint',+ key: 'z-main',+ name: 'Z-Image',+ type: 'main',+ } as unknown as ModelConfig;++ const values = await recallValues('remix', { positive_prompt: 'p', qwen3_encoder: { key: small.key } }, zImage, [+ zImage,+ small,+ fitting,+ ]);++ expect(values.qwen3EncoderModel?.key).toBe(fitting.key);+ });++ it('lets a working default take the slot of a recorded pick whose files are missing', async () => {+ const qwen = (key: string, extra: Record<string, unknown> = {}) =>+ ({+ base: 'any',+ format: 'checkpoint',+ key,+ name: key,+ type: 'qwen3_encoder',+ variant: 'qwen3_4b',+ ...extra,+ }) as unknown as ModelConfig;+ const gone = qwen('enc-gone', { is_missing: true });+ const working = qwen('enc-working');+ const zImage = {+ base: 'z-image',+ default_settings: { components: { qwen3_encoder: working.key } },+ format: 'checkpoint',+ key: 'z-main',+ name: 'Z-Image',+ type: 'main',+ } as unknown as ModelConfig;++ const values = await recallValues('remix', { positive_prompt: 'p', qwen3_encoder: { key: gone.key } }, zImage, [+ zImage,+ gone,+ working,+ ]);++ expect(values.qwen3EncoderModel?.key).toBe(working.key);+ });++ it('leaves the default vision tower out when the image clears the encoder it hangs on', async () => {+ const tower = { ...encoder, key: 'q21-tower', name: 'Tower', type: 'qwen3_vl_vision_tower' } as ModelConfig;+ const withTower = {+ ...q21,+ default_settings: { components: { qwen3_vl_encoder: encoder.key, qwen3_vl_vision_tower: tower.key } },+ } as unknown as ModelConfig;+ const installed = [withTower, encoder, tower];++ const filled = await recallValues('remix', { positive_prompt: 'p' }, withTower, installed);+ expect(filled.qwen3VLVisionTowerModel?.key).toBe(tower.key);++ const cleared = await recallValues(+ 'remix',+ { positive_prompt: 'p', qwen3_vl_encoder: null },+ withTower,+ installed+ );+ expect(cleared.qwen3VLEncoderModel).toBeNull();+ expect(cleared.qwen3VLVisionTowerModel).toBeNull();+ });++ it('lets a working default VAE take the place of a recorded VAE whose files are missing', async () => {+ const vae = (key: string, extra: Record<string, unknown> = {}) =>+ ({ base: 'flux', format: 'checkpoint', key, name: key, type: 'vae', ...extra }) as unknown as ModelConfig;+ const gone = vae('flux-vae-gone', { is_missing: true });+ const working = vae('flux-vae-working');+ const flux = {+ base: 'flux',+ default_settings: { vae: working.key },+ format: 'checkpoint',+ key: 'flux-main',+ name: 'FLUX',+ type: 'main',+ } as unknown as ModelConfig;++ const values = await recallValues('remix', { positive_prompt: 'p', vae: { key: gone.key } }, flux, [+ flux,+ gone,+ working,+ ]);++ expect(values.vae?.key).toBe(working.key);+ });++ it('starts a fresh project on a selectable main model, not on a standalone branch the metadata could name', async () => {+ const make = (key: string, base: string, extra: Record<string, unknown> = {}) =>+ ({ base, format: 'checkpoint', key, name: key, type: 'main', ...extra }) as unknown as ModelConfig;+ const gone = make('gone', 'sdxl', { is_missing: true });+ const branch = make('branch', 'ideogram-4', { branch: 'unconditional' });+ const sdxl = make('sdxl-ok', 'sdxl');++ const values = await recallValues('remix', { positive_prompt: 'p' }, make('unset', 'sdxl'), [gone, branch, sdxl]);++ expect(values.model.key).toBe('sdxl-ok');+ // The two families default to different step counts, so the settings show which model they were built for.+ expect(getDefaultGenerateSettings(branch as never).steps).not.toBe(+ getDefaultGenerateSettings(sdxl as never).steps+ );+ expect(values.steps).toBe(getDefaultGenerateSettings(sdxl as never).steps);+ });++ it('keeps a VAE the image records as empty cleared', async () => {+ const vae = { base: 'flux', format: 'checkpoint', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' } as ModelConfig;+ const flux = {+ base: 'flux',+ default_settings: { vae: vae.key },+ format: 'checkpoint',+ key: 'flux-main',+ name: 'FLUX',+ type: 'main',+ } as unknown as ModelConfig;++ expect((await recallValues('prompts', { positive_prompt: 'p' }, flux, [flux, vae])).vae?.key).toBe(vae.key);+ expect((await recallValues('remix', { positive_prompt: 'p', vae: null }, flux, [flux, vae])).vae).toBeNull();+ });++ it('still fills the saved default when the recall does not touch the model', async () => {+ await expect(recallInto('prompts', { positive_prompt: 'prompt only' })).resolves.toMatchObject({+ key: encoder.key,+ });+ });+ });});const legacyIPAdapter = () => ({diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.tsindex c9537e86b9..f539ce59fd 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts@@ -1,5 +1,6 @@import type { GalleryImage } from '@features/gallery';import type {+ ComponentModelConfig,GenerateModelConfig,GenerateReferenceImage,GenerateWidgetValues,@@ -16,9 +17,11 @@ import {getCompatibleReferenceImages,getDefaultGenerateSettings,getEffectiveReferenceImage,+ getModelDefaultFills,isSupportedGenerateModel,isVaeModelConfig,normalizeGenerateWidgetValues,+ pickFallbackGenerateModel,} from '@features/generation/settings';import { hasArchitectureCapabilities } from '@features/models/architectures';import {@@ -257,9 +260,14 @@ export const getMissingGenerateValuesMessage = (t: TFunction): string =>export const getCurrentGenerateValues = ({generateValues,+ models,supportedModels,+ fillDefaults = true,}: {+ /** False for a recall that reads the image first: its model, not the fallback's, decides the defaults. */+ fillDefaults?: boolean;generateValues: Record<string, unknown>;+ models: readonly ComponentModelConfig[];supportedModels: GenerateModelConfig[];}) => {const normalizedValues = normalizeGenerateWidgetValues(generateValues);@@ -274,16 +282,23 @@ export const getCurrentGenerateValues = ({}const fallbackModelKey = typeof generateValues.modelKey === 'string' ? generateValues.modelKey : null;- const fallbackModel = supportedModels.find((model) => model.key === fallbackModelKey) ?? supportedModels[0];-- return fallbackModel- ? ({- ...getDefaultGenerateSettings(fallbackModel),- ...generateValues,- model: fallbackModel,- modelKey: fallbackModel.key,- } as GenerateWidgetValues)- : null;+ const fallbackModel =+ supportedModels.find((model) => model.key === fallbackModelKey) ?? pickFallbackGenerateModel(supportedModels);++ if (!fallbackModel) {+ return null;+ }++ const initial = {+ ...getDefaultGenerateSettings(fallbackModel),+ ...generateValues,+ model: fallbackModel,+ modelKey: fallbackModel.key,+ } as GenerateWidgetValues;++ // The model's default components and VAE fill in as they do when Generate itself picks the first model: once the+ // values persist with a model, nothing fills them again.+ return fillDefaults ? { ...initial, ...getModelDefaultFills(fallbackModel, initial, models) } : initial;};let canvasRecallHolder: { owner: AccountScope } | null = null;@@ -358,7 +373,16 @@ export const executeImageRecall = async ({return false;}- const readGenerateValues = () => getCurrentGenerateValues({ generateValues: getGenerateValues(), supportedModels });+ // A recall of the model reads the image before any default fills a slot, or it would take the default for a pick+ // the image never made.+ const recallsModel = kind === 'all' || kind === 'remix';+ const readGenerateValues = () =>+ getCurrentGenerateValues({+ fillDefaults: !recallsModel,+ generateValues: getGenerateValues(),+ models,+ supportedModels,+ });const missingValuesNotice = () =>commands.notifications.add({kind: 'info',@@ -492,6 +516,23 @@ export const executeImageRecall = async ({return false;}+ // An image that names no model leaves the fallback model of a fresh project, which takes its defaults after all,+ // but not for a slot recall set from the image (a pick, or an explicit empty one): those are held, and the+ // defaults resolve beside them, so a slot that hangs on a cleared one is not filled either. A pick recall rejected+ // leaves its slot to the default.+ if (recallsModel && !result.fields.includes('model') && !normalizeGenerateWidgetValues(getGenerateValues())) {+ // A recorded pick whose files are gone stays as recalled, like the main model, LoRAs and adapters of the image,+ // but does not hold its slot: a working default takes its place.+ const held = [...result.appliedComponents, ...(result.fields.includes('vae') ? (['vae'] as const) : [])].filter(+ (setting) => !result.values[setting]?.is_missing+ );++ result.values = {+ ...result.values,+ ...getModelDefaultFills(result.values.model, result.values, models, { held }),+ };+ }+if (result.fields.includes('referenceImages') && result.values.referenceImages.length > 0) {result.values.referenceImages = keepAvailableReferenceImages(result.values.referenceImages,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.tsindex 23d67b945a..0550a6ba33 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts@@ -165,6 +165,7 @@ describe('executeRecallParameters', () => {const initialised = () =>getCurrentGenerateValues({generateValues: { modelKey: sdxl.key },+ models: [sdxl as unknown as GenerateModelConfig],supportedModels: [sdxl as unknown as GenerateModelConfig],}) as unknown as Record<string, unknown> & { height: number; width: number };diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.tsindex f684fd1e5f..0e07fef493 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts@@ -104,7 +104,7 @@ export const executeRecallParameters = async ({return false;}- const currentValues = getCurrentGenerateValues({ generateValues, supportedModels });+ const currentValues = getCurrentGenerateValues({ generateValues, models, supportedModels });if (!currentValues) {commands.notifications.add({@@ -167,7 +167,7 @@ export const executeRecallParameters = async ({if (latestRaw === null || (canvasTarget && !canvasTarget.getProject())) {return false;}- const latest = getCurrentGenerateValues({ generateValues: latestRaw, supportedModels });+ const latest = getCurrentGenerateValues({ generateValues: latestRaw, models, supportedModels });if (!latest) {return false;}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex d0eb3bba67..9caa024ee3 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -1495,6 +1495,167 @@ describe('legacy records', () => {expect(result?.fields).toEqual(expect.arrayContaining(['components', 'vae']));});+ describe("the recalled model's default components", () => {+ const defaultT5: ComponentModelConfig = {+ base: 'any',+ key: 't5-default',+ name: 'Default T5',+ type: 't5_encoder',+ };+ const recordedT5: ComponentModelConfig = {+ base: 'any',+ hash: 'blake3:recorded',+ key: 't5-recorded',+ name: 'Recorded T5',+ type: 't5_encoder',+ };+ const defaultClip: ComponentModelConfig = {+ base: 'any',+ key: 'clip-default',+ name: 'Default CLIP',+ type: 'clip_embed',+ variant: 'large',+ };+ const withDefaults: MainModelConfig = {+ ...fluxModel,+ default_settings: { components: { clip_embed_model: defaultClip.key, t5_encoder: defaultT5.key } },+ key: 'flux-with-defaults',+ };+ const installed = [withDefaults, defaultT5, recordedT5, defaultClip];++ it('fills the slots the image recorded nothing for, and lets a recorded component win', () => {+ const result = recall(+ { model: { key: withDefaults.key }, t5_encoder: { ...recordedT5 } },+ { model: sdxlModel, modelKey: sdxlModel.key },+ [sdxlModel, withDefaults],+ installed+ );++ expect(result?.values.t5EncoderModel?.key).toBe(recordedT5.key);+ expect(result?.values.clipEmbedModel?.key).toBe(defaultClip.key);+ });++ it('replaces a current selection that fits when the image recorded nothing for the slot, like Reset', () => {+ const result = recall(+ { model: { key: withDefaults.key } },+ { model: withDefaults, modelKey: withDefaults.key, t5EncoderModel: recordedT5 },+ [sdxlModel, withDefaults],+ installed+ );++ expect(result?.values.t5EncoderModel?.key).toBe(defaultT5.key);+ });++ it('lets a component the image recorded as empty clear the default', () => {+ const result = recall(+ { model: { key: withDefaults.key }, t5_encoder: null },+ { model: sdxlModel, modelKey: sdxlModel.key },+ [sdxlModel, withDefaults],+ installed+ );++ expect(result?.values.t5EncoderModel).toBeNull();+ expect(result?.values.clipEmbedModel?.key).toBe(defaultClip.key);+ });++ describe('on a generation record, which records what ran', () => {+ const q21: MainModelConfig = {+ base: 'qwen-image-2-1',+ default_settings: { components: { qwen3_vl_encoder: 'q21-gguf-encoder' }, vae: 'q21-vae' },+ format: 'diffusers',+ key: 'q21-main',+ name: 'Qwen-Image-2.1',+ type: 'main',+ variant: 'qwen_image_21_base',+ };+ const ggufEncoder: ComponentModelConfig = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'q21-gguf-encoder',+ name: 'GGUF encoder',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ };+ const otherEncoder: ComponentModelConfig = {+ ...ggufEncoder,+ format: 'checkpoint',+ key: 'q21-other-encoder',+ name: 'Other encoder',+ };+ const vae: VaeModelConfig = { base: 'qwen-image-2-1', key: 'q21-vae', name: 'Q21 VAE', type: 'vae' };+ const recallQ21 = (metadata: Record<string, unknown>, overrides: Partial<GenerateWidgetValues> = {}) =>+ recall(+ { model: { key: q21.key }, ...metadata },+ { model: sdxlModel, modelKey: sdxlModel.key, ...overrides },+ [sdxlModel, q21],+ [q21, ggufEncoder, otherEncoder],+ [vae]+ );++ it('applies no saved default component, and an unnamed slot keeps the current pick', () => {+ const result = recallQ21({ generation_mode: 'txt2img' }, { qwen3VLEncoderModel: otherEncoder });+ const empty = recallQ21({ generation_mode: 'txt2img' });++ expect(result?.values.qwen3VLEncoderModel?.key).toBe(otherEncoder.key);+ expect(empty?.values.qwen3VLEncoderModel).toBeNull();+ });++ it('still restores what the record names', () => {+ const result = recallQ21({ generation_mode: 'txt2img', qwen3_vl_encoder: { ...ggufEncoder } });++ expect(result?.values.qwen3VLEncoderModel?.key).toBe(ggufEncoder.key);+ });++ it('fills the defaults for a record that is no generation record, which says nothing of components', () => {+ const result = recallQ21({});++ expect(result?.values.qwen3VLEncoderModel?.key).toBe(ggufEncoder.key);+ expect(result?.values.vae?.key).toBe(vae.key);+ });+ });++ it('keeps the current VAE when the image clears the component source whose bundled VAE the default took', () => {+ const pipeline: MainModelConfig = {+ base: 'z-image',+ format: 'diffusers',+ key: 'z-pipeline',+ name: 'Z-Image pipeline',+ type: 'main',+ };+ const zGguf: MainModelConfig = {+ base: 'z-image',+ default_settings: { components: { component_source: pipeline.key }, vae: 'default' },+ format: 'gguf_quantized',+ key: 'z-gguf',+ name: 'Z-Image GGUF',+ type: 'main',+ };+ const vae: VaeModelConfig = { base: 'flux', key: 'z-vae', name: 'FLUX VAE', type: 'vae' };+ const result = recall(+ { model: { key: zGguf.key }, qwen3_source: null },+ { model: sdxlModel, modelKey: sdxlModel.key, vae },+ [sdxlModel, zGguf],+ [zGguf, pipeline],+ [vae]+ );++ expect(result?.values.componentSourceModel).toBeNull();+ expect(result?.values.vae).toEqual(vae);+ });++ it('fills every slot of an image that recorded none', () => {+ const result = recall(+ { model: { key: withDefaults.key } },+ { model: sdxlModel, modelKey: sdxlModel.key },+ [sdxlModel, withDefaults],+ installed+ );++ expect(result?.values.t5EncoderModel?.key).toBe(defaultT5.key);+ expect(result?.values.clipEmbedModel?.key).toBe(defaultClip.key);+ });+ });+describe('reference-image adapters', () => {const adapter: ComponentModelConfig = {base: 'sdxl',diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex 3ba4180e7a..2ca480b742 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -14,6 +14,8 @@ import {clampAnimaInpaintAdapterWeight,clampDimension,clampPidSteps,+ DEFAULT_COMPONENT_SLOTS,+ type DefaultComponentSlot,cloneGenerateWidgetValues,isIdeogram4SamplerPreset,deriveAspectRatioId,@@ -24,6 +26,7 @@ import {getGenerateModelSelectionResult,getGenerationUiPolicy,isComponentCompatibleWithModel,+ getModelDefaultComponents,getSettingsWithModelDefaults,isKnownScheduler,isLoraCompatibleWithModel,@@ -145,6 +148,8 @@ export interface ImageRecallSkip {}export interface ImageRecallResult {+ /** The component settings recall set from the image, an explicit empty one included; a pick it rejected is not. */+ appliedComponents: DefaultComponentSlot['setting'][];fields: RecalledField[];skipped: ImageRecallSkip[];values: GenerateWidgetValues;@@ -884,27 +889,8 @@ const getMetadataFlux3PromptUpsampler = (return getString(metadata, 'generation_mode')?.startsWith('flux3_') ? { flux3PromptUpsamplerEnabled: false } : {};};-type RecalledComponentSetting = keyof Pick<- GenerateWidgetValues,- | 'animaInpaintAdapterModel'- | 'clipEmbedModel'- | 'clipGEmbedModel'- | 'clipLEmbedModel'- | 'componentSourceModel'- | 'flux3PromptUpsamplerModel'- | 'gemma2EncoderModel'- | 'ideogram4UnconditionalModel'- | 'mistralEncoderModel'- | 'pidDecoderModel'- | 'qwen3EncoderModel'- | 'qwen3VLEncoderModel'- | 'qwen3VLVisionTowerModel'- | 'qwen35EncoderModel'- | 'qwenVLEncoderModel'- | 't5EncoderModel'- | 'wanLowNoiseModel'- | 'wanT5EncoderModel'->;+/** The component source is not recalled by its slot key: only its per-family names below recall it. */+type RecalledComponentSetting = DefaultComponentSlot['setting'];interface RecalledComponent {metadataKey: string;@@ -912,28 +898,22 @@ interface RecalledComponent {isMainModel?: true;}-/** Remix silently drops a key missing here. The first recorded key wins. */+/**+ * Remix silently drops a key missing here. The first recorded key wins for a shared setting. Slots a model stores+ * defaults for share their metadata key with them; the component source is recorded under per-family names, listed+ * first.+ */const RECALLED_COMPONENTS: readonly RecalledComponent[] = [{ isMainModel: true, metadataKey: 'qwen3_source', setting: 'componentSourceModel' },{ isMainModel: true, metadataKey: 'qwen_image_component_source', setting: 'componentSourceModel' },{ isMainModel: true, metadataKey: 'wan_component_source', setting: 'componentSourceModel' },- { isMainModel: true, metadataKey: 'ideogram4_unconditional_model', setting: 'ideogram4UnconditionalModel' },- { isMainModel: true, metadataKey: 'wan_transformer_low_noise', setting: 'wanLowNoiseModel' },- { metadataKey: 'anima_inpaint_adapter', setting: 'animaInpaintAdapterModel' },- { metadataKey: 'clip_embed_model', setting: 'clipEmbedModel' },- { metadataKey: 'clip_g_model', setting: 'clipGEmbedModel' },- { metadataKey: 'clip_l_model', setting: 'clipLEmbedModel' },- { metadataKey: 'flux3_prompt_upsampler', setting: 'flux3PromptUpsamplerModel' },- { metadataKey: 'gemma2_encoder', setting: 'gemma2EncoderModel' },- { metadataKey: 'mistral_encoder', setting: 'mistralEncoderModel' },- { metadataKey: 'pid_decoder', setting: 'pidDecoderModel' },- { metadataKey: 'qwen3_encoder', setting: 'qwen3EncoderModel' },- { metadataKey: 'qwen3_vl_encoder', setting: 'qwen3VLEncoderModel' },- { metadataKey: 'qwen3_vl_vision_tower', setting: 'qwen3VLVisionTowerModel' },- { metadataKey: 'qwen3_5_encoder', setting: 'qwen35EncoderModel' },- { metadataKey: 'qwen_image_qwen_vl_encoder', setting: 'qwenVLEncoderModel' },- { metadataKey: 't5_encoder', setting: 't5EncoderModel' },- { metadataKey: 'wan_t5_encoder_model', setting: 'wanT5EncoderModel' },+ ...DEFAULT_COMPONENT_SLOTS.filter((slot) => slot.setting !== 'componentSourceModel').map(+ ({ isMainModel, persistenceKey, setting }) => ({+ ...(isMainModel ? { isMainModel } : {}),+ metadataKey: persistenceKey,+ setting,+ })+ ),];const getRecalledComponent = (@@ -1511,14 +1491,22 @@ export const buildImageRecallSettings = ({let values: GenerateWidgetValues = cloneGenerateWidgetValues(currentValues);let restoredProviderSize = false;let referenceRecall: ReturnType<typeof readMetadataReferenceImages> | null = null;+ const appliedComponents: RecalledComponentSetting[] = [];if (kind === 'all' || kind === 'remix') {const model = getSupportedMetadataModel(metadata, supportedModels);if (model) {const valuesWithModelDefaults = getSettingsWithModelDefaults(values, model);- const vae = getRecallDefaultVae(resolveModelDefaultVae(model, valuesWithModelDefaults, vaeModels));- values = { ...valuesWithModelDefaults, model, ...(vae === undefined ? {} : { vae }) };+ // The recorded components below override these, and the default VAE is chosen after them. A generation record+ // names what ran, so it takes no saved default over a component it left out.+ values = {+ ...valuesWithModelDefaults,+ model,+ ...(isGenerationRecord(metadata)+ ? {}+ : getModelDefaultComponents(model, valuesWithModelDefaults, models, { replace: true })),+ };fields.push('model');}@@ -1526,7 +1514,7 @@ export const buildImageRecallSettings = ({const recordedSettings = Object.keys(componentPatch) as RecalledComponentSetting[];const effectiveModel = values.model;// Skip components that do not fit, judged beside those already restored (a Vision Tower depends on a GGUF encoder).- const fittingSettings: RecalledComponentSetting[] = [];+ const fittingSettings = appliedComponents;for (const setting of recordedSettings) {const component = componentPatch[setting];@@ -1537,6 +1525,13 @@ export const buildImageRecallSettings = ({}}+ if (model) {+ // Judged beside the recorded components: a component source bundles the VAE the default VAE then falls back to,+ // and an image that cleared that source has none.+ const defaultVae = getRecallDefaultVae(resolveModelDefaultVae(model, values, vaeModels));+ values = { ...values, ...(defaultVae === undefined ? {} : { vae: defaultVae }) };+ }+const rebalancePatch = getMetadataKrea2Rebalance(metadata, values.model);if (Object.keys(rebalancePatch).length > 0) {@@ -1754,7 +1749,7 @@ export const buildImageRecallSettings = ({skipped.length > 0 ||((kind === 'all' || kind === 'remix') &&(hasCanvasRecall(metadata) || referenceRecall?.partial || (referenceRecall?.names.length ?? 0) > 0))- ? { fields, skipped, values }+ ? { appliedComponents, fields, skipped, values }: null;};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.tsindex c8ef65bb0c..be249666b1 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts@@ -48,7 +48,7 @@ const vaeModels = models.filter(isVaeModelConfig) as VaeModelConfig[];const image = (imageName: string) => ({ height: 512, image_name: imageName, width: 512 });const currentFor = (model: ComponentModelConfig, overrides: Record<string, unknown> = {}) => {- const values = getCurrentGenerateValues({ generateValues: { modelKey: model.key }, supportedModels });+ const values = getCurrentGenerateValues({ generateValues: { modelKey: model.key }, models, supportedModels });if (!values) {throw new Error('fixture model is not a supported Generate model');}@@ -60,6 +60,24 @@ const build = (currentValues: ReturnType<typeof currentFor>, parameters: Record<seedArchitectureCapabilities();+describe('getCurrentGenerateValues', () => {+ it("fills the first model's default components and VAE, as Generate does when it picks the first model", () => {+ const t5 = makeModel('t5-default', 'any', 't5_encoder');+ const withDefaults = makeModel('flux-with-defaults', 'flux', 'main', {+ default_settings: { components: { t5_encoder: t5.key } },+ });+ const installed = [withDefaults, t5];+ const initial = getCurrentGenerateValues({+ generateValues: {},+ models: installed,+ supportedModels: installed.filter(isSupportedGenerateModel) as GenerateModelConfig[],+ });++ expect(initial?.model.key).toBe(withDefaults.key);+ expect(initial?.t5EncoderModel?.key).toBe(t5.key);+ });+});+describe('buildRecallParametersSettings', () => {it('applies prompts, seed, size and sampler parameters to the current values', () => {const result = build(currentFor(sdxl), {@@ -531,6 +549,7 @@ describe('buildRecallParametersSettings', () => {const krea2Supported = [krea2].filter(isSupportedGenerateModel) as GenerateModelConfig[];const krea2Values = getCurrentGenerateValues({generateValues: { modelKey: krea2.key },+ models: krea2Supported,supportedModels: krea2Supported,});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.tsindex 4c72b5af09..d6a548e225 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts@@ -21,6 +21,7 @@ import {getDefaultLoraWeight,getGenerateModelSelectionResult,getGenerationUiPolicy,+ getModelDefaultComponents,getSettingsWithModelDefaults,isLoraCompatibleWithModel,isLoraModelConfig,@@ -228,8 +229,14 @@ export const buildRecallParametersSettings = ({model,models,});- const vae = getRecallDefaultVae(resolveModelDefaultVae(model, settings, vaeModels));- values = { ...values, ...settings, model, ...(vae === undefined ? {} : { vae }) };+ // Components first: a default component source can bundle the VAE the default VAE then falls back to.+ const selected = { ...values, ...settings, model };+ const withComponents = {+ ...selected,+ ...getModelDefaultComponents(model, selected, models, { replace: true }),+ };+ const vae = getRecallDefaultVae(resolveModelDefaultVae(model, withComponents, vaeModels));+ values = { ...withComponents, ...(vae === undefined ? {} : { vae }) };fields.add('model');}}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.test.tsindex 404b01816f..5fb25de6c9 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.test.ts@@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest';import { resolveRecordedModel, toRecordedModelRef, type RecordedModelPolicy } from './recordedModel';-const model = (key: string, extra: Partial<{ base: string; hash: string; name: string; type: string }> = {}) => ({+const model = (+ key: string,+ extra: Partial<{ base: string; hash: string; is_missing: boolean; name: string; type: string }> = {}+) => ({base: 'sdxl',key,name: 'Juggernaut',@@ -59,6 +62,73 @@ describe('resolveRecordedModel', () => {expect(resolveRecordedModel(recorded, [first, second], LENIENT)).toBe(first);});+ it('prefers a present record over a missing one at every step, and takes a missing one only as the last resort', () => {+ const old = model('old', { hash: 'blake3:x', is_missing: true });+ const reinstalled = model('new', { hash: 'blake3:x' });+ const ref = { base: 'sdxl', hash: 'blake3:x', key: 'old', name: 'Juggernaut', type: 'main' };++ // The key names the missing record, the reinstall has the same hash: the present one wins, in either order.+ expect(resolveRecordedModel(ref, [old, reinstalled], STRICT)).toBe(reinstalled);+ expect(resolveRecordedModel(ref, [reinstalled, old], STRICT)).toBe(reinstalled);+ // Several missing matches beside one present one are no ambiguity.+ expect(+ resolveRecordedModel(+ { ...ref, key: null },+ [old, model('old2', { hash: 'blake3:x', is_missing: true }), reinstalled],+ STRICT+ )+ ).toBe(reinstalled);+ // Nothing present matches: the missing record stays what the image names.+ expect(resolveRecordedModel(ref, [old], STRICT)).toBe(old);+ expect(resolveRecordedModel({ ...ref, key: null }, [old], STRICT)).toBe(old);+ // By name and base, too.+ const named = { base: 'sdxl', hash: null, key: null, name: 'Juggernaut', type: null };+ expect(resolveRecordedModel(named, [model('gone', { is_missing: true }), model('here')], LENIENT)).toMatchObject({+ key: 'here',+ });+ });++ it('takes the reinstall of the weights a missing key stood for over another model with the recorded name', () => {+ // Metadata records the key and the name but no hash.+ const ref = { base: 'sdxl', hash: null, key: 'old', name: 'Juggernaut', type: 'main' };+ const missing = model('old', { hash: 'blake3:weights', is_missing: true });+ const reinstall = model('new', { hash: 'blake3:weights', name: 'Juggernaut (renamed)' });+ const namesake = model('namesake', { hash: 'blake3:other' });++ expect(resolveRecordedModel(ref, [missing, namesake, reinstall], STRICT)).toBe(reinstall);+ expect(resolveRecordedModel(ref, [reinstall, namesake, missing], LENIENT)).toBe(reinstall);+ // No reinstall: the recorded identifiers decide, as for any image without a hash.+ expect(resolveRecordedModel(ref, [missing, namesake], STRICT)).toBe(namesake);+ // Two present copies of those weights are as ambiguous as two with the recorded hash.+ expect(resolveRecordedModel(ref, [missing, reinstall, model('copy', { hash: 'blake3:weights' })], STRICT)).toBe(+ 'ambiguous'+ );+ expect(resolveRecordedModel(ref, [missing, reinstall, model('copy', { hash: 'blake3:weights' })], LENIENT)).toBe(+ reinstall+ );+ });++ it('counts only the copy of those weights registered for the recorded family and type', () => {+ // One VAE file registered as SDXL and as SD1; the image recorded the SDXL key, now missing, and no hash.+ const vae = (key: string, base: string, extra: Partial<{ is_missing: boolean }> = {}) =>+ model(key, { base, hash: 'blake3:vae', name: 'VAE', type: 'vae', ...extra });+ const missing = vae('old', 'sdxl', { is_missing: true });+ const sdxl = vae('sdxl-copy', 'sdxl');+ const sd1 = vae('sd1-copy', 'sd-1');++ expect(+ resolveRecordedModel(+ { base: 'sdxl', hash: null, key: 'old', name: 'VAE', type: 'vae' },+ [missing, sd1, sdxl],+ STRICT+ )+ ).toBe(sdxl);+ // Without a recorded family, the one the missing key stood for decides.+ expect(+ resolveRecordedModel({ base: null, hash: null, key: 'old', name: null, type: null }, [missing, sd1, sdxl], STRICT)+ ).toBe(sdxl);+ });+it('matches the type only when the ref records one', () => {const lora = model('lora', { type: 'lora' });diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.tsindex c3a5123c48..3a36adbf24 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recordedModel.ts@@ -14,6 +14,8 @@ export interface RecordedModelRef {interface ResolvableModel {base: string;hash?: string;+ /** Registered, but its files are gone. */+ is_missing?: boolean;key: string;name: string;type: string;@@ -56,18 +58,12 @@ export const toRecordedModelRef = (value: unknown): RecordedModelRef | null => {return ref && (ref.key || ref.hash || (ref.name && ref.base)) ? ref : null;};-/** Key first, then the content hash when recorded, else name and base (and type when recorded). */-export const resolveRecordedModel = <T extends ResolvableModel>(+/** The content hash when recorded, else name and base (and type when recorded). */+const matchRecordedModel = <T extends ResolvableModel>(ref: RecordedModelRef,models: readonly T[],policy: RecordedModelPolicy): T | 'ambiguous' | null => {- const byKey = ref.key ? models.find((model) => model.key === ref.key) : undefined;-- if (byKey) {- return byKey;- }-const byHash = ref.hash ? models.filter((model) => model.hash === ref.hash) : [];const matches =byHash.length > 0 || (ref.hash && policy.hashMiss === 'refuse')@@ -81,6 +77,51 @@ export const resolveRecordedModel = <T extends ResolvableModel>(return matches.length > 1 && policy.ambiguous === 'refuse' ? 'ambiguous' : (matches[0] ?? null);};+/**+ * Key first, then the content hash when recorded, else name and base (and type when recorded). A model whose files are+ * gone is the last resort: a reinstall leaves the old record beside the new one, and the new one is what the image+ * recorded in effect.+ */+export const resolveRecordedModel = <T extends ResolvableModel>(+ ref: RecordedModelRef,+ models: readonly T[],+ policy: RecordedModelPolicy+): T | 'ambiguous' | null => {+ const present = models.filter((model) => !model.is_missing);+ const byKey = ref.key ? present.find((model) => model.key === ref.key) : undefined;++ if (byKey) {+ return byKey;+ }++ const missingByKey = ref.key ? models.find((model) => model.key === ref.key) : undefined;++ // Metadata often records no hash. The catalog still knows the weights its key stood for, and a reinstall carries+ // them, so that hash outranks a name another model may share. It is only a hint: when nothing present has it, the+ // recorded identifiers decide as before, `hashMiss` included, since the image itself recorded no hash. The same+ // weights can be registered for several families (one VAE file as SDXL and as SD1), so only a copy of the family and+ // type the image recorded, else the ones its key stood for, counts.+ if (!ref.hash && missingByKey?.hash) {+ const base = ref.base ?? missingByKey.base;+ const type = ref.type ?? missingByKey.type;+ const reinstalls = present.filter(+ (model) => model.hash === missingByKey.hash && model.base === base && model.type === type+ );++ if (reinstalls.length > 0) {+ return reinstalls.length > 1 && policy.ambiguous === 'refuse' ? 'ambiguous' : reinstalls[0]!;+ }+ }++ const matched = matchRecordedModel(ref, present, policy);++ if (matched !== null) {+ return matched;+ }++ return missingByKey ?? matchRecordedModel(ref, models, policy);+};+export interface ParsedMetadataLoraTarget {lowNoiseWeight?: number;target?: WanLoraTarget;diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 35fbdecbc0..ee463764da 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -263,7 +263,7 @@ export const useImageActions = ({subscribeArchitectureCapabilities,getArchitectureCapabilitiesSnapshot,useCallback(() => {- const values = getCurrentGenerateValues({ generateValues, supportedModels });+ const values = getCurrentGenerateValues({ generateValues, models, supportedModels });return {canUseAsReferenceImage: Boolean(@@ -271,7 +271,7 @@ export const useImageActions = ({),currentGenerateValues: values,};- }, [generateValues, supportedModels])+ }, [generateValues, models, supportedModels]));const selectVideoPlacementRoom = useMemo(diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/executeQueueItemRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/executeQueueItemRecall.tsindex 36a648ea74..3d196f4c08 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/executeQueueItemRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/executeQueueItemRecall.ts@@ -65,6 +65,7 @@ export const executeQueueItemRecall = async ({return project? getCurrentGenerateValues({generateValues: getResolvedProjectWidgetValues(project, 'generate', queries.getSnapshot().scopedDefaults),+ models,supportedModels,}): null;diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.tsindex db7ba9a25d..02ec202029 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts@@ -65,10 +65,10 @@ export const useQueueItemRecall = (() =>getQueueRecallTargetState({hasCapabilityTable: hasArchitectureCapabilities(),- hasCurrentValues: getCurrentGenerateValues({ generateValues, supportedModels }) !== null,+ hasCurrentValues: getCurrentGenerateValues({ generateValues, models, supportedModels }) !== null,isCatalogSettled,}),- [generateValues, isCatalogSettled, supportedModels]+ [generateValues, isCatalogSettled, models, supportedModels]));const source = getQueueRecallSource(snapshot?.sourceId ?? null, isNonGenerateRun);diff --git a/scripts/family_e2e/graphs.py b/scripts/family_e2e/graphs.pyindex ffe2b44c5f..37a945c8a8 100644--- a/scripts/family_e2e/graphs.py+++ b/scripts/family_e2e/graphs.py@@ -55,6 +55,15 @@ class PreparedGraph:"""The denoise step count of each node that states the one it runs (`denoise_step_counts`), by node id."""+def flag_missing_models(models: list[dict[str, Any]], missing: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """The model list with `is_missing` set on registered models whose files are gone, as Generate reads the library.++ The exporter then skips them as default components like Generate does.+ """+ missing_keys = {model["key"] for model in missing}+ return [{**model, "is_missing": True} if model["key"] in missing_keys else model for model in models]++def build_export_request(cases: list[ResolvedCase],models: list[dict[str, Any]],diff --git a/scripts/family_e2e/runner.py b/scripts/family_e2e/runner.pyindex 86c1958f31..3df71b2e6a 100644--- a/scripts/family_e2e/runner.py+++ b/scripts/family_e2e/runner.py@@ -60,6 +60,7 @@ from scripts.family_e2e.detach import RUNNER_LOGfrom scripts.family_e2e.graphs import (PreparedGraph,build_export_request,+ flag_missing_models,output_image_name,prepare_batch,run_pnpm_exporter,@@ -968,7 +969,9 @@ class _Session:runtime_config = self.record_environment(server, client)if self.info.calibrate:calibration.check_available(client)- models = client.get("/api/v2/models/")["models"]+ models = flag_missing_models(+ client.get("/api/v2/models/")["models"], client.get("/api/v2/models/missing")["models"]+ )capabilities = client.get("/api/v2/models/capabilities")configs = {model["key"]: model for model in models}todo_cases = [self.cases[key] for key in dict.fromkeys(step.case_key for step in todo)]diff --git a/tests/app/services/model_manager/test_model_record_changes.py b/tests/app/services/model_manager/test_model_record_changes.pyindex daf6a0fe1a..b48c980999 100644--- a/tests/app/services/model_manager/test_model_record_changes.py+++ b/tests/app/services/model_manager/test_model_record_changes.py@@ -279,6 +279,39 @@ def test_cached_instances_are_dropped_under_the_model_load_write_lock(harness: _assert drops_under_write_lock == [True, True]+def test_update_round_trips_default_components_from_a_request_body(harness: _Harness) -> None:+ """A PATCH body that carries `components` parses as main-model settings and survives the record store."""+ harness.store.add_model(_sd1_record(default_settings=MainModelDefaultSettings(vae="vae-key", steps=20)))+ body = {"default_settings": {"vae": "vae-key", "steps": 20, "components": {"t5_encoder": "t5-key"}}}++ changes = ModelRecordChanges.model_validate(body)+ assert isinstance(changes.default_settings, MainModelDefaultSettings)+ harness.manager.update_model_record(KEY, changes)++ stored = harness.store.get_model(KEY)+ assert stored.default_settings == MainModelDefaultSettings(+ vae="vae-key", steps=20, components={"t5_encoder": "t5-key"}+ )++ harness.manager.update_model_record(+ KEY, ModelRecordChanges.model_validate({"default_settings": {"vae": "vae-key", "steps": 20, "components": {}}})+ )+ cleared = harness.store.get_model(KEY).default_settings+ assert cleared is not None and cleared.components is None+++def test_a_body_with_only_components_resolves_to_main_model_settings() -> None:+ changes = ModelRecordChanges.model_validate({"default_settings": {"components": {"t5_encoder": "t5-key"}}})++ assert isinstance(changes.default_settings, MainModelDefaultSettings)+ assert changes.default_settings.components == {"t5_encoder": "t5-key"}+++def test_a_request_body_with_an_invalid_default_component_is_rejected() -> None:+ with pytest.raises(ValueError, match="`vae` field"):+ ModelRecordChanges.model_validate({"default_settings": {"components": {"vae": "x"}}})++def test_update_that_the_store_rejects_changes_nothing(harness: _Harness) -> None:record = _sd1_record()harness.store.add_model(record)@@ -338,6 +371,73 @@ def test_reidentify_refiles_a_misidentified_model_and_keeps_what_the_user_set(assert (later_install.default_settings.cpu_only, later_install.default_settings.fp8_storage) == (None, None)+def test_reidentify_keeps_the_default_vae_and_default_components_while_the_base_is_unchanged(+ harness: _Harness,+) -> None:+ """The default VAE and component models are the user's choice; the probe cannot derive them, and the+ recommended generation parameters (steps) are still replaced."""+ _write_sd_checkpoint(harness.models_path / MODEL_PATH, BaseModelType.StableDiffusion1)+ components = {"t5_encoder": "t5-key", "clip_embed": "clip-key"}+ harness.store.add_model(+ _sd1_record(default_settings=MainModelDefaultSettings(vae="vae-key", components=components, steps=12))+ )++ updated = harness.manager.reidentify_model(KEY)++ assert updated.default_settings is not None+ assert updated.default_settings.vae == "vae-key"+ assert updated.default_settings.components == components+ assert updated.default_settings.steps != 12+ assert harness.store.get_model(KEY).default_settings == updated.default_settings+++def test_reidentify_into_another_base_drops_the_default_vae_and_components_but_keeps_load_preferences(+ harness: _Harness,+) -> None:+ """The keys name models of the old base, which the new base cannot use."""+ _write_sd_checkpoint(harness.models_path / MODEL_PATH, BaseModelType.StableDiffusionXL)+ harness.store.add_model(+ _sd1_record(+ default_settings=MainModelDefaultSettings(cpu_only=True, vae="vae-key", components={"t5_encoder": "t5-key"})+ )+ )++ updated = harness.manager.reidentify_model(KEY)++ assert isinstance(updated, Main_Checkpoint_SDXL_Config)+ assert updated.default_settings is not None+ assert (updated.default_settings.vae, updated.default_settings.components) == (None, None)+ assert updated.default_settings.cpu_only is True+++def test_reidentify_whose_probe_has_no_defaults_keeps_the_curated_fields(+ harness: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_sd_checkpoint(harness.models_path / MODEL_PATH, BaseModelType.StableDiffusion1)+ harness.store.add_model(+ _sd1_record(+ default_settings=MainModelDefaultSettings(+ fp8_storage=True, vae="vae-key", components={"t5_encoder": "t5-key"}, steps=12+ )+ )+ )+ from_model_on_disk = ModelConfigFactory.from_model_on_disk++ def without_defaults(*args, **kwargs):+ result = from_model_on_disk(*args, **kwargs)+ assert result.config is not None+ result.config.default_settings = None+ return result++ monkeypatch.setattr(ModelConfigFactory, "from_model_on_disk", without_defaults)++ updated = harness.manager.reidentify_model(KEY)++ assert updated.default_settings == MainModelDefaultSettings(+ fp8_storage=True, vae="vae-key", components={"t5_encoder": "t5-key"}+ )++def test_reidentify_of_a_file_the_probes_refuse_says_why_and_keeps_the_record(harness: _Harness) -> None:"""A CLIP-G without the projection SD 3 needs is recognised and refused as unusable; the record is not touched."""keys = dict(clip_g_comfy_keys.state_dict_keys)@@ -708,6 +808,47 @@ def test_reidentify_of_an_unknown_model_raises(harness: _Harness) -> None:harness.manager.reidentify_model(KEY)+def test_a_save_of_a_client_that_does_not_know_components_keeps_the_stored_ones(harness: _Harness) -> None:+ """A form that edits only the fields it knows posts the whole settings object back without `components`."""+ harness.store.add_model(+ _sd1_record(default_settings=MainModelDefaultSettings(steps=20, components={"t5_encoder": "t5-key"}))+ )++ harness.manager.update_model_record(+ KEY, ModelRecordChanges.model_validate({"default_settings": {"steps": 30, "cfg_scale": 5}})+ )++ assert harness.store.get_model(KEY).default_settings == MainModelDefaultSettings(+ steps=30, cfg_scale=5, components={"t5_encoder": "t5-key"}+ )++[email protected]("cleared", [None, {}])+def test_an_explicit_null_or_empty_components_still_clears_them(harness: _Harness, cleared: dict | None) -> None:+ harness.store.add_model(_sd1_record(default_settings=MainModelDefaultSettings(components={"t5_encoder": "t5-key"})))++ harness.manager.update_model_record(+ KEY, ModelRecordChanges.model_validate({"default_settings": {"steps": 20, "components": cleared}})+ )++ default_settings = harness.store.get_model(KEY).default_settings+ assert default_settings is not None and default_settings.components is None+ assert default_settings.steps == 20+++def test_an_in_place_update_keeps_the_stored_components_too(harness: _Harness) -> None:+ """The store's update without a class change takes the same rule as the manager's."""+ harness.store.add_model(_sd1_record(default_settings=MainModelDefaultSettings(components={"t5_encoder": "t5-key"})))++ harness.store.update_model(KEY, ModelRecordChanges.model_validate({"default_settings": {"steps": 30}}))+ kept = harness.store.get_model(KEY).default_settings+ assert kept is not None and kept.components == {"t5_encoder": "t5-key"}++ harness.store.update_model(KEY, ModelRecordChanges.model_validate({"default_settings": {"components": None}}))+ cleared = harness.store.get_model(KEY).default_settings+ assert cleared is not None and cleared.components is None++# A record that serves as another type loads through that type's config class and cache entry.diff --git a/tests/app/services/model_records/test_missing_model_detection.py b/tests/app/services/model_records/test_missing_model_detection.pynew file mode 100644index 0000000000..7644358f2f--- /dev/null+++ b/tests/app/services/model_records/test_missing_model_detection.py@@ -0,0 +1,41 @@+from pathlib import Path+from types import SimpleNamespace++import pytest++from invokeai.app.services.model_records.missing_models import find_missing_models, is_model_missing+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat+++def _config(key: str, path: str, base=BaseModelType.StableDiffusionXL, format=ModelFormat.Diffusers):+ return SimpleNamespace(key=key, path=path, base=base, format=format)+++def test_a_model_is_missing_when_its_path_does_not_exist(tmp_path: Path) -> None:+ (tmp_path / "present").mkdir()++ assert not is_model_missing(_config("a", "present"), tmp_path)+ assert is_model_missing(_config("b", "absent"), tmp_path)+++def test_external_models_have_no_files_to_miss(tmp_path: Path) -> None:+ assert not is_model_missing(_config("a", "nowhere", base=BaseModelType.External), tmp_path)+ assert not is_model_missing(_config("b", "nowhere", format=ModelFormat.ExternalApi), tmp_path)++[email protected]("error", [PermissionError("denied"), RuntimeError("Symlink loop")])+def test_an_unreadable_path_is_unavailable_and_does_not_stop_the_scan(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error: Exception+) -> None:+ (tmp_path / "healthy").mkdir()+ real_resolve = Path.resolve++ def resolve(self: Path, *args, **kwargs) -> Path:+ if self.name == "locked":+ raise error+ return real_resolve(self, *args, **kwargs)++ monkeypatch.setattr(Path, "resolve", resolve)+ configs = [_config("locked", "locked"), _config("healthy", "healthy"), _config("gone", "gone")]++ assert [config.key for config in find_missing_models(configs, tmp_path)] == ["locked", "gone"]diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.pyindex 840534fc20..fe5ce66d4c 100644--- a/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py@@ -14,6 +14,7 @@ from diffusers import AutoencoderKL, AutoencoderKLFlux2from invokeai.app.services.config import get_configfrom invokeai.app.services.invoker import Invoker+from invokeai.app.services.model_records.missing_models import is_model_missingfrom invokeai.app.services.working_memory_calibration.working_memory_calibration_default import _vae_dtypesfrom invokeai.app.services.working_memory_calibration.working_memory_calibration_plan import (DECODE_LINES,@@ -1035,3 +1036,80 @@ def test_the_service_tells_an_sdnq_quantized_vae_folder_where_the_loader_looks(tassert vaes.sdnq_quantized_vae(SimpleNamespace(path="flux-sdnq", submodels=None))assert not vaes.sdnq_quantized_vae(SimpleNamespace(path="flux-sdnq-plain", submodels=None))+++def _with_default_components(model: SimpleNamespace, **components: str) -> SimpleNamespace:+ return SimpleNamespace(**{**vars(model), "default_settings": SimpleNamespace(vae=None, components=components)})+++def test_a_z_image_model_decodes_with_the_vae_of_its_default_component_source() -> None:+ """Selecting the model fills its `component_source` slot (a Z-Image pipeline), whose own VAE the model loader node+ then takes where no VAE is set: under `precision: float32` the pipeline's VAE loads in bf16 where a standalone FLUX+ VAE stays fp32, and the case needs no VAE pick."""+ gguf = _model("z-image-gguf", BaseModelType.ZImage, format="gguf_quantized")+ pipeline = _model("z-image", BaseModelType.ZImage, format="diffusers")+ flux_vae = _model("ae", BaseModelType.Flux, ModelType.VAE)+ with_source = _with_default_components(gguf, component_source="z-image")++ assert _lines_of(_plan(gguf, [pipeline, flux_vae], vae_dtypes=FP32_VAES)) == {("decode_fp32", ())}+ assert _lines_of(_plan(with_source, [pipeline, flux_vae], vae_dtypes=FP32_VAES)) == {("decode_bf16", ())}+ # A default VAE is set beside the source and wins, as the loader takes a picked VAE first.+ with_vae = SimpleNamespace(+ **{+ **vars(with_source),+ "default_settings": SimpleNamespace(vae="ae", components={"component_source": "z-image"}),+ }+ )+ assert _lines_of(_plan(with_vae, [pipeline, flux_vae], vae_dtypes=FP32_VAES)) == {("decode_fp32", ())}+ # A key that names no installed Z-Image pipeline leaves the model as it was.+ assert _lines_of(+ _plan(_with_default_components(gguf, component_source="missing"), [pipeline, flux_vae], vae_dtypes=FP32_VAES)+ ) == {("decode_fp32", ())}+++def test_a_self_contained_z_image_pipeline_decodes_with_the_vae_of_its_default_component_source() -> None:+ """The Z-Image loader takes a source's VAE over the self-contained pipeline's own, and the slot is offered for it."""+ sdnq = _sdnq_pipeline("z-image-sdnq", BaseModelType.ZImage)+ pipeline = _model("z-image", BaseModelType.ZImage, format="diffusers")++ assert _lines_of(_plan(sdnq, [pipeline], vae_dtypes=FP32_VAES)) == {("decode_fp32", ())}+ assert _lines_of(+ _plan(_with_default_components(sdnq, component_source="z-image"), [pipeline], vae_dtypes=FP32_VAES)+ ) == {("decode_bf16", ())}+++def test_a_z_image_default_source_whose_files_are_gone_sizes_no_case(tmp_path: Path, mock_invoker: Invoker) -> None:+ """Generate skips a registered model whose files moved, so the graph decodes with the VAE it would without it."""+ models_dir = tmp_path / "models"+ (models_dir / "z-image").mkdir(parents=True)+ (models_dir / "z-image-gguf.gguf").touch()+ (models_dir / "ae.safetensors").touch()+ gguf = _with_default_components(+ _model("z-image-gguf", BaseModelType.ZImage, format="gguf_quantized", path="z-image-gguf.gguf"),+ component_source="z-image",+ )+ pipeline = _model("z-image", BaseModelType.ZImage, format="diffusers", path="z-image")+ flux_vae = _model("ae", BaseModelType.Flux, ModelType.VAE, format="checkpoint", path="ae.safetensors")++ def plan_lines(models: list) -> set:+ model_manager = MagicMock()+ model_manager.store.get_model.return_value = gguf+ model_manager.store.all_models.return_value = [gguf, *models]+ mock_invoker.services.model_manager = model_manager+ mock_invoker.services.configuration.models_dir = models_dir+ service = calibration_service(+ tmp_path,+ untiled_decode_reservation=lambda estimator, h, w, dtype, device: 1000 * h * w,+ vae_dtypes=FP32_VAES,+ is_model_missing=is_model_missing,+ )+ service.start(mock_invoker)+ try:+ return {(case.line, tuple(case.components.items())) for case in service.get_plan(gguf.key).cases}+ finally:+ service.stop(mock_invoker)++ # The pipeline's own VAE loads in bf16; the standalone FLUX VAE the model falls back to stays fp32.+ assert plan_lines([pipeline, flux_vae]) == {("decode_bf16", ())}+ (models_dir / "z-image").rmdir()+ assert plan_lines([pipeline, flux_vae]) == plan_lines([flux_vae]) == {("decode_fp32", ())}diff --git a/tests/backend/model_manager/configs/test_main_default_components.py b/tests/backend/model_manager/configs/test_main_default_components.pynew file mode 100644index 0000000000..13659c7e1f--- /dev/null+++ b/tests/backend/model_manager/configs/test_main_default_components.py@@ -0,0 +1,49 @@+import pytest+from pydantic import ValidationError++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+++def test_accepts_a_map_of_component_slots_to_model_keys() -> None:+ components = {"t5_encoder": "key-a", "qwen3_encoder": "key-b", "pid_decoder2": "key-c"}+ assert MainModelDefaultSettings(components=components).components == components+++def test_components_are_optional() -> None:+ assert MainModelDefaultSettings().components is None+ assert MainModelDefaultSettings(components={}).components is None++[email protected]("slot", ["", "T5Encoder", "t5-encoder", "t5 encoder", "t5_encoder\n", "köder"])+def test_rejects_a_slot_that_is_not_snake_case(slot: str) -> None:+ with pytest.raises(ValidationError, match="snake_case"):+ MainModelDefaultSettings(components={slot: "key"})+++def test_rejects_the_vae_slot_because_the_vae_field_owns_it() -> None:+ with pytest.raises(ValidationError, match="`vae` field"):+ MainModelDefaultSettings(components={"vae": "key"})++[email protected]("model_key", ["", " "])+def test_rejects_an_empty_model_key(model_key: str) -> None:+ with pytest.raises(ValidationError, match="needs a model key"):+ MainModelDefaultSettings(components={"t5_encoder": model_key})+++def test_allows_sixteen_components_and_rejects_seventeen() -> None:+ assert len(MainModelDefaultSettings(components={f"slot_{i}": "key" for i in range(16)}).components or {}) == 16+ with pytest.raises(ValidationError, match="at most 16"):+ MainModelDefaultSettings(components={f"slot_{i}": "key" for i in range(17)})+++def test_unknown_top_level_fields_stay_forbidden() -> None:+ with pytest.raises(ValidationError):+ MainModelDefaultSettings(component={"t5_encoder": "key"}) # type: ignore[call-arg]+++def test_a_record_without_components_dumps_without_the_key() -> None:+ """An older server forbids unknown fields, so even a null `components` would get the record skipped."""+ assert "components" not in MainModelDefaultSettings(steps=20).model_dump()+ assert "components" not in MainModelDefaultSettings(steps=20).model_dump_json()+ assert MainModelDefaultSettings(components={"t5_encoder": "k"}).model_dump()["components"] == {"t5_encoder": "k"}diff --git a/tests/family_e2e/fake_invokeai_server.py b/tests/family_e2e/fake_invokeai_server.pyindex 5176e9e4d5..04a5a44199 100644--- a/tests/family_e2e/fake_invokeai_server.py+++ b/tests/family_e2e/fake_invokeai_server.py@@ -192,6 +192,8 @@ class FakeInvoke:return reply({"set_fields": [], "config": {"multiuser": False, "fp8_compute": False}})if path == "/api/v2/models/":return reply({"models": [MODEL_CONFIG]})+ if path == "/api/v2/models/missing":+ return reply({"models": []})if path == "/api/v2/models/capabilities":return reply({"fake": {}})if path == "/api/v2/models/empty_model_cache":diff --git a/tests/family_e2e/test_graphs.py b/tests/family_e2e/test_graphs.pyindex c2e08c5238..010f0d826a 100644--- a/tests/family_e2e/test_graphs.py+++ b/tests/family_e2e/test_graphs.py@@ -3,6 +3,7 @@ import pytestfrom scripts.family_e2e.graphs import (IDEOGRAM4_PRESET_STEPS,build_export_request,+ flag_missing_models,output_image_name,prepare_batch,shareable_source,@@ -92,6 +93,11 @@ def test_output_image_comes_from_the_one_non_intermediate_image_node() -> None:output_image_name(graph, _session({}))+def test_models_whose_files_are_gone_reach_the_exporter_flagged() -> None:+ assert flag_missing_models([MAIN, LORA], [LORA]) == [MAIN, {**LORA, "is_missing": True}]+ assert flag_missing_models([MAIN], []) == [MAIN]++def test_export_request_carries_each_case_with_its_uploaded_images() -> None:spec = CaseSpec.model_validate({diff --git a/tests/fixtures/working_memory_calibration.py b/tests/fixtures/working_memory_calibration.pyindex 64d189e5c5..358507ece3 100644--- a/tests/fixtures/working_memory_calibration.py+++ b/tests/fixtures/working_memory_calibration.py@@ -62,11 +62,13 @@ def calibration_service(untiled_decode_reservation: Optional[Callable[[str, int, int, str, torch.device], int]] = None,device_memory: Optional[Callable[[torch.device], DeviceMemory]] | Literal["whole card"] = "whole card",vae_dtypes: VaeDtypes = GPU_VAE_DTYPES,+ is_model_missing: Callable[[Any, Path], bool] = lambda model, models_path: False,) -> WorkingMemoryCalibrationService:"""A service storing under `root`; not started (call `start(invoker)`, and `stop(invoker)` once it registeredthe user-fit provider estimates ask). What the cache can give a calibration's lock defaults to the whole card, withnothing outside torch; None asks the model cache of the invoker's model manager, as the service does. The VAE- dtypes default to those of a GPU with bf16 under `precision: auto`."""+ dtypes default to those of a GPU with bf16 under `precision: auto`. Models are present unless `is_model_missing` says+ otherwise: the fakes carry no files."""extra = {} if untiled_decode_reservation is None else {"untiled_decode_reservation": untiled_decode_reservation}return WorkingMemoryCalibrationService(CalibrationStore(root / "working_memory"),@@ -77,6 +79,7 @@ def calibration_service(if device_memory == "whole card"else device_memory,vae_dtypes=lambda device, models_path: vae_dtypes,+ is_model_missing=is_model_missing,**extra,)