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(video): expand dynamic prompts in the Video panel (#10128)

Lincoln Steina388b9c34264
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx
index faf1be49a5..284e7a9150 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx
@@ -214,7 +214,9 @@ An image's metadata records the prompt that was actually used, with the template
Dynamic prompts expand a single prompt into many variations. Write the parts you want to vary as a list of alternatives, and one press of **Invoke** generates an image for each variation. They are useful for brainstorming, exploring styles and subjects, and testing a model without rewriting the same prompt by hand.
-Dynamic prompts work in the **Generate** panel and on the Canvas. Only the positive prompt is expanded; the negative prompt is used as written for every variation.
+Dynamic prompts work in the **Generate** panel, on the Canvas and in the [**Video** panel](/users-guide/video-generation/introduction/#prompt). Only the positive prompt is expanded; the negative prompt is used as written for every variation.
+
+In the **Video** panel each variation queues a full video, so **Max prompts** starts at 10 there instead of 100. Projects saved before Video supported dynamic prompts open with them off, so their prompts keep running as typed; switch on **Use dynamic prompts** to expand them.
### Basic syntax
@@ -277,7 +279,7 @@ The number of prompts can be set from 1 to 10,000 and is 100 by default. Combina
By default, every variation within one iteration shares the same seed. Because only the prompt changes between the images, this makes it easy to see what each option does.
-Turn on **New seed for every image** to give each image its own seed instead, for the widest variety. When the panel's **Seed mode** is **Fixed**, every image uses the same seed and this switch is unavailable.
+Turn on **New seed for every generation** to give each image its own seed instead, for the widest variety. When the panel's **Seed mode** is **Fixed**, every image uses the same seed and this switch is unavailable.
### Dynamic prompts and other features
diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx
index 7f8cb177db..7508701e01 100644
--- a/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx
+++ b/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx
@@ -72,7 +72,7 @@ If you pick a model that can't run the current combination, the Invoke button te
### Prompt
-The prompt toolbar carries most of the helpers from the image Generate panel — prompt triggers, prompt expansion, image-to-prompt, and history (prompt templates are only available in Generate). On LTX-2, **Expand Prompt** starts from the enhancer LTX-2.5 was released with and, when a first frame is set, describes the video from that frame — see [prompt enhancement for LTX-2.5](/users-guide/image-generation/prompt-tools/#prompt-enhancement-for-ltx-25). The **negative prompt** behaves per family:
+The prompt toolbar carries most of the helpers from the image Generate panel — prompt triggers, prompt expansion, image-to-prompt, history and [dynamic prompts](/users-guide/image-generation/prompting-guide/#dynamic-prompts) (prompt templates are only available in Generate). Each expanded prompt queues a full video, and **Max prompts** defaults to 10 here. Projects saved before Video supported dynamic prompts open with them off. On LTX-2, **Expand Prompt** starts from the enhancer LTX-2.5 was released with and, when a first frame is set, describes the video from that frame — see [prompt enhancement for LTX-2.5](/users-guide/image-generation/prompt-tools/#prompt-enhancement-for-ltx-25). The **negative prompt** behaves per family:
* **Wan** — used only when CFG is greater than 1 (the field says so). With the Lightning fast path on (CFG 1), it is ignored by the graph.
* **MiniMax H3** — hidden entirely. H3 is guidance-distilled and has no CFG, so a negative prompt has nothing to act on.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index c8b078f630..2f46743708 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -478,6 +478,7 @@
"serverDisconnected": "The server is disconnected.",
"batchNotReady": "The batch is not ready",
"expansionFailed": "The prompt could not be expanded",
+ "expansionStale": "The prompt changed while it was being expanded, so nothing was queued. Invoke again.",
"expansionUnreachable": "The server could not be reached to expand the prompt. Check the connection and try again, or turn dynamic prompts off to use the prompt as typed.",
"generatorFailed": "The batch generator could not be resolved"
},
@@ -3031,7 +3032,7 @@
"selectedWildcardCount_other": "{{count}} selected",
"title": "Dynamic prompts",
"showPrompts": "Show dynamic prompts",
- "noDynamicSyntax": "Wrap alternatives in braces to generate one image per combination, e.g. a {red|green} ball",
+ "noDynamicSyntax": "Wrap alternatives in braces to generate one result per combination, e.g. a {red|green} ball",
"summary": "{{prompts}} × {{iterations}} → {{generations}}",
"expanding": "Expanding…",
"allCombinations": "All combinations",
@@ -3067,9 +3068,9 @@
"deleteWildcardBody": "Delete __{{name}}__ and its values? This cannot be undone.",
"resizeWildcardValues": "Resize wildcard values",
"mode": "Mode",
- "newSeedPerImage": "New seed for every image",
+ "newSeedPerImage": "New seed for every generation",
"newSampleEveryInvoke": "New sample for every Invoke",
- "seedHeldForEveryImage": "A fixed seed is used for every image.",
+ "seedHeldForEveryImage": "A fixed seed is used for every generation.",
"import": "Import",
"export": "Export",
"exportAsYaml": "As YAML",
diff --git a/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsx
index 1a22178e39..5f963479f3 100644
--- a/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsx
@@ -7,7 +7,7 @@ import { ChakraProvider } from '@chakra-ui/react';
import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
import { GenerationUiProvider, type GenerationUiAdapter } from '@features/generation/ui/GenerationUiContext';
import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';
-import { getDefaultVideoSettings } from '@features/video';
+import { getDefaultVideoSettings, normalizeVideoWidgetValues } from '@features/video';
import { VideoWidgetView } from '@features/video/ui/VideoWidgetView';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
@@ -506,3 +506,47 @@ describe('video model field without a model', () => {
expect(host.textContent).toContain('Select a Wan 2.2, LTX-2 or MiniMax H3 model.');
});
});
+
+describe('the dynamic prompts decision on first mount', () => {
+ const mount = () =>
+ act(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <QueryClientProvider client={new QueryClient()}>
+ <ChakraProvider value={system}>
+ <GenerationUiProvider adapter={generationAdapter}>
+ <VideoUiAdapterProvider>
+ <VideoWidgetView />
+ </VideoUiAdapterProvider>
+ </GenerationUiProvider>
+ </ChakraProvider>
+ </QueryClientProvider>
+ </I18nextProvider>
+ )
+ );
+
+ it('keeps a new panel expanding prompts when a partial edit lands before any model is installed', async () => {
+ modelStore.set([]);
+ await mount();
+
+ // A prompt resize: the first field a seeded panel stores, written alone.
+ store.commands.widgets.patchValues('video', { positivePromptHeightPx: 150 });
+
+ expect(normalizeVideoWidgetValues(stored())?.dynamicPromptsEnabled).toBe(true);
+ });
+
+ it('records a panel saved before Video expanded prompts as off', async () => {
+ const saved: Record<string, unknown> = {
+ ...getDefaultVideoSettings(ltxDev as never, catalog as never),
+ model: ltxDev,
+ modelKey: ltxDev.key,
+ };
+ for (const key of Object.keys(saved).filter((name) => name.startsWith('dynamicPrompts'))) {
+ delete saved[key];
+ }
+ store.commands.widgets.patchValues('video', saved);
+ await mount();
+
+ expect((stored() as unknown as Record<string, unknown>).dynamicPromptsEnabled).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index e2c57fa118..89b53c802d 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -56,7 +56,7 @@ import {
type GenerateComponentFilter,
} from './componentCompatibility';
import { MAX_DIMENSION, MIN_DIMENSION } from './dimensionLimits';
-import { DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS } from './dynamicPrompts';
+import { DEFAULT_DYNAMIC_PROMPTS_SETTINGS } from './dynamicPrompts';
import {
getExternalAspectRatioSizes,
getExternalReferenceImages,
@@ -532,12 +532,7 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): Generat
hiDiffusionWindowAttentionEnabled: true,
hiDiffusionT1Ratio: DEFAULT_HIDIFFUSION_T1_RATIO,
hiDiffusionT2Ratio: DEFAULT_HIDIFFUSION_T2_RATIO,
- dynamicPromptsCombinatorial: true,
- dynamicPromptsEnabled: true,
- dynamicPromptsMaxPrompts: DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,
- dynamicPromptsSampleSeed: 0,
- dynamicPromptsResample: true,
- dynamicPromptsSeedBehaviour: 'per-iteration',
+ ...DEFAULT_DYNAMIC_PROMPTS_SETTINGS,
clipEmbedModel: null,
clipGEmbedModel: null,
clipLEmbedModel: null,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
index 6a9aad7356..d6c757a8f0 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
@@ -1,6 +1,7 @@
import { planSeedSubmission, type SeedMode, type SeedStep, type SeedSubmissionPlan } from '@platform/core/seed';
import type { EffectivePrompts, PromptTemplateSnapshot } from './promptTemplates';
+import type { DynamicPromptsSettings } from './types';
import { getEffectivePrompts, isJsonPrompt } from './promptTemplates';
@@ -12,6 +13,16 @@ export const DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS = 100;
export type DynamicPromptsSeedBehaviour = 'per-iteration' | 'per-image';
+/** Generate's dynamic prompts settings, and the fallback for each one a stored record lacks. */
+export const DEFAULT_DYNAMIC_PROMPTS_SETTINGS: Readonly<DynamicPromptsSettings> = {
+ dynamicPromptsCombinatorial: true,
+ dynamicPromptsEnabled: true,
+ dynamicPromptsMaxPrompts: DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,
+ dynamicPromptsResample: true,
+ dynamicPromptsSampleSeed: 0,
+ dynamicPromptsSeedBehaviour: 'per-iteration',
+};
+
export interface DynamicPromptsConfig {
combinatorial: boolean;
/** Off keeps the prompt as typed: nothing is expanded and `{`, `#` and `__` are plain text. */
@@ -347,10 +358,10 @@ export const findDynamicPromptComment = (prompt: string): PromptCommentMarker |
export const isDynamicPromptsSeedBehaviour = (value: unknown): value is DynamicPromptsSeedBehaviour =>
value === 'per-iteration' || value === 'per-image';
-export const sanitizeMaxPrompts = (value: unknown): number =>
+export const sanitizeMaxPrompts = (value: unknown, fallback = DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS): 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;
+ : fallback;
/** Reads an untrusted persisted/transported config, or `null` when it is unusable. */
export const sanitizeDynamicPromptsConfig = (value: unknown): DynamicPromptsConfig | null => {
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index 332b462260..7f53eb2b9e 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -5,6 +5,7 @@ import type { DynamicPromptsConfig } from './dynamicPrompts';
import type {
AspectRatioId,
ComponentModelConfig,
+ DynamicPromptsSettings,
GenerateLora,
GenerateModelConfig,
GenerateReferenceImage,
@@ -31,7 +32,12 @@ import {
KREA2_REBALANCE_WEIGHT_COUNT,
} from './conditioningRebalance';
import { MAX_DIMENSION, MIN_DIMENSION } from './dimensionLimits';
-import { isDynamicPromptsSeedBehaviour, sanitizeMaxPrompts, sanitizeSampleSeed } from './dynamicPrompts';
+import {
+ DEFAULT_DYNAMIC_PROMPTS_SETTINGS,
+ isDynamicPromptsSeedBehaviour,
+ sanitizeMaxPrompts,
+ sanitizeSampleSeed,
+} from './dynamicPrompts';
import {
GEMINI_TEMPERATURE_MAX,
GEMINI_TEMPERATURE_MIN,
@@ -97,17 +103,7 @@ export const isAspectRatioId = (value: unknown): value is AspectRatioId =>
export const DIMENSION_GRID = 8;
/** The expansion config the settings describe, under the names the expansion route and preview use. */
-export const getDynamicPromptsConfig = (
- settings: Pick<
- GenerateSettings,
- | 'dynamicPromptsCombinatorial'
- | 'dynamicPromptsEnabled'
- | 'dynamicPromptsMaxPrompts'
- | 'dynamicPromptsResample'
- | 'dynamicPromptsSampleSeed'
- | 'dynamicPromptsSeedBehaviour'
- >
-): DynamicPromptsConfig => ({
+export const getDynamicPromptsConfig = (settings: DynamicPromptsSettings): DynamicPromptsConfig => ({
combinatorial: settings.dynamicPromptsCombinatorial,
enabled: settings.dynamicPromptsEnabled,
maxPrompts: settings.dynamicPromptsMaxPrompts,
@@ -115,6 +111,45 @@ export const getDynamicPromptsConfig = (
sampleSeed: settings.dynamicPromptsSampleSeed,
seedBehaviour: settings.dynamicPromptsSeedBehaviour,
});
+
+/** The flat settings field behind each dynamic prompts config key. */
+const DYNAMIC_PROMPT_SETTING_KEYS = {
+ combinatorial: 'dynamicPromptsCombinatorial',
+ enabled: 'dynamicPromptsEnabled',
+ maxPrompts: 'dynamicPromptsMaxPrompts',
+ resample: 'dynamicPromptsResample',
+ sampleSeed: 'dynamicPromptsSampleSeed',
+ seedBehaviour: 'dynamicPromptsSeedBehaviour',
+} as const satisfies Record<keyof DynamicPromptsConfig, keyof DynamicPromptsSettings>;
+
+/** A dynamic prompts panel edit, as the settings patch that stores it. */
+export const getDynamicPromptsSettingsPatch = (patch: Partial<DynamicPromptsConfig>): Partial<DynamicPromptsSettings> =>
+ Object.fromEntries(
+ Object.entries(patch).map(([key, value]) => [DYNAMIC_PROMPT_SETTING_KEYS[key as keyof DynamicPromptsConfig], value])
+ );
+
+/** Each field a stored record lacks reads as its default: Generate's unless the surface gives its own. */
+export const normalizeDynamicPromptsSettings = (
+ values: Partial<Record<keyof DynamicPromptsSettings, unknown>>,
+ defaults: Readonly<DynamicPromptsSettings> = DEFAULT_DYNAMIC_PROMPTS_SETTINGS
+): DynamicPromptsSettings => ({
+ dynamicPromptsCombinatorial:
+ typeof values.dynamicPromptsCombinatorial === 'boolean'
+ ? values.dynamicPromptsCombinatorial
+ : defaults.dynamicPromptsCombinatorial,
+ dynamicPromptsEnabled:
+ typeof values.dynamicPromptsEnabled === 'boolean' ? values.dynamicPromptsEnabled : defaults.dynamicPromptsEnabled,
+ dynamicPromptsMaxPrompts: sanitizeMaxPrompts(values.dynamicPromptsMaxPrompts, defaults.dynamicPromptsMaxPrompts),
+ dynamicPromptsSampleSeed: sanitizeSampleSeed(values.dynamicPromptsSampleSeed),
+ dynamicPromptsResample:
+ typeof values.dynamicPromptsResample === 'boolean'
+ ? values.dynamicPromptsResample
+ : defaults.dynamicPromptsResample,
+ dynamicPromptsSeedBehaviour: isDynamicPromptsSeedBehaviour(values.dynamicPromptsSeedBehaviour)
+ ? values.dynamicPromptsSeedBehaviour
+ : defaults.dynamicPromptsSeedBehaviour,
+});
+
export const MIN_NEGATIVE_PROMPT_HEIGHT_PX = 56;
export const MAX_NEGATIVE_PROMPT_HEIGHT_PX = 240;
export const DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX = 56;
@@ -895,15 +930,7 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n
MAX_HIDIFFUSION_RATIO,
DEFAULT_HIDIFFUSION_T2_RATIO
),
- dynamicPromptsCombinatorial:
- typeof values.dynamicPromptsCombinatorial === 'boolean' ? values.dynamicPromptsCombinatorial : true,
- dynamicPromptsEnabled: values.dynamicPromptsEnabled !== false,
- dynamicPromptsMaxPrompts: sanitizeMaxPrompts(values.dynamicPromptsMaxPrompts),
- dynamicPromptsSampleSeed: sanitizeSampleSeed(values.dynamicPromptsSampleSeed),
- dynamicPromptsResample: typeof values.dynamicPromptsResample === 'boolean' ? values.dynamicPromptsResample : true,
- dynamicPromptsSeedBehaviour: isDynamicPromptsSeedBehaviour(values.dynamicPromptsSeedBehaviour)
- ? values.dynamicPromptsSeedBehaviour
- : 'per-iteration',
+ ...normalizeDynamicPromptsSettings(values),
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.ts
index 46a8829073..ba0ee1eb69 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts
@@ -360,6 +360,17 @@ export interface GenerateSettings {
refinerStart: number;
}
+/** The dynamic prompts fields every surface whose prompt expands persists (Generate, Video). */
+export type DynamicPromptsSettings = Pick<
+ GenerateSettings,
+ | 'dynamicPromptsCombinatorial'
+ | 'dynamicPromptsEnabled'
+ | 'dynamicPromptsMaxPrompts'
+ | 'dynamicPromptsResample'
+ | 'dynamicPromptsSampleSeed'
+ | 'dynamicPromptsSeedBehaviour'
+>;
+
export type OpenAIImageQuality = 'auto' | 'high' | 'medium' | 'low';
export type OpenAIImageBackground = 'auto' | 'transparent' | 'opaque';
export type OpenAIInputFidelity = 'low' | 'high';
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 283dc4eb05..c27ae156fd 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -11,6 +11,8 @@ export {
deriveAspectRatioId,
GENERATE_UI_STATE_KEYS,
getDefaultLoraWeight,
+ getDynamicPromptsConfig,
+ getDynamicPromptsSettingsPatch,
getGenerateValuesRevertPatch,
getModelDefaultVae,
hasModelDefaultVae,
@@ -38,6 +40,7 @@ export {
MIN_POSITIVE_PROMPT_HEIGHT_PX,
MIN_TIMESTEP_SHIFT,
MIN_ZIMAGE_SEED_VARIANCE_RANDOMIZE_PERCENT,
+ normalizeDynamicPromptsSettings,
normalizeGenerateSettings,
normalizeMossImageSkipLayers,
normalizeGenerateWidgetValues,
@@ -134,6 +137,7 @@ export {
} from './core/sdxlRefiner';
export {
createDynamicPromptsSampleSeed,
+ DEFAULT_DYNAMIC_PROMPTS_SETTINGS,
describeDynamicPromptsFailure,
DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,
DYNAMIC_PROMPTS_MAX_PROMPTS,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
index 7cdf3ccd7a..ac6f6d8538 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
@@ -8,6 +8,7 @@ import { Stack } from '@chakra-ui/react';
import { getImageExpandPromptSuggestion, getPromptPolicy } from '@features/generation/core/baseGenerationPolicies';
import { sanitizeBatchCount } from '@features/generation/core/batch';
import { flattenPromptTemplateExpansion } from '@features/generation/core/promptTemplates';
+import { getDynamicPromptsSettingsPatch } from '@features/generation/core/settings';
import { type GenerateDraft, pickGenerateSettings } from '@features/generation/ui/generateDebounce';
import { flushGenerateDrafts } from '@features/generation/ui/generateDraftRegistry';
import { offerGenerateUndo } from '@features/generation/ui/generateUndo';
@@ -35,18 +36,6 @@ interface GeneratePromptValues {
positivePromptHeightPx: number;
}
-/** The flat GenerateSettings field behind each dynamic prompts config key. */
-const DYNAMIC_PROMPT_SETTING_KEYS = {
- combinatorial: 'dynamicPromptsCombinatorial',
- enabled: 'dynamicPromptsEnabled',
- maxPrompts: 'dynamicPromptsMaxPrompts',
- resample: 'dynamicPromptsResample',
- sampleSeed: 'dynamicPromptsSampleSeed',
- seedBehaviour: 'dynamicPromptsSeedBehaviour',
-} as const satisfies Record<keyof DynamicPromptsConfig, keyof GenerateSettings>;
-
-type DynamicPromptsConfigKey = keyof typeof DYNAMIC_PROMPT_SETTING_KEYS;
-
const getPromptValues = (values: Record<string, unknown>): GeneratePromptValues => ({
negativePrompt: typeof values.negativePrompt === 'string' ? values.negativePrompt : '',
negativePromptEnabled: values.negativePromptEnabled !== false,
@@ -194,15 +183,7 @@ export const GeneratePromptFields = ({
);
const handleDynamicPromptsChange = useCallback(
- (patch: Partial<DynamicPromptsConfig>) =>
- onCommitImmediate(
- Object.fromEntries(
- Object.entries(patch).map(([key, value]) => [
- DYNAMIC_PROMPT_SETTING_KEYS[key as DynamicPromptsConfigKey],
- value,
- ])
- )
- ),
+ (patch: Partial<DynamicPromptsConfig>) => onCommitImmediate(getDynamicPromptsSettingsPatch(patch)),
[onCommitImmediate]
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
index 45717a36d4..d4f7b30826 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -25,7 +25,12 @@ import {
type PromptTemplateState,
type SavedPromptModels,
} from './PositivePromptActions';
-import { editTextareaText, insertPromptText, registerPositivePromptElement } from './promptFocus';
+import {
+ editTextareaText,
+ insertPromptText,
+ type PositivePromptOwner,
+ registerPositivePromptElement,
+} from './promptFocus';
import { promptHistoryNavigation } from './promptHistoryNavigation';
import { PromptTextarea } from './PromptTextarea';
import { usePromptImageDrop } from './usePromptImageDrop';
@@ -40,6 +45,8 @@ interface PositivePromptFieldProps {
dynamicPrompts?: DynamicPromptsFieldConfig | null;
/** Absent on surfaces whose model family has no prompt enhancer of its own. */
expandPromptSuggestion?: ExpandPromptSuggestion | null;
+ /** Whose prompt focus requests reach this field; Upscale shares Generate's. */
+ focusOwner?: PositivePromptOwner;
/** Absent on surfaces with no template concept (Upscale). */
promptTemplate?: PromptTemplateSnapshot | null;
/** Show the merged prompt read-only instead of the authored text. */
@@ -69,6 +76,7 @@ export const PositivePromptField = ({
batchCount = 1,
dynamicPrompts = null,
expandPromptSuggestion = null,
+ focusOwner = 'generate',
heightPx,
isTemplateViewMode = false,
loras,
@@ -191,10 +199,13 @@ export const PositivePromptField = ({
[flushDraftValue, onUsePrompt, writePrompt]
);
- const handleTextareaRef = useCallback((element: HTMLTextAreaElement | null) => {
- textareaRef.current = element;
- registerPositivePromptElement(element);
- }, []);
+ const handleTextareaRef = useCallback(
+ (element: HTMLTextAreaElement | null) => {
+ registerPositivePromptElement(focusOwner, element, textareaRef.current);
+ textareaRef.current = element;
+ },
+ [focusOwner]
+ );
const insertTextAtCaret = useCallback(
(text: string) => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
index 3d96e39dd7..3514b4524a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
@@ -1,26 +1,43 @@
import { MAX_WILDCARD_NAME_LENGTH } from '@features/generation/core/dynamicPrompts';
-let positivePromptElement: HTMLTextAreaElement | null = null;
+/** Which surface's positive prompt: Generate (shared with Upscale) and Video are mounted side by side. */
+export type PositivePromptOwner = 'generate' | 'video';
+
+const positivePromptElements = new Map<PositivePromptOwner, HTMLTextAreaElement>();
export type PromptTextRange = { end: number; start: number };
-export const registerPositivePromptElement = (element: HTMLTextAreaElement | null): void => {
- positivePromptElement = element;
+/** `previous` is the field's own element, so one field unmounting never unregisters another's. */
+export const registerPositivePromptElement = (
+ owner: PositivePromptOwner,
+ element: HTMLTextAreaElement | null,
+ previous: HTMLTextAreaElement | null
+): void => {
+ if (element) {
+ positivePromptElements.set(owner, element);
+ } else if (positivePromptElements.get(owner) === previous) {
+ positivePromptElements.delete(owner);
+ }
};
-export const focusPositivePrompt = (): boolean => {
- if (!positivePromptElement) {
+export const focusPositivePrompt = (owner: PositivePromptOwner = 'generate'): boolean => {
+ const element = positivePromptElements.get(owner);
+
+ if (!element) {
return false;
}
- positivePromptElement.focus();
- positivePromptElement.select();
+ element.focus();
+ element.select();
return true;
};
-export const isPositivePromptFocused = (): boolean =>
- positivePromptElement !== null && document.activeElement === positivePromptElement;
+export const isPositivePromptFocused = (owner: PositivePromptOwner = 'generate'): boolean => {
+ const element = positivePromptElements.get(owner);
+
+ return element !== undefined && document.activeElement === element;
+};
const clamp = (value: number, min: number, max: number): number => Math.min(Math.max(value, min), max);
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
index 538c5d550e..df0db05e6a 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
@@ -130,6 +130,34 @@ describe('normalizeVideoSettings', () => {
expect(isVideoSettings(legacy)).toBe(false);
});
+ it("reads dynamic prompt settings saved before Video had them as off, with Video's prompt cap", () => {
+ const legacy: Record<string, unknown> = { ...createSettings() };
+
+ for (const key of Object.keys(legacy).filter((name) => name.startsWith('dynamicPrompts'))) {
+ delete legacy[key];
+ }
+
+ expect(normalizeVideoSettings(legacy)).toMatchObject({
+ dynamicPromptsCombinatorial: true,
+ dynamicPromptsEnabled: false,
+ dynamicPromptsMaxPrompts: 10,
+ dynamicPromptsResample: true,
+ dynamicPromptsSampleSeed: 0,
+ dynamicPromptsSeedBehaviour: 'per-iteration',
+ });
+ expect(isVideoSettings(legacy)).toBe(false);
+ });
+
+ it('starts a new Video panel, seeded or not yet, with dynamic prompts on and capped at 10', () => {
+ const newPanel = { dynamicPromptsEnabled: true, dynamicPromptsMaxPrompts: 10 };
+
+ expect(getDefaultVideoSettings()).toMatchObject(newPanel);
+ expect(normalizeVideoSettings({})).toMatchObject(newPanel);
+ expect(normalizeVideoSettings({ firstFrameImage: FIRST_FRAME, positivePrompt: 'a {red|green} fox' })).toMatchObject(
+ newPanel
+ );
+ });
+
it('round-trips canonical settings', () => {
const settings = createSettings({ firstFrameImage: FIRST_FRAME, positivePrompt: 'a cat' });
const normalized = normalizeVideoSettings(settings);
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
index 049da771eb..a454c52666 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -1,6 +1,7 @@
-import type { GenerateLora, ImageWithDims } from '@features/generation/contracts';
+import type { DynamicPromptsSettings, GenerateLora, ImageWithDims } from '@features/generation/contracts';
import {
+ DEFAULT_DYNAMIC_PROMPTS_SETTINGS,
DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,
DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,
isLoraModelConfig,
@@ -11,6 +12,7 @@ import {
MAX_POSITIVE_PROMPT_HEIGHT_PX,
MIN_NEGATIVE_PROMPT_HEIGHT_PX,
MIN_POSITIVE_PROMPT_HEIGHT_PX,
+ normalizeDynamicPromptsSettings,
sanitizeBatchCount,
} from '@features/generation/settings';
import { isSeedMode } from '@platform/core/seed';
@@ -303,6 +305,22 @@ export const resolveVideoMode = (
return settings.lastFrameImage ? 'last-frame' : 'txt2vid';
};
+/** Each video costs far more than an image, so a new Video panel expands to fewer prompts than Generate. */
+export const VIDEO_DYNAMIC_PROMPTS_DEFAULTS: Readonly<DynamicPromptsSettings> = {
+ ...DEFAULT_DYNAMIC_PROMPTS_SETTINGS,
+ dynamicPromptsMaxPrompts: 10,
+};
+
+/**
+ * A panel saved before Video expanded prompts keeps running its prompt as typed until the user turns expansion on.
+ * Every seeded panel stores `positivePromptHeightPx`; an unseeded record (a new panel, a partial Send to Video
+ * payload) lacks it and takes the new-panel defaults.
+ */
+const SAVED_VIDEO_DYNAMIC_PROMPTS_DEFAULTS: Readonly<DynamicPromptsSettings> = {
+ ...VIDEO_DYNAMIC_PROMPTS_DEFAULTS,
+ dynamicPromptsEnabled: false,
+};
+
/** Panel arrangement fields are UI state rather than generation parameters. */
export const VIDEO_UI_STATE_KEYS = {
batchCount: true,
@@ -431,6 +449,12 @@ export const normalizeVideoSettings = (values: unknown): VideoSettings | null =>
? 'fixed'
: 'random',
conditioningClip,
+ ...normalizeDynamicPromptsSettings(
+ values,
+ hasFiniteNumber(values, 'positivePromptHeightPx')
+ ? SAVED_VIDEO_DYNAMIC_PROMPTS_DEFAULTS
+ : VIDEO_DYNAMIC_PROMPTS_DEFAULTS
+ ),
sourceVideo,
steps: hasFiniteNumber(values, 'steps') ? (values.steps as number) : SETTINGS_FALLBACKS.steps,
targetResolution: isVideoTargetResolution(values.targetResolution)
@@ -493,7 +517,13 @@ export const isVideoSettings = (values: unknown): values is VideoSettings => {
(values.ltx2DurationHeadModel === null || isModelIdentifierConfig(values.ltx2DurationHeadModel)) &&
// Same invariant normalize enforces: there is no auto duration without a head to decide it.
(values.autoDuration === false || (values.autoDuration === true && values.ltx2DurationHeadModel !== null)) &&
- hasFiniteNumber(values, 'h3HybridStartBlock')
+ hasFiniteNumber(values, 'h3HybridStartBlock') &&
+ typeof values.dynamicPromptsCombinatorial === 'boolean' &&
+ typeof values.dynamicPromptsEnabled === 'boolean' &&
+ typeof values.dynamicPromptsResample === 'boolean' &&
+ values.dynamicPromptsMaxPrompts === normalized.dynamicPromptsMaxPrompts &&
+ values.dynamicPromptsSampleSeed === normalized.dynamicPromptsSampleSeed &&
+ values.dynamicPromptsSeedBehaviour === normalized.dynamicPromptsSeedBehaviour
);
};
diff --git a/invokeai/frontend/webv2/src/features/video/core/types.ts b/invokeai/frontend/webv2/src/features/video/core/types.ts
index 51b32d20d7..6a549e6ed4 100644
--- a/invokeai/frontend/webv2/src/features/video/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/types.ts
@@ -1,4 +1,5 @@
import type {
+ DynamicPromptsSettings,
GenerateLora,
ImageWithDims,
MainModelConfig,
@@ -88,8 +89,8 @@ export type VideoTargetResolution = WanTargetResolution | MiniMaxH3TargetResolut
/** Derive dimensions from preset ratio/resolution or conditioning media; no free-size fields are offered. */
export type VideoAspectRatioId = '21:9' | '16:9' | '3:2' | '4:3' | '1:1' | '3:4' | '2:3' | '9:16' | '9:21';
-/** Project-persisted settings owned by the Video widget. */
-export interface VideoSettings {
+/** Project-persisted settings owned by the Video widget; the prompt expands like Generate's. */
+export interface VideoSettings extends DynamicPromptsSettings {
batchCount: number;
modelKey: string;
positivePrompt: string;
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
index e576208dc5..3d19dc2920 100644
--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
@@ -73,6 +73,7 @@ import {
MINIMAX_H3_HYBRID_BLOCK_RANGE,
resolveVideoMode,
VIDEO_ASPECT_RATIO_IDS,
+ VIDEO_DYNAMIC_PROMPTS_DEFAULTS,
} from './settings';
// Wan variants differ in conditioning, pixel grid, and experts; key capabilities by base and variant.
@@ -1824,6 +1825,7 @@ export const getDefaultVideoSettings = (
cfgScale: config.defaults.cfgScale,
cfgScaleLowNoise: config.defaults.cfgScaleLowNoise,
conditioningClip: null,
+ ...VIDEO_DYNAMIC_PROMPTS_DEFAULTS,
audioCfgScale: config.defaults.audioCfgScale,
// Seed a component source from the catalog so a single-file main starts invokable; reset reuses defaults.
componentSourceModel:
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx
index df57c84d0b..00e0465a9e 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx
@@ -4,13 +4,15 @@ import type {
MainModelConfig,
PromptHistoryItem,
} from '@features/generation/contracts';
+import type { DynamicPromptsConfig } from '@features/generation/settings';
import type { VideoWidgetValues } from '@features/video/core/types';
import { Stack } from '@chakra-ui/react';
import { NegativePromptField, PositivePromptField } from '@features/generation/components';
+import { getDynamicPromptsSettingsPatch } from '@features/generation/settings';
import { normalizeVideoWidgetValues } from '@features/video/core/settings';
import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { areVideoLorasEquivalent, areVideoModelsEquivalent } from './videoComparators';
@@ -35,7 +37,10 @@ const getRecallRevert = (before: VideoPrompts, written: VideoPrompts, current: V
*/
export const VideoPromptFields = memo(
function VideoPromptFields({
+ batchCount,
+ dynamicPrompts,
expandPromptSuggestion,
+ isSeedFixed,
loras,
model,
negativeHelpText,
@@ -49,7 +54,10 @@ export const VideoPromptFields = memo(
projectId,
showSyntaxHighlighting,
}: {
+ batchCount: number;
+ dynamicPrompts: DynamicPromptsConfig;
expandPromptSuggestion: ExpandPromptSuggestion | null;
+ isSeedFixed: boolean;
loras: GenerateLora[];
model: MainModelConfig | null;
negativeHelpText?: string;
@@ -141,6 +149,14 @@ export const VideoPromptFields = memo(
(positivePromptHeight: number) => onPatchValues({ positivePromptHeightPx: positivePromptHeight }),
[onPatchValues]
);
+ const handleDynamicPromptsChange = useCallback(
+ (patch: Partial<DynamicPromptsConfig>) => onPatchValues(getDynamicPromptsSettingsPatch(patch)),
+ [onPatchValues]
+ );
+ const dynamicPromptsField = useMemo(
+ () => ({ ...dynamicPrompts, isSeedFixed, onChange: handleDynamicPromptsChange }),
+ [dynamicPrompts, handleDynamicPromptsChange, isSeedFixed]
+ );
const handleNegativeResizeEnd = useCallback(
(negativePromptHeight: number) => onPatchValues({ negativePromptHeightPx: negativePromptHeight }),
[onPatchValues]
@@ -149,7 +165,10 @@ export const VideoPromptFields = memo(
return (
<Stack gap="2" p="2">
<PositivePromptField
+ batchCount={batchCount}
+ dynamicPrompts={dynamicPromptsField}
expandPromptSuggestion={expandPromptSuggestion}
+ focusOwner="video"
heightPx={positivePromptHeightPx}
loras={loras}
projectId={projectId}
@@ -179,7 +198,10 @@ export const VideoPromptFields = memo(
);
},
(previous, next) =>
+ previous.batchCount === next.batchCount &&
+ previous.dynamicPrompts === next.dynamicPrompts &&
previous.expandPromptSuggestion === next.expandPromptSuggestion &&
+ previous.isSeedFixed === next.isSeedFixed &&
previous.negativePrompt === next.negativePrompt &&
previous.negativePromptEnabled === next.negativePromptEnabled &&
previous.negativePromptHeightPx === next.negativePromptHeightPx &&
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
index 4cc76f31bd..6c7a60103e 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
@@ -7,7 +7,11 @@ import type {
import { createListCollection, HStack, Stack, Switch, Text } from '@chakra-ui/react';
import { GenerationSettingsSection, SeedField } from '@features/generation/components';
-import { sanitizeBatchCount } from '@features/generation/settings';
+import {
+ getDynamicPromptsConfig,
+ normalizeDynamicPromptsSettings,
+ sanitizeBatchCount,
+} from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import {
getVideoDurationSeconds,
@@ -107,6 +111,11 @@ const VideoModelReconciler = ({
const normalized = normalizeVideoWidgetValues(rawValues);
if (normalized && areVideoValuesEqual(normalized, values)) {
+ // Pin whether this panel expands prompts while the record still says which kind it is: a later partial edit
+ // (a prompt resize) would make an unseeded panel read as one saved before Video expanded prompts.
+ if (typeof rawValues.dynamicPromptsEnabled !== 'boolean') {
+ patchValues(normalizeDynamicPromptsSettings(values), 'system');
+ }
return;
}
@@ -434,6 +443,34 @@ export const VideoWidgetView = () => {
() => getVideoExpandPromptSuggestion(promptEnhancer, firstFrameImage),
[promptEnhancer, firstFrameImage]
);
+ const {
+ dynamicPromptsCombinatorial,
+ dynamicPromptsEnabled,
+ dynamicPromptsMaxPrompts,
+ dynamicPromptsResample,
+ dynamicPromptsSampleSeed,
+ dynamicPromptsSeedBehaviour,
+ } = values;
+ // Memoized on its fields for the same check: patches recreate `values`.
+ const dynamicPrompts = useMemo(
+ () =>
+ getDynamicPromptsConfig({
+ dynamicPromptsCombinatorial,
+ dynamicPromptsEnabled,
+ dynamicPromptsMaxPrompts,
+ dynamicPromptsResample,
+ dynamicPromptsSampleSeed,
+ dynamicPromptsSeedBehaviour,
+ }),
+ [
+ dynamicPromptsCombinatorial,
+ dynamicPromptsEnabled,
+ dynamicPromptsMaxPrompts,
+ dynamicPromptsResample,
+ dynamicPromptsSampleSeed,
+ dynamicPromptsSeedBehaviour,
+ ]
+ );
const supportsExtend = policy.modes.includes('extend');
const supportsReferences = policy.modes.includes('reference');
const supportsConditioningClip = policy.modes.includes('audio-to-video') || policy.modes.includes('video-to-audio');
@@ -502,7 +539,10 @@ export const VideoWidgetView = () => {
</Stack>
<VideoPromptFields
+ batchCount={values.batchCount}
+ dynamicPrompts={dynamicPrompts}
expandPromptSuggestion={expandPromptSuggestion}
+ isSeedFixed={values.seedMode === 'fixed'}
loras={values.loras}
model={values.model}
negativeHelpText={policy.prompt.negativeHelpTextKey ? t(policy.prompt.negativeHelpTextKey) : undefined}
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.ts b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.ts
index 7e588f4fba..cbd88e918e 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.test.ts
@@ -35,4 +35,19 @@ describe('areVideoValuesEqual', () => {
expect(areVideoValuesEqual(values, { ...values, ltx2DurationHeadModel: head })).toBe(false);
expect(areVideoValuesEqual(values, { ...values, autoDuration: !values.autoDuration })).toBe(false);
});
+
+ it('treats every dynamic prompts setting as part of the values', () => {
+ const edits: Partial<typeof values>[] = [
+ { dynamicPromptsCombinatorial: !values.dynamicPromptsCombinatorial },
+ { dynamicPromptsEnabled: !values.dynamicPromptsEnabled },
+ { dynamicPromptsMaxPrompts: values.dynamicPromptsMaxPrompts + 1 },
+ { dynamicPromptsResample: !values.dynamicPromptsResample },
+ { dynamicPromptsSampleSeed: values.dynamicPromptsSampleSeed + 1 },
+ { dynamicPromptsSeedBehaviour: 'per-image' },
+ ];
+
+ for (const edit of edits) {
+ expect(areVideoValuesEqual(values, { ...values, ...edit })).toBe(false);
+ }
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.ts b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.ts
index 58ba2e34fd..348207088d 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/videoComparators.ts
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoComparators.ts
@@ -32,6 +32,12 @@ export const areVideoValuesEqual = (left: VideoWidgetValues, right: VideoWidgetV
left.negativePrompt === right.negativePrompt &&
left.negativePromptEnabled === right.negativePromptEnabled &&
left.positivePromptHeightPx === right.positivePromptHeightPx &&
+ left.dynamicPromptsCombinatorial === right.dynamicPromptsCombinatorial &&
+ left.dynamicPromptsEnabled === right.dynamicPromptsEnabled &&
+ left.dynamicPromptsMaxPrompts === right.dynamicPromptsMaxPrompts &&
+ left.dynamicPromptsResample === right.dynamicPromptsResample &&
+ left.dynamicPromptsSampleSeed === right.dynamicPromptsSampleSeed &&
+ left.dynamicPromptsSeedBehaviour === right.dynamicPromptsSeedBehaviour &&
left.negativePromptHeightPx === right.negativePromptHeightPx &&
left.aspectRatioId === right.aspectRatioId &&
left.targetResolution === right.targetResolution &&
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoPromptDynamicPrompts.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoPromptDynamicPrompts.browser.test.tsx
new file mode 100644
index 0000000000..9b97b3008c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoPromptDynamicPrompts.browser.test.tsx
@@ -0,0 +1,122 @@
+import type { DynamicPromptsConfig } from '@features/generation/settings';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { VideoPromptFields } from './VideoFormFields';
+import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';
+
+const i18n = i18next.createInstance();
+
+await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation: {} } } });
+
+const parseDynamicPrompts = vi.hoisted(() => vi.fn());
+
+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useGenerationUi: () => ({
+ capabilities: { canManagePromptTemplates: false, canManageSharedSystemPrompts: false },
+ gallery: { selectedImage: null },
+ models: { catalog: [], ensureLoaded: vi.fn() },
+ notifications: { reportError: vi.fn(), undoable: vi.fn() },
+ project: { activeProjectId: 'project-1' },
+ promptHistory: { clear: vi.fn(), items: [], remove: vi.fn(), restore: vi.fn() },
+ }),
+}));
+vi.mock('@features/generation/data/promptUtilities', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ parseDynamicPrompts,
+}));
+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),
+}));
+
+const adapter = {
+ getUploadBoardId: () => Promise.resolve('none'),
+ notifications: { info: () => undefined, undoable: () => undefined },
+ patchValues: vi.fn(),
+ readValues: () => ({}),
+} as unknown as VideoUiAdapter;
+
+const NO_LORAS: [] = [];
+const DYNAMIC_PROMPTS: DynamicPromptsConfig = {
+ combinatorial: true,
+ enabled: true,
+ maxPrompts: 10,
+ resample: true,
+ sampleSeed: 0,
+ seedBehaviour: 'per-iteration',
+};
+
+let host: HTMLDivElement;
+let root: Root;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ parseDynamicPrompts.mockReset();
+ parseDynamicPrompts.mockResolvedValue({ error: null, prompts: ['wall painted'] });
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+describe('Video prompt dynamic prompts', () => {
+ it('stores turning dynamic prompts off as the Video setting', async () => {
+ const onPatchValues = vi.fn();
+
+ await act(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <QueryClientProvider client={new QueryClient()}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <VideoUiProvider adapter={adapter}>
+ <VideoPromptFields
+ batchCount={1}
+ dynamicPrompts={DYNAMIC_PROMPTS}
+ expandPromptSuggestion={null}
+ isSeedFixed={false}
+ loras={NO_LORAS}
+ model={null}
+ negativePrompt=""
+ negativePromptEnabled
+ negativePromptHeightPx={56}
+ negativeVisible={false}
+ positivePrompt="wall painted #ff0000"
+ positivePromptHeightPx={96}
+ projectId="project-1"
+ showSyntaxHighlighting={false}
+ onPatchValues={onPatchValues}
+ />
+ </VideoUiProvider>
+ </DndContext>
+ </ChakraProvider>
+ </QueryClientProvider>
+ </I18nextProvider>
+ )
+ );
+
+ // The notice under the prompt offers the switch, as the panel's does; both write through the same handler.
+ const turnOff = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
+ (button) => button.textContent === 'widgets.generate.dynamicPrompts.turnOff'
+ );
+
+ expect(turnOff).toBeDefined();
+ await act(() => turnOff!.click());
+
+ expect(onPatchValues).toHaveBeenCalledWith({ dynamicPromptsEnabled: false });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index ded76cc972..04aeaec296 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -2,6 +2,7 @@ import type { ModelConfig } from '@features/models';
import type { ProjectGraphState } from '@features/workflow/contracts';
import type { CanvasLayerContract, CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engine/api';
import type {
+ DynamicPromptsExpansionSource,
InvocationMode,
InvocationRoute,
InvocationValidationReason,
@@ -17,12 +18,14 @@ import { getLayoutDraftRejectionReason, getLayoutPromptRejectionReason } from '@
import {
describeExternalCanvasRefusal,
describeGenerationIssue,
+ expandsDynamicPrompts,
getEffectivePrompts,
getGenerateInvocationIssues,
isExternalTextOnlyCanvasModel,
isGenerateModelConfig,
isSupportedGenerateModel,
NO_GENERATE_MODEL_ISSUE,
+ normalizeGenerateSettings,
normalizeGenerateWidgetValues,
sanitizeBatchCount,
} from '@features/generation/settings';
@@ -50,6 +53,52 @@ import { getActiveProjectGraph } from './projectWorkflows';
import { getWorkbenchPreferences } from './settings/store';
import { getProjectWidgetValues } from './widgetState';
+/**
+ * What the route's positive prompt expands from, with the sample seed to draw with, or null when the route sends its
+ * prompt as typed: Upscale and workflows never expand, and dynamic prompts may be off or the prompt plain. Canvas
+ * expands Generate's prompt.
+ */
+export const getDynamicPromptsExpansionSource = (
+ project: Project,
+ sourceId: InvocationSourceId
+): (DynamicPromptsExpansionSource & { sampleSeed: number }) | null => {
+ if (sourceId === 'upscale' || sourceId === 'workflow') {
+ return null;
+ }
+
+ const settings =
+ sourceId === 'video'
+ ? normalizeVideoWidgetValues(getProjectWidgetValues(project, 'video'))
+ : normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));
+
+ if (!settings) {
+ return null;
+ }
+
+ const positivePrompt =
+ 'promptTemplate' in settings ? getEffectivePrompts(settings).positivePrompt : settings.positivePrompt;
+
+ return expandsDynamicPrompts(positivePrompt, settings.dynamicPromptsEnabled)
+ ? {
+ combinatorial: settings.dynamicPromptsCombinatorial,
+ maxPrompts: settings.dynamicPromptsMaxPrompts,
+ positivePrompt,
+ sampleSeed: settings.dynamicPromptsSampleSeed,
+ }
+ : null;
+};
+
+/** Whether a submission prepared from `prepared` (null: not expanded) still describes what `current` compiles. */
+export const isSameDynamicPromptsExpansionSource = (
+ prepared: DynamicPromptsExpansionSource | null,
+ current: DynamicPromptsExpansionSource | null
+): boolean =>
+ prepared === null || current === null
+ ? prepared === current
+ : prepared.positivePrompt === current.positivePrompt &&
+ prepared.combinatorial === current.combinatorial &&
+ prepared.maxPrompts === current.maxPrompts;
+
export interface InvocationSourceMeta {
id: InvocationSourceId;
label: string;
diff --git a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
index 5ee3fee581..cf6403b269 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
@@ -8,8 +8,18 @@ export type InvocationMode = 'global' | 'dialog';
export type ResultDestination = 'canvas' | 'gallery';
+/** The prompt and settings an expansion was computed from. The sample seed travels on its own: it may rotate. */
+export interface DynamicPromptsExpansionSource {
+ combinatorial: boolean;
+ maxPrompts: number;
+ /** The effective (template-merged) positive prompt. */
+ positivePrompt: string;
+}
+
/** A dynamic prompt expansion, with the sample seed it drew from (null for All combinations). */
export interface ExpandedPositivePrompts {
+ /** A submission whose source no longer matches what it compiles is refused rather than queued. */
+ expandedFrom: DynamicPromptsExpansionSource;
positivePrompts: string[];
/** Recall reproduces this draw, and a resampling submission rotates only while the project still holds it. */
positivePromptsSampleSeed: number | null;
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
index 4e048c5f86..d6b04d01a8 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
@@ -37,6 +37,17 @@ vi.mock('@features/gallery/queries', async (importOriginal) => ({
ensureGalleryBoardDestinations: galleryQueriesMock.ensureGalleryBoardDestinations,
}));
+// Holds an expansion open so a test can edit the project while it is pending; otherwise the real resolver runs.
+const expansionMock = vi.hoisted(() => ({ pending: null as Promise<unknown> | null }));
+vi.mock('@features/generation/prompts', async (importOriginal) => {
+ const original = await importOriginal<{ resolveDynamicPrompts: (...args: unknown[]) => Promise<unknown> }>();
+
+ return {
+ ...original,
+ resolveDynamicPrompts: (...args: unknown[]) => expansionMock.pending ?? original.resolveDynamicPrompts(...args),
+ };
+});
+
vi.mock('@features/workflow/react', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getInvocationTemplatesSnapshot: () => templatesMock.snapshot,
@@ -393,7 +404,11 @@ describe('submitResolvedInvocation with a random dynamic prompt', () => {
// Seed capabilities to match app boot; submission fails closed without them.
seedArchitectureCapabilities();
- const drawn = { positivePrompts: ['a green cat'], positivePromptsSampleSeed: 7 };
+ const drawn = {
+ expandedFrom: { combinatorial: false, maxPrompts: 4, positivePrompt: 'a {red|green} cat' },
+ positivePrompts: ['a green cat'],
+ positivePromptsSampleSeed: 7,
+ };
const submitDrawn = async (sourceId: 'canvas' | 'generate', prepend?: boolean) => {
const model: MainModelConfig = { base: 'sd-1', key: 'main', name: 'Main', type: 'main' };
@@ -562,6 +577,186 @@ describe('submitResolvedInvocation without dynamic prompts', () => {
});
});
+describe('submitResolvedInvocation for Video', () => {
+ const wanModel = {
+ base: 'wan',
+ file_size: 1,
+ format: 'diffusers',
+ hash: 'wan-t2v-hash',
+ key: 'wan-t2v_a14b-diffusers',
+ name: 'Wan 2.2 t2v_a14b',
+ path: 'wan-t2v_a14b-diffusers',
+ source: 'wan-t2v_a14b-diffusers',
+ source_type: 'path',
+ type: 'main',
+ variant: 't2v_a14b',
+ } as const;
+
+ const submitVideo = async (dynamicPromptsEnabled: boolean) => {
+ let state = workbenchReducer(createInitialWorkbenchState(), {
+ region: 'left',
+ type: 'toggleRegionWidget',
+ widgetId: 'video',
+ });
+ state = workbenchReducer(state, {
+ type: 'patchWidgetValues',
+ values: { dynamicPromptsEnabled, model: wanModel, positivePrompt: 'a {red|green} fox' },
+ widgetId: 'video',
+ });
+ const project = getActiveProject(state);
+ // Infinite staleTime makes the cached expansion authoritative, so no request leaves the test.
+ queryClient.setQueryData(
+ dynamicPromptsKeys.expansion({ combinatorial: true, max_prompts: 10, prompt: 'a {red|green} fox', seed: null }),
+ { error: null, prompts: ['a red fox', 'a green fox'] }
+ );
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+
+ await submitResolvedInvocation({
+ commands,
+ formatControlLayerError,
+ formatUpscaleMetadataFailure,
+ scopedDefaults: {},
+ models: [wanModel],
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route: resolveInvocationRoute(
+ project,
+ 'global',
+ { destination: 'gallery', destinationLocked: false, sourceId: 'video', sourceLocked: false },
+ [wanModel]
+ ),
+ });
+
+ return submitResolved;
+ };
+
+ it('expands a dynamic prompt into one video per prompt', async () => {
+ const submitResolved = await submitVideo(true);
+
+ expect(submitResolved).toHaveBeenCalledTimes(1);
+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({
+ positivePrompts: ['a red fox', 'a green fox'],
+ positivePromptsSampleSeed: null,
+ });
+ });
+
+ it('dispatches the prompt as typed with dynamic prompts off', async () => {
+ const submitResolved = await submitVideo(false);
+
+ expect(submitResolved).toHaveBeenCalledTimes(1);
+ expect(submitResolved.mock.calls[0]?.[0]).not.toHaveProperty('positivePrompts');
+ });
+});
+
+describe('submitResolvedInvocation when the prompt changes while it expands', () => {
+ seedArchitectureCapabilities();
+
+ const wanModel = {
+ base: 'wan',
+ file_size: 1,
+ format: 'diffusers',
+ hash: 'wan-t2v-hash',
+ key: 'wan-t2v_a14b-diffusers',
+ name: 'Wan 2.2 t2v_a14b',
+ path: 'wan-t2v_a14b-diffusers',
+ source: 'wan-t2v_a14b-diffusers',
+ source_type: 'path',
+ type: 'main',
+ variant: 't2v_a14b',
+ } as const;
+ const sdModel: MainModelConfig = { base: 'sd-1', key: 'main', name: 'Main', type: 'main' };
+
+ const primeVideo = () => {
+ const state = workbenchReducer(createInitialWorkbenchState(), {
+ region: 'left',
+ type: 'toggleRegionWidget',
+ widgetId: 'video',
+ });
+
+ return workbenchReducer(state, {
+ type: 'patchWidgetValues',
+ values: { model: wanModel, positivePrompt: 'a {red|green} fox' },
+ widgetId: 'video',
+ });
+ };
+ const primeGenerate = () =>
+ workbenchReducer(createInitialWorkbenchState(), {
+ type: 'setGenerateSettings',
+ values: {
+ ...getDefaultGenerateSettings(sdModel),
+ model: sdModel,
+ modelKey: sdModel.key,
+ positivePrompt: 'a {red|green} fox',
+ },
+ });
+
+ /** Invokes, makes `edit` while the expansion is still out, then lets the expansion answer. */
+ const submitWithEditDuringExpansion = async (
+ sourceId: 'generate' | 'video',
+ edit?: (store: ReturnType<typeof createWorkbenchStore>) => void
+ ) => {
+ const store = createWorkbenchStore(sourceId === 'video' ? primeVideo() : primeGenerate());
+ const project = store.getSnapshot().activeProject;
+ const models = sourceId === 'video' ? [wanModel] : undefined;
+ let answer: (response: unknown) => void = () => undefined;
+ expansionMock.pending = new Promise((resolve) => {
+ answer = resolve;
+ });
+
+ try {
+ const submission = submitResolvedInvocation({
+ commands: store.commands,
+ formatControlLayerError,
+ formatUpscaleMetadataFailure,
+ scopedDefaults: {},
+ models,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route: resolveInvocationRoute(
+ project,
+ 'global',
+ { destination: 'gallery', destinationLocked: false, sourceId, sourceLocked: false },
+ models
+ ),
+ });
+
+ edit?.(store);
+ answer({ error: null, prompts: ['a red fox', 'a green fox'] });
+ await submission;
+ } finally {
+ expansionMock.pending = null;
+ }
+
+ const snapshot = store.getSnapshot();
+
+ return {
+ notices: snapshot.notifications.map((notification) => notification.titleKey),
+ queue: snapshot.activeProject.queue.items,
+ };
+ };
+
+ it.each(['generate', 'video'] as const)('queues nothing from %s and says so', async (sourceId) => {
+ const { notices, queue } = await submitWithEditDuringExpansion(sourceId, (store) =>
+ sourceId === 'video'
+ ? store.commands.widgets.patchValues('video', { positivePrompt: 'a {blue|yellow} bird' })
+ : store.commands.widgets.patchValues('generate', { positivePrompt: 'a {blue|yellow} bird' })
+ );
+
+ expect(queue).toEqual([]);
+ expect(notices).toContain('topbar.invoke.expansionStale');
+ });
+
+ it.each(['generate', 'video'] as const)('queues %s as expanded when the prompt held still', async (sourceId) => {
+ const { notices, queue } = await submitWithEditDuringExpansion(sourceId);
+
+ expect(notices).not.toContain('topbar.invoke.expansionStale');
+ expect(queue[0]?.snapshot.backendSubmission).toMatchObject({ positivePrompts: ['a red fox', 'a green fox'] });
+ });
+});
+
describe("submitResolvedInvocation reads the user's defaults", () => {
seedArchitectureCapabilities();
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
index 3ba47480e8..e4dc4665fd 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
@@ -3,13 +3,13 @@
* sources through reducer submission. Inject Canvas preparation to keep this decision independent of the engine.
*/
-import type { GenerateSettings } from '@features/generation/contracts';
import type { ParseDynamicPromptsResponse } from '@features/generation/prompts';
import type { ModelConfig } from '@features/models';
import type { ProjectGraphState } from '@features/workflow/contracts';
import type { WorkflowGeneratorResolutions, WorkflowPendingGenerator } from '@features/workflow/utility';
import type { AccountScope } from '@platform/state/accountLifecycle';
import type {
+ DynamicPromptsExpansionSource,
ExpandedPositivePrompts,
ResolvedInvocationRoute,
UpscaleSourceMetadata,
@@ -19,12 +19,7 @@ import type { ScopedDefaults } from '@workbench/settings/contracts';
import { ensureGalleryBoardDestinations } from '@features/gallery/queries';
import { resolveDynamicPrompts } from '@features/generation/prompts';
-import {
- expandsDynamicPrompts,
- getEffectivePrompts,
- normalizeGenerateSettings,
- sanitizeBatchCount,
-} from '@features/generation/settings';
+import { sanitizeBatchCount } from '@features/generation/settings';
import { normalizeUpscaleWidgetValues } from '@features/upscale';
import { getWorkflowBatchCapReason } from '@features/workflow/graph';
import { getInvocationTemplatesSnapshot } from '@features/workflow/react';
@@ -36,6 +31,7 @@ import { getApiErrorMessage } from '@platform/transport/http';
import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';
import type { WorkbenchCommands } from './workbenchStore';
+import { getDynamicPromptsExpansionSource } from './invocation';
import { getActiveProjectWorkflow } from './projectWorkflows';
import { getEffectiveProjectSettings, PROJECT_SETTINGS_OWNER } from './settings/projectSettings';
import { readCanvasCompositingSettings } from './widgets/canvas/invoke/canvasCompositing';
@@ -112,41 +108,19 @@ export interface SubmitResolvedInvocationDeps {
formatUpscaleMetadataFailure: (imageName: string) => string;
}
-/**
- * Return merged Generate prompts only for routes that expand them: dynamic prompts on and dynamic syntax present.
- * Templates may introduce syntax and must consume their own placeholders before expansion.
- */
-const getExpandableSettings = (project: Project, route: ResolvedInvocationRoute): GenerateSettings | null => {
- if (route.sourceId === 'upscale' || route.sourceId === 'video' || route.sourceId === 'workflow') {
- return null;
- }
-
- const settings = normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));
-
- if (!settings) {
- return null;
- }
-
- const effectiveSettings = { ...settings, ...getEffectivePrompts(settings) };
-
- return expandsDynamicPrompts(effectiveSettings.positivePrompt, effectiveSettings.dynamicPromptsEnabled)
- ? effectiveSettings
- : null;
-};
-
/**
* Expand here to avoid a gallery → queue → generation cycle. Treat null or response.error as failure even if
* prompts are present.
*/
const resolveExpandedPrompts = async (
- settings: GenerateSettings,
+ source: DynamicPromptsExpansionSource,
sampleSeed: number | null
): Promise<ParseDynamicPromptsResponse | null> => {
try {
return await resolveDynamicPrompts(queryClient, {
- combinatorial: settings.dynamicPromptsCombinatorial,
- max_prompts: settings.dynamicPromptsMaxPrompts,
- prompt: settings.positivePrompt,
+ combinatorial: source.combinatorial,
+ max_prompts: source.maxPrompts,
+ prompt: source.positivePrompt,
seed: sampleSeed,
});
} catch {
@@ -288,14 +262,13 @@ export const submitResolvedInvocation = async ({
workflowGenerators = resolved;
}
- const expandableSettings = getExpandableSettings(project, route);
+ const expansionSource = getDynamicPromptsExpansionSource(project, route.sourceId);
// Only dynamic prompts require a round trip.
- if (expandableSettings) {
- const sampleSeed = expandableSettings.dynamicPromptsCombinatorial
- ? null
- : expandableSettings.dynamicPromptsSampleSeed;
- const expansion = await resolveExpandedPrompts(expandableSettings, sampleSeed);
+ if (expansionSource) {
+ const { sampleSeed: drawSeed, ...expandedFrom } = expansionSource;
+ const sampleSeed = expandedFrom.combinatorial ? null : drawSeed;
+ const expansion = await resolveExpandedPrompts(expandedFrom, sampleSeed);
if (!isAccountScopeCurrent(owner)) {
return;
}
@@ -326,9 +299,8 @@ export const submitResolvedInvocation = async ({
scopedDefaults,
workflowId,
},
- expansion.prompts.length > 0
- ? { positivePrompts: expansion.prompts, positivePromptsSampleSeed: sampleSeed }
- : undefined,
+ // Sent even when empty: the reducer checks the source against what it compiles either way.
+ { expandedFrom, positivePrompts: expansion.prompts, positivePromptsSampleSeed: sampleSeed },
workflowGenerators,
workflowDocument?.id,
pendingBoards,
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsx
index 94a60c9a0c..7616a1ab49 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsx
@@ -12,6 +12,7 @@ import {
} from '@features/generation/core/architectureCapabilities';
import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
import { getDefaultGenerateSettings } from '@features/generation/settings';
+import { registerPositivePromptElement } from '@features/generation/ui/promptFields/promptFocus';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { DEFAULT_PREFERENCES, getWorkbenchPreferences, patchWorkbenchPreferences } from '@workbench/settings/store';
import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';
@@ -229,7 +230,39 @@ describe('useInvokeIssueActions', () => {
await run({ message: 'Settings are incomplete.', target: { kind: 'widget', widgetId: 'video' } }, 'show');
expect(isPlaced('video')).toBe(true);
- await run({ message: 'The prompt could not be expanded.', target: { kind: 'prompt' } }, 'show');
+ await run(
+ { message: 'The prompt could not be expanded.', target: { kind: 'prompt', widgetId: 'generate' } },
+ 'show'
+ );
expect(isPlaced('generate')).toBe(true);
});
+
+ it("opens Video and focuses its own prompt, not Generate's, for a Video prompt that cannot expand", async () => {
+ const generatePrompt = document.createElement('textarea');
+ const videoPrompt = document.createElement('textarea');
+ document.body.append(generatePrompt, videoPrompt);
+ registerPositivePromptElement('generate', generatePrompt, null);
+ registerPositivePromptElement('video', videoPrompt, null);
+
+ try {
+ await run(
+ { message: 'The prompt could not be expanded.', target: { kind: 'prompt', widgetId: 'video' } },
+ 'show'
+ );
+ await act(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ })
+ );
+
+ expect(isPlaced('video')).toBe(true);
+ expect(document.activeElement).toBe(videoPrompt);
+ } finally {
+ registerPositivePromptElement('generate', null, generatePrompt);
+ registerPositivePromptElement('video', null, videoPrompt);
+ generatePrompt.remove();
+ videoPrompt.remove();
+ }
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.ts
index 41a7ae7447..f9b6b5d303 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.ts
@@ -114,8 +114,8 @@ export const useInvokeIssueActions = (): ((issue: InvocationIssue) => InvokeIssu
case 'prompt':
return [
show(() => {
- reveal('generate');
- requestAnimationFrame(() => focusPositivePrompt());
+ reveal(target.widgetId);
+ requestAnimationFrame(() => focusPositivePrompt(target.widgetId));
}),
];
case 'layer':
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts
index 523b89e547..5176abea5a 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts
@@ -10,8 +10,8 @@ export type InvocationIssueTarget =
| { kind: 'connection' }
/** A Generate setting: open the Generate panel at its section, or apply its one-step fix. */
| { kind: 'generation'; issue: GenerationIssue }
- /** The positive prompt could not be expanded. */
- | { kind: 'prompt' }
+ /** The positive prompt of this widget could not be expanded. */
+ | { kind: 'prompt'; widgetId: 'generate' | 'video' }
| { kind: 'layer'; layerId: string }
| { kind: 'workflowNode'; nodeId: string }
/** The source's widget is not in the layout: add it, or run another source. */
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx
index 8746c8b35f..cb77851b5a 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx
@@ -17,6 +17,19 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
const harness = vi.hoisted(() => ({
project: null as unknown,
submit: vi.fn((_args: Record<string, unknown>) => Promise.resolve()),
+ // Stands in for the backend: one prompt per `|` alternative when expansion is on and the prompt has braces.
+ useDynamicPrompts: vi.fn((prompt: string, config: { enabled: boolean } | null) => {
+ const isDynamic = config?.enabled === true && prompt.includes('{');
+
+ return {
+ count: isDynamic ? prompt.split('|').length : 1,
+ error: null,
+ isDynamic,
+ isError: false,
+ isLoading: false,
+ prompts: [],
+ };
+ }),
}));
// A controllable stand-in for the node-template store, so a test can decide which of the two stores
@@ -68,9 +81,7 @@ const preferences = vi.hoisted(() => {
};
});
-vi.mock('@features/generation/react', () => ({
- useDynamicPrompts: () => ({ count: 1, error: null, isDynamic: false, isError: false, isLoading: false, prompts: [] }),
-}));
+vi.mock('@features/generation/react', () => ({ useDynamicPrompts: harness.useDynamicPrompts }));
vi.mock('@features/models', () => ({
ensureModelsLoaded: () => Promise.resolve(),
// One snapshot object, as the real store hands out. A fresh `models` array per render would change
@@ -141,7 +152,7 @@ const Probe = (): ReactNode => {
return (
<>
- <span data-batch-count={state.batchCount} data-testid="reasons">
+ <span data-batch-count={state.batchCount} data-prompt-count={state.promptExpansion.count} data-testid="reasons">
{state.issues.map((issue) => issue.message).join(' | ')}
</span>
<span data-testid="issue-layers">
@@ -278,3 +289,44 @@ describe('useInvocationState and the remembered control-model picks', () => {
expect(blockingReasons()).not.toContain('widgets.layers.control.invalidLayer');
});
});
+
+describe('useInvocationState and Video dynamic prompts', () => {
+ const renderVideo = async (videoValues: Record<string, unknown>) => {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ let state = workbenchReducer(createInitialWorkbenchState(), {
+ region: 'left',
+ type: 'toggleRegionWidget',
+ widgetId: 'video',
+ });
+ state = workbenchReducer(state, {
+ type: 'patchWidgetValues',
+ values: { positivePrompt: 'a {cat|dog|bird}' },
+ widgetId: 'generate',
+ });
+ state = workbenchReducer(state, { type: 'patchWidgetValues', values: videoValues, widgetId: 'video' });
+ state = workbenchReducer(state, { sourceId: 'video', type: 'setInvocationSource' });
+ harness.useDynamicPrompts.mockClear();
+ await renderProbe(activeProject(state));
+
+ return host?.querySelector('[data-testid="reasons"]')?.getAttribute('data-prompt-count');
+ };
+
+ it("counts the Video prompt's expansion with Video's settings, not Generate's prompt", async () => {
+ expect(await renderVideo({ positivePrompt: 'a {red|green} fox' })).toBe('2');
+ expect(harness.useDynamicPrompts).toHaveBeenLastCalledWith(
+ 'a {red|green} fox',
+ expect.objectContaining({ enabled: true, maxPrompts: 10 })
+ );
+ });
+
+ it('counts a Video prompt saved before Video expanded prompts as typed', async () => {
+ // The prompt height marks a panel saved before; one without dynamic prompts settings runs its prompt as typed.
+ expect(
+ await renderVideo({
+ dynamicPromptsEnabled: undefined,
+ positivePrompt: 'a {red|green} fox',
+ positivePromptHeightPx: 96,
+ })
+ ).toBe('1');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
index 06a6e6db36..ae6a97f858 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
@@ -8,6 +8,7 @@ import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities
import {
describeDynamicPromptsFailure,
describeGenerationIssue,
+ getDynamicPromptsConfig,
getEffectivePrompts,
normalizeGenerateSettings,
sanitizeBatchCount,
@@ -15,6 +16,7 @@ import {
} from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { isUpscaleBatchCountFixed } from '@features/upscale';
+import { normalizeVideoWidgetValues } from '@features/video';
import { getInvocationTemplatesSnapshot, subscribeInvocationTemplates } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import { useExternalStoreSelector } from '@platform/state/selectors';
@@ -168,11 +170,15 @@ export const useInvocationState = (): InvocationState => {
? routeInput.workflowValues
: routeInput.generateValues;
+ // Video reads its own normalized values, so the count follows what its submission expands.
+ const videoValues = invocation.sourceId === 'video' ? normalizeVideoWidgetValues(routeInput.videoValues) : null;
const promptExpansion = useDynamicPrompts(
- readEffectivePositivePrompt(routeInput.generateValues),
- invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'
- ? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues))
- : null
+ videoValues ? videoValues.positivePrompt : readEffectivePositivePrompt(routeInput.generateValues),
+ videoValues
+ ? getDynamicPromptsConfig(videoValues)
+ : invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'
+ ? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues))
+ : null
);
// Block unexpandable prompts rather than submitting literal dynamic syntax; hotkey submission enforces the same
// rule. The prompt field offers the way out: retry, or turn dynamic prompts off and run the prompt as typed.
@@ -184,7 +190,14 @@ export const useInvocationState = (): InvocationState => {
...(isConnected
? []
: [{ message: t('topbar.invoke.serverDisconnected'), target: { kind: 'connection' } } as const]),
- ...(expansionReason === null ? [] : [{ message: expansionReason, target: { kind: 'prompt' } } as const]),
+ ...(expansionReason === null
+ ? []
+ : [
+ {
+ message: expansionReason,
+ target: { kind: 'prompt', widgetId: invocation.sourceId === 'video' ? 'video' : 'generate' },
+ } as const,
+ ]),
...resolvedRoute.validationReasons.map((reason) => ({
message: localizeInvocationValidationReason(reason, t),
target: getInvocationIssueTarget(reason, invocation.sourceId),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index 6374f6be1c..b1eee77510 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -390,7 +390,11 @@ describe('prepareCanvasInvocation generation-device boundary', () => {
await prepareCanvasInvocation({
commands: harness.deps.commands,
destination: harness.deps.destination,
- expansion: { positivePrompts: ['a green cat'], positivePromptsSampleSeed: 7 },
+ expansion: {
+ expandedFrom: { combinatorial: false, maxPrompts: 100, positivePrompt: 'a {red|green} cat' },
+ positivePrompts: ['a green cat'],
+ positivePromptsSampleSeed: 7,
+ },
formatControlLayerError: harness.deps.formatControlLayerError,
generateValues: harness.deps.generateValues,
models: harness.deps.models,
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 7679d81fb5..2e56d2534b 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -11,7 +11,7 @@ import type {
CanvasStagingCandidateContract,
} from '@workbench/canvas-engine/contracts';
import type { GraphContract } from '@workbench/graphContracts';
-import type { ExpandedPositivePrompts } from '@workbench/invocationContracts';
+import type { ExpandedPositivePrompts, InvocationSourceId } from '@workbench/invocationContracts';
import type { WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import type { WidgetInstanceId } from '@workbench/widgetContracts';
@@ -40,6 +40,7 @@ import type { CanvasProjectMutation } from './canvasProjectMutations';
import { createEmptyCanvasDocument } from './canvasMigration';
import { MAX_CANVAS_SNAPSHOTS } from './canvasProjectMutations';
import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './canvasStagingView';
+import { getDynamicPromptsExpansionSource } from './invocation';
import { getLayoutPresetLabel, layoutPresets } from './layoutPresets';
import {
createLayoutPresetSnapshot,
@@ -67,6 +68,15 @@ import {
// Seed capabilities to match app boot; submission fails closed without them.
seedArchitectureCapabilities();
+/** What the caller would have expanded the project's prompt from, as it hands that to the resolved submission. */
+const preparedExpansionSource = (state: WorkbenchState, sourceId: InvocationSourceId) => {
+ const source = getDynamicPromptsExpansionSource(getActiveProject(state), sourceId);
+
+ return source
+ ? { combinatorial: source.combinatorial, maxPrompts: source.maxPrompts, positivePrompt: source.positivePrompt }
+ : undefined;
+};
+
const generationDeviceMock = vi.hoisted(() => ({
options: [] as { device: string; name: string }[],
}));
@@ -4414,6 +4424,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const submitResolvedTo = (primed: WorkbenchState, positivePrompts?: string[]) =>
workbenchReducer(primed, {
backendSupportsCancellation: true,
+ expandedFrom: preparedExpansionSource(primed, 'generate'),
positivePrompts,
projectId: primed.activeProjectId,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
@@ -4469,6 +4480,105 @@ describe('workbenchReducer Phase 5 generation flow', () => {
});
});
+ describe('expanded Video prompts on the compiled submission', () => {
+ const wanModel: ModelConfig = {
+ base: 'wan',
+ file_size: 1,
+ format: 'diffusers',
+ hash: 'wan-t2v-hash',
+ key: 'wan-t2v_a14b-diffusers',
+ name: 'Wan 2.2 t2v_a14b',
+ path: 'wan-t2v_a14b-diffusers',
+ source: 'wan-t2v_a14b-diffusers',
+ source_type: 'path',
+ type: 'main',
+ variant: 't2v_a14b',
+ };
+ const submitVideo = (
+ values: Record<string, unknown>,
+ positivePrompts?: string[],
+ positivePromptsSampleSeed: number | null = null
+ ) => {
+ let state = workbenchReducer(createInitialWorkbenchState(), {
+ region: 'left',
+ type: 'toggleRegionWidget',
+ widgetId: 'video',
+ });
+ state = workbenchReducer(state, {
+ type: 'patchWidgetValues',
+ values: { model: wanModel, positivePrompt: 'a {red|green} fox', ...values },
+ widgetId: 'video',
+ });
+
+ return workbenchReducer(state, {
+ backendSupportsCancellation: true,
+ expandedFrom: preparedExpansionSource(state, 'video'),
+ models: [wanModel],
+ positivePrompts,
+ positivePromptsSampleSeed,
+ projectId: state.activeProjectId,
+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'video', sourceLocked: false },
+ type: 'submitResolvedInvocationSnapshot',
+ });
+ };
+
+ it('queues one video per expanded prompt', () => {
+ const queueItem = getActiveProject(submitVideo({}, ['a red fox', 'a green fox'])).queue.items[0];
+
+ expect(queueItem?.snapshot.backendSubmission).toMatchObject({
+ kind: 'generate',
+ positivePrompts: ['a red fox', 'a green fox'],
+ });
+ expect(queueItem?.snapshot.presentation.batchCount).toBe(2);
+ });
+
+ it('drops an expansion and queues the prompt as typed with dynamic prompts off', () => {
+ const queueItem = getActiveProject(submitVideo({ dynamicPromptsEnabled: false }, ['a red fox', 'a green fox']))
+ .queue.items[0];
+
+ expect(queueItem?.snapshot.backendSubmission).toMatchObject({ positivePrompt: 'a {red|green} fox' });
+ expect(queueItem?.snapshot.backendSubmission).not.toHaveProperty('positivePrompts');
+ expect(queueItem?.snapshot.presentation.batchCount).toBe(1);
+ });
+
+ it('recalls the random sample the expansion drew and rotates the widget to a new one', () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);
+
+ try {
+ const state = submitVideo(
+ { dynamicPromptsCombinatorial: false, dynamicPromptsSampleSeed: 7 },
+ ['a green fox'],
+ 7
+ );
+ const project = getActiveProject(state);
+
+ expect(project.queue.items[0]?.snapshot.recall?.videoValues?.dynamicPromptsSampleSeed).toBe(7);
+ expect(getProjectWidgetValues(project, 'video').dynamicPromptsSampleSeed).toBe(Math.floor(0.5 * 4_294_967_295));
+ } finally {
+ random.mockRestore();
+ }
+ });
+
+ // A project saved before Video stored a sample seed draws with 0, the seed it normalizes to.
+ it('rotates a sample seed the stored values never held', () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);
+
+ try {
+ const state = submitVideo(
+ { dynamicPromptsCombinatorial: false, dynamicPromptsSampleSeed: undefined },
+ ['a green fox'],
+ 0
+ );
+
+ expect(getProjectWidgetValues(getActiveProject(state), 'video').dynamicPromptsSampleSeed).toBe(
+ Math.floor(0.5 * 4_294_967_295)
+ );
+ } finally {
+ random.mockRestore();
+ }
+ });
+ });
+
describe('workflow seed modes on the compiled submission', () => {
const SEED_MAX = 4_294_967_295;
const seedTemplate = {
@@ -5044,6 +5154,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
) =>
workbenchReducer(state, {
backendSupportsCancellation: true,
+ expandedFrom: preparedExpansionSource(state, 'generate'),
positivePrompts,
positivePromptsSampleSeed,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
@@ -5341,7 +5452,11 @@ describe('workbenchReducer Phase 5 generation flow', () => {
positivePrompt: 'a {red|green} cat',
});
// Canvas is told the sample its expansion drew, as Generate is.
- const drawn = { positivePrompts: ['a green cat'], positivePromptsSampleSeed: 7 };
+ const drawn = {
+ expandedFrom: { combinatorial: false, maxPrompts: 100, positivePrompt: 'a {red|green} cat' },
+ positivePrompts: ['a green cat'],
+ positivePromptsSampleSeed: 7,
+ };
const first = submitCanvas(primeGenerate(undefined, compiled), compiled, drawn);
const rotated = Math.floor(0.5 * SEED_MAX);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index e82db6861d..2e401ecf83 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -156,6 +156,7 @@ import {
removePromptHistoryItem,
restorePromptHistoryItems,
sanitizeBatchCount,
+ sanitizeSampleSeed,
syncGenerateWidgetValuesWithModels,
} from '@features/generation/settings';
import { getQueueSourceResultSelection, MAX_QUEUE_BATCH_ITEMS } from '@features/queue';
@@ -225,7 +226,9 @@ import {
import { getSourceIdForWidgetTypeId } from './graphWidgets';
import {
defaultInvocationRoute,
+ getDynamicPromptsExpansionSource,
isInvocationRouteValid,
+ isSameDynamicPromptsExpansionSource,
isInvocationSourceAvailable,
isResultDestinationAvailable,
resolveInvocationRoute,
@@ -3978,16 +3981,13 @@ const enqueueCompiledSnapshot = (
const videoSettings = route.sourceId === 'video' ? normalizeVideoWidgetValues(widgetStates.video.values) : null;
const backendGraph = graph.backendGraph;
const canvasGenerateSettings = route.sourceId === 'canvas' ? normalizeGenerateSettings(generate?.values) : null;
- // Upscale and Video have no dynamic prompts switch: their prompts always run as typed.
- const nonExpandingSettings = upscaleSettings ?? videoSettings;
+ // Upscale has no dynamic prompts switch: its prompt always runs as typed.
const sourceGenerateSettings =
route.sourceId === 'canvas'
? canvasGenerateSettings
: route.sourceId === 'generate'
? generateSettings
- : nonExpandingSettings
- ? { ...nonExpandingSettings, dynamicPromptsEnabled: false }
- : null;
+ : (videoSettings ?? (upscaleSettings ? { ...upscaleSettings, dynamicPromptsEnabled: false } : null));
// Resolve template-merged prompts and seeds here, where Generate, Canvas, Upscale and Video submissions converge; the
// planner decides whether the expansion counts.
const submissionPlan = sourceGenerateSettings
@@ -4053,15 +4053,11 @@ const enqueueCompiledSnapshot = (
: route.sourceId === 'generate'
? normalizeGenerateWidgetValues(widgetStates.generate?.values)
: null;
+ const recalledSampleSeed = expansionSampleSeed === null ? {} : { dynamicPromptsSampleSeed: expansionSampleSeed };
const recall = generateRecallValues
- ? {
- generateValues: {
- ...cloneGenerateWidgetValues(generateRecallValues),
- ...(expansionSampleSeed === null ? {} : { dynamicPromptsSampleSeed: expansionSampleSeed }),
- },
- }
+ ? { generateValues: { ...cloneGenerateWidgetValues(generateRecallValues), ...recalledSampleSeed } }
: videoSettings
- ? { videoValues: cloneVideoWidgetValues(videoSettings) }
+ ? { videoValues: { ...cloneVideoWidgetValues(videoSettings), ...recalledSampleSeed } }
: undefined;
const queueItem: QueueItem = {
cancellable: backendSupportsCancellation,
@@ -4120,7 +4116,7 @@ const enqueueCompiledSnapshot = (
? advanceWorkflowSeeds(project, compiled.projectWorkflowId, compiled.workflow.seedAdvances)
: project;
// The queued item carries the previewed draw; rotating afterward makes the preview show the next one.
- const dynamicPromptsSettings = canvasGenerateSettings ?? generateSettings;
+ const dynamicPromptsSettings = canvasGenerateSettings ?? generateSettings ?? videoSettings;
// Fencing on the expansion's seed keeps a submission that drew an already-rotated sample from rotating again.
const resampledProject =
expansionSampleSeed !== null &&
@@ -4131,7 +4127,9 @@ const enqueueCompiledSnapshot = (
advancedProject,
route.sourceId === 'canvas' ? 'generate' : route.sourceId,
(values) =>
- values.dynamicPromptsSampleSeed === expansionSampleSeed && values.dynamicPromptsCombinatorial === false
+ // Sanitized as the expansion read it: a record saved without the field drew sample seed 0.
+ sanitizeSampleSeed(values.dynamicPromptsSampleSeed) === expansionSampleSeed &&
+ values.dynamicPromptsCombinatorial === false
? { ...values, dynamicPromptsSampleSeed: createDynamicPromptsSampleSeed() }
: values
)
@@ -5503,6 +5501,27 @@ const reduceWorkbenchAction = (
);
}
+ // The prompt or its expansion settings changed while the prompt was being expanded. The reducer compiles the
+ // project as it is now, so neither the stale expansion nor the new prompt as typed may run in its place.
+ if (
+ target &&
+ !isSameDynamicPromptsExpansionSource(
+ action.expandedFrom ?? null,
+ getDynamicPromptsExpansionSource(target, action.route.sourceId)
+ )
+ ) {
+ return addNotification(
+ state,
+ createNotification({
+ category: 'enqueue',
+ kind: 'error',
+ projectId: target.id,
+ title: 'The prompt changed while it was being expanded, so nothing was queued. Invoke again.',
+ titleKey: 'topbar.invoke.expansionStale',
+ })
+ );
+ }
+
// The input image changed while Model only read its metadata: say so rather than queue nothing in silence.
if (
target &&