Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(workflow): improve editor connections and validation
joshistoastde50c6ac3b85
diff --git a/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsxindex f56d7cca8e..c136de11af 100644--- a/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx@@ -21,6 +21,8 @@ import { useEffect, useMemo, useState } from 'react';export const ModelSelect = ({excludeKeys,filter,+ id,+ invalid,modelTypes,onChange,placeholder,@@ -31,6 +33,8 @@ export const ModelSelect = ({excludeKeys?: ReadonlySet<string>;/** Extra predicate, e.g. base-architecture compatibility. */filter?: (model: ModelConfig) => boolean;+ id?: string;+ invalid?: boolean;/** The model types this instance searches. */modelTypes: ModelTaxonomyType[];onChange: (model: ModelConfig | null) => void;@@ -106,6 +110,7 @@ export const ModelSelect = ({return (<Combobox.Rootcollection={collection}+ invalid={invalid}openOnClickplaceholder={placeholder ?? `Search ${scopeLabel}…`}selectionBehavior="replace"@@ -118,7 +123,7 @@ export const ModelSelect = ({}}><Combobox.Control>- <Combobox.Input />+ <Combobox.Input id={id} /><Combobox.IndicatorGroup><Combobox.ClearTrigger /><Combobox.Trigger />diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxindex c2af958f40..6a9d36e14d 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -453,10 +453,10 @@ const WorkflowSection = () => {description="How connections between nodes are drawn in the editor."label="Connection style"value={workflowEdgeStyle}- onChange={(value) => updatePreferences({ workflowEdgeStyle: value === 'straight' ? 'straight' : 'curved' })}+ onChange={(value) => updatePreferences({ workflowEdgeStyle: value === 'square' ? 'square' : 'curved' })}><option value="curved">Curved</option>- <option value="straight">Straight</option>+ <option value="square">Square</option></SettingSelect><SettingTogglechecked={workflowSnapToGrid}diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex d86ecb5031..7862a56425 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -146,7 +146,11 @@ export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): PuseCpuNoise: typeof settings?.useCpuNoise === 'boolean' ? settings.useCpuNoise : DEFAULT_PROJECT_SETTINGS.useCpuNoise,});-export const normalizeWorkbenchPreferences = (preferences?: Partial<WorkbenchPreferences>): WorkbenchPreferences => ({+type WorkbenchPreferencesInput = Omit<Partial<WorkbenchPreferences>, 'workflowEdgeStyle'> & {+ workflowEdgeStyle?: unknown;+};++export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencesInput): WorkbenchPreferences => ({confirmImageDeletion:typeof preferences?.confirmImageDeletion === 'boolean'? preferences.confirmImageDeletion@@ -176,9 +180,11 @@ export const normalizeWorkbenchPreferences = (preferences?: Partial<WorkbenchPre: DEFAULT_PREFERENCES.showFocusRegionHighlight,themeId: isWorkbenchThemeId(preferences?.themeId) ? preferences.themeId : DEFAULT_PREFERENCES.themeId,workflowEdgeStyle:- preferences?.workflowEdgeStyle === 'straight' || preferences?.workflowEdgeStyle === 'curved'- ? preferences.workflowEdgeStyle- : DEFAULT_PREFERENCES.workflowEdgeStyle,+ preferences?.workflowEdgeStyle === 'square' || preferences?.workflowEdgeStyle === 'straight'+ ? 'square'+ : preferences?.workflowEdgeStyle === 'curved'+ ? preferences.workflowEdgeStyle+ : DEFAULT_PREFERENCES.workflowEdgeStyle,workflowShowMinimap:typeof preferences?.workflowShowMinimap === 'boolean'? preferences.workflowShowMinimapdiff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex cec0117bd3..5df872d872 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -513,7 +513,7 @@ export interface WorkbenchPreferences {/** Reject workflow connections with incompatible field types. */workflowValidateConnections: boolean;/** Connection line rendering in the workflow editor. */- workflowEdgeStyle: 'curved' | 'straight';+ workflowEdgeStyle: 'curved' | 'square';}export interface AccountState {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsxindex e69114b3b2..2ccd8b6385 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx@@ -6,14 +6,16 @@ import { IconButton } from '@workbench/components/ui/Button';import { ConfirmDialog } from '@workbench/components/ui/ConfirmDialog';import { useNotify } from '@workbench/useNotify';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '@workbench/workflows/connectors';import {+ buildConnectorNode,buildCurrentImageNode,buildInvocationNode,buildNotesNode,createProjectGraph,createWorkflowId,} from '@workbench/workflows/document';-import { getCompatibleInputTemplate } from '@workbench/workflows/validation';+import { getCompatibleInputTemplate, getCompatibleOutputTemplate } from '@workbench/workflows/validation';import { parseWorkflowJson } from '@workbench/workflows/workflowJson';import { HistoryIcon, LibraryIcon, PlusIcon } from 'lucide-react';import { useEffect, useId, useRef, type ChangeEvent } from 'react';@@ -189,9 +191,38 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {return;}- const targetInput = getCompatibleInputTemplate(template, addNodeConnection.sourceType);+ if (addNodeConnection.kind === 'source') {+ const targetInput = getCompatibleInputTemplate(template, addNodeConnection.sourceType);- if (!targetInput) {+ if (!targetInput) {+ dispatch({+ action: { node, type: 'addNode' },+ type: 'applyProjectGraphAction',+ });+ return;+ }++ dispatch({+ action: {+ edge: {+ id: createWorkflowId('edge'),+ source: addNodeConnection.sourceNodeId,+ sourceHandle: addNodeConnection.sourceHandle,+ target: node.id,+ targetHandle: targetInput.name,+ type: 'default',+ },+ node,+ type: 'addNodeAndEdge',+ },+ type: 'applyProjectGraphAction',+ });+ return;+ }++ const sourceOutput = getCompatibleOutputTemplate(template, addNodeConnection.targetType);++ if (!sourceOutput) {dispatch({action: { node, type: 'addNode' },type: 'applyProjectGraphAction',@@ -203,10 +234,10 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {action: {edge: {id: createWorkflowId('edge'),- source: addNodeConnection.sourceNodeId,- sourceHandle: addNodeConnection.sourceHandle,- target: node.id,- targetHandle: targetInput.name,+ source: node.id,+ sourceHandle: sourceOutput.name,+ target: addNodeConnection.targetNodeId,+ targetHandle: addNodeConnection.targetHandle,type: 'default',},node,@@ -223,6 +254,44 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {});};+ const addConnector = () => {+ const node = buildConnectorNode(getInsertPosition());++ if (!addNodeConnection) {+ dispatch({+ action: { node, type: 'addNode' },+ type: 'applyProjectGraphAction',+ });+ return;+ }++ dispatch({+ action: {+ edge:+ addNodeConnection.kind === 'source'+ ? {+ id: createWorkflowId('edge'),+ source: addNodeConnection.sourceNodeId,+ sourceHandle: addNodeConnection.sourceHandle,+ target: node.id,+ targetHandle: CONNECTOR_INPUT_HANDLE,+ type: 'default',+ }+ : {+ id: createWorkflowId('edge'),+ source: node.id,+ sourceHandle: CONNECTOR_OUTPUT_HANDLE,+ target: addNodeConnection.targetNodeId,+ targetHandle: addNodeConnection.targetHandle,+ type: 'default',+ },+ node,+ type: 'addNodeAndEdge',+ },+ type: 'applyProjectGraphAction',+ });+ };+const addCurrentImage = () => {dispatch({action: { node: buildCurrentImageNode(getInsertPosition()), type: 'addNode' },@@ -336,6 +405,7 @@ export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {connectionFilter={addNodeConnection}isOpen={isAddNodeOpen}onAddCurrentImage={addCurrentImage}+ onAddConnector={addConnector}onAddNode={addNode}onAddNote={addNote}onOpenChange={setAddNodeOpen}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsxindex 18dc71c487..c2efe5327b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx@@ -6,7 +6,7 @@ import { Button } from '@workbench/components/ui/Button';import { Scrollable } from '@workbench/components/ui/Scrollable';import { Tooltip } from '@workbench/components/ui/Tooltip';import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';-import { getCompatibleInputTemplate } from '@workbench/workflows/validation';+import { getCompatibleInputTemplate, getCompatibleOutputTemplate } from '@workbench/workflows/validation';import { HammerIcon } from 'lucide-react';import { useCallback, useMemo, useState, type ChangeEvent, type ReactNode } from 'react';@@ -32,6 +32,29 @@ const matchesSearch = (template: InvocationTemplate, terms: string[]): boolean =return terms.every((term) => haystack.includes(term));};+const isCompatibleConnectionTemplate = (+ template: InvocationTemplate,+ connectionFilter: AddNodeConnectionFilter | null+): boolean => {+ if (!connectionFilter) {+ return true;+ }++ if (connectionFilter.kind === 'source') {+ return getCompatibleInputTemplate(template, connectionFilter.sourceType) !== null;+ }++ return getCompatibleOutputTemplate(template, connectionFilter.targetType) !== null;+};++const getConnectionFilterName = (connectionFilter: AddNodeConnectionFilter): string => {+ if (connectionFilter.kind === 'source') {+ return connectionFilter.sourceType?.name ?? 'connector';+ }++ return connectionFilter.targetType?.name ?? 'connector';+};+interface NodeRow {description: string;isBeta: boolean;@@ -87,6 +110,7 @@ export const AddNodeDialog = ({connectionFilter,isOpen,onAddCurrentImage,+ onAddConnector,onAddNode,onAddNote,onOpenChange,@@ -94,6 +118,7 @@ export const AddNodeDialog = ({connectionFilter: AddNodeConnectionFilter | null;isOpen: boolean;onAddCurrentImage: () => void;+ onAddConnector: () => void;onAddNode: (template: InvocationTemplate) => void;onAddNote: () => void;onOpenChange: (isOpen: boolean) => void;@@ -103,6 +128,7 @@ export const AddNodeDialog = ({connectionFilter={connectionFilter}isOpen={isOpen}onAddCurrentImage={onAddCurrentImage}+ onAddConnector={onAddConnector}onAddNode={onAddNode}onAddNote={onAddNote}onOpenChange={onOpenChange}@@ -113,6 +139,7 @@ const AddNodeDialogContent = ({connectionFilter,isOpen,onAddCurrentImage,+ onAddConnector,onAddNode,onAddNote,onOpenChange,@@ -120,6 +147,7 @@ const AddNodeDialogContent = ({connectionFilter: AddNodeConnectionFilter | null;isOpen: boolean;onAddCurrentImage: () => void;+ onAddConnector: () => void;onAddNode: (template: InvocationTemplate) => void;onAddNote: () => void;onOpenChange: (isOpen: boolean) => void;@@ -144,30 +172,42 @@ const AddNodeDialogContent = ({const groups = useMemo<CategoryGroup[]>(() => {const terms = searchTerm.trim().toLowerCase().split(/\s+/).filter(Boolean);- const utilityRows: NodeRow[] = connectionFilter- ? []- : [- {- description: 'Annotate the workflow with a free-text note.',- isBeta: false,- nodePack: 'invokeai',- onAdd: () => {- onAddNote();- close(true);+ const utilityRows: NodeRow[] = [+ {+ description: 'Route a connection through a compact pass-through handle.',+ isBeta: false,+ nodePack: 'invokeai',+ onAdd: () => {+ onAddConnector();+ close(true);+ },+ title: 'Connector',+ },+ ...(connectionFilter+ ? []+ : [+ {+ description: 'Annotate the workflow with a free-text note.',+ isBeta: false,+ nodePack: 'invokeai',+ onAdd: () => {+ onAddNote();+ close(true);+ },+ title: 'Notes',},- title: 'Notes',- },- {- description: 'Show the latest generated image (and live progress) inside the graph.',- isBeta: false,- nodePack: 'invokeai',- onAdd: () => {- onAddCurrentImage();- close(true);+ {+ description: 'Show the latest generated image (and live progress) inside the graph.',+ isBeta: false,+ nodePack: 'invokeai',+ onAdd: () => {+ onAddCurrentImage();+ close(true);+ },+ title: 'Current Image',},- title: 'Current Image',- },- ].filter((row) => terms.every((term) => row.title.toLowerCase().includes(term)));+ ]),+ ].filter((row) => terms.every((term) => row.title.toLowerCase().includes(term)));const byCategory = new Map<string, NodeRow[]>();@@ -175,7 +215,7 @@ const AddNodeDialogContent = ({if (template.classification === 'internal' ||(terms.length > 0 && !matchesSearch(template, terms)) ||- (connectionFilter && !getCompatibleInputTemplate(template, connectionFilter.sourceType))+ !isCompatibleConnectionTemplate(template, connectionFilter)) {continue;}@@ -205,7 +245,7 @@ const AddNodeDialogContent = ({return utilityRows.length > 0? [{ label: UTILITY_CATEGORY, rows: utilityRows }, ...categoryGroups]: categoryGroups;- }, [close, connectionFilter, onAddCurrentImage, onAddNode, onAddNote, searchTerm, templates]);+ }, [close, connectionFilter, onAddConnector, onAddCurrentImage, onAddNode, onAddNote, searchTerm, templates]);const totalCount = groups.reduce((sum, group) => sum + group.rows.length, 0);const accordionValue = isSearching ? groups.map((group) => group.label) : expandedCategories;@@ -221,7 +261,9 @@ const AddNodeDialogContent = ({} else if (totalCount === 0) {body = (<Text color="fg.subtle" fontSize="xs" px="1" py="4" textAlign="center">- {connectionFilter ? `No nodes accept ${connectionFilter.sourceType.name}.` : 'No nodes match your search.'}+ {connectionFilter+ ? `No compatible ${getConnectionFilterName(connectionFilter)} nodes.`+ : 'No nodes match your search.'}</Text>);} else {@@ -285,7 +327,7 @@ const AddNodeDialogContent = ({aria-label="Search for nodes"placeholder={connectionFilter- ? `Search compatible ${connectionFilter.sourceType.name} nodes…`+ ? `Search compatible ${getConnectionFilterName(connectionFilter)} nodes…`: 'Search for nodes…'}size="md"diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsxindex ee3ff3f411..fafc2658ef 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/ConnectorFlowNode.tsx@@ -1,45 +1,87 @@+import type { FieldType } from '@workbench/workflows/types';+import { Box, Flex } from '@chakra-ui/react';+import { Tooltip } from '@workbench/components/ui/Tooltip';import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '@workbench/workflows/connectors';+import { getFieldTypeColor, getFieldTypeLabel, isModelFieldType } from '@workbench/workflows/fields';import { Handle, Position, type NodeProps } from '@xyflow/react';import { memo } from 'react';import type { ConnectorFlowNode as ConnectorFlowNodeType } from './flowAdapters';-const HANDLE_SIZE = 10;+import { getHandleTypeTooltip } from './handleTooltip';++const HANDLE_SIZE = 12;+type HandleSide = 'left' | 'right';-const handleStyle: React.CSSProperties = {+const genericHandleStyle: React.CSSProperties = {background: 'var(--wb-flow-grid)',border: '1px solid var(--chakra-colors-bg)',height: HANDLE_SIZE,width: HANDLE_SIZE,};+const typedHandleStyle = (type: FieldType, side: HandleSide): React.CSSProperties => {+ const color = getFieldTypeColor(type);+ const isFilled = type.cardinality === 'SINGLE';+ const isAngular = isModelFieldType(type) || type.batch;+ const centeredDiamondTransform = `translate(${side === 'left' ? '-' : ''}50%, -50%) rotate(45deg)`;++ return {+ background: isFilled ? color : 'var(--xy-background-color)',+ border: isFilled ? 'none' : `3px solid ${color}`,+ borderRadius: isAngular ? 3 : '50%',+ boxShadow: '0 0 0 1px var(--xy-background-color)',+ height: HANDLE_SIZE,+ transform: type.batch ? centeredDiamondTransform : undefined,+ width: HANDLE_SIZE,+ };+};++const getConnectorHandleStyle = (type: FieldType | null, side: HandleSide): React.CSSProperties =>+ type ? typedHandleStyle(type, side) : genericHandleStyle;++const getConnectorTitle = (inputType: FieldType | null, outputType: FieldType | null): string => {+ const inputLabel = inputType ? getFieldTypeLabel(inputType) : 'Any input';+ const outputLabel = outputType ? getFieldTypeLabel(outputType) : 'Any output';++ return `Connector: ${inputLabel} -> ${outputLabel}`;+};+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 align="center" data-connector-node-id={node.id} justify="center" position="relative">+ <Tooltip content={getHandleTypeTooltip(data.inputFieldType, 'Any input')} showArrow>+ <Handle+ id={CONNECTOR_INPUT_HANDLE}+ position={Position.Left}+ style={{ ...getConnectorHandleStyle(data.inputFieldType, 'left'), left: -HANDLE_SIZE / 2 }}+ type="target"+ />+ </Tooltip>+ <Tooltip content={getConnectorTitle(data.inputFieldType, data.outputFieldType)} showArrow>+ <Box+ bg="bg"+ borderColor={selected ? 'accent.solid' : 'border.emphasized'}+ borderWidth="1px"+ h="1rem"+ rounded="full"+ shadow={selected ? 'md' : 'sm'}+ transition="border-color 0.12s ease, box-shadow 0.12s ease"+ w="2.5rem"+ _hover={selected ? undefined : { borderColor: 'brand.solid', shadow: 'md' }}+ />+ </Tooltip>+ <Tooltip content={getHandleTypeTooltip(data.outputFieldType, 'Any output')} showArrow>+ <Handle+ id={CONNECTOR_OUTPUT_HANDLE}+ position={Position.Right}+ style={{ ...getConnectorHandleStyle(data.outputFieldType, 'right'), right: -HANDLE_SIZE / 2 }}+ type="source"+ />+ </Tooltip></Flex>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsxindex 0fe4e36bf9..d21055a300 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx@@ -36,7 +36,9 @@ const CurrentImageFlowNodeComponent = ({ data, selected }: NodeProps<CurrentImagoverflow="hidden"rounded="lg"shadow={selected ? 'md' : 'sm'}+ transition="border-color 0.12s ease, box-shadow 0.12s ease"w="20rem"+ _hover={selected ? undefined : { borderColor: 'brand.solid', shadow: 'md' }}><Flex align="center" bg="bg.subtle" borderBottomWidth="1px" borderColor="border.subtle" px="3" py="1.5"><Text fontWeight="700">{node.data.label || 'Current Image'}</Text>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsxindex cbae90505f..077b9ff735 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx@@ -1,6 +1,11 @@-import type { FieldInputTemplate, FieldOutputTemplate, WorkflowInvocationNode } from '@workbench/workflows/types';+import type {+ FieldInputTemplate,+ FieldOutputTemplate,+ FieldType,+ WorkflowInvocationNode,+} from '@workbench/workflows/types';-import { Badge, Box, Flex, HStack, Icon, Image, Input, Stack, Text, IconButton } from '@chakra-ui/react';+import { Badge, Box, Field, Flex, HStack, Icon, Image, Input, Stack, Text, IconButton } from '@chakra-ui/react';import { useNodeExecutionState, type NodeExecutionState } from '@workbench/backend/nodeExecutionStore';import { Tooltip } from '@workbench/components/ui/Tooltip';import { FieldDescriptionPopover } from '@workbench/widgets/workflow/fields/FieldDescriptionPopover';@@ -9,8 +14,10 @@ import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';import {getFieldTypeColor,getFieldTypeLabel,+ getWorkflowFieldInvalidReason,isDirectInputField,isExposableField,+ isModelFieldType,} from '@workbench/workflows/fields';import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';@@ -19,19 +26,32 @@ import { memo, useState, type ChangeEvent, type KeyboardEvent } from 'react';import type { InvocationFlowNode as InvocationFlowNodeType } from './flowAdapters';+import { getHandleTypeTooltip } from './handleTooltip';+const NODE_WIDTH = '18rem';-const HANDLE_SIZE = 10;+const HANDLE_SIZE = 12;+type HandleSide = 'left' | 'right';/** Row padding-x in px; inline handles sit in the label rows, so they pull back out past it. */const ROW_PADDING_X = 12;/** Below this viewport zoom, field content renders as skeleton bars (ComfyUI-style) for performance/readability. */const CONTENT_VISIBILITY_ZOOM = 0.4;-const handleStyle = (color: string): React.CSSProperties => ({- background: color,- border: 'none',- height: HANDLE_SIZE,- width: HANDLE_SIZE,-});+const handleStyle = (type: FieldType, side: HandleSide): React.CSSProperties => {+ const color = getFieldTypeColor(type);+ const isFilled = type.cardinality === 'SINGLE';+ const isAngular = isModelFieldType(type) || type.batch;+ const centeredDiamondTransform = `translate(${side === 'left' ? '-' : ''}50%, -50%) rotate(45deg)`;++ return {+ background: isFilled ? color : 'var(--xy-background-color)',+ border: isFilled ? 'none' : `3px solid ${color}`,+ borderRadius: isAngular ? 3 : '50%',+ boxShadow: '0 0 0 1.5px var(--xy-background-color)',+ height: HANDLE_SIZE,+ transform: type.batch ? centeredDiamondTransform : undefined,+ width: HANDLE_SIZE,+ };+};const sortByUiOrder = <T extends { uiOrder?: number | null }>(templates: T[]): T[] =>[...templates].sort((a, b) => (a.uiOrder ?? Number.MAX_SAFE_INTEGER) - (b.uiOrder ?? Number.MAX_SAFE_INTEGER));@@ -42,29 +62,53 @@ const useIsZoomedOut = (): boolean => useStore((state) => state.transform[2] < C/** Static placeholder bar standing in for text/controls at far zoom. No animation — there may be hundreds. */const SkeletonBar = ({ h = '2', w }: { h?: string; w?: string }) => <Box bg="bg.emphasized" h={h} rounded="sm" w={w} />;+const hasMissingRequiredInputs = (+ node: WorkflowInvocationNode,+ templateInputs: FieldInputTemplate[],+ connectedFieldNames: Set<string>+): boolean =>+ templateInputs.some(+ (inputTemplate) =>+ getWorkflowFieldInvalidReason({+ isConnected: connectedFieldNames.has(inputTemplate.name),+ template: inputTemplate,+ value: node.data.inputs[inputTemplate.name]?.value,+ }) !== null+ );+const NodeShell = ({+ hasMissingRequiredInput,children,isMissing,isRunning,selected,}: {+ hasMissingRequiredInput?: boolean;children: React.ReactNode;isMissing?: boolean;isRunning?: boolean;selected: boolean;-}) => (- <Box- bg="bg"- borderColor={isMissing ? 'red.solid' : isRunning ? 'brand.solid' : selected ? 'accent.solid' : 'border.emphasized'}- borderWidth="1px"- fontSize="xs"- rounded="lg"- shadow={isRunning ? '0 0 10px {colors.brand.solid/50}' : selected ? 'md' : 'sm'}- w={NODE_WIDTH}- >- {children}- </Box>-);+}) => {+ const isInvalid = isMissing || hasMissingRequiredInput;++ return (+ <Box+ bg="bg"+ borderColor={+ isInvalid ? 'red.solid' : selected ? 'accent.solid' : isRunning ? 'brand.solid' : 'border.emphasized'+ }+ borderWidth="1px"+ fontSize="xs"+ rounded="lg"+ shadow={isRunning ? '0 0 10px {colors.brand.solid/50}' : selected ? 'md' : 'sm'}+ transition="border-color 0.12s ease, box-shadow 0.12s ease"+ w={NODE_WIDTH}+ _hover={selected || isInvalid ? undefined : { borderColor: 'brand.solid', shadow: 'md' }}+ >+ {children}+ </Box>+ );+};/** Thin progress strip under the header while the node's invocation executes. */const NodeProgressStrip = ({ execution }: { execution: NodeExecutionState | null }) => {@@ -133,6 +177,54 @@ const NodeTitle = ({ node }: { node: WorkflowInvocationNode }) => {);};+const getInputModeLabel = (input: FieldInputTemplate['input']): string => {+ if (input === 'connection') {+ return 'Connection only';+ }++ if (input === 'direct') {+ return 'Direct value only';+ }++ return 'Direct value or connection';+};++const InputFieldTooltip = ({+ description,+ isConnected,+ isExposed,+ label,+ template,+}: {+ description: string;+ isConnected: boolean;+ isExposed: boolean;+ label: string;+ template: FieldInputTemplate;+}) => (+ <Stack gap="0.5" maxW="18rem">+ <Text fontWeight="700">{label}</Text>+ <Text color="fg.subtle">Field: {template.name}</Text>+ <Text color="fg.subtle">Type: {getFieldTypeLabel(template.type)}</Text>+ <Text color="fg.subtle">+ {template.required ? 'Required' : 'Optional'} · {getInputModeLabel(template.input)}+ </Text>+ {isConnected ? <Text color="fg.subtle">Connected by graph edge.</Text> : null}+ {isExposed ? <Text color="fg.subtle">Pinned to Linear UI.</Text> : null}+ {description ? <Text>{description}</Text> : null}+ </Stack>+);++const OutputFieldTooltip = ({ template }: { template: FieldOutputTemplate }) => (+ <Stack gap="0.5" maxW="18rem">+ <Text fontWeight="700">{template.title}</Text>+ <Text color="fg.subtle">Field: {template.name}</Text>+ <Text color="fg.subtle">Type: {getFieldTypeLabel(template.type)}</Text>+ <Text color="fg.subtle">Output</Text>+ {template.description ? <Text>{template.description}</Text> : null}+ </Stack>+);+const InputFieldRow = ({isConnected,isExposed,@@ -151,18 +243,27 @@ const InputFieldRow = ({const fieldIdentifier = { fieldName: template.name, nodeId: node.id };const showsControl = !isConnected && isDirectInputField(template);const label = instance?.label || template.title;+ const invalidReason = getWorkflowFieldInvalidReason({+ isConnected,+ template,+ value: instance?.value,+ });+ const isInvalid = invalidReason !== null;+ const handleTooltip = getHandleTypeTooltip(template.type);if (isSkeleton) {return (<Box px="3" py="1.5"><HStack gap="1.5" h="5" position="relative">{template.input !== 'direct' ? (- <Handle- id={template.name}- position={Position.Left}- style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -ROW_PADDING_X, top: '50%' }}- type="target"- />+ <Tooltip content={handleTooltip} showArrow>+ <Handle+ id={template.name}+ position={Position.Left}+ style={{ ...handleStyle(template.type, 'left'), left: -ROW_PADDING_X, top: '50%' }}+ type="target"+ />+ </Tooltip>) : null}<SkeletonBar w="55%" /></HStack>@@ -172,98 +273,137 @@ const InputFieldRow = ({}return (- <Box px="3" py="1.5">- {/* The handle lives inside the label row so it stays centered on the- label even when the value control below grows the row. */}- <HStack gap="1.5" justify="space-between" position="relative">- {template.input !== 'direct' ? (- <Handle- id={template.name}- position={Position.Left}- style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -ROW_PADDING_X, top: '50%' }}- type="target"- />- ) : null}- <Tooltip- content={`${instance?.description || template.description || label} — ${getFieldTypeLabel(template.type)}`}- >- <Text color={isConnected ? 'fg.muted' : 'fg'} fontSize="2xs" minW="0" truncate>- {label}- {template.required ? (- <Text as="span" color="fg.error">- {' *'}- </Text>+ <Box px="3" py="1.5" w="full">+ <Field.Root gap="0" invalid={isInvalid} minW="0" w="full">+ {/* The handle lives inside the label row so it stays centered on the+ label even when the value control below grows the row. */}+ <HStack gap="1.5" h="5" justify="space-between" minW="0" position="relative" w="full">+ {template.input !== 'direct' ? (+ <Tooltip content={handleTooltip} showArrow>+ <Handle+ id={template.name}+ position={Position.Left}+ style={{ ...handleStyle(template.type, 'left'), left: -ROW_PADDING_X, top: '50%' }}+ type="target"+ />+ </Tooltip>+ ) : null}+ <Tooltip+ positioning={{ placement: 'top-start' }}+ content={+ <InputFieldTooltip+ description={instance?.description || template.description}+ isConnected={isConnected}+ isExposed={isExposed}+ label={label}+ template={template}+ />+ }+ >+ <Text+ color={isInvalid ? 'fg.error' : isConnected ? 'fg.muted' : 'fg'}+ fontSize="2xs"+ lineHeight="1"+ minW="0"+ truncate+ >+ {label}+ {template.required ? (+ <Text as="span" color="fg.error">+ {' *'}+ </Text>+ ) : null}+ </Text>+ </Tooltip>+ <HStack flexShrink={0} gap="0" ml="auto">+ <FieldDescriptionPopover+ description={instance?.description}+ fieldName={template.name}+ nodeId={node.id}+ templateDescription={template.description}+ />+ {isExposableField(template) ? (+ <IconButton+ aria-label={isExposed ? `Remove ${label} from Linear UI` : `Expose ${label} in Linear UI`}+ className="nodrag"+ color={isExposed ? 'accent.solid' : 'fg.subtle'}+ size="2xs"+ title={isExposed ? 'Remove from Linear UI form' : 'Expose in Linear UI form'}+ variant="ghost"+ onClick={() =>+ dispatch({+ action: { fieldIdentifier, type: isExposed ? 'unexposeField' : 'exposeField' },+ type: 'applyProjectGraphAction',+ })+ }+ >+ <Icon as={isExposed ? PinOffIcon : PinIcon} boxSize="3" />+ </IconButton>) : null}- </Text>- </Tooltip>- <HStack flexShrink={0} gap="0">- <FieldDescriptionPopover- description={instance?.description}- fieldName={template.name}- nodeId={node.id}- templateDescription={template.description}- />- {isExposableField(template) ? (- <IconButton- aria-label={isExposed ? `Remove ${label} from Linear UI` : `Expose ${label} in Linear UI`}- className="nodrag"- color={isExposed ? 'accent.solid' : 'fg.subtle'}- size="2xs"- title={isExposed ? 'Remove from Linear UI form' : 'Expose in Linear UI form'}- variant="ghost"- onClick={() =>+ </HStack>+ </HStack>+ {showsControl ? (+ <Box mt="0.5" w="full">+ <WorkflowFieldInput+ id={`${node.id}-${template.name}-value`}+ invalid={isInvalid}+ template={template}+ value={instance?.value}+ onChange={(value) =>dispatch({- action: { fieldIdentifier, type: isExposed ? 'unexposeField' : 'exposeField' },+ action: { fieldName: template.name, nodeId: node.id, type: 'setFieldValue', value },type: 'applyProjectGraphAction',})}- >- <Icon as={isExposed ? PinOffIcon : PinIcon} boxSize="3" />- </IconButton>- ) : null}- </HStack>- </HStack>- {showsControl ? (- <Box mt="1">- <WorkflowFieldInput- template={template}- value={instance?.value}- onChange={(value) =>- dispatch({- action: { fieldName: template.name, nodeId: node.id, type: 'setFieldValue', value },- type: 'applyProjectGraphAction',- })- }- />- </Box>- ) : null}+ />+ </Box>+ ) : null}+ {invalidReason ? <Field.ErrorText fontSize="2xs">{invalidReason}</Field.ErrorText> : null}+ </Field.Root></Box>);};-const OutputFieldRow = ({ isSkeleton, template }: { isSkeleton: boolean; template: FieldOutputTemplate }) => (- <Box px="3" py="1">- <Box position="relative">- <Handle- id={template.name}- position={Position.Right}- style={{ ...handleStyle(getFieldTypeColor(template.type)), right: -ROW_PADDING_X, top: '50%' }}- type="source"- />- {isSkeleton ? (- <Flex h="4" justify="flex-end">- <SkeletonBar w="40%" />- </Flex>- ) : (- <Tooltip content={`${template.description || template.title} — ${getFieldTypeLabel(template.type)}`}>- <Text color="fg.muted" fontSize="2xs" textAlign="end" truncate>- {template.title}- </Text>+const OutputFieldRow = ({ isSkeleton, template }: { isSkeleton: boolean; template: FieldOutputTemplate }) => {+ const handleTooltip = getHandleTypeTooltip(template.type);++ return (+ <Box px="3" py="1">+ <Flex align="center" h="5" justify="flex-end" position="relative">+ <Tooltip content={handleTooltip} positioning={{ placement: 'left-start' }} showArrow>+ <Handle+ id={template.name}+ position={Position.Right}+ style={{ ...handleStyle(template.type, 'right'), right: -ROW_PADDING_X, top: '50%' }}+ type="source"+ /></Tooltip>- )}+ {isSkeleton ? (+ <Flex justify="flex-end" w="full">+ <SkeletonBar w="40%" />+ </Flex>+ ) : (+ <Box textAlign="end">+ <Tooltip content={<OutputFieldTooltip template={template} />} positioning={{ placement: 'top-end' }}>+ <Text+ as="span"+ color="fg.muted"+ display="inline-block"+ fontSize="2xs"+ lineHeight="1"+ maxW="full"+ textAlign="end"+ truncate+ >+ {template.title}+ </Text>+ </Tooltip>+ </Box>+ )}+ </Flex></Box>- </Box>-);+ );+};/** Keeps every handle mounted (invisible) so edges stay attached when rows are not rendered. */const HiddenHandles = ({@@ -279,7 +419,7 @@ const HiddenHandles = ({key={outputTemplate.name}id={outputTemplate.name}position={Position.Right}- style={{ ...handleStyle(getFieldTypeColor(outputTemplate.type)), opacity: 0, right: 0, top: -14 }}+ style={{ ...handleStyle(outputTemplate.type, 'right'), opacity: 0, right: 0, top: -14 }}type="source"/>))}@@ -289,7 +429,7 @@ const HiddenHandles = ({key={inputTemplate.name}id={inputTemplate.name}position={Position.Left}- style={{ ...handleStyle(getFieldTypeColor(inputTemplate.type)), left: 0, opacity: 0, top: -14 }}+ style={{ ...handleStyle(inputTemplate.type, 'left'), left: 0, opacity: 0, top: -14 }}type="target"/>) : null@@ -327,9 +467,10 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFloconst outputTemplates = Object.values(template.outputs);const isOpen = node.data.isOpen;const isRunning = execution?.status === 'running';+ const isMissingRequiredInput = hasMissingRequiredInputs(node, Object.values(template.inputs), connectedFieldNames);return (- <NodeShell isRunning={isRunning} selected={selected ?? false}>+ <NodeShell hasMissingRequiredInput={isMissingRequiredInput} isRunning={isRunning} selected={selected ?? false}><Flexalign="center"bg="bg.subtle"@@ -338,7 +479,8 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFloborderTopRadius="lg"borderBottomRadius={isOpen ? 'none' : 'lg'}gap="1"- px="2"+ ps="1.5"+ pe="2"py="1.5"><IconButton@@ -373,7 +515,7 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlo</Flex><NodeProgressStrip execution={execution} />{isOpen ? (- <Box py="1" bg="bg.muted">+ <Box bg="bg.muted" borderBottomRadius={execution?.outputImageUrl ? 'none' : 'lg'} py="1">{outputTemplates.map((outputTemplate) => (<OutputFieldRow key={outputTemplate.name} isSkeleton={isZoomedOut} template={outputTemplate} />))}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsxindex 9b02f5300f..d838e54a42 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx@@ -18,7 +18,9 @@ const NotesFlowNodeComponent = ({ data, selected }: NodeProps<NotesFlowNodeType>p="2"rounded="lg"shadow={selected ? 'md' : 'sm'}+ transition="border-color 0.12s ease, box-shadow 0.12s ease"w="16rem"+ _hover={selected ? undefined : { borderColor: 'brand.solid', shadow: 'md' }}><Inputaria-label="Note title"diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.test.tsnew file mode 100644index 0000000000..79374458cb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.test.ts@@ -0,0 +1,41 @@+import { Position } from '@xyflow/react';+import { createElement } from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import { describe, expect, it } from 'vitest';++import type { WorkflowEdgeData } from './flowAdapters';++import { WorkflowEdge } from './WorkflowEdge';++const data: WorkflowEdgeData = {+ fieldTypeLabel: 'Image',+ pathType: 'default',+ stroke: '#c4b5fd',+ strokeWidth: 2,+ tooltip: 'Image',+};++const props = {+ data,+ id: 'edge-1',+ markerEnd: undefined,+ selected: false,+ source: 'a',+ sourcePosition: Position.Right,+ sourceX: 0,+ sourceY: 0,+ target: 'b',+ targetPosition: Position.Left,+ targetX: 100,+ targetY: 0,+};++describe('WorkflowEdge', () => {+ it('attaches the field type tooltip to visible and interactive edge paths', () => {+ const markup = renderToStaticMarkup(createElement(WorkflowEdge, props));++ expect(markup).toContain('react-flow__edge-path');+ expect(markup).toContain('react-flow__edge-interaction');+ expect(markup.match(/<title>Image<\/title>/g)).toHaveLength(2);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.tsxnew file mode 100644index 0000000000..9b080ac9d0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEdge.tsx@@ -0,0 +1,89 @@+import type { EdgeProps } from '@xyflow/react';++import { getBezierPath, getSmoothStepPath } from '@xyflow/react';+import { memo, type CSSProperties } from 'react';++import type { WorkflowEdgeData } from './flowAdapters';++const FALLBACK_EDGE_DATA: WorkflowEdgeData = {+ fieldTypeLabel: 'Unknown',+ pathType: 'default',+ stroke: 'var(--xy-edge-stroke)',+ strokeWidth: 2,+ tooltip: 'Unknown field type',+};++const WorkflowEdgeComponent = ({+ data,+ interactionWidth = 20,+ markerEnd,+ markerStart,+ selected,+ sourcePosition,+ sourceX,+ sourceY,+ style,+ targetPosition,+ targetX,+ targetY,+}: EdgeProps) => {+ const edgeData = (data as WorkflowEdgeData | undefined) ?? FALLBACK_EDGE_DATA;+ const [edgePath] =+ edgeData.pathType === 'step'+ ? getSmoothStepPath({+ borderRadius: 0,+ sourcePosition,+ sourceX,+ sourceY,+ targetPosition,+ targetX,+ targetY,+ })+ : getBezierPath({+ sourcePosition,+ sourceX,+ sourceY,+ targetPosition,+ targetX,+ targetY,+ });+ const edgeStyle: CSSProperties = {+ ...style,+ animation: selected ? 'dashdraw 0.5s linear infinite' : undefined,+ stroke: edgeData.stroke,+ strokeDasharray: selected ? '5' : edgeData.strokeDasharray,+ strokeLinecap: 'round',+ strokeLinejoin: 'round',+ strokeWidth: edgeData.strokeWidth,+ };++ return (+ <g aria-label={edgeData.tooltip} role="img">+ <path+ aria-label={edgeData.tooltip}+ className="react-flow__edge-path"+ d={edgePath}+ fill="none"+ markerEnd={markerEnd}+ markerStart={markerStart}+ style={edgeStyle}+ >+ <title>{edgeData.tooltip}</title>+ </path>+ {interactionWidth ? (+ <path+ aria-label={edgeData.tooltip}+ className="react-flow__edge-interaction"+ d={edgePath}+ fill="none"+ strokeOpacity={0}+ strokeWidth={interactionWidth}+ >+ <title>{edgeData.tooltip}</title>+ </path>+ ) : null}+ </g>+ );+};++export const WorkflowEdge = memo(WorkflowEdgeComponent);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsxindex c660e689ea..72f62e4683 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx@@ -11,7 +11,11 @@ import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/Workbimport { getProjectGraphReadiness } from '@workbench/workflows/buildGraph';import { buildConnectorNode, createWorkflowId } from '@workbench/workflows/document';import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';-import { getWorkflowSourceFieldType, validateConnection } from '@workbench/workflows/validation';+import {+ getWorkflowSourceFieldType,+ getWorkflowTargetFieldType,+ validateConnection,+} from '@workbench/workflows/validation';import {Background,BackgroundVariant,@@ -22,8 +26,8 @@ import {applyEdgeChanges,applyNodeChanges,type Connection,- type Edge as FlowEdge,type EdgeChange,+ type EdgeTypes,type IsValidConnection,type NodeChange,type NodeTypes,@@ -44,7 +48,14 @@ import { buildDuplicateElements, buildPasteElements, copyNodesToClipboard, useHaimport { ConnectorFlowNode } from './ConnectorFlowNode';import { CurrentImageFlowNode } from './CurrentImageFlowNode';import { EditorToolbar, type EditorTool } from './EditorToolbar';-import { toFlowEdges, toFlowNodes, withNodeSelection, type FlowEdgeType, type WorkflowFlowNode } from './flowAdapters';+import {+ toFlowEdges,+ toFlowNodes,+ withNodeSelection,+ type FlowEdgeType,+ type WorkflowFlowEdge,+ type WorkflowFlowNode,+} from './flowAdapters';import {registerWorkflowFlowInstance,releaseWorkflowFlowInstance,@@ -53,10 +64,16 @@ import {import { InvocationFlowNode } from './InvocationFlowNode';import { NodeContextMenu, type WorkflowContextMenuState } from './NodeContextMenu';import { NotesFlowNode } from './NotesFlowNode';-import { clearNodeSelectionRequest, reportNodeSelection, workflowSelectionStore } from './selectionStore';+import {+ clearNodeSelectionRequest,+ reportNodeHover,+ reportNodeSelection,+ workflowSelectionStore,+} from './selectionStore';import { useEraser } from './useEraser';import { useLasso } from './useLasso';import { useModifierHeld } from './useModifierHeld';+import { WorkflowEdge } from './WorkflowEdge';const nodeTypes: NodeTypes = {connector: ConnectorFlowNode,@@ -65,6 +82,11 @@ const nodeTypes: NodeTypes = {notes: NotesFlowNode,};+const edgeTypes: EdgeTypes = {+ default: WorkflowEdge,+ step: WorkflowEdge,+};+/*** The workflow center view: an xyflow editor over the project graph document.* The document is the source of truth — flow state is rebuilt from it on every@@ -76,7 +98,7 @@ const SNAP_GRID: [number, number] = [24, 24];const DELETE_KEY_CODES = ['Backspace', 'Delete'];-const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 1.5 } };+const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 2 } };const isEditableTarget = (target: EventTarget | null): boolean =>target instanceof HTMLElement && target.closest('input, textarea, select, [contenteditable="true"]') !== null;@@ -91,6 +113,9 @@ const getEventClientPosition = (event: MouseEvent | TouchEvent): { x: number; y:return touch ? { x: touch.clientX, y: touch.clientY } : null;};+const getSelectedNodeIdSet = (nodes: WorkflowFlowNode[]): Set<string> =>+ new Set(nodes.filter((node) => node.selected).map((node) => node.id));+const WorkflowFlow = () => {const projectGraph = useActiveProjectSelector((project) => project.projectGraph);const dispatch = useWorkbenchDispatch();@@ -98,24 +123,35 @@ const WorkflowFlow = () => {const { themeId, workflowEdgeStyle, workflowShowMinimap, workflowSnapToGrid, workflowValidateConnections } =useWorkbenchPreferences();const templatesSnapshot = useInvocationTemplatesSnapshot();- const edgeType: FlowEdgeType = workflowEdgeStyle === 'straight' ? 'straight' : 'default';- const [flowNodes, setFlowNodes] = useState<WorkflowFlowNode[]>(() => toFlowNodes(projectGraph));- const [flowEdges, setFlowEdges] = useState<FlowEdge[]>(() => toFlowEdges(projectGraph, [], edgeType));+ const invocationTemplates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : undefined;+ const edgeType: FlowEdgeType = workflowEdgeStyle === 'square' ? 'step' : 'default';+ const [flowNodes, setFlowNodes] = useState<WorkflowFlowNode[]>(() =>+ toFlowNodes(projectGraph, [], invocationTemplates)+ );+ const [flowEdges, setFlowEdges] = useState<WorkflowFlowEdge[]>(() =>+ toFlowEdges(projectGraph, [], edgeType, new Set<string>(), invocationTemplates)+ );const [flowInstance, setFlowInstance] = useState<WorkflowFlowInstance | null>(null);const [tool, setTool] = useState<EditorTool>('pan');const [nodeOpacity, setNodeOpacity] = useState(1);const [contextMenu, setContextMenu] = useState<WorkflowContextMenuState | null>(null);- const { selectionRequest } = workflowSelectionStore.useSnapshot();+ const { selectedNodeIds, selectionRequest } = workflowSelectionStore.useSnapshot();const isSnapHeld = useModifierHeld('Control');const hasClipboardNodes = useHasClipboardNodes();const backgroundId = useId().replace(/:/g, '');/** Node ids to select once the next document-driven rebuild lands (fresh paste/duplicate results). */const pendingSelectionRef = useRef<string[] | null>(null);- const selectNodes = useCallback((nodeIds: string[]) => {- setFlowNodes((current) => withNodeSelection(current, new Set(nodeIds)));- reportNodeSelection(nodeIds);- }, []);+ const selectNodes = useCallback(+ (nodeIds: string[]) => {+ const selectedNodeIdSet = new Set(nodeIds);++ setFlowNodes((current) => withNodeSelection(current, selectedNodeIdSet));+ setFlowEdges((current) => toFlowEdges(projectGraph, current, edgeType, selectedNodeIdSet, invocationTemplates));+ reportNodeSelection(nodeIds);+ },+ [edgeType, invocationTemplates, projectGraph]+ );const { lassoHandlers, lassoOverlay } = useLasso({enabled: tool === 'lasso',@@ -157,17 +193,20 @@ const WorkflowFlow = () => {const pendingSelection = pendingSelectionRef.current;pendingSelectionRef.current = null;+ const nextSelectedNodeIds = pendingSelection ?? selectedNodeIds;+ const nextSelectedNodeIdSet = new Set(nextSelectedNodeIds);+setFlowNodes((current) => {- const next = toFlowNodes(projectGraph, current);+ const next = toFlowNodes(projectGraph, current, invocationTemplates);- return pendingSelection ? withNodeSelection(next, new Set(pendingSelection)) : next;+ return pendingSelection ? withNodeSelection(next, nextSelectedNodeIdSet) : next;});- setFlowEdges((current) => toFlowEdges(projectGraph, current, edgeType));+ setFlowEdges((current) => toFlowEdges(projectGraph, current, edgeType, nextSelectedNodeIdSet, invocationTemplates));if (pendingSelection) {reportNodeSelection(pendingSelection);}- }, [edgeType, projectGraph]);+ }, [edgeType, invocationTemplates, projectGraph, selectedNodeIds]);// Expose the instance to the widget header's actions (outside this provider).useEffect(() => {@@ -294,7 +333,7 @@ const WorkflowFlow = () => {);const onEdgesChange = useCallback(- (changes: EdgeChange<FlowEdge>[]) => {+ (changes: EdgeChange<WorkflowFlowEdge>[]) => {const removedEdgeIds = changes.flatMap((change) => (change.type === 'remove' ? [change.id] : []));if (removedEdgeIds.length > 0) {@@ -306,7 +345,7 @@ const WorkflowFlow = () => {[dispatch]);- const isValidConnection: IsValidConnection<FlowEdge> = useCallback(+ const isValidConnection: IsValidConnection<WorkflowFlowEdge> = useCallback((connection) => {if (!connection.sourceHandle || !connection.targetHandle) {return false;@@ -363,21 +402,15 @@ const WorkflowFlow = () => {return;}- const sourceHandle = connectionState.fromHandle?.id;- const sourceNodeId = connectionState.fromHandle?.nodeId ?? connectionState.fromNode?.id;-- if (!sourceHandle || !sourceNodeId || connectionState.fromHandle?.type !== 'source') {+ if (connectionState.isValid || connectionState.toHandle || connectionState.toNode) {return;}- const sourceType = getWorkflowSourceFieldType(- projectGraph,- templatesSnapshot.templates,- sourceNodeId,- sourceHandle- );+ const handle = connectionState.fromHandle;+ const handleId = handle?.id;+ const nodeId = handle?.nodeId ?? connectionState.fromNode?.id;- if (!sourceType) {+ if (!handleId || !nodeId) {return;}@@ -387,7 +420,36 @@ const WorkflowFlow = () => {return;}- setAddNodeOpen(true, flowInstance.screenToFlowPosition(position), { sourceHandle, sourceNodeId, sourceType });+ if (handle.type === 'source') {+ const sourceType = getWorkflowSourceFieldType(projectGraph, templatesSnapshot.templates, nodeId, handleId);++ if (sourceType === undefined) {+ return;+ }++ setAddNodeOpen(true, flowInstance.screenToFlowPosition(position), {+ kind: 'source',+ sourceHandle: handleId,+ sourceNodeId: nodeId,+ sourceType,+ });+ return;+ }++ if (handle.type === 'target') {+ const targetType = getWorkflowTargetFieldType(projectGraph, templatesSnapshot.templates, nodeId, handleId);++ if (targetType === undefined) {+ return;+ }++ setAddNodeOpen(true, flowInstance.screenToFlowPosition(position), {+ kind: 'target',+ targetHandle: handleId,+ targetNodeId: nodeId,+ targetType,+ });+ }},[flowInstance, projectGraph, templatesSnapshot.templates]);@@ -464,7 +526,7 @@ const WorkflowFlow = () => {);const onEdgeClick = useCallback(- (_: ReactMouseEvent, edge: FlowEdge) => {+ (_: ReactMouseEvent, edge: WorkflowFlowEdge) => {if (tool === 'eraser') {eraseElements({ edgeIds: [edge.id], nodeIds: [] });}@@ -473,14 +535,35 @@ const WorkflowFlow = () => {);const onSelectionChange = useCallback(- ({ nodes }: { nodes: WorkflowFlowNode[] }) => reportNodeSelection(nodes.map((node) => node.id)),- []+ ({ nodes }: { nodes: WorkflowFlowNode[] }) => {+ const nodeIds = nodes.map((node) => node.id);++ setFlowEdges((current) =>+ toFlowEdges(projectGraph, current, edgeType, getSelectedNodeIdSet(nodes), invocationTemplates)+ );+ reportNodeSelection(nodeIds);+ },+ [edgeType, invocationTemplates, projectGraph]);+ const onNodeMouseEnter = useCallback((_: ReactMouseEvent, node: WorkflowFlowNode) => {+ reportNodeHover(node.id);+ }, []);++ const onNodeMouseLeave = useCallback((_: ReactMouseEvent, node: WorkflowFlowNode) => {+ if (workflowSelectionStore.getSnapshot().hoveredNodeId === node.id) {+ reportNodeHover(null);+ }+ }, []);+const editorCss = useMemo(() => ({...flowThemeCss,'& .react-flow__node': { opacity: nodeOpacity },+ '& .react-flow__edge.workflow-selected-node-edge .react-flow__edge-path': {+ animation: 'dashdraw 0.5s linear infinite',+ strokeDasharray: '5',+ },...(tool === 'eraser'? { '& .react-flow__edge, & .react-flow__node, & .react-flow__pane': { cursor: 'crosshair' } }: {}),@@ -500,12 +583,14 @@ const WorkflowFlow = () => {onKeyDown={onEditorKeyDown}{...pointerToolHandlers}>- <ReactFlow+ <ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>colorMode={getFlowColorMode(themeId)}- connectionLineType={edgeType === 'straight' ? ConnectionLineType.Straight : ConnectionLineType.Bezier}+ connectionLineType={edgeType === 'step' ? ConnectionLineType.Step : ConnectionLineType.Bezier}defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}deleteKeyCode={DELETE_KEY_CODES}+ elevateEdgesOnSelectedges={flowEdges}+ edgeTypes={edgeTypes}fitViewisValidConnection={isValidConnection}maxZoom={2}@@ -526,6 +611,8 @@ const WorkflowFlow = () => {onInit={setFlowInstance}onNodeClick={onNodeClick}onNodeContextMenu={onNodeContextMenu}+ onNodeMouseEnter={onNodeMouseEnter}+ onNodeMouseLeave={onNodeMouseLeave}onNodesChange={onNodesChange}onPaneContextMenu={onPaneContextMenu}onSelectionChange={onSelectionChange}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.tsindex 869f163c2e..53f93258f9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts@@ -1,9 +1,62 @@-import type { ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from '@workbench/workflows/types';+import type {+ FieldType,+ InvocationTemplate,+ InvocationTemplates,+ ProjectGraphState,+ WorkflowConnectorNode,+ WorkflowEdge,+ WorkflowInvocationNode,+} from '@workbench/workflows/types';+import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '@workbench/workflows/connectors';import { buildCurrentImageNode, createProjectGraph } from '@workbench/workflows/document';import { describe, expect, it } from 'vitest';-import { toFlowEdges, toFlowNodes, withNodeSelection } from './flowAdapters';+import { getWorkflowEdgeData, toFlowEdges, toFlowNodes, withNodeSelection } from './flowAdapters';++const single = (name: string): FieldType => ({ batch: false, cardinality: 'SINGLE', name });+const collection = (name: string): FieldType => ({ batch: false, cardinality: 'COLLECTION', name });++const createTemplate = (outputType: FieldType = single('IntegerField')): InvocationTemplate => ({+ category: 'test',+ classification: 'stable',+ description: '',+ inputs: {+ a: {+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name: 'a',+ options: null,+ required: true,+ title: 'A',+ type: outputType,+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ },+ },+ nodePack: 'invokeai',+ outputType: 'test',+ outputs: {+ value: { description: '', name: 'value', title: 'Value', type: outputType },+ },+ tags: [],+ title: 'Add',+ type: 'add',+ useCache: true,+ version: '1.0.0',+});++const createTemplates = (outputType?: FieldType): InvocationTemplates => ({ add: createTemplate(outputType) });const createNode = (id: string): WorkflowInvocationNode => ({data: {@@ -22,15 +75,28 @@ const createNode = (id: string): WorkflowInvocationNode => ({type: 'invocation',});-const createEdge = (id: string, source: string, target: string): WorkflowEdge => ({+const createEdge = (+ id: string,+ source: string,+ target: string,+ sourceHandle = 'value',+ targetHandle = 'a'+): WorkflowEdge => ({id,source,- sourceHandle: 'value',+ sourceHandle,target,- targetHandle: 'a',+ targetHandle,type: 'default',});+const createConnector = (id: string): WorkflowConnectorNode => ({+ data: { label: '' },+ id,+ position: { x: 0, y: 0 },+ type: 'connector',+});+const createDoc = (overrides?: Partial<ProjectGraphState>): ProjectGraphState => ({...createProjectGraph('adapters-test'),edges: [createEdge('e1', 'a', 'b')],@@ -94,6 +160,39 @@ describe('flowAdapters identity preservation', () => {expect(nodeB?.type === 'invocation' && nodeB.data.exposedFieldNames).toEqual(['a']);});+ it('precomputes resolved connector field types onto connector node data', () => {+ const fieldType = single('ImageField');+ const templates = createTemplates(fieldType);+ const doc = createDoc({+ edges: [+ createEdge('e1', 'a', 'c', 'value', CONNECTOR_INPUT_HANDLE),+ createEdge('e2', 'c', 'b', CONNECTOR_OUTPUT_HANDLE, 'a'),+ ],+ nodes: [createNode('a'), createConnector('c'), createNode('b')],+ });+ const untyped = toFlowNodes(doc);+ const typed = toFlowNodes(doc, untyped, templates);+ const connector = typed[1];++ expect(connector?.type).toBe('connector');+ expect(connector?.type === 'connector' && connector.data.inputFieldType).toBe(fieldType);+ expect(connector?.type === 'connector' && connector.data.outputFieldType).toBe(fieldType);+ expect(connector).not.toBe(untyped[1]);+ expect(toFlowNodes(doc, typed, templates)[1]).toBe(connector);+ });++ it('does not mark a target as connected through an unresolved connector output', () => {+ const doc = createDoc({+ edges: [createEdge('e1', 'c', 'b', CONNECTOR_OUTPUT_HANDLE, 'a')],+ nodes: [createConnector('c'), createNode('b')],+ });+ const nodes = toFlowNodes(doc);+ const target = nodes.find((node) => node.id === 'b');++ expect(target?.type).toBe('invocation');+ expect(target?.type === 'invocation' ? target.data.connectedTargetHandles : []).toEqual([]);+ });+it('carries selection across rebuilds and toggles it without copying unchanged nodes', () => {const doc = createDoc();const selected = withNodeSelection(toFlowNodes(doc), new Set(['a']));@@ -126,9 +225,64 @@ describe('flowAdapters identity preservation', () => {expect(same[0]).toBe(first[0]);- const restyled = toFlowEdges(doc, first, 'straight');+ const restyled = toFlowEdges(doc, first, 'step');expect(restyled[0]).not.toBe(first[0]);- expect(restyled[0]?.type).toBe('straight');+ expect(restyled[0]?.type).toBe('step');+ });++ it('adds field type metadata for custom edge rendering', () => {+ const doc = createDoc();+ const edge = toFlowEdges(doc, [], 'default', new Set(), createTemplates())[0];++ expect(edge?.data).toMatchObject({+ fieldTypeLabel: 'Integer',+ pathType: 'default',+ stroke: '#f87171',+ strokeWidth: 2,+ tooltip: 'Integer',+ });+ });++ it('uses line pattern metadata for collection field types', () => {+ const doc = createDoc();+ const data = getWorkflowEdgeData(doc, doc.edges[0]!, 'step', createTemplates(collection('ImageField')));++ expect(data).toMatchObject({+ fieldTypeLabel: 'Image Collection',+ pathType: 'step',+ stroke: '#c4b5fd',+ strokeDasharray: '8 4',+ strokeWidth: 2.5,+ tooltip: 'Image Collection',+ });+ });++ it('replaces edges when templates resolve their field type styling', () => {+ const doc = createDoc();+ const untyped = toFlowEdges(doc, [], 'default');+ const typed = toFlowEdges(doc, untyped, 'default', new Set(), createTemplates());++ expect(typed[0]).not.toBe(untyped[0]);+ expect(typed[0]?.data?.tooltip).toBe('Integer');+ });++ it('styles edges connected to selected nodes without persisting the highlight after deselection', () => {+ const doc = createDoc();+ const highlighted = toFlowEdges(doc, [], 'default', new Set(['a']));++ expect(highlighted[0]?.animated).toBe(true);+ expect(highlighted[0]?.className).toBe('workflow-selected-node-edge');+ expect(highlighted[0]?.zIndex).toBe(1000);+ expect(highlighted[0]?.style).toEqual({ strokeWidth: 2 });+ expect(toFlowEdges(doc, highlighted, 'default', new Set(['a']))[0]).toBe(highlighted[0]);++ const cleared = toFlowEdges(doc, highlighted, 'default');++ expect(cleared[0]).not.toBe(highlighted[0]);+ expect(cleared[0]?.animated).toBeUndefined();+ expect(cleared[0]?.className).toBeUndefined();+ expect(cleared[0]?.zIndex).toBeUndefined();+ expect(cleared[0]?.style).toBeUndefined();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.tsindex cfe28faf01..dab9ec7377 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts@@ -1,11 +1,23 @@import type {+ FieldType,+ InvocationTemplates,ProjectGraphState,WorkflowConnectorNode,WorkflowCurrentImageNode,+ WorkflowEdge,WorkflowInvocationNode,WorkflowNotesNode,} from '@workbench/workflows/types';import type { Edge as FlowEdge, Node as FlowNode } from '@xyflow/react';+import type { CSSProperties } from 'react';++import {+ CONNECTOR_INPUT_HANDLE,+ CONNECTOR_OUTPUT_HANDLE,+ getResolvedWorkflowEdges,+} from '@workbench/workflows/connectors';+import { getFieldTypeColor, getFieldTypeLabel } from '@workbench/workflows/fields';+import { getWorkflowSourceFieldType, getWorkflowTargetFieldType } from '@workbench/workflows/validation';/*** Adapters between the project graph document and xyflow's node/edge state.@@ -32,17 +44,23 @@ export type InvocationFlowNode = FlowNode<>;export type NotesFlowNode = FlowNode<{ documentNode: WorkflowNotesNode }, 'notes'>;export type CurrentImageFlowNode = FlowNode<{ documentNode: WorkflowCurrentImageNode }, 'current_image'>;-export type ConnectorFlowNode = FlowNode<{ documentNode: WorkflowConnectorNode }, 'connector'>;+export type ConnectorFlowNode = FlowNode<+ { documentNode: WorkflowConnectorNode; inputFieldType: FieldType | null; outputFieldType: FieldType | null },+ 'connector'+>;export type WorkflowFlowNode = InvocationFlowNode | NotesFlowNode | CurrentImageFlowNode | ConnectorFlowNode;const EMPTY_NAMES: string[] = [];+const EMPTY_NODE_IDS = new Set<string>();+const SELECTED_NODE_EDGE_CLASS = 'workflow-selected-node-edge';+const SELECTED_NODE_EDGE_STYLE: CSSProperties = { strokeWidth: 2 };const sameNames = (a: string[], b: string[]): boolean => a.length === b.length && a.every((name, i) => name === b[i]);const getConnectedHandlesByNode = (document: ProjectGraphState): Map<string, string[]> => {const byNode = new Map<string, string[]>();- for (const edge of document.edges) {+ for (const edge of getResolvedWorkflowEdges(document.nodes, document.edges)) {byNode.set(edge.target, [...(byNode.get(edge.target) ?? []), edge.targetHandle]);}@@ -73,7 +91,8 @@ const getExposedFieldsByNode = (document: ProjectGraphState): Map<string, stringexport const toFlowNodes = (document: ProjectGraphState,- previousNodes: WorkflowFlowNode[] = []+ previousNodes: WorkflowFlowNode[] = [],+ templates?: InvocationTemplates): WorkflowFlowNode[] => {const previousById = new Map(previousNodes.map((node) => [node.id, node]));const connectedByNode = getConnectedHandlesByNode(document);@@ -120,12 +139,24 @@ export const toFlowNodes = (}if (documentNode.type === 'connector') {- if (previous?.type === 'connector' && previous.data.documentNode === documentNode) {+ const inputFieldType = templates+ ? (getWorkflowTargetFieldType(document, templates, documentNode.id, CONNECTOR_INPUT_HANDLE) ?? null)+ : null;+ const outputFieldType = templates+ ? (getWorkflowSourceFieldType(document, templates, documentNode.id, CONNECTOR_OUTPUT_HANDLE) ?? null)+ : null;++ if (+ previous?.type === 'connector' &&+ previous.data.documentNode === documentNode &&+ previous.data.inputFieldType === inputFieldType &&+ previous.data.outputFieldType === outputFieldType+ ) {return previous;}return {- data: { documentNode },+ data: { documentNode, inputFieldType, outputFieldType },id: documentNode.id,position: documentNode.position,selected,@@ -173,17 +204,99 @@ export const withNodeSelection = (nodes: WorkflowFlowNode[], selectedIds: Set<st});/** xyflow edge component per the user's connection-style preference. */-export type FlowEdgeType = 'default' | 'straight';+export type FlowEdgeType = 'default' | 'step';++export interface WorkflowEdgeData extends Record<string, unknown> {+ fieldTypeLabel: string;+ pathType: FlowEdgeType;+ stroke: string;+ strokeDasharray?: string;+ strokeWidth: number;+ tooltip: string;+}++export type WorkflowFlowEdge = FlowEdge<WorkflowEdgeData, FlowEdgeType>;++const UNKNOWN_EDGE_DATA = (pathType: FlowEdgeType): WorkflowEdgeData => ({+ fieldTypeLabel: 'Unknown',+ pathType,+ stroke: 'var(--xy-edge-stroke)',+ strokeWidth: 2,+ tooltip: 'Unknown field type',+});++const getWorkflowEdgeFieldType = (+ document: ProjectGraphState,+ templates: InvocationTemplates | undefined,+ edge: WorkflowEdge+): FieldType | null => {+ if (!templates) {+ return null;+ }++ return (+ getWorkflowSourceFieldType(document, templates, edge.source, edge.sourceHandle) ??+ getWorkflowTargetFieldType(document, templates, edge.target, edge.targetHandle) ??+ null+ );+};++export const getWorkflowEdgeData = (+ document: ProjectGraphState,+ edge: WorkflowEdge,+ pathType: FlowEdgeType,+ templates?: InvocationTemplates+): WorkflowEdgeData => {+ const fieldType = getWorkflowEdgeFieldType(document, templates, edge);++ if (!fieldType) {+ return UNKNOWN_EDGE_DATA(pathType);+ }++ const fieldTypeLabel = getFieldTypeLabel(fieldType);+ const strokeDasharray = fieldType.batch+ ? '2 5'+ : fieldType.cardinality === 'COLLECTION'+ ? '8 4'+ : fieldType.cardinality === 'SINGLE_OR_COLLECTION'+ ? '8 3 2 3'+ : undefined;++ return {+ fieldTypeLabel,+ pathType,+ stroke: getFieldTypeColor(fieldType),+ strokeDasharray,+ strokeWidth: fieldType.cardinality === 'SINGLE' && !fieldType.batch ? 2 : 2.5,+ tooltip: fieldType.batch ? `${fieldTypeLabel} batch` : fieldTypeLabel,+ };+};++const isSameEdgeData = (a: WorkflowEdgeData | undefined, b: WorkflowEdgeData): boolean =>+ a?.fieldTypeLabel === b.fieldTypeLabel &&+ a.pathType === b.pathType &&+ a.stroke === b.stroke &&+ a.strokeDasharray === b.strokeDasharray &&+ a.strokeWidth === b.strokeWidth &&+ a.tooltip === b.tooltip;export const toFlowEdges = (document: ProjectGraphState,- previousEdges: FlowEdge[] = [],- edgeType: FlowEdgeType = 'default'-): FlowEdge[] => {+ previousEdges: WorkflowFlowEdge[] = [],+ edgeType: FlowEdgeType = 'default',+ selectedNodeIds: Set<string> = EMPTY_NODE_IDS,+ templates?: InvocationTemplates+): WorkflowFlowEdge[] => {const previousById = new Map(previousEdges.map((edge) => [edge.id, edge]));return document.edges.map((edge) => {const previous = previousById.get(edge.id);+ const data = getWorkflowEdgeData(document, edge, edgeType, templates);+ const isConnectedToSelectedNode = selectedNodeIds.has(edge.source) || selectedNodeIds.has(edge.target);+ const animated = isConnectedToSelectedNode || undefined;+ const className = isConnectedToSelectedNode ? SELECTED_NODE_EDGE_CLASS : undefined;+ const style = isConnectedToSelectedNode ? SELECTED_NODE_EDGE_STYLE : undefined;+ const zIndex = isConnectedToSelectedNode ? 1000 : undefined;if (previous &&@@ -191,19 +304,29 @@ export const toFlowEdges = (previous.source === edge.source &&previous.sourceHandle === edge.sourceHandle &&previous.target === edge.target &&- previous.targetHandle === edge.targetHandle+ previous.targetHandle === edge.targetHandle &&+ previous.animated === animated &&+ previous.className === className &&+ isSameEdgeData(previous.data, data) &&+ previous.style === style &&+ previous.zIndex === zIndex) {return previous;}return {id: edge.id,+ animated,+ className,+ data,selected: previous?.selected ?? false,source: edge.source,sourceHandle: edge.sourceHandle,+ style,target: edge.target,targetHandle: edge.targetHandle,type: edgeType,+ zIndex,};});};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.tsindex 8a2c3abb99..2f1d651d42 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.ts@@ -1,6 +1,6 @@-import type { Edge as FlowEdge, ReactFlowInstance } from '@xyflow/react';+import type { ReactFlowInstance } from '@xyflow/react';-import type { WorkflowFlowNode } from './flowAdapters';+import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';/*** Module-level handle to the mounted workflow editor's ReactFlow instance, so@@ -9,7 +9,7 @@ import type { WorkflowFlowNode } from './flowAdapters';* editor's nanostore-held instance.*/-export type WorkflowFlowInstance = ReactFlowInstance<WorkflowFlowNode, FlowEdge>;+export type WorkflowFlowInstance = ReactFlowInstance<WorkflowFlowNode, WorkflowFlowEdge>;let flowInstance: WorkflowFlowInstance | null = null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.test.tsnew file mode 100644index 0000000000..0ad8d6c1e1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.test.ts@@ -0,0 +1,24 @@+import type { FieldType } from '@workbench/workflows/types';++import { describe, expect, it } from 'vitest';++import { getHandleTypeTooltip } from './handleTooltip';++const fieldType = (overrides: Partial<FieldType> = {}): FieldType => ({+ batch: false,+ cardinality: 'SINGLE',+ name: 'ImageField',+ ...overrides,+});++describe('handleTooltip', () => {+ it('uses the resolved field type label for handle titles', () => {+ expect(getHandleTypeTooltip(fieldType())).toBe('Image');+ expect(getHandleTypeTooltip(fieldType({ cardinality: 'COLLECTION' }))).toBe('Image Collection');+ expect(getHandleTypeTooltip(fieldType({ batch: true }))).toBe('Image batch');+ });++ it('uses fallbacks for unresolved connector handles', () => {+ expect(getHandleTypeTooltip(null, 'Any input')).toBe('Any input');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.tsnew file mode 100644index 0000000000..2ca6114539--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/handleTooltip.ts@@ -0,0 +1,13 @@+import type { FieldType } from '@workbench/workflows/types';++import { getFieldTypeLabel } from '@workbench/workflows/fields';++export const getHandleTypeTooltip = (type: FieldType | null, fallback = 'Any'): string => {+ if (!type) {+ return fallback;+ }++ const label = getFieldTypeLabel(type);++ return type.batch ? `${label} batch` : label;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.tsindex 2aef7d7a7f..f570993dad 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts@@ -8,12 +8,14 @@ import { createExternalStore } from '@workbench/externalStore';*/export interface WorkflowSelectionSnapshot {+ hoveredNodeId: string | null;selectedNodeIds: string[];/** A pending outside request: the editor selects + zooms to these, then clears. */selectionRequest: { nodeIds: string[]; token: number } | null;}export const workflowSelectionStore = createExternalStore<WorkflowSelectionSnapshot>({+ hoveredNodeId: null,selectedNodeIds: [],selectionRequest: null,});@@ -26,6 +28,12 @@ export const reportNodeSelection = (selectedNodeIds: string[]): void => {}};+export const reportNodeHover = (hoveredNodeId: string | null): void => {+ if (workflowSelectionStore.getSnapshot().hoveredNodeId !== hoveredNodeId) {+ workflowSelectionStore.patchSnapshot({ hoveredNodeId });+ }+};+export const requestNodeSelection = (nodeIds: string[]): void => {const previousToken = workflowSelectionStore.getSnapshot().selectionRequest?.token ?? 0;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsxindex 89e8894011..20bd784707 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx@@ -17,11 +17,15 @@ import { useEffect, useState, type ChangeEvent } from 'react';*/export interface WorkflowFieldInputProps {+ id?: string;+ invalid?: boolean;template: FieldInputTemplate;value: unknown;onChange: (value: unknown) => void;}+const invalidProps = (invalid: boolean | undefined) => (invalid ? { 'aria-invalid': true } : {});+const toFiniteNumber = (raw: string): number | null => {if (raw.trim() === '') {return null;@@ -32,7 +36,7 @@ const toFiniteNumber = (raw: string): number | null => {return Number.isFinite(parsed) ? parsed : null;};-const StringInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {+const StringInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const text = typeof value === 'string' ? value : '';if (template.uiComponent === 'textarea') {@@ -41,10 +45,13 @@ const StringInput = ({ onChange, template, value }: WorkflowFieldInputProps) =>aria-label={template.title}className="nodrag nowheel"fontFamily="mono"+ id={id ? `${id}-textarea` : undefined}minH="4.5rem"resize="vertical"size="xs"value={text}+ w="full"+ {...invalidProps(invalid)}onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onChange(event.currentTarget.value)}/>);@@ -54,14 +61,17 @@ const StringInput = ({ onChange, template, value }: WorkflowFieldInputProps) =><Inputaria-label={template.title}className="nodrag"+ id={id ? `${id}-input` : undefined}size="xs"value={text}+ w="full"+ {...invalidProps(invalid)}onChange={(event: ChangeEvent<HTMLInputElement>) => onChange(event.currentTarget.value)}/>);};-const NumberInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {+const NumberInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const isInteger = template.type.name === 'IntegerField';const numericValue = typeof value === 'number' && Number.isFinite(value) ? value : '';const min = template.minimum ?? template.exclusiveMinimum ?? undefined;@@ -71,12 +81,15 @@ const NumberInput = ({ onChange, template, value }: WorkflowFieldInputProps) =><Inputaria-label={template.title}className="nodrag"+ id={id ? `${id}-number-input` : undefined}max={max !== undefined ? String(max) : undefined}min={min !== undefined ? String(min) : undefined}size="xs"step={template.multipleOf !== null ? String(template.multipleOf) : isInteger ? '1' : 'any'}type="number"value={numericValue}+ w="full"+ {...invalidProps(invalid)}onChange={(event: ChangeEvent<HTMLInputElement>) => {const parsed = toFiniteNumber(event.currentTarget.value);@@ -88,14 +101,19 @@ const NumberInput = ({ onChange, template, value }: WorkflowFieldInputProps) =>);};-const BooleanInput = ({ onChange, template, value }: WorkflowFieldInputProps) => (+const BooleanInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => (<Switch.Rootchecked={value === true}className="nodrag"+ invalid={invalid}size="sm"onCheckedChange={(event) => onChange(event.checked)}>- <Switch.HiddenInput aria-label={template.title} />+ <Switch.HiddenInput+ aria-label={template.title}+ id={id ? `${id}-switch-input` : undefined}+ {...invalidProps(invalid)}+ /><Switch.Control _checked={{ bg: 'accent.solid' }}><Switch.Thumb /></Switch.Control>@@ -103,19 +121,24 @@ const BooleanInput = ({ onChange, template, value }: WorkflowFieldInputProps) =>);const SelectInput = ({+ id,+ invalid,onChange,options,title,value,}: {+ id?: string;onChange: (value: string) => void;+ invalid?: boolean;options: { label: string; value: string }[];title: string;value: unknown;}) => (- <NativeSelect.Root className="nodrag" size="xs">+ <NativeSelect.Root className="nodrag" invalid={invalid} size="xs" w="full"><NativeSelect.Fieldaria-label={title}+ id={id ? `${id}-select` : undefined}value={typeof value === 'string' ? value : ''}onChange={(event: ChangeEvent<HTMLSelectElement>) => onChange(event.currentTarget.value)}>@@ -132,8 +155,10 @@ const SelectInput = ({</NativeSelect.Root>);-const EnumInput = ({ onChange, template, value }: WorkflowFieldInputProps) => (+const EnumInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => (<SelectInput+ id={id}+ invalid={invalid}options={(template.options ?? []).map((option) => ({label: template.uiChoiceLabels?.[option] ?? option,value: option,@@ -146,7 +171,7 @@ const EnumInput = ({ onChange, template, value }: WorkflowFieldInputProps) => (const DEFAULT_MODEL_TYPES: ModelTaxonomyType[] = ['main', 'vae', 'lora', 'controlnet', 't2i_adapter', 'ip_adapter'];-const ModelIdentifierInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {+const ModelIdentifierInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const selectedKey =typeof (value as { key?: unknown } | null)?.key === 'string' ? (value as { key: string }).key : null;const modelTypes = (template.uiModelType as ModelTaxonomyType[] | null) ?? DEFAULT_MODEL_TYPES;@@ -155,6 +180,8 @@ const ModelIdentifierInput = ({ onChange, template, value }: WorkflowFieldInputPreturn (<ModelSelectfilter={allowedBases ? (model: ModelConfig) => allowedBases.includes(model.base) : undefined}+ id={id ? `${id}-model-combobox` : undefined}+ invalid={invalid}modelTypes={modelTypes}size="xs"value={selectedKey}@@ -167,11 +194,18 @@ const ModelIdentifierInput = ({ onChange, template, value }: WorkflowFieldInputP);};-const SchedulerInput = ({ onChange, template, value }: WorkflowFieldInputProps) => (- <SelectInput options={SCHEDULER_OPTIONS} title={template.title} value={value} onChange={onChange} />+const SchedulerInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => (+ <SelectInput+ id={id}+ invalid={invalid}+ options={SCHEDULER_OPTIONS}+ title={template.title}+ value={value}+ onChange={onChange}+ />);-const BoardInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {+const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const [boards, setBoards] = useState<GalleryBoard[]>([]);useEffect(() => {@@ -201,6 +235,8 @@ const BoardInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {return (<SelectInput+ id={id}+ invalid={invalid}options={[{ label: 'Auto', value: 'auto' },{ label: 'None', value: 'none' },@@ -213,7 +249,7 @@ const BoardInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {);};-const ImageInput = ({ onChange, value }: WorkflowFieldInputProps) => {+const ImageInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {const gallerySelection = useActiveProjectSelector((project) => project.widgetStates.gallery.values.selectedImage as GeneratedImageContract | null | undefined);@@ -222,7 +258,14 @@ const ImageInput = ({ onChange, value }: WorkflowFieldInputProps) => {? (value as { image_name: string }).image_name: null;return (- <HStack gap="1.5" minW="0">+ <HStack+ boxShadow={invalid ? '0 0 0 1px {colors.red.solid}' : undefined}+ gap="1.5"+ minW="0"+ rounded="sm"+ w="full"+ {...(invalid ? { 'aria-invalid': true } : {})}+ >{imageName ? (<Text color="fg.muted" flex="1" fontSize="2xs" minW="0" title={imageName} truncate>{imageName}@@ -257,22 +300,25 @@ const ImageInput = ({ onChange, value }: WorkflowFieldInputProps) => {const COLOR_CHANNELS = ['r', 'g', 'b', 'a'] as const;-const ColorInput = ({ onChange, value }: WorkflowFieldInputProps) => {+const ColorInput = ({ id, invalid, onChange, value }: WorkflowFieldInputProps) => {const color = (typeof value === 'object' && value !== null ? value : {}) as Partial<Record<string, number>>;return (- <HStack gap="1">+ <HStack gap="1" w="full">{COLOR_CHANNELS.map((channel) => (<Inputkey={channel}aria-label={`Color ${channel.toUpperCase()}`}className="nodrag"+ id={id ? `${id}-color-${channel}-input` : undefined}max="255"min="0"placeholder={channel.toUpperCase()}size="xs"type="number"value={typeof color[channel] === 'number' ? color[channel] : ''}+ w="full"+ {...invalidProps(invalid)}onChange={(event: ChangeEvent<HTMLInputElement>) => {const parsed = toFiniteNumber(event.currentTarget.value);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsxindex 27a3228ff6..c21bb320a6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx@@ -7,10 +7,14 @@ import type {import { Box, HStack, Icon, Input, Menu, Portal, Separator, Stack, Text, Textarea } from '@chakra-ui/react';import { Button, IconButton } from '@workbench/components/ui/Button';-import { requestNodeSelection } from '@workbench/widgets/workflow/editor/selectionStore';+import { requestNodeSelection, workflowSelectionStore } from '@workbench/widgets/workflow/editor/selectionStore';import { FieldDescriptionPopover } from '@workbench/widgets/workflow/fields/FieldDescriptionPopover';import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { getResolvedWorkflowEdges } from '@workbench/workflows/connectors';import { getFormChildren } from '@workbench/workflows/document';+import { getWorkflowFieldInvalidReason } from '@workbench/workflows/fields';+import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { isInvocationNode } from '@workbench/workflows/types';import {Columns2Icon,CrosshairIcon,@@ -54,6 +58,9 @@ const BuilderCard = ({element,extraActions,index,+ isHovered,+ isInvalid,+ isSelected,parentId,title,}: {@@ -61,6 +68,9 @@ const BuilderCard = ({element: WorkflowFormElement;extraActions?: ReactNode;index: number;+ isHovered?: boolean;+ isInvalid?: boolean;+ isSelected?: boolean;parentId: string;title: string;}) => {@@ -135,7 +145,33 @@ const BuilderCard = ({{...(dropEdge === 'above' ? { top: '-1px' } : { bottom: '-1px' })}/>) : null}- <Box borderColor="border.subtle" borderWidth="1px" overflow="hidden" rounded="md">+ <Box+ borderColor={isInvalid ? 'red.solid' : isHovered || isSelected ? 'accent.solid' : 'border.subtle'}+ borderWidth="1px"+ overflow="hidden"+ position="relative"+ rounded="md"+ shadow={+ isInvalid+ ? '0 0 0 1px {colors.red.solid/45}'+ : isHovered || isSelected+ ? '0 0 0 1px {colors.accent.solid/45}'+ : undefined+ }+ transition="border-color 0.12s ease, box-shadow 0.12s ease"+ _before={+ isHovered+ ? {+ bg: 'accent.solid/10',+ content: '""',+ inset: '0',+ pointerEvents: 'none',+ position: 'absolute',+ zIndex: '1',+ }+ : undefined+ }+ ><HStackbg="bg.muted"borderBottomWidth="1px"@@ -144,6 +180,8 @@ const BuilderCard = ({gap="1"px="1.5"py="0.5"+ position="relative"+ zIndex="2"_active={{ cursor: 'grabbing' }}onPointerDown={() => setIsDragArmed(true)}onPointerUp={() => setIsDragArmed(false)}@@ -170,7 +208,9 @@ const BuilderCard = ({</IconButton></HStack></HStack>- <Box p="2">{children}</Box>+ <Box p="2" position="relative" zIndex="2">+ {children}+ </Box></Box></Box>);@@ -259,13 +299,19 @@ const FieldDescriptionAction = ({const BuilderElement = ({element,index,+ hoveredNodeId,parentId,projectGraph,+ invalidElementIds,+ selectedNodeIds,}: {element: WorkflowFormElement;index: number;+ hoveredNodeId: string | null;+ invalidElementIds: Set<string>;parentId: string;projectGraph: ProjectGraphState;+ selectedNodeIds: Set<string>;}) => {const dispatch = useWorkbenchDispatch();@@ -301,9 +347,12 @@ const BuilderElement = ({<BuilderElementkey={child.id}element={child}+ hoveredNodeId={hoveredNodeId}+ invalidElementIds={invalidElementIds}index={childIndex}parentId={element.id}projectGraph={projectGraph}+ selectedNodeIds={selectedNodeIds}/>))}<ContainerDropZone container={element} isEmpty={element.data.children.length === 0} />@@ -352,6 +401,9 @@ const BuilderElement = ({</>}index={index}+ isHovered={element.data.fieldIdentifier.nodeId === hoveredNodeId}+ isInvalid={invalidElementIds.has(element.id)}+ isSelected={selectedNodeIds.has(element.data.fieldIdentifier.nodeId)}parentId={parentId}title="Node Field">@@ -456,12 +508,65 @@ const AddElementMenu = () => {);};+const getInvalidNodeFieldElementIds = (+ projectGraph: ProjectGraphState,+ templatesSnapshot: ReturnType<typeof useInvocationTemplatesSnapshot>+): Set<string> => {+ const invalidElementIds = new Set<string>();++ if (templatesSnapshot.status !== 'loaded') {+ return invalidElementIds;+ }++ const connectedInputKeys = new Set(+ getResolvedWorkflowEdges(projectGraph.nodes, projectGraph.edges).map(+ (edge) => `${edge.target}:${edge.targetHandle}`+ )+ );++ for (const element of Object.values(projectGraph.form.elements)) {+ if (element.type !== 'node-field') {+ continue;+ }++ const { fieldName, nodeId } = element.data.fieldIdentifier;+ const node = projectGraph.nodes.find((candidate) => candidate.id === nodeId);++ if (!node || !isInvocationNode(node)) {+ invalidElementIds.add(element.id);+ continue;+ }++ const template = templatesSnapshot.templates[node.data.type]?.inputs[fieldName];++ if (!template) {+ invalidElementIds.add(element.id);+ continue;+ }++ const isConnected = connectedInputKeys.has(`${nodeId}:${fieldName}`);++ if (getWorkflowFieldInvalidReason({ isConnected, template, value: node.data.inputs[fieldName]?.value }) !== null) {+ invalidElementIds.add(element.id);+ }+ }++ return invalidElementIds;+};+export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const { hoveredNodeId, selectedNodeIds } = workflowSelectionStore.useSnapshot();const [draggingElementId, setDraggingElementId] = useState<string | null>(null);const dndContextValue = useMemo<BuilderDndContextValue>(() => ({ draggingElementId, setDraggingElementId }),[draggingElementId]);+ const selectedNodeIdSet = useMemo(() => new Set(selectedNodeIds), [selectedNodeIds]);+ const invalidElementIds = useMemo(+ () => getInvalidNodeFieldElementIds(projectGraph, templatesSnapshot),+ [projectGraph, templatesSnapshot]+ );const rootChildren = getFormChildren(projectGraph.form);return (@@ -477,9 +582,12 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta<BuilderElementkey={element.id}element={element}+ hoveredNodeId={hoveredNodeId}+ invalidElementIds={invalidElementIds}index={index}parentId={projectGraph.form.rootElementId}projectGraph={projectGraph}+ selectedNodeIds={selectedNodeIdSet}/>))}<AddElementMenu />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsxindex fa1494005c..751b70783e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx@@ -1,13 +1,14 @@import type { NodeFieldFormElement, ProjectGraphState } from '@workbench/workflows/types';-import { HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';+import { Alert, Field, Input, Stack, Text } from '@chakra-ui/react';import { FieldLabel } from '@workbench/components/ui/Field';import { Tooltip } from '@workbench/components/ui/Tooltip';import { WorkflowFieldInput } from '@workbench/widgets/workflow/fields/WorkflowFieldInput';import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { getResolvedWorkflowEdges } from '@workbench/workflows/connectors';+import { getWorkflowFieldInvalidReason } from '@workbench/workflows/fields';import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';import { isInvocationNode } from '@workbench/workflows/types';-import { TriangleAlertIcon } from 'lucide-react';import { useState, type ChangeEvent } from 'react';/**@@ -52,71 +53,82 @@ export const NodeFieldControl = ({if (!invocationNode || !template) {return (- <HStack gap="1.5">- <Icon as={TriangleAlertIcon} boxSize="3" color="fg.error" />- <Text color="fg.subtle" fontSize="2xs">- This field no longer exists in the project graph.- </Text>- </HStack>+ <Alert.Root status="error" size="sm" variant="surface">+ <Alert.Indicator />+ <Alert.Title>This field no longer exists in the project graph.</Alert.Title>+ </Alert.Root>);}- const isConnected = projectGraph.edges.some((edge) => edge.target === nodeId && edge.targetHandle === fieldName);+ const isConnected = getResolvedWorkflowEdges(projectGraph.nodes, projectGraph.edges).some(+ (edge) => edge.target === nodeId && edge.targetHandle === fieldName+ );const label = instance?.label || template.title;const description = instance?.description || template.description;+ const invalidReason = getWorkflowFieldInvalidReason({ isConnected, template, value: instance?.value });+ const isInvalid = invalidReason !== null;+ const labelInputId = `${element.id}-label-input`;+ const valueInputId = `${element.id}-value`;return (- <Stack gap="1">- {isLabelEditable ? (- <Input- aria-label="Field label"- color="fg.muted"- fontSize="2xs"- fontWeight="600"- h="5"- placeholder={template.title}- size="2xs"- textTransform="uppercase"- value={draftLabel ?? label}- variant="flushed"- onBlur={() => setDraftLabel(null)}- onChange={(event: ChangeEvent<HTMLInputElement>) => {- setDraftLabel(event.currentTarget.value);- dispatch({- action: { fieldName, label: event.currentTarget.value, nodeId, type: 'setFieldLabel' },- type: 'applyProjectGraphAction',- });- }}- onFocus={() => setDraftLabel(label)}- />- ) : (- <Tooltip content={`${nodeContext} → ${template.title}`}>- <Stack gap="0" w="fit-content">- <FieldLabel>{label}</FieldLabel>- </Stack>- </Tooltip>- )}- {element.data.showDescription && description ? (- <Text color="fg.subtle" fontSize="2xs">- {description}- </Text>- ) : null}- {isConnected ? (- <Text color="fg.subtle" fontSize="2xs">- Driven by a graph connection.- </Text>- ) : (- <WorkflowFieldInput- template={template}- value={instance?.value}- onChange={(value) =>- dispatch({- action: { fieldName, nodeId, type: 'setFieldValue', value },- type: 'applyProjectGraphAction',- })- }- />- )}- </Stack>+ <Field.Root invalid={isInvalid} minW="0" w="full">+ <Stack gap="1" minW="0" w="full">+ {isLabelEditable ? (+ <Input+ aria-label="Field label"+ color={isInvalid ? 'fg.error' : 'fg.muted'}+ fontSize="2xs"+ fontWeight="600"+ h="5"+ id={labelInputId}+ placeholder={template.title}+ size="2xs"+ textTransform="uppercase"+ value={draftLabel ?? label}+ variant="flushed"+ w="full"+ onBlur={() => setDraftLabel(null)}+ onChange={(event: ChangeEvent<HTMLInputElement>) => {+ setDraftLabel(event.currentTarget.value);+ dispatch({+ action: { fieldName, label: event.currentTarget.value, nodeId, type: 'setFieldLabel' },+ type: 'applyProjectGraphAction',+ });+ }}+ onFocus={() => setDraftLabel(label)}+ />+ ) : (+ <Tooltip content={`${nodeContext} → ${template.title}`}>+ <Stack color={isInvalid ? 'fg.error' : undefined} gap="0" minW="0" w="full">+ <FieldLabel>{label}</FieldLabel>+ </Stack>+ </Tooltip>+ )}+ {element.data.showDescription && description ? (+ <Text color="fg.subtle" fontSize="2xs">+ {description}+ </Text>+ ) : null}+ {isConnected ? (+ <Text color="fg.subtle" fontSize="2xs">+ Driven by a graph connection.+ </Text>+ ) : (+ <WorkflowFieldInput+ id={valueInputId}+ invalid={isInvalid}+ template={template}+ value={instance?.value}+ onChange={(value) =>+ dispatch({+ action: { fieldName, nodeId, type: 'setFieldValue', value },+ type: 'applyProjectGraphAction',+ })+ }+ />+ )}+ {invalidReason ? <Field.ErrorText fontSize="2xs">{invalidReason}</Field.ErrorText> : null}+ </Stack>+ </Field.Root>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.tsindex d42c24282a..4a11ca35ca 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts@@ -2,11 +2,19 @@ import type { FieldType, XYPosition } from '@workbench/workflows/types';import { createExternalStore } from '@workbench/externalStore';-export interface AddNodeConnectionFilter {- sourceHandle: string;- sourceNodeId: string;- sourceType: FieldType;-}+export type AddNodeConnectionFilter =+ | {+ kind: 'source';+ sourceHandle: string;+ sourceNodeId: string;+ sourceType: FieldType | null;+ }+ | {+ kind: 'target';+ targetHandle: string;+ targetNodeId: string;+ targetType: FieldType | null;+ };/*** Session-lived UI coordination for the workflow widget. Menu items livediff --git a/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts b/invokeai/frontend/webv2/src/workbench/workflows/connectors.tsindex d65da73942..e2ade4696a 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts@@ -11,6 +11,12 @@ export interface ResolvedConnectorSource {type: FieldType | null;}+export interface ResolvedConnectorTarget {+ fieldName: string;+ nodeId: string;+ type: FieldType | null;+}+export interface ResolvedWorkflowEdge extends WorkflowEdge {source: string;sourceHandle: string;@@ -71,6 +77,59 @@ export const resolveConnectorSource = (return resolve(connectorId);};+export const resolveConnectorTarget = (+ connectorId: string,+ nodes: WorkflowNode[],+ edges: WorkflowEdge[],+ templates?: InvocationTemplates+): ResolvedConnectorTarget | null => {+ return resolveConnectorTargets(connectorId, nodes, edges, templates)[0] ?? null;+};++export const resolveConnectorTargets = (+ connectorId: string,+ nodes: WorkflowNode[],+ edges: WorkflowEdge[],+ templates?: InvocationTemplates+): ResolvedConnectorTarget[] => {+ const visited = new Set<string>();++ const resolve = (nodeId: string): ResolvedConnectorTarget[] => {+ if (visited.has(nodeId)) {+ return [];+ }++ visited.add(nodeId);++ const targets: ResolvedConnectorTarget[] = [];++ for (const outboundEdge of getConnectorOutputEdges(nodeId, edges)) {+ const targetNode = nodes.find((node) => node.id === outboundEdge.target);++ if (!targetNode) {+ continue;+ }++ if (isInvocationNode(targetNode)) {+ targets.push({+ fieldName: outboundEdge.targetHandle,+ nodeId: targetNode.id,+ type: templates?.[targetNode.data.type]?.inputs[outboundEdge.targetHandle]?.type ?? null,+ });+ continue;+ }++ if (isConnectorNode(targetNode) && outboundEdge.targetHandle === CONNECTOR_INPUT_HANDLE) {+ targets.push(...resolve(targetNode.id));+ }+ }++ return targets;+ };++ return resolve(connectorId);+};+export const resolveWorkflowEdgeSource = (edge: WorkflowEdge,nodes: WorkflowNode[],diff --git a/invokeai/frontend/webv2/src/workbench/workflows/fields.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/fields.test.tsnew file mode 100644index 0000000000..2c4f414879--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/fields.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest';++import type { FieldInputTemplate, FieldType } from './types';++import { getWorkflowFieldInvalidReason, isModelFieldType, isWorkflowFieldValueValid } from './fields';++const single = (name: string): FieldType => ({ batch: false, cardinality: 'SINGLE', name });++const input = (overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name: 'value',+ options: null,+ required: true,+ title: 'Value',+ type: single('StringField'),+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ ...overrides,+});++describe('workflow field validation', () => {+ it('flags empty required direct values and ignores optional fields', () => {+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: input(), value: '' })).toBe('Required value.');+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: input({ required: false }), value: '' })).toBe(+ null+ );+ });++ it('treats connected required fields as valid', () => {+ expect(+ getWorkflowFieldInvalidReason({ isConnected: true, template: input({ input: 'connection' }), value: '' })+ ).toBe(null);+ });++ it('flags missing required connections', () => {+ expect(+ getWorkflowFieldInvalidReason({ isConnected: false, template: input({ input: 'connection' }), value: undefined })+ ).toBe('Required connection.');+ expect(+ getWorkflowFieldInvalidReason({ isConnected: false, template: input({ input: 'connection' }), value: 'value' })+ ).toBe('Required connection.');+ });++ it('accepts persisted values for unsupported direct controls', () => {+ const template = input({ type: single('AnyField') });++ expect(getWorkflowFieldInvalidReason({ isConnected: false, template, value: { value: true } })).toBe(null);+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template, value: undefined })).toBe(+ 'Required connection.'+ );+ });++ it('validates numeric constraints', () => {+ const template = input({ maximum: 10, minimum: 1, type: single('IntegerField') });++ expect(isWorkflowFieldValueValid(template, 5)).toBe(true);+ expect(isWorkflowFieldValueValid(template, 0)).toBe(false);+ expect(isWorkflowFieldValueValid(template, 5.5)).toBe(false);+ });++ it('validates object-backed model and image fields', () => {+ expect(isWorkflowFieldValueValid(input({ type: single('ModelIdentifierField') }), { key: 'model-key' })).toBe(true);+ expect(isWorkflowFieldValueValid(input({ type: single('ModelIdentifierField') }), {})).toBe(false);+ expect(isWorkflowFieldValueValid(input({ type: single('ImageField') }), { image_name: 'image.png' })).toBe(true);+ expect(isWorkflowFieldValueValid(input({ type: single('ImageField') }), { image_name: '' })).toBe(false);+ });++ it('treats empty board values as the Auto sentinel', () => {+ expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), undefined)).toBe(true);+ expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), { board_id: 'board-id' })).toBe(true);+ expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), {})).toBe(false);+ });+});++describe('workflow field type helpers', () => {+ it('matches legacy model field shape classification', () => {+ expect(isModelFieldType(single('ModelIdentifierField'))).toBe(true);+ expect(isModelFieldType(single('UNetField'))).toBe(true);+ expect(isModelFieldType(single('CLIPField'))).toBe(true);+ expect(isModelFieldType(single('ImageField'))).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/fields.ts b/invokeai/frontend/webv2/src/workbench/workflows/fields.tsindex 9c6cde4293..b0c95d4588 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/fields.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/fields.ts@@ -22,6 +22,18 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set([export const isStatefulFieldType = (type: FieldType): boolean => STATEFUL_FIELD_TYPE_NAMES.has(type.name);+const MODEL_FIELD_TYPE_NAMES = new Set([+ 'CLIPField',+ 'ControlLoRAField',+ 'ModelIdentifierField',+ 'T5EncoderField',+ 'TransformerField',+ 'UNetField',+ 'VAEField',+]);++export const isModelFieldType = (type: FieldType): boolean => MODEL_FIELD_TYPE_NAMES.has(type.name);+/** True when the field renders an editable control on the node / linear form. */export const isDirectInputField = (template: FieldInputTemplate): boolean =>template.input !== 'connection' && isStatefulFieldType(template.type) && template.type.cardinality !== 'COLLECTION';@@ -29,6 +41,117 @@ export const isDirectInputField = (template: FieldInputTemplate): boolean =>/** A field can be exposed to the Linear UI when it can be edited directly. */export const isExposableField = (template: FieldInputTemplate): boolean => isDirectInputField(template);+const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0;++const hasNonEmptyStringProp = (value: unknown, prop: string): boolean =>+ typeof value === 'object' && value !== null && isNonEmptyString((value as Record<string, unknown>)[prop]);++const isNumberFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {+ if (typeof value !== 'number' || !Number.isFinite(value)) {+ return false;+ }++ if (template.type.name === 'IntegerField' && !Number.isInteger(value)) {+ return false;+ }++ if (template.minimum !== null && value < template.minimum) {+ return false;+ }++ if (template.maximum !== null && value > template.maximum) {+ return false;+ }++ if (template.exclusiveMinimum !== null && value <= template.exclusiveMinimum) {+ return false;+ }++ if (template.exclusiveMaximum !== null && value >= template.exclusiveMaximum) {+ return false;+ }++ if (template.multipleOf !== null) {+ const quotient = value / template.multipleOf;++ if (Math.abs(quotient - Math.round(quotient)) > Number.EPSILON * 100) {+ return false;+ }+ }++ return true;+};++const isColorValueValid = (value: unknown): boolean => {+ if (typeof value !== 'object' || value === null) {+ return false;+ }++ const channels = value as Record<string, unknown>;++ return ['r', 'g', 'b', 'a'].every((channel) => {+ const channelValue = channels[channel];++ return typeof channelValue === 'number' && channelValue >= 0 && channelValue <= 255;+ });+};++export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {+ switch (template.type.name) {+ case 'StringField':+ return isNonEmptyString(value);+ case 'IntegerField':+ case 'FloatField':+ return isNumberFieldValueValid(template, value);+ case 'BooleanField':+ return typeof value === 'boolean';+ case 'EnumField':+ return isNonEmptyString(value) && (template.options === null || template.options.includes(value));+ case 'ModelIdentifierField':+ return hasNonEmptyStringProp(value, 'key');+ case 'SchedulerField':+ return isNonEmptyString(value);+ case 'BoardField':+ return (+ value === undefined ||+ value === null ||+ value === 'auto' ||+ value === 'none' ||+ hasNonEmptyStringProp(value, 'board_id')+ );+ case 'ImageField':+ return hasNonEmptyStringProp(value, 'image_name');+ case 'ColorField':+ return isColorValueValid(value);+ default:+ return value !== undefined && value !== null;+ }+};++export const getWorkflowFieldInvalidReason = ({+ isConnected,+ template,+ value,+}: {+ isConnected: boolean;+ template: FieldInputTemplate;+ value: unknown;+}): string | null => {+ if (!template.required || isConnected) {+ return null;+ }++ if (template.input === 'connection') {+ return 'Required connection.';+ }++ if (isWorkflowFieldValueValid(template, value)) {+ return null;+ }++ return isDirectInputField(template) ? 'Required value.' : 'Required connection.';+};+// Raw hex (not Chakra tokens) because xyflow handles are styled inline.const FIELD_TYPE_COLORS: Record<string, string> = {AnyField: '#9ca3af',diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/validation.test.tsindex 67e3d7658e..912ddcda68 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts@@ -11,6 +11,9 @@ import type {import {getCompatibleInputTemplate,+ getCompatibleOutputTemplate,+ getWorkflowSourceFieldType,+ getWorkflowTargetFieldType,hasAnyCycle,validateConnection,validateConnectionTypes,@@ -197,6 +200,148 @@ describe('getCompatibleInputTemplate', () => {expect(getCompatibleInputTemplate(template, single('IntegerField'))?.name).toBe('early');expect(getCompatibleInputTemplate(template, single('ImageField'))).toBeNull();+ expect(getCompatibleInputTemplate(template, null)?.name).toBe('early');+ });+});++describe('getWorkflowSourceFieldType', () => {+ it('resolves typed and untyped connector outputs', () => {+ const document: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [],+ nodes: [makeConnector('connector')],+ };++ expect(getWorkflowSourceFieldType(document, templates, 'connector', 'out')).toBeNull();++ const upstreamDocument: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [+ {+ id: 'e1',+ source: 'n1',+ sourceHandle: 'value',+ target: 'connector',+ targetHandle: 'in',+ type: 'default',+ },+ ],+ nodes: [makeNode('n1', 'number'), makeConnector('connector')],+ };++ expect(getWorkflowSourceFieldType(upstreamDocument, templates, 'connector', 'out')).toEqual(single('IntegerField'));+ });++ it('resolves connector outputs from downstream targets when no input is connected', () => {+ const document: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [+ {+ id: 'connector-out',+ source: 'connector',+ sourceHandle: 'out',+ target: 'n1',+ targetHandle: 'value',+ type: 'default',+ },+ ],+ nodes: [makeConnector('connector'), makeNode('n1', 'number')],+ };++ expect(getWorkflowSourceFieldType(document, templates, 'connector', 'out')).toEqual(single('IntegerField'));+ });++ it('leaves fan-out connector outputs untyped when downstream targets disagree', () => {+ const mixedTemplates: InvocationTemplates = {+ ...templates,+ text: {+ ...templates.number,+ inputs: {+ value: { ...templates.number.inputs.value, type: single('StringField') },+ },+ outputs: {+ value: { ...templates.number.outputs.value, type: single('StringField') },+ },+ type: 'text',+ },+ };+ const document: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [+ {+ id: 'connector-out-string',+ source: 'connector',+ sourceHandle: 'out',+ target: 'text-1',+ targetHandle: 'value',+ type: 'default',+ },+ {+ id: 'connector-out-number',+ source: 'connector',+ sourceHandle: 'out',+ target: 'number-1',+ targetHandle: 'value',+ type: 'default',+ },+ ],+ nodes: [makeConnector('connector'), makeNode('text-1', 'text'), makeNode('number-1', 'number')],+ };++ expect(getWorkflowSourceFieldType(document, mixedTemplates, 'connector', 'out')).toBeNull();+ });+});++describe('getCompatibleOutputTemplate', () => {+ it('returns the first output compatible with the target type', () => {+ expect(getCompatibleOutputTemplate(templates.number, single('IntegerField'))?.name).toBe('value');+ expect(getCompatibleOutputTemplate(templates.number, single('ImageField'))).toBeNull();+ });++ it('accepts any output for untyped connector targets', () => {+ expect(getCompatibleOutputTemplate(templates.number, null)?.name).toBe('value');+ expect(getCompatibleOutputTemplate(templates.collect, null)).toBeNull();+ });+});++describe('getWorkflowTargetFieldType', () => {+ it('resolves connectable invocation inputs and connector inputs', () => {+ const document: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [],+ nodes: [makeNode('n1', 'number'), makeConnector('connector')],+ };++ expect(getWorkflowTargetFieldType(document, templates, 'n1', 'value')).toEqual(single('IntegerField'));+ expect(getWorkflowTargetFieldType(document, templates, 'connector', 'in')).toBeNull();+ });++ it('rejects direct-only inputs', () => {+ const directTemplates: InvocationTemplates = {+ number: {+ ...templates.number,+ inputs: {+ value: { ...templates.number.inputs.value, input: 'direct' },+ },+ },+ };++ expect(+ getWorkflowTargetFieldType({ edges: [], nodes: [makeNode('n1', 'number')] }, directTemplates, 'n1', 'value')+ ).toBe(undefined);+ });++ it('resolves connector inputs from downstream targets', () => {+ const document: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [+ {+ id: 'connector-out',+ source: 'connector',+ sourceHandle: 'out',+ target: 'n1',+ targetHandle: 'value',+ type: 'default',+ },+ ],+ nodes: [makeConnector('connector'), makeNode('n1', 'number')],+ };++ expect(getWorkflowTargetFieldType(document, templates, 'connector', 'in')).toEqual(single('IntegerField'));});});@@ -336,4 +481,91 @@ describe('validateConnection', () => {)).toMatch(/already has an input/);});++ it('rejects connector input sources incompatible with an existing downstream target', () => {+ const stringTemplates: InvocationTemplates = {+ ...templates,+ text: {+ ...templates.number,+ inputs: {+ value: { ...templates.number.inputs.value, type: single('StringField') },+ },+ outputs: {+ value: { ...templates.number.outputs.value, type: single('StringField') },+ },+ type: 'text',+ },+ };+ const connectorDocument: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [+ {+ id: 'connector-out',+ source: 'connector-1',+ sourceHandle: 'out',+ target: 'n1',+ targetHandle: 'value',+ type: 'default',+ },+ ],+ nodes: [makeNode('n1', 'number'), makeNode('text-1', 'text'), makeConnector('connector-1')],+ };++ expect(+ validateConnection(+ { sourceHandle: 'value', sourceNodeId: 'text-1', targetHandle: 'in', targetNodeId: 'connector-1' },+ connectorDocument,+ stringTemplates+ )+ ).toMatch(/StringField cannot connect to IntegerField/);+ });++ it('rejects connector input sources incompatible with any downstream fan-out target', () => {+ const stringTemplates: InvocationTemplates = {+ ...templates,+ text: {+ ...templates.number,+ inputs: {+ value: { ...templates.number.inputs.value, type: single('StringField') },+ },+ outputs: {+ value: { ...templates.number.outputs.value, type: single('StringField') },+ },+ type: 'text',+ },+ };+ const connectorDocument: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [+ {+ id: 'connector-out-string',+ source: 'connector-1',+ sourceHandle: 'out',+ target: 'text-target',+ targetHandle: 'value',+ type: 'default',+ },+ {+ id: 'connector-out-number',+ source: 'connector-1',+ sourceHandle: 'out',+ target: 'number-target',+ targetHandle: 'value',+ type: 'default',+ },+ ],+ nodes: [+ makeNode('number-target', 'number'),+ makeNode('text-source', 'text'),+ makeNode('text-target', 'text'),+ makeConnector('connector-1'),+ ],+ };++ expect(+ validateConnection(+ { sourceHandle: 'value', sourceNodeId: 'text-source', targetHandle: 'in', targetNodeId: 'connector-1' },+ connectorDocument,+ stringTemplates+ )+ ).toMatch(/StringField cannot connect to IntegerField/);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts b/invokeai/frontend/webv2/src/workbench/workflows/validation.tsindex 73d9d945a5..7f596ecf25 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/validation.ts@@ -1,5 +1,6 @@import type {FieldInputTemplate,+ FieldOutputTemplate,FieldType,InvocationTemplate,InvocationTemplates,@@ -8,7 +9,12 @@ import type {WorkflowNode,} from './types';-import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE, resolveConnectorSource } from './connectors';+import {+ CONNECTOR_INPUT_HANDLE,+ CONNECTOR_OUTPUT_HANDLE,+ resolveConnectorSource,+ resolveConnectorTargets,+} from './connectors';import { isConnectorNode, isInvocationNode } from './types';/**@@ -158,7 +164,7 @@ const allowsMultipleInboundEdges = (node: WorkflowNode, fieldName: string): boolexport const getCompatibleInputTemplate = (template: InvocationTemplate,- sourceType: FieldType+ sourceType: FieldType | null): FieldInputTemplate | null => {const inputTemplates = Object.values(template.inputs).sort((a, b) => (a.uiOrder ?? Number.MAX_SAFE_INTEGER) - (b.uiOrder ?? Number.MAX_SAFE_INTEGER)@@ -169,11 +175,43 @@ export const getCompatibleInputTemplate = ((inputTemplate) =>!inputTemplate.uiHidden &&inputTemplate.input !== 'direct' &&- validateConnectionTypes(sourceType, inputTemplate.type)+ (sourceType === null || validateConnectionTypes(sourceType, inputTemplate.type))) ?? null);};+export const getCompatibleOutputTemplate = (+ template: InvocationTemplate,+ targetType: FieldType | null+): FieldOutputTemplate | null => {+ return (+ Object.values(template.outputs).find(+ (outputTemplate) => targetType === null || validateConnectionTypes(outputTemplate.type, targetType)+ ) ?? null+ );+};++const isSameFieldType = (left: FieldType, right: FieldType): boolean =>+ left.name === right.name && left.cardinality === right.cardinality && left.batch === right.batch;++const getCommonConnectorTargetType = (+ connectorId: string,+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,+ templates: InvocationTemplates+): FieldType | null => {+ const targets = resolveConnectorTargets(connectorId, document.nodes, document.edges, templates);++ if (targets.length === 0 || targets.some((target) => target.type === null)) {+ return null;+ }++ const firstType = targets[0]?.type;++ return firstType && targets.every((target) => target.type !== null && isSameFieldType(firstType, target.type))+ ? firstType+ : null;+};+const getSourceFieldType = (node: WorkflowNode,handle: string,@@ -185,7 +223,9 @@ const getSourceFieldType = (}if (isConnectorNode(node) && handle === CONNECTOR_OUTPUT_HANDLE) {- return resolveConnectorSource(node.id, document.nodes, document.edges, templates)?.type ?? null;+ const source = resolveConnectorSource(node.id, document.nodes, document.edges, templates);++ return source ? source.type : getCommonConnectorTargetType(node.id, document, templates);}return undefined;@@ -202,6 +242,42 @@ export const getWorkflowSourceFieldType = (return sourceNode ? getSourceFieldType(sourceNode, sourceHandle, document, templates) : undefined;};+const getTargetFieldType = (+ node: WorkflowNode,+ handle: string,+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,+ templates: InvocationTemplates+): FieldType | null | undefined => {+ if (isInvocationNode(node)) {+ const inputTemplate = templates[node.data.type]?.inputs[handle];++ return inputTemplate && inputTemplate.input !== 'direct' ? inputTemplate.type : undefined;+ }++ if (isConnectorNode(node) && handle === CONNECTOR_INPUT_HANDLE) {+ const targetType = getCommonConnectorTargetType(node.id, document, templates);++ if (targetType) {+ return targetType;+ }++ return resolveConnectorSource(node.id, document.nodes, document.edges, templates)?.type ?? null;+ }++ return undefined;+};++export const getWorkflowTargetFieldType = (+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,+ templates: InvocationTemplates,+ targetNodeId: string,+ targetHandle: string+): FieldType | null | undefined => {+ const targetNode = document.nodes.find((node) => node.id === targetNodeId);++ return targetNode ? getTargetFieldType(targetNode, targetHandle, document, templates) : undefined;+};+const hasValidSourceHandle = (node: WorkflowNode, handle: string, templates: InvocationTemplates): boolean => {if (isInvocationNode(node)) {return templates[node.data.type]?.outputs[handle] !== undefined;@@ -242,6 +318,17 @@ export const validateConnection = (return 'Connector already has an input.';}+ const sourceFieldType = getSourceFieldType(sourceNode, sourceHandle, document, templates);+ const targetFieldTypes = resolveConnectorTargets(targetNodeId, document.nodes, document.edges, templates)+ .map((target) => target.type)+ .filter((type): type is FieldType => type !== null);++ for (const targetFieldType of targetFieldTypes) {+ if (sourceFieldType && !validateConnectionTypes(sourceFieldType, targetFieldType)) {+ return `${sourceFieldType.name} cannot connect to ${targetFieldType.name}.`;+ }+ }+if (wouldCreateCycle(sourceNodeId, targetNodeId, document.edges)) {return 'This connection would create a cycle.';}