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(webv2): edit integer, float, and string collection fields inline
Josh Corbett21d5ca1ed7eb
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 2f0a2281f5..bd11587322 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1506,6 +1506,11 @@"forLoopBodyBoundary": "For loop body","imageCollectionCount_one": "{{count}} image","imageCollectionCount_other": "{{count}} images",+ "addItem": "Add item",+ "removeItem": "Remove {{field}} item {{index}}",+ "collectionItemLabel": "{{field}} item {{index}}",+ "collectionItemCount_one": "{{count}} item",+ "collectionItemCount_other": "{{count}} items","forLoopBodyBoundaryStatus": {"missing_linkage": "missing loop linkage","invalid_linkage": "invalid loop linkage",diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.tsindex 14d71f54a9..b386bfab6c 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts@@ -425,6 +425,14 @@ describe('getProjectGraphUndoEntry', () => {expect(getProjectGraphUndoEntry({ fieldName: 'a', nodeId: 'n', type: 'setFieldValue', value: true })).toEqual({label: 'Edit workflow field value',});+ // Typing into a scalar list row streams like a scalar; picking images into a list does not.+ expect(+ getProjectGraphUndoEntry({ fieldName: 'a', nodeId: 'n', type: 'setFieldValue', value: [1, null, 'x'] })?.mergeKey+ ).toBe('setFieldValue:n:a');+ expect(+ getProjectGraphUndoEntry({ fieldName: 'a', nodeId: 'n', type: 'setFieldValue', value: [{ image_name: 'a' }] })+ ?.mergeKey+ ).toBeUndefined();expect(getProjectGraphUndoEntry({ fieldName: 'workflow_id', nodeId: 'n', type: 'setFieldValue', value: 'workflow-a' })).toEqual({diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.tsindex 13789177a2..a21e62e0dc 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts@@ -366,16 +366,20 @@ export interface ProjectGraphUndoEntry {mergeKey?: string;}+const isScalarList = (value: unknown): boolean =>+ Array.isArray(value) && value.every((item) => typeof item === 'string' || typeof item === 'number' || item === null);+const getUndoMergeKey = (action: ProjectGraphAction): string | undefined => {switch (action.type) {case 'setFieldDescription':case 'setFieldLabel':return `${action.type}:${action.nodeId}:${action.fieldName}`;case 'setFieldValue':- // Typed text and dragged numbers stream; a pick (model, board, switch) is one step of its own.+ // Typed text and dragged numbers stream, as do the rows of a scalar list; a pick (model, board,+ // switch, image list) is one step of its own.return action.fieldName === 'workflow_id'? undefined- : typeof action.value === 'string' || typeof action.value === 'number'+ : typeof action.value === 'string' || typeof action.value === 'number' || isScalarList(action.value)? `${action.type}:${action.nodeId}:${action.fieldName}`: undefined;case 'setNodeLabel':diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.tsindex 3590f7937c..781a075688 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts@@ -8,6 +8,7 @@ import {isDirectInputField,isLoraFieldCollectionEntry,isModelFieldType,+ isWorkflowCollectionItemValid,isWorkflowFieldValueValid,toLoraFieldCollectionList,getRandomWorkflowFieldValue,@@ -186,16 +187,69 @@ describe('workflow field validation', () => {expect(isWorkflowFieldValueValid(images, { image_name: 'a.png' })).toBe(false);});- it('exposes image collections as direct inputs but keeps other collections connection-only', () => {+ it('exposes image and scalar collections as direct inputs but keeps other collections connection-only', () => {expect(isDirectInputField(input({ type: { batch: false, cardinality: 'COLLECTION', name: 'ImageField' } }))).toBe(true);expect(isDirectInputField(input({ type: { batch: false, cardinality: 'COLLECTION', name: 'VideoField' } }))).toBe(false);- expect(isDirectInputField(input({ type: { batch: false, cardinality: 'COLLECTION', name: 'StringField' } }))).toBe(- false- );++ for (const name of ['StringField', 'IntegerField', 'FloatField']) {+ const template = input({ type: { batch: false, cardinality: 'COLLECTION', name } });++ expect(isDirectInputField(template)).toBe(true);+ // A list has no single number to randomize.+ expect(isShuffleableField(template)).toBe(false);+ }+ });++ describe('scalar collections', () => {+ const list = (name: string, overrides: Partial<FieldInputTemplate> = {}) =>+ input({ type: { batch: false, cardinality: 'COLLECTION', name }, ...overrides });+ const reason = (template: FieldInputTemplate, value: unknown) =>+ getWorkflowFieldInvalidReason({ isConnected: false, template, value });++ it('validates each entry with the scalar rules and reports the first bad one by position', () => {+ const integers = list('IntegerField', { minimum: 0, multipleOf: 2 });++ expect(isWorkflowFieldValueValid(integers, [0, 2, 4])).toBe(true);+ expect(isWorkflowFieldValueValid(integers, [])).toBe(true);+ expect(isWorkflowFieldValueValid(integers, 2)).toBe(false);+ expect(reason(integers, [2, 3])).toBe('Item 2 is invalid.');+ expect(reason(integers, [2, -2])).toBe('Item 2 is invalid.');+ expect(reason(integers, [2, 2.5])).toBe('Item 2 is invalid.');+ expect(reason(integers, [null, 2])).toBe('Item 1 is empty.');+ expect(isWorkflowCollectionItemValid(integers, 3)).toBe(false);+ expect(isWorkflowCollectionItemValid(integers, 4)).toBe(true);++ const strings = list('StringField', { maxLength: 3, minLength: 1 });++ expect(isWorkflowFieldValueValid(strings, ['a', 'abc'])).toBe(true);+ expect(reason(strings, ['a', ''])).toBe('Item 2 is invalid.');+ expect(reason(strings, ['abcd'])).toBe('Item 1 is invalid.');+ expect(reason(strings, ['a', 7])).toBe('Item 2 is invalid.');+ });++ it('enforces item counts before entries', () => {+ const floats = list('FloatField', { maxItems: 2, minItems: 1 });++ expect(reason(floats, [])).toBe('Collection is empty.');+ expect(reason(floats, [1, 2, 3])).toBe('Allows at most 2 items.');+ expect(reason(list('FloatField', { minItems: 2 }), [1])).toBe('Needs at least 2 items.');+ expect(reason(list('FloatField', { minItems: 2 }), [])).toBe('Collection is empty.');+ expect(reason(floats, [1, 2])).toBeNull();+ // Image lists share the count rules; their entries keep the image-ref check.+ expect(reason(list('ImageField', { minItems: 1 }), [])).toBe('Collection is empty.');+ expect(reason(list('ImageField'), [{ image_name: 'a.png' }, { image_name: '' }])).toBe('Item 2 is invalid.');+ });++ it('tells a missing required list apart from an empty optional one', () => {+ expect(reason(list('IntegerField'), undefined)).toBe('Required value.');+ expect(reason(list('IntegerField', { required: false }), undefined)).toBeNull();+ expect(reason(list('IntegerField', { required: false }), [null])).toBe('Item 1 is empty.');+ expect(reason(list('IntegerField', { input: 'connection' }), undefined)).toBe('Required connection.');+ });});it('accepts a LoRA collection as a list, a bare entry, or an empty list', () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.tsindex 142fae6f3e..0a4c3b3492 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts@@ -44,20 +44,26 @@ const MODEL_FIELD_TYPE_NAMES = new Set([export const isModelFieldType = (type: FieldType): boolean => MODEL_FIELD_TYPE_NAMES.has(type.name);/** Collection field types with a direct-input list widget; other collections are connection-only. */-const DIRECT_COLLECTION_FIELD_TYPE_NAMES = new Set(['ImageField']);+const DIRECT_COLLECTION_FIELD_TYPE_NAMES = new Set(['FloatField', 'ImageField', 'IntegerField', 'StringField']);++/** A list the editor can author item by item. */+export const isEditableCollectionFieldType = (type: FieldType): boolean =>+ type.cardinality === 'COLLECTION' && DIRECT_COLLECTION_FIELD_TYPE_NAMES.has(type.name);/** True when the field renders an editable control on the node / linear form. */export const isDirectInputField = (template: FieldInputTemplate): boolean =>template.input !== 'connection' &&isStatefulFieldType(template.type) &&- (template.type.cardinality !== 'COLLECTION' || DIRECT_COLLECTION_FIELD_TYPE_NAMES.has(template.type.name));+ (template.type.cardinality !== 'COLLECTION' || isEditableCollectionFieldType(template.type));/** A field can be exposed to the Linear UI when it can be edited directly. */export const isExposableField = (template: FieldInputTemplate): boolean => isDirectInputField(template);-/** Numeric fields whose linear-form element can show a randomize button. */+/** Scalar numeric fields whose linear-form element can show a randomize button. */export const isShuffleableField = (template: FieldInputTemplate): boolean =>- (template.type.name === 'IntegerField' || template.type.name === 'FloatField') && isDirectInputField(template);+ (template.type.name === 'IntegerField' || template.type.name === 'FloatField') &&+ template.type.cardinality !== 'COLLECTION' &&+ isDirectInputField(template);const countDecimals = (value: number): number => {const [, fraction = ''] = String(value).split('.');@@ -205,6 +211,60 @@ const isNumberFieldValueValid = (template: FieldInputTemplate, value: unknown):return true;};+const isStringFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {+ if (typeof value !== 'string') {+ return false;+ }++ const minLength = finiteNumberOrNull(template.minLength);+ const maxLength = finiteNumberOrNull(template.maxLength);++ return (minLength === null || value.length >= minLength) && (maxLength === null || value.length <= maxLength);+};++/** One entry of an editable list, judged by the template's per-item rules. */+export const isWorkflowCollectionItemValid = (template: FieldInputTemplate, item: unknown): boolean => {+ switch (template.type.name) {+ case 'StringField':+ return isStringFieldValueValid(template, item);+ case 'IntegerField':+ case 'FloatField':+ return isNumberFieldValueValid(template, item);+ case 'ImageField':+ return hasNonEmptyStringProp(item, 'image_name');+ default:+ return item !== undefined && item !== null;+ }+};++/** Count rules first, then the first bad entry, so the message names one thing to fix. */+const getCollectionInvalidReason = (template: FieldInputTemplate, items: readonly unknown[]): string | null => {+ const minItems = finiteNumberOrNull(template.minItems);+ const maxItems = finiteNumberOrNull(template.maxItems);++ if (minItems !== null && minItems > 0 && items.length === 0) {+ return 'Collection is empty.';+ }++ if (minItems !== null && items.length < minItems) {+ return `Needs at least ${minItems} items.`;+ }++ if (maxItems !== null && items.length > maxItems) {+ return `Allows at most ${maxItems} items.`;+ }++ const badIndex = items.findIndex((item) => !isWorkflowCollectionItemValid(template, item));++ if (badIndex === -1) {+ return null;+ }++ return items[badIndex] === null || items[badIndex] === undefined+ ? `Item ${badIndex + 1} is empty.`+ : `Item ${badIndex + 1} is invalid.`;+};+const isColorValueValid = (value: unknown): boolean => {if (typeof value !== 'object' || value === null) {return false;@@ -220,11 +280,22 @@ const isColorValueValid = (value: unknown): boolean => {};export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {+ if (+ template.type.cardinality === 'COLLECTION' &&+ (template.type.name === 'StringField' ||+ template.type.name === 'IntegerField' ||+ template.type.name === 'FloatField' ||+ template.type.name === 'ImageField')+ ) {+ return Array.isArray(value) && getCollectionInvalidReason(template, value) === null;+ }+switch (template.type.name) {case 'SavedWorkflowField':+ return typeof value === 'string';case 'StringField':// An empty string is a legitimate string value (e.g. a blank negative prompt).- return typeof value === 'string';+ return isStringFieldValueValid(template, value);case 'IntegerField':case 'FloatField':return isNumberFieldValueValid(template, value);@@ -258,10 +329,6 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: uhasNonEmptyStringProp(value, 'board_id'));case 'ImageField':- if (template.type.cardinality === 'COLLECTION') {- return Array.isArray(value) && value.every((item) => hasNonEmptyStringProp(item, 'image_name'));- }-return hasNonEmptyStringProp(value, 'image_name');case 'VideoField':// COLLECTION video values are arrays no direct-input widget authors; keep the@@ -297,6 +364,11 @@ export const getWorkflowFieldInvalidReason = ({return null;}+ // An editable list reports which count or entry rule it breaks; the generic reasons cannot say.+ if (template.type.cardinality === 'COLLECTION' && Array.isArray(value) && isDirectInputField(template)) {+ return getCollectionInvalidReason(template, value);+ }+if (!template.required) {return isDirectInputField(template) && !isWorkflowFieldValueValid(template, value) ? 'Invalid value.' : null;}diff --git a/invokeai/frontend/webv2/src/features/workflow/core/types.ts b/invokeai/frontend/webv2/src/features/workflow/core/types.tsindex 5102285a53..c117687f2f 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/types.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/types.ts@@ -37,6 +37,12 @@ export interface FieldInputTemplate {exclusiveMinimum: number | null;exclusiveMaximum: number | null;multipleOf: number | null;+ /** Item-count bounds of a collection; absent on templates built before lists were editable. */+ minItems?: number | null;+ maxItems?: number | null;+ /** String length bounds, applied per item for string collections. */+ minLength?: number | null;+ maxLength?: number | null;uiModelBase: string[] | null;uiModelFormat: string[] | null;uiModelType: string[] | null;diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.tsindex 17559bd970..294425da56 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts@@ -61,6 +61,42 @@ const openApiFixture = {orig_required: true,title: 'Prompts',},+ steps: {+ anyOf: [+ { items: { maximum: 100, minimum: 1, type: 'integer' }, maxItems: 4, minItems: 1, type: 'array' },+ { type: 'null' },+ ],+ field_kind: 'input',+ input: 'any',+ orig_required: true,+ title: 'Steps',+ },+ tags: {+ default: ['a'],+ field_kind: 'input',+ input: 'any',+ items: { maxLength: 8, type: 'string' },+ orig_required: false,+ title: 'Tags',+ type: 'array',+ },+ videos: {+ anyOf: [+ { items: { $ref: '#/components/schemas/VideoField' }, minItems: 2, type: 'array' },+ { type: 'null' },+ ],+ field_kind: 'input',+ input: 'any',+ orig_required: true,+ title: 'Videos',+ },+ weights: {+ anyOf: [{ items: { type: 'number' }, type: 'array' }, { type: 'null' }],+ field_kind: 'input',+ input: 'connection',+ orig_required: true,+ title: 'Weights',+ },scheduler: {default: 'euler',enum: ['euler', 'ddim'],@@ -207,6 +243,23 @@ describe('parseOpenApiToTemplates', () => {expect(denoise?.inputs.scheduler?.options).toEqual(['euler', 'ddim']);});+ it('reads list bounds and item constraints from the array schema of a collection input', () => {+ const denoise = templates.denoise;+ const steps = denoise?.inputs.steps;++ // `Optional[list[int]]` keeps its limits inside the array branch of the union.+ expect(steps?.type).toEqual({ batch: false, cardinality: 'COLLECTION', name: 'IntegerField' });+ expect(steps).toMatchObject({ maxItems: 4, maximum: 100, minItems: 1, minimum: 1 });+ // A required editable list starts empty; a connection-only or optional one keeps no default, and so does a+ // required list with no editor (readiness must still demand its connection).+ expect(steps?.default).toEqual([]);+ expect(denoise?.inputs.weights?.default).toBeUndefined();+ expect(denoise?.inputs.videos).toMatchObject({ default: undefined, minItems: 2, required: true });+ expect(denoise?.inputs.tags).toMatchObject({ default: ['a'], maxItems: null, maxLength: 8, minItems: null });+ // Scalars never carry list bounds.+ expect(denoise?.inputs.scheduler).not.toHaveProperty('minItems');+ });+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.diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.tsindex adfcad6d1f..f431b00bd0 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts@@ -7,6 +7,7 @@ import type {InvocationTemplatesSnapshot,} from '@features/workflow/core/types';+import { isEditableCollectionFieldType } from '@features/workflow/core/fields';import { createLogger } from '@platform/logging/logger';import {captureAccountScope,@@ -209,6 +210,23 @@ const getDefaultValueForType = (type: FieldType, options: unknown[] | null): unk}};+/** The array schema of a list property: the property itself, or the array branch of an `Optional[list[...]]`. */+const getArraySchema = (property: JsonObject): JsonObject | null => {+ if (property.type === 'array') {+ return property;+ }++ if (Array.isArray(property.anyOf)) {+ const arrays = property.anyOf.filter(+ (variant): variant is JsonObject => isJsonObject(variant) && variant.type === 'array'+ );++ return arrays.length === 1 ? (arrays[0] as JsonObject) : null;+ }++ return null;+};+const buildInputTemplate = (name: string,property: JsonObject,@@ -216,6 +234,9 @@ const buildInputTemplate = (fieldKind: FieldInputTemplate['fieldKind']): FieldInputTemplate => {const enumValues = getEnumValues(property);+ const arraySchema = type.cardinality === 'COLLECTION' ? getArraySchema(property) : null;+ // pydantic places a list's item constraints on `items`; scalar constraints stay on the property.+ const constraints = arraySchema && isJsonObject(arraySchema.items) ? arraySchema.items : property;const options = enumValues? enumValues.every((value) =>@@ -235,24 +256,38 @@ const buildInputTemplate = (): null;+ const required = property.orig_required === true;+return {default:- type.name === 'EnumField' && property.default === null && property.orig_required !== true+ type.name === 'EnumField' && property.default === null && !required? undefined: property.default !== undefined && property.default !== null? property.default- : getDefaultValueForType(type, options),+ : // A required editable list starts empty so the widget has something to append to; a list+ // without a widget stays absent so readiness still asks for its connection.+ required && input !== 'connection' && isEditableCollectionFieldType(type)+ ? []+ : getDefaultValueForType(type, options),description: typeof property.description === 'string' ? property.description : '',- exclusiveMaximum: getNumberOrNull(property.exclusiveMaximum),- exclusiveMinimum: getNumberOrNull(property.exclusiveMinimum),+ exclusiveMaximum: getNumberOrNull(constraints.exclusiveMaximum),+ exclusiveMinimum: getNumberOrNull(constraints.exclusiveMinimum),fieldKind,input,- maximum: getNumberOrNull(property.maximum),- minimum: getNumberOrNull(property.minimum),- multipleOf: getNumberOrNull(property.multipleOf),+ maximum: getNumberOrNull(constraints.maximum),+ minimum: getNumberOrNull(constraints.minimum),+ multipleOf: getNumberOrNull(constraints.multipleOf),name,options,- required: property.orig_required === true,+ required,+ ...(arraySchema+ ? {+ maxItems: getNumberOrNull(arraySchema.maxItems),+ maxLength: getNumberOrNull(constraints.maxLength),+ minItems: getNumberOrNull(arraySchema.minItems),+ minLength: getNumberOrNull(constraints.minLength),+ }+ : {}),title: typeof property.title === 'string' ? property.title : startCase(name),type,uiChoiceLabels,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.tsxindex 3dba1f5c43..fff158fa8a 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@@ -1706,3 +1706,137 @@ describe('WorkflowFieldInput text and number entry', () => {});});});++describe('WorkflowFieldInput scalar collections', () => {+ let renderCount = 0;+ const list = (typeName: 'FloatField' | 'IntegerField' | 'StringField', overrides: Partial<FieldInputTemplate> = {}) =>+ fullTemplate(typeName, { type: { batch: false, cardinality: 'COLLECTION', name: typeName }, ...overrides });+ const renderList = async (template: FieldInputTemplate, initial: unknown, echo?: 'deferred' | 'sync') => {+ const onCommit = vi.fn();++ renderCount += 1;+ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <StatefulField key={renderCount} echo={echo} initial={initial} template={template} onCommit={onCommit} />+ </ChakraProvider>+ );+ });++ return { onCommit };+ };+ // Browser tests render raw i18n keys, so interpolated row names collapse to one key: rows are found by position.+ const row = (index: number) =>+ host.querySelectorAll<HTMLInputElement>('input[aria-label="nodes.collectionItemLabel"]')[index - 1] ?? null;+ const rows = () => host.querySelectorAll('input[aria-label="nodes.collectionItemLabel"]').length;+ const button = (label: 'nodes.addItem' | 'common.clear') => findButton(label);+ const removeButton = (index: number) =>+ host.querySelectorAll<HTMLButtonElement>('button[aria-label="nodes.removeItem"]')[index - 1]!;+ const click = (element: HTMLElement) =>+ act(async () => {+ await userEvent.click(element);+ });+ const keys = (sequence: string) =>+ act(async () => {+ await userEvent.keyboard(sequence);+ });+ const isInvalid = (input: HTMLElement | null) => input?.getAttribute('aria-invalid') === 'true';++ it('appends, edits, and removes rows while each keystroke echoes back late', async () => {+ const { onCommit } = await renderList(list('IntegerField'), [1, 2], 'deferred');++ expect(rows()).toBe(2);+ await click(button('nodes.addItem'));+ expect(onCommit).toHaveBeenLastCalledWith([1, 2, 0]);+ expect(rows()).toBe(3);++ const third = row(3)!;++ await click(third);+ await keys('{Control>}a{/Control}42');+ expect(third.value).toBe('42');+ expect(onCommit).toHaveBeenLastCalledWith([1, 2, 42]);+ await keys('{Home}7');+ expect(third.value).toBe('742');+ expect(third.selectionStart).toBeNull(); // number inputs expose no caret; focus is the tell+ expect(document.activeElement).toBe(third);+ expect(onCommit).toHaveBeenLastCalledWith([1, 2, 742]);++ await click(removeButton(2));+ expect(onCommit).toHaveBeenLastCalledWith([1, 742]);+ expect(rows()).toBe(2);+ expect(row(2)?.value).toBe('742');+ });++ it('marks only the cleared or out-of-range row invalid and keeps the entry as typed', async () => {+ const { onCommit } = await renderList(list('IntegerField', { minimum: 0 }), [1, 2]);+ const first = row(1)!;++ await click(first);+ await keys('{Control>}a{/Control}{Backspace}-');+ expect(first.value).toBe('');+ expect(onCommit).toHaveBeenLastCalledWith([null, 2]);+ expect(isInvalid(first)).toBe(true);+ expect(isInvalid(row(2))).toBe(false);++ await keys('3');+ expect(first.value).toBe('-3');+ expect(onCommit).toHaveBeenLastCalledWith([-3, 2]);+ expect(isInvalid(first)).toBe(true);++ await keys('{Home}{Delete}');+ expect(first.value).toBe('3');+ expect(onCommit).toHaveBeenLastCalledWith([3, 2]);+ expect(isInvalid(first)).toBe(false);+ });++ it('clears a required list to empty and an optional one back to its absent default', async () => {+ const required = await renderList(list('StringField'), ['a', 'b']);++ await click(button('common.clear'));+ expect(required.onCommit).toHaveBeenLastCalledWith([]);+ expect(rows()).toBe(0);+ expect(Array.from(host.querySelectorAll('button')).map((element) => element.textContent)).not.toContain(+ 'common.clear'+ );++ await click(button('nodes.addItem'));+ expect(required.onCommit).toHaveBeenLastCalledWith(['']);+ await click(row(1)!);+ await keys('hello');+ expect(required.onCommit).toHaveBeenLastCalledWith(['hello']);++ const optional = await renderList(list('FloatField', { required: false }), [0.5]);++ await click(removeButton(1));+ expect(optional.onCommit).toHaveBeenLastCalledWith(undefined);+ expect(rows()).toBe(0);+ });++ it('keeps keyboard focus in the list when a removal or clear unmounts the focused button', async () => {+ const { onCommit } = await renderList(list('IntegerField'), [1, 2, 3]);++ // Removing the last row unmounts its own button; focus steps back to the previous row's.+ await act(() => removeButton(3).focus());+ await keys('{Enter}');+ expect(onCommit).toHaveBeenLastCalledWith([1, 2]);+ expect(document.activeElement).toBe(removeButton(2));++ // Removing an earlier row keeps the button at that position, now owning the next item.+ await act(() => removeButton(1).focus());+ await keys('{Enter}');+ expect(onCommit).toHaveBeenLastCalledWith([2]);+ expect(document.activeElement).toBe(removeButton(1));++ await keys('{Enter}');+ expect(onCommit).toHaveBeenLastCalledWith([]);+ expect(document.activeElement).toBe(button('nodes.addItem'));++ await keys('{Enter}{Enter}');+ expect(rows()).toBe(2);+ await act(() => button('common.clear').focus());+ await keys('{Enter}');+ expect(rows()).toBe(0);+ expect(document.activeElement).toBe(button('nodes.addItem'));+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 909d0fc7ad..6063774d4b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -7,6 +7,7 @@ import {Badge,Box,createListCollection,+ Field,Flex,HStack,Icon,@@ -62,6 +63,7 @@ import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/uiimport {getResolvedWorkflowEdges,isLoraFieldCollectionEntry,+ isWorkflowCollectionItemValid,toLoraFieldCollectionList,} from '@features/workflow/utility';import { planSeedSubmission, type SeedMode, wrapSeed } from '@platform/core/seed';@@ -90,7 +92,7 @@ import {import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { SeedInput } from '@platform/ui/SeedInput';import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query';-import { FilmIcon, ImageIcon, ImagePlusIcon, RotateCcwIcon, Trash2Icon, XIcon } from 'lucide-react';+import { FilmIcon, ImageIcon, ImagePlusIcon, PlusIcon, RotateCcwIcon, Trash2Icon, XIcon } from 'lucide-react';import {lazy,Suspense,@@ -166,7 +168,10 @@ const useFocusedDraft = () => {return [draft, setDraft, clearDraft] as const;};-const StringInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {+/** A row of a list names itself by position; a scalar field is named by its title. */+type ScalarInputProps = WorkflowFieldInputProps & { ariaLabel?: string };++const StringInput = ({ ariaLabel, id, invalid, onChange, template, value }: ScalarInputProps) => {const [draft, setDraft, clearDraft] = useFocusedDraft();const text = draft ?? (typeof value === 'string' ? value : '');const onTextChange = useCallback(@@ -180,7 +185,7 @@ const StringInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInif (template.uiComponent === 'textarea') {return (<ResizableTextarea- aria-label={template.title}+ aria-label={ariaLabel ?? template.title}className="nodrag nowheel"defaultHeightPx={96}fontFamily="mono"@@ -199,7 +204,7 @@ const StringInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInreturn (<Input- aria-label={template.title}+ aria-label={ariaLabel ?? template.title}className="nodrag"id={id ? `${id}-input` : undefined}size="xs"@@ -218,7 +223,7 @@ const selectInputText = (event: MouseEvent<HTMLInputElement>) => event.currentTa/** Chromium steps a focused number input on wheel and swallows the scroll; unfocused, the panel scrolls instead. */const blurOnWheel = (event: WheelEvent<HTMLInputElement>) => event.currentTarget.blur();-const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {+const NumericInput = ({ ariaLabel, id, invalid, onChange, template, value }: ScalarInputProps) => {const isInteger = template.type.name === 'IntegerField';const [draft, setDraft, clearDraft] = useFocusedDraft();// Chromium keeps an unparseable partial entry (`-`, `1e`) on screen but reports it as empty, so the empty commit@@ -256,7 +261,7 @@ const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldIreturn (<Input- aria-label={template.title}+ aria-label={ariaLabel ?? template.title}className="nodrag"id={id ? `${id}-number-input` : undefined}max={max !== undefined ? String(max) : undefined}@@ -1525,6 +1530,156 @@ const LoRACollectionRow = ({);};+const ScalarCollectionInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {+ const { t } = useTranslation();+ const items = useMemo<readonly unknown[]>(() => (Array.isArray(value) ? value : []), [value]);+ const isString = template.type.name === 'StringField';+ // Each row edits one scalar on a single line, whatever the list's own ui_component says.+ const itemTemplate = useMemo<FieldInputTemplate>(+ () => ({ ...template, type: { ...template.type, cardinality: 'SINGLE' }, uiComponent: null }),+ [template]+ );+ // Emptying the list restores the template's own default, so the reset affordance stays quiet.+ const clearsToUndefined = template.default === undefined && !template.required;+ const commit = useCallback(+ (next: unknown[]) => onChange(next.length === 0 && clearsToUndefined ? undefined : next),+ [clearsToUndefined, onChange]+ );+ const onAdd = useCallback(+ () => commit([...items, isString ? '' : (finiteNumberOrUndefined(template.minimum) ?? 0)]),+ [commit, isString, items, template.minimum]+ );+ const addButtonRef = useRef<HTMLButtonElement>(null);+ const listRef = useRef<HTMLDivElement>(null);+ // Rows are keyed by position, so a removal only unmounts the last row's controls. Move keyboard focus off+ // anything about to unmount before the commit lands, or it falls to the canvas and its delete shortcut.+ const onClear = useCallback(() => {+ addButtonRef.current?.focus();+ commit([]);+ }, [commit]);+ const onRemove = useCallback(+ (index: number) => {+ if (index === items.length - 1) {+ const removeButtons = listRef.current?.querySelectorAll<HTMLButtonElement>('[data-collection-remove]');++ (index > 0 ? removeButtons?.[index - 1] : addButtonRef.current)?.focus();+ }++ commit(items.filter((_, itemIndex) => itemIndex !== index));+ },+ [commit, items]+ );+ // A cleared or unparseable number row is kept as null: the list keeps its shape and the row reports itself.+ const onItemChange = useCallback(+ (index: number, next: unknown) =>+ commit(items.map((item, itemIndex) => (itemIndex === index ? (next === undefined ? null : next) : item))),+ [commit, items]+ );++ return (+ <Stack gap="1" w="full">+ {items.length > 0 ? (+ <Stack+ ref={listRef}+ borderWidth="1px"+ boxShadow={invalid ? '0 0 0 1px {colors.red.solid}' : undefined}+ className="nowheel"+ gap="1"+ maxH="40"+ overflowY="auto"+ p="1"+ rounded="sm"+ w="full"+ >+ {items.map((item, index) => (+ <ScalarCollectionRow+ key={index}+ id={id}+ index={index}+ itemTemplate={itemTemplate}+ value={item}+ onItemChange={onItemChange}+ onRemove={onRemove}+ />+ ))}+ </Stack>+ ) : null}+ <HStack gap="1.5" w="full">+ <Button ref={addButtonRef} className="nodrag" size="2xs" variant="outline" onClick={onAdd}>+ <Icon as={PlusIcon} boxSize="3" />+ {t('nodes.addItem')}+ </Button>+ {items.length > 0 ? (+ <Button className="nodrag" size="2xs" variant="ghost" onClick={onClear}>+ {t('common.clear')}+ </Button>+ ) : null}+ {items.length > 0 ? (+ <Text color="fg.subtle" fontSize="2xs" ms="auto">+ {t('nodes.collectionItemCount', { count: items.length })}+ </Text>+ ) : null}+ </HStack>+ </Stack>+ );+};++const ScalarCollectionRow = ({+ id,+ index,+ itemTemplate,+ onItemChange,+ onRemove,+ value,+}: {+ id?: string;+ index: number;+ itemTemplate: FieldInputTemplate;+ onItemChange: (index: number, next: unknown) => void;+ onRemove: (index: number) => void;+ value: unknown;+}) => {+ const { t } = useTranslation();+ const onChange = useCallback((next: unknown) => onItemChange(index, next), [index, onItemChange]);+ const onRemoveClick = useCallback(() => onRemove(index), [index, onRemove]);+ const Control = itemTemplate.type.name === 'StringField' ? StringInput : NumericInput;+ const invalid = !isWorkflowCollectionItemValid(itemTemplate, value);+ const removeLabel = t('nodes.removeItem', { field: itemTemplate.title, index: index + 1 });++ return (+ <HStack gap="1" w="full">+ <Text color="fg.subtle" flexShrink="0" fontSize="2xs" fontVariantNumeric="tabular-nums" minW="4" textAlign="end">+ {index + 1}.+ </Text>+ {/* The host's Field.Root marks every control inside it invalid; a row scopes its own validity instead. */}+ <Field.Root flex="1" invalid={invalid} minW="0">+ <Control+ ariaLabel={t('nodes.collectionItemLabel', { field: itemTemplate.title, index: index + 1 })}+ id={id ? `${id}-item-${index}` : undefined}+ invalid={invalid}+ template={itemTemplate}+ value={value}+ onChange={onChange}+ />+ </Field.Root>+ <Tooltip content={removeLabel}>+ <IconButton+ aria-label={removeLabel}+ className="nodrag"+ color="fg.muted"+ data-collection-remove=""+ flexShrink="0"+ size="2xs"+ variant="ghost"+ onClick={onRemoveClick}+ >+ <Trash2Icon />+ </IconButton>+ </Tooltip>+ </HStack>+ );+};+const CONNECTION_ONLY_FALLBACK = (<Text color="fg.subtle" fontSize="2xs">Connection only@@ -1679,11 +1834,20 @@ const SavedWorkflowInput = ({ nodeId, onChange, template, value }: WorkflowField};export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {- // COLLECTION fields hold arrays; only image lists have a list widget. Other+ // COLLECTION fields hold arrays; only image and scalar lists have a list widget. Other// collections stay connection-only even when a migrated linear-form element// points at them, since the single-value widget would write a bare value.if (props.template.type.cardinality === 'COLLECTION') {- return props.template.type.name === 'ImageField' ? <ImageCollectionInput {...props} /> : CONNECTION_ONLY_FALLBACK;+ switch (props.template.type.name) {+ case 'ImageField':+ return <ImageCollectionInput {...props} />;+ case 'FloatField':+ case 'IntegerField':+ case 'StringField':+ return <ScalarCollectionInput {...props} />;+ default:+ return CONNECTION_ONLY_FALLBACK;+ }}switch (props.template.type.name) {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsxindex cfc906f6ba..f9b1d4cc43 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx@@ -63,6 +63,11 @@ const entryTemplate: InvocationTemplate = {inputs: {prompt: entryInput('prompt', 'Prompt', 'StringField'),scale: entryInput('scale', 'Scale', 'FloatField', false),+ sizes: {+ ...entryInput('sizes', 'Sizes', 'IntegerField'),+ minimum: 1,+ type: { batch: false, cardinality: 'COLLECTION', name: 'IntegerField' },+ },steps: entryInput('steps', 'Steps', 'IntegerField'),weight: entryInput('weight', 'Weight', 'FloatField'),},@@ -443,6 +448,7 @@ describe('Linear form field entry', () => {inputs: {prompt: { label: '', name: 'prompt', value: 'hello world' },scale: { label: '', name: 'scale', value: 1.5 },+ sizes: { label: '', name: 'sizes', value: [4, 8] },steps: { label: '', name: 'steps', value: 20 },weight: { label: '', name: 'weight', value: 0.5 },},@@ -591,4 +597,45 @@ describe('Linear form field entry', () => {expect(scale.value).toBe('');expect(scale.getAttribute('aria-invalid')).toBeNull();});++ it('edits an exposed scalar list row by row and reports the first empty entry', async () => {+ const { value } = await renderForm();+ // Raw i18n keys: every list row shares one accessible name, so rows are found by position.+ const listRow = (index: number) =>+ host.querySelectorAll<HTMLInputElement>('input[aria-label="nodes.collectionItemLabel"]')[index - 1]!;+ // Each row scopes its own Field.Root; the reason text belongs to the host field around the list.+ const listError = (input: HTMLInputElement) =>+ input+ .closest('[data-scope="field"][data-part="root"]')+ ?.parentElement?.closest('[data-scope="field"][data-part="root"]')+ ?.querySelector('[data-part="error-text"]')?.textContent ?? null;++ expect(listRow(2).value).toBe('8');++ const addItem = Array.from(host.querySelectorAll('button')).find(+ (button) => button.textContent === 'nodes.addItem'+ )!;++ await act(async () => {+ await userEvent.click(addItem);+ });+ expect(value('sizes')).toEqual([4, 8, 1]);++ const third = listRow(3);++ await focusAtEnd(third);+ await keys('6');+ expect(third.value).toBe('16');+ expect(value('sizes')).toEqual([4, 8, 16]);+ expect(listError(third)).toBeNull();++ await keys('{Control>}a{/Control}{Backspace}');+ expect(value('sizes')).toEqual([4, 8, null]);+ expect(third.getAttribute('aria-invalid')).toBe('true');+ expect(listError(third)).toBe('Item 3 is empty.');+ // The host field is invalid as a whole, yet only the offending row carries the invalid state.+ expect(listRow(1).getAttribute('aria-invalid')).toBeNull();+ expect(listRow(1).getAttribute('data-invalid')).toBeNull();+ expect(listRow(2).getAttribute('aria-invalid')).toBeNull();+ });});