Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): improve workflow validation and editor controls
joshistoastce83d78167ed
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsxindex 71f6cb72f9..5e399d1856 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx@@ -2,15 +2,18 @@ import type {FieldInputTemplate,FieldOutputTemplate,FieldType,+ InvocationTemplate,WorkflowInvocationNode,} from '@workbench/workflows/types';-import { Badge, Box, Field, Flex, HStack, Icon, Image, Input, Stack, Text, IconButton } from '@chakra-ui/react';+import { Box, Checkbox, Field, Flex, HStack, Icon, IconButton, Image, Input, Stack, Text } from '@chakra-ui/react';+import { useAuthSession } from '@workbench/auth/session';import { useNodeExecutionState, type NodeExecutionState } from '@workbench/backend/nodeExecutionStore';import { Tooltip } from '@workbench/components/ui';import { FieldDescriptionPopover } from '@workbench/widgets/workflow/fields/FieldDescriptionPopover';import { WorkflowFieldInput } from '@workbench/widgets/workflow/fields/WorkflowFieldInput';import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { isExecutableInvocationType } from '@workbench/workflows/buildGraph';import {getFieldTypeColor,getFieldTypeLabel,@@ -21,7 +24,7 @@ import {} from '@workbench/workflows/fields';import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';-import { ChevronDownIcon, ChevronRightIcon, PinIcon, PinOffIcon, TriangleAlertIcon } from 'lucide-react';+import { ChevronDownIcon, ChevronRightIcon, InfoIcon, PinIcon, PinOffIcon, TriangleAlertIcon } from 'lucide-react';import { memo, useState, type ChangeEvent, type KeyboardEvent } from 'react';import type { InvocationFlowNode as InvocationFlowNodeType } from './flowAdapters';@@ -225,6 +228,105 @@ const OutputFieldTooltip = ({ template }: { template: FieldOutputTemplate }) =></Stack>);+const hasImageOutput = (template: InvocationTemplate): boolean =>+ template.type !== 'image' && Object.values(template.outputs).some((output) => output.type.name === 'ImageField');++const NodeInfoTooltipContent = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate }) => {+ const title = node.data.label ? `${node.data.label} (${template.title})` : template.title;+ const nodePack = node.data.nodePack || template.nodePack;++ return (+ <Stack gap="1" maxW="20rem">+ <Text fontWeight="700">{title}</Text>+ <Text color="fg.subtle">Type: {template.type}</Text>+ <Text color="fg.subtle">Node pack: {nodePack}</Text>+ <Text color="fg.subtle">Version: {node.data.version}</Text>+ <Text color="fg.subtle">Classification: {template.classification}</Text>+ <Text color="fg.subtle">Category: {template.category}</Text>+ {template.description ? <Text fontStyle="italic">{template.description}</Text> : null}+ {node.data.notes ? <Text>{node.data.notes}</Text> : null}+ </Stack>+ );+};++const NodeInfoButton = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate }) => (+ <Tooltip+ content={<NodeInfoTooltipContent node={node} template={template} />}+ positioning={{ placement: 'top-end' }}+ showArrow+ >+ <IconButton+ aria-label={`Show details for ${node.data.label || template.title}`}+ className="nodrag"+ size="2xs"+ variant="ghost"+ >+ <Icon as={InfoIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+);++const NodeFooter = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate }) => {+ const dispatch = useWorkbenchDispatch();+ const session = useAuthSession();+ const canUseCache = !session.multiuserEnabled || session.user?.is_admin === true;++ if (!isExecutableInvocationType(template.type) || !hasImageOutput(template)) {+ return null;+ }++ return (+ <Flex+ align="center"+ bg="bg.subtle"+ borderBottomRadius="lg"+ borderColor="border.subtle"+ borderTopWidth="1px"+ className="nodrag"+ gap="3"+ justify="space-between"+ minH="8"+ px="2.5"+ py="1"+ >+ <HStack gap="4">+ {canUseCache ? (+ <Checkbox.Root+ checked={node.data.useCache}+ colorPalette="accent"+ size="xs"+ onCheckedChange={(event) =>+ dispatch({+ action: { nodeId: node.id, type: 'setNodeUseCache', useCache: event.checked === true },+ type: 'applyProjectGraphAction',+ })+ }+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ <Checkbox.Label fontSize="2xs">Use Cache</Checkbox.Label>+ </Checkbox.Root>+ ) : null}+ <Checkbox.Root+ checked={!node.data.isIntermediate}+ colorPalette="accent"+ size="xs"+ onCheckedChange={(event) =>+ dispatch({+ action: { isIntermediate: event.checked !== true, nodeId: node.id, type: 'setNodeIsIntermediate' },+ type: 'applyProjectGraphAction',+ })+ }+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ <Checkbox.Label fontSize="2xs">Save to Gallery</Checkbox.Label>+ </Checkbox.Root>+ </HStack>+ </Flex>+ );+};+const InputFieldRow = ({isConnected,isExposed,@@ -279,7 +381,7 @@ const InputFieldRow = ({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>+ <Tooltip content={handleTooltip} positioning={{ placement: 'right-end' }} showArrow><Handleid={template.name}position={Position.Left}@@ -468,6 +570,8 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFloconst isOpen = node.data.isOpen;const isRunning = execution?.status === 'running';const isMissingRequiredInput = hasMissingRequiredInputs(node, Object.values(template.inputs), connectedFieldNames);+ const withFooter = !isZoomedOut && isExecutableInvocationType(template.type) && hasImageOutput(template);+ const withOutputPreview = Boolean(execution?.outputImageUrl);return (<NodeShell hasMissingRequiredInput={isMissingRequiredInput} isRunning={isRunning} selected={selected ?? false}>@@ -505,17 +609,13 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlo<><NodeTitle node={node} /><Box flex="1" />- <Tooltip content={template.description || template.type}>- <Badge size="xs" fontFamily="mono">- {template.type}- </Badge>- </Tooltip>+ <NodeInfoButton node={node} template={template} /></>)}</Flex><NodeProgressStrip execution={execution} />{isOpen ? (- <Box bg="bg.muted" borderBottomRadius={execution?.outputImageUrl ? 'none' : 'lg'} py="1">+ <Box bg="bg.muted" borderBottomRadius={withFooter || withOutputPreview ? 'none' : 'lg'} py="1">{outputTemplates.map((outputTemplate) => (<OutputFieldRow key={outputTemplate.name} isSkeleton={isZoomedOut} template={outputTemplate} />))}@@ -534,7 +634,7 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlo<HiddenHandles inputTemplates={inputTemplates} outputTemplates={outputTemplates} />)}{isOpen && execution?.outputImageUrl ? (- <Box borderColor="border.subtle" borderTopWidth="1px" p="1.5">+ <Box borderBottomRadius={withFooter ? 'none' : 'lg'} borderColor="border.subtle" borderTopWidth="1px" p="1.5">{isZoomedOut ? (<SkeletonBar h="6rem" w="full" />) : (@@ -550,6 +650,7 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlo)}</Box>) : null}+ {isOpen && withFooter ? <NodeFooter node={node} template={template} /> : null}</NodeShell>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsxindex 6d97d1d846..13e9689814 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx@@ -5,7 +5,7 @@ import type { FieldInputTemplate } from '@workbench/workflows/types';import { HStack, Input, NativeSelect, Switch, Text, Textarea } from '@chakra-ui/react';import { Button } from '@workbench/components/ui';import { listGalleryBoards, type GalleryBoard } from '@workbench/gallery/api';-import { SCHEDULER_OPTIONS } from '@workbench/generation/settings';+import { SCHEDULER_OPTIONS } from '@workbench/generation/baseGenerationPolicies';import { ModelSelect } from '@workbench/models/components';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useEffect, useState, type ChangeEvent } from 'react';@@ -179,6 +179,7 @@ const ModelIdentifierInput = ({ id, invalid, onChange, template, value }: Workflreturn (<ModelSelect+ className="nodrag nowheel"filter={allowedBases ? (model: ModelConfig) => allowedBases.includes(model.base) : undefined}id={id ? `${id}-model-combobox` : undefined}invalid={invalid}@@ -205,16 +206,31 @@ const SchedulerInput = ({ id, invalid, onChange, template, value }: WorkflowFiel/>);+let boardOptionsRequest: Promise<GalleryBoard[]> | null = null;++const getBoardOptions = (): Promise<GalleryBoard[]> => {+ if (!boardOptionsRequest) {+ boardOptionsRequest = listGalleryBoards()+ .then((loadedBoards) => loadedBoards.filter((board) => board.kind === 'board'))+ .catch((error: unknown) => {+ boardOptionsRequest = null;+ throw error;+ });+ }++ return boardOptionsRequest;+};+const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const [boards, setBoards] = useState<GalleryBoard[]>([]);useEffect(() => {let isCancelled = false;- listGalleryBoards()+ getBoardOptions().then((loadedBoards) => {if (!isCancelled) {- setBoards(loadedBoards.filter((board) => board.kind === 'board'));+ setBoards(loadedBoards);}}).catch(() => {diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.tsindex d9bca83b46..ef16a554f4 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts@@ -160,6 +160,73 @@ describe('getProjectGraphReadiness', () => {expect(getProjectGraphReadiness(doc, unknownTemplates).reasons[0]).toMatch(/Unknown node type "sink"/);});++ it('reports invalid required direct values', () => {+ const constrainedTemplate = template('constrained', {+ choice: input('choice', {+ options: ['a', 'b'],+ required: true,+ type: { batch: false, cardinality: 'SINGLE', name: 'EnumField' },+ }),+ count: input('count', {+ maximum: 4,+ minimum: 1,+ required: true,+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ }),+ });+ const node = buildInvocationNode(constrainedTemplate, { x: 0, y: 0 });+ let doc = createProjectGraph('invalid-values');++ doc = projectGraphReducer(doc, { node, type: 'addNode' });+ doc = projectGraphReducer(doc, { fieldName: 'choice', nodeId: node.id, type: 'setFieldValue', value: 'z' });+ doc = projectGraphReducer(doc, { fieldName: 'count', nodeId: node.id, type: 'setFieldValue', value: 10 });++ const readiness = getProjectGraphReadiness(doc, {+ error: null,+ status: 'loaded',+ templates: { constrained: constrainedTemplate },+ });++ expect(readiness.canInvoke).toBe(false);+ expect(readiness.reasons).toEqual([+ '"constrained" has invalid input "choice".',+ '"constrained" has invalid input "count".',+ ]);+ });++ it('reports invalid optional direct values when they are populated', () => {+ const constrainedTemplate = template('optional-constrained', {+ count: input('count', {+ maximum: 4,+ minimum: 1,+ required: false,+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ }),+ });+ const node = buildInvocationNode(constrainedTemplate, { x: 0, y: 0 });+ let doc = createProjectGraph('invalid-optional-values');++ doc = projectGraphReducer(doc, { node, type: 'addNode' });++ expect(+ getProjectGraphReadiness(doc, {+ error: null,+ status: 'loaded',+ templates: { 'optional-constrained': constrainedTemplate },+ })+ ).toEqual({ canInvoke: true, reasons: [] });++ doc = projectGraphReducer(doc, { fieldName: 'count', nodeId: node.id, type: 'setFieldValue', value: 10 });++ expect(+ getProjectGraphReadiness(doc, {+ error: null,+ status: 'loaded',+ templates: { 'optional-constrained': constrainedTemplate },+ })+ ).toEqual({ canInvoke: false, reasons: ['"optional-constrained" has invalid input "count".'] });+ });});describe('compileProjectGraph', () => {diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.tsindex 68e10b88ec..ed68e240a2 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts@@ -5,6 +5,7 @@ import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState, Workflimport { getResolvedWorkflowEdges } from './connectors';import { createWorkflowId } from './document';+import { getWorkflowFieldInvalidReason } from './fields';import { isInvocationNode } from './types';import { hasAnyCycle } from './validation';@@ -27,6 +28,8 @@ const UNSUPPORTED_NODE_TYPES = new Set(['string_generator',]);+export const isExecutableInvocationType = (type: string): boolean => !UNSUPPORTED_NODE_TYPES.has(type);+const getExecutableNodes = (document: ProjectGraphState): WorkflowInvocationNode[] =>document.nodes.filter(isInvocationNode);@@ -87,27 +90,35 @@ export const getProjectGraphReadiness = (continue;}- if (UNSUPPORTED_NODE_TYPES.has(node.data.type)) {+ if (!isExecutableInvocationType(node.data.type)) {reasons.push(`Batch/generator node "${getNodeDisplayName(node, templates)}" is not supported yet.`);continue;}for (const inputTemplate of Object.values(template.inputs)) {- if (!inputTemplate.required) {- continue;- }-if (connectedInputs.has(`${node.id}:${inputTemplate.name}`)) {continue;}if (inputTemplate.input === 'connection') {- reasons.push(`"${getNodeDisplayName(node, templates)}" is missing a connection for "${inputTemplate.title}".`);+ if (inputTemplate.required) {+ reasons.push(+ `"${getNodeDisplayName(node, templates)}" is missing a connection for "${inputTemplate.title}".`+ );+ }continue;}- if (isEmptyValue(node.data.inputs[inputTemplate.name]?.value)) {+ const invalidReason = getWorkflowFieldInvalidReason({+ isConnected: false,+ template: inputTemplate,+ value: node.data.inputs[inputTemplate.name]?.value,+ });++ if (inputTemplate.required && isEmptyValue(node.data.inputs[inputTemplate.name]?.value)) {reasons.push(`"${getNodeDisplayName(node, templates)}" is missing required input "${inputTemplate.title}".`);+ } else if (invalidReason) {+ reasons.push(`"${getNodeDisplayName(node, templates)}" has invalid input "${inputTemplate.title}".`);}}}diff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/document.test.tsindex 259079bcd3..6f6f30edbe 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts@@ -161,6 +161,14 @@ describe('projectGraphReducer', () => {expect(node?.type === 'invocation' && node.data.inputs.a?.value).toBe(42);});+ it('sets invocation cache preference', () => {+ const { doc, nodeAId } = createDocWithNodes();+ const next = projectGraphReducer(doc, { nodeId: nodeAId, type: 'setNodeUseCache', useCache: false });+ const node = next.nodes.find((candidate) => candidate.id === nodeAId);++ expect(node?.type === 'invocation' && node.data.useCache).toBe(false);+ });+it('sets and clears field description overrides', () => {const { doc, nodeAId } = createDocWithNodes();let next = projectGraphReducer(doc, {diff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.ts b/invokeai/frontend/webv2/src/workbench/workflows/document.tsindex a63e58c904..63e3a378f3 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/document.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/document.ts@@ -292,6 +292,7 @@ export type ProjectGraphAction =| { type: 'setNodeNotes'; nodeId: string; notes: string }| { type: 'setNodeIsOpen'; nodeId: string; isOpen: boolean }| { type: 'setNodeIsIntermediate'; nodeId: string; isIntermediate: boolean }+ | { type: 'setNodeUseCache'; nodeId: string; useCache: boolean }| { type: 'setFieldValue'; nodeId: string; fieldName: string; value: unknown }| { type: 'setFieldLabel'; nodeId: string; fieldName: string; label: string }| { type: 'setFieldDescription'; nodeId: string; fieldName: string; description: string }@@ -482,6 +483,12 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGradata: { ...node.data, isIntermediate: action.isIntermediate },}));}+ case 'setNodeUseCache': {+ return updateInvocationNode(document, action.nodeId, (node) => ({+ ...node,+ data: { ...node.data, useCache: action.useCache },+ }));+ }case 'setFieldValue': {return setFieldInstance(document, action.nodeId, action.fieldName, (instance) => ({...instance,diff --git a/invokeai/frontend/webv2/src/workbench/workflows/fields.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/fields.test.tsindex 2c4f414879..b1d9ac5270 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/fields.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/fields.test.ts@@ -69,6 +69,13 @@ describe('workflow field validation', () => {expect(isWorkflowFieldValueValid(template, 5.5)).toBe(false);});+ it('allows empty optional direct values but flags populated invalid optional values', () => {+ const template = input({ maximum: 10, minimum: 1, required: false, type: single('IntegerField') });++ expect(getWorkflowFieldInvalidReason({ isConnected: false, template, value: undefined })).toBe(null);+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template, value: 20 })).toBe('Invalid value.');+ });+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);diff --git a/invokeai/frontend/webv2/src/workbench/workflows/fields.ts b/invokeai/frontend/webv2/src/workbench/workflows/fields.tsindex b0c95d4588..9d2ff02112 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/fields.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/fields.ts@@ -128,6 +128,8 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: u}};+const isEmptyOptionalValue = (value: unknown): boolean => value === undefined || value === null || value === '';+export const getWorkflowFieldInvalidReason = ({isConnected,template,@@ -137,10 +139,18 @@ export const getWorkflowFieldInvalidReason = ({template: FieldInputTemplate;value: unknown;}): string | null => {- if (!template.required || isConnected) {+ if (isConnected) {+ return null;+ }++ if (!template.required && isEmptyOptionalValue(value)) {return null;}+ if (!template.required) {+ return isDirectInputField(template) && !isWorkflowFieldValueValid(template, value) ? 'Invalid value.' : null;+ }+if (template.input === 'connection') {return 'Required connection.';}