Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): live graph preview source with generate compile
joshistoast083bfcd7b990
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 348e449b7b..bffaf9e57b 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -543,10 +543,13 @@"you": "You"},"graphPreview": {+ "cfgScale": "CFG scale","graphJsonLabel": "{{title}} graph JSON","inputCount_one": "{{count}} input","inputCount_other": "{{count}} inputs","invokeRoute": "Invoke {{route}}",+ "loras": "LoRAs",+ "model": "Model","noCompiledGraph": "No compiled graph is available for \"{{graphId}}\" yet.","nodes": "Nodes","provenance": {@@ -562,6 +565,13 @@"size": "Generate → Size","steps": "Generate → Steps"},+ "scheduler": "Scheduler",+ "seed": "Seed",+ "seedRandomValue": "random",+ "seedRandomized": "Seed is randomized. This graph runs differently each time.",+ "seedRegenerated": "regenerated each run",+ "size": "Size",+ "steps": "Steps","title": "{{title}} Graph Preview"},"hotkeys": {diff --git a/invokeai/frontend/webv2/src/features/workflow/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/contracts.tsindex f3c3945b0c..eb09fb0d65 100644--- a/invokeai/frontend/webv2/src/features/workflow/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/contracts.ts@@ -1,3 +1,9 @@export type * from './core/graphContracts';export type * from './core/types';export { isConnectorNode, isCurrentImageNode, isInvocationNode, isNotesNode } from './core/types';+export type {+ GraphPreviewNotice,+ GraphPreviewProvenance,+ GraphPreviewSourceState,+ GraphPreviewSummaryRow,+} from './ui/contracts';diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.tsindex 501b5d9d57..795a8e87dc 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts@@ -1,5 +1,5 @@import type { ProjectGraphAction } from '@features/workflow/core/document';-import type { ProjectGraphState } from '@features/workflow/core/types';+import type { ProjectGraphState, XYPosition } from '@features/workflow/core/types';export type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover' | 'floating';@@ -90,6 +90,42 @@ export interface WorkflowPreviewGraph {backendGraph?: unknown;}+export interface GraphPreviewNotice {+ id: string;+ message: string;+ nodeId?: string;+}++export interface GraphPreviewSummaryRow {+ id: string;+ label: string;+ value: string;+}++export interface GraphPreviewProvenance {+ label: string;+}++/**+ * The preview dialog's data source, built fresh per render by+ * `workbench/widget-frame/graphPreviewSource.ts` from the active surface's+ * `sourceId`. `isLive` drives the dialog's "Updates as you change settings."+ * subtitle — true for sources that recompile from live project state+ * (`generate`, `workflow`), false for sources that only replay their last+ * compiled widget graph (`upscale`, `canvas`).+ */+export interface GraphPreviewSourceState {+ graph: WorkflowPreviewGraph | null;+ invalidReasons: string[];+ isLive: boolean;+ notices: GraphPreviewNotice[];+ positionHints?: Record<string, XYPosition>;+ /** nodeId → field → display text, for fields whose real value the preview can't show verbatim (e.g. a randomized seed). */+ resolvedInputOverrides?: Record<string, Record<string, string>>;+ summaryRows: GraphPreviewSummaryRow[];+ getProvenance?: (nodeId: string, fieldName: string) => GraphPreviewProvenance | null;+}+export interface WorkflowPerfSource {instanceId: string;kind: 'widget';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsxnew file mode 100644index 0000000000..94afb301a8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx@@ -0,0 +1,55 @@+import type { GraphBearingSurfaceContract } from '@workbench/widgetContracts';++import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { GraphPreviewDialog } from '@features/workflow/preview';+import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { buildGraphPreviewSource } from './graphPreviewSource';++/**+ * Mounted only while the preview dialog is open (it subscribes to the whole+ * active project so the compiled graph tracks every settings edit live).+ */+export const GraphPreviewHost = ({+ isOpen,+ surface,+ onOpenChange,+}: {+ isOpen: boolean;+ surface: GraphBearingSurfaceContract;+ onOpenChange: (isOpen: boolean) => void;+}) => {+ const { t } = useTranslation();+ const project = useActiveProjectSelector((activeProject) => activeProject);+ const modelsStatus = useModelsSelector((snapshot) => snapshot.status);+ const models = useModelsSelector((snapshot) => snapshot.models);+ const templates = useInvocationTemplatesSnapshot();+ const availabilityModels = modelsStatus === 'loaded' ? models : undefined;+ const source = useMemo(+ () => buildGraphPreviewSource({ models: availabilityModels, project, surface, t, templates }),+ [availabilityModels, project, surface, t, templates]+ );++ useMountEffect(() => {+ void ensureModelsLoaded();+ ensureInvocationTemplatesLoaded();+ });++ return (+ <GraphPreviewDialog+ graph={source.graph}+ graphId={surface.graphId}+ isOpen={isOpen}+ positionHints={source.positionHints}+ sourceId={surface.sourceId}+ title={surface.label}+ onOpenChange={onOpenChange}+ />+ );+};++export default GraphPreviewHost;diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsxindex 1a1bad1c4f..c00868aeac 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx@@ -1,5 +1,3 @@-import type { GraphContract } from '@workbench/graphContracts';-import type { Project } from '@workbench/projectContracts';import type {GraphBearingSurfaceContract,WidgetInstanceRuntimeMeta,@@ -16,7 +14,7 @@ import { createGraphBearingSurface } from '@workbench/graphSurfaces';import { resolveWidgetLabel } from '@workbench/widgetLabels';import { getEnabledCenterViewCount } from '@workbench/widgetPlacementCommands';import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';-import { shallowEqual, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';import { GitBranchIcon, MoreHorizontalIcon, PictureInPicture2Icon, TargetIcon } from 'lucide-react';import { lazy, Suspense, useCallback, useMemo, useState } from 'react';@@ -29,36 +27,7 @@ import { useTranslation } from 'react-i18next';* widgets extend the frame instead of stacking their own menus and toolbars.*/-const GraphPreviewDialog = lazy(() =>- import('@features/workflow/preview').then((module) => ({ default: module.GraphPreviewDialog }))-);--const getPreviewGraph = async (- project: Project,- surface: GraphBearingSurfaceContract-): Promise<GraphContract | null> => {- // The project graph compiles fresh for preview so `View Graph` always shows- // what Invoke would run right now; widget graphs keep their last compile.- if (surface.sourceId === 'workflow') {- const [{ compileProjectGraph }, { getInvocationTemplatesSnapshot }] = await Promise.all([- import('@features/workflow/graph'),- import('@features/workflow/react'),- ]);- const templatesSnapshot = getInvocationTemplatesSnapshot();-- if (templatesSnapshot.status !== 'loaded') {- return null;- }-- try {- return compileProjectGraph(project.projectGraph, templatesSnapshot.templates);- } catch {- return null;- }- }-- return project.widgetGraphs[surface.widgetId] ?? null;-};+const GraphPreviewHost = lazy(() => import('./GraphPreviewHost'));const MENU_POSITIONING = { placement: 'bottom-end' } as const;const DISABLED_PROPS = { opacity: 0.4 };@@ -117,15 +86,10 @@ export const WidgetActionsMenu = ({runtime: WidgetRuntimeApi;}) => {const { t } = useTranslation();- const activeProject = useActiveProjectSelector(- (project) => ({ projectGraph: project.projectGraph, widgetGraphs: project.widgetGraphs }),- shallowEqual- ) as Project;const placementProject = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const { getWidgetById } = useWorkbenchWidgetRegistry();const { widgets } = useWorkbenchCommands();const [isPreviewOpen, setIsPreviewOpen] = useState(false);- const [previewGraph, setPreviewGraph] = useState<GraphContract | null>(null);const label = resolveWidgetLabel(manifest, t);const surface = useMemo(() =>@@ -146,25 +110,15 @@ export const WidgetActionsMenu = ({flushWorkbenchDrafts();widgets.float(instance.id);}, [instance.id, widgets]);- const surfaceSourceId = surface?.sourceId;- const handlePreview = useCallback(async () => {+ const handlePreview = useCallback(() => {flushWorkbenchDrafts();- if (surface) {- setPreviewGraph(await getPreviewGraph(activeProject, surface));- }setIsPreviewOpen(true);- }, [activeProject, surface]);- const positionHints =- isPreviewOpen && surfaceSourceId === 'workflow'- ? Object.fromEntries(activeProject.projectGraph.nodes.map((node) => [node.id, node.position]))- : undefined;+ }, []);if (!surface && !HeaderMenu && !canFloat) {return null;}- // The project graph mirrors the editable document, so the preview can reuse- // the editor's node positions instead of auto-layouting.return (<><Menu.Root positioning={MENU_POSITIONING}>@@ -194,15 +148,7 @@ export const WidgetActionsMenu = ({</Menu.Root>{surface && isPreviewOpen ? (<Suspense fallback={null}>- <GraphPreviewDialog- graph={previewGraph}- graphId={surface.graphId}- isOpen={isPreviewOpen}- positionHints={positionHints}- sourceId={surface.sourceId}- title={surface.label}- onOpenChange={setIsPreviewOpen}- />+ <GraphPreviewHost isOpen={isPreviewOpen} surface={surface} onOpenChange={setIsPreviewOpen} /></Suspense>) : null}</>diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.tsnew file mode 100644index 0000000000..f10663bb35--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts@@ -0,0 +1,136 @@+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';+import type { InvocationTemplatesSnapshot } from '@features/workflow/react';+import type { GraphContract } from '@workbench/graphContracts';+import type { TFunction } from 'i18next';++import { getDefaultGenerateSettings } from '@features/generation/settings';+import { createGraphBearingSurface } from '@workbench/graphSurfaces';+import { canvasWidgetManifest } from '@workbench/widgets/canvas/manifest';+import { generateWidgetManifest } from '@workbench/widgets/generate/manifest';+import { workflowWidgetManifest } from '@workbench/widgets/workflow/manifest';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';+import { describe, expect, it } from 'vitest';++import { buildGraphPreviewSource } from './graphPreviewSource';++const t = ((key: string) => key) as TFunction;++const sdxlModel = {+ base: 'sdxl',+ file_size: 0,+ format: 'diffusers',+ hash: 'sdxl-hash',+ key: 'sdxl-model',+ name: 'SDXL',+ path: 'sdxl.safetensors',+ source: 'sdxl.safetensors',+ source_type: 'path',+ type: 'main',+} satisfies ModelConfig;++const models: ModelConfig[] = [sdxlModel];++const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({+ ...getDefaultGenerateSettings(sdxlModel),+ model: sdxlModel,+ modelKey: sdxlModel.key,+ positivePrompt: 'a sdxl prompt',+ ...overrides,+});++const getActiveProject = (values: GenerateWidgetValues) => {+ const state = workbenchReducer(createInitialWorkbenchState(), { type: 'setGenerateSettings', values });+ const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);++ expect(project).toBeDefined();++ return project!;+};++const idleTemplates: InvocationTemplatesSnapshot = { error: null, status: 'idle', templates: {} };+const loadedTemplates: InvocationTemplatesSnapshot = { error: null, status: 'loaded', templates: {} };++const project = getActiveProject(createGenerateValues());+const generateSurface = createGraphBearingSurface(generateWidgetManifest, 'left', 'Generate')!;+const workflowSurface = createGraphBearingSurface(workflowWidgetManifest, 'left', 'Workflow')!;+const canvasSurface = createGraphBearingSurface(canvasWidgetManifest, 'center', 'Canvas')!;++describe('buildGraphPreviewSource', () => {+ it('live-compiles the generate source and reports a seed notice when randomized', () => {+ const source = buildGraphPreviewSource({ models, project, surface: generateSurface, t, templates: idleTemplates });++ expect(source.isLive).toBe(true);+ expect(source.graph).not.toBeNull();+ expect(source.notices).toEqual([{ id: 'seed-random', message: 'graphPreview.seedRandomized', nodeId: 'seed' }]);+ expect(source.getProvenance?.('denoise_latents', 'steps')).toEqual({ label: 'graphPreview.provenance.steps' });+ expect(source.getProvenance?.('seed', 'value')).toEqual({ label: 'graphPreview.provenance.seedRandom' });+ expect(source.resolvedInputOverrides).toEqual({ seed: { value: 'graphPreview.seedRegenerated' } });+ expect(source.summaryRows.some((row) => row.id === 'steps')).toBe(true);+ });++ it('returns invalid reasons instead of a graph when generate settings cannot compile', () => {+ const invalidProject = getActiveProject(createGenerateValues({ width: 1000, height: 999 }));+ const source = buildGraphPreviewSource({+ models,+ project: invalidProject,+ surface: generateSurface,+ t,+ templates: idleTemplates,+ });++ expect(source.graph).toBeNull();+ expect(source.invalidReasons.length).toBeGreaterThan(0);+ expect(source.isLive).toBe(true);+ });++ it('compiles the workflow source from the live document with position hints', () => {+ const source = buildGraphPreviewSource({+ models: undefined,+ project,+ surface: workflowSurface,+ t,+ templates: loadedTemplates,+ });++ expect(source.isLive).toBe(true);+ expect(source.positionHints).toBeDefined();+ });++ it('returns null graph for workflow when templates are not loaded', () => {+ const source = buildGraphPreviewSource({+ models: undefined,+ project,+ surface: workflowSurface,+ t,+ templates: idleTemplates,+ });++ expect(source.graph).toBeNull();+ expect(source.isLive).toBe(true);+ });++ it('falls back to the last compiled widget graph for canvas', () => {+ const canvasGraph: GraphContract = {+ edges: [],+ id: 'canvas-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '',+ version: 1,+ };+ const canvasProject = { ...project, widgetGraphs: { ...project.widgetGraphs, canvas: canvasGraph } };+ const source = buildGraphPreviewSource({+ models: undefined,+ project: canvasProject,+ surface: canvasSurface,+ t,+ templates: idleTemplates,+ });++ expect(source.isLive).toBe(false);+ expect(source.graph).toBe(canvasGraph);+ expect(source.notices).toEqual([]);+ expect(source.summaryRows).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.tsnew file mode 100644index 0000000000..84276c14fe--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts@@ -0,0 +1,142 @@+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { ModelConfig } from '@features/models';+import type {+ GraphPreviewNotice,+ GraphPreviewProvenance,+ GraphPreviewSourceState,+ GraphPreviewSummaryRow,+} from '@features/workflow/contracts';+import type { InvocationTemplatesSnapshot } from '@features/workflow/react';+import type { Project } from '@workbench/projectContracts';+import type { GraphBearingSurfaceContract } from '@workbench/widgetContracts';+import type { TFunction } from 'i18next';++import { compileGeneratePreviewGraph, getGenerateNodeProvenance } from '@features/generation/graph';+import { compileProjectGraph } from '@features/workflow/graph';+import { getProjectWidgetValues } from '@workbench/widgetState';++/**+ * Pure translation from the active project + surface into the preview+ * dialog's data. Kept side-effect free so it can run on every keystroke+ * (`GraphPreviewHost` recomputes it in a `useMemo`) without triggering any+ * loads itself — callers are responsible for ensuring models/templates are+ * fetched (`ensureModelsLoaded`, `ensureInvocationTemplatesLoaded`).+ */+export interface GraphPreviewSourceDeps {+ models: readonly ModelConfig[] | undefined;+ project: Project;+ surface: GraphBearingSurfaceContract;+ t: TFunction;+ templates: InvocationTemplatesSnapshot;+}++const buildGenerateSummaryRows = (settings: GenerateWidgetValues, t: TFunction): GraphPreviewSummaryRow[] => {+ const activeLoras = settings.loras.filter((lora) => lora.isEnabled).length;++ return [+ { id: 'model', label: t('graphPreview.model'), value: settings.model.name },+ { id: 'size', label: t('graphPreview.size'), value: `${settings.width} × ${settings.height}` },+ { id: 'steps', label: t('graphPreview.steps'), value: String(settings.steps) },+ { id: 'cfgScale', label: t('graphPreview.cfgScale'), value: String(settings.cfgScale) },+ { id: 'scheduler', label: t('graphPreview.scheduler'), value: settings.scheduler },+ ...(activeLoras > 0 ? [{ id: 'loras', label: t('graphPreview.loras'), value: String(activeLoras) }] : []),+ {+ id: 'seed',+ label: t('graphPreview.seed'),+ value: settings.shouldRandomizeSeed ? t('graphPreview.seedRandomValue') : String(settings.seed),+ },+ ];+};++const EMPTY_SOURCE_BASE: Pick<GraphPreviewSourceState, 'invalidReasons' | 'notices' | 'summaryRows'> = {+ invalidReasons: [],+ notices: [],+ summaryRows: [],+};++const buildWorkflowSource = (project: Project, templates: InvocationTemplatesSnapshot): GraphPreviewSourceState => {+ if (templates.status !== 'loaded') {+ return { ...EMPTY_SOURCE_BASE, graph: null, isLive: true };+ }++ const positionHints = Object.fromEntries(project.projectGraph.nodes.map((node) => [node.id, node.position]));++ try {+ const graph = compileProjectGraph(project.projectGraph, templates.templates);++ return { ...EMPTY_SOURCE_BASE, graph, isLive: true, positionHints };+ } catch {+ return { ...EMPTY_SOURCE_BASE, graph: null, isLive: true, positionHints };+ }+};++const buildGenerateSource = (+ project: Project,+ models: readonly ModelConfig[] | undefined,+ t: TFunction+): GraphPreviewSourceState => {+ const result = compileGeneratePreviewGraph({+ destination: project.invocation.destination,+ models: models ?? [],+ storedValues: getProjectWidgetValues(project, 'generate'),+ useCpuNoise: project.settings.useCpuNoise,+ });++ if (result.status === 'invalid') {+ return { ...EMPTY_SOURCE_BASE, graph: null, invalidReasons: result.reasons, isLive: true };+ }++ const { settings } = result;+ const isSeedRandomized = settings.shouldRandomizeSeed;+ const notices: GraphPreviewNotice[] = isSeedRandomized+ ? [{ id: 'seed-random', message: t('graphPreview.seedRandomized'), nodeId: 'seed' }]+ : [];+ const resolvedInputOverrides = isSeedRandomized ? { seed: { value: t('graphPreview.seedRegenerated') } } : undefined;+ const getProvenance = (nodeId: string, fieldName: string): GraphPreviewProvenance | null => {+ const entry = getGenerateNodeProvenance(nodeId, fieldName);++ if (!entry) {+ return null;+ }++ if (entry.settingKey === 'seed' && isSeedRandomized) {+ return { label: t('graphPreview.provenance.seedRandom') };+ }++ return { label: t(entry.labelKey) };+ };++ return {+ getProvenance,+ graph: result.graph,+ invalidReasons: [],+ isLive: true,+ notices,+ resolvedInputOverrides,+ summaryRows: buildGenerateSummaryRows(settings, t),+ };+};++const buildWidgetGraphSource = (project: Project, surface: GraphBearingSurfaceContract): GraphPreviewSourceState => ({+ ...EMPTY_SOURCE_BASE,+ graph: project.widgetGraphs[surface.widgetId] ?? null,+ isLive: false,+});++export const buildGraphPreviewSource = ({+ models,+ project,+ surface,+ t,+ templates,+}: GraphPreviewSourceDeps): GraphPreviewSourceState => {+ switch (surface.sourceId) {+ case 'workflow':+ return buildWorkflowSource(project, templates);+ case 'generate':+ return buildGenerateSource(project, models, t);+ case 'upscale':+ case 'canvas':+ return buildWidgetGraphSource(project, surface);+ }+};