Skip to content

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.

fix(workflows): make PNG snapshot exports complete

JPPhoto7215f184f30e
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx
index 2038f8c276..c623095bff 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx
@@ -1,8 +1,10 @@
import { ChakraProvider } from '@chakra-ui/react';
import { applyThemeToRoot } from '@theme/applyTheme';
import { system } from '@theme/system';
+import { createInstance } from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
@@ -17,6 +19,7 @@ const toolbarMocks = vi.hoisted(() => ({
success: vi.fn(),
zoomIn: vi.fn(),
zoomOut: vi.fn(),
+ workflowName: 'Test workflow',
}));
vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({
@@ -27,9 +30,8 @@ vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({
}),
useWorkflowPreferencesSelector: () => false,
useWorkflowProjectSelector: (selector: (project: unknown) => unknown) =>
- selector({ activeWorkflow: { document: { name: 'Test workflow' } } }),
+ selector({ activeWorkflow: { document: { name: toolbarMocks.workflowName } } }),
}));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@xyflow/react', async (importOriginal) => ({
...(await importOriginal<object>()),
useReactFlow: () => toolbarMocks,
@@ -38,6 +40,14 @@ vi.mock('./workflowImageExport', () => ({ exportWorkflowAsPng: toolbarMocks.expo
const { EditorToolbar } = await import('./EditorToolbar');
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackNS: 'translation',
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+});
+
let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -50,7 +60,10 @@ const settle = (action: () => void): Promise<void> =>
});
});
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ toolbarMocks.workflowName = 'Test workflow';
+});
const render = async (nodeOpacity: number) => {
applyThemeToRoot('mono');
@@ -62,15 +75,17 @@ const render = async (nodeOpacity: number) => {
await settle(() => {
root?.render(
- <ChakraProvider value={system}>
- <EditorToolbar
- nodeOpacity={nodeOpacity}
- tool="pan"
- onExportPendingChange={toolbarMocks.onExportPendingChange}
- onNodeOpacityChange={vi.fn()}
- onToolChange={vi.fn()}
- />
- </ChakraProvider>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <EditorToolbar
+ nodeOpacity={nodeOpacity}
+ tool="pan"
+ onExportPendingChange={toolbarMocks.onExportPendingChange}
+ onNodeOpacityChange={vi.fn()}
+ onToolChange={vi.fn()}
+ />
+ </ChakraProvider>
+ </I18nextProvider>
);
});
};
@@ -110,26 +125,28 @@ describe('editor toolbar', () => {
it('offers to update outdated nodes only while there are some, without breaking the toolbar grid', async () => {
await render(1);
- expect(host!.querySelector('button[aria-label="nodes.updateAllNodes"]')).toBeNull();
+ expect(host!.querySelector('button[aria-label^="Update "]')).toBeNull();
const onUpdateNodes = vi.fn();
await settle(() => {
root?.render(
- <ChakraProvider value={system}>
- <EditorToolbar
- nodeOpacity={1}
- tool="pan"
- updatableNodeCount={2}
- onNodeOpacityChange={vi.fn()}
- onToolChange={vi.fn()}
- onUpdateNodes={onUpdateNodes}
- />
- </ChakraProvider>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <EditorToolbar
+ nodeOpacity={1}
+ tool="pan"
+ updatableNodeCount={2}
+ onNodeOpacityChange={vi.fn()}
+ onToolChange={vi.fn()}
+ onUpdateNodes={onUpdateNodes}
+ />
+ </ChakraProvider>
+ </I18nextProvider>
);
});
- const update = host!.querySelector<HTMLButtonElement>('button[aria-label="nodes.updateAllNodes"]')!;
+ const update = host!.querySelector<HTMLButtonElement>('button[aria-label="Update 2 outdated nodes"]')!;
expect(update).not.toBeNull();
expect(new Set(buttonBoxes())).toEqual(new Set(['28x28']));
@@ -156,7 +173,7 @@ describe('editor toolbar', () => {
toolbarMocks.exportWorkflowAsPng.mockResolvedValue(undefined);
await render(1);
- const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="workflow.exportAsPng"]')!;
+ const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="Download workflow as PNG"]')!;
expect(camera).not.toBeNull();
await settle(() => camera.click());
@@ -164,7 +181,7 @@ describe('editor toolbar', () => {
expect(toolbarMocks.exportWorkflowAsPng).toHaveBeenCalledWith({
bounds: { x: 12, y: 34, width: 56, height: 78 },
- fallbackWorkflowName: 'workflow.untitled',
+ fallbackWorkflowName: 'Untitled Workflow',
flowElement: host,
workflowName: 'Test workflow',
});
@@ -175,7 +192,7 @@ describe('editor toolbar', () => {
it('shows the translated label as a camera tooltip', async () => {
await render(1);
- const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="workflow.exportAsPng"]')!;
+ const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="Download workflow as PNG"]')!;
await act(async () => {
await userEvent.hover(camera);
await new Promise<void>((resolve) => {
@@ -184,7 +201,7 @@ describe('editor toolbar', () => {
});
const tooltip = [...document.querySelectorAll('[role="tooltip"]')].find(
- (element) => element.textContent === 'workflow.exportAsPng'
+ (element) => element.textContent === 'Download workflow as PNG'
);
expect(tooltip).not.toBeUndefined();
@@ -194,12 +211,27 @@ describe('editor toolbar', () => {
toolbarMocks.exportWorkflowAsPng.mockRejectedValueOnce(new Error('rasterization failed'));
await render(1);
- const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="workflow.exportAsPng"]')!;
+ const camera = host!.querySelector<HTMLButtonElement>('button[aria-label="Download workflow as PNG"]')!;
await settle(() => camera.click());
- await vi.waitFor(() => expect(toolbarMocks.error).toHaveBeenCalledWith('workflow.exportImageFailed'));
+ await vi.waitFor(() => expect(toolbarMocks.error).toHaveBeenCalledWith('Could not export workflow image.'));
- expect(toolbarMocks.error).toHaveBeenCalledWith('workflow.exportImageFailed');
+ expect(toolbarMocks.error).toHaveBeenCalledWith('Could not export workflow image.');
expect(toolbarMocks.onExportPendingChange.mock.calls).toEqual([[true], [false]]);
expect(camera.disabled).toBe(false);
});
+
+ it('uses the translated untitled workflow name for an unnamed export', async () => {
+ toolbarMocks.workflowName = '';
+ toolbarMocks.exportWorkflowAsPng.mockResolvedValue(undefined);
+ await render(1);
+
+ await settle(() =>
+ host!.querySelector<HTMLButtonElement>('button[aria-label="Download workflow as PNG"]')!.click()
+ );
+ await vi.waitFor(() => expect(toolbarMocks.exportWorkflowAsPng).toHaveBeenCalledOnce());
+
+ expect(toolbarMocks.exportWorkflowAsPng).toHaveBeenCalledWith(
+ expect.objectContaining({ fallbackWorkflowName: 'Untitled Workflow', workflowName: '' })
+ );
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
index 5360dc3244..e153e61d39 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx
@@ -81,8 +81,8 @@ export const EditorToolbar = ({
const isExportingWorkflowRef = useRef(false);
const [isExportingWorkflow, setIsExportingWorkflow] = useState(false);
const fitViewDuration = reduceMotion ? 0 : 300;
- const fallbackWorkflowName = t('workflow.untitled');
- const exportFailedLabel = t('workflow.exportImageFailed');
+ const fallbackWorkflowName = t('widgets.workflow.untitled');
+ const exportFailedLabel = t('widgets.workflow.exportImageFailed');
const opacityIds = useMemo(() => ({ trigger: opacityTriggerId }), [opacityTriggerId]);
const opacityValue = useMemo(() => [Math.round(nodeOpacity * 100)], [nodeOpacity]);
const onZoomInClick = useCallback(() => void zoomIn(), [zoomIn]);
@@ -168,7 +168,7 @@ export const EditorToolbar = ({
<ToolbarButton
disabled={isExportingWorkflow}
icon={CameraIcon}
- label={t('workflow.exportAsPng')}
+ label={t('widgets.workflow.exportAsPng')}
loading={isExportingWorkflow}
onClick={onExportWorkflowClick}
/>
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.tsx
index 31ed591c85..3e68a12239 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
@@ -17,9 +17,14 @@ import { page, userEvent } from 'vitest/browser';
import { toFlowEdges, toFlowNodes } from './flowAdapters';
import { InvocationFlowNode, WorkflowImageExportProvider } from './InvocationFlowNode';
+import { exportWorkflowAsPng } from './workflowImageExport';
import '@xyflow/react/dist/style.css';
+const exportMocks = vi.hoisted(() => ({ toBlob: vi.fn() }));
+vi.mock('html-to-image', () => ({ toBlob: exportMocks.toBlob }));
+vi.mock('@platform/browser/downloadBlob', () => ({ downloadBlob: vi.fn() }));
+
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock('react-i18next', () => ({
@@ -268,6 +273,64 @@ describe('InvocationFlowNode output preview', () => {
)!;
const nodeHeight = () => host.querySelector<HTMLElement>('.react-flow__node')!.getBoundingClientRect().height;
+ it('keeps node and field descriptions plus full output values in the exported graph clone', async () => {
+ const longOutput = 'x'.repeat(60);
+ const exportTemplate: InvocationTemplate = {
+ ...template,
+ description: 'Node export description',
+ inputs: { a: { ...template.inputs.a!, description: 'Template field description' } },
+ outputs: { value: { ...template.outputs.value!, description: 'Output export description' } },
+ };
+ const exportNode: WorkflowInvocationNode = {
+ ...documentNode,
+ data: {
+ ...documentNode.data,
+ inputs: {
+ a: { description: 'Field export description', descriptionOverride: true, label: 'A', name: 'a', value: 1 },
+ },
+ isOpen: false,
+ notes: 'Node export note',
+ },
+ };
+ const exportGraph = { ...projectGraph, nodes: [exportNode] };
+ const exportNodes = toFlowNodes(exportGraph, [], { preview: exportTemplate });
+ const execution = createExecutionPort();
+ const adapter = createAdapter(execution.port);
+ let capturedClone: HTMLElement | undefined;
+ exportMocks.toBlob.mockImplementation((clone: HTMLElement) => {
+ capturedClone = clone;
+ return Promise.resolve(new Blob(['png'], { type: 'image/png' }));
+ });
+
+ await render(adapter, 1, true, exportNodes);
+ await act(() =>
+ execution.set({
+ error: null,
+ latestOutput: { value: longOutput },
+ outputImageUrl: null,
+ progress: null,
+ progressMessage: null,
+ status: 'completed',
+ })
+ );
+ await page.screenshot({ path: '../../../../../artifacts/workflow-export-content.png' });
+
+ const flowElement = host.querySelector<HTMLElement>('.react-flow')!;
+ await exportWorkflowAsPng({
+ bounds: { x: 20, y: 20, width: 300, height: 260 },
+ fallbackWorkflowName: 'Untitled Workflow',
+ flowElement,
+ workflowName: 'Export content',
+ });
+
+ expect(capturedClone?.textContent).toContain('Node export description');
+ expect(capturedClone?.textContent).toContain('Node export note');
+ expect(capturedClone?.textContent).toContain('Field export description');
+ expect(capturedClone?.textContent).toContain('Output export description');
+ expect(capturedClone?.textContent).toContain(longOutput);
+ expect(capturedClone?.querySelectorAll('[data-workflow-export-content="true"]').length).toBeGreaterThanOrEqual(4);
+ });
+
it('keeps one preview height across differently shaped outputs and folds it away per node', async () => {
const execution = createExecutionPort();
const adapter = createAdapter(execution.port);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
index 168a404909..67a86e49d5 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
@@ -578,11 +578,13 @@ const InputFieldRow = ({
node: WorkflowInvocationNode;
template: FieldInputTemplate;
}) => {
+ const isWorkflowImageExport = useIsWorkflowImageExport();
const { editGraph } = useProjectGraphCommands();
const instance = node.data.inputs[template.name];
const fieldIdentifier = { fieldName: template.name, nodeId: node.id };
const showsControl = !isConnected && isDirectInputField(template);
const label = instance?.label || template.title;
+ const description = getEffectiveWorkflowFieldDescription(instance, template);
const invalidReason = getWorkflowFieldInvalidReason({
isConnected,
template,
@@ -633,7 +635,7 @@ const InputFieldRow = ({
positioning={{ placement: 'top-start' }}
content={
<InputFieldTooltip
- description={getEffectiveWorkflowFieldDescription(instance, template)}
+ description={description}
isConnected={isConnected}
isExposed={isExposed}
label={label}
@@ -701,6 +703,18 @@ const InputFieldRow = ({
) : null}
</HStack>
</HStack>
+ {isWorkflowImageExport && description ? (
+ <Text
+ color="fg.subtle"
+ data-workflow-export-content="true"
+ fontSize="2xs"
+ mt="0.5"
+ overflowWrap="anywhere"
+ whiteSpace="pre-wrap"
+ >
+ {description}
+ </Text>
+ ) : null}
{showsControl ? (
<Box mt="0.5" w="full">
<WorkflowFieldInput
@@ -736,6 +750,7 @@ const OutputFieldRow = ({
latestResult: unknown;
template: FieldOutputTemplate;
}) => {
+ const isWorkflowImageExport = useIsWorkflowImageExport();
const handleTooltip = getHandleTypeTooltip(template.type);
const value = latestResult === undefined ? null : formatOutputFieldValue(latestResult, template.name);
@@ -754,6 +769,20 @@ const OutputFieldRow = ({
<Flex justify="flex-end" w="full">
<SkeletonBar w="40%" />
</Flex>
+ ) : isWorkflowImageExport ? (
+ <Box flexShrink={0} maxW="full" textAlign="end">
+ <Tooltip content={<OutputFieldTooltip template={template} />} positioning={{ placement: 'top-end' }}>
+ <MiddleTruncate
+ as="span"
+ color="fg.muted"
+ fontSize="2xs"
+ justifyContent="flex-end"
+ lineHeight="shorter"
+ maxW="full"
+ text={template.title}
+ />
+ </Tooltip>
+ </Box>
) : (
<HStack gap="1.5" justify="flex-end" minW="0" w="full">
{value ? (
@@ -787,6 +816,30 @@ const OutputFieldRow = ({
</HStack>
)}
</Flex>
+ {isWorkflowImageExport && value ? (
+ <Text
+ color="fg.subtle"
+ data-workflow-export-content="true"
+ fontSize="2xs"
+ maxW="full"
+ overflowWrap="anywhere"
+ whiteSpace="pre-wrap"
+ >
+ {value.full}
+ </Text>
+ ) : null}
+ {isWorkflowImageExport && template.description ? (
+ <Text
+ color="fg.subtle"
+ data-workflow-export-content="true"
+ fontSize="2xs"
+ maxW="full"
+ overflowWrap="anywhere"
+ whiteSpace="pre-wrap"
+ >
+ {template.description}
+ </Text>
+ ) : null}
</Box>
);
};
@@ -951,7 +1004,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
const outputTemplates = templateView.outputTemplates;
const outputTemplatesByName = new Map(outputTemplates.map((template) => [template.name, template]));
const outputRows = getOutputFieldRows(getOutputFieldNamesByScope(outputTemplates));
- const isOpen = node.data.isOpen;
+ const isOpen = node.data.isOpen || isWorkflowImageExport;
const isRunning = execution?.status === 'running';
const isMissingRequiredInput = hasMissingRequiredInputs(node, inputTemplates, connectedFieldNames);
const isCompact = data.isCompact && !selected && !isWorkflowImageExport;
@@ -991,6 +1044,27 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
</>
)}
</Flex>
+ {isWorkflowImageExport && (template.description || node.data.notes) ? (
+ <Stack gap="1" px={WORKFLOW_NODE_DENSITY.rowPaddingX} py="1">
+ {template.description ? (
+ <Text
+ color="fg.subtle"
+ data-workflow-export-content="true"
+ fontSize="2xs"
+ fontStyle="italic"
+ overflowWrap="anywhere"
+ whiteSpace="pre-wrap"
+ >
+ {template.description}
+ </Text>
+ ) : null}
+ {node.data.notes ? (
+ <Text data-workflow-export-content="true" fontSize="2xs" overflowWrap="anywhere" whiteSpace="pre-wrap">
+ {node.data.notes}
+ </Text>
+ ) : null}
+ </Stack>
+ ) : null}
<NodeProgressStrip execution={execution} />
{isOpen && isCompact ? (
<>
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.edgeCases.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.edgeCases.test.ts
index f5eefd17ec..9f95fda6ce 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.edgeCases.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.edgeCases.test.ts
@@ -97,7 +97,7 @@ describe('workflow image export edge cases', () => {
vi.useRealTimers();
});
- it('settles and cleans up when rasterization never settles', async () => {
+ it('allows one bounded retry when a previous rasterization never settles', async () => {
vi.useFakeTimers();
let finishRasterization: (blob: Blob | null) => void = () => undefined;
vi.mocked(toBlob).mockReturnValue(
@@ -120,21 +120,16 @@ describe('workflow image export edge cases', () => {
await rejection;
expect(stagingWrapper.remove).toHaveBeenCalledOnce();
- const retry = exportWorkflowAsPng(exportOptions);
- const retryRejection = expect(retry).rejects.toThrow('still running');
-
- await vi.advanceTimersByTimeAsync(0);
- await retryRejection;
- expect(toBlob).toHaveBeenCalledOnce();
- expect(stagingWrapper.remove).toHaveBeenCalledOnce();
- finishRasterization(null);
- await vi.advanceTimersByTimeAsync(0);
-
- vi.mocked(toBlob).mockResolvedValueOnce(new Blob(['png'], { type: 'image/png' }));
+ const retryBlob = new Blob(['png'], { type: 'image/png' });
+ vi.mocked(toBlob).mockResolvedValueOnce(retryBlob);
await exportWorkflowAsPng(exportOptions);
expect(toBlob).toHaveBeenCalledTimes(2);
expect(stagingWrapper.remove).toHaveBeenCalledTimes(2);
+ finishRasterization(null);
+ await vi.advanceTimersByTimeAsync(0);
} finally {
+ finishRasterization(null);
+ await vi.advanceTimersByTimeAsync(0);
vi.useRealTimers();
}
});
@@ -155,6 +150,21 @@ describe('workflow image export edge cases', () => {
expect(stagingWrapper.remove).toHaveBeenCalledOnce();
});
+ it('uses the translated untitled name when downloading an unnamed workflow', async () => {
+ const blob = new Blob(['png'], { type: 'image/png' });
+ vi.mocked(toBlob).mockResolvedValue(blob);
+ const { flowElement } = createExportDom();
+
+ await exportWorkflowAsPng({
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: '',
+ fallbackWorkflowName: 'Untitled Workflow',
+ });
+
+ expect(downloadBlob).toHaveBeenCalledWith(blob, 'Untitled Workflow.png');
+ });
+
it('configures failed image embedding to degrade instead of aborting export', () => {
const options = getWorkflowExportOptions(
{ width: 100, height: 100, canvasWidth: 200, canvasHeight: 200 },
@@ -191,6 +201,62 @@ describe('workflow image export edge cases', () => {
).toMatchObject({ x: 0, y: 0, width: 690, height: 100 });
});
+ it('includes inline export descriptions in content bounds', () => {
+ const description = {
+ getBoundingClientRect: () => ({ left: 650, top: 250, width: 100, height: 50 }),
+ scrollWidth: 100,
+ scrollHeight: 50,
+ };
+ const viewport = { getBoundingClientRect: () => ({ left: 100, top: 200, width: 1000, height: 1000 }) };
+ const flowElement = {
+ getBoundingClientRect: () => ({ left: 100, top: 200 }),
+ querySelector: (selector: string) => (selector === '.react-flow__viewport' ? viewport : null),
+ querySelectorAll: (selector: string) =>
+ selector === '[data-workflow-export-content="true"]' ? [description] : [],
+ };
+
+ expect(
+ getWorkflowContentBounds(
+ flowElement as unknown as HTMLElement,
+ { x: 0, y: 0, width: 500, height: 100 },
+ {
+ includeInputFieldLabels: false,
+ }
+ )
+ ).toMatchObject({ x: 0, y: 0, width: 650, height: 100 });
+ });
+
+ it('measures export content in logical coordinates when the workflow is zoomed out', () => {
+ const description = {
+ getBoundingClientRect: () => ({ left: 50, top: 50, width: 100, height: 25 }),
+ scrollWidth: 200,
+ scrollHeight: 50,
+ };
+ const viewport = { getBoundingClientRect: () => ({ left: 0, top: 0, width: 1000, height: 1000 }) };
+ const flowElement = {
+ getBoundingClientRect: () => ({ left: 0, top: 0 }),
+ querySelector: (selector: string) => (selector === '.react-flow__viewport' ? viewport : null),
+ querySelectorAll: (selector: string) =>
+ selector === '[data-workflow-export-content="true"]' ? [description] : [],
+ };
+
+ vi.stubGlobal('getComputedStyle', (element: unknown) => ({
+ direction: 'ltr',
+ transform: element === viewport ? 'matrix(0.5, 0, 0, 0.5, 0, 0)' : 'none',
+ }));
+ try {
+ expect(
+ getWorkflowContentBounds(
+ flowElement as unknown as HTMLElement,
+ { x: 0, y: 0, width: 100, height: 100 },
+ { includeInputFieldLabels: false }
+ )
+ ).toEqual({ x: 0, y: 0, width: 300, height: 150 });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
it('measures overflowing labels after export styles are applied', async () => {
vi.mocked(toBlob).mockResolvedValue(null);
const label = createFakeElement({
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.ts
index 9a89916f48..d27c5fe765 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
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
EXPORT_MAX_CANVAS_DIMENSION,
+ EXPORT_MAX_CANVAS_PIXELS,
EXPORT_PADDING,
EXPORT_SCALE,
EXPORT_STYLE_PROPERTIES,
@@ -28,11 +29,13 @@ describe('workflow image export', () => {
});
});
- it('preserves the aspect ratio when large exports reach the canvas limit', () => {
+ it('keeps large exports within the total canvas pixel budget', () => {
const dimensions = getWorkflowImageDimensions({ x: 0, y: 0, width: 9000, height: 9000 });
- expect(dimensions.canvasWidth).toBe(EXPORT_MAX_CANVAS_DIMENSION);
- expect(dimensions.canvasHeight).toBe(EXPORT_MAX_CANVAS_DIMENSION);
+ 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);
});
it('keeps capture clone local to an offscreen staging wrapper', () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts
index a6f89aa3cb..fb7030c187 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts
@@ -7,10 +7,12 @@ 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; block another capture until a timed-out rasterization settles.
-let isWorkflowRasterizationPending = false;
+// html-to-image has no abort signal; bound captures that remain active after their caller times out.
+const MAX_ACTIVE_WORKFLOW_RASTERIZATIONS = 2;
+let activeWorkflowRasterizations = 0;
export const EXPORT_STYLE_PROPERTIES = [
'box-sizing',
'display',
@@ -171,7 +173,7 @@ export const getWorkflowContentBounds = (
maxY = Math.max(maxY, pathBounds.y + pathBounds.height);
});
- if (includeInputFieldLabels) {
+ {
const flowRect = flowElement.getBoundingClientRect();
const viewport = flowElement.querySelector<HTMLElement>('.react-flow__viewport');
const viewportRect = viewport?.getBoundingClientRect() ?? flowRect;
@@ -182,21 +184,27 @@ export const getWorkflowContentBounds = (
.map(Number);
const zoom = matrix?.[0] && Number.isFinite(matrix[0]) && matrix[0] > 0 ? matrix[0] : 1;
- flowElement.querySelectorAll<HTMLElement>('[data-node-input-field-title="true"]').forEach((label) => {
- const labelRect = label.getBoundingClientRect();
- const intrinsicWidth = Math.max(labelRect.width, label.scrollWidth);
- const intrinsicHeight = Math.max(labelRect.height, label.scrollHeight);
- const overflowWidth = Math.max(0, intrinsicWidth - labelRect.width) / zoom;
- const direction = getComputedStyle(label).direction;
- const labelX = (labelRect.left - viewportRect.left) / zoom - (direction === 'rtl' ? overflowWidth : 0);
- const labelY = (labelRect.top - viewportRect.top) / zoom;
+ const contentElements = new Set<HTMLElement>([
+ ...(includeInputFieldLabels
+ ? flowElement.querySelectorAll<HTMLElement>('[data-node-input-field-title="true"]')
+ : []),
+ ...flowElement.querySelectorAll<HTMLElement>('[data-workflow-export-content="true"]'),
+ ]);
+ contentElements.forEach((element) => {
+ const elementRect = element.getBoundingClientRect();
+ const intrinsicWidth = Math.max(elementRect.width, element.scrollWidth * zoom);
+ const intrinsicHeight = Math.max(elementRect.height, element.scrollHeight * zoom);
+ const overflowWidth = Math.max(0, intrinsicWidth - elementRect.width) / zoom;
+ const direction = getComputedStyle(element).direction;
+ const elementX = (elementRect.left - viewportRect.left) / zoom - (direction === 'rtl' ? overflowWidth : 0);
+ const elementY = (elementRect.top - viewportRect.top) / zoom;
const labelWidth = intrinsicWidth / zoom;
const labelHeight = intrinsicHeight / zoom;
- minX = Math.min(minX, labelX);
- minY = Math.min(minY, labelY);
- maxX = Math.max(maxX, labelX + labelWidth);
- maxY = Math.max(maxY, labelY + labelHeight);
+ minX = Math.min(minX, elementX);
+ minY = Math.min(minY, elementY);
+ maxX = Math.max(maxX, elementX + labelWidth);
+ maxY = Math.max(maxY, elementY + labelHeight);
});
}
@@ -209,7 +217,12 @@ export const getWorkflowImageDimensions = (bounds: Rect): WorkflowImageDimension
const 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);
+ 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));
@@ -450,22 +463,18 @@ const prepareExportClone = (clone: HTMLElement, bounds: Rect, dimensions: Workfl
};
const toBlobWithTimeout = async (clone: HTMLElement, options: ReturnType<typeof getWorkflowExportOptions>) => {
- if (isWorkflowRasterizationPending) {
+ if (activeWorkflowRasterizations >= MAX_ACTIVE_WORKFLOW_RASTERIZATIONS) {
throw new Error('A previous workflow image export is still running');
}
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
- isWorkflowRasterizationPending = true;
+ activeWorkflowRasterizations += 1;
+ const releaseRasterizationSlot = () => {
+ activeWorkflowRasterizations -= 1;
+ };
const rasterize = import('html-to-image').then(({ toBlob }) => (timedOut ? null : toBlob(clone, options)));
- void rasterize.then(
- () => {
- isWorkflowRasterizationPending = false;
- },
- () => {
- isWorkflowRasterizationPending = false;
- }
- );
+ void rasterize.then(releaseRasterizationSlot, releaseRasterizationSlot);
try {
return await Promise.race([
@@ -499,7 +508,7 @@ export const exportWorkflowAsPng = async ({
workflowName: string;
fallbackWorkflowName: string;
}): Promise<void> => {
- if (isWorkflowRasterizationPending) {
+ if (activeWorkflowRasterizations >= MAX_ACTIVE_WORKFLOW_RASTERIZATIONS) {
throw new Error('A previous workflow image export is still running');
}