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 prompt template merge policy
joshistoaste69d498d0b03
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 430f516a11..ca0749d64c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -564,6 +564,8 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): GeneratnegativePromptHeightPx: 56,positivePrompt: '',positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,qwen3EncoderModel: null,qwenVLEncoderModel: null,referenceImages: [],diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.tsnew file mode 100644index 0000000000..dae921dd54--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from 'vitest';++import {+ applyPromptTemplate,+ getEffectivePrompts,+ getPromptTemplateChunks,+ type PromptTemplateSnapshot,+ sanitizePromptTemplateSnapshot,+ syncPromptTemplateWithCatalog,+} from './promptTemplates';++const template = (overrides: Partial<PromptTemplateSnapshot> = {}): PromptTemplateSnapshot => ({+ id: 'template-1',+ name: 'Cinematic',+ negativePrompt: '',+ positivePrompt: '',+ ...overrides,+});++describe('applyPromptTemplate', () => {+ it('substitutes the authored prompt at the placeholder', () => {+ expect(applyPromptTemplate('{prompt}. photography, bokeh', 'a cat')).toBe('a cat. photography, bokeh');+ });++ it('appends after a single space when there is no placeholder', () => {+ expect(applyPromptTemplate('oil painting', 'a cat')).toBe('a cat oil painting');+ });++ // The legacy `String.replace` takes a string pattern, so only the first+ // placeholder is an insertion point. `getPromptTemplateChunks` has to agree.+ it('substitutes only the first of several placeholders', () => {+ expect(applyPromptTemplate('{prompt} in the style of {prompt}', 'a cat')).toBe('a cat in the style of {prompt}');+ });++ it('keeps the placeholder at either end of the template', () => {+ expect(applyPromptTemplate('{prompt}, 8k', 'a cat')).toBe('a cat, 8k');+ expect(applyPromptTemplate('a painting of {prompt}', 'a cat')).toBe('a painting of a cat');+ });++ // Whitespace is literal on both sides, including the leading space an empty+ // prompt produces. The legacy client emits exactly this, so a template written+ // there must render identically here.+ it('is whitespace-literal with an empty authored prompt', () => {+ expect(applyPromptTemplate('oil painting', '')).toBe(' oil painting');+ expect(applyPromptTemplate('{prompt}, 8k', '')).toBe(', 8k');+ });++ it('returns the authored prompt when the template is empty', () => {+ expect(applyPromptTemplate('', 'a cat')).toBe('a cat ');+ });+});++describe('getEffectivePrompts', () => {+ it('passes the authored prompts through when no template is active', () => {+ expect(getEffectivePrompts({ negativePrompt: 'blurry', positivePrompt: 'a cat', promptTemplate: null })).toEqual({+ negativePrompt: 'blurry',+ positivePrompt: 'a cat',+ });+ });++ it('merges the positive and negative sides independently', () => {+ expect(+ getEffectivePrompts({+ negativePrompt: 'blurry',+ positivePrompt: 'a cat',+ promptTemplate: template({ negativePrompt: '{prompt}, lowres', positivePrompt: '{prompt}, cinematic' }),+ })+ ).toEqual({ negativePrompt: 'blurry, lowres', positivePrompt: 'a cat, cinematic' });+ });++ // A template side left blank still appends its (empty) text, exactly as legacy+ // does — the trailing space is the observable consequence and is pinned here so+ // a "tidy up the whitespace" refactor has to be deliberate.+ it('appends an empty template side rather than skipping it', () => {+ expect(+ getEffectivePrompts({+ negativePrompt: 'blurry',+ positivePrompt: 'a cat',+ promptTemplate: template({ positivePrompt: 'cinematic' }),+ })+ ).toEqual({ negativePrompt: 'blurry ', positivePrompt: 'a cat cinematic' });+ });++ // The merged text is what the expansion gate sees, so a template may make an+ // otherwise-literal prompt dynamic. Guarding this here keeps the ordering+ // requirement visible next to the function that depends on it.+ it('can introduce dynamic syntax the authored prompt did not have', () => {+ expect(+ getEffectivePrompts({+ negativePrompt: '',+ positivePrompt: 'a cat',+ promptTemplate: template({ positivePrompt: '{prompt}, {red|green} tint' }),+ }).positivePrompt+ ).toBe('a cat, {red|green} tint');+ });+});++describe('getPromptTemplateChunks', () => {+ // Not `['', 'a cat', '']`: an empty template side still appends, so the middle+ // chunk carries the trailing space the merge produces.+ it('keeps the appended space when the template side is empty', () => {+ expect(getPromptTemplateChunks('a cat', '')).toEqual(['', 'a cat ', '']);+ });++ it('trails the template after the prompt when there is no placeholder', () => {+ expect(getPromptTemplateChunks('a cat', 'oil painting')).toEqual(['', 'a cat ', 'oil painting']);+ });++ it('splits around the placeholder', () => {+ expect(getPromptTemplateChunks('a cat', 'a photo of {prompt}, 8k')).toEqual(['a photo of ', 'a cat', ', 8k']);+ });++ it('rejoins later placeholders into the trailing chunk', () => {+ expect(getPromptTemplateChunks('a cat', '{prompt} by {prompt}')).toEqual(['', 'a cat', ' by {prompt}']);+ });++ // The chunks are only ever rendered, never submitted, so their concatenation+ // has to equal what `applyPromptTemplate` produces or the preview lies.+ it('concatenates to the merged prompt', () => {+ for (const templatePrompt of ['', 'oil painting', 'a photo of {prompt}, 8k', '{prompt} by {prompt}']) {+ expect(getPromptTemplateChunks('a cat', templatePrompt).join('')).toBe(+ applyPromptTemplate(templatePrompt, 'a cat')+ );+ }+ });+});++describe('sanitizePromptTemplateSnapshot', () => {+ it('reads a well-formed snapshot', () => {+ const snapshot = template({ negativePrompt: 'blurry', positivePrompt: '{prompt}, 8k' });++ expect(sanitizePromptTemplateSnapshot({ ...snapshot })).toEqual(snapshot);+ });++ it('defaults missing prompt sides to empty strings', () => {+ expect(sanitizePromptTemplateSnapshot({ id: 'a', name: 'A' })).toEqual({+ id: 'a',+ name: 'A',+ negativePrompt: '',+ positivePrompt: '',+ });+ });++ it('rejects values with no usable identity', () => {+ expect(sanitizePromptTemplateSnapshot(null)).toBeNull();+ expect(sanitizePromptTemplateSnapshot('template-1')).toBeNull();+ expect(sanitizePromptTemplateSnapshot([])).toBeNull();+ expect(sanitizePromptTemplateSnapshot({ id: '', name: 'A' })).toBeNull();+ expect(sanitizePromptTemplateSnapshot({ name: 'A' })).toBeNull();+ expect(sanitizePromptTemplateSnapshot({ id: 'a' })).toBeNull();+ });+});++describe('syncPromptTemplateWithCatalog', () => {+ it('picks up an upstream edit', () => {+ const stored = template({ positivePrompt: '{prompt}, cinematic' });+ const edited = template({ name: 'Cinematic v2', positivePrompt: '{prompt}, cinematic, 35mm' });++ expect(syncPromptTemplateWithCatalog(stored, [edited])).toBe(edited);+ });++ // The callers diff with `Object.is`, so an equal-but-new object each pass+ // would commit forever.+ it('returns the stored object by reference when nothing changed', () => {+ const stored = template({ positivePrompt: '{prompt}, cinematic' });++ expect(syncPromptTemplateWithCatalog(stored, [{ ...stored }])).toBe(stored);+ });++ // A catalog that is empty because it is still loading, or because another+ // user's template is not visible, must not silently change what generates.+ it('keeps a template the catalog does not carry', () => {+ const stored = template();++ expect(syncPromptTemplateWithCatalog(stored, [])).toBe(stored);+ expect(syncPromptTemplateWithCatalog(stored, [template({ id: 'other' })])).toBe(stored);+ });++ it('stays null when nothing is active', () => {+ expect(syncPromptTemplateWithCatalog(null, [template()])).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.tsnew file mode 100644index 0000000000..b0f6b9578d--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts@@ -0,0 +1,159 @@+/**+ * Prompt templates: named prompt fragments that wrap the authored prompt at+ * submit time.+ *+ * The authored prompt and the generated prompt are deliberately different+ * strings. The user edits and recalls what they typed; the model sees the+ * template's text with `{prompt}` replaced. `getEffectivePrompts` is the single+ * place that difference is computed, and every submit and preview path reads it+ * rather than merging inline.+ *+ * Order matters against dynamic prompts. `hasDynamicPromptSyntax` matches any+ * `{…}`, so an unmerged `{prompt}` would be handed to the expander and come back+ * as the literal word "prompt". Templates merge first, which consumes the+ * placeholder before the expander ever sees it — and lets a template carry its+ * own `{a|b}` or `__wildcard__` syntax.+ *+ * The active template is stored as a denormalized snapshot rather than an id, so+ * the pure submit reducer can resolve prompts with no catalog lookup and a queue+ * item still explains itself after its template is deleted.+ */++export const PROMPT_TEMPLATE_PLACEHOLDER = '{prompt}';++/** The active template, copied into GenerateSettings. */+export interface PromptTemplateSnapshot {+ id: string;+ name: string;+ negativePrompt: string;+ positivePrompt: string;+}++export interface EffectivePrompts {+ negativePrompt: string;+ positivePrompt: string;+}++interface AuthoredPrompts {+ negativePrompt: string;+ positivePrompt: string;+ /**+ * Optional so a surface with no template concept — Upscale, whose settings+ * carry no such field — can be passed straight through and merge to identity.+ */+ promptTemplate?: PromptTemplateSnapshot | null;+}++/**+ * Ported verbatim from the legacy `buildPresetModifiedPrompt` so a template+ * written in either client reads the same: the placeholder is substituted (first+ * occurrence only), and a template without one is appended after a space.+ */+export const applyPromptTemplate = (templatePrompt: string, prompt: string): string =>+ templatePrompt.includes(PROMPT_TEMPLATE_PLACEHOLDER)+ ? templatePrompt.replace(PROMPT_TEMPLATE_PLACEHOLDER, prompt)+ : `${prompt} ${templatePrompt}`;++/** The prompts that will actually generate. Identity when no template is active. */+export const getEffectivePrompts = (settings: AuthoredPrompts): EffectivePrompts => {+ const { negativePrompt, positivePrompt, promptTemplate } = settings;++ if (!promptTemplate) {+ return { negativePrompt, positivePrompt };+ }++ return {+ negativePrompt: applyPromptTemplate(promptTemplate.negativePrompt, negativePrompt),+ positivePrompt: applyPromptTemplate(promptTemplate.positivePrompt, positivePrompt),+ };+};++/**+ * The merged prompt split around the authored text, for the read-only view mode:+ * the outer chunks are the template's own words and are dimmed, the middle chunk+ * is what the user typed.+ *+ * A template with several placeholders only substitutes at the first, so the+ * rest are rejoined into the trailing chunk.+ *+ * The chunks must always concatenate to `applyPromptTemplate`'s output, or the+ * preview would describe something other than what generates. Legacy's+ * `getViewModeChunks` special-cases an empty template back to the bare prompt+ * and so disagrees by a trailing space; that divergence is not reproduced here.+ */+export const getPromptTemplateChunks = (prompt: string, templatePrompt: string): [string, string, string] => {+ if (!templatePrompt.includes(PROMPT_TEMPLATE_PLACEHOLDER)) {+ return ['', `${prompt} `, templatePrompt];+ }++ const [before, ...after] = templatePrompt.split(PROMPT_TEMPLATE_PLACEHOLDER);++ return [before ?? '', prompt, after.join(PROMPT_TEMPLATE_PLACEHOLDER)];+};++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++/**+ * True when a stored value is already exactly a snapshot, so normalization can+ * hand back the same object instead of allocating an equal one. `null` is not+ * canonical here — the caller distinguishes it before asking.+ */+export const isCanonicalPromptTemplateSnapshot = (value: unknown): value is PromptTemplateSnapshot =>+ isRecord(value) &&+ typeof value.id === 'string' &&+ value.id.length > 0 &&+ typeof value.name === 'string' &&+ typeof value.negativePrompt === 'string' &&+ typeof value.positivePrompt === 'string' &&+ Object.keys(value).length === 4;++/** Reads an untrusted persisted/transported snapshot, or `null` when unusable. */+export const sanitizePromptTemplateSnapshot = (value: unknown): PromptTemplateSnapshot | null => {+ if (!isRecord(value)) {+ return null;+ }++ const { id, name, negativePrompt, positivePrompt } = value;++ if (typeof id !== 'string' || !id || typeof name !== 'string') {+ return null;+ }++ return {+ id,+ name,+ negativePrompt: typeof negativePrompt === 'string' ? negativePrompt : '',+ positivePrompt: typeof positivePrompt === 'string' ? positivePrompt : '',+ };+};++const areSnapshotsEqual = (left: PromptTemplateSnapshot, right: PromptTemplateSnapshot): boolean =>+ left.id === right.id &&+ left.name === right.name &&+ left.negativePrompt === right.negativePrompt &&+ left.positivePrompt === right.positivePrompt;++/**+ * Re-reads the stored snapshot from the live catalog, the way model snapshots are+ * re-read in `syncGenerateWidgetValuesWithModels`, so an edit made in another tab+ * or by another client lands without a bespoke subscription.+ *+ * Returns the *existing* object whenever nothing changed. The caller diffs with+ * `Object.is`, so allocating an equal snapshot each pass would commit forever.+ * A template that has left the catalog is kept rather than cleared: it is still+ * the truthful record of what this project generates with, and dropping it would+ * silently change the prompt while the catalog is merely still loading.+ */+export const syncPromptTemplateWithCatalog = (+ promptTemplate: PromptTemplateSnapshot | null,+ catalog: readonly PromptTemplateSnapshot[]+): PromptTemplateSnapshot | null => {+ if (!promptTemplate) {+ return null;+ }++ const current = catalog.find((template) => template.id === promptTemplate.id);++ return current && !areSnapshotsEqual(current, promptTemplate) ? current : promptTemplate;+};diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex c969c3b306..0bd142e391 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -17,6 +17,7 @@ import type {import { sanitizeBatchCount } from './batch';import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';import { isDynamicPromptsSeedBehaviour, sanitizeMaxPrompts, sanitizeSampleSeed } from './dynamicPrompts';+import { isCanonicalPromptTemplateSnapshot, sanitizePromptTemplateSnapshot } from './promptTemplates';import { cloneCroppableImage, isCanonicalCroppableImage, normalizeCroppableImage } from './referenceImage';/** Preset ratios, with the preset to switch to when dimensions are swapped. */@@ -385,6 +386,7 @@ export const cloneGenerateWidgetValues = (componentSourceModel: values.componentSourceModel ? { ...values.componentSourceModel } : null,loras: values.loras.map((lora) => ({ ...lora, model: { ...lora.model } })),model: { ...values.model },+ promptTemplate: values.promptTemplate ? { ...values.promptTemplate } : null,qwen3EncoderModel: values.qwen3EncoderModel ? { ...values.qwen3EncoderModel } : null,qwenVLEncoderModel: values.qwenVLEncoderModel ? { ...values.qwenVLEncoderModel } : null,referenceImages: cloneReferenceImages(values.referenceImages),@@ -583,6 +585,14 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | nMAX_POSITIVE_PROMPT_HEIGHT_PX,DEFAULT_POSITIVE_PROMPT_HEIGHT_PX),+ // Reuse the stored object when it is already canonical. Callers diff settings+ // with `Object.is`, so re-sanitizing into a fresh object every pass would make+ // every commit look like a template change and loop the sync in+ // `GenerateWidgetView`.+ promptTemplate: isCanonicalPromptTemplateSnapshot(values.promptTemplate)+ ? values.promptTemplate+ : sanitizePromptTemplateSnapshot(values.promptTemplate),+ promptTemplateViewMode: typeof values.promptTemplateViewMode === 'boolean' ? values.promptTemplateViewMode : false,referenceImages: normalizeReferenceImages(values.referenceImages),scheduler: values.scheduler as string,seamlessXAxis: typeof values.seamlessXAxis === 'boolean' ? values.seamlessXAxis : false,@@ -635,6 +645,8 @@ export const isGenerateSettings = (values: unknown): values is GenerateSettingsArray.isArray(values.referenceImages) &&normalizeReferenceImages(values.referenceImages).length === values.referenceImages.length &&areReferenceImagesCanonical(values.referenceImages) &&+ (values.promptTemplate === null || isCanonicalPromptTemplateSnapshot(values.promptTemplate)) &&+ typeof values.promptTemplateViewMode === 'boolean' &&typeof values.seamlessXAxis === 'boolean' &&typeof values.seamlessYAxis === 'boolean' &&isVaePrecision(values.vaePrecision) &&diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex 054072357d..10b121b614 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -1,5 +1,6 @@import type { BackendGraphContract, GraphContract } from '@features/generation/core/contracts';import type { DynamicPromptsSeedBehaviour } from '@features/generation/core/dynamicPrompts';+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';export type ModelIdentifierConfig = {key: string;@@ -157,6 +158,14 @@ export interface GenerateSettings {negativePromptEnabled: boolean;negativePrompt: string;negativePromptHeightPx: number;+ /**+ * The active prompt template, copied rather than referenced by id so the pure+ * submit reducer can resolve prompts with no catalog lookup. See+ * `core/promptTemplates.ts`.+ */+ promptTemplate: PromptTemplateSnapshot | null;+ /** Show the merged prompt read-only instead of the authored text. */+ promptTemplateViewMode: boolean;/** Expand `{a|b}` into every combination; otherwise draw a random sample. */dynamicPromptsCombinatorial: boolean;/** Upper bound on expanded prompts (the sample size when not combinatorial). */diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 3e6f633b18..9ac0c6050f 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -63,6 +63,7 @@ export {type DynamicPromptsConfig,type DynamicPromptsSeedBehaviour,} from './core/dynamicPrompts';+export { getEffectivePrompts } from './core/promptTemplates';export {addPromptHistoryItem,getPromptHistoryItemFromGenerateSettings,diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex 10f453b5d9..8d20f550ad 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -67,6 +67,9 @@ const addUpscaleMetadata = (modelKey: settings.model.key,negativePromptHeightPx: 56,positivePromptHeightPx: 96,+ // Upscale submits its prompt literally, so no template is applied here.+ promptTemplate: null,+ promptTemplateViewMode: false,referenceImages: [],seamlessXAxis: false,seamlessYAxis: false,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex 7f33df743e..68f484dec5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -85,6 +85,8 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])negativePromptHeightPx: 56,positivePrompt: '',positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,qwen3EncoderModel: null,qwenVLEncoderModel: null,referenceImages: [],diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex f4909cc88f..144d915486 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -55,6 +55,8 @@ const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWinegativePromptHeightPx: 56,positivePrompt: '',positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,qwen3EncoderModel: null,qwenVLEncoderModel: null,referenceImages: [],diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 51dc601a09..54e16d2dfa 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -155,6 +155,8 @@ const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenegativePromptHeightPx: 56,positivePrompt: 'first prompt',positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,qwen3EncoderModel: null,qwenVLEncoderModel: null,referenceImages: [],@@ -1651,6 +1653,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).not.toHaveProperty('positivePrompts');});+});it('records submitted Generate prompt pairs in project prompt history', () => {