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): seed modes replace the random seed toggle

Josh Corbett2112b58d83bb
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 7361441384..f0840a3290 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2059,6 +2059,7 @@
"resizeWildcardValues": "Resize wildcard values",
"mode": "Mode",
"newSeedPerImage": "New seed for every image",
+ "seedHeldForEveryImage": "A fixed seed is used for every image.",
"import": "Import",
"export": "Export",
"exportAsYaml": "As YAML",
@@ -2191,6 +2192,20 @@
"promptHistoryEntries": "Prompt history entries",
"promptHistoryKeyboardHelp": "Alt+Up/Down switches between prompts while focused.",
"recentSeeds": "Recent seeds",
+ "seedMode": {
+ "label": "Seed mode",
+ "random": "Random",
+ "randomDescription": "Choose a fresh starting seed for each submission.",
+ "fixed": "Fixed",
+ "fixedDescription": "Reuse the entered seed.",
+ "increment": "Increment",
+ "incrementDescription": "Use successive seeds, increasing by 1.",
+ "decrement": "Decrement",
+ "decrementDescription": "Use successive seeds, decreasing by 1."
+ },
+ "seedNextBatch": "Next batch: {{seed}}",
+ "seedNextBatchRange": "Next batch: {{first}} → {{last}}",
+ "seedSummary": "{{mode}} · {{seed}}",
"renamePresetNamed": "Rename preset {{name}}",
"renamePresetTitle": "Rename preset",
"resetToModelDefault": "Reset to model default",
@@ -2283,8 +2298,6 @@
"loading": "Loading templates…"
},
"promptTriggerOptions": "Prompt trigger options",
- "random": "Random",
- "randomEachRun": "Random each run",
"readyWithIterations_one": "Ready · {{count}} iteration",
"readyWithIterations_other": "Ready · {{count}} iterations",
"referenceImage": "Reference Image",
diff --git a/invokeai/frontend/webv2/src/features/generation/contracts.ts b/invokeai/frontend/webv2/src/features/generation/contracts.ts
index 7dff1a82ce..f30d048a07 100644
--- a/invokeai/frontend/webv2/src/features/generation/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/contracts.ts
@@ -1,3 +1,4 @@
export type * from './core/contracts';
export type * from './core/types';
+export type { SeedMode, SeedStep, SeedSubmissionPlan } from './core/settings';
export type { CanvasScaleMethod, CanvasScalingSettings } from './core/canvas/types';
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
index 73bc15c681..bd5623c967 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
@@ -39,7 +39,7 @@ const createModel = (base: string, overrides: Partial<MainModelConfig> = {}): Ma
const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({
...getDefaultGenerateSettings(model),
seed: 1,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
...overrides,
});
@@ -598,7 +598,7 @@ describe('component policies', () => {
negativePrompt: 'blurry',
positivePrompt: 'a lighthouse',
seed: 1234,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
vae: sdxlVae,
});
@@ -610,7 +610,7 @@ describe('component policies', () => {
negativePrompt: 'blurry',
positivePrompt: 'a lighthouse',
seed: 1234,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
vae: sdxlVae,
});
expect(result.clearedLabels).toEqual([]);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index f7155cd1c4..4a0cbfb48e 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -678,7 +678,7 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): Generat
seamlessXAxis: false,
seamlessYAxis: false,
seed: Math.floor(Math.random() * SEED_MAX),
- shouldRandomizeSeed: true,
+ seedMode: 'random',
steps: defaults.steps,
t5EncoderModel: null,
vae: null,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
index 9652519d24..f97421bb27 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
@@ -84,7 +84,7 @@ const PROJECT_SETTINGS: GenerationProjectSettings = { useCpuNoise: true };
const settingsFor = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({
...getDefaultGenerateSettings(model),
seed: 1,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
...overrides,
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
index 2429462990..88ac835e51 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@ -10,7 +10,7 @@ import type {
} from './types';
import { getDefaultGenerateSettings, isSupportedGenerateModel } from './baseGenerationPolicies';
-import { compileGenerateGraph, generateSeedSequence, resolveGenerateSeed } from './graph';
+import { compileGenerateGraph, resolveGenerateSeed } from './graph';
const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };
const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };
@@ -137,7 +137,7 @@ const qwen3Encoder: ComponentModelConfig = {
const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({
...getDefaultGenerateSettings(model),
seed: 1,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
...overrides,
});
@@ -692,23 +692,19 @@ describe('compileGenerateGraph', () => {
});
describe('generate seeds', () => {
- it('keeps an explicit seed when randomization is disabled', () => {
- const settings = createSettings(sdxlModel, { seed: 123, shouldRandomizeSeed: false });
-
- expect(resolveGenerateSeed(settings)).toBe(123);
+ it('keeps the entered seed in every mode but random', () => {
+ expect(resolveGenerateSeed(createSettings(sdxlModel, { seed: 123, seedMode: 'fixed' }))).toBe(123);
+ expect(resolveGenerateSeed(createSettings(sdxlModel, { seed: 123, seedMode: 'increment' }))).toBe(123);
+ expect(resolveGenerateSeed(createSettings(sdxlModel, { seed: 123, seedMode: 'decrement' }))).toBe(123);
});
- it('resolves a random seed when randomization is enabled', () => {
+ it('draws a fresh seed in random mode', () => {
vi.spyOn(Math, 'random').mockReturnValue(0.5);
- const settings = createSettings(sdxlModel, { seed: 123, shouldRandomizeSeed: true });
+ const settings = createSettings(sdxlModel, { seed: 123, seedMode: 'random' });
expect(resolveGenerateSeed(settings)).toBe(2147483647);
});
-
- it('builds the legacy-style sequential seed batch starting from the resolved seed', () => {
- expect(generateSeedSequence(10, 4)).toEqual([10, 11, 12, 13]);
- });
});
describe('Krea-2, Ideogram 4 and Wan graphs', () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index 79325964c9..dc5981540d 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -1457,15 +1457,4 @@ export const compileGenerateGraph = (
};
export const resolveGenerateSeed = (settings: GenerateSettings): number =>
- settings.shouldRandomizeSeed ? Math.floor(Math.random() * SEED_MAX) : settings.seed;
-
-export const generateSeedSequence = (start: number, count: number): number[] => {
- const seedCount = Math.max(1, Math.round(count));
- const seeds: number[] = [];
-
- for (let index = 0; index < seedCount; index += 1) {
- seeds.push((start + index) % SEED_MAX);
- }
-
- return seeds;
-};
+ settings.seedMode === 'random' ? Math.floor(Math.random() * SEED_MAX) : settings.seed;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts
index 651e322737..f72664d03e 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/previewGraph.test.ts
@@ -29,7 +29,7 @@ const storedValues = createGenerateValues({
height: 1024,
loras: [loraA, loraB],
seed: 123,
- shouldRandomizeSeed: true,
+ seedMode: 'random',
steps: 28,
width: 1024,
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts
index 83f13ed44b..d434bf0ef0 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/resolveGenerateWidgetValues.test.ts
@@ -17,7 +17,7 @@ const createValues = (model: MainModelConfig, overrides: Partial<GenerateWidgetV
...getDefaultGenerateSettings(model),
model,
seed: 1,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
...overrides,
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
index b11f9eedbd..ef2e8cbe1d 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
@@ -17,13 +17,19 @@ import {
deriveAspectRatioId,
getDefaultLoraWeight,
getModelDefaultVae,
+ getSeedSequenceLength,
+ getSeedStep,
hasModelDefaultVae,
isLoraCompatibleWithModel,
isGenerateSettings,
+ isSeedMode,
moveReferenceImage,
normalizeGenerateSettings,
+ planSeedSubmission,
+ SEED_MAX,
syncGenerateWidgetValuesWithModels,
syncGenerateLorasWithModels,
+ wrapSeed,
} from './settings';
/** The persisted widget-value shape from before aspect ratio / VAE / seamless / CLIP skip landed. */
@@ -43,6 +49,24 @@ const legacyStoredValues = {
};
describe('normalizeGenerateSettings', () => {
+ it('reads the seed mode saved before modes existed from the random toggle', () => {
+ expect(normalizeGenerateSettings(legacyStoredValues)?.seedMode).toBe('fixed');
+ expect(normalizeGenerateSettings({ ...legacyStoredValues, shouldRandomizeSeed: true })?.seedMode).toBe('random');
+ // A saved mode wins over a stale toggle left behind by a partial patch.
+ expect(
+ normalizeGenerateSettings({ ...legacyStoredValues, seedMode: 'decrement', shouldRandomizeSeed: true })?.seedMode
+ ).toBe('decrement');
+ expect(
+ normalizeGenerateSettings({ ...legacyStoredValues, seedMode: 'bogus', shouldRandomizeSeed: true })?.seedMode
+ ).toBe('random');
+ });
+
+ it('rejects values that name neither a seed mode nor the random toggle', () => {
+ const { shouldRandomizeSeed: _, ...withoutSeedPolicy } = legacyStoredValues;
+
+ expect(normalizeGenerateSettings(withoutSeedPolicy)).toBeNull();
+ });
+
it('enforces template view mode only when a valid template remains', () => {
const validTemplate = {
id: 'template-1',
@@ -451,3 +475,103 @@ describe('dimension helpers', () => {
expect(clampDimension(888, getGenerationDimensions({ base: 'flux2', type: 'main' }).grid)).toBe(896);
});
});
+
+describe('seed modes', () => {
+ it('recognizes only the four modes', () => {
+ expect(isSeedMode('random')).toBe(true);
+ expect(isSeedMode('decrement')).toBe(true);
+ expect(isSeedMode('shuffle')).toBe(false);
+ expect(isSeedMode(true)).toBe(false);
+ });
+
+ it('steps forward for random, since a random start still runs consecutive seeds', () => {
+ expect(getSeedStep('random')).toBe(1);
+ expect(getSeedStep('increment')).toBe(1);
+ expect(getSeedStep('fixed')).toBe(0);
+ expect(getSeedStep('decrement')).toBe(-1);
+ });
+
+ it('wraps over the inclusive seed range in both directions', () => {
+ expect(wrapSeed(SEED_MAX)).toBe(SEED_MAX);
+ expect(wrapSeed(SEED_MAX + 1)).toBe(0);
+ expect(wrapSeed(-1)).toBe(SEED_MAX);
+ expect(wrapSeed(-2)).toBe(SEED_MAX - 1);
+ });
+});
+
+describe('getSeedSequenceLength', () => {
+ it('uses one seed for the whole fixed submission, whatever its shape', () => {
+ expect(
+ getSeedSequenceLength({ batchCount: 3, promptCount: 2, seedBehaviour: 'per-image', seedMode: 'fixed' })
+ ).toBe(1);
+ });
+
+ it('takes one entry per iteration unless every image of a prompt set gets its own', () => {
+ expect(
+ getSeedSequenceLength({ batchCount: 3, promptCount: 1, seedBehaviour: 'per-image', seedMode: 'increment' })
+ ).toBe(3);
+ expect(
+ getSeedSequenceLength({ batchCount: 3, promptCount: 2, seedBehaviour: 'per-iteration', seedMode: 'increment' })
+ ).toBe(3);
+ expect(
+ getSeedSequenceLength({ batchCount: 3, promptCount: 2, seedBehaviour: 'per-image', seedMode: 'random' })
+ ).toBe(6);
+ });
+});
+
+describe('planSeedSubmission', () => {
+ const plan = (seedMode: Parameters<typeof planSeedSubmission>[0]['seedMode'], startSeed = 42, batchCount = 3) =>
+ planSeedSubmission({ batchCount, promptCount: 1, seedBehaviour: 'per-iteration', seedMode, startSeed });
+
+ it('advances the editable seed past the batch only in the stepping modes', () => {
+ expect(plan('increment')).toEqual({
+ lastSeed: 44,
+ nextSeed: 45,
+ seedMode: 'increment',
+ sequenceLength: 3,
+ startSeed: 42,
+ step: 1,
+ });
+ expect(plan('decrement')).toEqual({
+ lastSeed: 40,
+ nextSeed: 39,
+ seedMode: 'decrement',
+ sequenceLength: 3,
+ startSeed: 42,
+ step: -1,
+ });
+ expect(plan('fixed')).toEqual({
+ lastSeed: 42,
+ nextSeed: null,
+ seedMode: 'fixed',
+ sequenceLength: 1,
+ startSeed: 42,
+ step: 0,
+ });
+ expect(plan('random')).toEqual({
+ lastSeed: 44,
+ nextSeed: null,
+ seedMode: 'random',
+ sequenceLength: 3,
+ startSeed: 42,
+ step: 1,
+ });
+ });
+
+ it('wraps the next seed at either end of the range', () => {
+ expect(plan('increment', SEED_MAX - 1, 2)).toMatchObject({ lastSeed: SEED_MAX, nextSeed: 0 });
+ expect(plan('decrement', 1, 2)).toMatchObject({ lastSeed: 0, nextSeed: SEED_MAX });
+ });
+
+ it('advances by every seed a prompt set consumes', () => {
+ expect(
+ planSeedSubmission({
+ batchCount: 2,
+ promptCount: 2,
+ seedBehaviour: 'per-image',
+ seedMode: 'increment',
+ startSeed: 42,
+ })
+ ).toMatchObject({ lastSeed: 45, nextSeed: 46, sequenceLength: 4 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index 21ca6a5261..16fb3c2f11 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -1,3 +1,4 @@
+import type { DynamicPromptsConfig } from './dynamicPrompts';
import type {
AspectRatioId,
ComponentModelConfig,
@@ -68,6 +69,22 @@ export const MIN_DIMENSION = 64;
export const MAX_DIMENSION = 4096;
export const SEED_MAX = 4_294_967_295;
+
+/** The expansion config the settings describe, under the names the expansion route and preview use. */
+export const getDynamicPromptsConfig = (
+ settings: Pick<
+ GenerateSettings,
+ | 'dynamicPromptsCombinatorial'
+ | 'dynamicPromptsMaxPrompts'
+ | 'dynamicPromptsSampleSeed'
+ | 'dynamicPromptsSeedBehaviour'
+ >
+): DynamicPromptsConfig => ({
+ combinatorial: settings.dynamicPromptsCombinatorial,
+ maxPrompts: settings.dynamicPromptsMaxPrompts,
+ sampleSeed: settings.dynamicPromptsSampleSeed,
+ seedBehaviour: settings.dynamicPromptsSeedBehaviour,
+});
export const MIN_NEGATIVE_PROMPT_HEIGHT_PX = 56;
export const MAX_NEGATIVE_PROMPT_HEIGHT_PX = 240;
export const DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX = 56;
@@ -661,7 +678,7 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n
typeof values.positivePrompt === 'string' &&
typeof values.negativePrompt === 'string' &&
typeof values.scheduler === 'string' &&
- typeof values.shouldRandomizeSeed === 'boolean' &&
+ (isSeedMode(values.seedMode) || typeof values.shouldRandomizeSeed === 'boolean') &&
['width', 'height', 'steps', 'cfgScale', 'cfgRescaleMultiplier', 'seed'].every((key) =>
hasFiniteNumber(values, key)
);
@@ -748,7 +765,8 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n
seamlessXAxis: typeof values.seamlessXAxis === 'boolean' ? values.seamlessXAxis : false,
seamlessYAxis: typeof values.seamlessYAxis === 'boolean' ? values.seamlessYAxis : false,
seed: values.seed as number,
- shouldRandomizeSeed: values.shouldRandomizeSeed as boolean,
+ // Values saved before seed modes carry the random toggle instead.
+ seedMode: isSeedMode(values.seedMode) ? values.seedMode : values.shouldRandomizeSeed ? 'random' : 'fixed',
steps: values.steps as number,
vae: isVaeModelConfig(values.vae) ? values.vae : null,
vaePrecision: isVaePrecision(values.vaePrecision) ? values.vaePrecision : 'fp32',
@@ -873,3 +891,76 @@ export const isGenerateSettings = (values: unknown): values is GenerateSettings
export const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues =>
isGenerateSettings(values) && isGenerateModelConfig((values as unknown as Record<string, unknown>).model);
+
+export const SEED_MODES = ['random', 'fixed', 'increment', 'decrement'] as const;
+
+export type SeedMode = (typeof SEED_MODES)[number];
+
+/** Direction the seed moves between the entries of one submission's sequence. */
+export type SeedStep = -1 | 0 | 1;
+
+export const isSeedMode = (value: unknown): value is SeedMode => SEED_MODES.includes(value as SeedMode);
+
+export const getSeedStep = (mode: SeedMode): SeedStep => (mode === 'fixed' ? 0 : mode === 'decrement' ? -1 : 1);
+
+/** Wraps over the inclusive seed range so decrementing past 0 lands on `SEED_MAX`. */
+export const wrapSeed = (seed: number): number => {
+ const range = SEED_MAX + 1;
+
+ return ((seed % range) + range) % range;
+};
+
+export interface SeedSequenceInput {
+ batchCount: number;
+ /** Concrete prompts the submission carries; one unless dynamic prompts expanded it. */
+ promptCount: number;
+ seedBehaviour: 'per-image' | 'per-iteration';
+ seedMode: SeedMode;
+}
+
+/**
+ * How many entries of the seed sequence one submission uses. A fixed seed uses
+ * its single entry however many images run. Otherwise every iteration takes an
+ * entry, and with several prompts sharing disabled every image does.
+ */
+export const getSeedSequenceLength = ({
+ batchCount,
+ promptCount,
+ seedBehaviour,
+ seedMode,
+}: SeedSequenceInput): number =>
+ seedMode === 'fixed' ? 1 : promptCount > 1 && seedBehaviour === 'per-image' ? promptCount * batchCount : batchCount;
+
+export interface SeedSubmissionPlan {
+ /** The last sequence entry the submission uses. */
+ lastSeed: number;
+ /** What the editable seed becomes once the submission is queued; null when the mode leaves it alone. */
+ nextSeed: number | null;
+ seedMode: SeedMode;
+ sequenceLength: number;
+ startSeed: number;
+ step: SeedStep;
+}
+
+/**
+ * The seeds a submission consumes and where the editable seed goes afterwards.
+ * Only the stepping modes advance it: random keeps the manual value in reserve,
+ * fixed reuses it.
+ */
+export const planSeedSubmission = ({
+ startSeed,
+ ...sequence
+}: SeedSequenceInput & { startSeed: number }): SeedSubmissionPlan => {
+ const step = getSeedStep(sequence.seedMode);
+ const sequenceLength = getSeedSequenceLength(sequence);
+ const advances = sequence.seedMode === 'increment' || sequence.seedMode === 'decrement';
+
+ return {
+ lastSeed: wrapSeed(startSeed + step * (sequenceLength - 1)),
+ nextSeed: advances ? wrapSeed(startSeed + step * sequenceLength) : null,
+ seedMode: sequence.seedMode,
+ sequenceLength,
+ startSeed,
+ step,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.ts
index 996263aa5c..e6f239313c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts
@@ -1,6 +1,7 @@
import type { BackendGraphContract, GraphContract } from '@features/generation/core/contracts';
import type { DynamicPromptsSeedBehaviour } from '@features/generation/core/dynamicPrompts';
import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
+import type { SeedMode } from '@features/generation/core/settings';
export type ModelIdentifierConfig = {
key: string;
@@ -198,7 +199,7 @@ export interface GenerateSettings {
hiDiffusionT1Ratio: number;
hiDiffusionT2Ratio: number;
seed: number;
- shouldRandomizeSeed: boolean;
+ seedMode: SeedMode;
seamlessXAxis: boolean;
seamlessYAxis: boolean;
/** Optional VAE override; null uses the VAE bundled with the main model. */
diff --git a/invokeai/frontend/webv2/src/features/generation/runtime.test.ts b/invokeai/frontend/webv2/src/features/generation/runtime.test.ts
index 55ac91f82d..d179892ae2 100644
--- a/invokeai/frontend/webv2/src/features/generation/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/runtime.test.ts
@@ -41,7 +41,7 @@ const createValues = (model: MainModelConfig, overrides: Partial<GenerateWidgetV
...getDefaultGenerateSettings(model),
model,
seed: 1,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
...overrides,
});
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index ac78d1f31d..42da326281 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -71,6 +71,15 @@ export {
type RebalancePreset,
} from './core/conditioningRebalance';
export { MIN_BATCH_COUNT, sanitizeBatchCount } from './core/batch';
+export {
+ getSeedStep,
+ isSeedMode,
+ planSeedSubmission,
+ SEED_MODES,
+ type SeedMode,
+ type SeedStep,
+ type SeedSubmissionPlan,
+} from './core/settings';
export {
createDynamicPromptsSampleSeed,
DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx
index d531d231de..0331f222dc 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx
@@ -44,7 +44,7 @@ type PresetDialogState = { mode: 'save' } | { mode: 'rename'; preset: GeneratePr
* "These settings are still this preset" must ignore what applying a preset
* does not write (`getGenerateFormCommitPatch` drops `batchCount`) and what is
* presentation or volatile: prompt-box heights, the template view mode, and
- * the seed while it randomizes.
+ * the seed unless it is held fixed — random draws it, stepping moves it.
*/
const getPresetComparisonKey = (settings: GenerateSettings): string => {
const comparable: Record<string, unknown> = { ...settings };
@@ -54,7 +54,7 @@ const getPresetComparisonKey = (settings: GenerateSettings): string => {
delete comparable.positivePromptHeightPx;
delete comparable.promptTemplateViewMode;
- if (settings.shouldRandomizeSeed) {
+ if (settings.seedMode !== 'fixed') {
delete comparable.seed;
}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx
new file mode 100644
index 0000000000..dcc48308fc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx
@@ -0,0 +1,199 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { GenerateSettings, MainModelConfig } from '@features/generation/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { GenerateRenderSection } from './GenerateRenderSection';
+
+const seedHistory = [
+ { seed: 777, thumbnailUrl: null },
+ { seed: 888, thumbnailUrl: null },
+];
+
+vi.mock('./GenerationUiContext', () => ({
+ useGenerationUi: () => ({
+ queueInsights: { secondsPerRun: null, seedHistory },
+ sectionPreferences: { sectionsOpen: { render: true }, setSectionOpen: vi.fn() },
+ }),
+}));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ common: { seed: 'Seed' },
+ widgets: {
+ generate: {
+ newSeed: 'New seed',
+ recentSeeds: 'Recent seeds',
+ render: 'Render',
+ seedMode: {
+ decrement: 'Decrement',
+ decrementDescription: 'Use successive seeds, decreasing by 1.',
+ fixed: 'Fixed',
+ fixedDescription: 'Reuse the entered seed.',
+ increment: 'Increment',
+ incrementDescription: 'Use successive seeds, increasing by 1.',
+ label: 'Seed mode',
+ random: 'Random',
+ randomDescription: 'Choose a fresh starting seed for each submission.',
+ },
+ seedNextBatch: 'Next batch: {{seed}}',
+ seedNextBatchRange: 'Next batch: {{first}} → {{last}}',
+ seedSummary: '{{mode}} · {{seed}}',
+ steps: 'Steps',
+ useSeed: 'Use seed {{seed}}',
+ },
+ },
+ },
+ },
+ },
+});
+
+const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1', name: 'SD 1.5', type: 'main' };
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const settle = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 50);
+ });
+ });
+
+const render = async (overrides: Partial<GenerateSettings>) => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ const settings: GenerateSettings = { ...getDefaultGenerateSettings(sd1Model), seed: 42, ...overrides };
+ const onCommit = vi.fn();
+
+ await settle(() => {
+ root?.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <GenerateRenderSection
+ selectedModel={sd1Model}
+ settings={settings}
+ onCommit={onCommit}
+ onCommitImmediate={vi.fn()}
+ />
+ </I18nextProvider>
+ </ChakraProvider>
+ </QueryClientProvider>
+ );
+ });
+
+ return onCommit;
+};
+
+const seedInput = () => host?.querySelector<HTMLInputElement>('input[aria-label="Seed"]') ?? null;
+const modeTrigger = () => host?.querySelector<HTMLButtonElement>('button[aria-label^="Seed mode:"]') ?? null;
+const menuItem = (label: string) =>
+ [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find((item) =>
+ item.textContent?.startsWith(label)
+ ) ?? null;
+const preview = () => host?.querySelector('[data-testid="seed-sequence-preview"]')?.textContent ?? null;
+
+afterEach(async () => {
+ await settle(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GenerateRenderSection seed field', () => {
+ it('quiets the input in random mode but keeps the entered seed on show', async () => {
+ await render({ seedMode: 'random' });
+
+ expect(seedInput()?.disabled).toBe(true);
+ expect(seedInput()?.value).toBe('42');
+ expect(host?.querySelector<HTMLButtonElement>('button[aria-label="New seed"]')?.disabled).toBe(true);
+ expect(modeTrigger()?.getAttribute('aria-label')).toBe('Seed mode: Random');
+ expect(preview()).toBeNull();
+ });
+
+ it('commits a mode chosen from the menu without touching the seed', async () => {
+ const onCommit = await render({ seedMode: 'random' });
+
+ await settle(() => modeTrigger()?.click());
+ const increment = menuItem('Increment');
+
+ expect(increment?.getAttribute('aria-checked')).toBe('false');
+ expect(menuItem('Random')?.getAttribute('aria-checked')).toBe('true');
+ expect(increment?.textContent).toContain('Use successive seeds, increasing by 1.');
+
+ await settle(() => increment?.click());
+
+ expect(onCommit).toHaveBeenCalledWith({ seedMode: 'increment' });
+ });
+
+ it('is operable from the keyboard and returns focus to the trigger', async () => {
+ const onCommit = await render({ seedMode: 'random' });
+ const trigger = modeTrigger();
+
+ await settle(() => trigger?.focus());
+ await settle(() => trigger?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' })));
+ // The menu itself takes focus and tracks the highlighted item by attribute.
+ const menu = document.activeElement;
+
+ expect(menu?.getAttribute('role')).toBe('menu');
+
+ // Enter opens on the first mode; one step down lands on the second.
+ await settle(() => menu?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown' })));
+
+ expect(document.querySelector('[role="menuitemradio"][data-highlighted]')?.getAttribute('data-value')).toBe(
+ 'fixed'
+ );
+
+ await settle(() => menu?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' })));
+
+ expect(onCommit).toHaveBeenCalledWith({ seedMode: 'fixed' });
+ expect(document.activeElement).toBe(trigger);
+ });
+
+ it('previews the seeds the next batch will run in a stepping mode', async () => {
+ await render({ batchCount: 3, seedMode: 'increment' });
+
+ expect(seedInput()?.disabled).toBe(false);
+ expect(preview()).toBe('Next batch: 42 → 44');
+ expect(document.getElementById(seedInput()?.getAttribute('aria-describedby') ?? '')?.textContent).toBe(
+ 'Next batch: 42 → 44'
+ );
+ });
+
+ it('previews a single-seed batch without a range', async () => {
+ await render({ batchCount: 1, seedMode: 'decrement' });
+
+ expect(preview()).toBe('Next batch: 42');
+ });
+
+ it('pins a recent seed by switching to fixed', async () => {
+ const onCommit = await render({ seedMode: 'increment' });
+
+ await settle(() => host?.querySelector<HTMLButtonElement>('button[aria-label="Use seed 888"]')?.click());
+
+ expect(onCommit).toHaveBeenCalledWith({ seed: 888, seedMode: 'fixed' });
+ });
+
+ it('names the active mode in the collapsed summary', async () => {
+ await render({ seedMode: 'decrement' });
+
+ expect(host?.textContent).toContain('Decrement · 42');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx
index ab70d4bfe4..c9baf31e62 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx
@@ -1,32 +1,20 @@
/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */
import type { GenerateModelConfig, GenerateSettings, Ideogram4SamplerPreset } from '@features/generation/core/types';
-import {
- Badge,
- Box,
- createListCollection,
- HStack,
- Image,
- Input,
- InputGroup,
- NumberInput,
- Stack,
- Text,
-} from '@chakra-ui/react';
+import { Badge, Box, createListCollection, HStack, Image, Input, Stack, Text } from '@chakra-ui/react';
import { getDefaultGenerateSettings, getGenerationModelPolicy } from '@features/generation/core/baseGenerationPolicies';
+import { getEffectivePrompts } from '@features/generation/core/promptTemplates';
import {
+ getDynamicPromptsConfig,
IDEOGRAM4_SAMPLER_PRESETS,
MAX_KREA2_SEED_VARIANCE_STRENGTH,
- SEED_MAX,
} from '@features/generation/core/settings';
-import { IconButton } from '@platform/ui/Button';
import { Combobox } from '@platform/ui/Combobox';
import { Field } from '@platform/ui/Field';
import { ModelDefaultButton } from '@platform/ui/ModelDefaultButton';
import { Select } from '@platform/ui/Select';
import { SliderNumberField } from '@platform/ui/SliderNumberField';
import { Tooltip } from '@platform/ui/Tooltip';
-import { DicesIcon, ShuffleIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { GenerateConditioningRebalanceField } from './GenerateConditioningRebalanceField';
@@ -34,11 +22,11 @@ import { useGenerationUi } from './GenerationUiContext';
import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';
import { GenerateFieldContextMenu } from './shared/GenerateFieldContextMenu';
import { GenerateToggleSwitch } from './shared/GenerateToggleSwitch';
+import { SeedField as SharedSeedField } from './shared/SeedField';
+import { useDynamicPrompts } from './useDynamicPrompts';
const STEPS_SLIDER_MAX = 100;
-const SEED_END_ELEMENT_PROPS = { pointerEvents: 'auto', pr: '0.5' } as const;
-
interface GenerateRenderSectionProps {
settings: GenerateSettings;
selectedModel: GenerateModelConfig | undefined;
@@ -239,97 +227,56 @@ const Krea2SeedVarianceFields = ({ onCommit, settings }: Pick<GenerateRenderSect
};
/**
- * One seed field with the shuffle-new-seed action inside it, and a random
- * toggle beside it: pressed means every queued run draws a fresh seed and the
- * pinned value goes quiet. `shouldRandomizeSeed` persists unchanged underneath.
+ * The shared seed row, with the executed seeds of recent runs underneath —
+ * each behind its result, so a seed stops being a magic number and becomes
+ * "that image's recipe". Clicking one pins it, switching to fixed mode.
*/
const SeedField = ({ onCommit, settings }: Pick<GenerateRenderSectionProps, 'onCommit' | 'settings'>) => {
const { t } = useTranslation();
const { seedHistory } = useGenerationUi().queueInsights;
- const randomLabel = t('widgets.generate.randomEachRun');
+ // The same query the topbar observes, so a prompt set counts its seeds the
+ // way the batch will without a second expansion request or cache entry.
+ const expansion = useDynamicPrompts(getEffectivePrompts(settings).positivePrompt, getDynamicPromptsConfig(settings));
return (
- <Field hint="seed" label={t('common.seed')}>
- <Stack gap="1" w="full">
- <HStack gap="1">
- <NumberInput.Root
- disabled={settings.shouldRandomizeSeed}
- max={SEED_MAX}
- min={0}
- size="xs"
- value={String(settings.seed)}
- w="full"
- onValueChange={({ valueAsNumber }) => {
- if (Number.isFinite(valueAsNumber)) {
- onCommit({ seed: valueAsNumber });
- }
- }}
- >
- <InputGroup
- endElement={
- <IconButton
- aria-label={t('widgets.generate.newSeed')}
- color="fg.muted"
- disabled={settings.shouldRandomizeSeed}
- size="2xs"
- title={t('widgets.generate.newSeed')}
- variant="ghost"
- onClick={() => onCommit({ seed: Math.floor(Math.random() * SEED_MAX) })}
- >
- <DicesIcon />
- </IconButton>
- }
- endElementProps={SEED_END_ELEMENT_PROPS}
- >
- <NumberInput.Input aria-label={t('common.seed')} />
- </InputGroup>
- </NumberInput.Root>
- <Tooltip content={randomLabel}>
- <IconButton
- aria-label={randomLabel}
- aria-pressed={settings.shouldRandomizeSeed}
- flexShrink="0"
- size="xs"
- variant={settings.shouldRandomizeSeed ? 'solid' : 'outline'}
- onClick={() => onCommit({ shouldRandomizeSeed: !settings.shouldRandomizeSeed })}
- >
- <ShuffleIcon />
- </IconButton>
- </Tooltip>
+ <SharedSeedField
+ batchCount={settings.batchCount}
+ label={t('common.seed')}
+ promptCount={expansion.prompts.length}
+ seed={settings.seed}
+ seedBehaviour={settings.dynamicPromptsSeedBehaviour}
+ seedMode={settings.seedMode}
+ onCommit={onCommit}
+ >
+ {seedHistory.length > 0 ? (
+ <HStack gap="1" pt="0.5">
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('widgets.generate.recentSeeds')}
+ </Text>
+ {seedHistory.map((item) => (
+ <Tooltip key={item.seed} content={t('widgets.generate.useSeed', { seed: item.seed })}>
+ <Box
+ aria-label={t('widgets.generate.useSeed', { seed: item.seed })}
+ as="button"
+ bg="bg.emphasized"
+ borderColor={
+ settings.seedMode !== 'random' && settings.seed === item.seed ? 'accent.solid' : 'border.subtle'
+ }
+ borderWidth="1px"
+ boxSize="5"
+ overflow="hidden"
+ rounded="3px"
+ onClick={() => onCommit({ seed: item.seed, seedMode: 'fixed' })}
+ >
+ {item.thumbnailUrl ? (
+ <Image alt="" boxSize="full" draggable={false} objectFit="cover" src={item.thumbnailUrl} />
+ ) : null}
+ </Box>
+ </Tooltip>
+ ))}
</HStack>
- {/* The executed seeds of recent runs, each behind its result — a seed
- stops being a magic number and becomes "that image's recipe".
- Clicking one pins it, switching to fixed mode if needed. */}
- {seedHistory.length > 0 ? (
- <HStack gap="1" pt="0.5">
- <Text color="fg.subtle" fontSize="2xs">
- {t('widgets.generate.recentSeeds')}
- </Text>
- {seedHistory.map((item) => (
- <Tooltip key={item.seed} content={t('widgets.generate.useSeed', { seed: item.seed })}>
- <Box
- aria-label={t('widgets.generate.useSeed', { seed: item.seed })}
- as="button"
- bg="bg.emphasized"
- borderColor={
- !settings.shouldRandomizeSeed && settings.seed === item.seed ? 'accent.solid' : 'border.subtle'
- }
- borderWidth="1px"
- boxSize="5"
- overflow="hidden"
- rounded="3px"
- onClick={() => onCommit({ seed: item.seed, shouldRandomizeSeed: false })}
- >
- {item.thumbnailUrl ? (
- <Image alt="" boxSize="full" draggable={false} objectFit="cover" src={item.thumbnailUrl} />
- ) : null}
- </Box>
- </Tooltip>
- ))}
- </HStack>
- ) : null}
- </Stack>
- </Field>
+ ) : null}
+ </SharedSeedField>
);
};
@@ -363,7 +310,16 @@ export const GenerateRenderSection = ({
{settings.steps} · {policy.ui.guidanceLabel} {settings.cfgScale}
</Badge>
{policy.ui.seedVisible ? (
- <Badge size="xs">{settings.shouldRandomizeSeed ? t('widgets.generate.random') : settings.seed}</Badge>
+ <Badge size="xs">
+ {settings.seedMode === 'random'
+ ? t('widgets.generate.seedMode.random')
+ : settings.seedMode === 'fixed'
+ ? settings.seed
+ : t('widgets.generate.seedSummary', {
+ mode: t(`widgets.generate.seedMode.${settings.seedMode}`),
+ seed: settings.seed,
+ })}
+ </Badge>
) : null}
</>
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.test.ts
index 7313725e04..935126e16a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateFormViewModel.test.ts
@@ -37,7 +37,7 @@ const createSettings = (overrides: Partial<GenerateSettings> = {}): GenerateSett
seamlessXAxis: false,
seamlessYAxis: false,
seed: 123,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
steps: 30,
t5EncoderModel: null,
vae: null,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
index 78a4ae1985..8b58962a3d 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx
@@ -1,4 +1,4 @@
-import type { DynamicPromptsConfig } from '@features/generation/core/dynamicPrompts';
+import type { DynamicPromptsFieldConfig } from '@features/generation/ui/promptFields/DynamicPromptsPanel';
import { ChakraProvider } from '@chakra-ui/react';
import { DynamicPromptsButton } from '@features/generation/ui/promptFields/DynamicPromptsButton';
@@ -26,8 +26,9 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const config: DynamicPromptsConfig & { onChange: () => void } = {
+const config: DynamicPromptsFieldConfig = {
combinatorial: true,
+ isSeedFixed: false,
maxPrompts: 100,
onChange: vi.fn(),
sampleSeed: 0,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
index 77d765d150..6fce82308c 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
@@ -43,7 +43,7 @@ const BASE_CONFIG: DynamicPromptsConfig = {
* Renders with real state, so a control that reflects its own value (a segmented
* control does) can actually be toggled back and forth.
*/
-const render = async (onChange: (patch: Partial<DynamicPromptsConfig>) => void = vi.fn()) => {
+const render = async (onChange: (patch: Partial<DynamicPromptsConfig>) => void = vi.fn(), isSeedFixed = false) => {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -58,6 +58,7 @@ const render = async (onChange: (patch: Partial<DynamicPromptsConfig>) => void =
batchCount={2}
config={{
...config,
+ isSeedFixed,
onChange: (patch) => {
onChange(patch);
config = { ...config, ...patch };
@@ -110,6 +111,27 @@ afterEach(async () => {
});
describe('dynamic prompts popover controls', () => {
+ it('retires the seed sharing switch while the seed is held fixed', async () => {
+ const onChange = vi.fn();
+
+ await render(onChange, true);
+ await openPopover();
+
+ const seedSwitch = document.querySelector<HTMLElement>('[data-scope="switch"][data-part="root"]')!;
+ const hiddenInput = seedSwitch.querySelector<HTMLInputElement>('input')!;
+ const explanation = document.getElementById(hiddenInput.getAttribute('aria-describedby') ?? '');
+
+ expect(hiddenInput.disabled).toBe(true);
+ // No i18n instance here, so the key itself is the rendered text.
+ expect(explanation?.textContent).toBe('widgets.generate.dynamicPrompts.seedHeldForEveryImage');
+
+ // A retired switch ignores the label click that normally toggles it.
+ await act(() => seedSwitch.querySelector<HTMLElement>('[data-part="label"]')?.click());
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(pageErrors).toEqual([]);
+ });
+
it('switches seed behaviour without tearing down the widget', async () => {
// Regression: a Chakra Select here threw `r.options is not iterable` from
// syncSelectElement as the popover opened, taking the Generate widget down
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
index 8fa758abc9..3d3b3038a3 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsPanel.tsx
@@ -34,6 +34,8 @@ const MENU_POSITIONING = { placement: 'bottom-start' } as const;
const SWITCH_CHECKED = { bg: 'accent.solid' } as const;
export interface DynamicPromptsFieldConfig extends DynamicPromptsConfig {
+ /** A fixed seed applies to every image, so per-image sharing has nothing left to decide. */
+ isSeedFixed: boolean;
onChange: (patch: Partial<DynamicPromptsConfig>) => void;
}
@@ -63,6 +65,7 @@ export const DynamicPromptsPanel = ({
const modeLabelledBy = `${modeFieldId}-label ${modeTriggerId}`;
const modeMenuIds = useMemo(() => ({ trigger: modeTriggerId }), [modeTriggerId]);
const seedSwitchIds = useMemo(() => ({ hiddenInput: seedSwitchId, label: `${seedSwitchId}-label` }), [seedSwitchId]);
+ const seedHeldNoteId = `${seedSwitchId}-held`;
const visiblePrompts = expansion.prompts.slice(0, MAX_PREVIEW_ROWS);
const hiddenPromptCount = expansion.prompts.length - visiblePrompts.length;
@@ -189,11 +192,12 @@ export const DynamicPromptsPanel = ({
<Switch.Root
checked={config.seedBehaviour === 'per-image'}
+ disabled={config.isSeedFixed}
ids={seedSwitchIds}
size="sm"
onCheckedChange={handleSeedBehaviourChange}
>
- <Switch.HiddenInput />
+ <Switch.HiddenInput aria-describedby={config.isSeedFixed ? seedHeldNoteId : undefined} />
<Switch.Control _checked={SWITCH_CHECKED}>
<Switch.Thumb />
</Switch.Control>
@@ -201,6 +205,11 @@ export const DynamicPromptsPanel = ({
{t('widgets.generate.dynamicPrompts.newSeedPerImage')}
</Switch.Label>
</Switch.Root>
+ {config.isSeedFixed ? (
+ <Text color="fg.subtle" fontSize="2xs" id={seedHeldNoteId} mt="-1">
+ {t('widgets.generate.dynamicPrompts.seedHeldForEveryImage')}
+ </Text>
+ ) : null}
{expansion.isError ? (
<Text color="fg.error" fontSize="2xs">
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
index c77c57e7ea..bc9f379f50 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
@@ -126,6 +126,7 @@ export const GeneratePromptFields = ({
const dynamicPrompts = useMemo(
() => ({
combinatorial: settings.dynamicPromptsCombinatorial,
+ isSeedFixed: settings.seedMode === 'fixed',
maxPrompts: settings.dynamicPromptsMaxPrompts,
onChange: handleDynamicPromptsChange,
sampleSeed: settings.dynamicPromptsSampleSeed,
@@ -137,6 +138,7 @@ export const GeneratePromptFields = ({
settings.dynamicPromptsMaxPrompts,
settings.dynamicPromptsSampleSeed,
settings.dynamicPromptsSeedBehaviour,
+ settings.seedMode,
]
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/SeedField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/SeedField.tsx
new file mode 100644
index 0000000000..d5ec44a4d6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/SeedField.tsx
@@ -0,0 +1,167 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */
+import type { DynamicPromptsSeedBehaviour } from '@features/generation/core/dynamicPrompts';
+import type { SeedMode } from '@features/generation/core/settings';
+import type { ReactNode } from 'react';
+
+import { HStack, Icon, InputGroup, Menu, NumberInput, Portal, Stack, Text } from '@chakra-ui/react';
+import { planSeedSubmission, SEED_MAX, SEED_MODES } from '@features/generation/core/settings';
+import { Button, IconButton } from '@platform/ui/Button';
+import { Field } from '@platform/ui/Field';
+import { MenuContent } from '@platform/ui/Menu';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { ChevronDownIcon, DicesIcon } from 'lucide-react';
+import { useId, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const SEED_END_ELEMENT_PROPS = { pointerEvents: 'auto', pr: '0.5' } as const;
+const SEED_MODE_MENU_POSITIONING = { placement: 'bottom-end' } as const;
+const TABULAR_NUMS = { fontVariantNumeric: 'tabular-nums' } as const;
+
+/**
+ * How the seed moves from one submission to the next. A menu rather than a
+ * toggle because the choice has four answers, and each needs a line of
+ * explanation the first time it is read.
+ */
+const SeedModeMenu = ({ onChange, value }: { value: SeedMode; onChange: (mode: SeedMode) => void }) => {
+ const { t } = useTranslation();
+ // Shared ids let the tooltip ride the menu trigger without wrapping it
+ // (wrapping `Menu.Trigger` swallows the anchor ref — see RoutingControl).
+ const triggerId = useId();
+ const triggerIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);
+ const label = t('widgets.generate.seedMode.label');
+ const valueLabel = t(`widgets.generate.seedMode.${value}`);
+
+ return (
+ <Menu.Root ids={triggerIds} positioning={SEED_MODE_MENU_POSITIONING}>
+ <Tooltip content={label} ids={triggerIds}>
+ <Menu.Trigger asChild>
+ <Button aria-label={`${label}: ${valueLabel}`} flexShrink={0} gap="1" size="xs" variant="outline">
+ {valueLabel}
+ <Icon as={ChevronDownIcon} boxSize="3" color="fg.muted" />
+ </Button>
+ </Menu.Trigger>
+ </Tooltip>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="16rem">
+ <Menu.RadioItemGroup value={value} onValueChange={(event) => onChange(event.value as SeedMode)}>
+ {SEED_MODES.map((mode) => (
+ <Menu.RadioItem key={mode} py="1.5" value={mode}>
+ {/* The recipe centers the check on the row; on a two-line item it belongs on the label line. */}
+ <Menu.ItemIndicator top="2" transform="none" />
+ <Stack gap="0" minW="0">
+ <Menu.ItemText>{t(`widgets.generate.seedMode.${mode}`)}</Menu.ItemText>
+ <Text color="fg.subtle" fontSize="2xs">
+ {t(`widgets.generate.seedMode.${mode}Description`)}
+ </Text>
+ </Stack>
+ </Menu.RadioItem>
+ ))}
+ </Menu.RadioItemGroup>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
+
+export interface SeedFieldPatch {
+ seed?: number;
+ seedMode?: SeedMode;
+}
+
+export interface SeedFieldProps {
+ label: string;
+ /** Validation error for the entered seed; shown only while the seed is in use. */
+ error?: string | null;
+ seed: number;
+ seedMode: SeedMode;
+ /** Iterations the next submission runs, which sizes the stepping-mode preview. */
+ batchCount: number;
+ /** Concrete prompts the next submission carries; one unless dynamic prompts expand it. */
+ promptCount?: number;
+ seedBehaviour?: DynamicPromptsSeedBehaviour;
+ onCommit: (patch: SeedFieldPatch) => void;
+ /** Rows under the input, such as recent seeds. */
+ children?: ReactNode;
+}
+
+/**
+ * The seed row every seeded widget shares: the input with the one-shot
+ * new-seed action inside it and the mode menu beside it. Random quiets the
+ * input but keeps its value; the stepping modes show the seed the next
+ * submission starts from and preview where it will end.
+ */
+export const SeedField = ({
+ batchCount,
+ children,
+ error,
+ label,
+ onCommit,
+ promptCount = 1,
+ seed,
+ seedBehaviour = 'per-iteration',
+ seedMode,
+}: SeedFieldProps) => {
+ const { t } = useTranslation();
+ const previewId = useId();
+ const isRandom = seedMode === 'random';
+ const plan =
+ seedMode === 'increment' || seedMode === 'decrement'
+ ? planSeedSubmission({ batchCount, promptCount, seedBehaviour, seedMode, startSeed: seed })
+ : null;
+
+ return (
+ <Field error={isRandom ? undefined : error} hint="seed" label={label}>
+ <Stack gap="1" w="full">
+ <HStack gap="1">
+ <NumberInput.Root
+ disabled={isRandom}
+ max={SEED_MAX}
+ min={0}
+ size="xs"
+ value={String(seed)}
+ w="full"
+ onValueChange={({ valueAsNumber }) => {
+ if (Number.isFinite(valueAsNumber)) {
+ onCommit({ seed: valueAsNumber });
+ }
+ }}
+ >
+ <InputGroup
+ endElement={
+ <IconButton
+ aria-label={t('widgets.generate.newSeed')}
+ color="fg.muted"
+ disabled={isRandom}
+ size="2xs"
+ title={t('widgets.generate.newSeed')}
+ variant="ghost"
+ onClick={() => onCommit({ seed: Math.floor(Math.random() * SEED_MAX) })}
+ >
+ <DicesIcon />
+ </IconButton>
+ }
+ endElementProps={SEED_END_ELEMENT_PROPS}
+ >
+ <NumberInput.Input
+ aria-describedby={plan ? previewId : undefined}
+ aria-label={label}
+ css={TABULAR_NUMS}
+ />
+ </InputGroup>
+ </NumberInput.Root>
+ <SeedModeMenu value={seedMode} onChange={(nextMode) => onCommit({ seedMode: nextMode })} />
+ </HStack>
+ {plan ? (
+ <Text color="fg.subtle" css={TABULAR_NUMS} data-testid="seed-sequence-preview" fontSize="2xs" id={previewId}>
+ {plan.sequenceLength > 1
+ ? t('widgets.generate.seedNextBatchRange', { first: plan.startSeed, last: plan.lastSeed })
+ : t('widgets.generate.seedNextBatch', { seed: plan.startSeed })}
+ </Text>
+ ) : null}
+ {children}
+ </Stack>
+ </Field>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.ts
index 5710cddf25..a6e3de5196 100644
--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts
@@ -22,6 +22,7 @@ export type {
QueueProcessorReadModel,
QueueQueryScope,
QueueReadModel,
+ QueueSeedStep,
QueueSourceId,
QueueStatusReadModel,
QueueSubmissionPresentation,
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 b7751a1cb5..bb761b4a24 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,9 @@ import { describe, expect, it } from 'vitest';
import type { GeneratePromptBatchPlanInput } from './promptBatch';
-import { buildGeneratePromptBatchPlan } from './promptBatch';
+import { buildGeneratePromptBatchPlan, generateSeedSequence } from './promptBatch';
+
+const SEED_MAX = 4_294_967_295;
const baseInput = (overrides: Partial<GeneratePromptBatchPlanInput> = {}): GeneratePromptBatchPlanInput => ({
batchCount: 1,
@@ -13,14 +15,21 @@ const baseInput = (overrides: Partial<GeneratePromptBatchPlanInput> = {}): Gener
seed: 100,
seedBehaviour: 'per-iteration',
seedNodeId: 'seed',
- shouldRandomizeSeed: false,
+ seedStep: 0,
...overrides,
});
+describe('generateSeedSequence', () => {
+ it('wraps over the inclusive seed range in either direction', () => {
+ expect(generateSeedSequence(SEED_MAX - 1, 3)).toEqual([SEED_MAX - 1, SEED_MAX, 0]);
+ expect(generateSeedSequence(1, 3, -1)).toEqual([1, 0, SEED_MAX]);
+ });
+});
+
describe('buildGeneratePromptBatchPlan with a single prompt', () => {
// These two pin the pre-dynamic-prompts payload built by `enqueueGenerate`.
- it('matches the fixed-seed payload: one datum each, runs carries the batch count', () => {
- const plan = buildGeneratePromptBatchPlan(baseInput({ batchCount: 3, shouldRandomizeSeed: false }));
+ it('matches the held-seed payload: one datum each, runs carries the batch count', () => {
+ const plan = buildGeneratePromptBatchPlan(baseInput({ batchCount: 3, seedStep: 0 }));
expect(plan.data).toEqual([
[
@@ -33,8 +42,8 @@ describe('buildGeneratePromptBatchPlan with a single prompt', () => {
expect(plan.expectedImageCount).toBe(3);
});
- it('matches the randomized-seed payload: a seed sequence zipped with repeated prompts', () => {
- const plan = buildGeneratePromptBatchPlan(baseInput({ batchCount: 3, shouldRandomizeSeed: true }));
+ it('matches the stepping-seed payload: a seed sequence zipped with repeated prompts', () => {
+ const plan = buildGeneratePromptBatchPlan(baseInput({ batchCount: 3, seedStep: 1 }));
expect(plan.data).toEqual([
[
@@ -47,6 +56,13 @@ describe('buildGeneratePromptBatchPlan with a single prompt', () => {
expect(plan.expectedImageCount).toBe(3);
});
+ it('counts down for a decrementing seed', () => {
+ const plan = buildGeneratePromptBatchPlan(baseInput({ batchCount: 3, seedStep: -1 }));
+
+ expect(plan.data[0][0].items).toEqual([100, 99, 98]);
+ expect(plan.runs).toBe(1);
+ });
+
it('ignores the seed behaviour, which only has meaning across a prompt set', () => {
const perIteration = buildGeneratePromptBatchPlan(baseInput({ batchCount: 2, seedBehaviour: 'per-iteration' }));
const perImage = buildGeneratePromptBatchPlan(baseInput({ batchCount: 2, seedBehaviour: 'per-image' }));
@@ -60,7 +76,7 @@ describe('buildGeneratePromptBatchPlan with several prompts', () => {
it('per-iteration keeps seeds in their own dimension so a seed spans the prompt set', () => {
const plan = buildGeneratePromptBatchPlan(
- baseInput({ batchCount: 2, prompts, shouldRandomizeSeed: true, seedBehaviour: 'per-iteration' })
+ baseInput({ batchCount: 2, prompts, seedBehaviour: 'per-iteration', seedStep: 1 })
);
expect(plan.data).toEqual([
@@ -74,9 +90,9 @@ describe('buildGeneratePromptBatchPlan with several prompts', () => {
expect(plan.expectedImageCount).toBe(6);
});
- it('per-iteration with a fixed seed leans on runs for the iterations', () => {
+ it('per-iteration with a held seed leans on runs for the iterations', () => {
const plan = buildGeneratePromptBatchPlan(
- baseInput({ batchCount: 2, prompts, shouldRandomizeSeed: false, seedBehaviour: 'per-iteration' })
+ baseInput({ batchCount: 2, prompts, seedBehaviour: 'per-iteration', seedStep: 0 })
);
expect(plan.data[0]).toEqual([{ field_name: 'value', items: [100], node_path: 'seed' }]);
@@ -84,9 +100,9 @@ describe('buildGeneratePromptBatchPlan with several prompts', () => {
expect(plan.expectedImageCount).toBe(6);
});
- it('per-image gives every generated image its own seed', () => {
+ it('per-image gives every generated image its own seed while the seed steps', () => {
const plan = buildGeneratePromptBatchPlan(
- baseInput({ batchCount: 2, prompts, shouldRandomizeSeed: false, seedBehaviour: 'per-image' })
+ baseInput({ batchCount: 2, prompts, seedBehaviour: 'per-image', seedStep: 1 })
);
expect(plan.data).toEqual([
@@ -100,24 +116,42 @@ describe('buildGeneratePromptBatchPlan with several prompts', () => {
expect(plan.expectedImageCount).toBe(6);
});
+ it('per-image with a held seed still uses that one seed for every image', () => {
+ const plan = buildGeneratePromptBatchPlan(
+ baseInput({ batchCount: 2, prompts, seedBehaviour: 'per-image', seedStep: 0 })
+ );
+
+ expect(plan.data[0]).toEqual([{ field_name: 'value', items: [100], node_path: 'seed' }]);
+ expect(plan.runs).toBe(2);
+ expect(plan.expectedImageCount).toBe(6);
+ });
+
it('keeps every zipped group the same length, as the backend requires', () => {
for (const seedBehaviour of ['per-iteration', 'per-image'] as const) {
- const plan = buildGeneratePromptBatchPlan(baseInput({ batchCount: 4, prompts, seedBehaviour }));
+ for (const seedStep of [-1, 0, 1] as const) {
+ const plan = buildGeneratePromptBatchPlan(baseInput({ batchCount: 4, prompts, seedBehaviour, seedStep }));
- for (const group of plan.data) {
- const lengths = new Set(group.map((datum) => datum.items.length));
+ for (const group of plan.data) {
+ const lengths = new Set(group.map((datum) => datum.items.length));
- expect(lengths.size).toBe(1);
+ expect(lengths.size).toBe(1);
+ }
}
}
});
- it('wraps seeds at the 32-bit ceiling', () => {
+ it('wraps seeds past the inclusive 32-bit ceiling', () => {
const plan = buildGeneratePromptBatchPlan(
- baseInput({ batchCount: 1, prompts: ['a', 'b', 'c'], seed: 4_294_967_294, seedBehaviour: 'per-image' })
+ baseInput({
+ batchCount: 1,
+ prompts: ['a', 'b', 'c'],
+ seed: SEED_MAX - 1,
+ seedBehaviour: 'per-image',
+ seedStep: 1,
+ })
);
- expect(plan.data[0][0].items).toEqual([4_294_967_294, 0, 1]);
+ expect(plan.data[0][0].items).toEqual([SEED_MAX - 1, SEED_MAX, 0]);
});
it('falls back to an empty prompt rather than emitting an empty batch', () => {
diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
index 0450321231..ef9e7f49d9 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
@@ -17,16 +17,28 @@ export const MAX_QUEUE_BATCH_ITEMS = 10_000;
export type QueuePromptSeedBehaviour = 'per-iteration' | 'per-image';
+/** Direction between consecutive seeds of one submission; 0 holds the start seed for every image. */
+export type QueueSeedStep = -1 | 0 | 1;
+
export const isQueuePromptSeedBehaviour = (value: unknown): value is QueuePromptSeedBehaviour =>
value === 'per-iteration' || value === 'per-image';
+export const isQueueSeedStep = (value: unknown): value is QueueSeedStep => value === -1 || value === 0 || value === 1;
+
export const sanitizeBatchCount = (value: unknown): number =>
typeof value === 'number' && Number.isFinite(value)
? Math.min(MAX_QUEUE_BATCH_ITEMS, Math.max(1, Math.round(value)))
: 1;
-export const generateSeedSequence = (start: number, count: number): number[] =>
- Array.from({ length: sanitizeBatchCount(count) }, (_, index) => (start + index) % SEED_MAX);
+/** Consecutive seeds from `start`, wrapping over the inclusive `0..SEED_MAX` range. */
+export const generateSeedSequence = (start: number, count: number, step: QueueSeedStep = 1): number[] => {
+ const range = SEED_MAX + 1;
+
+ return Array.from(
+ { length: sanitizeBatchCount(count) },
+ (_, index) => (((start + index * step) % range) + range) % range
+ );
+};
export interface GeneratePromptBatchDatum {
field_name: 'value';
@@ -43,7 +55,7 @@ export interface GeneratePromptBatchPlanInput {
seed: number;
seedBehaviour: QueuePromptSeedBehaviour;
seedNodeId: string;
- shouldRandomizeSeed: boolean;
+ seedStep: QueueSeedStep;
}
export interface GeneratePromptBatchPlan {
@@ -57,11 +69,12 @@ export interface GeneratePromptBatchPlan {
/**
* With a single prompt this reproduces the pre-dynamic-prompts payload exactly,
* which `promptBatch.test.ts` pins:
- * - randomized seed -> one zipped group of `batchCount` seeds and repeated
+ * - stepping seed -> one zipped group of `batchCount` seeds and repeated
* prompts, `runs: 1`
- * - fixed seed -> one zipped group of length 1, `runs: batchCount`
+ * - held seed -> one zipped group of length 1, `runs: batchCount`
*
- * With several prompts the seed behaviour decides the shape:
+ * With several prompts the seed behaviour decides the shape, but only while the
+ * seed steps — a held seed is the same for every image whatever the behaviour:
* - `per-iteration` -> seeds become their own group, so the product is
* `iterations x prompts` and every prompt in an iteration shares its seed
* - `per-image` -> one distinct sequential seed per image, zipped against the
@@ -76,7 +89,7 @@ export const buildGeneratePromptBatchPlan = ({
seed,
seedBehaviour,
seedNodeId,
- shouldRandomizeSeed,
+ seedStep,
}: GeneratePromptBatchPlanInput): GeneratePromptBatchPlan => {
const iterations = sanitizeBatchCount(batchCount);
const promptList = prompts.length > 0 ? [...prompts] : [''];
@@ -84,21 +97,22 @@ export const buildGeneratePromptBatchPlan = ({
{ field_name: 'value', items, node_path: positivePromptNodeId },
{ field_name: 'value', items: items.map(() => negativePrompt), node_path: negativePromptNodeId },
];
+ const isHeld = seedStep === 0;
if (promptList.length === 1) {
- const seeds = shouldRandomizeSeed ? generateSeedSequence(seed, iterations) : [seed];
+ const seeds = isHeld ? [seed] : generateSeedSequence(seed, iterations, seedStep);
return {
data: [
[{ field_name: 'value', items: seeds, node_path: seedNodeId }, ...promptDatum(seeds.map(() => promptList[0]))],
],
expectedImageCount: iterations,
- runs: shouldRandomizeSeed ? 1 : iterations,
+ runs: isHeld ? iterations : 1,
};
}
- if (seedBehaviour === 'per-image') {
- const seeds = generateSeedSequence(seed, promptList.length * iterations);
+ if (seedBehaviour === 'per-image' && !isHeld) {
+ const seeds = generateSeedSequence(seed, promptList.length * iterations, seedStep);
const repeatedPrompts = Array.from({ length: iterations }, () => promptList).flat();
return {
@@ -111,11 +125,11 @@ export const buildGeneratePromptBatchPlan = ({
// per-iteration: the seed list is its own dimension, so each iteration's seed
// is applied across the whole prompt set. Seeds first so results group by
// iteration rather than interleaving prompts.
- const seeds = shouldRandomizeSeed ? generateSeedSequence(seed, iterations) : [seed];
+ const seeds = isHeld ? [seed] : generateSeedSequence(seed, iterations, seedStep);
return {
data: [[{ field_name: 'value', items: seeds, node_path: seedNodeId }], promptDatum(promptList)],
expectedImageCount: promptList.length * iterations,
- runs: shouldRandomizeSeed ? 1 : iterations,
+ runs: isHeld ? iterations : 1,
};
};
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 16a977088f..7f8d82cdf5 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -1,4 +1,6 @@
-import type { QueuePromptSeedBehaviour } from '@features/queue/core/promptBatch';
+import type { QueuePromptSeedBehaviour, QueueSeedStep } from '@features/queue/core/promptBatch';
+
+export type { QueueSeedStep };
export interface QueueBackendInvocation {
id: string;
@@ -53,7 +55,7 @@ export interface QueueEnqueueGenerateRequest extends QueueEnqueueWorkflowRequest
seed: number;
seedBehaviour?: QueuePromptSeedBehaviour;
seedNodeId: string;
- shouldRandomizeSeed: boolean;
+ seedStep: QueueSeedStep;
}
export interface QueueEnqueueResult {
@@ -89,7 +91,8 @@ export type QueueCompiledSubmission =
seed: number;
seedBehaviour?: QueuePromptSeedBehaviour;
seedNodeId: string;
- shouldRandomizeSeed: boolean;
+ /** Items compiled before seed modes carry `shouldRandomizeSeed` instead; the runtime maps it on read. */
+ seedStep: QueueSeedStep;
}
| { error: string; kind: 'invalid' };
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 301713dadd..2aaa2d92b4 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
@@ -87,7 +87,7 @@ const createRequest = (overrides: Partial<QueueEnqueueGenerateRequest> = {}): Qu
projectId: 'project-1',
seed: 10,
seedNodeId: 'seed',
- shouldRandomizeSeed: false,
+ seedStep: 0,
sourceQueueItemId: 'local-1',
...overrides,
});
@@ -128,10 +128,10 @@ describe('enqueueGenerate', () => {
});
});
- it('keeps a fixed seed for every run when randomization is disabled', async () => {
+ it('keeps a held seed for every run', async () => {
const { enqueueGenerate } = await import('./submissionApi');
- await enqueueGenerate(createRequest({ shouldRandomizeSeed: false }));
+ await enqueueGenerate(createRequest({ seedStep: 0 }));
const body = getSubmittedBody();
@@ -143,10 +143,10 @@ describe('enqueueGenerate', () => {
]);
});
- it('expands seeds per batch item only when randomization is enabled', async () => {
+ it('expands seeds per batch item when the seed steps', async () => {
const { enqueueGenerate } = await import('./submissionApi');
- await enqueueGenerate(createRequest({ shouldRandomizeSeed: true }));
+ await enqueueGenerate(createRequest({ seedStep: 1 }));
const body = getSubmittedBody();
@@ -182,7 +182,7 @@ describe('enqueueGenerate', () => {
positivePrompt: 'a {red|green} cat',
positivePrompts: ['a red cat', 'a green cat'],
seedBehaviour: 'per-iteration',
- shouldRandomizeSeed: true,
+ seedStep: 1,
})
);
@@ -206,7 +206,7 @@ describe('enqueueGenerate', () => {
expect(getSubmittedBody().batch.data[0][1].items).toEqual(['a red cat']);
});
- it('gives every image its own seed under per-image behaviour', async () => {
+ it('gives every image its own seed under per-image behaviour while the seed steps', async () => {
const { enqueueGenerate } = await import('./submissionApi');
await enqueueGenerate(
@@ -214,6 +214,7 @@ describe('enqueueGenerate', () => {
batchCount: 2,
positivePrompts: ['a red cat', 'a green cat'],
seedBehaviour: 'per-image',
+ seedStep: 1,
})
);
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
index 585fd48ff1..6a7d329dea 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
@@ -80,7 +80,7 @@ export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Pro
seed: request.seed,
seedBehaviour: request.seedBehaviour ?? 'per-iteration',
seedNodeId: request.seedNodeId,
- shouldRandomizeSeed: request.shouldRandomizeSeed,
+ seedStep: request.seedStep,
});
const result = await apiFetchJson<unknown>('/api/v1/queue/default/enqueue_batch', {
body: JSON.stringify({
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index 9ff4b1de2e..6af0a0627e 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -34,7 +34,7 @@ const createPendingQueueItem = (): QueueItem => ({
positivePromptNodeId: 'positive_prompt',
seed: 0,
seedNodeId: 'seed',
- shouldRandomizeSeed: false,
+ seedStep: 0,
},
destination: 'canvas',
filterIntermediateResults: false,
@@ -126,6 +126,38 @@ describe('queue runtime', () => {
});
});
+ it('replays items queued before seed modes with the step their random toggle implied', () => {
+ const asLegacy = (shouldRandomizeSeed: boolean) => {
+ const queueItem = createPendingQueueItem();
+ const submission = queueItem.snapshot.backendSubmission as Record<string, unknown>;
+ delete submission.seedStep;
+ submission.shouldRandomizeSeed = shouldRandomizeSeed;
+ return queueItem;
+ };
+
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asLegacy(true))).toMatchObject({
+ kind: 'generate',
+ request: { seedStep: 1 },
+ });
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asLegacy(false))).toMatchObject({
+ kind: 'generate',
+ request: { seedStep: 0 },
+ });
+ expect(
+ (createQueueItemBackendSubmission({ id: 'project-1' }, asLegacy(false)) as { request: object }).request
+ ).not.toHaveProperty('shouldRandomizeSeed');
+ });
+
+ 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;
+
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, queueItem)).toEqual({
+ error: 'Queue item has malformed generate submission metadata.',
+ kind: 'invalid',
+ });
+ });
+
it('adopts a persisted backend run before submission so reload cannot duplicate it', async () => {
const queueItem = createPendingQueueItem();
const project = { id: 'project-1', queue: { items: [queueItem] } };
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index de983b23fc..a9bb1bf12c 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -10,7 +10,7 @@ import type {
import type { BackendConnectionStatus } from '@platform/transport/types';
import { collectGraphInputMediaNames } from '@features/queue/core/graphInputMedia';
-import { isQueuePromptSeedBehaviour, MAX_QUEUE_BATCH_ITEMS } from '@features/queue/core/promptBatch';
+import { isQueuePromptSeedBehaviour, isQueueSeedStep, MAX_QUEUE_BATCH_ITEMS } from '@features/queue/core/promptBatch';
import { shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';
import { progressImageStore } from '@features/queue/data/progressImageStore';
import {
@@ -118,6 +118,20 @@ const getQueueItemCompiledGraph = (queueItem: QueueItem): unknown => {
return submission && typeof submission === 'object' && 'graph' in submission ? submission.graph : undefined;
};
+/**
+ * Items queued before seed modes recorded the random toggle instead of a step;
+ * a randomized batch ran consecutive seeds and a pinned one held its seed, so
+ * recovery replays them exactly as they were planned.
+ */
+const readSubmissionSeedStep = (submission: { seedStep?: unknown; shouldRandomizeSeed?: unknown }) =>
+ isQueueSeedStep(submission.seedStep)
+ ? submission.seedStep
+ : typeof submission.shouldRandomizeSeed === 'boolean'
+ ? submission.shouldRandomizeSeed
+ ? 1
+ : 0
+ : null;
+
export const createQueueItemBackendSubmission = (
project: Pick<QueueHistoryProject, 'id'>,
queueItem: QueueItem
@@ -153,6 +167,8 @@ export const createQueueItemBackendSubmission = (
}
if (submission.kind === 'generate') {
+ const seedStep = readSubmissionSeedStep(submission);
+
if (
typeof submission.negativePrompt !== 'string' ||
typeof submission.negativePromptNodeId !== 'string' ||
@@ -161,7 +177,7 @@ export const createQueueItemBackendSubmission = (
typeof submission.seed !== 'number' ||
!Number.isFinite(submission.seed) ||
typeof submission.seedNodeId !== 'string' ||
- typeof submission.shouldRandomizeSeed !== 'boolean' ||
+ seedStep === null ||
(submission.positivePrompts !== undefined &&
(!Array.isArray(submission.positivePrompts) ||
submission.positivePrompts.some((prompt) => typeof prompt !== 'string'))) ||
@@ -169,13 +185,18 @@ export const createQueueItemBackendSubmission = (
) {
return { error: 'Queue item has malformed generate submission metadata.', kind: 'invalid' };
}
- const { kind: _, ...compiled } = submission;
+ const {
+ kind: _,
+ shouldRandomizeSeed: _legacyToggle,
+ ...compiled
+ } = submission as typeof submission & { shouldRandomizeSeed?: unknown };
return {
kind: 'generate',
request: {
...compiled,
destination: queueItem.snapshot.destination,
projectId: project.id,
+ seedStep,
sourceQueueItemId: queueItem.id,
},
};
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
index 1ed8df4e42..091f8d3636 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
@@ -171,7 +171,7 @@ const generateRequest: QueueEnqueueGenerateRequest = {
projectId: 'project-1',
seed: 1,
seedNodeId: 'seed',
- shouldRandomizeSeed: false,
+ seedStep: 0,
sourceQueueItemId: 'local-1',
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
index 3155b5ffe6..0211b6842f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -121,7 +121,7 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])
seamlessXAxis: false,
seamlessYAxis: false,
seed: 1,
- shouldRandomizeSeed: true,
+ seedMode: 'random',
steps: 30,
t5EncoderModel: null,
vae: null,
diff --git a/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts
index 887cfdf109..a25352cf62 100644
--- a/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts
@@ -20,7 +20,7 @@ const createModel = (base: string, key = `${base}-model`): GenerateModelConfig =
const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({
...getDefaultGenerateSettings(model),
seed: 7,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
...overrides,
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index bee1b8a2fc..d894b95df9 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -96,7 +96,7 @@ const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWi
seamlessXAxis: false,
seamlessYAxis: false,
seed: 123,
- shouldRandomizeSeed: true,
+ seedMode: 'random',
steps: 30,
t5EncoderModel: null,
vae: null,
@@ -210,7 +210,7 @@ describe('image recall', () => {
scheduler: 'euler',
seamlessXAxis: true,
seed: 42,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
steps: 25,
width: 512,
});
@@ -426,7 +426,7 @@ describe('image recall', () => {
it('remixes without changing the current seed state', () => {
const result = buildImageRecallSettings({
- currentValues: createValues({ seed: 999, shouldRandomizeSeed: false }),
+ currentValues: createValues({ seed: 999, seedMode: 'fixed' }),
image,
kind: 'remix',
metadata,
@@ -436,7 +436,7 @@ describe('image recall', () => {
});
expect(result?.values.seed).toBe(999);
- expect(result?.values.shouldRandomizeSeed).toBe(false);
+ expect(result?.values.seedMode).toBe('fixed');
expect(result?.values.positivePrompt).toBe('a recalled prompt');
expect(result?.fields).not.toContain('seed');
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
index 6fe500c7a1..fbcb05822d 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
@@ -604,7 +604,7 @@ export const buildImageRecallSettings = ({
const seed = getSeed(metadata);
if (seed !== null) {
- values = { ...values, seed, shouldRandomizeSeed: false };
+ values = { ...values, seed, seedMode: 'fixed' };
fields.push('seed');
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts
index d9ebac5301..7038c26e50 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts
@@ -72,7 +72,7 @@ describe('buildRecallParametersSettings', () => {
scheduler: 'euler',
seamlessXAxis: true,
seed: 42,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
steps: 30,
width: 1024,
})
@@ -157,7 +157,7 @@ describe('buildRecallParametersSettings', () => {
positivePrompt: 'keep me?',
referenceImages: [{ ...existingReference, config: { ...existingReference.config, model: sdxlIpAdapter } }],
seed: 7,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
steps: 50,
width: 1536,
});
@@ -181,7 +181,7 @@ describe('buildRecallParametersSettings', () => {
loras: [],
positivePrompt: '',
referenceImages: [],
- shouldRandomizeSeed: true,
+ seedMode: 'random',
steps: defaults.steps,
width: defaults.width,
})
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts
index ddbe9f68a2..376fc0462f 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts
@@ -265,9 +265,9 @@ export const buildRecallParametersSettings = ({
'seed',
() => {
const seed = getSeed(parameters);
- return seed === null ? null : { seed, shouldRandomizeSeed: false };
+ return seed === null ? null : { seed, seedMode: 'fixed' };
},
- () => ({ shouldRandomizeSeed: true })
+ () => ({ seedMode: 'random' })
);
applyField(
'steps',
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts
index 38d05641cc..39c4a73cd1 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts
@@ -22,14 +22,14 @@ const makeValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidg
negativePromptEnabled: false,
positivePrompt: 'current prompt',
seed: 1,
- shouldRandomizeSeed: true,
+ seedMode: 'random',
width: 1024,
...overrides,
}) as GenerateWidgetValues;
describe('getQueueRecallCapabilities', () => {
it('grants everything for local snapshots', () => {
- expect(getQueueRecallCapabilities(makeValues({ shouldRandomizeSeed: false }), {})).toEqual({
+ expect(getQueueRecallCapabilities(makeValues({ seedMode: 'fixed' }), {})).toEqual({
all: true,
clipSkip: true,
dimensions: true,
@@ -51,7 +51,7 @@ describe('getQueueRecallCapabilities', () => {
});
it('withholds seed for randomized local submissions without session meta', () => {
- expect(getQueueRecallCapabilities(makeValues({ shouldRandomizeSeed: true }), {}).seed).toBe(false);
+ expect(getQueueRecallCapabilities(makeValues({ seedMode: 'random' }), {}).seed).toBe(false);
});
});
@@ -59,12 +59,12 @@ describe('buildQueueRecallValues', () => {
const current = makeValues();
it('recalls all as the exact snapshot and remix with a randomized seed', () => {
- const snapshot = makeValues({ positivePrompt: 'snap', shouldRandomizeSeed: false });
+ const snapshot = makeValues({ positivePrompt: 'snap', seedMode: 'fixed' });
expect(buildQueueRecallValues('all', { current, meta: {}, snapshot })).toBe(snapshot);
expect(buildQueueRecallValues('remix', { current, meta: {}, snapshot })).toEqual({
...snapshot,
- shouldRandomizeSeed: true,
+ seedMode: 'random',
});
});
@@ -128,17 +128,17 @@ describe('buildQueueRecallValues', () => {
});
it('prefers the executed session seed and pins randomization off', () => {
- const snapshot = makeValues({ seed: 7, shouldRandomizeSeed: false });
+ const snapshot = makeValues({ seed: 7, seedMode: 'fixed' });
expect(buildQueueRecallValues('seed', { current, meta: { seed: 42 }, snapshot })).toEqual({
...current,
seed: 42,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
});
expect(buildQueueRecallValues('seed', { current, meta: {}, snapshot })).toEqual({
...current,
seed: 7,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
});
expect(buildQueueRecallValues('seed', { current, meta: {}, snapshot: null })).toBeNull();
});
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
index b6e018d0bf..01d4c74e2d 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
@@ -22,7 +22,7 @@ export const getQueueRecallCapabilities = (
dimensions: snapshot !== null,
prompts: snapshot !== null || meta.positivePrompt !== undefined,
remix: snapshot !== null,
- seed: meta.seed !== undefined || (snapshot !== null && !snapshot.shouldRandomizeSeed),
+ seed: meta.seed !== undefined || (snapshot !== null && snapshot.seedMode !== 'random'),
});
export const getVideoQueueRecallCapabilities = (
@@ -54,7 +54,7 @@ export const buildQueueRecallValues = (
}
if (kind === 'remix') {
- return snapshot ? { ...snapshot, shouldRandomizeSeed: true } : null;
+ return snapshot ? { ...snapshot, seedMode: 'random' } : null;
}
if (!current) {
@@ -92,9 +92,9 @@ export const buildQueueRecallValues = (
if (kind === 'seed') {
// The session's seed is what actually ran (randomized submissions store a
// placeholder in the snapshot), so it wins.
- const seed = meta.seed ?? (snapshot && !snapshot.shouldRandomizeSeed ? snapshot.seed : undefined);
+ const seed = meta.seed ?? (snapshot && snapshot.seedMode !== 'random' ? snapshot.seed : undefined);
- return seed === undefined ? null : { ...current, seed, shouldRandomizeSeed: false };
+ return seed === undefined ? null : { ...current, seed, seedMode: 'fixed' };
}
if (kind === 'dimensions') {
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx
index edd9e96a83..007b748bd5 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx
@@ -46,7 +46,7 @@ const NO_META: QueueGenerationMeta = {};
const generateSnapshot = {
positivePrompt: 'snapshot prompt',
seed: 7,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
} as GenerateWidgetValues;
type Handle = ReturnType<typeof useQueueItemRecall>;
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts
index 3ee9e6fd1b..e518cb1a56 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts
@@ -45,7 +45,7 @@ const buildGenerateSummaryRows = (settings: GenerateWidgetValues, t: TFunction):
{
id: 'seed',
label: t('graphPreview.seed'),
- value: settings.shouldRandomizeSeed ? t('graphPreview.seedRandomValue') : String(settings.seed),
+ value: settings.seedMode === 'random' ? t('graphPreview.seedRandomValue') : String(settings.seed),
},
];
};
@@ -107,7 +107,7 @@ const buildGenerateSource = (
}
const { settings } = result;
- const isSeedRandomized = settings.shouldRandomizeSeed;
+ const isSeedRandomized = settings.seedMode === 'random';
const notices: GraphPreviewNotice[] = isSeedRandomized
? [{ id: 'seed-random', message: t('graphPreview.seedRandomized'), nodeId: 'seed' }]
: [];
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index b1b4bff654..95f3331d91 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -85,7 +85,7 @@ const generateValuesFor = (model: GenerateModelConfig): Record<string, unknown>
modelKey: model.key,
positivePrompt: 'a canvas prompt',
seed: 7,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
});
const rasterLayer = (id: string, size = 64): CanvasRasterLayerContractV2 => ({
@@ -437,7 +437,7 @@ describe('runCanvasInvocation', () => {
negativePrompt: 'low quality',
positivePrompt: 'a resolved canvas prompt',
seed: 123,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
};
await runCanvasInvocation(harness.deps);
@@ -452,7 +452,7 @@ describe('runCanvasInvocation', () => {
negativePrompt: 'low quality',
positivePrompt: 'a resolved canvas prompt',
seed: 123,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
},
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index c97622181b..870c9cf3c7 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -233,7 +233,7 @@ const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): Ge
seamlessXAxis: false,
seamlessYAxis: false,
seed: 123,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
steps: 30,
t5EncoderModel: null,
vae: null,
@@ -453,7 +453,7 @@ describe('generation-device orchestration metadata', () => {
...createDefaultUpscaleWidgetValues(models),
inputImage: { height: 64, image_name: 'input.png', width: 64 },
seed: 1,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
};
let state = workbenchReducer(createInitialWorkbenchState(), {
settings: { useCpuNoise: false },
@@ -2244,7 +2244,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
});
it('keeps submitted Generate snapshots immutable after later settings changes', () => {
- let state = submitGenerate(primeGenerate(undefined, { positivePrompt: 'first prompt', shouldRandomizeSeed: true }));
+ let state = submitGenerate(primeGenerate(undefined, { positivePrompt: 'first prompt', seedMode: 'random' }));
const firstQueueItem = getActiveProject(state).queue.items[0];
expect(firstQueueItem).toBeDefined();
@@ -2257,7 +2257,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const secondValues = secondQueueItem?.snapshot.recall?.generateValues as GenerateWidgetValues;
expect(firstValues.positivePrompt).toBe('first prompt');
- expect(firstValues.shouldRandomizeSeed).toBe(true);
+ expect(firstValues.seedMode).toBe('random');
expect(typeof firstValues.seed).toBe('number');
expect(secondValues.positivePrompt).toBe('second prompt');
expect(secondValues.seed).toBe(999);
@@ -3080,7 +3080,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
negativePromptNodeId: 'negative_prompt',
positivePromptNodeId: 'positive_prompt',
seedNodeId: 'seed',
- values: createGenerateValues({ positivePrompt: 'canvas prompt', seed: 101, shouldRandomizeSeed: false }),
+ values: createGenerateValues({ positivePrompt: 'canvas prompt', seed: 101, seedMode: 'fixed' }),
},
graph,
projectId: otherProjectId,
@@ -3262,6 +3262,140 @@ describe('workbenchReducer Phase 5 generation flow', () => {
});
});
+ describe('seed modes on the compiled submission', () => {
+ const SEED_MAX = 4_294_967_295;
+ const readSeed = (state: WorkbenchState) => getProjectWidgetValues(getActiveProject(state), 'generate').seed;
+ const readSubmission = (state: WorkbenchState) =>
+ getActiveProject(state).queue.items[0]?.snapshot.backendSubmission;
+ const submitWithPrompts = (state: WorkbenchState, positivePrompts?: string[]) =>
+ workbenchReducer(state, {
+ backendSupportsCancellation: true,
+ positivePrompts,
+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
+ type: 'submitResolvedInvocationSnapshot',
+ });
+
+ it('increment queues consecutive seeds and leaves the editable seed after the batch', () => {
+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 3, seed: 42, seedMode: 'increment' }));
+
+ expect(readSubmission(state)).toMatchObject({ batchCount: 3, seed: 42, seedStep: 1 });
+ expect(readSeed(state)).toBe(45);
+
+ // Queued back to back, the next submission continues where the last one ended.
+ state = submitGenerate(state);
+
+ expect(readSubmission(state)).toMatchObject({ seed: 45, seedStep: 1 });
+ expect(readSeed(state)).toBe(48);
+ expect(getActiveProject(state).queue.items[1]?.snapshot.backendSubmission).toMatchObject({ seed: 42 });
+ });
+
+ it('decrement counts down and wraps below zero onto the top of the range', () => {
+ const state = submitGenerate(primeGenerate(undefined, { batchCount: 2, seed: 1, seedMode: 'decrement' }));
+
+ expect(readSubmission(state)).toMatchObject({ seed: 1, seedStep: -1 });
+ expect(readSeed(state)).toBe(SEED_MAX);
+ });
+
+ it('fixed holds the seed for the batch and does not move it', () => {
+ const state = submitGenerate(primeGenerate(undefined, { batchCount: 3, seed: 42, seedMode: 'fixed' }));
+
+ expect(readSubmission(state)).toMatchObject({ seed: 42, seedStep: 0 });
+ expect(readSeed(state)).toBe(42);
+ });
+
+ it('random draws the start seed for the batch and preserves the entered one', () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.25);
+
+ try {
+ const state = submitGenerate(primeGenerate(undefined, { batchCount: 2, seed: 42, seedMode: 'random' }));
+
+ expect(readSubmission(state)).toMatchObject({ seed: Math.floor(0.25 * SEED_MAX), seedStep: 1 });
+ expect(readSeed(state)).toBe(42);
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ it('advances by every seed a prompt set consumes', () => {
+ const perIteration = submitWithPrompts(
+ primeGenerate(undefined, {
+ batchCount: 2,
+ dynamicPromptsSeedBehaviour: 'per-iteration',
+ positivePrompt: 'a {red|green} cat',
+ seed: 42,
+ seedMode: 'increment',
+ }),
+ ['a red cat', 'a green cat']
+ );
+ const perImage = submitWithPrompts(
+ primeGenerate(undefined, {
+ batchCount: 2,
+ dynamicPromptsSeedBehaviour: 'per-image',
+ positivePrompt: 'a {red|green} cat',
+ seed: 42,
+ seedMode: 'increment',
+ }),
+ ['a red cat', 'a green cat']
+ );
+
+ expect(readSeed(perIteration)).toBe(44);
+ expect(readSeed(perImage)).toBe(46);
+ });
+
+ it('does not consume seeds when the submission is rejected', () => {
+ const state = primeGenerate(undefined, { seed: 42, seedMode: 'increment', steps: Number.NaN });
+ const next = submitGenerate(state);
+
+ expect(getActiveProject(next).queue.items).toEqual([]);
+ expect(readSeed(next)).toBe(42);
+ });
+
+ describe('from the canvas, which compiles outside the reducer', () => {
+ const submitCanvas = (state: WorkbenchState, values: GenerateWidgetValues) =>
+ workbenchReducer(state, {
+ backendSupportsCancellation: true,
+ canvas: structuredClone(getActiveProject(state).canvas),
+ destination: 'canvas',
+ generate: {
+ negativePromptNodeId: 'negative_prompt',
+ positivePromptNodeId: 'positive_prompt',
+ seedNodeId: 'seed',
+ values,
+ },
+ graph: {
+ backendGraph: { edges: [], id: 'canvas-backend-graph', nodes: {} },
+ edges: [],
+ id: 'canvas-graph',
+ label: 'Canvas',
+ nodes: [],
+ updatedAt: '2026-06-09T00:00:00.000Z',
+ version: 1,
+ },
+ projectId: state.activeProjectId,
+ type: 'submitCanvasInvocationSnapshot',
+ });
+
+ it('advances the settings the snapshot was compiled from', () => {
+ const values = createGenerateValues({ batchCount: 2, seed: 10, seedMode: 'increment' });
+ const state = submitCanvas(primeGenerate(undefined, values), values);
+
+ expect(readSubmission(state)).toMatchObject({ seed: 10, seedStep: 1 });
+ expect(readSeed(state)).toBe(12);
+ });
+
+ it('leaves settings the user changed while the canvas was compiling', () => {
+ const compiled = createGenerateValues({ batchCount: 2, seed: 10, seedMode: 'increment' });
+ const seedEdited = submitCanvas(primeGenerate(undefined, { ...compiled, seed: 500 }), compiled);
+ const modeEdited = submitCanvas(primeGenerate(undefined, { ...compiled, seedMode: 'fixed' }), compiled);
+
+ expect(readSubmission(seedEdited)).toMatchObject({ seed: 10, seedStep: 1 });
+ expect(readSeed(seedEdited)).toBe(500);
+ expect(readSubmission(modeEdited)).toMatchObject({ seed: 10, seedStep: 1 });
+ expect(readSeed(modeEdited)).toBe(10);
+ });
+ });
+ });
+
describe('prompt templates on the compiled submission', () => {
const template = {
id: 't1',
@@ -6254,7 +6388,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
negativePromptNodeId: 'negative_prompt',
positivePromptNodeId: 'positive_prompt',
seedNodeId: 'seed',
- values: createGenerateValues({ positivePrompt: 'canvas prompt', seed: 101, shouldRandomizeSeed: false }),
+ values: createGenerateValues({ positivePrompt: 'canvas prompt', seed: 101, seedMode: 'fixed' }),
});
const submitCanvasGeneration = (state: WorkbenchState): { queueItemId: string; state: WorkbenchState } => {
@@ -6343,7 +6477,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
negativePrompt: 'avoid blur',
positivePrompt: 'inpaint prompt',
seed: 42,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
}),
},
graph,
@@ -6360,7 +6494,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
negativePrompt: 'avoid blur',
positivePrompt: 'inpaint prompt',
seed: 42,
- shouldRandomizeSeed: false,
+ seedMode: 'fixed',
});
expect(queueItem?.snapshot).not.toHaveProperty('generate');
expect(queueItem?.snapshot).not.toHaveProperty('widgetStates');
@@ -6374,7 +6508,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
positivePromptNodeId: 'positive_prompt',
seed: 42,
seedNodeId: 'seed',
- shouldRandomizeSeed: false,
+ seedStep: 0,
});
expect(queueItem?.snapshot.resultNodeIds).toEqual(['canvas_output']);
expect(getActiveProject(state).invocation.sourceId).toBe('canvas');
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 2ff136c9b2..b0ceb56cd7 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -1,6 +1,6 @@
import type { GenerateWidgetValues } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
-import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';
+import type { QueueCompiledSubmission, QueueHistoryItemStatus, QueueSeedStep } from '@features/queue/contracts';
import type { ProjectGraphState } from '@features/workflow/contracts';
import type {
CanvasDocumentContractV3,
@@ -105,6 +105,7 @@ import {
migrateProjectPromptDraft,
normalizeGenerateSettings,
normalizeGenerateWidgetValues,
+ planSeedSubmission,
type ProjectPromptDraftPatch,
removePromptHistoryItem,
sanitizeBatchCount,
@@ -3148,6 +3149,29 @@ const enqueueCompiledSnapshot = (
const expandedSeedBehaviour = expandedPositivePrompts
? (canvasGenerateSettings ?? generateSettings)?.dynamicPromptsSeedBehaviour
: undefined;
+ // The seed was resolved when the graph compiled (random modes drew it then),
+ // so `seed` is this submission's start. The plan fixes how the batch steps
+ // from it and where the editable seed goes next; a submission that fails or
+ // is cancelled later keeps its seeds — the sequence only ever moves forward.
+ const seedModeSettings = canvasGenerateSettings ?? generateSettings;
+ const seedPlan = seedModeSettings
+ ? planSeedSubmission({
+ batchCount: seedModeSettings.batchCount,
+ promptCount: expandedPositivePrompts?.length ?? 1,
+ seedBehaviour: expandedSeedBehaviour ?? 'per-iteration',
+ seedMode: seedModeSettings.seedMode,
+ startSeed: seedModeSettings.seed,
+ })
+ : null;
+ // Upscale and Video keep their random toggle: on, the batch steps from the
+ // drawn seed; off, it holds the entered one.
+ const seedStep: QueueSeedStep = seedPlan
+ ? seedPlan.step
+ : sourceGenerateSettings &&
+ 'shouldRandomizeSeed' in sourceGenerateSettings &&
+ sourceGenerateSettings.shouldRandomizeSeed
+ ? 1
+ : 0;
const backendSubmission: QueueCompiledSubmission = !backendGraph
? { error: `${route.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' }
: route.sourceId === 'workflow'
@@ -3179,7 +3203,7 @@ const enqueueCompiledSnapshot = (
seed: sourceGenerateSettings.seed,
...(expandedSeedBehaviour ? { seedBehaviour: expandedSeedBehaviour } : {}),
seedNodeId: generate?.seedNodeId ?? 'seed',
- shouldRandomizeSeed: sourceGenerateSettings.shouldRandomizeSeed,
+ seedStep,
}
: { error: `${route.sourceId} queue item is missing source submission metadata.`, kind: 'invalid' };
const selectedGalleryBoardId = widgetStates.gallery?.values.selectedBoardId;
@@ -3252,8 +3276,22 @@ const enqueueCompiledSnapshot = (
status: 'pending',
};
+ // A stepping mode hands the next seed to the editable settings in the same
+ // transition that queues the batch, so submissions queued back to back
+ // continue the sequence. The canvas compiles outside the reducer, so its plan
+ // 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, 'generate', (values) =>
+ values.seed === seedPlan.startSeed && values.seedMode === seedPlan.seedMode
+ ? { ...values, seed: seedPlan.nextSeed }
+ : values
+ );
+
return {
- ...project,
+ ...advancedProject,
events: prependProjectEvent(project.events, {
createdAt: submittedAt,
id: createId('event'),