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(workflow): retain snapshot previews and current workflow names

JPPhoto63d5bae17bfb
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 e5bc215b0d..09333a12ae 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
@@ -737,7 +737,7 @@ describe('InvocationFlowNode output preview', () => {
{ updatedAt: 300 }
);
});
- expect(host.querySelector('[data-workflow-export-field-value="true"]')?.textContent).toBe(name);
+ expect(host.querySelector('[data-workflow-export-field-value="true"]')?.textContent).toBe(initialName);
await act(() => {
queryClient.setQueryData(
savedWorkflowDetailQueryKey(workflowId),
@@ -751,6 +751,22 @@ describe('InvocationFlowNode output preview', () => {
expect(host.querySelector('[data-workflow-export-field-value="true"]')?.textContent).toBe(
'Renamed child workflow'
);
+ await act(() => {
+ queryClient.setQueryData(
+ savedWorkflowPickerQueryOptions({ page: 0, query: 'Previous' }).queryKey,
+ {
+ pageParams: [0, 1],
+ pages: [
+ { items: [{ name: initialName, workflow_id: workflowId }], page: 0, pages: 2, total: 2 },
+ { items: [{ name: 'Other workflow', workflow_id: 'other' }], page: 1, pages: 2, total: 2 },
+ ],
+ },
+ { updatedAt: 500 }
+ );
+ });
+ expect(host.querySelector('[data-workflow-export-field-value="true"]')?.textContent).toBe(
+ 'Renamed child workflow'
+ );
}
if (source === 'unavailable') {
await act(() => {
@@ -767,9 +783,14 @@ describe('InvocationFlowNode output preview', () => {
}
);
- it.each(['SINGLE', 'COLLECTION'] as const)(
- 'exports scaled authored source images for %s fields',
- async (cardinality) => {
+ it.each([
+ { cardinality: 'SINGLE', failed: false },
+ { cardinality: 'COLLECTION', failed: false },
+ { cardinality: 'SINGLE', failed: true },
+ { cardinality: 'COLLECTION', failed: true },
+ ] as const)(
+ 'exports authored source images for $cardinality fields with failed=$failed',
+ async ({ cardinality, failed }) => {
const source = outputImage(800, 400);
const thumbnailSpy = vi.spyOn(galleryImageUrls, 'thumbnail').mockReturnValue(source);
const value = { image_name: 'authored-source.png' };
@@ -807,16 +828,41 @@ describe('InvocationFlowNode output preview', () => {
await render(adapter, 1, true, toFlowNodes(graph, [], { preview: imageTemplate }));
const sourceImage = host.querySelector<HTMLImageElement>('[data-workflow-export-field-value="true"] img');
expect(sourceImage).not.toBeNull();
- await vi.waitFor(() => expect(sourceImage!.naturalWidth).toBe(800));
+ // Simulate a pending thumbnail's zero dimensions until decoding completes.
+ const naturalWidthSpy = vi.spyOn(sourceImage!, 'naturalWidth', 'get').mockReturnValue(0);
+ sourceImage!.style.width = '0px';
+ sourceImage!.style.height = '0px';
+ expect(sourceImage!.naturalWidth).toBe(0);
+ const decode = sourceImage!.decode.bind(sourceImage);
+ let releaseImage!: () => void;
+ const imageReady = new Promise<void>((resolve) => {
+ releaseImage = resolve;
+ });
+ const decodeSpy = vi.spyOn(sourceImage!, 'decode').mockImplementation(async () => {
+ await imageReady;
+ if (failed) {
+ throw new Error('Thumbnail unavailable');
+ }
+ naturalWidthSpy.mockRestore();
+ sourceImage!.style.removeProperty('width');
+ sourceImage!.style.removeProperty('height');
+ await decode();
+ });
expect(getComputedStyle(sourceImage!).objectFit).toBe(cardinality === 'SINGLE' ? 'contain' : 'cover');
expect(sourceImage!.getBoundingClientRect().width).toBeLessThan(800);
expect(sourceImage!.getBoundingClientRect().height).toBeLessThanOrEqual(128);
- await exportWorkflowAsPng({
+ const exportPromise = exportWorkflowAsPng({
bounds: { x: 20, y: 20, width: 300, height: 260 },
fallbackWorkflowName: 'Untitled Workflow',
flowElement: host.querySelector<HTMLElement>('.react-flow')!,
workflowName: 'Authored source image',
});
+ await vi.waitFor(() => expect(decodeSpy).toHaveBeenCalledOnce());
+ expect(exportMocks.toBlob).not.toHaveBeenCalled();
+ releaseImage();
+ await exportPromise;
+ decodeSpy.mockRestore();
+ naturalWidthSpy.mockRestore();
expect(exportedBlob?.type).toBe('image/png');
const bitmap = await createImageBitmap(exportedBlob!);
const canvas = document.createElement('canvas');
@@ -832,9 +878,19 @@ describe('InvocationFlowNode output preview', () => {
}
}
bitmap.close();
- expect(sourcePixels).toBeGreaterThan(1000);
- expect(capturedClone?.querySelectorAll('img')).toHaveLength(1);
- expect(capturedClone?.querySelector('img')?.src).toBe(source);
+ if (failed) {
+ expect(sourcePixels).toBe(0);
+ expect(capturedClone?.querySelectorAll('img')).toHaveLength(0);
+ expect(capturedClone?.querySelector('[data-workflow-export-field-value="true"] span')?.textContent).toBe(
+ 'authored-source.png'
+ );
+ // The fallback belongs only to the clone; the editor image is preserved for later loads.
+ expect(host.querySelector('[data-workflow-export-field-value="true"] img')).toBe(sourceImage);
+ } else {
+ expect(sourcePixels).toBeGreaterThan(1000);
+ expect(capturedClone?.querySelectorAll('img')).toHaveLength(1);
+ expect(capturedClone?.querySelector('img')?.src).toBe(source);
+ }
expect(capturedClone?.textContent).toContain('authored-source.png');
expect(capturedClone?.textContent).not.toContain('Latest output');
expect(capturedClone?.querySelector('button, input')).toBeNull();
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 3a9dc291cb..bb19bf0437 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
@@ -16,6 +16,7 @@ import {
getWorkflowContentBounds,
getWorkflowExportOptions,
WORKFLOW_EXPORT_TIMEOUT_MS,
+ WORKFLOW_EXPORT_IMAGE_TIMEOUT_MS,
} from './workflowImageExport';
type FakeElement = {
@@ -97,6 +98,106 @@ describe('workflow image export edge cases', () => {
vi.useRealTimers();
});
+ it.each(['failed', 'hung'] as const)(
+ 'replaces %s source images without changing the editor or retaining timers',
+ async (state) => {
+ vi.useFakeTimers();
+ const { flowElement, clone, stagingWrapper } = createExportDom();
+ const decode = vi.fn(() =>
+ state === 'failed' ? Promise.reject(new Error('Unavailable')) : new Promise<void>(() => {})
+ );
+ const sourceImage = { decode, src: 'source.png' };
+ const replacement = vi.fn();
+ const clonedImage = { src: 'source.png', alt: 'source.png', replaceWith: replacement };
+ const selector = '[data-workflow-export-field-value="true"] img';
+ flowElement.querySelectorAll = (query) => (query === selector ? [sourceImage as unknown as FakeElement] : []);
+ clone.querySelectorAll = (query) => (query === selector ? [clonedImage as unknown as FakeElement] : []);
+ const fallback = { textContent: '', style: {} };
+ vi.stubGlobal('document', {
+ body: flowElement.parentElement,
+ createElement: (tag: string) => (tag === 'span' ? fallback : stagingWrapper),
+ });
+ vi.mocked(toBlob).mockResolvedValue(new Blob(['png'], { type: 'image/png' }));
+ const exportPromise = exportWorkflowAsPng({
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: 'Workflow',
+ fallbackWorkflowName: 'Unnamed Workflow',
+ });
+ try {
+ await vi.advanceTimersByTimeAsync(state === 'hung' ? WORKFLOW_EXPORT_IMAGE_TIMEOUT_MS - 1 : 0);
+ if (state === 'hung') {
+ expect(toBlob).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ }
+ await exportPromise;
+ expect(replacement).toHaveBeenCalledWith(fallback);
+ expect(fallback.textContent).toBe('source.png');
+ expect(flowElement.querySelectorAll(selector)).toEqual([sourceImage]);
+ expect(downloadBlob).toHaveBeenCalledOnce();
+ expect(stagingWrapper.remove).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ }
+ );
+
+ it.each(['removed', 'replaced'] as const)(
+ 'matches decoded images after a source is %s during the wait',
+ async (change) => {
+ vi.useFakeTimers();
+ const { flowElement, clone, stagingWrapper } = createExportDom();
+ let failFirst!: () => void;
+ const first = {
+ src: 'first.png',
+ decode: () =>
+ new Promise<void>((_, reject) => {
+ failFirst = () => reject(new Error('Unavailable'));
+ }),
+ };
+ const second = { src: 'second.png', naturalWidth: 800, naturalHeight: 400, decode: () => Promise.resolve() };
+ let images = [first, second];
+ const replaceWith = vi.fn();
+ const clonedImage = { src: 'second.png', alt: 'second.png', replaceWith };
+ const selector = '[data-workflow-export-field-value="true"] img';
+ flowElement.querySelectorAll = (query) => (query === selector ? (images as unknown as FakeElement[]) : []);
+ clone.querySelectorAll = (query) => (query === selector ? [clonedImage as unknown as FakeElement] : []);
+ const fallback = { textContent: '', style: {} };
+ vi.stubGlobal('document', {
+ body: flowElement.parentElement,
+ createElement: (tag: string) => (tag === 'span' ? fallback : stagingWrapper),
+ });
+ vi.mocked(toBlob).mockResolvedValue(new Blob(['png'], { type: 'image/png' }));
+ const exportPromise = exportWorkflowAsPng({
+ flowElement: flowElement as unknown as HTMLElement,
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ workflowName: 'Workflow',
+ fallbackWorkflowName: 'Unnamed Workflow',
+ });
+ try {
+ await vi.advanceTimersByTimeAsync(0);
+ images = [second];
+ if (change === 'replaced') {
+ second.src = 'new-source.png';
+ clonedImage.src = 'new-source.png';
+ clonedImage.alt = 'new-source.png';
+ }
+ failFirst();
+ await exportPromise;
+ if (change === 'removed') {
+ expect(replaceWith).not.toHaveBeenCalled();
+ } else {
+ expect(replaceWith).toHaveBeenCalledWith(fallback);
+ expect(fallback.textContent).toBe('new-source.png');
+ }
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ }
+ );
+
it('allows one bounded retry when a previous rasterization never settles', async () => {
vi.useFakeTimers();
let finishRasterization: (blob: Blob | null) => void = () => undefined;
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 a0815f5b0f..ba5fccbeb2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts
@@ -7,6 +7,7 @@ const WORKFLOW_GRID_SIZE = 25;
export const EXPORT_PADDING = 100;
export const EXPORT_SCALE = 2;
export const WORKFLOW_EXPORT_TIMEOUT_MS = 30_000;
+export const WORKFLOW_EXPORT_IMAGE_TIMEOUT_MS = 5_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.
const MAX_ACTIVE_WORKFLOW_RASTERIZATIONS = 2;
@@ -511,6 +512,63 @@ const downloadPng = (blob: Blob, workflowName: string, fallbackWorkflowName: str
downloadBlob(blob, `${sanitizeWorkflowImageFilename(workflowName, fallbackWorkflowName)}.png`);
};
+const SOURCE_IMAGE_SELECTOR = '[data-workflow-export-field-value="true"] img';
+
+/** Decode concurrently before html-to-image freezes computed image dimensions. */
+const decodeSourceImages = async (flowElement: HTMLElement): Promise<Map<HTMLImageElement, string>> => {
+ const images = Array.from(flowElement.querySelectorAll<HTMLImageElement>(SOURCE_IMAGE_SELECTOR));
+ const decoded = new Map<HTMLImageElement, string>();
+ if (!images.length) {
+ return decoded;
+ }
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ Promise.all(
+ images.map((image) => {
+ const source = image.src;
+ return image.decode().then(
+ () => {
+ if (image.naturalWidth > 0 && image.naturalHeight > 0 && image.src === source) {
+ decoded.set(image, source);
+ }
+ },
+ () => undefined
+ );
+ })
+ ),
+ new Promise<void>((resolve) => {
+ timeoutId = setTimeout(resolve, WORKFLOW_EXPORT_IMAGE_TIMEOUT_MS);
+ }),
+ ]);
+ // Late decodes must not change which images this export includes.
+ return new Map(decoded);
+ } finally {
+ if (timeoutId !== undefined) {
+ clearTimeout(timeoutId);
+ }
+ }
+};
+
+const replaceFailedSourceImages = (
+ flowElement: HTMLElement,
+ clone: HTMLElement,
+ decoded: Map<HTMLImageElement, string>
+) => {
+ const sourceImages = flowElement.querySelectorAll<HTMLImageElement>(SOURCE_IMAGE_SELECTOR);
+ clone.querySelectorAll<HTMLImageElement>(SOURCE_IMAGE_SELECTOR).forEach((image, index) => {
+ const original = sourceImages[index];
+ if (original && decoded.get(original) === original.src && original.src === image.src) {
+ return;
+ }
+ const fallback = document.createElement('span');
+ fallback.textContent = image.alt;
+ fallback.style.overflowWrap = 'anywhere';
+ fallback.style.maxWidth = '100%';
+ image.replaceWith(fallback);
+ });
+};
+
export const exportWorkflowAsPng = async ({
flowElement,
bounds,
@@ -526,12 +584,14 @@ export const exportWorkflowAsPng = async ({
throw new Error('A previous workflow image export is still running');
}
+ const decoded = await decodeSourceImages(flowElement);
const contentBounds = getWorkflowContentBounds(flowElement, bounds, { includeInputFieldLabels: false });
const dimensions = getWorkflowImageDimensions(contentBounds);
const clone = flowElement.cloneNode(true) as HTMLElement;
const stagingWrapper = document.createElement('div');
try {
+ replaceFailedSourceImages(flowElement, clone, decoded);
namespaceWorkflowExportIds(clone);
prepareExportClone(clone, contentBounds, dimensions);
Object.assign(stagingWrapper.style, getWorkflowExportStagingStyle(dimensions));
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index e53c57724f..9fe1c20682 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -1937,31 +1937,26 @@ const SNAPSHOT_VALUE_TEXT_PROPS = {
whiteSpace: 'pre-wrap',
} as const;
-/** Use the freshest cached name without fetching or notifying the child-signature synchronizer. */
+/** Prefer detail metadata: appending picker pages does not refresh earlier records. */
const SavedWorkflowSnapshot = ({ workflowId }: { workflowId: string }) => {
const queryClient = useQueryClient();
const getName = useCallback(() => {
const detailKey = savedWorkflowDetailQueryKey(workflowId);
const record = queryClient.getQueryData<WorkflowRecordDTO>(detailKey);
- let name = record?.name || workflowId;
- let updatedAt = record?.name ? (queryClient.getQueryState(detailKey)?.dataUpdatedAt ?? 0) : -1;
- for (const [key, pages] of queryClient.getQueriesData<InfiniteData<WorkflowLibraryPage>>({
+ if (record?.name) {
+ return record.name;
+ }
+ for (const [, pages] of queryClient.getQueriesData<InfiniteData<WorkflowLibraryPage>>({
queryKey: savedWorkflowPickerQueryKeyPrefix,
})) {
- const pickerUpdatedAt = queryClient.getQueryState(key)?.dataUpdatedAt ?? 0;
- if (pickerUpdatedAt < updatedAt) {
- continue;
- }
for (const page of pages?.pages ?? []) {
const workflow = page.items.find((item) => item.workflow_id === workflowId);
if (workflow?.name) {
- name = workflow.name;
- updatedAt = pickerUpdatedAt;
- break;
+ return workflow.name;
}
}
}
- return name;
+ return workflowId;
}, [queryClient, workflowId]);
const subscribe = useCallback(
(onChange: () => void) =>
@@ -2022,7 +2017,7 @@ export const WorkflowFieldSnapshot = ({
{names.map((name) => (
<Box key={name} aspectRatio="1" bg="bg.subtle" rounded="xs">
<Image
- alt=""
+ alt={name}
h="full"
objectFit="cover"
rounded="xs"
@@ -2034,7 +2029,13 @@ export const WorkflowFieldSnapshot = ({
</SimpleGrid>
) : (
<Flex align="center" borderWidth="1px" h="32" justify="center" overflow="hidden" rounded="sm" w="full">
- <Image alt="" maxH="full" maxW="full" objectFit="contain" src={galleryImageUrls.thumbnail(names[0]!)} />
+ <Image
+ alt={names[0]!}
+ maxH="full"
+ maxW="full"
+ objectFit="contain"
+ src={galleryImageUrls.thumbnail(names[0]!)}
+ />
</Flex>
)}
<Text {...SNAPSHOT_VALUE_TEXT_PROPS}>{text}</Text>