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 open-as actions and json download
joshistoast63ab53764766
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex a98cc88876..3802b58472 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -549,11 +549,16 @@"copied": "Copied","copyJson": "Copy JSON","destination": "Destination",+ "downloadJson": "Download JSON",+ "downloadJsonHint": "For bug reports and sharing","edges": "Edges","edgesIn_one": "in · {{count}} input from {{sources}}","edgesIn_other": "in · {{count}} inputs from {{sources}}","edgesInNone": "in · none","edgesOut": "out · {{field}} → {{target}}",+ "editInEditor": "Edit in workflow editor",+ "editInEditorFailed": "No editable nodes in this graph.",+ "editInEditorHint": "Replaces the current workflow","graph": "Graph","graphJsonLabel": "{{title}} graph JSON","inputCount_one": "{{count}} input",@@ -566,10 +571,14 @@"model": "Model","noCompiledGraph": "No compiled graph is available for \"{{graphId}}\" yet.","nodes": "Nodes",+ "nodesSkipped_one": "Skipped {{count}} node type without a template: {{types}}",+ "nodesSkipped_other": "Skipped {{count}} node types without templates: {{types}}","nodeSummary": {"denoise": "{{steps}} steps · cfg {{cfg}}","noise": "{{width}} × {{height}}"},+ "openAs": "Open as",+ "openedFromPreview": "Opened from graph preview","provenance": {"cfgScale": "Generate → CFG scale","clipSkip": "Generate → CLIP skip",@@ -584,6 +593,9 @@"steps": "Generate → Steps"},"resolvedInputs": "Resolved inputs",+ "savedToLibrary": "Saved to workflow library",+ "saveToLibrary": "Save to workflow library",+ "saveToLibraryHint": "Reusable, leaves this project alone","scheduler": "Scheduler","seed": "Seed","seedRandomValue": "random",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 b5c71f305e..b0c069baf1 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,4 +1,8 @@-import type { GraphPreviewSourceState, WorkflowPreviewGraph } from '@features/workflow/ui/contracts';+import type {+ GraphPreviewSourceState,+ WorkflowInvocationSourceId,+ WorkflowPreviewGraph,+} from '@features/workflow/ui/contracts';import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';import { ChakraProvider } from '@chakra-ui/react';@@ -19,6 +23,77 @@ vi.mock('./GraphPreviewFlow', () => ({},}));+// `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(() => {+ const fieldInput = (name: string, defaultValue: unknown) => ({+ default: defaultValue,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any' as const,+ maximum: null,+ minimum: null,+ multipleOf: null,+ name,+ options: null,+ required: false,+ title: name,+ type: { batch: false, cardinality: 'SINGLE' as const, name: 'IntegerField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelFormat: null,+ uiModelType: null,+ uiOrder: null,+ });+ const invocationTemplate = (type: string, inputs: Record<string, ReturnType<typeof fieldInput>>) => ({+ category: 'test',+ classification: 'stable',+ description: '',+ inputs,+ nodePack: 'invokeai',+ outputs: {},+ outputType: `${type}_output`,+ tags: [],+ title: type,+ type,+ useCache: true,+ version: '1.0.0',+ });++ 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', {}),+ },+ },+ };+});++vi.mock('@platform/browser/downloadBlob', () => downloads);++// The "Open as" menu (`GraphPreviewOpenAsMenu`) reads the invocation+// templates snapshot through the reactive hook, not the plain getter, so its+// disabled state can update live if the menu opens while templates are still+// loading — this stubs that hook (and the getter, for symmetry) with a+// 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,+}));+// The real client fetches en.json over HTTP (`platform/i18n/client.ts`), which// this browser test never boots. Stub `t` with the subset of English strings// this dialog renders, so assertions check real copy instead of raw dotted@@ -31,10 +106,15 @@ const TRANSLATIONS: Record<string, string> = {'graphPreview.copied': 'Copied','graphPreview.copyJson': 'Copy JSON','graphPreview.destination': 'Destination',+ 'graphPreview.downloadJson': 'Download JSON',+ 'graphPreview.downloadJsonHint': 'For bug reports and sharing','graphPreview.edges': 'Edges','graphPreview.edgesIn': 'in · {{count}} inputs from {{sources}}','graphPreview.edgesInNone': 'in · none','graphPreview.edgesOut': 'out · {{field}} → {{target}}',+ 'graphPreview.editInEditor': 'Edit in workflow editor',+ 'graphPreview.editInEditorFailed': 'No editable nodes in this graph.',+ 'graphPreview.editInEditorHint': 'Replaces the current workflow','graphPreview.graph': 'Graph','graphPreview.graphJsonLabel': '{{title}} graph JSON','graphPreview.inputCount': '{{count}} inputs',@@ -46,7 +126,12 @@ const TRANSLATIONS: Record<string, string> = {'graphPreview.nodeSummary.denoise': '{{steps}} steps · cfg {{cfg}}','graphPreview.nodeSummary.noise': '{{width}} × {{height}}','graphPreview.nodes': 'Nodes',+ 'graphPreview.openAs': 'Open as',+ 'graphPreview.openedFromPreview': 'Opened from graph preview','graphPreview.resolvedInputs': 'Resolved inputs',+ 'graphPreview.savedToLibrary': 'Saved to workflow library',+ 'graphPreview.saveToLibrary': 'Save to workflow library',+ 'graphPreview.saveToLibraryHint': 'Reusable, leaves this project alone','graphPreview.selectNode': 'Select a node for details.','graphPreview.setBy': 'Set by','graphPreview.showNode': 'show node',@@ -129,10 +214,35 @@ const preferencesSnapshot = {workflowValidateConnections: true,};-const createWorkflowUiAdapter = (): WorkflowUiAdapter =>- ({+// A stable object per adapter instance — `useWorkflowProjectSelector`+// (`useSaveWorkflowToLibrary`, called by `GraphPreviewOpenAsMenu`) runs this+// through `useSyncExternalStoreWithSelector`'s shallow-equality check, which+// would otherwise see a "changed" snapshot on every render (new object+// identity, same content) and force an infinite re-render loop — the same+// reason `preferencesSnapshot` above is hoisted rather than built inline.+const createProjectSnapshot = () => ({+ galleryValues: {},+ graphHistory: [],+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph: { edges: [], nodes: [], version: 1 as const },+ workflowValues: {},+});++const createWorkflowUiAdapter = (): WorkflowUiAdapter => {+ const projectSnapshot = createProjectSnapshot();++ return {capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe: () => () => {} },- commands: {},+ commands: {+ bindLibraryWorkflow: vi.fn(),+ editGraph: vi.fn(),+ redo: vi.fn(),+ replace: vi.fn(),+ restoreSnapshot: vi.fn(),+ saveSnapshot: vi.fn(),+ undo: vi.fn(),+ },getProjectGraph: () => ({ edges: [], nodes: [], version: 1 as const }),nodeExecution: { get: () => null, subscribe: () => () => {} },notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },@@ -143,19 +253,13 @@ const createWorkflowUiAdapter = (): WorkflowUiAdapter =>},preferences: { getSnapshot: () => preferencesSnapshot, subscribe: () => () => {} },project: {- getSnapshot: () => ({- galleryValues: {},- graphHistory: [],- id: 'project-1',- isWorkflowRunning: false,- projectGraph: { edges: [], nodes: [], version: 1 as const },- workflowValues: {},- }),+ getSnapshot: () => projectSnapshot,subscribe: () => () => {},},registerModalHotkeyLayer: vi.fn(() => vi.fn()),widgets: { open: vi.fn(), patchValues: vi.fn() },- }) as unknown as WorkflowUiAdapter;+ } as unknown as WorkflowUiAdapter;+};const createGraphPreviewPort = (): WorkflowGraphPreviewPort => ({focusSource: vi.fn(),@@ -169,10 +273,13 @@ describe('GraphPreviewDialog', () => {let root: Root;let onOpenChange: (isOpen: boolean) => void;let graphPreviewPort: WorkflowGraphPreviewPort;+ let workflowUiAdapter: WorkflowUiAdapter;- const renderDialog = async (source: GraphPreviewSourceState, isOpen = true) => {- const workflowUiAdapter = createWorkflowUiAdapter();-+ const renderDialog = async (+ source: GraphPreviewSourceState,+ isOpen = true,+ sourceId: WorkflowInvocationSourceId = 'generate'+ ) => {await act(() => {root.render(<StrictMode>@@ -183,7 +290,7 @@ describe('GraphPreviewDialog', () => {graphId="preview-graph-id"isOpen={isOpen}source={source}- sourceId="generate"+ sourceId={sourceId}sourceLabel="Generate"onOpenChange={onOpenChange}/>@@ -201,10 +308,17 @@ describe('GraphPreviewDialog', () => {root = createRoot(host);onOpenChange = vi.fn((_isOpen: boolean) => {});graphPreviewPort = createGraphPreviewPort();+ workflowUiAdapter = createWorkflowUiAdapter();+ downloads.downloadBlob.mockReset();+ downloads.downloadText.mockReset();});afterEach(async () => {await act(() => root.unmount());+ // The "Open as" menu's content portals to `document.body`, outside the+ // React root this suite unmounts above — sweep it so a leftover node+ // from one test can't answer a `[role="menuitem"]` query in the next.+ document.querySelectorAll('[data-scope="menu"]').forEach((element) => element.remove());host.remove();});@@ -230,6 +344,32 @@ describe('GraphPreviewDialog', () => {});};+ // Opens the "Open as" menu. Chakra's `Menu.Content` is lazy-mounted and+ // its open transition runs on a timer, so the click alone isn't enough —+ // give the portal a beat to attach before querying for items.+ const openAsMenu = async () => {+ await clickButtonWithText('Open as');+ await act(async () => {+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 40);+ });+ });+ };++ const findMenuItemWithText = (text: string) =>+ [...document.querySelectorAll('[role="menuitem"]')].find((candidate) =>+ (candidate.textContent ?? '').includes(text)+ );++ const clickMenuItemWithText = async (text: string) => {+ const item = findMenuItemWithText(text);+ expect(item).not.toBeUndefined();++ await act(() => {+ (item as HTMLElement | undefined)?.click();+ });+ };+it('renders summary rows, node count, and the live subtitle', async () => {await renderDialog(FIXTURE_SOURCE);@@ -342,4 +482,43 @@ describe('GraphPreviewDialog', () => {expect(text).toContain('Select a node for details.');expect(text).not.toContain('Resolved inputs');});++ it('Open as → Edit in workflow editor replaces the document, opens the editor, closes the dialog', async () => {+ await renderDialog(FIXTURE_SOURCE);++ await openAsMenu();+ await clickMenuItemWithText('Edit in workflow editor');++ expect(workflowUiAdapter.commands.replace).toHaveBeenCalledTimes(1);+ const [document_, label] = vi.mocked(workflowUiAdapter.commands.replace).mock.calls[0] ?? [];+ expect(document_?.nodes).toHaveLength(3);+ expect(label).toBe('Opened from graph preview');+ expect(graphPreviewPort.openWorkflowEditor).toHaveBeenCalledTimes(1);+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('Open as → Download JSON downloads the backend graph', async () => {+ await renderDialog(FIXTURE_SOURCE);++ await openAsMenu();+ await clickMenuItemWithText('Download JSON');++ expect(downloads.downloadText).toHaveBeenCalledTimes(1);+ const [content, fileName, type] = vi.mocked(downloads.downloadText).mock.calls[0] ?? [];+ // The fixture graph has no `backendGraph`, so this exercises the+ // `graph.backendGraph ?? graph` fallback, not just the happy path.+ expect(content).toContain('"denoise_latents"');+ expect(fileName).toBe('graph.json');+ expect(type).toBe('application/json');+ });++ it('hides Edit in workflow editor for the workflow source', async () => {+ await renderDialog(FIXTURE_SOURCE, true, 'workflow');++ await openAsMenu();++ expect(findMenuItemWithText('Edit in workflow editor')).toBeUndefined();+ expect(findMenuItemWithText('Save to workflow library')).not.toBeUndefined();+ expect(findMenuItemWithText('Download JSON')).not.toBeUndefined();+ });});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 b8642866a3..6b34025fe2 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@@ -5,12 +5,13 @@ import type { ReactNode } from 'react';import { Box, Dialog, Icon, Portal, SegmentGroup, Stack, Text } from '@chakra-ui/react';import { useWorkflowGraphPreview } from '@features/workflow/ui/WorkflowUiContext';import { Button, JsonPreview, toaster } from '@platform/ui';-import { CheckIcon, CopyIcon, SquareDashedIcon } from 'lucide-react';+import { CheckIcon, ChevronUpIcon, CopyIcon, SquareDashedIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { GraphPreviewFlow } from './GraphPreviewFlow';import { GraphPreviewList } from './GraphPreviewList';+import { GraphPreviewOpenAsMenu } from './GraphPreviewOpenAsMenu';import { GraphPreviewSidePanel } from './GraphPreviewSidePanel';interface GraphPreviewDialogProps {@@ -229,14 +230,29 @@ export const GraphPreviewDialog = ({)}</Dialog.Body><Dialog.Footer justifyContent="space-between">- <Button size="xs" variant="outline" onClick={copyJson}>- <Icon- as={hasCopied ? CheckIcon : CopyIcon}- boxSize="3.5"- color={hasCopied ? 'green.solid' : undefined}- />- {hasCopied ? t('graphPreview.copied') : t('graphPreview.copyJson')}- </Button>+ <Box display="flex" gap="2">+ <Button size="xs" variant="outline" onClick={copyJson}>+ <Icon+ as={hasCopied ? CheckIcon : CopyIcon}+ boxSize="3.5"+ color={hasCopied ? 'green.solid' : undefined}+ />+ {hasCopied ? t('graphPreview.copied') : t('graphPreview.copyJson')}+ </Button>+ {graph ? (+ <GraphPreviewOpenAsMenu+ graph={graph}+ sourceId={sourceId}+ sourceLabel={sourceLabel}+ onClose={closeDialog}+ >+ <Button size="xs" variant="outline">+ {t('graphPreview.openAs')}+ <Icon as={ChevronUpIcon} boxSize="3.5" />+ </Button>+ </GraphPreviewOpenAsMenu>+ ) : null}+ </Box><Box display="flex" gap="2">{dialogRoute ? (<Buttondiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsxnew file mode 100644index 0000000000..0092617f41--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx@@ -0,0 +1,134 @@+import type { WorkflowInvocationSourceId, WorkflowPreviewGraph } from '@features/workflow/ui/contracts';+import type { ReactNode } from 'react';++import { Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { previewGraphToDocument } from '@features/workflow/core/graphToDocument';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { useSaveWorkflowToLibrary } from '@features/workflow/ui/library/useSaveWorkflowToLibrary';+import {+ useWorkflowGraphPreview,+ useWorkflowHostCommands,+ useWorkflowNotifications,+} from '@features/workflow/ui/WorkflowUiContext';+import { downloadText } from '@platform/browser/downloadBlob';+import { BookmarkIcon, DownloadIcon, PencilRulerIcon } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++const MENU_POSITIONING = { placement: 'top-end' } as const;+const DISABLED_PROPS = { opacity: 0.4 };++interface GraphPreviewOpenAsMenuProps {+ children: ReactNode;+ graph: WorkflowPreviewGraph;+ sourceId?: WorkflowInvocationSourceId;+ sourceLabel: string;+ /** Dialog close after a successful "edit in editor". */+ onClose: () => void;+}++const MenuItemBody = ({ hint, label }: { hint: string; label: string }) => (+ <Stack gap="0" minW="0">+ <Menu.ItemText>{label}</Menu.ItemText>+ <Text color="fg.subtle" fontSize="2xs">+ {hint}+ </Text>+ </Stack>+);++/**+ * The graph preview dialog's "Open as" menu — three ways to hand a+ * read-only preview graph off to something that keeps it: convert it into an+ * editable document and load it into the workflow editor, save it to the+ * workflow library without touching the active project, or download the raw+ * JSON. The trigger button lives in the dialog (it needs `@platform/ui`'s+ * `Button`); this file stays out of that import so it doesn't add to that+ * package's fan-in.+ */+export const GraphPreviewOpenAsMenu = ({+ children,+ graph,+ sourceId,+ sourceLabel,+ onClose,+}: GraphPreviewOpenAsMenuProps) => {+ const { t } = useTranslation();+ const { workflows } = useWorkflowHostCommands();+ const graphPreview = useWorkflowGraphPreview();+ const notifications = useWorkflowNotifications();+ const { saveDocumentAsNew } = useSaveWorkflowToLibrary();+ // A hook (not `getInvocationTemplatesSnapshot()`) so the "Edit in workflow+ // editor" item's disabled state updates live if the menu is opened while+ // templates are still loading.+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const canEditInEditor = sourceId !== 'workflow';+ const isTemplatesLoaded = templatesSnapshot.status === 'loaded';++ const handleEditInEditor = useCallback(() => {+ const { document, skippedNodeTypes } = previewGraphToDocument(graph, templatesSnapshot.templates);++ if (document.nodes.length === 0) {+ notifications.error(t('graphPreview.editInEditorFailed'));+ return;+ }++ if (skippedNodeTypes.length > 0) {+ notifications.info(+ t('graphPreview.nodesSkipped', { count: skippedNodeTypes.length, types: skippedNodeTypes.join(', ') })+ );+ }++ // `replace` emits its own success notification and undo entry.+ workflows.replace(document, t('graphPreview.openedFromPreview'));+ graphPreview.openWorkflowEditor();+ onClose();+ }, [graph, templatesSnapshot, notifications, t, workflows, graphPreview, onClose]);++ const saveToLibrary = useCallback(async () => {+ const { document } = previewGraphToDocument(graph, templatesSnapshot.templates);+ document.name = graph.label ?? sourceLabel;++ const id = await saveDocumentAsNew(document);++ if (id !== null) {+ notifications.success(t('graphPreview.savedToLibrary'));+ }+ }, [graph, templatesSnapshot, sourceLabel, saveDocumentAsNew, notifications, t]);+ const handleSaveToLibrary = useCallback(() => void saveToLibrary(), [saveToLibrary]);++ const handleDownloadJson = useCallback(() => {+ const fileName = `${(graph.label ?? 'graph').trim().replaceAll(/\s+/g, '-').toLowerCase()}.json`;+ downloadText(JSON.stringify(graph.backendGraph ?? graph, null, 2), fileName, 'application/json');+ }, [graph]);++ return (+ <Menu.Root positioning={MENU_POSITIONING}>+ <Menu.Trigger asChild>{children}</Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <Menu.Content minW="16rem">+ {canEditInEditor ? (+ <Menu.Item+ _disabled={DISABLED_PROPS}+ disabled={!isTemplatesLoaded}+ value="edit-in-editor"+ onClick={handleEditInEditor}+ >+ <Icon as={PencilRulerIcon} boxSize="3.5" />+ <MenuItemBody hint={t('graphPreview.editInEditorHint')} label={t('graphPreview.editInEditor')} />+ </Menu.Item>+ ) : null}+ <Menu.Item value="save-to-library" onClick={handleSaveToLibrary}>+ <Icon as={BookmarkIcon} boxSize="3.5" />+ <MenuItemBody hint={t('graphPreview.saveToLibraryHint')} label={t('graphPreview.saveToLibrary')} />+ </Menu.Item>+ <Menu.Item value="download-json" onClick={handleDownloadJson}>+ <Icon as={DownloadIcon} boxSize="3.5" />+ <MenuItemBody hint={t('graphPreview.downloadJsonHint')} label={t('graphPreview.downloadJson')} />+ </Menu.Item>+ </Menu.Content>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};