Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
perf(workflows): optimize large workflow rendering
joshistoastdc87fe9d62ee
diff --git a/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts b/invokeai/frontend/webv2/src/workbench/performanceMarks.test.tsnew file mode 100644index 0000000000..71dd5b595b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts@@ -0,0 +1,55 @@+/* oxlint-disable no-console */++import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ getWorkbenchPerfEntries,+ markWorkbenchPerf,+ measureWorkbenchPerf,+ timeWorkbenchPerf,+} from './performanceMarks';++const storage = new Map<string, string>();++vi.stubGlobal('window', {+ localStorage: {+ getItem: (key: string): string | null => storage.get(key) ?? null,+ },+});++beforeEach(() => {+ storage.clear();+ window.__invokeaiWorkbenchPerf = [];+ vi.spyOn(performance, 'mark').mockImplementation((name: string) => ({ name }) as PerformanceMark);+ vi.spyOn(performance, 'measure').mockImplementation(+ (name: string) => ({ duration: 12.34, name }) as PerformanceMeasure+ );+ vi.spyOn(console, 'info').mockImplementation(() => undefined);+});++describe('performanceMarks', () => {+ it('does nothing when workbench perf logging is not enabled', () => {+ markWorkbenchPerf('workflow:test');+ measureWorkbenchPerf('workflow:measure', 'workflow:test');++ expect(performance.mark).not.toHaveBeenCalled();+ expect(performance.measure).not.toHaveBeenCalled();+ expect(console.info).not.toHaveBeenCalled();+ expect(getWorkbenchPerfEntries()).toEqual([]);+ });++ it('marks and measures when enabled', () => {+ storage.set('invokeai:webv2:perf', '1');++ const result = timeWorkbenchPerf('workflow:build', () => 42);++ expect(result).toBe(42);+ expect(performance.mark).toHaveBeenCalledWith('workflow:build:start');+ expect(performance.mark).toHaveBeenCalledWith('workflow:build:end');+ expect(performance.measure).toHaveBeenCalledWith('workflow:build', 'workflow:build:start', 'workflow:build:end');+ expect(console.info).toHaveBeenCalledWith('[workbench perf] workflow:build: 12.3ms');+ expect(getWorkbenchPerfEntries()).toEqual([+ { duration: 12.34, name: 'workflow:build', timestamp: expect.any(Number) },+ ]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/performanceMarks.ts b/invokeai/frontend/webv2/src/workbench/performanceMarks.tsnew file mode 100644index 0000000000..f220459e37--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/performanceMarks.ts@@ -0,0 +1,99 @@+/* oxlint-disable no-console */++const PERF_STORAGE_KEY = 'invokeai:webv2:perf';+const MAX_ENTRIES = 200;++interface WorkbenchPerfEntry {+ duration: number;+ name: string;+ timestamp: number;+}++declare global {+ interface Window {+ __invokeaiWorkbenchPerf?: WorkbenchPerfEntry[];+ }+}++const hasPerformanceApi = (): boolean => typeof performance !== 'undefined' && typeof performance.mark === 'function';++const isPerfEnabled = (): boolean => {+ if (!hasPerformanceApi()) {+ return false;+ }++ try {+ return typeof window !== 'undefined' && window.localStorage.getItem(PERF_STORAGE_KEY) === '1';+ } catch {+ return false;+ }+};++export const markWorkbenchPerf = (name: string): void => {+ if (!isPerfEnabled()) {+ return;+ }++ performance.mark(name);+};++const recordWorkbenchPerfEntry = (entry: WorkbenchPerfEntry): void => {+ if (typeof window === 'undefined') {+ return;+ }++ // TODO: Move benchmark collection out of a global window buffer when a real diagnostics surface exists.+ const entries = window.__invokeaiWorkbenchPerf ?? [];++ entries.push(entry);++ if (entries.length > MAX_ENTRIES) {+ entries.splice(0, entries.length - MAX_ENTRIES);+ }++ window.__invokeaiWorkbenchPerf = entries;+};++export const measureWorkbenchPerf = (name: string, startMark: string, endMark?: string): void => {+ if (!isPerfEnabled()) {+ return;+ }++ try {+ const measure = endMark ? performance.measure(name, startMark, endMark) : performance.measure(name, startMark);+ const entry = { duration: measure.duration, name: measure.name, timestamp: performance.now() };++ recordWorkbenchPerfEntry(entry);++ // TODO: Replace console logging with a dedicated benchmark sink/export UI before keeping this long-term.+ console.info(`[workbench perf] ${entry.name}: ${entry.duration.toFixed(1)}ms`);+ } catch {+ // A missing mark should never affect workflow behavior.+ }+};++export const getWorkbenchPerfEntries = (): WorkbenchPerfEntry[] => {+ if (typeof window === 'undefined') {+ return [];+ }++ return [...(window.__invokeaiWorkbenchPerf ?? [])];+};++export const timeWorkbenchPerf = <T>(name: string, callback: () => T): T => {+ if (!isPerfEnabled()) {+ return callback();+ }++ const startMark = `${name}:start`;+ const endMark = `${name}:end`;++ markWorkbenchPerf(startMark);++ try {+ return callback();+ } finally {+ markWorkbenchPerf(endMark);+ measureWorkbenchPerf(name, startMark, endMark);+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsxindex 6c37a9584a..f3eb18f77e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx@@ -3,18 +3,15 @@ import type {FieldInputTemplate,FieldOutputTemplate,FieldType,- InvocationTemplate,WorkflowInvocationNode,} from '@workbench/workflows/types';import { Box, Checkbox, Field, Flex, HStack, Icon, IconButton, Image, Input, Stack, Text } from '@chakra-ui/react';-import { useAuthSession } from '@workbench/auth/session';import { useNodeExecutionState, type NodeExecutionState } from '@workbench/backend/nodeExecutionStore';import { Tooltip } from '@workbench/components/ui';import { FieldDescriptionPopover } from '@workbench/widgets/workflow/fields/FieldDescriptionPopover';import { WorkflowFieldInput } from '@workbench/widgets/workflow/fields/WorkflowFieldInput';import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { isExecutableInvocationType } from '@workbench/workflows/buildGraph';import {cloneWorkflowFieldDefault,getFieldTypeColor,@@ -25,7 +22,6 @@ import {isWorkflowFieldValueDefault,isModelFieldType,} from '@workbench/workflows/fields';-import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';import {ChevronDownIcon,@@ -38,7 +34,7 @@ import {} from 'lucide-react';import { memo, useState, type ChangeEvent, type KeyboardEvent } from 'react';-import type { InvocationFlowNode as InvocationFlowNodeType } from './flowAdapters';+import type { InvocationFlowNode as InvocationFlowNodeType, InvocationNodeTemplateView } from './flowAdapters';import { getHandleTypeTooltip } from './handleTooltip';import { getWorkflowNodeChromeProps } from './nodeChrome';@@ -68,9 +64,6 @@ const handleStyle = (type: FieldType, side: HandleSide): React.CSSProperties =>};};-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);@@ -144,11 +137,9 @@ const NodeProgressStrip = ({ execution }: { execution: NodeExecutionState | null);};-const NodeTitle = ({ node }: { node: WorkflowInvocationNode }) => {+const NodeTitle = ({ node, title }: { node: WorkflowInvocationNode; title: string }) => {const dispatch = useWorkbenchDispatch();- const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const [draftLabel, setDraftLabel] = useState<string | null>(null);- const title = node.data.label || templates[node.data.type]?.title || node.data.type;if (draftLabel !== null) {return (@@ -238,10 +229,13 @@ const OutputFieldTooltip = ({ template }: { template: FieldOutputTemplate }) =></Stack>);-const hasImageOutput = (template: InvocationTemplate): boolean =>- template.type !== 'image' && Object.values(template.outputs).some((output) => output.type.name === 'ImageField');--const NodeInfoTooltipContent = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate }) => {+const NodeInfoTooltipContent = ({+ node,+ template,+}: {+ node: WorkflowInvocationNode;+ template: InvocationNodeTemplateView['template'];+}) => {const title = node.data.label ? `${node.data.label} (${template.title})` : template.title;const nodePack = node.data.nodePack || template.nodePack;@@ -259,7 +253,13 @@ const NodeInfoTooltipContent = ({ node, template }: { node: WorkflowInvocationNo);};-const NodeInfoButton = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate }) => (+const NodeInfoButton = ({+ node,+ template,+}: {+ node: WorkflowInvocationNode;+ template: InvocationNodeTemplateView['template'];+}) => (<Tooltipcontent={<NodeInfoTooltipContent node={node} template={template} />}positioning={{ placement: 'top-end' }}@@ -276,14 +276,8 @@ const NodeInfoButton = ({ node, template }: { node: WorkflowInvocationNode; temp</Tooltip>);-const NodeFooter = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate }) => {+const NodeFooter = ({ canUseCache, node }: { canUseCache: boolean; node: WorkflowInvocationNode }) => {const dispatch = useWorkbenchDispatch();- const session = useAuthSession();- const canUseCache = !session.multiuserEnabled || session.user?.is_admin === true;-- if (!isExecutableInvocationType(template.type) || !hasImageOutput(template)) {- return null;- }return (<Flex@@ -575,15 +569,100 @@ const HiddenHandles = ({</Box>);-const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {+const CompactHiddenHandles = ({+ connectedSourceHandles,+ connectedTargetHandles,+ inputTemplates,+ outputTemplates,+}: {+ connectedSourceHandles: string[];+ connectedTargetHandles: string[];+ inputTemplates: FieldInputTemplate[];+ outputTemplates: FieldOutputTemplate[];+}) => {+ const connectedSources = new Set(connectedSourceHandles);+ const connectedTargets = new Set(connectedTargetHandles);++ return (+ <HiddenHandles+ inputTemplates={inputTemplates.filter((inputTemplate) => connectedTargets.has(inputTemplate.name))}+ outputTemplates={outputTemplates.filter((outputTemplate) => connectedSources.has(outputTemplate.name))}+ />+ );+};++const CompactNodeBody = ({ inputCount, outputCount }: { inputCount: number; outputCount: number }) => (+ <Flex+ align="center"+ bg="bg.muted"+ borderBottomRadius="lg"+ borderTopWidth="1px"+ borderColor="border.subtle"+ color="fg.subtle"+ fontSize="2xs"+ gap="2"+ px="3"+ py="2"+ >+ <Text>+ {inputCount} input{inputCount === 1 ? '' : 's'}+ </Text>+ <Text>·</Text>+ <Text>+ {outputCount} output{outputCount === 1 ? '' : 's'}+ </Text>+ <Text ms="auto">Select for fields</Text>+ </Flex>+);++const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {+ const node = data.documentNode;+ const templateView = data.template;+ const inputTemplates = templateView?.inputTemplates ?? [];+ const outputTemplates = templateView?.outputTemplates ?? [];+ const title = node.data.label || templateView?.template.title || node.data.type;++ return (+ <NodeShell isMissing={!templateView} selected={selected ?? false}>+ <Flex+ align="center"+ bg="bg.subtle"+ borderBottomWidth="1px"+ borderColor="border.subtle"+ borderTopRadius="lg"+ gap="1"+ px="3"+ py="2"+ >+ <Text fontSize="sm" fontWeight="700" minW="0" title={title} truncate>+ {title}+ </Text>+ </Flex>+ {templateView ? (+ <CompactNodeBody inputCount={inputTemplates.length} outputCount={outputTemplates.length} />+ ) : (+ <Text bg="bg.muted" borderBottomRadius="lg" color="fg.subtle" fontSize="2xs" px="3" py="2">+ Unknown node type. Select for details.+ </Text>+ )}+ <CompactHiddenHandles+ connectedSourceHandles={data.connectedSourceHandles}+ connectedTargetHandles={data.connectedTargetHandles}+ inputTemplates={inputTemplates}+ outputTemplates={outputTemplates}+ />+ </NodeShell>+ );+};++const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {const dispatch = useWorkbenchDispatch();- const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const isZoomedOut = useIsZoomedOut();const node = data.documentNode;- const template = templates[node.data.type];+ const templateView = data.template;const execution = useNodeExecutionState(node.id);- if (!template) {+ if (!templateView) {return (<NodeShell isMissing selected={selected ?? false}><HStack gap="1.5" p="3">@@ -599,14 +678,16 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlo);}+ const template = templateView.template;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 inputTemplates = templateView.inputTemplates;+ const outputTemplates = templateView.outputTemplates;const isOpen = node.data.isOpen;const isRunning = execution?.status === 'running';const isMissingRequiredInput = hasMissingRequiredInputs(node, Object.values(template.inputs), connectedFieldNames);- const withFooter = !isZoomedOut && isExecutableInvocationType(template.type) && hasImageOutput(template);+ const isCompact = data.isCompact && !selected;+ const withFooter = !isZoomedOut && templateView.isExecutable && templateView.hasImageOutput;const withOutputPreview = Boolean(execution?.outputImageUrl);return (@@ -643,14 +724,19 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlo</Text>) : (<>- <NodeTitle node={node} />+ <NodeTitle node={node} title={node.data.label || template.title} /><Box flex="1" /><NodeInfoButton node={node} template={template} /></>)}</Flex><NodeProgressStrip execution={execution} />- {isOpen ? (+ {isOpen && isCompact ? (+ <>+ <CompactNodeBody inputCount={inputTemplates.length} outputCount={outputTemplates.length} />+ <HiddenHandles inputTemplates={inputTemplates} outputTemplates={outputTemplates} />+ </>+ ) : isOpen ? (<Box bg="bg.muted" borderBottomRadius={withFooter || withOutputPreview ? 'none' : 'lg'} py="1">{outputTemplates.map((outputTemplate) => (<OutputFieldRow key={outputTemplate.name} isSkeleton={isZoomedOut} template={outputTemplate} />@@ -686,9 +772,16 @@ const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlo)}</Box>) : null}- {isOpen && withFooter ? <NodeFooter node={node} template={template} /> : null}+ {isOpen && withFooter ? <NodeFooter canUseCache={data.canUseCache} node={node} /> : null}</NodeShell>);};+const InvocationFlowNodeComponent = (props: NodeProps<InvocationFlowNodeType>) =>+ props.data.isCompact && !props.selected ? (+ <CompactInvocationNode {...props} />+ ) : (+ <ExpandedInvocationNode {...props} />+ );+export const InvocationFlowNode = memo(InvocationFlowNodeComponent);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.test.tsnew file mode 100644index 0000000000..855664d421--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';++import { WORKFLOW_INITIAL_RENDER_NODE_COUNT } from './performanceConstants';+import { getInitialRenderFlowModel } from './WorkflowEditorView';++const createNode = (id: string, x: number): WorkflowFlowNode => ({+ data: { documentNode: { data: { label: '', notes: '' }, id, position: { x, y: 0 }, type: 'notes' } },+ id,+ position: { x, y: 0 },+ type: 'notes',+});++const createEdge = (id: string, source: string, target: string): WorkflowFlowEdge => ({+ data: {+ fieldTypeLabel: 'Unknown',+ pathType: 'default',+ stroke: 'var(--xy-edge-stroke)',+ strokeWidth: 2,+ tooltip: 'Unknown field type',+ },+ id,+ source,+ sourceHandle: 'value',+ target,+ targetHandle: 'value',+ type: 'default',+});++describe('getInitialRenderFlowModel', () => {+ it('keeps the nearest initial nodes and filters edges to that window', () => {+ const nodes = Array.from({ length: WORKFLOW_INITIAL_RENDER_NODE_COUNT + 2 }, (_, index) =>+ createNode(`node-${index}`, index)+ );+ const model = {+ nodes,+ edges: [+ createEdge('inside', 'node-0', 'node-1'),+ createEdge('outside', 'node-0', `node-${WORKFLOW_INITIAL_RENDER_NODE_COUNT + 1}`),+ ],+ };++ const windowed = getInitialRenderFlowModel(model, { x: 0, y: 0, zoom: 1 });++ expect(windowed.nodes).toHaveLength(WORKFLOW_INITIAL_RENDER_NODE_COUNT);+ expect(windowed.nodes.map((node) => node.id)).toContain('node-0');+ expect(windowed.nodes.map((node) => node.id)).not.toContain(`node-${WORKFLOW_INITIAL_RENDER_NODE_COUNT + 1}`);+ expect(windowed.edges.map((edge) => edge.id)).toEqual(['inside']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsxindex 9c2ce7f847..f869c8defc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx@@ -1,16 +1,19 @@/* eslint-disable react/react-compiler */import type { WidgetRuntimeApi } from '@workbench/types';-import type { XYPosition } from '@workbench/workflows/types';+import type { ProjectGraphState, XYPosition } from '@workbench/workflows/types';-import { Box, Flex, Stack, Text } from '@chakra-ui/react';+import { Box, Flex, HStack, Spinner, Stack, Text } from '@chakra-ui/react';+import { useAuthSession } from '@workbench/auth/session';import { FlowMiniMap, flowThemeCss, getFlowColorMode } from '@workbench/graph-preview';import '@xyflow/react/dist/style.css';+import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from '@workbench/performanceMarks';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { useNotify } from '@workbench/useNotify';import { setAddNodeOpen } from '@workbench/widgets/workflow/workflowUiStore';import { shallowEqual, useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { getProjectGraphReadiness } from '@workbench/workflows/buildGraph';import { buildConnectorNode, createWorkflowId } from '@workbench/workflows/document';+import { createWorkflowGraphIndex } from '@workbench/workflows/graphIndex';import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@workbench/workflows/templates';import {getWorkflowSourceFieldType,@@ -33,6 +36,7 @@ import {type NodeChange,type NodeTypes,type OnConnectEnd,+ type Viewport,} from '@xyflow/react';import {useCallback,@@ -42,6 +46,7 @@ import {useMemo,useRef,useState,+ startTransition,type MouseEvent as ReactMouseEvent,} from 'react';@@ -65,6 +70,11 @@ import {import { InvocationFlowNode } from './InvocationFlowNode';import { NodeContextMenu, type WorkflowContextMenuState } from './NodeContextMenu';import { NotesFlowNode } from './NotesFlowNode';+import {+ isLargeWorkflowGraph,+ WORKFLOW_INITIAL_RENDER_NODE_COUNT,+ WORKFLOW_MINIMAP_DELAY_MS,+} from './performanceConstants';import {clearNodeSelectionRequest,reportNodeHover,@@ -75,6 +85,7 @@ import { useEraser } from './useEraser';import { useLasso } from './useLasso';import { useModifierHeld } from './useModifierHeld';import { WorkflowEdge } from './WorkflowEdge';+import { getWorkflowViewport, getWorkflowViewportKey, setWorkflowViewport } from './workflowViewportStore';const nodeTypes: NodeTypes = {connector: ConnectorFlowNode,@@ -100,6 +111,50 @@ const SNAP_GRID: [number, number] = [24, 24];const DELETE_KEY_CODES = ['Backspace', 'Delete'];const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 2 } };+const DEFAULT_VIEWPORT = { x: 0, y: 0, zoom: 1 } as const;++interface WorkflowFlowModel {+ edges: WorkflowFlowEdge[];+ nodes: WorkflowFlowNode[];+}++const EMPTY_FLOW_EDGES: WorkflowFlowEdge[] = [];+const EMPTY_FLOW_NODES: WorkflowFlowNode[] = [];++const buildWorkflowFlowModel = ({+ document,+ edgeType,+ invocationTemplates,+ previousEdges = [],+ previousNodes = [],+ reduceMotion,+ selectedNodeIds = new Set<string>(),+ isCompact = false,+ canUseCache = false,+}: {+ canUseCache?: boolean;+ document: ProjectGraphState;+ edgeType: FlowEdgeType;+ isCompact?: boolean;+ invocationTemplates?: Parameters<typeof toFlowNodes>[2];+ previousEdges?: WorkflowFlowEdge[];+ previousNodes?: WorkflowFlowNode[];+ reduceMotion: boolean;+ selectedNodeIds?: Set<string>;+}): WorkflowFlowModel => {+ const index = timeWorkbenchPerf('workflow:create-graph-index', () =>+ createWorkflowGraphIndex(document.nodes, document.edges)+ );++ return timeWorkbenchPerf('workflow:build-flow-model', () => ({+ edges: timeWorkbenchPerf('workflow:to-flow-edges', () =>+ toFlowEdges(document, previousEdges, edgeType, selectedNodeIds, invocationTemplates, reduceMotion, index)+ ),+ nodes: timeWorkbenchPerf('workflow:to-flow-nodes', () =>+ toFlowNodes(document, previousNodes, invocationTemplates, index, isCompact, canUseCache)+ ),+ }));+};const getEventClientPosition = (event: MouseEvent | TouchEvent): { x: number; y: number } | null => {if (event instanceof MouseEvent) {@@ -111,11 +166,57 @@ const getEventClientPosition = (event: MouseEvent | TouchEvent): { x: number; y:return touch ? { x: touch.clientX, y: touch.clientY } : null;};+const WorkflowEditorPreparingState = ({ edgeCount, nodeCount }: { edgeCount: number; nodeCount: number }) => (+ <Flex align="center" bg="bg.inset" h="full" justify="center" p="6" w="full">+ <Stack align="center" gap="3" textAlign="center">+ <HStack color="fg.muted" gap="2">+ <Spinner size="sm" />+ <Text fontSize="sm" fontWeight="700">+ Preparing workflow graph+ </Text>+ </HStack>+ <Text color="fg.subtle" fontSize="xs">+ Loading {nodeCount.toLocaleString()} node{nodeCount === 1 ? '' : 's'} and {edgeCount.toLocaleString()} edge+ {edgeCount === 1 ? '' : 's'}.+ </Text>+ </Stack>+ </Flex>+);+const getSelectedNodeIdSet = (nodes: WorkflowFlowNode[]): Set<string> =>new Set(nodes.filter((node) => node.selected).map((node) => node.id));+const getNodeDistanceFromViewportOrigin = (node: WorkflowFlowNode, viewport: Viewport): number => {+ const zoom = viewport.zoom || 1;+ const originX = -viewport.x / zoom;+ const originY = -viewport.y / zoom;+ const dx = node.position.x - originX;+ const dy = node.position.y - originY;++ return dx * dx + dy * dy;+};++export const getInitialRenderFlowModel = (model: WorkflowFlowModel, viewport: Viewport): WorkflowFlowModel => {+ if (model.nodes.length <= WORKFLOW_INITIAL_RENDER_NODE_COUNT) {+ return model;+ }++ const nodes = [...model.nodes]+ .sort(+ (left, right) =>+ getNodeDistanceFromViewportOrigin(left, viewport) - getNodeDistanceFromViewportOrigin(right, viewport)+ )+ .slice(0, WORKFLOW_INITIAL_RENDER_NODE_COUNT);+ const nodeIds = new Set(nodes.map((node) => node.id));+ const edges = model.edges.filter((edge) => nodeIds.has(edge.source) && nodeIds.has(edge.target));++ return { edges, nodes };+};+const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const projectGraph = useActiveProjectSelector((project) => project.projectGraph);+ const projectId = useActiveProjectSelector((project) => project.id);+ const session = useAuthSession();const dispatch = useWorkbenchDispatch();const notify = useNotify();const {@@ -139,33 +240,81 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const invocationTemplates = templatesStatus === 'loaded' ? templates : undefined;+ const canUseCache = !session.multiuserEnabled || session.user?.is_admin === true;const edgeType: FlowEdgeType = workflowEdgeStyle === 'square' ? 'step' : 'default';- const [flowNodes, setFlowNodes] = useState<WorkflowFlowNode[]>(() =>- toFlowNodes(projectGraph, [], invocationTemplates)+ const isLargeGraph = isLargeWorkflowGraph({+ edgeCount: projectGraph.edges.length,+ nodeCount: projectGraph.nodes.length,+ });+ const viewportKey = useMemo(+ () => getWorkflowViewportKey(projectId, runtime.instanceId),+ [projectId, runtime.instanceId]);- const [flowEdges, setFlowEdges] = useState<WorkflowFlowEdge[]>(() =>- toFlowEdges(projectGraph, [], edgeType, new Set<string>(), invocationTemplates, reduceMotion)+ const defaultViewport = useMemo(() => getWorkflowViewport(viewportKey) ?? DEFAULT_VIEWPORT, [viewportKey]);+ const [flowModel, setFlowModel] = useState<WorkflowFlowModel | null>(() =>+ isLargeGraph+ ? null+ : buildWorkflowFlowModel({+ canUseCache,+ document: projectGraph,+ edgeType,+ invocationTemplates,+ isCompact: isLargeGraph,+ reduceMotion,+ }));+ const flowNodes = flowModel?.nodes ?? EMPTY_FLOW_NODES;+ const flowEdges = flowModel?.edges ?? EMPTY_FLOW_EDGES;+ const isPreparing = flowModel === null;+ const shouldDeferInitialBuild = isLargeGraph && flowModel === null;const [flowInstance, setFlowInstance] = useState<WorkflowFlowInstance | null>(null);+ const [isFullGraphMounted, setIsFullGraphMounted] = useState(!isLargeGraph);const [tool, setTool] = useState<EditorTool>('pan');const [nodeOpacity, setNodeOpacity] = useState(1);+ const [isMinimapReady, setIsMinimapReady] = useState(!isLargeGraph);const [contextMenu, setContextMenu] = useState<WorkflowContextMenuState | null>(null);const selectedNodeIds = workflowSelectionStore.useSelector((snapshot) => snapshot.selectedNodeIds);const selectionRequest = workflowSelectionStore.useSelector((snapshot) => snapshot.selectionRequest);const isSnapHeld = useModifierHeld('Control');const hasClipboardNodes = useHasClipboardNodes();const backgroundId = useId().replace(/:/g, '');+ const perfMountMarkRef = useRef(`workflow:${runtime.instanceId}:editor-mounted`);+ const perfReadyMarkRef = useRef(`workflow:${runtime.instanceId}:editor-ready`);+ const hasScheduledFullGraphMountRef = useRef(false);/** Node ids to select once the next document-driven rebuild lands (fresh paste/duplicate results). */const pendingSelectionRef = useRef<string[] | null>(null);+ const lastBuiltModelRef = useRef<{+ edgeType: FlowEdgeType;+ invocationTemplates: typeof invocationTemplates;+ projectGraph: ProjectGraphState;+ reduceMotion: boolean;+ selectedNodeIds: string[];+ } | null>(null);const selectNodes = useCallback((nodeIds: string[]) => {const selectedNodeIdSet = new Set(nodeIds);- setFlowNodes((current) => withNodeSelection(current, selectedNodeIdSet));- setFlowEdges((current) =>- toFlowEdges(projectGraph, current, edgeType, selectedNodeIdSet, invocationTemplates, reduceMotion)- );+ setFlowModel((current) => {+ if (!current) {+ return current;+ }++ const index = createWorkflowGraphIndex(projectGraph.nodes, projectGraph.edges);++ return {+ edges: toFlowEdges(+ projectGraph,+ current.edges,+ edgeType,+ selectedNodeIdSet,+ invocationTemplates,+ reduceMotion,+ index+ ),+ nodes: withNodeSelection(current.nodes, selectedNodeIdSet),+ };+ });reportNodeSelection(nodeIds);},[edgeType, invocationTemplates, projectGraph, reduceMotion]@@ -206,6 +355,71 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {onErase: eraseElements,});const pointerToolHandlers = tool === 'lasso' ? lassoHandlers : tool === 'eraser' ? eraserHandlers : {};+ const renderedFlowModel = useMemo(+ () =>+ flowModel && isLargeGraph && !isFullGraphMounted+ ? getInitialRenderFlowModel(flowModel, defaultViewport)+ : flowModel,+ [defaultViewport, flowModel, isFullGraphMounted, isLargeGraph]+ );+ const renderedFlowNodes = renderedFlowModel?.nodes ?? EMPTY_FLOW_NODES;+ const renderedFlowEdges = renderedFlowModel?.edges ?? EMPTY_FLOW_EDGES;++ useEffect(() => {+ hasScheduledFullGraphMountRef.current = false;+ setIsFullGraphMounted(!isLargeGraph);+ }, [isLargeGraph, projectId]);++ useEffect(() => {+ markWorkbenchPerf(perfMountMarkRef.current);+ }, []);++ useEffect(() => {+ if (isPreparing) {+ return;+ }++ markWorkbenchPerf(perfReadyMarkRef.current);+ measureWorkbenchPerf('workflow:editor-mounted-to-ready', perfMountMarkRef.current, perfReadyMarkRef.current);+ }, [isPreparing]);++ useEffect(() => {+ if (!isFullGraphMounted || !isLargeGraph) {+ return;+ }++ markWorkbenchPerf('workflow:full-graph-mounted');+ measureWorkbenchPerf(+ 'workflow:full-graph-expand',+ 'workflow:full-graph-expand-start',+ 'workflow:full-graph-mounted'+ );+ }, [isFullGraphMounted, isLargeGraph]);++ useEffect(() => {+ if (!workflowShowMinimap) {+ setIsMinimapReady(false);+ return undefined;+ }++ if (!isLargeGraph) {+ setIsMinimapReady(true);+ return undefined;+ }++ setIsMinimapReady(false);++ if (isPreparing) {+ return undefined;+ }++ const timeoutId = window.setTimeout(() => {+ markWorkbenchPerf('workflow:minimap-ready');+ setIsMinimapReady(true);+ }, WORKFLOW_MINIMAP_DELAY_MS);++ return () => window.clearTimeout(timeoutId);+ }, [isLargeGraph, isPreparing, workflowShowMinimap]);useEffect(() => {const pendingSelection = pendingSelectionRef.current;@@ -213,20 +427,75 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {pendingSelectionRef.current = null;const nextSelectedNodeIds = pendingSelection ?? selectedNodeIds;const nextSelectedNodeIdSet = new Set(nextSelectedNodeIds);+ let frameId: number | null = null;++ const lastBuiltModel = lastBuiltModelRef.current;++ if (+ pendingSelection === null &&+ !shouldDeferInitialBuild &&+ lastBuiltModel?.projectGraph === projectGraph &&+ lastBuiltModel.edgeType === edgeType &&+ lastBuiltModel.invocationTemplates === invocationTemplates &&+ lastBuiltModel.reduceMotion === reduceMotion &&+ lastBuiltModel.selectedNodeIds === nextSelectedNodeIds+ ) {+ return undefined;+ }- setFlowNodes((current) => {- const next = toFlowNodes(projectGraph, current, invocationTemplates);+ const updateModel = () => {+ lastBuiltModelRef.current = {+ edgeType,+ invocationTemplates,+ projectGraph,+ reduceMotion,+ selectedNodeIds: nextSelectedNodeIds,+ };++ startTransition(() => {+ setFlowModel((current) => {+ const next = buildWorkflowFlowModel({+ document: projectGraph,+ edgeType,+ canUseCache,+ isCompact: isLargeGraph,+ invocationTemplates,+ previousEdges: current?.edges,+ previousNodes: current?.nodes,+ reduceMotion,+ selectedNodeIds: nextSelectedNodeIdSet,+ });- return pendingSelection ? withNodeSelection(next, nextSelectedNodeIdSet) : next;- });- setFlowEdges((current) =>- toFlowEdges(projectGraph, current, edgeType, nextSelectedNodeIdSet, invocationTemplates, reduceMotion)- );+ return { ...next, nodes: withNodeSelection(next.nodes, nextSelectedNodeIdSet) };+ });+ });+ };++ if (shouldDeferInitialBuild) {+ frameId = window.requestAnimationFrame(updateModel);+ } else {+ updateModel();+ }if (pendingSelection) {reportNodeSelection(pendingSelection);}- }, [edgeType, invocationTemplates, projectGraph, reduceMotion, selectedNodeIds]);++ return () => {+ if (frameId !== null) {+ window.cancelAnimationFrame(frameId);+ }+ };+ }, [+ canUseCache,+ edgeType,+ invocationTemplates,+ isLargeGraph,+ projectGraph,+ reduceMotion,+ selectedNodeIds,+ shouldDeferInitialBuild,+ ]);// Expose the instance to the widget header's actions (outside this provider).useEffect(() => {@@ -419,7 +688,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}}- setFlowNodes((current) => applyNodeChanges(changes, current));+ setFlowModel((current) => (current ? { ...current, nodes: applyNodeChanges(changes, current.nodes) } : current));},[dispatch]);@@ -432,7 +701,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {dispatch({ action: { edgeIds: removedEdgeIds, type: 'removeEdges' }, type: 'applyProjectGraphAction' });}- setFlowEdges((current) => applyEdgeChanges(changes, current));+ setFlowModel((current) => (current ? { ...current, edges: applyEdgeChanges(changes, current.edges) } : current));},[dispatch]);@@ -630,12 +899,29 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {({ nodes }: { nodes: WorkflowFlowNode[] }) => {const nodeIds = nodes.map((node) => node.id);- setFlowEdges((current) =>- toFlowEdges(projectGraph, current, edgeType, getSelectedNodeIdSet(nodes), invocationTemplates)- );+ setFlowModel((current) => {+ if (!current) {+ return current;+ }++ const index = createWorkflowGraphIndex(projectGraph.nodes, projectGraph.edges);++ return {+ ...current,+ edges: toFlowEdges(+ projectGraph,+ current.edges,+ edgeType,+ getSelectedNodeIdSet(nodes),+ invocationTemplates,+ reduceMotion,+ index+ ),+ };+ });reportNodeSelection(nodeIds);},- [edgeType, invocationTemplates, projectGraph]+ [edgeType, invocationTemplates, projectGraph, reduceMotion]);const onNodeMouseEnter = useCallback((_: ReactMouseEvent, node: WorkflowFlowNode) => {@@ -647,6 +933,32 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {reportNodeHover(null);}}, []);+ const onMoveEnd = useCallback(+ (_: MouseEvent | TouchEvent | null, viewport: Viewport) => {+ setWorkflowViewport(viewportKey, viewport);+ },+ [viewportKey]+ );+ const onFlowInit = useCallback(+ (instance: WorkflowFlowInstance) => {+ const flowInitMark = 'workflow:react-flow-init';++ markWorkbenchPerf(flowInitMark);+ measureWorkbenchPerf('workflow:editor-ready-to-react-flow-init', perfReadyMarkRef.current, flowInitMark);+ measureWorkbenchPerf('workflow:editor-mounted-to-react-flow-init', perfMountMarkRef.current, flowInitMark);+ setFlowInstance(instance);++ if (isLargeGraph && !isFullGraphMounted && !hasScheduledFullGraphMountRef.current) {+ hasScheduledFullGraphMountRef.current = true;++ window.setTimeout(() => {+ markWorkbenchPerf('workflow:full-graph-expand-start');+ setIsFullGraphMounted(true);+ }, 0);+ }+ },+ [isFullGraphMounted, isLargeGraph]+ );const editorCss = useMemo(() => ({@@ -709,6 +1021,10 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {setContextMenu(null);}, [contextMenu, dispatch]);+ if (isPreparing) {+ return <WorkflowEditorPreparingState edgeCount={projectGraph.edges.length} nodeCount={projectGraph.nodes.length} />;+ }+return (<Boxbg="bg.inset"@@ -720,19 +1036,21 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {{...pointerToolHandlers}><ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>+ key={viewportKey}colorMode={getFlowColorMode(themeId)}connectionLineType={edgeType === 'step' ? ConnectionLineType.Step : ConnectionLineType.Bezier}defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}+ defaultViewport={defaultViewport}deleteKeyCode={DELETE_KEY_CODES}elevateEdgesOnSelect- edges={flowEdges}+ edges={renderedFlowEdges}edgeTypes={edgeTypes}- fitViewisValidConnection={isValidConnection}maxZoom={2}minZoom={0.1}- nodes={flowNodes}+ nodes={renderedFlowNodes}nodeTypes={nodeTypes}+ onlyRenderVisibleElements={isLargeGraph}panOnDrag={panOnDrag}proOptions={proOptions}selectionMode={SelectionMode.Partial}@@ -744,12 +1062,13 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {onConnectEnd={onConnectEnd}onEdgeClick={onEdgeClick}onEdgesChange={onEdgesChange}- onInit={setFlowInstance}+ onInit={onFlowInit}onNodeClick={onNodeClick}onNodeContextMenu={onNodeContextMenu}onNodeMouseEnter={onNodeMouseEnter}onNodeMouseLeave={onNodeMouseLeave}onNodesChange={onNodesChange}+ onMoveEnd={onMoveEnd}onPaneContextMenu={onPaneContextMenu}onSelectionChange={onSelectionChange}>@@ -767,7 +1086,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {onNodeOpacityChange={setNodeOpacity}onToolChange={setTool}/>- {workflowShowMinimap ? <FlowMiniMap /> : null}+ {workflowShowMinimap && isMinimapReady ? <FlowMiniMap /> : null}</ReactFlow>{lassoOverlay}{eraserOverlay}@@ -817,8 +1136,8 @@ const ReadinessBanner = () => {zIndex="1"><Stack gap="0.5">- {readiness.reasons.slice(0, 4).map((reason) => (- <Text key={reason} color="fg.muted" fontSize="2xs">+ {readiness.reasons.slice(0, 4).map((reason, index) => (+ <Text key={`${index}:${reason}`} color="fg.muted" fontSize="2xs">{reason}</Text>))}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.tsindex a3701597d6..3616f91ae3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.test.ts@@ -133,8 +133,19 @@ describe('flowAdapters identity preservation', () => {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]);+ // Node a lost its outgoing handle metadata, so it must also update.+ expect(second[0]).not.toBe(first[0]);+ expect(second[0]?.type === 'invocation' && second[0].data.connectedSourceHandles).toEqual([]);+ });++ it('precomputes connected source handles onto invocation node data', () => {+ const doc = createDoc();+ const nodes = toFlowNodes(doc);+ const source = nodes[0];+ const target = nodes[1];++ expect(source?.type === 'invocation' ? source.data.connectedSourceHandles : []).toEqual(['value']);+ expect(target?.type === 'invocation' ? target.data.connectedSourceHandles : []).toEqual([]);});it('precomputes exposed field names onto invocation node data', () => {@@ -160,6 +171,18 @@ describe('flowAdapters identity preservation', () => {expect(nodeB?.type === 'invocation' && nodeB.data.exposedFieldNames).toEqual(['a']);});+ it('marks invocation nodes compact for large workflow rendering', () => {+ const doc = createDoc();+ const normal = toFlowNodes(doc);+ const compact = toFlowNodes(doc, normal, undefined, undefined, true);+ const compactAgain = toFlowNodes(doc, compact, undefined, undefined, true);++ expect(normal[0]?.type === 'invocation' && normal[0].data.isCompact).toBe(false);+ expect(compact[0]?.type === 'invocation' && compact[0].data.isCompact).toBe(true);+ expect(compact[0]).not.toBe(normal[0]);+ expect(compactAgain[0]).toBe(compact[0]);+ });+it('precomputes resolved connector field types onto connector node data', () => {const fieldType = single('ImageField');const templates = createTemplates(fieldType);@@ -181,6 +204,20 @@ describe('flowAdapters identity preservation', () => {expect(toFlowNodes(doc, typed, templates)[1]).toBe(connector);});+ it('precomputes stable invocation template views onto invocation node data', () => {+ const doc = createDoc();+ const templates = createTemplates();+ const first = toFlowNodes(doc, [], templates);+ const second = toFlowNodes(doc, first, templates);+ const node = first[0];++ expect(node?.type === 'invocation' ? node.data.template?.template.title : null).toBe('Add');+ expect(node?.type === 'invocation' ? node.data.template?.inputTemplates.map((input) => input.name) : []).toEqual([+ 'a',+ ]);+ expect(second[0]).toBe(first[0]);+ });+it('does not mark a target as connected through an unresolved connector output', () => {const doc = createDoc({edges: [createEdge('e1', 'c', 'b', CONNECTOR_OUTPUT_HANDLE, 'a')],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.tsindex 71e0e1ed67..d6eb1f955f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/flowAdapters.ts@@ -1,5 +1,8 @@import type {FieldType,+ FieldInputTemplate,+ FieldOutputTemplate,+ InvocationTemplate,InvocationTemplates,ProjectGraphState,WorkflowConnectorNode,@@ -11,12 +14,14 @@ import type {import type { Edge as FlowEdge, Node as FlowNode } from '@xyflow/react';import type { CSSProperties } from 'react';+import { isExecutableInvocationType } from '@workbench/workflows/buildGraph';import {CONNECTOR_INPUT_HANDLE,CONNECTOR_OUTPUT_HANDLE,- getResolvedWorkflowEdges,+ getResolvedWorkflowEdgesIndexed,} from '@workbench/workflows/connectors';import { getFieldTypeColor, getFieldTypeLabel } from '@workbench/workflows/fields';+import { createWorkflowGraphIndex, type WorkflowGraphIndex } from '@workbench/workflows/graphIndex';import { getWorkflowSourceFieldType, getWorkflowTargetFieldType } from '@workbench/workflows/validation';/**@@ -34,11 +39,17 @@ import { getWorkflowSourceFieldType, getWorkflowTargetFieldType } from '@workbenexport type InvocationFlowNode = FlowNode<{+ canUseCache: boolean;documentNode: WorkflowInvocationNode;+ /** Source handle names with an outgoing edge. */+ connectedSourceHandles: string[];/** Target handle names with an incoming edge. */connectedTargetHandles: string[];/** Field names of this node exposed in the Linear UI form. */exposedFieldNames: string[];+ /** Large workflows render unselected nodes without field controls until selected. */+ isCompact: boolean;+ template: InvocationNodeTemplateView | null;},'invocation'>;@@ -57,10 +68,58 @@ const SELECTED_NODE_EDGE_STYLE: CSSProperties = { strokeWidth: 2 };const sameNames = (a: string[], b: string[]): boolean => a.length === b.length && a.every((name, i) => name === b[i]);-const getConnectedHandlesByNode = (document: ProjectGraphState): Map<string, string[]> => {+export interface InvocationNodeTemplateView {+ hasImageOutput: boolean;+ inputTemplates: FieldInputTemplate[];+ isExecutable: boolean;+ outputTemplates: FieldOutputTemplate[];+ template: InvocationTemplate;+}++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));++const hasImageOutput = (template: InvocationTemplate): boolean =>+ template.type !== 'image' && Object.values(template.outputs).some((output) => output.type.name === 'ImageField');++const createInvocationNodeTemplateView = (template: InvocationTemplate): InvocationNodeTemplateView => ({+ hasImageOutput: hasImageOutput(template),+ inputTemplates: sortByUiOrder(Object.values(template.inputs).filter((input) => !input.uiHidden)),+ isExecutable: isExecutableInvocationType(template.type),+ outputTemplates: Object.values(template.outputs),+ template,+});++const templateViewCache = new WeakMap<InvocationTemplates, Map<string, InvocationNodeTemplateView>>();++const getInvocationNodeTemplateViews = (+ templates: InvocationTemplates | undefined+): Map<string, InvocationNodeTemplateView> => {+ if (!templates) {+ return new Map();+ }++ const cached = templateViewCache.get(templates);++ if (cached) {+ return cached;+ }++ const views = new Map<string, InvocationNodeTemplateView>();++ for (const template of Object.values(templates)) {+ views.set(template.type, createInvocationNodeTemplateView(template));+ }++ templateViewCache.set(templates, views);++ return views;+};++const getConnectedHandlesByNode = (document: ProjectGraphState, index: WorkflowGraphIndex): Map<string, string[]> => {const byNode = new Map<string, string[]>();- for (const edge of getResolvedWorkflowEdges(document.nodes, document.edges)) {+ for (const edge of getResolvedWorkflowEdgesIndexed(document.edges, index)) {byNode.set(edge.target, [...(byNode.get(edge.target) ?? []), edge.targetHandle]);}@@ -71,6 +130,20 @@ const getConnectedHandlesByNode = (document: ProjectGraphState): Map<string, strreturn byNode;};+const getConnectedSourceHandlesByNode = (document: ProjectGraphState): Map<string, string[]> => {+ const byNode = new Map<string, string[]>();++ for (const edge of document.edges) {+ byNode.set(edge.source, [...(byNode.get(edge.source) ?? []), edge.sourceHandle]);+ }++ for (const handles of byNode.values()) {+ handles.sort();+ }++ return byNode;+};+const getExposedFieldsByNode = (document: ProjectGraphState): Map<string, string[]> => {const byNode = new Map<string, string[]>();@@ -92,23 +165,34 @@ const getExposedFieldsByNode = (document: ProjectGraphState): Map<string, stringexport const toFlowNodes = (document: ProjectGraphState,previousNodes: WorkflowFlowNode[] = [],- templates?: InvocationTemplates+ templates?: InvocationTemplates,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges),+ isCompact = false,+ canUseCache = false): WorkflowFlowNode[] => {const previousById = new Map(previousNodes.map((node) => [node.id, node]));- const connectedByNode = getConnectedHandlesByNode(document);+ const connectedByNode = getConnectedHandlesByNode(document, index);+ const connectedSourcesByNode = getConnectedSourceHandlesByNode(document);const exposedByNode = getExposedFieldsByNode(document);+ const templateViews = getInvocationNodeTemplateViews(templates);return document.nodes.map((documentNode): WorkflowFlowNode => {const previous = previousById.get(documentNode.id);const selected = previous?.selected ?? false;if (documentNode.type === 'invocation') {+ const connectedSourceHandles = connectedSourcesByNode.get(documentNode.id) ?? EMPTY_NAMES;const connectedTargetHandles = connectedByNode.get(documentNode.id) ?? EMPTY_NAMES;const exposedFieldNames = exposedByNode.get(documentNode.id) ?? EMPTY_NAMES;+ const template = templateViews.get(documentNode.data.type) ?? null;if (previous?.type === 'invocation' &&+ previous.data.canUseCache === canUseCache &&previous.data.documentNode === documentNode &&+ previous.data.isCompact === isCompact &&+ previous.data.template === template &&+ sameNames(previous.data.connectedSourceHandles, connectedSourceHandles) &&sameNames(previous.data.connectedTargetHandles, connectedTargetHandles) &&sameNames(previous.data.exposedFieldNames, exposedFieldNames)) {@@ -116,7 +200,15 @@ export const toFlowNodes = (}return {- data: { connectedTargetHandles, documentNode, exposedFieldNames },+ data: {+ canUseCache,+ connectedSourceHandles,+ connectedTargetHandles,+ documentNode,+ exposedFieldNames,+ isCompact,+ template,+ },id: documentNode.id,position: documentNode.position,selected,@@ -140,10 +232,10 @@ export const toFlowNodes = (if (documentNode.type === 'connector') {const inputFieldType = templates- ? (getWorkflowTargetFieldType(document, templates, documentNode.id, CONNECTOR_INPUT_HANDLE) ?? null)+ ? (getWorkflowTargetFieldType(document, templates, documentNode.id, CONNECTOR_INPUT_HANDLE, index) ?? null): null;const outputFieldType = templates- ? (getWorkflowSourceFieldType(document, templates, documentNode.id, CONNECTOR_OUTPUT_HANDLE) ?? null)+ ? (getWorkflowSourceFieldType(document, templates, documentNode.id, CONNECTOR_OUTPUT_HANDLE, index) ?? null): null;if (@@ -228,15 +320,16 @@ const UNKNOWN_EDGE_DATA = (pathType: FlowEdgeType): WorkflowEdgeData => ({const getWorkflowEdgeFieldType = (document: ProjectGraphState,templates: InvocationTemplates | undefined,- edge: WorkflowEdge+ edge: WorkflowEdge,+ index: WorkflowGraphIndex): FieldType | null => {if (!templates) {return null;}return (- getWorkflowSourceFieldType(document, templates, edge.source, edge.sourceHandle) ??- getWorkflowTargetFieldType(document, templates, edge.target, edge.targetHandle) ??+ getWorkflowSourceFieldType(document, templates, edge.source, edge.sourceHandle, index) ??+ getWorkflowTargetFieldType(document, templates, edge.target, edge.targetHandle, index) ??null);};@@ -245,9 +338,10 @@ export const getWorkflowEdgeData = (document: ProjectGraphState,edge: WorkflowEdge,pathType: FlowEdgeType,- templates?: InvocationTemplates+ templates?: InvocationTemplates,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): WorkflowEdgeData => {- const fieldType = getWorkflowEdgeFieldType(document, templates, edge);+ const fieldType = getWorkflowEdgeFieldType(document, templates, edge, index);if (!fieldType) {return UNKNOWN_EDGE_DATA(pathType);@@ -286,13 +380,14 @@ export const toFlowEdges = (edgeType: FlowEdgeType = 'default',selectedNodeIds: Set<string> = EMPTY_NODE_IDS,templates?: InvocationTemplates,- reduceMotion = false+ reduceMotion = false,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): WorkflowFlowEdge[] => {const previousById = new Map(previousEdges.map((edge) => [edge.id, edge]));return document.edges.map((edge) => {const previous = previousById.get(edge.id);- const data = getWorkflowEdgeData(document, edge, edgeType, templates);+ const data = getWorkflowEdgeData(document, edge, edgeType, templates, index);const isConnectedToSelectedNode = selectedNodeIds.has(edge.source) || selectedNodeIds.has(edge.target);const animated = isConnectedToSelectedNode && !reduceMotion ? true : undefined;const className = isConnectedToSelectedNode ? SELECTED_NODE_EDGE_CLASS : undefined;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/performanceConstants.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/performanceConstants.tsnew file mode 100644index 0000000000..55b4c87e90--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/performanceConstants.ts@@ -0,0 +1,8 @@+export const WORKFLOW_LARGE_GRAPH_NODE_COUNT = 300;+export const WORKFLOW_LARGE_GRAPH_EDGE_COUNT = 500;++export const WORKFLOW_MINIMAP_DELAY_MS = 450;+export const WORKFLOW_INITIAL_RENDER_NODE_COUNT = 120;++export const isLargeWorkflowGraph = ({ edgeCount, nodeCount }: { edgeCount: number; nodeCount: number }): boolean =>+ nodeCount >= WORKFLOW_LARGE_GRAPH_NODE_COUNT || edgeCount >= WORKFLOW_LARGE_GRAPH_EDGE_COUNT;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.test.tsnew file mode 100644index 0000000000..a290ed3629--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.test.ts@@ -0,0 +1,18 @@+import type { Viewport } from '@xyflow/react';++import { describe, expect, it } from 'vitest';++import { getWorkflowViewport, setWorkflowViewport } from './workflowViewportStore';++describe('workflowViewportStore', () => {+ it('stores workflow editor viewports per widget instance for the current session', () => {+ const viewport: Viewport = { x: 12, y: 24, zoom: 0.75 };++ expect(getWorkflowViewport('workflow:center')).toBeNull();++ setWorkflowViewport('workflow:center', viewport);++ expect(getWorkflowViewport('workflow:center')).toEqual(viewport);+ expect(getWorkflowViewport('workflow:bottom')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.tsnew file mode 100644index 0000000000..b182028331--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/workflowViewportStore.ts@@ -0,0 +1,17 @@+import type { WidgetInstanceId } from '@workbench/types';+import type { Viewport } from '@xyflow/react';++const viewports = new Map<string, Viewport>();++export const getWorkflowViewportKey = (projectId: string, instanceId: WidgetInstanceId): string =>+ `${projectId}:${instanceId}`;++export const getWorkflowViewport = (key: string): Viewport | null => {+ const viewport = viewports.get(key);++ return viewport ? { ...viewport } : null;+};++export const setWorkflowViewport = (key: string, viewport: Viewport): void => {+ viewports.set(key, { x: viewport.x, y: viewport.y, zoom: viewport.zoom });+};