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.

feat(webv2): set workflow thumbnails from the gallery or a graph snapshot

Josh Corbettead2d2db12fe
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 820adbf402..5957bd6ca9 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -55,6 +55,7 @@
"ag-psd": "^31.0.2",
"fflate": "^0.8.3",
"fuzzysort": "^4.0.2",
+ "html-to-image": "^1.11.13",
"i18next": "^26.4.2",
"i18next-http-backend": "^4.0.2",
"idb": "^8.0.3",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 536ed05daa..a7238516dc 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -3548,6 +3548,7 @@
"source:src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx",
"source:src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx",
"source:src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx",
+ "source:src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.tsx",
"source:src/features/workflow/ui/graph-preview/flowTheme.ts",
"source:src/features/workflow/ui/graph-preview/index.ts",
"source:src/features/workflow/ui/graph-preview/nodeSummaries.ts",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index 48d454ecb3..b9b4768716 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -55,6 +55,9 @@ importers:
fuzzysort:
specifier: ^4.0.2
version: 4.0.2
+ html-to-image:
+ specifier: ^1.11.13
+ version: 1.11.13
i18next:
specifier: ^26.4.2
version: 26.4.2([email protected])
@@ -1566,6 +1569,9 @@ packages:
resolution: {integrity: sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw==}
+ resolution: {integrity: sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==}
+
resolution: {integrity: sha512-oay62dIB2kL7+WHzoUXBjWfL3+mwijD3pQkQkIEaRLhy6kjXxUhrRenV0gInwlCASAaJaDy94+XvYizK+cAGdA==}
engines: {node: '>=18'}
@@ -3696,6 +3702,8 @@ snapshots:
+
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index f212e8033e..d0884ffae6 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4319,16 +4319,14 @@
"thisProject": "This project",
"thisProjectHint": "Workflows saved with this project. Edits autosave here; the library changes only when you save to it.",
"thumbnail": "Thumbnail",
- "thumbnailChooseTitle": "Choose a thumbnail from the gallery",
- "thumbnailFromGallery": "From gallery",
- "thumbnailNotAnImage": "The chosen file is not an image.",
+ "thumbnailChoose": "Choose thumbnail",
"thumbnailRemove": "Remove thumbnail",
"thumbnailRemoveFailed": "Failed to remove thumbnail",
"thumbnailRemoved": "Thumbnail removed",
+ "thumbnailSnapshot": "Snapshot the graph",
"thumbnailUpdateFailed": "Failed to update thumbnail",
"thumbnailUpdated": "Thumbnail updated",
"thumbnailUpdating": "Updating thumbnail…",
- "thumbnailUpload": "Upload",
"title": "Workflows",
"unavailableBundledBody": "\"{{name}}\" came from a bundled template, which cannot be changed. Save it as a new template instead.",
"unavailableForbiddenBody": "The library template behind \"{{name}}\" belongs to someone else. Save it as a new template instead.",
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx
index 7a248e402a..9fe8047add 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx
@@ -29,6 +29,8 @@ export interface GalleryPickerPopoverProps {
accept: GalleryPickerAccept;
/** The trigger element; must accept a ref and a click handler. */
children: ReactElement;
+ /** Shared with a Tooltip wrapping an icon-only trigger (see `useTooltipTriggerIds`). */
+ ids?: { trigger: string };
/** The dialog's accessible name, e.g. "Choose image". */
label: string;
selection?: GalleryPickerSelection;
@@ -39,6 +41,7 @@ export interface GalleryPickerPopoverProps {
export const GalleryPickerPopover = ({
accept,
children,
+ ids,
label,
selection = SINGLE_SELECTION,
onPick,
@@ -53,6 +56,7 @@ export const GalleryPickerPopover = ({
return (
<Popover.Root
+ ids={ids}
initialFocusEl={getInitialFocusEl}
lazyMount
open={isOpen}
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.tsx
index afcd3dfa1c..da88b4bf5b 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
@@ -14,6 +14,9 @@ import { GraphPreviewFlow } from './GraphPreviewFlow';
import { GraphPreviewOpenAsMenu } from './GraphPreviewOpenAsMenu';
import { GraphPreviewSidePanel } from './GraphPreviewSidePanel';
+// Loaded through this module so the snapshot shares the dialog's chunk; a second entry splits the flow out of it.
+export { GraphPreviewSnapshot } from './GraphPreviewSnapshot';
+
interface GraphPreviewDialogProps {
graphId: string;
isOpen: boolean;
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.browser.test.tsx
new file mode 100644
index 0000000000..61deb61e09
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.browser.test.tsx
@@ -0,0 +1,92 @@
+import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@features/workflow/ui/WorkflowUiContext', async () => {
+ const { DEFAULT_THEME_ID } = await import('@theme/themes');
+ return {
+ useWorkflowPreferencesSelector: (selector: (preferences: { themeId: string }) => unknown) =>
+ selector({ themeId: DEFAULT_THEME_ID }),
+ };
+});
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const { GraphPreviewSnapshot } = await import('./GraphPreviewSnapshot');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const GRAPH: WorkflowPreviewGraph = {
+ edges: [
+ { id: 'e1', sourceField: 'value', sourceNodeId: 'seed', targetField: 'seed', targetNodeId: 'noise' },
+ { id: 'e2', sourceField: 'noise', sourceNodeId: 'noise', targetField: 'noise', targetNodeId: 'denoise' },
+ ],
+ id: 'snapshot-graph',
+ nodes: [
+ { id: 'seed', inputs: { value: 1 }, type: 'integer' },
+ { id: 'noise', inputs: {}, type: 'noise' },
+ { id: 'denoise', inputs: { steps: 30 }, type: 'denoise_latents' },
+ ],
+};
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+/** Pixels that differ from the corner pixel, i.e. anything painted over the background. */
+const countPaintedPixels = async (image: Blob): Promise<{ height: number; painted: number; width: number }> => {
+ const bitmap = await createImageBitmap(image);
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d')!;
+ context.drawImage(bitmap, 0, 0);
+ const { data } = context.getImageData(0, 0, bitmap.width, bitmap.height);
+ const [r, g, b] = [data[0], data[1], data[2]];
+ let painted = 0;
+
+ for (let index = 0; index < data.length; index += 4) {
+ if (Math.abs(data[index]! - r!) + Math.abs(data[index + 1]! - g!) + Math.abs(data[index + 2]! - b!) > 24) {
+ painted += 1;
+ }
+ }
+
+ return { height: bitmap.height, painted, width: bitmap.width };
+};
+
+describe('GraphPreviewSnapshot', () => {
+ it('captures the rendered graph, not just its background, at the thumbnail shape', async () => {
+ const onCapture = vi.fn();
+ const onError = vi.fn();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <GraphPreviewSnapshot graph={GRAPH} onCapture={onCapture} onError={onError} />
+ </ChakraProvider>
+ );
+ });
+
+ await vi.waitFor(() => expect(onCapture.mock.calls.length + onError.mock.calls.length).toBe(1), {
+ timeout: 15_000,
+ });
+ expect(onError).not.toHaveBeenCalled();
+
+ const image = onCapture.mock.calls[0]![0] as Blob;
+ expect(image.type).toBe('image/png');
+ const { height, painted, width } = await countPaintedPixels(image);
+ expect([width, height]).toEqual([960, 640]);
+ // Three node cards and their edges cover well over a percent of the frame.
+ expect(painted).toBeGreaterThan(width * height * 0.01);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.tsx
new file mode 100644
index 0000000000..f24aadd227
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.tsx
@@ -0,0 +1,106 @@
+import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';
+import type { XYPosition } from '@xyflow/react';
+
+import { Box, Portal } from '@chakra-ui/react';
+import { useCallback, useRef } from 'react';
+
+import { GraphPreviewFlow } from './GraphPreviewFlow';
+
+/** Rendered at the workflow thumbnail's 3:2 shape; the server keeps a 256px copy, so this leaves room to downscale. */
+const SNAPSHOT_WIDTH_PX = 960;
+const SNAPSHOT_HEIGHT_PX = 640;
+const SNAPSHOT_TIMEOUT_MS = 15_000;
+/** Off-screen but laid out and painted: `html-to-image` copies computed styles, which hidden elements lose. */
+const STAGE_STYLE = {
+ height: `${SNAPSHOT_HEIGHT_PX}px`,
+ left: '-10000px',
+ pointerEvents: 'none',
+ position: 'fixed',
+ top: 0,
+ width: `${SNAPSHOT_WIDTH_PX}px`,
+} as const;
+
+const nextFrame = () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+
+/** Captures the graph surface, not the off-screen stage around it: a clone of the fixed stage paints nothing. */
+const captureSurface = async (surface: HTMLElement): Promise<Blob> => {
+ // Loaded on first use: only a snapshot needs the rasterizer.
+ const { toBlob } = await import('html-to-image');
+ let timeout: number | undefined;
+ const blob = await Promise.race([
+ toBlob(surface, {
+ backgroundColor: getComputedStyle(surface).backgroundColor,
+ height: SNAPSHOT_HEIGHT_PX,
+ pixelRatio: 1,
+ width: SNAPSHOT_WIDTH_PX,
+ }),
+ new Promise<never>((_resolve, reject) => {
+ timeout = window.setTimeout(() => reject(new Error('Timed out capturing the graph.')), SNAPSHOT_TIMEOUT_MS);
+ }),
+ ]).finally(() => window.clearTimeout(timeout));
+
+ if (!blob) {
+ throw new Error('The graph could not be captured.');
+ }
+
+ return blob;
+};
+
+/**
+ * Renders a graph preview off-screen, fits it, and hands back a PNG of it once: the "photo" of a workflow that the
+ * legacy editor's camera exported (#9501), used here for library thumbnails. Mount it to capture; unmount after.
+ */
+export const GraphPreviewSnapshot = ({
+ graph,
+ positionHints,
+ onCapture,
+ onError,
+}: {
+ graph: WorkflowPreviewGraph;
+ positionHints?: Record<string, XYPosition>;
+ onCapture: (image: Blob) => void;
+ onError: (error: unknown) => void;
+}) => {
+ const stageRef = useRef<HTMLDivElement | null>(null);
+ const hasStartedRef = useRef(false);
+
+ const handleInit = useCallback(
+ (instance: { fitView: (options?: { padding?: number }) => unknown }) => {
+ if (hasStartedRef.current) {
+ return;
+ }
+ hasStartedRef.current = true;
+
+ void (async () => {
+ try {
+ instance.fitView({ padding: 0.08 });
+ // One frame for the viewport transform, one for the nodes to paint at it.
+ await nextFrame();
+ await nextFrame();
+
+ const surface = stageRef.current?.firstElementChild;
+
+ if (!(surface instanceof HTMLElement)) {
+ throw new Error('The graph preview unmounted before it could be captured.');
+ }
+
+ onCapture(await captureSurface(surface));
+ } catch (error) {
+ onError(error);
+ }
+ })();
+ },
+ [onCapture, onError]
+ );
+
+ return (
+ <Portal>
+ <Box ref={stageRef} aria-hidden style={STAGE_STYLE}>
+ <GraphPreviewFlow graph={graph} positionHints={positionHints} onInit={handleInit} />
+ </Box>
+ </Portal>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
index 870b4e32be..74a477b25c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
@@ -1,3 +1,4 @@
+import type { GalleryHost } from '@features/gallery/picker';
import type { StarterModel } from '@features/models';
import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';
import type { ProjectWorkflowEntry } from '@features/workflow/core/types';
@@ -5,13 +6,15 @@ import type { WorkflowLibraryEntry, WorkflowLibraryEntryEnrichment } from '@feat
import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';
import { ChakraProvider } from '@chakra-ui/react';
+import { GalleryHostProvider } from '@features/gallery/picker';
import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';
import { createProjectGraph, serializeWorkflowJson } from '@features/workflow/utility';
import { system } from '@theme/system';
import { act, StrictMode, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { loadGraphPreview } from './libraryPreviewSource';
import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';
/**
@@ -84,11 +87,36 @@ vi.mock('@features/workflow/queries', async (importOriginal) => ({
}));
/** The picker's own view is covered by its tests; here a pick hands over an item whose thumbnail is a data URL. */
+/** The workbench derives this from its Gallery adapter; the panel only needs somewhere to report slot errors. */
+const GALLERY_HOST: GalleryHost = {
+ galleryValues: {},
+ notifications: { add: vi.fn(), reportError: vi.fn() },
+ projectName: '',
+};
+
const pickedGalleryItem = vi.hoisted(() => ({
current: { kind: 'image', name: 'picked.gif', thumbnailUrl: '' } as Record<string, unknown>,
}));
-vi.mock('@features/gallery/picker', async (importOriginal) => ({
+// Node definitions are loaded, so a template's document compiles for the snapshot.
+vi.mock('@features/workflow/react', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useInvocationTemplatesSnapshot: () => ({ error: null, status: 'loaded', templates: {} }),
+}));
+
+/** Its own test covers the off-screen capture; here it hands back a finished image as soon as it mounts. */
+const SNAPSHOT_IMAGE = vi.hoisted(() => new Blob(['snapshot'], { type: 'image/png' }));
+const snapshotCapture = vi.hoisted(() => ({ settles: true }));
+vi.mock('@features/workflow/ui/graph-preview/GraphPreviewSnapshot', () => ({
+ GraphPreviewSnapshot: ({ onCapture }: { onCapture: (image: Blob) => void }) => {
+ if (snapshotCapture.settles) {
+ queueMicrotask(() => onCapture(SNAPSHOT_IMAGE));
+ }
+ return null;
+ },
+}));
+
+vi.mock('@features/gallery/ui/picker/GalleryPickerPopover', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
GalleryPickerPopover: ({ children, onPick }: { children: ReactNode; onPick: (item: unknown) => void }) => (
<>
@@ -124,15 +152,14 @@ const TRANSLATIONS: Record<string, string> = {
'workflowLibrary.renamed': 'Template renamed',
'workflowLibrary.templateName': 'Template name',
'workflowLibrary.thumbnail': 'Thumbnail',
- 'workflowLibrary.thumbnailFromGallery': 'From gallery',
- 'workflowLibrary.thumbnailNotAnImage': 'The chosen file is not an image.',
+ 'workflowLibrary.thumbnailChoose': 'Choose thumbnail',
'workflowLibrary.thumbnailRemove': 'Remove thumbnail',
'workflowLibrary.thumbnailRemoveFailed': 'Failed to remove thumbnail',
'workflowLibrary.thumbnailRemoved': 'Thumbnail removed',
+ 'workflowLibrary.thumbnailSnapshot': 'Snapshot the graph',
'workflowLibrary.thumbnailUpdateFailed': 'Failed to update thumbnail',
'workflowLibrary.thumbnailUpdated': 'Thumbnail updated',
'workflowLibrary.thumbnailUpdating': 'Updating thumbnail…',
- 'workflowLibrary.thumbnailUpload': 'Upload',
'workflowLibrary.duplicateHint': 'Saves a copy under Yours, original untouched',
'workflowLibrary.duplicateName': '{{name}} copy',
'workflowLibrary.duplicated': 'Saved a copy under Yours',
@@ -350,21 +377,23 @@ describe('WorkflowLibraryDetailPanel', () => {
<StrictMode>
<ChakraProvider value={system}>
<WorkflowUiProvider adapter={ADAPTER}>
- <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
- <WorkflowLibraryDetailPanel
- contextMenuPoint={null}
- contextMenuTriggerId={null}
- entry={selected}
- projectWorkflows={projectWorkflows}
- onClose={onClose}
- onContextMenuClose={NOOP}
- onDeleted={onDeleted}
- onDuplicated={onDuplicated}
- onOpen={onOpen}
- onPreview={onPreview}
- onResume={onResume}
- />
- </WorkflowGraphPreviewProvider>
+ <GalleryHostProvider host={GALLERY_HOST}>
+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
+ <WorkflowLibraryDetailPanel
+ contextMenuPoint={null}
+ contextMenuTriggerId={null}
+ entry={selected}
+ projectWorkflows={projectWorkflows}
+ onClose={onClose}
+ onContextMenuClose={NOOP}
+ onDeleted={onDeleted}
+ onDuplicated={onDuplicated}
+ onOpen={onOpen}
+ onPreview={onPreview}
+ onResume={onResume}
+ />
+ </WorkflowGraphPreviewProvider>
+ </GalleryHostProvider>
</WorkflowUiProvider>
</ChakraProvider>
</StrictMode>
@@ -941,40 +970,43 @@ describe('WorkflowLibraryDetailPanel', () => {
});
describe('thumbnail', () => {
- const thumbnailGroup = () => document.querySelector<HTMLElement>('[role="group"][aria-label="Thumbnail"]');
- const thumbnailButton = (text: string) =>
- [...(thumbnailGroup()?.querySelectorAll('button') ?? [])].find(
- (candidate) => (candidate.getAttribute('aria-label') ?? candidate.textContent ?? '').trim() === text
- );
-
- const chooseFile = async (file: File) => {
- const input = thumbnailGroup()?.querySelector<HTMLInputElement>('input[type="file"]');
- expect(input).not.toBeNull();
-
- const transfer = new DataTransfer();
- transfer.items.add(file);
+ // The library dialog preloads the preview chunk as it opens; a cold import can outlast `waitFor` under load.
+ beforeAll(() => loadGraphPreview());
+ const buttonNamed = (name: string) =>
+ [...(panel()?.querySelectorAll('button') ?? [])].find(
+ (candidate) => (candidate.getAttribute('aria-label') ?? candidate.textContent ?? '').trim() === name
+ );
+ const choose = () => buttonNamed('Choose thumbnail');
+ const pick = async (item: Record<string, unknown>) => {
+ pickedGalleryItem.current = item;
await act(async () => {
- input!.files = transfer.files;
- input!.dispatchEvent(new Event('change', { bubbles: true }));
+ document.querySelector<HTMLElement>('[data-gallery-pick]')?.click();
await settleFrame();
});
};
+ const GIF_ITEM = {
+ kind: 'image',
+ name: 'picked.gif',
+ thumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
+ };
- it("is editable only on the account's own templates, and offers Remove only once one is set", async () => {
+ it("is chosen from the preview's corner only on the account's own templates, with Remove once one is set", async () => {
await renderPanel(DEFAULT_CATEGORY);
- expect(thumbnailGroup()).toBeNull();
+ expect(choose()).toBeUndefined();
await renderPanel(entry({ name: 'Plain', workflow_id: 'wf-plain' }, readyEnrichment(SDXL_REQUIREMENTS)));
- expect(thumbnailButton('From gallery')).not.toBeUndefined();
- expect(thumbnailButton('Upload')).not.toBeUndefined();
- expect(thumbnailButton('Remove thumbnail')).toBeUndefined();
+ expect(choose()).not.toBeUndefined();
+ expect(buttonNamed('Remove thumbnail')).toBeUndefined();
+ // No separate upload: the gallery picker the corner button opens uploads new files itself.
+ expect(buttonNamed('Upload')).toBeUndefined();
await renderPanel(TEXT_TO_IMAGE);
- expect(thumbnailButton('Remove thumbnail')).not.toBeUndefined();
+ expect(choose()).not.toBeUndefined();
+ expect(buttonNamed('Remove thumbnail')).not.toBeUndefined();
});
- it('uploads a chosen file, holding the controls busy until the library answers', async () => {
+ it('stores a picked gallery image, holding the slot busy until the library answers', async () => {
let answer: () => void = NOOP;
queries.setLibraryWorkflowThumbnail.mockImplementation(
() =>
@@ -982,27 +1014,22 @@ describe('WorkflowLibraryDetailPanel', () => {
answer = resolve;
})
);
- const file = new File([new Uint8Array([1, 2, 3])], 'cover.png', { type: 'image/png' });
await renderPanel(TEXT_TO_IMAGE);
const status = panel()?.querySelector('[role="status"]');
expect(status?.textContent).toBe('');
- thumbnailButton('Upload')?.focus();
- await chooseFile(file);
+ await pick(GIF_ITEM);
+ await vi.waitFor(() => expect(queries.setLibraryWorkflowThumbnail).toHaveBeenCalled());
- expect(queries.setLibraryWorkflowThumbnail).toHaveBeenCalledWith('wf-text-to-image', file, expect.anything());
- // The same live region carries the change, and the busy control keeps focus.
+ const [workflowId, image] = queries.setLibraryWorkflowThumbnail.mock.calls[0]!;
+ expect(workflowId).toBe('wf-text-to-image');
+ expect(image.type).toBe('image/gif');
+ // The same live region carries the change while the slot waits.
expect(panel()?.querySelector('[role="status"]')).toBe(status);
expect(status?.textContent).toBe('Updating thumbnail…');
- expect(document.activeElement).toBe(thumbnailButton('Upload'));
- expect(thumbnailButton('Upload')?.getAttribute('aria-disabled')).toBe('true');
- expect(thumbnailButton('Remove thumbnail')?.getAttribute('aria-disabled')).toBe('true');
- await act(async () => {
- thumbnailButton('Remove thumbnail')?.click();
- await settleFrame();
- });
- expect(queries.deleteLibraryWorkflowThumbnail).not.toHaveBeenCalled();
expect(panel()?.querySelector('[aria-busy="true"]')).not.toBeNull();
+ expect(choose()?.getAttribute('aria-disabled')).toBe('true');
+ expect(buttonNamed('Remove thumbnail')?.getAttribute('aria-disabled')).toBe('true');
expect(queries.invalidateWorkflowLibraryCache).not.toHaveBeenCalled();
await act(async () => {
@@ -1011,22 +1038,20 @@ describe('WorkflowLibraryDetailPanel', () => {
});
expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledWith('wf-text-to-image');
- expect(thumbnailButton('Upload')?.hasAttribute('aria-disabled')).toBe(false);
expect(panel()?.querySelector('[aria-busy="true"]')).toBeNull();
+ expect(choose()?.hasAttribute('aria-disabled')).toBe(false);
expect(status?.textContent).toBe('Thumbnail updated');
- expect(document.activeElement).toBe(thumbnailButton('Upload'));
});
it('does not carry a busy upload over to the next selected workflow', async () => {
queries.setLibraryWorkflowThumbnail.mockImplementation(() => new Promise<void>(NOOP));
await renderPanel(TEXT_TO_IMAGE);
- await chooseFile(new File([new Uint8Array([1])], 'cover.png', { type: 'image/png' }));
- expect(panel()?.querySelector('[aria-busy="true"]')).not.toBeNull();
+ await pick(GIF_ITEM);
+ await vi.waitFor(() => expect(panel()?.querySelector('[aria-busy="true"]')).not.toBeNull());
await renderPanel(IMAGE_TO_VIDEO);
expect(panel()?.querySelector('[aria-busy="true"]')).toBeNull();
- expect(thumbnailButton('Upload')?.hasAttribute('aria-disabled')).toBe(false);
expect(panel()?.querySelector('[role="status"]')?.textContent).toBe('');
});
@@ -1034,53 +1059,22 @@ describe('WorkflowLibraryDetailPanel', () => {
queries.setLibraryWorkflowThumbnail.mockRejectedValue(new Error('Not an image'));
await renderPanel(TEXT_TO_IMAGE);
- await chooseFile(new File([new Uint8Array([1])], 'cover.png', { type: 'image/png' }));
+ await pick(GIF_ITEM);
+ await vi.waitFor(() => expect(NOTIFICATIONS.error).toHaveBeenCalled());
expect(NOTIFICATIONS.error).toHaveBeenCalledWith('Failed to update thumbnail', 'Not an image');
expect(queries.invalidateWorkflowLibraryCache).not.toHaveBeenCalled();
expect(panel()?.querySelector('[role="status"]')?.textContent).toBe('');
});
- it('refuses a file that is not an image before sending anything', async () => {
- await renderPanel(TEXT_TO_IMAGE);
- await chooseFile(new File(['{}'], 'workflow.json', { type: 'application/json' }));
-
- expect(queries.setLibraryWorkflowThumbnail).not.toHaveBeenCalled();
- expect(NOTIFICATIONS.error).toHaveBeenCalledWith(
- 'Failed to update thumbnail',
- 'The chosen file is not an image.'
- );
- });
-
- it('uploads the picked gallery image', async () => {
- pickedGalleryItem.current = {
- kind: 'image',
- name: 'picked.gif',
- thumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
- };
-
- await renderPanel(TEXT_TO_IMAGE);
- await act(async () => {
- document.querySelector<HTMLElement>('[data-gallery-pick]')?.click();
- await vi.waitFor(() => expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalled());
- });
-
- const [workflowId, image] = queries.setLibraryWorkflowThumbnail.mock.calls[0]!;
- expect(workflowId).toBe('wf-text-to-image');
- expect(image.type).toBe('image/gif');
- expect(image.size).toBeGreaterThan(0);
- });
it('does not upload a gallery image that failed to load', async () => {
- pickedGalleryItem.current = { kind: 'image', name: 'gone.png', thumbnailUrl: '/gone-thumbnail.webp' };
const fetchSpy = vi
.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(new Response(null, { status: 404, statusText: 'Not Found' }));
await renderPanel(TEXT_TO_IMAGE);
- await act(async () => {
- document.querySelector<HTMLElement>('[data-gallery-pick]')?.click();
- await vi.waitFor(() => expect(NOTIFICATIONS.error).toHaveBeenCalled());
- });
+ await pick({ kind: 'image', name: 'gone.png', thumbnailUrl: '/gone-thumbnail.webp' });
+ await vi.waitFor(() => expect(NOTIFICATIONS.error).toHaveBeenCalled());
expect(NOTIFICATIONS.error).toHaveBeenCalledWith('Failed to update thumbnail', expect.stringContaining('404'));
expect(fetchSpy).toHaveBeenCalledWith('/gone-thumbnail.webp', expect.anything());
@@ -1088,24 +1082,69 @@ describe('WorkflowLibraryDetailPanel', () => {
fetchSpy.mockRestore();
});
- it('removes the custom image, and reports a failure without refreshing the library', async () => {
+ it('snapshots the graph once its document has loaded, storing the captured image', async () => {
+ const snapshot = () => buttonNamed('Snapshot the graph');
+
+ await renderPanel(entry({ name: 'Pending', workflow_id: 'wf-pending' }, { status: 'pending' }));
+ // Nothing to render until the template's document has been read.
+ expect(snapshot()?.getAttribute('aria-disabled')).toBe('true');
+
+ await renderPanel(TEXT_TO_IMAGE);
+ expect(snapshot()?.hasAttribute('aria-disabled')).toBe(false);
+ await act(async () => {
+ snapshot()?.click();
+ await settleFrame();
+ });
+
+ await vi.waitFor(() =>
+ expect(queries.setLibraryWorkflowThumbnail).toHaveBeenCalledWith(
+ 'wf-text-to-image',
+ SNAPSHOT_IMAGE,
+ expect.anything()
+ )
+ );
+ await vi.waitFor(() => expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledWith('wf-text-to-image'));
+ });
+
+ it('drops a snapshot still being captured when another workflow is selected, without reporting it', async () => {
+ snapshotCapture.settles = false;
+
+ try {
+ await renderPanel(TEXT_TO_IMAGE);
+ await act(async () => {
+ buttonNamed('Snapshot the graph')?.click();
+ await settleFrame();
+ });
+ expect(buttonNamed('Snapshot the graph')?.getAttribute('aria-disabled')).toBe('true');
+
+ await renderPanel(entry({ name: 'Other', workflow_id: 'wf-other' }, readyEnrichment(SDXL_REQUIREMENTS)));
+ await act(() => settleFrame());
+
+ expect(NOTIFICATIONS.error).not.toHaveBeenCalled();
+ expect(queries.setLibraryWorkflowThumbnail).not.toHaveBeenCalled();
+ } finally {
+ snapshotCapture.settles = true;
+ }
+ });
+
+ it('removes the custom image, handing focus to the choose button, and reports a failure without refreshing', async () => {
await renderPanel(TEXT_TO_IMAGE);
- thumbnailButton('Remove thumbnail')?.focus();
+ buttonNamed('Remove thumbnail')?.focus();
await act(async () => {
- thumbnailButton('Remove thumbnail')?.click();
+ buttonNamed('Remove thumbnail')?.click();
await settleFrame();
});
expect(queries.deleteLibraryWorkflowThumbnail).toHaveBeenCalledWith('wf-text-to-image', expect.anything());
expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledWith('wf-text-to-image');
- // Remove disappears with the refreshed record, so focus has already moved on.
- expect(document.activeElement).toBe(thumbnailButton('Upload'));
+ // Remove goes away with the refreshed record; focus has already moved to the choose button beside it.
+ expect(document.activeElement).toBe(choose());
expect(panel()?.querySelector('[role="status"]')?.textContent).toBe('Thumbnail removed');
queries.invalidateWorkflowLibraryCache.mockClear();
queries.deleteLibraryWorkflowThumbnail.mockRejectedValue(new Error('network down'));
await act(async () => {
- thumbnailButton('Remove thumbnail')?.click();
+ buttonNamed('Remove thumbnail')?.click();
await settleFrame();
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
index 5c0463c777..e00869390c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
@@ -513,7 +513,11 @@ export const WorkflowLibraryDetailPanel = ({
>
<Scrollable flex="1" label={name} minH="0">
<Stack gap="2" minW="0" p="2.5">
- <WorkflowLibraryThumbnail key={item.workflow_id} item={item} />
+ <WorkflowLibraryThumbnail
+ key={item.workflow_id}
+ item={item}
+ workflowDocument={entry.enrichment.status === 'ready' ? entry.enrichment.document : null}
+ />
{/*
* Wrap full names, including delimiter-free strings, in the detail rail; zero content min-width permits
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx
index 12225958be..9ab1e41cde 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx
@@ -18,6 +18,7 @@ import type {
} from '@features/workflow/ui/WorkflowUiContext';
import { ChakraProvider } from '@chakra-ui/react';
+import { GalleryHostProvider, type GalleryHost } from '@features/gallery/picker';
import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';
import {
openWorkflowLibraryAtProjectWorkflow,
@@ -36,6 +37,13 @@ import '@features/workflow/ui/graph-preview/GraphPreviewDialog';
import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';
+/** In the app the workbench derives this from its Gallery adapter; the library's thumbnail slot reads it. */
+const GALLERY_HOST: GalleryHost = {
+ galleryValues: {},
+ notifications: { add: vi.fn(), reportError: vi.fn() },
+ projectName: '',
+};
+
// Provide the fixture node's reactive template snapshot so preview compilation can run without backend schema
// loading.
const PREVIEW_NODE_TEMPLATE: InvocationTemplate = {
@@ -420,9 +428,11 @@ describe('WorkflowLibraryDialog', () => {
<StrictMode>
<ChakraProvider value={system}>
<WorkflowUiProvider adapter={UI_ADAPTER}>
- <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
- <WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />
- </WorkflowGraphPreviewProvider>
+ <GalleryHostProvider host={GALLERY_HOST}>
+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
+ <WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />
+ </WorkflowGraphPreviewProvider>
+ </GalleryHostProvider>
</WorkflowUiProvider>
</ChakraProvider>
</StrictMode>
@@ -1078,9 +1088,11 @@ describe('WorkflowLibraryDialog — This project', () => {
<StrictMode>
<ChakraProvider value={system}>
<WorkflowUiProvider adapter={UI_ADAPTER}>
- <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
- <WorkflowLibraryDialog isOpen onOpenChange={onOpenChange} />
- </WorkflowGraphPreviewProvider>
+ <GalleryHostProvider host={GALLERY_HOST}>
+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
+ <WorkflowLibraryDialog isOpen onOpenChange={onOpenChange} />
+ </WorkflowGraphPreviewProvider>
+ </GalleryHostProvider>
</WorkflowUiProvider>
</ChakraProvider>
</StrictMode>
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx
index 6a7f6d637f..b5c33142d9 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx
@@ -1,14 +1,19 @@
import type { GalleryItem } from '@features/gallery';
+import type { ProjectGraphState, XYPosition } from '@features/workflow/contracts';
import type { WorkflowLibraryListItem } from '@features/workflow/queries';
+import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';
-import { Box, Flex, HStack, Icon, Image, Spinner, Stack, Text } from '@chakra-ui/react';
-import { GalleryPickerPopover, getGalleryUploadAccept } from '@features/gallery/picker';
+import { Box, Flex, HStack, Icon, Image, Spinner, Stack, Text, type SystemStyleObject } from '@chakra-ui/react';
+import { GalleryPickerPopover } from '@features/gallery/picker';
+import { localizeForLoopValidationReason } from '@features/workflow/core/forLoops';
import {
deleteLibraryWorkflowThumbnail,
invalidateWorkflowLibraryCache,
setLibraryWorkflowThumbnail,
} from '@features/workflow/queries';
+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';
import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';
+import { useMountEffect } from '@platform/react/useMountEffect';
import {
type AccountScope,
assertAccountScopeCurrent,
@@ -16,33 +21,59 @@ import {
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
-import { Button, IconButton, Tooltip } from '@platform/ui';
-import { ChevronDownIcon, ImageOffIcon, ImagePlusIcon, Trash2Icon, UploadIcon } from 'lucide-react';
-import { useCallback, useRef, useState, type ChangeEvent, type MouseEvent } from 'react';
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
+import { CameraIcon, ImageOffIcon, Trash2Icon, UploadIcon } from 'lucide-react';
+import { Suspense, useCallback, useRef, useState, type MouseEvent } from 'react';
import { useTranslation } from 'react-i18next';
+import { buildLibraryGraphPreviewSource, DeferredGraphPreviewSnapshot, loadGraphPreview } from './libraryPreviewSource';
import { formatRelativeTime } from './relativeTime';
const THUMBNAIL_ASPECT_RATIO = 3 / 2;
const IMAGE_ONLY = ['image'] as const;
-const UPLOAD_ACCEPT = getGalleryUploadAccept(IMAGE_ONLY);
-/** Busy controls stay focusable (`aria-disabled`), so focus the picker or file dialog returns to survives the action. */
+/** Busy controls stay focusable (`aria-disabled`), so the focus the picker returns to survives the action. */
const preventClick = (event: MouseEvent) => event.preventDefault();
+const WELL_CSS: SystemStyleObject = {
+ aspectRatio: THUMBNAIL_ASPECT_RATIO,
+ bg: 'bg.muted',
+ overflow: 'hidden',
+ position: 'relative',
+ rounded: 'md',
+ w: 'full',
+};
/** Key by workflow id: an action in flight for one workflow must not show as busy on the next selection. */
-export const WorkflowLibraryThumbnail = ({ item }: { item: WorkflowLibraryListItem }) => {
+export const WorkflowLibraryThumbnail = ({
+ item,
+ workflowDocument,
+}: {
+ /** The template's parsed workflow once its row has loaded; the snapshot renders its graph. */
+ workflowDocument: ProjectGraphState | null;
+ item: WorkflowLibraryListItem;
+}) => {
const { t } = useTranslation();
const notify = useWorkflowNotifications();
- const inputRef = useRef<HTMLInputElement | null>(null);
// Keyed by URL: a replaced image arrives under a fresh URL and re-arms the thumbnail.
const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);
// Local rather than `useScopedAction`: the library ships in the editor boot graph, and a second importer of that
// models-only hook splits it into its own startup chunk.
const [isBusy, setIsBusy] = useState(false);
const isBusyRef = useRef(false);
+ const pendingSnapshotRef = useRef<{ reject: (error: unknown) => void } | null>(null);
+ const isMountedRef = useRef(true);
+ useMountEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ // Leaving the workflow abandons its snapshot; nothing is uploaded and nothing is reported.
+ isMountedRef.current = false;
+ pendingSnapshotRef.current?.reject(new Error('The snapshot was abandoned.'));
+ };
+ });
// One always-mounted live region: a region inserted together with its text is often not announced.
const [announcement, setAnnouncement] = useState('');
- const uploadButtonRef = useRef<HTMLButtonElement | null>(null);
+ const chooseButtonRef = useRef<HTMLButtonElement | null>(null);
+ const chooseIds = useTooltipTriggerIds();
const run = useCallback(
async (
action: (owner: AccountScope) => Promise<void>,
@@ -94,12 +125,70 @@ export const WorkflowLibraryThumbnail = ({ item }: { item: WorkflowLibraryListIt
invalidateWorkflowLibraryCache(workflowId);
},
t('workflowLibrary.thumbnailUpdated'),
- (error) =>
- notify.error(t('workflowLibrary.thumbnailUpdateFailed'), getApiErrorMessage(error, t('common.unknownError')))
+ (error) => {
+ if (isMountedRef.current) {
+ notify.error(
+ t('workflowLibrary.thumbnailUpdateFailed'),
+ getApiErrorMessage(error, t('common.unknownError'))
+ );
+ }
+ }
),
[notify, run, t, workflowId]
);
+ const templatesSnapshot = useInvocationTemplatesSnapshot();
+ const canSnapshot = workflowDocument !== null && templatesSnapshot.status === 'loaded';
+ // Settled by the off-screen preview once it has captured the graph.
+ const [snapshotRequest, setSnapshotRequest] = useState<{
+ graph: WorkflowPreviewGraph;
+ positionHints?: Record<string, XYPosition>;
+ reject: (error: unknown) => void;
+ resolve: (image: Blob) => void;
+ } | null>(null);
+ const takeSnapshot = useCallback(() => {
+ if (!workflowDocument || templatesSnapshot.status !== 'loaded') {
+ return;
+ }
+
+ void upload(async () => {
+ const source = buildLibraryGraphPreviewSource(workflowDocument, templatesSnapshot.templates);
+
+ if (!source.graph) {
+ const [reason] = source.invalidReasons;
+ throw new Error(reason ? localizeForLoopValidationReason(reason, t) : t('common.unknownError'));
+ }
+
+ const graph = source.graph;
+ await loadGraphPreview();
+
+ if (!isMountedRef.current) {
+ throw new Error('The snapshot was abandoned.');
+ }
+
+ return new Promise<Blob>((resolve, reject) => {
+ const settle = () => {
+ pendingSnapshotRef.current = null;
+ setSnapshotRequest(null);
+ };
+
+ pendingSnapshotRef.current = { reject };
+ setSnapshotRequest({
+ graph,
+ positionHints: source.positionHints,
+ reject: (error) => {
+ settle();
+ reject(error);
+ },
+ resolve: (image) => {
+ settle();
+ resolve(image);
+ },
+ });
+ });
+ });
+ }, [t, templatesSnapshot, upload, workflowDocument]);
+
// The server keeps a 256px copy, so the gallery's own thumbnail carries everything it will store.
const handlePick = useCallback(
(picked: GalleryItem) =>
@@ -115,28 +204,6 @@ export const WorkflowLibraryThumbnail = ({ item }: { item: WorkflowLibraryListIt
[upload]
);
- const openFilePicker = useCallback(() => inputRef.current?.click(), []);
- const handleFileChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const file = event.currentTarget.files?.[0];
-
- event.currentTarget.value = '';
-
- if (!file) {
- return;
- }
-
- // `accept` is advisory; the server takes only parts typed as images.
- if (!file.type.startsWith('image/')) {
- notify.error(t('workflowLibrary.thumbnailUpdateFailed'), t('workflowLibrary.thumbnailNotAnImage'));
- return;
- }
-
- void upload(() => Promise.resolve(file));
- },
- [notify, t, upload]
- );
-
const handleRemove = useCallback(
() =>
void run(
@@ -145,7 +212,7 @@ export const WorkflowLibraryThumbnail = ({ item }: { item: WorkflowLibraryListIt
assertAccountScopeCurrent(owner);
// Remove unmounts once the refreshed record arrives; hand focus on before it takes focus down with it.
if (document.activeElement?.closest('[data-thumbnail-remove]')) {
- uploadButtonRef.current?.focus();
+ chooseButtonRef.current?.focus();
}
invalidateWorkflowLibraryCache(workflowId);
},
@@ -165,40 +232,105 @@ export const WorkflowLibraryThumbnail = ({ item }: { item: WorkflowLibraryListIt
? t('workflowLibrary.sampleOutput')
: null;
+ const wellContent = (
+ <>
+ {showThumbnail ? (
+ <Image
+ alt=""
+ h="full"
+ objectFit="cover"
+ src={item.thumbnail_url ?? undefined}
+ w="full"
+ onError={handleThumbnailError}
+ />
+ ) : (
+ <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">
+ <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('workflowLibrary.notRunYet')}
+ </Text>
+ </Flex>
+ )}
+ {isBusy ? (
+ <Flex align="center" bg="bg.muted/90" inset="0" justify="center" position="absolute">
+ <Spinner size="sm" />
+ </Flex>
+ ) : null}
+ </>
+ );
+
return (
<Stack gap="1" minW="0">
- <Box
- aria-busy={isBusy || undefined}
- aspectRatio={THUMBNAIL_ASPECT_RATIO}
- bg="bg.muted"
- overflow="hidden"
- position="relative"
- rounded="md"
- w="full"
- >
- {showThumbnail ? (
- <Image
- alt=""
- h="full"
- objectFit="cover"
- src={item.thumbnail_url ?? undefined}
- w="full"
- onError={handleThumbnailError}
- />
- ) : (
- <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">
- <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />
- <Text color="fg.subtle" fontSize="2xs">
- {t('workflowLibrary.notRunYet')}
- </Text>
- </Flex>
- )}
- {isBusy ? (
- <Flex align="center" bg="bg.muted/90" inset="0" justify="center" position="absolute">
- <Spinner size="sm" />
- </Flex>
+ <Box aria-busy={isBusy || undefined} css={WELL_CSS}>
+ {wellContent}
+ {/* Bundled defaults keep their shipped image; the account's own templates choose theirs from the gallery. */}
+ {isEditable ? (
+ <HStack
+ aria-label={t('workflowLibrary.thumbnail')}
+ gap="1"
+ position="absolute"
+ right="1.5"
+ role="group"
+ top="1.5"
+ >
+ <GalleryPickerPopover
+ accept={IMAGE_ONLY}
+ ids={chooseIds}
+ label={t('workflowLibrary.thumbnailChoose')}
+ onPick={handlePick}
+ >
+ {/* Inside a dialog the tooltip must sit inside the popover trigger (see ProjectWorkflowsView). */}
+ <Tooltip content={t('workflowLibrary.thumbnailChoose')} ids={chooseIds}>
+ <IconButton
+ ref={chooseButtonRef}
+ aria-disabled={isBusy || undefined}
+ aria-label={t('workflowLibrary.thumbnailChoose')}
+ size="xs"
+ variant="outline"
+ onClickCapture={isBusy ? preventClick : undefined}
+ >
+ <UploadIcon />
+ </IconButton>
+ </Tooltip>
+ </GalleryPickerPopover>
+ <Tooltip content={t('workflowLibrary.thumbnailSnapshot')}>
+ <IconButton
+ aria-disabled={isBusy || !canSnapshot || undefined}
+ aria-label={t('workflowLibrary.thumbnailSnapshot')}
+ size="xs"
+ variant="outline"
+ onClick={isBusy || !canSnapshot ? undefined : takeSnapshot}
+ >
+ <CameraIcon />
+ </IconButton>
+ </Tooltip>
+ {item.thumbnail_url ? (
+ <Tooltip content={t('workflowLibrary.thumbnailRemove')}>
+ <IconButton
+ aria-disabled={isBusy || undefined}
+ aria-label={t('workflowLibrary.thumbnailRemove')}
+ data-thumbnail-remove
+ size="xs"
+ variant="outline"
+ onClick={isBusy ? undefined : handleRemove}
+ >
+ <Trash2Icon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ </HStack>
) : null}
</Box>
+ {snapshotRequest ? (
+ <Suspense fallback={null}>
+ <DeferredGraphPreviewSnapshot
+ graph={snapshotRequest.graph}
+ positionHints={snapshotRequest.positionHints}
+ onCapture={snapshotRequest.resolve}
+ onError={snapshotRequest.reject}
+ />
+ </Suspense>
+ ) : null}
<Text role="status" srOnly>
{announcement}
</Text>
@@ -207,52 +339,6 @@ export const WorkflowLibraryThumbnail = ({ item }: { item: WorkflowLibraryListIt
{caption}
</Text>
) : null}
- {isEditable ? (
- <HStack aria-label={t('workflowLibrary.thumbnail')} flexWrap="wrap" gap="0.5" role="group">
- <GalleryPickerPopover
- accept={IMAGE_ONLY}
- label={t('workflowLibrary.thumbnailChooseTitle')}
- onPick={handlePick}
- >
- <Button
- aria-disabled={isBusy || undefined}
- size="xs"
- variant="ghost"
- onClickCapture={isBusy ? preventClick : undefined}
- >
- <Icon as={ImagePlusIcon} boxSize="3.5" />
- {t('workflowLibrary.thumbnailFromGallery')}
- <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />
- </Button>
- </GalleryPickerPopover>
- <Button
- ref={uploadButtonRef}
- aria-disabled={isBusy || undefined}
- size="xs"
- variant="ghost"
- onClick={isBusy ? undefined : openFilePicker}
- >
- <Icon as={UploadIcon} boxSize="3" />
- {t('workflowLibrary.thumbnailUpload')}
- </Button>
- {item.thumbnail_url ? (
- <Tooltip content={t('workflowLibrary.thumbnailRemove')}>
- <IconButton
- aria-disabled={isBusy || undefined}
- aria-label={t('workflowLibrary.thumbnailRemove')}
- data-thumbnail-remove
- ms="auto"
- size="xs"
- variant="ghost"
- onClick={isBusy ? undefined : handleRemove}
- >
- <Trash2Icon />
- </IconButton>
- </Tooltip>
- ) : null}
- <input ref={inputRef} accept={UPLOAD_ACCEPT} hidden type="file" onChange={handleFileChange} />
- </HStack>
- ) : null}
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts
index 2eff06f2b3..cd274a8092 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts
@@ -45,6 +45,7 @@ const deferGraphPreview = <Props extends object>(pick: (module: GraphPreviewModu
};
export const DeferredGraphPreviewDialog = deferGraphPreview((module) => module.GraphPreviewDialog);
+export const DeferredGraphPreviewSnapshot = deferGraphPreview((module) => module.GraphPreviewSnapshot);
/**
* Preview the entry's saved document without active-project destination or live updates; catch malformed cached
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index d070c9240b..172256dd36 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -286,6 +286,11 @@ const getLegacyChunkName = (id: string): string | null => {
return 'yaml';
}
+ // Only a workflow thumbnail snapshot loads it, on demand.
+ if (id.includes('/node_modules/html-to-image/')) {
+ return 'html-to-image';
+ }
+
if (id.includes('/node_modules/fflate/')) {
return 'fflate';
}