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: add workflow graph invocation
joshistoast6cc93995b9c6
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsxindex db72826012..72c99fc61c 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx@@ -8,6 +8,7 @@ import {} from './backend/queueCoordinator';import { normalizeGenerateSettings } from './generation/settings';import { addImagesToGalleryBoard } from './gallery/api';+import { ensureInvocationTemplatesLoaded } from './workflows/templates';import type { Project, QueueItem } from './types';import { useWorkbench } from './WorkbenchContext';import type { WorkbenchAction } from './workbenchState';@@ -31,7 +32,11 @@ const routeRunResults = async (dispatch: Dispatch<WorkbenchAction>): Promise<void> => {try {- const images = await coordinator.waitForResults(queueItem.id, queueItem.snapshot.submittedAt);+ const allImages = await coordinator.waitForResults(queueItem.id, queueItem.snapshot.submittedAt);+ // A workflow session reports every image its nodes produced; only the+ // non-intermediate outputs are user-facing results.+ const images =+ queueItem.snapshot.sourceId === 'project-graph' ? allImages.filter((image) => !image.isIntermediate) : allImages;if (queueItem.snapshot.destination === 'gallery') {const selectedBoardId = getSnapshotGalleryBoardId(queueItem);@@ -68,11 +73,14 @@ const submitQueueItem = (dispatch: Dispatch<WorkbenchAction>): void => {const graph = queueItem.snapshot.graph.backendGraph;- const generateValues = normalizeGenerateSettings(queueItem.snapshot.widgetStates.generate.values);+ const generateValues =+ queueItem.snapshot.sourceId === 'generate'+ ? normalizeGenerateSettings(queueItem.snapshot.widgetStates.generate.values)+ : null;- if (!graph || !generateValues) {+ if (!graph || (queueItem.snapshot.sourceId === 'generate' && !generateValues)) {dispatch({- error: 'Generate queue item is missing a compiled backend graph.',+ error: `${queueItem.snapshot.sourceId} queue item is missing a compiled backend graph.`,projectId: project.id,queueItemId: queueItem.id,status: 'failed',@@ -81,20 +89,27 @@ const submitQueueItem = (return;}- coordinator- .submitGenerate(queueItem.id, {- batchCount: generateValues.batchCount,- destination: queueItem.snapshot.destination,- graph,- negativePrompt: generateValues.negativePrompt,- negativePromptNodeId: 'negative_prompt',- positivePrompt: generateValues.positivePrompt,- positivePromptNodeId: 'positive_prompt',- seed: generateValues.seed,- seedNodeId: 'seed',- shouldRandomizeSeed: generateValues.shouldRandomizeSeed,- sourceQueueItemId: queueItem.id,- })+ const submission = generateValues+ ? coordinator.submitGenerate(queueItem.id, {+ batchCount: generateValues.batchCount,+ destination: queueItem.snapshot.destination,+ graph,+ negativePrompt: generateValues.negativePrompt,+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: generateValues.positivePrompt,+ positivePromptNodeId: 'positive_prompt',+ seed: generateValues.seed,+ seedNodeId: 'seed',+ shouldRandomizeSeed: generateValues.shouldRandomizeSeed,+ sourceQueueItemId: queueItem.id,+ })+ : coordinator.submitWorkflow(queueItem.id, {+ destination: queueItem.snapshot.destination,+ graph,+ sourceQueueItemId: queueItem.id,+ });++ submission.then(({ batchId, itemIds }) => {dispatch({backendBatchId: batchId,@@ -143,6 +158,9 @@ export const WorkbenchRuntime = () => {coordinatorRef.current = coordinator;coordinator.connect();+ // Node definitions back project-graph route validation, which can be the+ // persisted invocation source before any workflow surface has mounted.+ ensureInvocationTemplatesLoaded();return () => {coordinatorRef.current = null;@@ -261,7 +279,7 @@ export const WorkbenchRuntime = () => {for (const queueItem of project.queue.items) {if (queueItem.status === 'pending' &&- queueItem.snapshot.sourceId === 'generate' &&+ (queueItem.snapshot.sourceId === 'generate' || queueItem.snapshot.sourceId === 'project-graph') &&!startedQueueItemIdsRef.current.has(queueItem.id)) {startedQueueItemIdsRef.current.add(queueItem.id);diff --git a/invokeai/frontend/webv2/src/workbench/backend/events.ts b/invokeai/frontend/webv2/src/workbench/backend/events.tsindex 91cd95fb75..439e488b6a 100644--- a/invokeai/frontend/webv2/src/workbench/backend/events.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/events.ts@@ -28,16 +28,39 @@ export interface QueueItemStatusChangedEvent extends QueueItemEventBase {session_id: string;}-export interface InvocationProgressEvent extends QueueItemEventBase {+/** Shared shape of per-invocation lifecycle events (`InvocationEventBase` on the backend). */+export interface InvocationEventBase extends QueueItemEventBase {session_id: string;+ /** The id of the executing invocation's source node — the editor's node id. */+ invocation_source_id: string;+}++export interface InvocationStartedEvent extends InvocationEventBase {}++export interface InvocationProgressEvent extends InvocationEventBase {message: string;/** 0..1, or null for indeterminate progress. */percentage: number | null;+ /** Intermittent denoising preview, when the invocation produces one. */+ image?: { width: number; height: number; dataURL: string } | null;+}++export interface InvocationCompleteEvent extends InvocationEventBase {+ /** The invocation's output, discriminated by its `type` (e.g. `image_output`). */+ result: { type: string } & Record<string, unknown>;+}++export interface InvocationErrorEvent extends InvocationEventBase {+ error_type: string;+ error_message: string;}export interface BackendSocketEvents {queue_item_status_changed: QueueItemStatusChangedEvent;+ invocation_started: InvocationStartedEvent;invocation_progress: InvocationProgressEvent;+ invocation_complete: InvocationCompleteEvent;+ invocation_error: InvocationErrorEvent;}export const isTerminalBackendStatus = (status: BackendQueueItemStatus): status is TerminalBackendQueueItemStatus =>diff --git a/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.tsnew file mode 100644index 0000000000..b6eceaa4ec--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.ts@@ -0,0 +1,128 @@+import { useSyncExternalStore } from 'react';++import type { InvocationCompleteEvent, InvocationErrorEvent, InvocationStartedEvent } from './events';+import { buildApiUrl } from './http';++/**+ * Ephemeral per-node execution state, keyed by the invocation's source node id+ * (the workflow editor's node id). Like the queue-item progress store, this is+ * high-frequency transient data that deliberately lives outside the workbench+ * reducer; the editor's nodes subscribe per id and only re-render when their+ * own node's state moves.+ */++export type NodeExecutionStatus = 'running' | 'completed' | 'failed';++export interface NodeExecutionState {+ status: NodeExecutionStatus;+ /** 0..1, or null while indeterminate. Only meaningful while running. */+ progress: number | null;+ progressMessage: string | null;+ /** Thumbnail of the node's most recent image output, when it produced one. */+ outputImageUrl: string | null;+ error: string | null;+}++const stateByNodeId = new Map<string, NodeExecutionState>();+const listeners = new Set<() => void>();++const emit = (): void => {+ for (const listener of listeners) {+ listener();+ }+};++const subscribe = (listener: () => void): (() => void) => {+ listeners.add(listener);++ return () => {+ listeners.delete(listener);+ };+};++/** Pull the produced image out of an invocation output, whatever the node type. */+const getResultImageName = (result: InvocationCompleteEvent['result']): string | null => {+ const image = (result as { image?: { image_name?: unknown } }).image;++ return typeof image?.image_name === 'string' ? image.image_name : null;+};++export const nodeExecutionStore = {+ clearAll(): void {+ if (stateByNodeId.size > 0) {+ stateByNodeId.clear();+ emit();+ }+ },+ completed(event: InvocationCompleteEvent): void {+ const imageName = getResultImageName(event.result);+ const previous = stateByNodeId.get(event.invocation_source_id);++ stateByNodeId.set(event.invocation_source_id, {+ error: null,+ outputImageUrl: imageName+ ? buildApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`)+ : (previous?.outputImageUrl ?? null),+ progress: null,+ progressMessage: null,+ status: 'completed',+ });+ emit();+ },+ failed(event: InvocationErrorEvent): void {+ const previous = stateByNodeId.get(event.invocation_source_id);++ stateByNodeId.set(event.invocation_source_id, {+ error: event.error_message,+ outputImageUrl: previous?.outputImageUrl ?? null,+ progress: null,+ progressMessage: null,+ status: 'failed',+ });+ emit();+ },+ progress(nodeId: string, percentage: number | null, message: string): void {+ const previous = stateByNodeId.get(nodeId);++ stateByNodeId.set(nodeId, {+ error: null,+ outputImageUrl: previous?.outputImageUrl ?? null,+ progress: percentage,+ progressMessage: message,+ status: 'running',+ });+ emit();+ },+ /** A queue item reached a terminal state: nothing can still be running. */+ settleRunning(): void {+ let changed = false;++ for (const [nodeId, state] of stateByNodeId) {+ if (state.status === 'running') {+ stateByNodeId.set(nodeId, { ...state, progress: null, progressMessage: null, status: 'completed' });+ changed = true;+ }+ }++ if (changed) {+ emit();+ }+ },+ started(event: InvocationStartedEvent): void {+ const previous = stateByNodeId.get(event.invocation_source_id);++ stateByNodeId.set(event.invocation_source_id, {+ error: null,+ outputImageUrl: previous?.outputImageUrl ?? null,+ progress: null,+ progressMessage: null,+ status: 'running',+ });+ emit();+ },+};++export type NodeExecutionSink = typeof nodeExecutionStore;++export const useNodeExecutionState = (nodeId: string): NodeExecutionState | null =>+ useSyncExternalStore(subscribe, () => stateByNodeId.get(nodeId) ?? null);diff --git a/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.ts b/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.tsnew file mode 100644index 0000000000..08d21621c3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.ts@@ -0,0 +1,47 @@+import { useSyncExternalStore } from 'react';++/**+ * The most recent denoising preview image from `invocation_progress` events,+ * as a b64 data URL. Cleared when the run settles so consumers (the editor's+ * Current Image node, progress surfaces) fall back to the last real output.+ */++export interface ProgressImageSnapshot {+ dataUrl: string;+ width: number;+ height: number;+}++let snapshot: ProgressImageSnapshot | null = null;+const listeners = new Set<() => void>();++const emit = (): void => {+ for (const listener of listeners) {+ listener();+ }+};++const subscribe = (listener: () => void): (() => void) => {+ listeners.add(listener);++ return () => {+ listeners.delete(listener);+ };+};++export const progressImageStore = {+ clear(): void {+ if (snapshot !== null) {+ snapshot = null;+ emit();+ }+ },+ set(image: ProgressImageSnapshot): void {+ snapshot = image;+ emit();+ },+};++export type ProgressImageSink = typeof progressImageStore;++export const useProgressImage = (): ProgressImageSnapshot | null => useSyncExternalStore(subscribe, () => snapshot);diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.tsindex c1cfd09c60..09651bd650 100644--- a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts@@ -112,6 +112,7 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): HarcancelQueueItems: vi.fn(() => Promise.resolve()),cancelQueueItemsByBatchIds: vi.fn(() => Promise.resolve()),enqueueGenerateGraph: vi.fn(() => Promise.resolve({ batchId: 'batch-1', itemIds: [1] })),+ enqueueWorkflowGraph: vi.fn(() => Promise.resolve({ batchId: 'batch-1', itemIds: [1] })),getQueueItem: vi.fn((itemId: number) => Promise.resolve(createQueueItemDTO({ item_id: itemId }))),getQueueItemResultImages: vi.fn((itemId: number, sourceQueueItemId: string) =>Promise.resolve([createImage(`image-${itemId}.png`, sourceQueueItemId)])diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.tsindex bb2ee1d4b2..6d8a5dbb74 100644--- a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts@@ -4,22 +4,34 @@ import {cancelQueueItems,cancelQueueItemsByBatchIds,enqueueGenerateGraph,+ enqueueWorkflowGraph,getQueueItem,getQueueItemResultImages,listAllQueueItems,} from '../generation/api';-import type { EnqueueGenerateRequest, EnqueueGenerateResult, ImageDTO, QueueItemDTO } from '../generation/types';+import type {+ EnqueueGenerateRequest,+ EnqueueGenerateResult,+ EnqueueWorkflowRequest,+ ImageDTO,+ QueueItemDTO,+} from '../generation/types';import { handleModelInstallSocketEvent, MODEL_INSTALL_SOCKET_EVENTS } from '../models/installsStore';import type { BackendConnectionStatus } from '../types';import {isTerminalBackendStatus,parseQueueItemOrigin,+ type InvocationCompleteEvent,+ type InvocationErrorEvent,type InvocationProgressEvent,+ type InvocationStartedEvent,type QueueItemStatusChangedEvent,type TerminalBackendQueueItemStatus,} from './events';import { ApiError, getAuthToken, getBackendSocketUrl } from './http';import { modelLoadStore } from './modelLoadStore';+import { nodeExecutionStore, type NodeExecutionSink } from './nodeExecutionStore';+import { progressImageStore, type ProgressImageSink } from './progressImageStore';import { queueItemProgressStore, type QueueItemProgressSink } from './progressStore';const SOCKET_PATH = '/ws/socket.io';@@ -41,6 +53,7 @@ export interface QueueCoordinatorApi {cancelQueueItems: typeof cancelQueueItems;cancelQueueItemsByBatchIds: typeof cancelQueueItemsByBatchIds;enqueueGenerateGraph: typeof enqueueGenerateGraph;+ enqueueWorkflowGraph: typeof enqueueWorkflowGraph;getQueueItem: typeof getQueueItem;getQueueItemResultImages: typeof getQueueItemResultImages;listAllQueueItems: typeof listAllQueueItems;@@ -95,6 +108,8 @@ export interface QueueCoordinator {reconcile(items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>>;/** Enqueue a generate batch and track its backend items for event-driven settlement. */submitGenerate(localQueueItemId: string, request: EnqueueGenerateRequest): Promise<EnqueueGenerateResult>;+ /** Enqueue a compiled workflow graph and track its backend items the same way. */+ submitWorkflow(localQueueItemId: string, request: EnqueueWorkflowRequest): Promise<EnqueueGenerateResult>;/*** Resolve once every backend item of the run reaches a terminal status —* driven by socket events, with a slow safety sweep as the only polling.@@ -128,6 +143,7 @@ const defaultApi: QueueCoordinatorApi = {cancelQueueItems,cancelQueueItemsByBatchIds,enqueueGenerateGraph,+ enqueueWorkflowGraph,getQueueItem,getQueueItemResultImages,listAllQueueItems,@@ -167,13 +183,17 @@ export const createQueueCoordinator = (api?: Partial<QueueCoordinatorApi>;createSocket?: () => BackendSocket;galleryRefreshCoalesceMs?: number;+ nodeExecution?: NodeExecutionSink;progress?: QueueItemProgressSink;+ progressImage?: ProgressImageSink;sweepIntervalMs?: number;} = {}): QueueCoordinator => {const api: QueueCoordinatorApi = { ...defaultApi, ...options.api };const createSocket = options.createSocket ?? createDefaultSocket;const progress = options.progress ?? queueItemProgressStore;+ const nodeExecution = options.nodeExecution ?? nodeExecutionStore;+ const progressImage = options.progressImage ?? progressImageStore;const galleryRefreshCoalesceMs = options.galleryRefreshCoalesceMs ?? GALLERY_REFRESH_COALESCE_MS;const sweepIntervalMs = options.sweepIntervalMs ?? SAFETY_SWEEP_INTERVAL_MS;@@ -334,6 +354,8 @@ export const createQueueCoordinator = (return;}+ nodeExecution.settleRunning();+ progressImage.clear();settleWait(event.item_id, toTerminalOutcome(event.status, event.error_message, event.error_type));if (event.status === 'completed') {@@ -342,6 +364,12 @@ export const createQueueCoordinator = (};const handleProgress = (event: InvocationProgressEvent): void => {+ nodeExecution.progress(event.invocation_source_id, event.percentage, event.message);++ if (event.image?.dataURL) {+ progressImage.set({ dataUrl: event.image.dataURL, height: event.image.height, width: event.image.width });+ }+const wait = waits.get(event.item_id);if (wait) {@@ -376,6 +404,7 @@ export const createQueueCoordinator = (socket.on('connect', () => {modelLoadStore.reset();progress.clearAll?.();+ nodeExecution.clearAll();notifyConnection('connected');socket?.emit('subscribe_queue', { queue_id: 'default' });scheduleGalleryRefresh();@@ -384,15 +413,26 @@ export const createQueueCoordinator = (socket.on('connect_error', (error: { message: string }) => {modelLoadStore.reset();progress.clearAll?.();+ nodeExecution.clearAll();notifyConnection('disconnected', error.message);});socket.on('disconnect', (reason: string) => {modelLoadStore.reset();progress.clearAll?.();+ nodeExecution.clearAll();notifyConnection('disconnected', reason);});socket.on('queue_item_status_changed', handleStatusChanged);socket.on('invocation_progress', handleProgress);+ socket.on('invocation_started', (event: InvocationStartedEvent) => {+ nodeExecution.started(event);+ });+ socket.on('invocation_complete', (event: InvocationCompleteEvent) => {+ nodeExecution.completed(event);+ });+ socket.on('invocation_error', (event: InvocationErrorEvent) => {+ nodeExecution.failed(event);+ });socket.on('model_load_started', (payload: never) => {modelLoadStore.started(payload);});@@ -498,6 +538,17 @@ export const createQueueCoordinator = (return result;};+ const submitWorkflow = async (+ localQueueItemId: string,+ request: EnqueueWorkflowRequest+ ): Promise<EnqueueGenerateResult> => {+ const result = await api.enqueueWorkflowGraph(request);++ beginRun(localQueueItemId, result.itemIds, result.batchId);++ return result;+ };+const waitForResults = async (localQueueItemId: string, queuedAt: string): Promise<ImageDTO[]> => {const run = runs.get(localQueueItemId);@@ -542,5 +593,5 @@ export const createQueueCoordinator = (}};- return { cancelRun, connect, dispose, reconcile, submitGenerate, waitForResults };+ return { cancelRun, connect, dispose, reconcile, submitGenerate, submitWorkflow, waitForResults };};diff --git a/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsxindex 8fd4728505..1ebfe0942b 100644--- a/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsx@@ -1,4 +1,4 @@-import { Flex, Group, HStack, Icon, Menu, Portal, Text, VStack } from '@chakra-ui/react';+import { Flex, Group, HStack, Icon, Menu, Portal, Stack, Text, VStack } from '@chakra-ui/react';import { useEffect, useRef } from 'react';import { CheckIcon, ChevronDownIcon, LockKeyholeIcon, SparklesIcon } from 'lucide-react';@@ -10,8 +10,10 @@ import {resolveInvocationRoute,resultDestinations,} from '../invocation';+import { useInvocationTemplatesSnapshot } from '../workflows/templates';import type { InvocationSourceId, ResultDestination } from '../types';import { Button, IconButton } from './ui/Button';+import { Tooltip } from './ui/Tooltip';/*** Fixed-width global Invoke control.@@ -26,12 +28,24 @@ import { Button, IconButton } from './ui/Button';const CONTROL_WIDTH = '12rem';export const InvokeControl = () => {- const { activeProject, dispatch } = useWorkbench();+ const { activeProject, dispatch, state } = useWorkbench();const { invocation } = activeProject;++ // Project-graph route validation reads the invocation templates imperatively;+ // subscribing here keeps the resolved route live while they load.+ useInvocationTemplatesSnapshot();+const resolvedRoute = resolveInvocationRoute(activeProject);const isLocked = invocation.sourceLocked || invocation.destinationLocked;- const isValid = isInvocationRouteValid(resolvedRoute);- const routeLabel = formatRoute(resolvedRoute);+ const isConnected = state.backendConnection.status === 'connected';+ // Legacy parity: the queue button disables with the full list of reasons,+ // including a disconnected backend.+ const blockingReasons = [+ ...(isConnected ? [] : ['The backend is disconnected.']),+ ...resolvedRoute.validationReasons,+ ];+ const isValid = isInvocationRouteValid(resolvedRoute) && isConnected;+ const routeLabel = isValid ? formatRoute(resolvedRoute) : (blockingReasons[0] ?? formatRoute(resolvedRoute));const resolvedRouteRef = useRef(resolvedRoute);const isValidRef = useRef(isValid);@@ -78,22 +92,47 @@ export const InvokeControl = () => {return (<Flex>- <Menu.Root positioning={{ placement: 'bottom-start' }}>+ <Menu.Root positioning={{ placement: 'bottom-end' }}><Group attached>- <Button colorPalette="brand" size="sm" onClick={onInvoke} w={CONTROL_WIDTH} minW="0" justifyContent="start">- <Icon as={SparklesIcon} boxSize="4" flexShrink={0} />- <VStack align="start" gap="0" minW="0">- <Text fontSize="sm" fontWeight="700" lineHeight="1">- Invoke- </Text>- <HStack gap="1" maxW="full">- <Text fontSize="2xs" fontWeight="600" lineHeight="1.1" opacity="0.85" truncate>- {routeLabel}+ <Tooltip+ content={+ <Stack gap="0.5">+ {blockingReasons.map((reason) => (+ <Text key={reason} fontSize="2xs">+ {reason}+ </Text>+ ))}+ </Stack>+ }+ disabled={isValid}+ >+ {/* aria-disabled (not disabled) keeps hover alive so the reasons tooltip can show. */}+ <Button+ aria-disabled={!isValid}+ colorPalette="brand"+ cursor={isValid ? undefined : 'not-allowed'}+ opacity={isValid ? undefined : 0.6}+ size="sm"+ roundedEnd="none"+ onClick={onInvoke}+ w={CONTROL_WIDTH}+ minW="0"+ justifyContent="start"+ >+ <Icon as={SparklesIcon} boxSize="4" flexShrink={0} />+ <VStack align="start" gap="0" minW="0">+ <Text fontSize="sm" fontWeight="700" lineHeight="1">+ Invoke</Text>- {isLocked ? <Icon as={LockKeyholeIcon} boxSize="2.5" flexShrink={0} /> : null}- </HStack>- </VStack>- </Button>+ <HStack gap="1" maxW="full">+ <Text fontSize="2xs" fontWeight="600" lineHeight="1.1" opacity="0.85" truncate>+ {routeLabel}+ </Text>+ {isLocked ? <Icon as={LockKeyholeIcon} boxSize="2.5" flexShrink={0} /> : null}+ </HStack>+ </VStack>+ </Button>+ </Tooltip><Menu.Trigger asChild><IconButton colorPalette="brand" size="sm" minW="0" w="7"><ChevronDownIcon />@@ -102,7 +141,7 @@ export const InvokeControl = () => {</Group><Portal><Menu.Positioner>- <Menu.Content minW="15rem">+ <Menu.Content minW="14rem"><Menu.RadioItemGroupvalue={invocation.sourceId}onValueChange={(event) =>diff --git a/invokeai/frontend/webv2/src/workbench/generation/api.ts b/invokeai/frontend/webv2/src/workbench/generation/api.tsindex 47edf3708f..08b7eead0e 100644--- a/invokeai/frontend/webv2/src/workbench/generation/api.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/api.ts@@ -2,7 +2,14 @@ import { absolutizeApiUrl, ApiError, apiFetchJson } from '../backend/http';import { buildQueueItemOrigin } from '../backend/events';import type { BackendGraphContract } from '../types';import { generateSeedSequence } from './graph';-import type { EnqueueGenerateRequest, EnqueueGenerateResult, ImageDTO, MainModelConfig, QueueItemDTO } from './types';+import type {+ EnqueueGenerateRequest,+ EnqueueGenerateResult,+ EnqueueWorkflowRequest,+ ImageDTO,+ MainModelConfig,+ QueueItemDTO,+} from './types';export const listMainModels = async (): Promise<MainModelConfig[]> => {const body = await apiFetchJson<{ models?: MainModelConfig[] }>('/api/v2/models/?model_type=main');@@ -41,6 +48,25 @@ export const enqueueGenerateGraph = async (request: EnqueueGenerateRequest): Proreturn { batchId: result.batch?.batch_id, itemIds: result.item_ids ?? [] };};+/** Enqueue an arbitrary compiled graph as a single run — the workflow / project-graph path. */+export const enqueueWorkflowGraph = async (request: EnqueueWorkflowRequest): Promise<EnqueueGenerateResult> => {+ const body = {+ batch: {+ destination: request.destination,+ graph: request.graph satisfies BackendGraphContract,+ origin: buildQueueItemOrigin(request.sourceQueueItemId),+ runs: 1,+ },+ prepend: false,+ };+ const result = await apiFetchJson<{ batch?: { batch_id?: string }; item_ids?: number[] }>(+ '/api/v1/queue/default/enqueue_batch',+ { body: JSON.stringify(body), method: 'POST' }+ );++ return { batchId: result.batch?.batch_id, itemIds: result.item_ids ?? [] };+};+export const getQueueItem = (itemId: number): Promise<QueueItemDTO> =>apiFetchJson<QueueItemDTO>(`/api/v1/queue/default/i/${itemId}`);diff --git a/invokeai/frontend/webv2/src/workbench/generation/types.ts b/invokeai/frontend/webv2/src/workbench/generation/types.tsindex 1c9c976d82..ccb3a88d72 100644--- a/invokeai/frontend/webv2/src/workbench/generation/types.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/types.ts@@ -104,6 +104,13 @@ export interface QueueItemDTO {};}+/** A source-agnostic graph submission (used by the project-graph / workflow source). */+export interface EnqueueWorkflowRequest {+ destination: ResultDestination;+ graph: BackendGraphContract;+ sourceQueueItemId: string;+}+export interface EnqueueGenerateRequest {batchCount: number;destination: ResultDestination;diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex 7e8d0332bf..9e23441b0e 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -7,6 +7,8 @@ import type {ResultDestination,WidgetId,} from './types';+import { getProjectGraphReadiness } from './workflows/buildGraph';+import { getInvocationTemplatesSnapshot } from './workflows/templates';/*** Static metadata for the Invocation Controller surfaces.@@ -30,7 +32,7 @@ export interface ResultDestinationMeta {export const invocationSources: InvocationSourceMeta[] = [{ id: 'generate', label: 'Generate', available: true },- { id: 'project-graph', label: 'Workflow', available: false },+ { id: 'project-graph', label: 'Workflow', available: true },{ id: 'upscale', label: 'Upscale', available: false },{ id: 'canvas-fill', label: 'Canvas Fill', available: false },];@@ -103,18 +105,35 @@ export const resolveInvocationRoute = (const sourceId = route.sourceId;const destination = route.destination;const sourceWidgetId = sourceWidgetIds[sourceId];- const sourceValid =- isInvocationSourceAvailable(sourceId) &&- (!sourceWidgetId || isWidgetMounted(project, sourceWidgetId)) &&- (sourceId !== 'generate' || hasGenerateSnapshotInputs(project));+ // The project graph validates against its compiled readiness; templates are+ // read imperatively, and surfaces that render the route subscribe to the+ // templates store so the result stays live.+ const projectGraphReadiness =+ sourceId === 'project-graph'+ ? getProjectGraphReadiness(project.projectGraph, getInvocationTemplatesSnapshot())+ : null;+ const validationReasons: string[] = [];++ if (!isInvocationSourceAvailable(sourceId)) {+ validationReasons.push(`${getSourceLabel(sourceId)} is not an available invocation source.`);+ } else if (sourceWidgetId && !isWidgetMounted(project, sourceWidgetId)) {+ validationReasons.push(`The ${getSourceLabel(sourceId)} widget is not mounted in this project.`);+ }++ if (sourceId === 'generate' && !hasGenerateSnapshotInputs(project)) {+ validationReasons.push('Generate needs a supported model before it can be invoked.');+ }++ if (projectGraphReadiness && !projectGraphReadiness.canInvoke) {+ validationReasons.push(...projectGraphReadiness.reasons);+ }++ const sourceValid = validationReasons.length === 0;const destinationValid = isResultDestinationAvailable(destination);- const validationMessage = !sourceValid- ? sourceId === 'generate'- ? 'Generate needs a supported model before it can be invoked.'- : `${getSourceLabel(sourceId)} is not an available invocation source.`- : !destinationValid- ? `${getDestinationLabel(destination)} is not an available result destination.`- : undefined;++ if (!destinationValid) {+ validationReasons.push(`${getDestinationLabel(destination)} is not an available result destination.`);+ }return {...route,@@ -123,7 +142,8 @@ export const resolveInvocationRoute = (mode,sourceId,sourceValid,- validationMessage,+ validationMessage: validationReasons[0],+ validationReasons,};};diff --git a/invokeai/frontend/webv2/src/workbench/queueSummary.ts b/invokeai/frontend/webv2/src/workbench/queueSummary.tsindex 6325100e02..a63ecacf23 100644--- a/invokeai/frontend/webv2/src/workbench/queueSummary.ts+++ b/invokeai/frontend/webv2/src/workbench/queueSummary.ts@@ -52,7 +52,8 @@ export const getQueueItemExpectedImageCount = (item: QueueItem): number => {return item.backendItemIds.length;}- const batchCount = item.snapshot.widgetStates.generate?.values.batchCount;+ // Only Generate snapshots batch by count; other sources (project graph) run once.+ const batchCount = item.snapshot.sourceId === 'generate' ? item.snapshot.widgetStates.generate?.values.batchCount : 1;return typeof batchCount === 'number' && Number.isFinite(batchCount) ? Math.max(1, Math.round(batchCount)) : 1;};diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 302a8cffbe..ef9f5aad4e 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -77,6 +77,10 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {reduceMotion: false,showFocusRegionHighlight: true,themeId: DEFAULT_THEME_ID,+ workflowEdgeStyle: 'curved',+ workflowShowMinimap: true,+ workflowSnapToGrid: false,+ workflowValidateConnections: true,};interface WorkbenchSettingsSnapshot {@@ -170,6 +174,22 @@ export const normalizeWorkbenchPreferences = (preferences?: Partial<WorkbenchPre? preferences.showFocusRegionHighlight: DEFAULT_PREFERENCES.showFocusRegionHighlight,themeId: isWorkbenchThemeId(preferences?.themeId) ? preferences.themeId : DEFAULT_PREFERENCES.themeId,+ workflowEdgeStyle:+ preferences?.workflowEdgeStyle === 'straight' || preferences?.workflowEdgeStyle === 'curved'+ ? preferences.workflowEdgeStyle+ : DEFAULT_PREFERENCES.workflowEdgeStyle,+ workflowShowMinimap:+ typeof preferences?.workflowShowMinimap === 'boolean'+ ? preferences.workflowShowMinimap+ : DEFAULT_PREFERENCES.workflowShowMinimap,+ workflowSnapToGrid:+ typeof preferences?.workflowSnapToGrid === 'boolean'+ ? preferences.workflowSnapToGrid+ : DEFAULT_PREFERENCES.workflowSnapToGrid,+ workflowValidateConnections:+ typeof preferences?.workflowValidateConnections === 'boolean'+ ? preferences.workflowValidateConnections+ : DEFAULT_PREFERENCES.workflowValidateConnections,});const parsePreferences = (raw: string | null): WorkbenchPreferences | null => {diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex a92ad4d8e6..cec0117bd3 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -1,5 +1,7 @@import type { ComponentType } from 'react';+import type { ProjectGraphState } from './workflows/types';+export type LayoutPresetId = 'canvas-default' | 'gallery' | 'workflow' | 'linear' | 'model-manager';export type CenterViewId = 'canvas' | 'gallery' | 'preview' | 'workflow' | 'models';@@ -34,7 +36,9 @@ export type ProjectEventType =| 'layout-updated'| 'invocation-updated'| 'queue-submitted'- | 'canvas-layer-accepted';+ | 'canvas-layer-accepted'+ | 'graph-replaced'+ | 'graph-snapshot-saved';export interface GraphNodeContract {id: string;@@ -111,6 +115,7 @@ export interface WidgetViewProps {export type WidgetView = ComponentType<WidgetViewProps>;export type WidgetHeaderActions = ComponentType<WidgetViewProps>;+export type WidgetHeaderMenu = ComponentType<WidgetViewProps>;export type WidgetFooter = ComponentType<WidgetViewProps>;export interface WidgetLabelProps {@@ -122,6 +127,9 @@ export type WidgetLabel = string | ComponentType<WidgetLabelProps>;export type WidgetIconId = `lucide-react:${string}`;+/** Sections of the workbench settings dialog, addressable via `openWorkbenchSettings`. */+export type SettingsSectionId = 'appearance' | 'behavior' | 'project' | 'workflow' | 'developer' | 'workspace';+export interface WidgetManifest {id: WidgetId;label: WidgetLabel;@@ -138,6 +146,15 @@ export interface WidgetManifest {};view?: WidgetView;headerActions?: WidgetHeaderActions;+ /**+ * Extra entries for the widget's shared header actions menu. Rendered inside+ * the same menu as the universal graph actions, so widgets extend the frame+ * menu instead of stacking their own. Render `Menu.Item`/`Menu.ItemGroup`+ * children only; own any dialogs from `headerActions` (always mounted).+ */+ headerMenu?: WidgetHeaderMenu;+ /** When set, the frame header shows a gear that opens this settings dialog section. */+ settingsSection?: SettingsSectionId;footer?: WidgetFooter;graphBearing?: {sourceId: InvocationSourceId;@@ -239,7 +256,10 @@ export interface ResolvedInvocationRoute extends InvocationRoute {mode: InvocationMode;sourceValid: boolean;destinationValid: boolean;+ /** The top validation issue, shown on the fixed Invoke control's secondary line. */validationMessage?: string;+ /** Every reason the route cannot run right now (legacy `reasonsWhyCannotEnqueue` equivalent). */+ validationReasons: string[];}export interface InvocationControllerState extends InvocationRoute {@@ -280,7 +300,8 @@ export interface Project {settings: ProjectSettings;layout: ProjectLayoutState;invocation: InvocationControllerState;- projectGraph: GraphContract;+ /** The one active project graph: an editable workflow document, compiled to a `GraphContract` at invoke time. */+ projectGraph: ProjectGraphState;widgetStates: Record<WidgetId, WidgetStateContract>;widgetRegions: Record<WidgetRegion, WidgetRegionState>;widgetGraphs: Partial<Record<WidgetId, GraphContract>>;@@ -296,6 +317,8 @@ export interface LayoutPreset {label: string;description: string;initialLayout: ProjectLayoutState;+ /** Widget to focus in the left rail when the preset is applied (e.g. the Linear UI for workflow presets). */+ leftRegionWidgetId?: WidgetId;}export interface WorkbenchState {@@ -330,11 +353,17 @@ export interface WorkbenchNotification {isRead: boolean;}+/**+ * One entry of the project's graph history. Queue submissions record the+ * compiled `graph`; workflow snapshots (manual save, pre-replacement) record+ * the editable `document`, which is what makes them restorable.+ */export interface GraphHistorySnapshot {id: string;createdAt: string;label: string;- graph: GraphContract;+ graph?: GraphContract;+ document?: ProjectGraphState;}export interface UndoRedoEntry {@@ -347,7 +376,7 @@ export interface UndoRedoEntry {export interface ProjectUndoSnapshot {layout: ProjectLayoutState;invocation: InvocationControllerState;- projectGraph: GraphContract;+ projectGraph: ProjectGraphState;widgetStates: Record<WidgetId, WidgetStateContract>;widgetRegions: Record<WidgetRegion, WidgetRegionState>;widgetGraphs: Partial<Record<WidgetId, GraphContract>>;@@ -477,6 +506,14 @@ export interface WorkbenchPreferences {developerLogEnabled: boolean;developerLogLevel: DeveloperLogLevel;developerLogNamespaces: DeveloperLogNamespace[];+ /** Always snap workflow nodes to the grid (Ctrl snaps temporarily when off). */+ workflowSnapToGrid: boolean;+ /** Show the minimap in the workflow editor. */+ workflowShowMinimap: boolean;+ /** Reject workflow connections with incompatible field types. */+ workflowValidateConnections: boolean;+ /** Connection line rendering in the workflow editor. */+ workflowEdgeStyle: 'curved' | 'straight';}export interface AccountState {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 68c73af0aa..5206efcd51 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -522,12 +522,12 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(state.errorLog).toEqual([]);});- it('does not queue unavailable workflow/project graph sources in Phase 5', () => {+ it('accepts the project graph source but does not queue an empty project graph', () => {let state = createInitialWorkbenchState();state = workbenchReducer(state, { sourceId: 'project-graph', type: 'setInvocationSource' });- expect(getActiveProject(state).invocation.sourceId).toBe('generate');+ expect(getActiveProject(state).invocation.sourceId).toBe('project-graph');state = workbenchReducer(state, {backendSupportsCancellation: true,@@ -538,6 +538,86 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).queue.items).toEqual([]);});+ it('applies workflow edits to the project graph with undo and auto-source', () => {+ let state = createInitialWorkbenchState();++ expect(getActiveProject(state).invocation.sourceId).toBe('generate');++ state = workbenchReducer(state, {+ action: {+ node: {+ data: {+ inputs: {},+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'add',+ useCache: true,+ version: '1.0.0',+ },+ id: 'node-1',+ position: { x: 0, y: 0 },+ type: 'invocation',+ },+ type: 'addNode',+ },+ type: 'applyProjectGraphAction',+ });++ const project = getActiveProject(state);++ // A meaningful graph edit lands in the document, creates an undo entry,+ // and steers the unlocked invocation source to the project graph.+ expect(project.projectGraph.nodes).toHaveLength(1);+ expect(project.undoRedo.past.at(-1)?.label).toBe('Add workflow node');+ expect(project.invocation.sourceId).toBe('project-graph');++ state = workbenchReducer(state, { type: 'undoProjectChange' });++ expect(getActiveProject(state).projectGraph.nodes).toHaveLength(0);+ });++ it('replaceProjectGraph snapshots the previous document into graph history', () => {+ let state = createInitialWorkbenchState();+ const originalGraphId = getActiveProject(state).projectGraph.id;++ state = workbenchReducer(state, {+ document: { ...getActiveProject(state).projectGraph, id: 'replacement-graph', name: 'Replacement' },+ label: 'Test replace',+ type: 'replaceProjectGraph',+ });++ const project = getActiveProject(state);++ expect(project.projectGraph.id).toBe('replacement-graph');+ expect(project.graphHistory[0]?.document?.id).toBe(originalGraphId);++ state = workbenchReducer(state, {+ snapshotId: project.graphHistory[0]?.id ?? '',+ type: 'restoreProjectGraphSnapshot',+ });++ expect(getActiveProject(state).projectGraph.id).toBe(originalGraphId);+ });++ it('does not queue sources that are still unavailable', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });++ expect(getActiveProject(state).invocation.sourceId).toBe('generate');++ state = workbenchReducer(state, {+ backendSupportsCancellation: true,+ route: { destination: 'canvas', destinationLocked: false, sourceId: 'upscale', sourceLocked: true },+ type: 'submitResolvedInvocationSnapshot',+ });++ expect(getActiveProject(state).queue.items).toEqual([]);+ });+it('does not queue Generate snapshots with non-finite numeric settings', () => {let state = primeGenerate(undefined, { seed: Number.NaN });diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 6326f854cd..0814745410 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -10,6 +10,18 @@ import type { GallerySettings } from './gallery/settings';import type { GenerateWidgetValues } from './generation/types';import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';import { normalizeProjectSettings } from './settings/store';+import { compileProjectGraph } from './workflows/buildGraph';+import {+ cloneProjectGraph,+ createProjectGraph,+ getProjectGraphUndoLabel,+ isHighConfidenceGraphEdit,+ normalizeProjectGraph,+ projectGraphReducer,+ type ProjectGraphAction,+} from './workflows/document';+import { getInvocationTemplatesSnapshot } from './workflows/templates';+import type { ProjectGraphState } from './workflows/types';import type {CanvasDocumentContract,CanvasPlacementContract,@@ -22,6 +34,7 @@ import type {GraphHistorySnapshot,InvocationRoute,InvocationSourceId,+ LayoutPreset,LayoutPresetId,Project,ProjectLayoutState,@@ -61,6 +74,12 @@ type WorkbenchAction =| { type: 'setRegionWidgetSize'; region: WidgetRegion; sizePx: number }| { type: 'setGenerateSettings'; values: GenerateWidgetValues }| { type: 'setGenerateBatchCount'; batchCount: number }+ | { type: 'patchWidgetValues'; widgetId: WidgetId; values: Record<string, unknown> }+ | { type: 'applyProjectGraphAction'; action: ProjectGraphAction }+ | { type: 'replaceProjectGraph'; document: ProjectGraphState; label: string }+ | { type: 'saveProjectGraphSnapshot' }+ | { type: 'restoreProjectGraphSnapshot'; snapshotId: string }+ | { type: 'setProjectGraphLibraryBinding'; libraryWorkflowId: string }| { type: 'submitInvocationSnapshot'; backendSupportsCancellation: boolean }| { type: 'submitResolvedInvocationSnapshot'; backendSupportsCancellation: boolean; route: InvocationRoute }| {@@ -352,7 +371,7 @@ const createUndoSnapshot = (project: Project): ProjectUndoSnapshot => ({canvas: cloneCanvas(project.canvas),invocation: { ...project.invocation },layout: { ...project.layout, panels: { ...project.layout.panels } },- projectGraph: cloneGraph(project.projectGraph),+ projectGraph: cloneProjectGraph(project.projectGraph),widgetGraphs: cloneWidgetGraphs(project.widgetGraphs),widgetRegions: cloneWidgetRegions(project.widgetRegions),widgetStates: cloneWidgetStates(project.widgetStates),@@ -363,7 +382,7 @@ const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): Pcanvas: { ...cloneCanvas(snapshot.canvas), stagingArea: cloneCanvas(project.canvas).stagingArea },invocation: { ...snapshot.invocation },layout: { ...snapshot.layout, panels: { ...snapshot.layout.panels } },- projectGraph: cloneGraph(snapshot.projectGraph),+ projectGraph: cloneProjectGraph(normalizeProjectGraph(snapshot.projectGraph)),widgetGraphs: cloneWidgetGraphs(snapshot.widgetGraphs),widgetRegions: cloneWidgetRegions(snapshot.widgetRegions),widgetStates: cloneWidgetStates(snapshot.widgetStates),@@ -376,6 +395,14 @@ const createGraphHistorySnapshot = (label: string, graph: GraphContract): GraphHlabel,});+/** A restorable history entry carrying the editable workflow document. */+const createDocumentHistorySnapshot = (label: string, document: ProjectGraphState): GraphHistorySnapshot => ({+ createdAt: now(),+ document: cloneProjectGraph(document),+ id: createId('graph-history'),+ label,+});+const pushUndo = (project: Project, label: string): Project => ({...project,undoRedo: {@@ -392,15 +419,6 @@ const pushUndo = (project: Project, label: string): Project => ({},});-const createProjectGraph = (index: number, projectId: string): GraphContract => ({- edges: [],- id: `${projectId}-graph`,- label: `Project ${index} Graph`,- nodes: [],- updatedAt: now(),- version: 1,-});-const createWidgetStates = (): Record<WidgetId, WidgetStateContract> => ({'autosave-status': { id: 'autosave-status', label: 'Autosave', values: {}, version: 1 },canvas: { id: 'canvas', label: 'Canvas', values: {}, version: 1 },@@ -446,6 +464,7 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({'history-controls','layout-actions','version-status',+ 'workflow',],isCollapsed: true,sizePx: 180,@@ -510,6 +529,7 @@ const ensureProjectWidgetContracts = (project: Project): Project => {return {...project,canvas: cloneCanvas(project.canvas ?? createCanvasState()),+ projectGraph: normalizeProjectGraph(project.projectGraph),settings: normalizeProjectSettings(project.settings),widgetRegions: {left: legacyWidgetRegions?.left ?? legacyWidgetRegions?.['left-panel'] ?? defaultWidgetRegions.left,@@ -559,7 +579,7 @@ const createProject = (index: number, id = `project-${index}`): Project => ({invocation: { ...defaultInvocationRoute },layout: { ...defaultLayoutPreset.initialLayout, panels: { ...defaultLayoutPreset.initialLayout.panels } },name: `Project Name #${index}`,- projectGraph: createProjectGraph(index, id),+ projectGraph: createProjectGraph(`${id}-graph`),queue: { items: [] },settings: normalizeProjectSettings(),undoRedo: { future: [], past: [] },@@ -610,6 +630,27 @@ const updateActiveWidgetRegion = (},}));+/** Focuses the regions a layout preset names: the center view and, when declared, a left-rail widget. */+const applyPresetRegionFocus = (state: WorkbenchState, preset: LayoutPreset): WorkbenchState => {+ const centerWidgetId = getCenterWidgetIdFromViewId(preset.initialLayout.centerViewId);+ const nextState = updateActiveWidgetRegion(state, 'center', (region) => ({+ ...region,+ activeWidgetId: region.enabledWidgetIds.includes(centerWidgetId) ? centerWidgetId : region.activeWidgetId,+ isCollapsed: false,+ }));+ const leftWidgetId = preset.leftRegionWidgetId;++ if (!leftWidgetId) {+ return nextState;+ }++ return updateActiveWidgetRegion(nextState, 'left', (region) => ({+ ...region,+ activeWidgetId: region.enabledWidgetIds.includes(leftWidgetId) ? leftWidgetId : region.activeWidgetId,+ isCollapsed: false,+ }));+};+const openPanelForRegion = (layout: ProjectLayoutState, region: WidgetRegion): ProjectLayoutState => ({...layout,panels: {@@ -674,20 +715,28 @@ const updateActiveInvocation = (};});-const selectGraphForInvocation = (project: Project, invocation: InvocationRoute): GraphContract => {- const widgetGraph = project.widgetGraphs[invocation.sourceId as WidgetId];-- return widgetGraph ? cloneGraph(widgetGraph) : cloneGraph(project.projectGraph);-};-const compileInvocationSnapshot = (project: Project,route: InvocationRoute): { graph: GraphContract; widgetStates: Record<WidgetId, WidgetStateContract> } | null => {const widgetStates = cloneWidgetStates(project.widgetStates);+ if (route.sourceId === 'project-graph') {+ // Compiles the workflow document into an immutable snapshot. Templates are+ // read imperatively; route validation already guaranteed they are loaded.+ const templatesSnapshot = getInvocationTemplatesSnapshot();++ if (templatesSnapshot.status !== 'loaded') {+ return null;+ }++ return { graph: compileProjectGraph(project.projectGraph, templatesSnapshot.templates), widgetStates };+ }+if (route.sourceId !== 'generate') {- return { graph: selectGraphForInvocation(project, route), widgetStates };+ const widgetGraph = project.widgetGraphs[route.sourceId as WidgetId];++ return widgetGraph ? { graph: cloneGraph(widgetGraph), widgetStates } : null;}const values = normalizeGenerateWidgetValues(project.widgetStates.generate.values);@@ -962,18 +1011,13 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)}case 'applyPreset': {const preset = getLayoutPreset(action.presetId);- const widgetId = getCenterWidgetIdFromViewId(preset.initialLayout.centerViewId);const nextState = updateActiveLayout(state, () => ({...preset.initialLayout,panels: { ...preset.initialLayout.panels },}));return {- ...updateActiveWidgetRegion(nextState, 'center', (region) => ({- ...region,- activeWidgetId: region.enabledWidgetIds.includes(widgetId) ? widgetId : region.activeWidgetId,- isCollapsed: false,- })),+ ...applyPresetRegionFocus(nextState, preset),account: { ...state.account, activeLayoutPresetId: action.presetId },};}@@ -982,16 +1026,11 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)state.projects.find((project) => project.id === state.activeProjectId)?.layout.presetId ??state.account.activeLayoutPresetId);- const widgetId = getCenterWidgetIdFromViewId(preset.initialLayout.centerViewId);const nextState = updateActiveLayout(state, () => {return { ...preset.initialLayout, panels: { ...preset.initialLayout.panels } };});- return updateActiveWidgetRegion(nextState, 'center', (region) => ({- ...region,- activeWidgetId: region.enabledWidgetIds.includes(widgetId) ? widgetId : region.activeWidgetId,- isCollapsed: false,- }));+ return applyPresetRegionFocus(nextState, preset);}case 'recoverShellLayout': {return updateActiveLayout(state, (layout) => ({@@ -1129,6 +1168,127 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)},}));}+ case 'patchWidgetValues': {+ // Generic widget-owned UI state (panel modes, tabs, sizes). Not undoable.+ return updateActiveProject(state, (project) => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ [action.widgetId]: {+ ...project.widgetStates[action.widgetId],+ values: { ...project.widgetStates[action.widgetId].values, ...action.values },+ },+ },+ }));+ }+ case 'applyProjectGraphAction': {+ return updateActiveProject(state, (project) => {+ const projectGraph = projectGraphReducer(project.projectGraph, action.action);++ if (projectGraph === project.projectGraph) {+ return project;+ }++ const undoLabel = getProjectGraphUndoLabel(action.action);+ const nextProject = undoLabel ? pushUndo(project, undoLabel) : project;+ // Meaningful workflow edits are high-confidence source events: they+ // steer the global Invoke route to the project graph unless locked.+ const shouldAutoSetSource =+ !project.invocation.sourceLocked &&+ project.invocation.sourceId !== 'project-graph' &&+ isHighConfidenceGraphEdit(action.action) &&+ isInvocationSourceAvailable('project-graph');++ return {+ ...nextProject,+ invocation: shouldAutoSetSource+ ? { ...nextProject.invocation, sourceId: 'project-graph' }+ : nextProject.invocation,+ projectGraph,+ };+ });+ }+ case 'replaceProjectGraph': {+ const nextState = updateActiveProject(state, (project) => {+ const nextProject = pushUndo(project, 'Replace project graph');++ return {+ ...nextProject,+ events: [+ {+ createdAt: now(),+ id: createId('event'),+ summary: `Replaced the project graph with "${action.document.name || 'Untitled Workflow'}" (${action.label})`,+ type: 'graph-replaced',+ },+ ...nextProject.events,+ ],+ graphHistory: [+ createDocumentHistorySnapshot(`Before: ${action.label}`, project.projectGraph),+ ...nextProject.graphHistory,+ ].slice(0, HISTORY_LIMIT),+ projectGraph: cloneProjectGraph(action.document),+ };+ });+ const activeProject = nextState.projects.find((project) => project.id === nextState.activeProjectId);++ return addNotification(+ nextState,+ createNotification({+ kind: 'info',+ message: `The previous project graph was saved to graph history.`,+ projectId: activeProject?.id,+ title: `Project graph replaced (${action.label})`,+ })+ );+ }+ case 'saveProjectGraphSnapshot': {+ return updateActiveProject(state, (project) => ({+ ...project,+ events: [+ {+ createdAt: now(),+ id: createId('event'),+ summary: `Saved a graph history snapshot of "${project.projectGraph.name || 'Untitled Workflow'}"`,+ type: 'graph-snapshot-saved',+ },+ ...project.events,+ ],+ graphHistory: [+ createDocumentHistorySnapshot(+ `Manual save: ${project.projectGraph.name || 'Untitled Workflow'}`,+ project.projectGraph+ ),+ ...project.graphHistory,+ ].slice(0, HISTORY_LIMIT),+ }));+ }+ case 'restoreProjectGraphSnapshot': {+ return updateActiveProject(state, (project) => {+ const snapshot = project.graphHistory.find((entry) => entry.id === action.snapshotId);++ if (!snapshot?.document) {+ return project;+ }++ const nextProject = pushUndo(project, 'Restore graph history snapshot');++ return {+ ...nextProject,+ graphHistory: [+ createDocumentHistorySnapshot('Before restore', project.projectGraph),+ ...nextProject.graphHistory,+ ].slice(0, HISTORY_LIMIT),+ projectGraph: cloneProjectGraph(normalizeProjectGraph(snapshot.document)),+ };+ });+ }+ case 'setProjectGraphLibraryBinding': {+ return updateActiveProject(state, (project) => ({+ ...project,+ projectGraph: { ...project.projectGraph, libraryWorkflowId: action.libraryWorkflowId },+ }));+ }case 'submitInvocationSnapshot': {const beforeProject = state.projects.find((project) => project.id === state.activeProjectId);const nextState = updateActiveProject(state, (project) =>diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.tsnew file mode 100644index 0000000000..4a8aa3e148--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it } from 'vitest';++import { compileProjectGraph, getProjectGraphReadiness } from './buildGraph';+import { buildInvocationNode, buildNotesNode, createProjectGraph, projectGraphReducer } from './document';+import type { InvocationTemplatesSnapshot } from './templates';+import type { FieldInputTemplate, InvocationTemplate, ProjectGraphState } from './types';++const input = (name: string, overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name,+ options: null,+ required: false,+ title: name,+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ ...overrides,+});++const template = (type: string, inputs: Record<string, FieldInputTemplate>): InvocationTemplate => ({+ category: 'test',+ classification: 'stable',+ description: '',+ inputs,+ nodePack: 'invokeai',+ outputs: {+ out: {+ description: '',+ name: 'out',+ title: 'Out',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ },+ },+ outputType: `${type}_output`,+ tags: [],+ title: type,+ type,+ useCache: true,+ version: '1.0.0',+});++const templates = {+ sink: template('sink', {+ board: input('board', { type: { batch: false, cardinality: 'SINGLE', name: 'BoardField' } }),+ text: input('text', { required: true }),+ }),+ source: template('source', { value: input('value', { default: 'hello', required: true }) }),+};++const loadedSnapshot: InvocationTemplatesSnapshot = { error: null, status: 'loaded', templates };++const buildDocument = (): { doc: ProjectGraphState; sinkId: string; sourceId: string } => {+ const sourceNode = buildInvocationNode(templates.source, { x: 0, y: 0 });+ const sinkNode = buildInvocationNode(templates.sink, { x: 10, y: 0 });+ let doc = createProjectGraph('compile-test');++ doc = projectGraphReducer(doc, { node: sourceNode, type: 'addNode' });+ doc = projectGraphReducer(doc, { node: sinkNode, type: 'addNode' });+ doc = projectGraphReducer(doc, { node: buildNotesNode({ x: 0, y: 100 }), type: 'addNode' });+ doc = projectGraphReducer(doc, {+ edge: {+ id: 'e1',+ source: sourceNode.id,+ sourceHandle: 'out',+ target: sinkNode.id,+ targetHandle: 'text',+ type: 'default',+ },+ type: 'addEdge',+ });++ return { doc, sinkId: sinkNode.id, sourceId: sourceNode.id };+};++describe('getProjectGraphReadiness', () => {+ it('requires loaded templates and at least one node', () => {+ const empty = createProjectGraph('empty');++ expect(getProjectGraphReadiness(empty, { error: null, status: 'loading', templates: {} }).reasons[0]).toMatch(+ /still loading/+ );+ expect(getProjectGraphReadiness(empty, loadedSnapshot).reasons[0]).toMatch(/no nodes/);+ });++ it('is ready when required inputs are connected or filled', () => {+ const { doc } = buildDocument();++ expect(getProjectGraphReadiness(doc, loadedSnapshot)).toEqual({ canInvoke: true, reasons: [] });+ });++ it('reports missing required inputs and unknown node types', () => {+ const { doc, sourceId } = buildDocument();+ const withEmptyValue = projectGraphReducer(doc, {+ fieldName: 'value',+ nodeId: sourceId,+ type: 'setFieldValue',+ value: '',+ });++ expect(getProjectGraphReadiness(withEmptyValue, loadedSnapshot).reasons[0]).toMatch(/missing required input/);++ const unknownTemplates: InvocationTemplatesSnapshot = {+ error: null,+ status: 'loaded',+ templates: { source: templates.source },+ };++ expect(getProjectGraphReadiness(doc, unknownTemplates).reasons[0]).toMatch(/Unknown node type "sink"/);+ });+});++describe('compileProjectGraph', () => {+ it('compiles nodes and edges, omitting notes nodes and connected direct values', () => {+ const { doc, sinkId, sourceId } = buildDocument();+ const withStaleValue = projectGraphReducer(doc, {+ fieldName: 'text',+ nodeId: sinkId,+ type: 'setFieldValue',+ value: 'stale direct value',+ });+ const compiled = compileProjectGraph(withStaleValue, templates);+ const backendGraph = compiled.backendGraph;++ expect(backendGraph).toBeDefined();+ expect(Object.keys(backendGraph?.nodes ?? {}).sort()).toEqual([sinkId, sourceId].sort());+ expect(backendGraph?.nodes[sourceId]).toMatchObject({ type: 'source', use_cache: true, value: 'hello' });+ // The connected input's direct value must not be sent alongside the edge.+ expect(backendGraph?.nodes[sinkId]).not.toHaveProperty('text');+ expect(backendGraph?.edges).toEqual([+ { destination: { field: 'text', node_id: sinkId }, source: { field: 'out', node_id: sourceId } },+ ]);+ });++ it('omits auto/none board sentinels and keeps explicit boards', () => {+ const { doc, sinkId } = buildDocument();+ const withAutoBoard = projectGraphReducer(doc, {+ fieldName: 'board',+ nodeId: sinkId,+ type: 'setFieldValue',+ value: 'auto',+ });++ expect(compileProjectGraph(withAutoBoard, templates).backendGraph?.nodes[sinkId]).not.toHaveProperty('board');++ const withExplicitBoard = projectGraphReducer(doc, {+ fieldName: 'board',+ nodeId: sinkId,+ type: 'setFieldValue',+ value: { board_id: 'board-1' },+ });++ expect(compileProjectGraph(withExplicitBoard, templates).backendGraph?.nodes[sinkId]).toMatchObject({+ board: { board_id: 'board-1' },+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.tsnew file mode 100644index 0000000000..1f303f5dd1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts@@ -0,0 +1,202 @@+import type { BackendGraphContract, GraphContract } from '../types';+import { createWorkflowId } from './document';+import type { InvocationTemplatesSnapshot } from './templates';+import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState, WorkflowInvocationNode } from './types';+import { isInvocationNode } from './types';+import { hasAnyCycle } from './validation';++/**+ * Compiles the project graph document into the immutable, queue-facing+ * `GraphContract`. Ported from the legacy `buildNodesGraph`, minus connector+ * resolution (connectors are not part of the v7 document) and batch handling+ * (batch/generator nodes are rejected by readiness until batching lands).+ */++/** Client-resolved batch/generator nodes from the legacy editor; executing them server-side is meaningless. */+const UNSUPPORTED_NODE_TYPES = new Set([+ 'float_batch',+ 'float_generator',+ 'image_batch',+ 'image_generator',+ 'integer_batch',+ 'integer_generator',+ 'string_batch',+ 'string_generator',+]);++const getExecutableNodes = (document: ProjectGraphState): WorkflowInvocationNode[] =>+ document.nodes.filter(isInvocationNode);++const isEmptyValue = (value: unknown): boolean =>+ value === undefined || value === null || (typeof value === 'string' && value.trim() === '');++const getNodeDisplayName = (node: WorkflowInvocationNode, templates: InvocationTemplates): string =>+ node.data.label || templates[node.data.type]?.title || node.data.type;++/**+ * Translates a board field value to the backend shape: `auto` and `none`+ * sentinels are omitted so the backend applies its default board behavior.+ */+const toBoardGraphValue = (value: unknown): unknown => {+ if (value === 'auto' || value === 'none' || isEmptyValue(value)) {+ return undefined;+ }++ return value;+};++export interface ProjectGraphReadiness {+ canInvoke: boolean;+ reasons: string[];+}++export const getProjectGraphReadiness = (+ document: ProjectGraphState,+ templatesSnapshot: InvocationTemplatesSnapshot+): ProjectGraphReadiness => {+ if (templatesSnapshot.status === 'error') {+ return { canInvoke: false, reasons: ['Node definitions failed to load from the backend.'] };+ }++ if (templatesSnapshot.status !== 'loaded') {+ return { canInvoke: false, reasons: ['Node definitions are still loading.'] };+ }++ const templates = templatesSnapshot.templates;+ const executableNodes = getExecutableNodes(document);++ if (executableNodes.length === 0) {+ return { canInvoke: false, reasons: ['The project graph has no nodes. Add nodes in the Workflow view.'] };+ }++ const reasons: string[] = [];+ const connectedInputs = new Set(document.edges.map((edge) => `${edge.target}:${edge.targetHandle}`));++ for (const node of executableNodes) {+ const template = templates[node.data.type];++ if (!template) {+ reasons.push(`Unknown node type "${node.data.type}".`);+ continue;+ }++ if (UNSUPPORTED_NODE_TYPES.has(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}".`);+ continue;+ }++ if (isEmptyValue(node.data.inputs[inputTemplate.name]?.value)) {+ reasons.push(`"${getNodeDisplayName(node, templates)}" is missing required input "${inputTemplate.title}".`);+ }+ }+ }++ if (hasAnyCycle(document.nodes, document.edges)) {+ reasons.push('The project graph contains a cycle.');+ }++ return { canInvoke: reasons.length === 0, reasons };+};++const toGraphInputValue = (inputTemplate: FieldInputTemplate, value: unknown): unknown => {+ if (inputTemplate.type.name === 'BoardField') {+ return toBoardGraphValue(value);+ }++ return value;+};++/** Compiles the document into a `GraphContract` carrying the executable backend graph. */+export const compileProjectGraph = (document: ProjectGraphState, templates: InvocationTemplates): GraphContract => {+ const executableNodes = getExecutableNodes(document).filter((node) => templates[node.data.type] !== undefined);+ const executableNodeIds = new Set(executableNodes.map((node) => node.id));+ const backendGraph: BackendGraphContract = { edges: [], id: createWorkflowId('workflow-graph'), nodes: {} };++ for (const node of executableNodes) {+ const template = templates[node.data.type] as NonNullable<(typeof templates)[string]>;+ const graphNode: Record<string, unknown> = {+ id: node.id,+ is_intermediate: node.data.isIntermediate,+ type: node.data.type,+ use_cache: node.data.useCache,+ };++ for (const instance of Object.values(node.data.inputs)) {+ const inputTemplate = template.inputs[instance.name];++ if (!inputTemplate || instance.value === undefined) {+ continue;+ }++ const value = toGraphInputValue(inputTemplate, instance.value);++ if (value !== undefined) {+ graphNode[instance.name] = value;+ }+ }++ backendGraph.nodes[node.id] = graphNode as BackendGraphContract['nodes'][string];+ }++ const seenEdgeKeys = new Set<string>();++ for (const edge of document.edges) {+ if (!executableNodeIds.has(edge.source) || !executableNodeIds.has(edge.target)) {+ continue;+ }++ const key = `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`;++ if (seenEdgeKeys.has(key)) {+ continue;+ }++ seenEdgeKeys.add(key);+ backendGraph.edges.push({+ destination: { field: edge.targetHandle, node_id: edge.target },+ source: { field: edge.sourceHandle, node_id: edge.source },+ });++ // A connected input always wins over a stale direct value; sending both+ // would let pydantic reject the node on the ignored direct value.+ const targetNode = backendGraph.nodes[edge.target];++ if (targetNode) {+ delete targetNode[edge.targetHandle];+ }+ }++ return {+ backendGraph,+ edges: document.edges.map((edge) => ({+ id: edge.id,+ sourceField: edge.sourceHandle,+ sourceNodeId: edge.source,+ targetField: edge.targetHandle,+ targetNodeId: edge.target,+ })),+ id: backendGraph.id,+ label: document.name || 'Workflow',+ nodes: executableNodes.map((node) => ({+ id: node.id,+ inputs: Object.fromEntries(Object.values(node.data.inputs).map((instance) => [instance.name, instance.value])),+ type: node.data.type,+ })),+ updatedAt: new Date().toISOString(),+ version: 1,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/document.test.tsnew file mode 100644index 0000000000..4c114ec90a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/document.test.ts@@ -0,0 +1,284 @@+import { describe, expect, it } from 'vitest';++import {+ buildInvocationNode,+ createProjectGraph,+ getFormChildren,+ isFieldExposed,+ normalizeProjectGraph,+ projectGraphReducer,+} from './document';+import type { InvocationTemplate, ProjectGraphState, WorkflowEdge } from './types';++const template: InvocationTemplate = {+ category: 'math',+ classification: 'stable',+ description: '',+ inputs: {+ a: {+ default: 1,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name: 'a',+ options: null,+ required: false,+ title: 'A',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ },+ },+ nodePack: 'invokeai',+ outputs: {+ value: {+ description: '',+ name: 'value',+ title: 'Value',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ },+ },+ outputType: 'integer_output',+ tags: [],+ title: 'Add',+ type: 'add',+ useCache: true,+ version: '1.0.0',+};++const createDocWithNodes = (): { doc: ProjectGraphState; nodeAId: string; nodeBId: string } => {+ const nodeA = buildInvocationNode(template, { x: 0, y: 0 });+ const nodeB = buildInvocationNode(template, { x: 100, y: 0 });+ let doc = createProjectGraph('test-graph');++ doc = projectGraphReducer(doc, { node: nodeA, type: 'addNode' });+ doc = projectGraphReducer(doc, { node: nodeB, type: 'addNode' });++ return { doc, nodeAId: nodeA.id, nodeBId: nodeB.id };+};++const createEdge = (source: string, target: string): WorkflowEdge => ({+ id: `edge-${source}-${target}`,+ source,+ sourceHandle: 'value',+ target,+ targetHandle: 'a',+ type: 'default',+});++describe('projectGraphReducer', () => {+ it('builds nodes from templates with default input values', () => {+ const node = buildInvocationNode(template, { x: 5, y: 6 });++ expect(node.data.inputs.a?.value).toBe(1);+ expect(node.data.useCache).toBe(true);+ expect(node.position).toEqual({ x: 5, y: 6 });+ });++ it('removing nodes drops their edges and exposed form fields', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ let next = projectGraphReducer(doc, { edge: createEdge(nodeAId, nodeBId), type: 'addEdge' });++ next = projectGraphReducer(next, { fieldIdentifier: { fieldName: 'a', nodeId: nodeBId }, type: 'exposeField' });++ expect(next.edges).toHaveLength(1);+ expect(isFieldExposed(next.form, { fieldName: 'a', nodeId: nodeBId })).toBe(true);++ next = projectGraphReducer(next, { nodeIds: [nodeBId], type: 'removeNodes' });++ expect(next.nodes.map((node) => node.id)).toEqual([nodeAId]);+ expect(next.edges).toEqual([]);+ expect(isFieldExposed(next.form, { fieldName: 'a', nodeId: nodeBId })).toBe(false);+ });++ it('adds pasted nodes and their internal edges in one action', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ const pastedA = buildInvocationNode(template, { x: 32, y: 32 });+ const pastedB = buildInvocationNode(template, { x: 132, y: 32 });+ const next = projectGraphReducer(doc, {+ edges: [createEdge(pastedA.id, pastedB.id)],+ nodes: [pastedA, pastedB],+ type: 'addGraphElements',+ });++ expect(next.nodes.map((node) => node.id)).toEqual([nodeAId, nodeBId, pastedA.id, pastedB.id]);+ expect(next.edges).toHaveLength(1);+ });++ it('addGraphElements drops colliding node ids and their edges', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ const existingNode = doc.nodes[0];+ const freshNode = buildInvocationNode(template, { x: 64, y: 64 });+ const next = projectGraphReducer(doc, {+ edges: [createEdge(nodeAId, freshNode.id)],+ nodes: [existingNode!, freshNode],+ type: 'addGraphElements',+ });++ expect(next.nodes.map((node) => node.id)).toEqual([nodeAId, nodeBId, freshNode.id]);+ // The edge referenced a dropped duplicate, so it is dropped too.+ expect(next.edges).toEqual([]);+ });++ it('connecting an already-connected input replaces the existing edge', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ let next = projectGraphReducer(doc, { edge: createEdge(nodeAId, nodeBId), type: 'addEdge' });+ const replacement = { ...createEdge(nodeAId, nodeBId), id: 'edge-replacement' };++ next = projectGraphReducer(next, { edge: replacement, type: 'addEdge' });++ expect(next.edges).toHaveLength(1);+ expect(next.edges[0]?.id).toBe('edge-replacement');+ });++ it('sets field values without disturbing other inputs', () => {+ const { doc, nodeAId } = createDocWithNodes();+ const next = projectGraphReducer(doc, { fieldName: 'a', nodeId: nodeAId, type: 'setFieldValue', value: 42 });+ const node = next.nodes.find((candidate) => candidate.id === nodeAId);++ expect(node?.type === 'invocation' && node.data.inputs.a?.value).toBe(42);+ });++ it('sets and clears field description overrides', () => {+ const { doc, nodeAId } = createDocWithNodes();+ let next = projectGraphReducer(doc, {+ description: 'Custom help text',+ fieldName: 'a',+ nodeId: nodeAId,+ type: 'setFieldDescription',+ });+ const getInstance = (document: typeof next) => {+ const node = document.nodes.find((candidate) => candidate.id === nodeAId);++ return node?.type === 'invocation' ? node.data.inputs.a : undefined;+ };++ expect(getInstance(next)?.description).toBe('Custom help text');++ next = projectGraphReducer(next, { description: '', fieldName: 'a', nodeId: nodeAId, type: 'setFieldDescription' });++ expect(getInstance(next)?.description).toBeUndefined();+ });++ it('exposing a field twice is a no-op, and form elements reorder', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ let next = projectGraphReducer(doc, { fieldIdentifier: { fieldName: 'a', nodeId: nodeAId }, type: 'exposeField' });++ next = projectGraphReducer(next, { fieldIdentifier: { fieldName: 'a', nodeId: nodeAId }, type: 'exposeField' });+ next = projectGraphReducer(next, { fieldIdentifier: { fieldName: 'a', nodeId: nodeBId }, type: 'exposeField' });++ const childrenBefore = getFormChildren(next.form).map((element) => element.id);++ expect(childrenBefore).toHaveLength(2);++ const lastElementId = childrenBefore[1] as string;++ next = projectGraphReducer(next, { direction: -1, elementId: lastElementId, type: 'moveFormElement' });++ expect(getFormChildren(next.form).map((element) => element.id)).toEqual([lastElementId, childrenBefore[0]]);+ });++ it('reparents form elements via moveFormElementTo with index adjustment and cycle guards', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ let next = projectGraphReducer(doc, { fieldIdentifier: { fieldName: 'a', nodeId: nodeAId }, type: 'exposeField' });++ next = projectGraphReducer(next, { fieldIdentifier: { fieldName: 'a', nodeId: nodeBId }, type: 'exposeField' });+ next = projectGraphReducer(next, { elementType: 'container', layout: 'row', type: 'addFormElement' });++ const rootId = next.form.rootElementId;+ const [fieldA, fieldB, container] = getFormChildren(next.form);++ expect(container?.type).toBe('container');++ // Reorder within the root: move fieldA after fieldB (index adjusts for removal).+ next = projectGraphReducer(next, {+ elementId: fieldA?.id ?? '',+ index: 2,+ parentId: rootId,+ type: 'moveFormElementTo',+ });++ expect(getFormChildren(next.form).map((element) => element.id)).toEqual([fieldB?.id, fieldA?.id, container?.id]);++ // Reparent fieldB into the container.+ next = projectGraphReducer(next, {+ elementId: fieldB?.id ?? '',+ index: 0,+ parentId: container?.id ?? '',+ type: 'moveFormElementTo',+ });++ const containerElement = next.form.elements[container?.id ?? ''];++ expect(containerElement?.type === 'container' && containerElement.data.children).toEqual([fieldB?.id]);+ expect(next.form.elements[fieldB?.id ?? '']?.parentId).toBe(container?.id);++ // A container cannot be dropped into its own subtree.+ const guarded = projectGraphReducer(next, {+ elementId: container?.id ?? '',+ index: 0,+ parentId: container?.id ?? '',+ type: 'moveFormElementTo',+ });++ expect(guarded).toBe(next);+ });++ it('toggles container layout and node-field descriptions', () => {+ const { doc, nodeAId } = createDocWithNodes();+ let next = projectGraphReducer(doc, { elementType: 'container', layout: 'column', type: 'addFormElement' });++ next = projectGraphReducer(next, { fieldIdentifier: { fieldName: 'a', nodeId: nodeAId }, type: 'exposeField' });++ const [container, field] = getFormChildren(next.form);++ next = projectGraphReducer(next, { elementId: container?.id ?? '', layout: 'row', type: 'setContainerLayout' });++ const updatedContainer = next.form.elements[container?.id ?? ''];++ expect(updatedContainer?.type === 'container' && updatedContainer.data.layout).toBe('row');++ next = projectGraphReducer(next, {+ elementId: field?.id ?? '',+ showDescription: true,+ type: 'setNodeFieldShowDescription',+ });++ const updatedField = next.form.elements[field?.id ?? ''];++ expect(updatedField?.type === 'node-field' && updatedField.data.showDescription).toBe(true);+ });++ it('updates metadata via patch', () => {+ const { doc } = createDocWithNodes();+ const next = projectGraphReducer(doc, { patch: { author: 'josh', name: 'My Flow' }, type: 'setMetadata' });++ expect(next.name).toBe('My Flow');+ expect(next.author).toBe('josh');+ });+});++describe('normalizeProjectGraph', () => {+ it('passes through current documents', () => {+ const doc = createProjectGraph('keep-me');++ expect(normalizeProjectGraph(doc)).toBe(doc);+ });++ it('replaces the Phase-1 placeholder graph with an empty document, preserving the id', () => {+ const normalized = normalizeProjectGraph({ edges: [], id: 'legacy-id', label: 'Old', nodes: [], version: 1 });++ expect(normalized.version).toBe(2);+ expect(normalized.id).toBe('legacy-id');+ expect(normalized.nodes).toEqual([]);+ expect(normalized.form.elements[normalized.form.rootElementId]?.type).toBe('container');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/document.ts b/invokeai/frontend/webv2/src/workbench/workflows/document.tsnew file mode 100644index 0000000000..8ee102bcb8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/document.ts@@ -0,0 +1,625 @@+import type {+ ContainerFormElement,+ FieldIdentifier,+ InvocationTemplate,+ ProjectGraphState,+ WorkflowCurrentImageNode,+ WorkflowEdge,+ WorkflowFieldInstance,+ WorkflowForm,+ WorkflowFormElement,+ WorkflowInvocationNode,+ WorkflowMetadata,+ WorkflowNode,+ WorkflowNotesNode,+ XYPosition,+} from './types';+import { isInvocationNode, isNotesNode } from './types';++/**+ * Pure operations on the project graph document. The workbench reducer+ * delegates all workflow edits to `projectGraphReducer` so the document logic+ * stays testable and `workbenchState.ts` only grows one action case.+ */++const now = (): string => new Date().toISOString();++export const createWorkflowId = (prefix: string): string =>+ `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;++export const createWorkflowForm = (): WorkflowForm => {+ const rootElementId = createWorkflowId('container');+ const root: ContainerFormElement = {+ data: { children: [], layout: 'column' },+ id: rootElementId,+ type: 'container',+ };++ return { elements: { [rootElementId]: root }, rootElementId };+};++export const createProjectGraph = (id: string, name = 'Untitled Workflow'): ProjectGraphState => ({+ author: '',+ contact: '',+ description: '',+ edges: [],+ form: createWorkflowForm(),+ id,+ name,+ nodes: [],+ notes: '',+ tags: '',+ updatedAt: now(),+ version: 2,+ workflowVersion: '1.0.0',+});++export const cloneProjectGraph = (document: ProjectGraphState): ProjectGraphState => structuredClone(document);++/** Accepts any persisted `projectGraph` shape and yields a current document, preserving the id. */+export const normalizeProjectGraph = (candidate: unknown): ProjectGraphState => {+ if (typeof candidate === 'object' && candidate !== null && (candidate as ProjectGraphState).version === 2) {+ return candidate as ProjectGraphState;+ }++ const legacyId =+ typeof (candidate as { id?: unknown } | null)?.id === 'string' ? (candidate as { id: string }).id : null;++ return createProjectGraph(legacyId ?? createWorkflowId('project-graph'));+};++export const buildInvocationNode = (template: InvocationTemplate, position: XYPosition): WorkflowInvocationNode => {+ const inputs: Record<string, WorkflowFieldInstance> = {};++ for (const inputTemplate of Object.values(template.inputs)) {+ inputs[inputTemplate.name] = {+ label: '',+ name: inputTemplate.name,+ value: inputTemplate.default === undefined ? undefined : structuredClone(inputTemplate.default),+ };+ }++ return {+ data: {+ inputs,+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: template.nodePack,+ notes: '',+ type: template.type,+ useCache: template.useCache,+ version: template.version,+ },+ id: createWorkflowId(template.type),+ position,+ type: 'invocation',+ };+};++export const buildNotesNode = (position: XYPosition): WorkflowNotesNode => ({+ data: { label: 'Notes', notes: '' },+ id: createWorkflowId('notes'),+ position,+ type: 'notes',+});++export const buildCurrentImageNode = (position: XYPosition): WorkflowCurrentImageNode => ({+ data: { label: 'Current Image' },+ id: createWorkflowId('current-image'),+ position,+ type: 'current_image',+});++// #region Form manipulation++const getRootContainer = (form: WorkflowForm): ContainerFormElement => {+ const root = form.elements[form.rootElementId];++ if (root?.type === 'container') {+ return root;+ }++ // A malformed form (bad import, old persistence) recovers as an empty root.+ const recovered = createWorkflowForm();++ return recovered.elements[recovered.rootElementId] as ContainerFormElement;+};++const collectDescendantIds = (form: WorkflowForm, elementId: string): string[] => {+ const element = form.elements[elementId];++ if (!element || element.type !== 'container') {+ return [elementId];+ }++ return [elementId, ...element.data.children.flatMap((childId) => collectDescendantIds(form, childId))];+};++const appendToRoot = (form: WorkflowForm, element: WorkflowFormElement): WorkflowForm => {+ const root = getRootContainer(form);+ const rooted = { ...element, parentId: root.id };++ return {+ elements: {+ ...form.elements,+ [root.id]: { ...root, data: { ...root.data, children: [...root.data.children, rooted.id] } },+ [rooted.id]: rooted,+ },+ rootElementId: root.id,+ };+};++const removeFormElement = (form: WorkflowForm, elementId: string): WorkflowForm => {+ if (elementId === form.rootElementId || !form.elements[elementId]) {+ return form;+ }++ const removedIds = new Set(collectDescendantIds(form, elementId));+ const elements: Record<string, WorkflowFormElement> = {};++ for (const [id, element] of Object.entries(form.elements)) {+ if (removedIds.has(id)) {+ continue;+ }++ elements[id] =+ element.type === 'container'+ ? {+ ...element,+ data: { ...element.data, children: element.data.children.filter((childId) => !removedIds.has(childId)) },+ }+ : element;+ }++ return { ...form, elements };+};++/**+ * Reparents an element to `parentId` at `index` (the drag-and-drop primitive).+ * No-ops when the move is impossible: unknown ids, non-container targets, or+ * dropping a container into its own subtree.+ */+const moveFormElementTo = (form: WorkflowForm, elementId: string, parentId: string, index: number): WorkflowForm => {+ const element = form.elements[elementId];+ const nextParent = form.elements[parentId];++ if (+ !element ||+ elementId === form.rootElementId ||+ !nextParent ||+ nextParent.type !== 'container' ||+ collectDescendantIds(form, elementId).includes(parentId)+ ) {+ return form;+ }++ const previousParent = element.parentId ? form.elements[element.parentId] : undefined;++ if (!previousParent || previousParent.type !== 'container') {+ return form;+ }++ const previousIndex = previousParent.data.children.indexOf(elementId);+ const withoutElement = previousParent.data.children.filter((childId) => childId !== elementId);+ // Removing the element above the drop point shifts the target index back one.+ const adjustedIndex =+ previousParent.id === nextParent.id && previousIndex !== -1 && previousIndex < index ? index - 1 : index;+ const targetChildren = previousParent.id === nextParent.id ? withoutElement : [...nextParent.data.children];+ const clampedIndex = Math.min(Math.max(0, adjustedIndex), targetChildren.length);++ targetChildren.splice(clampedIndex, 0, elementId);++ const elements: Record<string, WorkflowFormElement> = {+ ...form.elements,+ [elementId]: { ...element, parentId: nextParent.id },+ [previousParent.id]: { ...previousParent, data: { ...previousParent.data, children: withoutElement } },+ };++ elements[nextParent.id] = {+ ...(elements[nextParent.id] as ContainerFormElement),+ data: { ...(elements[nextParent.id] as ContainerFormElement).data, children: targetChildren },+ };++ return { ...form, elements };+};++const moveFormElement = (form: WorkflowForm, elementId: string, direction: -1 | 1): WorkflowForm => {+ const element = form.elements[elementId];+ const parent = element?.parentId ? form.elements[element.parentId] : getRootContainer(form);++ if (!element || !parent || parent.type !== 'container') {+ return form;+ }++ const index = parent.data.children.indexOf(elementId);+ const nextIndex = index + direction;++ if (index === -1 || nextIndex < 0 || nextIndex >= parent.data.children.length) {+ return form;+ }++ const children = [...parent.data.children];++ children[index] = children[nextIndex] as string;+ children[nextIndex] = elementId;++ return {+ ...form,+ elements: { ...form.elements, [parent.id]: { ...parent, data: { ...parent.data, children } } },+ };+};++export const findNodeFieldElement = (+ form: WorkflowForm,+ fieldIdentifier: FieldIdentifier+): WorkflowFormElement | undefined =>+ Object.values(form.elements).find(+ (element) =>+ element.type === 'node-field' &&+ element.data.fieldIdentifier.nodeId === fieldIdentifier.nodeId &&+ element.data.fieldIdentifier.fieldName === fieldIdentifier.fieldName+ );++export const isFieldExposed = (form: WorkflowForm, fieldIdentifier: FieldIdentifier): boolean =>+ findNodeFieldElement(form, fieldIdentifier) !== undefined;++const removeNodeFieldElements = (form: WorkflowForm, removedNodeIds: Set<string>): WorkflowForm =>+ Object.values(form.elements)+ .filter((element) => element.type === 'node-field' && removedNodeIds.has(element.data.fieldIdentifier.nodeId))+ .reduce((nextForm, element) => removeFormElement(nextForm, element.id), form);++// #endregion++// #region Document reducer++export type ProjectGraphAction =+ | { type: 'addNode'; node: WorkflowNode }+ | { type: 'addGraphElements'; nodes: WorkflowNode[]; edges: WorkflowEdge[] }+ | { type: 'removeNodes'; nodeIds: string[] }+ | { type: 'setNodePosition'; nodeId: string; position: XYPosition }+ | { type: 'setNodeLabel'; nodeId: string; label: string }+ | { type: 'setNodeNotes'; nodeId: string; notes: string }+ | { type: 'setNodeIsOpen'; nodeId: string; isOpen: boolean }+ | { type: 'setNodeIsIntermediate'; nodeId: string; isIntermediate: 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 }+ | { type: 'addEdge'; edge: WorkflowEdge }+ | { type: 'removeEdges'; edgeIds: string[] }+ | { type: 'exposeField'; fieldIdentifier: FieldIdentifier }+ | { type: 'unexposeField'; fieldIdentifier: FieldIdentifier }+ | { type: 'removeFormElement'; elementId: string }+ | { type: 'moveFormElement'; elementId: string; direction: -1 | 1 }+ | { type: 'moveFormElementTo'; elementId: string; parentId: string; index: number }+ | {+ type: 'addFormElement';+ elementType: 'heading' | 'text' | 'divider' | 'container';+ content?: string;+ layout?: 'row' | 'column';+ }+ | { type: 'setFormElementContent'; elementId: string; content: string }+ | { type: 'setNodeFieldShowDescription'; elementId: string; showDescription: boolean }+ | { type: 'setContainerLayout'; elementId: string; layout: 'row' | 'column' }+ | { type: 'setMetadata'; patch: Partial<WorkflowMetadata> };++const undoLabels: Partial<Record<ProjectGraphAction['type'], string>> = {+ addEdge: 'Connect workflow fields',+ addFormElement: 'Edit workflow form',+ addGraphElements: 'Paste workflow nodes',+ addNode: 'Add workflow node',+ exposeField: 'Expose workflow field',+ moveFormElement: 'Edit workflow form',+ moveFormElementTo: 'Edit workflow form',+ removeEdges: 'Disconnect workflow fields',+ removeFormElement: 'Edit workflow form',+ removeNodes: 'Delete workflow nodes',+ setContainerLayout: 'Edit workflow form',+ setNodeFieldShowDescription: 'Edit workflow form',+ unexposeField: 'Remove workflow field from form',+};++/** Returns the project-undo label for an action, or null when the edit should not create an undo entry. */+export const getProjectGraphUndoLabel = (action: ProjectGraphAction): string | null => undoLabels[action.type] ?? null;++/** Edits meaningful enough to auto-select the project graph as the invocation source. */+export const isHighConfidenceGraphEdit = (action: ProjectGraphAction): boolean =>+ action.type === 'addNode' ||+ action.type === 'addGraphElements' ||+ action.type === 'removeNodes' ||+ action.type === 'addEdge' ||+ action.type === 'removeEdges' ||+ action.type === 'setFieldValue';++const updateNode = (+ document: ProjectGraphState,+ nodeId: string,+ getNode: (node: WorkflowNode) => WorkflowNode+): ProjectGraphState => ({+ ...document,+ nodes: document.nodes.map((node) => (node.id === nodeId ? getNode(node) : node)),+});++const updateInvocationNode = (+ document: ProjectGraphState,+ nodeId: string,+ getNode: (node: WorkflowInvocationNode) => WorkflowInvocationNode+): ProjectGraphState => updateNode(document, nodeId, (node) => (isInvocationNode(node) ? getNode(node) : node));++const setFieldInstance = (+ document: ProjectGraphState,+ nodeId: string,+ fieldName: string,+ getInstance: (instance: WorkflowFieldInstance) => WorkflowFieldInstance+): ProjectGraphState =>+ updateInvocationNode(document, nodeId, (node) => {+ const instance = node.data.inputs[fieldName] ?? { label: '', name: fieldName };++ return {+ ...node,+ data: { ...node.data, inputs: { ...node.data.inputs, [fieldName]: getInstance(instance) } },+ };+ });++export const projectGraphReducer = (document: ProjectGraphState, action: ProjectGraphAction): ProjectGraphState => {+ const next = applyProjectGraphAction(document, action);++ return next === document ? document : { ...next, updatedAt: now() };+};++const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGraphAction): ProjectGraphState => {+ switch (action.type) {+ case 'addNode': {+ return { ...document, nodes: [...document.nodes, action.node] };+ }+ case 'addGraphElements': {+ if (action.nodes.length === 0 && action.edges.length === 0) {+ return document;+ }++ // Guard against id collisions (a stale paste after an undo): existing+ // ids win, incoming duplicates are dropped along with their edges.+ const existingNodeIds = new Set(document.nodes.map((node) => node.id));+ const nodes = action.nodes.filter((node) => !existingNodeIds.has(node.id));+ const acceptedNodeIds = new Set(nodes.map((node) => node.id));+ const existingEdgeIds = new Set(document.edges.map((edge) => edge.id));+ const edges = action.edges.filter(+ (edge) => !existingEdgeIds.has(edge.id) && acceptedNodeIds.has(edge.source) && acceptedNodeIds.has(edge.target)+ );++ if (nodes.length === 0) {+ return document;+ }++ return { ...document, edges: [...document.edges, ...edges], nodes: [...document.nodes, ...nodes] };+ }+ case 'removeNodes': {+ const removedNodeIds = new Set(action.nodeIds);++ if (removedNodeIds.size === 0) {+ return document;+ }++ return {+ ...document,+ edges: document.edges.filter((edge) => !removedNodeIds.has(edge.source) && !removedNodeIds.has(edge.target)),+ form: removeNodeFieldElements(document.form, removedNodeIds),+ nodes: document.nodes.filter((node) => !removedNodeIds.has(node.id)),+ };+ }+ case 'setNodePosition': {+ return updateNode(document, action.nodeId, (node) => ({ ...node, position: { ...action.position } }));+ }+ case 'setNodeLabel': {+ // Narrowed per branch so TS keeps the node type / data correlation through the spread.+ return updateNode(document, action.nodeId, (node) => {+ if (isInvocationNode(node)) {+ return { ...node, data: { ...node.data, label: action.label } };+ }++ if (isNotesNode(node)) {+ return { ...node, data: { ...node.data, label: action.label } };+ }++ return { ...node, data: { ...node.data, label: action.label } };+ });+ }+ case 'setNodeNotes': {+ return updateNode(document, action.nodeId, (node) => {+ if (isInvocationNode(node)) {+ return { ...node, data: { ...node.data, notes: action.notes } };+ }++ if (isNotesNode(node)) {+ return { ...node, data: { ...node.data, notes: action.notes } };+ }++ return node;+ });+ }+ case 'setNodeIsOpen': {+ return updateInvocationNode(document, action.nodeId, (node) => ({+ ...node,+ data: { ...node.data, isOpen: action.isOpen },+ }));+ }+ case 'setNodeIsIntermediate': {+ return updateInvocationNode(document, action.nodeId, (node) => ({+ ...node,+ data: { ...node.data, isIntermediate: action.isIntermediate },+ }));+ }+ case 'setFieldValue': {+ return setFieldInstance(document, action.nodeId, action.fieldName, (instance) => ({+ ...instance,+ value: action.value,+ }));+ }+ case 'setFieldLabel': {+ return setFieldInstance(document, action.nodeId, action.fieldName, (instance) => ({+ ...instance,+ label: action.label,+ }));+ }+ case 'setFieldDescription': {+ // An emptied override falls back to the template description.+ return setFieldInstance(document, action.nodeId, action.fieldName, (instance) => ({+ ...instance,+ description: action.description || undefined,+ }));+ }+ case 'addEdge': {+ // A non-collect input holds at most one connection; connecting replaces it.+ const targetNode = document.nodes.find((node) => node.id === action.edge.target);+ const keepsExisting =+ targetNode &&+ isInvocationNode(targetNode) &&+ targetNode.data.type === 'collect' &&+ action.edge.targetHandle === 'item';+ const edges = keepsExisting+ ? document.edges+ : document.edges.filter(+ (edge) => !(edge.target === action.edge.target && edge.targetHandle === action.edge.targetHandle)+ );++ return { ...document, edges: [...edges, action.edge] };+ }+ case 'removeEdges': {+ const removedEdgeIds = new Set(action.edgeIds);++ if (removedEdgeIds.size === 0) {+ return document;+ }++ return { ...document, edges: document.edges.filter((edge) => !removedEdgeIds.has(edge.id)) };+ }+ case 'exposeField': {+ if (isFieldExposed(document.form, action.fieldIdentifier)) {+ return document;+ }++ return {+ ...document,+ form: appendToRoot(document.form, {+ data: { fieldIdentifier: { ...action.fieldIdentifier }, showDescription: false },+ id: createWorkflowId('node-field'),+ type: 'node-field',+ }),+ };+ }+ case 'unexposeField': {+ const element = findNodeFieldElement(document.form, action.fieldIdentifier);++ if (!element) {+ return document;+ }++ return { ...document, form: removeFormElement(document.form, element.id) };+ }+ case 'removeFormElement': {+ return { ...document, form: removeFormElement(document.form, action.elementId) };+ }+ case 'moveFormElement': {+ const form = moveFormElement(document.form, action.elementId, action.direction);++ return form === document.form ? document : { ...document, form };+ }+ case 'moveFormElementTo': {+ const form = moveFormElementTo(document.form, action.elementId, action.parentId, action.index);++ return form === document.form ? document : { ...document, form };+ }+ case 'addFormElement': {+ const element: WorkflowFormElement =+ action.elementType === 'divider'+ ? { id: createWorkflowId('divider'), type: 'divider' }+ : action.elementType === 'container'+ ? {+ data: { children: [], layout: action.layout ?? 'column' },+ id: createWorkflowId('container'),+ type: 'container',+ }+ : {+ data: { content: action.content ?? '' },+ id: createWorkflowId(action.elementType),+ type: action.elementType,+ };++ return { ...document, form: appendToRoot(document.form, element) };+ }+ case 'setFormElementContent': {+ const element = document.form.elements[action.elementId];++ if (!element || (element.type !== 'heading' && element.type !== 'text')) {+ return document;+ }++ return {+ ...document,+ form: {+ ...document.form,+ elements: {+ ...document.form.elements,+ [element.id]: { ...element, data: { ...element.data, content: action.content } },+ },+ },+ };+ }+ case 'setContainerLayout': {+ const element = document.form.elements[action.elementId];++ if (!element || element.type !== 'container') {+ return document;+ }++ return {+ ...document,+ form: {+ ...document.form,+ elements: {+ ...document.form.elements,+ [element.id]: { ...element, data: { ...element.data, layout: action.layout } },+ },+ },+ };+ }+ case 'setNodeFieldShowDescription': {+ const element = document.form.elements[action.elementId];++ if (!element || element.type !== 'node-field') {+ return document;+ }++ return {+ ...document,+ form: {+ ...document.form,+ elements: {+ ...document.form.elements,+ [element.id]: { ...element, data: { ...element.data, showDescription: action.showDescription } },+ },+ },+ };+ }+ case 'setMetadata': {+ return { ...document, ...action.patch };+ }+ }+};++// #endregion++/** Ordered, render-ready view of the form tree starting at the root. */+export const getFormChildren = (form: WorkflowForm, containerId?: string): WorkflowFormElement[] => {+ const container = form.elements[containerId ?? form.rootElementId];++ if (!container || container.type !== 'container') {+ return [];+ }++ return container.data.children.flatMap((childId) => {+ const child = form.elements[childId];++ return child ? [child] : [];+ });+};diff --git a/invokeai/frontend/webv2/src/workbench/workflows/templates.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/templates.test.tsnew file mode 100644index 0000000000..29ae6b8e6a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/templates.test.ts@@ -0,0 +1,170 @@+import { describe, expect, it } from 'vitest';++import { parseFieldType, parseOpenApiToTemplates } from './templates';++const openApiFixture = {+ components: {+ schemas: {+ AddInvocation: {+ category: 'math',+ class: 'invocation',+ classification: 'stable',+ description: 'Adds two numbers',+ node_pack: 'invokeai',+ output: { $ref: '#/components/schemas/IntegerOutput' },+ properties: {+ a: {+ default: 0,+ field_kind: 'input',+ input: 'any',+ orig_required: false,+ title: 'A',+ type: 'integer',+ ui_hidden: false,+ },+ b: {+ default: 0,+ field_kind: 'input',+ input: 'any',+ minimum: 0,+ orig_required: false,+ title: 'B',+ type: 'integer',+ ui_hidden: false,+ },+ id: { field_kind: 'internal', title: 'Id', type: 'string' },+ is_intermediate: { default: false, field_kind: 'internal', type: 'boolean' },+ type: { const: 'add', default: 'add', title: 'type' },+ use_cache: { default: true, field_kind: 'internal', type: 'boolean' },+ },+ tags: ['math'],+ title: 'Add Integers',+ type: 'object',+ version: '1.0.1',+ },+ DenoiseInvocation: {+ class: 'invocation',+ output: { $ref: '#/components/schemas/LatentsOutput' },+ properties: {+ latents: {+ anyOf: [{ $ref: '#/components/schemas/LatentsField' }, { type: 'null' }],+ field_kind: 'input',+ input: 'connection',+ orig_required: true,+ title: 'Latents',+ },+ prompts: {+ anyOf: [{ items: { type: 'string' }, type: 'array' }, { type: 'string' }],+ field_kind: 'input',+ orig_required: true,+ title: 'Prompts',+ },+ scheduler: {+ default: 'euler',+ enum: ['euler', 'ddim'],+ field_kind: 'input',+ orig_required: false,+ title: 'Scheduler',+ type: 'string',+ },+ type: { const: 'denoise', default: 'denoise', title: 'type' },+ use_cache: { default: true, field_kind: 'internal', type: 'boolean' },+ },+ title: 'DenoiseInvocation',+ type: 'object',+ },+ GraphInvocation: {+ class: 'invocation',+ output: { $ref: '#/components/schemas/IntegerOutput' },+ properties: {+ type: { const: 'graph', default: 'graph', title: 'type' },+ },+ title: 'Graph',+ type: 'object',+ },+ IntegerOutput: {+ class: 'output',+ properties: {+ type: { const: 'integer_output', default: 'integer_output' },+ value: { field_kind: 'output', title: 'Value', type: 'integer' },+ },+ type: 'object',+ },+ LatentsOutput: {+ class: 'output',+ properties: {+ latents: {+ allOf: [{ $ref: '#/components/schemas/LatentsField' }],+ field_kind: 'output',+ title: 'Latents',+ },+ type: { const: 'latents_output', default: 'latents_output' },+ },+ type: 'object',+ },+ },+ },+};++describe('parseOpenApiToTemplates', () => {+ const templates = parseOpenApiToTemplates(openApiFixture);++ it('parses invocation schemas into templates, skipping the denylist', () => {+ expect(Object.keys(templates).sort()).toEqual(['add', 'denoise']);++ const add = templates.add;++ expect(add?.title).toBe('Add Integers');+ expect(add?.version).toBe('1.0.1');+ expect(add?.category).toBe('math');+ expect(add?.outputType).toBe('integer_output');+ });++ it('parses input templates with constraints and skips reserved fields', () => {+ const add = templates.add;++ expect(Object.keys(add?.inputs ?? {}).sort()).toEqual(['a', 'b']);+ expect(add?.inputs.b?.minimum).toBe(0);+ expect(add?.inputs.a?.type).toEqual({ batch: false, cardinality: 'SINGLE', name: 'IntegerField' });+ });++ it('parses ref, nullable-anyOf, single-or-collection, and enum field types', () => {+ const denoise = templates.denoise;++ expect(denoise?.inputs.latents?.type).toEqual({ batch: false, cardinality: 'SINGLE', name: 'LatentsField' });+ expect(denoise?.inputs.latents?.input).toBe('connection');+ expect(denoise?.inputs.latents?.required).toBe(true);+ expect(denoise?.inputs.prompts?.type).toEqual({+ batch: false,+ cardinality: 'SINGLE_OR_COLLECTION',+ name: 'StringField',+ });+ expect(denoise?.inputs.scheduler?.type.name).toBe('EnumField');+ expect(denoise?.inputs.scheduler?.options).toEqual(['euler', 'ddim']);+ });++ it('parses output templates', () => {+ expect(templates.denoise?.outputs.latents?.type.name).toBe('LatentsField');+ expect(templates.add?.outputs.value?.type.name).toBe('IntegerField');+ });+});++describe('parseFieldType', () => {+ it('parses collections of refs and primitives', () => {+ expect(parseFieldType({ items: { $ref: '#/components/schemas/ImageField' }, type: 'array' })).toEqual({+ batch: false,+ cardinality: 'COLLECTION',+ name: 'ImageField',+ });+ expect(parseFieldType({ items: { type: 'integer' }, type: 'array' })).toEqual({+ batch: false,+ cardinality: 'COLLECTION',+ name: 'IntegerField',+ });+ });++ it('returns null for unparseable shapes instead of throwing', () => {+ expect(parseFieldType({ anyOf: [{ type: 'string' }, { type: 'integer' }, { type: 'boolean' }] })).toBeNull();+ expect(parseFieldType('nonsense')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/templates.ts b/invokeai/frontend/webv2/src/workbench/workflows/templates.tsnew file mode 100644index 0000000000..c1f9a5458e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/templates.ts@@ -0,0 +1,383 @@+import { apiFetchJson, getApiErrorMessage } from '../backend/http';+import { createExternalStore } from '../externalStore';+import type {+ FieldInputTemplate,+ FieldOutputTemplate,+ FieldType,+ InvocationTemplate,+ InvocationTemplates,+} from './types';++/**+ * Invocation templates parsed from the backend OpenAPI schema. They are+ * session-lived, backend-owned data shared by every workflow surface, so they+ * live in an external store (the same pattern as the models library) rather+ * than in project state.+ */++export interface InvocationTemplatesSnapshot {+ status: 'idle' | 'loading' | 'loaded' | 'error';+ error: string | null;+ templates: InvocationTemplates;+}++const store = createExternalStore<InvocationTemplatesSnapshot>({ error: null, status: 'idle', templates: {} });++type JsonObject = Record<string, unknown>;++const isJsonObject = (value: unknown): value is JsonObject => typeof value === 'object' && value !== null;++/** Invocations that exist in the schema but are not user-placeable nodes. */+const INVOCATION_DENYLIST = new Set(['graph', 'linear_ui_output']);++const RESERVED_INPUT_FIELD_NAMES = new Set(['id', 'type', 'use_cache', 'is_intermediate']);+const RESERVED_FIELD_TYPE_NAMES = new Set(['IsIntermediate']);++const OPENAPI_TO_FIELD_TYPE_MAP: Record<string, string> = {+ boolean: 'BooleanField',+ integer: 'IntegerField',+ number: 'FloatField',+ string: 'StringField',+};++const COLLECTION_OVERRIDE_TYPE_NAMES = new Set(['CollectionField']);++const refToSchemaName = (ref: unknown): string | null => {+ if (typeof ref !== 'string') {+ return null;+ }++ return ref.split('/').at(-1) ?? null;+};++const getRef = (schema: JsonObject): string | null => refToSchemaName(schema.$ref);++/**+ * Derives the field type from an OpenAPI property schema. Ported from the+ * legacy `parseFieldType`; returns null instead of throwing so unparseable+ * fields are skipped rather than failing the whole template.+ */+export const parseFieldType = (schema: unknown): FieldType | null => {+ if (!isJsonObject(schema)) {+ return null;+ }++ const ref = getRef(schema);++ if (ref) {+ return { batch: false, cardinality: 'SINGLE', name: ref };+ }++ // `Literal["value"]` pydantic fields arrive as `const` — treated as an enum.+ if (schema.const !== undefined || schema.enum !== undefined) {+ return { batch: false, cardinality: 'SINGLE', name: 'EnumField' };+ }++ if (schema.type === undefined) {+ if (Array.isArray(schema.allOf) && isJsonObject(schema.allOf[0])) {+ const name = getRef(schema.allOf[0]);++ return name ? { batch: false, cardinality: 'SINGLE', name } : null;+ }++ if (Array.isArray(schema.anyOf)) {+ const variants = schema.anyOf.filter(+ (variant): variant is JsonObject => isJsonObject(variant) && variant.type !== 'null'+ );++ if (variants.length === 1) {+ return parseFieldType(variants[0]);+ }++ // `T | list[T]` unions become SINGLE_OR_COLLECTION of the base type.+ if (variants.length === 2) {+ const arrayVariant = variants.find((variant) => variant.type === 'array');+ const itemVariant = variants.find((variant) => variant.type !== 'array');++ if (arrayVariant && itemVariant && isJsonObject(arrayVariant.items)) {+ const arrayItemName =+ getRef(arrayVariant.items) ??+ (typeof arrayVariant.items.type === 'string' ? arrayVariant.items.type : null);+ const itemName = getRef(itemVariant) ?? (typeof itemVariant.type === 'string' ? itemVariant.type : null);++ if (arrayItemName && arrayItemName === itemName) {+ return {+ batch: false,+ cardinality: 'SINGLE_OR_COLLECTION',+ name: OPENAPI_TO_FIELD_TYPE_MAP[itemName] ?? itemName,+ };+ }+ }+ }++ return null;+ }++ return null;+ }++ if (schema.type === 'array') {+ if (!isJsonObject(schema.items)) {+ return null;+ }++ const itemRef = getRef(schema.items);++ if (itemRef) {+ return { batch: false, cardinality: 'COLLECTION', name: itemRef };+ }++ const itemType = typeof schema.items.type === 'string' ? OPENAPI_TO_FIELD_TYPE_MAP[schema.items.type] : undefined;++ return itemType ? { batch: false, cardinality: 'COLLECTION', name: itemType } : null;+ }++ if (typeof schema.type === 'string') {+ const name = OPENAPI_TO_FIELD_TYPE_MAP[schema.type];++ return name ? { batch: false, cardinality: 'SINGLE', name } : null;+ }++ return null;+};++const getUiTypeOverride = (property: JsonObject): FieldType | null => {+ if (typeof property.ui_type !== 'string') {+ return null;+ }++ return {+ batch: false,+ cardinality: COLLECTION_OVERRIDE_TYPE_NAMES.has(property.ui_type) ? 'COLLECTION' : 'SINGLE',+ name: property.ui_type,+ };+};++const startCase = (value: string): string =>+ value+ .replace(/[_-]+/g, ' ')+ .replace(/\b\w/g, (char) => char.toUpperCase())+ .trim();++const getNumberOrNull = (value: unknown): number | null => (typeof value === 'number' ? value : null);++const getStringArrayOrNull = (value: unknown): string[] | null =>+ Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : null;++const getDefaultValueForType = (type: FieldType, options: string[] | null): unknown => {+ if (type.cardinality === 'COLLECTION') {+ return undefined;+ }++ switch (type.name) {+ case 'StringField':+ return '';+ case 'IntegerField':+ case 'FloatField':+ return 0;+ case 'BooleanField':+ return false;+ case 'EnumField':+ return options?.[0];+ default:+ return undefined;+ }+};++const buildInputTemplate = (name: string, property: JsonObject, type: FieldType): FieldInputTemplate => {+ const enumValues = Array.isArray(property.enum)+ ? property.enum+ : property.const !== undefined+ ? [property.const]+ : null;+ const options = enumValues ? enumValues.filter((value): value is string => typeof value === 'string') : null;+ const input = property.input === 'connection' || property.input === 'direct' ? property.input : 'any';+ const uiChoiceLabels = isJsonObject(property.ui_choice_labels)+ ? Object.fromEntries(+ Object.entries(property.ui_choice_labels).filter(+ (entry): entry is [string, string] => typeof entry[1] === 'string'+ )+ )+ : null;++ return {+ default: property.default ?? getDefaultValueForType(type, options),+ description: typeof property.description === 'string' ? property.description : '',+ exclusiveMaximum: getNumberOrNull(property.exclusiveMaximum),+ exclusiveMinimum: getNumberOrNull(property.exclusiveMinimum),+ input,+ maximum: getNumberOrNull(property.maximum),+ minimum: getNumberOrNull(property.minimum),+ multipleOf: getNumberOrNull(property.multipleOf),+ name,+ options,+ required: property.orig_required === true,+ title: typeof property.title === 'string' ? property.title : startCase(name),+ type,+ uiChoiceLabels,+ uiComponent:+ property.ui_component === 'slider' || property.ui_component === 'textarea' ? property.ui_component : null,+ uiHidden: property.ui_hidden === true,+ uiModelBase: getStringArrayOrNull(property.ui_model_base),+ uiModelType: getStringArrayOrNull(property.ui_model_type),+ uiOrder: getNumberOrNull(property.ui_order),+ };+};++const parseFieldProperty = (property: JsonObject): FieldType | null => {+ const override = getUiTypeOverride(property);+ const parsed = parseFieldType(property);++ if (override) {+ if (parsed && (parsed.name !== override.name || parsed.cardinality !== override.cardinality)) {+ override.originalType = parsed;+ }++ return override;+ }++ return parsed;+};++const parseInvocationSchema = (schema: JsonObject, schemas: JsonObject): InvocationTemplate | null => {+ const properties = isJsonObject(schema.properties) ? schema.properties : null;+ const typeProperty = properties && isJsonObject(properties.type) ? properties.type : null;+ const type = typeProperty && typeof typeProperty.default === 'string' ? typeProperty.default : null;++ if (!properties || !type || INVOCATION_DENYLIST.has(type)) {+ return null;+ }++ const inputs: Record<string, FieldInputTemplate> = {};++ for (const [name, rawProperty] of Object.entries(properties)) {+ if (+ RESERVED_INPUT_FIELD_NAMES.has(name) ||+ (type === 'iterate' && name === 'index') ||+ !isJsonObject(rawProperty)+ ) {+ continue;+ }++ if (rawProperty.field_kind !== 'input') {+ continue;+ }++ const fieldType = parseFieldProperty(rawProperty);++ if (!fieldType || RESERVED_FIELD_TYPE_NAMES.has(fieldType.name)) {+ continue;+ }++ inputs[name] = buildInputTemplate(name, rawProperty, fieldType);+ }++ const outputRefName = isJsonObject(schema.output) ? getRef(schema.output) : null;+ const outputSchema =+ outputRefName && isJsonObject(schemas[outputRefName]) ? (schemas[outputRefName] as JsonObject) : null;+ const outputProperties = outputSchema && isJsonObject(outputSchema.properties) ? outputSchema.properties : null;++ if (!outputProperties) {+ return null;+ }++ const outputTypeProperty = isJsonObject(outputProperties.type) ? outputProperties.type : null;+ const outputType =+ outputTypeProperty && typeof outputTypeProperty.default === 'string' ? outputTypeProperty.default : '';+ const outputs: Record<string, FieldOutputTemplate> = {};++ for (const [name, rawProperty] of Object.entries(outputProperties)) {+ if (name === 'type' || !isJsonObject(rawProperty) || rawProperty.field_kind !== 'output') {+ continue;+ }++ const fieldType = parseFieldProperty(rawProperty);++ if (!fieldType) {+ continue;+ }++ outputs[name] = {+ description: typeof rawProperty.description === 'string' ? rawProperty.description : '',+ name,+ title: typeof rawProperty.title === 'string' ? rawProperty.title : startCase(name),+ type: fieldType,+ };+ }++ const useCacheProperty = isJsonObject(properties.use_cache) ? properties.use_cache : null;++ return {+ category: typeof schema.category === 'string' ? schema.category : 'other',+ classification: typeof schema.classification === 'string' ? schema.classification : 'stable',+ description: typeof schema.description === 'string' ? schema.description : '',+ inputs,+ nodePack: typeof schema.node_pack === 'string' ? schema.node_pack : 'invokeai',+ outputs,+ outputType,+ tags: getStringArrayOrNull(schema.tags) ?? [],+ title: typeof schema.title === 'string' ? schema.title.replace('Invocation', '').trim() : type,+ type,+ useCache: useCacheProperty?.default !== false,+ version: typeof schema.version === 'string' ? schema.version : '1.0.0',+ };+};++/** Parses a full OpenAPI document into invocation templates. Exported for tests. */+export const parseOpenApiToTemplates = (openApiDocument: unknown): InvocationTemplates => {+ if (!isJsonObject(openApiDocument)) {+ return {};+ }++ const components = isJsonObject(openApiDocument.components) ? openApiDocument.components : null;+ const schemas = components && isJsonObject(components.schemas) ? components.schemas : null;++ if (!schemas) {+ return {};+ }++ const templates: InvocationTemplates = {};++ for (const schema of Object.values(schemas)) {+ if (!isJsonObject(schema) || schema.class !== 'invocation') {+ continue;+ }++ const template = parseInvocationSchema(schema, schemas);++ if (template) {+ templates[template.type] = template;+ }+ }++ return templates;+};++export const refreshInvocationTemplates = async (): Promise<void> => {+ store.patchSnapshot({ error: null, status: 'loading' });++ try {+ // FastAPI serves the schema at the app root (proxied in dev), not under /api.+ const openApiDocument = await apiFetchJson<unknown>('/openapi.json');++ store.setSnapshot({ error: null, status: 'loaded', templates: parseOpenApiToTemplates(openApiDocument) });+ } catch (error) {+ store.patchSnapshot({+ error: getApiErrorMessage(error, 'Failed to load node definitions from the backend.'),+ status: 'error',+ });+ }+};++export const ensureInvocationTemplatesLoaded = (): void => {+ const { status } = store.getSnapshot();++ if (status === 'idle' || status === 'error') {+ void refreshInvocationTemplates();+ }+};++export const useInvocationTemplatesSnapshot = (): InvocationTemplatesSnapshot => store.useSnapshot();++/** Imperative read for the workbench reducer and route validation. */+export const getInvocationTemplatesSnapshot = (): InvocationTemplatesSnapshot => store.getSnapshot();diff --git a/invokeai/frontend/webv2/src/workbench/workflows/types.ts b/invokeai/frontend/webv2/src/workbench/workflows/types.tsnew file mode 100644index 0000000000..7501c72b58--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/types.ts@@ -0,0 +1,224 @@+/**+ * Workflow domain types.+ *+ * The project graph is a *document*: an editable node-and-edge workflow plus a+ * form describing its Linear UI. It compiles into the queue-facing+ * `GraphContract` only at invocation time, so queued snapshots stay immutable+ * while the document keeps evolving. The serialized shape stays compatible+ * with the legacy WorkflowV3 format so workflows round-trip between the v6+ * editor, the workflow library backend, and this workbench.+ */++export type FieldCardinality = 'SINGLE' | 'COLLECTION' | 'SINGLE_OR_COLLECTION';++export interface FieldType {+ name: string;+ cardinality: FieldCardinality;+ batch: boolean;+ /** Set when a `ui_type` override replaced the parsed type; both sides count for connection equality. */+ originalType?: FieldType;+}++export interface FieldInputTemplate {+ name: string;+ title: string;+ description: string;+ type: FieldType;+ required: boolean;+ /** How the field receives data: only via edge, only direct value, or either. */+ input: 'connection' | 'direct' | 'any';+ default?: unknown;+ uiHidden: boolean;+ uiOrder: number | null;+ uiComponent: 'slider' | 'textarea' | null;+ uiChoiceLabels: Record<string, string> | null;+ /** Enum choices when the field is an EnumField. */+ options: string[] | null;+ minimum: number | null;+ maximum: number | null;+ exclusiveMinimum: number | null;+ exclusiveMaximum: number | null;+ multipleOf: number | null;+ uiModelBase: string[] | null;+ uiModelType: string[] | null;+}++export interface FieldOutputTemplate {+ name: string;+ title: string;+ description: string;+ type: FieldType;+}++export interface InvocationTemplate {+ type: string;+ title: string;+ description: string;+ tags: string[];+ category: string;+ version: string;+ useCache: boolean;+ nodePack: string;+ classification: string;+ inputs: Record<string, FieldInputTemplate>;+ outputs: Record<string, FieldOutputTemplate>;+ outputType: string;+}++export type InvocationTemplates = Record<string, InvocationTemplate>;++export interface XYPosition {+ x: number;+ y: number;+}++/** A direct input value on a node. Connection-only fields keep `value` undefined. */+export interface WorkflowFieldInstance {+ name: string;+ label: string;+ /** User override of the template's field description (shown in the Linear UI). */+ description?: string;+ value?: unknown;+}++export interface WorkflowInvocationNodeData {+ type: string;+ version: string;+ label: string;+ notes: string;+ isOpen: boolean;+ isIntermediate: boolean;+ useCache: boolean;+ nodePack: string;+ inputs: Record<string, WorkflowFieldInstance>;+}++export interface WorkflowInvocationNode {+ id: string;+ type: 'invocation';+ position: XYPosition;+ data: WorkflowInvocationNodeData;+}++export interface WorkflowNotesNode {+ id: string;+ type: 'notes';+ position: XYPosition;+ data: {+ label: string;+ notes: string;+ };+}++/** UI-only node mirroring the legacy `current_image` node: shows the latest run output / progress image. */+export interface WorkflowCurrentImageNode {+ id: string;+ type: 'current_image';+ position: XYPosition;+ data: {+ label: string;+ };+}++export type WorkflowNode = WorkflowInvocationNode | WorkflowNotesNode | WorkflowCurrentImageNode;++export interface WorkflowEdge {+ id: string;+ type: 'default';+ source: string;+ target: string;+ sourceHandle: string;+ targetHandle: string;+}++export interface FieldIdentifier {+ nodeId: string;+ fieldName: string;+}++export interface ContainerFormElement {+ id: string;+ type: 'container';+ parentId?: string;+ data: {+ layout: 'row' | 'column';+ children: string[];+ };+}++export interface NodeFieldFormElement {+ id: string;+ type: 'node-field';+ parentId?: string;+ data: {+ fieldIdentifier: FieldIdentifier;+ showDescription: boolean;+ };+}++export interface HeadingFormElement {+ id: string;+ type: 'heading';+ parentId?: string;+ data: {+ content: string;+ };+}++export interface TextFormElement {+ id: string;+ type: 'text';+ parentId?: string;+ data: {+ content: string;+ };+}++export interface DividerFormElement {+ id: string;+ type: 'divider';+ parentId?: string;+}++export type WorkflowFormElement =+ | ContainerFormElement+ | NodeFieldFormElement+ | HeadingFormElement+ | TextFormElement+ | DividerFormElement;++/** The Linear UI description: a tree of form elements rooted in a column container. */+export interface WorkflowForm {+ rootElementId: string;+ elements: Record<string, WorkflowFormElement>;+}++export interface WorkflowMetadata {+ name: string;+ description: string;+ author: string;+ contact: string;+ tags: string;+ notes: string;+ /** The workflow's own semver, distinct from the document schema version. */+ workflowVersion: string;+}++/** The project-owned workflow document. `version: 2` distinguishes it from the Phase-1 placeholder graph. */+export interface ProjectGraphState extends WorkflowMetadata {+ id: string;+ version: 2;+ /** Backend workflow-library binding when the document was loaded from or saved to the library. */+ libraryWorkflowId?: string;+ nodes: WorkflowNode[];+ edges: WorkflowEdge[];+ form: WorkflowForm;+ updatedAt: string;+}++export const isInvocationNode = (node: WorkflowNode): node is WorkflowInvocationNode => node.type === 'invocation';++export const isNotesNode = (node: WorkflowNode): node is WorkflowNotesNode => node.type === 'notes';++export const isCurrentImageNode = (node: WorkflowNode): node is WorkflowCurrentImageNode =>+ node.type === 'current_image';diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/validation.test.tsnew file mode 100644index 0000000000..f993b6ad79--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/validation.test.ts@@ -0,0 +1,252 @@+import { describe, expect, it } from 'vitest';++import type { FieldType, InvocationTemplates, ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from './types';+import { hasAnyCycle, validateConnection, validateConnectionTypes, wouldCreateCycle } from './validation';++const single = (name: string): FieldType => ({ batch: false, cardinality: 'SINGLE', name });+const collection = (name: string): FieldType => ({ batch: false, cardinality: 'COLLECTION', name });+const singleOrCollection = (name: string): FieldType => ({ batch: false, cardinality: 'SINGLE_OR_COLLECTION', name });++describe('validateConnectionTypes', () => {+ it('accepts equal types and rejects mismatched names', () => {+ expect(validateConnectionTypes(single('ImageField'), single('ImageField'))).toBe(true);+ expect(validateConnectionTypes(single('ImageField'), single('LatentsField'))).toBe(false);+ });++ it('applies numeric/string subtype promotions with matching cardinality', () => {+ expect(validateConnectionTypes(single('IntegerField'), single('FloatField'))).toBe(true);+ expect(validateConnectionTypes(single('FloatField'), single('StringField'))).toBe(true);+ expect(validateConnectionTypes(single('FloatField'), single('IntegerField'))).toBe(false);+ expect(validateConnectionTypes(collection('IntegerField'), single('FloatField'))).toBe(false);+ });++ it('handles SINGLE_OR_COLLECTION targets and generic collections', () => {+ expect(validateConnectionTypes(single('StringField'), singleOrCollection('StringField'))).toBe(true);+ expect(validateConnectionTypes(collection('StringField'), singleOrCollection('StringField'))).toBe(true);+ expect(validateConnectionTypes(collection('StringField'), collection('CollectionField'))).toBe(true);+ expect(validateConnectionTypes(single('CollectionField'), collection('ImageField'))).toBe(true);+ });++ it('handles CollectionItemField and AnyField wildcards', () => {+ expect(validateConnectionTypes(single('CollectionItemField'), single('ImageField'))).toBe(true);+ expect(validateConnectionTypes(single('ImageField'), single('CollectionItemField'))).toBe(true);+ expect(validateConnectionTypes(single('ImageField'), single('AnyField'))).toBe(true);+ expect(validateConnectionTypes(single('AnyField'), single('ImageField'))).toBe(true);+ });++ it('rejects batch/non-batch mixes', () => {+ expect(validateConnectionTypes({ ...single('IntegerField'), batch: true }, single('IntegerField'))).toBe(false);+ });+});++describe('cycle detection', () => {+ const edges: WorkflowEdge[] = [+ { id: 'e1', source: 'a', sourceHandle: 'out', target: 'b', targetHandle: 'in', type: 'default' },+ { id: 'e2', source: 'b', sourceHandle: 'out', target: 'c', targetHandle: 'in', type: 'default' },+ ];++ it('detects when a new connection would close a loop', () => {+ expect(wouldCreateCycle('c', 'a', edges)).toBe(true);+ expect(wouldCreateCycle('a', 'c', edges)).toBe(false);+ });++ it('detects existing cycles in a whole graph', () => {+ const nodes = ['a', 'b', 'c'].map((id) => ({ id }) as { id: string });+ const cyclic = [+ ...edges,+ { id: 'e3', source: 'c', sourceHandle: 'out', target: 'a', targetHandle: 'in', type: 'default' as const },+ ];++ expect(hasAnyCycle(nodes as never, edges)).toBe(false);+ expect(hasAnyCycle(nodes as never, cyclic)).toBe(true);+ });+});++const makeNode = (id: string, type: string): WorkflowInvocationNode => ({+ data: {+ inputs: {},+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type,+ useCache: true,+ version: '1.0.0',+ },+ id,+ position: { x: 0, y: 0 },+ type: 'invocation',+});++const templates: InvocationTemplates = {+ collect: {+ category: 'util',+ classification: 'stable',+ description: '',+ inputs: {+ item: {+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'connection',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name: 'item',+ options: null,+ required: true,+ title: 'Item',+ type: { batch: false, cardinality: 'SINGLE', name: 'CollectionItemField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ },+ },+ nodePack: 'invokeai',+ outputs: {},+ outputType: 'collect_output',+ tags: [],+ title: 'Collect',+ type: 'collect',+ useCache: true,+ version: '1.0.0',+ },+ number: {+ category: 'math',+ classification: 'stable',+ description: '',+ inputs: {+ value: {+ default: 0,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name: 'value',+ options: null,+ required: false,+ title: 'Value',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelType: null,+ uiOrder: null,+ },+ },+ nodePack: 'invokeai',+ outputs: {+ value: {+ description: '',+ name: 'value',+ title: 'Value',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ },+ },+ outputType: 'integer_output',+ tags: [],+ title: 'Number',+ type: 'number',+ useCache: true,+ version: '1.0.0',+ },+};++describe('validateConnection', () => {+ const baseDocument: Pick<ProjectGraphState, 'edges' | 'nodes'> = {+ edges: [],+ nodes: [makeNode('n1', 'number'), makeNode('n2', 'number'), makeNode('c1', 'collect')],+ };++ it('accepts a valid connection', () => {+ expect(+ validateConnection(+ { sourceHandle: 'value', sourceNodeId: 'n1', targetHandle: 'value', targetNodeId: 'n2' },+ baseDocument,+ templates+ )+ ).toBeNull();+ });++ it('rejects self-connections and unknown fields', () => {+ expect(+ validateConnection(+ { sourceHandle: 'value', sourceNodeId: 'n1', targetHandle: 'value', targetNodeId: 'n1' },+ baseDocument,+ templates+ )+ ).toMatch(/itself/);+ expect(+ validateConnection(+ { sourceHandle: 'nope', sourceNodeId: 'n1', targetHandle: 'value', targetNodeId: 'n2' },+ baseDocument,+ templates+ )+ ).toMatch(/no known definition/);+ });++ it('rejects a second edge into an occupied input, except for collect item', () => {+ const document = {+ ...baseDocument,+ edges: [+ {+ id: 'e1',+ source: 'n1',+ sourceHandle: 'value',+ target: 'n2',+ targetHandle: 'value',+ type: 'default' as const,+ },+ { id: 'e2', source: 'n1', sourceHandle: 'value', target: 'c1', targetHandle: 'item', type: 'default' as const },+ ],+ };++ expect(+ validateConnection(+ { sourceHandle: 'value', sourceNodeId: 'n2', targetHandle: 'value', targetNodeId: 'n2' },+ document,+ templates+ )+ ).not.toBeNull();+ expect(+ validateConnection(+ { sourceHandle: 'value', sourceNodeId: 'n2', targetHandle: 'item', targetNodeId: 'c1' },+ document,+ templates+ )+ ).toBeNull();+ });++ it('rejects connections that would create a cycle', () => {+ const document = {+ ...baseDocument,+ edges: [+ {+ id: 'e1',+ source: 'n1',+ sourceHandle: 'value',+ target: 'n2',+ targetHandle: 'value',+ type: 'default' as const,+ },+ ],+ };++ expect(+ validateConnection(+ { sourceHandle: 'value', sourceNodeId: 'n2', targetHandle: 'value', targetNodeId: 'n1' },+ document,+ templates+ )+ ).toMatch(/cycle/);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts b/invokeai/frontend/webv2/src/workbench/workflows/validation.tsnew file mode 100644index 0000000000..32667d5cd9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/validation.ts@@ -0,0 +1,210 @@+import type { FieldType, InvocationTemplates, ProjectGraphState, WorkflowEdge, WorkflowNode } from './types';+import { isInvocationNode } from './types';++/**+ * Connection validation, ported from the legacy editor's+ * `validateConnectionTypes` / `validateConnection`. Connector and batch node+ * special cases are intentionally absent — those node kinds are not part of+ * the v7 document model.+ */++const isSingle = (type: FieldType): boolean => type.cardinality === 'SINGLE';+const isCollection = (type: FieldType): boolean => type.cardinality === 'COLLECTION';+const isSingleOrCollection = (type: FieldType): boolean => type.cardinality === 'SINGLE_OR_COLLECTION';++const isSameShape = (a: FieldType, b: FieldType): boolean =>+ a.name === b.name && a.cardinality === b.cardinality && a.batch === b.batch;++/** Types are equal when either declared or `ui_type`-original sides match. */+export const areFieldTypesEqual = (a: FieldType, b: FieldType): boolean =>+ isSameShape(a, b) ||+ (b.originalType !== undefined && isSameShape(a, b.originalType)) ||+ (a.originalType !== undefined && isSameShape(a.originalType, b)) ||+ (a.originalType !== undefined && b.originalType !== undefined && isSameShape(a.originalType, b.originalType));++export const validateConnectionTypes = (sourceType: FieldType, targetType: FieldType): boolean => {+ if (areFieldTypesEqual(sourceType, targetType)) {+ return true;+ }++ if (sourceType.batch !== targetType.batch) {+ return false;+ }++ const isCollectionItemToNonCollection = sourceType.name === 'CollectionItemField' && !isCollection(targetType);+ const isNonCollectionToCollectionItem = isSingle(sourceType) && targetType.name === 'CollectionItemField';+ const isAnythingToSingleOrCollectionOfSameBaseType =+ isSingleOrCollection(targetType) && sourceType.name === targetType.name;+ const isGenericCollectionToAnyCollectionOrSingleOrCollection =+ sourceType.name === 'CollectionField' && !isSingle(targetType);+ const isCollectionToGenericCollection = targetType.name === 'CollectionField' && isCollection(sourceType);++ const doesCardinalityMatch =+ (isSingle(sourceType) && isSingle(targetType)) ||+ (isCollection(sourceType) && isCollection(targetType)) ||+ (isCollection(sourceType) && isSingleOrCollection(targetType)) ||+ (isSingleOrCollection(sourceType) && isSingleOrCollection(targetType)) ||+ (isSingle(sourceType) && isSingleOrCollection(targetType));++ const isIntToFloat = sourceType.name === 'IntegerField' && targetType.name === 'FloatField';+ const isIntToString = sourceType.name === 'IntegerField' && targetType.name === 'StringField';+ const isFloatToString = sourceType.name === 'FloatField' && targetType.name === 'StringField';+ const isSubTypeMatch = doesCardinalityMatch && (isIntToFloat || isIntToString || isFloatToString);++ const isTargetAnyType = targetType.name === 'AnyField';+ const isSourceAnyType = sourceType.name === 'AnyField' && doesCardinalityMatch;++ return (+ isCollectionItemToNonCollection ||+ isNonCollectionToCollectionItem ||+ isAnythingToSingleOrCollectionOfSameBaseType ||+ isGenericCollectionToAnyCollectionOrSingleOrCollection ||+ isCollectionToGenericCollection ||+ isSubTypeMatch ||+ isTargetAnyType ||+ isSourceAnyType+ );+};++/** True if adding source→target would close a cycle: target must not already reach source. */+export const wouldCreateCycle = (sourceNodeId: string, targetNodeId: string, edges: WorkflowEdge[]): boolean => {+ if (sourceNodeId === targetNodeId) {+ return true;+ }++ const visited = new Set<string>();+ const stack = [targetNodeId];++ while (stack.length > 0) {+ const nodeId = stack.pop() as string;++ if (nodeId === sourceNodeId) {+ return true;+ }++ if (visited.has(nodeId)) {+ continue;+ }++ visited.add(nodeId);++ for (const edge of edges) {+ if (edge.source === nodeId) {+ stack.push(edge.target);+ }+ }+ }++ return false;+};++/** True if the graph already contains a cycle anywhere. */+export const hasAnyCycle = (nodes: WorkflowNode[], edges: WorkflowEdge[]): boolean => {+ const adjacency = new Map<string, string[]>();++ for (const edge of edges) {+ adjacency.set(edge.source, [...(adjacency.get(edge.source) ?? []), edge.target]);+ }++ const state = new Map<string, 'visiting' | 'done'>();++ const visit = (nodeId: string): boolean => {+ const nodeState = state.get(nodeId);++ if (nodeState === 'visiting') {+ return true;+ }++ if (nodeState === 'done') {+ return false;+ }++ state.set(nodeId, 'visiting');++ for (const nextNodeId of adjacency.get(nodeId) ?? []) {+ if (visit(nextNodeId)) {+ return true;+ }+ }++ state.set(nodeId, 'done');++ return false;+ };++ return nodes.some((node) => visit(node.id));+};++export interface ConnectionCandidate {+ sourceNodeId: string;+ sourceHandle: string;+ targetNodeId: string;+ targetHandle: string;+}++/** Multiple inbound edges are only meaningful for the collect node's `item` input. */+const allowsMultipleInboundEdges = (node: WorkflowNode, fieldName: string): boolean =>+ isInvocationNode(node) && node.data.type === 'collect' && fieldName === 'item';++/** Returns a human-readable rejection reason, or null when the connection is valid. */+export const validateConnection = (+ candidate: ConnectionCandidate,+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,+ templates: InvocationTemplates+): string | null => {+ const { sourceHandle, sourceNodeId, targetHandle, targetNodeId } = candidate;++ if (sourceNodeId === targetNodeId) {+ return 'A node cannot connect to itself.';+ }++ const sourceNode = document.nodes.find((node) => node.id === sourceNodeId);+ const targetNode = document.nodes.find((node) => node.id === targetNodeId);++ if (!sourceNode || !isInvocationNode(sourceNode) || !targetNode || !isInvocationNode(targetNode)) {+ return 'Both ends of a connection must be invocation nodes.';+ }++ const sourceTemplate = templates[sourceNode.data.type];+ const targetTemplate = templates[targetNode.data.type];+ const sourceField = sourceTemplate?.outputs[sourceHandle];+ const targetField = targetTemplate?.inputs[targetHandle];++ if (!sourceField || !targetField) {+ return 'One of the fields has no known definition.';+ }++ if (targetField.input === 'direct') {+ return `${targetField.title} only accepts direct values, not connections.`;+ }++ const isDuplicate = document.edges.some(+ (edge) =>+ edge.source === sourceNodeId &&+ edge.sourceHandle === sourceHandle &&+ edge.target === targetNodeId &&+ edge.targetHandle === targetHandle+ );++ if (isDuplicate) {+ return 'This connection already exists.';+ }++ const hasInboundEdge = document.edges.some(+ (edge) => edge.target === targetNodeId && edge.targetHandle === targetHandle+ );++ if (hasInboundEdge && !allowsMultipleInboundEdges(targetNode, targetHandle)) {+ return `${targetField.title} already has a connection.`;+ }++ if (!validateConnectionTypes(sourceField.type, targetField.type)) {+ return `${sourceField.type.name} cannot connect to ${targetField.type.name}.`;+ }++ if (wouldCreateCycle(sourceNodeId, targetNodeId, document.edges)) {+ return 'This connection would create a cycle.';+ }++ return null;+};