Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): add seed modes to workflow seed inputs
Josh Corbett49c746e8cfad
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex ac0dd7a762..f5989bfbd5 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -86,7 +86,7 @@ Feature interfaces remain ordinary module interfaces unless two adapters add lev| Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution || Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution || Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |-| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue interfaces; document reads/commands, compiled submission envelope and widget contribution |+| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution || Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |## Settings contributionsdiff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex a25bd7843b..8cd708c8c6 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -3197,6 +3197,7 @@"source:src/features/generation/queries.ts","source:src/features/generation/react.ts","source:src/features/generation/runtime.ts",+ "source:src/features/generation/seedModeMenu.ts","source:src/features/generation/settings.ts","source:src/features/generation/ui/GenerateAdvancedFields.tsx","source:src/features/generation/ui/GenerateCanvasSections.tsx",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex b760980c90..3641b49f4b 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1407,6 +1407,8 @@"nodeType": "Type: {{type}}","nodeVersion": "Version: {{version}}","nodeClassification": "Classification: {{classification}}",+ "seedModeTooltip": "Seed mode. Applies between queued runs of the workflow; a loop inside one run reuses that run's seed.",+ "seedProvidedByConnection": "Provided by connection.","iterationOutputs": "Iteration outputs","finalOutputs": "Final outputs","forLoopValidationFailed": "For loop validation failed",diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.tsindex 992eff22d4..58d71a6831 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts@@ -1,8 +1,14 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import type { FieldInputTemplate, InvocationTemplate, InvocationTemplatesSnapshot, ProjectGraphState } from './types';-import { compileProjectGraph, getProjectGraphReadiness } from './buildGraph';+import {+ compileProjectGraph,+ getProjectGraphReadiness,+ getWorkflowFieldSeedMode,+ isSeedInputField,+ planWorkflowSubmission,+} from './buildGraph';import {buildConnectorNode,buildInvocationNode,@@ -554,3 +560,192 @@ describe('compileProjectGraph', () => {});});});++describe('planWorkflowSubmission', () => {+ const SEED_MAX = 4_294_967_295;+ const seedInput = input('seed', {+ default: 0,+ maximum: SEED_MAX,+ minimum: 0,+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ });+ const seededTemplates = {+ integer: template('integer', {+ value: input('value', { default: 0, type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' } }),+ }),+ noise: template('noise', { seed: seedInput, width: input('width', { default: 512 }) }),+ };+ const seededTemplate = seededTemplates.noise;++ const buildSeeded = (nodes: Array<{ seed?: number; seedMode?: 'random' | 'fixed' | 'increment' | 'decrement' }>) => {+ let doc = createProjectGraph('seed-plan');+ const ids: string[] = [];++ for (const [index, config] of nodes.entries()) {+ const node = buildInvocationNode(seededTemplate, { x: index * 100, y: 0 });++ ids.push(node.id);+ doc = projectGraphReducer(doc, { node, type: 'addNode' });++ if (config.seed !== undefined) {+ doc = projectGraphReducer(doc, {+ fieldName: 'seed',+ nodeId: node.id,+ type: 'setFieldValue',+ value: config.seed,+ });+ }++ if (config.seedMode) {+ doc = projectGraphReducer(doc, {+ fieldName: 'seed',+ nodeId: node.id,+ seedMode: config.seedMode,+ type: 'setFieldSeedMode',+ });+ }+ }++ return { doc, ids };+ };++ 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 });++ expect(plan).toMatchObject({ data: null, generationCount: 3, runs: 3, seedAdvances: [] });+ expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(7);+ expect(plan.graph.backendGraph.nodes[ids[1] as string]?.seed).toBe(9);+ });++ it('zips every stepping seed into one group so three runs stay three runs', () => {+ const { doc, ids } = buildSeeded([+ { seed: 42, seedMode: 'increment' },+ { seed: 100, seedMode: 'decrement' },+ { seed: 5 },+ ]);+ const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });++ expect(plan.runs).toBe(1);+ expect(plan.generationCount).toBe(3);+ expect(plan.data).toEqual([+ [+ { field_name: 'seed', items: [42, 43, 44], node_path: ids[0] },+ { field_name: 'seed', items: [100, 99, 98], node_path: ids[1] },+ ],+ ]);+ expect(plan.seedAdvances).toEqual([+ { fieldName: 'seed', fromSeed: 42, nodeId: ids[0], seedMode: 'increment', toSeed: 45 },+ { fieldName: 'seed', fromSeed: 100, nodeId: ids[1], seedMode: 'decrement', toSeed: 97 },+ ]);+ // The fixed node keeps its constant in the graph; the varying ones keep theirs as the fallback the batch overrides.+ expect(plan.graph.backendGraph.nodes[ids[2] as string]?.seed).toBe(5);+ });++ it('wraps the sequence over the inclusive seed range', () => {+ const { doc } = buildSeeded([{ seed: 1, seedMode: 'decrement' }]);+ const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });++ expect(plan.data?.[0]?.[0]?.items).toEqual([1, 0, SEED_MAX]);+ expect(plan.seedAdvances[0]?.toSeed).toBe(SEED_MAX - 1);+ });++ it('draws a random start per input, runs consecutively from it, and never advances the entered seed', () => {+ const { doc, ids } = buildSeeded([+ { seed: 42, seedMode: 'random' },+ { seed: 42, seedMode: 'random' },+ ]);+ // A constant draw: the graph id generator shares the random source, so a queue of draws would skew.+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.25);+ const start = Math.floor(0.25 * SEED_MAX);++ try {+ const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 2 });++ expect(plan.data).toEqual([+ [+ { field_name: 'seed', items: [start, start + 1], node_path: ids[0] },+ { field_name: 'seed', items: [start, start + 1], node_path: ids[1] },+ ],+ ]);+ expect(plan.seedAdvances).toEqual([]);+ expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(42);+ } finally {+ random.mockRestore();+ }+ });++ it('leaves a connected seed to its upstream node and keeps the local mode for later', () => {+ const { doc, ids } = buildSeeded([{ seed: 42, seedMode: 'increment' }]);+ const source = buildInvocationNode(seededTemplates.integer, { x: -100, y: 0 });+ const connected = projectGraphReducer(projectGraphReducer(doc, { node: source, type: 'addNode' }), {+ edge: {+ id: 'e',+ source: source.id,+ sourceHandle: 'out',+ target: ids[0] as string,+ targetHandle: 'seed',+ type: 'default',+ },+ type: 'addEdge',+ });+ const plan = planWorkflowSubmission(connected, seededTemplates, { batchCount: 2 });++ expect(plan).toMatchObject({ data: null, runs: 2, seedAdvances: [] });+ expect(connected.nodes.find((node) => node.id === ids[0])).toMatchObject({+ data: { inputs: { seed: { seedMode: 'increment', value: 42 } } },+ });+ });++ it('steps an empty seed input from the template default', () => {+ const { doc, ids } = buildSeeded([{ seedMode: 'increment' }]);+ const emptied = projectGraphReducer(doc, {+ fieldName: 'seed',+ nodeId: ids[0] as string,+ type: 'setFieldValue',+ value: undefined,+ });+ const plan = planWorkflowSubmission(emptied, seededTemplates, { batchCount: 2 });++ expect(plan.data?.[0]?.[0]?.items).toEqual([0, 1]);+ // The advance is fenced on the empty value, so the field fills in with the seed after the batch.+ expect(plan.seedAdvances).toEqual([{ fieldName: 'seed', nodeId: ids[0], seedMode: 'increment', toSeed: 2 }]);+ expect(+ projectGraphReducer(emptied, { advances: plan.seedAdvances, type: 'advanceSeedFields' }).nodes[0]+ ).toMatchObject({ data: { inputs: { seed: { value: 2 } } } });+ });+});++describe('seed inputs', () => {+ const seed = (overrides: Partial<FieldInputTemplate> = {}) =>+ input('seed', {+ maximum: 4_294_967_295,+ minimum: 0,+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ ...overrides,+ });++ it('recognises the scalar integer a node declares as seed over the seed range', () => {+ expect(isSeedInputField(seed())).toBe(true);+ // The title is what a user edits; the name and range are what the backend declared.+ expect(isSeedInputField(seed({ title: 'Noise seed' }))).toBe(true);+ });++ it('leaves other integers, other ranges, and connection-only seeds alone', () => {+ expect(isSeedInputField(seed({ name: 'steps' }))).toBe(false);+ expect(isSeedInputField(seed({ maximum: 1_000 }))).toBe(false);+ expect(isSeedInputField(seed({ maximum: null }))).toBe(false);+ expect(isSeedInputField(seed({ type: { batch: false, cardinality: 'SINGLE', name: 'FloatField' } }))).toBe(false);+ expect(isSeedInputField(seed({ type: { batch: false, cardinality: 'COLLECTION', name: 'IntegerField' } }))).toBe(+ false+ );+ expect(isSeedInputField(seed({ input: 'connection' }))).toBe(false);+ });++ it('reads an absent or unknown mode as fixed', () => {+ expect(getWorkflowFieldSeedMode(undefined)).toBe('fixed');+ expect(getWorkflowFieldSeedMode({})).toBe('fixed');+ expect(getWorkflowFieldSeedMode({ seedMode: 'shuffle' as never })).toBe('fixed');+ expect(getWorkflowFieldSeedMode({ seedMode: 'decrement' })).toBe('decrement');+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.tsindex 7a78a2035b..b3f66285e9 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts@@ -1,14 +1,20 @@+import type { SeedMode } from '@features/generation/contracts';++import { isSeedMode, planSeedSubmission, SEED_MAX, wrapSeed } from '@features/generation/seed';+import type { CompiledWorkflowGraph, WorkflowBackendGraph } from './graphContracts';import type {FieldInputTemplate,InvocationTemplates,InvocationTemplatesSnapshot,ProjectGraphState,+ WorkflowFieldInstance,WorkflowInvocationNode,+ WorkflowSeedFieldAdvance,} from './types';import { createWorkflowId } from './document';-import { getWorkflowFieldInvalidReason } from './fields';+import { getWorkflowFieldInvalidReason, isDirectInputField } from './fields';import {createForLoopValidationReason,ForLoopGraphValidationError,@@ -267,3 +273,142 @@ export const compileProjectGraph = (version: 1,};};++/**+ * The inputs that carry a seed mode: the scalar integer a node declares as `seed`+ * over the full seed range. Read from the template alone, so an editable label+ * cannot turn an ordinary integer into a seed, and a provider's own-range `seed`+ * keeps its plain control instead of wrapping at a bound it never had.+ *+ * Seed policy lives here rather than in `fields.ts` because it is the one place+ * the workflow core depends on Generate's runtime seed arithmetic: the shared+ * field/document helpers stay in the lighter utility chunk every overlay loads.+ */+export const isSeedInputField = (template: FieldInputTemplate): boolean =>+ template.name === 'seed' &&+ template.type.name === 'IntegerField' &&+ template.type.cardinality === 'SINGLE' &&+ template.maximum === SEED_MAX &&+ isDirectInputField(template);++export const getWorkflowFieldSeedMode = (instance: Pick<WorkflowFieldInstance, 'seedMode'> | undefined): SeedMode =>+ isSeedMode(instance?.seedMode) ? instance.seedMode : 'fixed';++/**+ * The seeds one varying input contributes to a submission of `runCount` runs,+ * and where its authored seed goes afterwards. Stepping modes count from the+ * authored seed; random draws its start and runs consecutively from it, like+ * Generate's random mode, leaving the authored seed in reserve.+ */+const getWorkflowSeedFieldSequence = (+ seedMode: Exclude<SeedMode, 'fixed'>,+ authoredSeed: number,+ runCount: number+): { nextSeed: number | null; seeds: number[] } => {+ const startSeed = seedMode === 'random' ? Math.floor(Math.random() * SEED_MAX) : wrapSeed(authoredSeed);+ const plan = planSeedSubmission({+ batchCount: runCount,+ promptCount: 1,+ seedBehaviour: 'per-iteration',+ seedMode,+ startSeed,+ });++ return {+ nextSeed: plan.nextSeed,+ seeds: Array.from({ length: plan.sequenceLength }, (_, index) => wrapSeed(startSeed + plan.step * index)),+ };+};++/** One value list of a zipped batch group, in the backend's `BatchDatum` shape. */+export interface WorkflowBatchDatum {+ field_name: string;+ items: number[];+ node_path: string;+}++export interface WorkflowSubmissionPlan {+ graph: CompiledWorkflowGraph;+ /** One zipped group over every seed input that varies between runs; null while every seed holds. */+ data: WorkflowBatchDatum[][] | null;+ /** Backend `runs`: the batch count while every seed holds, else 1 with the runs enumerated by `data`. */+ runs: number;+ /** Sessions the submission produces either way. */+ generationCount: number;+ /** Stepping-mode fields to move once the submission is queued. */+ seedAdvances: WorkflowSeedFieldAdvance[];+}++export interface WorkflowSubmissionPlanOptions {+ /** Runs per submission; already sanitized to a positive integer by the caller. */+ batchCount: number;+}++/**+ * Compiles the document and fixes every seed input's values for one submission.+ * Seeds vary per queued run, not per iteration of a loop inside a run, which+ * repeats its run's seed. Every varying input joins one zipped group, so three+ * runs over two stepping seeds stay three runs rather than nine combinations;+ * fixed inputs stay constants in the graph. A random input draws its start here+ * and runs consecutively from it, like Generate's random mode, while the entered+ * seed stays in reserve. Only the stepping modes report an advance.+ */+export const planWorkflowSubmission = (+ document: ProjectGraphState,+ templates: InvocationTemplates,+ { batchCount }: WorkflowSubmissionPlanOptions+): WorkflowSubmissionPlan => {+ const graph = compileProjectGraph(document, templates);+ const connectedInputs = new Set(graph.edges.map((edge) => `${edge.targetNodeId}:${edge.targetField}`));+ const data: WorkflowBatchDatum[] = [];+ const seedAdvances: WorkflowSeedFieldAdvance[] = [];++ for (const node of getExecutableNodes(document)) {+ const template = templates[node.data.type];++ if (!template) {+ continue;+ }++ for (const inputTemplate of Object.values(template.inputs)) {+ if (!isSeedInputField(inputTemplate) || connectedInputs.has(`${node.id}:${inputTemplate.name}`)) {+ continue;+ }++ const instance = node.data.inputs[inputTemplate.name];+ const seedMode = getWorkflowFieldSeedMode(instance);++ if (seedMode === 'fixed') {+ continue;+ }++ const authoredSeed =+ typeof instance?.value === 'number'+ ? instance.value+ : typeof inputTemplate.default === 'number'+ ? inputTemplate.default+ : 0;+ const sequence = getWorkflowSeedFieldSequence(seedMode, authoredSeed, batchCount);++ data.push({ field_name: inputTemplate.name, items: sequence.seeds, node_path: node.id });++ if (sequence.nextSeed !== null) {+ seedAdvances.push({+ fieldName: inputTemplate.name,+ ...(typeof instance?.value === 'number' ? { fromSeed: instance.value } : {}),+ nodeId: node.id,+ seedMode,+ toSeed: sequence.nextSeed,+ });+ }+ }+ }++ return {+ data: data.length > 0 ? [data] : null,+ generationCount: batchCount,+ graph,+ runs: data.length > 0 ? 1 : batchCount,+ seedAdvances,+ };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.tsindex da4dd19172..7b317382ce 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts@@ -320,3 +320,70 @@ describe('normalizeProjectGraph', () => {expect(normalized.form.elements[normalized.form.rootElementId]?.type).toBe('container');});});++describe('seed modes', () => {+ it('stores a mode on the instance and clears it again for fixed, the absent default', () => {+ const { doc, nodeAId } = createDocWithNodes();+ const stepping = projectGraphReducer(doc, {+ fieldName: 'a',+ nodeId: nodeAId,+ seedMode: 'increment',+ type: 'setFieldSeedMode',+ });++ expect(stepping.nodes[0]).toMatchObject({ data: { inputs: { a: { seedMode: 'increment', value: 1 } } } });++ const fixed = projectGraphReducer(stepping, {+ fieldName: 'a',+ nodeId: nodeAId,+ seedMode: 'fixed',+ type: 'setFieldSeedMode',+ });++ expect(fixed.nodes[0]?.type === 'invocation' && fixed.nodes[0].data.inputs.a).not.toHaveProperty('seedMode');+ });++ it('advances only fields still holding the planned value under the planned mode', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ let next = projectGraphReducer(doc, {+ fieldName: 'a',+ nodeId: nodeAId,+ seedMode: 'increment',+ type: 'setFieldSeedMode',+ });+ next = projectGraphReducer(next, {+ fieldName: 'a',+ nodeId: nodeBId,+ seedMode: 'increment',+ type: 'setFieldSeedMode',+ });+ // B was edited after the plan was captured, so its advance is stale.+ next = projectGraphReducer(next, { fieldName: 'a', nodeId: nodeBId, type: 'setFieldValue', value: 50 });++ const advanced = projectGraphReducer(next, {+ advances: [+ { fieldName: 'a', fromSeed: 1, nodeId: nodeAId, seedMode: 'increment', toSeed: 4 },+ { fieldName: 'a', fromSeed: 1, nodeId: nodeBId, seedMode: 'increment', toSeed: 4 },+ { fieldName: 'a', fromSeed: 4, nodeId: 'missing', seedMode: 'increment', toSeed: 5 },+ ],+ type: 'advanceSeedFields',+ });++ expect(advanced.nodes[0]).toMatchObject({ data: { inputs: { a: { seedMode: 'increment', value: 4 } } } });+ expect(advanced.nodes[1]).toMatchObject({ data: { inputs: { a: { seedMode: 'increment', value: 50 } } } });++ // A mode switched since the plan keeps the value the user now expects to hold.+ const refixed = projectGraphReducer(next, {+ fieldName: 'a',+ nodeId: nodeAId,+ seedMode: 'fixed',+ type: 'setFieldSeedMode',+ });+ const held = projectGraphReducer(refixed, {+ advances: [{ fieldName: 'a', fromSeed: 1, nodeId: nodeAId, seedMode: 'increment', toSeed: 4 }],+ type: 'advanceSeedFields',+ });++ expect(held).toBe(refixed);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.tsindex 2c862cf38a..dc27372e50 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts@@ -1,3 +1,5 @@+import type { SeedMode } from '@features/generation/contracts';+import type {ContainerFormElement,FieldIdentifier,@@ -13,6 +15,7 @@ import type {WorkflowMetadata,WorkflowNode,WorkflowNotesNode,+ WorkflowSeedFieldAdvance,XYPosition,} from './types';@@ -297,6 +300,9 @@ export type ProjectGraphAction =| { type: 'setFieldValue'; nodeId: string; fieldName: string; value: unknown }| { type: 'setFieldLabel'; nodeId: string; fieldName: string; label: string }| { type: 'setFieldDescription'; nodeId: string; fieldName: string; description: string }+ | { type: 'setFieldSeedMode'; nodeId: string; fieldName: string; seedMode: SeedMode }+ /** Moves stepping-mode seeds past a queued submission; each field is fenced on the value and mode it was planned from. */+ | { type: 'advanceSeedFields'; advances: readonly WorkflowSeedFieldAdvance[] }| { type: 'addEdge'; edge: WorkflowEdge }| { type: 'removeEdges'; edgeIds: string[] }| { type: 'exposeField'; fieldIdentifier: FieldIdentifier }@@ -524,6 +530,29 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGradescription: action.description || undefined,}));}+ case 'setFieldSeedMode': {+ // Fixed is the absent default, so choosing it leaves the instance exactly as+ // pre-seed-mode documents (and legacy readers) write it.+ return setFieldInstance(document, action.nodeId, action.fieldName, ({ seedMode: _, ...instance }) =>+ action.seedMode === 'fixed' ? instance : { ...instance, seedMode: action.seedMode }+ );+ }+ case 'advanceSeedFields': {+ return action.advances.reduce((next, advance) => {+ const node = next.nodes.find((candidate) => candidate.id === advance.nodeId);+ const instance = node && isInvocationNode(node) ? node.data.inputs[advance.fieldName] : undefined;++ return instance &&+ instance.value === advance.fromSeed &&+ // An absent mode is fixed, which never plans an advance, so a bare compare is the whole fence.+ (instance.seedMode ?? 'fixed') === advance.seedMode+ ? setFieldInstance(next, advance.nodeId, advance.fieldName, (current) => ({+ ...current,+ value: advance.toSeed,+ }))+ : next;+ }, document);+ }case 'addEdge': {return addEdgeToDocument(document, action.edge);}diff --git a/invokeai/frontend/webv2/src/features/workflow/core/types.ts b/invokeai/frontend/webv2/src/features/workflow/core/types.tsindex 0a732556b9..96db366020 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/types.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/types.ts@@ -9,6 +9,8 @@* editor, the workflow library backend, and this workbench.*/+import type { SeedMode } from '@features/generation/contracts';+export type FieldCardinality = 'SINGLE' | 'COLLECTION' | 'SINGLE_OR_COLLECTION';export interface FieldType {@@ -87,9 +89,25 @@ export interface WorkflowFieldInstance {label: string;/** User override of the template's field description (shown in the Linear UI). */description?: string;+ /**+ * How a seed input (`isSeedInputField`) moves between queued runs. Absent means+ * fixed: what every document authored before seed modes did, and what a legacy+ * reader hands back after stripping the key.+ */+ seedMode?: SeedMode;value?: unknown;}+/** One seed input's move after a submission; applied only while the field still holds `fromSeed` under `seedMode`. */+export interface WorkflowSeedFieldAdvance {+ fieldName: string;+ /** The value the field held when planned; absent when it was empty and the sequence started from the template default. */+ fromSeed?: number;+ nodeId: string;+ seedMode: SeedMode;+ toSeed: number;+}+export interface WorkflowInvocationNodeData {type: string;version: string;diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.tsindex a1ee7574bc..11734fec25 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts@@ -241,3 +241,38 @@ describe('parseWorkflowJson tolerance', () => {expect(document.form.elements[document.form.rootElementId]?.type).toBe('container');});});++describe('seed modes in workflow JSON', () => {+ it('round-trips a stepping mode and reads its absence as unset', () => {+ const node = buildInvocationNode(template, { x: 0, y: 0 });+ let doc = createProjectGraph('seed-json');++ doc = projectGraphReducer(doc, { node, type: 'addNode' });+ doc = projectGraphReducer(doc, {+ fieldName: 'prompt',+ nodeId: node.id,+ seedMode: 'increment',+ type: 'setFieldSeedMode',+ });++ const serialized = serializeWorkflowJson(doc);+ const parsed = parseWorkflowJson(serialized).document.nodes[0];++ expect(parsed?.type === 'invocation' && parsed.data.inputs.prompt).toMatchObject({ seedMode: 'increment' });++ // Fixed is the absent key, which is also what a legacy reader hands back after stripping it.+ const fixed = serializeWorkflowJson(+ projectGraphReducer(doc, { fieldName: 'prompt', nodeId: node.id, seedMode: 'fixed', type: 'setFieldSeedMode' })+ ).nodes as Array<{ data: { inputs: { prompt: { seedMode?: unknown } } } }>;++ expect(fixed[0]?.data.inputs.prompt).not.toHaveProperty('seedMode');++ const nodes = serialized.nodes as Array<{ data: { inputs: { prompt: { seedMode?: unknown } } } }>;++ (nodes[0] as NonNullable<(typeof nodes)[number]>).data.inputs.prompt.seedMode = 'shuffle';++ const degraded = parseWorkflowJson(serialized).document.nodes[0];++ expect(degraded?.type === 'invocation' && degraded.data.inputs.prompt).not.toHaveProperty('seedMode');+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.tsindex 858d0e7257..54e07df20b 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts@@ -1,3 +1,4 @@+import { SEED_MODES } from '@features/generation/seed';import { z } from 'zod';import type {@@ -20,10 +21,15 @@ import { createWorkflowForm, createWorkflowId } from './document';const zXYPosition = z.object({ x: z.number().catch(0), y: z.number().catch(0) }).catch({ x: 0, y: 0 });+// `seedMode` is this workbench's extension of the field instance. The legacy+// editor parses instances through a stripping schema, so a workflow it re-saves+// comes back without the key — every seed reads as fixed again, which is the+// legacy behaviour rather than a corrupted value.const zFieldInstance = z.object({description: z.string().optional().catch(undefined),label: z.string().catch(''),name: z.string(),+ seedMode: z.enum(SEED_MODES).optional().catch(undefined),value: z.unknown().optional(),});@@ -281,6 +287,7 @@ export const parseWorkflowJson = (raw: unknown): ParsedWorkflow => {description: instance.description,label: instance.label,name: instance.name || name,+ ...(instance.seedMode === undefined ? {} : { seedMode: instance.seedMode }),value: instance.value,};}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxindex 0f6b8395fd..f23d4eaf7c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx@@ -3,6 +3,7 @@ import type { FieldInputTemplate, FieldOutputTemplate, WorkflowInvocationNode }import type { WorkflowNodeExecutionState as NodeExecutionState } from '@features/workflow/ui/contracts';import { Box, Checkbox, Field, Flex, HStack, Icon, IconButton, Image, Input, Stack, Text } from '@chakra-ui/react';+import { getWorkflowFieldSeedMode, isSeedInputField } from '@features/workflow/graph';import { FieldDescriptionPopover } from '@features/workflow/ui/fields/FieldDescriptionPopover';import { WorkflowFieldInput } from '@features/workflow/ui/fields/WorkflowFieldInput';import {@@ -287,6 +288,17 @@ const NodeFooter = ({ canUseCache, node }: { canUseCache: boolean; node: Workflo);};+/** The upstream node owns the seed now; the local mode waits for a disconnect. A leaf so only this row subscribes to i18n. */+const SeedProvidedByConnectionNote = () => {+ const { t } = useTranslation();++ return (+ <Text color="fg.subtle" fontSize="2xs" mt="0.5">+ {t('nodes.seedProvidedByConnection')}+ </Text>+ );+};+const InputFieldRow = ({isConnected,isExposed,@@ -428,13 +440,19 @@ const InputFieldRow = ({id={`${node.id}-${template.name}-value`}invalid={isInvalid}nodeId={node.id}+ seedMode={getWorkflowFieldSeedMode(instance)}template={template}value={instance?.value}onChange={(value) =>editGraph({ fieldName: template.name, nodeId: node.id, type: 'setFieldValue', value })}+ onSeedModeChange={(seedMode) =>+ editGraph({ fieldName: template.name, nodeId: node.id, seedMode, type: 'setFieldSeedMode' })+ }/></Box>+ ) : isConnected && isSeedInputField(template) ? (+ <SeedProvidedByConnectionNote />) : null}{invalidReason ? <Field.ErrorText fontSize="2xs">{invalidReason}</Field.ErrorText> : null}</Field.Root>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.tsxindex 5f358550fd..1446a0508d 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@@ -9,7 +9,7 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';-import { WorkflowFieldInput } from './WorkflowFieldInput';+import { WorkflowFieldInput, type WorkflowFieldInputProps } from './WorkflowFieldInput';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -114,6 +114,16 @@ const VIDEO_TEMPLATE = {type: { name: 'VideoField' },} as unknown as FieldInputTemplate;+const SEED_TEMPLATE = {+ input: 'any',+ maximum: 4_294_967_295,+ minimum: 0,+ multipleOf: null,+ name: 'seed',+ title: 'Seed',+ type: { cardinality: 'SINGLE', name: 'IntegerField' },+} as unknown as FieldInputTemplate;+const FRAME_INDEX_TEMPLATE = {name: 'frame_index',title: 'Frame Index',@@ -193,14 +203,15 @@ const renderField = async (template: FieldInputTemplate,value: unknown,onChange: (value: unknown) => void,- nodeId?: string+ nodeId?: string,+ seedProps: Pick<WorkflowFieldInputProps, 'onSeedModeChange' | 'seedMode'> = {}) => {await act(() => {root.render(<ChakraProvider value={system}><QueryClientProvider client={queryClient}><DndContext>- <WorkflowFieldInput nodeId={nodeId} template={template} value={value} onChange={onChange} />+ <WorkflowFieldInput nodeId={nodeId} template={template} value={value} onChange={onChange} {...seedProps} /></DndContext></QueryClientProvider></ChakraProvider>@@ -657,3 +668,61 @@ describe('WorkflowFieldInput LoRA collection', () => {expect(host.querySelectorAll('input')).toHaveLength(1);});});++describe('WorkflowFieldInput seed inputs', () => {+ const settle = async (action: () => void) => {+ await act(async () => {+ action();+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+ });+ };+ const seedInput = () => host.querySelector<HTMLInputElement>('input[type="number"]');+ const modeTrigger = () => host.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]');+ const menuItem = (mode: string) =>+ document.querySelector<HTMLElement>(`[role="menuitemradio"][data-value="${mode}"]`);++ it('renders a plain number input when no seed mode is supplied, and for non-seed integers', async () => {+ await renderField(SEED_TEMPLATE, 42, vi.fn());++ expect(seedInput()?.value).toBe('42');+ expect(modeTrigger()).toBeNull();++ await renderField({ ...SEED_TEMPLATE, name: 'steps' } as FieldInputTemplate, 20, vi.fn(), undefined, {+ onSeedModeChange: vi.fn(),+ seedMode: 'increment',+ });++ expect(modeTrigger()).toBeNull();+ });++ it('puts the mode menu beside a seed input and commits the chosen mode without touching the value', async () => {+ const onChange = vi.fn();+ const onSeedModeChange = vi.fn();++ await renderField(SEED_TEMPLATE, 42, onChange, undefined, { onSeedModeChange, seedMode: 'fixed' });++ expect(seedInput()?.disabled).toBe(false);+ // xyflow reads `.nokey` to leave a control's keys alone; the trigger and the portaled menu both need it,+ // or arrows nudge the node and Backspace deletes it while the menu is in use.+ expect(modeTrigger()?.closest('.nokey')).not.toBeNull();++ await settle(() => modeTrigger()?.click());++ expect(menuItem('fixed')?.getAttribute('aria-checked')).toBe('true');+ expect(menuItem('fixed')?.closest('.nokey')).not.toBeNull();++ await settle(() => menuItem('increment')?.click());++ expect(onSeedModeChange).toHaveBeenCalledWith('increment');+ expect(onChange).not.toHaveBeenCalled();+ });++ it('quiets the value in random mode but keeps it on show', async () => {+ await renderField(SEED_TEMPLATE, 42, vi.fn(), undefined, { onSeedModeChange: vi.fn(), seedMode: 'random' });++ expect(seedInput()?.disabled).toBe(true);+ expect(seedInput()?.value).toBe('42');+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 9524444ddb..6afd187e71 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -1,3 +1,4 @@+import type { SeedMode } from '@features/generation/contracts';import type { ModelConfig, ModelTaxonomyType } from '@features/models/react';import type { FieldInputTemplate } from '@features/workflow/contracts';import type { LoraFieldCollectionEntry } from '@features/workflow/utility';@@ -30,8 +31,10 @@ import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';import { GalleryPickerPopover } from '@features/gallery/picker';import { invalidateGallery } from '@features/gallery/queries';import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';+import { SeedModeMenu } from '@features/generation/seedModeMenu';import { DEFAULT_LORA_WEIGHT_CONFIG, SCHEDULER_OPTIONS } from '@features/generation/settings';import { isInvocationNode } from '@features/workflow/contracts';+import { isSeedInputField } from '@features/workflow/graph';import {getWorkflowMediaFieldDropId,getWorkflowMediaFieldDropItem,@@ -93,6 +96,9 @@ export interface WorkflowFieldInputProps {template: FieldInputTemplate;value: unknown;onChange: (value: unknown) => void;+ /** The instance's seed mode; read only for seed inputs (`isSeedInputField`), which render the mode menu. */+ seedMode?: SeedMode;+ onSeedModeChange?: (seedMode: SeedMode) => void;}const invalidProps = (invalid: boolean | undefined) => (invalid ? { 'aria-invalid': true } : {});@@ -154,7 +160,14 @@ const StringInput = ({ id, invalid, onChange, template, value }: WorkflowFieldIn);};-const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {+const NumericInput = ({+ disabled,+ id,+ invalid,+ onChange,+ template,+ value,+}: WorkflowFieldInputProps & { disabled?: boolean }) => {const isInteger = template.type.name === 'IntegerField';const numericValue = typeof value === 'number' && Number.isFinite(value) ? value : '';const min = template.minimum ?? template.exclusiveMinimum ?? undefined;@@ -174,6 +187,7 @@ const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldI<Inputaria-label={template.title}className="nodrag"+ disabled={disabled}id={id ? `${id}-number-input` : undefined}max={max !== undefined ? String(max) : undefined}min={min !== undefined ? String(min) : undefined}@@ -188,6 +202,35 @@ const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldI);};+/**+ * A seed input with its mode beside it. Random quiets the value the way the+ * Generate seed does: the entered seed stays in reserve for Fixed. The mode+ * applies between queued runs; a loop inside a run reuses that run's seed.+ *+ * `nokey` on the row and the portaled menu keeps xyflow's node key handling+ * out of the trigger and the open menu: arrows would nudge the selected node+ * and Backspace would delete it (zag lets unhandled keys propagate).+ */+const SeedInput = ({+ onSeedModeChange,+ seedMode,+ ...props+}: WorkflowFieldInputProps & { onSeedModeChange: (seedMode: SeedMode) => void; seedMode: SeedMode }) => {+ const { t } = useTranslation();++ return (+ <HStack className="nodrag nokey" gap="1" w="full">+ <NumericInput {...props} disabled={seedMode === 'random'} />+ <SeedModeMenu+ contentClassName="nokey"+ tooltip={t('nodes.seedModeTooltip')}+ value={seedMode}+ onChange={onSeedModeChange}+ />+ </HStack>+ );+};+const SWITCH_CHECKED_PROPS = { bg: 'accent.solid' };const BooleanInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {@@ -1159,6 +1202,10 @@ export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {return <VideoFrameIndexInput {...props} />;}+ if (props.onSeedModeChange && isSeedInputField(props.template)) {+ return <SeedInput {...props} onSeedModeChange={props.onSeedModeChange} seedMode={props.seedMode ?? 'fixed'} />;+ }+return <NumericInput {...props} />;case 'FloatField':return <NumericInput {...props} />;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsxindex 8c93f6c329..362134abca 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx@@ -1,5 +1,8 @@+import type { SeedMode } from '@features/generation/contracts';+import { Alert, Field, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';import { isInvocationNode, type NodeFieldFormElement, type ProjectGraphState } from '@features/workflow/contracts';+import { getWorkflowFieldSeedMode } from '@features/workflow/graph';import { useInvocationTemplatesSelector } from '@features/workflow/react';import { WorkflowFieldInput } from '@features/workflow/ui/fields/WorkflowFieldInput';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';@@ -93,6 +96,10 @@ export const NodeFieldControl = ({(value: unknown) => editGraph({ fieldName, nodeId, type: 'setFieldValue', value }),[editGraph, fieldName, nodeId]);+ const onSeedModeChange = useCallback(+ (seedMode: SeedMode) => editGraph({ fieldName, nodeId, seedMode, type: 'setFieldSeedMode' }),+ [editGraph, fieldName, nodeId]+ );const resetAriaLabel = useMemo(() => `Reset ${label} to default value`, [label]);if (!invocationNode || !template) {@@ -167,9 +174,11 @@ export const NodeFieldControl = ({id={valueInputId}invalid={isInvalid}nodeId={nodeId}+ seedMode={getWorkflowFieldSeedMode(instance)}template={template}value={instance?.value}onChange={onValueChange}+ onSeedModeChange={onSeedModeChange}/>)}{invalidReason ? <Field.ErrorText fontSize="2xs">{invalidReason}</Field.ErrorText> : null}diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.tsindex 64410eed5f..3123d696ef 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts@@ -82,6 +82,7 @@ const GRAPH_EDIT_CONFIDENCE = {addGraphElements: true,addNode: true,addNodeAndEdge: true,+ advanceSeedFields: false,exposeField: false,moveFormElement: false,moveFormElementTo: false,@@ -91,6 +92,7 @@ const GRAPH_EDIT_CONFIDENCE = {setContainerLayout: false,setFieldDescription: false,setFieldLabel: false,+ setFieldSeedMode: true,setFieldValue: true,setFormElementContent: false,setMetadata: false,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 162e67a9e0..357b71a19e 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -71,7 +71,22 @@ vi.mock('@features/queue/devices', async (importOriginal) => {};});+const workflowTemplatesMock = vi.hoisted(() => ({+ snapshot: { error: null, status: 'idle', templates: {} } as {+ error: string | null;+ status: 'idle' | 'loading' | 'loaded' | 'error';+ templates: Record<string, unknown>;+ },+}));++vi.mock('@features/workflow/react', async (importOriginal) => {+ const original = (await importOriginal()) as Record<string, unknown>;++ return { ...original, getInvocationTemplatesSnapshot: () => workflowTemplatesMock.snapshot };+});+afterEach(() => {+ workflowTemplatesMock.snapshot = { error: null, status: 'idle', templates: {} };generationDeviceMock.options = [];});@@ -3267,6 +3282,146 @@ describe('workbenchReducer Phase 5 generation flow', () => {});});+ describe('workflow seed modes on the compiled submission', () => {+ const SEED_MAX = 4_294_967_295;+ const seedTemplate = {+ category: 'noise',+ classification: 'stable',+ description: '',+ inputs: {+ seed: {+ default: 0,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ fieldKind: 'input',+ input: 'any',+ maximum: SEED_MAX,+ minimum: 0,+ multipleOf: null,+ name: 'seed',+ options: null,+ required: false,+ title: 'Seed',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelFormat: null,+ uiModelType: null,+ uiOrder: null,+ },+ },+ nodePack: 'invokeai',+ outputs: {},+ outputType: 'noise_output',+ tags: [],+ title: 'Noise',+ type: 'noise',+ useCache: true,+ version: '1.0.0',+ };+ const primeWorkflow = (seed: number, seedMode: 'random' | 'fixed' | 'increment' | 'decrement', batchCount = 3) => {+ workflowTemplatesMock.snapshot = { error: null, status: 'loaded', templates: { noise: seedTemplate } };++ // The Automate preset mounts the Workflow widget, which the route requires.+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'automate', type: 'applyPreset' });++ state = workbenchReducer(state, { type: 'patchWidgetValues', values: { batchCount }, widgetId: 'generate' });+ state = workbenchReducer(state, {+ action: {+ node: {+ data: {+ inputs: { seed: { label: '', name: 'seed', seedMode, value: seed } },+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'noise',+ useCache: true,+ version: '1.0.0',+ },+ id: 'noise-1',+ position: { x: 0, y: 0 },+ type: 'invocation',+ },+ type: 'addNode',+ },+ type: 'applyProjectGraphAction',+ });++ return state;+ };+ const submitWorkflow = (state: WorkbenchState) =>+ workbenchReducer(state, {+ backendSupportsCancellation: true,+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: false },+ type: 'submitResolvedInvocationSnapshot',+ });+ const readSubmission = (state: WorkbenchState, index = 0) =>+ getActiveProject(state).queue.items[index]?.snapshot.backendSubmission;+ const readNodeSeed = (state: WorkbenchState) => {+ const node = getActiveProject(state).projectGraph.nodes[0];++ return node?.type === 'invocation' ? node.data.inputs.seed?.value : undefined;+ };++ it('zips a stepping seed into the batch, advances the node, and continues on the next submission', () => {+ let state = submitWorkflow(primeWorkflow(42, 'increment'));++ expect(readSubmission(state)).toMatchObject({+ batchCount: 1,+ data: [[{ field_name: 'seed', items: [42, 43, 44], node_path: 'noise-1' }]],+ kind: 'workflow',+ });+ expect(getActiveProject(state).queue.items[0]?.snapshot.presentation.batchCount).toBe(3);+ expect(readNodeSeed(state)).toBe(45);++ state = submitWorkflow(state);++ expect(readSubmission(state)).toMatchObject({ data: [[{ items: [45, 46, 47] }]] });+ expect(readSubmission(state, 1)).toMatchObject({ data: [[{ items: [42, 43, 44] }]] });+ expect(readNodeSeed(state)).toBe(48);+ });++ it('holds a fixed seed as a graph constant and repeats the graph for every run', () => {+ const state = submitWorkflow(primeWorkflow(42, 'fixed'));+ const submission = readSubmission(state);++ expect(submission).toMatchObject({ batchCount: 3, kind: 'workflow' });+ expect(submission).not.toHaveProperty('data');+ expect(submission?.kind === 'workflow' && submission.graph.nodes['noise-1']?.seed).toBe(42);+ expect(readNodeSeed(state)).toBe(42);+ });++ it('draws a random start for the batch and preserves the entered seed', () => {+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.25);++ try {+ const state = submitWorkflow(primeWorkflow(42, 'random', 2));+ const start = Math.floor(0.25 * SEED_MAX);++ expect(readSubmission(state)).toMatchObject({ data: [[{ items: [start, start + 1] }]] });+ expect(readNodeSeed(state)).toBe(42);+ } finally {+ random.mockRestore();+ }+ });++ it('does not move the seed when the route is not ready to submit', () => {+ const state = primeWorkflow(42, 'increment');++ workflowTemplatesMock.snapshot = { error: null, status: 'loading', templates: {} };++ const next = submitWorkflow(state);++ expect(getActiveProject(next).queue.items).toEqual([]);+ expect(readNodeSeed(next)).toBe(42);+ });+ });+describe('seed modes on the compiled submission', () => {const SEED_MAX = 4_294_967_295;const readSeed = (state: WorkbenchState) => getProjectWidgetValues(getActiveProject(state), 'generate').seed;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 65f086a188..9861c83132 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -2,6 +2,7 @@ import type { GenerateWidgetValues } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';import type { ProjectGraphState } from '@features/workflow/contracts';+import type { WorkflowSubmissionPlan } from '@features/workflow/graph';import type {CanvasDocumentContractV3,CanvasPlacementContract,@@ -134,7 +135,7 @@ import {syncVideoWidgetValuesWithModels,type VideoWidgetValues,} from '@features/video';-import { compileProjectGraph } from '@features/workflow/graph';+import { planWorkflowSubmission } from '@features/workflow/graph';import { getInvocationTemplatesSnapshot } from '@features/workflow/react';import {cloneProjectGraph,@@ -2431,7 +2432,11 @@ const compileInvocationSnapshot = (project: Project,route: InvocationRoute,models?: readonly ModelConfig[]-): { graph: GraphContract; widgetStates: WidgetStateMap } | null => {+): {+ graph: GraphContract;+ widgetStates: WidgetStateMap;+ workflow?: Omit<WorkflowSubmissionPlan, 'graph'>;+} | null => {const widgetStates = getWidgetStatesSnapshot(project.widgetInstances);const randDevice = resolveRandDeviceMetadata(project.settings.useCpuNoise, getGenerationDevicesSnapshot().options);@@ -2444,7 +2449,11 @@ const compileInvocationSnapshot = (return null;}- return { graph: compileProjectGraph(project.projectGraph, templatesSnapshot.templates), widgetStates };+ const { graph, ...workflow } = planWorkflowSubmission(project.projectGraph, templatesSnapshot.templates, {+ batchCount: sanitizeBatchCount(widgetStates.generate?.values.batchCount),+ });++ return { graph, widgetStates, workflow };}if (route.sourceId === 'upscale') {@@ -3092,6 +3101,8 @@ const enqueueCompiledSnapshot = (graph: GraphContract;positivePrompts?: string[];widgetStates: WidgetStateMap;+ /** The workflow route's seed plan: batch data, run count, and the fields to advance. */+ workflow?: Omit<WorkflowSubmissionPlan, 'graph'>;},backendSupportsCancellation: boolean,canvasSnapshot?: CanvasStateContractV3@@ -3166,7 +3177,8 @@ const enqueueCompiledSnapshot = (? { error: `${route.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' }: route.sourceId === 'workflow'? {- batchCount: sanitizeBatchCount(widgetStates.generate?.values.batchCount),+ batchCount: compiled.workflow?.runs ?? sanitizeBatchCount(widgetStates.generate?.values.batchCount),+ ...(compiled.workflow?.data ? { data: compiled.workflow.data } : {}),graph: backendGraph,kind: 'workflow',// Provenance for the completed-run capture: a run submitted from a@@ -3245,7 +3257,9 @@ const enqueueCompiledSnapshot = (batchCount:backendSubmission.kind === 'invalid'? 1- : backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),+ : compiled.workflow+ ? compiled.workflow.generationCount+ : backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),height: presentationDimensions.height,// The merged prompt, so the queue row reads the same before and after the// backend session arrives with its own (already merged) field values.@@ -3272,13 +3286,21 @@ const enqueueCompiledSnapshot = (// may be stale by the time it lands: only settings still at the submitted// seed and mode are advanced; an edit made meanwhile is the user's, and stays.const advancedProject =- seedPlan === null || seedPlan.nextSeed === null- ? project- : updateProjectWidgetValues(project, route.sourceId === 'canvas' ? 'generate' : route.sourceId, (values) =>+ seedPlan !== null && seedPlan.nextSeed !== null+ ? updateProjectWidgetValues(project, route.sourceId === 'canvas' ? 'generate' : route.sourceId, (values) =>values.seed === seedPlan.startSeed && values.seedMode === seedPlan.seedMode? { ...values, seed: seedPlan.nextSeed }: values- );+ )+ : compiled.workflow && compiled.workflow.seedAdvances.length > 0+ ? {+ ...project,+ projectGraph: projectGraphReducer(project.projectGraph, {+ advances: compiled.workflow.seedAdvances,+ type: 'advanceSeedFields',+ }),+ }+ : project;return {...advancedProject,