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(nodes): Add a LoRA collection picker node that selects and applies an indefinite number of LoRAs (#9259)
Lincoln Stein9152232189c0
diff --git a/invokeai/app/invocations/anima_lora_loader.py b/invokeai/app/invocations/anima_lora_loader.pyindex 6a035b55aa..ce63e335b2 100644--- a/invokeai/app/invocations/anima_lora_loader.py+++ b/invokeai/app/invocations/anima_lora_loader.py@@ -94,14 +94,18 @@ class AnimaLoRALoaderInvocation(BaseInvocation):title="Apply LoRA Collection - Anima",tags=["lora", "model", "anima"],category="model",- version="1.0.0",+ version="1.0.1",classification=Classification.Prototype,)class AnimaLoRACollectionLoader(BaseInvocation):"""Applies a collection of LoRAs to an Anima transformer."""loras: Optional[LoRAField | list[LoRAField]] = InputField(- default=None, description="LoRA models and weights. May be a single LoRA or collection.", title="LoRAs"+ default=None,+ description="LoRA models and weights. May be a single LoRA or collection.",+ title="LoRAs",+ ui_model_base=[BaseModelType.Anima],+ ui_model_type=ModelType.LoRA,)transformer: Optional[TransformerField] = InputField(diff --git a/invokeai/app/invocations/flux2_klein_lora_loader.py b/invokeai/app/invocations/flux2_klein_lora_loader.pyindex b7d55b6b13..64df3a8258 100644--- a/invokeai/app/invocations/flux2_klein_lora_loader.py+++ b/invokeai/app/invocations/flux2_klein_lora_loader.py@@ -114,14 +114,18 @@ class Flux2KleinLoRALoaderInvocation(BaseInvocation):title="Apply LoRA Collection - Flux2 Klein",tags=["lora", "model", "flux", "klein", "flux2"],category="model",- version="1.0.0",+ version="1.0.1",classification=Classification.Prototype,)class Flux2KleinLoRACollectionLoader(BaseInvocation):"""Applies a collection of LoRAs to a FLUX.2 Klein transformer and/or Qwen3 text encoder."""loras: Optional[LoRAField | list[LoRAField]] = InputField(- default=None, description="LoRA models and weights. May be a single LoRA or collection.", title="LoRAs"+ default=None,+ description="LoRA models and weights. May be a single LoRA or collection.",+ title="LoRAs",+ ui_model_base=[BaseModelType.Flux2],+ ui_model_type=ModelType.LoRA,)transformer: Optional[TransformerField] = InputField(@@ -157,7 +161,11 @@ class Flux2KleinLoRACollectionLoader(BaseInvocation):if not context.models.exists(lora.lora.key):raise Exception(f"Unknown lora: {lora.lora.key}!")- assert lora.lora.base in (BaseModelType.Flux, BaseModelType.Flux2)+ if lora.lora.base is not BaseModelType.Flux2:+ raise ValueError(+ f"LoRA '{lora.lora.key}' is for {lora.lora.base.value if lora.lora.base else 'unknown'} models, "+ "not FLUX.2 Klein models. Ensure you are using a FLUX.2 compatible LoRA."+ )# Warn if LoRA variant doesn't match transformer variantlora_config = context.models.get_config(lora.lora.key)diff --git a/invokeai/app/invocations/flux_lora_loader.py b/invokeai/app/invocations/flux_lora_loader.pyindex 0fd96e097d..1c9b0933a4 100644--- a/invokeai/app/invocations/flux_lora_loader.py+++ b/invokeai/app/invocations/flux_lora_loader.py@@ -111,13 +111,17 @@ class FluxLoRALoaderInvocation(BaseInvocation):title="Apply LoRA Collection - FLUX",tags=["lora", "model", "flux"],category="model",- version="1.3.1",+ version="1.3.2",)class FLUXLoRACollectionLoader(BaseInvocation):"""Applies a collection of LoRAs to a FLUX transformer."""loras: Optional[LoRAField | list[LoRAField]] = InputField(- default=None, description="LoRA models and weights. May be a single LoRA or collection.", title="LoRAs"+ default=None,+ description="LoRA models and weights. May be a single LoRA or collection.",+ title="LoRAs",+ ui_model_base=[BaseModelType.Flux],+ ui_model_type=ModelType.LoRA,)transformer: Optional[TransformerField] = InputField(@@ -162,7 +166,11 @@ class FLUXLoRACollectionLoader(BaseInvocation):if not context.models.exists(lora.lora.key):raise Exception(f"Unknown lora: {lora.lora.key}!")- assert lora.lora.base in (BaseModelType.Flux, BaseModelType.Flux2)+ if lora.lora.base is not BaseModelType.Flux:+ raise ValueError(+ f"LoRA '{lora.lora.key}' is for {lora.lora.base.value if lora.lora.base else 'unknown'} models, "+ "not FLUX models. Ensure you are using a FLUX compatible LoRA."+ )added_loras.append(lora.lora.key)diff --git a/invokeai/app/invocations/model.py b/invokeai/app/invocations/model.pyindex 0c96cdb1d9..c82b4369bd 100644--- a/invokeai/app/invocations/model.py+++ b/invokeai/app/invocations/model.py@@ -282,13 +282,17 @@ class LoRASelectorInvocation(BaseInvocation):@invocation(- "lora_collection_loader", title="Apply LoRA Collection - SD1.5", tags=["model"], category="model", version="1.1.2"+ "lora_collection_loader", title="Apply LoRA Collection - SD1.5", tags=["model"], category="model", version="1.1.3")class LoRACollectionLoader(BaseInvocation):"""Applies a collection of LoRAs to the provided UNet and CLIP models."""loras: Optional[LoRAField | list[LoRAField]] = InputField(- default=None, description="LoRA models and weights. May be a single LoRA or collection.", title="LoRAs"+ default=None,+ description="LoRA models and weights. May be a single LoRA or collection.",+ title="LoRAs",+ ui_model_base=[BaseModelType.StableDiffusion1, BaseModelType.StableDiffusion2],+ ui_model_type=ModelType.LoRA,)unet: Optional[UNetField] = InputField(default=None,@@ -432,13 +436,17 @@ class SDXLLoRALoaderInvocation(BaseInvocation):title="Apply LoRA Collection - SDXL",tags=["model"],category="model",- version="1.1.2",+ version="1.1.3",)class SDXLLoRACollectionLoader(BaseInvocation):"""Applies a collection of SDXL LoRAs to the provided UNet and CLIP models."""loras: Optional[LoRAField | list[LoRAField]] = InputField(- default=None, description="LoRA models and weights. May be a single LoRA or collection.", title="LoRAs"+ default=None,+ description="LoRA models and weights. May be a single LoRA or collection.",+ title="LoRAs",+ ui_model_base=[BaseModelType.StableDiffusionXL],+ ui_model_type=ModelType.LoRA,)unet: Optional[UNetField] = InputField(default=None,diff --git a/invokeai/app/invocations/qwen_image_lora_loader.py b/invokeai/app/invocations/qwen_image_lora_loader.pyindex f670b2d895..dea5fc3df5 100644--- a/invokeai/app/invocations/qwen_image_lora_loader.py+++ b/invokeai/app/invocations/qwen_image_lora_loader.py@@ -75,14 +75,18 @@ class QwenImageLoRALoaderInvocation(BaseInvocation):title="Apply LoRA Collection - Qwen Image",tags=["lora", "model", "qwen_image"],category="model",- version="1.0.0",+ version="1.0.1",classification=Classification.Prototype,)class QwenImageLoRACollectionLoader(BaseInvocation):"""Applies a collection of LoRAs to a Qwen Image transformer."""loras: Optional[LoRAField | list[LoRAField]] = InputField(- default=None, description="LoRA models and weights. May be a single LoRA or collection.", title="LoRAs"+ default=None,+ description="LoRA models and weights. May be a single LoRA or collection.",+ title="LoRAs",+ ui_model_base=[BaseModelType.QwenImage],+ ui_model_type=ModelType.LoRA,)transformer: Optional[TransformerField] = InputField(default=None,diff --git a/invokeai/app/invocations/z_image_lora_loader.py b/invokeai/app/invocations/z_image_lora_loader.pyindex 54c353a6ab..8c1350f696 100644--- a/invokeai/app/invocations/z_image_lora_loader.py+++ b/invokeai/app/invocations/z_image_lora_loader.py@@ -106,13 +106,17 @@ class ZImageLoRALoaderInvocation(BaseInvocation):title="Apply LoRA Collection - Z-Image",tags=["lora", "model", "z-image"],category="model",- version="1.0.0",+ version="1.0.1",)class ZImageLoRACollectionLoader(BaseInvocation):"""Applies a collection of LoRAs to a Z-Image transformer."""loras: Optional[LoRAField | list[LoRAField]] = InputField(- default=None, description="LoRA models and weights. May be a single LoRA or collection.", title="LoRAs"+ default=None,+ description="LoRA models and weights. May be a single LoRA or collection.",+ title="LoRAs",+ ui_model_base=[BaseModelType.ZImage],+ ui_model_type=ModelType.LoRA,)transformer: Optional[TransformerField] = InputField(diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex ef1f81a745..be3ff4059e 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -11019,7 +11019,9 @@"input": "any","orig_default": null,"orig_required": false,- "title": "LoRAs"+ "title": "LoRAs",+ "ui_model_base": ["anima"],+ "ui_model_type": ["lora"]},"transformer": {"anyOf": [@@ -11067,7 +11069,7 @@"tags": ["lora", "model", "anima"],"title": "Apply LoRA Collection - Anima","type": "object",- "version": "1.0.0",+ "version": "1.0.1","output": {"$ref": "#/components/schemas/AnimaLoRALoaderOutput"}@@ -23094,7 +23096,9 @@"input": "any","orig_default": null,"orig_required": false,- "title": "LoRAs"+ "title": "LoRAs",+ "ui_model_base": ["flux"],+ "ui_model_type": ["lora"]},"transformer": {"anyOf": [@@ -23159,7 +23163,7 @@"tags": ["lora", "model", "flux"],"title": "Apply LoRA Collection - FLUX","type": "object",- "version": "1.3.1",+ "version": "1.3.2","output": {"$ref": "#/components/schemas/FluxLoRALoaderOutput"}@@ -24726,7 +24730,9 @@"input": "any","orig_default": null,"orig_required": false,- "title": "LoRAs"+ "title": "LoRAs",+ "ui_model_base": ["flux2"],+ "ui_model_type": ["lora"]},"transformer": {"anyOf": [@@ -24774,7 +24780,7 @@"tags": ["lora", "model", "flux", "klein", "flux2"],"title": "Apply LoRA Collection - Flux2 Klein","type": "object",- "version": "1.0.0",+ "version": "1.0.1","output": {"$ref": "#/components/schemas/Flux2KleinLoRALoaderOutput"}@@ -44093,7 +44099,9 @@"input": "any","orig_default": null,"orig_required": false,- "title": "LoRAs"+ "title": "LoRAs",+ "ui_model_base": ["sd-1", "sd-2"],+ "ui_model_type": ["lora"]},"unet": {"anyOf": [@@ -44141,7 +44149,7 @@"tags": ["model"],"title": "Apply LoRA Collection - SD1.5","type": "object",- "version": "1.1.2",+ "version": "1.1.3","output": {"$ref": "#/components/schemas/LoRALoaderOutput"}@@ -60915,7 +60923,9 @@"input": "any","orig_default": null,"orig_required": false,- "title": "LoRAs"+ "title": "LoRAs",+ "ui_model_base": ["qwen-image"],+ "ui_model_type": ["lora"]},"transformer": {"anyOf": [@@ -60946,7 +60956,7 @@"tags": ["lora", "model", "qwen_image"],"title": "Apply LoRA Collection - Qwen Image","type": "object",- "version": "1.0.0",+ "version": "1.0.1","output": {"$ref": "#/components/schemas/QwenImageLoRALoaderOutput"}@@ -63621,7 +63631,9 @@"input": "any","orig_default": null,"orig_required": false,- "title": "LoRAs"+ "title": "LoRAs",+ "ui_model_base": ["sdxl"],+ "ui_model_type": ["lora"]},"unet": {"anyOf": [@@ -63686,7 +63698,7 @@"tags": ["model"],"title": "Apply LoRA Collection - SDXL","type": "object",- "version": "1.1.2",+ "version": "1.1.3","output": {"$ref": "#/components/schemas/SDXLLoRALoaderOutput"}@@ -74931,7 +74943,9 @@"input": "any","orig_default": null,"orig_required": false,- "title": "LoRAs"+ "title": "LoRAs",+ "ui_model_base": ["z-image"],+ "ui_model_type": ["lora"]},"transformer": {"anyOf": [@@ -74979,7 +74993,7 @@"tags": ["lora", "model", "z-image"],"title": "Apply LoRA Collection - Z-Image","type": "object",- "version": "1.0.0",+ "version": "1.0.1","output": {"$ref": "#/components/schemas/ZImageLoRALoaderOutput"}diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsxindex 4fa020212e..053f8a0998 100644--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsx+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsx@@ -7,6 +7,7 @@ import { ImageFieldCollectionInputComponent } from 'features/nodes/components/flimport { ImageGeneratorFieldInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/ImageGeneratorFieldComponent';import { IntegerFieldCollectionInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/IntegerFieldCollectionInputComponent';import { IntegerGeneratorFieldInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/IntegerGeneratorFieldComponent';+import { LoRAFieldCollectionInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/LoRAFieldCollectionInputComponent';import ModelIdentifierFieldInputComponent from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/ModelIdentifierFieldInputComponent';import SavedWorkflowFieldInputComponent from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/SavedWorkflowFieldInputComponent';import { StringFieldCollectionInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/StringFieldCollectionInputComponent';@@ -46,6 +47,8 @@ import {isIntegerFieldInputTemplate,isIntegerGeneratorFieldInputInstance,isIntegerGeneratorFieldInputTemplate,+ isLoRAFieldCollectionInputInstance,+ isLoRAFieldCollectionInputTemplate,isModelIdentifierFieldInputInstance,isModelIdentifierFieldInputTemplate,isSavedWorkflowFieldInputInstance,@@ -94,6 +97,13 @@ export const InputFieldRenderer = memo(({ nodeId, fieldName, settings }: Props)return <StringFieldCollectionInputComponent nodeId={nodeId} field={field} fieldTemplate={template} />;}+ if (isLoRAFieldCollectionInputTemplate(template)) {+ if (!isLoRAFieldCollectionInputInstance(field)) {+ return null;+ }+ return <LoRAFieldCollectionInputComponent nodeId={nodeId} field={field} fieldTemplate={template} />;+ }+if (isStringFieldInputTemplate(template)) {if (!isStringFieldInputInstance(field)) {return null;diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/LoRAFieldCollectionInputComponent.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/LoRAFieldCollectionInputComponent.tsxnew file mode 100644index 0000000000..2a6b828100--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/LoRAFieldCollectionInputComponent.tsx@@ -0,0 +1,224 @@+import type { SystemStyleObject } from '@invoke-ai/ui-library';+import { CompositeNumberInput, Divider, Flex, Grid, GridItem, IconButton, Text } from '@invoke-ai/ui-library';+import { EMPTY_ARRAY } from 'app/store/constants';+import { useAppStore } from 'app/store/storeHooks';+import { getOverlayScrollbarsParams, overlayScrollbarsStyles } from 'common/components/OverlayScrollbars/constants';+import { DEFAULT_LORA_WEIGHT_CONFIG } from 'features/controlLayers/store/lorasSlice';+import { useInputFieldIsInvalid } from 'features/nodes/hooks/useInputFieldIsInvalid';+import { fieldLoRACollectionValueChanged } from 'features/nodes/store/nodesSlice';+import { zModelIdentifierField } from 'features/nodes/types/common';+import { NO_DRAG_CLASS, NO_WHEEL_CLASS } from 'features/nodes/types/constants';+import type {+ LoRAFieldCollectionInputInstance,+ LoRAFieldCollectionInputTemplate,+ LoRAFieldValue,+} from 'features/nodes/types/field';+import { ModelPicker } from 'features/parameters/components/ModelPicker';+import { OverlayScrollbarsComponent } from 'overlayscrollbars-react';+import { memo, useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { PiXBold } from 'react-icons/pi';+import { useLoRAModels } from 'services/api/hooks/modelsByType';+import type { LoRAModelConfig } from 'services/api/types';++import type { FieldComponentProps } from './types';++const overlayscrollbarsOptions = getOverlayScrollbarsParams({}).options;++const sx = {+ borderWidth: 1,+ '&[data-error=true]': {+ borderColor: 'error.500',+ borderStyle: 'solid',+ },+} satisfies SystemStyleObject;++export const LoRAFieldCollectionInputComponent = memo(+ (props: FieldComponentProps<LoRAFieldCollectionInputInstance, LoRAFieldCollectionInputTemplate>) => {+ const { nodeId, field, fieldTemplate } = props;+ const store = useAppStore();+ const { t } = useTranslation();++ const isInvalid = useInputFieldIsInvalid(field.name);+ const [allLoRAModels, { isLoading }] = useLoRAModels();++ const value = useMemo(() => field.value ?? EMPTY_ARRAY, [field.value]);++ // Filter the picker to LoRAs compatible with the node's base model(s). The collection loaders+ // stamp `ui_model_base` so each node only offers LoRAs it can actually apply.+ const compatibleLoRAs = useMemo(() => {+ const bases = fieldTemplate.ui_model_base;+ if (!bases || bases.length === 0) {+ return allLoRAModels;+ }+ return allLoRAModels.filter((model) => bases.includes(model.base));+ }, [allLoRAModels, fieldTemplate.ui_model_base]);++ const onChangeValue = useCallback(+ (newValue: LoRAFieldValue[]) => {+ store.dispatch(fieldLoRACollectionValueChanged({ nodeId, fieldName: field.name, value: newValue }));+ },+ [field.name, nodeId, store]+ );++ const onAddLoRA = useCallback(+ (model: LoRAModelConfig) => {+ const newItem: LoRAFieldValue = {+ lora: zModelIdentifierField.parse(model),+ weight: model.default_settings?.weight ?? DEFAULT_LORA_WEIGHT_CONFIG.initial,+ };+ onChangeValue([...value, newItem]);+ },+ [onChangeValue, value]+ );++ const onRemoveLoRA = useCallback(+ (index: number) => {+ const newValue = [...value];+ newValue.splice(index, 1);+ onChangeValue(newValue);+ },+ [onChangeValue, value]+ );++ const onChangeWeight = useCallback(+ (index: number, weight: number) => {+ const newValue = [...value];+ const item = newValue[index];+ if (!item) {+ return;+ }+ newValue[index] = { ...item, weight };+ onChangeValue(newValue);+ },+ [onChangeValue, value]+ );++ // Disable LoRAs that have already been added so the user can't add duplicates (the backend+ // dedupes by key anyway, but this is clearer in the UI).+ const addedKeys = useMemo(() => new Set(value.map((item) => item.lora.key)), [value]);+ const getIsOptionDisabled = useCallback((model: LoRAModelConfig) => addedKeys.has(model.key), [addedKeys]);++ const placeholder = useMemo(() => {+ if (isLoading) {+ return t('common.loading');+ }+ if (compatibleLoRAs.length === 0) {+ return t('models.noCompatibleLoRAs');+ }+ return t('models.addLora');+ }, [compatibleLoRAs.length, isLoading, t]);++ return (+ <Flex+ className={NO_DRAG_CLASS}+ position="relative"+ w="full"+ h="auto"+ maxH={64}+ alignItems="stretch"+ justifyContent="center"+ p={1}+ sx={sx}+ data-error={isInvalid}+ borderRadius="base"+ flexDir="column"+ gap={1}+ >+ <ModelPicker+ pickerId={`lora-collection-${nodeId}-${field.name}`}+ modelConfigs={compatibleLoRAs}+ selectedModelConfig={undefined}+ onChange={onAddLoRA}+ getIsOptionDisabled={getIsOptionDisabled}+ grouped={false}+ allowEmpty+ placeholder={placeholder}+ noOptionsText={t('models.noCompatibleLoRAs')}+ />+ {value.length > 0 && (+ <>+ <Divider />+ <OverlayScrollbarsComponent+ className={NO_WHEEL_CLASS}+ defer+ style={overlayScrollbarsStyles}+ options={overlayscrollbarsOptions}+ >+ <Grid gap={1} gridTemplateColumns="1fr auto auto" alignItems="center">+ {value.map((item, index) => (+ <LoRAListItemContent+ key={`${item.lora.key}-${index}`}+ item={item}+ index={index}+ onRemoveLoRA={onRemoveLoRA}+ onChangeWeight={onChangeWeight}+ />+ ))}+ </Grid>+ </OverlayScrollbarsComponent>+ </>+ )}+ </Flex>+ );+ }+);++LoRAFieldCollectionInputComponent.displayName = 'LoRAFieldCollectionInputComponent';++type LoRAListItemContentProps = {+ item: LoRAFieldValue;+ index: number;+ onRemoveLoRA: (index: number) => void;+ onChangeWeight: (index: number, weight: number) => void;+};++const LoRAListItemContent = memo(({ item, index, onRemoveLoRA, onChangeWeight }: LoRAListItemContentProps) => {+ const { t } = useTranslation();++ const onClickRemove = useCallback(() => {+ onRemoveLoRA(index);+ }, [index, onRemoveLoRA]);++ const onChange = useCallback(+ (weight: number) => {+ onChangeWeight(index, weight);+ },+ [index, onChangeWeight]+ );++ return (+ <>+ <GridItem minW={0}>+ <Text noOfLines={1} title={item.lora.name}>+ {item.lora.name}+ </Text>+ </GridItem>+ <GridItem>+ <CompositeNumberInput+ onChange={onChange}+ value={item.weight}+ min={DEFAULT_LORA_WEIGHT_CONFIG.numberInputMin}+ max={DEFAULT_LORA_WEIGHT_CONFIG.numberInputMax}+ step={DEFAULT_LORA_WEIGHT_CONFIG.coarseStep}+ fineStep={DEFAULT_LORA_WEIGHT_CONFIG.fineStep}+ className={NO_DRAG_CLASS}+ w={20}+ allowMath+ />+ </GridItem>+ <GridItem>+ <IconButton+ tabIndex={-1}+ size="sm"+ variant="link"+ alignSelf="stretch"+ onClick={onClickRemove}+ icon={<PiXBold />}+ aria-label={t('common.delete')}+ />+ </GridItem>+ </>+ );+});+LoRAListItemContent.displayName = 'LoRAListItemContent';diff --git a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.ts b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.tsindex 9c6a9eea9f..b03eacd24f 100644--- a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.ts+++ b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.ts@@ -42,6 +42,7 @@ import type {IntegerFieldCollectionValue,IntegerFieldValue,IntegerGeneratorFieldValue,+ LoRAFieldCollectionValue,ModelIdentifierFieldValue,SchedulerFieldValue,StatefulFieldValue,@@ -64,6 +65,7 @@ import {zIntegerFieldCollectionValue,zIntegerFieldValue,zIntegerGeneratorFieldValue,+ zLoRAFieldCollectionValue,zModelIdentifierFieldValue,zSchedulerFieldValue,zStatefulFieldValue,@@ -521,6 +523,9 @@ const slice = createSlice({fieldImageCollectionValueChanged: (state, action: FieldValueAction<ImageFieldCollectionValue>) => {fieldValueReducer(state, action, zImageFieldCollectionValue);},+ fieldLoRACollectionValueChanged: (state, action: FieldValueAction<LoRAFieldCollectionValue>) => {+ fieldValueReducer(state, action, zLoRAFieldCollectionValue);+ },fieldColorValueChanged: (state, action: FieldValueAction<ColorFieldValue>) => {fieldValueReducer(state, action, zColorFieldValue);},@@ -733,6 +738,7 @@ export const {fieldImageValueChanged,fieldImageCollectionValueChanged,fieldLabelChanged,+ fieldLoRACollectionValueChanged,fieldModelIdentifierValueChanged,fieldIntegerValueChanged,fieldFloatValueChanged,@@ -862,6 +868,7 @@ const isHighFrequencyFieldChangeAction = isAnyOf(fieldFloatValueChanged,fieldFloatCollectionValueChanged,fieldIntegerCollectionValueChanged,+ fieldLoRACollectionValueChanged,fieldStringValueChanged,fieldStringCollectionValueChanged,fieldFloatGeneratorValueChanged,diff --git a/invokeai/frontend/web/src/features/nodes/types/field.test.ts b/invokeai/frontend/web/src/features/nodes/types/field.test.tsnew file mode 100644index 0000000000..589f506daa--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/types/field.test.ts@@ -0,0 +1,83 @@+import type {+ FieldType,+ LoRAFieldCollectionInputInstance,+ LoRAFieldCollectionInputTemplate,+ LoRAFieldValue,+} from 'features/nodes/types/field';+import {+ isLoRAFieldCollectionFieldType,+ isLoRAFieldCollectionInputInstance,+ isLoRAFieldCollectionInputTemplate,+ zLoRAFieldCollectionValue,+} from 'features/nodes/types/field';+import { describe, expect, it } from 'vitest';++const loraValue: LoRAFieldValue = {+ lora: {+ key: 'some-key',+ hash: 'some-hash',+ name: 'My LoRA',+ base: 'sdxl',+ type: 'lora',+ },+ weight: 0.75,+};++describe('LoRAField collection', () => {+ describe('isLoRAFieldCollectionFieldType', () => {+ it.each([+ [{ name: 'LoRAField', cardinality: 'COLLECTION', batch: false }, true],+ [{ name: 'LoRAField', cardinality: 'SINGLE_OR_COLLECTION', batch: false }, true],+ // A bare SINGLE LoRAField (e.g. the Select LoRA output) is not the editable collection type+ [{ name: 'LoRAField', cardinality: 'SINGLE', batch: false }, false],+ [{ name: 'ImageField', cardinality: 'COLLECTION', batch: false }, false],+ ] satisfies [FieldType, boolean][])('%o -> %s', (fieldType, expected) => {+ expect(isLoRAFieldCollectionFieldType(fieldType)).toBe(expected);+ });+ });++ describe('zLoRAFieldCollectionValue', () => {+ it('accepts a list of lora/weight pairs', () => {+ expect(zLoRAFieldCollectionValue.safeParse([loraValue]).success).toBe(true);+ });+ it('accepts an empty list (an empty collection is valid and lets the graph fire)', () => {+ expect(zLoRAFieldCollectionValue.safeParse([]).success).toBe(true);+ });+ it('accepts undefined', () => {+ expect(zLoRAFieldCollectionValue.safeParse(undefined).success).toBe(true);+ });+ it('rejects a non-numeric weight', () => {+ expect(zLoRAFieldCollectionValue.safeParse([{ ...loraValue, weight: 'heavy' }]).success).toBe(false);+ });+ it('rejects an item missing its lora identifier', () => {+ expect(zLoRAFieldCollectionValue.safeParse([{ weight: 1 }]).success).toBe(false);+ });+ });++ describe('input instance / template guards', () => {+ it('recognizes a valid collection input instance', () => {+ const instance: LoRAFieldCollectionInputInstance = {+ name: 'loras',+ label: '',+ description: '',+ value: [loraValue],+ };+ expect(isLoRAFieldCollectionInputInstance(instance)).toBe(true);+ });++ it('recognizes a collection input template (SINGLE_OR_COLLECTION)', () => {+ const template: LoRAFieldCollectionInputTemplate = {+ name: 'loras',+ title: 'LoRAs',+ description: '',+ ui_hidden: false,+ fieldKind: 'input',+ input: 'any',+ required: false,+ type: { name: 'LoRAField', cardinality: 'SINGLE_OR_COLLECTION', batch: false },+ default: [],+ };+ expect(isLoRAFieldCollectionInputTemplate(template)).toBe(true);+ });+ });+});diff --git a/invokeai/frontend/web/src/features/nodes/types/field.ts b/invokeai/frontend/web/src/features/nodes/types/field.tsindex df2f909dc7..e3829b0cc8 100644--- a/invokeai/frontend/web/src/features/nodes/types/field.ts+++ b/invokeai/frontend/web/src/features/nodes/types/field.ts@@ -184,6 +184,10 @@ const zModelIdentifierFieldType = zFieldTypeBase.extend({name: z.literal('ModelIdentifierField'),originalType: zStatelessFieldType.optional(),});+const zLoRAFieldType = zFieldTypeBase.extend({+ name: z.literal('LoRAField'),+ originalType: zStatelessFieldType.optional(),+});const zSchedulerFieldType = zFieldTypeBase.extend({name: z.literal('SchedulerField'),originalType: zStatelessFieldType.optional(),@@ -218,6 +222,7 @@ const zStatefulFieldType = z.union([zBoardFieldType,zStylePresetFieldType,zModelIdentifierFieldType,+ zLoRAFieldType,zColorFieldType,zSchedulerFieldType,zSavedWorkflowFieldType,@@ -682,6 +687,56 @@ export const isModelIdentifierFieldInputTemplate =buildTemplateTypeGuard<ModelIdentifierFieldInputTemplate>('ModelIdentifierField');// #endregion+// #region LoRAField Collection+/**+ * A LoRAField pairs a LoRA model identifier with a weight. The backend collection loaders accept+ * `LoRAField | list[LoRAField]`; we treat this as a stateful, inline-editable collection so the user+ * can add/remove LoRAs directly on the node. The stored value is always a list (possibly empty).+ */+const zLoRAFieldValue = z.object({+ lora: zModelIdentifierField,+ weight: z.number(),+});+export type LoRAFieldValue = z.infer<typeof zLoRAFieldValue>;+export const zLoRAFieldCollectionValue = z.array(zLoRAFieldValue).optional();++export const isLoRAFieldCollectionFieldType = (fieldType: FieldType): fieldType is z.infer<typeof zLoRAFieldType> =>+ fieldType.name === 'LoRAField' &&+ (fieldType.cardinality === COLLECTION || fieldType.cardinality === SINGLE_OR_COLLECTION);++const zLoRAFieldCollectionInputInstance = zFieldInputInstanceBase.extend({+ value: zLoRAFieldCollectionValue,+});+const zLoRAFieldCollectionInputTemplate = zFieldInputTemplateBase+ .extend({+ type: zLoRAFieldType,+ originalType: zFieldType.optional(),+ default: zLoRAFieldCollectionValue,+ maxItems: z.number().int().gte(0).optional(),+ minItems: z.number().int().gte(0).optional(),+ })+ .refine(+ (val) => {+ if (val.maxItems !== undefined && val.minItems !== undefined) {+ return val.maxItems >= val.minItems;+ }+ return true;+ },+ { message: 'maxItems must be greater than or equal to minItems' }+ );+const zLoRAFieldCollectionOutputTemplate = zFieldOutputTemplateBase.extend({+ type: zLoRAFieldType,+});+export type LoRAFieldCollectionValue = z.infer<typeof zLoRAFieldCollectionValue>;+export type LoRAFieldCollectionInputInstance = z.infer<typeof zLoRAFieldCollectionInputInstance>;+export type LoRAFieldCollectionInputTemplate = z.infer<typeof zLoRAFieldCollectionInputTemplate>;+export const isLoRAFieldCollectionInputInstance = buildInstanceTypeGuard(zLoRAFieldCollectionInputInstance);+export const isLoRAFieldCollectionInputTemplate = buildTemplateTypeGuard<LoRAFieldCollectionInputTemplate>(+ 'LoRAField',+ ['COLLECTION', 'SINGLE_OR_COLLECTION']+);+// #endregion+// #region SchedulerFieldexport const zSchedulerFieldValue = zSchedulerField.optional();const zSchedulerFieldInputInstance = zFieldInputInstanceBase.extend({@@ -1315,6 +1370,7 @@ export const zStatefulFieldValue = z.union([zBoardFieldValue,zStylePresetFieldValue,zModelIdentifierFieldValue,+ zLoRAFieldCollectionValue,zColorFieldValue,zSchedulerFieldValue,zSavedWorkflowFieldValue,@@ -1344,6 +1400,7 @@ const zStatefulFieldInputInstance = z.union([zBoardFieldInputInstance,zStylePresetFieldInputInstance,zModelIdentifierFieldInputInstance,+ zLoRAFieldCollectionInputInstance,zColorFieldInputInstance,zSchedulerFieldInputInstance,zSavedWorkflowFieldInputInstance,@@ -1372,6 +1429,7 @@ const zStatefulFieldInputTemplate = z.union([zBoardFieldInputTemplate,zStylePresetFieldInputTemplate,zModelIdentifierFieldInputTemplate,+ zLoRAFieldCollectionInputTemplate,zColorFieldInputTemplate,zSchedulerFieldInputTemplate,zSavedWorkflowFieldInputTemplate,@@ -1400,6 +1458,7 @@ const zStatefulFieldOutputTemplate = z.union([zBoardFieldOutputTemplate,zStylePresetFieldOutputTemplate,zModelIdentifierFieldOutputTemplate,+ zLoRAFieldCollectionOutputTemplate,zColorFieldOutputTemplate,zSchedulerFieldOutputTemplate,zSavedWorkflowFieldOutputTemplate,diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.tsindex 6bb3155f47..cb508789df 100644--- a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts+++ b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts@@ -10,6 +10,7 @@ const FIELD_VALUE_FALLBACK_MAP: Record<StatefulFieldType['name'], FieldValue> =ImageField: undefined,IntegerField: 0,ModelIdentifierField: undefined,+ LoRAField: [],SchedulerField: 'dpmpp_3m_k',SavedWorkflowField: '',StringField: '',diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.tsindex ca31b988ff..7751390e9d 100644--- a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts+++ b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts@@ -16,6 +16,7 @@ import type {IntegerFieldCollectionInputTemplate,IntegerFieldInputTemplate,IntegerGeneratorFieldInputTemplate,+ LoRAFieldCollectionInputTemplate,ModelIdentifierFieldInputTemplate,SavedWorkflowFieldInputTemplate,SchedulerFieldInputTemplate,@@ -34,6 +35,7 @@ import {isFloatCollectionFieldType,isImageCollectionFieldType,isIntegerCollectionFieldType,+ isLoRAFieldCollectionFieldType,isStatefulFieldType,isStringCollectionFieldType,} from 'features/nodes/types/field';@@ -341,6 +343,30 @@ const buildImageFieldCollectionInputTemplate: FieldInputTemplateBuilder<ImageFiereturn template;};+const buildLoRAFieldCollectionInputTemplate: FieldInputTemplateBuilder<LoRAFieldCollectionInputTemplate> = ({+ schemaObject,+ baseField,+ fieldType,+}) => {+ const template: LoRAFieldCollectionInputTemplate = {+ ...baseField,+ type: fieldType,+ // An empty collection is always valid, so we default to an empty list rather than leaving the+ // field unsatisfied. This is what lets a node with no LoRAs selected still fire.+ default: schemaObject.default ?? [],+ };++ if (schemaObject.minItems !== undefined) {+ template.minItems = schemaObject.minItems;+ }++ if (schemaObject.maxItems !== undefined) {+ template.maxItems = schemaObject.maxItems;+ }++ return template;+};+const buildEnumFieldInputTemplate: FieldInputTemplateBuilder<EnumFieldInputTemplate> = ({schemaObject,baseField,@@ -495,6 +521,9 @@ const TEMPLATE_BUILDER_MAP: Record<StatefulFieldType['name'], FieldInputTemplateFloatField: buildFloatFieldInputTemplate,ImageField: buildImageFieldInputTemplate,IntegerField: buildIntegerFieldInputTemplate,+ // LoRAField is always handled by the collection branch above (COLLECTION / SINGLE_OR_COLLECTION);+ // this entry is a defensive fallback to satisfy the exhaustive builder map.+ LoRAField: buildLoRAFieldCollectionInputTemplate,ModelIdentifierField: buildModelIdentifierFieldInputTemplate,SchedulerField: buildSchedulerFieldInputTemplate,SavedWorkflowField: buildSavedWorkflowFieldInputTemplate,@@ -572,6 +601,12 @@ export const buildFieldInputTemplate = (baseField,fieldType,});+ } else if (isLoRAFieldCollectionFieldType(fieldType)) {+ return buildLoRAFieldCollectionInputTemplate({+ schemaObject: fieldSchema,+ baseField,+ fieldType,+ });} else {const builder = TEMPLATE_BUILDER_MAP[fieldType.name];const template = builder({