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.

fix: normalize prompt template view state

joshistoastd684fc2840b6
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
index 29b353ad6d..87fc1834ab 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
@@ -20,6 +20,7 @@ describe('hasDynamicPromptSyntax', () => {
it('detects a wildcard reference', () => {
expect(hasDynamicPromptSyntax('a __colors__ ball')).toBe(true);
+ expect(hasDynamicPromptSyntax('prefix__name__')).toBe(true);
expect(hasDynamicPromptSyntax('a __animals/dogs__ ball')).toBe(true);
expect(hasDynamicPromptSyntax('a __artists/*__ ball')).toBe(true);
expect(hasDynamicPromptSyntax('a __~colors__ ball')).toBe(true);
@@ -44,6 +45,13 @@ describe('hasDynamicPromptSyntax', () => {
});
describe('scanWildcardReferences', () => {
+ it('recognizes references adjacent to a word and preserves their exact ranges', () => {
+ expect(scanWildcardReferences('prefix__name__')).toEqual([{ lookupPath: 'name', range: { end: 14, start: 6 } }]);
+ expect(scanWildcardReferences('snake__case__ word')).toEqual([
+ { lookupPath: 'case', range: { end: 13, start: 5 } },
+ ]);
+ });
+
it('returns the full range and lookup path for sampler overrides and parameters', () => {
const prompt = 'a __~outfit(mood=warm)__ beside __animals/[dc]ogs__';
@@ -64,6 +72,12 @@ describe('scanWildcardReferences', () => {
{ lookupPath: 'valid', range: { end: 25, start: 16 } },
]);
});
+
+ it('leaves incomplete, malformed, and overlength tokens alone', () => {
+ expect(scanWildcardReferences('snake__case')).toEqual([]);
+ expect(scanWildcardReferences('__not a name__')).toEqual([]);
+ expect(scanWildcardReferences(`__${'x'.repeat(129)}__`)).toEqual([]);
+ });
});
describe('sanitizeMaxPrompts', () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
index 7bed53913c..185e47b96f 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
@@ -50,8 +50,9 @@ export interface WildcardReference {
const WILDCARD_GLOB_CHARACTER_RE = /[*?[]/;
const WILDCARD_REFERENCE_PATH_RE = /^[A-Za-z0-9_/*?[\]!-]+$/;
-const isWildcardBoundaryCharacter = (character: string | undefined): boolean =>
- character !== undefined && /[A-Za-z0-9_]/.test(character);
+
+/** Mirrors the backend's `MAX_WILDCARD_NAME_LENGTH`. */
+export const MAX_WILDCARD_NAME_LENGTH = 128;
const getWildcardLookupPath = (content: string): string | null => {
const withoutSampler = content[0] === '~' || content[0] === '@' ? content.slice(1) : content;
@@ -72,7 +73,7 @@ const getWildcardLookupPath = (content: string): string | null => {
return null;
}
- if (!lookupPath || !WILDCARD_REFERENCE_PATH_RE.test(lookupPath)) {
+ if (!lookupPath || lookupPath.length > MAX_WILDCARD_NAME_LENGTH || !WILDCARD_REFERENCE_PATH_RE.test(lookupPath)) {
return null;
}
@@ -85,7 +86,7 @@ export const scanWildcardReferences = (prompt: string): WildcardReference[] => {
let index = 0;
while (index < prompt.length - 1) {
- if (prompt[index] !== '_' || prompt[index + 1] !== '_' || isWildcardBoundaryCharacter(prompt[index - 1])) {
+ if (prompt[index] !== '_' || prompt[index + 1] !== '_') {
index++;
continue;
}
@@ -267,9 +268,6 @@ export const matchesKnownWildcard = (path: string, knownNames: ReadonlySet<strin
return false;
};
-/** Mirrors the backend's `MAX_WILDCARD_NAME_LENGTH`. */
-export const MAX_WILDCARD_NAME_LENGTH = 128;
-
/**
* The backend's bounds on a values list, mirrored here so both ways of writing
* one can say what is wrong before sending it.
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
index b7395bc9ce..5f38e39b12 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
@@ -42,6 +42,34 @@ const legacyStoredValues = {
};
describe('normalizeGenerateSettings', () => {
+ it('enforces template view mode only when a valid template remains', () => {
+ const validTemplate = {
+ id: 'template-1',
+ name: 'Cinematic',
+ negativePrompt: '',
+ positivePrompt: '{prompt}, cinematic',
+ };
+
+ expect(
+ normalizeGenerateSettings({ ...legacyStoredValues, promptTemplate: null, promptTemplateViewMode: true })
+ ?.promptTemplateViewMode
+ ).toBe(false);
+ expect(
+ normalizeGenerateSettings({
+ ...legacyStoredValues,
+ promptTemplate: { id: '', name: 'Broken' },
+ promptTemplateViewMode: true,
+ })?.promptTemplateViewMode
+ ).toBe(false);
+ expect(
+ normalizeGenerateSettings({ ...legacyStoredValues, promptTemplate: validTemplate, promptTemplateViewMode: true })
+ ?.promptTemplateViewMode
+ ).toBe(true);
+ expect(isGenerateSettings({ ...legacyStoredValues, promptTemplate: null, promptTemplateViewMode: true })).toBe(
+ false
+ );
+ });
+
it('normalizes persisted reference images and drops invalid entries', () => {
const normalized = normalizeGenerateSettings({
...legacyStoredValues,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index 550afc42eb..96a662c678 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -568,6 +568,10 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n
const width = values.width as number;
const height = values.height as number;
+ const promptTemplate = isCanonicalPromptTemplateSnapshot(values.promptTemplate)
+ ? values.promptTemplate
+ : sanitizePromptTemplateSnapshot(values.promptTemplate);
+
return {
aspectRatioId: isAspectRatioId(values.aspectRatioId) ? values.aspectRatioId : deriveAspectRatioId(width, height),
aspectRatioIsLocked: typeof values.aspectRatioIsLocked === 'boolean' ? values.aspectRatioIsLocked : false,
@@ -613,10 +617,8 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n
// 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,
+ promptTemplate,
+ promptTemplateViewMode: promptTemplate !== null && values.promptTemplateViewMode === true,
referenceImages: normalizeReferenceImages(values.referenceImages),
scheduler: values.scheduler as string,
seamlessXAxis: typeof values.seamlessXAxis === 'boolean' ? values.seamlessXAxis : false,
@@ -671,6 +673,7 @@ export const isGenerateSettings = (values: unknown): values is GenerateSettings
areReferenceImagesCanonical(values.referenceImages) &&
(values.promptTemplate === null || isCanonicalPromptTemplateSnapshot(values.promptTemplate)) &&
typeof values.promptTemplateViewMode === 'boolean' &&
+ (values.promptTemplate !== null || values.promptTemplateViewMode === false) &&
typeof values.seamlessXAxis === 'boolean' &&
typeof values.seamlessYAxis === 'boolean' &&
isVaePrecision(values.vaePrecision) &&
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx
index 38622d7fb6..19694b13c2 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx
@@ -93,6 +93,9 @@ describe('the negative prompt in template view mode', () => {
expect(textarea.readOnly).toBe(false);
expect(textarea.value).toBe('blurry');
+ expect(host!.querySelector<HTMLButtonElement>('[aria-label="widgets.generate.addPromptTrigger"]')?.disabled).toBe(
+ false
+ );
});
});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
index 528a234e08..b2e469d33f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx
@@ -150,7 +150,7 @@ export const NegativePromptField = ({
<HStack gap="0.5">
{isEnabled ? (
<AddPromptTriggerButton
- isOpen={triggerPicker.isOpen || isTemplateViewMode}
+ isOpen={triggerPicker.isOpen || isViewingMerged}
onOpenPromptTriggerPicker={triggerPicker.open}
/>
) : null}
@@ -168,7 +168,7 @@ export const NegativePromptField = ({
</Switch.Root>
</HStack>
),
- [enableSwitchInputId, handleEnabledChange, isEnabled, isTemplateViewMode, t, triggerPicker]
+ [enableSwitchInputId, handleEnabledChange, isEnabled, isViewingMerged, t, triggerPicker]
);
const templateChunks = useMemo(
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
new file mode 100644
index 0000000000..537bced78d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
@@ -0,0 +1,72 @@
+/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop */
+import { ChakraProvider } from '@chakra-ui/react';
+import { PositivePromptField } from '@features/generation/ui/promptFields/PositivePromptField';
+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, expect, it, vi } from 'vitest';
+
+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useGenerationUi: () => ({
+ gallery: { selectedImage: null },
+ models: { catalog: [], ensureLoaded: vi.fn() },
+ notifications: { reportError: vi.fn() },
+ project: { activeProjectId: 'project-1' },
+ promptHistory: { clear: vi.fn(), items: [] },
+ }),
+}));
+
+vi.mock('@features/generation/data/wildcards', () => ({
+ createWildcard: vi.fn(),
+ deleteWildcard: vi.fn(),
+ invalidateWildcardDependents: vi.fn(),
+ updateWildcard: vi.fn(),
+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),
+}));
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+it('keeps positive prompt actions enabled when stale view mode has no active template', async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <ChakraProvider value={system}>
+ <PositivePromptField
+ heightPx={96}
+ isTemplateViewMode
+ loras={[]}
+ projectId="project-1"
+ selectedModel={undefined}
+ showSyntaxHighlighting={false}
+ value="a cat"
+ onChange={vi.fn()}
+ onResizeEnd={vi.fn()}
+ onUsePrompt={vi.fn()}
+ />
+ </ChakraProvider>
+ </QueryClientProvider>
+ );
+ });
+
+ expect(host.querySelector('textarea')?.readOnly).toBe(false);
+ expect(host.querySelector<HTMLButtonElement>('[aria-label="widgets.generate.addPromptTrigger"]')?.disabled).toBe(
+ false
+ );
+ expect(host.querySelector<HTMLButtonElement>('[aria-label="widgets.generate.expandPrompt"]')?.disabled).toBe(false);
+ expect(host.querySelector<HTMLButtonElement>('[aria-label="widgets.generate.imageToPrompt"]')?.disabled).toBe(false);
+});
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 605c842db3..02a86f5e4b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -181,12 +181,12 @@ export const PositivePromptField = ({
const templateState = useMemo(
(): PromptTemplateState => ({
active: promptTemplate,
- isViewMode: isTemplateViewMode,
+ isViewMode: isViewingMerged,
onApply: onApplyPromptTemplate,
onFlatten: flattenPromptTemplate,
onViewModeChange: onTemplateViewModeChange,
}),
- [flattenPromptTemplate, isTemplateViewMode, onApplyPromptTemplate, onTemplateViewModeChange, promptTemplate]
+ [flattenPromptTemplate, isViewingMerged, onApplyPromptTemplate, onTemplateViewModeChange, promptTemplate]
);
const labelEnd = useMemo(
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts
index f3b671b699..e6d2faeee6 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.test.ts
@@ -30,6 +30,10 @@ describe('getActiveTriggerQuery', () => {
expect(query('a photo of __')).toEqual({ key: '_', query: '', range: { end: 13, start: 11 } });
});
+ it('opens for a wildcard trigger adjacent to a word character', () => {
+ expect(query('prefix__')).toEqual({ key: '_', query: '', range: { end: 8, start: 6 } });
+ });
+
it('narrows as the name is typed', () => {
expect(query('a photo of __col')).toEqual({ key: '_', query: 'col', range: { end: 16, start: 11 } });
});
@@ -46,6 +50,7 @@ describe('getActiveTriggerQuery', () => {
it('stays shut after a closed reference', () => {
expect(query('a __colours__')).toBeNull();
expect(query('a <embedding>')).toBeNull();
+ expect(query('prefix__name__')).toBeNull();
});
it('stays shut inside an ordinary word', () => {
@@ -91,6 +96,10 @@ describe('getActiveTriggerQuery', () => {
expect(query(`a __${maximum}x`)).toBeNull();
});
+ it('stays shut for malformed wildcard attempts', () => {
+ expect(query('a __not a name')).toBeNull();
+ });
+
it('honours the keys the field answers to', () => {
expect(query('a __col', ['<'])).toBeNull();
expect(query('a <emb', ['_'])).toBeNull();
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 cf67e4b6bc..10ada10291 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts
@@ -77,10 +77,6 @@ export const insertPositivePromptText = ({
/** Which trigger keys a field answers to. Wildcards only exist on the positive prompt. */
export type PromptTriggerKey = '<' | '_';
-/** `_` is a word character, so `snake__case` must not read as the start of a reference. */
-const isWordCharacter = (character: string | undefined): boolean =>
- character !== undefined && /[A-Za-z0-9_]/.test(character);
-
export interface PromptTriggerQuery {
key: PromptTriggerKey;
/** What has been typed since the trigger, for narrowing the list. */
@@ -114,6 +110,22 @@ export const getActiveTriggerQuery = (
caret: number,
keys: readonly PromptTriggerKey[]
): PromptTriggerQuery | null => {
+ // At a closing `__`, the backwards scan reaches that pair before its opening
+ // pair. Treat a non-empty delimited span as finished even when its content is
+ // malformed: autocomplete must not reopen over text the user has already
+ // closed.
+ const closingStart = caret - 2;
+ const openingStart = value.lastIndexOf('__', closingStart - 1);
+
+ if (
+ keys.includes('_') &&
+ value.slice(closingStart, caret) === '__' &&
+ openingStart >= 0 &&
+ openingStart + 2 < closingStart
+ ) {
+ return null;
+ }
+
const limit = Math.max(0, caret - MAX_TRIGGER_QUERY_LENGTH);
for (let index = caret - 1; index >= limit; index--) {
@@ -136,7 +148,7 @@ export const getActiveTriggerQuery = (
return keys.includes('<') ? findEnclosingEmbedding(value, caret, limit, index) : null;
}
- if (char === '_' && value[index - 1] === '_' && keys.includes('_') && !isWordCharacter(value[index - 2])) {
+ if (char === '_' && value[index - 1] === '_' && keys.includes('_')) {
const query = value.slice(index + 1, caret);
// `__colours__` with the caret after it: the scan reached the *opening*
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index 144d915486..fe5aeeee22 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -102,6 +102,60 @@ const metadata = {
};
describe('image recall', () => {
+ it.each(['all', 'remix', 'prompts'] as const)(
+ 'clears the active template and view mode when %s recalls prompt metadata',
+ (kind) => {
+ const result = buildImageRecallSettings({
+ currentValues: createValues({
+ promptTemplate: {
+ id: 'template-1',
+ name: 'Cinematic',
+ negativePrompt: 'lowres',
+ positivePrompt: '{prompt}, cinematic',
+ },
+ promptTemplateViewMode: true,
+ }),
+ image,
+ kind,
+ metadata: { positive_prompt: 'a recalled prompt' },
+ models: [],
+ supportedModels: [],
+ vaeModels: [],
+ });
+
+ expect(result?.values.promptTemplate).toBeNull();
+ expect(result?.values.promptTemplateViewMode).toBe(false);
+ }
+ );
+
+ it.each(['seed', 'dimensions', 'clipSkip'] as const)(
+ 'preserves the active template and view mode when %s has no prompt metadata',
+ (kind) => {
+ const currentValues = createValues({
+ ...(kind === 'clipSkip' ? { model: sd1Model, modelKey: sd1Model.key } : {}),
+ promptTemplate: {
+ id: 'template-1',
+ name: 'Cinematic',
+ negativePrompt: 'lowres',
+ positivePrompt: '{prompt}, cinematic',
+ },
+ promptTemplateViewMode: true,
+ });
+ const result = buildImageRecallSettings({
+ currentValues,
+ image,
+ kind,
+ metadata: kind === 'seed' ? { seed: 42 } : kind === 'clipSkip' ? { clip_skip: 1 } : null,
+ models: [],
+ supportedModels: [],
+ vaeModels: [],
+ });
+
+ expect(result?.values.promptTemplate).toEqual(currentValues.promptTemplate);
+ expect(result?.values.promptTemplateViewMode).toBe(true);
+ }
+ );
+
it('recalls supported image metadata into generate settings', () => {
const result = buildImageRecallSettings({
currentValues: createValues(),
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
index b3031b2acd..e50ae8f062 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
@@ -283,7 +283,9 @@ const getMetadataVae = (
const getPromptPatch = (
metadata: unknown
-): Partial<Pick<GenerateWidgetValues, 'negativePrompt' | 'positivePrompt' | 'promptTemplate'>> => {
+): Partial<
+ Pick<GenerateWidgetValues, 'negativePrompt' | 'positivePrompt' | 'promptTemplate' | 'promptTemplateViewMode'>
+> => {
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
@@ -294,7 +296,7 @@ const getPromptPatch = (
return {
...(positivePrompt !== null ? { positivePrompt } : {}),
...(negativePrompt !== undefined ? { negativePrompt: negativePrompt ?? '' } : {}),
- ...(clearTemplate ? { promptTemplate: null } : {}),
+ ...(clearTemplate ? { promptTemplate: null, promptTemplateViewMode: false } : {}),
};
};