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 the dynamic prompts preview and syntax colouring
joshistoastd425e76dbf05
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex a0de5d362d..1669d03ffa 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -944,7 +944,26 @@"coherenceMinDenoise": "Coherence min denoise","maskBlur": "Mask blur"},- "resetAllToModelDefaults": "Reset all to model defaults"+ "resetAllToModelDefaults": "Reset all to model defaults",+ "dynamicPrompts": {+ "title": "Dynamic Prompts",+ "showPrompts": "Show dynamic prompts",+ "noDynamicSyntax": "Wrap alternatives in braces to generate one image per combination, e.g. a {red|green} ball",+ "summary": "{{prompts}} × {{iterations}} → {{generations}}",+ "expanding": "Expanding…",+ "allCombinations": "All combinations",+ "randomSample": "Random sample",+ "shuffle": "Shuffle the sample",+ "maxPrompts": "Max prompts",+ "numberOfPrompts": "Number of prompts",+ "seedBehaviour": "Seed",+ "seedPerIteration": "Per iteration",+ "seedPerImage": "Per image",+ "promptsPreview": "Prompts preview",+ "usePrompt": "Use this prompt",+ "andMore": "and {{count}} more",+ "problemGeneratingPrompts": "Could not expand this prompt"+ }},"upscale": {"addLora": "LoRAs",diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 4e752c7b81..ac7b272b16 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -448,6 +448,19 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {return json(200, []);}+ // Dynamic prompt expansion. Enough of the `{a|b}` grammar for journeys to+ // exercise the preview and the batch dimension; the real generator lives+ // in the backend.+ if (method === 'POST' && path === '/api/v1/utilities/dynamicprompts') {+ const requested = await readJsonBody(request);+ const prompt = typeof requested?.prompt === 'string' ? requested.prompt : '';+ const maxPrompts = typeof requested?.max_prompts === 'number' ? requested.max_prompts : 100;+ const match = /\{([^{}]*)\}/.exec(prompt);+ const prompts = match ? match[1].split('|').map((value) => prompt.replace(match[0], value.trim())) : [prompt];++ return json(200, { error: null, prompts: prompts.slice(0, Math.max(1, maxPrompts)) });+ }+if (method === 'GET' && (path === '/api/v2/custom_nodes' || path === '/api/v2/custom_nodes/')) {return json(200, state.nodeCatalog);}diff --git a/invokeai/frontend/webv2/src/features/generation/react.ts b/invokeai/frontend/webv2/src/features/generation/react.tsindex 17d35c7196..e8130bdcf9 100644--- a/invokeai/frontend/webv2/src/features/generation/react.ts+++ b/invokeai/frontend/webv2/src/features/generation/react.ts@@ -6,6 +6,7 @@export { GenerationUiProvider, type GenerationUiAdapter } from './ui/GenerationUiContext';export { flushGenerateDrafts, useRegisterGenerateDraftFlusher } from './ui/generateDraftRegistry';export { useDebouncedDraftValue } from './ui/useDebouncedDraftValue';+export { useDynamicPrompts, type DynamicPromptsExpansion } from './ui/useDynamicPrompts';export { createGenerateFormValuesSelector } from './ui/generateFormViewModel';export { notifyGenerateModelSelectionCleared } from './ui/modelSelectionNotice';export { adjustFocusedPromptAttention } from './ui/promptFields/promptAttentionHotkeys';diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsxnew file mode 100644index 0000000000..86418db3f1--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx@@ -0,0 +1,121 @@+import type { DynamicPromptsConfig } from '@features/generation/core/dynamicPrompts';++import { ChakraProvider } from '@chakra-ui/react';+import { DynamicPromptsButton } from '@features/generation/ui/promptFields/DynamicPromptsButton';+import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++const parseDynamicPrompts = vi.hoisted(() => vi.fn());++vi.mock('@features/generation/data/promptUtilities', () => ({ parseDynamicPrompts }));++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const config: DynamicPromptsConfig & { onChange: () => void } = {+ combinatorial: true,+ maxPrompts: 100,+ onChange: vi.fn(),+ sampleSeed: 0,+ seedBehaviour: 'per-iteration',+};++const render = async (prompt: string, onUsePrompt = vi.fn()) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root?.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChakraProvider value={system}>+ <PromptTextarea+ aria-label="Prompt"+ defaultHeightPx={100}+ highlightDynamicPrompts+ minHeightPx={60}+ readOnly+ resizeHandleAriaLabel="Resize prompt"+ showSyntaxHighlighting+ value={prompt}+ />+ <DynamicPromptsButton batchCount={2} config={config} positivePrompt={prompt} onUsePrompt={onUsePrompt} />+ </ChakraProvider>+ </QueryClientProvider>+ );+ });++ return { onUsePrompt };+};++// i18n is not bootstrapped in browser tests, so labels come back as keys; the+// trigger is the last button rendered inside the host.+const findButton = () => [...host!.querySelectorAll('button')].at(-1)!;++beforeEach(() => {+ parseDynamicPrompts.mockReset();+ parseDynamicPrompts.mockResolvedValue({ error: null, prompts: ['a red cat', 'a green cat'] });+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('dynamic prompts in the positive prompt field', () => {+ it('marks braces and separators in the highlight underlay', async () => {+ await render('a {red|green} cat');++ const underlay = host!.querySelector('[aria-hidden="true"] pre')!;+ const spans = [...underlay.querySelectorAll('span')].map((span) => span.textContent);++ // Each brace and separator is its own span, so they can be coloured apart+ // from the surrounding text.+ expect(spans).toContain('{');+ expect(spans).toContain('|');+ expect(spans).toContain('}');+ });++ it('shows the expanded count on the button and the prompts in the popover', async () => {+ const { onUsePrompt } = await render('a {red|green} cat');++ await vi.waitFor(() => expect(findButton().textContent).toContain('2'));++ await act(async () => {+ await userEvent.click(findButton());+ });++ const rows = [...document.querySelectorAll('button')].filter((button) => button.textContent?.includes('a red cat'));++ expect(rows.length).toBe(1);+ expect(document.body.textContent).toContain('a green cat');++ // Clicking a previewed prompt adopts that concrete expansion.+ await act(async () => {+ await userEvent.click(rows[0]!);+ });++ expect(onUsePrompt).toHaveBeenCalledWith('a red cat');+ });++ it('stays inert and never expands a prompt with no dynamic syntax', async () => {+ await render('a plain cat');++ await act(async () => {+ await new Promise((resolve) => {+ window.setTimeout(resolve, 700);+ });+ });++ expect(parseDynamicPrompts).not.toHaveBeenCalled();+ expect(findButton().textContent).not.toMatch(/\d/);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsxnew file mode 100644index 0000000000..1d5daa8e18--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx@@ -0,0 +1,305 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop */+import type { DynamicPromptsConfig, DynamicPromptsSeedBehaviour } from '@features/generation/core/dynamicPrompts';++import {+ createListCollection,+ HStack,+ NumberInput,+ Popover,+ Portal,+ SegmentGroup,+ Stack,+ Text,+} from '@chakra-ui/react';+import {+ createDynamicPromptsSampleSeed,+ DYNAMIC_PROMPTS_MAX_PROMPTS,+ DYNAMIC_PROMPTS_MIN_PROMPTS,+ isDynamicPromptsSeedBehaviour,+ sanitizeMaxPrompts,+} from '@features/generation/core/dynamicPrompts';+import { useDynamicPrompts } from '@features/generation/ui/useDynamicPrompts';+import { Button, IconButton } from '@platform/ui/Button';+import { Scrollable } from '@platform/ui/Scrollable';+import { Select } from '@platform/ui/Select';+import { Tooltip } from '@platform/ui/Tooltip';+import { BracesIcon, ShuffleIcon } from 'lucide-react';+import { useCallback, useId, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++/** Rendering every row of a 10,000-prompt expansion would cost more than it tells the user. */+const MAX_PREVIEW_ROWS = 200;+const POPOVER_POSITIONING_BOTTOM_END = { placement: 'bottom-end' } as const;+const COUNT_TEXT_PROPS = { fontVariantNumeric: 'tabular-nums' } as const;++export interface DynamicPromptsFieldConfig extends DynamicPromptsConfig {+ onChange: (patch: Partial<DynamicPromptsConfig>) => void;+}++interface DynamicPromptsButtonProps {+ config: DynamicPromptsFieldConfig;+ batchCount: number;+ positivePrompt: string;+ onUsePrompt: (prompt: string) => void;+}++export const DynamicPromptsButton = ({+ batchCount,+ config,+ onUsePrompt,+ positivePrompt,+}: DynamicPromptsButtonProps) => {+ const { t } = useTranslation();+ const triggerId = useId();+ const [isOpen, setIsOpen] = useState(false);+ const expansion = useDynamicPrompts(positivePrompt, config);+ const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);+ const handleOpenChange = useCallback((event: { open: boolean }) => setIsOpen(event.open), []);+ const handleUsePrompt = useCallback(+ (prompt: string) => {+ onUsePrompt(prompt);+ setIsOpen(false);+ },+ [onUsePrompt]+ );++ const tooltip = expansion.isDynamic+ ? t('widgets.generate.dynamicPrompts.showPrompts')+ : t('widgets.generate.dynamicPrompts.noDynamicSyntax');+ // Quiet states only: an em-dash while the expansion is in flight, an error+ // tint when it failed. No spinner, no animation on a control this small.+ const countLabel = !expansion.isDynamic ? null : expansion.isLoading ? '—' : String(expansion.count);++ return (+ <Popover.Root+ ids={popoverIds}+ lazyMount+ open={isOpen}+ positioning={POPOVER_POSITIONING_BOTTOM_END}+ unmountOnExit+ onOpenChange={handleOpenChange}+ >+ <Tooltip content={tooltip} ids={popoverIds}>+ <Popover.Trigger asChild>+ <IconButton+ aria-label={t('widgets.generate.dynamicPrompts.showPrompts')}+ color={expansion.isError ? 'fg.error' : undefined}+ opacity={expansion.isDynamic ? undefined : 0.5}+ px={countLabel ? '1' : undefined}+ size="2xs"+ variant="ghost"+ w={countLabel ? 'auto' : undefined}+ >+ <BracesIcon />+ {countLabel ? (+ <Text as="span" css={COUNT_TEXT_PROPS} fontSize="2xs">+ {countLabel}+ </Text>+ ) : null}+ </IconButton>+ </Popover.Trigger>+ </Tooltip>+ <Portal>+ <Popover.Positioner>+ <Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="26rem">+ <Popover.Body p="2.5">+ <DynamicPromptsPanel+ batchCount={batchCount}+ config={config}+ expansion={expansion}+ onUsePrompt={handleUsePrompt}+ />+ </Popover.Body>+ </Popover.Content>+ </Popover.Positioner>+ </Portal>+ </Popover.Root>+ );+};++const DynamicPromptsPanel = ({+ batchCount,+ config,+ expansion,+ onUsePrompt,+}: {+ batchCount: number;+ config: DynamicPromptsFieldConfig;+ expansion: ReturnType<typeof useDynamicPrompts>;+ onUsePrompt: (prompt: string) => void;+}) => {+ const { t } = useTranslation();+ const { onChange } = config;+ const visiblePrompts = expansion.prompts.slice(0, MAX_PREVIEW_ROWS);+ const hiddenPromptCount = expansion.prompts.length - visiblePrompts.length;++ const handleModeChange = useCallback(+ (event: { value: string | null }) => onChange({ combinatorial: event.value !== 'random' }),+ [onChange]+ );+ const handleMaxPromptsChange = useCallback(+ ({ valueAsNumber }: { valueAsNumber: number }) =>+ Number.isFinite(valueAsNumber) && onChange({ maxPrompts: sanitizeMaxPrompts(valueAsNumber) }),+ [onChange]+ );+ const handleSeedBehaviourChange = useCallback(+ ({ value }: { value: string[] }) =>+ isDynamicPromptsSeedBehaviour(value[0]) && onChange({ seedBehaviour: value[0] as DynamicPromptsSeedBehaviour }),+ [onChange]+ );+ const handleShuffle = useCallback(() => onChange({ sampleSeed: createDynamicPromptsSampleSeed() }), [onChange]);+ const modeItems = useMemo(+ () => [+ { label: t('widgets.generate.dynamicPrompts.allCombinations'), value: 'all' },+ { label: t('widgets.generate.dynamicPrompts.randomSample'), value: 'random' },+ ],+ [t]+ );+ const maxPromptsLabel = config.combinatorial+ ? t('widgets.generate.dynamicPrompts.maxPrompts')+ : t('widgets.generate.dynamicPrompts.numberOfPrompts');+ const seedBehaviourValue = useMemo(() => [config.seedBehaviour], [config.seedBehaviour]);+ const seedBehaviourCollection = useMemo(+ () =>+ createListCollection({+ items: [+ { label: t('widgets.generate.dynamicPrompts.seedPerIteration'), value: 'per-iteration' },+ { label: t('widgets.generate.dynamicPrompts.seedPerImage'), value: 'per-image' },+ ],+ }),+ [t]+ );++ return (+ <Stack gap="2.5">+ <HStack justify="space-between">+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">+ {t('widgets.generate.dynamicPrompts.title')}+ </Text>+ <Text color="fg.muted" css={COUNT_TEXT_PROPS} fontSize="2xs">+ {expansion.isLoading+ ? t('widgets.generate.dynamicPrompts.expanding')+ : t('widgets.generate.dynamicPrompts.summary', {+ generations: expansion.count * batchCount,+ iterations: batchCount,+ prompts: expansion.count,+ })}+ </Text>+ </HStack>++ <HStack gap="2">+ <SegmentGroup.Root+ flex="1"+ size="xs"+ value={config.combinatorial ? 'all' : 'random'}+ onValueChange={handleModeChange}+ >+ <SegmentGroup.Indicator />+ <SegmentGroup.Items items={modeItems} />+ </SegmentGroup.Root>+ {config.combinatorial ? null : (+ <Tooltip content={t('widgets.generate.dynamicPrompts.shuffle')}>+ <IconButton+ aria-label={t('widgets.generate.dynamicPrompts.shuffle')}+ size="xs"+ variant="ghost"+ onClick={handleShuffle}+ >+ <ShuffleIcon />+ </IconButton>+ </Tooltip>+ )}+ </HStack>++ <HStack gap="2">+ <Stack flex="1" gap="1">+ <Text color="fg.subtle" fontSize="2xs">+ {maxPromptsLabel}+ </Text>+ <NumberInput.Root+ allowMouseWheel+ max={DYNAMIC_PROMPTS_MAX_PROMPTS}+ min={DYNAMIC_PROMPTS_MIN_PROMPTS}+ size="xs"+ value={String(config.maxPrompts)}+ onValueChange={handleMaxPromptsChange}+ >+ <NumberInput.Control />+ <NumberInput.Input aria-label={maxPromptsLabel} paddingStart="2" />+ </NumberInput.Root>+ </Stack>+ <Stack flex="1" gap="1">+ <Text color="fg.subtle" fontSize="2xs">+ {t('widgets.generate.dynamicPrompts.seedBehaviour')}+ </Text>+ <Select+ aria-label={t('widgets.generate.dynamicPrompts.seedBehaviour')}+ collection={seedBehaviourCollection}+ size="xs"+ value={seedBehaviourValue}+ onValueChange={handleSeedBehaviourChange}+ />+ </Stack>+ </HStack>++ {expansion.isError ? (+ <Text color="fg.error" fontSize="2xs">+ {t('widgets.generate.dynamicPrompts.problemGeneratingPrompts')}+ </Text>+ ) : expansion.error ? (+ <Text color="fg.error" fontSize="2xs" wordBreak="break-word">+ {expansion.error}+ </Text>+ ) : null}++ <Scrollable h="14rem" label={t('widgets.generate.dynamicPrompts.promptsPreview')}>+ <Stack gap="0">+ {visiblePrompts.map((prompt, index) => (+ <DynamicPromptRow key={`${index}-${prompt}`} index={index} prompt={prompt} onUsePrompt={onUsePrompt} />+ ))}+ {hiddenPromptCount > 0 ? (+ <Text color="fg.subtle" fontSize="2xs" px="2" py="1.5">+ {t('widgets.generate.dynamicPrompts.andMore', { count: hiddenPromptCount })}+ </Text>+ ) : null}+ </Stack>+ </Scrollable>+ </Stack>+ );+};++const DynamicPromptRow = ({+ index,+ onUsePrompt,+ prompt,+}: {+ index: number;+ prompt: string;+ onUsePrompt: (prompt: string) => void;+}) => {+ const { t } = useTranslation();+ const handleClick = useCallback(() => onUsePrompt(prompt), [onUsePrompt, prompt]);++ return (+ <Button+ alignItems="start"+ gap="2"+ h="auto"+ justifyContent="start"+ px="2"+ py="1.5"+ size="xs"+ title={t('widgets.generate.dynamicPrompts.usePrompt')}+ transitionDuration="faster"+ variant="ghost"+ onClick={handleClick}+ >+ <Text as="span" color="fg.subtle" css={COUNT_TEXT_PROPS} fontSize="2xs">+ {index + 1}+ </Text>+ <Text as="span" color="fg" fontFamily="mono" fontSize="0.72rem" textAlign="start" wordBreak="break-word">+ {prompt}+ </Text>+ </Button>+ );+};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsxindex aa9f6b283f..5fb230de7a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx@@ -1,10 +1,12 @@import type { PromptHistoryItem } from '@features/generation/contracts';+import type { DynamicPromptsConfig } from '@features/generation/core/dynamicPrompts';import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';import { Stack } from '@chakra-ui/react';import { getPromptPolicy } from '@features/generation/core/baseGenerationPolicies';+import { sanitizeBatchCount } from '@features/generation/core/batch';import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';-import { useCallback } from 'react';+import { useCallback, useMemo } from 'react';import { NegativePromptField } from './NegativePromptField';import { PositivePromptField } from './PositivePromptField';@@ -61,6 +63,34 @@ export const GeneratePromptFields = ({const handlePositivePromptChange = useCallback((positivePrompt: string) => onCommit({ positivePrompt }), [onCommit]);+ const handleDynamicPromptsChange = useCallback(+ (patch: Partial<DynamicPromptsConfig>) =>+ onCommitImmediate({+ ...(patch.combinatorial === undefined ? {} : { dynamicPromptsCombinatorial: patch.combinatorial }),+ ...(patch.maxPrompts === undefined ? {} : { dynamicPromptsMaxPrompts: patch.maxPrompts }),+ ...(patch.sampleSeed === undefined ? {} : { dynamicPromptsSampleSeed: patch.sampleSeed }),+ ...(patch.seedBehaviour === undefined ? {} : { dynamicPromptsSeedBehaviour: patch.seedBehaviour }),+ }),+ [onCommitImmediate]+ );++ const dynamicPrompts = useMemo(+ () => ({+ combinatorial: settings.dynamicPromptsCombinatorial,+ maxPrompts: settings.dynamicPromptsMaxPrompts,+ onChange: handleDynamicPromptsChange,+ sampleSeed: settings.dynamicPromptsSampleSeed,+ seedBehaviour: settings.dynamicPromptsSeedBehaviour,+ }),+ [+ handleDynamicPromptsChange,+ settings.dynamicPromptsCombinatorial,+ settings.dynamicPromptsMaxPrompts,+ settings.dynamicPromptsSampleSeed,+ settings.dynamicPromptsSeedBehaviour,+ ]+ );+const handlePositivePromptResizeEnd = useCallback((positivePromptHeightPx: number) => onCommitImmediate({ positivePromptHeightPx }),[onCommitImmediate]@@ -81,6 +111,8 @@ export const GeneratePromptFields = ({return (<Stack gap="1" py="2"><PositivePromptField+ batchCount={sanitizeBatchCount(generateValues.batchCount)}+ dynamicPrompts={dynamicPrompts}heightPx={promptValues.positivePromptHeightPx}value={promptValues.positivePrompt}loras={settings.loras}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsxindex 4fc8330e45..740df9dca0 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx@@ -7,6 +7,10 @@ import { HStack, Icon, Image, Input, Popover, Portal, Separator, Stack, Text } fimport { filterPromptHistory } from '@features/generation/core/promptHistory';import { expandPrompt, imageToPrompt } from '@features/generation/data/promptUtilities';import { GenerationModelSelect as ModelSelect, useGenerationUi } from '@features/generation/ui/GenerationUiContext';+import {+ DynamicPromptsButton,+ type DynamicPromptsFieldConfig,+} from '@features/generation/ui/promptFields/DynamicPromptsButton';import { useMountEffect } from '@platform/react/useMountEffect';import { getApiErrorMessage } from '@platform/transport/http';import { Button, IconButton, Scrollable, Tooltip } from '@platform/ui';@@ -19,6 +23,9 @@ const TEXT_LLM_MODEL_TYPES = ['text_llm'];const LLAVA_MODEL_TYPES = ['llava_onevision'];interface PositivePromptActionsProps {+ batchCount: number;+ /** Absent on surfaces whose prompt is not batch-expanded (Upscale). */+ dynamicPrompts: DynamicPromptsFieldConfig | null;loras: GenerateLora[];isPromptTriggerPickerOpen: boolean;onUsePrompt: (prompt: PromptHistoryItem) => void;@@ -30,6 +37,8 @@ interface PositivePromptActionsProps {}export const PositivePromptActions = ({+ batchCount,+ dynamicPrompts,isPromptTriggerPickerOpen,onOpenPromptTriggerPicker,onPositivePromptChangeImmediate,@@ -39,6 +48,14 @@ export const PositivePromptActions = ({}: PositivePromptActionsProps) => {return (<HStack gap="0.5">+ {dynamicPrompts ? (+ <DynamicPromptsButton+ batchCount={batchCount}+ config={dynamicPrompts}+ positivePrompt={positivePrompt}+ onUsePrompt={onPositivePromptChangeImmediate}+ />+ ) : null}<AddPromptTriggerButtonisOpen={isPromptTriggerPickerOpen}onOpenPromptTriggerPicker={onOpenPromptTriggerPicker}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsxindex ba808c3f47..3201e9bb8a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx@@ -8,6 +8,8 @@ import { Field } from '@platform/ui';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import type { DynamicPromptsFieldConfig } from './DynamicPromptsButton';+import { PositivePromptActions, PromptTriggerPopover } from './PositivePromptActions';import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';import { insertPromptText, type PromptTextRange, registerPositivePromptElement } from './promptFocus';@@ -17,6 +19,9 @@ import { PromptTextarea } from './PromptTextarea';const PROMPT_INPUT_DEBOUNCE_MS = 250;interface PositivePromptFieldProps {+ batchCount?: number;+ /** Absent on surfaces whose prompt is not batch-expanded (Upscale). */+ dynamicPrompts?: DynamicPromptsFieldConfig | null;heightPx: number;loras: GenerateLora[];projectId: string;@@ -34,6 +39,8 @@ type PromptTriggerPickerState = {};export const PositivePromptField = ({+ batchCount = 1,+ dynamicPrompts = null,heightPx,loras,onChange,@@ -133,6 +140,8 @@ export const PositivePromptField = ({const labelEnd = useMemo(() => (<PositivePromptActions+ batchCount={batchCount}+ dynamicPrompts={dynamicPrompts}isPromptTriggerPickerOpen={triggerPickerState !== null}loras={loras}positivePrompt={draftValue}@@ -144,8 +153,10 @@ export const PositivePromptField = ({/>),[+ batchCount,commitPromptChangeImmediately,draftValue,+ dynamicPrompts,handleOpenPromptTriggerPicker,handleUsePrompt,loras,@@ -175,6 +186,7 @@ export const PositivePromptField = ({resizeHandleAriaLabel={t('widgets.generate.resizePositivePrompt')}size="xs"fontFamily="mono"+ highlightDynamicPrompts={dynamicPrompts !== null}showSyntaxHighlighting={showSyntaxHighlighting}textareaRef={handleTextareaRef}value={draftValue}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsxindex 753c42e379..b02fe86b22 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx@@ -46,6 +46,12 @@ const PROMPT_TEXTAREA_HIGHLIGHTED_CSS = {};interface PromptTextareaProps extends Omit<ResizableTextareaProps, 'underlay'> {+ /**+ * Annotate `{a|b}` syntax. Only surfaces whose prompt is batch-expanded set+ * this — elsewhere the braces are literal text and colouring them would+ * promise an expansion that never happens.+ */+ highlightDynamicPrompts?: boolean;showSyntaxHighlighting: boolean;value: string;}@@ -83,6 +89,7 @@ const PromptHighlightSpan = ({ segment }: { segment: PromptHighlightSegment }) =export const PromptTextarea = ({fontFamily = 'mono',fontSize,+ highlightDynamicPrompts = false,lineHeight,onScroll,showSyntaxHighlighting,@@ -98,8 +105,8 @@ export const PromptTextarea = ({const effectiveLineHeight = lineHeight ?? PROMPT_TEXTAREA_LINE_HEIGHT;const segments = useMemo(- () => (shouldHighlight ? buildPromptHighlightSegments(value) : []),- [shouldHighlight, value]+ () => (shouldHighlight ? buildPromptHighlightSegments(value, { dynamicPrompts: highlightDynamicPrompts }) : []),+ [highlightDynamicPrompts, shouldHighlight, value]);useLayoutEffect(() => {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useDynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/ui/useDynamicPrompts.tsnew file mode 100644index 0000000000..96596151f2--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/useDynamicPrompts.ts@@ -0,0 +1,75 @@+import type { DynamicPromptsConfig } from '@features/generation/core/dynamicPrompts';++import { hasDynamicPromptSyntax } from '@features/generation/core/dynamicPrompts';+import { dynamicPromptsQueryOptions } from '@features/generation/data/dynamicPromptsQueries';+import { useQuery } from '@tanstack/react-query';+import { useEffect, useState } from 'react';++/**+ * On top of the Generate form's 250ms commit debounce, so a burst of typing+ * settles before it costs a round trip.+ */+const DYNAMIC_PROMPTS_DEBOUNCE_MS = 500;++const useDebouncedValue = <Value>(value: Value, delayMs: number): Value => {+ const [debouncedValue, setDebouncedValue] = useState(value);++ useEffect(() => {+ const timeout = window.setTimeout(() => setDebouncedValue(value), delayMs);++ return () => window.clearTimeout(timeout);+ }, [delayMs, value]);++ return debouncedValue;+};++export interface DynamicPromptsExpansion {+ /** The expanded prompts, or the prompt itself when there is nothing to expand. */+ prompts: string[];+ /** Generations one iteration will produce. */+ count: number;+ /** A backend parse notice; the prompts alongside it are still usable. */+ error: string | null;+ /** The request failed outright, so the literal prompt is what would generate. */+ isError: boolean;+ isLoading: boolean;+ /** The prompt contains `{…}`, so it is subject to expansion. */+ isDynamic: boolean;+}++/**+ * Reads the shared expansion cache. The Generate preview, the Invoke tooltip,+ * and the submit path all address the same query key, so observing here neither+ * duplicates a request nor goes stale relative to what is submitted.+ */+export const useDynamicPrompts = (prompt: string, config: DynamicPromptsConfig | null): DynamicPromptsExpansion => {+ const isDynamic = Boolean(config) && hasDynamicPromptSyntax(prompt);+ const debouncedPrompt = useDebouncedValue(prompt, DYNAMIC_PROMPTS_DEBOUNCE_MS);+ // A prompt that changed since the last debounce tick has a stale expansion, so+ // report loading rather than a count the user is about to see change.+ const isSettled = debouncedPrompt === prompt;+ const query = useQuery({+ ...dynamicPromptsQueryOptions({+ combinatorial: config?.combinatorial !== false,+ max_prompts: config?.maxPrompts,+ prompt: debouncedPrompt,+ seed: config?.combinatorial === false ? config.sampleSeed : null,+ }),+ enabled: isDynamic && isSettled,+ });++ if (!isDynamic) {+ return { count: 1, error: null, isDynamic: false, isError: false, isLoading: false, prompts: [prompt] };+ }++ const prompts = query.data?.prompts ?? [prompt];++ return {+ count: prompts.length,+ error: query.data?.error ?? null,+ isDynamic: true,+ isError: query.isError,+ isLoading: !isSettled || query.isPending,+ prompts,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxindex 1ab8aba4e8..3cbe0401dc 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx@@ -1,8 +1,8 @@import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';import { Flex, Group, HStack, Icon, Menu, Portal, Separator, Stack, Text, VStack } from '@chakra-ui/react';-import { flushGenerateDrafts } from '@features/generation/react';-import { sanitizeBatchCount } from '@features/generation/settings';+import { flushGenerateDrafts, useDynamicPrompts, type DynamicPromptsExpansion } from '@features/generation/react';+import { sanitizeBatchCount, sanitizeDynamicPromptsConfig } from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';import { useInvocationTemplatesSelector } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';@@ -39,6 +39,14 @@ const MENU_POSITIONING = { placement: 'bottom-end' } as const;const TOOLTIP_CONTENT_PROPS = { p: '0' };const DISABLED_PROPS = { opacity: 0.4 };+/** Reads the persisted dynamic prompt fields off untyped widget values. */+const readDynamicPromptsConfig = (values: Record<string, unknown>) => ({+ combinatorial: values.dynamicPromptsCombinatorial,+ maxPrompts: values.dynamicPromptsMaxPrompts,+ sampleSeed: values.dynamicPromptsSampleSeed,+ seedBehaviour: values.dynamicPromptsSeedBehaviour,+});+const getBatchCount = (values: Record<string, unknown>): number => {const batchCount = values.batchCount;@@ -53,23 +61,30 @@ const compactBlockingReason = (reason: string): string => {return reason.replace(/^The /, '').replace(/project graph/i, 'workflow');};+const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`;+const InvokeTooltipContent = ({blockingReasons,sourceValues,invocation,isValid,+ promptExpansion,}: {blockingReasons: string[];sourceValues: Record<string, unknown>;invocation: InvocationRoute;isValid: boolean;+ promptExpansion: DynamicPromptsExpansion;}) => {const batchCount = getBatchCount(sourceValues);const destination = getDestinationLabel(invocation.destination);+ const promptCount = promptExpansion.count;const summary =invocation.sourceId === 'generate' || invocation.sourceId === 'upscale'- ? `1 prompt × ${batchCount} iteration${batchCount === 1 ? '' : 's'} → ${batchCount} generation${batchCount === 1 ? '' : 's'}`- : `Workflow × ${batchCount} run${batchCount === 1 ? '' : 's'} → ${batchCount} generation${batchCount === 1 ? '' : 's'}`;+ ? promptExpansion.isLoading+ ? 'Expanding prompts…'+ : `${plural(promptCount, 'prompt')} × ${plural(batchCount, 'iteration')} → ${plural(promptCount * batchCount, 'generation')}`+ : `Workflow × ${plural(batchCount, 'run')} → ${plural(batchCount, 'generation')}`;return (<Stack gap="1.5" minW="14rem" p="2">@@ -127,9 +142,21 @@ export const InvokeControl = () => {const isLocked = invocation.sourceLocked || invocation.destinationLocked;const isConnected = backendConnectionStatus === 'connected';+ // Observing the shared expansion cache here keeps the count honest and costs+ // nothing extra: the Generate preview and the submit path use the same key.+ const promptExpansion = useDynamicPrompts(+ typeof routeInput.generateValues.positivePrompt === 'string' ? routeInput.generateValues.positivePrompt : '',+ invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'+ ? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues))+ : null+ );const blockingReasons = useMemo(- () => [...(isConnected ? [] : ['The backend is disconnected.']), ...resolvedRoute.validationReasons],- [isConnected, resolvedRoute.validationReasons]+ () => [+ ...(isConnected ? [] : ['The backend is disconnected.']),+ ...(promptExpansion.isError ? ['The prompt could not be expanded.'] : []),+ ...resolvedRoute.validationReasons,+ ],+ [isConnected, promptExpansion.isError, resolvedRoute.validationReasons]);const isValid = isInvocationRouteValid(resolvedRoute) && isConnected;const routeLabel = isValid ? formatRoute(resolvedRoute) : (blockingReasons[0] ?? formatRoute(resolvedRoute));@@ -187,12 +214,14 @@ export const InvokeControl = () => {}invocation={invocation}isValid={isValid}+ promptExpansion={promptExpansion}/>),[blockingReasons,invocation,isValid,+ promptExpansion,routeInput.generateValues,routeInput.invocation.sourceId,routeInput.upscaleValues,