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): open library workflows in the full graph preview dialog

joshistoast8ff190abd97b
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index c50dbb0496..9acc0499bd 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,17 +2,17 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 834309,
+ "brotliBytes": 833998,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 834049,
+ "gzipBytes": 833777,
"imageRawBytes": 156376,
- "initialRawBytes": 1938239,
+ "initialRawBytes": 1938000,
"largestAssetRawBytes": 746569,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 66347,
- "requestCount": 42,
- "scriptRequestCount": 26,
+ "ownedRawBytes": 67374,
+ "requestCount": 41,
+ "scriptRequestCount": 25,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -284,17 +284,17 @@
]
},
"limits": {
- "brotliBytes": 842653,
+ "brotliBytes": 842338,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 842390,
+ "gzipBytes": 842115,
"imageRawBytes": 157940,
- "initialRawBytes": 1957622,
+ "initialRawBytes": 1957380,
"largestAssetRawBytes": 754035,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 66347,
- "requestCount": 42,
- "scriptRequestCount": 26
+ "ownedRawBytes": 67374,
+ "requestCount": 41,
+ "scriptRequestCount": 25
},
"owner": "app",
"remediationTicket": "set-performance-budgets",
@@ -302,17 +302,17 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1033243,
+ "brotliBytes": 1032742,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1030701,
+ "gzipBytes": 1030097,
"imageRawBytes": 156376,
- "initialRawBytes": 2533298,
+ "initialRawBytes": 2532909,
"largestAssetRawBytes": 746569,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 112544,
- "requestCount": 92,
- "scriptRequestCount": 76,
+ "ownedRawBytes": 112397,
+ "requestCount": 90,
+ "scriptRequestCount": 74,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -844,24 +844,24 @@
]
},
"limits": {
- "brotliBytes": 1043576,
+ "brotliBytes": 1043070,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1041009,
+ "gzipBytes": 1040398,
"imageRawBytes": 157940,
- "initialRawBytes": 2558631,
+ "initialRawBytes": 2558239,
"largestAssetRawBytes": 754035,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 112544,
- "requestCount": 92,
- "scriptRequestCount": 76
+ "ownedRawBytes": 112397,
+ "requestCount": 90,
+ "scriptRequestCount": 74
},
"owner": "workbench",
"remediationTicket": "deepen-widget-registry-loading",
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-08-18",
+ "capturedAt": "2026-08-19",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx
index b0636e1ed2..4f3530c7df 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx
@@ -357,7 +357,8 @@ describe('GraphPreviewDialog', () => {
const renderDialog = async (
source: GraphPreviewSourceState,
isOpen = true,
- sourceId: WorkflowInvocationSourceId = 'generate'
+ sourceId: WorkflowInvocationSourceId = 'generate',
+ hideInvoke = false
) => {
await act(() => {
root.render(
@@ -367,6 +368,7 @@ describe('GraphPreviewDialog', () => {
<WorkflowGraphPreviewProvider adapter={graphPreviewPort}>
<GraphPreviewDialog
graphId="preview-graph-id"
+ hideInvoke={hideInvoke}
isOpen={isOpen}
source={source}
sourceId={sourceId}
@@ -680,6 +682,22 @@ describe('GraphPreviewDialog', () => {
expect(findMenuItemWithText('Download JSON')).not.toBeUndefined();
});
+ it('renders the footer Invoke button by default', async () => {
+ await renderDialog(FIXTURE_SOURCE);
+
+ const buttonText = [...document.querySelectorAll('button')].map((button) => button.textContent ?? '');
+ expect(buttonText.some((text) => text.includes('Invoke Generate → Gallery'))).toBe(true);
+ });
+
+ it('hideInvoke hides only the footer Invoke button — Copy JSON and Open as stay', async () => {
+ await renderDialog(FIXTURE_SOURCE, true, 'generate', true);
+
+ const buttonText = [...document.querySelectorAll('button')].map((button) => button.textContent ?? '');
+ expect(buttonText.some((text) => text.includes('Invoke'))).toBe(false);
+ expect(buttonText.some((text) => text.includes('Copy JSON'))).toBe(true);
+ expect(buttonText.some((text) => text.includes('Open as'))).toBe(true);
+ });
+
it('Open as → Save to workflow library names the document from the source label and notifies success', async () => {
createLibraryWorkflowMock.mockResolvedValue('library-workflow-1');
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 80c3f3414e..25a24a9191 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
@@ -21,6 +21,8 @@ interface GraphPreviewDialogProps {
sourceId?: WorkflowInvocationSourceId;
/** e.g. "Generate" — used in the header subtitle and the JSON preview label. */
sourceLabel: string;
+ /** Hides the footer Invoke button only — Copy JSON and the Open-as menu stay. For sources with no invocation route (e.g. a library entry, previewed before it's ever opened into a project). */
+ hideInvoke?: boolean;
onOpenChange: (isOpen: boolean) => void;
}
@@ -70,6 +72,7 @@ export const GraphPreviewDialog = ({
source,
sourceId,
sourceLabel,
+ hideInvoke = false,
onOpenChange,
}: GraphPreviewDialogProps) => {
const { t } = useTranslation();
@@ -279,7 +282,7 @@ export const GraphPreviewDialog = ({
) : null}
</Box>
<Box display="flex" gap="2">
- {dialogRoute ? (
+ {!hideInvoke && dialogRoute ? (
<Button
aria-disabled={!canInvoke}
cursor={canInvoke ? undefined : 'not-allowed'}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewPane.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewPane.tsx
deleted file mode 100644
index cd458a62c9..0000000000
--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewPane.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { ProjectGraphState } from '@features/workflow/contracts';
-
-import { Box } from '@chakra-ui/react';
-import { useTranslation } from 'react-i18next';
-
-import { documentToPreviewGraph, GraphPreviewFlow } from './GraphPreviewFlow';
-
-/**
- * The library dialog's node preview, conversion included.
- *
- * Both halves live here so the dialog can hold the whole thing behind one
- * `lazy()` boundary: `documentToPreviewGraph` shares a module with the flow
- * renderer, so importing it for the conversion alone pulled xyflow and d3
- * (~174 KB) into every editor boot through the workflow widget's host.
- */
-export const GraphPreviewPane = ({ document }: { document: ProjectGraphState }) => {
- const { t } = useTranslation();
- const { graph, positionHints } = documentToPreviewGraph(document, t('widgets.labels.workflow'));
-
- return (
- <Box h="24rem">
- <GraphPreviewFlow graph={graph} positionHints={positionHints} />
- </Box>
- );
-};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.ts
index f374e334b3..0c178971ff 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.ts
@@ -2,4 +2,3 @@ export { FlowMiniMap } from './FlowMiniMap';
export { flowThemeCss, getFlowColorMode } from './flowTheme';
export { GraphPreviewDialog } from './GraphPreviewDialog';
export { documentToPreviewGraph, GraphPreviewFlow } from './GraphPreviewFlow';
-export { GraphPreviewPane } from './GraphPreviewPane';
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 26a3279298..f64090cfdb 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
@@ -112,7 +112,7 @@ export const WorkflowLibraryDetailPanel = ({
}, [entry, onOpen]);
const handlePreview = useCallback(() => {
- if (entry) {
+ if (entry && entry.enrichment.status === 'ready') {
onPreview(entry);
}
}, [entry, onPreview]);
@@ -443,7 +443,7 @@ export const WorkflowLibraryDetailPanel = ({
</Portal>
</Menu.Root>
</HStack>
- <Button size="sm" variant="outline" w="full" onClick={handlePreview}>
+ <Button disabled={enrichment?.status !== 'ready'} size="sm" variant="outline" w="full" onClick={handlePreview}>
<WorkflowIcon />
{t('workflowLibrary.previewGraph')}
</Button>
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 17203b857c..10c060e17e 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
@@ -1,5 +1,6 @@
import type { StarterModel } from '@features/models';
import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';
+import type { InvocationTemplate, InvocationTemplatesSnapshot, ProjectGraphState } from '@features/workflow/core/types';
import type {
WorkflowLibraryBrowseSnapshot,
WorkflowLibraryEntry,
@@ -9,14 +10,80 @@ import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/work
import { ChakraProvider } from '@chakra-ui/react';
import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';
-import { createProjectGraph } from '@features/workflow/utility';
+import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/utility';
import { system } from '@theme/system';
import { act, StrictMode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+// A plain static import of the (mocked) module the dialog `lazy()`-loads, so
+// its dynamic `import()` resolves against an already-loaded module record
+// instead of paying a first-time compile cost mid-test — that cost is what
+// made a cold run of the graph-preview wiring tests below flaky.
+import '@features/workflow/ui/graph-preview/GraphPreviewDialog';
import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';
+// Task 8's graph preview wiring needs invocation templates loaded to compile
+// a library entry's document (`buildLibraryGraphPreviewSource`); this suite
+// never boots the real templates fetch, so it stubs the reactive snapshot
+// hook with one template — matching the node type `PREVIEW_DOCUMENT` (below)
+// uses — the same way `GraphPreviewDialog.browser.test.tsx` does.
+const PREVIEW_NODE_TEMPLATE: InvocationTemplate = {
+ category: 'test',
+ classification: 'stable',
+ description: '',
+ inputs: {},
+ nodePack: 'invokeai',
+ outputs: {},
+ outputType: 'integer_output',
+ tags: [],
+ title: 'integer',
+ type: 'integer',
+ useCache: true,
+ version: '1.0.0',
+};
+
+const TEMPLATES_SNAPSHOT: InvocationTemplatesSnapshot = {
+ error: null,
+ status: 'loaded',
+ templates: { integer: PREVIEW_NODE_TEMPLATE },
+};
+
+vi.mock('@features/workflow/react', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useInvocationTemplatesSnapshot: () => TEMPLATES_SNAPSHOT,
+}));
+
+// xyflow stays out of this shell test — the lazy-mounted `GraphPreviewDialog`
+// (Task 8) is replaced with a stub that surfaces exactly what the wiring is
+// responsible for: which graph got compiled, `hideInvoke`, and the close path.
+vi.mock('@features/workflow/ui/graph-preview/GraphPreviewDialog', () => ({
+ GraphPreviewDialog: ({
+ graphId,
+ hideInvoke,
+ source,
+ sourceLabel,
+ onOpenChange,
+ }: {
+ graphId: string;
+ hideInvoke?: boolean;
+ isOpen: boolean;
+ source: { graph: { nodes: { id: string; type: string }[] } | null };
+ sourceLabel: string;
+ onOpenChange: (isOpen: boolean) => void;
+ }) => (
+ <div
+ data-graph-id={graphId}
+ data-hide-invoke={String(hideInvoke)}
+ data-preview-dialog
+ data-source-label={sourceLabel}
+ >
+ {(source.graph?.nodes ?? []).map((node) => node.type).join(',')}
+ <button onClick={() => onOpenChange(false)}>Close preview</button>
+ </div>
+ ),
+}));
+
// The browse store is Task 5's; this suite owns the *dialog*, so the store is
// replaced by a real external store the test drives directly plus spies for
// its four commands. Using a real store (not a stub hook) keeps the dialog's
@@ -141,14 +208,22 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
const EMPTY_DOCUMENT = createProjectGraph('library-fixture');
+// One `integer` node — matches `PREVIEW_NODE_TEMPLATE` above, so this is the
+// document the graph-preview wiring tests compile.
+const PREVIEW_DOCUMENT: ProjectGraphState = projectGraphReducer(createProjectGraph('preview-fixture'), {
+ node: buildInvocationNode(PREVIEW_NODE_TEMPLATE, { x: 0, y: 0 }),
+ type: 'addNode',
+});
+
const NO_REQUIREMENTS: readonly WorkflowModelRequirement[] = [];
const readyEnrichment = (
nodeCount: number,
primaryBase: string | null,
- requirements: readonly WorkflowModelRequirement[] = NO_REQUIREMENTS
+ requirements: readonly WorkflowModelRequirement[] = NO_REQUIREMENTS,
+ document: ProjectGraphState = EMPTY_DOCUMENT
): WorkflowLibraryEntryEnrichment => ({
- document: EMPTY_DOCUMENT,
+ document,
nodeCount,
requirements: { primaryBase, requirements },
status: 'ready',
@@ -192,6 +267,14 @@ const UPSCALE = entry(
tags: ['upscale'],
}
);
+// The graph-preview wiring's own fixture: a `'ready'` entry whose document
+// actually has a node, so the mocked preview dialog has a compiled graph to
+// show instead of an empty one.
+const PREVIEW_FIXTURE = entry(
+ 'wf-preview-fixture',
+ 'Preview Fixture',
+ readyEnrichment(1, null, NO_REQUIREMENTS, PREVIEW_DOCUMENT)
+);
const LOADED_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {
entries: [PORTRAIT, LANDSCAPE, SKETCH, UPSCALE],
@@ -268,6 +351,27 @@ describe('WorkflowLibraryDialog', () => {
});
});
+ /**
+ * The lazy-loaded preview dialog (Task 8) resolves its `import()` on its
+ * own schedule — a fixed `wait` is either too short (flaky) or padded
+ * (slow), and letting it resolve outside `act` is what raises "a suspended
+ * resource finished loading" warnings. Polling inside `act` keeps every
+ * check, and the eventual resolution, in the same act scope.
+ */
+ const waitForPreviewDialog = () =>
+ act(async () => {
+ await vi.waitFor(
+ () => {
+ expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();
+ },
+ // Padded past `vi.waitFor`'s default 1000ms: the static side-effect
+ // import above keeps the module warm, but the dynamic `import()`
+ // still costs a real (if now small) round trip through Vite's module
+ // graph before `Suspense` re-renders.
+ { timeout: 2000 }
+ );
+ });
+
const cards = () => [...document.querySelectorAll<HTMLElement>('[data-workflow-card]')];
const card = (workflowId: string) => document.querySelector<HTMLElement>(`[data-workflow-card="${workflowId}"]`);
const buttonWithText = (text: string) =>
@@ -572,6 +676,77 @@ describe('WorkflowLibraryDialog', () => {
expect(document.querySelector('[data-pending-preview="wf-portrait"]')).not.toBeNull();
});
+ it("mounts the lazy preview dialog with the entry's compiled graph and hides Invoke", async () => {
+ await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));
+
+ await act(() => card('wf-preview-fixture')?.click());
+ await clickText('Preview graph');
+ await waitForPreviewDialog();
+
+ const preview = document.querySelector('[data-preview-dialog]');
+ expect(preview).not.toBeNull();
+ expect(preview?.getAttribute('data-graph-id')).toBe('wf-preview-fixture');
+ expect(preview?.getAttribute('data-hide-invoke')).toBe('true');
+ expect(preview?.getAttribute('data-source-label')).toBe('Preview Fixture');
+ // The document's one `integer` node made it through compilation.
+ expect(preview?.textContent).toContain('integer');
+ });
+
+ it('disables the Preview action for an entry whose enrichment is not ready', async () => {
+ await openWith(LOADED_SNAPSHOT);
+
+ await act(() => card('wf-sketch')?.click());
+
+ const button = buttonWithText('Preview graph') as HTMLButtonElement | undefined;
+ expect(button?.disabled).toBe(true);
+ });
+
+ it('resets the pending preview when the preview dialog itself closes', async () => {
+ await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));
+
+ await act(() => card('wf-preview-fixture')?.click());
+ await clickText('Preview graph');
+ await waitForPreviewDialog();
+
+ expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();
+
+ await clickText('Close preview');
+
+ expect(document.querySelector('[data-preview-dialog]')).toBeNull();
+ expect(document.querySelector('[data-pending-preview]')).toBeNull();
+ });
+
+ it('does not resurrect the preview after the library dialog closes and reopens', async () => {
+ await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));
+
+ await act(() => card('wf-preview-fixture')?.click());
+ await clickText('Preview graph');
+ await waitForPreviewDialog();
+
+ expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();
+
+ // The dialog's own Close control is the only path that ever flips `isOpen`
+ // to `false` in the real app (`WorkflowWidgetChrome` only ever sets it
+ // back to `true`) — clicking it exercises the same reset the parent
+ // relies on. The isOpen round trip below then confirms the closed render
+ // drops the mount and the reopened one does not bring it back.
+ const closeButton = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]');
+ expect(closeButton).not.toBeNull();
+ // Chakra's `Dialog` commits its close transition a task after the click
+ // (the same class of gap `settleFrame` exists for, above) — settle inside
+ // this `act` scope rather than a bare click.
+ await act(async () => {
+ closeButton?.click();
+ await settleFrame();
+ });
+
+ await renderDialog(false);
+ expect(document.querySelector('[data-preview-dialog]')).toBeNull();
+
+ await renderDialog(true);
+ expect(document.querySelector('[data-preview-dialog]')).toBeNull();
+ });
+
it('shows the busy overlay while a workflow is being applied', async () => {
loader.phase.current = 'applying';
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
index d092af1799..fd2fadfe65 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
@@ -9,17 +9,31 @@ import {
setWorkflowLibraryBrowseFilter,
useWorkflowLibraryBrowseSelector,
} from '@features/workflow/data/libraryBrowseStore';
+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import { CloseButton } from '@platform/ui';
-import { useCallback, useRef, useState } from 'react';
+import { lazy, Suspense, useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { buildLibraryGraphPreviewSource } from './libraryPreviewSource';
import { useLoadLibraryWorkflow } from './useLoadLibraryWorkflow';
import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';
import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';
import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';
import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';
+/**
+ * xyflow (~174 KB) stays out of this dialog's own chunk: the preview dialog
+ * is only ever needed once a card asks to preview it, so it is dynamic
+ * `import()`ed here rather than statically imported like every other panel
+ * in this file (mirrors `WidgetActionsMenu.tsx`'s `GraphPreviewHost`).
+ */
+const LazyGraphPreviewDialog = lazy(() =>
+ import('@features/workflow/ui/graph-preview/GraphPreviewDialog').then((module) => ({
+ default: module.GraphPreviewDialog,
+ }))
+);
+
/**
* Backend workflow library browser. Filtering and paging are server side and
* live in the browse store, so this shell owns exactly two pieces of state:
@@ -74,14 +88,21 @@ export const WorkflowLibraryDialog = ({
}) => {
const { t } = useTranslation();
const { category, entries, error, status, tag, tagCounts } = useWorkflowLibraryBrowseSelector(selectBrowseView);
+ const templatesSnapshot = useInvocationTemplatesSnapshot();
const [searchInput, setSearchInput] = useState('');
const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);
- // Task 8 mounts the real preview dialog from this; until then it is only the
- // record of which workflow the rail asked to preview.
+ // The record of which workflow the rail asked to preview — mounts the lazy
+ // preview dialog below while set. This dialog shell is never unmounted while
+ // the app is up (only its `isOpen` toggles), so every path that can close
+ // *this* dialog has to clear it too, or a stale preview would resurrect
+ // itself the next time the library opens.
const [previewEntry, setPreviewEntry] = useState<WorkflowLibraryEntry | null>(null);
const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const closeDialog = useCallback(() => onOpenChange(false), [onOpenChange]);
+ const closeDialog = useCallback(() => {
+ setPreviewEntry(null);
+ onOpenChange(false);
+ }, [onOpenChange]);
const { load, loadPhase } = useLoadLibraryWorkflow(closeDialog);
const isLoadPending = loadPhase !== 'idle';
const missingCounts = useWorkflowLibraryMissingCounts(entries);
@@ -95,13 +116,37 @@ export const WorkflowLibraryDialog = ({
const handleDialogOpenChange = useCallback(
(event: { open: boolean }) => {
- if (!isLoadPending) {
- onOpenChange(event.open);
+ if (isLoadPending) {
+ return;
+ }
+
+ if (event.open) {
+ onOpenChange(true);
+ } else {
+ closeDialog();
}
},
- [isLoadPending, onOpenChange]
+ [isLoadPending, onOpenChange, closeDialog]
);
+ const handlePreviewOpenChange = useCallback((open: boolean) => {
+ if (!open) {
+ setPreviewEntry(null);
+ }
+ }, []);
+
+ // Only a `'ready'` enrichment carries the compiled document; the rail's
+ // Preview action is disabled for anything else, so this is a defensive
+ // fallback (a stale `previewEntry` from before a revalidation), not a path
+ // the UI can normally reach.
+ const previewSource = useMemo(() => {
+ if (!previewEntry || previewEntry.enrichment.status !== 'ready' || templatesSnapshot.status !== 'loaded') {
+ return null;
+ }
+
+ return buildLibraryGraphPreviewSource(previewEntry.enrichment.document, templatesSnapshot.templates, t);
+ }, [previewEntry, templatesSnapshot, t]);
+
const handleSearchChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
const { value } = event.currentTarget;
@@ -146,87 +191,107 @@ export const WorkflowLibraryDialog = ({
const handleDeleted = useCallback(() => setSelectedWorkflowId(null), []);
return (
- <Dialog.Root open={isOpen} placement="center" size="xl" onOpenChange={handleDialogOpenChange}>
- <Portal>
- <Dialog.Backdrop />
- <Dialog.Positioner>
- <Dialog.Content
- aria-busy={isLoadPending}
- h="80vh"
- maxH="80vh"
- maxW="min(72rem, calc(100vw - 4rem))"
- position="relative"
- >
- {isLoadPending ? (
- <Stack
- alignItems="center"
- aria-live="polite"
- bg="bg/85"
- inset="0"
- justifyContent="center"
- position="absolute"
- role="status"
- zIndex="modal"
+ <>
+ <Dialog.Root open={isOpen} placement="center" size="xl" onOpenChange={handleDialogOpenChange}>
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content
+ aria-busy={isLoadPending}
+ h="80vh"
+ maxH="80vh"
+ maxW="min(72rem, calc(100vw - 4rem))"
+ position="relative"
+ >
+ {isLoadPending ? (
+ <Stack
+ alignItems="center"
+ aria-live="polite"
+ bg="bg/85"
+ inset="0"
+ justifyContent="center"
+ position="absolute"
+ role="status"
+ zIndex="modal"
+ >
+ <Spinner color="accent.solid" size="lg" />
+ <Text fontSize="xs" fontWeight="600">
+ {loadPhase === 'fetching' ? t('workflowLibrary.fetching') : t('workflowLibrary.applying')}
+ </Text>
+ </Stack>
+ ) : null}
+ <Dialog.Header>
+ <Stack gap="2" minW="0" w="full">
+ <HStack gap="3" minW="0">
+ <Dialog.Title flexShrink={0}>{t('workflowLibrary.title')}</Dialog.Title>
+ <Input
+ aria-label={t('workflowLibrary.searchPlaceholder')}
+ flex="1"
+ minW="0"
+ placeholder={t('workflowLibrary.searchPlaceholder')}
+ size="xs"
+ type="search"
+ value={searchInput}
+ onChange={handleSearchChange}
+ />
+ <SegmentGroup.Root flexShrink={0} size="xs" value={category} onValueChange={handleCategoryChange}>
+ <SegmentGroup.Indicator />
+ {CATEGORY_ITEMS.map((item) => (
+ <SegmentGroup.Item key={item.value} value={item.value}>
+ <SegmentGroup.ItemHiddenInput />
+ <SegmentGroup.ItemText>{t(item.labelKey)}</SegmentGroup.ItemText>
+ </SegmentGroup.Item>
+ ))}
+ </SegmentGroup.Root>
+ </HStack>
+ <WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />
+ </Stack>
+ </Dialog.Header>
+ <Dialog.Body
+ data-pending-preview={previewEntry?.item.workflow_id}
+ display="flex"
+ flex="1"
+ gap="3"
+ minH="0"
>
- <Spinner color="accent.solid" size="lg" />
- <Text fontSize="xs" fontWeight="600">
- {loadPhase === 'fetching' ? t('workflowLibrary.fetching') : t('workflowLibrary.applying')}
- </Text>
- </Stack>
- ) : null}
- <Dialog.Header>
- <Stack gap="2" minW="0" w="full">
- <HStack gap="3" minW="0">
- <Dialog.Title flexShrink={0}>{t('workflowLibrary.title')}</Dialog.Title>
- <Input
- aria-label={t('workflowLibrary.searchPlaceholder')}
- flex="1"
- minW="0"
- placeholder={t('workflowLibrary.searchPlaceholder')}
- size="xs"
- type="search"
- value={searchInput}
- onChange={handleSearchChange}
- />
- <SegmentGroup.Root flexShrink={0} size="xs" value={category} onValueChange={handleCategoryChange}>
- <SegmentGroup.Indicator />
- {CATEGORY_ITEMS.map((item) => (
- <SegmentGroup.Item key={item.value} value={item.value}>
- <SegmentGroup.ItemHiddenInput />
- <SegmentGroup.ItemText>{t(item.labelKey)}</SegmentGroup.ItemText>
- </SegmentGroup.Item>
- ))}
- </SegmentGroup.Root>
- </HStack>
- <WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />
- </Stack>
- </Dialog.Header>
- <Dialog.Body data-pending-preview={previewEntry?.item.workflow_id} display="flex" flex="1" gap="3" minH="0">
- <WorkflowLibraryGrid
- entries={entries}
- error={error}
- missingCounts={missingCounts}
- selectedWorkflowId={activeWorkflowId}
- status={status}
- onOpen={handleOpenWorkflow}
- onSelect={setSelectedWorkflowId}
- />
- <WorkflowLibraryDetailPanel
- entry={activeEntry}
- onClose={closeDialog}
- onDeleted={handleDeleted}
- onDuplicated={setSelectedWorkflowId}
- onOpen={handleOpenItem}
- onPreview={setPreviewEntry}
- />
- </Dialog.Body>
- {isOpen ? <WorkflowLibraryBrowseSession /> : null}
- <Dialog.CloseTrigger asChild>
- <CloseButton color="fg.muted" disabled={isLoadPending} size="sm" />
- </Dialog.CloseTrigger>
- </Dialog.Content>
- </Dialog.Positioner>
- </Portal>
- </Dialog.Root>
+ <WorkflowLibraryGrid
+ entries={entries}
+ error={error}
+ missingCounts={missingCounts}
+ selectedWorkflowId={activeWorkflowId}
+ status={status}
+ onOpen={handleOpenWorkflow}
+ onSelect={setSelectedWorkflowId}
+ />
+ <WorkflowLibraryDetailPanel
+ entry={activeEntry}
+ onClose={closeDialog}
+ onDeleted={handleDeleted}
+ onDuplicated={setSelectedWorkflowId}
+ onOpen={handleOpenItem}
+ onPreview={setPreviewEntry}
+ />
+ </Dialog.Body>
+ {isOpen ? <WorkflowLibraryBrowseSession /> : null}
+ <Dialog.CloseTrigger asChild>
+ <CloseButton color="fg.muted" disabled={isLoadPending} size="sm" />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ {previewEntry && previewSource ? (
+ <Suspense fallback={null}>
+ <LazyGraphPreviewDialog
+ graphId={previewEntry.item.workflow_id}
+ hideInvoke
+ isOpen={Boolean(previewEntry)}
+ source={previewSource}
+ sourceLabel={previewEntry.item.name || t('workflowLibrary.untitled')}
+ onOpenChange={handlePreviewOpenChange}
+ />
+ </Suspense>
+ ) : null}
+ </>
);
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.test.ts
new file mode 100644
index 0000000000..857060b9af
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.test.ts
@@ -0,0 +1,137 @@
+import type { FieldInputTemplate, InvocationTemplate, ProjectGraphState } from '@features/workflow/contracts';
+import type { TFunction } from 'i18next';
+
+import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/utility';
+import { describe, expect, it } from 'vitest';
+
+import { buildLibraryGraphPreviewSource } from './libraryPreviewSource';
+
+const translate = ((key: string) => (key === 'graphPreview.nodes' ? 'Nodes' : key)) as TFunction;
+
+const input = (name: string, overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({
+ default: undefined,
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ input: 'any',
+ maximum: null,
+ minimum: null,
+ multipleOf: null,
+ name,
+ options: null,
+ required: false,
+ title: name,
+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },
+ uiChoiceLabels: null,
+ uiComponent: null,
+ uiHidden: false,
+ uiModelBase: null,
+ uiModelFormat: null,
+ uiModelType: null,
+ uiOrder: null,
+ ...overrides,
+});
+
+const template = (type: string, inputs: Record<string, FieldInputTemplate>): InvocationTemplate => ({
+ category: 'test',
+ classification: 'stable',
+ description: '',
+ inputs,
+ nodePack: 'invokeai',
+ outputs: {
+ out: {
+ description: '',
+ name: 'out',
+ title: 'Out',
+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },
+ },
+ },
+ outputType: `${type}_output`,
+ tags: [],
+ title: type,
+ type,
+ useCache: true,
+ version: '1.0.0',
+});
+
+const templates = {
+ sink: template('sink', { text: input('text', { required: true }) }),
+ source: template('source', { value: input('value', { default: 'hello' }) }),
+};
+
+const buildDocument = (): { doc: ProjectGraphState; sinkId: string; sourceId: string } => {
+ const sourceNode = buildInvocationNode(templates.source, { x: 0, y: 0 });
+ const sinkNode = buildInvocationNode(templates.sink, { x: 240, y: 80 });
+ let doc = createProjectGraph('library-preview-fixture');
+
+ doc = projectGraphReducer(doc, { node: sourceNode, type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: sinkNode, type: 'addNode' });
+ doc = projectGraphReducer(doc, {
+ edge: {
+ id: 'e1',
+ source: sourceNode.id,
+ sourceHandle: 'out',
+ target: sinkNode.id,
+ targetHandle: 'text',
+ type: 'default',
+ },
+ type: 'addEdge',
+ });
+
+ return { doc, sinkId: sinkNode.id, sourceId: sourceNode.id };
+};
+
+describe('buildLibraryGraphPreviewSource', () => {
+ it('compiles the document into a graph with its nodes and edges', () => {
+ const { doc, sinkId, sourceId } = buildDocument();
+
+ const result = buildLibraryGraphPreviewSource(doc, templates, translate);
+
+ expect(result.invalidReasons).toEqual([]);
+ expect(result.graph?.nodes.map((node) => node.id).sort()).toEqual([sinkId, sourceId].sort());
+ expect(result.graph?.edges).toHaveLength(1);
+ expect(result.graph?.edges[0]).toMatchObject({ sourceNodeId: sourceId, targetNodeId: sinkId });
+ });
+
+ it('is never live and carries no destination or notices', () => {
+ const { doc } = buildDocument();
+
+ const result = buildLibraryGraphPreviewSource(doc, templates, translate);
+
+ expect(result.isLive).toBe(false);
+ expect(result.destinationLabel).toBeNull();
+ expect(result.notices).toEqual([]);
+ });
+
+ it('summarizes the compiled node count', () => {
+ const { doc } = buildDocument();
+
+ const result = buildLibraryGraphPreviewSource(doc, templates, translate);
+
+ expect(result.summaryRows).toEqual([{ id: 'nodes', label: 'Nodes', value: '2' }]);
+ });
+
+ it('maps position hints from the document node positions', () => {
+ const { doc, sinkId, sourceId } = buildDocument();
+
+ const result = buildLibraryGraphPreviewSource(doc, templates, translate);
+
+ expect(result.positionHints?.[sourceId]).toEqual({ x: 0, y: 0 });
+ expect(result.positionHints?.[sinkId]).toEqual({ x: 240, y: 80 });
+ });
+
+ it('surfaces a compile failure as an invalid reason instead of throwing', () => {
+ const { doc } = buildDocument();
+ // A malformed cached document (the shape a corrupted library record could
+ // produce) — `nodes` is not an array, so compilation throws instead of
+ // silently producing an empty graph.
+ const corrupt = { ...doc, nodes: null } as unknown as ProjectGraphState;
+
+ const result = buildLibraryGraphPreviewSource(corrupt, templates, translate);
+
+ expect(result.graph).toBeNull();
+ expect(result.invalidReasons).toHaveLength(1);
+ expect(result.invalidReasons[0]).toEqual(expect.any(String));
+ expect(result.summaryRows).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts
new file mode 100644
index 0000000000..d821317ac6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts
@@ -0,0 +1,45 @@
+import type { GraphPreviewSourceState, InvocationTemplates, ProjectGraphState } from '@features/workflow/contracts';
+import type { TFunction } from 'i18next';
+
+import { compileProjectGraph } from '@features/workflow/graph';
+
+/**
+ * The graph preview dialog's data source for a library entry — the library
+ * equivalent of `workbench/widget-frame/graphPreviewSource.ts`'s workflow
+ * branch, minus the active project: a library entry previews its own saved
+ * document, not the live project graph, so the result is never live and
+ * carries no destination (the entry has not been opened into a project yet).
+ *
+ * `document`/`templates` come from a `'ready'` library enrichment, which only
+ * exists once templates have loaded — so the try/catch below is defensive
+ * (a malformed cached document), not an expected path.
+ */
+export const buildLibraryGraphPreviewSource = (
+ document: ProjectGraphState,
+ templates: InvocationTemplates,
+ t: TFunction
+): GraphPreviewSourceState => {
+ try {
+ const graph = compileProjectGraph(document, templates);
+ const positionHints = Object.fromEntries(document.nodes.map((node) => [node.id, node.position]));
+
+ return {
+ destinationLabel: null,
+ graph,
+ invalidReasons: [],
+ isLive: false,
+ notices: [],
+ positionHints,
+ summaryRows: [{ id: 'nodes', label: t('graphPreview.nodes'), value: String(graph.nodes.length) }],
+ };
+ } catch (error) {
+ return {
+ destinationLabel: null,
+ graph: null,
+ invalidReasons: [error instanceof Error ? error.message : String(error)],
+ isLive: false,
+ notices: [],
+ summaryRows: [],
+ };
+ }
+};