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(workflow): preserve snapshot layout and full resolution
JPPhoto4f5989407737
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsxindex 3148290e7e..9b14dbe4f8 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx@@ -346,6 +346,82 @@ describe('InvocationFlowNode output preview', () => {});});+ it('bounds snapshots by rendered nodes instead of live editor result height', async () => {+ const execution = createExecutionPort();+ execution.set(completed(outputImage(400, 800)));+ const adapter = createAdapter(execution.port);+ let capturedHeight: number | undefined;+ exportMocks.toBlob.mockImplementation((_clone: HTMLElement, options: { height: number }) => {+ capturedHeight = options.height;+ return Promise.resolve(new Blob(['png'], { type: 'image/png' }));+ });++ await render(adapter);+ const liveRect = host.querySelector<HTMLElement>('.react-flow__node')!.getBoundingClientRect();+ const liveBounds = { x: 20, y: 20, width: liveRect.width, height: liveRect.height };+ await render(adapter, 1, true);+ const snapshotRect = host.querySelector<HTMLElement>('.react-flow__node')!.getBoundingClientRect();+ expect(snapshotRect.height).toBeLessThan(liveRect.height);++ await exportWorkflowAsPng({+ bounds: liveBounds,+ fallbackWorkflowName: 'Untitled Workflow',+ flowElement: host.querySelector<HTMLElement>('.react-flow')!,+ workflowName: 'Pristine bounds',+ });++ expect(capturedHeight).toBe(Math.ceil(snapshotRect.height + 200));+ });++ it.each([+ { kind: 'plain', uiComponent: null, value: 'Authored text' },+ { kind: 'multiline', uiComponent: 'textarea', value: 'First line\nSecond line' },+ { kind: 'long', uiComponent: 'textarea', value: 'UnbrokenText'.repeat(50) },+ { kind: 'empty', uiComponent: null, value: '' },+ ] as const)('preserves static text field entry boxes for $kind fields', async ({ uiComponent, value }) => {+ const textTemplate: InvocationTemplate = {+ ...template,+ inputs: {+ a: {+ ...template.inputs.a!,+ input: 'direct',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ uiComponent,+ },+ },+ };+ const textNode: WorkflowInvocationNode = {+ ...documentNode,+ data: { ...documentNode.data, inputs: { a: { label: '', name: 'a', value } } },+ };+ const graph = { ...projectGraph, nodes: [textNode] };+ const nodes = toFlowNodes(graph, [], { preview: textTemplate });+ const adapter = createAdapter(createExecutionPort().port, projectSnapshotFor(graph));+ let capturedText: string | null | undefined;+ let capturedBorderWidth: string | undefined;+ exportMocks.toBlob.mockImplementation((clone: HTMLElement) => {+ const entryBox = clone.querySelector<HTMLElement>('[data-workflow-export-field-value="true"]');+ capturedText = entryBox?.textContent;+ capturedBorderWidth = entryBox ? getComputedStyle(entryBox).borderTopWidth : undefined;+ expect(entryBox).not.toBeNull();+ expect(entryBox!.scrollWidth).toBeLessThanOrEqual(entryBox!.clientWidth);+ expect(clone.querySelector('input, textarea, button')).toBeNull();+ return Promise.resolve(new Blob(['png'], { type: 'image/png' }));+ });++ await render(adapter, 1, true, nodes);+ await exportWorkflowAsPng({+ bounds: { x: 20, y: 20, width: 300, height: 260 },+ fallbackWorkflowName: 'Untitled Workflow',+ flowElement: host.querySelector<HTMLElement>('.react-flow')!,+ workflowName: 'Text entry boxes',+ });++ expect(capturedText).toBe(value);+ expect(capturedBorderWidth).toBe('1px');+ expect(adapter.commands.editGraph).not.toHaveBeenCalled();+ });+it('renders authored notes as static text in snapshot exports', async () => {const noteBody = Array.from({ length: 60 }, (_, index) => `Snapshot note line ${index + 1}`).join('\n');const authoredNote = {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.browser.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.browser.test.tsindex f281f9eb08..0535a58d75 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.browser.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.browser.test.ts@@ -30,56 +30,64 @@ const countPaintedPixels = async (image: Blob): Promise<{ height: number; painte};describe('workflow image export in the browser', () => {- it('downloads a full resolution PNG containing the graph', async () => {- const clicked: { download: string }[] = [];- vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function mockClick(this: HTMLAnchorElement) {- clicked.push({ download: this.download });- });- const createObjectURL = vi.spyOn(URL, 'createObjectURL');+ it.each([+ { zoom: 1, nodeX: 20, nodeY: 20, width: 660, height: 520 },+ { zoom: 0.5, nodeX: 20, nodeY: 20, width: 660, height: 520 },+ { zoom: 2, nodeX: -20, nodeY: -40, width: 740, height: 570 },+ { zoom: 1, nodeX: 8500, nodeY: 20, width: 17420, height: 520, minimumPaintedPixels: 5000 },+ ])(+ 'downloads a tight full resolution PNG at zoom $zoom',+ async ({ zoom, nodeX, nodeY, width, height, minimumPaintedPixels = width * height * 0.01 }) => {+ const clicked: { download: string }[] = [];+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function mockClick(this: HTMLAnchorElement) {+ clicked.push({ download: this.download });+ });+ const createObjectURL = vi.spyOn(URL, 'createObjectURL');- host = document.createElement('div');- host.style.cssText = 'height:480px;position:relative;width:640px';- document.body.append(host);- const flowElement = document.createElement('div');- flowElement.className = 'react-flow';- flowElement.style.cssText = 'background-color:rgb(18, 20, 24);height:480px;position:relative;width:640px';- flowElement.innerHTML = `- <div class="react-flow__edges" style="height:100%;position:absolute;width:100%">- <svg height="120" width="200">- <path class="react-flow__edge-path" d="M 80 45 C 110 45 120 45 150 45" style="fill:none;stroke:rgb(220, 220, 220);stroke-width:4px" />- </svg>- </div>- <div class="react-flow__viewport" style="position:absolute;transform:translate(0px,0px) scale(1)">+ host = document.createElement('div');+ host.style.cssText = 'height:480px;position:relative;width:640px';+ document.body.append(host);+ const flowElement = document.createElement('div');+ flowElement.className = 'react-flow';+ flowElement.style.cssText = 'background-color:rgb(18, 20, 24);height:480px;position:relative;width:640px';+ flowElement.innerHTML = `+ <div class="react-flow__viewport" style="position:absolute;transform-origin:0 0;transform:translate(80px,-40px) scale(${zoom})">+ <div class="react-flow__edges" style="height:100%;position:absolute;width:100%">+ <svg height="120" width="200">+ <path class="react-flow__edge-path" d="M 80 45 C 110 45 120 45 150 45" style="fill:none;stroke:rgb(220, 220, 220);stroke-width:4px" />+ </svg>+ </div><div class="react-flow__nodes" style="height:120px;position:absolute;width:200px">- <div class="react-flow__node" style="height:60px;left:20px;position:absolute;top:20px;width:90px">+ <div class="react-flow__node" style="height:60px;left:${nodeX}px;position:absolute;top:${nodeY}px;width:90px"><div data-workflow-node-shell="true" style="background-color:rgb(192, 36, 52);height:60px;width:90px">Test node</div></div></div></div><div data-workflow-export-control="true" style="background-color:rgb(0, 255, 0);height:30px;position:absolute;width:30px"></div>`;- host.append(flowElement);+ host.append(flowElement);- await exportWorkflowAsPng({- bounds: { x: 0, y: 0, width: 200, height: 120 },- fallbackWorkflowName: 'Unnamed Workflow',- flowElement,- workflowName: 'Camera workflow',- });+ await exportWorkflowAsPng({+ bounds: { x: 0, y: 0, width: 200, height: 120 },+ fallbackWorkflowName: 'Unnamed Workflow',+ flowElement,+ workflowName: 'Camera workflow',+ });- expect(clicked).toEqual([{ download: 'Camera workflow.png' }]);- expect(createObjectURL).toHaveBeenCalledOnce();- expect(host.children).toHaveLength(1);+ expect(clicked).toEqual([{ download: 'Camera workflow.png' }]);+ expect(createObjectURL).toHaveBeenCalledOnce();+ expect(host.children).toHaveLength(1);- const capturedSource = createObjectURL.mock.calls[0]![0];- if (!(capturedSource instanceof Blob)) {- throw new Error('Workflow export did not download a Blob.');- }+ const capturedSource = createObjectURL.mock.calls[0]![0];+ if (!(capturedSource instanceof Blob)) {+ throw new Error('Workflow export did not download a Blob.');+ }- const blob = capturedSource;- expect(blob.type).toBe('image/png');- const { height, painted, width } = await countPaintedPixels(blob);- expect([width, height]).toEqual([800, 640]);- expect(painted).toBeGreaterThan(width * height * 0.01);- });+ const blob = capturedSource;+ expect(blob.type).toBe('image/png');+ const { height: imageHeight, painted, width: imageWidth } = await countPaintedPixels(blob);+ expect([imageWidth, imageHeight]).toEqual([width, height]);+ expect(painted).toBeGreaterThan(minimumPaintedPixels);+ }+ );});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.test.tsindex d27c5fe765..657d55d78c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.test.ts@@ -1,8 +1,6 @@import { describe, expect, it, vi } from 'vitest';import {- EXPORT_MAX_CANVAS_DIMENSION,- EXPORT_MAX_CANVAS_PIXELS,EXPORT_PADDING,EXPORT_SCALE,EXPORT_STYLE_PROPERTIES,@@ -29,13 +27,16 @@ describe('workflow image export', () => {});});- it('keeps large exports within the total canvas pixel budget', () => {- const dimensions = getWorkflowImageDimensions({ x: 0, y: 0, width: 9000, height: 9000 });+ it.each([+ [9000, 9000, 18400, 18400],+ [20000, 300, 40400, 1000],+ [300, 20000, 1000, 40400],+ ])('preserves full export resolution for %i by %i bounds', (width, height, canvasWidth, canvasHeight) => {+ const dimensions = getWorkflowImageDimensions({ x: 0, y: 0, width, height });- expect(dimensions.canvasWidth).toBeLessThanOrEqual(EXPORT_MAX_CANVAS_DIMENSION);- expect(dimensions.canvasHeight).toBeLessThanOrEqual(EXPORT_MAX_CANVAS_DIMENSION);- expect(dimensions.canvasWidth * dimensions.canvasHeight).toBeLessThanOrEqual(EXPORT_MAX_CANVAS_PIXELS);- expect(dimensions.canvasWidth / dimensions.canvasHeight).toBeCloseTo(1);+ expect(dimensions.canvasWidth).toBe(canvasWidth);+ expect(dimensions.canvasHeight).toBe(canvasHeight);+ expect(getWorkflowExportOptions(dimensions, 'white').skipAutoScale).toBe(true);});it('keeps capture clone local to an offscreen staging wrapper', () => {@@ -69,6 +70,7 @@ describe('workflow image export', () => {canvasHeight: 1000,backgroundColor: 'rgb(1, 2, 3)',pixelRatio: 1,+ skipAutoScale: true,includeStyleProperties: [...EXPORT_STYLE_PROPERTIES],imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=',onImageErrorHandler: expect.any(Function),diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.tsindex 0f98a6f349..a0815f5b0f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts@@ -6,8 +6,6 @@ const WORKFLOW_GRID_SIZE = 25;export const EXPORT_PADDING = 100;export const EXPORT_SCALE = 2;-export const EXPORT_MAX_CANVAS_DIMENSION = 16_384;-export const EXPORT_MAX_CANVAS_PIXELS = 16_777_216;export const WORKFLOW_EXPORT_TIMEOUT_MS = 30_000;const WORKFLOW_EXPORT_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';// html-to-image has no abort signal; bound captures that remain active after their caller times out.@@ -146,10 +144,39 @@ export const getWorkflowContentBounds = (nodeBounds: Rect,{ includeInputFieldLabels = true }: WorkflowContentBoundsOptions = {}): Rect => {- let minX = nodeBounds.x;- let minY = nodeBounds.y;- let maxX = nodeBounds.x + nodeBounds.width;- let maxY = nodeBounds.y + nodeBounds.height;+ const flowRect = flowElement.getBoundingClientRect();+ const viewport = flowElement.querySelector<HTMLElement>('.react-flow__viewport');+ const viewportRect = viewport?.getBoundingClientRect() ?? flowRect;+ const transform = viewport ? (getComputedStyle(viewport).transform ?? 'none') : 'none';+ const matrix = transform+ .match(/^matrix\(([^)]+)\)$/)?.[1]+ ?.split(',')+ .map(Number);+ const zoom = matrix?.[0] && Number.isFinite(matrix[0]) && matrix[0] > 0 ? matrix[0] : 1;+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ // The editor's measured nodes may be taller because of execution previews or textarea resize state.+ flowElement.querySelectorAll<HTMLElement>('.react-flow__node').forEach((node) => {+ const rect = node.getBoundingClientRect();+ if (rect.width <= 0 || rect.height <= 0) {+ return;+ }+ const x = (rect.left - viewportRect.left) / zoom;+ const y = (rect.top - viewportRect.top) / zoom;+ minX = Math.min(minX, x);+ minY = Math.min(minY, y);+ maxX = Math.max(maxX, x + rect.width / zoom);+ maxY = Math.max(maxY, y + rect.height / zoom);+ });+ if (minX === Infinity) {+ minX = nodeBounds.x;+ minY = nodeBounds.y;+ maxX = nodeBounds.x + nodeBounds.width;+ maxY = nodeBounds.y + nodeBounds.height;+ }flowElement.querySelectorAll<SVGGraphicsElement>('.react-flow__edge-path').forEach((path) => {let pathBounds: DOMRect;@@ -174,16 +201,6 @@ export const getWorkflowContentBounds = (});{- const flowRect = flowElement.getBoundingClientRect();- const viewport = flowElement.querySelector<HTMLElement>('.react-flow__viewport');- const viewportRect = viewport?.getBoundingClientRect() ?? flowRect;- const transform = viewport ? (getComputedStyle(viewport).transform ?? 'none') : 'none';- const matrix = transform- .match(/^matrix\(([^)]+)\)$/)?.[1]- ?.split(',')- .map(Number);- const zoom = matrix?.[0] && Number.isFinite(matrix[0]) && matrix[0] > 0 ? matrix[0] : 1;-const contentElements = new Set<HTMLElement>([...(includeInputFieldLabels? flowElement.querySelectorAll<HTMLElement>('[data-node-input-field-title="true"]')@@ -219,14 +236,8 @@ export const getWorkflowImageDimensions = (bounds: Rect): WorkflowImageDimensionconst width = Math.max(1, Math.ceil(paddedBounds.width));const height = Math.max(1, Math.ceil(paddedBounds.height));- const scale = Math.min(- EXPORT_SCALE,- EXPORT_MAX_CANVAS_DIMENSION / width,- EXPORT_MAX_CANVAS_DIMENSION / height,- Math.sqrt(EXPORT_MAX_CANVAS_PIXELS / (width * height))- );- const canvasWidth = Math.max(1, Math.floor(width * scale));- const canvasHeight = Math.max(1, Math.floor(height * scale));+ const canvasWidth = width * EXPORT_SCALE;+ const canvasHeight = height * EXPORT_SCALE;return { width, height, canvasWidth, canvasHeight };};@@ -247,6 +258,7 @@ export const getWorkflowExportOptions = (dimensions: WorkflowImageDimensions, bacanvasHeight: dimensions.canvasHeight,backgroundColor,pixelRatio: 1,+ skipAutoScale: true,includeStyleProperties: [...EXPORT_STYLE_PROPERTIES],imagePlaceholder: WORKFLOW_EXPORT_IMAGE_PLACEHOLDER,onImageErrorHandler: () => WORKFLOW_EXPORT_IMAGE_PLACEHOLDER,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex e56b8493e5..3769062c0b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -1941,6 +1941,29 @@ export const WorkflowFieldSnapshot = ({text = seedMode === 'random' || !text ? modeLabel : `${text} (${modeLabel})`;}+ if (template.type.name === 'StringField') {+ return (+ <Box+ borderColor="border"+ borderRadius="control"+ borderWidth="1px"+ data-workflow-export-field-value="true"+ fontFamily={template.uiComponent === 'textarea' ? 'mono' : undefined}+ minH="7"+ minW="0"+ mt="0.5"+ overflowWrap="anywhere"+ px="2"+ py="1"+ textStyle="xs"+ w="full"+ whiteSpace="pre-wrap"+ >+ {text}+ </Box>+ );+ }+return text ? (<Textcolor="fg.muted"