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): add deterministic generate preview graph compile
joshistoastfd94f72cf15b
diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.tsnew file mode 100644index 0000000000..00e2ed43f0--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it } from 'vitest';++import type { GenerationModelCatalogItem } from './contracts';+import type { GenerateLora, GenerateWidgetValues, LoraModelConfig, MainModelConfig } from './types';++import { getDefaultGenerateSettings } from './baseGenerationPolicies';+import { compileGeneratePreviewGraph, stabilizeBackendGraphIds } from './previewGraph';++const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };++const loraModelA: LoraModelConfig = { base: 'sdxl', key: 'lora-a', name: 'Lora A', type: 'lora' };+const loraModelB: LoraModelConfig = { base: 'sdxl', key: 'lora-b', name: 'Lora B', type: 'lora' };++const loraA: GenerateLora = { isEnabled: true, model: loraModelA, weight: 0.75 };+const loraB: GenerateLora = { isEnabled: true, model: loraModelB, weight: 0.5 };++const models: GenerationModelCatalogItem[] = [sdxlModel, loraModelA, loraModelB];++const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({+ ...getDefaultGenerateSettings(sdxlModel),+ model: sdxlModel,+ modelKey: sdxlModel.key,+ positivePrompt: 'a preview prompt',+ ...overrides,+});++const storedValues = createGenerateValues({+ cfgScale: 4,+ height: 1024,+ loras: [loraA, loraB],+ seed: 123,+ shouldRandomizeSeed: true,+ steps: 28,+ width: 1024,+});++describe('compileGeneratePreviewGraph', () => {+ it('compiles a ready graph with deterministic node ids across repeated compiles', () => {+ const input = { destination: 'gallery' as const, models, storedValues, useCpuNoise: false };+ const first = compileGeneratePreviewGraph(input);+ const second = compileGeneratePreviewGraph(input);++ expect(first.status).toBe('ready');++ if (first.status !== 'ready' || second.status !== 'ready') {+ return;+ }++ expect(first.graph.id).toBe('generate-preview');+ expect(first.graph.nodes.map((node) => node.id)).toEqual(second.graph.nodes.map((node) => node.id));++ const ids = first.graph.nodes.map((node) => node.id);++ expect(ids).toContain('core_metadata');+ expect(ids).toContain('lora_selector');+ expect(ids).toContain('lora_selector_2');+ expect(ids).toContain('denoise_latents');+ });++ it('keeps the literal seed value instead of resolving a random one', () => {+ const result = compileGeneratePreviewGraph({ destination: 'gallery', models, storedValues, useCpuNoise: false });++ if (result.status !== 'ready') {+ throw new Error('expected ready');+ }++ const seedNode = result.graph.nodes.find((node) => node.id === 'seed');++ expect(seedNode?.inputs.value).toBe(123);+ });++ it('rewrites edges consistently with rewritten node ids', () => {+ const result = compileGeneratePreviewGraph({ destination: 'gallery', models, storedValues, useCpuNoise: false });++ if (result.status !== 'ready') {+ throw new Error('expected ready');+ }++ const nodeIds = new Set(result.graph.nodes.map((node) => node.id));++ for (const edge of result.graph.edges) {+ expect(nodeIds.has(edge.sourceNodeId)).toBe(true);+ expect(nodeIds.has(edge.targetNodeId)).toBe(true);+ }+ });++ it('returns invalid with reasons instead of throwing on bad settings', () => {+ // 999 is not a multiple of the SDXL dimension grid (8).+ const badValues = { ...storedValues, height: 999 };+ const result = compileGeneratePreviewGraph({+ destination: 'gallery',+ models,+ storedValues: badValues,+ useCpuNoise: false,+ });++ expect(result.status).toBe('invalid');++ if (result.status === 'invalid') {+ expect(result.reasons.length).toBeGreaterThan(0);+ }+ });++ it('returns invalid when no supported model resolves', () => {+ const result = compileGeneratePreviewGraph({+ destination: 'gallery',+ models: [],+ storedValues,+ useCpuNoise: false,+ });++ expect(result.status).toBe('invalid');+ });+});++describe('stabilizeBackendGraphIds', () => {+ it('rewrites createId-suffixed ids to stable prefixes in insertion order, including edges', () => {+ const graph = {+ edges: [+ {+ destination: { field: 'value', node_id: 'lora_selector_lqx1abc_a1b2c3' },+ source: { field: 'value', node_id: 'seed' },+ },+ ],+ id: 'sdxl_graph_lqx1abc_z9z9z9',+ nodes: {+ core_metadata_lqx1abc_d4e5f6: { id: 'core_metadata_lqx1abc_d4e5f6', type: 'core_metadata' },+ lora_selector_lqx1abc_a1b2c3: { id: 'lora_selector_lqx1abc_a1b2c3', type: 'lora_selector' },+ lora_selector_lqx1abc_z9y8x7: { id: 'lora_selector_lqx1abc_z9y8x7', type: 'lora_selector' },+ seed: { id: 'seed', type: 'integer' },+ },+ };++ const result = stabilizeBackendGraphIds(graph);++ expect(Object.keys(result.nodes)).toEqual(['core_metadata', 'lora_selector', 'lora_selector_2', 'seed']);+ expect(result.edges[0]).toEqual({+ destination: { field: 'value', node_id: 'lora_selector' },+ source: { field: 'value', node_id: 'seed' },+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.tsnew file mode 100644index 0000000000..c8790bca85--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.ts@@ -0,0 +1,122 @@+import type { BackendGraphContract, GenerationModelCatalogItem, GraphContract, ResultDestination } from './contracts';+import type { GenerateWidgetValues } from './types';++import { getGenerationModelAvailabilityReasons, getGenerationValidationReasons } from './baseGenerationPolicies';+import { compileGenerateGraph } from './graph';+import { resolveGenerateWidgetValues } from './resolveGenerateWidgetValues';++/**+ * Preview-only compile: deterministic where the submit path is intentionally+ * random. Ids from `createId` (`prefix_<b36 time>_<6 rand>`) collapse to+ * `prefix`, `prefix_2`, … in insertion order so selection and layout survive+ * live recompiles, and the seed stays the stored literal (the dialog labels it+ * "regenerated each run" when randomization is on).+ */++const NO_SUPPORTED_MODEL = 'Generate needs a supported model before it can be invoked.';++export interface GeneratePreviewInput {+ destination: ResultDestination;+ models: readonly GenerationModelCatalogItem[];+ storedValues: unknown;+ useCpuNoise: boolean;+}++export type GeneratePreviewResult =+ | { status: 'ready'; graph: GraphContract; settings: GenerateWidgetValues }+ | { status: 'invalid'; reasons: string[] };++const CREATED_ID_PATTERN = /^(.+)_[a-z0-9]{7,9}_[a-z0-9]{4,6}$/;++export const stabilizeBackendGraphIds = (graph: BackendGraphContract): BackendGraphContract => {+ const rename = new Map<string, string>();+ const used = new Set<string>();++ for (const id of Object.keys(graph.nodes)) {+ const match = CREATED_ID_PATTERN.exec(id);+ const base = match ? match[1] : id;+ let candidate = base;+ let suffix = 2;++ while (used.has(candidate)) {+ candidate = `${base}_${suffix}`;+ suffix += 1;+ }++ used.add(candidate);+ rename.set(id, candidate);+ }++ return {+ edges: graph.edges.map((edge) => ({+ destination: {+ field: edge.destination.field,+ node_id: rename.get(edge.destination.node_id) ?? edge.destination.node_id,+ },+ source: { field: edge.source.field, node_id: rename.get(edge.source.node_id) ?? edge.source.node_id },+ })),+ id: 'generate-preview',+ nodes: Object.fromEntries(+ Object.entries(graph.nodes).map(([id, node]) => {+ const nextId = rename.get(id) ?? id;++ return [nextId, { ...node, id: nextId }];+ })+ ),+ };+};++const toPreviewContract = (backendGraph: BackendGraphContract, label: string): GraphContract => ({+ backendGraph,+ edges: backendGraph.edges.map((edge, index) => ({+ id: `edge-${index}`,+ sourceField: edge.source.field,+ sourceNodeId: edge.source.node_id,+ targetField: edge.destination.field,+ targetNodeId: edge.destination.node_id,+ })),+ id: backendGraph.id,+ label,+ nodes: Object.values(backendGraph.nodes).map(({ id, type, ...inputs }) => ({ id, inputs, type })),+ updatedAt: '',+ version: 1,+});++export const compileGeneratePreviewGraph = (input: GeneratePreviewInput): GeneratePreviewResult => {+ const resolved = resolveGenerateWidgetValues({ models: input.models, storedValues: input.storedValues });++ if (!resolved) {+ return { reasons: [NO_SUPPORTED_MODEL], status: 'invalid' };+ }++ const settings = resolved.values;+ const reasons = [+ ...getGenerationValidationReasons(settings.model, settings),+ ...getGenerationModelAvailabilityReasons(settings.model, settings, input.models),+ ];++ if (reasons.length > 0) {+ return { reasons, status: 'invalid' };+ }++ try {+ const compiled = compileGenerateGraph(settings, settings.model, input.destination, {+ useCpuNoise: input.useCpuNoise,+ });+ // The submit path leaves the seed node's `value` unset and injects the+ // resolved seed via queue batch data instead (see `promptBatch.ts`). The+ // preview has no batch step, so bake the literal, unresolved seed in here.+ const seedNode = compiled.backendGraph.nodes[compiled.seedNodeId];+ const backendGraphWithSeed: BackendGraphContract = seedNode+ ? {+ ...compiled.backendGraph,+ nodes: { ...compiled.backendGraph.nodes, [compiled.seedNodeId]: { ...seedNode, value: settings.seed } },+ }+ : compiled.backendGraph;+ const backendGraph = stabilizeBackendGraphIds(backendGraphWithSeed);++ return { graph: toPreviewContract(backendGraph, compiled.graph.label), settings, status: 'ready' };+ } catch (error) {+ return { reasons: [error instanceof Error ? error.message : String(error)], status: 'invalid' };+ }+};diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.tsindex 3cc9edc737..4771ad28ea 100644--- a/invokeai/frontend/webv2/src/features/generation/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts@@ -4,6 +4,8 @@* Curated, caller-driven export list — add a symbol only when a consumer needs it.*/export { addLoraCollectionLoader, compileGenerateGraph, resolveGenerateSeed } from './core/graph';+export { compileGeneratePreviewGraph, stabilizeBackendGraphIds } from './core/previewGraph';+export type { GeneratePreviewInput, GeneratePreviewResult } from './core/previewGraph';export { addEdge, addNode, getActiveCompatibleLoras, toGraphContract, toModelIdentifier } from './core/graphBuilder';export { compileCanvasGraph } from './core/canvas/compileCanvasGraph';export { detectCanvasMode } from './core/canvas/canvasMode';