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): run batch and generator nodes in workflows

Josh Corbett7599f6fecf2f
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 4adb091127..dd31f49718 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -668,6 +668,7 @@
"source:src/features/video/core/widgetValues.ts",
"source:src/features/video/index.ts",
"source:src/features/video/ui/VideoUiContext.tsx",
+ "source:src/features/workflow/core/batch.ts",
"source:src/features/workflow/core/buildGraph.ts",
"source:src/features/workflow/core/callSavedWorkflow.ts",
"source:src/features/workflow/core/connectors.ts",
@@ -679,6 +680,7 @@
"source:src/features/workflow/core/validation.ts",
"source:src/features/workflow/core/workflowJson.ts",
"source:src/features/workflow/data/api.ts",
+ "source:src/features/workflow/data/generatorQueries.ts",
"source:src/features/workflow/data/libraryCache.ts",
"source:src/features/workflow/data/runCapture.ts",
"source:src/features/workflow/data/savedWorkflowQueries.ts",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 094bf0410f..36c944973f 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1173,6 +1173,7 @@
"source:src/features/video/core/widgetValues.ts",
"source:src/features/video/index.ts",
"source:src/features/video/ui/VideoUiContext.tsx",
+ "source:src/features/workflow/core/batch.ts",
"source:src/features/workflow/core/buildGraph.ts",
"source:src/features/workflow/core/callSavedWorkflow.ts",
"source:src/features/workflow/core/connectors.ts",
@@ -1186,6 +1187,7 @@
"source:src/features/workflow/core/validation.ts",
"source:src/features/workflow/core/workflowJson.ts",
"source:src/features/workflow/data/api.ts",
+ "source:src/features/workflow/data/generatorQueries.ts",
"source:src/features/workflow/data/libraryBrowseStore.ts",
"source:src/features/workflow/data/libraryCache.ts",
"source:src/features/workflow/data/runCapture.ts",
@@ -2226,6 +2228,7 @@
"source:src/features/video/core/widgetValues.ts",
"source:src/features/video/index.ts",
"source:src/features/video/ui/VideoUiContext.tsx",
+ "source:src/features/workflow/core/batch.ts",
"source:src/features/workflow/core/buildGraph.ts",
"source:src/features/workflow/core/callSavedWorkflow.ts",
"source:src/features/workflow/core/connectors.ts",
@@ -2240,6 +2243,7 @@
"source:src/features/workflow/core/validation.ts",
"source:src/features/workflow/core/workflowJson.ts",
"source:src/features/workflow/data/api.ts",
+ "source:src/features/workflow/data/generatorQueries.ts",
"source:src/features/workflow/data/libraryBrowseStore.ts",
"source:src/features/workflow/data/libraryCache.ts",
"source:src/features/workflow/data/runCapture.ts",
@@ -3455,6 +3459,7 @@
"source:src/features/video/core/widgetValues.ts",
"source:src/features/video/index.ts",
"source:src/features/video/ui/VideoUiContext.tsx",
+ "source:src/features/workflow/core/batch.ts",
"source:src/features/workflow/core/buildGraph.ts",
"source:src/features/workflow/core/callSavedWorkflow.ts",
"source:src/features/workflow/core/connectors.ts",
@@ -3471,6 +3476,7 @@
"source:src/features/workflow/core/validation.ts",
"source:src/features/workflow/core/workflowJson.ts",
"source:src/features/workflow/data/api.ts",
+ "source:src/features/workflow/data/generatorQueries.ts",
"source:src/features/workflow/data/libraryBrowseStore.ts",
"source:src/features/workflow/data/libraryCache.ts",
"source:src/features/workflow/data/runCapture.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 23c17eff53..4cebb0012e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1536,6 +1536,41 @@
"contextCollapse": "Collapse",
"contextExpand": "Expand",
"contextAddConnector": "Add connector",
+ "arithmeticSequence": "Arithmetic sequence",
+ "linearDistribution": "Linear distribution",
+ "uniformRandomDistribution": "Uniform random distribution",
+ "parseString": "Parse string",
+ "splitOn": "Split on",
+ "dynamicPromptsRandom": "Dynamic prompts (random)",
+ "dynamicPromptsCombinatorial": "Dynamic prompts (combinatorial)",
+ "generatorImagesFromBoard": "Images from board",
+ "generatorImagesCategory": "Category",
+ "generatorCategoryImages": "Images",
+ "generatorCategoryAssets": "Assets",
+ "generatorImages_one": "{{count}} image",
+ "generatorImages_other": "{{count}} images",
+ "generatorNRandomValues_one": "{{count}} random value",
+ "generatorNRandomValues_other": "{{count}} random values",
+ "generatorNoValues": "empty",
+ "generatorLoading": "Loading…",
+ "generatorLoadFromFile": "Load from file",
+ "generatorFileTooLarge": "The file is larger than 128 KB.",
+ "generatorPreviewFailed": "The preview could not be loaded.",
+ "generatorPreviewTruncated": "{{count}} values in all",
+ "generatorTooMany": "More than {{max}} values; the queue cannot take that many.",
+ "generatorStart": "Start",
+ "generatorStep": "Step",
+ "generatorEnd": "End",
+ "generatorCount": "Count",
+ "generatorMin": "Min",
+ "generatorMax": "Max",
+ "generatorSeed": "Seed",
+ "generatorMaxPrompts": "Max prompts",
+ "generatorInput": "Input",
+ "generatorBoard": "Board",
+ "generatorSelectBoard": "Select a board…",
+ "generatorBoardMissing": "Board unavailable",
+ "noBatchGroup": "no group",
"collectionItemCount_one": "{{count}} item",
"collectionItemCount_other": "{{count}} items",
"forLoopBodyBoundaryStatus": {
diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.test.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.test.ts
index bb761b4a24..4e0ac22d57 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.test.ts
@@ -2,7 +2,12 @@ import { describe, expect, it } from 'vitest';
import type { GeneratePromptBatchPlanInput } from './promptBatch';
-import { buildGeneratePromptBatchPlan, generateSeedSequence } from './promptBatch';
+import {
+ buildGeneratePromptBatchPlan,
+ buildQueueWorkflowBatchPlan,
+ generateSeedSequence,
+ isQueueWorkflowBatchDatum,
+} from './promptBatch';
const SEED_MAX = 4_294_967_295;
@@ -161,3 +166,65 @@ describe('buildGeneratePromptBatchPlan with several prompts', () => {
expect(plan.expectedImageCount).toBe(1);
});
});
+
+describe('buildQueueWorkflowBatchPlan', () => {
+ const seed = { fieldName: 'seed', nodeId: 'noise', seed: 10, seedStep: 1 as const };
+ const cfg = { fieldName: 'cfg', items: [1, 2], nodeId: 'denoise' };
+ const prompt = { fieldName: 'text', items: ['a', 'b', 'c'], nodeId: 'prompt' };
+ const image = {
+ fieldName: 'image',
+ items: [{ image_name: 'x.png' }, { image_name: 'y.png' }, { image_name: 'z.png' }],
+ nodeId: 'sink',
+ };
+
+ it('repeats one graph, or lets the backend multiply the groups, while every seed holds', () => {
+ expect(buildQueueWorkflowBatchPlan({ batchCount: 3, batchData: undefined, seeds: [] })).toEqual({ runs: 3 });
+ expect(
+ buildQueueWorkflowBatchPlan({ batchCount: 2, batchData: [[cfg], [prompt, image]], seeds: undefined })
+ ).toEqual({
+ data: [
+ [{ field_name: 'cfg', items: [1, 2], node_path: 'denoise' }],
+ [
+ { field_name: 'text', items: ['a', 'b', 'c'], node_path: 'prompt' },
+ { field_name: 'image', items: image.items, node_path: 'sink' },
+ ],
+ ],
+ runs: 2,
+ });
+ });
+
+ it('keeps the seed-only plan: one zipped group of seeds over the runs', () => {
+ expect(buildQueueWorkflowBatchPlan({ batchCount: 3, batchData: [], seeds: [seed] })).toEqual({
+ data: [[{ field_name: 'seed', items: [10, 11, 12], node_path: 'noise' }]],
+ runs: 1,
+ });
+ });
+
+ it('gives every session its own seed by expanding the product run-major into one zipped group', () => {
+ const plan = buildQueueWorkflowBatchPlan({ batchCount: 2, batchData: [[cfg], [prompt, image]], seeds: [seed] });
+
+ expect(plan.runs).toBe(1);
+ expect(plan.data).toHaveLength(1);
+
+ const group = plan.data?.[0] ?? [];
+ const byField = Object.fromEntries(group.map((datum) => [datum.field_name, datum.items]));
+
+ // 2 runs × (2 cfg × 3 prompts) = 12 sessions, seeds walking straight through them.
+ expect(byField.seed).toEqual([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]);
+ // The first group varies slowest within a run, the run repeats the whole product.
+ expect(byField.cfg).toEqual([1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2]);
+ expect(byField.text).toEqual(['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']);
+ expect(byField.image).toEqual([...image.items, ...image.items, ...image.items, ...image.items]);
+ expect(new Set(group.map((datum) => datum.items.length)).size).toBe(1);
+ });
+
+ it('recognises a persisted batch datum and rejects malformed ones', () => {
+ expect(isQueueWorkflowBatchDatum(cfg)).toBe(true);
+ expect(isQueueWorkflowBatchDatum(image)).toBe(true);
+ expect(isQueueWorkflowBatchDatum({ ...cfg, items: [] })).toBe(false);
+ expect(isQueueWorkflowBatchDatum({ ...cfg, items: [Number.NaN] })).toBe(false);
+ expect(isQueueWorkflowBatchDatum({ ...cfg, items: [{ image_name: '' }] })).toBe(false);
+ expect(isQueueWorkflowBatchDatum({ ...cfg, nodeId: '' })).toBe(false);
+ expect(isQueueWorkflowBatchDatum({ ...cfg, items: Array.from({ length: 10_001 }, () => 1) })).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
index 063b347327..1a42d04dfb 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
@@ -32,13 +32,50 @@ export const generateSeedSequence = (start: number, count: number, step: QueueSe
);
};
+/** A value the backend substitutes into a node field per session. */
+export type QueueBatchItem = number | string | { image_name: string };
+
/** One value list of a zipped batch group, in the backend's `BatchDatum` shape. */
export interface QueueBatchDatum {
field_name: string;
- items: (number | string)[];
+ items: QueueBatchItem[];
node_path: string;
}
+/** A batch-node value list, as a workflow submission persists it (camelCase, like `QueueWorkflowSeed`). */
+export interface QueueWorkflowBatchDatum {
+ fieldName: string;
+ items: QueueBatchItem[];
+ nodeId: string;
+}
+
+const isQueueBatchItem = (value: unknown): value is QueueBatchItem =>
+ typeof value === 'string' ||
+ (typeof value === 'number' && Number.isFinite(value)) ||
+ (typeof value === 'object' &&
+ value !== null &&
+ typeof (value as { image_name?: unknown }).image_name === 'string' &&
+ (value as { image_name: string }).image_name.length > 0);
+
+export const isQueueWorkflowBatchDatum = (value: unknown): value is QueueWorkflowBatchDatum => {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+
+ const datum = value as Partial<QueueWorkflowBatchDatum>;
+
+ return (
+ typeof datum.fieldName === 'string' &&
+ datum.fieldName.length > 0 &&
+ typeof datum.nodeId === 'string' &&
+ datum.nodeId.length > 0 &&
+ Array.isArray(datum.items) &&
+ datum.items.length > 0 &&
+ datum.items.length <= MAX_QUEUE_BATCH_ITEMS &&
+ datum.items.every(isQueueBatchItem)
+ );
+};
+
export interface GeneratePromptBatchDatum extends QueueBatchDatum {
field_name: 'value';
}
@@ -71,41 +108,99 @@ export const isQueueWorkflowSeed = (value: unknown): value is QueueWorkflowSeed
);
};
-export interface WorkflowSeedBatchPlan {
- /** One zipped group over every varying input, or undefined while every seed holds. */
+export interface WorkflowBatchPlan {
+ /** Batch groups in the backend's shape, or undefined when one graph repeats unchanged. */
data?: QueueBatchDatum[][];
runs: number;
}
+const toBackendDatum = (datum: QueueWorkflowBatchDatum): QueueBatchDatum => ({
+ field_name: datum.fieldName,
+ items: datum.items,
+ node_path: datum.nodeId,
+});
+
+/**
+ * Every combination the backend would produce from `groups`, in its order: the first group varies slowest, and
+ * each group's datums are read in step. Each entry maps a datum to the index of the item that combination uses.
+ */
+const expandCombinations = (groups: readonly (readonly QueueWorkflowBatchDatum[])[]): number[][] => {
+ let combinations: number[][] = [[]];
+
+ for (const group of groups) {
+ const length = group[0]?.items.length ?? 0;
+ const next: number[][] = [];
+
+ for (const prefix of combinations) {
+ for (let index = 0; index < length; index += 1) {
+ next.push([...prefix, index]);
+ }
+ }
+
+ combinations = next;
+ }
+
+ return combinations;
+};
+
/**
- * A workflow batch repeats one graph unless a seed input varies, in which case
- * every varying input joins one zipped group so `batchCount` runs stay
- * `batchCount` runs. A single run needs no data: the plan already wrote each
- * start seed into the graph.
+ * Without varying seeds the backend multiplies the batch groups itself and repeats the product `batchCount` times.
+ * Once a seed steps, every session must get its own seed, so the product is expanded here into one zipped group,
+ * run-major, with each seed walking straight through it.
*/
-export const buildWorkflowSeedBatchPlan = ({
+export const buildQueueWorkflowBatchPlan = ({
batchCount,
+ batchData,
seeds,
}: {
batchCount: number;
+ batchData: readonly (readonly QueueWorkflowBatchDatum[])[] | undefined;
seeds: readonly QueueWorkflowSeed[] | undefined;
-}): WorkflowSeedBatchPlan => {
+}): WorkflowBatchPlan => {
const runs = sanitizeBatchCount(batchCount);
+ const groups = (batchData ?? []).filter((group) => group.length > 0);
+ const hasSeeds = !!seeds && seeds.length > 0;
- if (!seeds || seeds.length === 0 || runs === 1) {
- return { runs };
+ if (!hasSeeds || (runs === 1 && groups.length === 0)) {
+ return groups.length > 0 ? { data: groups.map((group) => group.map(toBackendDatum)), runs } : { runs };
}
- return {
- data: [
- seeds.map((seed) => ({
- field_name: seed.fieldName,
- items: generateSeedSequence(seed.seed, runs, seed.seedStep),
- node_path: seed.nodeId,
- })),
- ],
- runs: 1,
- };
+ if (groups.length === 0) {
+ return {
+ data: [
+ seeds.map((seed) => ({
+ field_name: seed.fieldName,
+ items: generateSeedSequence(seed.seed, runs, seed.seedStep),
+ node_path: seed.nodeId,
+ })),
+ ],
+ runs: 1,
+ };
+ }
+
+ const combinations = expandCombinations(groups);
+ const total = combinations.length * runs;
+ const zipped: QueueBatchDatum[] = seeds.map((seed) => ({
+ field_name: seed.fieldName,
+ items: generateSeedSequence(seed.seed, total, seed.seedStep),
+ node_path: seed.nodeId,
+ }));
+
+ groups.forEach((group, groupIndex) => {
+ for (const datum of group) {
+ const items: QueueBatchItem[] = [];
+
+ for (let run = 0; run < runs; run += 1) {
+ for (const combination of combinations) {
+ items.push(datum.items[combination[groupIndex] as number] as QueueBatchItem);
+ }
+ }
+
+ zipped.push({ field_name: datum.fieldName, items, node_path: datum.nodeId });
+ }
+ });
+
+ return { data: [zipped], runs: 1 };
};
export interface GeneratePromptBatchPlanInput {
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 578239db02..d253a32f34 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -1,6 +1,11 @@
-import type { QueuePromptSeedBehaviour, QueueSeedStep, QueueWorkflowSeed } from '@features/queue/core/promptBatch';
+import type {
+ QueuePromptSeedBehaviour,
+ QueueSeedStep,
+ QueueWorkflowBatchDatum,
+ QueueWorkflowSeed,
+} from '@features/queue/core/promptBatch';
-export type { QueueSeedStep, QueueWorkflowSeed };
+export type { QueueSeedStep, QueueWorkflowBatchDatum, QueueWorkflowSeed };
export interface QueueBackendInvocation {
id: string;
@@ -47,6 +52,8 @@ export interface QueueEnqueueWorkflowRequest extends QueueEnqueueRequestBase {
workflow?: Record<string, unknown>;
/** The seed inputs that vary between the `batchCount` runs; the graph carries each one's first seed. */
seeds?: QueueWorkflowSeed[];
+ /** Batch-node value lists: outer groups multiply, inner datums zip. */
+ batchData?: QueueWorkflowBatchDatum[][];
}
export interface QueueEnqueueGenerateRequest extends QueueEnqueueRequestBase {
@@ -84,6 +91,8 @@ export type QueueCompiledSubmission =
workflow?: Record<string, unknown>;
/** The seed inputs that vary between runs, expanded into one zipped batch group at send time. */
seeds?: QueueWorkflowSeed[];
+ /** Batch-node value lists resolved at compile time: outer groups multiply, inner datums zip. */
+ batchData?: QueueWorkflowBatchDatum[][];
/** Capture the bound library ID at compile time so completion attribution survives later editor changes. */
libraryWorkflowId?: string;
}
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
index b37bf3d093..6026bb6a39 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
@@ -338,6 +338,24 @@ describe('enqueueWorkflow', () => {
expect(getSubmittedBody().batch.batch_id).toBeUndefined();
});
+ it('sends batch-node groups in the backend shape and lets it multiply them across runs', async () => {
+ const { enqueueWorkflow } = await import('./submissionApi');
+
+ await enqueueWorkflow({
+ ...createWorkflowRequest(),
+ batchData: [
+ [{ fieldName: 'cfg', items: [1, 2], nodeId: 'denoise' }],
+ [{ fieldName: 'image', items: [{ image_name: 'a.png' }], nodeId: 'sink' }],
+ ],
+ });
+
+ expect(getSubmittedBody().batch.runs).toBe(2);
+ expect(getSubmittedBody().batch.data).toEqual([
+ [{ field_name: 'cfg', items: [1, 2], node_path: 'denoise' }],
+ [{ field_name: 'image', items: [{ image_name: 'a.png' }], node_path: 'sink' }],
+ ]);
+ });
+
it('includes the serialized parent workflow in the batch', async () => {
const { enqueueWorkflow } = await import('./submissionApi');
const workflow = {
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
index c1414e5735..095b8408f0 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
@@ -10,7 +10,7 @@ import type {
import {
buildGeneratePromptBatchPlan,
buildLegacyGeneratePromptBatchPlan,
- buildWorkflowSeedBatchPlan,
+ buildQueueWorkflowBatchPlan,
sanitizeBatchCount,
} from '@features/queue/core/promptBatch';
import { mapWithConcurrency } from '@platform/core/concurrency';
@@ -111,7 +111,11 @@ export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Pro
};
export const enqueueWorkflow = async (request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult> => {
- const plan = buildWorkflowSeedBatchPlan({ batchCount: request.batchCount, seeds: request.seeds });
+ const plan = buildQueueWorkflowBatchPlan({
+ batchCount: request.batchCount,
+ batchData: request.batchData,
+ seeds: request.seeds,
+ });
const result = await apiFetchJson<unknown>('/api/v1/queue/default/enqueue_batch', {
body: JSON.stringify({
batch: {
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index c0a8015944..b11ec40a85 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -197,6 +197,61 @@ describe('queue runtime', () => {
expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([seed, seed]))).toEqual(invalid);
});
+ it('replays persisted batch groups and rejects ones the graph or the backend would refuse', () => {
+ const asWorkflow = (batchData: unknown, seeds?: unknown) => {
+ const queueItem = createPendingQueueItem();
+ queueItem.snapshot.backendSubmission = {
+ batchCount: 2,
+ graph: {
+ edges: [],
+ id: 'backend-graph',
+ nodes: { denoise: { id: 'denoise', type: 'denoise' }, noise: { id: 'noise', seed: 7, type: 'noise' } },
+ },
+ kind: 'workflow',
+ ...(seeds === undefined ? {} : { seeds: seeds as never }),
+ batchData: batchData as never,
+ };
+ queueItem.snapshot.sourceId = 'workflow';
+ return queueItem;
+ };
+ const cfg = { fieldName: 'cfg', items: [1, 2], nodeId: 'denoise' };
+ const invalid = { error: 'Queue item has malformed workflow batch metadata.', kind: 'invalid' };
+
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([[cfg]]))).toMatchObject({
+ kind: 'workflow',
+ request: { batchData: [[cfg]] },
+ });
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([]))).toEqual(invalid);
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([[]]))).toEqual(invalid);
+ expect(
+ createQueueItemBackendSubmission(
+ { id: 'project-1' },
+ asWorkflow([[cfg, { ...cfg, fieldName: 'steps', items: [1] }]])
+ )
+ ).toEqual(invalid);
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([[{ ...cfg, nodeId: 'gone' }]]))).toEqual(
+ invalid
+ );
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([[cfg], [cfg]]))).toEqual(invalid);
+ // The product must fit the queue together with the runs, as the planner enforced when it was queued.
+ expect(
+ createQueueItemBackendSubmission(
+ { id: 'project-1' },
+ asWorkflow([[{ ...cfg, items: Array.from({ length: 5_001 }, (_, i) => i) }]])
+ )
+ ).toEqual(invalid);
+ // A field a seed already walks cannot also be batched.
+ expect(
+ createQueueItemBackendSubmission(
+ { id: 'project-1' },
+ asWorkflow(
+ [[{ fieldName: 'seed', items: [1, 2], nodeId: 'noise' }]],
+ [{ fieldName: 'seed', nodeId: 'noise', seed: 7, seedStep: 1 }]
+ )
+ )
+ ).toEqual(invalid);
+ });
+
it('rejects a generate item that records neither a seed step nor the legacy toggle', () => {
const queueItem = createPendingQueueItem();
delete (queueItem.snapshot.backendSubmission as Record<string, unknown>).seedStep;
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 722a9da457..1c73044a4e 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -14,7 +14,9 @@ import {
isQueuePromptSeedBehaviour,
isQueueSeedStep,
isQueueWorkflowSeed,
+ isQueueWorkflowBatchDatum,
MAX_QUEUE_BATCH_ITEMS,
+ type QueueWorkflowSeed,
} from '@features/queue/core/promptBatch';
import { shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';
import { progressImageStore } from '@features/queue/data/progressImageStore';
@@ -148,6 +150,46 @@ const areQueueWorkflowSeedsValid = (seeds: unknown, graph: { nodes?: Record<stri
});
};
+/**
+ * Every group zips datums of one length onto fields of nodes the graph still has, no field is fed twice (by
+ * another group or by a seed), and the product stays within what the queue accepts.
+ */
+const areQueueWorkflowBatchGroupsValid = (
+ batchData: unknown,
+ graph: { nodes?: Record<string, unknown> },
+ seeds: readonly QueueWorkflowSeed[] | undefined,
+ batchCount: number
+): boolean => {
+ if (!Array.isArray(batchData) || batchData.length === 0) {
+ return false;
+ }
+
+ const targets = new Set((seeds ?? []).map((seed) => `${seed.nodeId}:${seed.fieldName}`));
+ let sessions = 1;
+
+ for (const group of batchData) {
+ if (!Array.isArray(group) || group.length === 0 || !group.every(isQueueWorkflowBatchDatum)) {
+ return false;
+ }
+
+ const length = group[0].items.length;
+
+ for (const datum of group) {
+ const target = `${datum.nodeId}:${datum.fieldName}`;
+
+ if (datum.items.length !== length || !graph.nodes || !(datum.nodeId in graph.nodes) || targets.has(target)) {
+ return false;
+ }
+
+ targets.add(target);
+ }
+
+ sessions *= length;
+ }
+
+ return sessions * batchCount <= MAX_QUEUE_BATCH_ITEMS;
+};
+
export const createQueueItemBackendSubmission = (
project: Pick<QueueHistoryProject, 'id'>,
queueItem: QueueItem
@@ -223,6 +265,13 @@ export const createQueueItemBackendSubmission = (
return { error: 'Queue item has malformed workflow seed metadata.', kind: 'invalid' };
}
+ if (
+ submission.batchData !== undefined &&
+ !areQueueWorkflowBatchGroupsValid(submission.batchData, submission.graph, submission.seeds, submission.batchCount)
+ ) {
+ return { error: 'Queue item has malformed workflow batch metadata.', kind: 'invalid' };
+ }
+
// `libraryWorkflowId` is provenance for the completed-run sink, not something
// the backend enqueue accepts; it stays on the snapshot and off the request.
const { kind: _, libraryWorkflowId: _libraryWorkflowId, ...compiled } = submission;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/batch.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/batch.test.ts
new file mode 100644
index 0000000000..e7c6f41858
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/core/batch.test.ts
@@ -0,0 +1,507 @@
+import { describe, expect, it } from 'vitest';
+
+import type {
+ FieldInputTemplate,
+ InvocationTemplate,
+ ProjectGraphState,
+ WorkflowEdge,
+ WorkflowInvocationNode,
+} from './types';
+
+import {
+ createSeededRandom,
+ getDefaultWorkflowGeneratorValue,
+ getWorkflowBatchGroupId,
+ getWorkflowGeneratorKey,
+ getWorkflowGeneratorVariantDefaults,
+ isRandomWorkflowGeneratorValue,
+ isWorkflowBatchNodeType,
+ isWorkflowGeneratorNodeType,
+ parseWorkflowGeneratorValue,
+ planWorkflowBatch,
+ resolveWorkflowGeneratorValue,
+ type WorkflowGeneratorValue,
+} from './batch';
+import { createProjectGraph } from './document';
+
+const items = (value: WorkflowGeneratorValue, random?: () => number) => {
+ const resolution = resolveWorkflowGeneratorValue(value, random);
+
+ if (resolution.kind !== 'items') {
+ throw new Error('Expected synchronous items');
+ }
+
+ return resolution.items;
+};
+
+describe('generator values', () => {
+ it('classifies the eight client-resolved node types', () => {
+ expect(isWorkflowBatchNodeType('image_batch')).toBe(true);
+ expect(isWorkflowGeneratorNodeType('float_generator')).toBe(true);
+ expect(isWorkflowBatchNodeType('float_generator')).toBe(false);
+ expect(isWorkflowGeneratorNodeType('noise')).toBe(false);
+ });
+
+ it('starts each field on its legacy default variant', () => {
+ expect(getDefaultWorkflowGeneratorValue('FloatGeneratorField')).toEqual({
+ count: 10,
+ start: 0,
+ step: 0.1,
+ type: 'float_generator_arithmetic_sequence',
+ });
+ expect(getDefaultWorkflowGeneratorValue('StringGeneratorField')?.type).toBe('string_generator_parse_string');
+ expect(getDefaultWorkflowGeneratorValue('ImageGeneratorField')).toEqual({
+ category: 'images',
+ type: 'image_generator_images_from_board',
+ });
+ expect(getDefaultWorkflowGeneratorValue('StringField')).toBeUndefined();
+ // Defaults are copies: an edit to one node's value cannot leak into the next node's default.
+ expect(getWorkflowGeneratorVariantDefaults('integer_generator_parse_string')).not.toBe(
+ getWorkflowGeneratorVariantDefaults('integer_generator_parse_string')
+ );
+ });
+
+ it('reads stored values tolerantly, as the legacy schemas did', () => {
+ // A legacy float value with its resolved override and a null seed.
+ expect(
+ parseWorkflowGeneratorValue('FloatGeneratorField', {
+ count: 3,
+ max: 1,
+ min: 0,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ values: [0.1, 0.2, 0.3],
+ })
+ ).toEqual({
+ count: 3,
+ max: 1,
+ min: 0,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ values: [0.1, 0.2, 0.3],
+ });
+ // Missing properties take their defaults; a missing variant is the field's first one.
+ expect(parseWorkflowGeneratorValue('IntegerGeneratorField', {})).toEqual({
+ count: 10,
+ start: 0,
+ step: 1,
+ type: 'integer_generator_arithmetic_sequence',
+ });
+ expect(parseWorkflowGeneratorValue('ImageGeneratorField', { board_id: ' ', category: 'bogus' })).toEqual({
+ category: 'images',
+ type: 'image_generator_images_from_board',
+ });
+ // A wrong-typed required property, a variant from another field, or a non-object is unusable.
+ expect(
+ parseWorkflowGeneratorValue('IntegerGeneratorField', {
+ start: '1',
+ type: 'integer_generator_arithmetic_sequence',
+ })
+ ).toBeNull();
+ expect(
+ parseWorkflowGeneratorValue('IntegerGeneratorField', { count: 0, type: 'integer_generator_arithmetic_sequence' })
+ ).toBeNull();
+ expect(parseWorkflowGeneratorValue('IntegerGeneratorField', { type: 'float_generator_parse_string' })).toBeNull();
+ expect(parseWorkflowGeneratorValue('FloatGeneratorField', 'nope')).toBeNull();
+ // Optional properties recover from bad input instead.
+ expect(
+ parseWorkflowGeneratorValue('FloatGeneratorField', {
+ seed: 'x',
+ type: 'float_generator_random_distribution_uniform',
+ values: 'x',
+ })
+ ).toMatchObject({ seed: null });
+ });
+
+ it('fingerprints a value independently of key order and spots unseeded random variants', () => {
+ expect(
+ getWorkflowGeneratorKey({ count: 2, start: 0, step: 1, type: 'integer_generator_arithmetic_sequence' })
+ ).toBe(getWorkflowGeneratorKey({ type: 'integer_generator_arithmetic_sequence', step: 1, start: 0, count: 2 }));
+ expect(
+ isRandomWorkflowGeneratorValue({
+ count: 1,
+ max: 1,
+ min: 0,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ })
+ ).toBe(true);
+ expect(
+ isRandomWorkflowGeneratorValue({
+ count: 1,
+ max: 1,
+ min: 0,
+ seed: 4,
+ type: 'float_generator_random_distribution_uniform',
+ })
+ ).toBe(false);
+ });
+});
+
+describe('generator resolution', () => {
+ it('produces sequences and distributions with the legacy edge cases', () => {
+ expect(items({ count: 3, start: 1, step: 0.5, type: 'float_generator_arithmetic_sequence' })).toEqual([1, 1.5, 2]);
+ expect(items({ count: 5, start: 4, step: 0, type: 'integer_generator_arithmetic_sequence' })).toEqual([4]);
+ expect(items({ count: 3, end: 1, start: 0, type: 'float_generator_linear_distribution' })).toEqual([0, 0.5, 1]);
+ expect(items({ count: 1, end: 9, start: 2, type: 'float_generator_linear_distribution' })).toEqual([2]);
+ expect(items({ count: 4, end: 10, start: 0, type: 'integer_generator_linear_distribution' })).toEqual([
+ 0, 3, 7, 10,
+ ]);
+ // A resolved override wins over the settings it was computed from.
+ expect(items({ count: 3, start: 0, step: 1, type: 'float_generator_arithmetic_sequence', values: [9] })).toEqual([
+ 9,
+ ]);
+ });
+
+ it('draws random values inside the bounds, repeatably for a seed and from the injected source without one', () => {
+ const seeded = items({
+ count: 5,
+ max: 10,
+ min: 5,
+ seed: 42,
+ type: 'integer_generator_random_distribution_uniform',
+ });
+
+ expect(seeded).toEqual(
+ items({ count: 5, max: 10, min: 5, seed: 42, type: 'integer_generator_random_distribution_uniform' })
+ );
+ expect(seeded.every((value) => Number.isInteger(value) && (value as number) >= 5 && (value as number) <= 10)).toBe(
+ true
+ );
+ expect(
+ items({ count: 2, max: 1, min: 0, seed: null, type: 'float_generator_random_distribution_uniform' }, () => 0.25)
+ ).toEqual([0.25, 0.25]);
+
+ const random = createSeededRandom(7);
+ const draw = random();
+
+ expect(draw).toBeGreaterThanOrEqual(0);
+ expect(draw).toBeLessThan(1);
+ expect(createSeededRandom(7)()).toBe(draw);
+ });
+
+ it('splits text the legacy way: escapes honoured, numbers trimmed and filtered, strings kept verbatim', () => {
+ expect(items({ input: ' 1, 2 ,x, 3.5', splitOn: ',', type: 'float_generator_parse_string' })).toEqual([1, 2, 3.5]);
+ expect(items({ input: '1\n2\n\n3', splitOn: '\\n', type: 'integer_generator_parse_string' })).toEqual([1, 2, 3]);
+ expect(items({ input: 'a b', splitOn: '', type: 'string_generator_parse_string' })).toEqual(['a b']);
+ expect(items({ input: ' foo|bar||baz ', splitOn: '|', type: 'string_generator_parse_string' })).toEqual([
+ ' foo',
+ 'bar',
+ 'baz ',
+ ]);
+ // An unparseable escape falls back to the raw separator.
+ expect(items({ input: 'a\\qb', splitOn: '\\q', type: 'string_generator_parse_string' })).toEqual(['a', 'b']);
+ });
+
+ it('hands dynamic prompts and board listings to the async resolver, and an unset board to nobody', () => {
+ expect(
+ resolveWorkflowGeneratorValue({
+ count: 4,
+ input: '{a|b}',
+ seed: 3,
+ type: 'string_generator_dynamic_prompts_random',
+ })
+ ).toEqual({
+ kind: 'async',
+ request: { combinatorial: false, kind: 'dynamicPrompts', maxPrompts: 4, prompt: '{a|b}', seed: 3 },
+ });
+ expect(
+ resolveWorkflowGeneratorValue({
+ input: '{a|b}',
+ maxPrompts: 9,
+ type: 'string_generator_dynamic_prompts_combinatorial',
+ })
+ ).toEqual({
+ kind: 'async',
+ request: { combinatorial: true, kind: 'dynamicPrompts', maxPrompts: 9, prompt: '{a|b}', seed: null },
+ });
+ expect(
+ resolveWorkflowGeneratorValue({ board_id: 'b1', category: 'assets', type: 'image_generator_images_from_board' })
+ ).toEqual({
+ kind: 'async',
+ request: { boardId: 'b1', category: 'assets', kind: 'boardImages' },
+ });
+ expect(resolveWorkflowGeneratorValue({ category: 'images', type: 'image_generator_images_from_board' })).toEqual({
+ items: [],
+ kind: 'items',
+ });
+ });
+});
+
+describe('planWorkflowBatch', () => {
+ const field = (name: string, typeName: string, overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({
+ default: undefined,
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ fieldKind: 'input',
+ input: 'any',
+ maximum: null,
+ minimum: null,
+ multipleOf: null,
+ name,
+ options: null,
+ required: true,
+ title: name,
+ type: { batch: false, cardinality: 'SINGLE', name: typeName },
+ 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: {},
+ outputType: `${type}_output`,
+ tags: [],
+ title: type,
+ type,
+ useCache: true,
+ version: '1.0.0',
+ });
+ const templates = {
+ float_batch: template('float_batch', {
+ batch_group_id: field('batch_group_id', 'EnumField'),
+ floats: field('floats', 'FloatField'),
+ }),
+ float_generator: template('float_generator', { generator: field('generator', 'FloatGeneratorField') }),
+ image_batch: template('image_batch', {
+ batch_group_id: field('batch_group_id', 'EnumField'),
+ images: field('images', 'ImageField'),
+ }),
+ prompt: template('prompt', { text: field('text', 'StringField') }),
+ sink: template('sink', {
+ cfg: field('cfg', 'FloatField'),
+ image: field('image', 'ImageField'),
+ steps: field('steps', 'IntegerField'),
+ }),
+ string_batch: template('string_batch', {
+ batch_group_id: field('batch_group_id', 'EnumField'),
+ strings: field('strings', 'StringField'),
+ }),
+ };
+ const node = (id: string, type: string, inputs: Record<string, unknown>, label = ''): WorkflowInvocationNode => ({
+ data: {
+ inputs: Object.fromEntries(Object.entries(inputs).map(([name, value]) => [name, { label: '', name, value }])),
+ isIntermediate: true,
+ isOpen: true,
+ label,
+ nodePack: 'invokeai',
+ notes: '',
+ type,
+ useCache: true,
+ version: '1.0.0',
+ },
+ id,
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+ });
+ const edge = (source: string, sourceHandle: string, target: string, targetHandle: string): WorkflowEdge => ({
+ id: `${source}.${sourceHandle}->${target}.${targetHandle}`,
+ source,
+ sourceHandle,
+ target,
+ targetHandle,
+ type: 'default',
+ });
+ const doc = (nodes: WorkflowInvocationNode[], edges: WorkflowEdge[]): ProjectGraphState => ({
+ ...createProjectGraph('batch-test'),
+ edges,
+ nodes,
+ });
+
+ it('reports no batch for a plain graph', () => {
+ expect(planWorkflowBatch(doc([node('s', 'sink', {})], []), templates)).toEqual({
+ batchSize: 1,
+ groups: [],
+ hasBatchNodes: false,
+ pendingGenerators: [],
+ reasons: [],
+ });
+ });
+
+ it('multiplies ungrouped nodes and zips a named group, one datum per fed input', () => {
+ const graph = doc(
+ [
+ node('a', 'float_batch', { batch_group_id: 'None', floats: [1, 2] }),
+ node('b', 'string_batch', { batch_group_id: 'Group 1', strings: ['x', 'y', 'z'] }),
+ node('c', 'float_batch', { batch_group_id: 'Group 1', floats: [7, 8, 9] }),
+ node('s', 'sink', {}),
+ node('p', 'prompt', {}),
+ ],
+ [
+ edge('a', 'value', 's', 'cfg'),
+ edge('a', 'value', 's', 'steps'),
+ edge('b', 'value', 'p', 'text'),
+ edge('c', 'value', 's', 'cfg'),
+ ]
+ );
+ const plan = planWorkflowBatch(graph, templates);
+
+ // 'cfg' is fed twice: once from the ungrouped node and once from the group.
+ expect(plan.reasons).toEqual(['"cfg" on "sink" receives values from more than one batch node.']);
+ expect(plan.batchSize).toBe(6);
+ expect(plan.groups).toEqual([
+ [
+ { fieldName: 'cfg', items: [1, 2], nodeId: 's' },
+ { fieldName: 'steps', items: [1, 2], nodeId: 's' },
+ ],
+ [{ fieldName: 'text', items: ['x', 'y', 'z'], nodeId: 'p' }],
+ ]);
+ expect(getWorkflowBatchGroupId(node('g', 'float_batch', { batch_group_id: 'Group 9' }))).toBe('None');
+ });
+
+ it('feeds a batch from a generator, through connectors, and coerces numbers into string inputs', () => {
+ const graph = doc(
+ [
+ node('g', 'float_generator', {
+ generator: { count: 3, start: 1, step: 1, type: 'float_generator_arithmetic_sequence' },
+ }),
+ node('b', 'string_batch', { batch_group_id: 'None' }),
+ node('p', 'prompt', {}),
+ ],
+ [edge('g', 'floats', 'b', 'strings'), edge('b', 'value', 'p', 'text')]
+ );
+ // The batch's own (missing) list is ignored once a generator feeds it; a string batch stringifies its items.
+ const plan = planWorkflowBatch(graph, templates);
+
+ expect(plan.reasons).toEqual([]);
+ expect(plan.groups).toEqual([[{ fieldName: 'text', items: ['1', '2', '3'], nodeId: 'p' }]]);
+ expect(plan.batchSize).toBe(3);
+ });
+
+ it('leaves an async generator pending until its resolution matches the value it was computed from', () => {
+ const generator = {
+ board_id: 'board-1',
+ category: 'images' as const,
+ type: 'image_generator_images_from_board' as const,
+ };
+ const graph = doc(
+ [
+ node('g', 'image_generator', { generator }),
+ node('b', 'image_batch', { batch_group_id: 'None' }),
+ node('s', 'sink', {}),
+ ],
+ [edge('g', 'images', 'b', 'images'), edge('b', 'image', 's', 'image')]
+ );
+ const pending = planWorkflowBatch(graph, templates);
+ const key = getWorkflowGeneratorKey(generator);
+
+ expect(pending.batchSize).toBeNull();
+ expect(pending.reasons).toEqual([]);
+ expect(pending.pendingGenerators).toEqual([
+ {
+ key,
+ nodeId: 'g',
+ nodeLabel: 'image_generator',
+ request: { boardId: 'board-1', category: 'images', kind: 'boardImages' },
+ },
+ ]);
+
+ const stale = planWorkflowBatch(graph, templates, {
+ generators: { g: { items: [{ image_name: 'old.png' }], key: 'other' } },
+ });
+
+ expect(stale.pendingGenerators).toHaveLength(1);
+
+ const resolved = planWorkflowBatch(graph, templates, {
+ generators: { g: { items: [{ image_name: 'a.png' }, { image_name: 'b.png' }], key } },
+ });
+
+ expect(resolved.pendingGenerators).toEqual([]);
+ expect(resolved.batchSize).toBe(2);
+ expect(resolved.groups).toEqual([
+ [{ fieldName: 'image', items: [{ image_name: 'a.png' }, { image_name: 'b.png' }], nodeId: 's' }],
+ ]);
+
+ const empty = planWorkflowBatch(graph, templates, { generators: { g: { items: [], key } } });
+
+ expect(empty.reasons).toEqual(['Batch node "image_batch" has an empty collection.']);
+
+ // Without a board there is nothing to list; the fix is on the generator, so the reason names it.
+ const boardless = doc(
+ [
+ node('g', 'image_generator', { generator: { category: 'images', type: 'image_generator_images_from_board' } }),
+ node('b', 'image_batch', { batch_group_id: 'None' }),
+ node('s', 'sink', {}),
+ ],
+ [edge('g', 'images', 'b', 'images'), edge('b', 'image', 's', 'image')]
+ );
+
+ expect(planWorkflowBatch(boardless, templates).reasons).toEqual([
+ 'Image generator "image_generator" has no board selected.',
+ ]);
+ });
+
+ it('explains every way a batch node can be wired wrong', () => {
+ const graph = doc(
+ [
+ node('lonely', 'float_batch', { batch_group_id: 'None', floats: [1] }, 'Lonely'),
+ node('empty', 'float_batch', { batch_group_id: 'Group 2', floats: [] }, 'Empty'),
+ node('short', 'float_batch', { batch_group_id: 'Group 2', floats: [1, 2] }, 'Short'),
+ node('fed', 'float_batch', { batch_group_id: 'None', floats: [1] }, 'Fed'),
+ node('pics', 'image_batch', { batch_group_id: 'None', images: [{ image_name: 'a.png' }] }, 'Pics'),
+ node('p', 'prompt', {}),
+ node('s', 'sink', {}),
+ ],
+ [
+ edge('empty', 'value', 's', 'cfg'),
+ edge('short', 'value', 's', 'steps'),
+ edge('p', 'text', 'fed', 'floats'),
+ edge('fed', 'value', 'pics', 'images'),
+ edge('pics', 'width', 's', 'cfg'),
+ edge('pics', 'image', 's', 'image'),
+ ]
+ );
+ const plan = planWorkflowBatch(graph, templates);
+
+ expect(plan.reasons).toEqual([
+ 'Batch node "Lonely" is not connected to any node.',
+ 'Batch node "Empty" has an empty collection.',
+ 'Batch node "Fed" can only receive its collection from a generator.',
+ '"Fed" cannot supply batch values to "images" on "Pics".',
+ 'Batch node "Pics" can only receive its collection from a generator.',
+ 'Batch node "Pics" can only batch its image output; width and height are not supported.',
+ 'Batch group "Group 2" mixes collection sizes (Empty: 0, Short: 2).',
+ ]);
+ });
+
+ it('refuses an oversized generator by its count alone, without building the list', () => {
+ const graph = doc(
+ [
+ node('g', 'float_generator', {
+ generator: { count: 2_000_000_000, start: 0, step: 1, type: 'float_generator_arithmetic_sequence' },
+ }),
+ node('b', 'float_batch', { batch_group_id: 'None' }),
+ node('s', 'sink', {}),
+ ],
+ [edge('g', 'floats', 'b', 'floats'), edge('b', 'value', 's', 'cfg')]
+ );
+
+ expect(planWorkflowBatch(graph, templates).reasons).toEqual([
+ 'Batch node "float_batch" has more than 10,000 items.',
+ ]);
+ });
+
+ it('refuses more items than the queue accepts', () => {
+ const graph = doc(
+ [
+ node('big', 'float_batch', { batch_group_id: 'None', floats: Array.from({ length: 10_001 }, (_, i) => i) }),
+ node('s', 'sink', {}),
+ ],
+ [edge('big', 'value', 's', 'cfg')]
+ );
+
+ expect(planWorkflowBatch(graph, templates).reasons).toEqual([
+ 'Batch node "float_batch" has more than 10,000 items.',
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/batch.ts b/invokeai/frontend/webv2/src/features/workflow/core/batch.ts
new file mode 100644
index 0000000000..b338ed9a90
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/core/batch.ts
@@ -0,0 +1,793 @@
+/**
+ * Batch and generator nodes never run on the backend: the editor resolves them into queue batch groups at submit
+ * time. Value shapes and resolution rules mirror the legacy editor so saved workflows keep their meaning, with one
+ * exception: seeded random draws use a different generator, so a legacy seed yields different values here.
+ */
+
+import type { InvocationTemplates, ProjectGraphState, WorkflowInvocationNode } from './types';
+
+import { getCanonicalWorkflowEdges } from './forLoops';
+import { isInvocationNode } from './types';
+
+// #region Node classification
+
+export const WORKFLOW_BATCH_GROUP_IDS = ['None', 'Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5'] as const;
+export type WorkflowBatchGroupId = (typeof WORKFLOW_BATCH_GROUP_IDS)[number];
+
+/** The backend truncates a batch to its remaining queue capacity, whose default ceiling this mirrors. */
+export const WORKFLOW_BATCH_MAX_ITEMS = 10_000;
+
+const BATCH_COLLECTION_FIELDS = {
+ float_batch: 'floats',
+ image_batch: 'images',
+ integer_batch: 'integers',
+ string_batch: 'strings',
+} as const;
+
+const GENERATOR_OUTPUT_FIELDS = {
+ float_generator: 'floats',
+ image_generator: 'images',
+ integer_generator: 'integers',
+ string_generator: 'strings',
+} as const;
+
+const GENERATOR_FIELD_TYPE_NAMES = {
+ float_generator: 'FloatGeneratorField',
+ image_generator: 'ImageGeneratorField',
+ integer_generator: 'IntegerGeneratorField',
+ string_generator: 'StringGeneratorField',
+} as const;
+
+export type WorkflowBatchNodeType = keyof typeof BATCH_COLLECTION_FIELDS;
+export type WorkflowGeneratorNodeType = keyof typeof GENERATOR_OUTPUT_FIELDS;
+
+export const isWorkflowBatchNodeType = (type: string): type is WorkflowBatchNodeType =>
+ Object.hasOwn(BATCH_COLLECTION_FIELDS, type);
+
+export const isWorkflowGeneratorNodeType = (type: string): type is WorkflowGeneratorNodeType =>
+ Object.hasOwn(GENERATOR_OUTPUT_FIELDS, type);
+
+/** The list input a batch node iterates, or the list output a generator produces. */
+export const getWorkflowBatchCollectionField = (type: string): string | null =>
+ isWorkflowBatchNodeType(type) ? BATCH_COLLECTION_FIELDS[type] : null;
+
+export const getWorkflowGeneratorOutputField = (type: string): string | null =>
+ isWorkflowGeneratorNodeType(type) ? GENERATOR_OUTPUT_FIELDS[type] : null;
+
+/** The one output a batch node substitutes per session; Image Batch also declares width/height, which cannot batch. */
+export const getWorkflowBatchOutputField = (type: WorkflowBatchNodeType): 'image' | 'value' =>
+ type === 'image_batch' ? 'image' : 'value';
+
+export const getWorkflowBatchGroupId = (node: WorkflowInvocationNode): WorkflowBatchGroupId => {
+ const value = node.data.inputs.batch_group_id?.value;
+
+ return WORKFLOW_BATCH_GROUP_IDS.includes(value as WorkflowBatchGroupId) ? (value as WorkflowBatchGroupId) : 'None';
+};
+
+// #endregion
+
+// #region Generator values
+
+export interface FloatGeneratorArithmeticSequence {
+ type: 'float_generator_arithmetic_sequence';
+ start: number;
+ step: number;
+ count: number;
+ values?: number[];
+}
+
+export interface FloatGeneratorLinearDistribution {
+ type: 'float_generator_linear_distribution';
+ start: number;
+ end: number;
+ count: number;
+ values?: number[];
+}
+
+export interface FloatGeneratorUniformRandom {
+ type: 'float_generator_random_distribution_uniform';
+ min: number;
+ max: number;
+ count: number;
+ seed: number | null;
+ values?: number[];
+}
+
+export interface FloatGeneratorParseString {
+ type: 'float_generator_parse_string';
+ input: string;
+ splitOn: string;
+ values?: number[];
+}
+
+export type FloatGeneratorValue =
+ | FloatGeneratorArithmeticSequence
+ | FloatGeneratorLinearDistribution
+ | FloatGeneratorUniformRandom
+ | FloatGeneratorParseString;
+
+export interface IntegerGeneratorArithmeticSequence {
+ type: 'integer_generator_arithmetic_sequence';
+ start: number;
+ step: number;
+ count: number;
+}
+
+export interface IntegerGeneratorLinearDistribution {
+ type: 'integer_generator_linear_distribution';
+ start: number;
+ end: number;
+ count: number;
+}
+
+export interface IntegerGeneratorUniformRandom {
+ type: 'integer_generator_random_distribution_uniform';
+ min: number;
+ max: number;
+ count: number;
+ seed: number | null;
+}
+
+export interface IntegerGeneratorParseString {
+ type: 'integer_generator_parse_string';
+ input: string;
+ splitOn: string;
+}
+
+export type IntegerGeneratorValue =
+ | IntegerGeneratorArithmeticSequence
+ | IntegerGeneratorLinearDistribution
+ | IntegerGeneratorUniformRandom
+ | IntegerGeneratorParseString;
+
+export interface StringGeneratorParseString {
+ type: 'string_generator_parse_string';
+ input: string;
+ splitOn: string;
+}
+
+export interface StringGeneratorDynamicPromptsRandom {
+ type: 'string_generator_dynamic_prompts_random';
+ input: string;
+ count: number;
+ seed: number | null;
+}
+
+export interface StringGeneratorDynamicPromptsCombinatorial {
+ type: 'string_generator_dynamic_prompts_combinatorial';
+ input: string;
+ maxPrompts: number;
+}
+
+export type StringGeneratorValue =
+ | StringGeneratorParseString
+ | StringGeneratorDynamicPromptsRandom
+ | StringGeneratorDynamicPromptsCombinatorial;
+
+export interface ImageGeneratorImagesFromBoard {
+ type: 'image_generator_images_from_board';
+ board_id?: string;
+ category: 'images' | 'assets';
+}
+
+export type ImageGeneratorValue = ImageGeneratorImagesFromBoard;
+
+export type WorkflowGeneratorValue =
+ | FloatGeneratorValue
+ | IntegerGeneratorValue
+ | StringGeneratorValue
+ | ImageGeneratorValue;
+export type WorkflowGeneratorVariant = WorkflowGeneratorValue['type'];
+
+/** Variants per generator field type, first entry being the default a fresh node starts with (as in legacy). */
+export const WORKFLOW_GENERATOR_VARIANTS = {
+ FloatGeneratorField: [
+ 'float_generator_arithmetic_sequence',
+ 'float_generator_linear_distribution',
+ 'float_generator_random_distribution_uniform',
+ 'float_generator_parse_string',
+ ],
+ ImageGeneratorField: ['image_generator_images_from_board'],
+ IntegerGeneratorField: [
+ 'integer_generator_arithmetic_sequence',
+ 'integer_generator_linear_distribution',
+ 'integer_generator_random_distribution_uniform',
+ 'integer_generator_parse_string',
+ ],
+ StringGeneratorField: [
+ 'string_generator_parse_string',
+ 'string_generator_dynamic_prompts_random',
+ 'string_generator_dynamic_prompts_combinatorial',
+ ],
+} as const satisfies Record<string, readonly WorkflowGeneratorVariant[]>;
+
+export type WorkflowGeneratorFieldTypeName = keyof typeof WORKFLOW_GENERATOR_VARIANTS;
+
+export const isWorkflowGeneratorFieldTypeName = (name: string): name is WorkflowGeneratorFieldTypeName =>
+ Object.hasOwn(WORKFLOW_GENERATOR_VARIANTS, name);
+
+const VARIANT_DEFAULTS: { [V in WorkflowGeneratorVariant]: Extract<WorkflowGeneratorValue, { type: V }> } = {
+ float_generator_arithmetic_sequence: { count: 10, start: 0, step: 0.1, type: 'float_generator_arithmetic_sequence' },
+ float_generator_linear_distribution: { count: 10, end: 1, start: 0, type: 'float_generator_linear_distribution' },
+ float_generator_parse_string: {
+ input: '0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1',
+ splitOn: ',',
+ type: 'float_generator_parse_string',
+ },
+ float_generator_random_distribution_uniform: {
+ count: 10,
+ max: 1,
+ min: 0,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ },
+ image_generator_images_from_board: { category: 'images', type: 'image_generator_images_from_board' },
+ integer_generator_arithmetic_sequence: {
+ count: 10,
+ start: 0,
+ step: 1,
+ type: 'integer_generator_arithmetic_sequence',
+ },
+ integer_generator_linear_distribution: {
+ count: 10,
+ end: 10,
+ start: 0,
+ type: 'integer_generator_linear_distribution',
+ },
+ integer_generator_parse_string: {
+ input: '1,2,3,4,5,6,7,8,9,10',
+ splitOn: ',',
+ type: 'integer_generator_parse_string',
+ },
+ integer_generator_random_distribution_uniform: {
+ count: 10,
+ max: 10,
+ min: 0,
+ seed: null,
+ type: 'integer_generator_random_distribution_uniform',
+ },
+ string_generator_dynamic_prompts_combinatorial: {
+ input: 'a super {cute|ferocious} {dog|cat}',
+ maxPrompts: 10,
+ type: 'string_generator_dynamic_prompts_combinatorial',
+ },
+ string_generator_dynamic_prompts_random: {
+ count: 10,
+ input: 'a super {cute|ferocious} {dog|cat}',
+ seed: null,
+ type: 'string_generator_dynamic_prompts_random',
+ },
+ string_generator_parse_string: { input: 'foo,bar,baz,qux', splitOn: ',', type: 'string_generator_parse_string' },
+};
+
+/** How each stored property is read: what it must be, and what an absent one falls back to. */
+type PropertySpec = 'boardId' | 'category' | 'count' | 'integer' | 'number' | 'seed' | 'string' | 'values';
+
+const VARIANT_PROPERTIES: Record<WorkflowGeneratorVariant, Record<string, PropertySpec>> = {
+ float_generator_arithmetic_sequence: { count: 'count', start: 'number', step: 'number', values: 'values' },
+ float_generator_linear_distribution: { count: 'count', end: 'number', start: 'number', values: 'values' },
+ float_generator_parse_string: { input: 'string', splitOn: 'string', values: 'values' },
+ float_generator_random_distribution_uniform: {
+ count: 'count',
+ max: 'number',
+ min: 'number',
+ seed: 'seed',
+ values: 'values',
+ },
+ image_generator_images_from_board: { board_id: 'boardId', category: 'category' },
+ integer_generator_arithmetic_sequence: { count: 'count', start: 'integer', step: 'integer' },
+ integer_generator_linear_distribution: { count: 'count', end: 'integer', start: 'integer' },
+ integer_generator_parse_string: { input: 'string', splitOn: 'string' },
+ integer_generator_random_distribution_uniform: { count: 'count', max: 'integer', min: 'integer', seed: 'seed' },
+ string_generator_dynamic_prompts_combinatorial: { input: 'string', maxPrompts: 'count' },
+ string_generator_dynamic_prompts_random: { count: 'count', input: 'string', seed: 'seed' },
+ string_generator_parse_string: { input: 'string', splitOn: 'string' },
+};
+
+export const getWorkflowGeneratorVariantDefaults = (variant: WorkflowGeneratorVariant): WorkflowGeneratorValue =>
+ structuredClone(VARIANT_DEFAULTS[variant]);
+
+export const getDefaultWorkflowGeneratorValue = (fieldTypeName: string): WorkflowGeneratorValue | undefined =>
+ isWorkflowGeneratorFieldTypeName(fieldTypeName)
+ ? getWorkflowGeneratorVariantDefaults(WORKFLOW_GENERATOR_VARIANTS[fieldTypeName][0])
+ : undefined;
+
+const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
+
+/** `undefined` means the property is omitted; `null` means the stored value is unusable. */
+const readProperty = (spec: PropertySpec, raw: unknown, fallback: unknown): unknown => {
+ if (raw === undefined) {
+ return fallback;
+ }
+
+ switch (spec) {
+ case 'number':
+ return isFiniteNumber(raw) ? raw : null;
+ case 'integer':
+ return Number.isInteger(raw) ? raw : null;
+ case 'count':
+ return Number.isInteger(raw) && (raw as number) >= 1 ? raw : null;
+ case 'string':
+ return typeof raw === 'string' ? raw : null;
+ case 'seed':
+ return raw === null ? null : Number.isInteger(raw) ? raw : undefined;
+ case 'category':
+ return raw === 'images' || raw === 'assets' ? raw : undefined;
+ case 'boardId':
+ return raw === null ? undefined : typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined;
+ case 'values':
+ return raw === null ? undefined : Array.isArray(raw) && raw.every(isFiniteNumber) ? raw : undefined;
+ }
+};
+
+/**
+ * Reads a stored generator value the way the legacy schemas did: missing properties take their defaults, a missing
+ * variant is the field's first one, and a wrong-typed property makes the whole value unusable (null).
+ */
+export const parseWorkflowGeneratorValue = (fieldTypeName: string, raw: unknown): WorkflowGeneratorValue | null => {
+ if (!isWorkflowGeneratorFieldTypeName(fieldTypeName) || typeof raw !== 'object' || raw === null) {
+ return null;
+ }
+
+ const variants = WORKFLOW_GENERATOR_VARIANTS[fieldTypeName] as readonly WorkflowGeneratorVariant[];
+ const source = raw as Record<string, unknown>;
+ const variant = source.type === undefined ? variants[0] : (source.type as WorkflowGeneratorVariant);
+
+ if (variant === undefined || !variants.includes(variant)) {
+ return null;
+ }
+
+ const defaults = VARIANT_DEFAULTS[variant] as unknown as Record<string, unknown>;
+ const value: Record<string, unknown> = { type: variant };
+
+ for (const [key, spec] of Object.entries(VARIANT_PROPERTIES[variant])) {
+ const read = readProperty(spec, source[key], defaults[key]);
+
+ // Optional properties (seed, board, override values, category) recover from bad input; required ones do not.
+ if (read === null && spec !== 'seed') {
+ return null;
+ }
+
+ if (read === undefined) {
+ if (spec === 'seed') {
+ value[key] = null;
+ } else if (spec === 'category') {
+ value[key] = 'images';
+ }
+
+ continue;
+ }
+
+ value[key] = read;
+ }
+
+ return value as unknown as WorkflowGeneratorValue;
+};
+
+const sortKeys = (value: unknown): unknown =>
+ Array.isArray(value)
+ ? value.map(sortKeys)
+ : typeof value === 'object' && value !== null
+ ? Object.fromEntries(
+ Object.keys(value as Record<string, unknown>)
+ .sort()
+ .map((key) => [key, sortKeys((value as Record<string, unknown>)[key])])
+ )
+ : value;
+
+/** A stable fingerprint of a generator value, so an async result can be matched to the value it came from. */
+export const getWorkflowGeneratorKey = (value: WorkflowGeneratorValue): string => JSON.stringify(sortKeys(value));
+
+export const isWorkflowGeneratorVariant = (type: string): type is WorkflowGeneratorVariant =>
+ Object.hasOwn(VARIANT_PROPERTIES, type);
+
+/**
+ * How many items a generator asks for, before any are built: a stored count can be arbitrarily large, and the
+ * queue accepts at most `WORKFLOW_BATCH_MAX_ITEMS`, so callers refuse oversized requests without materializing them.
+ */
+export const getWorkflowGeneratorRequestedCount = (value: WorkflowGeneratorValue): number | null =>
+ 'values' in value && value.values
+ ? value.values.length
+ : 'step' in value && value.step === 0
+ ? 1
+ : 'count' in value
+ ? value.count
+ : 'maxPrompts' in value
+ ? value.maxPrompts
+ : null;
+
+/** Random variants without a seed draw fresh values on every resolve, so no preview can show them. */
+export const isRandomWorkflowGeneratorValue = (value: WorkflowGeneratorValue): boolean =>
+ (value.type === 'float_generator_random_distribution_uniform' ||
+ value.type === 'integer_generator_random_distribution_uniform' ||
+ value.type === 'string_generator_dynamic_prompts_random') &&
+ value.seed === null;
+
+// #endregion
+
+// #region Resolution
+
+export type WorkflowBatchItem = number | string | { image_name: string };
+
+export type WorkflowAsyncGeneratorRequest =
+ | { kind: 'dynamicPrompts'; prompt: string; maxPrompts: number; combinatorial: boolean; seed: number | null }
+ | { kind: 'boardImages'; boardId: string; category: 'images' | 'assets' };
+
+export type WorkflowGeneratorResolution =
+ | { kind: 'items'; items: WorkflowBatchItem[] }
+ | { kind: 'async'; request: WorkflowAsyncGeneratorRequest };
+
+/** mulberry32: small, seedable, and good enough for spreading sample values; not bit-compatible with legacy. */
+export const createSeededRandom = (seed: number): (() => number) => {
+ let state = seed >>> 0;
+
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+
+ let t = state;
+
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+};
+
+/** An empty separator keeps the whole input; escapes such as `\n` are honoured, a lone backslash is literal. */
+const splitInput = (input: string, splitOn: string): string[] => {
+ if (splitOn === '') {
+ return [input];
+ }
+
+ let separator = splitOn;
+
+ try {
+ const parsed: unknown = JSON.parse(`"${splitOn}"`);
+
+ if (typeof parsed === 'string') {
+ separator = parsed;
+ }
+ } catch {
+ // Not a valid escape sequence: split on the text as typed.
+ }
+
+ return input.split(separator);
+};
+
+const parseNumbers = (input: string, splitOn: string, parse: (text: string) => number): number[] =>
+ splitInput(input, splitOn)
+ .map((text) => text.trim())
+ .filter((text) => text !== '')
+ .map(parse)
+ .filter((number) => !Number.isNaN(number));
+
+const sequence = (count: number, at: (index: number) => number): number[] =>
+ Array.from({ length: count }, (_, index) => at(index));
+
+/** Turns a stored generator into its items, or into the request an async source needs. */
+export const resolveWorkflowGeneratorValue = (
+ value: WorkflowGeneratorValue,
+ random: () => number = Math.random
+): WorkflowGeneratorResolution => {
+ const items = (list: WorkflowBatchItem[]): WorkflowGeneratorResolution => ({ items: list, kind: 'items' });
+
+ if ('values' in value && value.values) {
+ return items(value.values);
+ }
+
+ switch (value.type) {
+ case 'float_generator_arithmetic_sequence':
+ case 'integer_generator_arithmetic_sequence':
+ return items(value.step === 0 ? [value.start] : sequence(value.count, (i) => value.start + i * value.step));
+ case 'float_generator_linear_distribution':
+ return items(
+ value.count === 1
+ ? [value.start]
+ : sequence(value.count, (i) => value.start + (value.end - value.start) * (i / (value.count - 1)))
+ );
+ case 'integer_generator_linear_distribution':
+ return items(
+ value.count === 1
+ ? [value.start]
+ : sequence(value.count, (i) => value.start + Math.round((value.end - value.start) * (i / (value.count - 1))))
+ );
+ case 'float_generator_random_distribution_uniform': {
+ const draw = value.seed === null ? random : createSeededRandom(value.seed);
+
+ return items(sequence(value.count, () => draw() * (value.max - value.min) + value.min));
+ }
+ case 'integer_generator_random_distribution_uniform': {
+ const draw = value.seed === null ? random : createSeededRandom(value.seed);
+
+ return items(sequence(value.count, () => Math.floor(draw() * (value.max - value.min + 1)) + value.min));
+ }
+ case 'float_generator_parse_string':
+ return items(parseNumbers(value.input, value.splitOn, parseFloat));
+ case 'integer_generator_parse_string':
+ return items(parseNumbers(value.input, value.splitOn, (text) => parseInt(text, 10)));
+ case 'string_generator_parse_string':
+ return items(splitInput(value.input, value.splitOn).filter((text) => text !== ''));
+ case 'string_generator_dynamic_prompts_random':
+ return {
+ kind: 'async',
+ request: {
+ combinatorial: false,
+ kind: 'dynamicPrompts',
+ maxPrompts: value.count,
+ prompt: value.input,
+ seed: value.seed,
+ },
+ };
+ case 'string_generator_dynamic_prompts_combinatorial':
+ return {
+ kind: 'async',
+ request: {
+ combinatorial: true,
+ kind: 'dynamicPrompts',
+ maxPrompts: value.maxPrompts,
+ prompt: value.input,
+ seed: null,
+ },
+ };
+ case 'image_generator_images_from_board':
+ return value.board_id === undefined
+ ? items([])
+ : { kind: 'async', request: { boardId: value.board_id, category: value.category, kind: 'boardImages' } };
+ }
+};
+
+// #endregion
+
+// #region Planning
+
+export interface WorkflowBatchDatum {
+ nodeId: string;
+ fieldName: string;
+ items: WorkflowBatchItem[];
+}
+
+/** Async generator outputs resolved before submission, keyed by generator node id and fingerprinted by value. */
+export type WorkflowGeneratorResolutions = Record<string, { key: string; items: WorkflowBatchItem[] }>;
+
+export interface WorkflowPendingGenerator {
+ nodeId: string;
+ /** The generator's display name, for the error a failed resolution shows. */
+ nodeLabel: string;
+ key: string;
+ request: WorkflowAsyncGeneratorRequest;
+}
+
+export interface WorkflowBatchPlan {
+ /** Outer list is a cartesian product; each inner list is zipped, the backend's `Batch.data` shape. */
+ groups: WorkflowBatchDatum[][];
+ /** Sessions one run of the graph produces, or null while an async generator is still unresolved. */
+ batchSize: number | null;
+ hasBatchNodes: boolean;
+ pendingGenerators: WorkflowPendingGenerator[];
+ reasons: string[];
+}
+
+export interface WorkflowBatchPlanOptions {
+ generators?: WorkflowGeneratorResolutions;
+ random?: () => number;
+}
+
+const getNodeDisplayName = (node: WorkflowInvocationNode, templates: InvocationTemplates): string =>
+ node.data.label || templates[node.data.type]?.title || node.data.type;
+
+const toBatchKind = (type: WorkflowBatchNodeType, items: unknown[]): WorkflowBatchItem[] =>
+ items.map((item) =>
+ type === 'string_batch' && typeof item === 'number' ? String(item) : item
+ ) as WorkflowBatchItem[];
+
+/**
+ * Resolves every batch node into the datums its outgoing connections need, grouped the way the backend zips and
+ * multiplies them: ungrouped nodes each form a cartesian dimension, named groups zip their members together.
+ */
+export const planWorkflowBatch = (
+ document: Pick<ProjectGraphState, 'nodes' | 'edges'>,
+ templates: InvocationTemplates,
+ { generators = {}, random = Math.random }: WorkflowBatchPlanOptions = {}
+): WorkflowBatchPlan => {
+ const batchNodes = document.nodes.filter(
+ (node): node is WorkflowInvocationNode => isInvocationNode(node) && isWorkflowBatchNodeType(node.data.type)
+ );
+
+ if (batchNodes.length === 0) {
+ return { batchSize: 1, groups: [], hasBatchNodes: false, pendingGenerators: [], reasons: [] };
+ }
+
+ const nodesById = new Map(document.nodes.map((node) => [node.id, node]));
+ const edges = getCanonicalWorkflowEdges(document);
+ const reasons: string[] = [];
+ const pendingGenerators: WorkflowPendingGenerator[] = [];
+ const ungrouped: Array<{ datums: WorkflowBatchDatum[]; size: number | null }> = [];
+ const grouped = new Map<
+ WorkflowBatchGroupId,
+ Array<{ node: WorkflowInvocationNode; datums: WorkflowBatchDatum[]; size: number | null }>
+ >();
+ const claimedTargets = new Map<string, WorkflowInvocationNode>();
+ const pendingNodeIds = new Set<string>();
+
+ for (const batchNode of batchNodes) {
+ const type = batchNode.data.type as WorkflowBatchNodeType;
+ const name = getNodeDisplayName(batchNode, templates);
+ const collectionField = BATCH_COLLECTION_FIELDS[type];
+ const incoming = edges.find(
+ (edge) => edge.destination.node_id === batchNode.id && edge.destination.field === collectionField
+ );
+ let items: WorkflowBatchItem[] | null = null;
+ let oversizedGenerator = false;
+
+ if (incoming) {
+ const source = nodesById.get(incoming.source.node_id);
+ const generatorType = source && isInvocationNode(source) ? source.data.type : '';
+
+ if (!source || !isInvocationNode(source) || !isWorkflowGeneratorNodeType(generatorType)) {
+ reasons.push(`Batch node "${name}" can only receive its collection from a generator.`);
+ } else {
+ const value = parseWorkflowGeneratorValue(
+ GENERATOR_FIELD_TYPE_NAMES[generatorType],
+ source.data.inputs.generator?.value
+ );
+
+ // An unreadable generator is reported by the field check; here it only leaves the size unknown.
+ const requested = value ? getWorkflowGeneratorRequestedCount(value) : null;
+
+ if (requested !== null && requested > WORKFLOW_BATCH_MAX_ITEMS) {
+ // Refused by its count alone: building the list would cost memory in every readiness pass.
+ oversizedGenerator = true;
+ } else if (value?.type === 'image_generator_images_from_board' && value.board_id === undefined) {
+ reasons.push(`Image generator "${getNodeDisplayName(source, templates)}" has no board selected.`);
+ } else if (value) {
+ const resolution = resolveWorkflowGeneratorValue(value, random);
+
+ if (resolution.kind === 'items') {
+ items = resolution.items;
+ } else {
+ const key = getWorkflowGeneratorKey(value);
+ const resolved = generators[source.id];
+
+ if (resolved && resolved.key === key) {
+ items = resolved.items;
+ } else if (!pendingNodeIds.has(source.id)) {
+ // One generator may feed several batch nodes; it is resolved once and shared.
+ pendingNodeIds.add(source.id);
+ pendingGenerators.push({
+ key,
+ nodeId: source.id,
+ nodeLabel: getNodeDisplayName(source, templates),
+ request: resolution.request,
+ });
+ }
+ }
+ }
+ }
+ } else {
+ const own = batchNode.data.inputs[collectionField]?.value;
+
+ items = Array.isArray(own) ? (own as WorkflowBatchItem[]) : [];
+ }
+
+ if (items) {
+ items = toBatchKind(type, items);
+ }
+
+ const outputField = getWorkflowBatchOutputField(type);
+ const datums: WorkflowBatchDatum[] = [];
+ let hasOutgoing = false;
+
+ for (const edge of edges) {
+ if (edge.source.node_id !== batchNode.id) {
+ continue;
+ }
+
+ hasOutgoing = true;
+
+ if (edge.source.field !== outputField) {
+ reasons.push(`Batch node "${name}" can only batch its image output; width and height are not supported.`);
+ continue;
+ }
+
+ const target = nodesById.get(edge.destination.node_id);
+
+ if (!target || !isInvocationNode(target)) {
+ continue;
+ }
+
+ const targetName = getNodeDisplayName(target, templates);
+ const targetTemplate = templates[target.data.type];
+ const targetInput = targetTemplate?.inputs[edge.destination.field];
+
+ if (
+ isWorkflowBatchNodeType(target.data.type) ||
+ isWorkflowGeneratorNodeType(target.data.type) ||
+ (targetTemplate && !targetInput)
+ ) {
+ reasons.push(
+ `"${name}" cannot supply batch values to "${targetInput?.title ?? edge.destination.field}" on "${targetName}".`
+ );
+ continue;
+ }
+
+ const targetKey = `${target.id}:${edge.destination.field}`;
+ const claimedBy = claimedTargets.get(targetKey);
+
+ if (claimedBy && claimedBy !== batchNode) {
+ reasons.push(
+ `"${targetInput?.title ?? edge.destination.field}" on "${targetName}" receives values from more than one batch node.`
+ );
+ continue;
+ }
+
+ claimedTargets.set(targetKey, batchNode);
+
+ if (items) {
+ const coerced =
+ targetInput?.type.name === 'StringField'
+ ? items.map((item) => (typeof item === 'number' ? String(item) : item))
+ : items;
+
+ datums.push({ fieldName: edge.destination.field, items: coerced, nodeId: target.id });
+ }
+ }
+
+ if (!hasOutgoing) {
+ reasons.push(`Batch node "${name}" is not connected to any node.`);
+ }
+
+ const size = items ? items.length : null;
+
+ if (size === 0) {
+ reasons.push(`Batch node "${name}" has an empty collection.`);
+ } else if (oversizedGenerator || (size !== null && size > WORKFLOW_BATCH_MAX_ITEMS)) {
+ reasons.push(`Batch node "${name}" has more than ${WORKFLOW_BATCH_MAX_ITEMS.toLocaleString('en-US')} items.`);
+ }
+
+ const groupId = getWorkflowBatchGroupId(batchNode);
+
+ if (groupId === 'None') {
+ ungrouped.push({ datums, size });
+ } else {
+ const members = grouped.get(groupId) ?? [];
+
+ members.push({ datums, node: batchNode, size });
+ grouped.set(groupId, members);
+ }
+ }
+
+ const groups: WorkflowBatchDatum[][] = ungrouped
+ .filter((entry) => entry.datums.length > 0)
+ .map((entry) => entry.datums);
+ let batchSize: number | null = ungrouped.reduce<number | null>(
+ (product, entry) => (product === null || entry.size === null ? null : product * entry.size),
+ 1
+ );
+
+ for (const [groupId, members] of grouped) {
+ const knownSizes = members.flatMap((member) => (member.size === null ? [] : [member.size]));
+
+ if (new Set(knownSizes).size > 1) {
+ const sizes = members
+ .filter((member) => member.size !== null)
+ .map((member) => `${getNodeDisplayName(member.node, templates)}: ${member.size}`)
+ .join(', ');
+
+ reasons.push(`Batch group "${groupId}" mixes collection sizes (${sizes}).`);
+ }
+
+ const groupDatums = members.flatMap((member) => member.datums);
+
+ if (groupDatums.length > 0) {
+ groups.push(groupDatums);
+ }
+
+ const size = members.some((member) => member.size === null) ? null : (knownSizes[0] ?? 1);
+
+ batchSize = batchSize === null || size === null ? null : batchSize * size;
+ }
+
+ return { batchSize, groups, hasBatchNodes: true, pendingGenerators, reasons };
+};
+
+// #endregion
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
index 221f3e7cfd..e136b5354f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
@@ -112,7 +112,7 @@ describe('getProjectGraphReadiness', () => {
it('is ready when required inputs are connected or filled', () => {
const { doc } = buildDocument();
- expect(getProjectGraphReadiness(doc, loadedSnapshot)).toEqual({ canInvoke: true, reasons: [] });
+ expect(getProjectGraphReadiness(doc, loadedSnapshot)).toEqual({ batch: null, canInvoke: true, reasons: [] });
});
it('treats resolved connector output edges as connected required inputs', () => {
@@ -147,7 +147,7 @@ describe('getProjectGraphReadiness', () => {
type: 'addEdge',
});
- expect(getProjectGraphReadiness(doc, loadedSnapshot)).toEqual({ canInvoke: true, reasons: [] });
+ expect(getProjectGraphReadiness(doc, loadedSnapshot)).toEqual({ batch: null, canInvoke: true, reasons: [] });
});
it('reports missing required inputs and unknown node types', () => {
@@ -159,7 +159,11 @@ describe('getProjectGraphReadiness', () => {
value: '',
});
- expect(getProjectGraphReadiness(withEmptyString, loadedSnapshot)).toEqual({ canInvoke: true, reasons: [] });
+ expect(getProjectGraphReadiness(withEmptyString, loadedSnapshot)).toEqual({
+ batch: null,
+ canInvoke: true,
+ reasons: [],
+ });
const withMissingValue = projectGraphReducer(doc, {
fieldName: 'value',
@@ -233,7 +237,7 @@ describe('getProjectGraphReadiness', () => {
status: 'loaded',
templates: { 'optional-constrained': constrainedTemplate },
})
- ).toEqual({ canInvoke: true, reasons: [] });
+ ).toEqual({ batch: null, canInvoke: true, reasons: [] });
doc = projectGraphReducer(doc, { fieldName: 'count', nodeId: node.id, type: 'setFieldValue', value: 10 });
@@ -243,7 +247,7 @@ describe('getProjectGraphReadiness', () => {
status: 'loaded',
templates: { 'optional-constrained': constrainedTemplate },
})
- ).toEqual({ canInvoke: false, reasons: ['"optional-constrained" has invalid input "count".'] });
+ ).toEqual({ batch: null, canInvoke: false, reasons: ['"optional-constrained" has invalid input "count".'] });
});
it('treats only explicitly externally satisfied connection inputs as ready', () => {
@@ -270,6 +274,7 @@ describe('getProjectGraphReadiness', () => {
};
expect(getProjectGraphReadiness(doc, snapshot, { externallySatisfiedInputs: new Set(['sink:image']) })).toEqual({
+ batch: null,
canInvoke: false,
reasons: ['"connection-sink" is missing a connection for "Mask image".'],
});
@@ -277,7 +282,7 @@ describe('getProjectGraphReadiness', () => {
getProjectGraphReadiness(doc, snapshot, {
externallySatisfiedInputs: new Set(['sink:image', 'sink:mask']),
})
- ).toEqual({ canInvoke: true, reasons: [] });
+ ).toEqual({ batch: null, canInvoke: true, reasons: [] });
});
it('does not let external satisfaction bypass a required direct value', () => {
@@ -298,6 +303,7 @@ describe('getProjectGraphReadiness', () => {
};
expect(getProjectGraphReadiness(doc, snapshot, { externallySatisfiedInputs: new Set(['sink:image']) })).toEqual({
+ batch: null,
canInvoke: false,
reasons: ['"direct-sink" is missing required input "Layer image".'],
});
@@ -596,6 +602,7 @@ describe('compileProjectGraph', () => {
const loopTemplates = { for: forTemplate, for_return: returnTemplate, sink: sinkTemplate };
expect(getProjectGraphReadiness(document, { error: null, status: 'loaded', templates: loopTemplates })).toEqual({
+ batch: null,
canInvoke: false,
reasons: [{ key: 'nodes.forLoopLinkageInvalid' }],
});
@@ -603,6 +610,17 @@ describe('compileProjectGraph', () => {
});
describe('planWorkflowSubmission', () => {
+ /** These graphs have no batch nodes, so a plan is always produced. */
+ const planSubmission = (...args: Parameters<typeof planWorkflowSubmission>) => {
+ const result = planWorkflowSubmission(...args);
+
+ if (!result) {
+ throw new Error('Expected a submission plan');
+ }
+
+ return result;
+ };
+
const SEED_MAX = 4_294_967_295;
const seedInput = input('seed', {
default: 0,
@@ -652,7 +670,7 @@ describe('planWorkflowSubmission', () => {
it('repeats an unchanged graph while every seed holds', () => {
const { doc, ids } = buildSeeded([{ seed: 7 }, { seed: 9, seedMode: 'fixed' }]);
- const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });
+ const plan = planSubmission(doc, seededTemplates, { batchCount: 3 });
expect(plan).toMatchObject({ batchCount: 3, seedAdvances: [], seeds: [] });
expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(7);
@@ -665,7 +683,7 @@ describe('planWorkflowSubmission', () => {
{ seed: 100, seedMode: 'decrement' },
{ seed: 5 },
]);
- const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });
+ const plan = planSubmission(doc, seededTemplates, { batchCount: 3 });
expect(plan.seeds).toEqual([
{ fieldName: 'seed', nodeId: ids[0], seed: 42, seedStep: 1 },
@@ -688,7 +706,7 @@ describe('planWorkflowSubmission', () => {
node.data.inputs.seed = { label: 'Seed', name: 'seed', seedMode: 'increment', value: 42 };
const document = { ...createProjectGraph('dynamic-seed-plan'), nodes: [node] };
- const plan = planWorkflowSubmission(document, { dynamic_node: dynamicTemplate }, { batchCount: 2 });
+ const plan = planSubmission(document, { dynamic_node: dynamicTemplate }, { batchCount: 2 });
expect(plan.seeds).toEqual([{ fieldName: 'seed', nodeId: node.id, seed: 42, seedStep: 1 }]);
expect(plan.graph.backendGraph.nodes[node.id]?.seed).toBe(42);
@@ -696,7 +714,7 @@ describe('planWorkflowSubmission', () => {
it('wraps the authored seed and the advance over the inclusive seed range', () => {
const { doc } = buildSeeded([{ seed: 1, seedMode: 'decrement' }]);
- const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });
+ const plan = planSubmission(doc, seededTemplates, { batchCount: 3 });
expect(plan.seeds[0]).toMatchObject({ seed: 1, seedStep: -1 });
expect(plan.seedAdvances[0]?.toSeed).toBe(SEED_MAX - 1);
@@ -712,7 +730,7 @@ describe('planWorkflowSubmission', () => {
const start = Math.floor(0.25 * SEED_MAX);
try {
- const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 2 });
+ const plan = planSubmission(doc, seededTemplates, { batchCount: 2 });
expect(plan.seeds).toEqual([
{ fieldName: 'seed', nodeId: ids[0], seed: start, seedStep: 1 },
@@ -741,7 +759,7 @@ describe('planWorkflowSubmission', () => {
},
type: 'addEdge',
});
- const plan = planWorkflowSubmission(connected, seededTemplates, { batchCount: 2 });
+ const plan = planSubmission(connected, seededTemplates, { batchCount: 2 });
expect(plan).toMatchObject({ seedAdvances: [], seeds: [] });
expect(plan.graph.backendGraph.nodes[ids[0] as string]).not.toHaveProperty('seed');
@@ -758,7 +776,7 @@ describe('planWorkflowSubmission', () => {
type: 'setFieldValue',
value: undefined,
});
- const plan = planWorkflowSubmission(emptied, seededTemplates, { batchCount: 2 });
+ const plan = planSubmission(emptied, seededTemplates, { batchCount: 2 });
expect(plan.seeds).toEqual([{ fieldName: 'seed', nodeId: ids[0], seed: 0, seedStep: 1 }]);
expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(0);
@@ -886,3 +904,170 @@ describe('integer Literal enum values in the compiled graph', () => {
});
});
});
+
+describe('batch nodes', () => {
+ const list = (name: string, typeName: string): FieldInputTemplate =>
+ input(name, { required: true, type: { batch: true, cardinality: 'COLLECTION', name: typeName } });
+ const batchTemplates = {
+ ...templates,
+ float_batch: template('float_batch', {
+ batch_group_id: input('batch_group_id', {
+ default: 'None',
+ options: ['None', 'Group 1'],
+ type: { batch: false, cardinality: 'SINGLE', name: 'EnumField' },
+ }),
+ floats: list('floats', 'FloatField'),
+ }),
+ float_generator: template('float_generator', {
+ generator: input('generator', {
+ default: { count: 10, start: 0, step: 0.1, type: 'float_generator_arithmetic_sequence' },
+ input: 'direct',
+ required: true,
+ type: { batch: false, cardinality: 'SINGLE', name: 'FloatGeneratorField' },
+ }),
+ }),
+ noise: template('noise', {
+ cfg: input('cfg', { default: 7, type: { batch: false, cardinality: 'SINGLE', name: 'FloatField' } }),
+ seed: input('seed', {
+ default: 0,
+ maximum: 4_294_967_295,
+ minimum: 0,
+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },
+ }),
+ }),
+ };
+ const snapshot: InvocationTemplatesSnapshot = { error: null, status: 'loaded', templates: batchTemplates };
+ const build = (floats: number[], generator?: Record<string, unknown>) => {
+ const noise = buildInvocationNode(batchTemplates.noise, { x: 0, y: 0 });
+ const batch = buildInvocationNode(batchTemplates.float_batch, { x: 0, y: 100 });
+ let doc = createProjectGraph('batch-plan');
+
+ doc = projectGraphReducer(doc, { node: noise, type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: batch, type: 'addNode' });
+ doc = projectGraphReducer(doc, { fieldName: 'floats', nodeId: batch.id, type: 'setFieldValue', value: floats });
+ doc = projectGraphReducer(doc, {
+ edge: {
+ id: 'b->n',
+ source: batch.id,
+ sourceHandle: 'value',
+ target: noise.id,
+ targetHandle: 'cfg',
+ type: 'default',
+ },
+ type: 'addEdge',
+ });
+
+ if (generator) {
+ const gen = buildInvocationNode(batchTemplates.float_generator, { x: 0, y: 200 });
+
+ doc = projectGraphReducer(doc, { node: gen, type: 'addNode' });
+ doc = projectGraphReducer(doc, {
+ fieldName: 'generator',
+ nodeId: gen.id,
+ type: 'setFieldValue',
+ value: generator,
+ });
+ doc = projectGraphReducer(doc, {
+ edge: {
+ id: 'g->b',
+ source: gen.id,
+ sourceHandle: 'floats',
+ target: batch.id,
+ targetHandle: 'floats',
+ type: 'default',
+ },
+ type: 'addEdge',
+ });
+ }
+
+ return { batchId: batch.id, doc, noiseId: noise.id };
+ };
+
+ it('is ready with a fed, wired batch node and reports the batch size', () => {
+ const { doc } = build([1.5, 2.5]);
+
+ expect(getProjectGraphReadiness(doc, snapshot)).toEqual({ batch: { size: 2 }, canInvoke: true, reasons: [] });
+ });
+
+ it("still judges each entry of a batch node's own list, so a cleared row cannot reach the queue", () => {
+ const { doc } = build([1.5, null as unknown as number]);
+
+ expect(getProjectGraphReadiness(doc, snapshot)).toMatchObject({
+ canInvoke: false,
+ reasons: ['"float_batch" has invalid input "floats".'],
+ });
+ });
+
+ it('refuses a batch whose runs would overflow the queue before anything is submitted', () => {
+ const { doc } = build([1.5, 2.5]);
+
+ expect(getProjectGraphReadiness(doc, snapshot, { batchCount: 5_000 })).toEqual({
+ batch: { size: 2 },
+ canInvoke: true,
+ reasons: [],
+ });
+ expect(getProjectGraphReadiness(doc, snapshot, { batchCount: 5_001 })).toMatchObject({
+ canInvoke: false,
+ reasons: ['This batch would queue 10,002 sessions; the queue accepts at most 10,000.'],
+ });
+ });
+
+ it('blocks on batch reasons and leaves the size unknown while a generator is unresolved', () => {
+ const { doc } = build([]);
+
+ expect(getProjectGraphReadiness(doc, snapshot)).toMatchObject({
+ batch: { size: 0 },
+ canInvoke: false,
+ reasons: ['Batch node "float_batch" has an empty collection.'],
+ });
+
+ // A batch node's own list is the planner's business: a generator-fed batch has no list of its own.
+ const generated = build([], { count: 3, start: 1, step: 1, type: 'float_generator_arithmetic_sequence' });
+
+ expect(getProjectGraphReadiness(generated.doc, snapshot)).toEqual({
+ batch: { size: 3 },
+ canInvoke: true,
+ reasons: [],
+ });
+ });
+
+ it("compiles the executable graph without batch or generator nodes and keeps the fed input's static value", () => {
+ const { batchId, doc, noiseId } = build([1.5, 2.5], {
+ count: 3,
+ start: 1,
+ step: 1,
+ type: 'float_generator_arithmetic_sequence',
+ });
+ const compiled = compileProjectGraph(doc, batchTemplates);
+
+ expect(Object.keys(compiled.backendGraph.nodes)).toEqual([noiseId]);
+ expect(compiled.backendGraph.edges).toEqual([]);
+ expect(compiled.backendGraph.nodes[noiseId]?.cfg).toBe(7);
+ expect(compiled.nodes.map((node) => node.id)).not.toContain(batchId);
+ });
+
+ it('plans batch data beside the seed walk, sized for every session, and nothing while the batch is blocked', () => {
+ const { doc, noiseId } = build([1.5, 2.5]);
+ const stepping = projectGraphReducer(doc, {
+ fieldName: 'seed',
+ nodeId: noiseId,
+ seedMode: 'increment',
+ type: 'setFieldSeedMode',
+ });
+ const plan = planWorkflowSubmission(stepping, batchTemplates, { batchCount: 3 });
+
+ expect(plan).toMatchObject({
+ batchCount: 3,
+ batchData: [[{ fieldName: 'cfg', items: [1.5, 2.5], nodeId: noiseId }]],
+ batchSize: 2,
+ seeds: [{ fieldName: 'seed', nodeId: noiseId, seed: 0, seedStep: 1 }],
+ });
+ // Three runs of two sessions: the next authored seed sits past all six.
+ expect(plan?.seedAdvances).toEqual([
+ { fieldName: 'seed', fromSeed: 0, nodeId: noiseId, seedMode: 'increment', toSeed: 6 },
+ ]);
+
+ expect(planWorkflowSubmission(build([]).doc, batchTemplates, { batchCount: 1 })).toBeNull();
+ expect(planWorkflowSubmission(doc, batchTemplates, { batchCount: 6_000 })).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
index 99cf890d4e..c50f4b7492 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
@@ -11,9 +11,18 @@ import type {
WorkflowSeedFieldAdvance,
} from './types';
+import {
+ getWorkflowBatchCollectionField,
+ isWorkflowBatchNodeType,
+ isWorkflowGeneratorNodeType,
+ planWorkflowBatch,
+ WORKFLOW_BATCH_MAX_ITEMS,
+ type WorkflowBatchDatum,
+ type WorkflowGeneratorResolutions,
+} from './batch';
import { CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX } from './callSavedWorkflow';
import { createWorkflowId } from './document';
-import { getWorkflowFieldInvalidReason, isDirectInputField } from './fields';
+import { getWorkflowFieldInvalidReason, isDirectInputField, isWorkflowCollectionItemValid } from './fields';
import {
createForLoopValidationReason,
ForLoopGraphValidationError,
@@ -25,26 +34,17 @@ import { isInvocationNode } from './types';
import { hasAnyCycle } from './validation';
/**
- * Compile documents to immutable queue GraphContract with connector resolution; readiness rejects unsupported
- * batch/generator nodes.
+ * Compile documents to immutable queue GraphContract with connector resolution. Batch and generator nodes never
+ * reach the backend graph: the batch planner turns them into queue batch groups instead.
*/
-/** Client-resolved batch/generator nodes from the legacy editor; executing them server-side is meaningless. */
-const UNSUPPORTED_NODE_TYPES = new Set([
- 'float_batch',
- 'float_generator',
- 'image_batch',
- 'image_generator',
- 'integer_batch',
- 'integer_generator',
- 'string_batch',
- 'string_generator',
-]);
-
-export const isExecutableInvocationType = (type: string): boolean => !UNSUPPORTED_NODE_TYPES.has(type);
+export const isExecutableInvocationType = (type: string): boolean =>
+ !isWorkflowBatchNodeType(type) && !isWorkflowGeneratorNodeType(type);
const getExecutableNodes = (document: ProjectGraphState): WorkflowInvocationNode[] =>
- document.nodes.filter(isInvocationNode);
+ document.nodes.filter(
+ (node): node is WorkflowInvocationNode => isInvocationNode(node) && isExecutableInvocationType(node.data.type)
+ );
const isMissingValue = (value: unknown): boolean => value === undefined || value === null;
@@ -70,42 +70,54 @@ const toBoardGraphValue = (value: unknown): unknown => {
export interface ProjectGraphReadiness {
canInvoke: boolean;
reasons: Array<string | ForLoopValidationReason>;
+ /** Sessions one run produces through batch nodes; size is null while an async generator is unresolved. */
+ batch: { size: number | null } | null;
}
export interface ProjectGraphReadinessOptions {
/** Required connection inputs supplied by an ephemeral caller after document compilation. */
externallySatisfiedInputs?: ReadonlySet<string>;
+ /** Runs the submission would make; with batch nodes the product must fit the queue. */
+ batchCount?: number;
}
+/** The reason a batch of `sessions` sessions cannot be queued, or null while it fits. */
+export const getWorkflowBatchCapReason = (sessions: number): string | null =>
+ sessions > WORKFLOW_BATCH_MAX_ITEMS
+ ? `This batch would queue ${sessions.toLocaleString('en-US')} sessions; the queue accepts at most ${WORKFLOW_BATCH_MAX_ITEMS.toLocaleString('en-US')}.`
+ : null;
+
export const getProjectGraphReadiness = (
document: ProjectGraphState,
templatesSnapshot: InvocationTemplatesSnapshot,
options: ProjectGraphReadinessOptions = {}
): ProjectGraphReadiness => {
if (templatesSnapshot.status === 'error') {
- return { canInvoke: false, reasons: ['Node definitions failed to load from the backend.'] };
+ return { batch: null, canInvoke: false, reasons: ['Node definitions failed to load from the backend.'] };
}
if (templatesSnapshot.status !== 'loaded') {
- return { canInvoke: false, reasons: ['Node definitions are still loading.'] };
+ return { batch: null, canInvoke: false, reasons: ['Node definitions are still loading.'] };
}
const templates = templatesSnapshot.templates;
- const executableNodes = getExecutableNodes(document);
+ const invocationNodes = document.nodes.filter(isInvocationNode);
const canonicalEdges = getCanonicalWorkflowEdges(document);
- if (executableNodes.length === 0) {
- return { canInvoke: false, reasons: ['The project graph has no nodes. Add nodes in the Workflow view.'] };
+ if (getExecutableNodes(document).length === 0) {
+ return {
+ batch: null,
+ canInvoke: false,
+ reasons: ['The project graph has no nodes. Add nodes in the Workflow view.'],
+ };
}
const reasons: Array<string | ForLoopValidationReason> = [];
const connectedInputs = new Set(
- canonicalEdges
- .filter((edge) => executableNodes.some((node) => node.id === edge.destination.node_id))
- .map((edge) => `${edge.destination.node_id}:${edge.destination.field}`)
+ canonicalEdges.map((edge) => `${edge.destination.node_id}:${edge.destination.field}`)
);
- for (const node of executableNodes) {
+ for (const node of invocationNodes) {
const template = templates[node.data.type];
if (!template) {
@@ -113,10 +125,8 @@ export const getProjectGraphReadiness = (
continue;
}
- if (!isExecutableInvocationType(node.data.type)) {
- reasons.push(`Batch/generator node "${getNodeDisplayName(node, templates)}" is not supported yet.`);
- continue;
- }
+ // The batch planner judges a batch node's own list (size, connections); the field rules would only repeat it.
+ const batchCollectionField = getWorkflowBatchCollectionField(node.data.type);
if (node.data.type === 'call_saved_workflow') {
const workflowId = node.data.inputs.workflow_id?.value;
@@ -142,6 +152,17 @@ export const getProjectGraphReadiness = (
continue;
}
+ // A batch node's own list: the planner judges its size, the item rules still judge each entry.
+ if (inputTemplate.name === batchCollectionField) {
+ const list = node.data.inputs[inputTemplate.name]?.value;
+
+ if (Array.isArray(list) && !list.every((item) => isWorkflowCollectionItemValid(inputTemplate, item))) {
+ reasons.push(`"${getNodeDisplayName(node, templates)}" has invalid input "${inputTemplate.title}".`);
+ }
+
+ continue;
+ }
+
if (inputTemplate.input === 'connection') {
if (inputTemplate.required && !options.externallySatisfiedInputs?.has(`${node.id}:${inputTemplate.name}`)) {
reasons.push(
@@ -187,7 +208,23 @@ export const getProjectGraphReadiness = (
reasons.push(createForLoopValidationReason(forLoopError));
}
- return { canInvoke: reasons.length === 0, reasons };
+ const batchPlan = planWorkflowBatch(document, templates);
+
+ reasons.push(...batchPlan.reasons);
+
+ if (batchPlan.hasBatchNodes && batchPlan.batchSize !== null && options.batchCount !== undefined) {
+ const capReason = getWorkflowBatchCapReason(batchPlan.batchSize * options.batchCount);
+
+ if (capReason) {
+ reasons.push(capReason);
+ }
+ }
+
+ return {
+ batch: batchPlan.hasBatchNodes ? { size: batchPlan.batchSize } : null,
+ canInvoke: reasons.length === 0,
+ reasons,
+ };
};
const toGraphInputValue = (
@@ -364,7 +401,8 @@ export interface WorkflowSeedPlan {
export const planWorkflowSeeds = (
document: ProjectGraphState,
templates: InvocationTemplates,
- batchCount: number
+ batchCount: number,
+ batchSize = 1
): WorkflowSeedPlan => {
const connectedInputs = new Set(
getCanonicalWorkflowEdges(document).map((edge) => `${edge.destination.node_id}:${edge.destination.field}`)
@@ -398,10 +436,11 @@ export const planWorkflowSeeds = (
? inputTemplate.default
: 0;
const startSeed = seedMode === 'random' ? Math.floor(Math.random() * SEED_MAX) : wrapSeed(authoredSeed);
+ // Every session gets its own seed, as ComfyUI's per-execution advance does, so the walk spans the batch.
const plan = planSeedSubmission({
batchCount,
- promptCount: 1,
- seedBehaviour: 'per-iteration',
+ promptCount: batchSize,
+ seedBehaviour: 'per-image',
seedMode,
startSeed,
});
@@ -452,25 +491,48 @@ export const applyWorkflowSeeds = (
export interface WorkflowSubmissionPlan extends WorkflowSeedPlan {
/** Runs the submission produces. */
batchCount: number;
+ /** Batch-node groups, in the backend's product-of-zips shape; empty without batch nodes. */
+ batchData: WorkflowBatchDatum[][];
+ /** Sessions one run produces through batch nodes. */
+ batchSize: number;
graph: CompiledWorkflowGraph;
}
export interface WorkflowSubmissionPlanOptions {
/** Runs per submission; already sanitized to a positive integer by the caller. */
batchCount: number;
+ /** Async generator outputs resolved by the submitter; the plan is null while any are still pending. */
+ generators?: WorkflowGeneratorResolutions;
+ random?: () => number;
}
-/** Compiles the document with every planned first seed in place and reports the seeds that vary. */
+/**
+ * Compiles the document with every planned first seed in place and reports the seeds that vary. Returns null when
+ * the batch plan is not ready: an unresolved generator, a batch reason, or more sessions than the queue accepts.
+ */
export const planWorkflowSubmission = (
document: ProjectGraphState,
templates: InvocationTemplates,
- { batchCount }: WorkflowSubmissionPlanOptions
-): WorkflowSubmissionPlan => {
- const seedPlan = planWorkflowSeeds(document, templates, batchCount);
+ { batchCount, generators, random }: WorkflowSubmissionPlanOptions
+): WorkflowSubmissionPlan | null => {
+ const batchPlan = planWorkflowBatch(document, templates, { generators, random });
+
+ if (
+ batchPlan.reasons.length > 0 ||
+ batchPlan.pendingGenerators.length > 0 ||
+ batchPlan.batchSize === null ||
+ batchPlan.batchSize * batchCount > WORKFLOW_BATCH_MAX_ITEMS
+ ) {
+ return null;
+ }
+
+ const seedPlan = planWorkflowSeeds(document, templates, batchCount, batchPlan.batchSize);
return {
...seedPlan,
batchCount,
+ batchData: batchPlan.groups,
+ batchSize: batchPlan.batchSize,
graph: applyWorkflowSeeds(compileProjectGraph(document, templates), seedPlan.seeds),
};
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
index 40e6645e9e..6198aa8724 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
@@ -437,6 +437,15 @@ describe('getProjectGraphUndoEntry', () => {
getProjectGraphUndoEntry({ fieldName: 'a', nodeId: 'n', type: 'setFieldValue', value: [{ image_name: 'a' }] })
?.mergeKey
).toBeUndefined();
+ // Typing generator settings folds per variant; switching variants starts a new step.
+ expect(
+ getProjectGraphUndoEntry({
+ fieldName: 'generator',
+ nodeId: 'n',
+ type: 'setFieldValue',
+ value: { input: 'a,b', splitOn: ',', type: 'string_generator_parse_string' },
+ })?.mergeKey
+ ).toBe('setFieldValue:n:generator:string_generator_parse_string');
expect(
getProjectGraphUndoEntry({ fieldName: 'workflow_id', nodeId: 'n', type: 'setFieldValue', value: 'workflow-a' })
).toEqual({
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
index a3331fff06..30bb2d1882 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
@@ -21,6 +21,7 @@ import type {
XYPosition,
} from './types';
+import { isWorkflowGeneratorVariant } from './batch';
import {
CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX,
clearSavedWorkflowDynamicFields,
@@ -646,6 +647,12 @@ export interface ProjectGraphUndoEntry {
const isScalarList = (value: unknown): boolean =>
Array.isArray(value) && value.every((item) => typeof item === 'string' || typeof item === 'number' || item === null);
+const getGeneratorVariant = (value: unknown): string | null => {
+ const type = typeof value === 'object' && value !== null ? (value as { type?: unknown }).type : undefined;
+
+ return typeof type === 'string' && isWorkflowGeneratorVariant(type) ? type : null;
+};
+
const getUndoMergeKey = (action: ProjectGraphAction): string | undefined => {
switch (action.type) {
case 'setFieldDescription':
@@ -654,11 +661,18 @@ const getUndoMergeKey = (action: ProjectGraphAction): string | undefined => {
case 'setFieldValue':
// Typed text and dragged numbers stream, as do the rows of a scalar list; a pick (model, board,
// switch, image list) is one step of its own.
- return action.fieldName === 'workflow_id'
- ? undefined
- : typeof action.value === 'string' || typeof action.value === 'number' || isScalarList(action.value)
- ? `${action.type}:${action.nodeId}:${action.fieldName}`
- : undefined;
+ if (action.fieldName === 'workflow_id') {
+ return undefined;
+ }
+
+ if (typeof action.value === 'string' || typeof action.value === 'number' || isScalarList(action.value)) {
+ return `${action.type}:${action.nodeId}:${action.fieldName}`;
+ }
+
+ // Generator settings are typed too; switching the variant starts a new step.
+ const variant = getGeneratorVariant(action.value);
+
+ return variant ? `${action.type}:${action.nodeId}:${action.fieldName}:${variant}` : undefined;
case 'setNodeLabel':
case 'setNodeNotes':
return `${action.type}:${action.nodeId}`;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
index 8d5c58076f..3521c8c89f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
@@ -304,6 +304,24 @@ describe('workflow field validation', () => {
expect(getFieldRecordId(undefined, 'style_preset_id')).toBeNull();
});
+ it('treats a generator field as editable and judges its value by the generator schema', () => {
+ const generator = input({ type: single('FloatGeneratorField') });
+
+ expect(isDirectInputField(generator)).toBe(true);
+ expect(
+ isWorkflowFieldValueValid(generator, { count: 2, start: 0, step: 1, type: 'float_generator_arithmetic_sequence' })
+ ).toBe(true);
+ expect(isWorkflowFieldValueValid(generator, { count: 0, type: 'float_generator_arithmetic_sequence' })).toBe(false);
+ expect(isWorkflowFieldValueValid(generator, undefined)).toBe(false);
+ expect(
+ getWorkflowFieldInvalidReason({
+ isConnected: false,
+ template: generator,
+ value: { type: 'integer_generator_parse_string' },
+ })
+ ).toBe('Invalid value.');
+ });
+
it('treats empty board values as the Auto sentinel', () => {
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), undefined)).toBe(true);
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), { board_id: 'board-id' })).toBe(true);
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
index a7aef4f32e..a07c512b67 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
@@ -2,6 +2,8 @@ import { SEED_MAX } from '@platform/core/seed';
import type { FieldInputTemplate, FieldType, WorkflowFieldInstance } from './types';
+import { isWorkflowGeneratorFieldTypeName, parseWorkflowGeneratorValue } from './batch';
+
export const getEffectiveWorkflowFieldDescription = (
instance: WorkflowFieldInstance | undefined,
template: FieldInputTemplate | undefined
@@ -17,8 +19,11 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set([
'ColorField',
'EnumField',
'FloatField',
+ 'FloatGeneratorField',
'ImageField',
+ 'ImageGeneratorField',
'IntegerField',
+ 'IntegerGeneratorField',
// Collection loaders accept scalar or list LoRA fields; edit lists inline without extra selector/collector
// nodes.
'LoRAField',
@@ -26,6 +31,7 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set([
'SchedulerField',
'SavedWorkflowField',
'StringField',
+ 'StringGeneratorField',
'StylePresetField',
'SystemPromptField',
'VideoField',
@@ -286,6 +292,10 @@ const isColorValueValid = (value: unknown): boolean => {
};
export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: unknown): boolean => {
+ if (isWorkflowGeneratorFieldTypeName(template.type.name)) {
+ return parseWorkflowGeneratorValue(template.type.name, value) !== null;
+ }
+
if (
template.type.cardinality === 'COLLECTION' &&
(template.type.name === 'StringField' ||
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
index 2f9377d808..5c33459cf3 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
@@ -272,6 +272,50 @@ describe('layer workflow binding discovery', () => {
});
});
+describe('layer workflow batch guard', () => {
+ it('never runs a document with batch nodes, which a single layer graph cannot expand', () => {
+ const floatType = { batch: false, cardinality: 'SINGLE' as const, name: 'FloatField' };
+ const processorTemplate = template(
+ 'processor',
+ {
+ cfg: input('cfg', { default: 7, input: 'direct', title: 'CFG', type: floatType }),
+ source: input('source', { input: 'direct', title: 'Source', uiOrder: 0 }),
+ },
+ { image: output('image', { title: 'Result' }) }
+ );
+ const batchTemplate = template('float_batch', {
+ batch_group_id: input('batch_group_id', {
+ default: 'None',
+ input: 'direct',
+ options: ['None'],
+ type: { batch: false, cardinality: 'SINGLE', name: 'EnumField' },
+ }),
+ floats: input('floats', {
+ default: [],
+ required: true,
+ type: { batch: true, cardinality: 'COLLECTION', name: 'FloatField' },
+ }),
+ });
+ const templates = { float_batch: batchTemplate, processor: processorTemplate };
+ const processor = node('processor', processorTemplate);
+ const batch = node('batch', batchTemplate);
+
+ batch.data.inputs.floats = { label: '', name: 'floats', value: [1, 2] };
+
+ const plain = document([processor]);
+ const batched = document(
+ [processor, batch],
+ [{ id: 'e', source: 'batch', sourceHandle: 'value', target: 'processor', targetHandle: 'cfg', type: 'default' }]
+ );
+ const outputBinding = getLayerWorkflowOutputs(plain, templates)[0]!;
+
+ expect(getRunnableLayerWorkflowInputs(plain, loaded(templates), outputBinding)).toEqual([
+ binding('processor', 'source', 'processor → Source'),
+ ]);
+ expect(getRunnableLayerWorkflowInputs(batched, loaded(templates), outputBinding)).toEqual([]);
+ });
+});
+
describe('layer workflow dialog selection', () => {
it('defaults to Gallery and the first output that has a runnable input', () => {
const firstOutput = binding('first-output', 'image', 'First output');
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
index 67486738c7..f8b3d9bdff 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
@@ -265,6 +265,11 @@ export const buildLayerWorkflowGraph = (options: BuildLayerWorkflowGraphOptions)
throw new Error(`Workflow is not ready: ${readiness.reasons.join(' ')}`);
}
+ // A layer runs exactly one graph; batch data has nowhere to go.
+ if (readiness.batch) {
+ throw new Error('Layer workflows cannot contain batch nodes.');
+ }
+
const compiled = compileProjectGraph(cloned, templates);
const graph = compiled.backendGraph;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/validation.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/validation.test.ts
index be504980ab..f862feeced 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/validation.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/validation.test.ts
@@ -52,6 +52,14 @@ describe('validateConnectionTypes', () => {
});
it('rejects batch/non-batch mixes', () => {
+ // A generator's list only feeds a batch node's list, and a plain list never can.
+ expect(
+ validateConnectionTypes(
+ { ...collection('FloatField'), batch: true },
+ { ...collection('FloatField'), batch: true }
+ )
+ ).toBe(true);
+ expect(validateConnectionTypes(collection('FloatField'), { ...collection('FloatField'), batch: true })).toBe(false);
expect(validateConnectionTypes({ ...single('IntegerField'), batch: true }, single('IntegerField'))).toBe(false);
});
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
index c5a448ee8f..c25717af73 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
@@ -557,3 +557,54 @@ describe('field label overrides', () => {
});
});
});
+
+describe('batch and generator nodes', () => {
+ it('keeps legacy generator values and batch group ids verbatim through a load and save', () => {
+ const generator = {
+ count: 3,
+ max: 1,
+ min: 0,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ values: [0.2, 0.4, 0.6],
+ };
+ const { document, warnings } = parseWorkflowJson({
+ edges: [],
+ name: 'Batch',
+ nodes: [
+ {
+ data: {
+ id: 'g',
+ inputs: { generator: { label: '', name: 'generator', value: generator } },
+ type: 'float_generator',
+ },
+ id: 'g',
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+ },
+ {
+ data: {
+ id: 'b',
+ inputs: {
+ batch_group_id: { label: '', name: 'batch_group_id', value: 'Group 2' },
+ floats: { label: '', name: 'floats', value: [1, 2] },
+ },
+ type: 'float_batch',
+ },
+ id: 'b',
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+ },
+ ],
+ version: '1.0.0',
+ });
+ const serialized = serializeWorkflowJson(document) as {
+ nodes: Array<{ data: { inputs: Record<string, { value: unknown }> } }>;
+ };
+
+ expect(warnings).toEqual([]);
+ expect(serialized.nodes[0]?.data.inputs.generator?.value).toEqual(generator);
+ expect(serialized.nodes[1]?.data.inputs.batch_group_id?.value).toBe('Group 2');
+ expect(serialized.nodes[1]?.data.inputs.floats?.value).toEqual([1, 2]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/generatorQueries.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/generatorQueries.test.ts
new file mode 100644
index 0000000000..3d5d781972
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/generatorQueries.test.ts
@@ -0,0 +1,94 @@
+import { galleryItemNamesOptions } from '@features/gallery/queries';
+import { QueryClient } from '@tanstack/react-query';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveWorkflowGenerators } from './generatorQueries';
+
+const http = vi.hoisted(() => ({ apiFetchJson: vi.fn() }));
+
+vi.mock('@platform/transport/http', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ apiFetchJson: http.apiFetchJson,
+}));
+
+const promptsRequest = (seed: number | null, combinatorial = false) => ({
+ key: 'k',
+ nodeId: 'gen',
+ nodeLabel: 'Prompts',
+ request: { combinatorial, kind: 'dynamicPrompts' as const, maxPrompts: 3, prompt: '{a|b}', seed },
+});
+const boardRequest = {
+ key: 'k',
+ nodeId: 'board',
+ nodeLabel: 'Board images',
+ request: { boardId: 'board-1', category: 'images' as const, kind: 'boardImages' as const },
+};
+const sentSeeds = () =>
+ http.apiFetchJson.mock.calls
+ .filter(([path]) => String(path).includes('dynamicprompts'))
+ .map(([, init]) => JSON.parse((init as { body: string }).body).seed as number | null);
+
+describe('resolveWorkflowGenerators', () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ http.apiFetchJson.mockReset();
+ http.apiFetchJson.mockImplementation((path: string) =>
+ String(path).includes('dynamicprompts')
+ ? Promise.resolve({ error: null, prompts: ['a', 'b'] })
+ : Promise.resolve({
+ items: [
+ { kind: 'image', name: 'a.png' },
+ { kind: 'video', name: 'clip.mp4' },
+ ],
+ total: 2,
+ })
+ );
+ });
+
+ it('draws a fresh seed for an unseeded random prompt on every submission, so repeats differ', async () => {
+ const first = await resolveWorkflowGenerators(queryClient, [promptsRequest(null)]);
+ const second = await resolveWorkflowGenerators(queryClient, [promptsRequest(null)]);
+
+ expect(first.resolutions).toEqual({ gen: { items: ['a', 'b'], key: 'k' } });
+ expect(second.errors).toEqual([]);
+ expect(sentSeeds()).toHaveLength(2);
+ expect(sentSeeds().every((seed) => Number.isInteger(seed))).toBe(true);
+ expect(sentSeeds()[0]).not.toBe(sentSeeds()[1]);
+
+ // A pinned seed reuses its expansion: one request for two submissions.
+ await resolveWorkflowGenerators(queryClient, [promptsRequest(7)]);
+ await resolveWorkflowGenerators(queryClient, [promptsRequest(7)]);
+ expect(sentSeeds()).toEqual([...sentSeeds().slice(0, 2), 7]);
+ });
+
+ it('lists a board fresh rather than from the preview cache, and keeps only its images', async () => {
+ queryClient.setQueryData(
+ galleryItemNamesOptions({ boardId: 'board-1', galleryView: 'images', searchTerm: '' }).queryKey,
+ { items: [{ kind: 'image', name: 'stale.png' }], total: 1 }
+ );
+
+ const { errors, resolutions } = await resolveWorkflowGenerators(queryClient, [boardRequest]);
+
+ expect(errors).toEqual([]);
+ expect(http.apiFetchJson).toHaveBeenCalledTimes(1);
+ expect(resolutions).toEqual({ board: { items: [{ image_name: 'a.png' }], key: 'k' } });
+ });
+
+ it('names the generator in every failure and resolves nothing for it', async () => {
+ http.apiFetchJson.mockImplementation((path: string) =>
+ String(path).includes('dynamicprompts')
+ ? Promise.resolve({ error: 'Unbalanced braces', prompts: [] })
+ : Promise.reject(new Error('offline'))
+ );
+
+ const { errors, resolutions } = await resolveWorkflowGenerators(queryClient, [
+ promptsRequest(null, true),
+ boardRequest,
+ ]);
+
+ expect(resolutions).toEqual({});
+ expect(errors.sort()).toEqual(['Board images: offline', 'Prompts: Unbalanced braces']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/generatorQueries.ts b/invokeai/frontend/webv2/src/features/workflow/data/generatorQueries.ts
new file mode 100644
index 0000000000..b923e0b9ff
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/generatorQueries.ts
@@ -0,0 +1,101 @@
+import type { GalleryItemsFilter } from '@features/gallery/queries';
+import type { ParseDynamicPromptsRequest, ParseDynamicPromptsResponse } from '@features/generation/prompts';
+import type {
+ WorkflowAsyncGeneratorRequest,
+ WorkflowBatchItem,
+ WorkflowGeneratorResolutions,
+ WorkflowPendingGenerator,
+} from '@features/workflow/core/batch';
+import type { QueryClient } from '@tanstack/react-query';
+
+import { galleryItemNamesOptions } from '@features/gallery/queries';
+import { dynamicPromptsQueryOptions } from '@features/generation/prompts';
+import { queryOptions } from '@tanstack/react-query';
+
+export interface WorkflowGeneratorQueryResult {
+ items: WorkflowBatchItem[];
+ /** The backend's own complaint about the request (bad dynamic-prompt syntax), shown instead of the items. */
+ error: string | null;
+}
+
+const toDynamicPromptsRequest = (
+ request: Extract<WorkflowAsyncGeneratorRequest, { kind: 'dynamicPrompts' }>
+): ParseDynamicPromptsRequest => ({
+ combinatorial: request.combinatorial,
+ max_prompts: request.maxPrompts,
+ prompt: request.prompt,
+ seed: request.combinatorial ? null : request.seed,
+});
+
+const toBoardFilter = (
+ request: Extract<WorkflowAsyncGeneratorRequest, { kind: 'boardImages' }>
+): GalleryItemsFilter => ({
+ boardId: request.boardId,
+ galleryView: request.category,
+ searchTerm: '',
+});
+
+const fromDynamicPrompts = (response: ParseDynamicPromptsResponse): WorkflowGeneratorQueryResult => ({
+ error: response.error ?? null,
+ items: response.prompts,
+});
+
+const fromBoardImages = (page: { items: readonly { kind: string; name: string }[] }): WorkflowGeneratorQueryResult => ({
+ error: null,
+ items: page.items.filter((item) => item.kind === 'image').map((item) => ({ image_name: item.name })),
+});
+
+/**
+ * The query behind an async generator: dynamic prompts or a board's images. The preview widget and the submit
+ * path share the underlying queries so a preview that already loaded needs no second round trip.
+ */
+export const getWorkflowGeneratorQueryOptions = (request: WorkflowAsyncGeneratorRequest) =>
+ request.kind === 'dynamicPrompts'
+ ? queryOptions({ ...dynamicPromptsQueryOptions(toDynamicPromptsRequest(request)), select: fromDynamicPrompts })
+ : queryOptions({ ...galleryItemNamesOptions(toBoardFilter(request)), select: fromBoardImages });
+
+/** A seed for an unseeded random prompt draw; the server needs an integer and a fresh one per submission. */
+const drawSeed = (): number => Math.floor(Math.random() * 0x7fffffff);
+
+const fetchWorkflowGenerator = (
+ queryClient: QueryClient,
+ request: WorkflowAsyncGeneratorRequest
+): Promise<WorkflowGeneratorQueryResult> =>
+ request.kind === 'dynamicPrompts'
+ ? queryClient.fetchQuery(dynamicPromptsQueryOptions(toDynamicPromptsRequest(request))).then(fromDynamicPrompts)
+ : // Fetched fresh so the batch sees the board as it is now, not as the picker last showed it.
+ queryClient
+ .fetchQuery({ ...galleryItemNamesOptions(toBoardFilter(request)), staleTime: 0 })
+ .then(fromBoardImages);
+
+/** Resolves every pending async generator for a submission; unseeded random prompts draw a new seed each time. */
+export const resolveWorkflowGenerators = async (
+ queryClient: QueryClient,
+ pending: readonly WorkflowPendingGenerator[]
+): Promise<{ resolutions: WorkflowGeneratorResolutions; errors: string[] }> => {
+ const resolutions: WorkflowGeneratorResolutions = {};
+ const errors: string[] = [];
+
+ await Promise.all(
+ pending.map(async ({ key, nodeId, nodeLabel, request }) => {
+ const effectiveRequest: WorkflowAsyncGeneratorRequest =
+ request.kind === 'dynamicPrompts' && !request.combinatorial && request.seed === null
+ ? { ...request, seed: drawSeed() }
+ : request;
+
+ try {
+ const result = await fetchWorkflowGenerator(queryClient, effectiveRequest);
+
+ if (result.error) {
+ errors.push(`${nodeLabel}: ${result.error}`);
+ } else {
+ resolutions[nodeId] = { items: result.items, key };
+ }
+ } catch (error) {
+ errors.push(`${nodeLabel}: ${error instanceof Error ? error.message : 'the request failed.'}`);
+ }
+ })
+ );
+
+ return { errors, resolutions };
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
index d15caef250..6ea4769477 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
@@ -133,6 +133,63 @@ const openApiFixture = {
title: 'DenoiseInvocation',
type: 'object',
},
+ FloatBatchInvocation: {
+ class: 'invocation',
+ output: { $ref: '#/components/schemas/FloatOutput' },
+ properties: {
+ batch_group_id: {
+ default: 'None',
+ enum: ['None', 'Group 1'],
+ field_kind: 'input',
+ input: 'direct',
+ orig_required: false,
+ title: 'Batch Group',
+ type: 'string',
+ },
+ floats: {
+ anyOf: [{ items: { type: 'number' }, minItems: 1, type: 'array' }, { type: 'null' }],
+ field_kind: 'input',
+ input: 'any',
+ orig_required: true,
+ title: 'Floats',
+ },
+ type: { const: 'float_batch', default: 'float_batch', title: 'type' },
+ },
+ title: 'Float Batch',
+ type: 'object',
+ },
+ FloatGeneratorInvocation: {
+ class: 'invocation',
+ output: { $ref: '#/components/schemas/FloatGeneratorOutput' },
+ properties: {
+ generator: {
+ $ref: '#/components/schemas/FloatGeneratorField',
+ field_kind: 'input',
+ input: 'direct',
+ orig_required: true,
+ title: 'Generator Type',
+ },
+ type: { const: 'float_generator', default: 'float_generator', title: 'type' },
+ },
+ title: 'Float Generator',
+ type: 'object',
+ },
+ FloatGeneratorOutput: {
+ class: 'output',
+ properties: {
+ floats: { field_kind: 'output', items: { type: 'number' }, title: 'Floats', type: 'array' },
+ type: { const: 'float_generator_output', default: 'float_generator_output' },
+ },
+ type: 'object',
+ },
+ FloatOutput: {
+ class: 'output',
+ properties: {
+ type: { const: 'float_output', default: 'float_output' },
+ value: { field_kind: 'output', title: 'Value', type: 'number' },
+ },
+ type: 'object',
+ },
GraphInvocation: {
class: 'invocation',
output: { $ref: '#/components/schemas/IntegerOutput' },
@@ -226,7 +283,14 @@ describe('parseOpenApiToTemplates', () => {
const templates = parseOpenApiToTemplates(openApiFixture);
it('parses invocation schemas into templates, skipping the denylist', () => {
- expect(Object.keys(templates).sort()).toEqual(['add', 'denoise', 'lora_collection_loader', 'save_video']);
+ expect(Object.keys(templates).sort()).toEqual([
+ 'add',
+ 'denoise',
+ 'float_batch',
+ 'float_generator',
+ 'lora_collection_loader',
+ 'save_video',
+ ]);
const add = templates.add;
@@ -272,6 +336,28 @@ describe('parseOpenApiToTemplates', () => {
});
});
+ it('marks batch lists and generator outputs so only they can connect, and gives generators a default', () => {
+ const batch = templates.float_batch;
+ const generator = templates.float_generator;
+
+ expect(batch?.inputs.floats?.type).toEqual({ batch: true, cardinality: 'COLLECTION', name: 'FloatField' });
+ expect(batch?.inputs.floats?.default).toEqual([]);
+ expect(batch?.inputs.batch_group_id?.type.batch).toBe(false);
+ expect(generator?.outputs.floats?.type).toEqual({ batch: true, cardinality: 'COLLECTION', name: 'FloatField' });
+ expect(generator?.inputs.generator?.type).toEqual({
+ batch: false,
+ cardinality: 'SINGLE',
+ name: 'FloatGeneratorField',
+ });
+ // The backend model is empty, so the editor supplies the first variant as the default.
+ expect(generator?.inputs.generator?.default).toEqual({
+ count: 10,
+ start: 0,
+ step: 0.1,
+ type: 'float_generator_arithmetic_sequence',
+ });
+ });
+
it('reads list bounds and item constraints from the array schema of a collection input', () => {
const denoise = templates.denoise;
const steps = denoise?.inputs.steps;
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts
index d8658aa326..9dbe82fd4e 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts
@@ -8,6 +8,11 @@ import type {
ProjectGraphState,
} from '@features/workflow/core/types';
+import {
+ getDefaultWorkflowGeneratorValue,
+ getWorkflowBatchCollectionField,
+ getWorkflowGeneratorOutputField,
+} from '@features/workflow/core/batch';
import { updateWorkflowNodes } from '@features/workflow/core/document';
import { isEditableCollectionFieldType } from '@features/workflow/core/fields';
import { createLogger } from '@platform/logging/logger';
@@ -270,7 +275,8 @@ const buildInputTemplate = (
// without a widget stays absent so readiness still asks for its connection.
required && input !== 'connection' && isEditableCollectionFieldType(type)
? []
- : getDefaultValueForType(type, options),
+ : // The backend's generator models are empty; the editor owns their shape and their default.
+ (getDefaultWorkflowGeneratorValue(type.name) ?? getDefaultValueForType(type, options)),
description: typeof property.description === 'string' ? property.description : '',
exclusiveMaximum: getNumberOrNull(constraints.exclusiveMaximum),
exclusiveMinimum: getNumberOrNull(constraints.exclusiveMinimum),
@@ -356,6 +362,11 @@ const parseInvocationSchema = (schema: JsonObject, schemas: JsonObject): Invocat
continue;
}
+ // A batch node's list only accepts a generator, and a generator's list only feeds a batch node.
+ if (getWorkflowBatchCollectionField(type) === name) {
+ fieldType.batch = true;
+ }
+
inputs[name] = buildInputTemplate(name, rawProperty, fieldType, isInternal ? 'internal' : 'input');
}
@@ -384,6 +395,10 @@ const parseInvocationSchema = (schema: JsonObject, schemas: JsonObject): Invocat
continue;
}
+ if (getWorkflowGeneratorOutputField(type) === name) {
+ fieldType.batch = true;
+ }
+
outputs[name] = {
description: typeof rawProperty.description === 'string' ? rawProperty.description : '',
name,
diff --git a/invokeai/frontend/webv2/src/features/workflow/queries.ts b/invokeai/frontend/webv2/src/features/workflow/queries.ts
index 77ac013aeb..4a04fd6ca4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/queries.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/queries.ts
@@ -1,4 +1,5 @@
export * from './data/api';
+export * from './data/generatorQueries';
export * from './data/libraryCache';
export * from './data/savedWorkflowQueries';
export { createWorkflowRunCaptureSink, type RunCaptureDeps } from './data/runCapture';
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx
index a7ef61ed1f..b241cabf5c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx
@@ -732,3 +732,94 @@ describe('InvocationFlowNode template version', () => {
expect(updateIcon()?.getAttribute('aria-label')).toBe('nodes.nodeVersionIncompatible');
});
});
+
+describe('InvocationFlowNode batch nodes', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ host = document.createElement('div');
+ host.style.cssText = 'width: 480px; height: 520px;';
+ document.body.append(host);
+ root = createRoot(host);
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ });
+
+ const batchTemplate: InvocationTemplate = {
+ ...template,
+ inputs: {
+ batch_group_id: {
+ ...(template.inputs.a as InvocationTemplate['inputs'][string]),
+ default: 'None',
+ input: 'direct',
+ name: 'batch_group_id',
+ options: ['None', 'Group 1', 'Group 2'],
+ title: 'Batch Group',
+ type: { batch: false, cardinality: 'SINGLE', name: 'EnumField' },
+ },
+ floats: {
+ ...(template.inputs.a as InvocationTemplate['inputs'][string]),
+ default: [],
+ input: 'any',
+ name: 'floats',
+ title: 'Floats',
+ type: { batch: true, cardinality: 'COLLECTION', name: 'FloatField' },
+ },
+ },
+ outputs: {
+ value: {
+ description: '',
+ name: 'value',
+ title: 'Value',
+ type: { batch: false, cardinality: 'SINGLE', name: 'FloatField' },
+ },
+ },
+ type: 'float_batch',
+ };
+ const batchNode = (groupId: string): WorkflowInvocationNode => ({
+ ...documentNode,
+ data: {
+ ...documentNode.data,
+ inputs: {
+ batch_group_id: { label: '', name: 'batch_group_id', value: groupId },
+ floats: { label: '', name: 'floats', value: [1, 2] },
+ },
+ type: 'float_batch',
+ },
+ id: 'batch-node',
+ });
+ const render = (groupId: string) => {
+ const graph: ProjectGraphState = { ...createProjectGraph('batch-test'), nodes: [batchNode(groupId)] };
+
+ return act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <WorkflowUiProvider adapter={createAdapter(createExecutionPort().port)}>
+ <ReactFlow
+ edges={[]}
+ nodes={toFlowNodes(graph, [], { float_batch: batchTemplate })}
+ nodeTypes={nodeTypes}
+ />
+ </WorkflowUiProvider>
+ </ChakraProvider>
+ )
+ );
+ };
+ const header = () => host.querySelector<HTMLElement>('.react-flow__node > div > div')!;
+
+ it('names the group beside the title, draws the batch list handle as a diamond, and keeps the footer off', async () => {
+ await render('Group 2');
+ expect(header().textContent).toContain('(Group 2)');
+ expect(host.querySelector<HTMLElement>('.react-flow__handle[data-handleid="floats"]')?.style.transform).toContain(
+ 'rotate(45deg)'
+ );
+ expect(host.textContent).not.toContain('Use Cache');
+
+ await render('None');
+ expect(header().textContent).toContain('(nodes.noBatchGroup)');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
index d82656164f..d6b5e25c18 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
@@ -41,6 +41,8 @@ import {
getFieldTypeLabel,
getNodeUpdateStatus,
getOutputFieldNamesByScope,
+ getWorkflowBatchGroupId,
+ isWorkflowBatchNodeType,
getOutputFieldRows,
getWorkflowFieldInvalidReason,
isDirectInputField,
@@ -313,6 +315,32 @@ const getUpdateStatusText = (
const UPDATE_TOOLTIP_POSITIONING = { placement: 'top-end' } as const;
+/** Legacy's group tints, so a zipped group reads as one colour across the canvas. */
+const BATCH_GROUP_COLORS: Record<string, string> = {
+ 'Group 1': 'green.fg',
+ 'Group 2': 'blue.fg',
+ 'Group 3': 'purple.fg',
+ 'Group 4': 'red.fg',
+ 'Group 5': 'yellow.fg',
+};
+
+/** A batch node's group beside its title: zipped groups share a colour, an ungrouped node says so. */
+const BatchGroupSuffix = ({ node }: { node: WorkflowInvocationNode }) => {
+ const { t } = useTranslation();
+
+ if (!isWorkflowBatchNodeType(node.data.type)) {
+ return null;
+ }
+
+ const groupId = getWorkflowBatchGroupId(node);
+
+ return (
+ <Text color={BATCH_GROUP_COLORS[groupId] ?? 'fg.subtle'} flexShrink={0} fontSize="2xs" fontWeight="600">
+ ({groupId === 'None' ? t('nodes.noBatchGroup') : groupId})
+ </Text>
+ );
+};
+
/** Header mark for a node whose version is not its template's; the tooltip says what can be done about it. */
const NodeUpdateIcon = ({
node,
@@ -839,6 +867,7 @@ const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeT
>
<Flex {...getWorkflowNodeHeaderProps()}>
<MiddleTruncate fontSize="sm" fontWeight="700" minW="0" text={title} />
+ <BatchGroupSuffix node={node} />
<Box flex="1" />
<NodeOutcomeIcon execution={execution} node={node} />
{templateView && isOutdated ? <NodeUpdateIcon node={node} template={templateView.template} /> : null}
@@ -924,6 +953,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
) : (
<>
<NodeTitle node={node} title={node.data.label || template.title} />
+ <BatchGroupSuffix node={node} />
<Box flex="1" />
<NodeOutcomeIcon execution={execution} node={node} />
{isOutdated ? <NodeUpdateIcon node={node} template={template} /> : null}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/GeneratorFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/GeneratorFieldInput.tsx
new file mode 100644
index 0000000000..3617a1ffa6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/GeneratorFieldInput.tsx
@@ -0,0 +1,663 @@
+import type { ChangeEvent, WheelEvent } from 'react';
+
+import { Box, chakra, Checkbox, createListCollection, HStack, Input, Stack, Textarea } from '@chakra-ui/react';
+import { galleryBoardsOptions } from '@features/gallery/queries';
+import {
+ getWorkflowGeneratorQueryOptions,
+ type WorkflowGeneratorQueryResult,
+} from '@features/workflow/data/generatorQueries';
+import {
+ getDefaultWorkflowGeneratorValue,
+ getWorkflowGeneratorRequestedCount,
+ getWorkflowGeneratorVariantDefaults,
+ isRandomWorkflowGeneratorValue,
+ isWorkflowGeneratorVariant,
+ WORKFLOW_BATCH_MAX_ITEMS,
+ parseWorkflowGeneratorValue,
+ resolveWorkflowGeneratorValue,
+ WORKFLOW_GENERATOR_VARIANTS,
+ type WorkflowAsyncGeneratorRequest,
+ type WorkflowGeneratorValue,
+ type WorkflowGeneratorVariant,
+} from '@features/workflow/utility';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { Button, Combobox, Select, toaster } from '@platform/ui';
+import { useQuery, type UseQueryOptions } from '@tanstack/react-query';
+import { UploadIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { WorkflowFieldInputProps } from './WorkflowFieldInput';
+
+const VARIANT_LABEL_KEYS: Record<WorkflowGeneratorVariant, string> = {
+ float_generator_arithmetic_sequence: 'nodes.arithmeticSequence',
+ float_generator_linear_distribution: 'nodes.linearDistribution',
+ float_generator_parse_string: 'nodes.parseString',
+ float_generator_random_distribution_uniform: 'nodes.uniformRandomDistribution',
+ image_generator_images_from_board: 'nodes.generatorImagesFromBoard',
+ integer_generator_arithmetic_sequence: 'nodes.arithmeticSequence',
+ integer_generator_linear_distribution: 'nodes.linearDistribution',
+ integer_generator_parse_string: 'nodes.parseString',
+ integer_generator_random_distribution_uniform: 'nodes.uniformRandomDistribution',
+ string_generator_dynamic_prompts_combinatorial: 'nodes.dynamicPromptsCombinatorial',
+ string_generator_dynamic_prompts_random: 'nodes.dynamicPromptsRandom',
+ string_generator_parse_string: 'nodes.parseString',
+};
+
+/** Dynamic prompt expansion is bounded server-side; the legacy editor capped the request at this. */
+const DYNAMIC_PROMPTS_MAX = 1000;
+const FILE_SIZE_LIMIT = 128 * 1024;
+const PREVIEW_ITEM_LIMIT = 200;
+const PREVIEW_DEBOUNCE_MS = 300;
+const SELECT_VALUE_TEXT_PROPS = { placeholder: 'Select…' };
+const HIDDEN_FILE_INPUT_STYLE = { display: 'none' } as const;
+const CATEGORY_OPTIONS = [
+ { labelKey: 'nodes.generatorCategoryImages', value: 'images' },
+ { labelKey: 'nodes.generatorCategoryAssets', value: 'assets' },
+] as const;
+
+const toFiniteNumber = (raw: string): number | undefined => {
+ if (raw.trim() === '') {
+ return undefined;
+ }
+
+ const parsed = Number(raw);
+
+ return Number.isFinite(parsed) ? parsed : undefined;
+};
+
+/** Chromium steps a focused number input on wheel and swallows the scroll; unfocused, the panel scrolls instead. */
+const blurOnWheel = (event: WheelEvent<HTMLInputElement>) => event.currentTarget.blur();
+
+/**
+ * One labelled number in a settings row. Committed as typed, like the scalar field inputs: an empty or partial
+ * entry keeps the last committed number, so a setting never silently becomes NaN.
+ */
+const NumberSetting = ({
+ ariaLabel,
+ disabled,
+ id,
+ integer,
+ label,
+ max,
+ min,
+ value,
+ onCommit,
+}: {
+ /** The accessible name when the visible label lives elsewhere (the seed row's checkbox). */
+ ariaLabel?: string;
+ disabled?: boolean;
+ id: string;
+ integer: boolean;
+ label: string;
+ max?: number;
+ min?: number;
+ value: number;
+ onCommit: (value: number) => void;
+}) => {
+ const [draft, setDraft] = useState<string | null>(null);
+ const onChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const text = event.currentTarget.value;
+ const next = toFiniteNumber(text);
+
+ setDraft(text);
+
+ // Out-of-range entries stay on screen as a draft but never commit: a count of 0 would make the stored
+ // value unreadable and the widget would lose the variant.
+ if (
+ next !== undefined &&
+ (!integer || Number.isInteger(next)) &&
+ (min === undefined || next >= min) &&
+ (max === undefined || next <= max)
+ ) {
+ onCommit(next);
+ }
+ },
+ [integer, max, min, onCommit]
+ );
+ const onBlur = useCallback(() => setDraft(null), []);
+
+ return (
+ <HStack gap="1" minW="0">
+ {label ? (
+ <chakra.label color="fg.subtle" flexShrink={0} fontSize="2xs" htmlFor={id} minW="10">
+ {label}
+ </chakra.label>
+ ) : null}
+ <Input
+ aria-label={ariaLabel}
+ className="nodrag"
+ disabled={disabled}
+ id={id}
+ max={max}
+ min={min}
+ size="2xs"
+ step={integer ? 1 : 'any'}
+ type="number"
+ value={draft ?? String(value)}
+ onBlur={onBlur}
+ onChange={onChange}
+ onWheel={blurOnWheel}
+ />
+ </HStack>
+ );
+};
+
+/** The seed row: unchecked draws fresh values every time, checked pins them to a seed. */
+const SeedSetting = ({
+ id,
+ seed,
+ onCommit,
+}: {
+ id: string;
+ seed: number | null;
+ onCommit: (seed: number | null) => void;
+}) => {
+ const { t } = useTranslation();
+ const onCheckedChange = useCallback(
+ (event: { checked: boolean | 'indeterminate' }) => onCommit(event.checked === true ? 0 : null),
+ [onCommit]
+ );
+
+ return (
+ <HStack gap="2" minW="0">
+ <Checkbox.Root checked={seed !== null} colorPalette="accent" size="xs" onCheckedChange={onCheckedChange}>
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label fontSize="2xs">{t('nodes.generatorSeed')}</Checkbox.Label>
+ </Checkbox.Root>
+ <NumberSetting
+ ariaLabel={t('nodes.generatorSeed')}
+ disabled={seed === null}
+ id={`${id}-seed`}
+ integer
+ label=""
+ min={0}
+ value={seed ?? 0}
+ onCommit={onCommit}
+ />
+ </HStack>
+ );
+};
+
+/** The multi-line source of a parse-string or dynamic-prompt generator, with the legacy load-from-file action. */
+const InputSetting = ({ id, value, onCommit }: { id: string; value: string; onCommit: (value: string) => void }) => {
+ const { t } = useTranslation();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const onTextChange = useCallback(
+ (event: ChangeEvent<HTMLTextAreaElement>) => onCommit(event.currentTarget.value),
+ [onCommit]
+ );
+ const onLoadClick = useCallback(() => fileInputRef.current?.click(), []);
+ const onFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+
+ event.currentTarget.value = '';
+
+ if (!file) {
+ return;
+ }
+
+ if (file.size > FILE_SIZE_LIMIT) {
+ toaster.create({ title: t('nodes.generatorFileTooLarge'), type: 'error' });
+ return;
+ }
+
+ void file.text().then(onCommit);
+ },
+ [onCommit, t]
+ );
+
+ return (
+ <Stack gap="1">
+ <HStack justify="space-between">
+ <chakra.label color="fg.subtle" fontSize="2xs" htmlFor={id}>
+ {t('nodes.generatorInput')}
+ </chakra.label>
+ <Button className="nodrag" size="2xs" variant="ghost" onClick={onLoadClick}>
+ <UploadIcon />
+ {t('nodes.generatorLoadFromFile')}
+ </Button>
+ <input
+ ref={fileInputRef}
+ accept=".txt,.csv,text/plain,text/csv"
+ aria-label={t('nodes.generatorLoadFromFile')}
+ style={HIDDEN_FILE_INPUT_STYLE}
+ type="file"
+ onChange={onFileChange}
+ />
+ </HStack>
+ <Textarea
+ className="nodrag nowheel"
+ fontFamily="mono"
+ id={id}
+ resize="none"
+ rows={4}
+ size="xs"
+ value={value}
+ onChange={onTextChange}
+ />
+ </Stack>
+ );
+};
+
+const BoardSetting = ({
+ boardId,
+ id,
+ onCommit,
+}: {
+ boardId: string | undefined;
+ id: string;
+ onCommit: (boardId: string | undefined) => void;
+}) => {
+ const { t } = useTranslation();
+ const boards = useQuery(galleryBoardsOptions());
+ const isMissing =
+ boardId !== undefined && boards.data !== undefined && !boards.data.some((board) => board.id === boardId);
+ const options = useMemo(() => {
+ const base = (boards.data ?? []).map((board) => ({ label: board.name, value: board.id }));
+
+ return isMissing && boardId !== undefined
+ ? [{ label: t('nodes.generatorBoardMissing'), value: boardId }, ...base]
+ : base;
+ }, [boardId, boards.data, isMissing, t]);
+ const onValueChange = useCallback((value: string) => onCommit(value), [onCommit]);
+
+ return (
+ <Combobox
+ aria-label={t('nodes.generatorBoard')}
+ className="nodrag nowheel"
+ id={id}
+ invalid={isMissing}
+ noResultsText={t('nodes.generatorSelectBoard')}
+ options={options}
+ searchPlaceholder={boards.isLoading ? t('nodes.recordListLoading') : t('nodes.generatorSelectBoard')}
+ value={boardId ?? null}
+ onValueChange={onValueChange}
+ />
+ );
+};
+
+const formatItem = (item: unknown): string =>
+ typeof item === 'number' ? String(Math.round(item * 100) / 100) : typeof item === 'string' ? item : '';
+
+const PreviewBox = ({ children, tone = 'fg.muted' }: { children: string; tone?: string }) => (
+ <Box
+ bg="bg.subtle"
+ className="nowheel"
+ color={tone}
+ fontFamily="mono"
+ fontSize="2xs"
+ maxH="32"
+ overflowY="auto"
+ px="1.5"
+ py="1"
+ rounded="sm"
+ whiteSpace="pre-wrap"
+ wordBreak="break-word"
+ >
+ {children}
+ </Box>
+);
+
+const AsyncPreview = ({ request }: { request: WorkflowAsyncGeneratorRequest }) => {
+ const { t } = useTranslation();
+ // Both request kinds select into the same result shape; the union of option types is wider than useQuery wants.
+ // Query identity comes from the key hash, so a fresh options object per render costs nothing.
+ const query = useQuery(
+ getWorkflowGeneratorQueryOptions(request) as unknown as UseQueryOptions<
+ unknown,
+ Error,
+ WorkflowGeneratorQueryResult
+ >
+ );
+
+ if (query.isError) {
+ return <PreviewBox tone="fg.error">{t('nodes.generatorPreviewFailed')}</PreviewBox>;
+ }
+
+ if (!query.data) {
+ return <PreviewBox>{t('nodes.generatorLoading')}</PreviewBox>;
+ }
+
+ if (query.data.error) {
+ return <PreviewBox tone="fg.error">{query.data.error}</PreviewBox>;
+ }
+
+ const items = query.data.items;
+
+ if (items.length === 0) {
+ return <PreviewBox>{`<${t('nodes.generatorNoValues')}>`}</PreviewBox>;
+ }
+
+ return (
+ <PreviewBox>
+ {request.kind === 'boardImages'
+ ? `<${t('nodes.generatorImages', { count: items.length })}>`
+ : items.slice(0, PREVIEW_ITEM_LIMIT).map(formatItem).join(', ') +
+ (items.length > PREVIEW_ITEM_LIMIT
+ ? ` … ${t('nodes.generatorPreviewTruncated', { count: items.length })}`
+ : '')}
+ </PreviewBox>
+ );
+};
+
+/**
+ * What the generator will produce. Synchronous variants derive in render; async ones query, on the value as it
+ * stood before the current burst of typing until the burst settles.
+ */
+const GeneratorPreview = ({
+ generator,
+ settled,
+}: {
+ generator: WorkflowGeneratorValue;
+ settled: WorkflowGeneratorValue;
+}) => {
+ const { t } = useTranslation();
+ const requested = getWorkflowGeneratorRequestedCount(settled);
+
+ // Never build an oversized list for a preview; readiness refuses it on the same rule.
+ if (requested !== null && requested > WORKFLOW_BATCH_MAX_ITEMS) {
+ return (
+ <PreviewBox tone="fg.error">
+ {t('nodes.generatorTooMany', { max: WORKFLOW_BATCH_MAX_ITEMS.toLocaleString() })}
+ </PreviewBox>
+ );
+ }
+
+ if (isRandomWorkflowGeneratorValue(generator)) {
+ const count = 'count' in generator ? generator.count : 0;
+
+ return <PreviewBox>{`<${t('nodes.generatorNRandomValues', { count })}>`}</PreviewBox>;
+ }
+
+ const resolution = resolveWorkflowGeneratorValue(settled);
+
+ if (resolution.kind === 'async') {
+ return <AsyncPreview request={resolution.request} />;
+ }
+
+ if (resolution.items.length === 0) {
+ return <PreviewBox>{`<${t('nodes.generatorNoValues')}>`}</PreviewBox>;
+ }
+
+ return (
+ <PreviewBox>
+ {resolution.items.slice(0, PREVIEW_ITEM_LIMIT).map(formatItem).join(', ') +
+ (resolution.items.length > PREVIEW_ITEM_LIMIT
+ ? ` … ${t('nodes.generatorPreviewTruncated', { count: resolution.items.length })}`
+ : '')}
+ </PreviewBox>
+ );
+};
+
+/** The generator widget: a variant picker, the variant's settings, and a preview of what it yields. */
+export const GeneratorFieldInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {
+ const { t } = useTranslation();
+ const typeName = template.type.name;
+ const parsed = parseWorkflowGeneratorValue(typeName, value);
+ // An unreadable stored value still shows its own variant's defaults, so the user's variant choice survives.
+ const storedVariant = typeof value === 'object' && value !== null ? (value as { type?: unknown }).type : undefined;
+ const generator =
+ parsed ??
+ (typeof storedVariant === 'string' &&
+ isWorkflowGeneratorVariant(storedVariant) &&
+ (WORKFLOW_GENERATOR_VARIANTS as Record<string, readonly string[]>)[typeName]?.includes(storedVariant)
+ ? getWorkflowGeneratorVariantDefaults(storedVariant)
+ : getDefaultWorkflowGeneratorValue(typeName));
+ const variantCollection = useMemo(() => {
+ const variants =
+ (WORKFLOW_GENERATOR_VARIANTS as Record<string, readonly WorkflowGeneratorVariant[]>)[typeName] ?? [];
+
+ return createListCollection({
+ items: variants.map((variant) => ({ label: t(VARIANT_LABEL_KEYS[variant]), value: variant })),
+ });
+ }, [t, typeName]);
+ const categoryCollection = useMemo(
+ () =>
+ createListCollection({
+ items: CATEGORY_OPTIONS.map((option) => ({ label: t(option.labelKey), value: option.value })),
+ }),
+ [t]
+ );
+ const prefix = id ?? 'generator';
+
+ // A typing burst previews the value it started from until it settles; undo and picks land immediately.
+ const [held, setHeld] = useState<WorkflowGeneratorValue | null>(null);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useMountEffect(() => () => {
+ if (timerRef.current !== null) {
+ clearTimeout(timerRef.current);
+ }
+ });
+
+ const commit = useCallback(
+ (next: WorkflowGeneratorValue, { debounce = false } = {}) => {
+ if (debounce && generator) {
+ if (timerRef.current === null) {
+ setHeld(generator);
+ } else {
+ clearTimeout(timerRef.current);
+ }
+
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+ setHeld(null);
+ }, PREVIEW_DEBOUNCE_MS);
+ }
+
+ // A legacy resolved override would hide the edit; drop it whenever the settings change.
+ const { values: _values, ...rest } = next as WorkflowGeneratorValue & { values?: number[] };
+
+ onChange(rest);
+ },
+ [generator, onChange]
+ );
+ const setProperty = useCallback(
+ (key: string, propertyValue: unknown, debounce = false) => {
+ if (generator) {
+ commit({ ...generator, [key]: propertyValue } as WorkflowGeneratorValue, { debounce });
+ }
+ },
+ [commit, generator]
+ );
+ const onVariantChange = useCallback(
+ ({ value: next }: { value: string[] }) => {
+ const variant = next[0] as WorkflowGeneratorVariant | undefined;
+
+ if (variant) {
+ commit(getWorkflowGeneratorVariantDefaults(variant));
+ }
+ },
+ [commit]
+ );
+ const onCategoryChange = useCallback(
+ ({ value: next }: { value: string[] }) => setProperty('category', next[0]),
+ [setProperty]
+ );
+ const onBoardChange = useCallback((boardId: string | undefined) => setProperty('board_id', boardId), [setProperty]);
+ const onInputChange = useCallback((text: string) => setProperty('input', text, true), [setProperty]);
+ const onSplitOnChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => setProperty('splitOn', event.currentTarget.value, true),
+ [setProperty]
+ );
+ const onSeedChange = useCallback((seed: number | null) => setProperty('seed', seed), [setProperty]);
+ const number = (key: string) => (next: number) => setProperty(key, next, true);
+ const variantType = generator?.type ?? '';
+ const variantValue = useMemo(() => [variantType], [variantType]);
+ const category = generator?.type === 'image_generator_images_from_board' ? generator.category : 'images';
+ const categoryValue = useMemo(() => [category], [category]);
+
+ if (!generator) {
+ return null;
+ }
+
+ return (
+ <Stack gap="1.5" w="full">
+ <Select
+ aria-label={template.title}
+ className="nodrag"
+ collection={variantCollection}
+ invalid={invalid}
+ size="xs"
+ value={variantValue}
+ valueTextProps={SELECT_VALUE_TEXT_PROPS}
+ w="full"
+ onValueChange={onVariantChange}
+ />
+ {generator.type === 'float_generator_arithmetic_sequence' ||
+ generator.type === 'integer_generator_arithmetic_sequence' ? (
+ <HStack gap="2">
+ <NumberSetting
+ id={`${prefix}-start`}
+ integer={generator.type.startsWith('integer')}
+ label={t('nodes.generatorStart')}
+ value={generator.start}
+ onCommit={number('start')}
+ />
+ <NumberSetting
+ id={`${prefix}-step`}
+ integer={generator.type.startsWith('integer')}
+ label={t('nodes.generatorStep')}
+ value={generator.step}
+ onCommit={number('step')}
+ />
+ <NumberSetting
+ id={`${prefix}-count`}
+ integer
+ label={t('nodes.generatorCount')}
+ min={1}
+ value={generator.count}
+ onCommit={number('count')}
+ />
+ </HStack>
+ ) : null}
+ {generator.type === 'float_generator_linear_distribution' ||
+ generator.type === 'integer_generator_linear_distribution' ? (
+ <HStack gap="2">
+ <NumberSetting
+ id={`${prefix}-start`}
+ integer={generator.type.startsWith('integer')}
+ label={t('nodes.generatorStart')}
+ value={generator.start}
+ onCommit={number('start')}
+ />
+ <NumberSetting
+ id={`${prefix}-end`}
+ integer={generator.type.startsWith('integer')}
+ label={t('nodes.generatorEnd')}
+ value={generator.end}
+ onCommit={number('end')}
+ />
+ <NumberSetting
+ id={`${prefix}-count`}
+ integer
+ label={t('nodes.generatorCount')}
+ min={1}
+ value={generator.count}
+ onCommit={number('count')}
+ />
+ </HStack>
+ ) : null}
+ {generator.type === 'float_generator_random_distribution_uniform' ||
+ generator.type === 'integer_generator_random_distribution_uniform' ? (
+ <Stack gap="1.5">
+ <HStack gap="2">
+ <NumberSetting
+ id={`${prefix}-min`}
+ integer={generator.type.startsWith('integer')}
+ label={t('nodes.generatorMin')}
+ value={generator.min}
+ onCommit={number('min')}
+ />
+ <NumberSetting
+ id={`${prefix}-max`}
+ integer={generator.type.startsWith('integer')}
+ label={t('nodes.generatorMax')}
+ value={generator.max}
+ onCommit={number('max')}
+ />
+ <NumberSetting
+ id={`${prefix}-count`}
+ integer
+ label={t('nodes.generatorCount')}
+ min={1}
+ value={generator.count}
+ onCommit={number('count')}
+ />
+ </HStack>
+ <SeedSetting id={prefix} seed={generator.seed} onCommit={onSeedChange} />
+ </Stack>
+ ) : null}
+ {generator.type === 'float_generator_parse_string' ||
+ generator.type === 'integer_generator_parse_string' ||
+ generator.type === 'string_generator_parse_string' ? (
+ <Stack gap="1.5">
+ <HStack gap="1">
+ <chakra.label color="fg.subtle" flexShrink={0} fontSize="2xs" htmlFor={`${prefix}-split-on`}>
+ {t('nodes.splitOn')}
+ </chakra.label>
+ <Input
+ className="nodrag"
+ id={`${prefix}-split-on`}
+ size="2xs"
+ value={generator.splitOn}
+ onChange={onSplitOnChange}
+ />
+ </HStack>
+ <InputSetting id={`${prefix}-input`} value={generator.input} onCommit={onInputChange} />
+ </Stack>
+ ) : null}
+ {generator.type === 'string_generator_dynamic_prompts_random' ? (
+ <Stack gap="1.5">
+ <HStack gap="2">
+ <NumberSetting
+ id={`${prefix}-count`}
+ integer
+ label={t('nodes.generatorCount')}
+ max={DYNAMIC_PROMPTS_MAX}
+ min={1}
+ value={generator.count}
+ onCommit={number('count')}
+ />
+ <SeedSetting id={prefix} seed={generator.seed} onCommit={onSeedChange} />
+ </HStack>
+ <InputSetting id={`${prefix}-input`} value={generator.input} onCommit={onInputChange} />
+ </Stack>
+ ) : null}
+ {generator.type === 'string_generator_dynamic_prompts_combinatorial' ? (
+ <Stack gap="1.5">
+ <NumberSetting
+ id={`${prefix}-max-prompts`}
+ integer
+ label={t('nodes.generatorMaxPrompts')}
+ max={DYNAMIC_PROMPTS_MAX}
+ min={1}
+ value={generator.maxPrompts}
+ onCommit={number('maxPrompts')}
+ />
+ <InputSetting id={`${prefix}-input`} value={generator.input} onCommit={onInputChange} />
+ </Stack>
+ ) : null}
+ {generator.type === 'image_generator_images_from_board' ? (
+ <Stack gap="1.5">
+ <BoardSetting boardId={generator.board_id} id={`${prefix}-board`} onCommit={onBoardChange} />
+ <Select
+ aria-label={t('nodes.generatorImagesCategory')}
+ className="nodrag"
+ collection={categoryCollection}
+ size="xs"
+ value={categoryValue}
+ valueTextProps={SELECT_VALUE_TEXT_PROPS}
+ w="full"
+ onValueChange={onCategoryChange}
+ />
+ </Stack>
+ ) : null}
+ <GeneratorPreview generator={generator} settled={held ?? generator} />
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
index e53eaa9240..48fa2f7965 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
@@ -1937,3 +1937,186 @@ describe('WorkflowFieldInput record pickers', () => {
await vi.waitFor(() => expect(option('Helpful')).toBeDefined());
});
});
+
+describe('WorkflowFieldInput generators', () => {
+ const FLOAT_GENERATOR = fullTemplate('FloatField', {
+ default: { count: 10, start: 0, step: 0.1, type: 'float_generator_arithmetic_sequence' },
+ input: 'direct',
+ title: 'Generator Type',
+ type: { batch: false, cardinality: 'SINGLE', name: 'FloatGeneratorField' },
+ });
+ const STRING_GENERATOR = fullTemplate('StringField', {
+ default: { input: 'foo,bar,baz,qux', splitOn: ',', type: 'string_generator_parse_string' },
+ input: 'direct',
+ title: 'Generator Type',
+ type: { batch: false, cardinality: 'SINGLE', name: 'StringGeneratorField' },
+ });
+ const IMAGE_GENERATOR = fullTemplate('StringField', {
+ default: { category: 'images', type: 'image_generator_images_from_board' },
+ input: 'direct',
+ title: 'Generator Type',
+ type: { batch: false, cardinality: 'SINGLE', name: 'ImageGeneratorField' },
+ });
+ let renderCount = 0;
+ const renderGenerator = async (template: FieldInputTemplate, initial: unknown) => {
+ const onCommit = vi.fn();
+
+ renderCount += 1;
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <StatefulField key={renderCount} initial={initial} template={template} onCommit={onCommit} />
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
+ });
+ await vi.waitFor(() => expect(host.querySelector('[data-scope="select"][data-part="trigger"]')).not.toBeNull());
+
+ return { onCommit };
+ };
+ const numberInput = (suffix: string) =>
+ host.querySelector<HTMLInputElement>(`input[type="number"][id$="${suffix}"]`)!;
+ const selectVariant = async (label: string) => {
+ await act(() => userEvent.click(host.querySelector('[data-scope="select"][data-part="trigger"]')!));
+ const item = Array.from(document.querySelectorAll<HTMLElement>('[data-scope="select"][data-part="item"]')).find(
+ (candidate) => candidate.textContent?.includes(label)
+ )!;
+ await act(() => userEvent.click(item));
+ };
+
+ it('previews an arithmetic sequence, commits edited settings as typed, and resets on a variant switch', async () => {
+ const { onCommit } = await renderGenerator(FLOAT_GENERATOR, {
+ count: 3,
+ start: 1,
+ step: 0.5,
+ type: 'float_generator_arithmetic_sequence',
+ });
+
+ expect(host.textContent).toContain('1, 1.5, 2');
+
+ await act(() => numberInput('-count').focus());
+ await act(() => userEvent.keyboard('{Control>}a{/Control}4'));
+ expect(onCommit).toHaveBeenLastCalledWith({
+ count: 4,
+ start: 1,
+ step: 0.5,
+ type: 'float_generator_arithmetic_sequence',
+ });
+ // The preview holds the pre-edit value through the typing burst, then settles.
+ await vi.waitFor(() => expect(host.textContent).toContain('1, 1.5, 2, 2.5'), { timeout: 2000 });
+
+ await selectVariant('nodes.parseString');
+ expect(onCommit).toHaveBeenLastCalledWith({
+ input: '0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1',
+ splitOn: ',',
+ type: 'float_generator_parse_string',
+ });
+ });
+
+ it('shows a random draw as a count until a seed pins it, and refuses a count the queue cannot take', async () => {
+ const { onCommit } = await renderGenerator(FLOAT_GENERATOR, {
+ count: 4,
+ max: 9,
+ min: 2,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ });
+
+ expect(host.textContent).toContain('<nodes.generatorNRandomValues>');
+ expect(numberInput('-seed').disabled).toBe(true);
+ expect(numberInput('-seed').getAttribute('aria-label')).toBe('nodes.generatorSeed');
+
+ // A count below its minimum stays a draft: nothing commits, so the variant and its settings survive.
+ await act(() => numberInput('-count').focus());
+ await act(() => userEvent.keyboard('{Control>}a{/Control}0'));
+ expect(numberInput('-count').value).toBe('0');
+ expect(onCommit).not.toHaveBeenCalled();
+ expect(numberInput('-min').value).toBe('2');
+ await act(() => userEvent.keyboard('5'));
+ expect(onCommit).toHaveBeenLastCalledWith({
+ count: 5,
+ max: 9,
+ min: 2,
+ seed: null,
+ type: 'float_generator_random_distribution_uniform',
+ });
+
+ await act(() => userEvent.click(host.querySelector('[data-scope="checkbox"][data-part="control"]')!));
+ expect(onCommit).toHaveBeenLastCalledWith({
+ count: 5,
+ max: 9,
+ min: 2,
+ seed: 0,
+ type: 'float_generator_random_distribution_uniform',
+ });
+ expect(numberInput('-seed').disabled).toBe(false);
+ expect(host.textContent).not.toContain('<nodes.generatorNRandomValues>');
+ expect(host.textContent).toMatch(/\d+(\.\d+)?, \d+(\.\d+)?/);
+
+ await act(() => numberInput('-count').focus());
+ await act(() => userEvent.keyboard('{Control>}a{/Control}20000'));
+ await vi.waitFor(() => expect(host.textContent).toContain('nodes.generatorTooMany'), { timeout: 2000 });
+ });
+
+ it('loads a parse-string source from a file and previews the split values', async () => {
+ const { onCommit } = await renderGenerator(STRING_GENERATOR, {
+ input: 'a|b',
+ splitOn: '|',
+ type: 'string_generator_parse_string',
+ });
+
+ expect(host.textContent).toContain('a, b');
+
+ const fileInput = host.querySelector<HTMLInputElement>('input[type="file"]')!;
+
+ await act(() => userEvent.upload(fileInput, new File(['x|y|z'], 'values.txt', { type: 'text/plain' })));
+ await vi.waitFor(() =>
+ expect(onCommit).toHaveBeenLastCalledWith({ input: 'x|y|z', splitOn: '|', type: 'string_generator_parse_string' })
+ );
+ await vi.waitFor(() => expect(host.textContent).toContain('x, y, z'), { timeout: 2000 });
+
+ const toast = vi.spyOn(toaster, 'create');
+
+ await act(() =>
+ userEvent.upload(fileInput, new File([new Uint8Array(129 * 1024)], 'big.txt', { type: 'text/plain' }))
+ );
+ await vi.waitFor(() => expect(toast).toHaveBeenCalledWith({ title: 'nodes.generatorFileTooLarge', type: 'error' }));
+ expect(onCommit).toHaveBeenLastCalledWith({ input: 'x|y|z', splitOn: '|', type: 'string_generator_parse_string' });
+ toast.mockRestore();
+ });
+
+ it('previews dynamic prompts from the backend and marks a board the gallery no longer has', async () => {
+ workflowApiMock.apiFetchJson.mockImplementation((path: string) =>
+ path.includes('dynamicprompts')
+ ? Promise.resolve({ error: null, prompts: ['a cute dog', 'a cute cat'] })
+ : Promise.resolve([
+ {
+ board_id: 'b1',
+ board_name: 'Portraits',
+ image_count: 2,
+ asset_count: 0,
+ video_count: 0,
+ asset_video_count: 0,
+ archived: false,
+ },
+ ])
+ );
+ await renderGenerator(STRING_GENERATOR, {
+ input: 'a cute {dog|cat}',
+ maxPrompts: 5,
+ type: 'string_generator_dynamic_prompts_combinatorial',
+ });
+ await vi.waitFor(() => expect(host.textContent).toContain('a cute dog, a cute cat'));
+
+ await renderGenerator(IMAGE_GENERATOR, {
+ board_id: 'gone',
+ category: 'assets',
+ type: 'image_generator_images_from_board',
+ });
+ await vi.waitFor(() =>
+ expect(host.querySelector<HTMLInputElement>('input[role="combobox"]')?.value).toBe('nodes.generatorBoardMissing')
+ );
+ expect(host.querySelector('input[role="combobox"]')?.getAttribute('aria-invalid')).toBe('true');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index 2a16006c04..892bfe84a2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -64,6 +64,7 @@ import {
getResolvedWorkflowEdges,
isLoraFieldCollectionEntry,
isWorkflowCollectionItemValid,
+ isWorkflowGeneratorFieldTypeName,
toLoraFieldCollectionList,
} from '@features/workflow/utility';
import { planSeedSubmission, type SeedMode, wrapSeed } from '@platform/core/seed';
@@ -121,6 +122,10 @@ const RECORD_PICKER_FALLBACK = (
Loading…
</Button>
);
+// Generator settings load with their node; a plain workflow never pays for them.
+const GeneratorFieldInput = lazy(() =>
+ import('./GeneratorFieldInput').then((module) => ({ default: module.GeneratorFieldInput }))
+);
// Record pickers load with their node so the system-prompt query stays out of the editor's boot graph.
const StylePresetInput = lazy(() =>
@@ -1863,6 +1868,14 @@ export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
}
}
+ if (isWorkflowGeneratorFieldTypeName(props.template.type.name)) {
+ return (
+ <Suspense fallback={RECORD_PICKER_FALLBACK}>
+ <GeneratorFieldInput {...props} />
+ </Suspense>
+ );
+ }
+
switch (props.template.type.name) {
case 'SavedWorkflowField':
return <SavedWorkflowInput {...props} />;
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx
index d969fe96bf..6f3f71fef7 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx
@@ -15,6 +15,8 @@ import {
isDirectInputField,
isShuffleableField,
isWorkflowFieldValueDefault,
+ getWorkflowBatchGroupId,
+ isWorkflowBatchNodeType,
} from '@features/workflow/utility';
import { FieldLabel, IconButton, Tooltip } from '@platform/ui';
import { DicesIcon, RotateCcwIcon } from 'lucide-react';
@@ -23,6 +25,7 @@ import { useTranslation } from 'react-i18next';
/** Resolves a form element's node, field instance, and input template against the document. */
export const useNodeFieldBinding = (element: NodeFieldFormElement, projectGraph: ProjectGraphState) => {
+ const { t } = useTranslation();
const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);
const { fieldName, nodeId } = element.data.fieldIdentifier;
const node = projectGraph.nodes.find((candidate) => candidate.id === nodeId);
@@ -31,8 +34,13 @@ export const useNodeFieldBinding = (element: NodeFieldFormElement, projectGraph:
? (invocationNode.data.dynamicInputTemplates?.[fieldName] ?? templates[invocationNode.data.type]?.inputs[fieldName])
: undefined;
const instance = invocationNode?.data.inputs[fieldName];
+ const groupId =
+ invocationNode && isWorkflowBatchNodeType(invocationNode.data.type)
+ ? getWorkflowBatchGroupId(invocationNode)
+ : null;
+ const groupSuffix = groupId === null ? '' : ` (${groupId === 'None' ? t('nodes.noBatchGroup') : groupId})`;
const nodeContext = invocationNode
- ? invocationNode.data.label || templates[invocationNode.data.type]?.title || invocationNode.data.type
+ ? `${invocationNode.data.label || templates[invocationNode.data.type]?.title || invocationNode.data.type}${groupSuffix}`
: '';
return { fieldName, instance, invocationNode, nodeContext, nodeId, template };
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx
index 92c0a81d09..bb058d57d7 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx
@@ -15,7 +15,12 @@ import {
useWorkflowNodeExecutionState,
useWorkflowProjectSelector,
} from '@features/workflow/ui/WorkflowUiContext';
-import { formatOutputFieldValue, getNodeUpdateStatus } from '@features/workflow/utility';
+import {
+ formatOutputFieldValue,
+ getNodeUpdateStatus,
+ getWorkflowBatchGroupId,
+ isWorkflowBatchNodeType,
+} from '@features/workflow/utility';
import { Button, JsonPreview, Scrollable, Tabs } from '@platform/ui';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -40,6 +45,17 @@ const DetailRow = ({ label, value }: { label: string; value: string }) => (
const JsonBlock = ({ label, value }: { label: string; value: unknown }) => <JsonPreview label={label} value={value} />;
+/** " (Group 1)" or " (no group)" after a batch node's title; empty for every other node. */
+const getBatchGroupSuffix = (node: WorkflowInvocationNode, t: ReturnType<typeof useTranslation>['t']): string => {
+ if (!isWorkflowBatchNodeType(node.data.type)) {
+ return '';
+ }
+
+ const groupId = getWorkflowBatchGroupId(node);
+
+ return ` (${groupId === 'None' ? t('nodes.noBatchGroup') : groupId})`;
+};
+
/** The version row's action: update in place when the template allows it, otherwise say why not. */
const NodeUpdateRow = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate }) => {
const { t } = useTranslation();
@@ -93,7 +109,10 @@ const DetailsTab = ({ node, template }: { node: WorkflowInvocationNode; template
return (
<Stack gap="2">
- <DetailRow label={t('widgets.workflow.title')} value={node.data.label || template?.title || node.data.type} />
+ <DetailRow
+ label={t('widgets.workflow.title')}
+ value={`${node.data.label || template?.title || node.data.type}${getBatchGroupSuffix(node, t)}`}
+ />
<DetailRow label={t('widgets.workflow.type')} value={node.data.type} />
<DetailRow label={t('widgets.workflow.version')} value={node.data.version} />
{template ? <NodeUpdateRow node={node} template={template} /> : null}
diff --git a/invokeai/frontend/webv2/src/features/workflow/utility.ts b/invokeai/frontend/webv2/src/features/workflow/utility.ts
index cea91a2ae1..e08296a4ff 100644
--- a/invokeai/frontend/webv2/src/features/workflow/utility.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/utility.ts
@@ -1,3 +1,4 @@
+export * from './core/batch';
export * from './core/connectorHandles';
export * from './core/connectors';
export * from './core/document';
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index 1e5d363908..1582c3283e 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -17,6 +17,7 @@ import {
getGenerationValidationReasons,
isSupportedGenerateModel,
normalizeGenerateWidgetValues,
+ sanitizeBatchCount,
} from '@features/generation/settings';
import { getUpscaleValidationReasons, normalizeUpscaleWidgetValues } from '@features/upscale';
import { getVideoWidgetValidationReasons, normalizeVideoWidgetValues } from '@features/video';
@@ -195,7 +196,11 @@ export const resolveInvocationRouteInput = (
const sourceWidgetId = sourceWidgetIds[sourceId];
// Route-rendering surfaces subscribe to templates because readiness reads them imperatively.
const projectGraphReadiness =
- sourceId === 'workflow' ? getProjectGraphReadiness(input.projectGraph, getInvocationTemplatesSnapshot()) : null;
+ sourceId === 'workflow'
+ ? getProjectGraphReadiness(input.projectGraph, getInvocationTemplatesSnapshot(), {
+ batchCount: sanitizeBatchCount(input.workflowValues.batchCount),
+ })
+ : null;
const validationReasons: Array<string | ForLoopValidationReason> = [];
if (!isInvocationSourceAvailable(sourceId)) {
@@ -272,6 +277,7 @@ export const resolveInvocationRouteInput = (
sourceValid,
validationMessage: validationReasons[0],
validationReasons,
+ ...(projectGraphReadiness?.batch ? { workflowBatch: projectGraphReadiness.batch } : {}),
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
index 095190a739..95bce00e28 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
@@ -21,6 +21,8 @@ export interface ResolvedInvocationRoute extends InvocationRoute {
validationMessage?: string | ForLoopValidationReason;
/** Every reason the route cannot run right now (legacy `reasonsWhyCannotEnqueue` equivalent). */
validationReasons: Array<string | ForLoopValidationReason>;
+ /** Present when the workflow has batch nodes; size is null until an async generator resolves on invoke. */
+ workflowBatch?: { size: number | null };
}
export interface InvocationControllerState extends InvocationRoute {
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
new file mode 100644
index 0000000000..0e616129db
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
@@ -0,0 +1,244 @@
+import type { InvocationRoute } from '@workbench/invocationContracts';
+
+import { captureAccountScope } from '@platform/state/accountLifecycle';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const templatesMock = vi.hoisted(() => ({
+ snapshot: { error: null, status: 'idle', templates: {} } as {
+ error: string | null;
+ status: 'idle' | 'loading' | 'loaded' | 'error';
+ templates: Record<string, unknown>;
+ },
+}));
+const generatorsMock = vi.hoisted(() => ({ resolveWorkflowGenerators: vi.fn() }));
+
+vi.mock('@features/workflow/react', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getInvocationTemplatesSnapshot: () => templatesMock.snapshot,
+}));
+vi.mock('@features/workflow/queries', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ resolveWorkflowGenerators: generatorsMock.resolveWorkflowGenerators,
+}));
+
+import { resolveInvocationRoute } from './invocation';
+import { submitResolvedInvocation } from './invocationSubmit';
+import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
+
+const getActiveProject = (state: ReturnType<typeof createInitialWorkbenchState>) => {
+ const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);
+
+ if (!project) {
+ throw new Error('No active project');
+ }
+
+ return project;
+};
+import { createWorkbenchStore } from './workbenchStore';
+
+const field = (name: string, typeName: string, overrides: Record<string, unknown> = {}) => ({
+ default: undefined,
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ fieldKind: 'input',
+ input: 'any',
+ maximum: null,
+ minimum: null,
+ multipleOf: null,
+ name,
+ options: null,
+ required: true,
+ title: name,
+ type: { batch: false, cardinality: 'SINGLE', name: typeName },
+ uiChoiceLabels: null,
+ uiComponent: null,
+ uiHidden: false,
+ uiModelBase: null,
+ uiModelFormat: null,
+ uiModelType: null,
+ uiOrder: null,
+ ...overrides,
+});
+const template = (type: string, inputs: Record<string, unknown>) => ({
+ category: 'test',
+ classification: 'stable',
+ description: '',
+ inputs,
+ nodePack: 'invokeai',
+ outputs: {},
+ outputType: `${type}_output`,
+ tags: [],
+ title: type,
+ type,
+ useCache: true,
+ version: '1.0.0',
+});
+const templates = {
+ string: template('string', { value: field('value', 'StringField', { default: '' }) }),
+ string_batch: template('string_batch', {
+ batch_group_id: field('batch_group_id', 'EnumField', { default: 'None', options: ['None'] }),
+ strings: field('strings', 'StringField', {
+ default: [],
+ type: { batch: true, cardinality: 'COLLECTION', name: 'StringField' },
+ }),
+ }),
+ string_generator: template('string_generator', {
+ generator: field('generator', 'StringGeneratorField', { input: 'direct' }),
+ }),
+};
+const generatorValue = {
+ input: 'a {red|green} cat',
+ maxPrompts: 4,
+ type: 'string_generator_dynamic_prompts_combinatorial',
+};
+const invocationNode = (id: string, type: string, inputs: Record<string, unknown>) => ({
+ data: {
+ inputs: Object.fromEntries(Object.entries(inputs).map(([name, value]) => [name, { label: '', name, value }])),
+ isIntermediate: true,
+ isOpen: true,
+ label: '',
+ nodePack: 'invokeai',
+ notes: '',
+ type,
+ useCache: true,
+ version: '1.0.0',
+ },
+ id,
+ position: { x: 0, y: 0 },
+ type: 'invocation' as const,
+});
+const edge = (source: string, sourceHandle: string, target: string, targetHandle: string) => ({
+ id: `${source}->${target}`,
+ source,
+ sourceHandle,
+ target,
+ targetHandle,
+ type: 'default' as const,
+});
+
+/** A workflow whose only batch is fed by a dynamic-prompt generator, so submission must resolve it first. */
+const buildProject = () => {
+ templatesMock.snapshot = { error: null, status: 'loaded', templates };
+
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'automate', type: 'applyPreset' });
+
+ state = workbenchReducer(state, {
+ action: { node: invocationNode('gen', 'string_generator', { generator: generatorValue }), type: 'addNode' },
+ type: 'applyProjectGraphAction',
+ });
+ state = workbenchReducer(state, {
+ action: {
+ edge: edge('gen', 'strings', 'batch', 'strings'),
+ node: invocationNode('batch', 'string_batch', { batch_group_id: 'None' }),
+ type: 'addNodeAndEdge',
+ },
+ type: 'applyProjectGraphAction',
+ });
+ state = workbenchReducer(state, {
+ action: {
+ edge: edge('batch', 'value', 'prompt', 'value'),
+ node: invocationNode('prompt', 'string', { value: 'static' }),
+ type: 'addNodeAndEdge',
+ },
+ type: 'applyProjectGraphAction',
+ });
+
+ return getActiveProject(state);
+};
+const workflowRoute: InvocationRoute = {
+ destination: 'gallery',
+ destinationLocked: false,
+ sourceId: 'workflow',
+ sourceLocked: false,
+};
+
+describe('submitResolvedInvocation with a workflow generator', () => {
+ beforeEach(() => {
+ generatorsMock.resolveWorkflowGenerators.mockReset();
+ });
+
+ const submit = async () => {
+ const project = buildProject();
+ const route = resolveInvocationRoute(project, 'global', workflowRoute);
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+ const notify = vi.spyOn(commands.notifications, 'add');
+
+ expect(route.validationReasons).toEqual([]);
+ expect(route.workflowBatch).toEqual({ size: null });
+
+ await submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route,
+ });
+
+ return { notify, submitResolved };
+ };
+
+ it('resolves the pending generator and dispatches its output with the snapshot', async () => {
+ generatorsMock.resolveWorkflowGenerators.mockImplementation(
+ (_client: unknown, pending: Array<{ key: string; nodeId: string }>) =>
+ Promise.resolve({
+ errors: [],
+ resolutions: Object.fromEntries(
+ pending.map((item) => [item.nodeId, { items: ['a red cat', 'a green cat'], key: item.key }])
+ ),
+ })
+ );
+
+ const { notify, submitResolved } = await submit();
+
+ expect(generatorsMock.resolveWorkflowGenerators).toHaveBeenCalledTimes(1);
+ expect(generatorsMock.resolveWorkflowGenerators.mock.calls[0]?.[1]).toMatchObject([
+ {
+ nodeId: 'gen',
+ request: { combinatorial: true, kind: 'dynamicPrompts', maxPrompts: 4, prompt: 'a {red|green} cat' },
+ },
+ ]);
+ expect(notify).not.toHaveBeenCalled();
+ expect(submitResolved).toHaveBeenCalledTimes(1);
+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({
+ workflowGenerators: { gen: { items: ['a red cat', 'a green cat'] } },
+ });
+ });
+
+ it('reports a generator that failed to resolve and queues nothing', async () => {
+ generatorsMock.resolveWorkflowGenerators.mockResolvedValue({
+ errors: ['string_generator: Unbalanced braces'],
+ resolutions: {},
+ });
+
+ const { notify, submitResolved } = await submit();
+
+ expect(submitResolved).not.toHaveBeenCalled();
+ expect(notify).toHaveBeenCalledWith({
+ kind: 'error',
+ message: 'string_generator: Unbalanced braces',
+ title: 'The batch generator could not be resolved',
+ });
+ });
+
+ it('reports a batch that only turns out empty once its generator resolved', async () => {
+ generatorsMock.resolveWorkflowGenerators.mockImplementation(
+ (_client: unknown, pending: Array<{ key: string; nodeId: string }>) =>
+ Promise.resolve({
+ errors: [],
+ resolutions: Object.fromEntries(pending.map((item) => [item.nodeId, { items: [], key: item.key }])),
+ })
+ );
+
+ const { notify, submitResolved } = await submit();
+
+ expect(submitResolved).not.toHaveBeenCalled();
+ expect(notify).toHaveBeenCalledWith({
+ kind: 'error',
+ message: 'Batch node "string_batch" has an empty collection.',
+ title: 'The batch is not ready',
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
index 5283e3e09c..72e9c72eeb 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
@@ -6,12 +6,22 @@
import type { GenerateSettings } from '@features/generation/contracts';
import type { ParseDynamicPromptsResponse } from '@features/generation/prompts';
import type { ModelConfig } from '@features/models';
+import type { WorkflowGeneratorResolutions, WorkflowPendingGenerator } from '@features/workflow/utility';
import type { AccountScope } from '@platform/state/accountLifecycle';
import type { ResolvedInvocationRoute } from '@workbench/invocationContracts';
import type { Project } from '@workbench/projectContracts';
import { resolveDynamicPrompts } from '@features/generation/prompts';
-import { getEffectivePrompts, hasDynamicPromptSyntax, normalizeGenerateSettings } from '@features/generation/settings';
+import {
+ getEffectivePrompts,
+ hasDynamicPromptSyntax,
+ normalizeGenerateSettings,
+ sanitizeBatchCount,
+} from '@features/generation/settings';
+import { getWorkflowBatchCapReason } from '@features/workflow/graph';
+import { resolveWorkflowGenerators } from '@features/workflow/queries';
+import { getInvocationTemplatesSnapshot } from '@features/workflow/react';
+import { planWorkflowBatch } from '@features/workflow/utility';
import { queryClient } from '@platform/query/client';
import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
@@ -24,6 +34,8 @@ import { getProjectWidgetValues } from './widgetState';
/** Plain English, like the shell's other notices — this module has no i18n context. */
const EXPANSION_FAILED_TITLE = 'The prompt could not be expanded';
+const GENERATOR_FAILED_TITLE = 'The batch generator could not be resolved';
+const BATCH_NOT_READY_TITLE = 'The batch is not ready';
export interface SubmitResolvedInvocationDeps {
/** The resolved route to submit — the caller has already checked it is valid. */
@@ -81,6 +93,65 @@ const resolveExpandedPrompts = async (settings: GenerateSettings): Promise<Parse
}
};
+/** The async generators (dynamic prompts, board listings) a workflow submission still has to resolve. */
+const getPendingWorkflowGenerators = (project: Project, route: ResolvedInvocationRoute): WorkflowPendingGenerator[] => {
+ const templatesSnapshot = getInvocationTemplatesSnapshot();
+
+ if (route.sourceId !== 'workflow' || templatesSnapshot.status !== 'loaded') {
+ return [];
+ }
+
+ return planWorkflowBatch(project.projectGraph, templatesSnapshot.templates).pendingGenerators;
+};
+
+/**
+ * Resolves the pending generators, the only asynchronous step before the reducer; their outputs travel with the
+ * action and the planner re-checks them against the document it compiles.
+ */
+const resolveWorkflowGeneratorsForRoute = async (
+ project: Project,
+ pending: readonly WorkflowPendingGenerator[],
+ owner: AccountScope,
+ commands: Pick<WorkbenchCommands, 'notifications'>
+): Promise<WorkflowGeneratorResolutions | null> => {
+ const templatesSnapshot = getInvocationTemplatesSnapshot();
+
+ if (templatesSnapshot.status !== 'loaded') {
+ return null;
+ }
+
+ const { errors, resolutions } = await resolveWorkflowGenerators(queryClient, pending);
+
+ if (!isAccountScopeCurrent(owner)) {
+ return null;
+ }
+
+ if (errors.length > 0) {
+ commands.notifications.add({ kind: 'error', message: errors[0], title: GENERATOR_FAILED_TITLE });
+ return null;
+ }
+
+ // Sizes were unknown until now: an empty board or a mismatched group only shows once the lists exist.
+ const resolvedPlan = planWorkflowBatch(project.projectGraph, templatesSnapshot.templates, {
+ generators: resolutions,
+ });
+
+ const capReason =
+ resolvedPlan.batchSize === null
+ ? null
+ : getWorkflowBatchCapReason(
+ resolvedPlan.batchSize * sanitizeBatchCount(getProjectWidgetValues(project, 'workflow').batchCount)
+ );
+ const reason = resolvedPlan.reasons[0] ?? capReason;
+
+ if (reason) {
+ commands.notifications.add({ kind: 'error', message: reason, title: BATCH_NOT_READY_TITLE });
+ return null;
+ }
+
+ return resolutions;
+};
+
export const submitResolvedInvocation = async ({
commands,
formatControlLayerError,
@@ -94,6 +165,20 @@ export const submitResolvedInvocation = async ({
return;
}
+ // Only a workflow with unresolved generators needs this round trip; every other route dispatches synchronously.
+ const pendingGenerators = getPendingWorkflowGenerators(project, route);
+ let workflowGenerators: WorkflowGeneratorResolutions | undefined;
+
+ if (pendingGenerators.length > 0) {
+ const resolved = await resolveWorkflowGeneratorsForRoute(project, pendingGenerators, owner, commands);
+
+ if (resolved === null) {
+ return;
+ }
+
+ workflowGenerators = resolved;
+ }
+
const expandableSettings = getExpandableSettings(project, route);
// Only dynamic prompts require a round trip.
@@ -116,14 +201,16 @@ export const submitResolvedInvocation = async ({
await dispatchResolvedInvocation(
{ commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
- expansion.prompts.length > 0 ? expansion.prompts : undefined
+ expansion.prompts.length > 0 ? expansion.prompts : undefined,
+ workflowGenerators
);
return;
}
await dispatchResolvedInvocation(
{ commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
- undefined
+ undefined,
+ workflowGenerators
);
};
@@ -137,7 +224,8 @@ const dispatchResolvedInvocation = async (
project,
route,
}: SubmitResolvedInvocationDeps,
- positivePrompts: string[] | undefined
+ positivePrompts: string[] | undefined,
+ workflowGenerators: WorkflowGeneratorResolutions | undefined
): Promise<void> => {
if (route.sourceId === 'canvas') {
// Await Canvas preparation to retain the submission guard until completion; pass the resolved destination so
@@ -164,5 +252,6 @@ const dispatchResolvedInvocation = async (
models,
positivePrompts,
route,
+ ...(workflowGenerators ? { workflowGenerators } : {}),
});
};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx
index fc1110fd04..65e2a54473 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx
@@ -125,7 +125,7 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {
const InvokeTooltipContent = ({ shortcutParts, state }: { shortcutParts: string[] | null; state: InvocationState }) => {
const { t } = useTranslation();
- const { batchCount, blockingReasons, invocation, isPreparing, isValid, promptExpansion } = state;
+ const { batchCount, blockingReasons, invocation, isPreparing, isValid, promptExpansion, workflowBatchSize } = state;
const destination = getDestinationLabel(invocation.destination);
const promptCount = promptExpansion.count;
const summary =
@@ -133,7 +133,11 @@ const InvokeTooltipContent = ({ shortcutParts, state }: { shortcutParts: string[
? promptExpansion.isLoading
? t('topbar.invoke.expandingPrompts')
: `${plural(promptCount, 'prompt')} × ${plural(batchCount, 'iteration')} → ${plural(promptCount * batchCount, 'generation')}`
- : `Workflow × ${plural(batchCount, 'run')} → ${plural(batchCount, 'generation')}`;
+ : workflowBatchSize === undefined
+ ? `Workflow × ${plural(batchCount, 'run')} → ${plural(batchCount, 'generation')}`
+ : workflowBatchSize === null
+ ? `Workflow × ${plural(batchCount, 'run')} × batch (size resolves on invoke)`
+ : `Workflow × ${plural(batchCount, 'run')} × ${plural(workflowBatchSize, 'batch item')} → ${plural(batchCount * workflowBatchSize, 'generation')}`;
return (
<Stack gap="1.5" minW="14rem" p="2">
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
index 5686bec29f..d6baff6ca1 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
@@ -88,6 +88,8 @@ export interface InvocationState {
batchCount: number;
blockingReasons: string[];
invocation: InvocationRoute;
+ /** Sessions one workflow run produces through batch nodes; absent without batch nodes, null while unresolved. */
+ workflowBatchSize?: number | null;
isPreparing: boolean;
isValid: boolean;
sources: GraphWidgetSource[];
@@ -187,5 +189,6 @@ export const useInvocationState = (): InvocationState => {
sourceValues,
sources: graphWidgetSources,
visibleTypeIds,
+ ...(resolvedRoute.workflowBatch ? { workflowBatchSize: resolvedRoute.workflowBatch.size } : {}),
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 164610b0e7..7ee5459862 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -3367,6 +3367,102 @@ describe('workbenchReducer Phase 5 generation flow', () => {
return node?.type === 'invocation' ? node.data.inputs.seed?.value : undefined;
};
+ it('carries batch-node groups on the submission and sizes the placeholders for every session', () => {
+ const floatField = {
+ ...(seedTemplate.inputs.seed as NonNullable<(typeof seedTemplate.inputs)['seed']>),
+ maximum: null,
+ minimum: null,
+ name: 'value',
+ title: 'Value',
+ type: { batch: false, cardinality: 'SINGLE' as const, name: 'FloatField' },
+ };
+ const batchTemplates = {
+ float: {
+ ...seedTemplate,
+ inputs: { value: floatField },
+ outputType: 'float_output',
+ title: 'Float',
+ type: 'float',
+ },
+ float_batch: {
+ ...seedTemplate,
+ inputs: {
+ batch_group_id: {
+ ...floatField,
+ default: 'None',
+ name: 'batch_group_id',
+ options: ['None', 'Group 1'],
+ title: 'Batch Group',
+ type: { batch: false, cardinality: 'SINGLE' as const, name: 'EnumField' },
+ },
+ floats: {
+ ...floatField,
+ default: [],
+ name: 'floats',
+ required: true,
+ title: 'Floats',
+ type: { batch: true, cardinality: 'COLLECTION' as const, name: 'FloatField' },
+ },
+ },
+ outputType: 'float_output',
+ title: 'Float Batch',
+ type: 'float_batch',
+ },
+ noise: seedTemplate,
+ };
+ let state = primeWorkflow(42, 'fixed');
+
+ workflowTemplatesMock.snapshot = { error: null, status: 'loaded', templates: batchTemplates };
+
+ const invocationNode = (id: string, type: string, inputs: Record<string, unknown>) => ({
+ data: {
+ inputs: Object.fromEntries(Object.entries(inputs).map(([name, value]) => [name, { label: '', name, value }])),
+ isIntermediate: true,
+ isOpen: true,
+ label: '',
+ nodePack: 'invokeai',
+ notes: '',
+ type,
+ useCache: true,
+ version: '1.0.0',
+ },
+ id,
+ position: { x: 0, y: 0 },
+ type: 'invocation' as const,
+ });
+
+ state = workbenchReducer(state, {
+ action: { node: invocationNode('float-1', 'float', { value: 0.5 }), type: 'addNode' },
+ type: 'applyProjectGraphAction',
+ });
+ state = workbenchReducer(state, {
+ action: {
+ edge: {
+ id: 'batch-edge',
+ source: 'batch-1',
+ sourceHandle: 'value',
+ target: 'float-1',
+ targetHandle: 'value',
+ type: 'default',
+ },
+ node: invocationNode('batch-1', 'float_batch', { batch_group_id: 'None', floats: [1.5, 2.5] }),
+ type: 'addNodeAndEdge',
+ },
+ type: 'applyProjectGraphAction',
+ });
+ state = submitWorkflow(state);
+
+ expect(readSubmission(state)).toMatchObject({
+ batchCount: 3,
+ batchData: [[{ fieldName: 'value', items: [1.5, 2.5], nodeId: 'float-1' }]],
+ kind: 'workflow',
+ });
+ // Batch nodes never reach the backend graph; the fed input keeps its static value for the server to overwrite.
+ expect(readSubmission(state)).toMatchObject({ graph: { nodes: { 'float-1': { value: 0.5 } } } });
+ expect(Object.keys((readSubmission(state) as { graph: { nodes: object } }).graph.nodes)).not.toContain('batch-1');
+ expect(getActiveProject(state).queue.items[0]?.snapshot.presentation.batchCount).toBe(6);
+ });
+
it('zips a stepping seed into the batch, advances the node, and continues on the next submission', () => {
let state = submitWorkflow(primeWorkflow(42, 'increment'));
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index e4d7d85a99..506edd4f20 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -117,6 +117,7 @@ import {
sanitizeBatchCount,
syncGenerateWidgetValuesWithModels,
} from '@features/generation/settings';
+import { MAX_QUEUE_BATCH_ITEMS } from '@features/queue';
import { getGenerationDevicesSnapshot, resolveRandDeviceMetadata } from '@features/queue/devices';
import {
clearDeletedUpscaleInput,
@@ -151,6 +152,7 @@ import {
projectGraphReducer,
serializeWorkflowJsonForSubmission,
type ProjectGraphAction,
+ type WorkflowGeneratorResolutions,
} from '@features/workflow/utility';
import {
@@ -315,6 +317,8 @@ type WorkbenchReducerAction =
backendSupportsCancellation: boolean;
/** Expanded positive prompts, resolved by the caller before dispatch. */
positivePrompts?: string[];
+ /** Async workflow generator outputs, resolved by the caller before dispatch. */
+ workflowGenerators?: WorkflowGeneratorResolutions;
route: InvocationRoute;
models?: readonly ModelConfig[];
}
@@ -2365,7 +2369,8 @@ const applyAutoRouteForRegionFront = (
const compileInvocationSnapshot = (
project: Project,
route: InvocationRoute,
- models?: readonly ModelConfig[]
+ models?: readonly ModelConfig[],
+ workflowGenerators?: WorkflowGeneratorResolutions
): {
graph: GraphContract;
widgetStates: WidgetStateMap;
@@ -2383,9 +2388,17 @@ const compileInvocationSnapshot = (
return null;
}
- const { graph, ...workflow } = planWorkflowSubmission(project.projectGraph, templatesSnapshot.templates, {
+ const plan = planWorkflowSubmission(project.projectGraph, templatesSnapshot.templates, {
batchCount: sanitizeBatchCount(widgetStates.workflow?.values.batchCount),
+ generators: workflowGenerators,
});
+
+ // Null means a generator is still unresolved or was edited during its round trip; nothing is queued.
+ if (!plan) {
+ return null;
+ }
+
+ const { graph, ...workflow } = plan;
const { id: _id, ...workflowJson } = serializeWorkflowJsonForSubmission(project.projectGraph);
return {
@@ -3071,6 +3084,7 @@ const enqueueCompiledSnapshot = (
: {
batchCount: compiled.workflow.batchCount,
...(compiled.workflow.seeds.length ? { seeds: compiled.workflow.seeds } : {}),
+ ...(compiled.workflow.batchData.length ? { batchData: compiled.workflow.batchData } : {}),
graph: backendGraph,
kind: 'workflow',
...(compiled.workflowJson ? { workflow: compiled.workflowJson } : {}),
@@ -3146,7 +3160,12 @@ const enqueueCompiledSnapshot = (
batchCount:
backendSubmission.kind === 'invalid'
? 1
- : backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),
+ : Math.min(
+ MAX_QUEUE_BATCH_ITEMS,
+ backendSubmission.batchCount *
+ (expandedPositivePrompts?.length ?? 1) *
+ (compiled.workflow?.batchSize ?? 1)
+ ),
height: presentationDimensions.height,
// Use merged prompts so queue text stays consistent when the backend session arrives.
...(effectivePrompts?.positivePrompt ? { positivePrompt: effectivePrompts.positivePrompt } : {}),
@@ -3229,13 +3248,14 @@ const submitInvocationSnapshot = (
backendSupportsCancellation: boolean,
route = resolveInvocationRoute(project),
models?: readonly ModelConfig[],
- positivePrompts?: string[]
+ positivePrompts?: string[],
+ workflowGenerators?: WorkflowGeneratorResolutions
): Project => {
if (!isInvocationRouteValid(route)) {
return project;
}
- const compiledSnapshot = compileInvocationSnapshot(project, route, models);
+ const compiledSnapshot = compileInvocationSnapshot(project, route, models, workflowGenerators);
if (!compiledSnapshot) {
return project;
@@ -4162,7 +4182,8 @@ export const __workbenchReducerInternal = (
action.backendSupportsCancellation,
resolveInvocationRoute(project, 'global', action.route, action.models),
action.models,
- action.positivePrompts
+ action.positivePrompts,
+ action.workflowGenerators
)
),
state.activeProjectId