Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): graph preview node inspector, list mode, and provenance links
joshistoast83b1e5fcc964
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 36f3cef715..a98cc88876 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -543,11 +543,17 @@"you": "You"},"graphPreview": {+ "back": "Back","cfgScale": "CFG scale","compiledFrom": "Compiled from {{source}}.","copied": "Copied","copyJson": "Copy JSON","destination": "Destination",+ "edges": "Edges",+ "edgesIn_one": "in · {{count}} input from {{sources}}",+ "edgesIn_other": "in · {{count}} inputs from {{sources}}",+ "edgesInNone": "in · none",+ "edgesOut": "out · {{field}} → {{target}}","graph": "Graph","graphJsonLabel": "{{title}} graph JSON","inputCount_one": "{{count}} input",@@ -560,6 +566,10 @@"model": "Model","noCompiledGraph": "No compiled graph is available for \"{{graphId}}\" yet.","nodes": "Nodes",+ "nodeSummary": {+ "denoise": "{{steps}} steps · cfg {{cfg}}",+ "noise": "{{width}} × {{height}}"+ },"provenance": {"cfgScale": "Generate → CFG scale","clipSkip": "Generate → CLIP skip",@@ -573,12 +583,15 @@"size": "Generate → Size","steps": "Generate → Steps"},+ "resolvedInputs": "Resolved inputs","scheduler": "Scheduler","seed": "Seed","seedRandomValue": "random","seedRandomized": "Seed is randomized. This graph runs differently each time.","seedRegenerated": "regenerated each run","selectNode": "Select a node for details.",+ "setBy": "Set by",+ "showNode": "show node","size": "Size","steps": "Steps","thisGraph": "This graph",diff --git a/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.test.tsnew file mode 100644index 0000000000..321a7dff1e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';++import type { LayoutGraphEdge, LayoutGraphNode } from './graphLayout';++import { getLayeredPositions, getNodeDepths, getTopologicalOrder } from './graphLayout';++// Diamond: a -> b, a -> c, b -> d, c -> d+const DIAMOND_NODES: LayoutGraphNode[] = [{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }];+const DIAMOND_EDGES: LayoutGraphEdge[] = [+ { sourceNodeId: 'a', targetNodeId: 'b' },+ { sourceNodeId: 'a', targetNodeId: 'c' },+ { sourceNodeId: 'b', targetNodeId: 'd' },+ { sourceNodeId: 'c', targetNodeId: 'd' },+];++describe('getNodeDepths', () => {+ it('assigns longest-path-from-roots depth for a diamond graph', () => {+ const depths = getNodeDepths(DIAMOND_NODES, DIAMOND_EDGES);++ expect(Object.fromEntries(depths)).toEqual({ a: 0, b: 1, c: 1, d: 2 });+ });++ it('terminates on a cycle instead of recursing forever, breaking the loop at re-entry', () => {+ const nodes: LayoutGraphNode[] = [{ id: 'x' }, { id: 'y' }];+ const edges: LayoutGraphEdge[] = [+ { sourceNodeId: 'x', targetNodeId: 'y' },+ { sourceNodeId: 'y', targetNodeId: 'x' },+ ];++ const depths = getNodeDepths(nodes, edges);++ expect(depths.size).toBe(2);+ expect(Number.isFinite(depths.get('x'))).toBe(true);+ expect(Number.isFinite(depths.get('y'))).toBe(true);+ });+});++describe('getTopologicalOrder', () => {+ it('orders by depth ascending, then by input node-array order within a depth', () => {+ expect(getTopologicalOrder(DIAMOND_NODES, DIAMOND_EDGES)).toEqual(['a', 'b', 'c', 'd']);+ });++ it('preserves array order for nodes at the same depth even when reversed', () => {+ const nodes: LayoutGraphNode[] = [{ id: 'c' }, { id: 'b' }, { id: 'a' }];+ const edges: LayoutGraphEdge[] = [+ { sourceNodeId: 'a', targetNodeId: 'b' },+ { sourceNodeId: 'a', targetNodeId: 'c' },+ ];++ // a is depth 0; b and c are both depth 1 — order should follow the input array: c, b.+ expect(getTopologicalOrder(nodes, edges)).toEqual(['a', 'c', 'b']);+ });+});++describe('getLayeredPositions', () => {+ it('places nodes at x = depth * 300, rows spaced by 100 within a depth', () => {+ const positions = getLayeredPositions(DIAMOND_NODES, DIAMOND_EDGES);++ expect(positions.a).toEqual({ x: 0, y: 0 });+ expect(positions.b).toEqual({ x: 300, y: 0 });+ expect(positions.c).toEqual({ x: 300, y: 100 });+ expect(positions.d).toEqual({ x: 600, y: 0 });+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.tsnew file mode 100644index 0000000000..9dbca556a8--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/graphLayout.ts@@ -0,0 +1,85 @@+/**+ * Generic node/edge layout helpers shared by the graph preview flow renderer+ * (`ui/graph-preview/GraphPreviewFlow.tsx`) and, eventually, Task 7's project+ * graph → preview converter. Deliberately xyflow-free and contract-free —+ * callers adapt their own node/edge shapes to the minimal shapes below.+ */++export interface LayoutGraphNode {+ id: string;+}++export interface LayoutGraphEdge {+ sourceNodeId: string;+ targetNodeId: string;+}++const LAYER_WIDTH = 300;+const ROW_HEIGHT = 100;++/** Longest-path-from-roots depth per node; cycle members settle at their first depth. */+export const getNodeDepths = (nodes: LayoutGraphNode[], edges: LayoutGraphEdge[]): Map<string, number> => {+ const depths = new Map<string, number>();+ const incoming = new Map<string, string[]>();++ for (const edge of 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 nodes) {+ resolve(node.id, new Set());+ }++ return depths;+};++/** Layered layout: x = depth * LAYER_WIDTH, y = row-within-depth * ROW_HEIGHT (row order follows node-array order). */+export const getLayeredPositions = (+ nodes: LayoutGraphNode[],+ edges: LayoutGraphEdge[]+): Record<string, { x: number; y: number }> => {+ const depths = getNodeDepths(nodes, edges);+ const rowsPerDepth = new Map<number, number>();+ const positions: Record<string, { x: number; y: number }> = {};++ for (const node of nodes) {+ const depth = depths.get(node.id) ?? 0;+ const row = rowsPerDepth.get(depth) ?? 0;++ rowsPerDepth.set(depth, row + 1);+ positions[node.id] = { x: depth * LAYER_WIDTH, y: row * ROW_HEIGHT };+ }++ return positions;+};++/** Node ids ordered by depth ascending; ties broken by input node-array order. */+export const getTopologicalOrder = (nodes: LayoutGraphNode[], edges: LayoutGraphEdge[]): string[] => {+ const depths = getNodeDepths(nodes, edges);++ return [...nodes]+ .map((node, index) => ({ depth: depths.get(node.id) ?? 0, id: node.id, index }))+ .sort((a, b) => a.depth - b.depth || a.index - b.index)+ .map((entry) => entry.id);+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsxindex 9acbd15e91..3873d4c370 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx@@ -26,19 +26,30 @@ vi.mock('./GraphPreviewFlow', () => ({const TRANSLATIONS: Record<string, string> = {'common.close': 'Close','common.json': 'JSON',+ 'graphPreview.back': 'Back','graphPreview.compiledFrom': 'Compiled from {{source}}.','graphPreview.copied': 'Copied','graphPreview.copyJson': 'Copy JSON','graphPreview.destination': 'Destination',+ 'graphPreview.edges': 'Edges',+ 'graphPreview.edgesIn': 'in · {{count}} inputs from {{sources}}',+ 'graphPreview.edgesInNone': 'in · none',+ 'graphPreview.edgesOut': 'out · {{field}} → {{target}}','graphPreview.graph': 'Graph','graphPreview.graphJsonLabel': '{{title}} graph JSON',+ 'graphPreview.inputCount': '{{count}} inputs','graphPreview.invalidTitle': "This graph can't compile yet.",'graphPreview.invokeRoute': 'Invoke {{route}}','graphPreview.list': 'List','graphPreview.liveHint': 'Updates as you change settings.','graphPreview.noCompiledGraph': 'No compiled graph is available for "{{graphId}}" yet.',+ 'graphPreview.nodeSummary.denoise': '{{steps}} steps · cfg {{cfg}}',+ 'graphPreview.nodeSummary.noise': '{{width}} × {{height}}','graphPreview.nodes': 'Nodes',+ 'graphPreview.resolvedInputs': 'Resolved inputs','graphPreview.selectNode': 'Select a node for details.',+ 'graphPreview.setBy': 'Set by',+ 'graphPreview.showNode': 'show node','graphPreview.thisGraph': 'This graph','graphPreview.title': 'Graph preview',};@@ -76,12 +87,24 @@ const FIXTURE_GRAPH: WorkflowPreviewGraph = {const FIXTURE_SOURCE: GraphPreviewSourceState = {destinationLabel: 'Gallery',+ getProvenance: (nodeId, fieldName) => {+ if (nodeId === 'denoise_latents' && fieldName === 'steps') {+ return { label: 'Generate → Steps' };+ }++ if (nodeId === 'denoise_latents' && fieldName === 'cfg_scale') {+ return { label: 'Generate → CFG scale' };+ }++ return null;+ },graph: FIXTURE_GRAPH,invalidReasons: [],isLive: true,notices: [{ id: 'seed-random', message: 'Seed is randomized. This graph runs differently each time.', nodeId: 'seed' },],+ resolvedInputOverrides: { seed: { value: 'regenerated each run' } },summaryRows: [{ id: 'steps', label: 'Steps', value: '28' },{ id: 'model', label: 'Model', value: 'SDXL' },@@ -145,10 +168,10 @@ describe('GraphPreviewDialog', () => {let host: HTMLDivElement;let root: Root;let onOpenChange: (isOpen: boolean) => void;+ let graphPreviewPort: WorkflowGraphPreviewPort;const renderDialog = async (source: GraphPreviewSourceState) => {const workflowUiAdapter = createWorkflowUiAdapter();- const graphPreviewPort = createGraphPreviewPort();await act(() => {root.render(@@ -177,6 +200,7 @@ describe('GraphPreviewDialog', () => {document.body.append(host);root = createRoot(host);onOpenChange = vi.fn((_isOpen: boolean) => {});+ graphPreviewPort = createGraphPreviewPort();});afterEach(async () => {@@ -184,6 +208,28 @@ describe('GraphPreviewDialog', () => {host.remove();});+ const switchToMode = async (mode: 'graph' | 'list' | 'json') => {+ const input = document.querySelector<HTMLInputElement>(`input[value="${mode}"]`);+ expect(input).not.toBeNull();+ const label = input?.closest('label');+ expect(label).not.toBeNull();++ await act(() => {+ label?.click();+ });+ };++ const clickButtonWithText = async (text: string) => {+ const button = [...document.querySelectorAll('button')].find((candidate) =>+ (candidate.textContent ?? '').includes(text)+ );+ expect(button).not.toBeUndefined();++ await act(() => {+ button?.click();+ });+ };+it('renders summary rows, node count, and the live subtitle', async () => {await renderDialog(FIXTURE_SOURCE);@@ -225,4 +271,46 @@ describe('GraphPreviewDialog', () => {expect(document.body.textContent ?? '').toContain('Height must be a multiple of 8.');expect(document.querySelector('[data-flow-stub]')).toBeNull();});++ it('selecting a node from the list opens the inspector with resolved inputs and edges', async () => {+ await renderDialog(FIXTURE_SOURCE);++ await switchToMode('list');+ expect(document.querySelector('[data-flow-stub]')).toBeNull();++ await clickButtonWithText('denoise_latents');++ // List selection reveals the node in graph mode, not list mode.+ expect(document.querySelector<HTMLInputElement>('input[value="graph"]')?.checked).toBe(true);+ expect(document.querySelector('[data-flow-stub]')).not.toBeNull();++ const text = document.body.textContent ?? '';+ expect(text).toContain('denoise_latents');+ expect(text).toContain('Resolved inputs');+ expect(text).toContain('28');+ expect(text).toContain('Set by');+ expect(text).toContain('Generate → Steps');+ });++ it('show node selects the seed node and inspector shows the randomized override', async () => {+ await renderDialog(FIXTURE_SOURCE);++ await clickButtonWithText('show node');++ const text = document.body.textContent ?? '';+ expect(text).toContain('integer');+ expect(text).toContain('seed');+ expect(text).toContain('regenerated each run');+ });++ it('clicking a provenance link focuses the source and closes the dialog', async () => {+ await renderDialog(FIXTURE_SOURCE);++ await switchToMode('list');+ await clickButtonWithText('denoise_latents');+ await clickButtonWithText('Generate → Steps');++ expect(graphPreviewPort.focusSource).toHaveBeenCalledWith('generate');+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsxindex 7caa58d3de..b8642866a3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx@@ -1,4 +1,5 @@import type { GraphPreviewSourceState, WorkflowInvocationSourceId } from '@features/workflow/ui/contracts';+import type { ReactFlowInstance } from '@xyflow/react';import type { ReactNode } from 'react';import { Box, Dialog, Icon, Portal, SegmentGroup, Stack, Text } from '@chakra-ui/react';@@ -9,6 +10,7 @@ import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { GraphPreviewFlow } from './GraphPreviewFlow';+import { GraphPreviewList } from './GraphPreviewList';import { GraphPreviewSidePanel } from './GraphPreviewSidePanel';interface GraphPreviewDialogProps {@@ -26,8 +28,6 @@ type PreviewMode = 'graph' | 'list' | 'json';const MODE_VALUES: readonly PreviewMode[] = ['graph', 'list', 'json'];const isPreviewMode = (value: string | null): value is PreviewMode => MODE_VALUES.includes(value as PreviewMode);-// `list` renders the same pane as `graph` until Task 6 fills in the node list — the-// segment stays visible so the header layout is final now.const modeItems = [{ labelKey: 'graphPreview.graph', value: 'graph' },{ labelKey: 'graphPreview.list', value: 'list' },@@ -35,6 +35,7 @@ const modeItems = [] as const;const COPY_RESET_DELAY_MS = 1500;+const SELECT_AND_REVEAL_FIT_VIEW_OPTIONS = { duration: 150, maxZoom: 1 } as const;const PreviewPane = ({ children }: { children: ReactNode }) => (<Box flex="1" h="full" minH="0" minW="0" w="full" rounded="md" borderWidth={1} overflow="hidden">@@ -45,10 +46,24 @@ const PreviewPane = ({ children }: { children: ReactNode }) => (const NoticeBanner = ({ bg, color, children }: { bg: string; color: string; children: ReactNode }) => (<Box alignItems="center" bg={bg} color={color} display="flex" fontSize="sm" gap="2" px="3" py="2" rounded="md"><Icon as={SquareDashedIcon} boxSize="4" flexShrink={0} />- <Text>{children}</Text>+ <Box alignItems="center" display="flex" flex="1" gap="2" justifyContent="space-between" minW="0">+ {children}+ </Box></Box>);+/** The banner's "show node" action — a notice may point at the node that caused it (e.g. a randomized seed). */+const ShowNodeLink = ({ nodeId, onSelect }: { nodeId: string; onSelect: (nodeId: string) => void }) => {+ const { t } = useTranslation();+ const handleClick = useCallback(() => onSelect(nodeId), [nodeId, onSelect]);++ return (+ <Button flexShrink={0} fontWeight="normal" h="auto" px="0" size="2xs" variant="plain" onClick={handleClick}>+ {t('graphPreview.showNode')}+ </Button>+ );+};+export const GraphPreviewDialog = ({graphId,isOpen,@@ -60,28 +75,69 @@ export const GraphPreviewDialog = ({const { t } = useTranslation();const graphPreview = useWorkflowGraphPreview();const [mode, setMode] = useState<PreviewMode>('graph');+ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);const [hasCopied, setHasCopied] = useState(false);const copyResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const flowInstanceRef = useRef<ReactFlowInstance | null>(null);const dialogRoute = graphPreview.getRoute(sourceId);const canInvoke = dialogRoute?.canInvoke === true;const hasInvalidReasons = source.invalidReasons.length > 0;- const handleOpenChange = useCallback((event: { open: boolean }) => onOpenChange(event.open), [onOpenChange]);+ const graph = source.graph;+ const selectedNode = graph?.nodes.find((node) => node.id === selectedNodeId) ?? null;++ // Every path that can close the dialog routes through this, so the+ // selection never survives into the next time it's opened.+ const closeAndReset = useCallback(+ (open: boolean) => {+ if (!open) {+ setSelectedNodeId(null);+ }++ onOpenChange(open);+ },+ [onOpenChange]+ );++ const handleOpenChange = useCallback((event: { open: boolean }) => closeAndReset(event.open), [closeAndReset]);const handleModeChange = useCallback((event: { value: string | null }) => {if (isPreviewMode(event.value)) {setMode(event.value);}}, []);- const closeDialog = useCallback(() => onOpenChange(false), [onOpenChange]);+ const closeDialog = useCallback(() => closeAndReset(false), [closeAndReset]);const invokeRoute = useCallback(() => {void graphPreview.invoke(sourceId).then((submitted) => {if (submitted) {- onOpenChange(false);+ closeAndReset(false);}});- }, [graphPreview, onOpenChange, sourceId]);+ }, [graphPreview, closeAndReset, sourceId]);++ const handleFlowInit = useCallback((instance: ReactFlowInstance) => {+ flowInstanceRef.current = instance;+ }, []);+ const handleFlowNodeSelect = useCallback((nodeId: string | null) => setSelectedNodeId(nodeId), []);+ const handleBack = useCallback(() => setSelectedNodeId(null), []);+ const handleProvenanceClick = useCallback(() => {+ graphPreview.focusSource(sourceId);+ closeAndReset(false);+ }, [graphPreview, sourceId, closeAndReset]);++ // Selects a node and, if the flow is mounted and initialized, brings it into+ // view. List rows and the notice banner's "show node" link both switch to+ // graph mode so the selection is always visible after they fire.+ const selectAndReveal = useCallback((nodeId: string) => {+ setSelectedNodeId(nodeId);+ setMode('graph');++ const instance = flowInstanceRef.current;++ if (instance) {+ void instance.fitView({ ...SELECT_AND_REVEAL_FIT_VIEW_OPTIONS, nodes: [{ id: nodeId }] });+ }+ }, []);- const graph = source.graph;const copyJson = useCallback(() => {const json = JSON.stringify(graph?.backendGraph ?? graph, null, 2);@@ -131,12 +187,15 @@ export const GraphPreviewDialog = ({<Dialog.Body display="flex" flex="1" flexDirection="column" gap="3" minH="0">{source.notices.map((notice) => (<NoticeBanner key={notice.id} bg="orange.subtle" color="fg">- {notice.message}+ <Text>{notice.message}</Text>+ {notice.nodeId ? <ShowNodeLink nodeId={notice.nodeId} onSelect={selectAndReveal} /> : null}</NoticeBanner>))}{hasInvalidReasons ? (<NoticeBanner bg="bg.muted" color="fg.muted">- {t('graphPreview.invalidTitle')} {source.invalidReasons[0]}+ <Text>+ {t('graphPreview.invalidTitle')} {source.invalidReasons[0]}+ </Text></NoticeBanner>) : null}{hasInvalidReasons ? null : (@@ -148,11 +207,24 @@ export const GraphPreviewDialog = ({</Text>) : mode === 'json' ? (<JsonPreview h="full" label={jsonLabel} maxH="100%" value={graph} />+ ) : mode === 'list' ? (+ <GraphPreviewList graph={graph} onSelect={selectAndReveal} />) : (- <GraphPreviewFlow graph={graph} positionHints={source.positionHints} />+ <GraphPreviewFlow+ graph={graph}+ positionHints={source.positionHints}+ selectedNodeId={selectedNodeId}+ onInit={handleFlowInit}+ onNodeSelect={handleFlowNodeSelect}+ />)}</PreviewPane>- <GraphPreviewSidePanel source={source} />+ <GraphPreviewSidePanel+ source={source}+ selectedNode={selectedNode}+ onBack={handleBack}+ onProvenanceClick={handleProvenanceClick}+ /></Box>)}</Dialog.Body>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsxindex 47fe78c1c4..8205bb7724 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx@@ -1,25 +1,26 @@import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';+import type {+ Edge as FlowEdge,+ Node as FlowNode,+ NodeMouseHandler,+ NodeProps,+ NodeTypes,+ ReactFlowInstance,+} from '@xyflow/react';+import type { TFunction } from 'i18next';import { Badge, Box, Stack, Text } from '@chakra-ui/react';import { isInvocationNode, type ProjectGraphState, type XYPosition } from '@features/workflow/contracts';+import { getLayeredPositions } from '@features/workflow/core/graphLayout';import '@xyflow/react/dist/style.css';import { useWorkflowPreferencesSelector } from '@features/workflow/ui/WorkflowUiContext';import { getResolvedWorkflowEdges } from '@features/workflow/utility';-import {- Background,- BackgroundVariant,- Handle,- Position,- ReactFlow,- type Edge as FlowEdge,- type Node as FlowNode,- type NodeProps,- type NodeTypes,-} from '@xyflow/react';-import { useId, useMemo } from 'react';+import { Background, BackgroundVariant, Handle, Position, ReactFlow } from '@xyflow/react';+import { useCallback, useId, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { flowThemeCss, getFlowColorMode } from './flowTheme';+import { getNodeSubtitle } from './nodeSummaries';/*** A read-only flow rendering of a compiled `GraphContract` — the "nodes" half@@ -28,7 +29,10 @@ import { flowThemeCss, getFlowColorMode } from './flowTheme';* came from the project graph) and falls back to a layered topological layout.*/-type PreviewFlowNode = FlowNode<{ inputCount: number; nodeId: string; nodeType: string }, 'preview'>;+type PreviewFlowNode = FlowNode<+ { inputCount: number; isSelected: boolean; nodeId: string; nodeType: string; subtitle: string | null },+ 'preview'+>;/*** A lightweight contract view of an editable document (no templates needed),@@ -67,8 +71,6 @@ export const documentToPreviewGraph = (};};-const LAYER_WIDTH = 300;-const ROW_HEIGHT = 100;const handleStyle = { background: 'var(--wb-flow-grid)', border: 'none' } as const;const reactFlowProOptions = { hideAttribution: true } as const;const reactFlowStyle = { background: 'transparent' } as const;@@ -77,7 +79,15 @@ const PreviewNode = ({ data }: NodeProps<PreviewFlowNode>) => {const { t } = useTranslation();return (- <Box bg="bg" borderColor="border.emphasized" borderWidth="1px" fontSize="xs" minW="14rem" rounded="lg" shadow="sm">+ <Box+ bg="bg"+ borderColor={data.isSelected ? 'accent.emphasized' : 'border.emphasized'}+ borderWidth="1px"+ fontSize="xs"+ minW="14rem"+ rounded="lg"+ shadow="sm"+ ><Handle position={Position.Left} style={handleStyle} type="target" /><Handle position={Position.Right} style={handleStyle} type="source" /><Stack gap="0.5" px="3" py="2">@@ -85,7 +95,7 @@ const PreviewNode = ({ data }: NodeProps<PreviewFlowNode>) => {{data.nodeType}</Badge><Text color="fg.subtle" fontSize="2xs" truncate>- {data.nodeId} · {t('graphPreview.inputCount', { count: data.inputCount })}+ {data.subtitle ?? `${data.nodeId} · ${t('graphPreview.inputCount', { count: data.inputCount })}`}</Text></Stack></Box>@@ -94,71 +104,29 @@ const PreviewNode = ({ data }: NodeProps<PreviewFlowNode>) => {const nodeTypes: NodeTypes = { preview: PreviewNode };-/** Longest-path-from-roots depth per node; cycle members settle at their first depth. */-const getNodeDepths = (graph: WorkflowPreviewGraph): 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: WorkflowPreviewGraph, 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);+const toPreviewNodes = (+ graph: WorkflowPreviewGraph,+ t: TFunction,+ positionHints?: Record<string, XYPosition>,+ selectedNodeId?: string | null+): PreviewFlowNode[] => {+ const positions = getLayeredPositions(+ graph.nodes,+ graph.edges.map((edge) => ({ sourceNodeId: edge.sourceNodeId, targetNodeId: edge.targetNodeId }))+ );- 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,- };- });+ return graph.nodes.map((node) => ({+ data: {+ inputCount: Object.keys(node.inputs).length,+ isSelected: node.id === selectedNodeId,+ nodeId: node.id,+ nodeType: node.type,+ subtitle: getNodeSubtitle(node, t),+ },+ id: node.id,+ position: positionHints?.[node.id] ?? positions[node.id] ?? { x: 0, y: 0 },+ type: 'preview' as const,+ }));};const toPreviewEdges = (graph: WorkflowPreviewGraph): FlowEdge[] =>@@ -172,14 +140,36 @@ const toPreviewEdges = (graph: WorkflowPreviewGraph): FlowEdge[] =>export const GraphPreviewFlow = ({graph,positionHints,+ selectedNodeId = null,+ onInit,+ onNodeSelect,}: {graph: WorkflowPreviewGraph;positionHints?: Record<string, XYPosition>;+ selectedNodeId?: string | null;+ onInit?: (instance: ReactFlowInstance) => void;+ onNodeSelect?: (nodeId: string | null) => void;}) => {+ const { t } = useTranslation();const themeId = useWorkflowPreferencesSelector((preferences) => preferences.themeId);const backgroundId = useId().replace(/:/g, '');- const nodes = useMemo(() => toPreviewNodes(graph, positionHints), [graph, positionHints]);+ const nodes = useMemo(+ () => toPreviewNodes(graph, t, positionHints, selectedNodeId),+ [graph, t, positionHints, selectedNodeId]+ );const edges = useMemo(() => toPreviewEdges(graph), [graph]);+ const handleNodeClick = useCallback<NodeMouseHandler<PreviewFlowNode>>(+ (_event, node) => onNodeSelect?.(node.id),+ [onNodeSelect]+ );+ const handlePaneClick = useCallback(() => onNodeSelect?.(null), [onNodeSelect]);+ // xyflow types `onInit` against this component's node/edge generics; the caller+ // (`GraphPreviewDialog`) only calls generic instance methods (`fitView`), so the+ // narrower instance is safe to widen back to the public, type-erased signature.+ const handleInit = useCallback(+ (instance: ReactFlowInstance<PreviewFlowNode, FlowEdge>) => onInit?.(instance as unknown as ReactFlowInstance),+ [onInit]+ );return (<Box bg="bg.inset" css={flowThemeCss} h="full" rounded="md" w="full">@@ -198,6 +188,9 @@ export const GraphPreviewFlow = ({nodeTypes={nodeTypes}proOptions={reactFlowProOptions}style={reactFlowStyle}+ onInit={handleInit}+ onNodeClick={handleNodeClick}+ onPaneClick={handlePaneClick}><BackgroundbgColor="var(--xy-background-color)"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsxnew file mode 100644index 0000000000..8882f7d6fb--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsx@@ -0,0 +1,73 @@+import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';++import { Badge, Button, Stack, Text } from '@chakra-ui/react';+import { getTopologicalOrder } from '@features/workflow/core/graphLayout';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { getNodeSubtitle } from './nodeSummaries';++type PreviewListNode = WorkflowPreviewGraph['nodes'][number];++const GraphPreviewListRow = ({ node, onSelect }: { node: PreviewListNode; onSelect: (nodeId: string) => void }) => {+ const { t } = useTranslation();+ const subtitle =+ getNodeSubtitle(node, t) ??+ `${node.id} · ${t('graphPreview.inputCount', { count: Object.keys(node.inputs).length })}`;+ const handleClick = useCallback(() => onSelect(node.id), [node.id, onSelect]);++ return (+ <Button+ fontWeight="normal"+ h="auto"+ justifyContent="flex-start"+ px="3"+ py="2"+ variant="ghost"+ w="full"+ onClick={handleClick}+ >+ <Stack align="flex-start" gap="0.5" w="full">+ <Badge fontFamily="mono" size="xs">+ {node.type}+ </Badge>+ <Text color="fg.muted" fontSize="2xs" fontWeight="normal" truncate>+ {subtitle}+ </Text>+ </Stack>+ </Button>+ );+};++/**+ * The preview dialog's "List" mode: every node as a full-width row, in+ * topological order, so a keyboard/screen-reader user can reach any node+ * without depending on the flow canvas. Selecting a row opens the same+ * inspector the flow's node click does (`GraphPreviewDialog.selectAndReveal`).+ *+ * Deliberately avoids `@platform/ui` — the barrel's fan-in budget is nearly+ * exhausted, and this component only needs plain Chakra primitives.+ */+export const GraphPreviewList = ({+ graph,+ onSelect,+}: {+ graph: WorkflowPreviewGraph;+ onSelect: (nodeId: string) => void;+}) => {+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));+ const order = getTopologicalOrder(+ graph.nodes,+ graph.edges.map((edge) => ({ sourceNodeId: edge.sourceNodeId, targetNodeId: edge.targetNodeId }))+ );++ return (+ <Stack gap="1" h="full" overflowY="auto" p="2">+ {order.map((nodeId) => {+ const node = nodesById.get(nodeId);++ return node ? <GraphPreviewListRow key={node.id} node={node} onSelect={onSelect} /> : null;+ })}+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsxindex b26b1658f9..6be86910bd 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx@@ -1,53 +1,225 @@-import type { GraphPreviewSourceState } from '@features/workflow/ui/contracts';+import type { GraphPreviewSourceState, WorkflowPreviewGraph } from '@features/workflow/ui/contracts';+import type { TFunction } from 'i18next';-import { DataList, Stack, Text } from '@chakra-ui/react';-import { Scrollable } from '@platform/ui';+import { Badge, Box, DataList, Stack, Text } from '@chakra-ui/react';+import { Button, IconButton, Scrollable } from '@platform/ui';+import { ArrowLeftIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';+type PreviewGraphNode = WorkflowPreviewGraph['nodes'][number];+/**- * The preview dialog's right-hand rail: a quick summary of the compiled- * graph (node count, result destination, source-specific settings rows).- * Task 6 extends this with a node-selection state that replaces the summary- * with the selected node's field values.+ * The preview dialog's right-hand rail: either a summary of the compiled+ * graph (node count, result destination, source-specific settings rows), or+ * — once a node is selected in the flow/list — that node's inspector (who+ * set its inputs, their resolved values, and its edges). The outer+ * `Scrollable` stays mounted across the switch so selecting a node doesn't+ * remount the panel's scroll container.*/-export const GraphPreviewSidePanel = ({ source }: { source: GraphPreviewSourceState }) => {+export const GraphPreviewSidePanel = ({+ source,+ selectedNode,+ onBack,+ onProvenanceClick,+}: {+ source: GraphPreviewSourceState;+ selectedNode: PreviewGraphNode | null;+ onBack: () => void;+ onProvenanceClick: () => void;+}) => {const { t } = useTranslation();- const nodeCount = source.graph?.nodes.length;return (<Scrollable flexShrink={0} h="full" label={t('graphPreview.thisGraph')} w="19rem">- <Stack gap="2" p="2">- <Stack gap="0.5">- <Text fontSize="sm" fontWeight="semibold">- {t('graphPreview.thisGraph')}+ {selectedNode ? (+ <NodeInspector node={selectedNode} source={source} onBack={onBack} onProvenanceClick={onProvenanceClick} />+ ) : (+ <GraphSummary source={source} />+ )}+ </Scrollable>+ );+};++const GraphSummary = ({ source }: { source: GraphPreviewSourceState }) => {+ const { t } = useTranslation();+ const nodeCount = source.graph?.nodes.length;++ return (+ <Stack gap="2" p="2">+ <Stack gap="0.5">+ <Text fontSize="sm" fontWeight="semibold">+ {t('graphPreview.thisGraph')}+ </Text>+ <Text color="fg.muted" fontSize="2xs">+ {t('graphPreview.selectNode')}+ </Text>+ </Stack>+ <DataList.Root gap="1.5" orientation="horizontal" size="sm">+ <DataList.Item>+ <DataList.ItemLabel fontSize="2xs">{t('graphPreview.nodes')}</DataList.ItemLabel>+ <DataList.ItemValue fontSize="2xs" minW="0">+ {nodeCount !== undefined ? String(nodeCount) : '—'}+ </DataList.ItemValue>+ </DataList.Item>+ <DataList.Item>+ <DataList.ItemLabel fontSize="2xs">{t('graphPreview.destination')}</DataList.ItemLabel>+ <DataList.ItemValue fontSize="2xs" minW="0">+ {source.destinationLabel ?? '—'}+ </DataList.ItemValue>+ </DataList.Item>+ {source.summaryRows.map((row) => (+ <DataList.Item key={row.id}>+ <DataList.ItemLabel fontSize="2xs">{row.label}</DataList.ItemLabel>+ <DataList.ItemValue fontSize="2xs" minW="0">+ {row.value}+ </DataList.ItemValue>+ </DataList.Item>+ ))}+ </DataList.Root>+ </Stack>+ );+};++/** string/number/boolean → `String`; object with a string `name` → the name; other object/array → truncated JSON; `undefined` → `null` (caller skips the row). */+const formatResolvedValue = (value: unknown): string | null => {+ if (value === undefined) {+ return null;+ }++ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {+ return String(value);+ }++ if (value !== null && typeof value === 'object' && typeof (value as { name?: unknown }).name === 'string') {+ return (value as { name: string }).name;+ }++ const json = JSON.stringify(value);++ return json.length > 40 ? `${json.slice(0, 40)}…` : json;+};++const getDistinctProvenanceLabels = (node: PreviewGraphNode, source: GraphPreviewSourceState): string[] => {+ if (!source.getProvenance) {+ return [];+ }++ const labels = new Set<string>();++ for (const field of Object.keys(node.inputs)) {+ const provenance = source.getProvenance(node.id, field);++ if (provenance) {+ labels.add(provenance.label);+ }+ }++ return [...labels];+};++const getEdgesInLine = (node: PreviewGraphNode, graph: WorkflowPreviewGraph | null, t: TFunction): string => {+ const incoming = graph?.edges.filter((edge) => edge.targetNodeId === node.id) ?? [];++ if (incoming.length === 0) {+ return t('graphPreview.edgesInNone');+ }++ const sources = [...new Set(incoming.map((edge) => edge.sourceNodeId))].join(', ');++ return t('graphPreview.edgesIn', { count: incoming.length, sources });+};++const NodeInspector = ({+ node,+ source,+ onBack,+ onProvenanceClick,+}: {+ node: PreviewGraphNode;+ source: GraphPreviewSourceState;+ onBack: () => void;+ onProvenanceClick: () => void;+}) => {+ const { t } = useTranslation();+ const provenanceLabels = getDistinctProvenanceLabels(node, source);+ const outgoingEdges = source.graph?.edges.filter((edge) => edge.sourceNodeId === node.id) ?? [];+ const resolvedFields = Object.entries(node.inputs)+ .map(([field, value]) => ({+ field,+ value: source.resolvedInputOverrides?.[node.id]?.[field] ?? formatResolvedValue(value),+ }))+ .filter((entry): entry is { field: string; value: string } => entry.value !== null);++ return (+ <Stack gap="3" p="2">+ <Box alignItems="center" display="flex" gap="2">+ <IconButton aria-label={t('graphPreview.back')} size="2xs" variant="ghost" onClick={onBack}>+ <ArrowLeftIcon />+ </IconButton>+ <Stack gap="0" minW="0">+ <Badge fontFamily="mono" size="xs" w="fit-content">+ {node.type}+ </Badge>+ <Text color="fg.muted" fontSize="2xs" truncate>+ {node.id}</Text>- <Text color="fg.muted" fontSize="2xs">- {t('graphPreview.selectNode')}+ </Stack>+ </Box>++ {provenanceLabels.length > 0 ? (+ <Stack gap="1">+ <Text color="fg.muted" fontSize="2xs" fontWeight="semibold">+ {t('graphPreview.setBy')}</Text>+ <Stack gap="0.5">+ {provenanceLabels.map((label) => (+ <Button+ key={label}+ alignSelf="flex-start"+ fontSize="2xs"+ fontWeight="normal"+ h="auto"+ px="0"+ size="2xs"+ variant="plain"+ onClick={onProvenanceClick}+ >+ {label}+ </Button>+ ))}+ </Stack></Stack>+ ) : null}++ <Stack gap="1">+ <Text color="fg.muted" fontSize="2xs" fontWeight="semibold">+ {t('graphPreview.resolvedInputs')}+ </Text><DataList.Root gap="1.5" orientation="horizontal" size="sm">- <DataList.Item>- <DataList.ItemLabel fontSize="2xs">{t('graphPreview.nodes')}</DataList.ItemLabel>- <DataList.ItemValue fontSize="2xs" minW="0">- {nodeCount !== undefined ? String(nodeCount) : '—'}- </DataList.ItemValue>- </DataList.Item>- <DataList.Item>- <DataList.ItemLabel fontSize="2xs">{t('graphPreview.destination')}</DataList.ItemLabel>- <DataList.ItemValue fontSize="2xs" minW="0">- {source.destinationLabel ?? '—'}- </DataList.ItemValue>- </DataList.Item>- {source.summaryRows.map((row) => (- <DataList.Item key={row.id}>- <DataList.ItemLabel fontSize="2xs">{row.label}</DataList.ItemLabel>+ {resolvedFields.map(({ field, value }) => (+ <DataList.Item key={field}>+ <DataList.ItemLabel fontSize="2xs">{field}</DataList.ItemLabel><DataList.ItemValue fontSize="2xs" minW="0">- {row.value}+ {value}</DataList.ItemValue></DataList.Item>))}</DataList.Root></Stack>- </Scrollable>++ <Stack gap="1">+ <Text color="fg.muted" fontSize="2xs" fontWeight="semibold">+ {t('graphPreview.edges')}+ </Text>+ <Stack gap="0.5">+ <Text fontSize="2xs">{getEdgesInLine(node, source.graph, t)}</Text>+ {outgoingEdges.map((edge) => (+ <Text key={edge.id} fontSize="2xs">+ {t('graphPreview.edgesOut', { field: edge.sourceField, target: edge.targetNodeId })}+ </Text>+ ))}+ </Stack>+ </Stack>+ </Stack>);};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.test.tsnew file mode 100644index 0000000000..574de1aca7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.test.ts@@ -0,0 +1,36 @@+import type { TFunction } from 'i18next';++import { describe, expect, it } from 'vitest';++import { getNodeSubtitle } from './nodeSummaries';++const t = ((key: string, options?: Record<string, unknown>) => `${key}:${JSON.stringify(options ?? {})}`) as TFunction;++describe('getNodeSubtitle', () => {+ it('returns the denoise summary when steps and cfg_scale are numbers', () => {+ const subtitle = getNodeSubtitle(+ { id: 'denoise_latents', inputs: { cfg_scale: 4, steps: 28 }, type: 'denoise_latents' },+ t+ );++ expect(subtitle).toBe('graphPreview.nodeSummary.denoise:{"cfg":4,"steps":28}');+ });++ it('returns the noise summary when width and height are numbers', () => {+ const subtitle = getNodeSubtitle({ id: 'noise', inputs: { height: 512, width: 768 }, type: 'noise' }, t);++ expect(subtitle).toBe('graphPreview.nodeSummary.noise:{"height":512,"width":768}');+ });++ it('returns null for denoise_latents when the numeric fields are missing', () => {+ const subtitle = getNodeSubtitle({ id: 'denoise_latents', inputs: {}, type: 'denoise_latents' }, t);++ expect(subtitle).toBeNull();+ });++ it('returns null for an unknown node type', () => {+ const subtitle = getNodeSubtitle({ id: 'l2i', inputs: {}, type: 'l2i' }, t);++ expect(subtitle).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.tsnew file mode 100644index 0000000000..3b6a3e2c7d--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts@@ -0,0 +1,34 @@+import type { TFunction } from 'i18next';++/**+ * One-line, type-specific summaries shown under a preview node's id (e.g.+ * "28 steps · cfg 4" for `denoise_latents`). Callers fall back to the generic+ * `id · N inputs` line when this returns `null` — most invocation types have+ * no bespoke summary.+ */+export const getNodeSubtitle = (+ node: { id: string; type: string; inputs: Record<string, unknown> },+ t: TFunction+): string | null => {+ if (node.type === 'denoise_latents') {+ const { cfg_scale: cfg, steps } = node.inputs;++ if (typeof cfg === 'number' && typeof steps === 'number') {+ return t('graphPreview.nodeSummary.denoise', { cfg, steps });+ }++ return null;+ }++ if (node.type === 'noise') {+ const { height, width } = node.inputs;++ if (typeof height === 'number' && typeof width === 'number') {+ return t('graphPreview.nodeSummary.noise', { height, width });+ }++ return null;+ }++ return null;+};