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): submit dynamic prompts as a batch dimension

joshistoast07df12da9c75
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index 74b63bcfdc..fa79bf82f6 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -173,6 +173,12 @@ describe('feature public-interface registry', () => {
expect(checkDependency('features/gallery/ui/View.tsx', '@features/queue/publicApi')).toMatchObject([
{ rule: 'feature-public-interface' },
]);
+ // Workbench resolves prompt expansion before submitting, so it reads
+ // Generation's prompt cache through the public entry module.
+ expect(checkDependency('workbench/invocationSubmit.ts', '@features/generation/prompts')).toEqual([]);
+ expect(
+ checkDependency('workbench/invocationSubmit.ts', '@features/generation/data/dynamicPromptsQueries')
+ ).toMatchObject([{ rule: 'feature-private-interface' }]);
});
it('treats unregistered features as fully private', () => {
diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
index 299f1928be..3d5f7836cf 100644
--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
@@ -6,7 +6,7 @@
*/
export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[]>> = {
gallery: ['contracts', 'paletteSearch', 'queries', 'react', 'utility', 'widget'],
- generation: ['components', 'contracts', 'graph', 'react', 'settings', 'widget'],
+ generation: ['components', 'contracts', 'graph', 'prompts', 'react', 'settings', 'widget'],
identity: [],
models: ['react'],
nodes: [],
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index 9ed9ef9d36..430f516a11 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -550,6 +550,7 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): Generat
colorCompensation: false,
dynamicPromptsCombinatorial: true,
dynamicPromptsMaxPrompts: DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,
+ dynamicPromptsSampleSeed: 0,
dynamicPromptsSeedBehaviour: 'per-iteration',
clipEmbedModel: null,
clipGEmbedModel: null,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
index ceca28651a..1eba21111b 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
@@ -1,26 +1,6 @@
import { describe, expect, it } from 'vitest';
-import type { GeneratePromptBatchPlanInput } from './dynamicPrompts';
-
-import {
- buildGeneratePromptBatchPlan,
- hasDynamicPromptSyntax,
- sanitizeDynamicPromptsConfig,
- sanitizeMaxPrompts,
-} from './dynamicPrompts';
-
-const baseInput = (overrides: Partial<GeneratePromptBatchPlanInput> = {}): GeneratePromptBatchPlanInput => ({
- batchCount: 1,
- negativePrompt: 'blurry',
- negativePromptNodeId: 'negative_prompt',
- positivePromptNodeId: 'positive_prompt',
- prompts: ['a cat'],
- seed: 100,
- seedBehaviour: 'per-iteration',
- seedNodeId: 'seed',
- shouldRandomizeSeed: false,
- ...overrides,
-});
+import { hasDynamicPromptSyntax, sanitizeDynamicPromptsConfig, sanitizeMaxPrompts } from './dynamicPrompts';
describe('hasDynamicPromptSyntax', () => {
it('detects a variant anywhere in the prompt', () => {
@@ -57,124 +37,17 @@ describe('sanitizeDynamicPromptsConfig', () => {
expect(sanitizeDynamicPromptsConfig({})).toEqual({
combinatorial: true,
maxPrompts: 100,
+ sampleSeed: 0,
seedBehaviour: 'per-iteration',
});
- expect(sanitizeDynamicPromptsConfig({ combinatorial: false, maxPrompts: 7, seedBehaviour: 'per-image' })).toEqual({
+ expect(
+ sanitizeDynamicPromptsConfig({ combinatorial: false, maxPrompts: 7, sampleSeed: 42, seedBehaviour: 'per-image' })
+ ).toEqual({
combinatorial: false,
maxPrompts: 7,
+ sampleSeed: 42,
seedBehaviour: 'per-image',
});
expect(sanitizeDynamicPromptsConfig({ seedBehaviour: 'PER_PROMPT' })?.seedBehaviour).toBe('per-iteration');
});
});
-
-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 }));
-
- expect(plan.data).toEqual([
- [
- { field_name: 'value', items: [100], node_path: 'seed' },
- { field_name: 'value', items: ['a cat'], node_path: 'positive_prompt' },
- { field_name: 'value', items: ['blurry'], node_path: 'negative_prompt' },
- ],
- ]);
- expect(plan.runs).toBe(3);
- 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 }));
-
- expect(plan.data).toEqual([
- [
- { field_name: 'value', items: [100, 101, 102], node_path: 'seed' },
- { field_name: 'value', items: ['a cat', 'a cat', 'a cat'], node_path: 'positive_prompt' },
- { field_name: 'value', items: ['blurry', 'blurry', 'blurry'], node_path: 'negative_prompt' },
- ],
- ]);
- expect(plan.runs).toBe(1);
- expect(plan.expectedImageCount).toBe(3);
- });
-
- 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' }));
-
- expect(perImage).toEqual(perIteration);
- });
-});
-
-describe('buildGeneratePromptBatchPlan with several prompts', () => {
- const prompts = ['a red cat', 'a green cat', 'a blue cat'];
-
- 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' })
- );
-
- expect(plan.data).toEqual([
- [{ field_name: 'value', items: [100, 101], node_path: 'seed' }],
- [
- { field_name: 'value', items: prompts, node_path: 'positive_prompt' },
- { field_name: 'value', items: ['blurry', 'blurry', 'blurry'], node_path: 'negative_prompt' },
- ],
- ]);
- expect(plan.runs).toBe(1);
- expect(plan.expectedImageCount).toBe(6);
- });
-
- it('per-iteration with a fixed seed leans on runs for the iterations', () => {
- const plan = buildGeneratePromptBatchPlan(
- baseInput({ batchCount: 2, prompts, shouldRandomizeSeed: false, seedBehaviour: 'per-iteration' })
- );
-
- expect(plan.data[0]).toEqual([{ field_name: 'value', items: [100], node_path: 'seed' }]);
- expect(plan.runs).toBe(2);
- expect(plan.expectedImageCount).toBe(6);
- });
-
- it('per-image gives every generated image its own seed', () => {
- const plan = buildGeneratePromptBatchPlan(
- baseInput({ batchCount: 2, prompts, shouldRandomizeSeed: false, seedBehaviour: 'per-image' })
- );
-
- expect(plan.data).toEqual([
- [
- { field_name: 'value', items: [100, 101, 102, 103, 104, 105], node_path: 'seed' },
- { field_name: 'value', items: [...prompts, ...prompts], node_path: 'positive_prompt' },
- { field_name: 'value', items: Array.from({ length: 6 }, () => 'blurry'), node_path: 'negative_prompt' },
- ],
- ]);
- expect(plan.runs).toBe(1);
- 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 group of plan.data) {
- const lengths = new Set(group.map((datum) => datum.items.length));
-
- expect(lengths.size).toBe(1);
- }
- }
- });
-
- it('wraps seeds at the 32-bit ceiling', () => {
- const plan = buildGeneratePromptBatchPlan(
- baseInput({ batchCount: 1, prompts: ['a', 'b', 'c'], seed: 4_294_967_294, seedBehaviour: 'per-image' })
- );
-
- expect(plan.data[0][0].items).toEqual([4_294_967_294, 0, 1]);
- });
-
- it('falls back to an empty prompt rather than emitting an empty batch', () => {
- const plan = buildGeneratePromptBatchPlan(baseInput({ prompts: [] }));
-
- expect(plan.data[0][1].items).toEqual(['']);
- expect(plan.expectedImageCount).toBe(1);
- });
-});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
index 1e5efefcbb..09728f3598 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
@@ -1,20 +1,12 @@
/**
- * Dynamic prompting policy: detecting the syntax, bounding the expansion, and
- * turning an expanded prompt list into the batch matrix the backend expects.
+ * Dynamic prompting policy: detecting the syntax and bounding the expansion.
*
* The backend expands `a {red|green} {cat|dog}` into concrete prompts; the
- * frontend never rebuilds the graph per prompt. Instead the expansion becomes a
- * batch dimension over the graph's existing `positive_prompt` string node, which
- * is why every decision here is expressed as `BatchDatum` groups rather than as
- * a list of graphs.
- *
- * Batch semantics (see `invokeai/app/services/session_queue/session_queue_common.py`):
- * the outer list is a cartesian PRODUCT of groups, and each inner group is
- * ZIPPED (all its items must have the same length).
+ * frontend never rebuilds the graph per prompt. Turning the expanded list into a
+ * batch dimension over the graph's existing `positive_prompt` string node is
+ * Queue's job — see `features/queue/core/promptBatch.ts`.
*/
-import { sanitizeBatchCount } from './batch';
-
// Local copy: `core/settings.ts` exports the same bound but imports this module,
// so taking it from there would be a cycle.
const SEED_MAX = 4_294_967_295;
@@ -31,6 +23,12 @@ export const DYNAMIC_PROMPTS_SEED_BEHAVIOURS: readonly DynamicPromptsSeedBehavio
export interface DynamicPromptsConfig {
combinatorial: boolean;
maxPrompts: number;
+ /**
+ * Seeds the random sampler. Held apart from the generation seed and stable
+ * until the user shuffles, so the previewed prompts are the prompts that
+ * generate. Unused when combinatorial.
+ */
+ sampleSeed: number;
seedBehaviour: DynamicPromptsSeedBehaviour;
}
@@ -62,105 +60,12 @@ export const sanitizeDynamicPromptsConfig = (value: unknown): DynamicPromptsConf
return {
combinatorial: config.combinatorial !== false,
maxPrompts: sanitizeMaxPrompts(config.maxPrompts),
+ sampleSeed: sanitizeSampleSeed(config.sampleSeed),
seedBehaviour: isDynamicPromptsSeedBehaviour(config.seedBehaviour) ? config.seedBehaviour : 'per-iteration',
};
};
-export const generateSeedSequence = (start: number, count: number): number[] =>
- Array.from({ length: Math.max(1, Math.round(count)) }, (_, index) => (start + index) % SEED_MAX);
-
-export interface GeneratePromptBatchDatum {
- field_name: 'value';
- items: (number | string)[];
- node_path: string;
-}
-
-export interface GeneratePromptBatchPlanInput {
- batchCount: number;
- negativePrompt: string;
- negativePromptNodeId: string;
- positivePromptNodeId: string;
- prompts: readonly string[];
- seed: number;
- seedBehaviour: DynamicPromptsSeedBehaviour;
- seedNodeId: string;
- shouldRandomizeSeed: boolean;
-}
-
-export interface GeneratePromptBatchPlan {
- /** Outer list is a cartesian product; each inner list is zipped. */
- data: GeneratePromptBatchDatum[][];
- runs: number;
- /** Images this plan produces, for optimistic placeholder sizing. */
- expectedImageCount: number;
-}
-
-/**
- * Builds the `batch.data` / `batch.runs` payload for a generate submission.
- *
- * With a single prompt this reproduces the pre-dynamic-prompts payload exactly,
- * which `dynamicPrompts.test.ts` pins:
- * - randomized seed -> one zipped group of `batchCount` seeds and repeated
- * prompts, `runs: 1`
- * - fixed seed -> one zipped group of length 1, `runs: batchCount`
- *
- * With several prompts the seed behaviour decides the shape:
- * - `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
- * prompt list repeated `batchCount` times, `runs: 1`
- */
-export const buildGeneratePromptBatchPlan = ({
- batchCount,
- negativePrompt,
- negativePromptNodeId,
- positivePromptNodeId,
- prompts,
- seed,
- seedBehaviour,
- seedNodeId,
- shouldRandomizeSeed,
-}: GeneratePromptBatchPlanInput): GeneratePromptBatchPlan => {
- const iterations = sanitizeBatchCount(batchCount);
- const promptList = prompts.length > 0 ? [...prompts] : [''];
- const promptDatum = (items: string[]): GeneratePromptBatchDatum[] => [
- { field_name: 'value', items, node_path: positivePromptNodeId },
- { field_name: 'value', items: items.map(() => negativePrompt), node_path: negativePromptNodeId },
- ];
-
- // A single prompt keeps the legacy shape: seeds and prompts stay in one zipped
- // group so the payload is byte-identical to what shipped before this feature.
- if (promptList.length === 1) {
- const seeds = shouldRandomizeSeed ? generateSeedSequence(seed, iterations) : [seed];
-
- return {
- data: [
- [{ field_name: 'value', items: seeds, node_path: seedNodeId }, ...promptDatum(seeds.map(() => promptList[0]))],
- ],
- expectedImageCount: iterations,
- runs: shouldRandomizeSeed ? 1 : iterations,
- };
- }
-
- if (seedBehaviour === 'per-image') {
- const seeds = generateSeedSequence(seed, promptList.length * iterations);
- const repeatedPrompts = Array.from({ length: iterations }, () => promptList).flat();
+export const sanitizeSampleSeed = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) ? Math.abs(Math.round(value)) % SEED_MAX : 0;
- return {
- data: [[{ field_name: 'value', items: seeds, node_path: seedNodeId }, ...promptDatum(repeatedPrompts)]],
- expectedImageCount: seeds.length,
- runs: 1,
- };
- }
-
- // 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];
-
- return {
- data: [[{ field_name: 'value', items: seeds, node_path: seedNodeId }], promptDatum(promptList)],
- expectedImageCount: promptList.length * iterations,
- runs: shouldRandomizeSeed ? 1 : iterations,
- };
-};
+export const createDynamicPromptsSampleSeed = (): number => Math.floor(Math.random() * SEED_MAX);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index 1186d54aa6..c969c3b306 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -16,7 +16,7 @@ import type {
import { sanitizeBatchCount } from './batch';
import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';
-import { isDynamicPromptsSeedBehaviour, sanitizeMaxPrompts } from './dynamicPrompts';
+import { isDynamicPromptsSeedBehaviour, sanitizeMaxPrompts, sanitizeSampleSeed } from './dynamicPrompts';
import { cloneCroppableImage, isCanonicalCroppableImage, normalizeCroppableImage } from './referenceImage';
/** Preset ratios, with the preset to switch to when dimensions are swapped. */
@@ -559,6 +559,7 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n
dynamicPromptsCombinatorial:
typeof values.dynamicPromptsCombinatorial === 'boolean' ? values.dynamicPromptsCombinatorial : true,
dynamicPromptsMaxPrompts: sanitizeMaxPrompts(values.dynamicPromptsMaxPrompts),
+ dynamicPromptsSampleSeed: sanitizeSampleSeed(values.dynamicPromptsSampleSeed),
dynamicPromptsSeedBehaviour: isDynamicPromptsSeedBehaviour(values.dynamicPromptsSeedBehaviour)
? values.dynamicPromptsSeedBehaviour
: 'per-iteration',
diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.ts
index 51909ec7a0..054072357d 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts
@@ -161,6 +161,8 @@ export interface GenerateSettings {
dynamicPromptsCombinatorial: boolean;
/** Upper bound on expanded prompts (the sample size when not combinatorial). */
dynamicPromptsMaxPrompts: number;
+ /** Seeds the random sampler so the preview matches what generates. */
+ dynamicPromptsSampleSeed: number;
dynamicPromptsSeedBehaviour: DynamicPromptsSeedBehaviour;
width: number;
height: number;
diff --git a/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.ts b/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.ts
new file mode 100644
index 0000000000..f8e9c9d818
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/data/dynamicPromptsQueries.ts
@@ -0,0 +1,60 @@
+/**
+ * The one cache for prompt expansion. The preview popover and the Invoke tooltip
+ * observe it through `useQuery`; the enqueue path reads it through
+ * `resolveDynamicPrompts`. Because all three address the same key, invoking
+ * normally costs no extra round trip, and invoking before the preview has
+ * settled still enqueues the prompts the backend actually produces rather than a
+ * stale list.
+ *
+ * Expansion is deterministic for a given request — combinatorial by
+ * construction, and seeded when random — so entries never go stale on their own.
+ */
+
+import type {
+ ParseDynamicPromptsRequest,
+ ParseDynamicPromptsResponse,
+} from '@features/generation/data/promptUtilities';
+import type { QueryClient } from '@tanstack/react-query';
+
+import { parseDynamicPrompts } from '@features/generation/data/promptUtilities';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
+import { queryOptions } from '@tanstack/react-query';
+
+const DYNAMIC_PROMPTS_GC_TIME = 30 * 60 * 1000;
+
+export const dynamicPromptsKeys = {
+ all: ['generation', 'dynamic-prompts'] as const,
+ expansion: (request: ParseDynamicPromptsRequest) =>
+ [
+ ...dynamicPromptsKeys.all,
+ request.prompt,
+ request.combinatorial !== false,
+ request.max_prompts ?? null,
+ request.combinatorial === false ? (request.seed ?? null) : null,
+ ] as const,
+};
+
+export const dynamicPromptsQueryOptions = (request: ParseDynamicPromptsRequest) =>
+ (() => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
+ gcTime: DYNAMIC_PROMPTS_GC_TIME,
+ queryFn: async ({ signal }): Promise<ParseDynamicPromptsResponse> => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
+ const response = await parseDynamicPrompts(request, requestSignal);
+
+ assertAccountScopeCurrent(owner);
+ return response;
+ },
+ queryKey: dynamicPromptsKeys.expansion(request),
+ retry: false,
+ staleTime: Infinity,
+ });
+ })();
+
+/** Cache-first expansion for the enqueue path, which cannot render a loading state. */
+export const resolveDynamicPrompts = (
+ queryClient: QueryClient,
+ request: ParseDynamicPromptsRequest
+): Promise<ParseDynamicPromptsResponse> => queryClient.ensureQueryData(dynamicPromptsQueryOptions(request));
diff --git a/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts b/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts
index 00b712d8bd..c319067225 100644
--- a/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts
+++ b/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts
@@ -34,3 +34,30 @@ export const imageToPrompt = (request: ImageToPromptRequest): Promise<ImageToPro
body: JSON.stringify(request),
method: 'POST',
});
+
+export interface ParseDynamicPromptsRequest {
+ prompt: string;
+ max_prompts?: number;
+ combinatorial?: boolean;
+ /** Only read by the random generator; ignored when combinatorial. */
+ seed?: number | null;
+}
+
+export interface ParseDynamicPromptsResponse {
+ prompts: string[];
+ /**
+ * A soft failure. The route still returns usable prompts alongside a parse
+ * message or a "No values found for wildcard(s)" notice.
+ */
+ error?: string | null;
+}
+
+export const parseDynamicPrompts = (
+ request: ParseDynamicPromptsRequest,
+ signal?: AbortSignal
+): Promise<ParseDynamicPromptsResponse> =>
+ apiFetchJson('/api/v1/utilities/dynamicprompts', {
+ body: JSON.stringify(request),
+ method: 'POST',
+ signal,
+ });
diff --git a/invokeai/frontend/webv2/src/features/generation/prompts.ts b/invokeai/frontend/webv2/src/features/generation/prompts.ts
new file mode 100644
index 0000000000..da84d8d29a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/prompts.ts
@@ -0,0 +1,10 @@
+/**
+ * Generation's prompt-expansion transport surface: the shared dynamic prompts
+ * cache used by the Generate preview, the Invoke tooltip, and Queue's
+ * submission. The pure policy (`hasDynamicPromptSyntax`,
+ * `buildGeneratePromptBatchPlan`, bounds and config sanitization) lives on
+ * `@features/generation/settings`.
+ * Curated, caller-driven export list — add a symbol only when a consumer needs it.
+ */
+export { dynamicPromptsKeys, dynamicPromptsQueryOptions, resolveDynamicPrompts } from './data/dynamicPromptsQueries';
+export type { ParseDynamicPromptsRequest, ParseDynamicPromptsResponse } from './data/promptUtilities';
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 25c97cd9bb..0a181c7bff 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -51,7 +51,7 @@ export {
export { isVaeCompatibleWithGenerateModel } from './core/componentCompatibility';
export { MIN_BATCH_COUNT, sanitizeBatchCount } from './core/batch';
export {
- buildGeneratePromptBatchPlan,
+ createDynamicPromptsSampleSeed,
DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,
DYNAMIC_PROMPTS_MAX_PROMPTS,
DYNAMIC_PROMPTS_MIN_PROMPTS,
@@ -60,9 +60,9 @@ export {
isDynamicPromptsSeedBehaviour,
sanitizeDynamicPromptsConfig,
sanitizeMaxPrompts,
+ sanitizeSampleSeed,
type DynamicPromptsConfig,
type DynamicPromptsSeedBehaviour,
- type GeneratePromptBatchPlan,
} from './core/dynamicPrompts';
export {
addPromptHistoryItem,
diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.test.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.test.ts
new file mode 100644
index 0000000000..b7751a1cb5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+
+import type { GeneratePromptBatchPlanInput } from './promptBatch';
+
+import { buildGeneratePromptBatchPlan } from './promptBatch';
+
+const baseInput = (overrides: Partial<GeneratePromptBatchPlanInput> = {}): GeneratePromptBatchPlanInput => ({
+ batchCount: 1,
+ negativePrompt: 'blurry',
+ negativePromptNodeId: 'negative_prompt',
+ positivePromptNodeId: 'positive_prompt',
+ prompts: ['a cat'],
+ seed: 100,
+ seedBehaviour: 'per-iteration',
+ seedNodeId: 'seed',
+ shouldRandomizeSeed: false,
+ ...overrides,
+});
+
+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 }));
+
+ expect(plan.data).toEqual([
+ [
+ { field_name: 'value', items: [100], node_path: 'seed' },
+ { field_name: 'value', items: ['a cat'], node_path: 'positive_prompt' },
+ { field_name: 'value', items: ['blurry'], node_path: 'negative_prompt' },
+ ],
+ ]);
+ expect(plan.runs).toBe(3);
+ 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 }));
+
+ expect(plan.data).toEqual([
+ [
+ { field_name: 'value', items: [100, 101, 102], node_path: 'seed' },
+ { field_name: 'value', items: ['a cat', 'a cat', 'a cat'], node_path: 'positive_prompt' },
+ { field_name: 'value', items: ['blurry', 'blurry', 'blurry'], node_path: 'negative_prompt' },
+ ],
+ ]);
+ expect(plan.runs).toBe(1);
+ expect(plan.expectedImageCount).toBe(3);
+ });
+
+ 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' }));
+
+ expect(perImage).toEqual(perIteration);
+ });
+});
+
+describe('buildGeneratePromptBatchPlan with several prompts', () => {
+ const prompts = ['a red cat', 'a green cat', 'a blue cat'];
+
+ 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' })
+ );
+
+ expect(plan.data).toEqual([
+ [{ field_name: 'value', items: [100, 101], node_path: 'seed' }],
+ [
+ { field_name: 'value', items: prompts, node_path: 'positive_prompt' },
+ { field_name: 'value', items: ['blurry', 'blurry', 'blurry'], node_path: 'negative_prompt' },
+ ],
+ ]);
+ expect(plan.runs).toBe(1);
+ expect(plan.expectedImageCount).toBe(6);
+ });
+
+ it('per-iteration with a fixed seed leans on runs for the iterations', () => {
+ const plan = buildGeneratePromptBatchPlan(
+ baseInput({ batchCount: 2, prompts, shouldRandomizeSeed: false, seedBehaviour: 'per-iteration' })
+ );
+
+ expect(plan.data[0]).toEqual([{ field_name: 'value', items: [100], node_path: 'seed' }]);
+ expect(plan.runs).toBe(2);
+ expect(plan.expectedImageCount).toBe(6);
+ });
+
+ it('per-image gives every generated image its own seed', () => {
+ const plan = buildGeneratePromptBatchPlan(
+ baseInput({ batchCount: 2, prompts, shouldRandomizeSeed: false, seedBehaviour: 'per-image' })
+ );
+
+ expect(plan.data).toEqual([
+ [
+ { field_name: 'value', items: [100, 101, 102, 103, 104, 105], node_path: 'seed' },
+ { field_name: 'value', items: [...prompts, ...prompts], node_path: 'positive_prompt' },
+ { field_name: 'value', items: Array.from({ length: 6 }, () => 'blurry'), node_path: 'negative_prompt' },
+ ],
+ ]);
+ expect(plan.runs).toBe(1);
+ 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 group of plan.data) {
+ const lengths = new Set(group.map((datum) => datum.items.length));
+
+ expect(lengths.size).toBe(1);
+ }
+ }
+ });
+
+ it('wraps seeds at the 32-bit ceiling', () => {
+ const plan = buildGeneratePromptBatchPlan(
+ baseInput({ batchCount: 1, prompts: ['a', 'b', 'c'], seed: 4_294_967_294, seedBehaviour: 'per-image' })
+ );
+
+ expect(plan.data[0][0].items).toEqual([4_294_967_294, 0, 1]);
+ });
+
+ it('falls back to an empty prompt rather than emitting an empty batch', () => {
+ const plan = buildGeneratePromptBatchPlan(baseInput({ prompts: [] }));
+
+ expect(plan.data[0][1].items).toEqual(['']);
+ expect(plan.expectedImageCount).toBe(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
new file mode 100644
index 0000000000..88e2e90eee
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
@@ -0,0 +1,118 @@
+/**
+ * The seed/prompt matrix for a generate submission.
+ *
+ * A generate graph carries one `positive_prompt` string node, so submitting
+ * several prompts is a batch dimension over that node rather than several
+ * graphs. Backend batch semantics (see
+ * `invokeai/app/services/session_queue/session_queue_common.py`): the outer list
+ * is a cartesian PRODUCT of groups, and each inner group is ZIPPED, so all of
+ * its items must have the same length.
+ *
+ * The prompt list arrives already expanded — Queue never talks to the expansion
+ * route itself.
+ */
+
+const SEED_MAX = 4_294_967_295;
+
+export type QueuePromptSeedBehaviour = 'per-iteration' | 'per-image';
+
+export const isQueuePromptSeedBehaviour = (value: unknown): value is QueuePromptSeedBehaviour =>
+ value === 'per-iteration' || value === 'per-image';
+
+export const sanitizeBatchCount = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) ? 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);
+
+export interface GeneratePromptBatchDatum {
+ field_name: 'value';
+ items: (number | string)[];
+ node_path: string;
+}
+
+export interface GeneratePromptBatchPlanInput {
+ batchCount: number;
+ negativePrompt: string;
+ negativePromptNodeId: string;
+ positivePromptNodeId: string;
+ prompts: readonly string[];
+ seed: number;
+ seedBehaviour: QueuePromptSeedBehaviour;
+ seedNodeId: string;
+ shouldRandomizeSeed: boolean;
+}
+
+export interface GeneratePromptBatchPlan {
+ /** Outer list is a cartesian product; each inner list is zipped. */
+ data: GeneratePromptBatchDatum[][];
+ runs: number;
+ /** Images this plan produces, for optimistic placeholder sizing. */
+ expectedImageCount: number;
+}
+
+/**
+ * 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
+ * prompts, `runs: 1`
+ * - fixed seed -> one zipped group of length 1, `runs: batchCount`
+ *
+ * With several prompts the seed behaviour decides the shape:
+ * - `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
+ * prompt list repeated `batchCount` times, `runs: 1`
+ */
+export const buildGeneratePromptBatchPlan = ({
+ batchCount,
+ negativePrompt,
+ negativePromptNodeId,
+ positivePromptNodeId,
+ prompts,
+ seed,
+ seedBehaviour,
+ seedNodeId,
+ shouldRandomizeSeed,
+}: GeneratePromptBatchPlanInput): GeneratePromptBatchPlan => {
+ const iterations = sanitizeBatchCount(batchCount);
+ const promptList = prompts.length > 0 ? [...prompts] : [''];
+ const promptDatum = (items: string[]): GeneratePromptBatchDatum[] => [
+ { field_name: 'value', items, node_path: positivePromptNodeId },
+ { field_name: 'value', items: items.map(() => negativePrompt), node_path: negativePromptNodeId },
+ ];
+
+ if (promptList.length === 1) {
+ const seeds = shouldRandomizeSeed ? generateSeedSequence(seed, iterations) : [seed];
+
+ return {
+ data: [
+ [{ field_name: 'value', items: seeds, node_path: seedNodeId }, ...promptDatum(seeds.map(() => promptList[0]))],
+ ],
+ expectedImageCount: iterations,
+ runs: shouldRandomizeSeed ? 1 : iterations,
+ };
+ }
+
+ if (seedBehaviour === 'per-image') {
+ const seeds = generateSeedSequence(seed, promptList.length * iterations);
+ const repeatedPrompts = Array.from({ length: iterations }, () => promptList).flat();
+
+ return {
+ data: [[{ field_name: 'value', items: seeds, node_path: seedNodeId }, ...promptDatum(repeatedPrompts)]],
+ expectedImageCount: seeds.length,
+ runs: 1,
+ };
+ }
+
+ // 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];
+
+ return {
+ data: [[{ field_name: 'value', items: seeds, node_path: seedNodeId }], promptDatum(promptList)],
+ expectedImageCount: promptList.length * iterations,
+ runs: shouldRandomizeSeed ? 1 : iterations,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 5b92b86c9e..aa0195017c 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -1,3 +1,5 @@
+import type { QueuePromptSeedBehaviour } from '@features/queue/core/promptBatch';
+
export interface QueueBackendInvocation {
id: string;
type: string;
@@ -48,7 +50,13 @@ export interface QueueEnqueueGenerateRequest extends QueueEnqueueWorkflowRequest
negativePromptNodeId: string;
positivePrompt: string;
positivePromptNodeId: string;
+ /**
+ * Prompts to submit as a batch dimension, already expanded by the caller.
+ * Absent or empty submits `positivePrompt` verbatim.
+ */
+ positivePrompts?: string[];
seed: number;
+ seedBehaviour?: QueuePromptSeedBehaviour;
seedNodeId: string;
shouldRandomizeSeed: boolean;
}
@@ -75,7 +83,10 @@ export type QueueCompiledSubmission =
negativePromptNodeId: string;
positivePrompt: string;
positivePromptNodeId: string;
+ /** Absent on items compiled before dynamic prompting shipped. */
+ positivePrompts?: string[];
seed: number;
+ seedBehaviour?: QueuePromptSeedBehaviour;
seedNodeId: string;
shouldRandomizeSeed: boolean;
}
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 3bc9b55363..0cd1424a22 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
@@ -111,6 +111,58 @@ describe('enqueueGenerate', () => {
expect(getSubmittedBody().batch.origin).toBe('webv2:p:project-1:q:local-1');
});
+
+ describe('expanded prompts', () => {
+ it('submits several prompts as their own batch dimension', async () => {
+ const { enqueueGenerate } = await import('./submissionApi');
+
+ await enqueueGenerate(
+ createRequest({
+ batchCount: 2,
+ positivePrompt: 'a {red|green} cat',
+ positivePrompts: ['a red cat', 'a green cat'],
+ seedBehaviour: 'per-iteration',
+ shouldRandomizeSeed: true,
+ })
+ );
+
+ const body = getSubmittedBody();
+
+ expect(body.batch.data).toEqual([
+ [{ field_name: 'value', items: [10, 11], node_path: 'seed' }],
+ [
+ { field_name: 'value', items: ['a red cat', 'a green cat'], node_path: 'positive_prompt' },
+ { field_name: 'value', items: ['low quality', 'low quality'], node_path: 'negative_prompt' },
+ ],
+ ]);
+ expect(body.batch.runs).toBe(1);
+ });
+
+ it('gives every image its own seed under per-image behaviour', async () => {
+ const { enqueueGenerate } = await import('./submissionApi');
+
+ await enqueueGenerate(
+ createRequest({
+ batchCount: 2,
+ positivePrompts: ['a red cat', 'a green cat'],
+ seedBehaviour: 'per-image',
+ })
+ );
+
+ const body = getSubmittedBody();
+
+ expect(body.batch.data[0][0]).toEqual({ field_name: 'value', items: [10, 11, 12, 13], node_path: 'seed' });
+ expect(body.batch.runs).toBe(1);
+ });
+
+ it('falls back to the literal prompt when the expanded list is empty', async () => {
+ const { enqueueGenerate } = await import('./submissionApi');
+
+ await enqueueGenerate(createRequest({ positivePrompts: [] }));
+
+ expect(getSubmittedBody().batch.data[0][1].items).toEqual(['a fjord at dawn']);
+ });
+ });
});
describe('enqueueWorkflow', () => {
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
index 6d3f817222..564f09cb79 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
@@ -6,6 +6,7 @@ import type {
QueueResultImageOptions,
} from '@features/queue/core/types';
+import { buildGeneratePromptBatchPlan, sanitizeBatchCount } from '@features/queue/core/promptBatch';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { absolutizeApiUrl, ApiError, apiFetchJson } from '@platform/transport/http';
@@ -14,14 +15,6 @@ import type { QueueImageDTO, QueueServerItemDTO } from './serverTypes';
import { buildQueueItemOrigin } from './events';
import { getQueueItem } from './serverApi';
-const SEED_MAX = 4_294_967_295;
-
-const sanitizeBatchCount = (value: unknown): number =>
- typeof value === 'number' && Number.isFinite(value) ? Math.max(1, Math.round(value)) : 1;
-
-const generateSeedSequence = (start: number, count: number): number[] =>
- Array.from({ length: sanitizeBatchCount(count) }, (_, index) => (start + index) % SEED_MAX);
-
const mapEnqueueResult = (result: {
batch?: { batch_id?: string };
enqueued?: number;
@@ -35,12 +28,17 @@ const mapEnqueueResult = (result: {
});
export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult> => {
- const batchCount = sanitizeBatchCount(request.batchCount);
- const seeds = request.shouldRandomizeSeed ? generateSeedSequence(request.seed, batchCount) : [request.seed];
- const prompts = request.shouldRandomizeSeed ? seeds.map(() => request.positivePrompt) : [request.positivePrompt];
- const negativePrompts = request.shouldRandomizeSeed
- ? seeds.map(() => request.negativePrompt)
- : [request.negativePrompt];
+ const plan = buildGeneratePromptBatchPlan({
+ batchCount: sanitizeBatchCount(request.batchCount),
+ negativePrompt: request.negativePrompt,
+ negativePromptNodeId: request.negativePromptNodeId,
+ positivePromptNodeId: request.positivePromptNodeId,
+ prompts: request.positivePrompts?.length ? request.positivePrompts : [request.positivePrompt],
+ seed: request.seed,
+ seedBehaviour: request.seedBehaviour ?? 'per-iteration',
+ seedNodeId: request.seedNodeId,
+ shouldRandomizeSeed: request.shouldRandomizeSeed,
+ });
const result = await apiFetchJson<{
batch?: { batch_id?: string };
enqueued?: number;
@@ -49,17 +47,11 @@ export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Pro
}>('/api/v1/queue/default/enqueue_batch', {
body: JSON.stringify({
batch: {
- data: [
- [
- { field_name: 'value', items: seeds, node_path: request.seedNodeId },
- { field_name: 'value', items: prompts, node_path: request.positivePromptNodeId },
- { field_name: 'value', items: negativePrompts, node_path: request.negativePromptNodeId },
- ],
- ],
+ data: plan.data,
destination: request.destination,
graph: request.graph,
origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),
- runs: request.shouldRandomizeSeed ? 1 : batchCount,
+ runs: plan.runs,
},
prepend: false,
}),
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 601b2bb23e..bcaf9023be 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -8,6 +8,7 @@ import type {
} from '@features/queue/core/types';
import type { BackendConnectionStatus } from '@platform/transport/types';
+import { isQueuePromptSeedBehaviour } from '@features/queue/core/promptBatch';
import { shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';
import {
createQueueCoordinator,
@@ -114,7 +115,11 @@ export const createQueueItemBackendSubmission = (
typeof submission.seed !== 'number' ||
!Number.isFinite(submission.seed) ||
typeof submission.seedNodeId !== 'string' ||
- typeof submission.shouldRandomizeSeed !== 'boolean'
+ typeof submission.shouldRandomizeSeed !== 'boolean' ||
+ (submission.positivePrompts !== undefined &&
+ (!Array.isArray(submission.positivePrompts) ||
+ submission.positivePrompts.some((prompt) => typeof prompt !== 'string'))) ||
+ (submission.seedBehaviour !== undefined && !isQueuePromptSeedBehaviour(submission.seedBehaviour))
) {
return { error: 'Queue item has malformed generate submission metadata.', kind: 'invalid' };
}
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
index e6fae6d9d9..10f453b5d9 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
@@ -61,6 +61,7 @@ const addUpscaleMetadata = (
// Upscale prompts are not batch-expanded; these only satisfy the shape.
dynamicPromptsCombinatorial: true,
dynamicPromptsMaxPrompts: DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,
+ dynamicPromptsSampleSeed: 0,
dynamicPromptsSeedBehaviour: 'per-iteration',
height: dimensions.height,
modelKey: settings.model.key,
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 cb72a27b9f..7f33df743e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -75,6 +75,7 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])
colorCompensation: false,
dynamicPromptsCombinatorial: true,
dynamicPromptsMaxPrompts: 100,
+ dynamicPromptsSampleSeed: 0,
dynamicPromptsSeedBehaviour: 'per-iteration',
componentSourceModel: null,
height: 1024,
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 3c8db4e454..f4909cc88f 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -43,6 +43,7 @@ const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWi
colorCompensation: false,
dynamicPromptsCombinatorial: true,
dynamicPromptsMaxPrompts: 100,
+ dynamicPromptsSampleSeed: 0,
dynamicPromptsSeedBehaviour: 'per-iteration',
componentSourceModel: null,
height: 1024,
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index c39e9f6ca1..3135c7e419 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -12,8 +12,14 @@ import type { WidgetId } from '@workbench/widgetContracts';
import { getDefaultGenerateSettings } from '@features/generation/settings';
import { createDefaultUpscaleWidgetValues } from '@features/upscale';
+import { queryClient } from '@platform/query/client';
import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Dynamic prompt expansion is the only transport `submitResolvedInvocation` touches.
+const parseDynamicPromptsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@features/generation/data/promptUtilities', () => ({ parseDynamicPrompts: parseDynamicPromptsMock }));
import {
areInvocationRouteInputsEqual,
@@ -339,6 +345,12 @@ describe('submitResolvedInvocation', () => {
const routeFor = (project: Parameters<typeof resolveInvocationRoute>[0], route: InvocationRoute) =>
resolveInvocationRoute(project, 'global', route);
+ beforeEach(() => {
+ queryClient.clear();
+ parseDynamicPromptsMock.mockReset();
+ parseDynamicPromptsMock.mockResolvedValue({ prompts: ['a red cat', 'a green cat'] });
+ });
+
it('routes a canvas source through prepareCanvasInvocation and does not dispatch a resolved snapshot', () => {
const project = getActiveProject(
createGenerateValues(animaModel, { qwen3EncoderModel: qwen3Encoder, vae: animaVae })
@@ -386,6 +398,76 @@ describe('submitResolvedInvocation', () => {
});
});
+ it('expands a dynamic prompt before dispatching, and only then', async () => {
+ const project = getActiveProject(
+ createGenerateValues(animaModel, {
+ positivePrompt: 'a {red|green} cat',
+ qwen3EncoderModel: qwen3Encoder,
+ vae: animaVae,
+ })
+ );
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+ const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'generate' });
+
+ submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route,
+ });
+
+ // The expansion is a round trip, so dispatch cannot have happened yet.
+ expect(submitResolved).not.toHaveBeenCalled();
+
+ await vi.waitFor(() => expect(submitResolved).toHaveBeenCalledTimes(1));
+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({
+ positivePrompts: ['a red cat', 'a green cat'],
+ });
+ });
+
+ it('dispatches synchronously when the prompt has no dynamic syntax', () => {
+ const project = getActiveProject(createGenerateValues(animaModel, { positivePrompt: 'a plain cat' }));
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+ const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'generate' });
+
+ submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route,
+ });
+
+ expect(submitResolved).toHaveBeenCalledTimes(1);
+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({ positivePrompts: undefined });
+ });
+
+ it('falls back to the literal prompt when expansion fails', async () => {
+ parseDynamicPromptsMock.mockRejectedValueOnce(new Error('offline'));
+
+ const project = getActiveProject(createGenerateValues(animaModel, { positivePrompt: 'a {red|green} cat' }));
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+ const route = routeFor(project, { ...project.invocation, destination: 'gallery', sourceId: 'generate' });
+
+ submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route,
+ });
+
+ await vi.waitFor(() => expect(submitResolved).toHaveBeenCalledTimes(1));
+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({ positivePrompts: undefined });
+ });
+
it('quietly ignores a submission owned by an expired account scope', () => {
const project = getActiveProject(createGenerateValues(animaModel));
const commands = createWorkbenchStore().commands;
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
index 3766689b26..cc2018b1a4 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
@@ -13,11 +13,15 @@
* node-testable with a fake dispatch + a stubbed canvas pipeline.
*/
+import type { GenerateSettings } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
import type { AccountScope } from '@platform/state/accountLifecycle';
import type { ResolvedInvocationRoute } from '@workbench/invocationContracts';
import type { Project } from '@workbench/projectContracts';
+import { resolveDynamicPrompts } from '@features/generation/prompts';
+import { hasDynamicPromptSyntax, normalizeGenerateSettings } from '@features/generation/settings';
+import { queryClient } from '@platform/query/client';
import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';
@@ -47,6 +51,42 @@ export interface SubmitResolvedInvocationDeps {
formatControlLayerError?: PrepareCanvasInvocationArgs['formatControlLayerError'];
}
+/**
+ * The GenerateSettings behind a route that expands `{a|b}`, or `null` when the
+ * route submits its prompt literally (Upscale, Workflow) or has no such syntax.
+ */
+const getExpandableSettings = (project: Project, route: ResolvedInvocationRoute): GenerateSettings | null => {
+ if (route.sourceId === 'upscale' || route.sourceId === 'workflow') {
+ return null;
+ }
+
+ const settings = normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));
+
+ return settings && hasDynamicPromptSyntax(settings.positivePrompt) ? settings : null;
+};
+
+/**
+ * Resolving the expansion here rather than inside Queue keeps Queue free of a
+ * Generation import, which would close a `gallery -> queue -> generation`
+ * dependency cycle. Reading the shared cache means invoking mid-edit still
+ * submits the prompts the backend actually produces. A failed expansion falls
+ * back to the literal prompt so an Invoke is never silently swallowed.
+ */
+const resolveExpandedPrompts = async (settings: GenerateSettings): Promise<string[] | undefined> => {
+ try {
+ const { prompts } = await resolveDynamicPrompts(queryClient, {
+ combinatorial: settings.dynamicPromptsCombinatorial,
+ max_prompts: settings.dynamicPromptsMaxPrompts,
+ prompt: settings.positivePrompt,
+ seed: settings.dynamicPromptsCombinatorial ? null : settings.dynamicPromptsSampleSeed,
+ });
+
+ return prompts.length > 0 ? prompts : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
export const submitResolvedInvocation = ({
commands,
formatControlLayerError,
@@ -60,6 +100,40 @@ export const submitResolvedInvocation = ({
return;
}
+ const expandableSettings = getExpandableSettings(project, route);
+
+ // Only a prompt with dynamic syntax pays for a round trip; every other Invoke
+ // stays on the synchronous path it has always taken.
+ if (expandableSettings) {
+ void resolveExpandedPrompts(expandableSettings).then((positivePrompts) => {
+ if (isAccountScopeCurrent(owner)) {
+ dispatchResolvedInvocation(
+ { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
+ positivePrompts
+ );
+ }
+ });
+ return;
+ }
+
+ dispatchResolvedInvocation(
+ { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
+ undefined
+ );
+};
+
+const dispatchResolvedInvocation = (
+ {
+ commands,
+ formatControlLayerError,
+ models,
+ owner,
+ prepareCanvasInvocation,
+ project,
+ route,
+ }: SubmitResolvedInvocationDeps,
+ positivePrompts: string[] | undefined
+): void => {
if (route.sourceId === 'canvas') {
// The canvas graph is composited + compiled asynchronously outside the
// reducer; fire-and-track (the orchestrator records any failure notice and
@@ -74,6 +148,7 @@ export const submitResolvedInvocation = ({
generateValues: getProjectWidgetValues(project, 'generate'),
models,
owner,
+ positivePrompts,
projectId: project.id,
projectSettings: project.settings,
strength: readCanvasDenoisingStrength(getProjectWidgetValues(project, 'canvas')),
@@ -84,6 +159,7 @@ export const submitResolvedInvocation = ({
commands.generation.submitResolved({
backendSupportsCancellation: true,
models,
+ positivePrompts,
route,
});
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 5f71f0137e..f4b9bca504 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -98,6 +98,8 @@ export interface RunCanvasInvocationDeps {
* composite → upload, releasing pixel resources on both success and failure.
*/
composeForGeneration: (options: ComposeForGenerationOptions) => Promise<ComposeForGenerationResult>;
+ /** Expanded positive prompts, resolved by the caller before submitting. */
+ positivePrompts?: string[];
/** Cancels raster capture for this invocation. */
signal: AbortSignal;
/** Paint-bitmap persistence barrier, awaited before compositing. */
@@ -401,6 +403,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
},
graph: compiled.graph,
canvas: composites.canvas,
+ positivePrompts: deps.positivePrompts,
projectId,
});
composed.dedupeCommit.commit();
@@ -440,6 +443,8 @@ export interface PrepareCanvasInvocationArgs {
models?: readonly ModelConfig[];
/** Caller-captured identity lifetime; direct synchronous callers may omit it. */
owner?: AccountScope;
+ /** Expanded positive prompts, resolved by the caller before submitting. */
+ positivePrompts?: string[];
projectSettings: Pick<ProjectSettings, 'useCpuNoise'>;
strength: number;
signal?: AbortSignal;
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 84370d2d97..e089994963 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -143,6 +143,7 @@ const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): Ge
colorCompensation: false,
dynamicPromptsCombinatorial: true,
dynamicPromptsMaxPrompts: 100,
+ dynamicPromptsSampleSeed: 0,
dynamicPromptsSeedBehaviour: 'per-iteration',
componentSourceModel: null,
height: 1024,
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 979945ab8b..18251ffff5 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -74,6 +74,7 @@ import {
getGenerationModelAvailabilityReasons,
getPromptDraftFromValues,
getPromptHistoryItemFromGenerateSettings,
+ hasDynamicPromptSyntax,
migrateProjectPromptDraft,
normalizeGenerateSettings,
normalizeGenerateWidgetValues,
@@ -214,6 +215,8 @@ type WorkbenchReducerAction =
| {
type: 'submitResolvedInvocationSnapshot';
backendSupportsCancellation: boolean;
+ /** Expanded positive prompts, resolved by the caller before dispatch. */
+ positivePrompts?: string[];
route: InvocationRoute;
models?: readonly ModelConfig[];
}
@@ -280,6 +283,8 @@ type WorkbenchReducerAction =
destination: ResultDestination;
generate: QueueGenerateSnapshot;
graph: GraphContract;
+ /** Expanded positive prompts, resolved by the caller before dispatch. */
+ positivePrompts?: string[];
projectId: string;
}
| { type: 'cancelQueueItem'; queueItemId: string; projectId?: string }
@@ -2006,7 +2011,12 @@ const routeQueueItemResults = (project: Project, queueItemId: string, images: Ge
const enqueueCompiledSnapshot = (
project: Project,
route: InvocationRoute,
- compiled: { generate?: QueueGenerateSnapshot; graph: GraphContract; widgetStates: WidgetStateMap },
+ compiled: {
+ generate?: QueueGenerateSnapshot;
+ graph: GraphContract;
+ positivePrompts?: string[];
+ widgetStates: WidgetStateMap;
+ },
backendSupportsCancellation: boolean,
canvasSnapshot?: CanvasStateContractV2
): Project => {
@@ -2024,14 +2034,29 @@ const enqueueCompiledSnapshot = (
const upscaleSettings =
route.sourceId === 'upscale' ? normalizeUpscaleWidgetValues(widgetStates.upscale.values) : null;
const backendGraph = graph.backendGraph;
+ const canvasGenerateSettings = route.sourceId === 'canvas' ? normalizeGenerateSettings(generate?.values) : null;
const sourceGenerateSettings =
route.sourceId === 'canvas'
- ? normalizeGenerateSettings(generate?.values)
+ ? canvasGenerateSettings
: route.sourceId === 'generate'
? generateSettings
: route.sourceId === 'upscale'
? upscaleSettings
: null;
+ // Dynamic prompting is a Generate setting, so only the routes compiled from
+ // GenerateSettings honour it; Upscale keeps its prompt literal. The caller has
+ // already expanded, so the queue item records the exact prompts it will submit.
+ const expandedPositivePrompts =
+ route.sourceId !== 'upscale' &&
+ compiled.positivePrompts &&
+ compiled.positivePrompts.length > 1 &&
+ sourceGenerateSettings &&
+ hasDynamicPromptSyntax(sourceGenerateSettings.positivePrompt)
+ ? compiled.positivePrompts
+ : undefined;
+ const expandedSeedBehaviour = expandedPositivePrompts
+ ? (canvasGenerateSettings ?? generateSettings)?.dynamicPromptsSeedBehaviour
+ : undefined;
const backendSubmission: QueueCompiledSubmission = !backendGraph
? { error: `${route.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' }
: route.sourceId === 'workflow'
@@ -2049,7 +2074,9 @@ const enqueueCompiledSnapshot = (
negativePromptNodeId: generate?.negativePromptNodeId ?? 'negative_prompt',
positivePrompt: sourceGenerateSettings.positivePrompt,
positivePromptNodeId: generate?.positivePromptNodeId ?? 'positive_prompt',
+ ...(expandedPositivePrompts ? { positivePrompts: expandedPositivePrompts } : {}),
seed: sourceGenerateSettings.seed,
+ ...(expandedSeedBehaviour ? { seedBehaviour: expandedSeedBehaviour } : {}),
seedNodeId: generate?.seedNodeId ?? 'seed',
shouldRandomizeSeed: sourceGenerateSettings.shouldRandomizeSeed,
}
@@ -2075,7 +2102,12 @@ const enqueueCompiledSnapshot = (
...(generate ? { generate: cloneQueueGenerateSnapshot(generate) } : {}),
graph,
presentation: {
- batchCount: backendSubmission.kind === 'invalid' ? 1 : backendSubmission.batchCount,
+ // Placeholder sizing only: superseded by the backend's real item ids as
+ // soon as the batch is accepted.
+ batchCount:
+ backendSubmission.kind === 'invalid'
+ ? 1
+ : backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),
height: presentationDimensions.height,
...(sourceGenerateSettings?.positivePrompt ? { positivePrompt: sourceGenerateSettings.positivePrompt } : {}),
width: presentationDimensions.width,
@@ -2132,7 +2164,8 @@ const submitInvocationSnapshot = (
project: Project,
backendSupportsCancellation: boolean,
route = resolveInvocationRoute(project),
- models?: readonly ModelConfig[]
+ models?: readonly ModelConfig[],
+ positivePrompts?: string[]
): Project => {
if (!isInvocationRouteValid(route)) {
return project;
@@ -2144,7 +2177,7 @@ const submitInvocationSnapshot = (
return project;
}
- return enqueueCompiledSnapshot(project, route, compiledSnapshot, backendSupportsCancellation);
+ return enqueueCompiledSnapshot(project, route, { ...compiledSnapshot, positivePrompts }, backendSupportsCancellation);
};
export const createInitialWorkbenchState = (): WorkbenchState => {
@@ -2704,7 +2737,8 @@ export const __workbenchReducerInternal = (
project,
action.backendSupportsCancellation,
resolveInvocationRoute(project, 'global', action.route, action.models),
- action.models
+ action.models,
+ action.positivePrompts
)
);
}
@@ -3204,6 +3238,7 @@ export const __workbenchReducerInternal = (
{
generate: action.generate,
graph: action.graph,
+ positivePrompts: action.positivePrompts,
widgetStates: getWidgetStatesSnapshot(project.widgetInstances),
},
action.backendSupportsCancellation,