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): convert preview graphs to editable workflow documents
joshistoast9b6ad3d002c2
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.test.tsnew file mode 100644index 0000000000..e9456ced46--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it } from 'vitest';++import type { FieldInputTemplate, InvocationTemplate } from './types';++import { compileProjectGraph } from './buildGraph';+import { previewGraphToDocument, type PreviewGraphLike } from './graphToDocument';+import { isInvocationNode } from './types';++const input = (name: string, overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name,+ options: null,+ required: false,+ title: name,+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelFormat: null,+ uiModelType: null,+ uiOrder: null,+ ...overrides,+});++const template = (type: string, inputs: Record<string, FieldInputTemplate>): InvocationTemplate => ({+ category: 'test',+ classification: 'stable',+ description: '',+ inputs,+ nodePack: 'invokeai',+ outputs: {+ value: {+ description: '',+ name: 'value',+ title: 'Value',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ },+ },+ outputType: `${type}_output`,+ tags: [],+ title: type,+ type,+ useCache: true,+ version: '1.0.0',+});++const templates = {+ denoise: template('denoise', {+ seed: input('seed', { default: 0 }),+ steps: input('steps', { default: 30 }),+ }),+ integer: template('integer', {+ value: input('value', { default: 0 }),+ }),+};++const graph: PreviewGraphLike = {+ edges: [+ {+ id: 'ignored',+ sourceField: 'value',+ sourceNodeId: 'seed',+ targetField: 'seed',+ targetNodeId: 'denoise_latents',+ },+ {+ id: 'ignored-2',+ sourceField: 'value',+ sourceNodeId: 'seed',+ targetField: 'value',+ targetNodeId: 'mystery',+ },+ ],+ nodes: [+ { id: 'seed', inputs: { use_cache: false, value: 123 }, type: 'integer' },+ { id: 'denoise_latents', inputs: { is_intermediate: true, steps: 28 }, type: 'denoise' },+ { id: 'mystery', inputs: {}, type: 'unknown_type' },+ ],+};++describe('previewGraphToDocument', () => {+ it('converts a preview graph into an editable document, skipping unknown node types', () => {+ const { document, skippedNodeTypes } = previewGraphToDocument(graph, templates);++ expect(skippedNodeTypes).toEqual(['unknown_type']);+ expect(document.nodes.map((node) => node.id)).toEqual(['seed', 'denoise_latents']);++ const denoise = document.nodes.filter(isInvocationNode).find((node) => node.id === 'denoise_latents');++ expect(denoise?.data.inputs.steps.value).toBe(28); // literal copied+ expect(denoise?.data.inputs.seed.value).toBeUndefined(); // connected input cleared+ expect(document.edges).toHaveLength(1);+ expect(document.edges[0]).toMatchObject({+ source: 'seed',+ sourceHandle: 'value',+ target: 'denoise_latents',+ targetHandle: 'seed',+ });++ const seed = document.nodes.filter(isInvocationNode).find((node) => node.id === 'seed');++ expect(seed?.data.useCache).toBe(false); // is_intermediate/use_cache lifted out of inputs+ expect(seed?.data.inputs.value.value).toBe(123);+ expect(seed?.position.x).toBe(0);+ expect(denoise?.position.x).toBe(300); // layered layout+ });++ it('round-trips through compileProjectGraph back to the fixture edge', () => {+ const { document } = previewGraphToDocument(graph, templates);+ const compiled = compileProjectGraph(document, templates);++ expect(compiled.edges).toHaveLength(1);+ expect(compiled.edges[0]).toMatchObject({ sourceNodeId: 'seed', targetField: 'seed' });+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.ts b/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.tsnew file mode 100644index 0000000000..36322488e3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/graphToDocument.ts@@ -0,0 +1,125 @@+import type { InvocationTemplates, ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from './types';++import { buildInvocationNode, createProjectGraph, createWorkflowId } from './document';+import { getLayeredPositions } from './graphLayout';++/**+ * Structural shape of the read-only preview graph (Task 1's contract graph,+ * as rendered by `GraphPreviewFlow.tsx`). Kept structural rather than+ * importing the ui contract so this module stays a pure `core` dependency.+ */+export interface PreviewGraphLike {+ label?: string;+ nodes: Array<{ id: string; type: string; inputs: Record<string, unknown> }>;+ edges: Array<{ id: string; sourceField: string; sourceNodeId: string; targetField: string; targetNodeId: string }>;+}++export interface PreviewGraphDocumentResult {+ document: ProjectGraphState;+ skippedNodeTypes: string[];+}++/** Converts a read-only preview graph into an editable project graph document. */+export const previewGraphToDocument = (+ graph: PreviewGraphLike,+ templates: InvocationTemplates+): PreviewGraphDocumentResult => {+ const skippedNodeTypes: string[] = [];+ const seenSkippedTypes = new Set<string>();+ // Positions are derived from the full graph (skipped nodes still occupy a+ // depth/row), matching Task 6's documented behavior rather than inventing+ // a hint mechanism to exclude them.+ const positions = getLayeredPositions(+ graph.nodes.map((node) => ({ id: node.id })),+ graph.edges.map((edge) => ({ sourceNodeId: edge.sourceNodeId, targetNodeId: edge.targetNodeId }))+ );++ const nodes: WorkflowInvocationNode[] = [];++ for (const graphNode of graph.nodes) {+ const template = templates[graphNode.type];++ if (!template) {+ if (!seenSkippedTypes.has(graphNode.type)) {+ seenSkippedTypes.add(graphNode.type);+ skippedNodeTypes.push(graphNode.type);+ }+ continue;+ }++ const node = buildInvocationNode(template, positions[graphNode.id] ?? { x: 0, y: 0 });++ node.id = graphNode.id;++ const isIntermediate = graphNode.inputs.is_intermediate;++ if (typeof isIntermediate === 'boolean') {+ node.data.isIntermediate = isIntermediate;+ }++ const useCache = graphNode.inputs.use_cache;++ if (typeof useCache === 'boolean') {+ node.data.useCache = useCache;+ }++ for (const key of Object.keys(template.inputs)) {+ const value = graphNode.inputs[key];++ if (value === undefined) {+ continue;+ }++ const instance = node.data.inputs[key];++ if (instance) {+ instance.value = structuredClone(value);+ }+ }++ nodes.push(node);+ }++ const nodeIds = new Set(nodes.map((node) => node.id));+ const edges: WorkflowEdge[] = [];++ for (const graphEdge of graph.edges) {+ if (!nodeIds.has(graphEdge.sourceNodeId) || !nodeIds.has(graphEdge.targetNodeId)) {+ continue;+ }++ const targetNode = nodes.find((node) => node.id === graphEdge.targetNodeId);+ const targetTemplate = targetNode ? templates[targetNode.data.type] : undefined;++ if (!targetTemplate || !(graphEdge.targetField in targetTemplate.inputs)) {+ continue;+ }++ edges.push({+ id: createWorkflowId('edge'),+ source: graphEdge.sourceNodeId,+ sourceHandle: graphEdge.sourceField,+ target: graphEdge.targetNodeId,+ targetHandle: graphEdge.targetField,+ type: 'default',+ });+ }++ // Clear literal values on connected inputs after wiring, so a stale direct+ // value can't shadow the edge during compilation.+ for (const edge of edges) {+ const targetNode = nodes.find((node) => node.id === edge.target);+ const instance = targetNode?.data.inputs[edge.targetHandle];++ if (instance) {+ instance.value = undefined;+ }+ }++ const document = createProjectGraph(createWorkflowId('workflow'), graph.label || 'Untitled Workflow');++ document.nodes = nodes;+ document.edges = edges;++ return { document, skippedNodeTypes };+};