Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): add dynamic prompt policy and syntax scanning
joshistoastf5c20fbbed65
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 68660e215d..9ed9ef9d36 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -27,6 +27,7 @@ import {isVaeForBases,type GenerateComponentFilter,} from './componentCompatibility';+import { DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS } from './dynamicPrompts';import {clampDimension,DEFAULT_REFERENCE_IMAGE_LIMIT,@@ -547,6 +548,9 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): GeneratcfgScale: defaults.cfgScale,clipSkip: 0,colorCompensation: false,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,+ dynamicPromptsSeedBehaviour: 'per-iteration',clipEmbedModel: null,clipGEmbedModel: null,clipLEmbedModel: null,diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.tsnew file mode 100644index 0000000000..ceca28651a--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts@@ -0,0 +1,180 @@+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,+});++describe('hasDynamicPromptSyntax', () => {+ it('detects a variant anywhere in the prompt', () => {+ expect(hasDynamicPromptSyntax('a {red|green} ball')).toBe(true);+ expect(hasDynamicPromptSyntax('{a}')).toBe(true);+ expect(hasDynamicPromptSyntax('multi\nline {a|b}')).toBe(true);+ });++ it('ignores prompts with no braces, including bare wildcards', () => {+ expect(hasDynamicPromptSyntax('a red ball')).toBe(false);+ expect(hasDynamicPromptSyntax('a __color__ ball')).toBe(false);+ expect(hasDynamicPromptSyntax('unclosed { brace')).toBe(false);+ });+});++describe('sanitizeMaxPrompts', () => {+ it('clamps to the backend bounds and falls back on garbage', () => {+ expect(sanitizeMaxPrompts(50)).toBe(50);+ expect(sanitizeMaxPrompts(0)).toBe(1);+ expect(sanitizeMaxPrompts(99_999)).toBe(10_000);+ expect(sanitizeMaxPrompts(12.6)).toBe(13);+ expect(sanitizeMaxPrompts('many')).toBe(100);+ expect(sanitizeMaxPrompts(undefined)).toBe(100);+ });+});++describe('sanitizeDynamicPromptsConfig', () => {+ it('returns null for non-object values', () => {+ expect(sanitizeDynamicPromptsConfig(null)).toBeNull();+ expect(sanitizeDynamicPromptsConfig('nope')).toBeNull();+ });++ it('defaults every unusable field', () => {+ expect(sanitizeDynamicPromptsConfig({})).toEqual({+ combinatorial: true,+ maxPrompts: 100,+ seedBehaviour: 'per-iteration',+ });+ expect(sanitizeDynamicPromptsConfig({ combinatorial: false, maxPrompts: 7, seedBehaviour: 'per-image' })).toEqual({+ combinatorial: false,+ maxPrompts: 7,+ 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.tsnew file mode 100644index 0000000000..1e5efefcbb--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts@@ -0,0 +1,166 @@+/**+ * Dynamic prompting policy: detecting the syntax, bounding the expansion, and+ * turning an expanded prompt list into the batch matrix the backend expects.+ *+ * 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).+ */++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;++/** Matches the backend's `max_prompts: int = Body(ge=1, le=10000)`. */+export const DYNAMIC_PROMPTS_MIN_PROMPTS = 1;+export const DYNAMIC_PROMPTS_MAX_PROMPTS = 10_000;+export const DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS = 100;++export type DynamicPromptsSeedBehaviour = 'per-iteration' | 'per-image';++export const DYNAMIC_PROMPTS_SEED_BEHAVIOURS: readonly DynamicPromptsSeedBehaviour[] = ['per-iteration', 'per-image'];++export interface DynamicPromptsConfig {+ combinatorial: boolean;+ maxPrompts: number;+ seedBehaviour: DynamicPromptsSeedBehaviour;+}++/**+ * Whether a prompt is worth sending to the expansion route at all. A prompt with+ * no `{…}` is its own single expansion, so the round trip is skipped entirely.+ *+ * Deliberately does not look for `__wildcard__`: this deployment runs an+ * unconfigured `WildcardManager`, so wildcards never resolve.+ */+export const hasDynamicPromptSyntax = (prompt: string): boolean => /\{[\s\S]*\}/.test(prompt);++export const isDynamicPromptsSeedBehaviour = (value: unknown): value is DynamicPromptsSeedBehaviour =>+ value === 'per-iteration' || value === 'per-image';++export const sanitizeMaxPrompts = (value: unknown): number =>+ typeof value === 'number' && Number.isFinite(value)+ ? Math.min(DYNAMIC_PROMPTS_MAX_PROMPTS, Math.max(DYNAMIC_PROMPTS_MIN_PROMPTS, Math.round(value)))+ : DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS;++/** Reads an untrusted persisted/transported config, or `null` when it is unusable. */+export const sanitizeDynamicPromptsConfig = (value: unknown): DynamicPromptsConfig | null => {+ if (!value || typeof value !== 'object') {+ return null;+ }++ const config = value as Partial<DynamicPromptsConfig>;++ return {+ combinatorial: config.combinatorial !== false,+ maxPrompts: sanitizeMaxPrompts(config.maxPrompts),+ 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();++ 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/generation/core/prompt/dynamicPromptSyntax.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.tsnew file mode 100644index 0000000000..0ddbff2ca3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from 'vitest';++import { scanDynamicPromptSyntax } from './dynamicPromptSyntax';++const annotate = (prompt: string) =>+ scanDynamicPromptSyntax(prompt)+ .sort((left, right) => left.range.start - right.range.start)+ .map(({ kind, range }) => [kind, prompt.slice(range.start, range.end)]);++describe('scanDynamicPromptSyntax', () => {+ it('annotates braces and separators of a variant', () => {+ expect(annotate('a {red|green|blue} ball')).toEqual([+ ['variantBrace', '{'],+ ['variantSeparator', '|'],+ ['variantSeparator', '|'],+ ['variantBrace', '}'],+ ]);+ });++ it('leaves a pipe outside a variant alone', () => {+ expect(annotate('a | b')).toEqual([]);+ });++ it('annotates value weights', () => {+ expect(annotate('{2::red|1.5::green}')).toEqual([+ ['variantBrace', '{'],+ ['variantWeight', '2::'],+ ['variantSeparator', '|'],+ ['variantWeight', '1.5::'],+ ['variantBrace', '}'],+ ]);+ });++ it('annotates count and range prefixes, including a custom separator', () => {+ expect(annotate('{2$$a|b}')).toEqual([+ ['variantBrace', '{'],+ ['variantRange', '2$$'],+ ['variantSeparator', '|'],+ ['variantBrace', '}'],+ ]);+ expect(annotate('{1-3$$a|b}')).toEqual([+ ['variantBrace', '{'],+ ['variantRange', '1-3$$'],+ ['variantSeparator', '|'],+ ['variantBrace', '}'],+ ]);+ expect(annotate('{2$$ and $$a|b}')).toEqual([+ ['variantBrace', '{'],+ ['variantRange', '2$$ and $$'],+ ['variantSeparator', '|'],+ ['variantBrace', '}'],+ ]);+ });++ it('handles nested variants', () => {+ expect(annotate('{a|{b|c}}')).toEqual([+ ['variantBrace', '{'],+ ['variantSeparator', '|'],+ ['variantBrace', '{'],+ ['variantSeparator', '|'],+ ['variantBrace', '}'],+ ['variantBrace', '}'],+ ]);+ });++ it('flags an unclosed brace', () => {+ expect(annotate('a {red|green ball')).toEqual([+ ['error', '{'],+ ['variantSeparator', '|'],+ ]);+ });++ it('flags a stray closing brace', () => {+ expect(annotate('a red} ball')).toEqual([['error', '}']]);+ });++ it('annotates wildcards', () => {+ expect(annotate('a __color__ __animals/dogs__')).toEqual([+ ['wildcard', '__color__'],+ ['wildcard', '__animals/dogs__'],+ ]);+ });++ it('annotates a variable reference as one span, without descending into it', () => {+ expect(annotate(`\${colour} ball`)).toEqual([['promptVariable', `\${colour}`]]);+ expect(annotate(`\${colour=red|green}`)).toEqual([['promptVariable', `\${colour=red|green}`]]);+ });++ it('skips escaped braces', () => {+ expect(annotate('a \\{literal\\} brace')).toEqual([]);+ });++ it('returns nothing for a plain prompt', () => {+ expect(annotate('a photo of a cat, highly detailed')).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.tsnew file mode 100644index 0000000000..ad52e72087--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts@@ -0,0 +1,161 @@+/**+ * Scanner for adieyal/dynamicprompts syntax (`{a|b}`, `{2::a|b}`, `{2-3$$a|b}`,+ * `__wildcard__`, `${variable}`).+ *+ * This is intentionally a standalone character scanner rather than an extension+ * of `ast.ts`. That tokenizer already emits every character we care about as its+ * own whole token — `{`/`}` fall through to its single-char catch-all, `|`/`$`/`:`+ * are single-char punctuation, and `__wildcard__` reads as one word because `_`+ * is a word character. So the ranges produced here always cover whole tokens and+ * compose with the existing highlight annotations, leaving the attention and+ * embedding parser untouched.+ */++import type { PromptRange } from './ast';++export type DynamicPromptSyntaxKind =+ | 'variantBrace'+ | 'variantSeparator'+ | 'variantWeight'+ | 'variantRange'+ | 'wildcard'+ | 'promptVariable'+ | 'error';++export interface DynamicPromptSyntaxAnnotation {+ kind: DynamicPromptSyntaxKind;+ range: PromptRange;+}++const WILDCARD_PATTERN = /__(.+?)__/g;+/** `2::`, `1.5::` — a variant value's relative weight. */+const WEIGHT_PATTERN = /^\s*\d+(?:\.\d+)?::/;+/** `2$$`, `2-3$$`, `-3$$`, and the custom-separator form `2$$, $$`. */+const RANGE_PATTERN = /^\s*(?:\d+)?(?:-\d+)?\$\$(?:[^$|{}]*\$\$)?/;++const isEscaped = (prompt: string, index: number): boolean => {+ let backslashes = 0;++ for (let cursor = index - 1; cursor >= 0 && prompt[cursor] === '\\'; cursor--) {+ backslashes++;+ }++ return backslashes % 2 === 1;+};++const findVariableEnd = (prompt: string, openBraceIndex: number): number => {+ let depth = 0;++ for (let cursor = openBraceIndex; cursor < prompt.length; cursor++) {+ if (prompt[cursor] === '{' && !isEscaped(prompt, cursor)) {+ depth++;+ } else if (prompt[cursor] === '}' && !isEscaped(prompt, cursor)) {+ depth--;++ if (depth === 0) {+ return cursor + 1;+ }+ }+ }++ return -1;+};++const covers = (outer: PromptRange, inner: PromptRange): boolean =>+ outer.start <= inner.start && outer.end >= inner.end;++/**+ * Annotates a prompt's dynamic syntax. Unmatched braces in either direction are+ * reported as `error` so the textarea can underline them the same way it already+ * underlines unbalanced attention parentheses.+ */+export const scanDynamicPromptSyntax = (prompt: string): DynamicPromptSyntaxAnnotation[] => {+ const annotations: DynamicPromptSyntaxAnnotation[] = [];+ const variableRanges: PromptRange[] = [];+ // Open braces awaiting a `}`, paired with the annotation to rewrite if none arrives.+ const openBraces: { annotationIndex: number }[] = [];+ let index = 0;++ const annotateValueStart = (start: number): void => {+ const weight = prompt.slice(start).match(WEIGHT_PATTERN)?.[0];++ if (weight) {+ annotations.push({ kind: 'variantWeight', range: { end: start + weight.length, start } });+ }+ };++ while (index < prompt.length) {+ const char = prompt[index];++ if (char === '\\') {+ index += 2;+ continue;+ }++ if (char === '$' && prompt[index + 1] === '{') {+ const end = findVariableEnd(prompt, index + 1);++ if (end > 0) {+ annotations.push({ kind: 'promptVariable', range: { end, start: index } });+ variableRanges.push({ end, start: index });+ index = end;+ continue;+ }+ }++ if (char === '{') {+ annotations.push({ kind: 'variantBrace', range: { end: index + 1, start: index } });+ openBraces.push({ annotationIndex: annotations.length - 1 });++ const rangePrefix = prompt.slice(index + 1).match(RANGE_PATTERN)?.[0];++ if (rangePrefix) {+ annotations.push({+ kind: 'variantRange',+ range: { end: index + 1 + rangePrefix.length, start: index + 1 },+ });+ index += 1 + rangePrefix.length;+ } else {+ index++;+ }++ annotateValueStart(index);+ continue;+ }++ if (char === '}') {+ annotations.push({+ kind: openBraces.length > 0 ? 'variantBrace' : 'error',+ range: { end: index + 1, start: index },+ });+ openBraces.pop();+ index++;+ continue;+ }++ if (char === '|' && openBraces.length > 0) {+ annotations.push({ kind: 'variantSeparator', range: { end: index + 1, start: index } });+ index++;+ annotateValueStart(index);+ continue;+ }++ index++;+ }++ for (const openBrace of openBraces) {+ annotations[openBrace.annotationIndex].kind = 'error';+ }++ WILDCARD_PATTERN.lastIndex = 0;++ for (let match = WILDCARD_PATTERN.exec(prompt); match; match = WILDCARD_PATTERN.exec(prompt)) {+ const wildcardRange = { end: match.index + match[0].length, start: match.index };++ if (!variableRanges.some((variableRange) => covers(variableRange, wildcardRange))) {+ annotations.push({ kind: 'wildcard', range: wildcardRange });+ }+ }++ return annotations;+};diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.tsindex 7a75a2053a..a69074319f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts@@ -53,4 +53,35 @@ describe('prompt highlight segments', () => {expect(kindForText(prompt, '-')).toBe('punctuation');});++ describe('dynamic prompt syntax', () => {+ const dynamicKindForText = (prompt: string, text: string): PromptHighlightKind | undefined =>+ buildPromptHighlightSegments(prompt, { dynamicPrompts: true }).find((segment) => segment.text === text)?.kind;++ it('is off by default, so surfaces that never expand see plain text', () => {+ const prompt = 'a {red|green} ball';++ expect(kindForText(prompt, '{')).toBe('text');+ expect(kindForText(prompt, '|')).toBe('punctuation');+ });++ it('marks variant braces, separators and weights when enabled', () => {+ expect(dynamicKindForText('a {red|green} ball', '{')).toBe('variantBrace');+ expect(dynamicKindForText('a {red|green} ball', '|')).toBe('variantSeparator');+ expect(dynamicKindForText('a {red|green} ball', '}')).toBe('variantBrace');+ expect(dynamicKindForText('{2::red|green}', '2::')).toBe('variantWeight');+ expect(dynamicKindForText('{1-2$$red|green}', '1-2$$')).toBe('variantRange');+ expect(dynamicKindForText('a __color__ ball', '__color__')).toBe('wildcard');+ expect(dynamicKindForText(`\${colour} ball`, `\${colour}`)).toBe('promptVariable');+ });++ it('marks an unbalanced brace as an error, like an unbalanced parenthesis', () => {+ expect(dynamicKindForText('a {red green', '{')).toBe('error');+ expect(dynamicKindForText('a red} green', '}')).toBe('error');+ });++ it('leaves attention syntax inside a variant intact', () => {+ expect(dynamicKindForText('{red+|green}', '+')).toBe('attention');+ });+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.tsindex 47098e7763..ffdbecc539 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts@@ -1,6 +1,7 @@import type { PromptAstNode, PromptRange, PromptToken } from './ast';import { parsePromptTokens, tokenizePrompt } from './ast';+import { scanDynamicPromptSyntax } from './dynamicPromptSyntax';export type PromptHighlightKind =| 'text'@@ -12,8 +13,24 @@ export type PromptHighlightKind =| 'promptFunctionMethod'| 'promptFunctionArg'| 'punctuation'+ | 'variantBrace'+ | 'variantSeparator'+ | 'variantWeight'+ | 'variantRange'+ | 'wildcard'+ | 'promptVariable'| 'error';+export interface PromptHighlightOptions {+ /**+ * Annotate dynamic prompting syntax. Only surfaces whose prompt is actually+ * batch-expanded enable this — a `{a|b}` in a regional guidance or negative+ * prompt is literal text, and colouring it would promise an expansion that+ * never happens.+ */+ dynamicPrompts?: boolean;+}+export interface PromptHighlightSegment {kind: PromptHighlightKind;range: PromptRange;@@ -28,6 +45,12 @@ interface HighlightAnnotation {const ANNOTATION_PRIORITY = {error: 100,+ wildcard: 45,+ promptVariable: 45,+ variantRange: 42,+ variantWeight: 42,+ variantBrace: 41,+ variantSeparator: 41,embedding: 40,promptFunctionMethod: 35,promptFunctionArg: 5,@@ -42,8 +65,14 @@ const BASE_PRIORITY: Record<PromptHighlightKind, number> = {group: 20,promptFunctionArg: 5,promptFunctionMethod: 35,+ promptVariable: 45,punctuation: 10,text: 0,+ variantBrace: 41,+ variantRange: 42,+ variantSeparator: 41,+ variantWeight: 42,+ wildcard: 45,};const isNumericAttention = (value: unknown): boolean => typeof value === 'number' || !Number.isNaN(Number(value));@@ -167,14 +196,28 @@ const appendSegment = (segments: PromptHighlightSegment[], segment: PromptHighlisegments.push(segment);};-export const buildPromptHighlightSegments = (prompt: string): PromptHighlightSegment[] => {+const collectDynamicPromptAnnotations = (prompt: string): HighlightAnnotation[] =>+ scanDynamicPromptSyntax(prompt).map(({ kind, range }) => ({+ kind,+ priority: ANNOTATION_PRIORITY[kind],+ range,+ }));++export const buildPromptHighlightSegments = (+ prompt: string,+ options: PromptHighlightOptions = {}+): PromptHighlightSegment[] => {if (!prompt) {return [];}try {const tokens = tokenizePrompt(prompt);- const annotations = [...collectAnnotations(prompt, parsePromptTokens(tokens)), ...collectParenthesisErrors(tokens)];+ const annotations = [+ ...collectAnnotations(prompt, parsePromptTokens(tokens)),+ ...collectParenthesisErrors(tokens),+ ...(options.dynamicPrompts ? collectDynamicPromptAnnotations(prompt) : []),+ ];const segments: PromptHighlightSegment[] = [];for (const token of tokens) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex f98223beb2..1186d54aa6 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -16,6 +16,7 @@ import type {import { sanitizeBatchCount } from './batch';import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';+import { isDynamicPromptsSeedBehaviour, sanitizeMaxPrompts } from './dynamicPrompts';import { cloneCroppableImage, isCanonicalCroppableImage, normalizeCroppableImage } from './referenceImage';/** Preset ratios, with the preset to switch to when dimensions are swapped. */@@ -555,6 +556,12 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | ncfgScale: values.cfgScale as number,clipSkip: hasFiniteNumber(values, 'clipSkip') ? (values.clipSkip as number) : 0,colorCompensation: typeof values.colorCompensation === 'boolean' ? values.colorCompensation : false,+ dynamicPromptsCombinatorial:+ typeof values.dynamicPromptsCombinatorial === 'boolean' ? values.dynamicPromptsCombinatorial : true,+ dynamicPromptsMaxPrompts: sanitizeMaxPrompts(values.dynamicPromptsMaxPrompts),+ dynamicPromptsSeedBehaviour: isDynamicPromptsSeedBehaviour(values.dynamicPromptsSeedBehaviour)+ ? values.dynamicPromptsSeedBehaviour+ : 'per-iteration',height,loras: Array.isArray(values.loras) ? values.loras.filter(isGenerateLora) : [],modelKey: values.modelKey as string,diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex 1542acfc90..51909ec7a0 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -1,4 +1,5 @@import type { BackendGraphContract, GraphContract } from '@features/generation/core/contracts';+import type { DynamicPromptsSeedBehaviour } from '@features/generation/core/dynamicPrompts';export type ModelIdentifierConfig = {key: string;@@ -156,6 +157,11 @@ export interface GenerateSettings {negativePromptEnabled: boolean;negativePrompt: string;negativePromptHeightPx: number;+ /** Expand `{a|b}` into every combination; otherwise draw a random sample. */+ dynamicPromptsCombinatorial: boolean;+ /** Upper bound on expanded prompts (the sample size when not combinatorial). */+ dynamicPromptsMaxPrompts: number;+ dynamicPromptsSeedBehaviour: DynamicPromptsSeedBehaviour;width: number;height: number;aspectRatioId: AspectRatioId;diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 8c3c9c229c..25c97cd9bb 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -50,6 +50,20 @@ export {} from './core/baseGenerationPolicies';export { isVaeCompatibleWithGenerateModel } from './core/componentCompatibility';export { MIN_BATCH_COUNT, sanitizeBatchCount } from './core/batch';+export {+ buildGeneratePromptBatchPlan,+ DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,+ DYNAMIC_PROMPTS_MAX_PROMPTS,+ DYNAMIC_PROMPTS_MIN_PROMPTS,+ DYNAMIC_PROMPTS_SEED_BEHAVIOURS,+ hasDynamicPromptSyntax,+ isDynamicPromptsSeedBehaviour,+ sanitizeDynamicPromptsConfig,+ sanitizeMaxPrompts,+ type DynamicPromptsConfig,+ type DynamicPromptsSeedBehaviour,+ type GeneratePromptBatchPlan,+} from './core/dynamicPrompts';export {addPromptHistoryItem,getPromptHistoryItemFromGenerateSettings,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsxindex 488b59fceb..753c42e379 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx@@ -24,8 +24,14 @@ const HIGHLIGHT_STYLE_BY_KIND: Record<group: { color: 'fg.subtle' },promptFunctionArg: { bg: 'accent.subtle/20', color: 'fg' },promptFunctionMethod: { color: 'accent.fg' },+ promptVariable: { color: 'accent.fg' },punctuation: { color: 'fg.subtle' },text: { color: 'fg' },+ variantBrace: { color: 'accent.fg' },+ variantRange: { color: 'fg.success' },+ variantSeparator: { color: 'fg.muted' },+ variantWeight: { color: 'fg.success' },+ wildcard: { color: 'fg.subtle' },};const PROMPT_TEXTAREA_FORCED_COLORS_CSS = { '@media (forced-colors: active)': { display: 'none' } };diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex 40c745ca73..e6fae6d9d9 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -13,7 +13,7 @@ import {toGraphContract,toModelIdentifier,} from '@features/generation/graph';-import { coerceSchedulerForGraph } from '@features/generation/settings';+import { coerceSchedulerForGraph, DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS } from '@features/generation/settings';import type { CompiledUpscaleGraph, UpscaleWidgetValues } from './types';@@ -58,6 +58,10 @@ const addUpscaleMetadata = (cfgRescaleMultiplier: 0,colorCompensation: false,componentSourceModel: null,+ // Upscale prompts are not batch-expanded; these only satisfy the shape.+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,+ dynamicPromptsSeedBehaviour: 'per-iteration',height: dimensions.height,modelKey: settings.model.key,negativePromptHeightPx: 56,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex 78b56c15fb..cb72a27b9f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -73,6 +73,9 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])clipLEmbedModel: null,clipSkip: 0,colorCompensation: false,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: 100,+ dynamicPromptsSeedBehaviour: 'per-iteration',componentSourceModel: null,height: 1024,loras: [],diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex 5a08cc0098..3c8db4e454 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -41,6 +41,9 @@ const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWiclipLEmbedModel: null,clipSkip: 0,colorCompensation: false,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: 100,+ dynamicPromptsSeedBehaviour: 'per-iteration',componentSourceModel: null,height: 1024,loras: [],diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex eb18d2d168..84370d2d97 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -141,6 +141,9 @@ const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GeclipLEmbedModel: null,clipSkip: 0,colorCompensation: false,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: 100,+ dynamicPromptsSeedBehaviour: 'per-iteration',componentSourceModel: null,height: 1024,loras: [],