Skip to content

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

feat(webv2): add workflow connector support

joshistoast85b1510c8185
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx
new file mode 100644
index 0000000000..1b51168938
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx
@@ -0,0 +1,47 @@
+import { Box, Flex } from '@chakra-ui/react';
+import { Handle, Position, type NodeProps } from '@xyflow/react';
+import { memo } from 'react';
+
+import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '../../../workflows/connectors';
+import type { ConnectorFlowNode as ConnectorFlowNodeType } from './flowAdapters';
+
+const HANDLE_SIZE = 10;
+
+const handleStyle: React.CSSProperties = {
+ background: 'var(--wb-flow-grid)',
+ border: '1px solid var(--chakra-colors-bg)',
+ height: HANDLE_SIZE,
+ width: HANDLE_SIZE,
+};
+
+const ConnectorFlowNodeComponent = ({ data, selected }: NodeProps<ConnectorFlowNodeType>) => {
+ const node = data.documentNode;
+
+ return (
+ <Flex align="center" data-connector-node-id={node.id} justify="center" position="relative" title="Connector">
+ <Handle
+ id={CONNECTOR_INPUT_HANDLE}
+ position={Position.Left}
+ style={{ ...handleStyle, left: -HANDLE_SIZE / 2 }}
+ type="target"
+ />
+ <Box
+ bg="bg"
+ borderColor={selected ? 'accent.solid' : 'border.emphasized'}
+ borderWidth="1px"
+ h="1rem"
+ w="2.5rem"
+ rounded="full"
+ shadow={selected ? 'md' : 'sm'}
+ />
+ <Handle
+ id={CONNECTOR_OUTPUT_HANDLE}
+ position={Position.Right}
+ style={{ ...handleStyle, right: -HANDLE_SIZE / 2 }}
+ type="source"
+ />
+ </Flex>
+ );
+};
+
+export const ConnectorFlowNode = memo(ConnectorFlowNodeComponent);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx
index 5af983e93d..2d19f60e49 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx
@@ -155,7 +155,7 @@ const InputFieldRow = ({
<Handle
id={template.name}
position={Position.Left}
- style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -(ROW_PADDING_X + HANDLE_SIZE / 2) }}
+ style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -ROW_PADDING_X, top: '50%' }}
type="target"
/>
) : null}
@@ -175,7 +175,7 @@ const InputFieldRow = ({
<Handle
id={template.name}
position={Position.Left}
- style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -(ROW_PADDING_X + HANDLE_SIZE / 2) }}
+ style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -ROW_PADDING_X, top: '50%' }}
type="target"
/>
) : null}
@@ -242,7 +242,7 @@ const OutputFieldRow = ({ isSkeleton, template }: { isSkeleton: boolean; templat
<Handle
id={template.name}
position={Position.Right}
- style={{ ...handleStyle(getFieldTypeColor(template.type)), right: -(ROW_PADDING_X + HANDLE_SIZE / 2) }}
+ style={{ ...handleStyle(getFieldTypeColor(template.type)), right: -ROW_PADDING_X, top: '50%' }}
type="source"
/>
{isSkeleton ? (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts
index 1785427f17..e44bd89f9e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts
@@ -2,6 +2,7 @@ import type { Edge as FlowEdge, Node as FlowNode } from '@xyflow/react';
import type {
ProjectGraphState,
+ WorkflowConnectorNode,
WorkflowCurrentImageNode,
WorkflowInvocationNode,
WorkflowNotesNode,
@@ -32,7 +33,8 @@ export type InvocationFlowNode = FlowNode<
>;
export type NotesFlowNode = FlowNode<{ documentNode: WorkflowNotesNode }, 'notes'>;
export type CurrentImageFlowNode = FlowNode<{ documentNode: WorkflowCurrentImageNode }, 'current_image'>;
-export type WorkflowFlowNode = InvocationFlowNode | NotesFlowNode | CurrentImageFlowNode;
+export type ConnectorFlowNode = FlowNode<{ documentNode: WorkflowConnectorNode }, 'connector'>;
+export type WorkflowFlowNode = InvocationFlowNode | NotesFlowNode | CurrentImageFlowNode | ConnectorFlowNode;
const EMPTY_NAMES: string[] = [];
@@ -118,6 +120,20 @@ export const toFlowNodes = (
};
}
+ if (documentNode.type === 'connector') {
+ if (previous?.type === 'connector' && previous.data.documentNode === documentNode) {
+ return previous;
+ }
+
+ return {
+ data: { documentNode },
+ id: documentNode.id,
+ position: documentNode.position,
+ selected,
+ type: 'connector' as const,
+ };
+ }
+
if (previous?.type === 'current_image' && previous.data.documentNode === documentNode) {
return previous;
}
@@ -150,6 +166,10 @@ export const withNodeSelection = (nodes: WorkflowFlowNode[], selectedIds: Set<st
return { ...node, selected };
}
+ if (node.type === 'connector') {
+ return { ...node, selected };
+ }
+
return { ...node, selected };
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
index ccaf222091..75ae93f935 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
@@ -97,11 +97,14 @@ const OutputsTab = ({ template }: { template: InvocationTemplate | undefined })
const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab }) => {
const { templates } = useInvocationTemplatesSnapshot();
- if (node.type === 'notes' || node.type === 'current_image') {
+ if (node.type === 'notes' || node.type === 'current_image' || node.type === 'connector') {
+ const typeLabel =
+ node.type === 'notes' ? 'Notes node' : node.type === 'current_image' ? 'Current Image node' : 'Connector node';
+
return tab === 'data' ? (
<JsonBlock label="Node data" value={node.data} />
) : (
- <DetailRow label="Type" value={node.type === 'notes' ? 'Notes node' : 'Current Image node'} />
+ <DetailRow label="Type" value={typeLabel} />
);
}
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts
index 4a8aa3e148..979f4a81ee 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts
@@ -1,7 +1,13 @@
import { describe, expect, it } from 'vitest';
import { compileProjectGraph, getProjectGraphReadiness } from './buildGraph';
-import { buildInvocationNode, buildNotesNode, createProjectGraph, projectGraphReducer } from './document';
+import {
+ buildConnectorNode,
+ buildInvocationNode,
+ buildNotesNode,
+ createProjectGraph,
+ projectGraphReducer,
+} from './document';
import type { InvocationTemplatesSnapshot } from './templates';
import type { FieldInputTemplate, InvocationTemplate, ProjectGraphState } from './types';
@@ -99,6 +105,41 @@ describe('getProjectGraphReadiness', () => {
expect(getProjectGraphReadiness(doc, loadedSnapshot)).toEqual({ canInvoke: true, reasons: [] });
});
+ it('treats resolved connector output edges as connected required inputs', () => {
+ const sourceNode = buildInvocationNode(templates.source, { x: 0, y: 0 });
+ const sinkNode = buildInvocationNode(templates.sink, { x: 10, y: 0 });
+ const connector = buildConnectorNode({ x: 5, y: 0 });
+ let doc = createProjectGraph('connector-readiness');
+
+ doc = projectGraphReducer(doc, { node: sourceNode, type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: sinkNode, type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: connector, type: 'addNode' });
+ doc = projectGraphReducer(doc, {
+ edge: {
+ id: 'connector-in',
+ source: sourceNode.id,
+ sourceHandle: 'out',
+ target: connector.id,
+ targetHandle: 'in',
+ type: 'default',
+ },
+ type: 'addEdge',
+ });
+ doc = projectGraphReducer(doc, {
+ edge: {
+ id: 'connector-out',
+ source: connector.id,
+ sourceHandle: 'out',
+ target: sinkNode.id,
+ targetHandle: 'text',
+ type: 'default',
+ },
+ type: 'addEdge',
+ });
+
+ expect(getProjectGraphReadiness(doc, loadedSnapshot)).toEqual({ canInvoke: true, reasons: [] });
+ });
+
it('reports missing required inputs and unknown node types', () => {
const { doc, sourceId } = buildDocument();
const withEmptyValue = projectGraphReducer(doc, {
@@ -164,4 +205,41 @@ describe('compileProjectGraph', () => {
board: { board_id: 'board-1' },
});
});
+
+ it('resolves connector chains into executable backend edges', () => {
+ const sourceNode = buildInvocationNode(templates.source, { x: 0, y: 0 });
+ const sinkNode = buildInvocationNode(templates.sink, { x: 10, y: 0 });
+ const connector = buildConnectorNode({ x: 5, y: 0 });
+ let doc = createProjectGraph('connector-compile');
+
+ doc = projectGraphReducer(doc, { node: sourceNode, type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: sinkNode, type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: connector, type: 'addNode' });
+ doc = projectGraphReducer(doc, {
+ edge: {
+ id: 'connector-in',
+ source: sourceNode.id,
+ sourceHandle: 'out',
+ target: connector.id,
+ targetHandle: 'in',
+ type: 'default',
+ },
+ type: 'addEdge',
+ });
+ doc = projectGraphReducer(doc, {
+ edge: {
+ id: 'connector-out',
+ source: connector.id,
+ sourceHandle: 'out',
+ target: sinkNode.id,
+ targetHandle: 'text',
+ type: 'default',
+ },
+ type: 'addEdge',
+ });
+
+ expect(compileProjectGraph(doc, templates).backendGraph?.edges).toEqual([
+ { destination: { field: 'text', node_id: sinkNode.id }, source: { field: 'out', node_id: sourceNode.id } },
+ ]);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts
index 1f303f5dd1..4d71e52b92 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts
@@ -1,4 +1,5 @@
import type { BackendGraphContract, GraphContract } from '../types';
+import { getResolvedWorkflowEdges } from './connectors';
import { createWorkflowId } from './document';
import type { InvocationTemplatesSnapshot } from './templates';
import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState, WorkflowInvocationNode } from './types';
@@ -7,9 +8,9 @@ import { hasAnyCycle } from './validation';
/**
* Compiles the project graph document into the immutable, queue-facing
- * `GraphContract`. Ported from the legacy `buildNodesGraph`, minus connector
- * resolution (connectors are not part of the v7 document) and batch handling
- * (batch/generator nodes are rejected by readiness until batching lands).
+ * `GraphContract`. Ported from the legacy `buildNodesGraph`, with connector
+ * resolution and without batch handling (batch/generator nodes are rejected by
+ * readiness until batching lands).
*/
/** Client-resolved batch/generator nodes from the legacy editor; executing them server-side is meaningless. */
@@ -70,7 +71,11 @@ export const getProjectGraphReadiness = (
}
const reasons: string[] = [];
- const connectedInputs = new Set(document.edges.map((edge) => `${edge.target}:${edge.targetHandle}`));
+ const connectedInputs = new Set(
+ getResolvedWorkflowEdges(document.nodes, document.edges, templates)
+ .filter((edge) => executableNodes.some((node) => node.id === edge.target))
+ .map((edge) => `${edge.target}:${edge.targetHandle}`)
+ );
for (const node of executableNodes) {
const template = templates[node.data.type];
@@ -154,7 +159,7 @@ export const compileProjectGraph = (document: ProjectGraphState, templates: Invo
const seenEdgeKeys = new Set<string>();
- for (const edge of document.edges) {
+ for (const edge of getResolvedWorkflowEdges(document.nodes, document.edges, templates)) {
if (!executableNodeIds.has(edge.source) || !executableNodeIds.has(edge.target)) {
continue;
}
@@ -182,13 +187,15 @@ export const compileProjectGraph = (document: ProjectGraphState, templates: Invo
return {
backendGraph,
- edges: document.edges.map((edge) => ({
- id: edge.id,
- sourceField: edge.sourceHandle,
- sourceNodeId: edge.source,
- targetField: edge.targetHandle,
- targetNodeId: edge.target,
- })),
+ edges: getResolvedWorkflowEdges(document.nodes, document.edges, templates)
+ .filter((edge) => executableNodeIds.has(edge.source) && executableNodeIds.has(edge.target))
+ .map((edge) => ({
+ id: edge.id,
+ sourceField: edge.sourceHandle,
+ sourceNodeId: edge.source,
+ targetField: edge.targetHandle,
+ targetNodeId: edge.target,
+ })),
id: backendGraph.id,
label: document.name || 'Workflow',
nodes: executableNodes.map((node) => ({
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts b/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts
new file mode 100644
index 0000000000..76f10aa53a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts
@@ -0,0 +1,118 @@
+import type { FieldType, InvocationTemplates, WorkflowEdge, WorkflowNode } from './types';
+import { isConnectorNode, isInvocationNode } from './types';
+
+export const CONNECTOR_INPUT_HANDLE = 'in';
+export const CONNECTOR_OUTPUT_HANDLE = 'out';
+
+export interface ResolvedConnectorSource {
+ fieldName: string;
+ nodeId: string;
+ type: FieldType | null;
+}
+
+export interface ResolvedWorkflowEdge extends WorkflowEdge {
+ source: string;
+ sourceHandle: string;
+}
+
+export const getConnectorInputEdge = (connectorId: string, edges: WorkflowEdge[]): WorkflowEdge | undefined =>
+ edges.find(
+ (edge) => edge.type === 'default' && edge.target === connectorId && edge.targetHandle === CONNECTOR_INPUT_HANDLE
+ );
+
+export const getConnectorOutputEdges = (connectorId: string, edges: WorkflowEdge[]): WorkflowEdge[] =>
+ edges.filter(
+ (edge) => edge.type === 'default' && edge.source === connectorId && edge.sourceHandle === CONNECTOR_OUTPUT_HANDLE
+ );
+
+export const resolveConnectorSource = (
+ connectorId: string,
+ nodes: WorkflowNode[],
+ edges: WorkflowEdge[],
+ templates?: InvocationTemplates
+): ResolvedConnectorSource | null => {
+ const visited = new Set<string>();
+
+ const resolve = (nodeId: string): ResolvedConnectorSource | null => {
+ if (visited.has(nodeId)) {
+ return null;
+ }
+
+ visited.add(nodeId);
+
+ const inboundEdge = getConnectorInputEdge(nodeId, edges);
+
+ if (!inboundEdge) {
+ return null;
+ }
+
+ const sourceNode = nodes.find((node) => node.id === inboundEdge.source);
+
+ if (!sourceNode) {
+ return null;
+ }
+
+ if (isInvocationNode(sourceNode)) {
+ return {
+ fieldName: inboundEdge.sourceHandle,
+ nodeId: sourceNode.id,
+ type: templates?.[sourceNode.data.type]?.outputs[inboundEdge.sourceHandle]?.type ?? null,
+ };
+ }
+
+ if (isConnectorNode(sourceNode) && inboundEdge.sourceHandle === CONNECTOR_OUTPUT_HANDLE) {
+ return resolve(sourceNode.id);
+ }
+
+ return null;
+ };
+
+ return resolve(connectorId);
+};
+
+export const resolveWorkflowEdgeSource = (
+ edge: WorkflowEdge,
+ nodes: WorkflowNode[],
+ edges: WorkflowEdge[],
+ templates?: InvocationTemplates
+): ResolvedConnectorSource | null => {
+ const sourceNode = nodes.find((node) => node.id === edge.source);
+
+ if (!sourceNode) {
+ return null;
+ }
+
+ if (isInvocationNode(sourceNode)) {
+ return {
+ fieldName: edge.sourceHandle,
+ nodeId: sourceNode.id,
+ type: templates?.[sourceNode.data.type]?.outputs[edge.sourceHandle]?.type ?? null,
+ };
+ }
+
+ if (isConnectorNode(sourceNode) && edge.sourceHandle === CONNECTOR_OUTPUT_HANDLE) {
+ return resolveConnectorSource(sourceNode.id, nodes, edges, templates);
+ }
+
+ return null;
+};
+
+export const getResolvedWorkflowEdges = (
+ nodes: WorkflowNode[],
+ edges: WorkflowEdge[],
+ templates?: InvocationTemplates
+): ResolvedWorkflowEdge[] => {
+ const resolved: ResolvedWorkflowEdge[] = [];
+
+ for (const edge of edges) {
+ const source = resolveWorkflowEdgeSource(edge, nodes, edges, templates);
+
+ if (!source) {
+ continue;
+ }
+
+ resolved.push({ ...edge, source: source.nodeId, sourceHandle: source.fieldName });
+ }
+
+ return resolved;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts
index 4c114ec90a..431e33a33d 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts
@@ -113,6 +113,19 @@ describe('projectGraphReducer', () => {
expect(next.edges).toHaveLength(1);
});
+ it('adds a new node connected to an existing node in one action', () => {
+ const { doc, nodeAId, nodeBId } = createDocWithNodes();
+ const insertedNode = buildInvocationNode(template, { x: 200, y: 0 });
+ const next = projectGraphReducer(doc, {
+ edge: createEdge(nodeAId, insertedNode.id),
+ node: insertedNode,
+ type: 'addNodeAndEdge',
+ });
+
+ expect(next.nodes.map((node) => node.id)).toEqual([nodeAId, nodeBId, insertedNode.id]);
+ expect(next.edges).toEqual([createEdge(nodeAId, insertedNode.id)]);
+ });
+
it('addGraphElements drops colliding node ids and their edges', () => {
const { doc, nodeAId, nodeBId } = createDocWithNodes();
const existingNode = doc.nodes[0];
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.ts b/invokeai/frontend/webv2/src/workbench/workflows/document.ts
index 8ee102bcb8..de534c2e11 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/document.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/document.ts
@@ -4,6 +4,7 @@ import type {
InvocationTemplate,
ProjectGraphState,
WorkflowCurrentImageNode,
+ WorkflowConnectorNode,
WorkflowEdge,
WorkflowFieldInstance,
WorkflowForm,
@@ -111,6 +112,13 @@ export const buildCurrentImageNode = (position: XYPosition): WorkflowCurrentImag
type: 'current_image',
});
+export const buildConnectorNode = (position: XYPosition): WorkflowConnectorNode => ({
+ data: { label: '' },
+ id: createWorkflowId('connector'),
+ position,
+ type: 'connector',
+});
+
// #region Form manipulation
const getRootContainer = (form: WorkflowForm): ContainerFormElement => {
@@ -275,6 +283,7 @@ const removeNodeFieldElements = (form: WorkflowForm, removedNodeIds: Set<string>
export type ProjectGraphAction =
| { type: 'addNode'; node: WorkflowNode }
+ | { type: 'addNodeAndEdge'; node: WorkflowNode; edge: WorkflowEdge }
| { type: 'addGraphElements'; nodes: WorkflowNode[]; edges: WorkflowEdge[] }
| { type: 'removeNodes'; nodeIds: string[] }
| { type: 'setNodePosition'; nodeId: string; position: XYPosition }
@@ -308,6 +317,7 @@ const undoLabels: Partial<Record<ProjectGraphAction['type'], string>> = {
addFormElement: 'Edit workflow form',
addGraphElements: 'Paste workflow nodes',
addNode: 'Add workflow node',
+ addNodeAndEdge: 'Add workflow node',
exposeField: 'Expose workflow field',
moveFormElement: 'Edit workflow form',
moveFormElementTo: 'Edit workflow form',
@@ -325,6 +335,7 @@ export const getProjectGraphUndoLabel = (action: ProjectGraphAction): string | n
/** Edits meaningful enough to auto-select the project graph as the invocation source. */
export const isHighConfidenceGraphEdit = (action: ProjectGraphAction): boolean =>
action.type === 'addNode' ||
+ action.type === 'addNodeAndEdge' ||
action.type === 'addGraphElements' ||
action.type === 'removeNodes' ||
action.type === 'addEdge' ||
@@ -361,6 +372,20 @@ const setFieldInstance = (
};
});
+const addEdgeToDocument = (document: ProjectGraphState, edge: WorkflowEdge): ProjectGraphState => {
+ // A non-collect input holds at most one connection; connecting replaces it.
+ const targetNode = document.nodes.find((node) => node.id === edge.target);
+ const keepsExisting =
+ targetNode && isInvocationNode(targetNode) && targetNode.data.type === 'collect' && edge.targetHandle === 'item';
+ const edges = keepsExisting
+ ? document.edges
+ : document.edges.filter(
+ (existingEdge) => !(existingEdge.target === edge.target && existingEdge.targetHandle === edge.targetHandle)
+ );
+
+ return { ...document, edges: [...edges, edge] };
+};
+
export const projectGraphReducer = (document: ProjectGraphState, action: ProjectGraphAction): ProjectGraphState => {
const next = applyProjectGraphAction(document, action);
@@ -372,6 +397,13 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGra
case 'addNode': {
return { ...document, nodes: [...document.nodes, action.node] };
}
+ case 'addNodeAndEdge': {
+ if (document.nodes.some((node) => node.id === action.node.id)) {
+ return document;
+ }
+
+ return addEdgeToDocument({ ...document, nodes: [...document.nodes, action.node] }, action.edge);
+ }
case 'addGraphElements': {
if (action.nodes.length === 0 && action.edges.length === 0) {
return document;
@@ -469,20 +501,7 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGra
}));
}
case 'addEdge': {
- // A non-collect input holds at most one connection; connecting replaces it.
- const targetNode = document.nodes.find((node) => node.id === action.edge.target);
- const keepsExisting =
- targetNode &&
- isInvocationNode(targetNode) &&
- targetNode.data.type === 'collect' &&
- action.edge.targetHandle === 'item';
- const edges = keepsExisting
- ? document.edges
- : document.edges.filter(
- (edge) => !(edge.target === action.edge.target && edge.targetHandle === action.edge.targetHandle)
- );
-
- return { ...document, edges: [...edges, action.edge] };
+ return addEdgeToDocument(document, action.edge);
}
case 'removeEdges': {
const removedEdgeIds = new Set(action.edgeIds);
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/types.ts b/invokeai/frontend/webv2/src/workbench/workflows/types.ts
index 7501c72b58..a2164a1963 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/types.ts
@@ -120,7 +120,20 @@ export interface WorkflowCurrentImageNode {
};
}
-export type WorkflowNode = WorkflowInvocationNode | WorkflowNotesNode | WorkflowCurrentImageNode;
+export interface WorkflowConnectorNode {
+ id: string;
+ type: 'connector';
+ position: XYPosition;
+ data: {
+ label: string;
+ };
+}
+
+export type WorkflowNode =
+ | WorkflowInvocationNode
+ | WorkflowNotesNode
+ | WorkflowCurrentImageNode
+ | WorkflowConnectorNode;
export interface WorkflowEdge {
id: string;
@@ -222,3 +235,5 @@ export const isNotesNode = (node: WorkflowNode): node is WorkflowNotesNode => no
export const isCurrentImageNode = (node: WorkflowNode): node is WorkflowCurrentImageNode =>
node.type === 'current_image';
+
+export const isConnectorNode = (node: WorkflowNode): node is WorkflowConnectorNode => node.type === 'connector';
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts
index f993b6ad79..f158849b1e 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts
@@ -1,7 +1,20 @@
import { describe, expect, it } from 'vitest';
-import type { FieldType, InvocationTemplates, ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from './types';
-import { hasAnyCycle, validateConnection, validateConnectionTypes, wouldCreateCycle } from './validation';
+import type {
+ FieldType,
+ InvocationTemplates,
+ ProjectGraphState,
+ WorkflowConnectorNode,
+ WorkflowEdge,
+ WorkflowInvocationNode,
+} from './types';
+import {
+ getCompatibleInputTemplate,
+ hasAnyCycle,
+ validateConnection,
+ validateConnectionTypes,
+ wouldCreateCycle,
+} from './validation';
const single = (name: string): FieldType => ({ batch: false, cardinality: 'SINGLE', name });
const collection = (name: string): FieldType => ({ batch: false, cardinality: 'COLLECTION', name });
@@ -79,6 +92,13 @@ const makeNode = (id: string, type: string): WorkflowInvocationNode => ({
type: 'invocation',
});
+const makeConnector = (id: string): WorkflowConnectorNode => ({
+ data: { label: 'Connector' },
+ id,
+ position: { x: 0, y: 0 },
+ type: 'connector',
+});
+
const templates: InvocationTemplates = {
collect: {
category: 'util',
@@ -161,6 +181,24 @@ const templates: InvocationTemplates = {
},
};
+describe('getCompatibleInputTemplate', () => {
+ it('returns the first visible connectable input by UI order', () => {
+ const baseInput = templates.number.inputs.value;
+ const template = {
+ ...templates.number,
+ inputs: {
+ direct: { ...baseInput, input: 'direct' as const, name: 'direct', title: 'Direct', uiOrder: 0 },
+ hidden: { ...baseInput, name: 'hidden', title: 'Hidden', uiHidden: true, uiOrder: 1 },
+ late: { ...baseInput, name: 'late', title: 'Late', uiOrder: 3 },
+ early: { ...baseInput, name: 'early', title: 'Early', uiOrder: 2 },
+ },
+ };
+
+ expect(getCompatibleInputTemplate(template, single('IntegerField'))?.name).toBe('early');
+ expect(getCompatibleInputTemplate(template, single('ImageField'))).toBeNull();
+ });
+});
+
describe('validateConnection', () => {
const baseDocument: Pick<ProjectGraphState, 'edges' | 'nodes'> = {
edges: [],
@@ -249,4 +287,52 @@ describe('validateConnection', () => {
)
).toMatch(/cycle/);
});
+
+ it('accepts connectors as pass-through routing nodes', () => {
+ const connectorDocument: Pick<ProjectGraphState, 'edges' | 'nodes'> = {
+ edges: [
+ {
+ id: 'connector-in',
+ source: 'n1',
+ sourceHandle: 'value',
+ target: 'connector-1',
+ targetHandle: 'in',
+ type: 'default',
+ },
+ ],
+ nodes: [makeNode('n1', 'number'), makeNode('n2', 'number'), makeConnector('connector-1')],
+ };
+
+ expect(
+ validateConnection(
+ { sourceHandle: 'out', sourceNodeId: 'connector-1', targetHandle: 'value', targetNodeId: 'n2' },
+ connectorDocument,
+ templates
+ )
+ ).toBeNull();
+ });
+
+ it('rejects a second connector input', () => {
+ const connectorDocument: Pick<ProjectGraphState, 'edges' | 'nodes'> = {
+ edges: [
+ {
+ id: 'connector-in',
+ source: 'n1',
+ sourceHandle: 'value',
+ target: 'connector-1',
+ targetHandle: 'in',
+ type: 'default',
+ },
+ ],
+ nodes: [makeNode('n1', 'number'), makeNode('n2', 'number'), makeConnector('connector-1')],
+ };
+
+ expect(
+ validateConnection(
+ { sourceHandle: 'value', sourceNodeId: 'n2', targetHandle: 'in', targetNodeId: 'connector-1' },
+ connectorDocument,
+ templates
+ )
+ ).toMatch(/already has an input/);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts b/invokeai/frontend/webv2/src/workbench/workflows/validation.ts
index 32667d5cd9..529688b826 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/validation.ts
@@ -1,11 +1,20 @@
-import type { FieldType, InvocationTemplates, ProjectGraphState, WorkflowEdge, WorkflowNode } from './types';
-import { isInvocationNode } from './types';
+import type {
+ FieldInputTemplate,
+ FieldType,
+ InvocationTemplate,
+ InvocationTemplates,
+ ProjectGraphState,
+ WorkflowEdge,
+ WorkflowNode,
+} from './types';
+import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE, resolveConnectorSource } from './connectors';
+import { isConnectorNode, isInvocationNode } from './types';
/**
* Connection validation, ported from the legacy editor's
- * `validateConnectionTypes` / `validateConnection`. Connector and batch node
- * special cases are intentionally absent — those node kinds are not part of
- * the v7 document model.
+ * `validateConnectionTypes` / `validateConnection`. Connector nodes are
+ * pass-through routing nodes: their source type is resolved from the first
+ * upstream invocation output when one exists.
*/
const isSingle = (type: FieldType): boolean => type.cardinality === 'SINGLE';
@@ -146,6 +155,60 @@ export interface ConnectionCandidate {
const allowsMultipleInboundEdges = (node: WorkflowNode, fieldName: string): boolean =>
isInvocationNode(node) && node.data.type === 'collect' && fieldName === 'item';
+export const getCompatibleInputTemplate = (
+ template: InvocationTemplate,
+ sourceType: FieldType
+): FieldInputTemplate | null => {
+ const inputTemplates = Object.values(template.inputs).sort(
+ (a, b) => (a.uiOrder ?? Number.MAX_SAFE_INTEGER) - (b.uiOrder ?? Number.MAX_SAFE_INTEGER)
+ );
+
+ return (
+ inputTemplates.find(
+ (inputTemplate) =>
+ !inputTemplate.uiHidden &&
+ inputTemplate.input !== 'direct' &&
+ validateConnectionTypes(sourceType, inputTemplate.type)
+ ) ?? null
+ );
+};
+
+const getSourceFieldType = (
+ node: WorkflowNode,
+ handle: string,
+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,
+ templates: InvocationTemplates
+): FieldType | null | undefined => {
+ if (isInvocationNode(node)) {
+ return templates[node.data.type]?.outputs[handle]?.type;
+ }
+
+ if (isConnectorNode(node) && handle === CONNECTOR_OUTPUT_HANDLE) {
+ return resolveConnectorSource(node.id, document.nodes, document.edges, templates)?.type ?? null;
+ }
+
+ return undefined;
+};
+
+export const getWorkflowSourceFieldType = (
+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,
+ templates: InvocationTemplates,
+ sourceNodeId: string,
+ sourceHandle: string
+): FieldType | null | undefined => {
+ const sourceNode = document.nodes.find((node) => node.id === sourceNodeId);
+
+ return sourceNode ? getSourceFieldType(sourceNode, sourceHandle, document, templates) : undefined;
+};
+
+const hasValidSourceHandle = (node: WorkflowNode, handle: string, templates: InvocationTemplates): boolean => {
+ if (isInvocationNode(node)) {
+ return templates[node.data.type]?.outputs[handle] !== undefined;
+ }
+
+ return isConnectorNode(node) && handle === CONNECTOR_OUTPUT_HANDLE;
+};
+
/** Returns a human-readable rejection reason, or null when the connection is valid. */
export const validateConnection = (
candidate: ConnectionCandidate,
@@ -161,16 +224,39 @@ export const validateConnection = (
const sourceNode = document.nodes.find((node) => node.id === sourceNodeId);
const targetNode = document.nodes.find((node) => node.id === targetNodeId);
- if (!sourceNode || !isInvocationNode(sourceNode) || !targetNode || !isInvocationNode(targetNode)) {
- return 'Both ends of a connection must be invocation nodes.';
+ if (!sourceNode || !targetNode) {
+ return 'Both ends of a connection must be workflow nodes.';
+ }
+
+ if (!hasValidSourceHandle(sourceNode, sourceHandle, templates)) {
+ return 'One of the fields has no known definition.';
+ }
+
+ if (isConnectorNode(targetNode)) {
+ if (targetHandle !== CONNECTOR_INPUT_HANDLE) {
+ return 'Connectors only accept input on their left handle.';
+ }
+
+ if (document.edges.some((edge) => edge.target === targetNodeId && edge.targetHandle === targetHandle)) {
+ return 'Connector already has an input.';
+ }
+
+ if (wouldCreateCycle(sourceNodeId, targetNodeId, document.edges)) {
+ return 'This connection would create a cycle.';
+ }
+
+ return null;
+ }
+
+ if (!isInvocationNode(targetNode)) {
+ return 'The target node cannot receive connections.';
}
- const sourceTemplate = templates[sourceNode.data.type];
const targetTemplate = templates[targetNode.data.type];
- const sourceField = sourceTemplate?.outputs[sourceHandle];
+ const sourceFieldType = getSourceFieldType(sourceNode, sourceHandle, document, templates);
const targetField = targetTemplate?.inputs[targetHandle];
- if (!sourceField || !targetField) {
+ if (sourceFieldType === undefined || !targetField) {
return 'One of the fields has no known definition.';
}
@@ -198,8 +284,8 @@ export const validateConnection = (
return `${targetField.title} already has a connection.`;
}
- if (!validateConnectionTypes(sourceField.type, targetField.type)) {
- return `${sourceField.type.name} cannot connect to ${targetField.type.name}.`;
+ if (sourceFieldType && !validateConnectionTypes(sourceFieldType, targetField.type)) {
+ return `${sourceFieldType.name} cannot connect to ${targetField.type.name}.`;
}
if (wouldCreateCycle(sourceNodeId, targetNodeId, document.edges)) {
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts
index c5f70aa756..ccdd536594 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
buildCurrentImageNode,
+ buildConnectorNode,
buildInvocationNode,
buildNotesNode,
createProjectGraph,
@@ -96,21 +97,27 @@ describe('workflow JSON round-trip', () => {
expect(serialized).toHaveProperty('form');
});
- it('round-trips notes and current_image UI nodes', () => {
+ it('round-trips notes, current_image, and connector UI nodes', () => {
let doc = createProjectGraph('ui-nodes');
doc = projectGraphReducer(doc, { node: buildNotesNode({ x: 1, y: 2 }), type: 'addNode' });
doc = projectGraphReducer(doc, { node: buildCurrentImageNode({ x: 3, y: 4 }), type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: buildConnectorNode({ x: 5, y: 6 }), type: 'addNode' });
const { document: parsed, warnings } = parseWorkflowJson(serializeWorkflowJson(doc));
expect(warnings).toEqual([]);
- expect(parsed.nodes.map((node) => node.type).sort()).toEqual(['current_image', 'notes']);
+ expect(parsed.nodes.map((node) => node.type).sort()).toEqual(['connector', 'current_image', 'notes']);
const currentImage = parsed.nodes.find((node) => node.type === 'current_image');
expect(currentImage?.position).toEqual({ x: 3, y: 4 });
expect(currentImage?.type === 'current_image' && currentImage.data.label).toBe('Current Image');
+
+ const connector = parsed.nodes.find((node) => node.type === 'connector');
+
+ expect(connector?.position).toEqual({ x: 5, y: 6 });
+ expect(connector?.type === 'connector' && connector.data.label).toBe('');
});
});
@@ -142,7 +149,7 @@ describe('parseWorkflowJson tolerance', () => {
});
});
- it('flattens connector chains back to their real source', () => {
+ it('preserves connector nodes and edges', () => {
const { document, warnings } = parseWorkflowJson({
edges: [
{ id: 'e1', source: 'n1', sourceHandle: 'out', target: 'conn1', targetHandle: 'in', type: 'default' },
@@ -152,14 +159,16 @@ describe('parseWorkflowJson tolerance', () => {
nodes: [
{ data: { id: 'n1', inputs: {}, type: 'a' }, id: 'n1', position: { x: 0, y: 0 }, type: 'invocation' },
{ data: { id: 'n2', inputs: {}, type: 'b' }, id: 'n2', position: { x: 0, y: 0 }, type: 'invocation' },
- { id: 'conn1', position: { x: 0, y: 0 }, type: 'connector' },
+ { data: { label: 'Connector' }, id: 'conn1', position: { x: 4, y: 5 }, type: 'connector' },
],
});
- expect(warnings.some((warning) => warning.includes('connector'))).toBe(true);
- expect(document.nodes).toHaveLength(2);
+ expect(warnings).toEqual([]);
+ expect(document.nodes.map((node) => node.type).sort()).toEqual(['connector', 'invocation', 'invocation']);
+ expect(document.nodes.find((node) => node.type === 'connector')?.position).toEqual({ x: 4, y: 5 });
expect(document.edges).toEqual([
- { id: 'e2', source: 'n1', sourceHandle: 'out', target: 'n2', targetHandle: 'text', type: 'default' },
+ { id: 'e1', source: 'n1', sourceHandle: 'out', target: 'conn1', targetHandle: 'in', type: 'default' },
+ { id: 'e2', source: 'conn1', sourceHandle: 'out', target: 'n2', targetHandle: 'text', type: 'default' },
]);
});
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts
index de184fab43..1f8fadb92d 100644
--- a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts
+++ b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts
@@ -14,8 +14,7 @@ import type {
* Import/export between the project graph document and the legacy WorkflowV3
* JSON format — the format used by workflow files, image-embedded workflows,
* and the backend workflow library. Parsing is tolerant: recoverable problems
- * (unknown elements, dangling edges, connector nodes) become warnings instead
- * of failures.
+ * (unknown elements and dangling edges) become warnings instead of failures.
*/
const zXYPosition = z.object({ x: z.number().catch(0), y: z.number().catch(0) }).catch({ x: 0, y: 0 });
@@ -64,6 +63,11 @@ const zCurrentImageNode = z.object({
});
const zConnectorNode = z.object({
+ data: z
+ .looseObject({
+ label: z.string().catch('Connector'),
+ })
+ .catch({ label: 'Connector' }),
id: z.string().min(1),
position: zXYPosition,
type: z.literal('connector'),
@@ -148,64 +152,6 @@ export interface ParsedWorkflow {
warnings: string[];
}
-/**
- * Resolves edges that pass through legacy connector nodes by walking each
- * connector chain back to its real invocation source.
- */
-const resolveConnectorEdges = (
- edges: Array<z.infer<typeof zDefaultEdge>>,
- connectorIds: Set<string>
-): { resolved: Array<z.infer<typeof zDefaultEdge>>; dropped: number } => {
- if (connectorIds.size === 0) {
- return { dropped: 0, resolved: edges };
- }
-
- const findRealSource = (nodeId: string, visited: Set<string>): { source: string; sourceHandle: string } | null => {
- if (visited.has(nodeId)) {
- return null;
- }
-
- visited.add(nodeId);
-
- const inboundEdge = edges.find((edge) => edge.target === nodeId);
-
- if (!inboundEdge) {
- return null;
- }
-
- if (!connectorIds.has(inboundEdge.source)) {
- return { source: inboundEdge.source, sourceHandle: inboundEdge.sourceHandle };
- }
-
- return findRealSource(inboundEdge.source, visited);
- };
-
- let dropped = 0;
- const resolved: Array<z.infer<typeof zDefaultEdge>> = [];
-
- for (const edge of edges) {
- if (connectorIds.has(edge.target)) {
- continue; // Edges into connectors are consumed by the resolution walk.
- }
-
- if (!connectorIds.has(edge.source)) {
- resolved.push(edge);
- continue;
- }
-
- const realSource = findRealSource(edge.source, new Set());
-
- if (!realSource) {
- dropped += 1;
- continue;
- }
-
- resolved.push({ ...edge, source: realSource.source, sourceHandle: realSource.sourceHandle });
- }
-
- return { dropped, resolved };
-};
-
const parseForm = (
rawForm: z.infer<typeof zWorkflowJson>['form'],
exposedFields: Array<z.infer<typeof zFieldIdentifier>>,
@@ -286,7 +232,6 @@ export const parseWorkflowJson = (raw: unknown): ParsedWorkflow => {
const warnings: string[] = [];
const nodes: WorkflowNode[] = [];
- const connectorIds = new Set<string>();
for (const rawNode of parsed.data.nodes) {
const nodeResult = zAnyNode.safeParse(rawNode);
@@ -299,7 +244,12 @@ export const parseWorkflowJson = (raw: unknown): ParsedWorkflow => {
const node = nodeResult.data;
if (node.type === 'connector') {
- connectorIds.add(node.id);
+ nodes.push({
+ data: { label: node.data.label },
+ id: node.id,
+ position: node.position,
+ type: 'connector',
+ });
continue;
}
@@ -352,25 +302,16 @@ export const parseWorkflowJson = (raw: unknown): ParsedWorkflow => {
});
}
- if (connectorIds.size > 0) {
- warnings.push(`Flattened ${connectorIds.size} connector node(s); connectors are not part of this editor.`);
- }
-
const rawEdges = parsed.data.edges.flatMap((rawEdge) => {
const edgeResult = zDefaultEdge.safeParse(rawEdge);
return edgeResult.success ? [edgeResult.data] : [];
});
- const { dropped, resolved } = resolveConnectorEdges(rawEdges, connectorIds);
-
- if (dropped > 0) {
- warnings.push(`Dropped ${dropped} connection(s) that could not be resolved through connectors.`);
- }
const nodeIds = new Set(nodes.map((node) => node.id));
const edges: WorkflowEdge[] = [];
- for (const edge of resolved) {
+ for (const edge of rawEdges) {
if (!nodeIds.has(edge.source) || !nodeIds.has(edge.target)) {
warnings.push('Dropped a connection that referenced a missing node.');
continue;
@@ -421,19 +362,26 @@ export const serializeWorkflowJson = (document: ProjectGraphState): Record<strin
meta: { category: 'user', version: '3.0.0' },
name: document.name,
nodes: document.nodes.map((node) =>
- node.type === 'notes' || node.type === 'current_image'
+ node.type === 'connector'
? {
- data: { ...node.data, id: node.id, isOpen: true },
- id: node.id,
- position: { ...node.position },
- type: node.type,
- }
- : {
- data: { ...structuredClone(node.data), id: node.id },
+ data: { ...node.data, id: node.id, isOpen: true, type: 'connector' },
id: node.id,
position: { ...node.position },
type: node.type,
}
+ : node.type === 'notes' || node.type === 'current_image'
+ ? {
+ data: { ...node.data, id: node.id, isOpen: true },
+ id: node.id,
+ position: { ...node.position },
+ type: node.type,
+ }
+ : {
+ data: { ...structuredClone(node.data), id: node.id },
+ id: node.id,
+ position: { ...node.position },
+ type: node.type,
+ }
),
notes: document.notes,
tags: document.tags,