Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): fold wildcards into the dynamic prompting flow

joshistoast65d619dffff5
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index b05702f3be..f6149a97b8 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -39,22 +39,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 19,
"scriptRawBytes": 1453501,
"scriptRequestCount": 15,
- "totalRawBytes": 1568596
+ "totalRawBytes": 1569173
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 19,
"scriptRawBytes": 1468037,
"scriptRequestCount": 15,
- "totalRawBytes": 1584282
+ "totalRawBytes": 1584859
},
"routeReadyMedianMs": 227.19999999925494,
"scriptSourceOwnerSet": "launchpad-static",
@@ -97,22 +97,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 19,
"scriptRawBytes": 1453501,
"scriptRequestCount": 15,
- "totalRawBytes": 1568596
+ "totalRawBytes": 1569173
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 19,
"scriptRawBytes": 1468037,
"scriptRequestCount": 15,
- "totalRawBytes": 1584282
+ "totalRawBytes": 1584859
},
"routeReadyMedianMs": 278.8999999985099,
"scriptSourceOwnerSet": "launchpad-static",
@@ -155,22 +155,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 95,
"scriptRawBytes": 2920198,
"scriptRequestCount": 89,
- "totalRawBytes": 3207082
+ "totalRawBytes": 3207659
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 95,
"scriptRawBytes": 2949400,
"scriptRequestCount": 89,
- "totalRawBytes": 3239153
+ "totalRawBytes": 3239730
},
"routeReadyMedianMs": 614.6999999992549,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -213,22 +213,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 95,
"scriptRawBytes": 2920198,
"scriptRequestCount": 89,
- "totalRawBytes": 3207082
+ "totalRawBytes": 3207659
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 95,
"scriptRawBytes": 2949400,
"scriptRequestCount": 89,
- "totalRawBytes": 3239153
+ "totalRawBytes": 3239730
},
"routeReadyMedianMs": 663.1999999992549,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -271,22 +271,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 99,
"scriptRawBytes": 3196397,
"scriptRequestCount": 93,
- "totalRawBytes": 3483281
+ "totalRawBytes": 3483858
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 99,
"scriptRawBytes": 3228361,
"scriptRequestCount": 93,
- "totalRawBytes": 3518114
+ "totalRawBytes": 3518691
},
"routeReadyMedianMs": 767.3000000007451,
"scriptSourceOwnerSet": "editor-canvas-static",
@@ -329,22 +329,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 99,
"scriptRawBytes": 3196397,
"scriptRequestCount": 93,
- "totalRawBytes": 3483281
+ "totalRawBytes": 3483858
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 99,
"scriptRawBytes": 3228361,
"scriptRequestCount": 93,
- "totalRawBytes": 3518114
+ "totalRawBytes": 3518691
},
"routeReadyMedianMs": 1164.4000000003725,
"scriptSourceOwnerSet": "editor-canvas-static",
@@ -387,22 +387,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 95,
"scriptRawBytes": 2920198,
"scriptRequestCount": 89,
- "totalRawBytes": 3207082
+ "totalRawBytes": 3207659
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 95,
"scriptRawBytes": 2949400,
"scriptRequestCount": 89,
- "totalRawBytes": 3239153
+ "totalRawBytes": 3239730
},
"routeReadyMedianMs": 750.6999999992549,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -445,22 +445,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 95,
"scriptRawBytes": 2920198,
"scriptRequestCount": 89,
- "totalRawBytes": 3207082
+ "totalRawBytes": 3207659
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 95,
"scriptRawBytes": 2949400,
"scriptRequestCount": 89,
- "totalRawBytes": 3239153
+ "totalRawBytes": 3239730
},
"routeReadyMedianMs": 977.9000000003725,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -503,22 +503,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 95,
"scriptRawBytes": 2920198,
"scriptRequestCount": 89,
- "totalRawBytes": 3207082
+ "totalRawBytes": 3207659
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 95,
"scriptRawBytes": 2949400,
"scriptRequestCount": 89,
- "totalRawBytes": 3239153
+ "totalRawBytes": 3239730
},
"routeReadyMedianMs": 708.5,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -561,22 +561,22 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89272,
+ "otherRawBytes": 89849,
"requestCount": 95,
"scriptRawBytes": 2920198,
"scriptRequestCount": 89,
- "totalRawBytes": 3207082
+ "totalRawBytes": 3207659
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90165,
+ "otherRawBytes": 90742,
"requestCount": 95,
"scriptRawBytes": 2949400,
"scriptRequestCount": 89,
- "totalRawBytes": 3239153
+ "totalRawBytes": 3239730
},
"routeReadyMedianMs": 857,
"scriptSourceOwnerSet": "editor-minimal-static",
@@ -1004,6 +1004,7 @@
"source:src/features/generation/data/dynamicPromptsQueries.ts",
"source:src/features/generation/data/promptUtilities.ts",
"source:src/features/generation/data/referenceImageUrls.ts",
+ "source:src/features/generation/data/wildcards.ts",
"source:src/features/generation/graph.ts",
"source:src/features/generation/prompts.ts",
"source:src/features/generation/react.ts",
@@ -1028,6 +1029,7 @@
"source:src/features/generation/ui/promptFields/PositivePromptActions.tsx",
"source:src/features/generation/ui/promptFields/PositivePromptField.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
+ "source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
"source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts",
"source:src/features/generation/ui/promptFields/promptFocus.ts",
@@ -1044,6 +1046,7 @@
"source:src/features/generation/ui/shared/modelDefaultSettings.ts",
"source:src/features/generation/ui/useDebouncedDraftValue.ts",
"source:src/features/generation/ui/useDynamicPrompts.ts",
+ "source:src/features/generation/ui/useWildcards.ts",
"source:src/features/generation/widget.ts",
"source:src/features/identity/capabilities.ts",
"source:src/features/identity/core/schemas.ts",
@@ -1782,6 +1785,7 @@
"source:src/features/generation/data/dynamicPromptsQueries.ts",
"source:src/features/generation/data/promptUtilities.ts",
"source:src/features/generation/data/referenceImageUrls.ts",
+ "source:src/features/generation/data/wildcards.ts",
"source:src/features/generation/graph.ts",
"source:src/features/generation/prompts.ts",
"source:src/features/generation/react.ts",
@@ -1806,6 +1810,7 @@
"source:src/features/generation/ui/promptFields/PositivePromptActions.tsx",
"source:src/features/generation/ui/promptFields/PositivePromptField.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
+ "source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
"source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts",
"source:src/features/generation/ui/promptFields/promptFocus.ts",
@@ -1822,6 +1827,7 @@
"source:src/features/generation/ui/shared/modelDefaultSettings.ts",
"source:src/features/generation/ui/useDebouncedDraftValue.ts",
"source:src/features/generation/ui/useDynamicPrompts.ts",
+ "source:src/features/generation/ui/useWildcards.ts",
"source:src/features/generation/widget.ts",
"source:src/features/identity/capabilities.ts",
"source:src/features/identity/core/schemas.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 1669d03ffa..cc4b392563 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -962,7 +962,19 @@
"promptsPreview": "Prompts preview",
"usePrompt": "Use this prompt",
"andMore": "and {{count}} more",
- "problemGeneratingPrompts": "Could not expand this prompt"
+ "problemGeneratingPrompts": "Could not expand this prompt",
+ "preview": "Preview",
+ "wildcards": "Wildcards",
+ "newWildcard": "New wildcard",
+ "editWildcard": "Edit wildcard",
+ "wildcardName": "Name",
+ "wildcardNamePlaceholder": "colors",
+ "wildcardValues": "Values",
+ "wildcardValuesPlaceholder": "One value per line",
+ "wildcardHasNoValues": "No values yet",
+ "noWildcardsYet": "No wildcards yet. Create one to reuse a list of values as __name__.",
+ "insertWildcard": "Insert into the prompt",
+ "couldNotSaveWildcard": "Could not save this wildcard"
}
},
"upscale": {
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index ac7b272b16..37d9d5470e 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -448,6 +448,10 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, []);
}
+ if (method === 'GET' && (path === '/api/v1/wildcards' || path === '/api/v1/wildcards/')) {
+ 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.
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 1eba21111b..a778617ec4 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { hasDynamicPromptSyntax, sanitizeDynamicPromptsConfig, sanitizeMaxPrompts } from './dynamicPrompts';
+import {
+ findWildcardReferences,
+ hasDynamicPromptSyntax,
+ sanitizeDynamicPromptsConfig,
+ sanitizeMaxPrompts,
+} from './dynamicPrompts';
describe('hasDynamicPromptSyntax', () => {
it('detects a variant anywhere in the prompt', () => {
@@ -9,10 +14,30 @@ describe('hasDynamicPromptSyntax', () => {
expect(hasDynamicPromptSyntax('multi\nline {a|b}')).toBe(true);
});
- it('ignores prompts with no braces, including bare wildcards', () => {
+ it('detects a wildcard reference', () => {
+ expect(hasDynamicPromptSyntax('a __colors__ ball')).toBe(true);
+ expect(hasDynamicPromptSyntax('a __animals/dogs__ ball')).toBe(true);
+ });
+
+ it('ignores prompts with neither a variant nor a wildcard', () => {
expect(hasDynamicPromptSyntax('a red ball')).toBe(false);
- expect(hasDynamicPromptSyntax('a __color__ ball')).toBe(false);
expect(hasDynamicPromptSyntax('unclosed { brace')).toBe(false);
+ // Not a reference: a name may not start or end with an underscore, so this
+ // cannot round-trip through the `__` delimiters.
+ expect(hasDynamicPromptSyntax('snake__case word')).toBe(false);
+ });
+});
+
+describe('findWildcardReferences', () => {
+ it('collects each referenced name once, in order', () => {
+ expect(findWildcardReferences('a __colors__ __animals/dogs__ and __colors__ again')).toEqual([
+ 'colors',
+ 'animals/dogs',
+ ]);
+ });
+
+ it('returns nothing for a prompt with no references', () => {
+ expect(findWildcardReferences('a {red|green} ball')).toEqual([]);
});
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
index 09728f3598..f0352bef3f 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
@@ -32,14 +32,31 @@ export interface DynamicPromptsConfig {
seedBehaviour: DynamicPromptsSeedBehaviour;
}
+/** `__name__`, the reference form for a wildcard. Mirrors the backend's name rule. */
+export const WILDCARD_REFERENCE_RE =
+ /__([A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?(?:\/[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?)*)__/;
+
/**
* Whether a prompt is worth sending to the expansion route at all. A prompt with
- * no `{…}` is its own single expansion, so the round trip is skipped entirely.
- *
- * Deliberately does not look for `__wildcard__`: this deployment runs an
- * unconfigured `WildcardManager`, so wildcards never resolve.
+ * neither a `{…}` variant nor a `__wildcard__` reference is its own single
+ * expansion, so the round trip is skipped entirely.
*/
-export const hasDynamicPromptSyntax = (prompt: string): boolean => /\{[\s\S]*\}/.test(prompt);
+export const hasDynamicPromptSyntax = (prompt: string): boolean =>
+ /\{[\s\S]*\}/.test(prompt) || WILDCARD_REFERENCE_RE.test(prompt);
+
+/** The wildcard names a prompt references, in order of first appearance. */
+export const findWildcardReferences = (prompt: string): string[] => {
+ const pattern = new RegExp(WILDCARD_REFERENCE_RE, 'g');
+ const names: string[] = [];
+
+ for (let match = pattern.exec(prompt); match; match = pattern.exec(prompt)) {
+ if (!names.includes(match[1])) {
+ names.push(match[1]);
+ }
+ }
+
+ return names;
+};
export const isDynamicPromptsSeedBehaviour = (value: unknown): value is DynamicPromptsSeedBehaviour =>
value === 'per-iteration' || value === 'per-image';
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
index ad52e72087..91bc065088 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
@@ -69,7 +69,14 @@ const covers = (outer: PromptRange, inner: PromptRange): boolean =>
* reported as `error` so the textarea can underline them the same way it already
* underlines unbalanced attention parentheses.
*/
-export const scanDynamicPromptSyntax = (prompt: string): DynamicPromptSyntaxAnnotation[] => {
+export const scanDynamicPromptSyntax = (
+ prompt: string,
+ /**
+ * Wildcard names the backend can resolve. Omitted means "unknown", so callers
+ * without a catalog get the neutral wildcard colour rather than a false error.
+ */
+ knownWildcards?: ReadonlySet<string>
+): DynamicPromptSyntaxAnnotation[] => {
const annotations: DynamicPromptSyntaxAnnotation[] = [];
const variableRanges: PromptRange[] = [];
// Open braces awaiting a `}`, paired with the annotation to rewrite if none arrives.
@@ -153,7 +160,11 @@ export const scanDynamicPromptSyntax = (prompt: string): DynamicPromptSyntaxAnno
const wildcardRange = { end: match.index + match[0].length, start: match.index };
if (!variableRanges.some((variableRange) => covers(variableRange, wildcardRange))) {
- annotations.push({ kind: 'wildcard', range: wildcardRange });
+ // An unresolvable wildcard makes the whole prompt fail to expand, so it earns the same
+ // treatment as an unbalanced brace rather than looking like ordinary recognised syntax.
+ const isUnknown = knownWildcards !== undefined && !knownWildcards.has(match[1]);
+
+ annotations.push({ kind: isUnknown ? 'error' : 'wildcard', range: wildcardRange });
}
}
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts
index a69074319f..f0f057f8e3 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts
@@ -75,6 +75,19 @@ describe('prompt highlight segments', () => {
expect(dynamicKindForText(`\${colour} ball`, `\${colour}`)).toBe('promptVariable');
});
+ it('marks an unknown wildcard as an error and a known one as recognised syntax', () => {
+ const known = new Set(['colors']);
+ const kindWithCatalog = (prompt: string, text: string) =>
+ buildPromptHighlightSegments(prompt, { dynamicPrompts: true, knownWildcards: known }).find(
+ (segment) => segment.text === text
+ )?.kind;
+
+ expect(kindWithCatalog('a __colors__ ball', '__colors__')).toBe('wildcard');
+ expect(kindWithCatalog('a __nope__ ball', '__nope__')).toBe('error');
+ // Without a catalog nothing is known to be missing, so neither is an error.
+ expect(dynamicKindForText('a __nope__ ball', '__nope__')).toBe('wildcard');
+ });
+
it('marks an unbalanced brace as an error, like an unbalanced parenthesis', () => {
expect(dynamicKindForText('a {red green', '{')).toBe('error');
expect(dynamicKindForText('a red} green', '}')).toBe('error');
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts
index ffdbecc539..62c757d5e1 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts
@@ -29,6 +29,8 @@ export interface PromptHighlightOptions {
* never happens.
*/
dynamicPrompts?: boolean;
+ /** Resolvable wildcard names; omitted leaves every `__name__` neutral. */
+ knownWildcards?: ReadonlySet<string>;
}
export interface PromptHighlightSegment {
@@ -196,8 +198,8 @@ const appendSegment = (segments: PromptHighlightSegment[], segment: PromptHighli
segments.push(segment);
};
-const collectDynamicPromptAnnotations = (prompt: string): HighlightAnnotation[] =>
- scanDynamicPromptSyntax(prompt).map(({ kind, range }) => ({
+const collectDynamicPromptAnnotations = (prompt: string, knownWildcards?: ReadonlySet<string>): HighlightAnnotation[] =>
+ scanDynamicPromptSyntax(prompt, knownWildcards).map(({ kind, range }) => ({
kind,
priority: ANNOTATION_PRIORITY[kind],
range,
@@ -216,7 +218,7 @@ export const buildPromptHighlightSegments = (
const annotations = [
...collectAnnotations(prompt, parsePromptTokens(tokens)),
...collectParenthesisErrors(tokens),
- ...(options.dynamicPrompts ? collectDynamicPromptAnnotations(prompt) : []),
+ ...(options.dynamicPrompts ? collectDynamicPromptAnnotations(prompt, options.knownWildcards) : []),
];
const segments: PromptHighlightSegment[] = [];
diff --git a/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts b/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts
new file mode 100644
index 0000000000..0347e7f895
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts
@@ -0,0 +1,68 @@
+/**
+ * The current user's wildcards: named value lists that `__name__` expands to.
+ *
+ * The catalog feeds three consumers — the `__` autocomplete, the highlighter's
+ * known/unknown distinction, and the wildcards editor — so it is fetched once
+ * and shared. Mutations must invalidate the dynamic prompts cache as well; see
+ * `invalidateWildcardDependents`.
+ */
+
+import type { QueryClient } from '@tanstack/react-query';
+
+import { dynamicPromptsKeys } from '@features/generation/data/dynamicPromptsQueries';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
+import { apiFetch, apiFetchJson } from '@platform/transport/http';
+import { queryOptions } from '@tanstack/react-query';
+
+export interface WildcardRecord {
+ id: string;
+ name: string;
+ values: string[];
+}
+
+export const wildcardKeys = {
+ all: ['generation', 'wildcards'] as const,
+};
+
+export const wildcardsQueryOptions = () =>
+ (() => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
+ queryFn: async ({ signal }): Promise<WildcardRecord[]> => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
+ const wildcards = await apiFetchJson<WildcardRecord[]>('/api/v1/wildcards/', { signal: requestSignal });
+
+ assertAccountScopeCurrent(owner);
+ return wildcards;
+ },
+ queryKey: wildcardKeys.all,
+ staleTime: 30_000,
+ });
+ })();
+
+export const createWildcard = (wildcard: { name: string; values: string[] }): Promise<WildcardRecord> =>
+ apiFetchJson('/api/v1/wildcards/', { body: JSON.stringify(wildcard), method: 'POST' });
+
+export const updateWildcard = (id: string, changes: { name?: string; values?: string[] }): Promise<WildcardRecord> =>
+ apiFetchJson(`/api/v1/wildcards/${encodeURIComponent(id)}`, {
+ body: JSON.stringify(changes),
+ method: 'PATCH',
+ });
+
+export const deleteWildcard = async (id: string): Promise<void> => {
+ await apiFetch(`/api/v1/wildcards/${encodeURIComponent(id)}`, { method: 'DELETE' });
+};
+
+/**
+ * Editing a wildcard changes what a prompt expands to without changing the
+ * prompt, and the expansion cache is keyed only on the request (with
+ * `staleTime: Infinity`). Both caches must therefore be dropped together, or the
+ * preview and the submitted batch would both keep serving the old expansion.
+ */
+export const invalidateWildcardDependents = async (queryClient: QueryClient): Promise<void> => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: wildcardKeys.all }),
+ queryClient.invalidateQueries({ queryKey: dynamicPromptsKeys.all }),
+ ]);
+};
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.tsx
index 86418db3f1..57e94c6e48 100644
--- 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.tsx
@@ -14,6 +14,15 @@ const parseDynamicPrompts = vi.hoisted(() => vi.fn());
vi.mock('@features/generation/data/promptUtilities', () => ({ parseDynamicPrompts }));
+// The wildcards tab fetches the catalog on mount; the preview assertions do not need it.
+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;
@@ -45,7 +54,13 @@ const render = async (prompt: string, onUsePrompt = vi.fn()) => {
showSyntaxHighlighting
value={prompt}
/>
- <DynamicPromptsButton batchCount={2} config={config} positivePrompt={prompt} onUsePrompt={onUsePrompt} />
+ <DynamicPromptsButton
+ batchCount={2}
+ config={config}
+ positivePrompt={prompt}
+ onInsertText={vi.fn()}
+ onUsePrompt={onUsePrompt}
+ />
</ChakraProvider>
</QueryClientProvider>
);
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx
index 1d5daa8e18..15ac17eec4 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx
@@ -18,7 +18,9 @@ import {
isDynamicPromptsSeedBehaviour,
sanitizeMaxPrompts,
} from '@features/generation/core/dynamicPrompts';
+import { WildcardsPanel } from '@features/generation/ui/promptFields/WildcardsPanel';
import { useDynamicPrompts } from '@features/generation/ui/useDynamicPrompts';
+import { useWildcards } from '@features/generation/ui/useWildcards';
import { Button, IconButton } from '@platform/ui/Button';
import { Scrollable } from '@platform/ui/Scrollable';
import { Select } from '@platform/ui/Select';
@@ -41,18 +43,22 @@ interface DynamicPromptsButtonProps {
batchCount: number;
positivePrompt: string;
onUsePrompt: (prompt: string) => void;
+ onInsertText: (text: string) => void;
}
export const DynamicPromptsButton = ({
batchCount,
config,
+ onInsertText,
onUsePrompt,
positivePrompt,
}: DynamicPromptsButtonProps) => {
const { t } = useTranslation();
const triggerId = useId();
const [isOpen, setIsOpen] = useState(false);
+ const [tab, setTab] = useState<'preview' | 'wildcards'>('preview');
const expansion = useDynamicPrompts(positivePrompt, config);
+ const catalog = useWildcards();
const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);
const handleOpenChange = useCallback((event: { open: boolean }) => setIsOpen(event.open), []);
const handleUsePrompt = useCallback(
@@ -62,6 +68,24 @@ export const DynamicPromptsButton = ({
},
[onUsePrompt]
);
+ const handleInsert = useCallback(
+ (text: string) => {
+ onInsertText(text);
+ setIsOpen(false);
+ },
+ [onInsertText]
+ );
+ const handleTabChange = useCallback(
+ (event: { value: string | null }) => setTab(event.value === 'wildcards' ? 'wildcards' : 'preview'),
+ []
+ );
+ const tabItems = useMemo(
+ () => [
+ { label: t('widgets.generate.dynamicPrompts.preview'), value: 'preview' },
+ { label: t('widgets.generate.dynamicPrompts.wildcards'), value: 'wildcards' },
+ ],
+ [t]
+ );
const tooltip = expansion.isDynamic
? t('widgets.generate.dynamicPrompts.showPrompts')
@@ -103,12 +127,22 @@ export const DynamicPromptsButton = ({
<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}
- />
+ <Stack gap="2.5">
+ <SegmentGroup.Root size="xs" value={tab} onValueChange={handleTabChange}>
+ <SegmentGroup.Indicator />
+ <SegmentGroup.Items items={tabItems} />
+ </SegmentGroup.Root>
+ {tab === 'preview' ? (
+ <DynamicPromptsPanel
+ batchCount={batchCount}
+ config={config}
+ expansion={expansion}
+ onUsePrompt={handleUsePrompt}
+ />
+ ) : (
+ <WildcardsPanel catalog={catalog} onInsert={handleInsert} />
+ )}
+ </Stack>
</Popover.Body>
</Popover.Content>
</Popover.Positioner>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
index 740df9dca0..da46a458cc 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
@@ -11,6 +11,7 @@ import {
DynamicPromptsButton,
type DynamicPromptsFieldConfig,
} from '@features/generation/ui/promptFields/DynamicPromptsButton';
+import { useWildcards } from '@features/generation/ui/useWildcards';
import { useMountEffect } from '@platform/react/useMountEffect';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton, Scrollable, Tooltip } from '@platform/ui';
@@ -34,12 +35,14 @@ interface PositivePromptActionsProps {
projectId: string;
onOpenPromptTriggerPicker: (anchorElement: HTMLElement) => void;
onPositivePromptChangeImmediate: (prompt: string) => void;
+ onInsertText: (text: string) => void;
}
export const PositivePromptActions = ({
batchCount,
dynamicPrompts,
isPromptTriggerPickerOpen,
+ onInsertText,
onOpenPromptTriggerPicker,
onPositivePromptChangeImmediate,
onUsePrompt,
@@ -53,6 +56,7 @@ export const PositivePromptActions = ({
batchCount={batchCount}
config={dynamicPrompts}
positivePrompt={positivePrompt}
+ onInsertText={onInsertText}
onUsePrompt={onPositivePromptChangeImmediate}
/>
) : null}
@@ -95,15 +99,25 @@ const getPromptTriggerOptions = ({
mainModelLabel,
models,
selectedModel,
+ wildcards,
+ wildcardsLabel,
}: {
compatibleEmbeddingsLabel: string;
loras: GenerateLora[];
mainModelLabel: string;
models: readonly ModelConfig[];
selectedModel: GenerateModelConfig | undefined;
+ wildcards: readonly { name: string; values: string[] }[];
+ wildcardsLabel: string;
}): PromptTriggerOption[] => {
const options: PromptTriggerOption[] = [];
+ // A wildcard inserts as `__name__`, which is just another trigger the picker
+ // can splice in, so it rides in the same list as embeddings and LoRA phrases.
+ for (const wildcard of wildcards) {
+ options.push({ group: wildcardsLabel, label: wildcard.name, value: `__${wildcard.name}__` });
+ }
+
for (const phrase of getTriggerPhrases(selectedModel)) {
options.push({ group: selectedModel?.name ?? mainModelLabel, label: phrase, value: phrase });
}
@@ -183,6 +197,7 @@ export const PromptTriggerPopover = ({
}) => {
const { t } = useTranslation();
const { catalog: models, ensureLoaded: ensureModelsLoaded } = useGenerationUi().models;
+ const { wildcards } = useWildcards();
const [searchTerm, setSearchTerm] = useState('');
const options = useMemo(
@@ -193,8 +208,10 @@ export const PromptTriggerPopover = ({
mainModelLabel: t('widgets.generate.mainModel'),
models,
selectedModel,
+ wildcards,
+ wildcardsLabel: t('widgets.generate.dynamicPrompts.wildcards'),
}),
- [loras, models, selectedModel, t]
+ [loras, models, selectedModel, t, wildcards]
);
const filteredOptions = useMemo(
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 3201e9bb8a..46d503053f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -4,6 +4,7 @@ import type { ChangeEvent, KeyboardEvent } from 'react';
import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';
import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';
+import { useWildcards } from '@features/generation/ui/useWildcards';
import { Field } from '@platform/ui';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -54,6 +55,7 @@ export const PositivePromptField = ({
const { t } = useTranslation();
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const [triggerPickerState, setTriggerPickerState] = useState<PromptTriggerPickerState | null>(null);
+ const { knownNames: knownWildcards } = useWildcards();
const { commitDraftValue, draftValue, flushDraftValue, replaceDraftValue, setDraftValue } = useDebouncedDraftValue({
delayMs: PROMPT_INPUT_DEBOUNCE_MS,
onCommit: onChange,
@@ -90,15 +92,26 @@ export const PositivePromptField = ({
const handlePromptKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
- if (event.key !== '<' || event.altKey || event.ctrlKey || event.metaKey) {
+ if (event.altKey || event.ctrlKey || event.metaKey) {
+ return;
+ }
+
+ // `<` opens the picker outright; `__` does too, on the second underscore,
+ // since that is the point where the user has committed to a wildcard.
+ const opensPicker =
+ event.key === '<' ||
+ (event.key === '_' && event.currentTarget.value.slice(0, event.currentTarget.selectionStart).endsWith('_'));
+
+ if (!opensPicker) {
return;
}
event.preventDefault();
- openPromptTriggerPicker(event.currentTarget, {
- end: event.currentTarget.selectionEnd,
- start: event.currentTarget.selectionStart,
- });
+ // The `__` case replaces the underscore already typed, so the inserted
+ // `__name__` does not end up with three leading underscores.
+ const start = event.key === '_' ? event.currentTarget.selectionStart - 1 : event.currentTarget.selectionStart;
+
+ openPromptTriggerPicker(event.currentTarget, { end: event.currentTarget.selectionEnd, start });
},
[openPromptTriggerPicker]
);
@@ -137,12 +150,20 @@ export const PositivePromptField = ({
[openPromptTriggerPicker]
);
+ const insertTextAtCaret = useCallback(
+ (text: string) => {
+ insertPromptText({ onChange: commitPromptChange, textarea: textareaRef.current, text, value: draftValue });
+ },
+ [commitPromptChange, draftValue]
+ );
+
const labelEnd = useMemo(
() => (
<PositivePromptActions
batchCount={batchCount}
dynamicPrompts={dynamicPrompts}
isPromptTriggerPickerOpen={triggerPickerState !== null}
+ onInsertText={insertTextAtCaret}
loras={loras}
positivePrompt={draftValue}
projectId={projectId}
@@ -159,6 +180,7 @@ export const PositivePromptField = ({
dynamicPrompts,
handleOpenPromptTriggerPicker,
handleUsePrompt,
+ insertTextAtCaret,
loras,
projectId,
selectedModel,
@@ -187,6 +209,7 @@ export const PositivePromptField = ({
size="xs"
fontFamily="mono"
highlightDynamicPrompts={dynamicPrompts !== null}
+ knownWildcards={knownWildcards}
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.tsx
index b02fe86b22..6a7055cf6c 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx
@@ -52,6 +52,8 @@ interface PromptTextareaProps extends Omit<ResizableTextareaProps, 'underlay'> {
* promise an expansion that never happens.
*/
highlightDynamicPrompts?: boolean;
+ /** Resolvable wildcard names; an unknown `__name__` is underlined as an error. */
+ knownWildcards?: ReadonlySet<string>;
showSyntaxHighlighting: boolean;
value: string;
}
@@ -90,6 +92,7 @@ export const PromptTextarea = ({
fontFamily = 'mono',
fontSize,
highlightDynamicPrompts = false,
+ knownWildcards,
lineHeight,
onScroll,
showSyntaxHighlighting,
@@ -105,8 +108,11 @@ export const PromptTextarea = ({
const effectiveLineHeight = lineHeight ?? PROMPT_TEXTAREA_LINE_HEIGHT;
const segments = useMemo(
- () => (shouldHighlight ? buildPromptHighlightSegments(value, { dynamicPrompts: highlightDynamicPrompts }) : []),
- [highlightDynamicPrompts, shouldHighlight, value]
+ () =>
+ shouldHighlight
+ ? buildPromptHighlightSegments(value, { dynamicPrompts: highlightDynamicPrompts, knownWildcards })
+ : [],
+ [highlightDynamicPrompts, knownWildcards, shouldHighlight, value]
);
useLayoutEffect(() => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
new file mode 100644
index 0000000000..a0841cc60d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
@@ -0,0 +1,210 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { WildcardRecord } from '@features/generation/data/wildcards';
+import type { WildcardCatalog } from '@features/generation/ui/useWildcards';
+import type { ChangeEvent } from 'react';
+
+import { HStack, Input, Stack, Text, Textarea } from '@chakra-ui/react';
+import { Button, IconButton } from '@platform/ui/Button';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { CheckIcon, PencilIcon, PlusIcon, TrashIcon, XIcon } from 'lucide-react';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/** One value per line: the same shape the user is editing a variant in. */
+const toValuesText = (values: string[]): string => values.join('\n');
+const fromValuesText = (text: string): string[] => text.split('\n');
+
+interface WildcardDraft {
+ id: string | null;
+ name: string;
+ valuesText: string;
+}
+
+export const WildcardsPanel = ({
+ catalog,
+ onInsert,
+}: {
+ catalog: WildcardCatalog;
+ /** Splices `__name__` into the prompt at the caret. */
+ onInsert: (reference: string) => void;
+}) => {
+ const { t } = useTranslation();
+ const [draft, setDraft] = useState<WildcardDraft | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const startCreate = useCallback(() => {
+ setError(null);
+ setDraft({ id: null, name: '', valuesText: '' });
+ }, []);
+
+ const startEdit = useCallback((wildcard: WildcardRecord) => {
+ setError(null);
+ setDraft({ id: wildcard.id, name: wildcard.name, valuesText: toValuesText(wildcard.values) });
+ }, []);
+
+ const cancel = useCallback(() => {
+ setError(null);
+ setDraft(null);
+ }, []);
+
+ const save = useCallback(async () => {
+ if (!draft) {
+ return;
+ }
+
+ const values = fromValuesText(draft.valuesText);
+
+ try {
+ if (draft.id === null) {
+ await catalog.create({ name: draft.name, values });
+ } else {
+ await catalog.update(draft.id, { name: draft.name, values });
+ }
+ setDraft(null);
+ setError(null);
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : t('widgets.generate.dynamicPrompts.couldNotSaveWildcard'));
+ }
+ }, [catalog, draft, t]);
+
+ if (draft) {
+ return (
+ <Stack gap="2">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ {draft.id === null
+ ? t('widgets.generate.dynamicPrompts.newWildcard')
+ : t('widgets.generate.dynamicPrompts.editWildcard')}
+ </Text>
+ <Input
+ aria-label={t('widgets.generate.dynamicPrompts.wildcardName')}
+ placeholder={t('widgets.generate.dynamicPrompts.wildcardNamePlaceholder')}
+ size="xs"
+ value={draft.name}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft({ ...draft, name: event.currentTarget.value })}
+ />
+ <Textarea
+ aria-label={t('widgets.generate.dynamicPrompts.wildcardValues')}
+ fontFamily="mono"
+ fontSize="0.72rem"
+ h="9rem"
+ placeholder={t('widgets.generate.dynamicPrompts.wildcardValuesPlaceholder')}
+ resize="none"
+ size="xs"
+ value={draft.valuesText}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) =>
+ setDraft({ ...draft, valuesText: event.currentTarget.value })
+ }
+ />
+ {error ? (
+ <Text color="fg.error" fontSize="2xs" wordBreak="break-word">
+ {error}
+ </Text>
+ ) : null}
+ <HStack justify="end">
+ <Button size="xs" variant="ghost" onClick={cancel}>
+ <XIcon />
+ {t('common.cancel')}
+ </Button>
+ <Button disabled={!draft.name.trim()} size="xs" onClick={() => void save()}>
+ <CheckIcon />
+ {t('common.save')}
+ </Button>
+ </HStack>
+ </Stack>
+ );
+ }
+
+ return (
+ <Stack gap="2">
+ <HStack justify="space-between">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ {t('widgets.generate.dynamicPrompts.wildcards')}
+ </Text>
+ <Button size="2xs" variant="ghost" onClick={startCreate}>
+ <PlusIcon />
+ {t('widgets.generate.dynamicPrompts.newWildcard')}
+ </Button>
+ </HStack>
+
+ <Scrollable h="14rem" label={t('widgets.generate.dynamicPrompts.wildcards')}>
+ {catalog.wildcards.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs" px="2" py="1.5">
+ {t('widgets.generate.dynamicPrompts.noWildcardsYet')}
+ </Text>
+ ) : (
+ <Stack gap="0">
+ {catalog.wildcards.map((wildcard) => (
+ <WildcardRow
+ key={wildcard.id}
+ catalog={catalog}
+ wildcard={wildcard}
+ onEdit={startEdit}
+ onInsert={onInsert}
+ />
+ ))}
+ </Stack>
+ )}
+ </Scrollable>
+ </Stack>
+ );
+};
+
+const WildcardRow = ({
+ catalog,
+ onEdit,
+ onInsert,
+ wildcard,
+}: {
+ catalog: WildcardCatalog;
+ wildcard: WildcardRecord;
+ onEdit: (wildcard: WildcardRecord) => void;
+ onInsert: (reference: string) => void;
+}) => {
+ const { t } = useTranslation();
+
+ return (
+ <HStack align="start" gap="1" pr="1">
+ <Button
+ alignItems="start"
+ flex="1"
+ h="auto"
+ justifyContent="start"
+ minW="0"
+ px="2"
+ py="1.5"
+ size="xs"
+ title={t('widgets.generate.dynamicPrompts.insertWildcard')}
+ variant="ghost"
+ onClick={() => onInsert(`__${wildcard.name}__`)}
+ >
+ <Stack align="start" gap="0" minW="0">
+ <Text as="span" color="fg" fontFamily="mono" fontSize="0.72rem">
+ __{wildcard.name}__
+ </Text>
+ <Text as="span" color="fg.subtle" fontSize="2xs" truncate>
+ {wildcard.values.length > 0
+ ? wildcard.values.join(', ')
+ : t('widgets.generate.dynamicPrompts.wildcardHasNoValues')}
+ </Text>
+ </Stack>
+ </Button>
+ <Tooltip content={t('common.edit')}>
+ <IconButton aria-label={t('common.edit')} size="2xs" variant="ghost" onClick={() => onEdit(wildcard)}>
+ <PencilIcon />
+ </IconButton>
+ </Tooltip>
+ <Tooltip content={t('common.delete')}>
+ <IconButton
+ aria-label={t('common.delete')}
+ colorPalette="red"
+ size="2xs"
+ variant="ghost"
+ onClick={() => void catalog.remove(wildcard.id)}
+ >
+ <TrashIcon />
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
new file mode 100644
index 0000000000..cef7a1aef8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
@@ -0,0 +1,64 @@
+import type { WildcardRecord } from '@features/generation/data/wildcards';
+
+import {
+ createWildcard,
+ deleteWildcard,
+ invalidateWildcardDependents,
+ updateWildcard,
+ wildcardsQueryOptions,
+} from '@features/generation/data/wildcards';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { useCallback, useMemo } from 'react';
+
+export interface WildcardCatalog {
+ wildcards: WildcardRecord[];
+ /** Names the backend can resolve, for the highlighter's known/unknown split. */
+ knownNames: ReadonlySet<string>;
+ isLoading: boolean;
+ create: (wildcard: { name: string; values: string[] }) => Promise<void>;
+ update: (id: string, changes: { name?: string; values?: string[] }) => Promise<void>;
+ remove: (id: string) => Promise<void>;
+}
+
+/**
+ * The shared wildcard catalog. Every mutation invalidates the dynamic prompts
+ * cache too, because editing a wildcard changes what an unchanged prompt expands
+ * to and that cache never goes stale on its own.
+ */
+export const useWildcards = (): WildcardCatalog => {
+ const queryClient = useQueryClient();
+ const query = useQuery(wildcardsQueryOptions());
+ const wildcards = useMemo(() => query.data ?? [], [query.data]);
+ // Only a wildcard with values resolves; the backend omits empty ones from its
+ // manager, so an empty one must read as unknown here too.
+ const knownNames = useMemo(
+ () => new Set(wildcards.filter((wildcard) => wildcard.values.length > 0).map((wildcard) => wildcard.name)),
+ [wildcards]
+ );
+
+ const create = useCallback(
+ async (wildcard: { name: string; values: string[] }) => {
+ await createWildcard(wildcard);
+ await invalidateWildcardDependents(queryClient);
+ },
+ [queryClient]
+ );
+
+ const update = useCallback(
+ async (id: string, changes: { name?: string; values?: string[] }) => {
+ await updateWildcard(id, changes);
+ await invalidateWildcardDependents(queryClient);
+ },
+ [queryClient]
+ );
+
+ const remove = useCallback(
+ async (id: string) => {
+ await deleteWildcard(id);
+ await invalidateWildcardDependents(queryClient);
+ },
+ [queryClient]
+ );
+
+ return { create, isLoading: query.isPending, knownNames, remove, update, wildcards };
+};