Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): edit LoRA collections inline on the Apply LoRA Collection nodes

Lincoln Stein97293ad2afdd
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 0c09c875a9..5af94ad50f 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -8,6 +8,7 @@ export {
calculateNewSize,
clampDimension,
cloneGenerateWidgetValues,
+ DEFAULT_LORA_WEIGHT_CONFIG,
DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,
DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,
deriveAspectRatioId,
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
index 9c33652d5d..7bd1af979d 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
@@ -2,10 +2,22 @@ import { describe, expect, it } from 'vitest';
import type { FieldInputTemplate, FieldType } from './types';
-import { getWorkflowFieldInvalidReason, isModelFieldType, isWorkflowFieldValueValid } from './fields';
+import {
+ getWorkflowFieldInvalidReason,
+ isDirectInputField,
+ isLoraFieldCollectionEntry,
+ isModelFieldType,
+ isWorkflowFieldValueValid,
+ toLoraFieldCollectionList,
+} from './fields';
const single = (name: string): FieldType => ({ batch: false, cardinality: 'SINGLE', name });
+const LORA_ENTRY = {
+ lora: { base: 'sd-1', hash: 'hash', key: 'lora-key', name: 'LoRA', type: 'lora' },
+ weight: 0.75,
+};
+
const input = (overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({
default: undefined,
description: '',
@@ -100,6 +112,33 @@ describe('workflow field validation', () => {
expect(isWorkflowFieldValueValid(images, [{ image_name: 'a.png' }])).toBe(true);
});
+ it('accepts a LoRA collection as a list, a bare entry, or an empty list', () => {
+ const loras = input({
+ required: false,
+ type: { batch: false, cardinality: 'SINGLE_OR_COLLECTION', name: 'LoRAField' },
+ });
+
+ expect(isWorkflowFieldValueValid(loras, [])).toBe(true);
+ expect(isWorkflowFieldValueValid(loras, [LORA_ENTRY])).toBe(true);
+ expect(isWorkflowFieldValueValid(loras, LORA_ENTRY)).toBe(true);
+ expect(isWorkflowFieldValueValid(loras, [{ ...LORA_ENTRY, weight: 'heavy' }])).toBe(false);
+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: loras, value: [] })).toBe(null);
+ });
+
+ it('rejects a LoRA identifier missing the fields the backend requires, rather than enqueuing a 422', () => {
+ const loras = input({
+ required: false,
+ type: { batch: false, cardinality: 'SINGLE_OR_COLLECTION', name: 'LoRAField' },
+ });
+
+ // A key alone would render a nameless row and be rejected at enqueue time.
+ expect(isWorkflowFieldValueValid(loras, [{ lora: { key: 'lora-key' }, weight: 0.75 }])).toBe(false);
+ expect(isWorkflowFieldValueValid(loras, [{ ...LORA_ENTRY, lora: { ...LORA_ENTRY.lora, hash: '' } }])).toBe(false);
+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: loras, value: [{ weight: 1 }] })).toBe(
+ 'Invalid value.'
+ );
+ });
+
it('treats empty board values as the Auto sentinel', () => {
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), undefined)).toBe(true);
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), { board_id: 'board-id' })).toBe(true);
@@ -107,6 +146,33 @@ describe('workflow field validation', () => {
});
});
+describe('LoRA collection values', () => {
+ const loras = input({
+ required: false,
+ type: { batch: false, cardinality: 'SINGLE_OR_COLLECTION', name: 'LoRAField' },
+ });
+
+ it('gives the collection loaders an inline widget instead of a connection-only handle', () => {
+ expect(isDirectInputField(loras)).toBe(true);
+ });
+
+ it('normalizes the `LoRAField | list[LoRAField]` union', () => {
+ expect(toLoraFieldCollectionList([LORA_ENTRY])).toEqual([LORA_ENTRY]);
+ expect(toLoraFieldCollectionList(LORA_ENTRY)).toEqual([LORA_ENTRY]);
+ expect(toLoraFieldCollectionList(undefined)).toEqual([]);
+ expect(toLoraFieldCollectionList(null)).toEqual([]);
+ });
+
+ it('preserves unreadable items verbatim so an edit cannot silently delete them', () => {
+ // The widget writes back the list it is given; dropping or blanking these here would make one
+ // click on an unrelated row destroy a hand-authored entry.
+ const items = [LORA_ENTRY, { lora: { key: 'ghost' }, weight: 1 }, null, 'lora'];
+
+ expect(toLoraFieldCollectionList(items)).toEqual(items);
+ expect(items.filter(isLoraFieldCollectionEntry)).toEqual([LORA_ENTRY]);
+ });
+});
+
describe('workflow field type helpers', () => {
it('matches legacy model field shape classification', () => {
expect(isModelFieldType(single('ModelIdentifierField'))).toBe(true);
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
index 23d542d731..53749159d4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
@@ -15,6 +15,9 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set([
'FloatField',
'ImageField',
'IntegerField',
+ // The LoRA collection loaders take `LoRAField | list[LoRAField]`; the widget edits that list
+ // inline so a node can apply several LoRAs without a chain of Select LoRA / Collect nodes.
+ 'LoRAField',
'ModelIdentifierField',
'SchedulerField',
'StringField',
@@ -66,6 +69,48 @@ const isNonEmptyString = (value: unknown): value is string => typeof value === '
const hasNonEmptyStringProp = (value: unknown, prop: string): boolean =>
typeof value === 'object' && value !== null && isNonEmptyString((value as Record<string, unknown>)[prop]);
+/** A LoRA model identifier paired with its weight — one entry of a LoRA collection field. */
+export interface LoraFieldCollectionEntry {
+ lora: { base: string; hash: string; key: string; name: string; type: string };
+ weight: number;
+}
+
+/**
+ * Every field of the identifier is required, because that is what the backend's own
+ * `ModelIdentifierField` requires: a key-only entry renders as a nameless row and is rejected at
+ * enqueue time with a 422 that names nothing useful, so it is better treated as unreadable here.
+ */
+export const isLoraFieldCollectionEntry = (value: unknown): value is LoraFieldCollectionEntry => {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+
+ const entry = value as { lora?: unknown; weight?: unknown };
+
+ return (
+ ['base', 'hash', 'key', 'name', 'type'].every((prop) => hasNonEmptyStringProp(entry.lora, prop)) &&
+ typeof entry.weight === 'number' &&
+ Number.isFinite(entry.weight)
+ );
+};
+
+/**
+ * The collection loaders accept `LoRAField | list[LoRAField]`, so a stored value may be a single
+ * entry, a list, or absent. The widget always authors a list; normalizing on read keeps imported
+ * workflows and hand-edited JSON rendering the same way.
+ *
+ * Items are returned as-is, including ones `isLoraFieldCollectionEntry` rejects. The widget writes
+ * the list it is given straight back on the next edit, so discarding or blanking an unreadable item
+ * here would let one click on an unrelated row silently destroy a hand-authored entry.
+ */
+export const toLoraFieldCollectionList = (value: unknown): unknown[] => {
+ if (Array.isArray(value)) {
+ return value;
+ }
+
+ return value === undefined || value === null ? [] : [value];
+};
+
const isNumberFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {
if (typeof value !== 'number' || !Number.isFinite(value)) {
return false;
@@ -129,6 +174,10 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: u
return isNonEmptyString(value) && (template.options === null || template.options.includes(value));
case 'ModelIdentifierField':
return hasNonEmptyStringProp(value, 'key');
+ case 'LoRAField':
+ // An empty list is a legitimate value: a collection loader with no LoRAs passes its
+ // models through untouched.
+ return Array.isArray(value) ? value.every(isLoraFieldCollectionEntry) : isLoraFieldCollectionEntry(value);
case 'SchedulerField':
return isNonEmptyString(value);
case 'BoardField':
@@ -210,6 +259,7 @@ const FIELD_TYPE_COLORS: Record<string, string> = {
ImageField: '#c4b5fd',
IntegerField: '#f87171',
LatentsField: '#f9a8d4',
+ LoRAField: '#e879f9',
ModelIdentifierField: '#14b8a6',
SchedulerField: '#3b82f6',
StringField: '#facc15',
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts
index 2e69603c74..1233c60167 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts
@@ -1,6 +1,6 @@
import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState } from './types';
-import { isModelFieldType } from './fields';
+import { isLoraFieldCollectionEntry, isModelFieldType, toLoraFieldCollectionList } from './fields';
import { isInvocationNode } from './types';
/**
@@ -218,8 +218,37 @@ export const extractWorkflowModelRequirements = (
continue;
}
+ const addExactRequirement = (value: unknown): void => {
+ if (!isDuckTypedModelValue(value)) {
+ return;
+ }
+
+ const identifier = buildIdentifier(value);
+
+ let dedupeKey = identifier.key;
+
+ if (exactKeyHashes.has(identifier.key)) {
+ const existingHash = exactKeyHashes.get(identifier.key);
+
+ if (identifier.hash !== undefined && existingHash !== undefined && existingHash !== identifier.hash) {
+ dedupeKey = `${identifier.key}::${identifier.hash}`;
+ }
+ } else {
+ exactKeyHashes.set(identifier.key, identifier.hash);
+ }
+
+ if (seenExactDedupeKeys.has(dedupeKey)) {
+ return;
+ }
+
+ seenExactDedupeKeys.add(dedupeKey);
+ requirements.push({ identifier, kind: 'exact', label: identifier.name ?? identifier.key });
+ };
+
for (const fieldTemplate of Object.values(template.inputs)) {
- if (!isModelFieldType(fieldTemplate.type)) {
+ const isLoraCollection = fieldTemplate.type.name === 'LoRAField';
+
+ if (!isModelFieldType(fieldTemplate.type) && !isLoraCollection) {
continue;
}
@@ -229,27 +258,27 @@ export const extractWorkflowModelRequirements = (
const value = node.data.inputs[fieldTemplate.name]?.value;
- if (isDuckTypedModelValue(value)) {
- const identifier = buildIdentifier(value);
-
- let dedupeKey = identifier.key;
-
- if (exactKeyHashes.has(identifier.key)) {
- const existingHash = exactKeyHashes.get(identifier.key);
+ // A LoRA collection holds its identifiers one level down, and holds several of them. Without
+ // this the LoRAs a collection loader applies are invisible to "what does this workflow need",
+ // even though the same LoRAs wired through Select LoRA nodes are counted.
+ if (isLoraCollection) {
+ const entries = toLoraFieldCollectionList(value);
- if (identifier.hash !== undefined && existingHash !== undefined && existingHash !== identifier.hash) {
- dedupeKey = `${identifier.key}::${identifier.hash}`;
+ for (const entry of entries) {
+ if (isLoraFieldCollectionEntry(entry)) {
+ addExactRequirement(entry.lora);
}
- } else {
- exactKeyHashes.set(identifier.key, identifier.hash);
}
- if (seenExactDedupeKeys.has(dedupeKey)) {
+ // An empty collection still falls through to the slot path below, so a required-but-blank
+ // field keeps describing what it needs the way every other blank model field does.
+ if (entries.length > 0) {
continue;
}
+ }
- seenExactDedupeKeys.add(dedupeKey);
- requirements.push({ identifier, kind: 'exact', label: identifier.name ?? identifier.key });
+ if (isDuckTypedModelValue(value)) {
+ addExactRequirement(value);
continue;
}
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
index 852e392df9..1e49bd1bbd 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
@@ -92,6 +92,29 @@ const openApiFixture = {
},
type: 'object',
},
+ LoRACollectionLoaderInvocation: {
+ class: 'invocation',
+ output: { $ref: '#/components/schemas/IntegerOutput' },
+ properties: {
+ loras: {
+ anyOf: [
+ { $ref: '#/components/schemas/LoRAField' },
+ { items: { $ref: '#/components/schemas/LoRAField' }, type: 'array' },
+ { type: 'null' },
+ ],
+ default: null,
+ field_kind: 'input',
+ input: 'any',
+ orig_required: false,
+ title: 'LoRAs',
+ ui_model_base: ['sd-1', 'sd-2'],
+ ui_model_type: ['lora'],
+ },
+ type: { const: 'lora_collection_loader', default: 'lora_collection_loader', title: 'type' },
+ },
+ title: 'Apply LoRA Collection - SD1.5',
+ type: 'object',
+ },
SaveVideoInvocation: {
class: 'invocation',
output: { $ref: '#/components/schemas/IntegerOutput' },
@@ -145,7 +168,7 @@ describe('parseOpenApiToTemplates', () => {
const templates = parseOpenApiToTemplates(openApiFixture);
it('parses invocation schemas into templates, skipping the denylist', () => {
- expect(Object.keys(templates).sort()).toEqual(['add', 'denoise', 'save_video']);
+ expect(Object.keys(templates).sort()).toEqual(['add', 'denoise', 'lora_collection_loader', 'save_video']);
const add = templates.add;
@@ -184,6 +207,18 @@ describe('parseOpenApiToTemplates', () => {
expect(denoise?.inputs.scheduler?.options).toEqual(['euler', 'ddim']);
});
+ it('parses the LoRA collection loader input as an inline-editable model collection', () => {
+ // `LoRAField | list[LoRAField] | None`: the null variant drops out, leaving the union the
+ // widget edits as a list. `default: null` must not become the field's value.
+ const loras = templates.lora_collection_loader?.inputs.loras;
+
+ expect(loras?.type).toEqual({ batch: false, cardinality: 'SINGLE_OR_COLLECTION', name: 'LoRAField' });
+ expect(loras?.input).toBe('any');
+ expect(loras?.default).toBeUndefined();
+ expect(loras?.uiModelBase).toEqual(['sd-1', 'sd-2']);
+ expect(loras?.uiModelType).toEqual(['lora']);
+ });
+
it('keeps internal-kind metadata and board inputs, but drops node attributes', () => {
// `metadata` and `board` are the only two internal-kind properties in the schema, and
// both are real inputs. Without `metadata` a bundled workflow's Core Metadata edge has
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
index 70b987316b..4030fcd365 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
@@ -4,9 +4,10 @@ import { ChakraProvider } from '@chakra-ui/react';
import { DndContext } from '@dnd-kit/core';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
-import { act } from 'react';
+import { act, useCallback, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
import { WorkflowFieldInput } from './WorkflowFieldInput';
@@ -26,6 +27,50 @@ vi.mock('@features/gallery', () => ({
},
}));
+const modelSelectState = vi.hoisted(() => ({
+ props: null as null | {
+ excludeKeys?: ReadonlySet<string>;
+ filter?: (model: Record<string, unknown>) => boolean;
+ modelTypes: readonly string[];
+ onChange: (model: unknown) => void;
+ placeholder?: string;
+ },
+}));
+
+// The real picker pulls in the whole model library; the widget's contract with it is the props it
+// passes (scope, exclusions, base filter) and the model it gets back.
+vi.mock('@features/models/react', () => ({
+ ModelSelect: (props: NonNullable<typeof modelSelectState.props>) => {
+ modelSelectState.props = props;
+
+ return (
+ <button type="button" onClick={() => props.onChange(ADDABLE_LORA)}>
+ {props.placeholder}
+ </button>
+ );
+ },
+}));
+
+const SD_LORA = {
+ base: 'sd-1',
+ default_settings: { weight: 0.4 },
+ hash: 'hash-sd',
+ key: 'sd-lora',
+ name: 'Detail Tweaker',
+ type: 'lora',
+};
+const SDXL_LORA = { base: 'sdxl', hash: 'hash-sdxl', key: 'sdxl-lora', name: 'Pixel Art XL', type: 'lora' };
+// What the real picker would hand back for this template: an sd-1 LoRA carrying a model default
+// weight, so "adds at the model default" cannot pass by coincidence.
+const ADDABLE_LORA = {
+ base: 'sd-1',
+ default_settings: { weight: 0.4 },
+ hash: 'hash-add',
+ key: 'add-lora',
+ name: 'Add Me',
+ type: 'lora',
+};
+
const galleryValues: Record<string, unknown> = {};
const graphNodes: unknown[] = [];
const graphEdges: unknown[] = [];
@@ -68,6 +113,20 @@ const makeFrameNode = (videoValue: { video_name: string } | undefined) => ({
type: 'invocation',
});
+const LORA_COLLECTION_TEMPLATE = {
+ name: 'loras',
+ title: 'LoRAs',
+ type: { cardinality: 'SINGLE_OR_COLLECTION', name: 'LoRAField' },
+ uiModelBase: ['sd-1', 'sd-2'],
+ uiModelType: ['lora'],
+} as unknown as FieldInputTemplate;
+
+const loraEntry = (overrides: Record<string, unknown> = {}) => ({
+ lora: { base: 'sd-1', hash: 'hash-sd', key: 'sd-lora', name: 'Detail Tweaker', type: 'lora' },
+ weight: 0.75,
+ ...overrides,
+});
+
const SELECTED_GALLERY_VIDEO = {
boardId: 'none',
category: 'general',
@@ -94,6 +153,9 @@ beforeEach(() => {
uploadVideoMock.mockReset();
resolveItemMock.mockReset();
resolveItemMock.mockResolvedValue(SELECTED_GALLERY_VIDEO);
+ // Module-level capture: without this the next test's wait is satisfied by the previous test's
+ // props and asserts against a picker that is no longer mounted.
+ modelSelectState.props = null;
queryClient.clear();
delete galleryValues.selectedImage;
graphNodes.length = 0;
@@ -126,6 +188,30 @@ const renderField = async (
});
};
+/**
+ * Real keystrokes, not a synthetic `input` event: the weight control is a zag-js number input that
+ * ignores a value written straight onto the DOM node, and the defect being guarded against here is
+ * specifically what happens between keystrokes.
+ */
+const typeWeight = async (input: HTMLInputElement, keys: string) => {
+ await act(async () => {
+ await userEvent.click(input);
+ await userEvent.keyboard(`{Control>}a{/Control}${keys}`);
+ });
+};
+
+const pressKey = async (key: string) => {
+ await act(async () => {
+ await userEvent.keyboard(key);
+ });
+};
+
+const blurWeight = async (input: HTMLInputElement) => {
+ await act(() => {
+ input.blur();
+ });
+};
+
const findButton = (label: string): HTMLButtonElement => {
const button = Array.from(host.querySelectorAll('button')).find((el) => el.textContent?.includes(label));
@@ -385,3 +471,182 @@ describe('WorkflowFieldInput media inputs', () => {
expect(uploadVideoMock).not.toHaveBeenCalled();
});
});
+
+/**
+ * A parent that actually owns the value, the way the node editor does. The static `renderField`
+ * harness never feeds a committed value back, which hides every defect that only shows up on the
+ * re-render after a keystroke — the snap-back and the clamp-on-blur are exactly those.
+ */
+const StatefulLoRAField = ({ initial, onCommit }: { initial: unknown; onCommit: (value: unknown) => void }) => {
+ const [value, setValue] = useState(initial);
+ const onChange = useCallback(
+ (next: unknown) => {
+ setValue(next);
+ onCommit(next);
+ },
+ [onCommit]
+ );
+
+ return <WorkflowFieldInput template={LORA_COLLECTION_TEMPLATE} value={value} onChange={onChange} />;
+};
+
+describe('WorkflowFieldInput LoRA collection', () => {
+ const renderStatefulLoras = async (initial: unknown, onCommit: (value: unknown) => void) => {
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <DndContext>
+ <StatefulLoRAField initial={initial} onCommit={onCommit} />
+ </DndContext>
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
+ });
+ await vi.waitFor(() => {
+ expect(modelSelectState.props).not.toBeNull();
+ });
+ };
+
+ const renderLoras = async (value: unknown, onChange: (value: unknown) => void) => {
+ await renderField(LORA_COLLECTION_TEMPLATE, value, onChange);
+ // The picker is lazy; wait for Suspense to resolve it before asserting on the mounted widget.
+ await vi.waitFor(() => {
+ expect(modelSelectState.props).not.toBeNull();
+ });
+ };
+
+ it('scopes the picker to the LoRAs the node can apply and hides the ones already added', async () => {
+ await renderLoras([loraEntry()], vi.fn());
+
+ const props = modelSelectState.props!;
+
+ expect(props.modelTypes).toEqual(['lora']);
+ expect(Array.from(props.excludeKeys ?? [])).toEqual(['sd-lora']);
+ expect(props.filter?.(SD_LORA)).toBe(true);
+ expect(props.filter?.(SDXL_LORA)).toBe(false);
+ });
+
+ it("appends a picked LoRA at the model's own default weight", async () => {
+ const onChange = vi.fn();
+
+ await renderLoras([loraEntry()], onChange);
+ await act(() => findButton('Add LoRA…').click());
+
+ // 0.4 comes from ADDABLE_LORA.default_settings, not from DEFAULT_LORA_WEIGHT_CONFIG.initial.
+ expect(onChange).toHaveBeenCalledWith([
+ loraEntry(),
+ { lora: { base: 'sd-1', hash: 'hash-add', key: 'add-lora', name: 'Add Me', type: 'lora' }, weight: 0.4 },
+ ]);
+ });
+
+ it('edits one weight and removes one entry without disturbing the rest', async () => {
+ const onChange = vi.fn();
+ const other = loraEntry({
+ lora: { base: 'sd-1', hash: 'hash-other', key: 'other-lora', name: 'Other', type: 'lora' },
+ weight: 1,
+ });
+
+ await renderLoras([loraEntry(), other], onChange);
+
+ const weightInputs = Array.from(host.querySelectorAll<HTMLInputElement>('input'));
+
+ expect(weightInputs).toHaveLength(2);
+ expect(host.textContent).toContain('Detail Tweaker');
+ expect(host.textContent).toContain('Other');
+
+ await typeWeight(weightInputs[0]!, '0.5');
+ expect(onChange).toHaveBeenCalledWith([loraEntry({ weight: 0.5 }), other]);
+
+ const removeOther = host.querySelector<HTMLButtonElement>('button[aria-label="Remove Other"]')!;
+
+ await act(() => removeOther.click());
+ expect(onChange).toHaveBeenLastCalledWith([loraEntry()]);
+ });
+
+ it('edits the right row when the same LoRA appears twice in an imported workflow', async () => {
+ const onChange = vi.fn();
+
+ await renderLoras([loraEntry(), loraEntry({ weight: 1 })], onChange);
+
+ const removeButtons = host.querySelectorAll<HTMLButtonElement>('button[aria-label="Remove Detail Tweaker"]');
+
+ expect(removeButtons).toHaveLength(2);
+ await act(() => removeButtons[1]!.click());
+ expect(onChange).toHaveBeenCalledWith([loraEntry()]);
+ });
+
+ it('keeps a half-typed decimal instead of snapping back to the last committed number', async () => {
+ const onChange = vi.fn();
+
+ await renderStatefulLoras([loraEntry()], onChange);
+
+ const weight = host.querySelector<HTMLInputElement>('input')!;
+
+ // One keystroke at a time, because the defect lives between them: `<input type="number">`
+ // reports "" for a trailing ".", so the commit is dropped, the box is restored to "0", and the
+ // next keystroke lands as "05" = 5 — a 10x weight from a completely ordinary typing sequence.
+ await typeWeight(weight, '0');
+ await pressKey('.');
+
+ expect(weight.value).toBe('0.');
+
+ await pressKey('5');
+
+ expect(weight.value).toBe('0.5');
+ expect(onChange).toHaveBeenLastCalledWith([loraEntry({ weight: 0.5 })]);
+ // Nothing on the way there was ever an order of magnitude out.
+ expect(onChange.mock.calls.every(([value]) => (value as { weight: number }[])[0]!.weight <= 0.5)).toBe(true);
+ });
+
+ it('clamps a typed weight to the configured range on blur', async () => {
+ const onChange = vi.fn();
+
+ await renderStatefulLoras([loraEntry()], onChange);
+
+ const weight = host.querySelector<HTMLInputElement>('input')!;
+
+ await typeWeight(weight, '999');
+ await blurWeight(weight);
+
+ await vi.waitFor(() => {
+ expect(onChange).toHaveBeenLastCalledWith([loraEntry({ weight: 10 })]);
+ });
+ });
+
+ it('keeps an unreadable entry in the list and lets the user remove it', async () => {
+ const onChange = vi.fn();
+ // A key-only identifier is not renderable and the backend would reject it.
+ const broken = { lora: { key: 'ghost' }, weight: 1 };
+
+ await renderLoras([loraEntry(), broken], onChange);
+
+ expect(host.textContent).toContain('Unreadable entry');
+ // Only the readable row gets a weight control.
+ expect(host.querySelectorAll('input')).toHaveLength(1);
+
+ // Editing the good row must not drop the bad one.
+ await typeWeight(host.querySelector<HTMLInputElement>('input')!, '0.5');
+ expect(onChange).toHaveBeenLastCalledWith([loraEntry({ weight: 0.5 }), broken]);
+
+ await act(() => host.querySelector<HTMLButtonElement>('button[aria-label="Remove Unreadable entry"]')!.click());
+ expect(onChange).toHaveBeenLastCalledWith([loraEntry()]);
+ });
+
+ it('clears the field back to its default when the last entry is removed', async () => {
+ const onChange = vi.fn();
+
+ await renderLoras([loraEntry()], onChange);
+ await act(() => host.querySelector<HTMLButtonElement>('button[aria-label="Remove Detail Tweaker"]')!.click());
+
+ // `undefined`, not `[]`: the loaders default to no LoRAs, so the node returns to its default.
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+
+ it('renders a single stored LoRAField as a one-row list rather than falling back', async () => {
+ await renderLoras(loraEntry(), vi.fn());
+
+ expect(host.textContent).not.toContain('Connection only');
+ expect(host.querySelectorAll('input')).toHaveLength(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index 5f76dbe65b..9f332006e2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -1,7 +1,21 @@
import type { ModelConfig, ModelTaxonomyType } from '@features/models/react';
import type { FieldInputTemplate } from '@features/workflow/contracts';
+import type { LoraFieldCollectionEntry } from '@features/workflow/utility';
-import { Badge, Box, createListCollection, Flex, HStack, Icon, Image, Input, Switch, Text } from '@chakra-ui/react';
+import {
+ Badge,
+ Box,
+ createListCollection,
+ Flex,
+ HStack,
+ Icon,
+ Image,
+ Input,
+ NumberInput,
+ Stack,
+ Switch,
+ Text,
+} from '@chakra-ui/react';
import { useDndContext, useDndMonitor, useDroppable, type DragEndEvent } from '@dnd-kit/core';
import {
formatGalleryVideoDuration,
@@ -14,7 +28,7 @@ import {
import { getSelectedGalleryImageFromValues, getSelectedGalleryItemFromValues } from '@features/gallery/contracts';
import { invalidateGallery } from '@features/gallery/queries';
import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';
-import { SCHEDULER_OPTIONS } from '@features/generation/settings';
+import { DEFAULT_LORA_WEIGHT_CONFIG, SCHEDULER_OPTIONS } from '@features/generation/settings';
import { isInvocationNode } from '@features/workflow/contracts';
import {
getWorkflowMediaFieldDropId,
@@ -22,7 +36,11 @@ import {
type WorkflowMediaKind,
} from '@features/workflow/ui/fields/mediaFieldDnd';
import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';
-import { getResolvedWorkflowEdges } from '@features/workflow/utility';
+import {
+ getResolvedWorkflowEdges,
+ isLoraFieldCollectionEntry,
+ toLoraFieldCollectionList,
+} from '@features/workflow/utility';
import {
assertAccountScopeCurrent,
captureAccountScope,
@@ -36,14 +54,17 @@ import {
Combobox,
DropZone,
formatHexColor,
+ IconButton,
parseHexColor,
ResizableTextarea,
Select,
Slider,
toaster,
+ Tooltip,
} from '@platform/ui';
+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { FilmIcon, ImageIcon } from 'lucide-react';
+import { FilmIcon, ImageIcon, Trash2Icon } from 'lucide-react';
import { lazy, Suspense, useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent } from 'react';
const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));
@@ -935,6 +956,183 @@ const ColorInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {
);
};
+const LORA_MODEL_TYPES: ModelTaxonomyType[] = ['lora'];
+
+/**
+ * The `Apply LoRA Collection` loaders take `LoRAField | list[LoRAField]`. Rather than making the
+ * user wire up one `Select LoRA` node per LoRA and collect them, this edits the list in place: pick
+ * a LoRA from the model picker to append it, then tune each weight on its own row.
+ *
+ * Rows address entries by index, not by model key. The picker keeps the user from adding a
+ * duplicate, but an imported workflow can already contain one, and a key-based edit would hit every
+ * copy at once. Indexing also keeps entries this widget cannot read (`null` holes from
+ * `normalizeLoraFieldCollectionValue`) in place instead of dropping them on the next edit.
+ */
+const LoRACollectionInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {
+ // The raw list, unreadable items included — see `toLoraFieldCollectionList`.
+ const entries = useMemo(() => toLoraFieldCollectionList(value), [value]);
+ const selectedKeys = useMemo(
+ () => new Set(entries.filter(isLoraFieldCollectionEntry).map((entry) => entry.lora.key)),
+ [entries]
+ );
+ // The loaders stamp `ui_model_base`, so each node offers only the LoRAs it can actually apply.
+ const allowedBases = template.uiModelBase;
+ const filter = useCallback(
+ (model: ModelConfig) => (allowedBases ? allowedBases.includes(model.base) : true),
+ [allowedBases]
+ );
+ // An emptied list is written back as `undefined` rather than `[]`: it is the loaders' own default,
+ // so the node returns to "no LoRAs" instead of sitting on a value that is equal in effect but
+ // different from its default.
+ const commit = useCallback((next: unknown[]) => onChange(next.length === 0 ? undefined : next), [onChange]);
+ const onAdd = useCallback(
+ (model: ModelConfig | null) => {
+ // The picker already excludes what is in the list; the guard covers a stale selection.
+ if (!model || selectedKeys.has(model.key)) {
+ return;
+ }
+
+ const defaultWeight = model.default_settings?.weight;
+ const entry: LoraFieldCollectionEntry = {
+ lora: { base: model.base, hash: model.hash, key: model.key, name: model.name, type: model.type },
+ weight:
+ typeof defaultWeight === 'number' && Number.isFinite(defaultWeight)
+ ? defaultWeight
+ : DEFAULT_LORA_WEIGHT_CONFIG.initial,
+ };
+
+ commit([...entries, entry]);
+ },
+ [commit, entries, selectedKeys]
+ );
+ const onRemove = useCallback(
+ (index: number) => commit(entries.filter((_, entryIndex) => entryIndex !== index)),
+ [commit, entries]
+ );
+ const onWeightChange = useCallback(
+ (index: number, weight: number) =>
+ commit(
+ entries.map((entry, entryIndex) =>
+ entryIndex === index && isLoraFieldCollectionEntry(entry) ? { ...entry, weight } : entry
+ )
+ ),
+ [commit, entries]
+ );
+
+ return (
+ <Stack gap="1" w="full">
+ <Suspense fallback={MODEL_SELECT_FALLBACK}>
+ <ModelSelect
+ className="nodrag nowheel"
+ excludeKeys={selectedKeys}
+ filter={allowedBases ? filter : undefined}
+ id={id ? `${id}-lora-combobox` : undefined}
+ invalid={invalid}
+ modelTypes={(template.uiModelType as ModelTaxonomyType[] | null) ?? LORA_MODEL_TYPES}
+ placeholder="Add LoRA…"
+ size="xs"
+ value={null}
+ onChange={onAdd}
+ />
+ </Suspense>
+ {entries.length > 0 ? (
+ <Stack className="nowheel" gap="1" maxH="40" overflowY="auto" w="full">
+ {entries.map((item, index) => (
+ <LoRACollectionRow
+ key={isLoraFieldCollectionEntry(item) ? `${item.lora.key}-${index}` : `unreadable-${index}`}
+ entry={isLoraFieldCollectionEntry(item) ? item : null}
+ id={id}
+ index={index}
+ onRemove={onRemove}
+ onWeightChange={onWeightChange}
+ />
+ ))}
+ </Stack>
+ ) : null}
+ </Stack>
+ );
+};
+
+const LoRACollectionRow = ({
+ entry,
+ id,
+ index,
+ onRemove,
+ onWeightChange,
+}: {
+ entry: LoraFieldCollectionEntry | null;
+ id?: string;
+ index: number;
+ onRemove: (index: number) => void;
+ onWeightChange: (index: number, weight: number) => void;
+}) => {
+ const label = entry ? entry.lora.name : 'Unreadable entry';
+ // The committed value is a number, so re-rendering from it alone would rewrite a half-typed
+ // "0." to "0" mid-keystroke and turn the next digit into "05" — a 10x wrong weight from a
+ // plausible typing sequence. The draft holds the raw text until the field is left; blur drops
+ // it so the row picks up the committed (and range-clamped) value again.
+ const [draft, setDraft] = useState<string | null>(null);
+ const onRemoveClick = useCallback(() => onRemove(index), [index, onRemove]);
+ const onValueChange = useCallback(
+ ({ value: valueAsText, valueAsNumber }: NumberInput.ValueChangeDetails) => {
+ setDraft(valueAsText);
+
+ if (Number.isFinite(valueAsNumber)) {
+ onWeightChange(index, valueAsNumber);
+ }
+ },
+ [index, onWeightChange]
+ );
+ const onFocusChange = useCallback(({ focused }: NumberInput.FocusChangeDetails) => {
+ if (!focused) {
+ setDraft(null);
+ }
+ }, []);
+
+ return (
+ <HStack gap="1" minW="0" w="full">
+ <Tooltip content={entry ? label : 'This entry is not a readable LoRA and will block invoking.'}>
+ <MiddleTruncate color={entry ? undefined : 'fg.error'} flex="1" fontSize="2xs" minW="0" text={label} />
+ </Tooltip>
+ {entry ? (
+ <NumberInput.Root
+ className="nodrag"
+ // Stated rather than left to the default: `min`/`max` are otherwise advisory here, and a
+ // mistyped 999 would run — the backend takes an unbounded float and nothing downstream
+ // rejects it.
+ clampValueOnBlur
+ flexShrink="0"
+ max={DEFAULT_LORA_WEIGHT_CONFIG.numberInputMax}
+ min={DEFAULT_LORA_WEIGHT_CONFIG.numberInputMin}
+ size="xs"
+ step={DEFAULT_LORA_WEIGHT_CONFIG.coarseStep}
+ value={draft ?? String(entry.weight)}
+ w="16"
+ onFocusChange={onFocusChange}
+ onValueChange={onValueChange}
+ >
+ <NumberInput.Input
+ aria-label={`${label} weight`}
+ fontVariantNumeric="tabular-nums"
+ id={id ? `${id}-lora-${index}-weight` : undefined}
+ />
+ </NumberInput.Root>
+ ) : null}
+ <IconButton
+ aria-label={`Remove ${label}`}
+ className="nodrag"
+ color="fg.muted"
+ flexShrink="0"
+ size="2xs"
+ variant="ghost"
+ onClick={onRemoveClick}
+ >
+ <Trash2Icon />
+ </IconButton>
+ </HStack>
+ );
+};
+
const CONNECTION_ONLY_FALLBACK = (
<Text color="fg.subtle" fontSize="2xs">
Connection only
@@ -968,6 +1166,8 @@ export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
return <BooleanInput {...props} />;
case 'EnumField':
return <EnumInput {...props} />;
+ case 'LoRAField':
+ return <LoRACollectionInput {...props} />;
case 'ModelIdentifierField':
return <ModelIdentifierInput {...props} />;
case 'SchedulerField':