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
fix(webv2): graph preview final review fixes
joshistoast812d8571fce4
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 3802b58472..6d343ca517 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -547,6 +547,7 @@"cfgScale": "CFG scale","compiledFrom": "Compiled from {{source}}.","copied": "Copied",+ "copyFailed": "Failed to copy JSON","copyJson": "Copy JSON","destination": "Destination","downloadJson": "Download JSON",@@ -595,6 +596,7 @@"resolvedInputs": "Resolved inputs","savedToLibrary": "Saved to workflow library","saveToLibrary": "Save to workflow library",+ "saveToLibraryFailed": "No saveable nodes in this graph.","saveToLibraryHint": "Reusable, leaves this project alone","scheduler": "Scheduler","seed": "Seed",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 07d490e392..842c2d21e2 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@@ -1,3 +1,4 @@+import type { InvocationTemplatesSnapshot } from '@features/workflow/core/types';import type {GraphPreviewSourceState,WorkflowInvocationSourceId,@@ -14,19 +15,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { GraphPreviewDialog } from './GraphPreviewDialog';-// xyflow stays out of this shell test — the flow pane itself is covered-// elsewhere (`GraphPreviewFlow`'s own tests).-vi.mock('./GraphPreviewFlow', () => ({- GraphPreviewFlow: () => <div data-flow-stub />,- documentToPreviewGraph: () => {- throw new Error('not used');- },-}));--// `downloadText` and the invocation templates snapshot both need to exist-// before `vi.mock` factories below run (they're hoisted above the imports-// that would otherwise define them), so they're built through `vi.hoisted`.-const { downloads, TEMPLATES_SNAPSHOT } = vi.hoisted(() => {+// `downloadText`, the invocation templates snapshot, and the flow's `onInit`+// instance stub all need to exist before `vi.mock` factories below run+// (they're hoisted above the imports that would otherwise define them), so+// they're built through `vi.hoisted`.+const { downloads, fitViewMock, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.hoisted(() => {const fieldInput = (name: string, defaultValue: unknown) => ({default: defaultValue,description: '',@@ -64,23 +57,50 @@ const { downloads, TEMPLATES_SNAPSHOT } = vi.hoisted(() => {version: '1.0.0',});+ // Typed against the real snapshot shape (not inferred from this literal)+ // so `templatesSnapshotRef.current` can be reassigned to other statuses+ // (e.g. 'loading') from a test without a structural mismatch.+ const templatesSnapshot: InvocationTemplatesSnapshot = {+ error: null,+ status: 'loaded',+ templates: {+ denoise_latents: invocationTemplate('denoise_latents', {+ cfg_scale: fieldInput('cfg_scale', 7),+ steps: fieldInput('steps', 30),+ }),+ integer: invocationTemplate('integer', { value: fieldInput('value', 0) }),+ l2i: invocationTemplate('l2i', {}),+ },+ };+return {downloads: { downloadBlob: vi.fn(), downloadText: vi.fn() },- TEMPLATES_SNAPSHOT: {- error: null,- status: 'loaded' as const,- templates: {- denoise_latents: invocationTemplate('denoise_latents', {- cfg_scale: fieldInput('cfg_scale', 7),- steps: fieldInput('steps', 30),- }),- integer: invocationTemplate('integer', { value: fieldInput('value', 0) }),- l2i: invocationTemplate('l2i', {}),- },- },+ // `GraphPreviewFlow`'s mock (below) calls `onInit` with this so+ // `handleFlowInit`'s pending-reveal consumption has a real `fitView` spy+ // to assert against — asserting the dialog's own reveal logic runs to+ // completion, not just that it doesn't crash.+ fitViewMock: vi.fn(() => Promise.resolve(true)),+ TEMPLATES_SNAPSHOT: templatesSnapshot,+ // Mutable so a single test can point `useInvocationTemplatesSnapshot` at+ // a non-loaded status without a per-test `vi.mock` factory.+ templatesSnapshotRef: { current: templatesSnapshot },};});+// xyflow stays out of this shell test — the flow pane's own rendering is+// covered elsewhere (`GraphPreviewFlow`'s own tests). It still calls `onInit`+// with a stub instance so `GraphPreviewDialog`'s pending-reveal handoff+// (`selectAndReveal` → `handleFlowInit`) has something real to run against.+vi.mock('./GraphPreviewFlow', () => ({+ GraphPreviewFlow: ({ onInit }: { onInit?: (instance: { fitView: typeof fitViewMock }) => void }) => {+ onInit?.({ fitView: fitViewMock });+ return <div data-flow-stub />;+ },+ documentToPreviewGraph: () => {+ throw new Error('not used');+ },+}));+vi.mock('@platform/browser/downloadBlob', () => downloads);// The "Open as" menu (`GraphPreviewOpenAsMenu`) reads the invocation@@ -90,8 +110,8 @@ vi.mock('@platform/browser/downloadBlob', () => downloads);// pre-loaded snapshot covering the fixture graph's node types.vi.mock('@features/workflow/react', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- getInvocationTemplatesSnapshot: () => TEMPLATES_SNAPSHOT,- useInvocationTemplatesSnapshot: () => TEMPLATES_SNAPSHOT,+ getInvocationTemplatesSnapshot: () => templatesSnapshotRef.current,+ useInvocationTemplatesSnapshot: () => templatesSnapshotRef.current,}));// "Save to workflow library" goes through `useSaveWorkflowToLibrary`@@ -117,6 +137,7 @@ const TRANSLATIONS: Record<string, string> = {'graphPreview.back': 'Back','graphPreview.compiledFrom': 'Compiled from {{source}}.','graphPreview.copied': 'Copied',+ 'graphPreview.copyFailed': 'Failed to copy JSON','graphPreview.copyJson': 'Copy JSON','graphPreview.destination': 'Destination','graphPreview.downloadJson': 'Download JSON',@@ -144,6 +165,7 @@ const TRANSLATIONS: Record<string, string> = {'graphPreview.resolvedInputs': 'Resolved inputs','graphPreview.savedToLibrary': 'Saved to workflow library','graphPreview.saveToLibrary': 'Save to workflow library',+ 'graphPreview.saveToLibraryFailed': 'No saveable nodes in this graph.','graphPreview.saveToLibraryHint': 'Reusable, leaves this project alone','graphPreview.selectNode': 'Select a node for details.','graphPreview.setBy': 'Set by',@@ -218,6 +240,46 @@ const INVALID_SOURCE: GraphPreviewSourceState = {summaryRows: [],};+// A single node of a type absent from `TEMPLATES_SNAPSHOT.templates` —+// `previewGraphToDocument` skips it, so the converted document has zero+// nodes and both "Open as" actions that convert to a document should bail.+const UNKNOWN_NODE_GRAPH: WorkflowPreviewGraph = {+ id: 'unknown-node-graph',+ nodes: [{ id: 'mystery', type: 'unknown_type', inputs: {} }],+ edges: [],+ version: 1,+};++const UNKNOWN_NODE_SOURCE: GraphPreviewSourceState = {+ destinationLabel: 'Gallery',+ graph: UNKNOWN_NODE_GRAPH,+ invalidReasons: [],+ isLive: false,+ notices: [],+ summaryRows: [],+};++// Long enough to exercise the side panel's ~40-char truncation policy for+// resolved-input strings.+const LONG_STRING_VALUE =+ 'a value long enough to need truncation in the resolved inputs list, well past forty characters';++const LONG_VALUE_GRAPH: WorkflowPreviewGraph = {+ id: 'long-value-graph',+ nodes: [{ id: 'note', type: 'integer', inputs: { value: LONG_STRING_VALUE } }],+ edges: [],+ version: 1,+};++const LONG_VALUE_SOURCE: GraphPreviewSourceState = {+ destinationLabel: 'Gallery',+ graph: LONG_VALUE_GRAPH,+ invalidReasons: [],+ isLive: false,+ notices: [],+ summaryRows: [],+};+const preferencesSnapshot = {reduceMotion: false,themeId: 'classic' as const,@@ -325,6 +387,8 @@ describe('GraphPreviewDialog', () => {downloads.downloadBlob.mockReset();downloads.downloadText.mockReset();createLibraryWorkflowMock.mockReset();+ fitViewMock.mockClear();+ templatesSnapshotRef.current = TEMPLATES_SNAPSHOT;});afterEach(async () => {@@ -437,6 +501,39 @@ describe('GraphPreviewDialog', () => {expect(document.querySelector('[data-flow-stub]')).toBeNull();});+ it('renders the side panel only in graph mode', async () => {+ // The fixture's own notice text ("...This graph runs differently each+ // time.") contains the panel's heading as a substring, so this checks+ // for the panel's `Scrollable` region (`aria-label="This graph"`)+ // instead of a raw text match.+ const findSidePanel = () => document.querySelector('[role="region"][aria-label="This graph"]');++ await renderDialog(FIXTURE_SOURCE);++ // Graph mode (the default): the panel is present.+ expect(findSidePanel()).not.toBeNull();++ await switchToMode('list');+ expect(findSidePanel()).toBeNull();++ await switchToMode('json');+ expect(findSidePanel()).toBeNull();++ await switchToMode('graph');+ expect(findSidePanel()).not.toBeNull();+ });++ it('disables Copy JSON when there is no compiled graph to copy', async () => {+ await renderDialog(INVALID_SOURCE);++ const copyButton = [...document.querySelectorAll('button')].find((candidate) =>+ (candidate.textContent ?? '').includes('Copy JSON')+ );++ expect(copyButton).toBeInstanceOf(HTMLButtonElement);+ expect((copyButton as HTMLButtonElement).disabled).toBe(true);+ });+it('selecting a node from the list opens the inspector with resolved inputs and edges', async () => {await renderDialog(FIXTURE_SOURCE);@@ -462,6 +559,14 @@ describe('GraphPreviewDialog', () => {expect(text).toContain('Edges');expect(text).toContain('in · 1 inputs from seed');expect(text).toContain('out · latents → l2i');++ // The flow wasn't mounted when the row was clicked (mode was still+ // 'list'), so the reveal had to go through the pending-reveal path:+ // `selectAndReveal` stashes the id, and the flow's remount (its `onInit`+ // firing again) is what actually calls `fitView`. This is the case the+ // stale-ref bug broke — before the fix, `flowInstanceRef` still pointed+ // at the unmounted flow's instance and this fit never happened.+ expect(fitViewMock).toHaveBeenCalledWith(expect.objectContaining({ nodes: [{ id: 'denoise_latents' }] }));});it('show node selects the seed node and inspector shows the randomized override', async () => {@@ -473,6 +578,11 @@ describe('GraphPreviewDialog', () => {expect(text).toContain('integer');expect(text).toContain('seed');expect(text).toContain('regenerated each run');++ // Mode was already 'graph' with the flow mounted, so this reveal takes+ // the immediate branch — `fitView` runs straight off `flowInstanceRef`+ // instead of waiting on a remount.+ expect(fitViewMock).toHaveBeenCalledWith(expect.objectContaining({ nodes: [{ id: 'seed' }] }));});it('clicking a provenance link focuses the source and closes the dialog', async () => {@@ -578,4 +688,45 @@ describe('GraphPreviewDialog', () => {// `useSaveWorkflowToLibrary`'s own catch path (Task 8) reports the failure.expect(workflowUiAdapter.notifications.error).toHaveBeenCalledWith('Failed to save workflow', expect.any(String));});++ it('Open as → Save to workflow library bails with an error notification when the graph has no saveable nodes', async () => {+ await renderDialog(UNKNOWN_NODE_SOURCE);++ await openAsMenu();+ await clickMenuItemWithText('Save to workflow library');+ await flushAsync();++ // The fixture's only node is a type with no matching template, so+ // `previewGraphToDocument` skips it and the converted document is empty —+ // this must bail before ever reaching the backend save call.+ expect(createLibraryWorkflowMock).not.toHaveBeenCalled();+ expect(workflowUiAdapter.notifications.error).toHaveBeenCalledWith('No saveable nodes in this graph.');+ expect(workflowUiAdapter.notifications.success).not.toHaveBeenCalled();+ });++ it('disables "Save to workflow library" while invocation templates are still loading', async () => {+ templatesSnapshotRef.current = { error: null, status: 'loading', templates: {} };++ await renderDialog(FIXTURE_SOURCE);+ await openAsMenu();++ const item = findMenuItemWithText('Save to workflow library');+ expect(item).not.toBeUndefined();+ expect(item?.getAttribute('aria-disabled')).toBe('true');+ });++ it('truncates a long resolved-input string and exposes the full value via title', async () => {+ await renderDialog(LONG_VALUE_SOURCE);++ await switchToMode('list');+ await clickButtonWithText('note');++ const truncated = `${LONG_STRING_VALUE.slice(0, 40)}…`;+ const valueElement = [...document.querySelectorAll('dd')].find((element) => element.textContent === truncated);++ expect(valueElement).not.toBeUndefined();+ expect(valueElement?.getAttribute('title')).toBe(LONG_STRING_VALUE);+ // The untruncated value never appears verbatim in the rendered text.+ expect(document.body.textContent ?? '').not.toContain(LONG_STRING_VALUE);+ });});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 6b34025fe2..96b13f646d 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@@ -115,8 +115,22 @@ export const GraphPreviewDialog = ({});}, [graphPreview, closeAndReset, sourceId]);+ // Consumed by `handleFlowInit` the next time the flow mounts. Set by+ // `selectAndReveal` when it fires while the flow isn't the visible pane —+ // `flowInstanceRef` still points at the *previous* mount's (destroyed)+ // instance until then, so fitting it immediately would no-op on a dead+ // instance instead of the one that's about to render.+ const pendingRevealNodeIdRef = useRef<string | null>(null);+const handleFlowInit = useCallback((instance: ReactFlowInstance) => {flowInstanceRef.current = instance;++ const pendingNodeId = pendingRevealNodeIdRef.current;++ if (pendingNodeId !== null) {+ pendingRevealNodeIdRef.current = null;+ void instance.fitView({ ...SELECT_AND_REVEAL_FIT_VIEW_OPTIONS, nodes: [{ id: pendingNodeId }] });+ }}, []);const handleFlowNodeSelect = useCallback((nodeId: string | null) => setSelectedNodeId(nodeId), []);const handleBack = useCallback(() => setSelectedNodeId(null), []);@@ -125,19 +139,30 @@ export const GraphPreviewDialog = ({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');+ // Selects a node and 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 — but if the flow isn't the mounted pane right+ // now (`mode` is still 'list'/'json' at call time), setting `mode` below+ // only *starts* the remount; the fresh instance doesn't exist until+ // `handleFlowInit` runs next render. Stash the id for that instead of+ // fitting a stale/dead instance.+ const selectAndReveal = useCallback(+ (nodeId: string) => {+ setSelectedNodeId(nodeId);- const instance = flowInstanceRef.current;+ const instance = flowInstanceRef.current;+ const isFlowMounted = mode === 'graph' && instance !== null;- if (instance) {- void instance.fitView({ ...SELECT_AND_REVEAL_FIT_VIEW_OPTIONS, nodes: [{ id: nodeId }] });- }- }, []);+ if (isFlowMounted) {+ void instance.fitView({ ...SELECT_AND_REVEAL_FIT_VIEW_OPTIONS, nodes: [{ id: nodeId }] });+ } else {+ pendingRevealNodeIdRef.current = nodeId;+ }++ setMode('graph');+ },+ [mode]+ );const copyJson = useCallback(() => {const json = JSON.stringify(graph?.backendGraph ?? graph, null, 2);@@ -151,10 +176,14 @@ export const GraphPreviewDialog = ({clearTimeout(copyResetTimerRef.current);}+ // Deliberately not a `useEffect` cleanup (unlike `JsonPreview`'s+ // equivalent timer) — the no-useEffect rule keeps this in the+ // handler, and a `setHasCopied` that fires after unmount is a no-op+ // in React 18+, not a leak.copyResetTimerRef.current = setTimeout(() => setHasCopied(false), COPY_RESET_DELAY_MS);})- .catch(() => toaster.create({ title: 'Failed to copy JSON', type: 'error' }));- }, [graph]);+ .catch(() => toaster.create({ title: t('graphPreview.copyFailed'), type: 'error' }));+ }, [graph, t]);const jsonLabel = useMemo(() => t('graphPreview.graphJsonLabel', { title: sourceLabel }), [t, sourceLabel]);const subtitle = useMemo(() => {@@ -220,18 +249,20 @@ export const GraphPreviewDialog = ({/>)}</PreviewPane>- <GraphPreviewSidePanel- source={source}- selectedNode={selectedNode}- onBack={handleBack}- onProvenanceClick={handleProvenanceClick}- />+ {mode === 'graph' ? (+ <GraphPreviewSidePanel+ source={source}+ selectedNode={selectedNode}+ onBack={handleBack}+ onProvenanceClick={handleProvenanceClick}+ />+ ) : null}</Box>)}</Dialog.Body><Dialog.Footer justifyContent="space-between"><Box display="flex" gap="2">- <Button size="xs" variant="outline" onClick={copyJson}>+ <Button disabled={!graph} size="xs" variant="outline" onClick={copyJson}><Iconas={hasCopied ? CheckIcon : CopyIcon}boxSize="3.5"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsxindex 0092617f41..c94b10e13b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx@@ -85,7 +85,19 @@ export const GraphPreviewOpenAsMenu = ({}, [graph, templatesSnapshot, notifications, t, workflows, graphPreview, onClose]);const saveToLibrary = useCallback(async () => {- const { document } = previewGraphToDocument(graph, templatesSnapshot.templates);+ const { document, skippedNodeTypes } = previewGraphToDocument(graph, templatesSnapshot.templates);++ if (document.nodes.length === 0) {+ notifications.error(t('graphPreview.saveToLibraryFailed'));+ return;+ }++ if (skippedNodeTypes.length > 0) {+ notifications.info(+ t('graphPreview.nodesSkipped', { count: skippedNodeTypes.length, types: skippedNodeTypes.join(', ') })+ );+ }+document.name = graph.label ?? sourceLabel;const id = await saveDocumentAsNew(document);@@ -118,7 +130,12 @@ export const GraphPreviewOpenAsMenu = ({<MenuItemBody hint={t('graphPreview.editInEditorHint')} label={t('graphPreview.editInEditor')} /></Menu.Item>) : null}- <Menu.Item value="save-to-library" onClick={handleSaveToLibrary}>+ <Menu.Item+ _disabled={DISABLED_PROPS}+ disabled={!isTemplatesLoaded}+ value="save-to-library"+ onClick={handleSaveToLibrary}+ ><Icon as={BookmarkIcon} boxSize="3.5" /><MenuItemBody hint={t('graphPreview.saveToLibraryHint')} label={t('graphPreview.saveToLibrary')} /></Menu.Item>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 6be86910bd..884808c74c 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@@ -80,8 +80,19 @@ const GraphSummary = ({ source }: { source: GraphPreviewSourceState }) => {);};-/** 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 => {+const TRUNCATE_LENGTH = 40;++/** Truncates a display string past {@link TRUNCATE_LENGTH}, reporting whether it did — callers use that to decide whether the untruncated value needs a `title` tooltip. */+const truncateForDisplay = (value: string): { display: string; isTruncated: boolean } => {+ if (value.length <= TRUNCATE_LENGTH) {+ return { display: value, isTruncated: false };+ }++ return { display: `${value.slice(0, TRUNCATE_LENGTH)}…`, isTruncated: true };+};++/** string/number/boolean → `String`; object with a string `name` → the name; other object/array → JSON; `undefined` → `null` (caller skips the row). Untruncated — pass through {@link truncateForDisplay} for display. */+const stringifyResolvedValue = (value: unknown): string | null => {if (value === undefined) {return null;}@@ -94,9 +105,7 @@ const formatResolvedValue = (value: unknown): string | null => {return (value as { name: string }).name;}- const json = JSON.stringify(value);-- return json.length > 40 ? `${json.slice(0, 40)}…` : json;+ return JSON.stringify(value);};const getDistinctProvenanceLabels = (node: PreviewGraphNode, source: GraphPreviewSourceState): string[] => {@@ -146,7 +155,7 @@ const NodeInspector = ({const resolvedFields = Object.entries(node.inputs).map(([field, value]) => ({field,- value: source.resolvedInputOverrides?.[node.id]?.[field] ?? formatResolvedValue(value),+ value: source.resolvedInputOverrides?.[node.id]?.[field] ?? stringifyResolvedValue(value),})).filter((entry): entry is { field: string; value: string } => entry.value !== null);@@ -196,14 +205,18 @@ const NodeInspector = ({{t('graphPreview.resolvedInputs')}</Text><DataList.Root gap="1.5" orientation="horizontal" size="sm">- {resolvedFields.map(({ field, value }) => (- <DataList.Item key={field}>- <DataList.ItemLabel fontSize="2xs">{field}</DataList.ItemLabel>- <DataList.ItemValue fontSize="2xs" minW="0">- {value}- </DataList.ItemValue>- </DataList.Item>- ))}+ {resolvedFields.map(({ field, value }) => {+ const { display, isTruncated } = truncateForDisplay(value);++ return (+ <DataList.Item key={field}>+ <DataList.ItemLabel fontSize="2xs">{field}</DataList.ItemLabel>+ <DataList.ItemValue fontSize="2xs" minW="0" title={isTruncated ? value : undefined}>+ {display}+ </DataList.ItemValue>+ </DataList.Item>+ );+ })}</DataList.Root></Stack>