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): apply prompt templates on every submit path
joshistoast4f02bcc7e17e
diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.tsindex 2fce8c0e20..42fd90b7c2 100644--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts@@ -43,6 +43,9 @@ const GENERATE_UI_NOISE_KEYS: ReadonlySet<string> = new Set(['batchCount','negativePromptHeightPx','positivePromptHeightPx',+ // Toggling the read-only template view changes nothing about what generates.+ // Applying a template does, so `promptTemplate` is deliberately not noise.+ 'promptTemplateViewMode',]);const UPSCALE_UI_NOISE_KEYS: ReadonlySet<string> = new Set([diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.tsindex da6a0eaf00..f01c74cb12 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts@@ -3,7 +3,11 @@ import type { Project } from '@workbench/projectContracts';import { isGalleryVirtualBoard } from '@features/gallery';import { toModelIdentifier } from '@features/generation/graph';-import { isSupportedGenerateModel, normalizeGenerateWidgetValues } from '@features/generation/settings';+import {+ getEffectivePrompts,+ isSupportedGenerateModel,+ normalizeGenerateWidgetValues,+} from '@features/generation/settings';import {assertAccountScopeCurrent,captureAccountScope,@@ -30,11 +34,16 @@ const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, ureturn dimensions;}+ // The merged prompts, matching what a generated image's `core_metadata` records.+ // A saved canvas is recalled through the same path, so the two must agree or+ // recalling from a saved image would restore different text.+ const effectivePrompts = getEffectivePrompts(generateValues);+return {...dimensions,...(isSupportedGenerateModel(generateValues.model) ? { model: toModelIdentifier(generateValues.model) } : {}),- ...(generateValues.negativePromptEnabled ? { negative_prompt: generateValues.negativePrompt } : {}),- positive_prompt: generateValues.positivePrompt,+ ...(generateValues.negativePromptEnabled ? { negative_prompt: effectivePrompts.negativePrompt } : {}),+ positive_prompt: effectivePrompts.positivePrompt,seed: generateValues.seed,};};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex ada06080e2..b3031b2acd 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -283,18 +283,33 @@ const getMetadataVae = (const getPromptPatch = (metadata: unknown-): Partial<Pick<GenerateWidgetValues, 'negativePrompt' | 'positivePrompt'>> => {+): Partial<Pick<GenerateWidgetValues, 'negativePrompt' | 'positivePrompt' | 'promptTemplate'>> => {const positivePrompt = getString(metadata, 'positive_prompt');const negativePrompt = getNullableString(metadata, 'negative_prompt');+ // Image metadata records the prompt the model was given, so it already has any+ // template baked in. Clearing the active template stops it wrapping the text a+ // second time on the next Invoke.+ const clearTemplate = positivePrompt !== null || negativePrompt !== undefined;return {...(positivePrompt !== null ? { positivePrompt } : {}),...(negativePrompt !== undefined ? { negativePrompt: negativePrompt ?? '' } : {}),+ ...(clearTemplate ? { promptTemplate: null } : {}),};};const hasPrompt = (metadata: unknown): boolean => Object.keys(getPromptPatch(metadata)).length > 0;+/**+ * The prompts an image was generated with, for seeding a new prompt template.+ * These are the merged prompts — metadata records what the model was given — so+ * the template starts from the text that produced the image.+ */+export const getMetadataPrompts = (metadata: unknown): { negativePrompt: string; positivePrompt: string } => ({+ negativePrompt: getNullableString(metadata, 'negative_prompt') ?? '',+ positivePrompt: getString(metadata, 'positive_prompt') ?? '',+});+const hasMetadataSize = (metadata: unknown, model: GenerateModelConfig): boolean =>Object.keys(getMetadataSize(metadata, model)).length > 0;diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.tsindex d3f9d2c315..26bc537413 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts@@ -21,7 +21,7 @@ import type { ResolvedInvocationRoute } from '@workbench/invocationContracts';import type { Project } from '@workbench/projectContracts';import { resolveDynamicPrompts } from '@features/generation/prompts';-import { hasDynamicPromptSyntax, normalizeGenerateSettings } from '@features/generation/settings';+import { getEffectivePrompts, hasDynamicPromptSyntax, normalizeGenerateSettings } from '@features/generation/settings';import { queryClient } from '@platform/query/client';import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';@@ -58,6 +58,12 @@ export interface SubmitResolvedInvocationDeps {/*** The GenerateSettings behind a route that expands `{a|b}`, or `null` when the* route submits its prompt literally (Upscale, Workflow) or has no such syntax.+ *+ * The returned settings carry the *merged* prompts, so both the gate and the+ * expansion below see what will actually generate. That matters in both+ * directions: an active template can introduce `{a|b}` a plain authored prompt+ * never had, and it always consumes its own `{prompt}` placeholder before the+ * expander could mistake it for a one-option group.*/const getExpandableSettings = (project: Project, route: ResolvedInvocationRoute): GenerateSettings | null => {if (route.sourceId === 'upscale' || route.sourceId === 'workflow') {@@ -66,7 +72,13 @@ const getExpandableSettings = (project: Project, route: ResolvedInvocationRoute)const settings = normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));- return settings && hasDynamicPromptSyntax(settings.positivePrompt) ? settings : null;+ if (!settings) {+ return null;+ }++ const effectiveSettings = { ...settings, ...getEffectivePrompts(settings) };++ return hasDynamicPromptSyntax(effectiveSettings.positivePrompt) ? effectiveSettings : null;};/**diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.tsindex d63cbbc747..9a3d2386e6 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts@@ -70,6 +70,7 @@ describe('buildQueueRecallValues', () => {negativePrompt: 'snap neg',negativePromptEnabled: true,positivePrompt: 'snap',+ promptTemplate: null,});});@@ -85,9 +86,23 @@ describe('buildQueueRecallValues', () => {negativePrompt: 'meta neg',negativePromptEnabled: true,positivePrompt: 'meta',+ promptTemplate: null,});});+ // Session metadata carries the prompt the model was given, template already+ // applied, so recalling it has to stop the active template wrapping it again.+ it('clears the active prompt template when recalling prompts', () => {+ const withTemplate = makeValues({+ promptTemplate: { id: 't1', name: 'Cinematic', negativePrompt: '', positivePrompt: '{prompt}, cinematic' },+ });++ expect(+ buildQueueRecallValues('prompts', { current: withTemplate, meta: { positivePrompt: 'meta' }, snapshot: null })+ ?.promptTemplate+ ).toBeNull();+ });+it('prefers the executed session seed and pins randomization off', () => {const snapshot = makeValues({ seed: 7, shouldRandomizeSeed: false });diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.tsindex 36cf975e61..3b49596612 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts@@ -58,6 +58,10 @@ export const buildQueueRecallValues = (return {...current,positivePrompt,+ // The recalled text already went through whatever template that run used —+ // the session metadata carries the merged prompt outright. Keeping the+ // current template active would wrap it a second time.+ promptTemplate: null,...(negativePrompt !== undefined? { negativePrompt, negativePromptEnabled: snapshot?.negativePromptEnabled ?? negativePrompt.length > 0 }: {}),diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.tsindex 02485ffdbb..8fb9f7f81d 100644--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts@@ -1,3 +1,4 @@+import type { GenerateSettings } from '@features/generation/contracts';import type {QueueBackendGraph,QueueCompiledSubmission,@@ -8,7 +9,7 @@ import type { CanvasStateContractV2 } from '@workbench/canvas-engine/api';import type { GraphContract } from '@workbench/graphContracts';import type { WidgetInstanceContract, WidgetInstanceId, WidgetStateMap } from '@workbench/widgetContracts';-import { normalizeGenerateSettings, sanitizeBatchCount } from '@features/generation/settings';+import { getEffectivePrompts, normalizeGenerateSettings, sanitizeBatchCount } from '@features/generation/settings';import { getUpscaleOutputDimensions, normalizeUpscaleWidgetValues } from '@features/upscale';import type { WorkbenchQueueItem, WorkbenchQueueState } from './queueHistoryContracts';@@ -159,6 +160,9 @@ const getFiniteDimension = (value: unknown, fallback: number): number =>const createInvalidSubmission = (message: string): QueueCompiledSubmission => ({ error: message, kind: 'invalid' });+const toPresentationSource = (settings: GenerateSettings | null): PresentationSource =>+ settings ? { ...settings, positivePrompt: getEffectivePrompts(settings).positivePrompt } : null;+const getBackendSubmission = (sourceId: QueueSourceId | null,snapshot: UnknownRecord,@@ -168,8 +172,10 @@ const getBackendSubmission = (const backendGraph = graph?.backendGraph;const generateCapture = getGenerateCapture(snapshot);const generateValues = getWidgetValues(widgetStates, 'generate');- const presentationSource = normalizeGenerateSettings(- sourceId === 'canvas' ? (generateCapture?.values ?? generateValues) : generateValues+ // Carries the merged prompt, so a rehydrated row reads the same as it will once+ // the backend session arrives with its own (already merged) field values.+ const presentationSource = toPresentationSource(+ normalizeGenerateSettings(sourceId === 'canvas' ? (generateCapture?.values ?? generateValues) : generateValues));if (!sourceId) {@@ -209,18 +215,23 @@ const getBackendSubmission = (};}+ // Re-deriving the submission has to reapply the prompt template, or a rehydrated+ // item that is retried would submit the bare authored text. The snapshot rides+ // in the persisted widget values, so this needs no catalog.+ const effectivePrompts = getEffectivePrompts(sourceSettings);+return {presentationSource: sourceId === 'upscale' ? null : sourceSettings,submission: {batchCount: sourceSettings.batchCount,graph: backendGraph,kind: 'generate',- negativePrompt: sourceSettings.negativePromptEnabled ? sourceSettings.negativePrompt : '',+ negativePrompt: sourceSettings.negativePromptEnabled ? effectivePrompts.negativePrompt : '',negativePromptNodeId:typeof generateCapture?.negativePromptNodeId === 'string'? generateCapture.negativePromptNodeId: 'negative_prompt',- positivePrompt: sourceSettings.positivePrompt,+ positivePrompt: effectivePrompts.positivePrompt,positivePromptNodeId:typeof generateCapture?.positivePromptNodeId === 'string'? generateCapture.positivePromptNodeIddiff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxindex 1284c6bcec..1b97a275ad 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx@@ -2,7 +2,12 @@ import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@woimport { Flex, Group, HStack, Icon, Menu, Portal, Separator, Stack, Text, VStack } from '@chakra-ui/react';import { flushGenerateDrafts, useDynamicPrompts, type DynamicPromptsExpansion } from '@features/generation/react';-import { sanitizeBatchCount, sanitizeDynamicPromptsConfig } from '@features/generation/settings';+import {+ getEffectivePrompts,+ normalizeGenerateSettings,+ sanitizeBatchCount,+ sanitizeDynamicPromptsConfig,+} from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';import { useInvocationTemplatesSelector } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';@@ -47,6 +52,17 @@ const readDynamicPromptsConfig = (values: Record<string, unknown>) => ({seedBehaviour: values.dynamicPromptsSeedBehaviour,});+/**+ * The prompt that will actually be expanded and submitted — the authored text+ * wrapped by the active template, since a template can introduce `{a|b}` the+ * authored prompt never had.+ */+const readEffectivePositivePrompt = (values: Record<string, unknown>): string => {+ const settings = normalizeGenerateSettings(values);++ return settings ? getEffectivePrompts(settings).positivePrompt : '';+};+const getBatchCount = (values: Record<string, unknown>): number => {const batchCount = values.batchCount;@@ -145,7 +161,7 @@ export const InvokeControl = () => {// 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 : '',+ readEffectivePositivePrompt(routeInput.generateValues),invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues)): nulldiff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 54e16d2dfa..442b6afc09 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1654,6 +1654,89 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).not.toHaveProperty('positivePrompts');});+ // The template is what introduced the `{…}` here, so the gate has to read the+ // merged prompt or the expansion would be discarded and the literal submitted.+ it('keeps an expansion whose dynamic syntax came from the prompt template', () => {+ const state = workbenchReducer(+ primeGenerate(undefined, {+ positivePrompt: 'a cat',+ promptTemplate: {+ id: 't1',+ name: 'Tinted',+ negativePrompt: '',+ positivePrompt: '{prompt}, {red|green} tint',+ },+ }),+ {+ backendSupportsCancellation: true,+ positivePrompts: ['a cat, red tint', 'a cat, green tint'],+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },+ type: 'submitResolvedInvocationSnapshot',+ }+ );++ expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).toMatchObject({+ positivePrompts: ['a cat, red tint', 'a cat, green tint'],+ });+ });+ });++ describe('prompt templates on the compiled submission', () => {+ const template = {+ id: 't1',+ name: 'Cinematic',+ negativePrompt: '{prompt}, lowres',+ positivePrompt: '{prompt}, cinematic',+ };++ it('submits the merged prompts while the widget keeps the authored text', () => {+ const state = submitGenerate(+ primeGenerate(undefined, {+ negativePrompt: 'blurry',+ negativePromptEnabled: true,+ positivePrompt: 'a cat',+ promptTemplate: template,+ })+ );+ const queueItem = getActiveProject(state).queue.items[0];++ expect(queueItem?.snapshot.backendSubmission).toMatchObject({+ negativePrompt: 'blurry, lowres',+ positivePrompt: 'a cat, cinematic',+ });+ expect(queueItem?.snapshot.widgetStates.generate.values.positivePrompt).toBe('a cat');+ });++ // Switching the negative field off must not let a template put one back.+ it('still sends an empty negative prompt when the field is disabled', () => {+ const state = submitGenerate(+ primeGenerate(undefined, {+ negativePrompt: 'blurry',+ negativePromptEnabled: false,+ positivePrompt: 'a cat',+ promptTemplate: template,+ })+ );++ expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).toMatchObject({+ negativePrompt: '',+ });+ });++ // Recall and the history popover both write straight back into the textarea,+ // so history has to hold what the user typed, not what generated.+ it('records the authored prompt in prompt history', () => {+ const state = submitGenerate(+ primeGenerate(undefined, {+ negativePrompt: 'blurry',+ negativePromptEnabled: true,+ positivePrompt: 'a cat',+ promptTemplate: template,+ })+ );++ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: 'blurry', positivePrompt: 'a cat' }]);+ });});it('records submitted Generate prompt pairs in project prompt history', () => {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex eacf3584b6..ddb22a52e4 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -71,6 +71,7 @@ import {addPromptHistoryItem,applyProjectPromptDraft,cloneGenerateWidgetValues,+ getEffectivePrompts,getGenerationModelAvailabilityReasons,getPromptDraftFromValues,getPromptHistoryItemFromGenerateSettings,@@ -2043,6 +2044,12 @@ const enqueueCompiledSnapshot = (: route.sourceId === 'upscale'? upscaleSettings: null;+ // The prompts that actually generate: the authored text wrapped by the active+ // prompt template. Computed once here because this is the only place every+ // Generate-shaped route converges — `generate` and `canvas` both land here, as+ // do the topbar, hotkey and graph-preview submits. Upscale carries no template+ // and merges to identity.+ const effectivePrompts = sourceGenerateSettings ? getEffectivePrompts(sourceGenerateSettings) : null;// Dynamic prompting is a Generate setting, so only the routes compiled from// GenerateSettings honour it; Upscale keeps its prompt literal. The caller has// already expanded, so the queue item records the exact prompts it will submit.@@ -2050,12 +2057,15 @@ const enqueueCompiledSnapshot = (// A one-prompt expansion counts: `a {red} cat` and a random sample of one both// resolve to a single concrete prompt, and dropping it here would fall the// submission back to the authored text — sending the literal `{…}` to the model.+ //+ // The gate reads the *merged* prompt: a template may introduce `{a|b}` that the+ // authored prompt never had, and the caller expanded the merged text too.const expandedPositivePrompts =route.sourceId !== 'upscale' &&compiled.positivePrompts &&compiled.positivePrompts.length > 0 &&- sourceGenerateSettings &&- hasDynamicPromptSyntax(sourceGenerateSettings.positivePrompt)+ effectivePrompts &&+ hasDynamicPromptSyntax(effectivePrompts.positivePrompt)? compiled.positivePrompts: undefined;const expandedSeedBehaviour = expandedPositivePrompts@@ -2069,14 +2079,17 @@ const enqueueCompiledSnapshot = (graph: backendGraph,kind: 'workflow',}- : sourceGenerateSettings+ : sourceGenerateSettings && effectivePrompts? {batchCount: sourceGenerateSettings.batchCount,graph: backendGraph,kind: 'generate',- negativePrompt: sourceGenerateSettings.negativePromptEnabled ? sourceGenerateSettings.negativePrompt : '',+ // A disabled negative prompt stays empty, which also suppresses the+ // template's negative side — switching the field off must not let a+ // template put one back.+ negativePrompt: sourceGenerateSettings.negativePromptEnabled ? effectivePrompts.negativePrompt : '',negativePromptNodeId: generate?.negativePromptNodeId ?? 'negative_prompt',- positivePrompt: sourceGenerateSettings.positivePrompt,+ positivePrompt: effectivePrompts.positivePrompt,positivePromptNodeId: generate?.positivePromptNodeId ?? 'positive_prompt',...(expandedPositivePrompts ? { positivePrompts: expandedPositivePrompts } : {}),seed: sourceGenerateSettings.seed,@@ -2113,7 +2126,9 @@ const enqueueCompiledSnapshot = (? 1: backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),height: presentationDimensions.height,- ...(sourceGenerateSettings?.positivePrompt ? { positivePrompt: sourceGenerateSettings.positivePrompt } : {}),+ // The merged prompt, so the queue row reads the same before and after the+ // backend session arrives with its own (already merged) field values.+ ...(effectivePrompts?.positivePrompt ? { positivePrompt: effectivePrompts.positivePrompt } : {}),width: presentationDimensions.width,},sourceId: route.sourceId,