Skip to content

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

feat: add workflow editor UI

joshistoastd0a7f80dd109
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 3cbccc714e..46a5ac7569 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -23,6 +23,7 @@
"@fontsource/inter": "^5.2.8",
"@tanstack/react-router": "^1.170.15",
"@tanstack/react-virtual": "^3.14.2",
+ "@xyflow/react": "^12.11.0",
"lucide-react": "^1.17.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index f3c6147527..f3d47acb36 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -23,6 +23,9 @@ importers:
'@tanstack/react-virtual':
specifier: ^3.14.2
+ '@xyflow/react':
+ specifier: ^12.11.0
lucide-react:
specifier: ^1.17.0
version: 1.17.0([email protected])
@@ -803,6 +806,24 @@ packages:
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==}
+
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
@@ -865,6 +886,22 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==}
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-na4IO33FSs2OS72hASgZDmTYwFAkef7Z74uBUVrong3ARmQQHfnRUVaCFn1kTt5LbS6pK03TbYjCPGLjLFfziA==}
+ peerDependencies:
+ '@types/react': '>=17'
+ '@types/react-dom': '>=17'
+ react: '>=17'
+ react-dom: '>=17'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-qCDCMCQAAgUu8yHnhloHG9F5mwPX5E+Wl8McpYIOPSSXfzFJJoZcwOcsDiAjitVKIg2de1WmJbCHfpcvxprsgg==}
+
'@zag-js/[email protected]':
resolution: {integrity: sha512-7G//V7svGGT8k5avw7bbQvbRC0Q/9QtX51b4iyAB1alR9E5mFd6Ch8q4njwcXClMQ7xePS3jUfVnzVGiRInEiQ==}
@@ -1131,6 +1168,9 @@ packages:
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==}
+
resolution: {integrity: sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==}
@@ -1147,6 +1187,44 @@ packages:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+ resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==}
+ engines: {node: '>=12'}
+ peerDependencies:
+ d3-selection: 2 - 3
+
+ resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
@@ -1665,6 +1743,21 @@ packages:
resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
+ resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
+ engines: {node: '>=12.7.0'}
+ peerDependencies:
+ '@types/react': '>=16.8'
+ immer: '>=9.0.6'
+ react: '>=16.8'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ immer:
+ optional: true
+ react:
+ optional: true
+
snapshots:
@@ -2294,6 +2387,27 @@ snapshots:
'@types/deep-eql': 4.0.2
assertion-error: 2.0.1
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-selection': 3.0.11
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-color': 3.1.3
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-selection': 3.0.11
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-selection': 3.0.11
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -2361,6 +2475,31 @@ snapshots:
convert-source-map: 2.0.0
tinyrainbow: 3.1.0
+ dependencies:
+ '@xyflow/system': 0.0.77
+ classcat: 5.0.5
+ react: 19.2.7
+ react-dom: 19.2.7([email protected])
+ zustand: 4.5.7(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.17
+ '@types/react-dom': 19.2.3(@types/[email protected])
+ transitivePeerDependencies:
+ - immer
+
+ '@xyflow/[email protected]':
+ dependencies:
+ '@types/d3-drag': 3.0.7
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-selection': 3.0.11
+ '@types/d3-transition': 3.0.9
+ '@types/d3-zoom': 3.0.8
+ d3-drag: 3.0.0
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-zoom: 3.0.0
+
'@zag-js/[email protected]':
dependencies:
'@zag-js/anatomy': 1.41.2
@@ -2956,6 +3095,8 @@ snapshots:
+
@@ -2972,6 +3113,42 @@ snapshots:
+
+
+ dependencies:
+ d3-dispatch: 3.0.1
+ d3-selection: 3.0.0
+
+
+ dependencies:
+ d3-color: 3.1.0
+
+
+
+ dependencies:
+ d3-color: 3.1.0
+ d3-dispatch: 3.0.1
+ d3-ease: 3.0.1
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-timer: 3.0.1
+
+ dependencies:
+ d3-dispatch: 3.0.1
+ d3-drag: 3.0.0
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-transition: 3.0.1([email protected])
+
dependencies:
ms: 2.1.3
@@ -3405,3 +3582,10 @@ snapshots:
+
+ dependencies:
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.17
+ react: 19.2.7
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index 28ee5eb490..afbff50dbf 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -32,6 +32,14 @@ interface WorkbenchContextValue {
const WorkbenchContext = createContext<WorkbenchContextValue | null>(null);
+/**
+ * The reducer dispatch alone, on its own context. `dispatch` is stable for the
+ * provider's lifetime, so subscribers never re-render on state changes — the
+ * subscription of choice for hot, many-instance components (e.g. flow nodes)
+ * that only write.
+ */
+const WorkbenchDispatchContext = createContext<Dispatch<WorkbenchAction> | null>(null);
+
const AUTOSAVE_DELAY_MS = 500;
const getPersistedStateKey = (state: WorkbenchState): string =>
@@ -200,7 +208,11 @@ export const WorkbenchProvider = ({
return { state, activeProject, dispatch, hasHydrated };
}, [state, hasHydrated]);
- return <WorkbenchContext value={value}>{children}</WorkbenchContext>;
+ return (
+ <WorkbenchContext value={value}>
+ <WorkbenchDispatchContext value={dispatch}>{children}</WorkbenchDispatchContext>
+ </WorkbenchContext>
+ );
};
export const useWorkbench = (): WorkbenchContextValue => {
@@ -214,3 +226,13 @@ export const useWorkbench = (): WorkbenchContextValue => {
};
export const useOptionalWorkbench = (): WorkbenchContextValue | null => use(WorkbenchContext);
+
+export const useWorkbenchDispatch = (): Dispatch<WorkbenchAction> => {
+ const dispatch = use(WorkbenchDispatchContext);
+
+ if (!dispatch) {
+ throw new Error('useWorkbenchDispatch must be used within a WorkbenchProvider.');
+ }
+
+ return dispatch;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/components/FlowMiniMap.tsx b/invokeai/frontend/webv2/src/workbench/components/FlowMiniMap.tsx
new file mode 100644
index 0000000000..dbf9ffdf0c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/FlowMiniMap.tsx
@@ -0,0 +1,23 @@
+import { chakra } from '@chakra-ui/react';
+import { MiniMap } from '@xyflow/react';
+
+/**
+ * xyflow's MiniMap wrapped in the chakra factory so its frame is styled with
+ * workbench tokens (the fills inside the SVG come from the `--xy-minimap-*`
+ * vars in `flowTheme.ts`).
+ */
+const StyledMiniMap = chakra(MiniMap);
+
+export const FlowMiniMap = () => (
+ <StyledMiniMap
+ borderColor="border.subtle"
+ borderWidth="1px"
+ m="3"
+ overflow="hidden"
+ pannable
+ position="bottom-right"
+ rounded="md"
+ shadow="sm"
+ zoomable
+ />
+);
diff --git a/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx
index 77a63ec4d1..c35683917c 100644
--- a/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx
@@ -1,64 +1,77 @@
-import { Code, Dialog, Portal, ScrollArea, Stack, Text } from '@chakra-ui/react';
+import { Box, Dialog, Portal, SegmentGroup, Text } from '@chakra-ui/react';
+import { useState } from 'react';
import { formatRoute, isInvocationRouteValid, resolveInvocationRoute } from '../invocation';
import type { GraphContract, GraphId, InvocationSourceId } from '../types';
import { useWorkbench } from '../WorkbenchContext';
+import type { XYPosition } from '../workflows/types';
+import { GraphPreviewFlow } from './GraphPreviewFlow';
import { Button } from './ui/Button';
+import { JsonPreview } from './ui/JsonPreview';
interface GraphPreviewDialogProps {
graph: GraphContract | null;
graphId: GraphId;
isOpen: boolean;
+ /** Editor positions keyed by node id, when the graph mirrors an editable document. */
+ positionHints?: Record<string, XYPosition>;
sourceId?: InvocationSourceId;
title: string;
onOpenChange: (isOpen: boolean) => void;
}
+type PreviewMode = 'nodes' | 'json';
+
export const GraphPreviewDialog = ({
graph,
graphId,
isOpen,
+ positionHints,
sourceId,
title,
onOpenChange,
}: GraphPreviewDialogProps) => {
const { activeProject, dispatch } = useWorkbench();
+ const [mode, setMode] = useState<PreviewMode>('nodes');
const dialogRoute = sourceId
? resolveInvocationRoute(activeProject, 'dialog', { ...activeProject.invocation, sourceId, sourceLocked: true })
: null;
const canInvoke = dialogRoute ? isInvocationRouteValid(dialogRoute) : false;
return (
- <Dialog.Root open={isOpen} onOpenChange={(event) => onOpenChange(event.open)}>
+ <Dialog.Root open={isOpen} size="xl" onOpenChange={(event) => onOpenChange(event.open)}>
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
- <Dialog.Content>
- <Dialog.Header>
+ <Dialog.Content h="75vh" maxH="75vh">
+ <Dialog.Header alignItems="center" flexDirection="row" justifyContent="space-between">
<Dialog.Title>{title} Graph Preview</Dialog.Title>
+ <SegmentGroup.Root
+ size="xs"
+ value={mode}
+ onValueChange={(event) => setMode(event.value === 'json' ? 'json' : 'nodes')}
+ >
+ <SegmentGroup.Indicator />
+ <SegmentGroup.Items
+ items={[
+ { label: 'Nodes', value: 'nodes' },
+ { label: 'JSON', value: 'json' },
+ ]}
+ />
+ </SegmentGroup.Root>
</Dialog.Header>
- <Dialog.Body>
- <Stack gap="3">
+ <Dialog.Body display="flex" flexDirection="column" minH="0">
+ {!graph ? (
<Text color="fg.muted" fontSize="sm">
- Read-only shell for graph inspection. Full graph preview rendering lands in later phases.
+ No compiled graph is available for "{graphId}" yet.
</Text>
- <ScrollArea.Root maxH="20rem" size="xs" variant="hover">
- <ScrollArea.Viewport maxH="20rem">
- <ScrollArea.Content>
- <Code display="block" p="3" whiteSpace="pre-wrap">
- {JSON.stringify(graph ?? { id: graphId, status: 'not-created-yet' }, null, 2)}
- </Code>
- </ScrollArea.Content>
- </ScrollArea.Viewport>
- <ScrollArea.Scrollbar>
- <ScrollArea.Thumb />
- </ScrollArea.Scrollbar>
- <ScrollArea.Scrollbar orientation="horizontal">
- <ScrollArea.Thumb />
- </ScrollArea.Scrollbar>
- <ScrollArea.Corner />
- </ScrollArea.Root>
- </Stack>
+ ) : mode === 'nodes' ? (
+ <Box flex="1" minH="0">
+ <GraphPreviewFlow graph={graph} positionHints={positionHints} />
+ </Box>
+ ) : (
+ <JsonPreview label={`${title} graph JSON`} value={graph} />
+ )}
</Dialog.Body>
<Dialog.Footer>
{dialogRoute ? (
diff --git a/invokeai/frontend/webv2/src/workbench/components/GraphPreviewFlow.tsx b/invokeai/frontend/webv2/src/workbench/components/GraphPreviewFlow.tsx
new file mode 100644
index 0000000000..396148e799
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/GraphPreviewFlow.tsx
@@ -0,0 +1,188 @@
+import { Badge, Box, Stack, Text } from '@chakra-ui/react';
+import {
+ Background,
+ BackgroundVariant,
+ Handle,
+ Position,
+ ReactFlow,
+ type Edge as FlowEdge,
+ type Node as FlowNode,
+ type NodeProps,
+ type NodeTypes,
+} from '@xyflow/react';
+import { useMemo } from 'react';
+
+import '@xyflow/react/dist/style.css';
+
+import { useWorkbenchPreferences } from '../settings/store';
+import type { GraphContract } from '../types';
+import { isInvocationNode, type ProjectGraphState, type XYPosition } from '../workflows/types';
+import { flowThemeCss, getFlowColorMode } from './flowTheme';
+
+/**
+ * A read-only flow rendering of a compiled `GraphContract` — the "nodes" half
+ * of the graph preview dialog. Contracts carry no positions, so the renderer
+ * uses the caller's hints (the editable document's positions, when the graph
+ * came from the project graph) and falls back to a layered topological layout.
+ */
+
+type PreviewFlowNode = FlowNode<{ inputCount: number; nodeId: string; nodeType: string }, 'preview'>;
+
+/**
+ * A lightweight contract view of an editable document (no templates needed),
+ * for previewing workflows that are not the active project graph — e.g.
+ * library entries before loading them.
+ */
+export const documentToPreviewGraph = (
+ document: ProjectGraphState
+): { graph: GraphContract; positionHints: Record<string, XYPosition> } => ({
+ graph: {
+ edges: document.edges.map((edge) => ({
+ id: edge.id,
+ sourceField: edge.sourceHandle,
+ sourceNodeId: edge.source,
+ targetField: edge.targetHandle,
+ targetNodeId: edge.target,
+ })),
+ id: document.id,
+ label: document.name || 'Workflow',
+ nodes: document.nodes.filter(isInvocationNode).map((node) => ({
+ id: node.id,
+ inputs: Object.fromEntries(Object.values(node.data.inputs).map((instance) => [instance.name, instance.value])),
+ type: node.data.type,
+ })),
+ updatedAt: document.updatedAt,
+ version: 1,
+ },
+ positionHints: Object.fromEntries(document.nodes.map((node) => [node.id, node.position])),
+});
+
+const LAYER_WIDTH = 300;
+const ROW_HEIGHT = 100;
+
+const PreviewNode = ({ data }: NodeProps<PreviewFlowNode>) => (
+ <Box bg="bg" borderColor="border.emphasized" borderWidth="1px" fontSize="xs" minW="14rem" rounded="lg" shadow="sm">
+ <Handle position={Position.Left} style={{ background: 'var(--wb-flow-grid)', border: 'none' }} type="target" />
+ <Handle position={Position.Right} style={{ background: 'var(--wb-flow-grid)', border: 'none' }} type="source" />
+ <Stack gap="0.5" px="3" py="2">
+ <Badge fontFamily="mono" size="xs" w="fit-content">
+ {data.nodeType}
+ </Badge>
+ <Text color="fg.subtle" fontSize="2xs" truncate>
+ {data.nodeId} · {data.inputCount} input{data.inputCount === 1 ? '' : 's'}
+ </Text>
+ </Stack>
+ </Box>
+);
+
+const nodeTypes: NodeTypes = { preview: PreviewNode };
+
+/** Longest-path-from-roots depth per node; cycle members settle at their first depth. */
+const getNodeDepths = (graph: GraphContract): Map<string, number> => {
+ const depths = new Map<string, number>();
+ const incoming = new Map<string, string[]>();
+
+ for (const edge of graph.edges) {
+ incoming.set(edge.targetNodeId, [...(incoming.get(edge.targetNodeId) ?? []), edge.sourceNodeId]);
+ }
+
+ const resolve = (nodeId: string, seen: Set<string>): number => {
+ const known = depths.get(nodeId);
+
+ if (known !== undefined) {
+ return known;
+ }
+
+ if (seen.has(nodeId)) {
+ return 0;
+ }
+
+ seen.add(nodeId);
+
+ const parents = incoming.get(nodeId) ?? [];
+ const depth = parents.length === 0 ? 0 : Math.max(...parents.map((parent) => resolve(parent, seen))) + 1;
+
+ depths.set(nodeId, depth);
+
+ return depth;
+ };
+
+ for (const node of graph.nodes) {
+ resolve(node.id, new Set());
+ }
+
+ return depths;
+};
+
+const toPreviewNodes = (graph: GraphContract, positionHints?: Record<string, XYPosition>): PreviewFlowNode[] => {
+ const depths = getNodeDepths(graph);
+ const rowsPerDepth = new Map<number, number>();
+
+ return graph.nodes.map((node) => {
+ const hint = positionHints?.[node.id];
+
+ if (hint) {
+ return {
+ data: { inputCount: Object.keys(node.inputs).length, nodeId: node.id, nodeType: node.type },
+ id: node.id,
+ position: hint,
+ type: 'preview' as const,
+ };
+ }
+
+ const depth = depths.get(node.id) ?? 0;
+ const row = rowsPerDepth.get(depth) ?? 0;
+
+ rowsPerDepth.set(depth, row + 1);
+
+ return {
+ data: { inputCount: Object.keys(node.inputs).length, nodeId: node.id, nodeType: node.type },
+ id: node.id,
+ position: { x: depth * LAYER_WIDTH, y: row * ROW_HEIGHT },
+ type: 'preview' as const,
+ };
+ });
+};
+
+const toPreviewEdges = (graph: GraphContract): FlowEdge[] =>
+ graph.edges.map((edge) => ({
+ id: edge.id,
+ source: edge.sourceNodeId,
+ target: edge.targetNodeId,
+ type: 'default',
+ }));
+
+export const GraphPreviewFlow = ({
+ graph,
+ positionHints,
+}: {
+ graph: GraphContract;
+ positionHints?: Record<string, XYPosition>;
+}) => {
+ const { themeId } = useWorkbenchPreferences();
+ const nodes = useMemo(() => toPreviewNodes(graph, positionHints), [graph, positionHints]);
+ const edges = useMemo(() => toPreviewEdges(graph), [graph]);
+
+ return (
+ <Box bg="bg.inset" css={flowThemeCss} h="full" rounded="md" w="full">
+ <ReactFlow
+ colorMode={getFlowColorMode(themeId)}
+ edges={edges}
+ edgesFocusable={false}
+ elementsSelectable={false}
+ fitView
+ maxZoom={1.5}
+ minZoom={0.1}
+ nodes={nodes}
+ nodesConnectable={false}
+ nodesDraggable={false}
+ nodesFocusable={false}
+ nodeTypes={nodeTypes}
+ proOptions={{ hideAttribution: true }}
+ style={{ background: 'transparent' }}
+ >
+ <Background color="var(--wb-flow-grid)" gap={24} size={1.5} variant={BackgroundVariant.Dots} />
+ </ReactFlow>
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/components/GraphSurfaceActions.tsx b/invokeai/frontend/webv2/src/workbench/components/GraphSurfaceActions.tsx
deleted file mode 100644
index cf6301112e..0000000000
--- a/invokeai/frontend/webv2/src/workbench/components/GraphSurfaceActions.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { Icon, Menu, Portal, Text } from '@chakra-ui/react';
-import { useState } from 'react';
-import { GitBranchIcon, TargetIcon, MoreHorizontalIcon } from 'lucide-react';
-
-import { useWorkbench } from '../WorkbenchContext';
-import type { GraphBearingSurfaceContract, GraphContract, WidgetId } from '../types';
-import { GraphPreviewDialog } from './GraphPreviewDialog';
-import { IconButton } from './ui/Button';
-
-interface GraphSurfaceActionsProps {
- surface: GraphBearingSurfaceContract;
-}
-
-const getPreviewGraph = (
- widgetGraphs: Partial<Record<WidgetId, GraphContract>>,
- surface: GraphBearingSurfaceContract
-) => widgetGraphs[surface.widgetId] ?? null;
-
-export const GraphSurfaceActions = ({ surface }: GraphSurfaceActionsProps) => {
- const { activeProject, dispatch } = useWorkbench();
- const [isPreviewOpen, setIsPreviewOpen] = useState(false);
- const isActiveSource = activeProject.invocation.sourceId === surface.sourceId;
- const previewGraph = getPreviewGraph(activeProject.widgetGraphs, surface);
-
- return (
- <>
- <Menu.Root positioning={{ placement: 'bottom-end' }}>
- <Menu.Trigger asChild>
- <IconButton aria-label={`${surface.label} graph actions`} color="fg.muted" size="2xs" variant="ghost">
- <MoreHorizontalIcon />
- </IconButton>
- </Menu.Trigger>
- <Portal>
- <Menu.Positioner>
- <Menu.Content minW="11rem">
- <Menu.ItemGroup>
- <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
- Graph
- </Menu.ItemGroupLabel>
- <Menu.Item
- value="set-source"
- disabled={isActiveSource || !surface.canSetSource}
- _disabled={{ opacity: 0.4 }}
- onClick={() => dispatch({ sourceId: surface.sourceId, type: 'setInvocationSource' })}
- >
- <Icon as={TargetIcon} boxSize="3.5" />
- <Menu.ItemText>Set Source</Menu.ItemText>
- {isActiveSource ? (
- <Text color="fg.subtle" fontSize="2xs" ms="auto">
- Active
- </Text>
- ) : null}
- </Menu.Item>
- <Menu.Item
- value="view-graph"
- disabled={!surface.canPreviewGraph}
- onClick={() => setIsPreviewOpen(true)}
- >
- <Icon as={GitBranchIcon} boxSize="3.5" />
- <Menu.ItemText>View Graph</Menu.ItemText>
- </Menu.Item>
- </Menu.ItemGroup>
- </Menu.Content>
- </Menu.Positioner>
- </Portal>
- </Menu.Root>
- <GraphPreviewDialog
- graph={previewGraph}
- graphId={surface.graphId}
- isOpen={isPreviewOpen}
- sourceId={surface.sourceId}
- title={surface.label}
- onOpenChange={setIsPreviewOpen}
- />
- </>
- );
-};
diff --git a/invokeai/frontend/webv2/src/workbench/components/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/components/WidgetActionsMenu.tsx
new file mode 100644
index 0000000000..6cfc08cc67
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/WidgetActionsMenu.tsx
@@ -0,0 +1,126 @@
+import { Icon, Menu, Portal, Text } from '@chakra-ui/react';
+import { useState } from 'react';
+import { GitBranchIcon, MoreHorizontalIcon, TargetIcon } from 'lucide-react';
+
+import { useWorkbench } from '../WorkbenchContext';
+import { createGraphBearingSurface } from '../graphSurfaces';
+import { compileProjectGraph } from '../workflows/buildGraph';
+import { getInvocationTemplatesSnapshot } from '../workflows/templates';
+import type { GraphBearingSurfaceContract, GraphContract, Project, WidgetManifest, WorkbenchRegion } from '../types';
+import { GraphPreviewDialog } from './GraphPreviewDialog';
+import { IconButton } from './ui/Button';
+
+/**
+ * The widget frame's shared header actions menu. It hosts the universal
+ * graph-bearing actions (`Set Source`, `View Graph`) and any extra entries the
+ * widget's manifest contributes via `headerMenu` — one menu per widget, so
+ * widgets extend the frame instead of stacking their own menus and toolbars.
+ */
+
+const getPreviewGraph = (project: Project, surface: GraphBearingSurfaceContract): GraphContract | null => {
+ // The project graph compiles fresh for preview so `View Graph` always shows
+ // what Invoke would run right now; widget graphs keep their last compile.
+ if (surface.sourceId === 'project-graph') {
+ const templatesSnapshot = getInvocationTemplatesSnapshot();
+
+ if (templatesSnapshot.status !== 'loaded') {
+ return null;
+ }
+
+ try {
+ return compileProjectGraph(project.projectGraph, templatesSnapshot.templates);
+ } catch {
+ return null;
+ }
+ }
+
+ return project.widgetGraphs[surface.widgetId] ?? null;
+};
+
+const GraphSurfaceMenuItems = ({
+ surface,
+ onPreview,
+}: {
+ surface: GraphBearingSurfaceContract;
+ onPreview: () => void;
+}) => {
+ const { activeProject, dispatch } = useWorkbench();
+ const isActiveSource = activeProject.invocation.sourceId === surface.sourceId;
+
+ return (
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Graph
+ </Menu.ItemGroupLabel>
+ <Menu.Item
+ value="set-source"
+ disabled={isActiveSource || !surface.canSetSource}
+ _disabled={{ opacity: 0.4 }}
+ onClick={() => dispatch({ sourceId: surface.sourceId, type: 'setInvocationSource' })}
+ >
+ <Icon as={TargetIcon} boxSize="3.5" />
+ <Menu.ItemText>Set Source</Menu.ItemText>
+ {isActiveSource ? (
+ <Text color="fg.subtle" fontSize="2xs" ms="auto">
+ Active
+ </Text>
+ ) : null}
+ </Menu.Item>
+ <Menu.Item value="view-graph" disabled={!surface.canPreviewGraph} onClick={onPreview}>
+ <Icon as={GitBranchIcon} boxSize="3.5" />
+ <Menu.ItemText>View Graph</Menu.ItemText>
+ </Menu.Item>
+ </Menu.ItemGroup>
+ );
+};
+
+export const WidgetActionsMenu = ({ manifest, region }: { manifest: WidgetManifest; region: WorkbenchRegion }) => {
+ const { activeProject } = useWorkbench();
+ const [isPreviewOpen, setIsPreviewOpen] = useState(false);
+ const surface = manifest.graphBearing?.surfaces.includes(region) ? createGraphBearingSurface(manifest, region) : null;
+ const HeaderMenu = manifest.headerMenu;
+
+ if (!surface && !HeaderMenu) {
+ return null;
+ }
+
+ const previewGraph = surface && isPreviewOpen ? getPreviewGraph(activeProject, surface) : null;
+ // The project graph mirrors the editable document, so the preview can reuse
+ // the editor's node positions instead of auto-layouting.
+ const positionHints =
+ surface?.sourceId === 'project-graph'
+ ? Object.fromEntries(activeProject.projectGraph.nodes.map((node) => [node.id, node.position]))
+ : undefined;
+
+ return (
+ <>
+ <Menu.Root positioning={{ placement: 'bottom-end' }}>
+ <Menu.Trigger asChild>
+ <IconButton aria-label={`${manifest.labelText} actions`} color="fg.muted" size="2xs" variant="ghost">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <Menu.Content minW="13rem">
+ {surface ? <GraphSurfaceMenuItems surface={surface} onPreview={() => setIsPreviewOpen(true)} /> : null}
+ {surface && HeaderMenu ? <Menu.Separator borderColor="border.subtle" /> : null}
+ {HeaderMenu ? <HeaderMenu manifest={manifest} region={region} /> : null}
+ </Menu.Content>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ {surface ? (
+ <GraphPreviewDialog
+ graph={previewGraph}
+ graphId={surface.graphId}
+ isOpen={isPreviewOpen}
+ positionHints={positionHints}
+ sourceId={surface.sourceId}
+ title={surface.label}
+ onOpenChange={setIsPreviewOpen}
+ />
+ ) : null}
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx
index 7970226632..fa780bc6d1 100644
--- a/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx
@@ -7,13 +7,14 @@ import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
} from 'react';
-import type { LucideIcon } from 'lucide-react';
+import { SettingsIcon, type LucideIcon } from 'lucide-react';
-import { createGraphBearingSurface } from '../graphSurfaces';
import { useFocusRegionProps } from '../focusRegions';
+import { openWorkbenchSettings } from '../settings/settingsDialogStore';
import type { WidgetManifest, WidgetRegion, WorkbenchRegion } from '../types';
import { useWorkbench } from '../WorkbenchContext';
-import { GraphSurfaceActions } from './GraphSurfaceActions';
+import { WidgetActionsMenu } from './WidgetActionsMenu';
+import { IconButton } from './ui/Button';
const PANEL_SIZE_STEP_PX = 16;
const MIN_PANEL_SIZE_PX = 180;
@@ -118,7 +119,6 @@ export const WidgetPanelFrame = ({
borderTopWidth={isBottom ? '1px' : '0'}
direction="column"
flexShrink={0}
- gap="3"
overflow="hidden"
minW="0"
{...focusRegionProps}
@@ -159,16 +159,36 @@ export const WidgetHeader = ({
manifest: WidgetManifest;
region: WorkbenchRegion;
}) => {
- const surface = manifest.graphBearing?.surfaces.includes(region) ? createGraphBearingSurface(manifest, region) : null;
+ // Manifests may provide a component label (e.g. Workflow's editable
+ // `Workflow / [name]`); plain strings render as the standard title.
+ const Label = manifest.label;
return (
<HStack justify="space-between" borderBottomWidth={1} h={10} ps="3" pe="2">
- <Text fontSize="xs" fontWeight="700">
- {manifest.labelText}
- </Text>
+ <HStack flex="1" gap="1.5" minW="0">
+ {typeof Label === 'string' ? (
+ <Text fontSize="xs" fontWeight="700">
+ {Label}
+ </Text>
+ ) : (
+ <Label region={region} />
+ )}
+ </HStack>
<HStack flexShrink={0} gap="1.5">
{actions}
- {surface ? <GraphSurfaceActions surface={surface} /> : null}
+ {manifest.settingsSection ? (
+ <IconButton
+ aria-label={`${manifest.labelText} settings`}
+ color="fg.muted"
+ size="2xs"
+ title={`${manifest.labelText} settings`}
+ variant="ghost"
+ onClick={() => openWorkbenchSettings(manifest.settingsSection)}
+ >
+ <Icon as={SettingsIcon} boxSize="3.5" />
+ </IconButton>
+ ) : null}
+ <WidgetActionsMenu manifest={manifest} region={region} />
</HStack>
</HStack>
);
diff --git a/invokeai/frontend/webv2/src/workbench/components/flowTheme.ts b/invokeai/frontend/webv2/src/workbench/components/flowTheme.ts
new file mode 100644
index 0000000000..2b846f253a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/flowTheme.ts
@@ -0,0 +1,28 @@
+import type { SystemStyleObject } from '@chakra-ui/react';
+
+import { THEMES_BY_ID } from '../../theme/themes';
+import type { WorkbenchThemeId } from '../types';
+
+/**
+ * Theme bridge for xyflow surfaces. xyflow's stylesheet only knows light/dark,
+ * so every flow renderer (workflow editor, graph preview) applies these
+ * Chakra-token-backed `--xy-*` override vars on its wrapper — they inherit
+ * into `.react-flow` and outrank the colorMode defaults. `--wb-flow-grid` is
+ * ours, consumed by `<Background color>` and preview handles.
+ */
+export const flowThemeCss: SystemStyleObject = {
+ '--wb-flow-grid': '{colors.fg.grid}',
+ '--xy-attribution-background-color': 'transparent',
+ '--xy-connectionline-stroke': '{colors.accent.solid}',
+ '--xy-edge-stroke': '{colors.border.emphasized}',
+ '--xy-edge-stroke-selected': '{colors.accent.solid}',
+ '--xy-minimap-background-color': '{colors.bg.muted}',
+ '--xy-minimap-mask-background-color': '{colors.bg.inset/70}',
+ '--xy-minimap-mask-stroke-color': '{colors.border.subtle}',
+ '--xy-minimap-node-background-color': '{colors.bg.emphasized}',
+ '--xy-selection-background-color': '{colors.accent.solid/10}',
+ '--xy-selection-border': '1px dashed {colors.accent.solid}',
+};
+
+/** The xyflow color mode matching a workbench theme. */
+export const getFlowColorMode = (themeId: WorkbenchThemeId): 'light' | 'dark' => THEMES_BY_ID[themeId].colorScheme;
diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/JsonPreview.tsx b/invokeai/frontend/webv2/src/workbench/components/ui/JsonPreview.tsx
new file mode 100644
index 0000000000..fe13bf1f91
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/ui/JsonPreview.tsx
@@ -0,0 +1,102 @@
+import { Box, Code, Icon, ScrollArea } from '@chakra-ui/react';
+import { CheckIcon, CopyIcon } from 'lucide-react';
+import { useEffect, useMemo, useRef, useState } from 'react';
+
+import { useNotify } from '../../useNotify';
+import { IconButton } from './Button';
+
+/**
+ * The workbench's standard JSON preview: a monospace block with a copy button
+ * that owns its scrolling in both axes — long strings scroll horizontally
+ * instead of stretching the surrounding layout. Pass `value` to serialize, or
+ * `text` when the JSON string already exists (an export payload that must be
+ * copied byte-for-byte). Defaults to a bounded height; pass `maxH` (or wrap in
+ * a flex parent and pass `maxH="100%"`) to control it.
+ */
+export const JsonPreview = ({
+ label = 'JSON preview',
+ maxH = '24rem',
+ text,
+ value,
+}: {
+ /** Accessible name for the scroll viewport. */
+ label?: string;
+ maxH?: string;
+ text?: string;
+ value?: unknown;
+}) => {
+ const notify = useNotify();
+ const [hasCopied, setHasCopied] = useState(false);
+ const copyResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const json = useMemo(() => text ?? JSON.stringify(value, null, 2) ?? 'null', [text, value]);
+
+ useEffect(
+ () => () => {
+ if (copyResetTimerRef.current !== null) {
+ clearTimeout(copyResetTimerRef.current);
+ }
+ },
+ []
+ );
+
+ const copy = () => {
+ navigator.clipboard
+ .writeText(json)
+ .then(() => {
+ setHasCopied(true);
+
+ if (copyResetTimerRef.current !== null) {
+ clearTimeout(copyResetTimerRef.current);
+ }
+
+ copyResetTimerRef.current = setTimeout(() => setHasCopied(false), 1500);
+ })
+ .catch(() => notify.error('Failed to copy JSON'));
+ };
+
+ return (
+ <Box
+ bg="bg.inset"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ display="flex"
+ flexDirection="column"
+ maxH={maxH}
+ minH="0"
+ overflow="hidden"
+ position="relative"
+ rounded="md"
+ >
+ <IconButton
+ aria-label="Copy JSON"
+ bg="bg.muted"
+ position="absolute"
+ right="1.5"
+ size="2xs"
+ title="Copy JSON"
+ top="1.5"
+ variant="ghost"
+ zIndex="1"
+ onClick={copy}
+ >
+ <Icon as={hasCopied ? CheckIcon : CopyIcon} boxSize="3" color={hasCopied ? 'green.solid' : undefined} />
+ </IconButton>
+ <ScrollArea.Root flex="1" minH="0" size="xs" variant="hover">
+ <ScrollArea.Viewport aria-label={label} h="full" maxH={maxH} w="full">
+ <ScrollArea.Content minW="fit-content" w="full">
+ <Code bg="transparent" display="block" fontSize="2xs" p="2" whiteSpace="pre" wordBreak="normal">
+ {json}
+ </Code>
+ </ScrollArea.Content>
+ </ScrollArea.Viewport>
+ <ScrollArea.Scrollbar>
+ <ScrollArea.Thumb />
+ </ScrollArea.Scrollbar>
+ <ScrollArea.Scrollbar orientation="horizontal">
+ <ScrollArea.Thumb />
+ </ScrollArea.Scrollbar>
+ <ScrollArea.Corner />
+ </ScrollArea.Root>
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx b/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx
new file mode 100644
index 0000000000..bd55f42048
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx
@@ -0,0 +1,55 @@
+import { Icon, Separator, Stack, type StackProps } from '@chakra-ui/react';
+import type { ComponentProps } from 'react';
+
+import { IconButton } from './Button';
+
+/**
+ * The workbench's floating tool strip, shared by canvas-like surfaces (the
+ * workflow editor today, the canvas later). Vertical by default — designed to
+ * dock against a surface edge. Compose from `ToolbarButton`s (sticky tools via
+ * `isActive`, one-shot actions without) and `ToolbarSeparator`s between
+ * groups.
+ */
+
+export const Toolbar = ({ children, direction = 'column', ...stackProps }: StackProps) => (
+ <Stack
+ bg="bg.subtle"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ direction={direction}
+ gap="0.5"
+ p="1"
+ rounded="lg"
+ shadow="sm"
+ {...stackProps}
+ >
+ {children}
+ </Stack>
+);
+
+export const ToolbarButton = ({
+ icon,
+ isActive,
+ label,
+ ...buttonProps
+}: {
+ icon: React.ElementType;
+ /** Sticky-tool styling; omit for one-shot action buttons. */
+ isActive?: boolean;
+ label: string;
+} & Omit<ComponentProps<typeof IconButton>, 'aria-label'>) => (
+ <IconButton
+ aria-label={label}
+ aria-pressed={isActive}
+ size="sm"
+ title={label}
+ variant={isActive ? 'solid' : 'ghost'}
+ {...buttonProps}
+ >
+ <Icon as={icon} boxSize="3.5" />
+ </IconButton>
+);
+
+export const ToolbarSeparator = ({ direction = 'column' }: { direction?: 'column' | 'row' }) => (
+ <Separator borderColor="border.subtle" orientation={direction === 'column' ? 'horizontal' : 'vertical'} />
+);
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
index 7977d23ac3..f91b297d68 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
@@ -22,7 +22,7 @@ export const layoutPresets: LayoutPreset[] = [
label: 'Gallery',
},
{
- description: 'Future graph authoring preset.',
+ description: 'Project graph editing with the Linear UI panel alongside.',
id: 'workflow',
initialLayout: {
centerViewId: 'workflow',
@@ -30,9 +30,10 @@ export const layoutPresets: LayoutPreset[] = [
presetId: 'workflow',
},
label: 'Workflow',
+ leftRegionWidgetId: 'workflow',
},
{
- description: 'Future linear generation preset.',
+ description: 'The project graph as simple linear controls, generating to Canvas.',
id: 'linear',
initialLayout: {
centerViewId: 'canvas',
@@ -40,6 +41,7 @@ export const layoutPresets: LayoutPreset[] = [
presetId: 'linear',
},
label: 'Linear UI',
+ leftRegionWidgetId: 'workflow',
},
{
description: 'Full-width model library, installs, and download queue.',
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
index 606a15de91..821644f19f 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
@@ -27,6 +27,7 @@ import {
SettingsIcon,
SlidersHorizontalIcon,
Trash2Icon,
+ WorkflowIcon,
type LucideIcon,
} from 'lucide-react';
@@ -39,11 +40,18 @@ import type {
DeveloperLogLevel,
DeveloperLogNamespace,
ProjectSettings,
+ SettingsSectionId,
WorkbenchLanguage,
WorkbenchPreferences,
WorkbenchThemeId,
} from '../types';
import { useOptionalWorkbench } from '../WorkbenchContext';
+import {
+ closeWorkbenchSettings,
+ openWorkbenchSettings,
+ setWorkbenchSettingsSection,
+ settingsDialogStore,
+} from './settingsDialogStore';
import {
clearWorkbenchSettings,
DEVELOPER_LOG_LEVELS,
@@ -55,7 +63,7 @@ import {
} from './store';
interface SettingsTabDefinition {
- value: string;
+ value: SettingsSectionId;
label: string;
icon: LucideIcon;
condition?: boolean;
@@ -66,8 +74,13 @@ const updatePreferences = (patch: Partial<WorkbenchPreferences>): void => {
void patchWorkbenchPreferences(patch);
};
+/**
+ * The top bar's settings entry point. It also hosts the dialog itself, driven
+ * by `settingsDialogStore` so any surface can deep-link into a section via
+ * `openWorkbenchSettings('workflow')`.
+ */
export const SettingsButton = () => {
- const [isOpen, setIsOpen] = useState(false);
+ const { isOpen } = settingsDialogStore.useSnapshot();
return (
<>
@@ -77,11 +90,11 @@ export const SettingsButton = () => {
size="sm"
variant="ghost"
_hover={{ color: 'fg' }}
- onClick={() => setIsOpen(true)}
+ onClick={() => openWorkbenchSettings()}
>
<SettingsIcon />
</IconButton>
- <SettingsDialog isOpen={isOpen} onClose={() => setIsOpen(false)} />
+ <SettingsDialog isOpen={isOpen} onClose={closeWorkbenchSettings} />
</>
);
};
@@ -143,7 +156,7 @@ const SettingsDialogContent = () => {
const SettingsTabs = () => {
const workbench = useOptionalWorkbench();
- const tabs: SettingsTabDefinition[] = [
+ const allTabs: SettingsTabDefinition[] = [
{
children: <AppearanceSection />,
icon: PaletteIcon,
@@ -163,6 +176,12 @@ const SettingsTabs = () => {
label: 'Project',
value: 'project',
},
+ {
+ children: <WorkflowSection />,
+ icon: WorkflowIcon,
+ label: 'Workflow',
+ value: 'workflow',
+ },
{
children: <DeveloperSection />,
icon: Code2Icon,
@@ -175,10 +194,21 @@ const SettingsTabs = () => {
label: 'Workspace',
value: 'workspace',
},
- ].filter((tab) => tab.condition !== false);
+ ];
+ const tabs = allTabs.filter((tab) => tab.condition !== false);
+ const { sectionId } = settingsDialogStore.useSnapshot();
+ const activeSectionId = tabs.some((tab) => tab.value === sectionId) ? sectionId : 'appearance';
return (
- <Tabs.Root defaultValue="appearance" display="flex" h="full" minH="0" orientation="vertical" variant="subtle">
+ <Tabs.Root
+ display="flex"
+ h="full"
+ minH="0"
+ orientation="vertical"
+ value={activeSectionId}
+ variant="subtle"
+ onValueChange={(event) => setWorkbenchSettingsSection(event.value as SettingsSectionId)}
+ >
<Tabs.List
alignItems="stretch"
bg="bg"
@@ -405,6 +435,43 @@ const ProjectSection = () => {
);
};
+const WorkflowSection = () => {
+ const { workflowEdgeStyle, workflowShowMinimap, workflowSnapToGrid, workflowValidateConnections } =
+ useWorkbenchPreferences();
+
+ return (
+ <SettingsSection description="Editing behavior for the project graph workflow editor." title="Workflow">
+ <SettingSelect
+ description="How connections between nodes are drawn in the editor."
+ label="Connection style"
+ value={workflowEdgeStyle}
+ onChange={(value) => updatePreferences({ workflowEdgeStyle: value === 'straight' ? 'straight' : 'curved' })}
+ >
+ <option value="curved">Curved</option>
+ <option value="straight">Straight</option>
+ </SettingSelect>
+ <SettingToggle
+ checked={workflowSnapToGrid}
+ description="Snap nodes to the grid while dragging. When off, hold Ctrl to snap temporarily."
+ label="Always snap to grid"
+ onChange={(checked) => updatePreferences({ workflowSnapToGrid: checked })}
+ />
+ <SettingToggle
+ checked={workflowShowMinimap}
+ description="Show the minimap overview in the corner of the workflow editor."
+ label="Show minimap"
+ onChange={(checked) => updatePreferences({ workflowShowMinimap: checked })}
+ />
+ <SettingToggle
+ checked={workflowValidateConnections}
+ description="Reject connections between incompatible field types while wiring nodes. Turn off to wire anything (runs may fail)."
+ label="Validate connections"
+ onChange={(checked) => updatePreferences({ workflowValidateConnections: checked })}
+ />
+ </SettingsSection>
+ );
+};
+
const DeveloperSection = () => {
const { developerLogEnabled, developerLogLevel, developerLogNamespaces } = useWorkbenchPreferences();
const enabledNamespaces = new Set(developerLogNamespaces);
diff --git a/invokeai/frontend/webv2/src/workbench/settings/index.ts b/invokeai/frontend/webv2/src/workbench/settings/index.ts
index b0175d4b12..b82f03b9d7 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/index.ts
@@ -1,2 +1,3 @@
export * from './SettingsDialog';
+export * from './settingsDialogStore';
export * from './store';
diff --git a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
new file mode 100644
index 0000000000..11254f0331
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
@@ -0,0 +1,32 @@
+import { createExternalStore } from '../externalStore';
+import type { SettingsSectionId } from '../types';
+
+/**
+ * Open/close state for the workbench settings dialog, addressable from
+ * anywhere: widget frames, menus, and commands call `openWorkbenchSettings`
+ * with the section they want. The dialog itself is hosted by the top bar's
+ * `SettingsButton`, which subscribes to this store.
+ */
+
+interface SettingsDialogSnapshot {
+ isOpen: boolean;
+ sectionId: SettingsSectionId;
+}
+
+export const settingsDialogStore = createExternalStore<SettingsDialogSnapshot>({
+ isOpen: false,
+ sectionId: 'appearance',
+});
+
+/** Open the workbench settings dialog, optionally at a specific section. */
+export const openWorkbenchSettings = (sectionId: SettingsSectionId = 'appearance'): void => {
+ settingsDialogStore.setSnapshot({ isOpen: true, sectionId });
+};
+
+export const closeWorkbenchSettings = (): void => {
+ settingsDialogStore.patchSnapshot({ isOpen: false });
+};
+
+export const setWorkbenchSettingsSection = (sectionId: SettingsSectionId): void => {
+ settingsDialogStore.patchSnapshot({ sectionId });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
new file mode 100644
index 0000000000..ba6106ede7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
@@ -0,0 +1,315 @@
+import { HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';
+import { HistoryIcon, LibraryIcon, PlusIcon } from 'lucide-react';
+import { useEffect, useId, useRef, type ChangeEvent } from 'react';
+
+import { IconButton } from '../../components/ui/Button';
+import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
+import { useNotify } from '../../useNotify';
+import { useWorkbench } from '../../WorkbenchContext';
+import {
+ buildCurrentImageNode,
+ buildInvocationNode,
+ buildNotesNode,
+ createProjectGraph,
+ createWorkflowId,
+} from '../../workflows/document';
+import type { InvocationTemplate, XYPosition } from '../../workflows/types';
+import { parseWorkflowJson } from '../../workflows/workflowJson';
+import type { WidgetLabelProps, WidgetViewProps } from '../../types';
+import { AddNodeDialog } from './editor/AddNodeDialog';
+import { getWorkflowFlowInstance } from './editor/flowInstanceStore';
+import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';
+import { copyWorkflowJson, downloadWorkflowJson } from './workflowTransfer';
+import {
+ claimWorkflowDialogHost,
+ releaseWorkflowDialogHost,
+ requestWorkflowImport,
+ setAddNodeOpen,
+ setNewWorkflowConfirmOpen,
+ setWorkflowLibraryOpen,
+ workflowUiStore,
+} from './workflowUiStore';
+
+/**
+ * The workflow widget's frame chrome. The label renders the editable
+ * `Workflow / [name]` title; quick actions (add node, library, history) are
+ * header icon buttons; everything else contributes to the shared widget
+ * actions menu via the manifest's `headerMenu`. Dialogs live here (always
+ * mounted) and are driven through `workflowUiStore`.
+ */
+
+export const WorkflowWidgetLabel = ({ region }: WidgetLabelProps) => {
+ const { activeProject, dispatch } = useWorkbench();
+
+ if (region !== 'center') {
+ return (
+ <Text fontSize="xs" fontWeight="700">
+ Workflow
+ </Text>
+ );
+ }
+
+ return (
+ <HStack flex="1" gap="1" minW="0">
+ <Text flexShrink={0} fontSize="xs" fontWeight="700">
+ Workflow
+ </Text>
+ <Text color="fg.subtle" flexShrink={0} fontSize="xs">
+ /
+ </Text>
+ <Input
+ aria-label="Workflow name"
+ fontSize="xs"
+ fontWeight="600"
+ h="6"
+ maxW="16rem"
+ placeholder="Untitled Workflow"
+ size="2xs"
+ value={activeProject.projectGraph.name}
+ variant="flushed"
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ dispatch({
+ action: { patch: { name: event.currentTarget.value }, type: 'setMetadata' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ </HStack>
+ );
+};
+
+/** Entries contributed to the shared widget actions menu. */
+export const WorkflowMenuItems = (_props: WidgetViewProps) => {
+ const { activeProject, dispatch } = useWorkbench();
+ const notify = useNotify();
+ const projectGraph = activeProject.projectGraph;
+
+ const openDetailsPanel = () => {
+ dispatch({ region: 'left', type: 'openRegionWidget', widgetId: 'workflow' });
+ dispatch({ type: 'patchWidgetValues', values: { editTab: 'details', panelMode: 'edit' }, widgetId: 'workflow' });
+ };
+
+ return (
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Workflow
+ </Menu.ItemGroupLabel>
+ <Menu.Item value="snapshot" onClick={() => dispatch({ type: 'saveProjectGraphSnapshot' })}>
+ Save graph snapshot
+ </Menu.Item>
+ <Menu.Item value="details" onClick={openDetailsPanel}>
+ Workflow details…
+ </Menu.Item>
+ <Menu.Item value="import" onClick={requestWorkflowImport}>
+ Import workflow JSON…
+ </Menu.Item>
+ <Menu.Item value="export" onClick={() => downloadWorkflowJson(projectGraph)}>
+ Export workflow JSON
+ </Menu.Item>
+ <Menu.Item
+ value="copy"
+ onClick={() => {
+ copyWorkflowJson(projectGraph)
+ .then(() => notify.success('Workflow JSON copied'))
+ .catch(() => notify.error('Failed to copy workflow JSON'));
+ }}
+ >
+ Copy workflow JSON
+ </Menu.Item>
+ <Menu.Item color="fg.error" value="new" onClick={() => setNewWorkflowConfirmOpen(true)}>
+ New workflow…
+ </Menu.Item>
+ </Menu.ItemGroup>
+ );
+};
+
+export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {
+ const { activeProject, dispatch } = useWorkbench();
+ const notify = useNotify();
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const { dialogHostId, importRequestCount, isAddNodeOpen, isLibraryOpen, isNewWorkflowConfirmOpen } =
+ workflowUiStore.useSnapshot();
+ const restorableHistory = activeProject.graphHistory.filter((entry) => entry.document);
+
+ // Both workflow surfaces can be mounted at once; exactly one (the first to
+ // mount) hosts the shared dialogs and the import file input.
+ const hostId = useId();
+ const isDialogHost = dialogHostId === hostId;
+ const lastImportRequestRef = useRef(importRequestCount);
+
+ useEffect(() => {
+ claimWorkflowDialogHost(hostId);
+
+ return () => {
+ releaseWorkflowDialogHost(hostId);
+ };
+ }, [hostId]);
+
+ useEffect(() => {
+ if (isDialogHost && importRequestCount > lastImportRequestRef.current) {
+ fileInputRef.current?.click();
+ }
+
+ lastImportRequestRef.current = importRequestCount;
+ }, [importRequestCount, isDialogHost]);
+
+ const getInsertPosition = (): XYPosition => {
+ const instance = getWorkflowFlowInstance();
+ const center = instance
+ ? instance.screenToFlowPosition({ x: window.innerWidth / 2, y: window.innerHeight / 2 })
+ : { x: 0, y: 0 };
+
+ // Slight scatter so repeated inserts do not stack perfectly.
+ return { x: center.x + (Math.random() - 0.5) * 80, y: center.y + (Math.random() - 0.5) * 80 };
+ };
+
+ const addNode = (template: InvocationTemplate) => {
+ dispatch({
+ action: { node: buildInvocationNode(template, getInsertPosition()), type: 'addNode' },
+ type: 'applyProjectGraphAction',
+ });
+ };
+
+ const addNote = () => {
+ dispatch({
+ action: { node: buildNotesNode(getInsertPosition()), type: 'addNode' },
+ type: 'applyProjectGraphAction',
+ });
+ };
+
+ const addCurrentImage = () => {
+ dispatch({
+ action: { node: buildCurrentImageNode(getInsertPosition()), type: 'addNode' },
+ type: 'applyProjectGraphAction',
+ });
+ };
+
+ const importFile = (file: File) => {
+ file
+ .text()
+ .then((text) => {
+ const { document, warnings } = parseWorkflowJson(JSON.parse(text));
+
+ dispatch({ document, label: `Imported "${file.name}"`, type: 'replaceProjectGraph' });
+
+ for (const warning of warnings) {
+ notify.info('Workflow import warning', warning);
+ }
+ })
+ .catch((error: unknown) => {
+ notify.error(
+ 'Failed to import workflow',
+ error instanceof Error ? error.message : 'The file is not a valid workflow JSON.'
+ );
+ });
+ };
+
+ return (
+ <HStack gap="0.5">
+ {region === 'center' ? (
+ <IconButton
+ aria-label="Add node"
+ color="fg.muted"
+ size="2xs"
+ title="Add node"
+ variant="ghost"
+ onClick={() => setAddNodeOpen(true)}
+ >
+ <Icon as={PlusIcon} boxSize="3.5" />
+ </IconButton>
+ ) : null}
+ <IconButton
+ aria-label="Workflow library"
+ color="fg.muted"
+ size="2xs"
+ title="Workflow library"
+ variant="ghost"
+ onClick={() => setWorkflowLibraryOpen(true)}
+ >
+ <Icon as={LibraryIcon} boxSize="3.5" />
+ </IconButton>
+ <Menu.Root positioning={{ placement: 'bottom-end' }}>
+ <Menu.Trigger asChild>
+ <IconButton
+ aria-label="Graph history snapshots"
+ color="fg.muted"
+ disabled={restorableHistory.length === 0}
+ size="2xs"
+ title="Graph history snapshots"
+ variant="ghost"
+ >
+ <Icon as={HistoryIcon} boxSize="3.5" />
+ </IconButton>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <Menu.Content maxH="18rem" minW="16rem" overflowY="auto">
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Graph History Snapshots
+ </Menu.ItemGroupLabel>
+ {restorableHistory.map((entry) => (
+ <Menu.Item
+ key={entry.id}
+ value={entry.id}
+ onClick={() => dispatch({ snapshotId: entry.id, type: 'restoreProjectGraphSnapshot' })}
+ >
+ <Stack gap="0" minW="0">
+ <Menu.ItemText fontSize="xs" truncate>
+ {entry.label}
+ </Menu.ItemText>
+ <Text color="fg.subtle" fontSize="2xs">
+ {new Date(entry.createdAt).toLocaleString()}
+ </Text>
+ </Stack>
+ </Menu.Item>
+ ))}
+ </Menu.ItemGroup>
+ </Menu.Content>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ {isDialogHost ? (
+ <>
+ <input
+ ref={fileInputRef}
+ accept=".json,application/json"
+ hidden
+ type="file"
+ onChange={(event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+
+ event.currentTarget.value = '';
+
+ if (file) {
+ importFile(file);
+ }
+ }}
+ />
+ <AddNodeDialog
+ isOpen={isAddNodeOpen}
+ onAddCurrentImage={addCurrentImage}
+ onAddNode={addNode}
+ onAddNote={addNote}
+ onOpenChange={setAddNodeOpen}
+ />
+ <WorkflowLibraryDialog isOpen={isLibraryOpen} onOpenChange={setWorkflowLibraryOpen} />
+ <ConfirmDialog
+ body="Replace the project graph with an empty workflow? The current graph is saved to graph history first."
+ confirmLabel="New workflow"
+ isOpen={isNewWorkflowConfirmOpen}
+ title="New workflow"
+ onClose={() => setNewWorkflowConfirmOpen(false)}
+ onConfirm={() => {
+ dispatch({
+ document: createProjectGraph(createWorkflowId('project-graph')),
+ label: 'New workflow',
+ type: 'replaceProjectGraph',
+ });
+ }}
+ />
+ </>
+ ) : null}
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx
index 3b099fafab..5cba2f757a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx
@@ -1,21 +1,44 @@
-import { Flex, Text } from '@chakra-ui/react';
+import { Box, HStack, Icon, Text } from '@chakra-ui/react';
+import { WorkflowIcon } from 'lucide-react';
+import { useWorkbench } from '../../WorkbenchContext';
import type { WidgetViewProps } from '../../types';
+import { WorkflowEditorView } from './editor/WorkflowEditorView';
+import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';
-export const WorkflowWidgetView = ({ region }: WidgetViewProps) => {
- if (region === 'left') {
- return (
- <Text color="fg.subtle" fontSize="2xs">
- Workflow controls will render here when this widget is mounted into the left panel.
- </Text>
- );
- }
+/**
+ * The workflow widget's surfaces, per its manifest: the center region is the
+ * node editor over the project graph; the left region is the Linear UI panel
+ * bound to the same document; the bottom region is a status-bar entry whose
+ * expanded panel is the same node editor — handy while another widget (e.g.
+ * the canvas and its staging area) holds the center.
+ */
+
+const WorkflowStatusBarItem = () => {
+ const { activeProject } = useWorkbench();
+ const isRunning = activeProject.queue.items.some(
+ (item) => item.snapshot.sourceId === 'project-graph' && (item.status === 'running' || item.status === 'pending')
+ );
return (
- <Flex align="center" h="full" justify="center" w="full">
- <Text color="fg.subtle" fontSize="sm">
- Workflow view
+ <HStack gap="1" maxW="14rem" minW="0">
+ <Icon as={WorkflowIcon} boxSize="3" color={isRunning ? 'brand.solid' : undefined} flexShrink={0} />
+ <Text fontSize="2xs" minW="0" truncate>
+ {activeProject.projectGraph.name || 'Untitled Workflow'}
</Text>
- </Flex>
+ {isRunning ? <Box bg="brand.solid" boxSize="1.5" flexShrink={0} rounded="full" /> : null}
+ </HStack>
);
};
+
+export const WorkflowWidgetView = ({ presentation, region }: WidgetViewProps) => {
+ if (region === 'bottom') {
+ return presentation === 'expanded' ? <WorkflowEditorView /> : <WorkflowStatusBarItem />;
+ }
+
+ if (region === 'left') {
+ return <WorkflowLinearPanel />;
+ }
+
+ return <WorkflowEditorView />;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx
new file mode 100644
index 0000000000..3895f3aed7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx
@@ -0,0 +1,270 @@
+import { Accordion, Badge, Box, Dialog, HStack, Icon, Input, Portal, Stack, Text } from '@chakra-ui/react';
+import { HammerIcon } from 'lucide-react';
+import { useCallback, useMemo, useState, type ChangeEvent, type ReactNode } from 'react';
+
+import { Button } from '../../../components/ui/Button';
+import { Scrollable } from '../../../components/ui/Scrollable';
+import { Tooltip } from '../../../components/ui/Tooltip';
+import { useInvocationTemplatesSnapshot } from '../../../workflows/templates';
+import type { InvocationTemplate } from '../../../workflows/types';
+
+/**
+ * Command-palette-style node picker: a centered search dialog whose results
+ * are grouped into collapsible categories (with counts), mirroring the legacy
+ * editor's add-node menu. Beta nodes carry the hammer icon. The two UI-only
+ * nodes (Notes, Current Image) lead as a "Utility" group. No result cap —
+ * searching auto-expands every group; idle shows all categories collapsed.
+ */
+
+const UTILITY_CATEGORY = 'Utility';
+
+const toCategoryLabel = (value: string): string =>
+ value
+ .replace(/[_-]+/g, ' ')
+ .replace(/\b\w/g, (char) => char.toUpperCase())
+ .trim();
+
+const matchesSearch = (template: InvocationTemplate, terms: string[]): boolean => {
+ const haystack = `${template.title} ${template.type} ${template.tags.join(' ')} ${template.category}`.toLowerCase();
+
+ return terms.every((term) => haystack.includes(term));
+};
+
+interface NodeRow {
+ description: string;
+ isBeta: boolean;
+ nodePack: string;
+ onAdd: () => void;
+ title: string;
+}
+
+interface CategoryGroup {
+ label: string;
+ rows: NodeRow[];
+}
+
+const NodeResultRow = ({ row }: { row: NodeRow }) => (
+ <Box
+ as="button"
+ _hover={{ bg: 'bg.emphasized' }}
+ px="3"
+ py="2"
+ rounded="md"
+ textAlign="start"
+ w="full"
+ onClick={row.onAdd}
+ >
+ <HStack gap="2" justify="space-between">
+ <Stack gap="0" minW="0">
+ <HStack gap="1.5" minW="0">
+ {row.isBeta ? (
+ <Tooltip content="Beta node — may change in the future">
+ <Icon as={HammerIcon} boxSize="3" color="fg.subtle" flexShrink={0} />
+ </Tooltip>
+ ) : null}
+ <Text fontSize="sm" fontWeight="600" truncate>
+ {row.title}
+ </Text>
+ </HStack>
+ {row.description ? (
+ <Text color="fg.subtle" fontSize="2xs" lineClamp={2}>
+ {row.description}
+ </Text>
+ ) : null}
+ </Stack>
+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs">
+ {row.nodePack}
+ </Text>
+ </HStack>
+ </Box>
+);
+
+export const AddNodeDialog = ({
+ isOpen,
+ onAddCurrentImage,
+ onAddNode,
+ onAddNote,
+ onOpenChange,
+}: {
+ isOpen: boolean;
+ onAddCurrentImage: () => void;
+ onAddNode: (template: InvocationTemplate) => void;
+ onAddNote: () => void;
+ onOpenChange: (isOpen: boolean) => void;
+}) => {
+ const { error, status, templates } = useInvocationTemplatesSnapshot();
+ const [searchTerm, setSearchTerm] = useState('');
+ const [expandedCategories, setExpandedCategories] = useState<string[]>([]);
+ // While searching, every matching group is force-expanded regardless of the
+ // manual expand/collapse state, so results are never hidden behind a header.
+ const isSearching = searchTerm.trim().length > 0;
+
+ const close = useCallback(
+ (added: boolean) => {
+ onOpenChange(false);
+
+ if (added) {
+ setSearchTerm('');
+ }
+ },
+ [onOpenChange]
+ );
+
+ const groups = useMemo<CategoryGroup[]>(() => {
+ const terms = searchTerm.trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const utilityRows: NodeRow[] = [
+ {
+ description: 'Annotate the workflow with a free-text note.',
+ isBeta: false,
+ nodePack: 'invokeai',
+ onAdd: () => {
+ onAddNote();
+ close(true);
+ },
+ title: 'Notes',
+ },
+ {
+ description: 'Show the latest generated image (and live progress) inside the graph.',
+ isBeta: false,
+ nodePack: 'invokeai',
+ onAdd: () => {
+ onAddCurrentImage();
+ close(true);
+ },
+ title: 'Current Image',
+ },
+ ].filter((row) => terms.every((term) => row.title.toLowerCase().includes(term)));
+
+ const byCategory = new Map<string, NodeRow[]>();
+
+ for (const template of Object.values(templates)) {
+ if (template.classification === 'internal' || (terms.length > 0 && !matchesSearch(template, terms))) {
+ continue;
+ }
+
+ const label = toCategoryLabel(template.category || 'other');
+ const row: NodeRow = {
+ description: template.description,
+ isBeta: template.classification === 'beta',
+ nodePack: template.nodePack,
+ onAdd: () => {
+ onAddNode(template);
+ close(true);
+ },
+ title: template.title,
+ };
+
+ byCategory.set(label, [...(byCategory.get(label) ?? []), row]);
+ }
+
+ const categoryGroups = [...byCategory.entries()]
+ .map(([label, rows]) => ({
+ label,
+ rows: rows.sort((a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: 'base' })),
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label));
+
+ return utilityRows.length > 0
+ ? [{ label: UTILITY_CATEGORY, rows: utilityRows }, ...categoryGroups]
+ : categoryGroups;
+ }, [close, onAddCurrentImage, onAddNode, onAddNote, searchTerm, templates]);
+
+ const totalCount = groups.reduce((sum, group) => sum + group.rows.length, 0);
+ const accordionValue = isSearching ? groups.map((group) => group.label) : expandedCategories;
+
+ let body: ReactNode;
+
+ if (status !== 'loaded') {
+ body = (
+ <Text color={status === 'error' ? 'fg.error' : 'fg.subtle'} fontSize="xs" px="1" py="4">
+ {status === 'error' ? (error ?? 'Failed to load node definitions.') : 'Loading node definitions…'}
+ </Text>
+ );
+ } else if (totalCount === 0) {
+ body = (
+ <Text color="fg.subtle" fontSize="xs" px="1" py="4" textAlign="center">
+ No nodes match your search.
+ </Text>
+ );
+ } else {
+ body = (
+ <Accordion.Root
+ multiple
+ value={accordionValue}
+ variant="plain"
+ onValueChange={(event) => setExpandedCategories(event.value)}
+ >
+ {groups.map((group) => (
+ <Accordion.Item key={group.label} value={group.label}>
+ <Accordion.ItemTrigger cursor="pointer" px="1" py="1.5">
+ <Accordion.ItemIndicator />
+ <Text flex="1" fontSize="xs" fontWeight="700" textAlign="start">
+ {group.label}
+ </Text>
+ <Badge size="sm" variant="surface">
+ {group.rows.length}
+ </Badge>
+ </Accordion.ItemTrigger>
+ <Accordion.ItemContent>
+ <Stack gap="0.5" pb="2">
+ {group.rows.map((row) => (
+ <NodeResultRow key={`${group.label}:${row.title}`} row={row} />
+ ))}
+ </Stack>
+ </Accordion.ItemContent>
+ </Accordion.Item>
+ ))}
+ </Accordion.Root>
+ );
+ }
+
+ return (
+ <Dialog.Root
+ open={isOpen}
+ placement="top"
+ scrollBehavior="inside"
+ size="lg"
+ onOpenChange={(event) => {
+ if (!event.open) {
+ close(false);
+ }
+ }}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg" mt="16">
+ <Dialog.Body p="3">
+ <Stack gap="2">
+ <Input
+ autoFocus
+ aria-label="Search for nodes"
+ placeholder="Search for nodes…"
+ size="md"
+ value={searchTerm}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setSearchTerm(event.currentTarget.value)}
+ />
+ <HStack gap="2">
+ <Button
+ disabled={isSearching}
+ size="2xs"
+ variant="ghost"
+ onClick={() => setExpandedCategories(groups.map((group) => group.label))}
+ >
+ Expand All
+ </Button>
+ <Button disabled={isSearching} size="2xs" variant="ghost" onClick={() => setExpandedCategories([])}>
+ Collapse All
+ </Button>
+ </HStack>
+ <Scrollable label="Node search results" maxH="60vh" minH="12rem">
+ {body}
+ </Scrollable>
+ </Stack>
+ </Dialog.Body>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx
new file mode 100644
index 0000000000..45589c1e26
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx
@@ -0,0 +1,59 @@
+import { Box, Flex, Image, Text } from '@chakra-ui/react';
+import type { NodeProps } from '@xyflow/react';
+import { memo } from 'react';
+
+import { useProgressImage } from '../../../backend/progressImageStore';
+import { useWorkbench } from '../../../WorkbenchContext';
+import type { GeneratedImageContract } from '../../../types';
+import type { CurrentImageFlowNode as CurrentImageFlowNodeType } from './flowAdapters';
+
+/**
+ * The legacy `current_image` UI node: a live monitor inside the graph. Shows
+ * the in-flight denoising preview while a run executes, and the most recently
+ * generated image otherwise.
+ */
+
+const getLatestImage = (values: Record<string, unknown>): GeneratedImageContract | null => {
+ const recentImages = Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : [];
+
+ return recentImages[0] ?? null;
+};
+
+const CurrentImageFlowNodeComponent = ({ data, selected }: NodeProps<CurrentImageFlowNodeType>) => {
+ const { activeProject } = useWorkbench();
+ const progressImage = useProgressImage();
+ const node = data.documentNode;
+ const latestImage = getLatestImage(activeProject.widgetStates.gallery.values);
+ const src = progressImage?.dataUrl ?? latestImage?.imageUrl ?? null;
+
+ return (
+ <Box
+ bg="bg"
+ borderColor={selected ? 'accent.solid' : 'border.emphasized'}
+ borderWidth="1px"
+ fontSize="xs"
+ overflow="hidden"
+ rounded="lg"
+ shadow={selected ? 'md' : 'sm'}
+ w="20rem"
+ >
+ <Flex align="center" bg="bg.subtle" borderBottomWidth="1px" borderColor="border.subtle" px="3" py="1.5">
+ <Text fontWeight="700">{node.data.label || 'Current Image'}</Text>
+ {progressImage ? (
+ <Text color="brand.solid" fontSize="2xs" ms="auto">
+ generating…
+ </Text>
+ ) : null}
+ </Flex>
+ {src ? (
+ <Image alt="Current image" draggable={false} h="18rem" objectFit="contain" src={src} w="full" />
+ ) : (
+ <Flex align="center" color="fg.subtle" fontSize="2xs" h="18rem" justify="center" px="4" textAlign="center">
+ No image yet — the latest generation will appear here.
+ </Flex>
+ )}
+ </Box>
+ );
+};
+
+export const CurrentImageFlowNode = memo(CurrentImageFlowNodeComponent);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/EditorToolbar.tsx
new file mode 100644
index 0000000000..4d906aa8f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/EditorToolbar.tsx
@@ -0,0 +1,94 @@
+import { Box, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';
+import { useReactFlow } from '@xyflow/react';
+import {
+ BlendIcon,
+ BoxSelectIcon,
+ EraserIcon,
+ HandIcon,
+ LassoIcon,
+ MaximizeIcon,
+ ZoomInIcon,
+ ZoomOutIcon,
+} from 'lucide-react';
+
+import { Toolbar, ToolbarButton, ToolbarSeparator } from '../../../components/ui/Toolbar';
+
+/**
+ * The editor's single tool strip, docked to the left edge: interaction tools
+ * on top (legacy-toolbar style), viewport actions and the node-opacity slider
+ * below.
+ * - pan: dragging the pane moves the viewport (Shift-drag still box-selects)
+ * - box-select: dragging the pane draws a selection rectangle (middle-mouse pans)
+ * - lasso: dragging the pane draws a freeform selection
+ * - eraser: clicking nodes or edges deletes them
+ */
+export type EditorTool = 'pan' | 'box-select' | 'lasso' | 'eraser';
+
+const TOOLS: { icon: typeof HandIcon; id: EditorTool; label: string }[] = [
+ { icon: HandIcon, id: 'pan', label: 'Pan (drag to move the viewport)' },
+ { icon: BoxSelectIcon, id: 'box-select', label: 'Box select (drag to select nodes)' },
+ { icon: LassoIcon, id: 'lasso', label: 'Lasso select (draw around nodes)' },
+ { icon: EraserIcon, id: 'eraser', label: 'Eraser (click nodes or edges to delete)' },
+];
+
+export const EditorToolbar = ({
+ nodeOpacity,
+ tool,
+ onNodeOpacityChange,
+ onToolChange,
+}: {
+ nodeOpacity: number;
+ tool: EditorTool;
+ onNodeOpacityChange: (opacity: number) => void;
+ onToolChange: (tool: EditorTool) => void;
+}) => {
+ const { fitView, zoomIn, zoomOut } = useReactFlow();
+
+ return (
+ <Box left="3" position="absolute" top="50%" transform="translateY(-50%)" zIndex="5">
+ <Toolbar>
+ {TOOLS.map(({ icon, id, label }) => (
+ <ToolbarButton key={id} icon={icon} isActive={tool === id} label={label} onClick={() => onToolChange(id)} />
+ ))}
+ <ToolbarSeparator />
+ <ToolbarButton icon={ZoomInIcon} label="Zoom in" onClick={() => void zoomIn()} />
+ <ToolbarButton icon={ZoomOutIcon} label="Zoom out" onClick={() => void zoomOut()} />
+ <ToolbarButton icon={MaximizeIcon} label="Fit view" onClick={() => void fitView({ duration: 300 })} />
+ <ToolbarSeparator />
+ <Popover.Root positioning={{ placement: 'right' }}>
+ <Popover.Trigger asChild>
+ <ToolbarButton color={nodeOpacity < 1 ? 'accent.solid' : undefined} icon={BlendIcon} label="Node opacity" />
+ </Popover.Trigger>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content w="12rem">
+ <Popover.Body p="3">
+ <Stack gap="1.5">
+ <Text color="fg.muted" fontSize="2xs" fontWeight="600">
+ Node opacity · {Math.round(nodeOpacity * 100)}%
+ </Text>
+ <Slider.Root
+ max={100}
+ min={20}
+ size="sm"
+ step={5}
+ value={[Math.round(nodeOpacity * 100)]}
+ onValueChange={(event) => onNodeOpacityChange((event.value[0] ?? 100) / 100)}
+ >
+ <Slider.Control>
+ <Slider.Track>
+ <Slider.Range />
+ </Slider.Track>
+ <Slider.Thumbs />
+ </Slider.Control>
+ </Slider.Root>
+ </Stack>
+ </Popover.Body>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ </Toolbar>
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx
new file mode 100644
index 0000000000..5af983e93d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx
@@ -0,0 +1,410 @@
+import { Badge, Box, Flex, HStack, Icon, Image, Input, Stack, Text } from '@chakra-ui/react';
+import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';
+import { ChevronDownIcon, ChevronRightIcon, PinIcon, PinOffIcon, TriangleAlertIcon } from 'lucide-react';
+import { memo, useState, type ChangeEvent, type KeyboardEvent } from 'react';
+
+import { useNodeExecutionState, type NodeExecutionState } from '../../../backend/nodeExecutionStore';
+import { IconButton } from '../../../components/ui/Button';
+import { Tooltip } from '../../../components/ui/Tooltip';
+import { useWorkbenchDispatch } from '../../../WorkbenchContext';
+import { getFieldTypeColor, getFieldTypeLabel, isDirectInputField, isExposableField } from '../../../workflows/fields';
+import { useInvocationTemplatesSnapshot } from '../../../workflows/templates';
+import type { FieldInputTemplate, FieldOutputTemplate, WorkflowInvocationNode } from '../../../workflows/types';
+import { FieldDescriptionPopover } from '../fields/FieldDescriptionPopover';
+import { WorkflowFieldInput } from '../fields/WorkflowFieldInput';
+import type { InvocationFlowNode as InvocationFlowNodeType } from './flowAdapters';
+
+const NODE_WIDTH = '18rem';
+const HANDLE_SIZE = 10;
+/** Row padding-x in px; inline handles sit in the label rows, so they pull back out past it. */
+const ROW_PADDING_X = 12;
+/** Below this viewport zoom, field content renders as skeleton bars (ComfyUI-style) for performance/readability. */
+const CONTENT_VISIBILITY_ZOOM = 0.4;
+
+const handleStyle = (color: string): React.CSSProperties => ({
+ background: color,
+ border: 'none',
+ height: HANDLE_SIZE,
+ width: HANDLE_SIZE,
+});
+
+const sortByUiOrder = <T extends { uiOrder?: number | null }>(templates: T[]): T[] =>
+ [...templates].sort((a, b) => (a.uiOrder ?? Number.MAX_SAFE_INTEGER) - (b.uiOrder ?? Number.MAX_SAFE_INTEGER));
+
+/** True while the viewport is zoomed out far enough that field content is unreadable noise. */
+const useIsZoomedOut = (): boolean => useStore((state) => state.transform[2] < CONTENT_VISIBILITY_ZOOM);
+
+/** Static placeholder bar standing in for text/controls at far zoom. No animation — there may be hundreds. */
+const SkeletonBar = ({ h = '2', w }: { h?: string; w?: string }) => <Box bg="bg.emphasized" h={h} rounded="sm" w={w} />;
+
+const NodeShell = ({
+ children,
+ isMissing,
+ isRunning,
+ selected,
+}: {
+ children: React.ReactNode;
+ isMissing?: boolean;
+ isRunning?: boolean;
+ selected: boolean;
+}) => (
+ <Box
+ bg="bg"
+ borderColor={isMissing ? 'red.solid' : isRunning ? 'brand.solid' : selected ? 'accent.solid' : 'border.emphasized'}
+ borderWidth="1px"
+ fontSize="xs"
+ rounded="lg"
+ shadow={isRunning ? '0 0 10px {colors.brand.solid/50}' : selected ? 'md' : 'sm'}
+ w={NODE_WIDTH}
+ >
+ {children}
+ </Box>
+);
+
+/** Thin progress strip under the header while the node's invocation executes. */
+const NodeProgressStrip = ({ execution }: { execution: NodeExecutionState | null }) => {
+ if (execution?.status !== 'running') {
+ return null;
+ }
+
+ return (
+ <Box bg="bg.muted" h="2px" overflow="hidden" position="relative" w="full">
+ <Box
+ bg="brand.solid"
+ h="full"
+ transition="width 0.2s ease"
+ w={execution.progress === null ? 'full' : `${Math.round(execution.progress * 100)}%`}
+ {...(execution.progress === null
+ ? { animationDuration: '1.2s', animationIterationCount: 'infinite', animationName: 'pulse' }
+ : {})}
+ />
+ </Box>
+ );
+};
+
+const NodeTitle = ({ node }: { node: WorkflowInvocationNode }) => {
+ const dispatch = useWorkbenchDispatch();
+ const { templates } = useInvocationTemplatesSnapshot();
+ const [draftLabel, setDraftLabel] = useState<string | null>(null);
+ const title = node.data.label || templates[node.data.type]?.title || node.data.type;
+
+ if (draftLabel !== null) {
+ return (
+ <Input
+ autoFocus
+ aria-label="Node label"
+ className="nodrag"
+ size="2xs"
+ value={draftLabel}
+ onBlur={() => {
+ dispatch({
+ action: { label: draftLabel.trim(), nodeId: node.id, type: 'setNodeLabel' },
+ type: 'applyProjectGraphAction',
+ });
+ setDraftLabel(null);
+ }}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setDraftLabel(event.currentTarget.value)}
+ onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter' || event.key === 'Escape') {
+ event.currentTarget.blur();
+ }
+ }}
+ />
+ );
+ }
+
+ return (
+ <Text
+ fontWeight="700"
+ minW="0"
+ title="Double-click to rename"
+ truncate
+ // Editing always starts from the displayed title: an unset label
+ // prefills with the template title rather than an empty input.
+ onDoubleClick={() => setDraftLabel(title)}
+ >
+ {title}
+ </Text>
+ );
+};
+
+const InputFieldRow = ({
+ isConnected,
+ isExposed,
+ isSkeleton,
+ node,
+ template,
+}: {
+ isConnected: boolean;
+ isExposed: boolean;
+ isSkeleton: boolean;
+ node: WorkflowInvocationNode;
+ template: FieldInputTemplate;
+}) => {
+ const dispatch = useWorkbenchDispatch();
+ const instance = node.data.inputs[template.name];
+ const fieldIdentifier = { fieldName: template.name, nodeId: node.id };
+ const showsControl = !isConnected && isDirectInputField(template);
+ const label = instance?.label || template.title;
+
+ if (isSkeleton) {
+ return (
+ <Box px="3" py="1.5">
+ <HStack gap="1.5" h="5" position="relative">
+ {template.input !== 'direct' ? (
+ <Handle
+ id={template.name}
+ position={Position.Left}
+ style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -(ROW_PADDING_X + HANDLE_SIZE / 2) }}
+ type="target"
+ />
+ ) : null}
+ <SkeletonBar w="55%" />
+ </HStack>
+ {showsControl ? <SkeletonBar h="6" w="full" /> : null}
+ </Box>
+ );
+ }
+
+ return (
+ <Box px="3" py="1.5">
+ {/* The handle lives inside the label row so it stays centered on the
+ label even when the value control below grows the row. */}
+ <HStack gap="1.5" justify="space-between" position="relative">
+ {template.input !== 'direct' ? (
+ <Handle
+ id={template.name}
+ position={Position.Left}
+ style={{ ...handleStyle(getFieldTypeColor(template.type)), left: -(ROW_PADDING_X + HANDLE_SIZE / 2) }}
+ type="target"
+ />
+ ) : null}
+ <Tooltip
+ content={`${instance?.description || template.description || label} — ${getFieldTypeLabel(template.type)}`}
+ >
+ <Text color={isConnected ? 'fg.muted' : 'fg'} fontSize="2xs" minW="0" truncate>
+ {label}
+ {template.required ? (
+ <Text as="span" color="fg.error">
+ {' *'}
+ </Text>
+ ) : null}
+ </Text>
+ </Tooltip>
+ <HStack flexShrink={0} gap="0">
+ <FieldDescriptionPopover
+ description={instance?.description}
+ fieldName={template.name}
+ nodeId={node.id}
+ templateDescription={template.description}
+ />
+ {isExposableField(template) ? (
+ <IconButton
+ aria-label={isExposed ? `Remove ${label} from Linear UI` : `Expose ${label} in Linear UI`}
+ className="nodrag"
+ color={isExposed ? 'accent.solid' : 'fg.subtle'}
+ size="2xs"
+ title={isExposed ? 'Remove from Linear UI form' : 'Expose in Linear UI form'}
+ variant="ghost"
+ onClick={() =>
+ dispatch({
+ action: { fieldIdentifier, type: isExposed ? 'unexposeField' : 'exposeField' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ >
+ <Icon as={isExposed ? PinOffIcon : PinIcon} boxSize="3" />
+ </IconButton>
+ ) : null}
+ </HStack>
+ </HStack>
+ {showsControl ? (
+ <Box mt="1">
+ <WorkflowFieldInput
+ template={template}
+ value={instance?.value}
+ onChange={(value) =>
+ dispatch({
+ action: { fieldName: template.name, nodeId: node.id, type: 'setFieldValue', value },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ </Box>
+ ) : null}
+ </Box>
+ );
+};
+
+const OutputFieldRow = ({ isSkeleton, template }: { isSkeleton: boolean; template: FieldOutputTemplate }) => (
+ <Box px="3" py="1">
+ <Box position="relative">
+ <Handle
+ id={template.name}
+ position={Position.Right}
+ style={{ ...handleStyle(getFieldTypeColor(template.type)), right: -(ROW_PADDING_X + HANDLE_SIZE / 2) }}
+ type="source"
+ />
+ {isSkeleton ? (
+ <Flex h="4" justify="flex-end">
+ <SkeletonBar w="40%" />
+ </Flex>
+ ) : (
+ <Tooltip content={`${template.description || template.title} — ${getFieldTypeLabel(template.type)}`}>
+ <Text color="fg.muted" fontSize="2xs" textAlign="end" truncate>
+ {template.title}
+ </Text>
+ </Tooltip>
+ )}
+ </Box>
+ </Box>
+);
+
+/** Keeps every handle mounted (invisible) so edges stay attached when rows are not rendered. */
+const HiddenHandles = ({
+ inputTemplates,
+ outputTemplates,
+}: {
+ inputTemplates: FieldInputTemplate[];
+ outputTemplates: FieldOutputTemplate[];
+}) => (
+ <Box position="relative" h="0">
+ {outputTemplates.map((outputTemplate) => (
+ <Handle
+ key={outputTemplate.name}
+ id={outputTemplate.name}
+ position={Position.Right}
+ style={{ ...handleStyle(getFieldTypeColor(outputTemplate.type)), opacity: 0, right: 0, top: -14 }}
+ type="source"
+ />
+ ))}
+ {inputTemplates.map((inputTemplate) =>
+ inputTemplate.input !== 'direct' ? (
+ <Handle
+ key={inputTemplate.name}
+ id={inputTemplate.name}
+ position={Position.Left}
+ style={{ ...handleStyle(getFieldTypeColor(inputTemplate.type)), left: 0, opacity: 0, top: -14 }}
+ type="target"
+ />
+ ) : null
+ )}
+ </Box>
+);
+
+const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {
+ const dispatch = useWorkbenchDispatch();
+ const { templates } = useInvocationTemplatesSnapshot();
+ const isZoomedOut = useIsZoomedOut();
+ const node = data.documentNode;
+ const template = templates[node.data.type];
+ const execution = useNodeExecutionState(node.id);
+
+ if (!template) {
+ return (
+ <NodeShell isMissing selected={selected ?? false}>
+ <HStack gap="1.5" p="3">
+ <Icon as={TriangleAlertIcon} boxSize="3.5" color="red.solid" />
+ <Stack gap="0">
+ <Text fontWeight="700">{node.data.label || node.data.type}</Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ Unknown node type "{node.data.type}". It cannot run on this backend.
+ </Text>
+ </Stack>
+ </HStack>
+ </NodeShell>
+ );
+ }
+
+ const connectedFieldNames = new Set(data.connectedTargetHandles);
+ const exposedFieldNames = new Set(data.exposedFieldNames);
+ const inputTemplates = sortByUiOrder(Object.values(template.inputs).filter((input) => !input.uiHidden));
+ const outputTemplates = Object.values(template.outputs);
+ const isOpen = node.data.isOpen;
+ const isRunning = execution?.status === 'running';
+
+ return (
+ <NodeShell isRunning={isRunning} selected={selected ?? false}>
+ <Flex
+ align="center"
+ bg="bg.subtle"
+ borderBottomWidth={isOpen ? '1px' : '0'}
+ borderColor="border.subtle"
+ borderTopRadius="lg"
+ borderBottomRadius={isOpen ? 'none' : 'lg'}
+ gap="1"
+ px="2"
+ py="1.5"
+ >
+ <IconButton
+ aria-label={isOpen ? 'Collapse node' : 'Expand node'}
+ className="nodrag"
+ size="2xs"
+ variant="ghost"
+ onClick={() =>
+ dispatch({
+ action: { isOpen: !isOpen, nodeId: node.id, type: 'setNodeIsOpen' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ >
+ <Icon as={isOpen ? ChevronDownIcon : ChevronRightIcon} boxSize="3.5" />
+ </IconButton>
+ {isZoomedOut ? (
+ <Text fontSize="sm" fontWeight="700" minW="0" truncate>
+ {node.data.label || template.title}
+ </Text>
+ ) : (
+ <>
+ <NodeTitle node={node} />
+ <Box flex="1" />
+ <Tooltip content={template.description || template.type}>
+ <Badge size="xs" fontFamily="mono">
+ {template.type}
+ </Badge>
+ </Tooltip>
+ </>
+ )}
+ </Flex>
+ <NodeProgressStrip execution={execution} />
+ {isOpen ? (
+ <Box py="1">
+ {outputTemplates.map((outputTemplate) => (
+ <OutputFieldRow key={outputTemplate.name} isSkeleton={isZoomedOut} template={outputTemplate} />
+ ))}
+ {inputTemplates.map((inputTemplate) => (
+ <InputFieldRow
+ key={inputTemplate.name}
+ isConnected={connectedFieldNames.has(inputTemplate.name)}
+ isExposed={exposedFieldNames.has(inputTemplate.name)}
+ isSkeleton={isZoomedOut}
+ node={node}
+ template={inputTemplate}
+ />
+ ))}
+ </Box>
+ ) : (
+ <HiddenHandles inputTemplates={inputTemplates} outputTemplates={outputTemplates} />
+ )}
+ {isOpen && execution?.outputImageUrl ? (
+ <Box borderColor="border.subtle" borderTopWidth="1px" p="1.5">
+ {isZoomedOut ? (
+ <SkeletonBar h="6rem" w="full" />
+ ) : (
+ <Image
+ alt="Latest output of this node"
+ draggable={false}
+ maxH="10rem"
+ mx="auto"
+ objectFit="contain"
+ rounded="sm"
+ src={execution.outputImageUrl}
+ />
+ )}
+ </Box>
+ ) : null}
+ </NodeShell>
+ );
+};
+
+export const InvocationFlowNode = memo(InvocationFlowNodeComponent);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx
new file mode 100644
index 0000000000..cbe359a381
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NodeContextMenu.tsx
@@ -0,0 +1,89 @@
+import { Icon, Menu, Portal } from '@chakra-ui/react';
+import {
+ ChevronDownIcon,
+ ChevronRightIcon,
+ ClipboardPasteIcon,
+ CopyIcon,
+ CopyPlusIcon,
+ Trash2Icon,
+} from 'lucide-react';
+
+/**
+ * Right-click utilities for a flow node, anchored at the pointer. The menu is
+ * fully controlled — the editor owns the open state and the actions, since
+ * copy/paste/duplicate need the flow instance and selection context.
+ */
+
+export interface NodeContextMenuState {
+ nodeId: string;
+ /** The node's `isOpen`; null for node types without a collapse toggle (notes). */
+ isNodeOpen: boolean | null;
+ x: number;
+ y: number;
+}
+
+export const NodeContextMenu = ({
+ canPaste,
+ menuState,
+ onClose,
+ onCopy,
+ onDelete,
+ onDuplicate,
+ onPaste,
+ onToggleOpen,
+}: {
+ canPaste: boolean;
+ menuState: NodeContextMenuState | null;
+ onClose: () => void;
+ onCopy: () => void;
+ onDelete: () => void;
+ onDuplicate: () => void;
+ onPaste: () => void;
+ onToggleOpen: () => void;
+}) => (
+ <Menu.Root
+ open={menuState !== null}
+ positioning={{
+ getAnchorRect: () => (menuState ? { height: 1, width: 1, x: menuState.x, y: menuState.y } : null),
+ placement: 'bottom-start',
+ }}
+ onOpenChange={(event) => {
+ if (!event.open) {
+ onClose();
+ }
+ }}
+ >
+ <Portal>
+ <Menu.Positioner>
+ <Menu.Content minW="11rem">
+ <Menu.Item value="copy" onClick={onCopy}>
+ <Icon as={CopyIcon} boxSize="3.5" />
+ <Menu.ItemText>Copy</Menu.ItemText>
+ <Menu.ItemCommand>Ctrl C</Menu.ItemCommand>
+ </Menu.Item>
+ <Menu.Item disabled={!canPaste} value="paste" _disabled={{ opacity: 0.4 }} onClick={onPaste}>
+ <Icon as={ClipboardPasteIcon} boxSize="3.5" />
+ <Menu.ItemText>Paste</Menu.ItemText>
+ <Menu.ItemCommand>Ctrl V</Menu.ItemCommand>
+ </Menu.Item>
+ <Menu.Item value="duplicate" onClick={onDuplicate}>
+ <Icon as={CopyPlusIcon} boxSize="3.5" />
+ <Menu.ItemText>Duplicate</Menu.ItemText>
+ </Menu.Item>
+ {menuState?.isNodeOpen !== null ? (
+ <Menu.Item value="toggle-open" onClick={onToggleOpen}>
+ <Icon as={menuState?.isNodeOpen ? ChevronRightIcon : ChevronDownIcon} boxSize="3.5" />
+ <Menu.ItemText>{menuState?.isNodeOpen ? 'Collapse' : 'Expand'}</Menu.ItemText>
+ </Menu.Item>
+ ) : null}
+ <Menu.Separator borderColor="border.subtle" />
+ <Menu.Item color="fg.error" value="delete" onClick={onDelete}>
+ <Icon as={Trash2Icon} boxSize="3.5" />
+ <Menu.ItemText>Delete</Menu.ItemText>
+ <Menu.ItemCommand>Del</Menu.ItemCommand>
+ </Menu.Item>
+ </Menu.Content>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx
new file mode 100644
index 0000000000..8dcfd22735
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/NotesFlowNode.tsx
@@ -0,0 +1,57 @@
+import { Box, Input, Textarea } from '@chakra-ui/react';
+import type { NodeProps } from '@xyflow/react';
+import { memo, type ChangeEvent } from 'react';
+
+import { useWorkbenchDispatch } from '../../../WorkbenchContext';
+import type { NotesFlowNode as NotesFlowNodeType } from './flowAdapters';
+
+const NotesFlowNodeComponent = ({ data, selected }: NodeProps<NotesFlowNodeType>) => {
+ const dispatch = useWorkbenchDispatch();
+ const node = data.documentNode;
+
+ return (
+ <Box
+ bg="bg.subtle"
+ borderColor={selected ? 'accent.solid' : 'border.emphasized'}
+ borderWidth="1px"
+ p="2"
+ rounded="lg"
+ shadow={selected ? 'md' : 'sm'}
+ w="16rem"
+ >
+ <Input
+ aria-label="Note title"
+ className="nodrag"
+ fontWeight="700"
+ mb="1.5"
+ size="2xs"
+ value={node.data.label}
+ variant="flushed"
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ dispatch({
+ action: { label: event.currentTarget.value, nodeId: node.id, type: 'setNodeLabel' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ <Textarea
+ aria-label="Note text"
+ className="nodrag nowheel"
+ fontSize="2xs"
+ minH="5rem"
+ placeholder="Write a note…"
+ resize="vertical"
+ size="xs"
+ value={node.data.notes}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>
+ dispatch({
+ action: { nodeId: node.id, notes: event.currentTarget.value, type: 'setNodeNotes' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ </Box>
+ );
+};
+
+export const NotesFlowNode = memo(NotesFlowNodeComponent);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
new file mode 100644
index 0000000000..1d78ad034b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
@@ -0,0 +1,513 @@
+import { Box, Flex, Stack, Text } from '@chakra-ui/react';
+import {
+ Background,
+ BackgroundVariant,
+ ConnectionLineType,
+ ReactFlow,
+ ReactFlowProvider,
+ SelectionMode,
+ applyEdgeChanges,
+ applyNodeChanges,
+ type Connection,
+ type Edge as FlowEdge,
+ type EdgeChange,
+ type IsValidConnection,
+ type NodeChange,
+ type NodeTypes,
+} from '@xyflow/react';
+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react';
+
+import '@xyflow/react/dist/style.css';
+
+import { FlowMiniMap } from '../../../components/FlowMiniMap';
+import { flowThemeCss, getFlowColorMode } from '../../../components/flowTheme';
+import { useNotify } from '../../../useNotify';
+import { useWorkbenchPreferences } from '../../../settings/store';
+import { useWorkbench } from '../../../WorkbenchContext';
+import { getProjectGraphReadiness } from '../../../workflows/buildGraph';
+import { createWorkflowId } from '../../../workflows/document';
+import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSnapshot } from '../../../workflows/templates';
+import { validateConnection } from '../../../workflows/validation';
+import { buildDuplicateElements, buildPasteElements, copyNodesToClipboard, useHasClipboardNodes } from './clipboard';
+import { CurrentImageFlowNode } from './CurrentImageFlowNode';
+import { EditorToolbar, type EditorTool } from './EditorToolbar';
+import { toFlowEdges, toFlowNodes, withNodeSelection, type FlowEdgeType, type WorkflowFlowNode } from './flowAdapters';
+import {
+ registerWorkflowFlowInstance,
+ releaseWorkflowFlowInstance,
+ type WorkflowFlowInstance,
+} from './flowInstanceStore';
+import { InvocationFlowNode } from './InvocationFlowNode';
+import { NodeContextMenu, type NodeContextMenuState } from './NodeContextMenu';
+import { NotesFlowNode } from './NotesFlowNode';
+import { clearNodeSelectionRequest, reportNodeSelection, workflowSelectionStore } from './selectionStore';
+import { useEraser } from './useEraser';
+import { useLasso } from './useLasso';
+import { useModifierHeld } from './useModifierHeld';
+
+const nodeTypes: NodeTypes = {
+ current_image: CurrentImageFlowNode,
+ invocation: InvocationFlowNode,
+ notes: NotesFlowNode,
+};
+
+/**
+ * The workflow center view: an xyflow editor over the project graph document.
+ * The document is the source of truth — flow state is rebuilt from it on every
+ * document change (undo, import, field edits), while transient view state
+ * (selection, in-flight drags, the active tool) lives in local component state.
+ */
+/** Snap spacing matches the background dot grid. */
+const SNAP_GRID: [number, number] = [24, 24];
+
+const DELETE_KEY_CODES = ['Backspace', 'Delete'];
+
+const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 1.5 } };
+
+const isEditableTarget = (target: EventTarget | null): boolean =>
+ target instanceof HTMLElement && target.closest('input, textarea, select, [contenteditable="true"]') !== null;
+
+const WorkflowFlow = () => {
+ const { activeProject, dispatch } = useWorkbench();
+ const notify = useNotify();
+ const { themeId, workflowEdgeStyle, workflowShowMinimap, workflowSnapToGrid, workflowValidateConnections } =
+ useWorkbenchPreferences();
+ const templatesSnapshot = useInvocationTemplatesSnapshot();
+ const projectGraph = activeProject.projectGraph;
+ const edgeType: FlowEdgeType = workflowEdgeStyle === 'straight' ? 'straight' : 'default';
+ const [flowNodes, setFlowNodes] = useState<WorkflowFlowNode[]>(() => toFlowNodes(projectGraph));
+ const [flowEdges, setFlowEdges] = useState<FlowEdge[]>(() => toFlowEdges(projectGraph, [], edgeType));
+ const [flowInstance, setFlowInstance] = useState<WorkflowFlowInstance | null>(null);
+ const [tool, setTool] = useState<EditorTool>('pan');
+ const [nodeOpacity, setNodeOpacity] = useState(1);
+ const [contextMenu, setContextMenu] = useState<NodeContextMenuState | null>(null);
+ const { selectionRequest } = workflowSelectionStore.useSnapshot();
+ const isSnapHeld = useModifierHeld('Control');
+ const hasClipboardNodes = useHasClipboardNodes();
+ /** Node ids to select once the next document-driven rebuild lands (fresh paste/duplicate results). */
+ const pendingSelectionRef = useRef<string[] | null>(null);
+
+ const selectNodes = useCallback((nodeIds: string[]) => {
+ setFlowNodes((current) => withNodeSelection(current, new Set(nodeIds)));
+ reportNodeSelection(nodeIds);
+ }, []);
+
+ const { lassoHandlers, lassoOverlay } = useLasso({
+ enabled: tool === 'lasso',
+ flowInstance,
+ onSelect: selectNodes,
+ });
+ const eraseElements = useCallback(
+ ({ edgeIds, nodeIds }: { edgeIds: string[]; nodeIds: string[] }) => {
+ const requestedNodeIds = new Set(nodeIds);
+ const existingNodeIds = projectGraph.nodes.filter((node) => requestedNodeIds.has(node.id)).map((node) => node.id);
+
+ if (existingNodeIds.length > 0) {
+ dispatch({ action: { nodeIds: existingNodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });
+ }
+
+ const removedNodeIds = new Set(existingNodeIds);
+ const requestedEdgeIds = new Set(edgeIds);
+ const existingEdgeIds = projectGraph.edges
+ .filter(
+ (edge) =>
+ requestedEdgeIds.has(edge.id) && !removedNodeIds.has(edge.source) && !removedNodeIds.has(edge.target)
+ )
+ .map((edge) => edge.id);
+
+ if (existingEdgeIds.length > 0) {
+ dispatch({ action: { edgeIds: existingEdgeIds, type: 'removeEdges' }, type: 'applyProjectGraphAction' });
+ }
+ },
+ [dispatch, projectGraph.edges, projectGraph.nodes]
+ );
+ const { eraserHandlers, eraserOverlay } = useEraser({
+ enabled: tool === 'eraser',
+ flowInstance,
+ onErase: eraseElements,
+ });
+ const pointerToolHandlers = tool === 'lasso' ? lassoHandlers : tool === 'eraser' ? eraserHandlers : {};
+
+ useEffect(() => {
+ const pendingSelection = pendingSelectionRef.current;
+
+ pendingSelectionRef.current = null;
+ setFlowNodes((current) => {
+ const next = toFlowNodes(projectGraph, current);
+
+ return pendingSelection ? withNodeSelection(next, new Set(pendingSelection)) : next;
+ });
+ setFlowEdges((current) => toFlowEdges(projectGraph, current, edgeType));
+
+ if (pendingSelection) {
+ reportNodeSelection(pendingSelection);
+ }
+ }, [edgeType, projectGraph]);
+
+ // Expose the instance to the widget header's actions (outside this provider).
+ useEffect(() => {
+ if (!flowInstance) {
+ return undefined;
+ }
+
+ registerWorkflowFlowInstance(flowInstance);
+
+ return () => {
+ releaseWorkflowFlowInstance(flowInstance);
+ };
+ }, [flowInstance]);
+
+ // Outside surfaces (the form builder's zoom-to-node) request a selection;
+ // the editor applies it and brings the nodes into view.
+ useEffect(() => {
+ if (!selectionRequest || !flowInstance) {
+ return;
+ }
+
+ selectNodes(selectionRequest.nodeIds);
+ void flowInstance.fitView({
+ duration: 300,
+ maxZoom: 1.25,
+ nodes: selectionRequest.nodeIds.map((id) => ({ id })),
+ });
+ clearNodeSelectionRequest();
+ }, [flowInstance, selectNodes, selectionRequest]);
+
+ /** The context-menu node acts alone unless it is part of the current selection. */
+ const getActionNodeIds = (nodeId?: string): string[] => {
+ const selectedIds = flowNodes.filter((node) => node.selected).map((node) => node.id);
+
+ if (nodeId && !selectedIds.includes(nodeId)) {
+ return [nodeId];
+ }
+
+ return selectedIds;
+ };
+
+ const copyNodes = (nodeId?: string) => {
+ const copiedCount = copyNodesToClipboard(projectGraph, getActionNodeIds(nodeId));
+
+ if (copiedCount > 0) {
+ notify.success(`Copied ${copiedCount} node${copiedCount === 1 ? '' : 's'}`);
+ }
+ };
+
+ const pasteNodes = () => {
+ const { edges, nodes } = buildPasteElements();
+
+ if (nodes.length === 0) {
+ return;
+ }
+
+ pendingSelectionRef.current = nodes.map((node) => node.id);
+ dispatch({ action: { edges, nodes, type: 'addGraphElements' }, type: 'applyProjectGraphAction' });
+ };
+
+ const duplicateNodes = (nodeId?: string) => {
+ const { edges, nodes } = buildDuplicateElements(projectGraph, getActionNodeIds(nodeId));
+
+ if (nodes.length === 0) {
+ return;
+ }
+
+ pendingSelectionRef.current = nodes.map((node) => node.id);
+ dispatch({ action: { edges, nodes, type: 'addGraphElements' }, type: 'applyProjectGraphAction' });
+ };
+
+ const deleteNodes = (nodeId?: string) => {
+ const nodeIds = getActionNodeIds(nodeId);
+
+ if (nodeIds.length > 0) {
+ dispatch({ action: { nodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });
+ }
+ };
+
+ const onEditorKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (isEditableTarget(event.target) || !(event.ctrlKey || event.metaKey)) {
+ return;
+ }
+
+ const key = event.key.toLowerCase();
+
+ if (key === 'c') {
+ copyNodes();
+ } else if (key === 'v') {
+ pasteNodes();
+ } else if (key === 'd') {
+ event.preventDefault();
+ duplicateNodes();
+ }
+ };
+
+ const onNodesChange = useCallback(
+ (changes: NodeChange<WorkflowFlowNode>[]) => {
+ const removedNodeIds = changes.flatMap((change) => (change.type === 'remove' ? [change.id] : []));
+
+ if (removedNodeIds.length > 0) {
+ dispatch({ action: { nodeIds: removedNodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });
+ }
+
+ for (const change of changes) {
+ if (change.type === 'position' && change.dragging === false && change.position) {
+ dispatch({
+ action: { nodeId: change.id, position: change.position, type: 'setNodePosition' },
+ type: 'applyProjectGraphAction',
+ });
+ }
+ }
+
+ setFlowNodes((current) => applyNodeChanges(changes, current));
+ },
+ [dispatch]
+ );
+
+ const onEdgesChange = useCallback(
+ (changes: EdgeChange<FlowEdge>[]) => {
+ const removedEdgeIds = changes.flatMap((change) => (change.type === 'remove' ? [change.id] : []));
+
+ if (removedEdgeIds.length > 0) {
+ dispatch({ action: { edgeIds: removedEdgeIds, type: 'removeEdges' }, type: 'applyProjectGraphAction' });
+ }
+
+ setFlowEdges((current) => applyEdgeChanges(changes, current));
+ },
+ [dispatch]
+ );
+
+ const isValidConnection: IsValidConnection<FlowEdge> = useCallback(
+ (connection) => {
+ if (!connection.sourceHandle || !connection.targetHandle) {
+ return false;
+ }
+
+ // Lenient wiring: the user opted out of type validation in settings.
+ if (!workflowValidateConnections) {
+ return true;
+ }
+
+ return (
+ validateConnection(
+ {
+ sourceHandle: connection.sourceHandle,
+ sourceNodeId: connection.source,
+ targetHandle: connection.targetHandle,
+ targetNodeId: connection.target,
+ },
+ projectGraph,
+ templatesSnapshot.templates
+ ) === null
+ );
+ },
+ [projectGraph, templatesSnapshot.templates, workflowValidateConnections]
+ );
+
+ const onConnect = useCallback(
+ (connection: Connection) => {
+ if (!connection.sourceHandle || !connection.targetHandle) {
+ return;
+ }
+
+ dispatch({
+ action: {
+ edge: {
+ id: createWorkflowId('edge'),
+ source: connection.source,
+ sourceHandle: connection.sourceHandle,
+ target: connection.target,
+ targetHandle: connection.targetHandle,
+ type: 'default',
+ },
+ type: 'addEdge',
+ },
+ type: 'applyProjectGraphAction',
+ });
+ },
+ [dispatch]
+ );
+
+ const onNodeContextMenu = useCallback((event: MouseEvent, node: WorkflowFlowNode) => {
+ event.preventDefault();
+ setContextMenu({
+ isNodeOpen: node.type === 'invocation' ? node.data.documentNode.data.isOpen : null,
+ nodeId: node.id,
+ x: event.clientX,
+ y: event.clientY,
+ });
+ }, []);
+
+ const onNodeClick = useCallback(
+ (_: MouseEvent, node: WorkflowFlowNode) => {
+ if (tool === 'eraser') {
+ eraseElements({ edgeIds: [], nodeIds: [node.id] });
+ }
+ },
+ [eraseElements, tool]
+ );
+
+ const onEdgeClick = useCallback(
+ (_: MouseEvent, edge: FlowEdge) => {
+ if (tool === 'eraser') {
+ eraseElements({ edgeIds: [edge.id], nodeIds: [] });
+ }
+ },
+ [eraseElements, tool]
+ );
+
+ const onSelectionChange = useCallback(
+ ({ nodes }: { nodes: WorkflowFlowNode[] }) => reportNodeSelection(nodes.map((node) => node.id)),
+ []
+ );
+
+ const editorCss = useMemo(
+ () => ({
+ ...flowThemeCss,
+ '& .react-flow__node': { opacity: nodeOpacity },
+ ...(tool === 'eraser'
+ ? { '& .react-flow__edge, & .react-flow__node, & .react-flow__pane': { cursor: 'crosshair' } }
+ : {}),
+ ...(tool === 'lasso' ? { '& .react-flow__pane': { cursor: 'crosshair' } } : {}),
+ }),
+ [nodeOpacity, tool]
+ );
+
+ return (
+ <Box
+ bg="bg.inset"
+ css={editorCss}
+ h="full"
+ position="relative"
+ w="full"
+ onKeyDown={onEditorKeyDown}
+ {...pointerToolHandlers}
+ >
+ <ReactFlow
+ colorMode={getFlowColorMode(themeId)}
+ connectionLineType={edgeType === 'straight' ? ConnectionLineType.Straight : ConnectionLineType.Bezier}
+ defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}
+ deleteKeyCode={DELETE_KEY_CODES}
+ edges={flowEdges}
+ fitView
+ isValidConnection={isValidConnection}
+ maxZoom={2}
+ minZoom={0.1}
+ nodes={flowNodes}
+ nodeTypes={nodeTypes}
+ panOnDrag={tool === 'pan' ? true : [1, 2]}
+ proOptions={{ hideAttribution: true }}
+ selectionMode={SelectionMode.Partial}
+ selectionOnDrag={tool === 'box-select'}
+ snapGrid={SNAP_GRID}
+ snapToGrid={workflowSnapToGrid || isSnapHeld}
+ style={{ background: 'transparent' }}
+ onConnect={onConnect}
+ onEdgeClick={onEdgeClick}
+ onEdgesChange={onEdgesChange}
+ onInit={setFlowInstance}
+ onNodeClick={onNodeClick}
+ onNodeContextMenu={onNodeContextMenu}
+ onNodesChange={onNodesChange}
+ onSelectionChange={onSelectionChange}
+ >
+ <Background color="var(--wb-flow-grid)" gap={24} size={1.5} variant={BackgroundVariant.Dots} />
+ <EditorToolbar
+ nodeOpacity={nodeOpacity}
+ tool={tool}
+ onNodeOpacityChange={setNodeOpacity}
+ onToolChange={setTool}
+ />
+ {workflowShowMinimap ? <FlowMiniMap /> : null}
+ </ReactFlow>
+ {lassoOverlay}
+ {eraserOverlay}
+ <NodeContextMenu
+ canPaste={hasClipboardNodes}
+ menuState={contextMenu}
+ onClose={() => setContextMenu(null)}
+ onCopy={() => {
+ copyNodes(contextMenu?.nodeId);
+ setContextMenu(null);
+ }}
+ onDelete={() => {
+ deleteNodes(contextMenu?.nodeId);
+ setContextMenu(null);
+ }}
+ onDuplicate={() => {
+ duplicateNodes(contextMenu?.nodeId);
+ setContextMenu(null);
+ }}
+ onPaste={() => {
+ pasteNodes();
+ setContextMenu(null);
+ }}
+ onToggleOpen={() => {
+ if (contextMenu && contextMenu.isNodeOpen !== null) {
+ dispatch({
+ action: { isOpen: !contextMenu.isNodeOpen, nodeId: contextMenu.nodeId, type: 'setNodeIsOpen' },
+ type: 'applyProjectGraphAction',
+ });
+ }
+
+ setContextMenu(null);
+ }}
+ />
+ </Box>
+ );
+};
+
+const ReadinessBanner = () => {
+ const { activeProject } = useWorkbench();
+ const templatesSnapshot = useInvocationTemplatesSnapshot();
+ const readiness = useMemo(
+ () => getProjectGraphReadiness(activeProject.projectGraph, templatesSnapshot),
+ [activeProject.projectGraph, templatesSnapshot]
+ );
+
+ if (readiness.canInvoke || activeProject.projectGraph.nodes.length === 0) {
+ return null;
+ }
+
+ return (
+ <Box
+ bg="bg.muted"
+ borderColor="border.subtle"
+ borderRadius="md"
+ borderWidth="1px"
+ left="3"
+ maxW="24rem"
+ p="2"
+ position="absolute"
+ top="3"
+ zIndex="1"
+ >
+ <Stack gap="0.5">
+ {readiness.reasons.slice(0, 4).map((reason) => (
+ <Text key={reason} color="fg.muted" fontSize="2xs">
+ {reason}
+ </Text>
+ ))}
+ {readiness.reasons.length > 4 ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ +{readiness.reasons.length - 4} more
+ </Text>
+ ) : null}
+ </Stack>
+ </Box>
+ );
+};
+
+export const WorkflowEditorView = () => {
+ useEffect(() => {
+ ensureInvocationTemplatesLoaded();
+ }, []);
+
+ return (
+ <ReactFlowProvider>
+ <Flex direction="column" h="full" minH="0" w="full">
+ <Box flex="1" minH="0" position="relative">
+ <WorkflowFlow />
+ <ReadinessBanner />
+ </Box>
+ </Flex>
+ </ReactFlowProvider>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.test.ts
new file mode 100644
index 0000000000..9482059741
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from 'vitest';
+
+import { createProjectGraph } from '../../../workflows/document';
+import type { ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from '../../../workflows/types';
+import { buildDuplicateElements, buildPasteElements, copyNodesToClipboard, hasClipboardNodes } from './clipboard';
+
+const createNode = (id: string, x: number, y: number): WorkflowInvocationNode => ({
+ data: {
+ inputs: { a: { label: '', name: 'a', value: 1 } },
+ isIntermediate: true,
+ isOpen: true,
+ label: '',
+ nodePack: 'invokeai',
+ notes: '',
+ type: 'add',
+ useCache: true,
+ version: '1.0.0',
+ },
+ id,
+ position: { x, y },
+ type: 'invocation',
+});
+
+const createEdge = (id: string, source: string, target: string): WorkflowEdge => ({
+ id,
+ source,
+ sourceHandle: 'value',
+ target,
+ targetHandle: 'a',
+ type: 'default',
+});
+
+const createDoc = (): ProjectGraphState => ({
+ ...createProjectGraph('clipboard-test'),
+ edges: [createEdge('edge-1', 'node-a', 'node-b'), createEdge('edge-2', 'node-outside', 'node-a')],
+ nodes: [createNode('node-a', 0, 0), createNode('node-b', 100, 50), createNode('node-outside', -200, 0)],
+});
+
+describe('workflow clipboard', () => {
+ it('copies selected nodes with only their internal edges', () => {
+ const copiedCount = copyNodesToClipboard(createDoc(), ['node-a', 'node-b']);
+
+ expect(copiedCount).toBe(2);
+ expect(hasClipboardNodes()).toBe(true);
+
+ const { edges, nodes } = buildPasteElements();
+
+ expect(nodes).toHaveLength(2);
+ // The edge from node-outside is not part of the copied set.
+ expect(edges).toHaveLength(1);
+ });
+
+ it('pastes with fresh ids, remapped edges, and offset positions', () => {
+ copyNodesToClipboard(createDoc(), ['node-a', 'node-b']);
+
+ const { edges, nodes } = buildPasteElements();
+ const pastedIds = new Set(nodes.map((node) => node.id));
+
+ expect(pastedIds.has('node-a')).toBe(false);
+ expect(pastedIds.has('node-b')).toBe(false);
+ expect(edges[0]?.id).not.toBe('edge-1');
+ expect(pastedIds.has(edges[0]?.source ?? '')).toBe(true);
+ expect(pastedIds.has(edges[0]?.target ?? '')).toBe(true);
+ expect(nodes[0]?.position).toEqual({ x: 32, y: 32 });
+
+ // Pasting twice yields fresh ids each time.
+ const second = buildPasteElements();
+
+ expect(second.nodes.every((node) => !pastedIds.has(node.id))).toBe(true);
+ });
+
+ it('anchors the pasted group on an explicit position, preserving relative layout', () => {
+ copyNodesToClipboard(createDoc(), ['node-a', 'node-b']);
+
+ const { nodes } = buildPasteElements({ x: 500, y: 500 });
+
+ expect(nodes.map((node) => node.position)).toEqual([
+ { x: 500, y: 500 },
+ { x: 600, y: 550 },
+ ]);
+ });
+
+ it('duplicates in place without touching the clipboard', () => {
+ copyNodesToClipboard(createDoc(), ['node-a']);
+
+ const { edges, nodes } = buildDuplicateElements(createDoc(), ['node-a', 'node-b']);
+
+ expect(nodes).toHaveLength(2);
+ expect(edges).toHaveLength(1);
+ // The clipboard still holds the single copied node.
+ expect(buildPasteElements().nodes).toHaveLength(1);
+ });
+
+ it('copying nothing leaves the clipboard untouched', () => {
+ copyNodesToClipboard(createDoc(), ['node-a']);
+
+ expect(copyNodesToClipboard(createDoc(), ['missing-node'])).toBe(0);
+ expect(buildPasteElements().nodes).toHaveLength(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts
new file mode 100644
index 0000000000..22e7d8949b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts
@@ -0,0 +1,101 @@
+import { createExternalStore } from '../../../externalStore';
+import { createWorkflowId } from '../../../workflows/document';
+import type { ProjectGraphState, WorkflowEdge, WorkflowNode, XYPosition } from '../../../workflows/types';
+
+/**
+ * Session-lived clipboard for workflow nodes. Copies hold deep clones of the
+ * selected nodes plus the edges that connect them to each other; pasting
+ * materializes fresh ids (remapping those internal edges) so a payload can be
+ * pasted repeatedly. Deliberately not the system clipboard: node fragments are
+ * not a valid workflow JSON, so a partial graph on the OS clipboard would only
+ * masquerade as an importable document.
+ */
+
+interface WorkflowClipboardSnapshot {
+ nodes: WorkflowNode[];
+ edges: WorkflowEdge[];
+}
+
+const clipboardStore = createExternalStore<WorkflowClipboardSnapshot>({ edges: [], nodes: [] });
+
+const PASTE_OFFSET = 32;
+
+export const copyNodesToClipboard = (document: ProjectGraphState, nodeIds: string[]): number => {
+ const copiedIds = new Set(nodeIds);
+ const nodes = document.nodes.filter((node) => copiedIds.has(node.id));
+
+ if (nodes.length === 0) {
+ return 0;
+ }
+
+ const edges = document.edges.filter((edge) => copiedIds.has(edge.source) && copiedIds.has(edge.target));
+
+ clipboardStore.setSnapshot(structuredClone({ edges, nodes }));
+
+ return nodes.length;
+};
+
+export const hasClipboardNodes = (): boolean => clipboardStore.getSnapshot().nodes.length > 0;
+
+export const useHasClipboardNodes = (): boolean => clipboardStore.useSnapshot().nodes.length > 0;
+
+const materializeElements = (
+ payload: WorkflowClipboardSnapshot,
+ at?: XYPosition
+): { nodes: WorkflowNode[]; edges: WorkflowEdge[] } => {
+ const { edges, nodes } = structuredClone(payload);
+
+ if (nodes.length === 0) {
+ return { edges: [], nodes: [] };
+ }
+
+ const idMap = new Map<string, string>();
+
+ for (const node of nodes) {
+ idMap.set(node.id, createWorkflowId(node.type === 'invocation' ? node.data.type : node.type));
+ }
+
+ let offset: XYPosition = { x: PASTE_OFFSET, y: PASTE_OFFSET };
+
+ if (at) {
+ const minX = Math.min(...nodes.map((node) => node.position.x));
+ const minY = Math.min(...nodes.map((node) => node.position.y));
+
+ offset = { x: at.x - minX, y: at.y - minY };
+ }
+
+ return {
+ edges: edges.map((edge) => ({
+ ...edge,
+ id: createWorkflowId('edge'),
+ source: idMap.get(edge.source) ?? edge.source,
+ target: idMap.get(edge.target) ?? edge.target,
+ })),
+ nodes: nodes.map((node) => ({
+ ...node,
+ id: idMap.get(node.id) ?? node.id,
+ position: { x: node.position.x + offset.x, y: node.position.y + offset.y },
+ })),
+ };
+};
+
+/**
+ * Materializes the clipboard into paste-ready elements with fresh ids.
+ * Positions shift by a fixed offset from the copied originals (or anchor the
+ * group's top-left on `at` when given) so pastes do not stack on their source.
+ */
+export const buildPasteElements = (at?: XYPosition): { nodes: WorkflowNode[]; edges: WorkflowEdge[] } =>
+ materializeElements(clipboardStore.getSnapshot(), at);
+
+/** Clone-in-place for the given nodes (and their internal edges) without touching the clipboard. */
+export const buildDuplicateElements = (
+ document: ProjectGraphState,
+ nodeIds: string[]
+): { nodes: WorkflowNode[]; edges: WorkflowEdge[] } => {
+ const copiedIds = new Set(nodeIds);
+
+ return materializeElements({
+ edges: document.edges.filter((edge) => copiedIds.has(edge.source) && copiedIds.has(edge.target)),
+ nodes: document.nodes.filter((node) => copiedIds.has(node.id)),
+ });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts
new file mode 100644
index 0000000000..bcb77f4a2c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCurrentImageNode, createProjectGraph } from '../../../workflows/document';
+import type { ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from '../../../workflows/types';
+import { toFlowEdges, toFlowNodes, withNodeSelection } from './flowAdapters';
+
+const createNode = (id: string): WorkflowInvocationNode => ({
+ data: {
+ inputs: {},
+ isIntermediate: true,
+ isOpen: true,
+ label: '',
+ nodePack: 'invokeai',
+ notes: '',
+ type: 'add',
+ useCache: true,
+ version: '1.0.0',
+ },
+ id,
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+});
+
+const createEdge = (id: string, source: string, target: string): WorkflowEdge => ({
+ id,
+ source,
+ sourceHandle: 'value',
+ target,
+ targetHandle: 'a',
+ type: 'default',
+});
+
+const createDoc = (overrides?: Partial<ProjectGraphState>): ProjectGraphState => ({
+ ...createProjectGraph('adapters-test'),
+ edges: [createEdge('e1', 'a', 'b')],
+ nodes: [createNode('a'), createNode('b')],
+ ...overrides,
+});
+
+describe('flowAdapters identity preservation', () => {
+ it('reuses unchanged node objects across rebuilds (memo-friendly)', () => {
+ const doc = createDoc();
+ const first = toFlowNodes(doc);
+ const second = toFlowNodes(doc, first);
+
+ expect(second[0]).toBe(first[0]);
+ expect(second[1]).toBe(first[1]);
+ });
+
+ it('replaces only the node whose document node changed', () => {
+ const doc = createDoc();
+ const first = toFlowNodes(doc);
+ const movedNodeB = { ...doc.nodes[1]!, position: { x: 50, y: 50 } };
+ const second = toFlowNodes({ ...doc, nodes: [doc.nodes[0]!, movedNodeB] }, first);
+
+ expect(second[0]).toBe(first[0]);
+ expect(second[1]).not.toBe(first[1]);
+ });
+
+ it('recomputes a node when its incoming connections change', () => {
+ const doc = createDoc();
+ const first = toFlowNodes(doc);
+ // Drop the edge into node b; its connectedTargetHandles must update.
+ const second = toFlowNodes({ ...doc, edges: [] }, first);
+ const nodeB = second[1];
+
+ expect(nodeB?.type === 'invocation' && nodeB.data.connectedTargetHandles).toEqual([]);
+ expect(second[1]).not.toBe(first[1]);
+ // Node a had no incoming edges either way — still identity-stable.
+ expect(second[0]).toBe(first[0]);
+ });
+
+ it('precomputes exposed field names onto invocation node data', () => {
+ const doc = createDoc();
+ const exposed = {
+ ...doc,
+ form: {
+ ...doc.form,
+ elements: {
+ ...doc.form.elements,
+ 'field-1': {
+ data: { fieldIdentifier: { fieldName: 'a', nodeId: 'b' }, showDescription: false },
+ id: 'field-1',
+ parentId: doc.form.rootElementId,
+ type: 'node-field' as const,
+ },
+ },
+ },
+ };
+ const nodes = toFlowNodes(exposed);
+ const nodeB = nodes[1];
+
+ expect(nodeB?.type === 'invocation' && nodeB.data.exposedFieldNames).toEqual(['a']);
+ });
+
+ it('carries selection across rebuilds and toggles it without copying unchanged nodes', () => {
+ const doc = createDoc();
+ const selected = withNodeSelection(toFlowNodes(doc), new Set(['a']));
+
+ expect(selected[0]?.selected).toBe(true);
+
+ const rebuilt = toFlowNodes(doc, selected);
+
+ expect(rebuilt[0]?.selected).toBe(true);
+
+ // Re-applying the same selection set returns identical node objects.
+ const reselected = withNodeSelection(selected, new Set(['a']));
+
+ expect(reselected[0]).toBe(selected[0]);
+ });
+
+ it('builds current_image nodes and reuses them when unchanged', () => {
+ const currentImage = buildCurrentImageNode({ x: 0, y: 0 });
+ const doc = createDoc({ nodes: [createNode('a'), currentImage] });
+ const first = toFlowNodes(doc);
+
+ expect(first[1]?.type).toBe('current_image');
+ expect(toFlowNodes(doc, first)[1]).toBe(first[1]);
+ });
+
+ it('reuses unchanged edge objects but replaces edges on type change', () => {
+ const doc = createDoc();
+ const first = toFlowEdges(doc, [], 'default');
+ const same = toFlowEdges(doc, first, 'default');
+
+ expect(same[0]).toBe(first[0]);
+
+ const restyled = toFlowEdges(doc, first, 'straight');
+
+ expect(restyled[0]).not.toBe(first[0]);
+ expect(restyled[0]?.type).toBe('straight');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts
new file mode 100644
index 0000000000..1785427f17
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts
@@ -0,0 +1,190 @@
+import type { Edge as FlowEdge, Node as FlowNode } from '@xyflow/react';
+
+import type {
+ ProjectGraphState,
+ WorkflowCurrentImageNode,
+ WorkflowInvocationNode,
+ WorkflowNotesNode,
+} from '../../../workflows/types';
+
+/**
+ * Adapters between the project graph document and xyflow's node/edge state.
+ * The document is the source of truth; xyflow state is rebuilt from it on
+ * every document change, carrying over transient view state (selection).
+ *
+ * Rebuilds preserve object identity for unchanged nodes/edges so memoized
+ * node components skip re-rendering (see React Flow's performance guidance) —
+ * the document reducer already keeps untouched node identities stable.
+ * Derived per-node facts the node components need (incoming connections,
+ * Linear-UI exposure) are precomputed into `data` here, so node components
+ * never subscribe to workbench state.
+ */
+
+export type InvocationFlowNode = FlowNode<
+ {
+ documentNode: WorkflowInvocationNode;
+ /** Target handle names with an incoming edge. */
+ connectedTargetHandles: string[];
+ /** Field names of this node exposed in the Linear UI form. */
+ exposedFieldNames: string[];
+ },
+ 'invocation'
+>;
+export type NotesFlowNode = FlowNode<{ documentNode: WorkflowNotesNode }, 'notes'>;
+export type CurrentImageFlowNode = FlowNode<{ documentNode: WorkflowCurrentImageNode }, 'current_image'>;
+export type WorkflowFlowNode = InvocationFlowNode | NotesFlowNode | CurrentImageFlowNode;
+
+const EMPTY_NAMES: string[] = [];
+
+const sameNames = (a: string[], b: string[]): boolean => a.length === b.length && a.every((name, i) => name === b[i]);
+
+const getConnectedHandlesByNode = (document: ProjectGraphState): Map<string, string[]> => {
+ const byNode = new Map<string, string[]>();
+
+ for (const edge of document.edges) {
+ byNode.set(edge.target, [...(byNode.get(edge.target) ?? []), edge.targetHandle]);
+ }
+
+ for (const handles of byNode.values()) {
+ handles.sort();
+ }
+
+ return byNode;
+};
+
+const getExposedFieldsByNode = (document: ProjectGraphState): Map<string, string[]> => {
+ const byNode = new Map<string, string[]>();
+
+ for (const element of Object.values(document.form.elements)) {
+ if (element.type === 'node-field') {
+ const { fieldName, nodeId } = element.data.fieldIdentifier;
+
+ byNode.set(nodeId, [...(byNode.get(nodeId) ?? []), fieldName]);
+ }
+ }
+
+ for (const fields of byNode.values()) {
+ fields.sort();
+ }
+
+ return byNode;
+};
+
+export const toFlowNodes = (
+ document: ProjectGraphState,
+ previousNodes: WorkflowFlowNode[] = []
+): WorkflowFlowNode[] => {
+ const previousById = new Map(previousNodes.map((node) => [node.id, node]));
+ const connectedByNode = getConnectedHandlesByNode(document);
+ const exposedByNode = getExposedFieldsByNode(document);
+
+ return document.nodes.map((documentNode): WorkflowFlowNode => {
+ const previous = previousById.get(documentNode.id);
+ const selected = previous?.selected ?? false;
+
+ if (documentNode.type === 'invocation') {
+ const connectedTargetHandles = connectedByNode.get(documentNode.id) ?? EMPTY_NAMES;
+ const exposedFieldNames = exposedByNode.get(documentNode.id) ?? EMPTY_NAMES;
+
+ if (
+ previous?.type === 'invocation' &&
+ previous.data.documentNode === documentNode &&
+ sameNames(previous.data.connectedTargetHandles, connectedTargetHandles) &&
+ sameNames(previous.data.exposedFieldNames, exposedFieldNames)
+ ) {
+ return previous;
+ }
+
+ return {
+ data: { connectedTargetHandles, documentNode, exposedFieldNames },
+ id: documentNode.id,
+ position: documentNode.position,
+ selected,
+ type: 'invocation' as const,
+ };
+ }
+
+ if (documentNode.type === 'notes') {
+ if (previous?.type === 'notes' && previous.data.documentNode === documentNode) {
+ return previous;
+ }
+
+ return {
+ data: { documentNode },
+ id: documentNode.id,
+ position: documentNode.position,
+ selected,
+ type: 'notes' as const,
+ };
+ }
+
+ if (previous?.type === 'current_image' && previous.data.documentNode === documentNode) {
+ return previous;
+ }
+
+ return {
+ data: { documentNode },
+ id: documentNode.id,
+ position: documentNode.position,
+ selected,
+ type: 'current_image' as const,
+ };
+ });
+};
+
+/** Returns nodes with exactly `selectedIds` selected, preserving identity where unchanged. */
+export const withNodeSelection = (nodes: WorkflowFlowNode[], selectedIds: Set<string>): WorkflowFlowNode[] =>
+ nodes.map((node) => {
+ const selected = selectedIds.has(node.id);
+
+ if ((node.selected ?? false) === selected) {
+ return node;
+ }
+
+ // Narrowed per branch so TS keeps the node type / data correlation through the spread.
+ if (node.type === 'invocation') {
+ return { ...node, selected };
+ }
+
+ if (node.type === 'notes') {
+ return { ...node, selected };
+ }
+
+ return { ...node, selected };
+ });
+
+/** xyflow edge component per the user's connection-style preference. */
+export type FlowEdgeType = 'default' | 'straight';
+
+export const toFlowEdges = (
+ document: ProjectGraphState,
+ previousEdges: FlowEdge[] = [],
+ edgeType: FlowEdgeType = 'default'
+): FlowEdge[] => {
+ const previousById = new Map(previousEdges.map((edge) => [edge.id, edge]));
+
+ return document.edges.map((edge) => {
+ const previous = previousById.get(edge.id);
+
+ if (
+ previous &&
+ previous.type === edgeType &&
+ previous.source === edge.source &&
+ previous.sourceHandle === edge.sourceHandle &&
+ previous.target === edge.target &&
+ previous.targetHandle === edge.targetHandle
+ ) {
+ return previous;
+ }
+
+ return {
+ id: edge.id,
+ selected: previous?.selected ?? false,
+ source: edge.source,
+ sourceHandle: edge.sourceHandle,
+ target: edge.target,
+ targetHandle: edge.targetHandle,
+ type: edgeType,
+ };
+ });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.ts
new file mode 100644
index 0000000000..8a2c3abb99
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowInstanceStore.ts
@@ -0,0 +1,26 @@
+import type { Edge as FlowEdge, ReactFlowInstance } from '@xyflow/react';
+
+import type { WorkflowFlowNode } from './flowAdapters';
+
+/**
+ * Module-level handle to the mounted workflow editor's ReactFlow instance, so
+ * surfaces outside the ReactFlowProvider (the widget frame's header actions)
+ * can place inserted nodes at the current viewport center. Mirrors the legacy
+ * editor's nanostore-held instance.
+ */
+
+export type WorkflowFlowInstance = ReactFlowInstance<WorkflowFlowNode, FlowEdge>;
+
+let flowInstance: WorkflowFlowInstance | null = null;
+
+export const registerWorkflowFlowInstance = (instance: WorkflowFlowInstance): void => {
+ flowInstance = instance;
+};
+
+export const releaseWorkflowFlowInstance = (instance: WorkflowFlowInstance): void => {
+ if (flowInstance === instance) {
+ flowInstance = null;
+ }
+};
+
+export const getWorkflowFlowInstance = (): WorkflowFlowInstance | null => flowInstance;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts
new file mode 100644
index 0000000000..0cb63b73ce
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/selectionStore.ts
@@ -0,0 +1,37 @@
+import { createExternalStore } from '../../../externalStore';
+
+/**
+ * Session-lived editor selection, shared with surfaces outside the flow (the
+ * node inspector, the form builder's zoom-to-node). The editor writes
+ * `selectedNodeIds` from its selection events; other surfaces ask for a
+ * selection via `requestNodeSelection`, which the editor applies and focuses.
+ */
+
+export interface WorkflowSelectionSnapshot {
+ selectedNodeIds: string[];
+ /** A pending outside request: the editor selects + zooms to these, then clears. */
+ selectionRequest: { nodeIds: string[]; token: number } | null;
+}
+
+export const workflowSelectionStore = createExternalStore<WorkflowSelectionSnapshot>({
+ selectedNodeIds: [],
+ selectionRequest: null,
+});
+
+const areSameIds = (a: string[], b: string[]): boolean => a.length === b.length && a.every((id, i) => id === b[i]);
+
+export const reportNodeSelection = (selectedNodeIds: string[]): void => {
+ if (!areSameIds(workflowSelectionStore.getSnapshot().selectedNodeIds, selectedNodeIds)) {
+ workflowSelectionStore.patchSnapshot({ selectedNodeIds });
+ }
+};
+
+export const requestNodeSelection = (nodeIds: string[]): void => {
+ const previousToken = workflowSelectionStore.getSnapshot().selectionRequest?.token ?? 0;
+
+ workflowSelectionStore.patchSnapshot({ selectionRequest: { nodeIds, token: previousToken + 1 } });
+};
+
+export const clearNodeSelectionRequest = (): void => {
+ workflowSelectionStore.patchSnapshot({ selectionRequest: null });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useEraser.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useEraser.tsx
new file mode 100644
index 0000000000..a1aedbe2dc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useEraser.tsx
@@ -0,0 +1,261 @@
+import { Box } from '@chakra-ui/react';
+import {
+ useEffect,
+ useRef,
+ useState,
+ type MouseEvent as ReactMouseEvent,
+ type PointerEvent as ReactPointerEvent,
+ type ReactNode,
+} from 'react';
+
+import type { XYPosition } from '../../../workflows/types';
+import type { WorkflowFlowInstance } from './flowInstanceStore';
+
+const ERASER_RADIUS_PX = 14;
+const EDGE_SAMPLE_DISTANCE = 12;
+
+type ErasedElements = { edgeIds: string[]; nodeIds: string[] };
+
+const getDistanceToSegmentSquared = (point: XYPosition, start: XYPosition, end: XYPosition): number => {
+ const dx = end.x - start.x;
+ const dy = end.y - start.y;
+ const lengthSquared = dx * dx + dy * dy;
+
+ if (lengthSquared === 0) {
+ return (point.x - start.x) ** 2 + (point.y - start.y) ** 2;
+ }
+
+ const t = Math.max(0, Math.min(1, ((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared));
+ const closest = { x: start.x + t * dx, y: start.y + t * dy };
+
+ return (point.x - closest.x) ** 2 + (point.y - closest.y) ** 2;
+};
+
+const getEraserRect = (start: XYPosition, end: XYPosition, radius: number) => ({
+ height: Math.abs(end.y - start.y) + radius * 2,
+ width: Math.abs(end.x - start.x) + radius * 2,
+ x: Math.min(start.x, end.x) - radius,
+ y: Math.min(start.y, end.y) - radius,
+});
+
+const getLocalPoint = (bounds: DOMRect, clientX: number, clientY: number): XYPosition => ({
+ x: clientX - bounds.left,
+ y: clientY - bounds.top,
+});
+
+const isEraserTarget = (target: EventTarget | null): target is Element =>
+ target instanceof Element && target.closest('.react-flow__pane, .react-flow__node, .react-flow__edge') !== null;
+
+const getIntersectingEdgeIds = ({
+ container,
+ erasedEdgeIds,
+ end,
+ radius,
+ start,
+}: {
+ container: HTMLElement;
+ erasedEdgeIds: Set<string>;
+ end: XYPosition;
+ radius: number;
+ start: XYPosition;
+}): string[] => {
+ const edgeIds: string[] = [];
+ const radiusSquared = radius * radius;
+ const sampleDistance = Math.max(radius, EDGE_SAMPLE_DISTANCE);
+
+ for (const path of container.querySelectorAll<SVGPathElement>('.react-flow__edge-path')) {
+ const edgeId = path.closest<SVGGElement>('.react-flow__edge')?.dataset.id;
+
+ if (!edgeId || erasedEdgeIds.has(edgeId)) {
+ continue;
+ }
+
+ let length: number;
+
+ try {
+ length = path.getTotalLength();
+ } catch {
+ continue;
+ }
+
+ for (let distance = 0; distance <= length; distance += sampleDistance) {
+ const point = path.getPointAtLength(distance);
+
+ if (getDistanceToSegmentSquared(point, start, end) <= radiusSquared) {
+ edgeIds.push(edgeId);
+ break;
+ }
+ }
+
+ if (!edgeIds.includes(edgeId)) {
+ const point = path.getPointAtLength(length);
+
+ if (getDistanceToSegmentSquared(point, start, end) <= radiusSquared) {
+ edgeIds.push(edgeId);
+ }
+ }
+ }
+
+ return edgeIds;
+};
+
+export const useEraser = ({
+ enabled,
+ flowInstance,
+ onErase,
+}: {
+ enabled: boolean;
+ flowInstance: WorkflowFlowInstance | null;
+ onErase: (elements: ErasedElements) => void;
+}): {
+ eraserHandlers: {
+ onClickCapture: (event: ReactMouseEvent<HTMLDivElement>) => void;
+ onPointerDownCapture: (event: ReactPointerEvent<HTMLDivElement>) => void;
+ };
+ eraserOverlay: ReactNode;
+} => {
+ const [screenPoints, setScreenPoints] = useState<XYPosition[]>([]);
+ const boundsRef = useRef<DOMRect | null>(null);
+ const cleanupRef = useRef<(() => void) | null>(null);
+ const erasedEdgeIdsRef = useRef(new Set<string>());
+ const erasedNodeIdsRef = useRef(new Set<string>());
+ const flowPointsRef = useRef<XYPosition[]>([]);
+ const suppressClickRef = useRef(false);
+
+ useEffect(
+ () => () => {
+ cleanupRef.current?.();
+ },
+ []
+ );
+
+ const eraseSegment = (container: HTMLElement, start: XYPosition, end: XYPosition) => {
+ if (!flowInstance) {
+ return;
+ }
+
+ const radius = ERASER_RADIUS_PX / flowInstance.getZoom();
+ const nodeIds = flowInstance
+ .getIntersectingNodes(getEraserRect(start, end, radius), true)
+ .map((node) => node.id)
+ .filter((nodeId) => !erasedNodeIdsRef.current.has(nodeId));
+ const nodeIdSet = new Set(nodeIds);
+
+ for (const edge of flowInstance.getEdges()) {
+ if (nodeIdSet.has(edge.source) || nodeIdSet.has(edge.target)) {
+ erasedEdgeIdsRef.current.add(edge.id);
+ }
+ }
+
+ const edgeIds = getIntersectingEdgeIds({
+ container,
+ erasedEdgeIds: erasedEdgeIdsRef.current,
+ end,
+ radius,
+ start,
+ });
+
+ if (nodeIds.length === 0 && edgeIds.length === 0) {
+ return;
+ }
+
+ for (const nodeId of nodeIds) {
+ erasedNodeIdsRef.current.add(nodeId);
+ }
+
+ for (const edgeId of edgeIds) {
+ erasedEdgeIdsRef.current.add(edgeId);
+ }
+
+ onErase({ edgeIds, nodeIds });
+ };
+
+ const addPoint = (container: HTMLElement, event: Pick<PointerEvent, 'clientX' | 'clientY'>) => {
+ const bounds = boundsRef.current;
+
+ if (!flowInstance || !bounds) {
+ return;
+ }
+
+ const flowPoint = flowInstance.screenToFlowPosition({ x: event.clientX, y: event.clientY });
+ const previousPoint = flowPointsRef.current.at(-1) ?? flowPoint;
+
+ flowPointsRef.current = [...flowPointsRef.current, flowPoint];
+ setScreenPoints((current) => [...current, getLocalPoint(bounds, event.clientX, event.clientY)]);
+ eraseSegment(container, previousPoint, flowPoint);
+ };
+
+ const onPointerDownCapture = (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (!enabled || !flowInstance || event.button !== 0 || !isEraserTarget(event.target)) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ suppressClickRef.current = true;
+ erasedEdgeIdsRef.current = new Set();
+ erasedNodeIdsRef.current = new Set();
+ flowPointsRef.current = [];
+
+ const container = event.currentTarget;
+ boundsRef.current = container.getBoundingClientRect();
+ setScreenPoints([]);
+ addPoint(container, event.nativeEvent);
+
+ const onPointerMove = (moveEvent: globalThis.PointerEvent) => {
+ moveEvent.preventDefault();
+ addPoint(container, moveEvent);
+ };
+
+ const onPointerUp = () => {
+ cleanupRef.current?.();
+ flowPointsRef.current = [];
+ boundsRef.current = null;
+ setScreenPoints([]);
+ };
+
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp);
+ cleanupRef.current = () => {
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ cleanupRef.current = null;
+ };
+ };
+
+ const onClickCapture = (event: ReactMouseEvent<HTMLDivElement>) => {
+ if (!suppressClickRef.current) {
+ return;
+ }
+
+ suppressClickRef.current = false;
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ const points = screenPoints.map((point) => `${point.x},${point.y}`).join(' ');
+ const eraserOverlay =
+ screenPoints.length > 0 ? (
+ <Box as="svg" h="full" inset="0" overflow="visible" pointerEvents="none" position="absolute" w="full" zIndex="4">
+ <polyline
+ fill="none"
+ points={points}
+ stroke="var(--xy-selection-background-color)"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={ERASER_RADIUS_PX * 2}
+ />
+ <polyline
+ fill="none"
+ points={points}
+ stroke="var(--xy-edge-stroke-selected)"
+ strokeDasharray="4 3"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ </Box>
+ ) : null;
+
+ return { eraserHandlers: { onClickCapture, onPointerDownCapture }, eraserOverlay };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useLasso.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useLasso.tsx
new file mode 100644
index 0000000000..106883ccab
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useLasso.tsx
@@ -0,0 +1,184 @@
+import { Box } from '@chakra-ui/react';
+import {
+ useEffect,
+ useRef,
+ useState,
+ type MouseEvent as ReactMouseEvent,
+ type PointerEvent as ReactPointerEvent,
+ type ReactNode,
+} from 'react';
+
+import type { XYPosition } from '../../../workflows/types';
+import type { WorkflowFlowInstance } from './flowInstanceStore';
+
+/**
+ * Freeform lasso selection for the flow editor. xyflow has no core lasso (its
+ * official one is a copy-in component), so this follows the same approach:
+ * capture-phase pointer handlers on the flow wrapper stop the pane's own drag,
+ * the path is hit-tested against node bounds in flow coordinates, and a
+ * pointer-events-free SVG overlay draws the path. Partial mode: a node is
+ * selected when any corner or its center falls inside the polygon.
+ */
+
+const MIN_POLYGON_POINTS = 3;
+
+/** Ray-casting point-in-polygon. */
+const isInsidePolygon = (point: XYPosition, polygon: XYPosition[]): boolean => {
+ let isInside = false;
+
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i, i += 1) {
+ const a = polygon[i] as XYPosition;
+ const b = polygon[j] as XYPosition;
+
+ if (a.y > point.y !== b.y > point.y && point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x) {
+ isInside = !isInside;
+ }
+ }
+
+ return isInside;
+};
+
+export const useLasso = ({
+ enabled,
+ flowInstance,
+ onSelect,
+}: {
+ enabled: boolean;
+ flowInstance: WorkflowFlowInstance | null;
+ onSelect: (nodeIds: string[]) => void;
+}): {
+ /** Spread onto the flow wrapper (capture phase, so the pane never sees the drag). */
+ lassoHandlers: {
+ onClickCapture: (event: ReactMouseEvent<HTMLDivElement>) => void;
+ onPointerDownCapture: (event: ReactPointerEvent<HTMLDivElement>) => void;
+ };
+ /** Render inside the (position: relative) flow wrapper. */
+ lassoOverlay: ReactNode;
+} => {
+ const [screenPoints, setScreenPoints] = useState<XYPosition[]>([]);
+ const flowPointsRef = useRef<XYPosition[]>([]);
+ const frameRef = useRef<number | null>(null);
+ const cleanupRef = useRef<(() => void) | null>(null);
+ const suppressClickRef = useRef(false);
+
+ useEffect(
+ () => () => {
+ cleanupRef.current?.();
+
+ if (frameRef.current !== null) {
+ cancelAnimationFrame(frameRef.current);
+ }
+ },
+ []
+ );
+
+ const applySelection = () => {
+ const polygon = flowPointsRef.current;
+
+ if (!flowInstance || polygon.length < MIN_POLYGON_POINTS) {
+ return;
+ }
+
+ const selectedIds: string[] = [];
+
+ for (const node of flowInstance.getNodes()) {
+ const width = node.measured?.width ?? 0;
+ const height = node.measured?.height ?? 0;
+ const { x, y } = node.position;
+ const probes: XYPosition[] = [
+ { x, y },
+ { x: x + width, y },
+ { x, y: y + height },
+ { x: x + width, y: y + height },
+ { x: x + width / 2, y: y + height / 2 },
+ ];
+
+ if (probes.some((probe) => isInsidePolygon(probe, polygon))) {
+ selectedIds.push(node.id);
+ }
+ }
+
+ onSelect(selectedIds);
+ };
+
+ const onPointerDownCapture = (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (!enabled || !flowInstance || event.button !== 0) {
+ return;
+ }
+
+ // Let clicks inside nodes/controls behave normally; the lasso only owns
+ // drags that start on the pane itself.
+ if (!(event.target instanceof Element) || !event.target.classList.contains('react-flow__pane')) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ const container = event.currentTarget;
+ const bounds = container.getBoundingClientRect();
+ const toLocal = (clientX: number, clientY: number): XYPosition => ({
+ x: clientX - bounds.left,
+ y: clientY - bounds.top,
+ });
+
+ flowPointsRef.current = [flowInstance.screenToFlowPosition({ x: event.clientX, y: event.clientY })];
+ setScreenPoints([toLocal(event.clientX, event.clientY)]);
+
+ const onPointerMove = (moveEvent: globalThis.PointerEvent) => {
+ flowPointsRef.current = [
+ ...flowPointsRef.current,
+ flowInstance.screenToFlowPosition({ x: moveEvent.clientX, y: moveEvent.clientY }),
+ ];
+ setScreenPoints((current) => [...current, toLocal(moveEvent.clientX, moveEvent.clientY)]);
+
+ if (frameRef.current === null) {
+ frameRef.current = requestAnimationFrame(() => {
+ frameRef.current = null;
+ applySelection();
+ });
+ }
+ };
+
+ const onPointerUp = () => {
+ suppressClickRef.current = flowPointsRef.current.length >= MIN_POLYGON_POINTS;
+ cleanupRef.current?.();
+ applySelection();
+ flowPointsRef.current = [];
+ setScreenPoints([]);
+ };
+
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp);
+ cleanupRef.current = () => {
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ cleanupRef.current = null;
+ };
+ };
+
+ const onClickCapture = (event: ReactMouseEvent<HTMLDivElement>) => {
+ if (!suppressClickRef.current) {
+ return;
+ }
+
+ suppressClickRef.current = false;
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ const lassoOverlay =
+ screenPoints.length >= 2 ? (
+ <Box as="svg" h="full" inset="0" overflow="visible" pointerEvents="none" position="absolute" w="full" zIndex="4">
+ <polygon
+ fill="var(--xy-selection-background-color)"
+ points={screenPoints.map((point) => `${point.x},${point.y}`).join(' ')}
+ stroke="var(--xy-edge-stroke-selected)"
+ strokeDasharray="4 2"
+ strokeWidth="1"
+ />
+ </Box>
+ ) : null;
+
+ return { lassoHandlers: { onClickCapture, onPointerDownCapture }, lassoOverlay };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useModifierHeld.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useModifierHeld.ts
new file mode 100644
index 0000000000..ea914027f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/useModifierHeld.ts
@@ -0,0 +1,33 @@
+import { useEffect, useState } from 'react';
+
+/** Tracks whether a keyboard modifier is currently held (e.g. Control for grid snapping). */
+export const useModifierHeld = (key: 'Alt' | 'Control' | 'Meta' | 'Shift'): boolean => {
+ const [isHeld, setIsHeld] = useState(false);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === key) {
+ setIsHeld(true);
+ }
+ };
+ const onKeyUp = (event: KeyboardEvent) => {
+ if (event.key === key) {
+ setIsHeld(false);
+ }
+ };
+ // Releasing the key outside the window would otherwise leave it stuck on.
+ const onBlur = () => setIsHeld(false);
+
+ window.addEventListener('keydown', onKeyDown);
+ window.addEventListener('keyup', onKeyUp);
+ window.addEventListener('blur', onBlur);
+
+ return () => {
+ window.removeEventListener('keydown', onKeyDown);
+ window.removeEventListener('keyup', onKeyUp);
+ window.removeEventListener('blur', onBlur);
+ };
+ }, [key]);
+
+ return isHeld;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/FieldDescriptionPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/FieldDescriptionPopover.tsx
new file mode 100644
index 0000000000..0d710aec24
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/FieldDescriptionPopover.tsx
@@ -0,0 +1,76 @@
+import { Icon, Popover, Portal, Stack, Text, Textarea } from '@chakra-ui/react';
+import { FileTextIcon } from 'lucide-react';
+import type { ChangeEvent } from 'react';
+
+import { IconButton } from '../../../components/ui/Button';
+import { useWorkbenchDispatch } from '../../../WorkbenchContext';
+
+/**
+ * Small textarea popover overriding a field's template description ("field
+ * notes"), shared by the editor's node field rows and the form builder.
+ */
+export const FieldDescriptionPopover = ({
+ description,
+ fieldName,
+ nodeId,
+ templateDescription,
+}: {
+ /** The current override, if any. */
+ description: string | undefined;
+ fieldName: string;
+ nodeId: string;
+ templateDescription: string;
+}) => {
+ const dispatch = useWorkbenchDispatch();
+
+ return (
+ <Popover.Root lazyMount positioning={{ placement: 'bottom-end' }}>
+ <Popover.Trigger asChild>
+ <IconButton
+ aria-label="Edit field description"
+ className="nodrag"
+ color={description ? 'accent.solid' : 'fg.subtle'}
+ size="2xs"
+ title="Edit field description"
+ variant="ghost"
+ >
+ <Icon as={FileTextIcon} boxSize="3" />
+ </IconButton>
+ </Popover.Trigger>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="18rem">
+ <Popover.Body p="2">
+ <Stack gap="1">
+ <Text color="fg.subtle" fontSize="2xs">
+ Field description — overrides the node's default. Clear to restore it.
+ </Text>
+ <Textarea
+ aria-label="Field description"
+ className="nodrag nowheel"
+ fontSize="2xs"
+ minH="4rem"
+ placeholder={templateDescription || 'Describe this field…'}
+ resize="vertical"
+ size="xs"
+ value={description ?? ''}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>
+ dispatch({
+ action: {
+ description: event.currentTarget.value,
+ fieldName,
+ nodeId,
+ type: 'setFieldDescription',
+ },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ </Stack>
+ </Popover.Body>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx
new file mode 100644
index 0000000000..72c012d4ee
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx
@@ -0,0 +1,327 @@
+import { HStack, Input, NativeSelect, Switch, Text, Textarea } from '@chakra-ui/react';
+import { useEffect, useState, type ChangeEvent } from 'react';
+
+import { ModelSelect } from '../../../components/ModelSelect';
+import { Button } from '../../../components/ui/Button';
+import { SCHEDULER_OPTIONS } from '../../../generation/settings';
+import { listGalleryBoards, type GalleryBoard } from '../../../gallery/api';
+import type { ModelConfig, ModelTaxonomyType } from '../../../models/types';
+import type { GeneratedImageContract } from '../../../types';
+import { useWorkbench } from '../../../WorkbenchContext';
+import type { FieldInputTemplate } from '../../../workflows/types';
+
+/**
+ * Direct-input controls for workflow fields, shared between the node editor
+ * and the Linear UI panel. Renders by template field type; connection-only
+ * and unsupported types fall through to a muted note.
+ */
+
+export interface WorkflowFieldInputProps {
+ template: FieldInputTemplate;
+ value: unknown;
+ onChange: (value: unknown) => void;
+}
+
+const toFiniteNumber = (raw: string): number | null => {
+ if (raw.trim() === '') {
+ return null;
+ }
+
+ const parsed = Number(raw);
+
+ return Number.isFinite(parsed) ? parsed : null;
+};
+
+const StringInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {
+ const text = typeof value === 'string' ? value : '';
+
+ if (template.uiComponent === 'textarea') {
+ return (
+ <Textarea
+ aria-label={template.title}
+ className="nodrag nowheel"
+ fontFamily="mono"
+ minH="4.5rem"
+ resize="vertical"
+ size="xs"
+ value={text}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onChange(event.currentTarget.value)}
+ />
+ );
+ }
+
+ return (
+ <Input
+ aria-label={template.title}
+ className="nodrag"
+ size="xs"
+ value={text}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => onChange(event.currentTarget.value)}
+ />
+ );
+};
+
+const NumberInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {
+ const isInteger = template.type.name === 'IntegerField';
+ const numericValue = typeof value === 'number' && Number.isFinite(value) ? value : '';
+ const min = template.minimum ?? template.exclusiveMinimum ?? undefined;
+ const max = template.maximum ?? template.exclusiveMaximum ?? undefined;
+
+ return (
+ <Input
+ aria-label={template.title}
+ className="nodrag"
+ max={max !== undefined ? String(max) : undefined}
+ min={min !== undefined ? String(min) : undefined}
+ size="xs"
+ step={template.multipleOf !== null ? String(template.multipleOf) : isInteger ? '1' : 'any'}
+ type="number"
+ value={numericValue}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => {
+ const parsed = toFiniteNumber(event.currentTarget.value);
+
+ if (parsed !== null) {
+ onChange(isInteger ? Math.round(parsed) : parsed);
+ }
+ }}
+ />
+ );
+};
+
+const BooleanInput = ({ onChange, template, value }: WorkflowFieldInputProps) => (
+ <Switch.Root
+ checked={value === true}
+ className="nodrag"
+ size="sm"
+ onCheckedChange={(event) => onChange(event.checked)}
+ >
+ <Switch.HiddenInput aria-label={template.title} />
+ <Switch.Control _checked={{ bg: 'accent.solid' }}>
+ <Switch.Thumb />
+ </Switch.Control>
+ </Switch.Root>
+);
+
+const SelectInput = ({
+ onChange,
+ options,
+ title,
+ value,
+}: {
+ onChange: (value: string) => void;
+ options: { label: string; value: string }[];
+ title: string;
+ value: unknown;
+}) => (
+ <NativeSelect.Root className="nodrag" size="xs">
+ <NativeSelect.Field
+ aria-label={title}
+ value={typeof value === 'string' ? value : ''}
+ onChange={(event: ChangeEvent<HTMLSelectElement>) => onChange(event.currentTarget.value)}
+ >
+ {typeof value !== 'string' || !options.some((option) => option.value === value) ? (
+ <option value="">Select…</option>
+ ) : null}
+ {options.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+);
+
+const EnumInput = ({ onChange, template, value }: WorkflowFieldInputProps) => (
+ <SelectInput
+ options={(template.options ?? []).map((option) => ({
+ label: template.uiChoiceLabels?.[option] ?? option,
+ value: option,
+ }))}
+ title={template.title}
+ value={value}
+ onChange={onChange}
+ />
+);
+
+const DEFAULT_MODEL_TYPES: ModelTaxonomyType[] = ['main', 'vae', 'lora', 'controlnet', 't2i_adapter', 'ip_adapter'];
+
+const ModelIdentifierInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {
+ const selectedKey =
+ typeof (value as { key?: unknown } | null)?.key === 'string' ? (value as { key: string }).key : null;
+ const modelTypes = (template.uiModelType as ModelTaxonomyType[] | null) ?? DEFAULT_MODEL_TYPES;
+ const allowedBases = template.uiModelBase;
+
+ return (
+ <ModelSelect
+ filter={allowedBases ? (model: ModelConfig) => allowedBases.includes(model.base) : undefined}
+ modelTypes={modelTypes}
+ size="xs"
+ value={selectedKey}
+ onChange={(model) =>
+ onChange(
+ model ? { base: model.base, hash: model.hash, key: model.key, name: model.name, type: model.type } : undefined
+ )
+ }
+ />
+ );
+};
+
+const SchedulerInput = ({ onChange, template, value }: WorkflowFieldInputProps) => (
+ <SelectInput options={SCHEDULER_OPTIONS} title={template.title} value={value} onChange={onChange} />
+);
+
+const BoardInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {
+ const [boards, setBoards] = useState<GalleryBoard[]>([]);
+
+ useEffect(() => {
+ let isCancelled = false;
+
+ listGalleryBoards()
+ .then((loadedBoards) => {
+ if (!isCancelled) {
+ setBoards(loadedBoards.filter((board) => board.kind === 'board'));
+ }
+ })
+ .catch(() => {
+ // Board listing is a convenience; the auto/none sentinels still work.
+ });
+
+ return () => {
+ isCancelled = true;
+ };
+ }, []);
+
+ const selected =
+ value === 'auto' || value === 'none'
+ ? value
+ : typeof (value as { board_id?: unknown } | null)?.board_id === 'string'
+ ? (value as { board_id: string }).board_id
+ : 'auto';
+
+ return (
+ <SelectInput
+ options={[
+ { label: 'Auto', value: 'auto' },
+ { label: 'None', value: 'none' },
+ ...boards.map((board) => ({ label: board.name, value: board.id })),
+ ]}
+ title={template.title}
+ value={selected}
+ onChange={(next) => onChange(next === 'auto' || next === 'none' ? next : { board_id: next })}
+ />
+ );
+};
+
+const ImageInput = ({ onChange, value }: WorkflowFieldInputProps) => {
+ const { activeProject } = useWorkbench();
+ const imageName =
+ typeof (value as { image_name?: unknown } | null)?.image_name === 'string'
+ ? (value as { image_name: string }).image_name
+ : null;
+ const gallerySelection = activeProject.widgetStates.gallery.values.selectedImage as
+ | GeneratedImageContract
+ | null
+ | undefined;
+
+ return (
+ <HStack gap="1.5" minW="0">
+ {imageName ? (
+ <Text color="fg.muted" flex="1" fontSize="2xs" minW="0" title={imageName} truncate>
+ {imageName}
+ </Text>
+ ) : (
+ <Text color="fg.subtle" flex="1" fontSize="2xs">
+ No image set
+ </Text>
+ )}
+ <Button
+ className="nodrag"
+ disabled={!gallerySelection}
+ size="2xs"
+ title={gallerySelection ? `Use ${gallerySelection.imageName}` : 'Select an image in the Gallery first.'}
+ variant="outline"
+ onClick={() => {
+ if (gallerySelection) {
+ onChange({ image_name: gallerySelection.imageName });
+ }
+ }}
+ >
+ Use gallery selection
+ </Button>
+ {imageName ? (
+ <Button className="nodrag" size="2xs" variant="ghost" onClick={() => onChange(undefined)}>
+ Clear
+ </Button>
+ ) : null}
+ </HStack>
+ );
+};
+
+const COLOR_CHANNELS = ['r', 'g', 'b', 'a'] as const;
+
+const ColorInput = ({ onChange, value }: WorkflowFieldInputProps) => {
+ const color = (typeof value === 'object' && value !== null ? value : {}) as Partial<Record<string, number>>;
+
+ return (
+ <HStack gap="1">
+ {COLOR_CHANNELS.map((channel) => (
+ <Input
+ key={channel}
+ aria-label={`Color ${channel.toUpperCase()}`}
+ className="nodrag"
+ max="255"
+ min="0"
+ placeholder={channel.toUpperCase()}
+ size="xs"
+ type="number"
+ value={typeof color[channel] === 'number' ? color[channel] : ''}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => {
+ const parsed = toFiniteNumber(event.currentTarget.value);
+
+ if (parsed !== null) {
+ onChange({
+ a: 255,
+ b: 0,
+ g: 0,
+ r: 0,
+ ...color,
+ [channel]: Math.min(255, Math.max(0, Math.round(parsed))),
+ });
+ }
+ }}
+ />
+ ))}
+ </HStack>
+ );
+};
+
+export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
+ switch (props.template.type.name) {
+ case 'StringField':
+ return <StringInput {...props} />;
+ case 'IntegerField':
+ case 'FloatField':
+ return <NumberInput {...props} />;
+ case 'BooleanField':
+ return <BooleanInput {...props} />;
+ case 'EnumField':
+ return <EnumInput {...props} />;
+ case 'ModelIdentifierField':
+ return <ModelIdentifierInput {...props} />;
+ case 'SchedulerField':
+ return <SchedulerInput {...props} />;
+ case 'BoardField':
+ return <BoardInput {...props} />;
+ case 'ImageField':
+ return <ImageInput {...props} />;
+ case 'ColorField':
+ return <ColorInput {...props} />;
+ default:
+ return (
+ <Text color="fg.subtle" fontSize="2xs">
+ Connection only
+ </Text>
+ );
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts
index 5707269847..b36162e86b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts
@@ -1,18 +1,23 @@
import type { WidgetManifest } from '../../types';
+import { WorkflowHeaderActions, WorkflowMenuItems, WorkflowWidgetLabel } from './WorkflowWidgetChrome';
import { WorkflowWidgetView } from './WorkflowWidgetView';
export const workflowWidgetManifest: WidgetManifest = {
+ bottomPanel: 'expandable',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
graphBearing: {
defaultGraphId: 'workflow-graph',
sourceId: 'project-graph',
- surfaces: ['center', 'left'],
+ surfaces: ['center', 'left', 'bottom'],
},
+ headerActions: WorkflowHeaderActions,
+ headerMenu: WorkflowMenuItems,
icon: 'lucide-react:workflow',
id: 'workflow',
- label: 'Workflow',
+ label: WorkflowWidgetLabel,
labelText: 'Workflow',
- regions: ['center', 'left'],
+ regions: ['center', 'left', 'bottom'],
+ settingsSection: 'workflow',
version: 1,
view: WorkflowWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx
new file mode 100644
index 0000000000..5f9c069619
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx
@@ -0,0 +1,461 @@
+import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Stack, Tabs, Text } from '@chakra-ui/react';
+import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
+
+import { getApiErrorMessage } from '../../../backend/http';
+import { documentToPreviewGraph, GraphPreviewFlow } from '../../../components/GraphPreviewFlow';
+import { Button, CloseButton } from '../../../components/ui/Button';
+import { ConfirmDialog } from '../../../components/ui/ConfirmDialog';
+import { JsonPreview } from '../../../components/ui/JsonPreview';
+import { Scrollable } from '../../../components/ui/Scrollable';
+import { useNotify } from '../../../useNotify';
+import { useWorkbench } from '../../../WorkbenchContext';
+import {
+ createLibraryWorkflow,
+ deleteLibraryWorkflow,
+ touchLibraryWorkflowOpenedAt,
+ updateLibraryWorkflow,
+ type WorkflowLibraryCategory,
+ type WorkflowLibraryListItem,
+} from '../../../workflows/api';
+import {
+ getCachedWorkflowPage,
+ getLibraryWorkflowCached,
+ invalidateWorkflowLibraryCache,
+ listLibraryWorkflowsCached,
+} from '../../../workflows/libraryCache';
+import type { ProjectGraphState } from '../../../workflows/types';
+import { parseWorkflowJson, serializeWorkflowJson } from '../../../workflows/workflowJson';
+
+/**
+ * Backend workflow library browser: list/search user and default workflows,
+ * preview one (read-only nodes / JSON) before loading it into the project
+ * graph (with an automatic graph-history snapshot of the current graph), and
+ * save the project graph back to the library. Lists serve from the session
+ * cache instantly and revalidate in the background.
+ */
+
+interface WorkflowPreviewState {
+ document: ProjectGraphState;
+ item: WorkflowLibraryListItem;
+ raw: Record<string, unknown>;
+}
+
+const WorkflowPreviewPane = ({
+ isLoadingWorkflow,
+ preview,
+ onBack,
+ onLoad,
+}: {
+ isLoadingWorkflow: boolean;
+ preview: WorkflowPreviewState;
+ onBack: () => void;
+ onLoad: () => void;
+}) => {
+ const [mode, setMode] = useState<'nodes' | 'json'>('nodes');
+ const { graph, positionHints } = documentToPreviewGraph(preview.document);
+
+ return (
+ <Stack gap="2">
+ <HStack gap="2" justify="space-between">
+ <HStack gap="2" minW="0">
+ <Button size="2xs" variant="ghost" onClick={onBack}>
+ ← Back
+ </Button>
+ <Text fontSize="xs" fontWeight="600" minW="0" truncate>
+ {preview.item.name || 'Untitled Workflow'}
+ </Text>
+ </HStack>
+ <HStack flexShrink={0} gap="2">
+ <SegmentGroup.Root
+ size="xs"
+ value={mode}
+ onValueChange={(event) => setMode(event.value === 'json' ? 'json' : 'nodes')}
+ >
+ <SegmentGroup.Indicator />
+ <SegmentGroup.Items
+ items={[
+ { label: 'Nodes', value: 'nodes' },
+ { label: 'JSON', value: 'json' },
+ ]}
+ />
+ </SegmentGroup.Root>
+ <Button loading={isLoadingWorkflow} size="2xs" onClick={onLoad}>
+ Load
+ </Button>
+ </HStack>
+ </HStack>
+ {mode === 'nodes' ? (
+ <Box h="24rem">
+ <GraphPreviewFlow graph={graph} positionHints={positionHints} />
+ </Box>
+ ) : (
+ <JsonPreview label={`${preview.item.name} JSON`} maxH="24rem" value={preview.raw} />
+ )}
+ </Stack>
+ );
+};
+
+export const WorkflowLibraryDialog = ({
+ isOpen,
+ onOpenChange,
+}: {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+}) => {
+ const { activeProject, dispatch } = useWorkbench();
+ const notify = useNotify();
+ const [category, setCategory] = useState<WorkflowLibraryCategory>('user');
+ const [searchTerm, setSearchTerm] = useState('');
+ const [items, setItems] = useState<WorkflowLibraryListItem[]>([]);
+ const [pages, setPages] = useState(0);
+ const [page, setPage] = useState(0);
+ const [isLoading, setIsLoading] = useState(false);
+ const [loadingWorkflowId, setLoadingWorkflowId] = useState<string | null>(null);
+ const [previewingWorkflowId, setPreviewingWorkflowId] = useState<string | null>(null);
+ const [preview, setPreview] = useState<WorkflowPreviewState | null>(null);
+ const [pendingDelete, setPendingDelete] = useState<WorkflowLibraryListItem | null>(null);
+ const [isSaving, setIsSaving] = useState(false);
+ const hasAutoSwitchedRef = useRef(false);
+ const refreshTokenRef = useRef(0);
+ const projectGraph = activeProject.projectGraph;
+
+ const refresh = useCallback(
+ (nextPage: number) => {
+ const params = { category, page: nextPage, query: searchTerm };
+ const cached = getCachedWorkflowPage(params);
+ const token = (refreshTokenRef.current += 1);
+
+ // A cached page renders instantly; the fetch below only revalidates it.
+ if (cached) {
+ setItems(cached.items);
+ setPage(cached.page);
+ setPages(cached.pages);
+ } else {
+ setIsLoading(true);
+ }
+
+ listLibraryWorkflowsCached(params)
+ .then((result) => {
+ if (token !== refreshTokenRef.current) {
+ return;
+ }
+
+ setItems(result.items);
+ setPage(result.page);
+ setPages(result.pages);
+
+ // A fresh install has no user workflows; land on the bundled
+ // defaults instead of an empty tab. Once per dialog open.
+ if (category === 'user' && result.total === 0 && !searchTerm && !hasAutoSwitchedRef.current) {
+ hasAutoSwitchedRef.current = true;
+ setCategory('default');
+ }
+ })
+ .catch((error: unknown) => {
+ if (cached) {
+ return; // Stale-but-rendered beats an error toast on revalidation.
+ }
+
+ notify.error('Workflow library unavailable', getApiErrorMessage(error, 'Failed to list workflows.'));
+ })
+ .finally(() => {
+ if (token === refreshTokenRef.current) {
+ setIsLoading(false);
+ }
+ });
+ },
+ [category, notify, searchTerm]
+ );
+
+ useEffect(() => {
+ if (isOpen) {
+ refresh(0);
+ } else {
+ hasAutoSwitchedRef.current = false;
+ setPreview(null);
+ }
+ }, [isOpen, refresh]);
+
+ const fetchParsedWorkflow = async (item: WorkflowLibraryListItem) => {
+ const raw = await getLibraryWorkflowCached(item.workflow_id);
+ const { document, warnings } = parseWorkflowJson(raw);
+
+ return { document, raw, warnings };
+ };
+
+ const applyLoadedWorkflow = (item: WorkflowLibraryListItem, document: ProjectGraphState, warnings: string[]) => {
+ dispatch({ document, label: `Loaded "${item.name}" from library`, type: 'replaceProjectGraph' });
+
+ for (const warning of warnings) {
+ notify.info('Workflow load warning', warning);
+ }
+
+ void touchLibraryWorkflowOpenedAt(item.workflow_id).catch(() => {
+ // Recency bookkeeping only; loading already succeeded.
+ });
+ onOpenChange(false);
+ };
+
+ const loadWorkflow = async (item: WorkflowLibraryListItem) => {
+ setLoadingWorkflowId(item.workflow_id);
+
+ try {
+ const { document, warnings } = await fetchParsedWorkflow(item);
+
+ applyLoadedWorkflow(item, document, warnings);
+ } catch (error) {
+ notify.error('Failed to load workflow', getApiErrorMessage(error, `Could not load "${item.name}".`));
+ } finally {
+ setLoadingWorkflowId(null);
+ }
+ };
+
+ const previewWorkflow = async (item: WorkflowLibraryListItem) => {
+ setPreviewingWorkflowId(item.workflow_id);
+
+ try {
+ const { document, raw } = await fetchParsedWorkflow(item);
+
+ setPreview({ document, item, raw });
+ } catch (error) {
+ notify.error('Failed to preview workflow', getApiErrorMessage(error, `Could not preview "${item.name}".`));
+ } finally {
+ setPreviewingWorkflowId(null);
+ }
+ };
+
+ const saveToLibrary = async (asNew: boolean) => {
+ setIsSaving(true);
+
+ try {
+ const serialized = serializeWorkflowJson(projectGraph);
+
+ if (!asNew && projectGraph.libraryWorkflowId) {
+ await updateLibraryWorkflow(projectGraph.libraryWorkflowId, serialized);
+ notify.success('Workflow saved', `Updated "${projectGraph.name || 'Untitled Workflow'}" in the library.`);
+ } else {
+ const workflowId = await createLibraryWorkflow(serialized);
+
+ dispatch({ libraryWorkflowId: workflowId, type: 'setProjectGraphLibraryBinding' });
+ notify.success('Workflow saved', `Saved "${projectGraph.name || 'Untitled Workflow'}" to the library.`);
+ }
+
+ invalidateWorkflowLibraryCache();
+ refresh(page);
+ } catch (error) {
+ notify.error('Failed to save workflow', getApiErrorMessage(error, 'The workflow could not be saved.'));
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <>
+ <Dialog.Root open={isOpen} size="lg" onOpenChange={(event) => onOpenChange(event.open)}>
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg">
+ <Dialog.Header>
+ <Dialog.Title fontSize="sm" fontWeight="700">
+ Workflow Library
+ </Dialog.Title>
+ </Dialog.Header>
+ <Dialog.Body>
+ {preview ? (
+ <WorkflowPreviewPane
+ isLoadingWorkflow={loadingWorkflowId === preview.item.workflow_id}
+ preview={preview}
+ onBack={() => setPreview(null)}
+ onLoad={() => applyLoadedWorkflow(preview.item, preview.document, [])}
+ />
+ ) : (
+ <Stack gap="3">
+ <HStack gap="2">
+ <Tabs.Root
+ size="sm"
+ value={category}
+ variant="enclosed"
+ onValueChange={(event) => setCategory(event.value as WorkflowLibraryCategory)}
+ >
+ <Tabs.List>
+ <Tabs.Trigger fontSize="xs" value="user">
+ Yours
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="xs" value="default">
+ Defaults
+ </Tabs.Trigger>
+ </Tabs.List>
+ </Tabs.Root>
+ <Input
+ aria-label="Search workflows"
+ placeholder="Search workflows…"
+ size="xs"
+ value={searchTerm}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setSearchTerm(event.currentTarget.value)}
+ />
+ </HStack>
+ <Scrollable label="Workflow library results" maxH="20rem" minH="8rem">
+ <Stack gap="1">
+ {items.map((item) => (
+ <HStack
+ key={item.workflow_id}
+ _hover={{ bg: 'bg.emphasized' }}
+ gap="2"
+ px="1"
+ rounded="md"
+ transition="background 0.12s ease"
+ >
+ <Box
+ as="button"
+ _focusVisible={{ outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' }}
+ aria-disabled={previewingWorkflowId !== null}
+ cursor="pointer"
+ flex="1"
+ minW="0"
+ px="1"
+ py="1.5"
+ rounded="md"
+ textAlign="start"
+ title={`Preview "${item.name || 'Untitled Workflow'}"`}
+ onClick={() => {
+ if (previewingWorkflowId === null) {
+ void previewWorkflow(item);
+ }
+ }}
+ >
+ <Stack gap="0" minW="0">
+ <Text fontSize="xs" fontWeight="600" truncate>
+ {item.name || 'Untitled Workflow'}
+ </Text>
+ {item.description ? (
+ <Text color="fg.subtle" fontSize="2xs" truncate>
+ {item.description}
+ </Text>
+ ) : null}
+ </Stack>
+ </Box>
+ <Button
+ flexShrink={0}
+ loading={previewingWorkflowId === item.workflow_id}
+ size="2xs"
+ variant="outline"
+ onClick={() => void previewWorkflow(item)}
+ >
+ Preview
+ </Button>
+ <Button
+ flexShrink={0}
+ loading={loadingWorkflowId === item.workflow_id}
+ size="2xs"
+ variant="outline"
+ onClick={() => void loadWorkflow(item)}
+ >
+ Load
+ </Button>
+ {category === 'user' ? (
+ <Button
+ colorPalette="red"
+ flexShrink={0}
+ size="2xs"
+ variant="ghost"
+ onClick={() => setPendingDelete(item)}
+ >
+ Delete
+ </Button>
+ ) : null}
+ </HStack>
+ ))}
+ {!isLoading && items.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs" px="2" py="4" textAlign="center">
+ {category === 'user'
+ ? 'No saved workflows yet. Save the project graph below to start your library.'
+ : 'No default workflows are installed on this backend.'}
+ </Text>
+ ) : null}
+ {isLoading ? (
+ <Text color="fg.subtle" fontSize="2xs" px="2" py="1.5">
+ Loading workflows…
+ </Text>
+ ) : null}
+ </Stack>
+ </Scrollable>
+ {pages > 1 ? (
+ <HStack gap="2" justify="center">
+ <Button disabled={page === 0} size="2xs" variant="ghost" onClick={() => refresh(page - 1)}>
+ Previous
+ </Button>
+ <Text color="fg.subtle" fontSize="2xs">
+ Page {page + 1} of {pages}
+ </Text>
+ <Button
+ disabled={page >= pages - 1}
+ size="2xs"
+ variant="ghost"
+ onClick={() => refresh(page + 1)}
+ >
+ Next
+ </Button>
+ </HStack>
+ ) : null}
+ <Box borderColor="border.subtle" borderTopWidth="1px" pt="3">
+ <HStack gap="2" justify="space-between">
+ <Text color="fg.muted" fontSize="2xs" minW="0" truncate>
+ Project graph: {projectGraph.name || 'Untitled Workflow'}
+ {projectGraph.libraryWorkflowId ? ' (linked to library)' : ''}
+ </Text>
+ <HStack flexShrink={0} gap="2">
+ {projectGraph.libraryWorkflowId ? (
+ <Button
+ loading={isSaving}
+ size="2xs"
+ variant="outline"
+ onClick={() => void saveToLibrary(false)}
+ >
+ Save
+ </Button>
+ ) : null}
+ <Button
+ loading={isSaving}
+ size="2xs"
+ variant="outline"
+ onClick={() => void saveToLibrary(true)}
+ >
+ Save as new
+ </Button>
+ </HStack>
+ </HStack>
+ </Box>
+ </Stack>
+ )}
+ </Dialog.Body>
+ <Dialog.CloseTrigger asChild>
+ <CloseButton color="fg.muted" size="sm" />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ <ConfirmDialog
+ body={`Delete "${pendingDelete?.name || 'Untitled Workflow'}" from the workflow library? This cannot be undone.`}
+ confirmLabel="Delete"
+ isOpen={pendingDelete !== null}
+ title="Delete workflow"
+ onClose={() => setPendingDelete(null)}
+ onConfirm={async () => {
+ if (!pendingDelete) {
+ return;
+ }
+
+ try {
+ await deleteLibraryWorkflow(pendingDelete.workflow_id);
+ invalidateWorkflowLibraryCache();
+ refresh(page);
+ } catch (error) {
+ notify.error('Failed to delete workflow', getApiErrorMessage(error, 'The workflow could not be deleted.'));
+ }
+ }}
+ />
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx
new file mode 100644
index 0000000000..7850ac04a7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx
@@ -0,0 +1,472 @@
+import { Box, HStack, Icon, Input, Menu, Portal, Separator, Stack, Text, Textarea } from '@chakra-ui/react';
+import { Columns2Icon, CrosshairIcon, GripVerticalIcon, InfoIcon, PlusIcon, Rows2Icon, XIcon } from 'lucide-react';
+import { createContext, use, useMemo, useState, type ChangeEvent, type DragEvent, type ReactNode } from 'react';
+
+import { Button, IconButton } from '../../../components/ui/Button';
+import { useWorkbench } from '../../../WorkbenchContext';
+import { getFormChildren } from '../../../workflows/document';
+import type {
+ ContainerFormElement,
+ NodeFieldFormElement,
+ ProjectGraphState,
+ WorkflowFormElement,
+} from '../../../workflows/types';
+import { FieldDescriptionPopover } from '../fields/FieldDescriptionPopover';
+import { requestNodeSelection } from '../editor/selectionStore';
+import { NodeFieldControl, useNodeFieldBinding } from './NodeFieldControl';
+
+/**
+ * The form builder: edit mode of the Linear UI. Every element renders as a
+ * card with its own title bar — type label on the left, actions on the right,
+ * content below — mirroring the legacy builder. Cards reorder and reparent by
+ * dragging their title bar (drop indicators above/below, containers accept
+ * drops into their body). All edits go through the project graph document
+ * reducer.
+ */
+
+interface BuilderDndContextValue {
+ draggingElementId: string | null;
+ setDraggingElementId: (elementId: string | null) => void;
+}
+
+const BuilderDndContext = createContext<BuilderDndContextValue>({
+ draggingElementId: null,
+ setDraggingElementId: () => undefined,
+});
+
+type DropEdge = 'above' | 'below';
+
+/** A builder card: typed title bar (drag handle + actions) over the element's content. */
+const BuilderCard = ({
+ children,
+ element,
+ extraActions,
+ index,
+ parentId,
+ title,
+}: {
+ children: ReactNode;
+ element: WorkflowFormElement;
+ extraActions?: ReactNode;
+ index: number;
+ parentId: string;
+ title: string;
+}) => {
+ const { dispatch } = useWorkbench();
+ const { draggingElementId, setDraggingElementId } = use(BuilderDndContext);
+ const [isDragArmed, setIsDragArmed] = useState(false);
+ const [dropEdge, setDropEdge] = useState<DropEdge | null>(null);
+ const isDropTarget = draggingElementId !== null && draggingElementId !== element.id;
+
+ const onDragOver = (event: DragEvent<HTMLDivElement>) => {
+ if (!isDropTarget) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ const bounds = event.currentTarget.getBoundingClientRect();
+
+ setDropEdge(event.clientY < bounds.top + bounds.height / 2 ? 'above' : 'below');
+ };
+
+ const onDrop = (event: DragEvent<HTMLDivElement>) => {
+ if (!isDropTarget || !draggingElementId || !dropEdge) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ dispatch({
+ action: {
+ elementId: draggingElementId,
+ index: dropEdge === 'above' ? index : index + 1,
+ parentId,
+ type: 'moveFormElementTo',
+ },
+ type: 'applyProjectGraphAction',
+ });
+ setDropEdge(null);
+ };
+
+ return (
+ <Box
+ draggable={isDragArmed}
+ flex="1"
+ minW="0"
+ opacity={draggingElementId === element.id ? 0.4 : 1}
+ position="relative"
+ onDragEnd={() => {
+ setDraggingElementId(null);
+ setIsDragArmed(false);
+ }}
+ onDragLeave={() => setDropEdge(null)}
+ onDragOver={onDragOver}
+ onDragStart={(event: DragEvent<HTMLDivElement>) => {
+ event.stopPropagation();
+ event.dataTransfer.effectAllowed = 'move';
+ setDraggingElementId(element.id);
+ }}
+ onDrop={onDrop}
+ >
+ {dropEdge ? (
+ <Box
+ bg="accent.solid"
+ h="2px"
+ left="0"
+ pointerEvents="none"
+ position="absolute"
+ right="0"
+ rounded="full"
+ zIndex="1"
+ {...(dropEdge === 'above' ? { top: '-1px' } : { bottom: '-1px' })}
+ />
+ ) : null}
+ <Box bg="bg" borderColor="border.subtle" borderWidth="1px" overflow="hidden" rounded="md">
+ <HStack
+ bg="bg.subtle"
+ borderBottomWidth="1px"
+ borderColor="border.subtle"
+ cursor="grab"
+ gap="1"
+ px="1.5"
+ py="0.5"
+ _active={{ cursor: 'grabbing' }}
+ onPointerDown={() => setIsDragArmed(true)}
+ onPointerUp={() => setIsDragArmed(false)}
+ >
+ <Icon as={GripVerticalIcon} boxSize="3" color="fg.subtle" flexShrink={0} />
+ <Text color="fg.muted" fontSize="2xs" fontWeight="600" minW="0" truncate>
+ {title}
+ </Text>
+ <Box flex="1" />
+ <HStack flexShrink={0} gap="0" onPointerDown={(event) => event.stopPropagation()}>
+ {extraActions}
+ <IconButton
+ aria-label="Remove from form"
+ size="2xs"
+ variant="ghost"
+ onClick={() =>
+ dispatch({
+ action: { elementId: element.id, type: 'removeFormElement' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ >
+ <Icon as={XIcon} boxSize="3" />
+ </IconButton>
+ </HStack>
+ </HStack>
+ <Box p="2">{children}</Box>
+ </Box>
+ </Box>
+ );
+};
+
+/** Drop zone covering a container's body, appending at the end. Doubles as the empty-container hint. */
+const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormElement; isEmpty: boolean }) => {
+ const { dispatch } = useWorkbench();
+ const { draggingElementId } = use(BuilderDndContext);
+ const [isActive, setIsActive] = useState(false);
+ const canDrop = draggingElementId !== null && draggingElementId !== container.id;
+
+ if (!canDrop && !isEmpty) {
+ return null;
+ }
+
+ return (
+ <Box
+ alignSelf="stretch"
+ borderColor={isActive ? 'accent.solid' : 'border.subtle'}
+ borderStyle="dashed"
+ borderWidth="1px"
+ color="fg.subtle"
+ flex={isEmpty ? '1' : undefined}
+ fontSize="2xs"
+ px="2"
+ py="1.5"
+ rounded="md"
+ textAlign="center"
+ onDragLeave={() => setIsActive(false)}
+ onDragOver={(event: DragEvent<HTMLDivElement>) => {
+ if (canDrop) {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsActive(true);
+ }
+ }}
+ onDrop={(event: DragEvent<HTMLDivElement>) => {
+ if (!canDrop || !draggingElementId) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ dispatch({
+ action: {
+ elementId: draggingElementId,
+ index: container.data.children.length,
+ parentId: container.id,
+ type: 'moveFormElementTo',
+ },
+ type: 'applyProjectGraphAction',
+ });
+ setIsActive(false);
+ }}
+ >
+ {canDrop ? 'Drop here' : 'Empty container — drag elements here'}
+ </Box>
+ );
+};
+
+/** The shared description popover, bound through the form element. */
+const FieldDescriptionAction = ({
+ element,
+ projectGraph,
+}: {
+ element: NodeFieldFormElement;
+ projectGraph: ProjectGraphState;
+}) => {
+ const { fieldName, instance, nodeId, template } = useNodeFieldBinding(element, projectGraph);
+
+ if (!template) {
+ return null;
+ }
+
+ return (
+ <FieldDescriptionPopover
+ description={instance?.description}
+ fieldName={fieldName}
+ nodeId={nodeId}
+ templateDescription={template.description}
+ />
+ );
+};
+
+const BuilderElement = ({
+ element,
+ index,
+ parentId,
+ projectGraph,
+}: {
+ element: WorkflowFormElement;
+ index: number;
+ parentId: string;
+ projectGraph: ProjectGraphState;
+}) => {
+ const { dispatch } = useWorkbench();
+
+ switch (element.type) {
+ case 'container': {
+ const isRow = element.data.layout === 'row';
+
+ return (
+ <BuilderCard
+ element={element}
+ extraActions={
+ <IconButton
+ aria-label={isRow ? 'Switch container to column layout' : 'Switch container to row layout'}
+ size="2xs"
+ title={isRow ? 'Switch to column layout' : 'Switch to row layout'}
+ variant="ghost"
+ onClick={() =>
+ dispatch({
+ action: { elementId: element.id, layout: isRow ? 'column' : 'row', type: 'setContainerLayout' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ >
+ <Icon as={isRow ? Rows2Icon : Columns2Icon} boxSize="3" />
+ </IconButton>
+ }
+ index={index}
+ parentId={parentId}
+ title={`Container (${element.data.layout} layout)`}
+ >
+ <Stack align={isRow ? 'stretch' : undefined} direction={isRow ? 'row' : 'column'} gap="2" w="full">
+ {getFormChildren(projectGraph.form, element.id).map((child, childIndex) => (
+ <BuilderElement
+ key={child.id}
+ element={child}
+ index={childIndex}
+ parentId={element.id}
+ projectGraph={projectGraph}
+ />
+ ))}
+ <ContainerDropZone container={element} isEmpty={element.data.children.length === 0} />
+ </Stack>
+ </BuilderCard>
+ );
+ }
+ case 'node-field': {
+ return (
+ <BuilderCard
+ element={element}
+ extraActions={
+ <>
+ <IconButton
+ aria-label="Zoom to node in editor"
+ size="2xs"
+ title="Zoom to node in the Workflow editor"
+ variant="ghost"
+ onClick={() => {
+ dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'workflow' });
+ requestNodeSelection([element.data.fieldIdentifier.nodeId]);
+ }}
+ >
+ <Icon as={CrosshairIcon} boxSize="3" />
+ </IconButton>
+ <FieldDescriptionAction element={element} projectGraph={projectGraph} />
+ <IconButton
+ aria-label="Toggle description"
+ color={element.data.showDescription ? 'accent.solid' : undefined}
+ size="2xs"
+ title={element.data.showDescription ? 'Hide field description' : 'Show field description'}
+ variant="ghost"
+ onClick={() =>
+ dispatch({
+ action: {
+ elementId: element.id,
+ showDescription: !element.data.showDescription,
+ type: 'setNodeFieldShowDescription',
+ },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ >
+ <Icon as={InfoIcon} boxSize="3" />
+ </IconButton>
+ </>
+ }
+ index={index}
+ parentId={parentId}
+ title="Node Field"
+ >
+ <NodeFieldControl element={element} isLabelEditable projectGraph={projectGraph} />
+ </BuilderCard>
+ );
+ }
+ case 'heading': {
+ return (
+ <BuilderCard element={element} index={index} parentId={parentId} title="Heading">
+ <Input
+ aria-label="Form heading"
+ fontSize="sm"
+ fontWeight="700"
+ placeholder="Heading"
+ size="xs"
+ value={element.data.content}
+ variant="flushed"
+ onChange={(event: ChangeEvent<HTMLInputElement>) =>
+ dispatch({
+ action: { content: event.currentTarget.value, elementId: element.id, type: 'setFormElementContent' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ </BuilderCard>
+ );
+ }
+ case 'text': {
+ return (
+ <BuilderCard element={element} index={index} parentId={parentId} title="Text">
+ <Textarea
+ aria-label="Form text"
+ color="fg.muted"
+ fontSize="2xs"
+ minH="2.5rem"
+ placeholder="Text"
+ resize="vertical"
+ size="xs"
+ value={element.data.content}
+ variant="flushed"
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>
+ dispatch({
+ action: { content: event.currentTarget.value, elementId: element.id, type: 'setFormElementContent' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ </BuilderCard>
+ );
+ }
+ case 'divider': {
+ return (
+ <BuilderCard element={element} index={index} parentId={parentId} title="Divider">
+ <Separator borderColor="border.subtle" />
+ </BuilderCard>
+ );
+ }
+ }
+};
+
+const AddElementMenu = () => {
+ const { dispatch } = useWorkbench();
+ const add = (elementType: 'divider' | 'heading' | 'text' | 'container', layout?: 'row' | 'column') =>
+ dispatch({ action: { elementType, layout, type: 'addFormElement' }, type: 'applyProjectGraphAction' });
+
+ return (
+ <Menu.Root positioning={{ placement: 'bottom-start' }}>
+ <Menu.Trigger asChild>
+ <Button size="2xs" variant="ghost">
+ <Icon as={PlusIcon} boxSize="3" />
+ Add form element
+ </Button>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <Menu.Content minW="11rem">
+ <Menu.Item value="heading" onClick={() => add('heading')}>
+ Heading
+ </Menu.Item>
+ <Menu.Item value="text" onClick={() => add('text')}>
+ Text
+ </Menu.Item>
+ <Menu.Item value="divider" onClick={() => add('divider')}>
+ Divider
+ </Menu.Item>
+ <Menu.Item value="container-column" onClick={() => add('container', 'column')}>
+ Container (column)
+ </Menu.Item>
+ <Menu.Item value="container-row" onClick={() => add('container', 'row')}>
+ Container (row)
+ </Menu.Item>
+ </Menu.Content>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
+
+export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {
+ const [draggingElementId, setDraggingElementId] = useState<string | null>(null);
+ const dndContextValue = useMemo<BuilderDndContextValue>(
+ () => ({ draggingElementId, setDraggingElementId }),
+ [draggingElementId]
+ );
+ const rootChildren = getFormChildren(projectGraph.form);
+
+ return (
+ <BuilderDndContext value={dndContextValue}>
+ <Stack gap="2" p="3" w="full">
+ {rootChildren.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ The form is empty. Pin fields from the Workflow editor's nodes, then arrange them here — drag card title
+ bars to reorder, drop them into containers, and add headings or dividers below.
+ </Text>
+ ) : null}
+ {rootChildren.map((element, index) => (
+ <BuilderElement
+ key={element.id}
+ element={element}
+ index={index}
+ parentId={projectGraph.form.rootElementId}
+ projectGraph={projectGraph}
+ />
+ ))}
+ <AddElementMenu />
+ </Stack>
+ </BuilderDndContext>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx
new file mode 100644
index 0000000000..72a00ecd02
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx
@@ -0,0 +1,73 @@
+import { Separator, Stack, Text } from '@chakra-ui/react';
+
+import { Button } from '../../../components/ui/Button';
+import { useWorkbench } from '../../../WorkbenchContext';
+import { getFormChildren } from '../../../workflows/document';
+import type { ProjectGraphState, WorkflowFormElement } from '../../../workflows/types';
+import { NodeFieldControl } from './NodeFieldControl';
+
+/**
+ * The Linear UI's view mode: the form rendered as clean, runnable controls —
+ * field values stay editable, the form structure does not.
+ */
+
+const ViewElement = ({ element, projectGraph }: { element: WorkflowFormElement; projectGraph: ProjectGraphState }) => {
+ switch (element.type) {
+ case 'container':
+ return (
+ <Stack direction={element.data.layout === 'row' ? 'row' : 'column'} gap="3">
+ {getFormChildren(projectGraph.form, element.id).map((child) => (
+ <ViewElement key={child.id} element={child} projectGraph={projectGraph} />
+ ))}
+ </Stack>
+ );
+ case 'node-field':
+ return <NodeFieldControl element={element} projectGraph={projectGraph} />;
+ case 'heading':
+ return (
+ <Text fontSize="sm" fontWeight="700">
+ {element.data.content}
+ </Text>
+ );
+ case 'text':
+ return (
+ <Text color="fg.muted" fontSize="2xs" whiteSpace="pre-wrap">
+ {element.data.content}
+ </Text>
+ );
+ case 'divider':
+ return <Separator borderColor="border.subtle" />;
+ }
+};
+
+export const LinearFormView = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {
+ const { dispatch } = useWorkbench();
+ const rootChildren = getFormChildren(projectGraph.form);
+
+ if (rootChildren.length === 0) {
+ return (
+ <Stack gap="2" px="1" py="1">
+ <Text color="fg.subtle" fontSize="2xs">
+ No fields are exposed yet. Pin fields in the Workflow editor, or switch to Edit mode to build this form — it
+ maps the project graph to simple controls, like the legacy Linear UI.
+ </Text>
+ <Button
+ size="2xs"
+ variant="outline"
+ w="fit-content"
+ onClick={() => dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'workflow' })}
+ >
+ Open Workflow Editor
+ </Button>
+ </Stack>
+ );
+ }
+
+ return (
+ <Stack gap="3" p="3">
+ {rootChildren.map((element) => (
+ <ViewElement key={element.id} element={element} projectGraph={projectGraph} />
+ ))}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx
new file mode 100644
index 0000000000..90e1fee538
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx
@@ -0,0 +1,122 @@
+import { HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
+import { TriangleAlertIcon } from 'lucide-react';
+import { useState, type ChangeEvent } from 'react';
+
+import { FieldLabel } from '../../../components/ui/Field';
+import { Tooltip } from '../../../components/ui/Tooltip';
+import { useWorkbench } from '../../../WorkbenchContext';
+import { useInvocationTemplatesSnapshot } from '../../../workflows/templates';
+import type { NodeFieldFormElement, ProjectGraphState } from '../../../workflows/types';
+import { isInvocationNode } from '../../../workflows/types';
+import { WorkflowFieldInput } from '../fields/WorkflowFieldInput';
+
+/**
+ * One exposed node field, shared by the Linear UI's view mode and the form
+ * builder: label (optionally editable), optional description, and the live
+ * input — or a note when the field is driven by a graph connection.
+ */
+/** Resolves a form element's node, field instance, and input template against the document. */
+export const useNodeFieldBinding = (element: NodeFieldFormElement, projectGraph: ProjectGraphState) => {
+ const { templates } = useInvocationTemplatesSnapshot();
+ const { fieldName, nodeId } = element.data.fieldIdentifier;
+ const node = projectGraph.nodes.find((candidate) => candidate.id === nodeId);
+ const invocationNode = node && isInvocationNode(node) ? node : null;
+ const template = invocationNode ? templates[invocationNode.data.type]?.inputs[fieldName] : undefined;
+ const instance = invocationNode?.data.inputs[fieldName];
+ const nodeContext = invocationNode
+ ? invocationNode.data.label || templates[invocationNode.data.type]?.title || invocationNode.data.type
+ : '';
+
+ return { fieldName, instance, invocationNode, nodeContext, nodeId, template };
+};
+
+export const NodeFieldControl = ({
+ element,
+ isLabelEditable = false,
+ projectGraph,
+}: {
+ element: NodeFieldFormElement;
+ /** Builder mode renders the label as an input bound to the field instance label. */
+ isLabelEditable?: boolean;
+ projectGraph: ProjectGraphState;
+}) => {
+ const { dispatch } = useWorkbench();
+ const { fieldName, instance, invocationNode, nodeContext, nodeId, template } = useNodeFieldBinding(
+ element,
+ projectGraph
+ );
+ // While the label input is focused it edits a draft seeded from the
+ // *displayed* label, so an unset override starts from the template title
+ // instead of an empty box.
+ const [draftLabel, setDraftLabel] = useState<string | null>(null);
+
+ if (!invocationNode || !template) {
+ return (
+ <HStack gap="1.5">
+ <Icon as={TriangleAlertIcon} boxSize="3" color="fg.error" />
+ <Text color="fg.subtle" fontSize="2xs">
+ This field no longer exists in the project graph.
+ </Text>
+ </HStack>
+ );
+ }
+
+ const isConnected = projectGraph.edges.some((edge) => edge.target === nodeId && edge.targetHandle === fieldName);
+ const label = instance?.label || template.title;
+ const description = instance?.description || template.description;
+
+ return (
+ <Stack gap="1">
+ {isLabelEditable ? (
+ <Input
+ aria-label="Field label"
+ color="fg.muted"
+ fontSize="2xs"
+ fontWeight="600"
+ h="5"
+ placeholder={template.title}
+ size="2xs"
+ textTransform="uppercase"
+ value={draftLabel ?? label}
+ variant="flushed"
+ onBlur={() => setDraftLabel(null)}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => {
+ setDraftLabel(event.currentTarget.value);
+ dispatch({
+ action: { fieldName, label: event.currentTarget.value, nodeId, type: 'setFieldLabel' },
+ type: 'applyProjectGraphAction',
+ });
+ }}
+ onFocus={() => setDraftLabel(label)}
+ />
+ ) : (
+ <Tooltip content={`${nodeContext} → ${template.title}`}>
+ <Stack gap="0" w="fit-content">
+ <FieldLabel>{label}</FieldLabel>
+ </Stack>
+ </Tooltip>
+ )}
+ {element.data.showDescription && description ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ {description}
+ </Text>
+ ) : null}
+ {isConnected ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ Driven by a graph connection.
+ </Text>
+ ) : (
+ <WorkflowFieldInput
+ template={template}
+ value={instance?.value}
+ onChange={(value) =>
+ dispatch({
+ action: { fieldName, nodeId, type: 'setFieldValue', value },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ )}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
new file mode 100644
index 0000000000..43712f6bf1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
@@ -0,0 +1,171 @@
+import { Flex, HStack, Stack, Text, Textarea } from '@chakra-ui/react';
+import type { ChangeEvent } from 'react';
+
+import { JsonPreview } from '../../../components/ui/JsonPreview';
+import { Scrollable } from '../../../components/ui/Scrollable';
+import { Tabs } from '../../../components/ui/Tabs';
+import { useWorkbench } from '../../../WorkbenchContext';
+import { useInvocationTemplatesSnapshot } from '../../../workflows/templates';
+import type {
+ InvocationTemplate,
+ ProjectGraphState,
+ WorkflowInvocationNode,
+ WorkflowNode,
+} from '../../../workflows/types';
+import { workflowSelectionStore } from '../editor/selectionStore';
+
+/**
+ * Edit-mode inspector for the editor's selected node, with the legacy tab
+ * set: Details (summary + notes), Outputs, Data (raw node data), Template
+ * (the node's backend definition). Sizing is owned by the panel's Splitter.
+ */
+
+type InspectorTab = 'details' | 'outputs' | 'data' | 'template';
+
+const getInspectorTab = (values: Record<string, unknown>): InspectorTab =>
+ values.inspectorTab === 'outputs' || values.inspectorTab === 'data' || values.inspectorTab === 'template'
+ ? values.inspectorTab
+ : 'details';
+
+const DetailRow = ({ label, value }: { label: string; value: string }) => (
+ <HStack align="start" gap="2">
+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs" minW="16">
+ {label}
+ </Text>
+ <Text fontSize="2xs" minW="0" wordBreak="break-word">
+ {value}
+ </Text>
+ </HStack>
+);
+
+const JsonBlock = ({ label, value }: { label: string; value: unknown }) => <JsonPreview label={label} value={value} />;
+
+const DetailsTab = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate | undefined }) => {
+ const { dispatch } = useWorkbench();
+
+ return (
+ <Stack gap="2">
+ <DetailRow label="Title" value={node.data.label || template?.title || node.data.type} />
+ <DetailRow label="Type" value={node.data.type} />
+ <DetailRow label="Version" value={node.data.version} />
+ {template ? <DetailRow label="Class" value={template.classification} /> : null}
+ {template ? <DetailRow label="Pack" value={template.nodePack} /> : null}
+ {template?.description ? <DetailRow label="About" value={template.description} /> : null}
+ <Stack gap="1">
+ <Text color="fg.subtle" fontSize="2xs">
+ Notes
+ </Text>
+ <Textarea
+ aria-label="Node notes"
+ fontSize="2xs"
+ minH="3rem"
+ placeholder="Notes about this node…"
+ resize="vertical"
+ size="xs"
+ value={node.data.notes}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>
+ dispatch({
+ action: { nodeId: node.id, notes: event.currentTarget.value, type: 'setNodeNotes' },
+ type: 'applyProjectGraphAction',
+ })
+ }
+ />
+ </Stack>
+ </Stack>
+ );
+};
+
+const OutputsTab = ({ template }: { template: InvocationTemplate | undefined }) => (
+ <Stack gap="2">
+ <Text color="fg.subtle" fontSize="2xs">
+ Run outputs are not recorded per node yet — results currently route to the Gallery or Canvas. This tab will show
+ the node's outputs from its most recent run once run records land.
+ </Text>
+ {template ? (
+ <Stack gap="1">
+ <Text color="fg.subtle" fontSize="2xs">
+ Declared outputs
+ </Text>
+ {Object.values(template.outputs).map((output) => (
+ <DetailRow key={output.name} label={output.title} value={output.type.name} />
+ ))}
+ </Stack>
+ ) : null}
+ </Stack>
+);
+
+const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab }) => {
+ const { templates } = useInvocationTemplatesSnapshot();
+
+ if (node.type === 'notes' || node.type === 'current_image') {
+ return tab === 'data' ? (
+ <JsonBlock label="Node data" value={node.data} />
+ ) : (
+ <DetailRow label="Type" value={node.type === 'notes' ? 'Notes node' : 'Current Image node'} />
+ );
+ }
+
+ const template = templates[node.data.type];
+
+ switch (tab) {
+ case 'details':
+ return <DetailsTab node={node} template={template} />;
+ case 'outputs':
+ return <OutputsTab template={template} />;
+ case 'data':
+ return <JsonBlock label="Node data" value={node.data} />;
+ case 'template':
+ return template ? (
+ <JsonBlock label="Node template" value={template} />
+ ) : (
+ <Text color="fg.subtle" fontSize="2xs">
+ No template is known for "{node.data.type}" on this backend.
+ </Text>
+ );
+ }
+};
+
+export const NodeInspector = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {
+ const { activeProject, dispatch } = useWorkbench();
+ const { selectedNodeIds } = workflowSelectionStore.useSnapshot();
+ const tab = getInspectorTab(activeProject.widgetStates.workflow.values);
+ const selectedNode = projectGraph.nodes.find((node) => node.id === selectedNodeIds[0]);
+
+ return (
+ <Flex direction="column" h="full" minH="0">
+ <HStack flexShrink={0} justify="space-between" px="2" h={10} borderBottomWidth={1}>
+ <Text color="fg.muted" fontSize="2xs" fontWeight="600" textTransform="uppercase">
+ Node Inspector
+ </Text>
+ <Tabs.Root
+ size="sm"
+ value={tab}
+ variant="outline"
+ mb="-1"
+ onValueChange={(event) =>
+ dispatch({ type: 'patchWidgetValues', values: { inspectorTab: event.value }, widgetId: 'workflow' })
+ }
+ >
+ <Tabs.List>
+ {(['details', 'outputs', 'data', 'template'] as const).map((value) => (
+ <Tabs.Trigger key={value} fontSize="2xs" textTransform="capitalize" value={value}>
+ {value}
+ </Tabs.Trigger>
+ ))}
+ </Tabs.List>
+ </Tabs.Root>
+ </HStack>
+ <Scrollable flex="1" label="Selected node inspector" minH="0">
+ <Stack p="3">
+ {selectedNode ? (
+ <InspectorBody node={selectedNode} tab={tab} />
+ ) : (
+ <Text color="fg.subtle" fontSize="2xs">
+ Select a node in the Workflow editor to inspect it.
+ </Text>
+ )}
+ </Stack>
+ </Scrollable>
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx
new file mode 100644
index 0000000000..c1f4a81db5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx
@@ -0,0 +1,55 @@
+import { HStack, Input, Stack, Textarea } from '@chakra-ui/react';
+import type { ChangeEvent } from 'react';
+
+import { Field } from '../../../components/ui/Field';
+import { useWorkbench } from '../../../WorkbenchContext';
+import type { WorkflowMetadata } from '../../../workflows/types';
+
+/** Workflow metadata editing — the legacy "Details" tab. */
+export const WorkflowDetailsTab = ({ metadata }: { metadata: WorkflowMetadata }) => {
+ const { dispatch } = useWorkbench();
+ const commit = (patch: Partial<WorkflowMetadata>) =>
+ dispatch({ action: { patch, type: 'setMetadata' }, type: 'applyProjectGraphAction' });
+
+ const textField = (label: string, key: keyof WorkflowMetadata) => (
+ <Field label={label}>
+ <Input
+ size="xs"
+ value={metadata[key]}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => commit({ [key]: event.currentTarget.value })}
+ />
+ </Field>
+ );
+
+ return (
+ <Stack gap="3" p="3">
+ {textField('Name', 'name')}
+ <Field label="Description">
+ <Textarea
+ minH="3.5rem"
+ resize="vertical"
+ size="xs"
+ value={metadata.description}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => commit({ description: event.currentTarget.value })}
+ />
+ </Field>
+ <HStack align="start" gap="2">
+ {textField('Author', 'author')}
+ {textField('Version', 'workflowVersion')}
+ </HStack>
+ <HStack align="start" gap="2">
+ {textField('Tags', 'tags')}
+ {textField('Contact', 'contact')}
+ </HStack>
+ <Field label="Notes">
+ <Textarea
+ minH="3.5rem"
+ resize="vertical"
+ size="xs"
+ value={metadata.notes}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => commit({ notes: event.currentTarget.value })}
+ />
+ </Field>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowJsonTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowJsonTab.tsx
new file mode 100644
index 0000000000..88b2c48aa0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowJsonTab.tsx
@@ -0,0 +1,12 @@
+import { Stack } from '@chakra-ui/react';
+
+import { JsonPreview } from '../../../components/ui/JsonPreview';
+import type { ProjectGraphState } from '../../../workflows/types';
+import { getWorkflowJsonText } from '../workflowTransfer';
+
+/** Read-only view of the serialized workflow — the legacy "JSON" tab. */
+export const WorkflowJsonTab = ({ projectGraph }: { projectGraph: ProjectGraphState }) => (
+ <Stack p="1.5">
+ <JsonPreview label="Workflow JSON" text={getWorkflowJsonText(projectGraph)} />
+ </Stack>
+);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx
new file mode 100644
index 0000000000..e2dd0b3a0c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx
@@ -0,0 +1,161 @@
+import { Flex, HStack, Icon, SegmentGroup, Splitter } from '@chakra-ui/react';
+import { EyeIcon, PencilIcon } from 'lucide-react';
+import { useEffect } from 'react';
+
+import { Scrollable } from '../../../components/ui/Scrollable';
+import { Tabs } from '../../../components/ui/Tabs';
+import { useWorkbench } from '../../../WorkbenchContext';
+import { ensureInvocationTemplatesLoaded } from '../../../workflows/templates';
+import { FormBuilderTab } from './FormBuilderTab';
+import { LinearFormView } from './LinearFormView';
+import { NodeInspector } from './NodeInspector';
+import { WorkflowDetailsTab } from './WorkflowDetailsTab';
+import { WorkflowJsonTab } from './WorkflowJsonTab';
+
+/**
+ * The workflow widget's side panel — the Linear UI. View mode runs the
+ * project graph through its form; Edit mode opens the legacy-style tab set
+ * (Form builder / Details / JSON) with the node inspector pinned below.
+ * Panel mode, tab, and inspector height live in the widget's own state.
+ */
+
+type PanelMode = 'view' | 'edit';
+type EditTab = 'form' | 'details' | 'json';
+
+/** Inspector share of the splitter, as a percentage of the panel height. */
+const DEFAULT_INSPECTOR_SIZE_PCT = 35;
+const SPLITTER_PANELS = [
+ { id: 'content', minSize: 25 },
+ { id: 'inspector', minSize: 12 },
+];
+
+const getPanelMode = (values: Record<string, unknown>): PanelMode => (values.panelMode === 'edit' ? 'edit' : 'view');
+
+const getEditTab = (values: Record<string, unknown>): EditTab =>
+ values.editTab === 'details' || values.editTab === 'json' ? values.editTab : 'form';
+
+const getInspectorSizePct = (values: Record<string, unknown>): number =>
+ typeof values.inspectorSizePct === 'number' && Number.isFinite(values.inspectorSizePct)
+ ? Math.min(75, Math.max(12, values.inspectorSizePct))
+ : DEFAULT_INSPECTOR_SIZE_PCT;
+
+const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange: (mode: PanelMode) => void }) => {
+ type PanelModeItem = {
+ label: string;
+ icon: typeof EyeIcon;
+ mode: PanelMode;
+ };
+
+ const PANEL_MODES: PanelModeItem[] = [
+ {
+ label: 'View',
+ icon: EyeIcon,
+ mode: 'view',
+ },
+ {
+ label: 'Edit',
+ icon: PencilIcon,
+ mode: 'edit',
+ },
+ ];
+
+ const onValueChange = (details: { value: string | null }) => {
+ if (details.value === 'view' || details.value === 'edit') {
+ onChange(details.value);
+ }
+ };
+
+ return (
+ <SegmentGroup.Root value={mode} onValueChange={onValueChange} size="xs">
+ <SegmentGroup.Indicator />
+ {PANEL_MODES.map(({ label, icon, mode }) => (
+ <SegmentGroup.Item key={mode} value={mode}>
+ <SegmentGroup.ItemHiddenInput />
+ <Icon as={icon} boxSize="3" />
+ <SegmentGroup.ItemText>{label}</SegmentGroup.ItemText>
+ </SegmentGroup.Item>
+ ))}
+ </SegmentGroup.Root>
+ );
+};
+
+export const WorkflowLinearPanel = () => {
+ const { activeProject, dispatch } = useWorkbench();
+ const projectGraph = activeProject.projectGraph;
+ const widgetValues = activeProject.widgetStates.workflow.values;
+ const mode = getPanelMode(widgetValues);
+ const editTab = getEditTab(widgetValues);
+
+ useEffect(() => {
+ ensureInvocationTemplatesLoaded();
+ }, []);
+
+ const patchValues = (values: Record<string, unknown>) =>
+ dispatch({ type: 'patchWidgetValues', values, widgetId: 'workflow' });
+
+ return (
+ <Flex direction="column" flex="1" h="full" minH="0">
+ <HStack flexShrink={0} justify="space-between" px="2" h={10} borderBottomWidth={1}>
+ <PanelModeToggle mode={mode} onChange={(panelMode) => patchValues({ panelMode })} />
+ {mode === 'edit' ? (
+ <Tabs.Root
+ size="sm"
+ value={editTab}
+ variant="outline"
+ mb="-1"
+ onValueChange={(event) => patchValues({ editTab: event.value })}
+ >
+ <Tabs.List>
+ <Tabs.Trigger value="form" fontSize="2xs">
+ Form
+ </Tabs.Trigger>
+ <Tabs.Trigger value="details" fontSize="2xs">
+ Details
+ </Tabs.Trigger>
+ <Tabs.Trigger value="json" fontSize="2xs">
+ JSON
+ </Tabs.Trigger>
+ </Tabs.List>
+ </Tabs.Root>
+ ) : null}
+ </HStack>
+ {mode === 'view' ? (
+ <Scrollable flex="1" label="Workflow panel content" minH="0">
+ <LinearFormView projectGraph={projectGraph} />
+ </Scrollable>
+ ) : (
+ <Splitter.Root
+ defaultSize={[100 - getInspectorSizePct(widgetValues), getInspectorSizePct(widgetValues)]}
+ flex="1"
+ gap="0"
+ minH="0"
+ orientation="vertical"
+ panels={SPLITTER_PANELS}
+ onResizeEnd={(details) => {
+ const inspectorSizePct = details.size[1];
+
+ if (typeof inspectorSizePct === 'number') {
+ patchValues({ inspectorSizePct });
+ }
+ }}
+ >
+ <Splitter.Panel id="content" minH="0" overflow="hidden">
+ <Scrollable flex="1" h="full" label="Workflow panel content" minH="0" w="full">
+ {editTab === 'form' ? (
+ <FormBuilderTab projectGraph={projectGraph} />
+ ) : editTab === 'details' ? (
+ <WorkflowDetailsTab metadata={projectGraph} />
+ ) : (
+ <WorkflowJsonTab projectGraph={projectGraph} />
+ )}
+ </Scrollable>
+ </Splitter.Panel>
+ <Splitter.ResizeTrigger aria-label="Resize node inspector" id="content:inspector" />
+ <Splitter.Panel id="inspector" minH="0" overflow="hidden">
+ <NodeInspector projectGraph={projectGraph} />
+ </Splitter.Panel>
+ </Splitter.Root>
+ )}
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowTransfer.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowTransfer.ts
new file mode 100644
index 0000000000..c298bf5e51
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowTransfer.ts
@@ -0,0 +1,21 @@
+import type { ProjectGraphState } from '../../workflows/types';
+import { serializeWorkflowJson } from '../../workflows/workflowJson';
+
+/** Export-side helpers shared by the workflow menu items and panels. */
+
+export const downloadWorkflowJson = (document: ProjectGraphState): void => {
+ const blob = new Blob([JSON.stringify(serializeWorkflowJson(document), null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const anchor = window.document.createElement('a');
+
+ anchor.href = url;
+ anchor.download = `${document.name.trim() || 'workflow'}.json`;
+ anchor.click();
+ URL.revokeObjectURL(url);
+};
+
+export const getWorkflowJsonText = (document: ProjectGraphState): string =>
+ JSON.stringify(serializeWorkflowJson(document), null, 2);
+
+export const copyWorkflowJson = (document: ProjectGraphState): Promise<void> =>
+ navigator.clipboard.writeText(getWorkflowJsonText(document));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts
new file mode 100644
index 0000000000..fe1e8fd83d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/workflowUiStore.ts
@@ -0,0 +1,63 @@
+import { createExternalStore } from '../../externalStore';
+
+/**
+ * Session-lived UI coordination for the workflow widget. Menu items live
+ * inside the shared widget actions menu while their dialogs and the import
+ * file input live in the always-mounted header actions — this store is the
+ * bridge between the two.
+ */
+
+export interface WorkflowUiSnapshot {
+ isAddNodeOpen: boolean;
+ isLibraryOpen: boolean;
+ isNewWorkflowConfirmOpen: boolean;
+ /** Bumped to ask the dialog host to open the JSON file picker. */
+ importRequestCount: number;
+ /**
+ * The workflow surface currently responsible for rendering the shared
+ * dialogs and file input. Both surfaces (center editor, left panel) can be
+ * mounted at once; exactly one — the first to mount — hosts them.
+ */
+ dialogHostId: string | null;
+}
+
+export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>({
+ dialogHostId: null,
+ importRequestCount: 0,
+ isAddNodeOpen: false,
+ isLibraryOpen: false,
+ isNewWorkflowConfirmOpen: false,
+});
+
+const dialogHostIds: string[] = [];
+
+export const claimWorkflowDialogHost = (hostId: string): void => {
+ dialogHostIds.push(hostId);
+ workflowUiStore.patchSnapshot({ dialogHostId: dialogHostIds[0] ?? null });
+};
+
+export const releaseWorkflowDialogHost = (hostId: string): void => {
+ const index = dialogHostIds.indexOf(hostId);
+
+ if (index !== -1) {
+ dialogHostIds.splice(index, 1);
+ }
+
+ workflowUiStore.patchSnapshot({ dialogHostId: dialogHostIds[0] ?? null });
+};
+
+export const setWorkflowLibraryOpen = (isOpen: boolean): void => {
+ workflowUiStore.patchSnapshot({ isLibraryOpen: isOpen });
+};
+
+export const setAddNodeOpen = (isOpen: boolean): void => {
+ workflowUiStore.patchSnapshot({ isAddNodeOpen: isOpen });
+};
+
+export const setNewWorkflowConfirmOpen = (isOpen: boolean): void => {
+ workflowUiStore.patchSnapshot({ isNewWorkflowConfirmOpen: isOpen });
+};
+
+export const requestWorkflowImport = (): void => {
+ workflowUiStore.patchSnapshot({ importRequestCount: workflowUiStore.getSnapshot().importRequestCount + 1 });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/api.ts b/invokeai/frontend/webv2/src/workbench/workflows/api.ts
new file mode 100644
index 0000000000..43a4dac055
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/workflows/api.ts
@@ -0,0 +1,95 @@
+import { apiFetch, apiFetchJson } from '../backend/http';
+
+/**
+ * Client for the backend workflow library (`/api/v1/workflows`). The library
+ * stores legacy-format WorkflowV3 JSON, so payloads round-trip through
+ * `workflowJson.ts` on their way in and out of the project graph document.
+ */
+
+export type WorkflowLibraryCategory = 'user' | 'default';
+
+export interface WorkflowLibraryListItem {
+ workflow_id: string;
+ name: string;
+ description: string;
+ category: WorkflowLibraryCategory;
+ tags?: string | null;
+ created_at?: string;
+ updated_at?: string;
+ opened_at?: string | null;
+ thumbnail_url?: string | null;
+}
+
+export interface WorkflowLibraryPage {
+ items: WorkflowLibraryListItem[];
+ page: number;
+ pages: number;
+ total: number;
+}
+
+export interface ListWorkflowsParams {
+ category: WorkflowLibraryCategory;
+ page: number;
+ perPage?: number;
+ query?: string;
+}
+
+export const listLibraryWorkflows = ({
+ category,
+ page,
+ perPage = 20,
+ query,
+}: ListWorkflowsParams): Promise<WorkflowLibraryPage> => {
+ const params = new URLSearchParams({
+ direction: 'DESC',
+ order_by: 'updated_at',
+ page: String(page),
+ per_page: String(perPage),
+ });
+
+ params.append('categories', category);
+
+ if (query?.trim()) {
+ params.set('query', query.trim());
+ }
+
+ return apiFetchJson<WorkflowLibraryPage>(`/api/v1/workflows/?${params.toString()}`);
+};
+
+interface WorkflowRecordDTO {
+ workflow_id: string;
+ name: string;
+ workflow: Record<string, unknown>;
+}
+
+/** Returns the stored workflow JSON, with the record id stamped in. */
+export const getLibraryWorkflow = async (workflowId: string): Promise<Record<string, unknown>> => {
+ const record = await apiFetchJson<WorkflowRecordDTO>(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`);
+
+ return { ...record.workflow, id: record.workflow_id };
+};
+
+export const createLibraryWorkflow = async (workflow: Record<string, unknown>): Promise<string> => {
+ const { id: _id, ...workflowWithoutId } = workflow;
+ const record = await apiFetchJson<WorkflowRecordDTO>('/api/v1/workflows/', {
+ body: JSON.stringify({ workflow: workflowWithoutId }),
+ method: 'POST',
+ });
+
+ return record.workflow_id;
+};
+
+export const updateLibraryWorkflow = async (workflowId: string, workflow: Record<string, unknown>): Promise<void> => {
+ await apiFetchJson(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, {
+ body: JSON.stringify({ workflow: { ...workflow, id: workflowId } }),
+ method: 'PATCH',
+ });
+};
+
+export const deleteLibraryWorkflow = async (workflowId: string): Promise<void> => {
+ await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, { method: 'DELETE' });
+};
+
+export const touchLibraryWorkflowOpenedAt = async (workflowId: string): Promise<void> => {
+ await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/opened_at`, { method: 'PUT' });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/fields.ts b/invokeai/frontend/webv2/src/workbench/workflows/fields.ts
new file mode 100644
index 0000000000..9c6cde4293
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/workflows/fields.ts
@@ -0,0 +1,86 @@
+import type { FieldInputTemplate, FieldType } from './types';
+
+/**
+ * Field-kind helpers shared by the node editor and the Linear UI panel:
+ * which field types render direct-input controls, and how handles/edges are
+ * tinted by type so connections stay readable.
+ */
+
+/** Field types with a direct-input widget. Everything else is connection-only. */
+const STATEFUL_FIELD_TYPE_NAMES = new Set([
+ 'BoardField',
+ 'BooleanField',
+ 'ColorField',
+ 'EnumField',
+ 'FloatField',
+ 'ImageField',
+ 'IntegerField',
+ 'ModelIdentifierField',
+ 'SchedulerField',
+ 'StringField',
+]);
+
+export const isStatefulFieldType = (type: FieldType): boolean => STATEFUL_FIELD_TYPE_NAMES.has(type.name);
+
+/** True when the field renders an editable control on the node / linear form. */
+export const isDirectInputField = (template: FieldInputTemplate): boolean =>
+ template.input !== 'connection' && isStatefulFieldType(template.type) && template.type.cardinality !== 'COLLECTION';
+
+/** A field can be exposed to the Linear UI when it can be edited directly. */
+export const isExposableField = (template: FieldInputTemplate): boolean => isDirectInputField(template);
+
+// Raw hex (not Chakra tokens) because xyflow handles are styled inline.
+const FIELD_TYPE_COLORS: Record<string, string> = {
+ AnyField: '#9ca3af',
+ BoardField: '#a78bfa',
+ BooleanField: '#4ade80',
+ CLIPField: '#2dd4bf',
+ ColorField: '#f472b6',
+ ConditioningField: '#22d3ee',
+ ControlField: '#5eead4',
+ DenoiseMaskField: '#93c5fd',
+ EnumField: '#60a5fa',
+ FloatField: '#fb923c',
+ ImageField: '#c4b5fd',
+ IntegerField: '#f87171',
+ LatentsField: '#f9a8d4',
+ ModelIdentifierField: '#14b8a6',
+ SchedulerField: '#3b82f6',
+ StringField: '#facc15',
+ UNetField: '#fca5a5',
+ VAEField: '#2563eb',
+};
+
+const FALLBACK_COLORS = ['#06b6d4', '#a855f7', '#22c55e', '#f97316', '#ec4899', '#0d9488'];
+
+/** Stable tint for a field type: known types get fixed colors, the rest hash into a small palette. */
+export const getFieldTypeColor = (type: FieldType): string => {
+ const known = FIELD_TYPE_COLORS[type.name];
+
+ if (known) {
+ return known;
+ }
+
+ let hash = 0;
+
+ for (const char of type.name) {
+ hash = (hash * 31 + char.charCodeAt(0)) % FALLBACK_COLORS.length;
+ }
+
+ return FALLBACK_COLORS[hash] as string;
+};
+
+/** Display label for a field type, e.g. `ImageField (Collection)`. */
+export const getFieldTypeLabel = (type: FieldType): string => {
+ const base = type.name.replace(/Field$/, '');
+
+ if (type.cardinality === 'COLLECTION') {
+ return `${base} Collection`;
+ }
+
+ if (type.cardinality === 'SINGLE_OR_COLLECTION') {
+ return `${base} (single or collection)`;
+ }
+
+ return base;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/libraryCache.ts b/invokeai/frontend/webv2/src/workbench/workflows/libraryCache.ts
new file mode 100644
index 0000000000..ce69eaec0d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/workflows/libraryCache.ts
@@ -0,0 +1,46 @@
+import { getLibraryWorkflow, listLibraryWorkflows, type ListWorkflowsParams, type WorkflowLibraryPage } from './api';
+
+/**
+ * Session-lived cache in front of the workflow library API. The library
+ * dialog opens instantly on cached pages and revalidates in the background;
+ * any local mutation (save/delete) invalidates everything since it shifts
+ * ordering and pagination.
+ */
+
+const pageCache = new Map<string, WorkflowLibraryPage>();
+const workflowCache = new Map<string, Record<string, unknown>>();
+
+const getPageKey = (params: ListWorkflowsParams): string =>
+ `${params.category}|${params.page}|${params.perPage ?? 20}|${params.query?.trim() ?? ''}`;
+
+export const getCachedWorkflowPage = (params: ListWorkflowsParams): WorkflowLibraryPage | null =>
+ pageCache.get(getPageKey(params)) ?? null;
+
+/** Fetches a page and stores it; callers show `getCachedWorkflowPage` while this resolves. */
+export const listLibraryWorkflowsCached = async (params: ListWorkflowsParams): Promise<WorkflowLibraryPage> => {
+ const result = await listLibraryWorkflows(params);
+
+ pageCache.set(getPageKey(params), result);
+
+ return result;
+};
+
+/** Workflow payloads are immutable per save; cache hits skip the fetch entirely. */
+export const getLibraryWorkflowCached = async (workflowId: string): Promise<Record<string, unknown>> => {
+ const cached = workflowCache.get(workflowId);
+
+ if (cached) {
+ return cached;
+ }
+
+ const result = await getLibraryWorkflow(workflowId);
+
+ workflowCache.set(workflowId, result);
+
+ return result;
+};
+
+export const invalidateWorkflowLibraryCache = (): void => {
+ pageCache.clear();
+ workflowCache.clear();
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts
new file mode 100644
index 0000000000..c5f70aa756
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildCurrentImageNode,
+ buildInvocationNode,
+ buildNotesNode,
+ createProjectGraph,
+ getFormChildren,
+ projectGraphReducer,
+} from './document';
+import type { InvocationTemplate } from './types';
+import { parseWorkflowJson, serializeWorkflowJson } from './workflowJson';
+
+const template: InvocationTemplate = {
+ category: 'test',
+ classification: 'stable',
+ description: '',
+ inputs: {
+ prompt: {
+ default: 'a cat',
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ input: 'any',
+ maximum: null,
+ minimum: null,
+ multipleOf: null,
+ name: 'prompt',
+ options: null,
+ required: true,
+ title: 'Prompt',
+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },
+ uiChoiceLabels: null,
+ uiComponent: 'textarea',
+ uiHidden: false,
+ uiModelBase: null,
+ uiModelType: null,
+ uiOrder: null,
+ },
+ },
+ nodePack: 'invokeai',
+ outputs: {},
+ outputType: 'string_output',
+ tags: [],
+ title: 'Prompt',
+ type: 'prompt',
+ useCache: true,
+ version: '1.2.0',
+};
+
+describe('workflow JSON round-trip', () => {
+ it('serializes and re-parses a document, preserving nodes, edges, form, and metadata', () => {
+ const node = buildInvocationNode(template, { x: 10, y: 20 });
+ let doc = createProjectGraph('roundtrip');
+
+ doc = projectGraphReducer(doc, { node, type: 'addNode' });
+ doc = projectGraphReducer(doc, {
+ description: 'Custom description',
+ fieldName: 'prompt',
+ nodeId: node.id,
+ type: 'setFieldDescription',
+ });
+ doc = projectGraphReducer(doc, { fieldIdentifier: { fieldName: 'prompt', nodeId: node.id }, type: 'exposeField' });
+ doc = projectGraphReducer(doc, {
+ patch: { author: 'josh', description: 'desc', name: 'Round Trip', tags: 'a,b' },
+ type: 'setMetadata',
+ });
+
+ const serialized = serializeWorkflowJson(doc);
+ const { document: parsed, warnings } = parseWorkflowJson(serialized);
+
+ expect(warnings).toEqual([]);
+ expect(parsed.name).toBe('Round Trip');
+ expect(parsed.author).toBe('josh');
+ expect(parsed.nodes).toHaveLength(1);
+
+ const parsedNode = parsed.nodes[0];
+
+ expect(parsedNode?.id).toBe(node.id);
+ expect(parsedNode?.position).toEqual({ x: 10, y: 20 });
+ expect(parsedNode?.type === 'invocation' && parsedNode.data.inputs.prompt?.value).toBe('a cat');
+ expect(parsedNode?.type === 'invocation' && parsedNode.data.inputs.prompt?.description).toBe('Custom description');
+
+ const formChildren = getFormChildren(parsed.form);
+
+ expect(formChildren).toHaveLength(1);
+ expect(formChildren[0]?.type).toBe('node-field');
+ });
+
+ it('keeps the serialized shape legacy-compatible', () => {
+ const doc = createProjectGraph('legacy-shape');
+ const serialized = serializeWorkflowJson(doc);
+
+ expect(serialized.meta).toEqual({ category: 'user', version: '3.0.0' });
+ expect(serialized.exposedFields).toEqual([]);
+ expect(serialized).toHaveProperty('form');
+ });
+
+ it('round-trips notes and current_image UI nodes', () => {
+ let doc = createProjectGraph('ui-nodes');
+
+ doc = projectGraphReducer(doc, { node: buildNotesNode({ x: 1, y: 2 }), type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: buildCurrentImageNode({ x: 3, y: 4 }), type: 'addNode' });
+
+ const { document: parsed, warnings } = parseWorkflowJson(serializeWorkflowJson(doc));
+
+ expect(warnings).toEqual([]);
+ expect(parsed.nodes.map((node) => node.type).sort()).toEqual(['current_image', 'notes']);
+
+ const currentImage = parsed.nodes.find((node) => node.type === 'current_image');
+
+ expect(currentImage?.position).toEqual({ x: 3, y: 4 });
+ expect(currentImage?.type === 'current_image' && currentImage.data.label).toBe('Current Image');
+ });
+});
+
+describe('parseWorkflowJson tolerance', () => {
+ it('migrates pre-form exposedFields into form elements', () => {
+ const { document, warnings } = parseWorkflowJson({
+ edges: [],
+ exposedFields: [{ fieldName: 'prompt', nodeId: 'n1' }],
+ name: 'Old Workflow',
+ nodes: [
+ {
+ data: { id: 'n1', inputs: { prompt: { label: '', name: 'prompt', value: 'hi' } }, type: 'prompt' },
+ id: 'n1',
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+ },
+ ],
+ version: '1.0.0',
+ });
+
+ expect(warnings).toEqual([]);
+
+ const children = getFormChildren(document.form);
+
+ expect(children).toHaveLength(1);
+ expect(children[0]?.type === 'node-field' && children[0].data.fieldIdentifier).toEqual({
+ fieldName: 'prompt',
+ nodeId: 'n1',
+ });
+ });
+
+ it('flattens connector chains back to their real source', () => {
+ const { document, warnings } = parseWorkflowJson({
+ edges: [
+ { id: 'e1', source: 'n1', sourceHandle: 'out', target: 'conn1', targetHandle: 'in', type: 'default' },
+ { id: 'e2', source: 'conn1', sourceHandle: 'out', target: 'n2', targetHandle: 'text', type: 'default' },
+ ],
+ name: 'Connectors',
+ nodes: [
+ { data: { id: 'n1', inputs: {}, type: 'a' }, id: 'n1', position: { x: 0, y: 0 }, type: 'invocation' },
+ { data: { id: 'n2', inputs: {}, type: 'b' }, id: 'n2', position: { x: 0, y: 0 }, type: 'invocation' },
+ { id: 'conn1', position: { x: 0, y: 0 }, type: 'connector' },
+ ],
+ });
+
+ expect(warnings.some((warning) => warning.includes('connector'))).toBe(true);
+ expect(document.nodes).toHaveLength(2);
+ expect(document.edges).toEqual([
+ { id: 'e2', source: 'n1', sourceHandle: 'out', target: 'n2', targetHandle: 'text', type: 'default' },
+ ]);
+ });
+
+ it('drops dangling edges and unknown form elements with warnings', () => {
+ const { document, warnings } = parseWorkflowJson({
+ edges: [{ id: 'e1', source: 'missing', sourceHandle: 'out', target: 'n1', targetHandle: 'in', type: 'default' }],
+ form: { elements: { weird: { id: 'weird', type: 'mystery' } }, rootElementId: 'missing-root' },
+ name: 'Broken',
+ nodes: [{ data: { id: 'n1', inputs: {}, type: 'a' }, id: 'n1', position: { x: 0, y: 0 }, type: 'invocation' }],
+ });
+
+ expect(document.edges).toEqual([]);
+ expect(document.form.elements[document.form.rootElementId]?.type).toBe('container');
+ expect(warnings.length).toBeGreaterThan(0);
+ });
+
+ it('rejects non-workflow payloads', () => {
+ expect(() => parseWorkflowJson('not a workflow')).toThrow(/not a recognizable/);
+ });
+
+ it('accepts form: null, as stored by pre-form-builder library workflows', () => {
+ const { document, warnings } = parseWorkflowJson({
+ edges: [],
+ form: null,
+ name: 'No Form',
+ nodes: [{ data: { id: 'n1', inputs: {}, type: 'a' }, id: 'n1', position: { x: 0, y: 0 }, type: 'invocation' }],
+ });
+
+ expect(warnings).toEqual([]);
+ expect(document.form.elements[document.form.rootElementId]?.type).toBe('container');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts
new file mode 100644
index 0000000000..de184fab43
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/workflows/workflowJson.ts
@@ -0,0 +1,441 @@
+import { z } from 'zod';
+
+import { createWorkflowForm, createWorkflowId } from './document';
+import type {
+ ProjectGraphState,
+ WorkflowEdge,
+ WorkflowFieldInstance,
+ WorkflowForm,
+ WorkflowFormElement,
+ WorkflowNode,
+} from './types';
+
+/**
+ * Import/export between the project graph document and the legacy WorkflowV3
+ * JSON format — the format used by workflow files, image-embedded workflows,
+ * and the backend workflow library. Parsing is tolerant: recoverable problems
+ * (unknown elements, dangling edges, connector nodes) become warnings instead
+ * of failures.
+ */
+
+const zXYPosition = z.object({ x: z.number().catch(0), y: z.number().catch(0) }).catch({ x: 0, y: 0 });
+
+const zFieldInstance = z.object({
+ description: z.string().optional().catch(undefined),
+ label: z.string().catch(''),
+ name: z.string(),
+ value: z.unknown().optional(),
+});
+
+const zInvocationNode = z.object({
+ data: z.looseObject({
+ inputs: z.record(z.string(), zFieldInstance).catch({}),
+ isIntermediate: z.boolean().catch(true),
+ isOpen: z.boolean().catch(true),
+ label: z.string().catch(''),
+ nodePack: z.string().catch('invokeai'),
+ notes: z.string().catch(''),
+ type: z.string(),
+ useCache: z.boolean().catch(true),
+ version: z.string().catch('1.0.0'),
+ }),
+ id: z.string().min(1),
+ position: zXYPosition,
+ type: z.literal('invocation'),
+});
+
+const zNotesNode = z.object({
+ data: z.looseObject({
+ label: z.string().catch('Notes'),
+ notes: z.string().catch(''),
+ }),
+ id: z.string().min(1),
+ position: zXYPosition,
+ type: z.literal('notes'),
+});
+
+const zCurrentImageNode = z.object({
+ data: z.looseObject({
+ label: z.string().catch('Current Image'),
+ }),
+ id: z.string().min(1),
+ position: zXYPosition,
+ type: z.literal('current_image'),
+});
+
+const zConnectorNode = z.object({
+ id: z.string().min(1),
+ position: zXYPosition,
+ type: z.literal('connector'),
+});
+
+const zAnyNode = z.union([zInvocationNode, zNotesNode, zCurrentImageNode, zConnectorNode]);
+
+const zDefaultEdge = z.object({
+ id: z.string().catch(''),
+ source: z.string().min(1),
+ sourceHandle: z.string().min(1),
+ target: z.string().min(1),
+ targetHandle: z.string().min(1),
+ type: z.literal('default').catch('default'),
+});
+
+const zFieldIdentifier = z.object({ fieldName: z.string(), nodeId: z.string() });
+
+const zFormElement = z.discriminatedUnion('type', [
+ z.object({
+ data: z.looseObject({
+ children: z.array(z.string()).catch([]),
+ layout: z.enum(['column', 'row']).catch('column'),
+ }),
+ id: z.string(),
+ parentId: z.string().optional(),
+ type: z.literal('container'),
+ }),
+ z.object({
+ data: z.looseObject({
+ fieldIdentifier: zFieldIdentifier,
+ showDescription: z.boolean().catch(false),
+ }),
+ id: z.string(),
+ parentId: z.string().optional(),
+ type: z.literal('node-field'),
+ }),
+ z.object({
+ data: z.looseObject({ content: z.string().catch('') }),
+ id: z.string(),
+ parentId: z.string().optional(),
+ type: z.literal('heading'),
+ }),
+ z.object({
+ data: z.looseObject({ content: z.string().catch('') }),
+ id: z.string(),
+ parentId: z.string().optional(),
+ type: z.literal('text'),
+ }),
+ z.object({
+ id: z.string(),
+ parentId: z.string().optional(),
+ type: z.literal('divider'),
+ }),
+]);
+
+const zWorkflowJson = z.looseObject({
+ author: z.string().catch(''),
+ contact: z.string().catch(''),
+ description: z.string().catch(''),
+ edges: z.array(z.unknown()).catch([]),
+ exposedFields: z.array(zFieldIdentifier).catch([]),
+ // Workflows that predate the form builder store `form: null`; a malformed
+ // form also degrades to "absent" rather than failing the whole parse.
+ form: z
+ .object({
+ elements: z.record(z.string(), z.unknown()),
+ rootElementId: z.string(),
+ })
+ .nullish()
+ .catch(null),
+ id: z.string().optional(),
+ name: z.string().catch(''),
+ nodes: z.array(z.unknown()).catch([]),
+ notes: z.string().catch(''),
+ tags: z.string().catch(''),
+ version: z.string().catch('1.0.0'),
+});
+
+export interface ParsedWorkflow {
+ document: ProjectGraphState;
+ warnings: string[];
+}
+
+/**
+ * Resolves edges that pass through legacy connector nodes by walking each
+ * connector chain back to its real invocation source.
+ */
+const resolveConnectorEdges = (
+ edges: Array<z.infer<typeof zDefaultEdge>>,
+ connectorIds: Set<string>
+): { resolved: Array<z.infer<typeof zDefaultEdge>>; dropped: number } => {
+ if (connectorIds.size === 0) {
+ return { dropped: 0, resolved: edges };
+ }
+
+ const findRealSource = (nodeId: string, visited: Set<string>): { source: string; sourceHandle: string } | null => {
+ if (visited.has(nodeId)) {
+ return null;
+ }
+
+ visited.add(nodeId);
+
+ const inboundEdge = edges.find((edge) => edge.target === nodeId);
+
+ if (!inboundEdge) {
+ return null;
+ }
+
+ if (!connectorIds.has(inboundEdge.source)) {
+ return { source: inboundEdge.source, sourceHandle: inboundEdge.sourceHandle };
+ }
+
+ return findRealSource(inboundEdge.source, visited);
+ };
+
+ let dropped = 0;
+ const resolved: Array<z.infer<typeof zDefaultEdge>> = [];
+
+ for (const edge of edges) {
+ if (connectorIds.has(edge.target)) {
+ continue; // Edges into connectors are consumed by the resolution walk.
+ }
+
+ if (!connectorIds.has(edge.source)) {
+ resolved.push(edge);
+ continue;
+ }
+
+ const realSource = findRealSource(edge.source, new Set());
+
+ if (!realSource) {
+ dropped += 1;
+ continue;
+ }
+
+ resolved.push({ ...edge, source: realSource.source, sourceHandle: realSource.sourceHandle });
+ }
+
+ return { dropped, resolved };
+};
+
+const parseForm = (
+ rawForm: z.infer<typeof zWorkflowJson>['form'],
+ exposedFields: Array<z.infer<typeof zFieldIdentifier>>,
+ nodeIds: Set<string>,
+ warnings: string[]
+): WorkflowForm => {
+ let form: WorkflowForm | null = null;
+
+ if (rawForm) {
+ const elements: Record<string, WorkflowFormElement> = {};
+
+ for (const [id, rawElement] of Object.entries(rawForm.elements)) {
+ const parsed = zFormElement.safeParse(rawElement);
+
+ if (parsed.success) {
+ elements[id] = parsed.data as WorkflowFormElement;
+ } else {
+ warnings.push(`Skipped an unrecognized form element (${id}).`);
+ }
+ }
+
+ const root = elements[rawForm.rootElementId];
+
+ if (root?.type === 'container') {
+ form = { elements, rootElementId: rawForm.rootElementId };
+ } else if (Object.keys(rawForm.elements).length > 0) {
+ warnings.push('The workflow form was malformed and has been reset.');
+ }
+ }
+
+ if (!form) {
+ form = createWorkflowForm();
+
+ // Pre-form workflows list exposed fields instead; migrate them into form elements.
+ const root = form.elements[form.rootElementId];
+
+ if (root?.type === 'container') {
+ for (const fieldIdentifier of exposedFields) {
+ const element: WorkflowFormElement = {
+ data: { fieldIdentifier, showDescription: false },
+ id: createWorkflowId('node-field'),
+ parentId: root.id,
+ type: 'node-field',
+ };
+
+ form.elements[element.id] = element;
+ root.data.children.push(element.id);
+ }
+ }
+ }
+
+ // Drop node-field elements that point at nodes which did not survive parsing.
+ for (const element of Object.values(form.elements)) {
+ if (element.type !== 'node-field' || nodeIds.has(element.data.fieldIdentifier.nodeId)) {
+ continue;
+ }
+
+ delete form.elements[element.id];
+
+ const parent = element.parentId ? form.elements[element.parentId] : undefined;
+
+ if (parent?.type === 'container') {
+ parent.data.children = parent.data.children.filter((childId) => childId !== element.id);
+ }
+
+ warnings.push('Removed a form field that referenced a missing node.');
+ }
+
+ return form;
+};
+
+export const parseWorkflowJson = (raw: unknown): ParsedWorkflow => {
+ const parsed = zWorkflowJson.safeParse(raw);
+
+ if (!parsed.success) {
+ throw new Error('This file is not a recognizable InvokeAI workflow.');
+ }
+
+ const warnings: string[] = [];
+ const nodes: WorkflowNode[] = [];
+ const connectorIds = new Set<string>();
+
+ for (const rawNode of parsed.data.nodes) {
+ const nodeResult = zAnyNode.safeParse(rawNode);
+
+ if (!nodeResult.success) {
+ warnings.push('Skipped an unrecognized node.');
+ continue;
+ }
+
+ const node = nodeResult.data;
+
+ if (node.type === 'connector') {
+ connectorIds.add(node.id);
+ continue;
+ }
+
+ if (node.type === 'notes') {
+ nodes.push({
+ data: { label: node.data.label, notes: node.data.notes },
+ id: node.id,
+ position: node.position,
+ type: 'notes',
+ });
+ continue;
+ }
+
+ if (node.type === 'current_image') {
+ nodes.push({
+ data: { label: node.data.label },
+ id: node.id,
+ position: node.position,
+ type: 'current_image',
+ });
+ continue;
+ }
+
+ const inputs: Record<string, WorkflowFieldInstance> = {};
+
+ for (const [name, instance] of Object.entries(node.data.inputs)) {
+ inputs[name] = {
+ description: instance.description,
+ label: instance.label,
+ name: instance.name || name,
+ value: instance.value,
+ };
+ }
+
+ nodes.push({
+ data: {
+ inputs,
+ isIntermediate: node.data.isIntermediate,
+ isOpen: node.data.isOpen,
+ label: node.data.label,
+ nodePack: node.data.nodePack,
+ notes: node.data.notes,
+ type: node.data.type,
+ useCache: node.data.useCache,
+ version: node.data.version,
+ },
+ id: node.id,
+ position: node.position,
+ type: 'invocation',
+ });
+ }
+
+ if (connectorIds.size > 0) {
+ warnings.push(`Flattened ${connectorIds.size} connector node(s); connectors are not part of this editor.`);
+ }
+
+ const rawEdges = parsed.data.edges.flatMap((rawEdge) => {
+ const edgeResult = zDefaultEdge.safeParse(rawEdge);
+
+ return edgeResult.success ? [edgeResult.data] : [];
+ });
+ const { dropped, resolved } = resolveConnectorEdges(rawEdges, connectorIds);
+
+ if (dropped > 0) {
+ warnings.push(`Dropped ${dropped} connection(s) that could not be resolved through connectors.`);
+ }
+
+ const nodeIds = new Set(nodes.map((node) => node.id));
+ const edges: WorkflowEdge[] = [];
+
+ for (const edge of resolved) {
+ if (!nodeIds.has(edge.source) || !nodeIds.has(edge.target)) {
+ warnings.push('Dropped a connection that referenced a missing node.');
+ continue;
+ }
+
+ edges.push({
+ id: edge.id || createWorkflowId('edge'),
+ source: edge.source,
+ sourceHandle: edge.sourceHandle,
+ target: edge.target,
+ targetHandle: edge.targetHandle,
+ type: 'default',
+ });
+ }
+
+ const document: ProjectGraphState = {
+ author: parsed.data.author,
+ contact: parsed.data.contact,
+ description: parsed.data.description,
+ edges,
+ form: parseForm(parsed.data.form, parsed.data.exposedFields, nodeIds, warnings),
+ id: createWorkflowId('project-graph'),
+ libraryWorkflowId: parsed.data.id,
+ name: parsed.data.name,
+ nodes,
+ notes: parsed.data.notes,
+ tags: parsed.data.tags,
+ updatedAt: new Date().toISOString(),
+ version: 2,
+ workflowVersion: parsed.data.version,
+ };
+
+ return { document, warnings };
+};
+
+/** Serializes the document to legacy WorkflowV3 JSON (loadable by the v6 editor and the library backend). */
+export const serializeWorkflowJson = (document: ProjectGraphState): Record<string, unknown> => ({
+ author: document.author,
+ contact: document.contact,
+ description: document.description,
+ edges: document.edges.map((edge) => ({ ...edge })),
+ exposedFields: [],
+ form: {
+ elements: structuredClone(document.form.elements),
+ rootElementId: document.form.rootElementId,
+ },
+ ...(document.libraryWorkflowId ? { id: document.libraryWorkflowId } : {}),
+ meta: { category: 'user', version: '3.0.0' },
+ name: document.name,
+ nodes: document.nodes.map((node) =>
+ node.type === 'notes' || node.type === 'current_image'
+ ? {
+ data: { ...node.data, id: node.id, isOpen: true },
+ id: node.id,
+ position: { ...node.position },
+ type: node.type,
+ }
+ : {
+ data: { ...structuredClone(node.data), id: node.id },
+ id: node.id,
+ position: { ...node.position },
+ type: node.type,
+ }
+ ),
+ notes: document.notes,
+ tags: document.tags,
+ version: document.workflowVersion,
+});