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.

fix(workflows): preserve core_metadata recall fields across workflow roundtrip (#9162)

Alexander Eichhorn302a10263b44
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldGate.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldGate.tsx
index 75d658fdb2..c24af5869d 100644
--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldGate.tsx
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldGate.tsx
@@ -3,6 +3,8 @@ import { InputFieldWrapper } from 'features/nodes/components/flow/nodes/Invocati
import { useInputFieldInstanceExists } from 'features/nodes/hooks/useInputFieldInstanceExists';
import { useInputFieldNameSafe } from 'features/nodes/hooks/useInputFieldNameSafe';
import { useInputFieldTemplateExists } from 'features/nodes/hooks/useInputFieldTemplateExists';
+import { useNodeType } from 'features/nodes/hooks/useNodeType';
+import { nodeAcceptsExtraInputs } from 'features/nodes/types/extraInputs';
import type { PropsWithChildren, ReactNode } from 'react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,8 +19,14 @@ type Props = PropsWithChildren<{
export const InputFieldGate = memo(({ nodeId, fieldName, children, fallback, formatLabel }: Props) => {
const hasInstance = useInputFieldInstanceExists(fieldName);
const hasTemplate = useInputFieldTemplateExists(fieldName);
+ const nodeType = useNodeType();
if (!hasTemplate || !hasInstance) {
+ // Backend nodes with `extra='allow'` (e.g. core_metadata) accept inputs that aren't declared
+ // in the OpenAPI schema. Render nothing rather than an "unexpected field" warning.
+ if (hasInstance && !hasTemplate && nodeAcceptsExtraInputs(nodeType)) {
+ return null;
+ }
// fallback may be null, indicating we should render nothing at all - must check for undefined explicitly
if (fallback !== undefined) {
return fallback;
diff --git a/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.ts b/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.ts
index b3ac3424fd..225ed2445d 100644
--- a/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.ts
+++ b/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.ts
@@ -5,6 +5,7 @@ import { debounce } from 'es-toolkit';
import { $templates } from 'features/nodes/store/nodesSlice';
import { selectNodesSlice } from 'features/nodes/store/selectors';
import type { NodesState, Templates } from 'features/nodes/store/types';
+import { nodeAcceptsExtraInputs } from 'features/nodes/types/extraInputs';
import type {
FieldInputInstance,
FieldInputTemplate,
@@ -280,6 +281,11 @@ export const getInvocationNodeErrors = (
const fieldTemplate = getInvocationNodeInputTemplate(node.data, nodeTemplate, fieldName);
if (!fieldTemplate) {
+ // Backend nodes with `extra='allow'` accept inputs that aren't declared in the OpenAPI
+ // schema; these carry recall metadata and don't need template-based validation.
+ if (nodeAcceptsExtraInputs(node.data.type)) {
+ continue;
+ }
errors.push({ type: 'node-error', nodeId, issue: t('parameters.invoke.missingFieldTemplate') });
continue;
}
@@ -315,6 +321,9 @@ const syncNodeErrors = (nodesState: NodesState, templates: Templates) => {
const fieldTemplate = getInvocationNodeInputTemplate(node.data, nodeTemplate, fieldName);
if (!fieldTemplate) {
+ if (nodeAcceptsExtraInputs(node.data.type)) {
+ continue;
+ }
errors.push({ type: 'node-error', nodeId: node.id, issue: t('parameters.invoke.missingFieldTemplate') });
$nodeErrors.setKey(node.id, errors);
continue;
diff --git a/invokeai/frontend/web/src/features/nodes/types/extraInputs.ts b/invokeai/frontend/web/src/features/nodes/types/extraInputs.ts
new file mode 100644
index 0000000000..4291dbd411
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/types/extraInputs.ts
@@ -0,0 +1,16 @@
+/**
+ * Some backend nodes are configured with pydantic `extra='allow'` and accept inputs that aren't
+ * declared in the OpenAPI schema. The most important case is `core_metadata`, which collects
+ * generation-mode-specific recall data (`z_image_seed_variance_*`, `dype_preset`, `ref_images`, ...).
+ *
+ * The frontend must round-trip those extras intact:
+ * - `graphToWorkflow` synthesizes a `MetadataExtraField` template for them
+ * - `buildNodesGraph` forwards their values verbatim
+ * - `fieldValidators` does not treat them as errors
+ * - `InputFieldGate` does not render an "unexpected field" warning
+ *
+ * See: https://github.com/invoke-ai/InvokeAI/issues/9151
+ */
+const NODES_ACCEPTING_EXTRA_INPUTS: ReadonlySet<string> = new Set(['core_metadata']);
+
+export const nodeAcceptsExtraInputs = (nodeType: string): boolean => NODES_ACCEPTING_EXTRA_INPUTS.has(nodeType);
diff --git a/invokeai/frontend/web/src/features/nodes/types/field.ts b/invokeai/frontend/web/src/features/nodes/types/field.ts
index e3829b0cc8..63955c62fb 100644
--- a/invokeai/frontend/web/src/features/nodes/types/field.ts
+++ b/invokeai/frontend/web/src/features/nodes/types/field.ts
@@ -212,6 +212,32 @@ const zImageGeneratorFieldType = zFieldTypeBase.extend({
name: z.literal('ImageGeneratorField'),
originalType: zStatelessFieldType.optional(),
});
+/**
+ * Synthetic field type used for `core_metadata` extra fields that are not declared in the backend
+ * schema (e.g. `z_image_seed_variance_*`, `dype_preset`, `ref_images`, ...). The backend's
+ * `CoreMetadataInvocation` is configured with `extra='allow'`, so these are valid metadata to
+ * round-trip even though there is no OpenAPI template for them.
+ */
+const zMetadataExtraFieldType = zFieldTypeBase.extend({
+ name: z.literal('MetadataExtraField'),
+ originalType: zStatelessFieldType.optional(),
+});
+const zLoRAMetadataFieldType = zFieldTypeBase.extend({
+ name: z.literal('LoRAMetadataField'),
+ originalType: zStatelessFieldType.optional(),
+});
+const zControlNetMetadataFieldType = zFieldTypeBase.extend({
+ name: z.literal('ControlNetMetadataField'),
+ originalType: zStatelessFieldType.optional(),
+});
+const zIPAdapterMetadataFieldType = zFieldTypeBase.extend({
+ name: z.literal('IPAdapterMetadataField'),
+ originalType: zStatelessFieldType.optional(),
+});
+const zT2IAdapterMetadataFieldType = zFieldTypeBase.extend({
+ name: z.literal('T2IAdapterMetadataField'),
+ originalType: zStatelessFieldType.optional(),
+});
const zStatefulFieldType = z.union([
zIntegerFieldType,
zFloatFieldType,
@@ -230,6 +256,11 @@ const zStatefulFieldType = z.union([
zIntegerGeneratorFieldType,
zStringGeneratorFieldType,
zImageGeneratorFieldType,
+ zLoRAMetadataFieldType,
+ zControlNetMetadataFieldType,
+ zIPAdapterMetadataFieldType,
+ zT2IAdapterMetadataFieldType,
+ zMetadataExtraFieldType,
]);
export type StatefulFieldType = z.infer<typeof zStatefulFieldType>;
const statefulFieldTypeNames = zStatefulFieldType.options.map((o) => o.shape.name.value);
@@ -1310,6 +1341,93 @@ export const getImageGeneratorDefaults = (type: ImageGeneratorFieldValue['type']
};
// #endregion
+// #region Metadata pass-through fields
+/**
+ * The `core_metadata` node carries metadata lists that are not edited via the UI - they are set by
+ * the Generate-mode graph builder (or by an edge) and must survive the workflow roundtrip verbatim
+ * so that the resulting image retains its recall metadata. Modeled as opaque object lists.
+ *
+ * See: https://github.com/invoke-ai/InvokeAI/issues/9151
+ */
+// `z.any()` (not `z.unknown()`) so the inferred type stays JSON-assignable for logging/serialization.
+const zMetadataPassthroughValue = z.array(z.record(z.string(), z.any())).nullish();
+
+const zLoRAMetadataFieldValue = zMetadataPassthroughValue;
+const zLoRAMetadataFieldInputInstance = zFieldInputInstanceBase.extend({
+ value: zLoRAMetadataFieldValue,
+});
+const zLoRAMetadataFieldInputTemplate = zFieldInputTemplateBase.extend({
+ type: zLoRAMetadataFieldType,
+ originalType: zFieldType.optional(),
+ default: zLoRAMetadataFieldValue,
+});
+const zLoRAMetadataFieldOutputTemplate = zFieldOutputTemplateBase.extend({
+ type: zLoRAMetadataFieldType,
+});
+export type LoRAMetadataFieldInputTemplate = z.infer<typeof zLoRAMetadataFieldInputTemplate>;
+
+const zControlNetMetadataFieldValue = zMetadataPassthroughValue;
+const zControlNetMetadataFieldInputInstance = zFieldInputInstanceBase.extend({
+ value: zControlNetMetadataFieldValue,
+});
+const zControlNetMetadataFieldInputTemplate = zFieldInputTemplateBase.extend({
+ type: zControlNetMetadataFieldType,
+ originalType: zFieldType.optional(),
+ default: zControlNetMetadataFieldValue,
+});
+const zControlNetMetadataFieldOutputTemplate = zFieldOutputTemplateBase.extend({
+ type: zControlNetMetadataFieldType,
+});
+export type ControlNetMetadataFieldInputTemplate = z.infer<typeof zControlNetMetadataFieldInputTemplate>;
+
+const zIPAdapterMetadataFieldValue = zMetadataPassthroughValue;
+const zIPAdapterMetadataFieldInputInstance = zFieldInputInstanceBase.extend({
+ value: zIPAdapterMetadataFieldValue,
+});
+const zIPAdapterMetadataFieldInputTemplate = zFieldInputTemplateBase.extend({
+ type: zIPAdapterMetadataFieldType,
+ originalType: zFieldType.optional(),
+ default: zIPAdapterMetadataFieldValue,
+});
+const zIPAdapterMetadataFieldOutputTemplate = zFieldOutputTemplateBase.extend({
+ type: zIPAdapterMetadataFieldType,
+});
+export type IPAdapterMetadataFieldInputTemplate = z.infer<typeof zIPAdapterMetadataFieldInputTemplate>;
+
+const zT2IAdapterMetadataFieldValue = zMetadataPassthroughValue;
+const zT2IAdapterMetadataFieldInputInstance = zFieldInputInstanceBase.extend({
+ value: zT2IAdapterMetadataFieldValue,
+});
+const zT2IAdapterMetadataFieldInputTemplate = zFieldInputTemplateBase.extend({
+ type: zT2IAdapterMetadataFieldType,
+ originalType: zFieldType.optional(),
+ default: zT2IAdapterMetadataFieldValue,
+});
+const zT2IAdapterMetadataFieldOutputTemplate = zFieldOutputTemplateBase.extend({
+ type: zT2IAdapterMetadataFieldType,
+});
+export type T2IAdapterMetadataFieldInputTemplate = z.infer<typeof zT2IAdapterMetadataFieldInputTemplate>;
+
+/**
+ * `MetadataExtraField` carries arbitrary JSON values for `core_metadata` extras that are not in the
+ * OpenAPI schema (e.g. `z_image_seed_variance_*`, `dype_preset`). Synthesized only by
+ * `graphToWorkflow` for `core_metadata` nodes; never produced by `parseSchema`.
+ */
+const zMetadataExtraFieldValue = z.any();
+const zMetadataExtraFieldInputInstance = zFieldInputInstanceBase.extend({
+ value: zMetadataExtraFieldValue,
+});
+const zMetadataExtraFieldInputTemplate = zFieldInputTemplateBase.extend({
+ type: zMetadataExtraFieldType,
+ originalType: zFieldType.optional(),
+ default: zMetadataExtraFieldValue,
+});
+const zMetadataExtraFieldOutputTemplate = zFieldOutputTemplateBase.extend({
+ type: zMetadataExtraFieldType,
+});
+export type MetadataExtraFieldInputTemplate = z.infer<typeof zMetadataExtraFieldInputTemplate>;
+// #endregion
+
// #region StatelessField
/**
* StatelessField is a catchall for stateless fields with no UI input components. They do not
@@ -1378,6 +1496,13 @@ export const zStatefulFieldValue = z.union([
zIntegerGeneratorFieldValue,
zStringGeneratorFieldValue,
zImageGeneratorFieldValue,
+ zLoRAMetadataFieldValue,
+ zControlNetMetadataFieldValue,
+ zIPAdapterMetadataFieldValue,
+ zT2IAdapterMetadataFieldValue,
+ // NOTE: `zMetadataExtraFieldValue` is intentionally NOT part of this union. It is `z.any()`, which
+ // would collapse the whole union (and `StatefulFieldValue`/`FieldValue`) to `any`. Extras are only
+ // ever handled via the scoped `zFieldInputInstanceWithExtras` union below.
]);
export type StatefulFieldValue = z.infer<typeof zStatefulFieldValue>;
@@ -1408,10 +1533,57 @@ const zStatefulFieldInputInstance = z.union([
zIntegerGeneratorFieldInputInstance,
zStringGeneratorFieldInputInstance,
zImageGeneratorFieldInputInstance,
+ // NOTE: the metadata pass-through instances (LoRA/ControlNet/IPAdapter/T2IAdapter) and the
+ // `MetadataExtraField` catch-all are intentionally NOT part of this union - see
+ // `zMetadataFieldInputInstances` / `zMetadataExtraFieldInputInstance` below and
+ // `zFieldInputInstanceWithExtras`.
]);
+/**
+ * The metadata pass-through instances accept opaque `array(record(string, any)) | nullish` values.
+ * That is greedy enough to match a stale array-of-objects value on ANY field, so they must not be
+ * parsed for arbitrary nodes - inputs are parsed without their template (see `zInvocationNodeData`),
+ * and a preserved stale value would leak into the backend graph via `buildNodesGraph`. These fields
+ * are only declared on nodes that accept extras (pydantic `extra='allow'`, currently `core_metadata`),
+ * so they are scoped to `zFieldInputInstanceWithExtras`.
+ */
+const zMetadataFieldInputInstances = [
+ zLoRAMetadataFieldInputInstance,
+ zControlNetMetadataFieldInputInstance,
+ zIPAdapterMetadataFieldInputInstance,
+ zT2IAdapterMetadataFieldInputInstance,
+] as const;
+
export const zFieldInputInstance = z.union([zStatefulFieldInputInstance, zStatelessFieldInputInstance]);
-export type FieldInputInstance = z.infer<typeof zFieldInputInstance>;
+
+/**
+ * Like {@link zFieldInputInstance}, but additionally accepts the metadata pass-through instances and
+ * the `MetadataExtraField` catch-all. Both groups accept very permissive values, so this union MUST
+ * only be used for node types known to accept extras (see `nodeAcceptsExtraInputs`). It is applied
+ * conditionally in `zInvocationNodeData` based on the node type. The metadata/extra branches are
+ * placed before the stateless branch so that genuine values are preserved rather than coerced to
+ * `undefined` by the stateless catch.
+ */
+export const zFieldInputInstanceWithExtras = z.union([
+ zStatefulFieldInputInstance,
+ ...zMetadataFieldInputInstances,
+ zMetadataExtraFieldInputInstance,
+ zStatelessFieldInputInstance,
+]);
+
+/**
+ * The `FieldInputInstance` TYPE must describe every instance shape the app constructs - including the
+ * metadata pass-through instances built for `core_metadata` fields (e.g. via `buildFieldInputInstance`)
+ * - even though the runtime `zFieldInputInstance` schema excludes them for scoping reasons. The
+ * `MetadataExtraField` instance is excluded here too: its value is `z.any()`, which would collapse the
+ * whole instance value type to `any`.
+ */
+const _zFieldInputInstanceType = z.union([
+ zStatefulFieldInputInstance,
+ ...zMetadataFieldInputInstances,
+ zStatelessFieldInputInstance,
+]);
+export type FieldInputInstance = z.infer<typeof _zFieldInputInstanceType>;
// #endregion
// #region StatefulFieldInputTemplate & FieldInputTemplate
@@ -1437,6 +1609,11 @@ const zStatefulFieldInputTemplate = z.union([
zIntegerGeneratorFieldInputTemplate,
zStringGeneratorFieldInputTemplate,
zImageGeneratorFieldInputTemplate,
+ zLoRAMetadataFieldInputTemplate,
+ zControlNetMetadataFieldInputTemplate,
+ zIPAdapterMetadataFieldInputTemplate,
+ zT2IAdapterMetadataFieldInputTemplate,
+ zMetadataExtraFieldInputTemplate,
]);
export const zFieldInputTemplate = z.union([zStatefulFieldInputTemplate, zStatelessFieldInputTemplate]);
@@ -1466,6 +1643,11 @@ const zStatefulFieldOutputTemplate = z.union([
zIntegerGeneratorFieldOutputTemplate,
zStringGeneratorFieldOutputTemplate,
zImageGeneratorFieldOutputTemplate,
+ zLoRAMetadataFieldOutputTemplate,
+ zControlNetMetadataFieldOutputTemplate,
+ zIPAdapterMetadataFieldOutputTemplate,
+ zT2IAdapterMetadataFieldOutputTemplate,
+ zMetadataExtraFieldOutputTemplate,
]);
export const zFieldOutputTemplate = z.union([zStatefulFieldOutputTemplate, zStatelessFieldOutputTemplate]);
diff --git a/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts b/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts
new file mode 100644
index 0000000000..3b92f63108
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Regression tests for PR #9162 review:
+ * The `MetadataExtraField` catch-all (value: `z.any()`) must only preserve undeclared "extra"
+ * input values for node types that accept extras (pydantic `extra='allow'`, e.g. `core_metadata`).
+ *
+ * Workflow inputs are parsed WITHOUT their field template (see `zInvocationNodeData.inputs`), so a
+ * global catch-all would let any stale/malformed connection-only value survive parsing for ANY
+ * node and later leak into the backend graph via `buildNodesGraph`. Scoping the catch-all to
+ * extra-accepting node types prevents that.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { zInvocationNodeData } from './invocation';
+
+const buildNodeData = (type: string, inputs: Record<string, unknown>) => ({
+ id: 'node-1',
+ version: '1.0.0',
+ nodePack: 'invokeai',
+ label: '',
+ notes: '',
+ type,
+ isOpen: true,
+ isIntermediate: false,
+ useCache: true,
+ inputs,
+});
+
+// A value that matches no stateful field-instance schema: the `type` discriminator rules out the
+// generator/color/model/image schemas, and it is neither a primitive nor a collection. Pre-PR such a
+// value coerced to `undefined` via the stateless branch; the `MetadataExtraField` catch-all is what
+// preserves it, so it is the ideal probe for the scoping boundary.
+const opaqueValue = { type: 'connection-payload', payload: 123 };
+
+describe('zInvocationNodeData: extra-input scoping', () => {
+ it('drops a stale value on a NON-extra node (coerced to undefined)', () => {
+ const parsed = zInvocationNodeData.parse(
+ buildNodeData('some_stateless_node', {
+ unet: { name: 'unet', label: '', description: '', value: opaqueValue },
+ })
+ );
+ // The key is preserved (it's a real input on the node) but its value is NOT — it falls through
+ // to the stateless branch which coerces to undefined, so it cannot leak into the backend graph.
+ expect(parsed.inputs.unet).toBeDefined();
+ expect(parsed.inputs.unet?.value).toBeUndefined();
+ });
+
+ it('drops a stale array-of-records value on a NON-extra node (would match a metadata passthrough instance)', () => {
+ // The metadata pass-through instances (LoRA/ControlNet/...) accept `array(record(string, any))`.
+ // On a non-extra node they must NOT be used, so a stale array-of-objects value is coerced away.
+ const parsed = zInvocationNodeData.parse(
+ buildNodeData('some_stateless_node', {
+ metadata: { name: 'metadata', label: '', description: '', value: [{ foo: 'bar' }] },
+ })
+ );
+ expect(parsed.inputs.metadata).toBeDefined();
+ expect(parsed.inputs.metadata?.value).toBeUndefined();
+ });
+
+ it('preserves a metadata passthrough value (loras) on core_metadata', () => {
+ const loras = [{ model: { key: 'k', hash: 'h', name: 'n', base: 'z-image', type: 'lora' }, weight: 0.75 }];
+ const parsed = zInvocationNodeData.parse(
+ buildNodeData('core_metadata', {
+ loras: { name: 'loras', label: '', description: '', value: loras },
+ })
+ );
+ expect(parsed.inputs.loras?.value).toEqual(loras);
+ });
+
+ it('preserves an undeclared extra value on core_metadata (extra=allow)', () => {
+ const parsed = zInvocationNodeData.parse(
+ buildNodeData('core_metadata', {
+ some_extra: { name: 'some_extra', label: '', description: '', value: opaqueValue },
+ })
+ );
+ expect(parsed.inputs.some_extra?.value).toEqual(opaqueValue);
+ });
+
+ it('preserves primitive extras on core_metadata', () => {
+ const parsed = zInvocationNodeData.parse(
+ buildNodeData('core_metadata', {
+ z_image_seed_variance_enabled: {
+ name: 'z_image_seed_variance_enabled',
+ label: '',
+ description: '',
+ value: false,
+ },
+ z_image_seed_variance_strength: {
+ name: 'z_image_seed_variance_strength',
+ label: '',
+ description: '',
+ value: 0.1,
+ },
+ })
+ );
+ expect(parsed.inputs.z_image_seed_variance_enabled?.value).toBe(false);
+ expect(parsed.inputs.z_image_seed_variance_strength?.value).toBe(0.1);
+ });
+});
diff --git a/invokeai/frontend/web/src/features/nodes/types/invocation.ts b/invokeai/frontend/web/src/features/nodes/types/invocation.ts
index 5ceb30f779..4013e2518c 100644
--- a/invokeai/frontend/web/src/features/nodes/types/invocation.ts
+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.ts
@@ -2,7 +2,9 @@ import type { Edge, Node } from '@xyflow/react';
import { z } from 'zod';
import { zClassification, zProgressImage } from './common';
-import { zFieldInputInstance, zFieldInputTemplate, zFieldOutputTemplate } from './field';
+import { nodeAcceptsExtraInputs } from './extraInputs';
+import type { FieldInputInstance } from './field';
+import { zFieldInputInstance, zFieldInputInstanceWithExtras, zFieldInputTemplate, zFieldOutputTemplate } from './field';
import { zSemVer } from './semver';
// #region InvocationTemplate
@@ -24,19 +26,44 @@ export type InvocationTemplate = z.infer<typeof _zInvocationTemplate>;
// #endregion
// #region NodeData
-export const zInvocationNodeData = z.object({
- id: z.string().trim().min(1),
- version: zSemVer,
- nodePack: z.string().min(1).default('invokeai'),
- label: z.string(),
- notes: z.string(),
- type: z.string().trim().min(1),
- inputs: z.record(z.string(), zFieldInputInstance),
- dynamicInputTemplates: z.record(z.string(), zFieldInputTemplate).default({}),
- isOpen: z.boolean(),
- isIntermediate: z.boolean(),
- useCache: z.boolean(),
-});
+export const zInvocationNodeData = z
+ .object({
+ id: z.string().trim().min(1),
+ version: zSemVer,
+ nodePack: z.string().min(1).default('invokeai'),
+ label: z.string(),
+ notes: z.string(),
+ type: z.string().trim().min(1),
+ // Parsed per-input in the transform below so that the input-instance schema can be chosen based
+ // on the node type (extras are only accepted for nodes that declare `extra='allow'`).
+ inputs: z.record(z.string(), z.unknown()),
+ dynamicInputTemplates: z.record(z.string(), zFieldInputTemplate).default({}),
+ isOpen: z.boolean(),
+ isIntermediate: z.boolean(),
+ useCache: z.boolean(),
+ })
+ .transform((data, ctx) => {
+ // Undeclared "extra" inputs (pydantic `extra='allow'`, e.g. `core_metadata`) carry arbitrary
+ // values that must round-trip. Only nodes known to accept extras get the permissive
+ // `MetadataExtraField` catch-all; every other node uses the strict instance union so stale or
+ // malformed saved values are coerced away (via the stateless branch) rather than preserved and
+ // later leaked into the backend graph by `buildNodesGraph`.
+ const instanceSchema = nodeAcceptsExtraInputs(data.type) ? zFieldInputInstanceWithExtras : zFieldInputInstance;
+ const inputs: Record<string, FieldInputInstance> = {};
+ for (const [name, rawInput] of Object.entries(data.inputs)) {
+ const result = instanceSchema.safeParse(rawInput);
+ if (!result.success) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `Invalid input "${name}": ${result.error.message}`,
+ path: ['inputs', name],
+ });
+ return z.NEVER;
+ }
+ inputs[name] = result.data;
+ }
+ return { ...data, inputs };
+ });
export const zNotesNodeData = z.object({
id: z.string().trim().min(1),
diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.ts b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.ts
index 046487e40e..ea772a16bf 100644
--- a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.ts
@@ -3,6 +3,7 @@ import { callSavedWorkflowDynamicFieldsChanged, nodesSliceConfig } from 'feature
import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from 'features/nodes/store/util/connectorTopology';
import { add, buildEdge, buildNode, img_resize, sub, templates } from 'features/nodes/store/util/testUtils';
import type { IntegerFieldInputTemplate } from 'features/nodes/types/field';
+import { zInvocationNodeData } from 'features/nodes/types/invocation';
import { describe, expect, it } from 'vitest';
import { buildNodesGraph } from './buildNodesGraph';
@@ -342,4 +343,37 @@ describe('buildNodesGraph', () => {
]);
expect(graph.nodes[target.id]).not.toHaveProperty('a');
});
+
+ it('does not serialize a stale array-of-records value on a connection-only input of a non-extra node', () => {
+ // Regression for PR #9162: the metadata pass-through instances accept opaque
+ // `array(record(string, any)) | nullish` values. Because workflow inputs are parsed without
+ // their field template, a stale array-of-objects value on a connection-only input of a
+ // non-extra node could match a metadata pass-through instance, survive parsing, and be emitted
+ // into the backend graph. `img_resize.metadata` is a connection-only MetadataField input.
+ const parsedData = zInvocationNodeData.parse({
+ id: 'img_resize-1',
+ type: 'img_resize',
+ version: img_resize.version,
+ label: '',
+ notes: '',
+ nodePack: 'invokeai',
+ isOpen: true,
+ isIntermediate: false,
+ useCache: true,
+ inputs: {
+ metadata: { name: 'metadata', label: '', description: '', value: [{ foo: 'bar' }] },
+ },
+ });
+
+ // The stale value must be coerced away by the stateless branch, not preserved by a metadata
+ // pass-through instance.
+ expect(parsedData.inputs.metadata?.value).toBeUndefined();
+
+ const node = { id: 'img_resize-1', type: 'invocation' as const, position: { x: 0, y: 0 }, data: parsedData };
+ const graph = buildNodesGraph(buildState([node], []), templates);
+
+ // ...and therefore must not reach the backend graph as a direct input value.
+ const graphNode = graph.nodes['img_resize-1'] as Record<string, unknown> | undefined;
+ expect(graphNode?.metadata).toBeUndefined();
+ });
});
diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.ts b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.ts
index eb2ce06d15..47e4d779c2 100644
--- a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.ts
@@ -6,6 +6,7 @@ import { selectNodesSlice } from 'features/nodes/store/selectors';
import type { Templates } from 'features/nodes/store/types';
import { resolveConnectorSource } from 'features/nodes/store/util/connectorTopology';
import type { BoardField } from 'features/nodes/types/common';
+import { nodeAcceptsExtraInputs } from 'features/nodes/types/extraInputs';
import type { BoardFieldInputInstance } from 'features/nodes/types/field';
import { isBoardFieldInputInstance, isBoardFieldInputTemplate } from 'features/nodes/types/field';
import {
@@ -80,7 +81,11 @@ export const buildNodesGraph = (state: RootState, templates: Templates): Require
const fieldTemplate = getInvocationNodeInputTemplate(data, nodeTemplate, name);
if (!fieldTemplate) {
- log.warn({ id, name }, 'Field template not found!');
+ if (nodeAcceptsExtraInputs(type) && input.value !== undefined) {
+ inputsAccumulator[name] = input.value;
+ } else {
+ log.warn({ id, name }, 'Field template not found!');
+ }
return inputsAccumulator;
}
if (isBoardFieldInputTemplate(fieldTemplate) && isBoardFieldInputInstance(input)) {
diff --git a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts
index 00c19a0cf3..8c3e3b5c55 100644
--- a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts
@@ -2,6 +2,7 @@ import { deepClone } from 'common/util/deepClone';
import { compare, satisfies } from 'compare-versions';
import { defaultsDeep, keys, pick } from 'es-toolkit/compat';
import { NodeUpdateError } from 'features/nodes/types/error';
+import { nodeAcceptsExtraInputs } from 'features/nodes/types/extraInputs';
import type { InvocationNode, InvocationNodeData, InvocationTemplate } from 'features/nodes/types/invocation';
import { zParsedSemver } from 'features/nodes/types/semver';
@@ -111,7 +112,15 @@ export const updateNode = (
defaultsDeep(clone, defaults); // mutates!
migrateImageCollectionInputValues(clone, { ...options, sourceVersion });
- // Remove any fields that are not in the template
- clone.data.inputs = pick(clone.data.inputs, keys(defaults.data.inputs));
+ // Remove any fields that are not in the template. Nodes that accept extras (pydantic
+ // `extra='allow'`, e.g. `core_metadata`) may carry undeclared inputs that are not in the template
+ // but must be preserved across the update, so keep those keys too.
+ const allowedKeys = keys(defaults.data.inputs);
+ if (nodeAcceptsExtraInputs(clone.data.type)) {
+ const extraKeys = keys(clone.data.inputs).filter((key) => !(key in defaults.data.inputs));
+ clone.data.inputs = pick(clone.data.inputs, [...allowedKeys, ...extraKeys]);
+ } else {
+ clone.data.inputs = pick(clone.data.inputs, allowedKeys);
+ }
return clone;
};
diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts
index cb508789df..3631fea49e 100644
--- a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts
@@ -19,6 +19,11 @@ const FIELD_VALUE_FALLBACK_MAP: Record<StatefulFieldType['name'], FieldValue> =
IntegerGeneratorField: undefined,
StringGeneratorField: undefined,
ImageGeneratorField: undefined,
+ LoRAMetadataField: undefined,
+ ControlNetMetadataField: undefined,
+ IPAdapterMetadataField: undefined,
+ T2IAdapterMetadataField: undefined,
+ MetadataExtraField: undefined,
};
export const buildFieldInputInstance = (id: string, template: FieldInputTemplate): FieldInputInstance => {
diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts
index 7751390e9d..41185aa249 100644
--- a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts
@@ -4,6 +4,7 @@ import type {
BoardFieldInputTemplate,
BooleanFieldInputTemplate,
ColorFieldInputTemplate,
+ ControlNetMetadataFieldInputTemplate,
EnumFieldInputTemplate,
FieldInputTemplate,
FieldType,
@@ -16,7 +17,10 @@ import type {
IntegerFieldCollectionInputTemplate,
IntegerFieldInputTemplate,
IntegerGeneratorFieldInputTemplate,
+ IPAdapterMetadataFieldInputTemplate,
LoRAFieldCollectionInputTemplate,
+ LoRAMetadataFieldInputTemplate,
+ MetadataExtraFieldInputTemplate,
ModelIdentifierFieldInputTemplate,
SavedWorkflowFieldInputTemplate,
SchedulerFieldInputTemplate,
@@ -26,6 +30,7 @@ import type {
StringFieldInputTemplate,
StringGeneratorFieldInputTemplate,
StylePresetFieldInputTemplate,
+ T2IAdapterMetadataFieldInputTemplate,
} from 'features/nodes/types/field';
import {
getFloatGeneratorArithmeticSequenceDefaults,
@@ -513,6 +518,53 @@ const buildImageGeneratorFieldInputTemplate: FieldInputTemplateBuilder<ImageGene
return template;
};
+const buildLoRAMetadataFieldInputTemplate: FieldInputTemplateBuilder<LoRAMetadataFieldInputTemplate> = ({
+ baseField,
+ fieldType,
+}) => ({
+ ...baseField,
+ type: fieldType,
+ default: undefined,
+});
+
+const buildControlNetMetadataFieldInputTemplate: FieldInputTemplateBuilder<ControlNetMetadataFieldInputTemplate> = ({
+ baseField,
+ fieldType,
+}) => ({
+ ...baseField,
+ type: fieldType,
+ default: undefined,
+});
+
+const buildIPAdapterMetadataFieldInputTemplate: FieldInputTemplateBuilder<IPAdapterMetadataFieldInputTemplate> = ({
+ baseField,
+ fieldType,
+}) => ({
+ ...baseField,
+ type: fieldType,
+ default: undefined,
+});
+
+const buildT2IAdapterMetadataFieldInputTemplate: FieldInputTemplateBuilder<T2IAdapterMetadataFieldInputTemplate> = ({
+ baseField,
+ fieldType,
+}) => ({
+ ...baseField,
+ type: fieldType,
+ default: undefined,
+});
+
+// MetadataExtraField is synthesized by graphToWorkflow for `core_metadata` extras and never
+// produced by parseSchema. This builder exists only to satisfy the StatefulFieldType['name'] record.
+const buildMetadataExtraFieldInputTemplate: FieldInputTemplateBuilder<MetadataExtraFieldInputTemplate> = ({
+ baseField,
+ fieldType,
+}) => ({
+ ...baseField,
+ type: fieldType,
+ default: undefined,
+});
+
const TEMPLATE_BUILDER_MAP: Record<StatefulFieldType['name'], FieldInputTemplateBuilder> = {
BoardField: buildBoardFieldInputTemplate,
BooleanField: buildBooleanFieldInputTemplate,
@@ -533,6 +585,11 @@ const TEMPLATE_BUILDER_MAP: Record<StatefulFieldType['name'], FieldInputTemplate
IntegerGeneratorField: buildIntegerGeneratorFieldInputTemplate,
StringGeneratorField: buildStringGeneratorFieldInputTemplate,
ImageGeneratorField: buildImageGeneratorFieldInputTemplate,
+ LoRAMetadataField: buildLoRAMetadataFieldInputTemplate,
+ ControlNetMetadataField: buildControlNetMetadataFieldInputTemplate,
+ IPAdapterMetadataField: buildIPAdapterMetadataFieldInputTemplate,
+ T2IAdapterMetadataField: buildT2IAdapterMetadataFieldInputTemplate,
+ MetadataExtraField: buildMetadataExtraFieldInputTemplate,
};
export const buildFieldInputTemplate = (
diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/parseSchemaCoreMetadata.test.ts b/invokeai/frontend/web/src/features/nodes/util/schema/parseSchemaCoreMetadata.test.ts
new file mode 100644
index 0000000000..f01a734314
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/util/schema/parseSchemaCoreMetadata.test.ts
@@ -0,0 +1,110 @@
+/**
+ * Verifies that parseSchema produces a stateful LoRAMetadataField template
+ * for core_metadata.loras given the real OpenAPI schema shape that the
+ * backend emits.
+ *
+ * Part of issue #9151 investigation.
+ */
+
+import type { OpenAPIV3_1 } from 'openapi-types';
+import { describe, expect, it } from 'vitest';
+
+import { parseSchema } from './parseSchema';
+
+const minimalSchema = {
+ openapi: '3.1.0',
+ info: { title: 'test', version: '0.0.0' },
+ components: {
+ schemas: {
+ LoRAMetadataField: {
+ title: 'LoRAMetadataField',
+ type: 'object',
+ properties: {
+ model: { $ref: '#/components/schemas/ModelIdentifierField' },
+ weight: { type: 'number', title: 'Weight' },
+ },
+ required: ['model', 'weight'],
+ },
+ ModelIdentifierField: {
+ title: 'ModelIdentifierField',
+ type: 'object',
+ properties: {
+ key: { type: 'string' },
+ hash: { type: 'string' },
+ name: { type: 'string' },
+ base: { type: 'string' },
+ type: { type: 'string' },
+ },
+ required: ['key', 'hash', 'name', 'base', 'type'],
+ },
+ CoreMetadataOutput: {
+ class: 'output',
+ title: 'CoreMetadataOutput',
+ type: 'object',
+ properties: {
+ metadata: { type: 'object', title: 'Metadata', field_kind: 'output' },
+ type: { type: 'string', const: 'metadata_output', default: 'metadata_output', field_kind: 'node_attribute' },
+ },
+ },
+ CoreMetadataInvocation: {
+ class: 'invocation',
+ title: 'CoreMetadataInvocation',
+ type: 'object',
+ category: 'metadata',
+ classification: 'internal',
+ node_pack: 'invokeai',
+ tags: ['metadata'],
+ version: '2.1.0',
+ output: { $ref: '#/components/schemas/CoreMetadataOutput' },
+ properties: {
+ id: { type: 'string', title: 'Id', field_kind: 'node_attribute' },
+ is_intermediate: {
+ type: 'boolean',
+ title: 'Is Intermediate',
+ default: false,
+ field_kind: 'node_attribute',
+ ui_hidden: false,
+ ui_type: 'IsIntermediate',
+ input: 'direct',
+ orig_required: true,
+ },
+ use_cache: { type: 'boolean', default: true, title: 'Use Cache', field_kind: 'node_attribute' },
+ type: {
+ type: 'string',
+ const: 'core_metadata',
+ default: 'core_metadata',
+ title: 'type',
+ field_kind: 'node_attribute',
+ },
+ loras: {
+ anyOf: [{ items: { $ref: '#/components/schemas/LoRAMetadataField' }, type: 'array' }, { type: 'null' }],
+ default: null,
+ description: 'The LoRAs used for inference',
+ title: 'Loras',
+ field_kind: 'input',
+ input: 'any',
+ orig_default: null,
+ orig_required: false,
+ },
+ },
+ required: ['type', 'id'],
+ },
+ },
+ },
+} as unknown as OpenAPIV3_1.Document;
+
+describe('parseSchema: core_metadata.loras', () => {
+ it('produces a LoRAMetadataField template (not stateless)', () => {
+ const templates = parseSchema(minimalSchema);
+ const coreMetadata = templates.core_metadata;
+ expect(coreMetadata).toBeDefined();
+
+ const lorasInput = coreMetadata?.inputs.loras;
+ expect(lorasInput).toBeDefined();
+ expect(lorasInput?.type.name).toBe('LoRAMetadataField');
+ expect(lorasInput?.type.cardinality).toBe('COLLECTION');
+ // Stateless inputs only accept 'connection'. If our template is correctly
+ // stateful, this should be 'any' (the input mode declared in the schema).
+ expect(lorasInput?.input).toBe('any');
+ });
+});
diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.test.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.test.ts
index d4f0f75a57..18c30d486b 100644
--- a/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.test.ts
@@ -1,9 +1,188 @@
import { $templates } from 'features/nodes/store/nodesSlice';
+import type { Templates } from 'features/nodes/store/types';
import type { InvocationTemplate } from 'features/nodes/types/invocation';
import { isWorkflowInvocationNode } from 'features/nodes/types/workflow';
-import { graphToWorkflow } from 'features/nodes/util/workflow/graphToWorkflow';
import type { NonNullableGraph } from 'services/api/types';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
+
+import { graphToWorkflow } from './graphToWorkflow';
+import { parseAndMigrateWorkflow } from './migrations';
+
+// Minimal templates needed to render the user's graph. We use the same shape
+// the real parseSchema would produce for these nodes' fields - only the
+// `core_metadata.loras` and `lora_selector.{lora,weight}` templates need to
+// be accurate enough for the roundtrip; other inputs are mocked permissively.
+const looseStringInput = {
+ name: '',
+ title: '',
+ description: '',
+ ui_hidden: false,
+ fieldKind: 'input' as const,
+ input: 'any' as const,
+ required: false,
+ default: undefined,
+};
+const passthroughTemplate = (typeName: string) => ({
+ type: 'invocation',
+ title: typeName,
+ version: '1.0.0',
+ tags: [],
+ description: '',
+ outputType: `${typeName}_output`,
+ inputs: new Proxy(
+ {},
+ {
+ get: (_, prop: string) => ({
+ ...looseStringInput,
+ name: prop,
+ title: prop,
+ type: { name: 'StringField', cardinality: 'SINGLE', batch: false },
+ }),
+ has: () => true,
+ }
+ ),
+ outputs: {},
+ useCache: true,
+ nodePack: 'invokeai',
+ classification: 'stable',
+ category: 'misc',
+});
+
+const templates: Templates = new Proxy(
+ {},
+ {
+ get: (_, prop: string) => {
+ if (prop === 'core_metadata') {
+ return {
+ ...passthroughTemplate('core_metadata'),
+ inputs: new Proxy(
+ {},
+ {
+ get: (_, key: string) => ({
+ ...looseStringInput,
+ name: key,
+ title: key,
+ type:
+ key === 'loras'
+ ? { name: 'LoRAMetadataField', cardinality: 'COLLECTION', batch: false }
+ : { name: 'StringField', cardinality: 'SINGLE', batch: false },
+ }),
+ has: () => true,
+ }
+ ),
+ classification: 'internal',
+ };
+ }
+ if (prop === 'lora_selector') {
+ return {
+ ...passthroughTemplate('lora_selector'),
+ version: '1.0.3',
+ inputs: new Proxy(
+ {},
+ {
+ get: (_, key: string) => ({
+ ...looseStringInput,
+ name: key,
+ title: key,
+ type:
+ key === 'lora'
+ ? { name: 'ModelIdentifierField', cardinality: 'SINGLE', batch: false }
+ : { name: 'FloatField', cardinality: 'SINGLE', batch: false },
+ }),
+ has: () => true,
+ }
+ ),
+ };
+ }
+ return passthroughTemplate(typeof prop === 'string' ? prop : 'unknown');
+ },
+ }
+) as unknown as Templates;
+
+const expectedLorasValue = [
+ {
+ model: {
+ key: '1bce536a-a770-49bd-a58e-c6576a7fe41d',
+ hash: 'blake3:5dc8b2234366702e22410e5f2de079d24c13eb58aa9597fa6a4d6688ce9f1da2',
+ name: 'hina_zImageTurbo_anime_v2.52-dream',
+ base: 'z-image',
+ type: 'lora',
+ submodel_type: null,
+ },
+ weight: 0.75,
+ },
+];
+
+const userFirstGraph = {
+ id: 'z_image_graph:EnnoIJwImk',
+ nodes: {
+ 'core_metadata:sbmUlPbCpY': {
+ id: 'core_metadata:sbmUlPbCpY',
+ type: 'core_metadata',
+ is_intermediate: true,
+ use_cache: true,
+ generation_mode: 'z_image_txt2img',
+ loras: expectedLorasValue,
+ // Backend `extra='allow'` extras - not declared in OpenAPI schema:
+ z_image_seed_variance_enabled: false,
+ z_image_seed_variance_strength: 0.1,
+ z_image_seed_variance_randomize_percent: 50,
+ },
+ 'lora_selector:lXZkTpWiQQ': {
+ id: 'lora_selector:lXZkTpWiQQ',
+ type: 'lora_selector',
+ is_intermediate: true,
+ use_cache: true,
+ lora: expectedLorasValue[0]?.model,
+ weight: 0.75,
+ },
+ },
+ edges: [],
+} as unknown as NonNullableGraph;
+
+const findInput = (workflow: ReturnType<typeof graphToWorkflow>, nodeId: string, fieldName: string) => {
+ const node = workflow.nodes.find((n) => n.id === nodeId);
+ if (!node || node.type !== 'invocation') {
+ return undefined;
+ }
+ return node.data.inputs[fieldName];
+};
+
+describe('issue #9151: graphToWorkflow + zod validation roundtrip', () => {
+ beforeAll(() => {
+ $templates.set(templates);
+ });
+
+ it('graphToWorkflow preserves core_metadata.loras value', () => {
+ const workflow = graphToWorkflow(userFirstGraph, false);
+ const lorasInput = findInput(workflow, 'core_metadata:sbmUlPbCpY', 'loras');
+ expect(lorasInput).toBeDefined();
+ expect(lorasInput?.value).toEqual(expectedLorasValue);
+ });
+
+ it('parseAndMigrateWorkflow does not strip core_metadata.loras', () => {
+ const workflow = graphToWorkflow(userFirstGraph, false);
+ const migrated = parseAndMigrateWorkflow(workflow);
+ const lorasInput = findInput(migrated, 'core_metadata:sbmUlPbCpY', 'loras');
+ expect(lorasInput).toBeDefined();
+ expect(lorasInput?.value).toEqual(expectedLorasValue);
+ });
+
+ it('graphToWorkflow preserves core_metadata extra fields (z_image_seed_variance_*)', () => {
+ const workflow = graphToWorkflow(userFirstGraph, false);
+ expect(findInput(workflow, 'core_metadata:sbmUlPbCpY', 'z_image_seed_variance_enabled')?.value).toBe(false);
+ expect(findInput(workflow, 'core_metadata:sbmUlPbCpY', 'z_image_seed_variance_strength')?.value).toBe(0.1);
+ expect(findInput(workflow, 'core_metadata:sbmUlPbCpY', 'z_image_seed_variance_randomize_percent')?.value).toBe(50);
+ });
+
+ it('parseAndMigrateWorkflow does not strip core_metadata extra fields', () => {
+ const workflow = graphToWorkflow(userFirstGraph, false);
+ const migrated = parseAndMigrateWorkflow(workflow);
+ expect(findInput(migrated, 'core_metadata:sbmUlPbCpY', 'z_image_seed_variance_enabled')?.value).toBe(false);
+ expect(findInput(migrated, 'core_metadata:sbmUlPbCpY', 'z_image_seed_variance_strength')?.value).toBe(0.1);
+ expect(findInput(migrated, 'core_metadata:sbmUlPbCpY', 'z_image_seed_variance_randomize_percent')?.value).toBe(50);
+ });
+});
const imageCollectionTemplate = {
title: 'Image Collection Primitive',
diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.ts
index d853d3574e..2245c0b709 100644
--- a/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.ts
@@ -3,7 +3,8 @@ import { logger } from 'app/logging/logger';
import { forEach } from 'es-toolkit/compat';
import { $templates } from 'features/nodes/store/nodesSlice';
import { NODE_WIDTH } from 'features/nodes/types/constants';
-import type { FieldInputInstance } from 'features/nodes/types/field';
+import { nodeAcceptsExtraInputs } from 'features/nodes/types/extraInputs';
+import type { FieldInputInstance, FieldInputTemplate } from 'features/nodes/types/field';
import type { WorkflowV3 } from 'features/nodes/types/workflow';
import { getDefaultForm, isWorkflowInvocationNode } from 'features/nodes/types/workflow';
import { getConnectedInputNames, migrateImageCollectionInputValues } from 'features/nodes/util/node/nodeUpdate';
@@ -13,6 +14,20 @@ import { v4 as uuidv4 } from 'uuid';
const log = logger('workflows');
+// Synthesize a MetadataExtraField template so values for `extra='allow'` keys round-trip through
+// the workflow when the OpenAPI schema does not declare them.
+const buildMetadataExtraFieldTemplate = (name: string): FieldInputTemplate => ({
+ name,
+ title: name,
+ description: '',
+ ui_hidden: true,
+ fieldKind: 'input',
+ input: 'any',
+ required: false,
+ default: undefined,
+ type: { name: 'MetadataExtraField', cardinality: 'SINGLE', batch: false },
+});
+
/**
* Converts a graph to a workflow. This is a best-effort conversion and may not be perfect.
* For example, if a graph references an unknown node type, that node will be skipped.
@@ -61,12 +76,17 @@ export const graphToWorkflow = (graph: NonNullableGraph, autoLayout = true): Wor
return;
}
- const inputTemplate = template.inputs[key];
+ let inputTemplate = template.inputs[key];
- // Skip missing input templates
if (!inputTemplate) {
- log.warn(`Input ${key} not found in template for node type ${node.type}`);
- return;
+ if (nodeAcceptsExtraInputs(node.type)) {
+ // The backend node accepts extras (pydantic `extra='allow'`); preserve the value so
+ // recall metadata survives the round-trip.
+ inputTemplate = buildMetadataExtraFieldTemplate(key);
+ } else {
+ log.warn(`Input ${key} not found in template for node type ${node.type}`);
+ return;
+ }
}
// This _should_ be all we need to do!
diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/loraMetadataRoundtrip.test.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/loraMetadataRoundtrip.test.ts
new file mode 100644
index 0000000000..da5a25522e
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/loraMetadataRoundtrip.test.ts
@@ -0,0 +1,117 @@
+/**
+ * Regression tests for issue #9151:
+ * "Lora collection not firing during generation on workflow"
+ *
+ * Actual root cause: the LoRA *is* applied during the second run (verified
+ * by the user's generation logs and by inspecting the second-run graph —
+ * lora_selector / collect / z_image_lora_collection_loader nodes and edges
+ * are identical to the first run). What was broken: `core_metadata.loras`
+ * and the sibling metadata lists were dropped during the graph -> workflow
+ * -> graph roundtrip, so the resulting image had no LoRA in its metadata
+ * and Recall found nothing.
+ *
+ * Cause: `LoRAMetadataField` (and the ControlNet/IPAdapter/T2IAdapter
+ * metadata field types) were not registered as `zStatefulFieldType`, so
+ * inputs holding them fell through to `zStatelessFieldInputInstance`,
+ * whose `value` is `z.undefined().catch(undefined)` — coercing the value
+ * to undefined.
+ *
+ * These metadata pass-through instances are only declared on nodes that
+ * accept extras (`core_metadata`), so they round-trip via the scoped
+ * `zFieldInputInstanceWithExtras` union rather than the global one - see
+ * PR #9162.
+ */
+
+import { zFieldInputInstanceWithExtras } from 'features/nodes/types/field';
+import { describe, expect, it } from 'vitest';
+
+describe('issue #9151: metadata-field roundtrip', () => {
+ it('preserves a LoRAMetadataField[] value', () => {
+ const inputInstance = {
+ name: 'loras',
+ label: '',
+ description: '',
+ value: [
+ {
+ model: {
+ key: 'lora-key-1',
+ hash: 'hash1',
+ name: 'My Z-Image LoRA',
+ base: 'z-image',
+ type: 'lora',
+ submodel_type: null,
+ },
+ weight: 0.75,
+ },
+ ],
+ };
+
+ const parsed = zFieldInputInstanceWithExtras.parse(inputInstance);
+ expect(parsed.value).toEqual(inputInstance.value);
+ });
+
+ it('preserves a ControlNetMetadataField[] value', () => {
+ const inputInstance = {
+ name: 'controlnets',
+ label: '',
+ description: '',
+ value: [
+ {
+ image: { image_name: 'in.png' },
+ control_model: { key: 'cn', hash: 'h', name: 'cn', base: 'sdxl', type: 'controlnet' },
+ control_weight: 0.5,
+ },
+ ],
+ };
+
+ expect(zFieldInputInstanceWithExtras.parse(inputInstance).value).toEqual(inputInstance.value);
+ });
+
+ it('preserves an IPAdapterMetadataField[] value', () => {
+ const inputInstance = {
+ name: 'ipAdapters',
+ label: '',
+ description: '',
+ value: [
+ {
+ image: { image_name: 'in.png' },
+ ip_adapter_model: { key: 'ip', hash: 'h', name: 'ip', base: 'sdxl', type: 'ip_adapter' },
+ clip_vision_model: 'ViT-H',
+ method: 'full',
+ weight: 0.6,
+ begin_step_percent: 0,
+ end_step_percent: 1,
+ },
+ ],
+ };
+
+ expect(zFieldInputInstanceWithExtras.parse(inputInstance).value).toEqual(inputInstance.value);
+ });
+
+ it('preserves a T2IAdapterMetadataField[] value', () => {
+ const inputInstance = {
+ name: 't2iAdapters',
+ label: '',
+ description: '',
+ value: [
+ {
+ image: { image_name: 'in.png' },
+ t2i_adapter_model: { key: 't2i', hash: 'h', name: 't2i', base: 'sdxl', type: 't2i_adapter' },
+ },
+ ],
+ };
+
+ expect(zFieldInputInstanceWithExtras.parse(inputInstance).value).toEqual(inputInstance.value);
+ });
+
+ it('null is still accepted (no loras applied case)', () => {
+ const inputInstance = {
+ name: 'loras',
+ label: '',
+ description: '',
+ value: null,
+ };
+
+ expect(zFieldInputInstanceWithExtras.parse(inputInstance).value).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts
index cad966f31c..4ef04c0d0c 100644
--- a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts
@@ -584,4 +584,104 @@ describe('validateWorkflow', () => {
expect(refreshedCallNode.data.inputs['saved_workflow_input::child-add::b']?.value).toBe(2);
expect(refreshedCallNode.data.dynamicInputTemplates['saved_workflow_input::child-add::b']).toBeDefined();
});
+
+ // Regression for PR #9162: `core_metadata` accepts undeclared extras (pydantic `extra='allow'`).
+ // These must round-trip without producing "missing field template" load warnings.
+ const core_metadata: InvocationTemplate = {
+ title: 'Core Metadata',
+ type: 'core_metadata',
+ version: '2.1.0',
+ tags: ['metadata'],
+ description: 'Collects core generation metadata into a MetadataField',
+ outputType: 'metadata_output',
+ // Empty inputs: every input on the node below is an undeclared extra, which is exactly what
+ // core_metadata accepts. This keeps the template minimal while exercising the extra path.
+ inputs: {},
+ outputs: {},
+ useCache: true,
+ nodePack: 'invokeai',
+ classification: 'internal',
+ category: 'metadata',
+ };
+
+ const getCoreMetadataWorkflow = (): WorkflowV3 => ({
+ name: '',
+ author: '',
+ description: '',
+ version: '',
+ contact: '',
+ tags: '',
+ notes: '',
+ exposedFields: [],
+ form: getDefaultForm(),
+ meta: { version: '4.0.0', category: 'user' },
+ nodes: [
+ {
+ id: 'core_metadata-1',
+ type: 'invocation',
+ data: {
+ id: 'core_metadata-1',
+ type: 'core_metadata',
+ version: '2.1.0',
+ label: '',
+ notes: '',
+ isOpen: true,
+ isIntermediate: true,
+ useCache: true,
+ nodePack: 'invokeai',
+ dynamicInputTemplates: {},
+ inputs: {
+ generation_mode: { name: 'generation_mode', label: '', description: '', value: 'z_image_txt2img' },
+ // Undeclared extra - not in the template. Must be preserved without a warning.
+ z_image_seed_variance_enabled: {
+ name: 'z_image_seed_variance_enabled',
+ label: '',
+ description: '',
+ value: false,
+ },
+ },
+ },
+ position: { x: 0, y: 0 },
+ },
+ ],
+ edges: [],
+ });
+
+ it('should not warn about undeclared extras on core_metadata and should preserve them', async () => {
+ const validationResult = await validateWorkflow({
+ workflow: getCoreMetadataWorkflow(),
+ templates: { core_metadata },
+ checkImageAccess: resolveTrue,
+ checkBoardAccess: resolveTrue,
+ checkModelAccess: resolveTrue,
+ });
+
+ expect(validationResult.warnings).toEqual([]);
+ expect(get(validationResult, 'workflow.nodes[0].data.inputs.z_image_seed_variance_enabled.value')).toBe(false);
+ });
+
+ it('should still warn about undeclared inputs on nodes that do NOT accept extras', async () => {
+ const workflow = getWorkflow();
+ // main_model_loader does not accept extras - an undeclared input must produce a warning.
+ const node = workflow.nodes[0];
+ if (!node || node.type !== 'invocation') {
+ throw new Error('expected an invocation node');
+ }
+ node.data.inputs.bogus_extra = {
+ name: 'bogus_extra',
+ label: '',
+ description: '',
+ value: 'should-warn',
+ };
+
+ const validationResult = await validateWorkflow({
+ workflow,
+ templates: { img_resize, main_model_loader },
+ checkImageAccess: resolveTrue,
+ checkBoardAccess: resolveTrue,
+ checkModelAccess: resolveTrue,
+ });
+
+ expect(validationResult.warnings.length).toBe(1);
+ });
});
diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.ts
index 3b1752635b..ea1e97f645 100644
--- a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.ts
@@ -4,6 +4,7 @@ import { addElement, getIsFormEmpty } from 'features/nodes/components/sidePanel/
import { CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX } from 'features/nodes/store/nodesSlice';
import type { Templates } from 'features/nodes/store/types';
import { validateConnection } from 'features/nodes/store/util/validateConnection';
+import { nodeAcceptsExtraInputs } from 'features/nodes/types/extraInputs';
import {
isBoardFieldInputInstance,
isImageFieldCollectionInputInstance,
@@ -283,6 +284,11 @@ export const validateWorkflow = async (args: ValidateWorkflowArgs): Promise<Vali
const fieldTemplate = getInvocationNodeInputTemplate(node.data, template, input.name);
if (!fieldTemplate) {
+ if (nodeAcceptsExtraInputs(node.data.type)) {
+ // Undeclared extras on `extra='allow'` nodes (e.g. `core_metadata`) are expected and are
+ // preserved intentionally, so they must not be reported as missing-template warnings.
+ continue;
+ }
const message = t('nodes.missingFieldTemplate');
warnings.push({
message,