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
refactor(webv2): slim prompt generation code
joshistoast95304eacde24
diff --git a/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.ts b/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.tsindex 95dc032dcb..517af38dc5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.ts@@ -1,50 +1,10 @@-/**- * One search rule for every saved-prompt catalog: fuzzy on the short name,- * substring on the long prose, name matches first.- *- * The three lists that hold saved things — wildcards, prompt templates, prompt- * history — each grew their own filter, and the two that sit side by side in- * the same popover disagreed about what typing means: a wildcard was found by- * name fuzzily (`adg` finds `animals/dogs`), a template only where its name- * contained the query letter for letter. Same box, same gesture, two answers.- *- * The split between the two kinds of field is the part worth keeping, and it is- * why one rule fits all three. Names are short slugs, where fuzzy matching earns- * its keep; prose is free text, where a fuzzy match fires on almost anything, so- * it takes a plain substring test. Searching the prose at all matters because a- * record is mostly its prose — you remember that "cyberpunk" is in one of these- * lists long before you remember which.- *- * Prose is scanned in full rather than sampled: stopping early would silently- * hide a match in a long list, which is worse than the scan being slow.- *- * The inline `__` autocomplete deliberately does *not* come through here. It- * completes a word while it is being typed, where anything looser than a- * substring on the one visible field inserts text nobody asked for.- */-import fuzzysort from 'fuzzysort';-/** Matches below this fuzzysort score (0–1) are noise, not results. */const NAME_MATCH_THRESHOLD = 0.2;type ProseOf<T> = (item: T) => readonly string[];-/**- * Lowercased prose, derived once per record rather than once per keystroke.- *- * Lowercasing on the fly was the whole cost of searching a large catalog: 200- * wildcards of 200 values allocated 40 000 strings per character typed, and the- * search box is not debounced. Keyed by record identity, so an edited record —- * a new object every time, as the query cache hands them back — derives afresh.- *- * Keyed by the accessor too, so two callers reading different fields off the- * same record can never read each other's lowercased copy.- *- * Fields stay separate rather than joining into one string: a query is free to- * contain whatever the user typed, and no separator both survives that and- * stops a match from spanning the end of one value and the start of the next.- */+// Both record and accessor identity are cache keys; callers may read different fields from one record.const proseCaches = new WeakMap<object, WeakMap<object, readonly string[]>>();const matchesProse = <T extends object>(item: T, getProse: ProseOf<T>, needle: string): boolean => {@@ -65,10 +25,6 @@ const matchesProse = <T extends object>(item: T, getProse: ProseOf<T>, needle: sreturn lowercased.some((field) => field.includes(needle));};-/**- * Records matching on their prose alone, in the order given. For lists whose- * entries have no name of their own — prompt history is the prompts.- */export const searchProse = <T extends object>(items: readonly T[], query: string, getProse: ProseOf<T>): T[] => {const needle = query.trim().toLowerCase();@@ -79,14 +35,6 @@ export const searchProse = <T extends object>(items: readonly T[], query: stringreturn items.filter((item) => matchesProse(item, getProse, needle));};-/**- * Name matches first, ranked fuzzily, then records whose prose contains the- * query, in the order given.- *- * Ordering is otherwise preserved, so a caller that groups or sections the- * result keeps the ranking: the best hit stays at the top rather than being- * sorted away.- */export const searchCatalog = <T extends { name: string }>(items: readonly T[],query: string,@@ -98,10 +46,6 @@ export const searchCatalog = <T extends { name: string }>(return [...items];}- // `key: 'name'` rather than an accessor: fuzzysort reads `obj[key]` before it- // considers calling it, so a function key is first used as a property key —- // stringifying the function's source once per record per keystroke. Plain- // names also hit fuzzysort's own prepared-target cache.const nameMatches = fuzzysort.go(trimmed, items, { key: 'name', threshold: NAME_MATCH_THRESHOLD });const named = new Set<T>();const results: T[] = [];diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.tsindex 185e47b96f..146cfa7fe2 100644--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts@@ -1,17 +1,5 @@-/**- * Dynamic prompting policy: detecting the syntax and bounding the expansion.- *- * The backend expands `a {red|green} {cat|dog}` into concrete prompts; the- * frontend never rebuilds the graph per prompt. Turning the expanded list into a- * batch dimension over the graph's existing `positive_prompt` string node is- * Queue's job — see `features/queue/core/promptBatch.ts`.- */--// Local copy: `core/settings.ts` exports the same bound but imports this module,-// so taking it from there would be a cycle.const SEED_MAX = 4_294_967_295;-/** Matches the backend's `max_prompts: int = Body(ge=1, le=10000)`. */export const DYNAMIC_PROMPTS_MIN_PROMPTS = 1;export const DYNAMIC_PROMPTS_MAX_PROMPTS = 10_000;export const DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS = 100;@@ -21,37 +9,23 @@ export type DynamicPromptsSeedBehaviour = 'per-iteration' | 'per-image';export interface DynamicPromptsConfig {combinatorial: boolean;maxPrompts: number;- /**- * Seeds the random sampler. Held apart from the generation seed and stable- * until the user shuffles, so the previewed prompts are the prompts that- * generate. Unused when combinatorial.- */sampleSeed: number;seedBehaviour: DynamicPromptsSeedBehaviour;}-/**- * One `/`-separated segment of a wildcard name. Mirrors the backend's- * `_WILDCARD_NAME_SEGMENT`: it must begin and end alphanumerically, so- * `snake__case` is ordinary text rather than a reference.- */const WILDCARD_NAME_SEGMENT = '[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?';const WILDCARD_NAME_SOURCE = `${WILDCARD_NAME_SEGMENT}(?:/${WILDCARD_NAME_SEGMENT})*`;-/** The same rule anchored, for validating a name the user is typing. */export const WILDCARD_NAME_RE = new RegExp(`^${WILDCARD_NAME_SOURCE}$`);export interface WildcardReference {- /** The path sent to the wildcard manager, without sampler or parameters. */lookupPath: string;- /** Full `__…__` span in the authored prompt. */range: { end: number; start: number };}const WILDCARD_GLOB_CHARACTER_RE = /[*?[]/;const WILDCARD_REFERENCE_PATH_RE = /^[A-Za-z0-9_/*?[\]!-]+$/;-/** Mirrors the backend's `MAX_WILDCARD_NAME_LENGTH`. */export const MAX_WILDCARD_NAME_LENGTH = 128;const getWildcardLookupPath = (content: string): string | null => {@@ -80,7 +54,6 @@ const getWildcardLookupPath = (content: string): string | null => {return WILDCARD_GLOB_CHARACTER_RE.test(lookupPath) || WILDCARD_NAME_RE.test(lookupPath) ? lookupPath : null;};-/** Scans every backend-compatible wildcard reference without regex state or backtracking. */export const scanWildcardReferences = (prompt: string): WildcardReference[] => {const references: WildcardReference[] = [];let index = 0;@@ -216,7 +189,6 @@ const globTokenMatches = (token: Exclude<GlobToken, { kind: 'star' }>, characterreturn token.negated ? !inClass : inClass;};-/** Bounded O(pattern × name) matcher mirroring Python `fnmatchcase`. */const matchesGlob = (pattern: string, name: string): boolean => {let reachable = Array.from({ length: name.length + 1 }, (_, index) => index === 0);@@ -242,18 +214,6 @@ const matchesGlob = (pattern: string, name: string): boolean => {return reachable[name.length] === true;};-/**- * Whether a referenced path resolves against the catalog.- *- * A glob matches when *any* known name matches it, mirroring the backend, where- * `*` is an unanchored run of any characters — `/` included, so `__*s__` reaches- * `animals/dogs`. `**` is spelt differently but means the same thing there, and- * falls out of the same translation.- *- * A path matching nothing is still worth flagging: the expansion leaves the- * literal `__name__` in the prompt rather than failing, so an unnoticed typo- * goes to the model as text.- */export const matchesKnownWildcard = (path: string, knownNames: ReadonlySet<string>): boolean => {if (!WILDCARD_GLOB_CHARACTER_RE.test(path)) {return knownNames.has(path);@@ -268,23 +228,13 @@ export const matchesKnownWildcard = (path: string, knownNames: ReadonlySet<strinreturn false;};-/**- * The backend's bounds on a values list, mirrored here so both ways of writing- * one can say what is wrong before sending it.- *- * These lived next to the import planner, which meant an import pre-flighted- * them politely while the editor discovered them as a raw error from the server.- */export const MAX_WILDCARD_VALUES = 10_000;export const MAX_WILDCARD_VALUE_LENGTH = 2_000;-/** Why a values list would be rejected, or `null` if it would be accepted. */export const getWildcardValuesError = (values: readonly string[]): 'tooManyValues' | 'valueTooLong' | null => {if (values.length > MAX_WILDCARD_VALUES) {return 'tooManyValues';}- // Kept apart from the count: told "too many values", someone holding three- // values and one long paragraph has no idea which one to shorten.if (values.some((value) => value.length > MAX_WILDCARD_VALUE_LENGTH)) {return 'valueTooLong';}@@ -292,32 +242,9 @@ export const getWildcardValuesError = (values: readonly string[]): 'tooManyValuereturn null;};-/**- * The values as they will be stored: comments removed, trimmed, blanks dropped.- *- * Applied wherever a list is authored, so that what is saved is what an export- * writes and a re-import reads back. Without it a stray blank line survived into- * the catalog and vanished on the next round trip.- *- * `#` comments to end of line, and the expander applies that to a substituted- * value as readily as to the prompt around it — a value of `poster #1` reaches- * the model as `poster `, and `#ff0000 glow` reaches it as nothing at all. There- * is no escape for it upstream. Dropping the comment here is what makes that- * visible while the list is in front of the user, rather than at generation time- * with no clue as to where the text went. The `.txt` reader has always done- * this, being the only format with no parser of its own; the rule belongs to the- * value rather than to the file it arrived in.- */export const normalizeWildcardValues = (values: readonly string[]): string[] =>values.map((value) => value.split('#')[0]?.trim() ?? '').filter((value) => value.length > 0);-/**- * Why a wildcard name would be rejected, or `null` if it would be accepted.- *- * The server remains the authority — only it can see the whole catalog at save- * time — but a name is typed character by character, and finding out it was- * invalid only after a round trip is a poor way to learn the rule.- */export const getWildcardNameError = (name: string,existingNames: ReadonlySet<string> = new Set()diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.tsindex 8756162854..5e1dcf4aa6 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts@@ -1,45 +1,3 @@-/**- * Scanner for adieyal/dynamicprompts syntax.- *- * ## The syntax, in full- *- * The backend runs the real `dynamicprompts` library, so everything below works- * at generate time whether or not this scanner colours it. Kept here, beside the- * code that recognizes each form, so the two cannot drift apart.- *- * | Form | Meaning | Example |- * | --- | --- | --- |- * | `{a\|b}` | Pick one alternative | `a {red\|green} ball` |- * | `{2$$a\|b\|c}` | Pick exactly two, comma-joined | `{2$$red\|green\|blue}` |- * | `{1-3$$a\|b\|c}` | Pick between one and three | `{1-3$$red\|green\|blue}` |- * | `{2$$ and $$a\|b}` | Pick two, joined by a custom separator | `{2$$ and $$red\|green}` |- * | `{2::a\|b}` | Weight an alternative — `a` twice as likely | `{2::red\|green}` |- * | `{~a\|b}` | Sample randomly, ignoring combinatorial mode | `{~red\|green}` |- * | `{@a\|b}` | Cycle through the alternatives in order | `{@red\|green}` |- * | `__name__` | Substitute one value from a wildcard | `a __colours__ ball` |- * | `__a/b__` | Nested wildcard names | `__animals/dogs__` |- * | `__art/*__` | Glob — draws from every matching wildcard | `__artists/*__` |- * | `__~name__` | Sampler override on a wildcard | `__@colours__` |- * | `__name(k=v)__` | Bind `${k}` inside that wildcard's values | `__outfit(mood=warm)__` |- * | `${v=a}` | Assign a variable; expands to nothing itself | `${lens=85mm} shot on ${lens}` |- * | `${v=!{a\|b}}` | Assign once, immediately — every use is the same value | `${v=!{a\|b}} ${v} ${v}` |- * | `${v}` | Use a variable | `${lens}` |- * | `${v:fallback}` | Use a variable, or this if it is unset | `${lens:50mm}` |- * | `# …` | Comment to end of line; stripped before generating | `a cat # for now` |- *- * Written to be lifted wholesale into the app-wide help system when that lands.- *- * ## Why a separate scanner- *- * This is intentionally a standalone character scanner rather than an extension- * of `ast.ts`. That tokenizer already emits every character we care about as its- * own whole token — `{`/`}` fall through to its single-char catch-all, `|`/`$`/`:`- * are single-char punctuation, and `__wildcard__` reads as one word because `_`- * is a word character. So the ranges produced here always cover whole tokens and- * compose with the existing highlight annotations, leaving the attention and- * embedding parser untouched.- */-import { matchesKnownWildcard, scanWildcardReferences } from '@features/generation/core/dynamicPrompts';import type { PromptRange } from './ast';@@ -61,16 +19,8 @@ export interface DynamicPromptSyntaxAnnotation {range: PromptRange;}-/** `2::`, `1.5::` — a variant value's relative weight. */const WEIGHT_PATTERN = /^\s*\d+(?:\.\d+)?::/;-/** `2$$`, `2-3$$`, `-3$$`, and the custom-separator form `2$$, $$`. */const RANGE_PATTERN = /^\s*(?:\d+)?(?:-\d+)?\$\$(?:[^$|{}]*\$\$)?/;-/**- * The operator that makes a `${…}` an assignment rather than a use: `=`, the- * immediate `=!`, or the `:` introducing a fallback. Muted like a variant's `|`,- * which is enough to tell a definition from a reference at a glance without- * spending another colour on it.- */const VARIABLE_OPERATOR_PATTERN = /=!?|:/;const isEscaped = (prompt: string, index: number): boolean => {@@ -104,26 +54,13 @@ const findVariableEnd = (prompt: string, openBraceIndex: number): number => {const covers = (outer: PromptRange, inner: PromptRange): boolean =>outer.start <= inner.start && outer.end >= inner.end;-/**- * Annotates a prompt's dynamic syntax. Unmatched braces in either direction are- * reported as `error` so the textarea can underline them the same way it already- * underlines unbalanced attention parentheses.- */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[] = [];- // Spans the wildcard sweep below must not look inside: a `__name__` written in- // either is not a reference, and reporting one would be a mistake the renderer- // then has to out-prioritize.const variableRanges: PromptRange[] = [];const commentRanges: PromptRange[] = [];- // Open braces awaiting a `}`, paired with the annotation to rewrite if none arrives.const openBraces: { annotationIndex: number }[] = [];let index = 0;@@ -135,11 +72,6 @@ export const scanDynamicPromptSyntax = (}};- /**- * The first operator inside a `${…}`, over the name and nothing after it — a- * `:` or `=` further in belongs to the assigned value, which may itself be a- * whole nested prompt.- */const annotateVariableOperator = (contentStart: number, contentEnd: number): void => {const name = prompt.slice(contentStart, contentEnd);const operator = name.match(VARIABLE_OPERATOR_PATTERN);@@ -154,9 +86,6 @@ export const scanDynamicPromptSyntax = (while (index < prompt.length) {const char = prompt[index];- // Comments outrank everything: the parser strips them before it sees any of- // the syntax below, so an unbalanced brace or an unknown wildcard inside one- // is inert text rather than a mistake.if (char === '#') {const lineEnd = prompt.indexOf('\n', index);const end = lineEnd === -1 ? prompt.length : lineEnd;@@ -168,9 +97,6 @@ export const scanDynamicPromptSyntax = (}if (char === '\\') {- // `#` is the one character a backslash does not escape: upstream still- // comments from it and leaves the backslash in the prompt. Stepping over- // just the backslash lets the branch above see it on the next pass.index += prompt[index + 1] === '#' ? 1 : 2;continue;}@@ -191,8 +117,6 @@ export const scanDynamicPromptSyntax = (annotations.push({ kind: 'variantBrace', range: { end: index + 1, start: index } });openBraces.push({ annotationIndex: annotations.length - 1 });- // The sampler override binds tightest — `{~2$$a|b}` samples randomly, while- // `{2$$~a|b}` has `~a` as an ordinary alternative.if (prompt[index + 1] === '~' || prompt[index + 1] === '@') {annotations.push({ kind: 'variantSampler', range: { end: index + 2, start: index + 1 } });index++;@@ -238,18 +162,12 @@ export const scanDynamicPromptSyntax = (annotations[openBrace.annotationIndex].kind = 'error';}- // Concatenated once. Built inside the loop, this allocated a fresh array of- // every variable and comment in the prompt for every wildcard reference in it.const enclosingRanges = [...variableRanges, ...commentRanges];for (const reference of scanWildcardReferences(prompt)) {const wildcardRange = reference.range;if (!enclosingRanges.some((outer) => covers(outer, wildcardRange))) {- // An unresolvable wildcard survives expansion as its own literal text, so it earns the- // same treatment as an unbalanced brace rather than looking like ordinary recognised- // syntax. `matchesKnownWildcard` resolves globs, which is why a valid `__artists/*__`- // is no longer flagged for the sin of not being a name.const isUnknown = knownWildcards !== undefined && !matchesKnownWildcard(reference.lookupPath, knownWildcards);annotations.push({ kind: isUnknown ? 'error' : 'wildcard', range: wildcardRange });diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.tsindex 27057afea0..a1f4b4d9ca 100644--- a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts@@ -6,281 +6,106 @@ import {getEffectivePrompts,getPromptTemplateChunks,isCanonicalPromptTemplateSnapshot,- type PromptTemplateSnapshot,sanitizePromptTemplateSnapshot,syncPromptTemplateWithCatalog,+ type PromptTemplateSnapshot,} from './promptTemplates';-const template = (overrides: Partial<PromptTemplateSnapshot> = {}): PromptTemplateSnapshot => ({+const template: 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 ');+ negativePrompt: '{prompt}, blurry',+ positivePrompt: 'photo of {prompt}, 35mm',+};++describe('prompt template expansion', () => {+ it.each([+ ['before {prompt} after', 'subject', 'before subject after'],+ ['{prompt} after', 'subject', 'subject after'],+ ['before {prompt}', 'subject', 'before subject'],+ ['before {prompt} after {prompt}', 'subject', 'before subject after {prompt}'],+ ['cinematic', 'subject', 'subject cinematic'],+ ['', 'subject', 'subject '],+ ['{prompt}', 'costs $$$ and $&', 'costs $$$ and $&'],+ ])('applies %j to %j', (templatePrompt, prompt, expected) => {+ expect(applyPromptTemplate(templatePrompt, prompt)).toBe(expected);+ });++ it('merges both prompt sides and passes them through when no template is active', () => {+ expect(getEffectivePrompts({ negativePrompt: 'noise', positivePrompt: 'owl' })).toEqual({+ negativePrompt: 'noise',+ positivePrompt: 'owl',+ });+ expect(getEffectivePrompts({ negativePrompt: 'noise', positivePrompt: 'owl', promptTemplate: template })).toEqual({+ negativePrompt: 'noise, blurry',+ positivePrompt: 'photo of owl, 35mm',+ });});-});-describe('flattenPromptTemplateExpansion', () => {- it('keeps the selected positive expansion, merges the negative prompt, and clears template view state', () => {+ it('flattens with the selected positive expansion and clears template state', () => {expect(flattenPromptTemplateExpansion({- authoredNegativePrompt: 'blurry',- selectedPositivePrompt: 'a red cinematic cat',- template: {- id: 'cinematic',- name: 'Cinematic',- negativePrompt: 'lowres, {prompt}',- positivePrompt: '{prompt}, cinematic',- },+ authoredNegativePrompt: 'noise',+ selectedPositivePrompt: 'chosen expansion',+ template,})).toEqual({- negativePrompt: 'lowres, blurry',- positivePrompt: 'a red cinematic cat',+ negativePrompt: 'noise, blurry',+ positivePrompt: 'chosen expansion',promptTemplate: null,promptTemplateViewMode: false,});});-});--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' });- });+ it.each([+ ['subject', '', ['', 'subject ', '']],+ ['subject', 'cinematic', ['', 'subject ', 'cinematic']],+ ['subject', 'before {prompt} after', ['before ', 'subject', ' after']],+ ['subject', '{prompt} and {prompt}', ['', 'subject', ' and {prompt}']],+ ])('splits %j around the authored prompt', (prompt, templatePrompt, expected) => {+ const chunks = getPromptTemplateChunks(prompt, templatePrompt);- // 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');+ expect(chunks).toEqual(expected);+ expect(chunks.join('')).toBe(applyPromptTemplate(templatePrompt, prompt));});});-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.- //- // The prompts here are the interesting half: the chunks split (literal) while- // the merge replaces, and `$&` and friends are special in a replacement string- // whatever the pattern is. Holding this over one prompt let that diverge.- it('concatenates to the merged prompt', () => {- const prompts = ['a cat', 'a poster reading $$$', 'x $& y', "x $' y", 'x $` y', 'a $1 note'];-- for (const templatePrompt of ['', 'oil painting', 'a photo of {prompt}, 8k', '{prompt} by {prompt}']) {- for (const prompt of prompts) {- expect(getPromptTemplateChunks(prompt, templatePrompt).join('')).toBe(- applyPromptTemplate(templatePrompt, prompt)- );- }- }- });-});--describe('applyPromptTemplate', () => {- // Regression: the prompt was passed as a replacement *string*, so `$&` put the- // placeholder back and the expander turned it into the word "prompt", while- // `$$` swallowed a character outright.- it('substitutes the prompt literally, dollars and all', () => {- expect(applyPromptTemplate('a photo of {prompt}, 8k', 'x $& y')).toBe('a photo of x $& y, 8k');- expect(applyPromptTemplate('a photo of {prompt}, 8k', 'a poster reading $$$')).toBe(- 'a photo of a poster reading $$$, 8k'- );- expect(applyPromptTemplate('a photo of {prompt}, 8k', "x $' y")).toBe("a photo of x $' y, 8k");- });-- it('substitutes only the first placeholder', () => {- expect(applyPromptTemplate('{prompt} by {prompt}', 'a cat')).toBe('a cat by {prompt}');- });-- it('appends a template that carries no placeholder', () => {- expect(applyPromptTemplate('oil painting', 'a cat')).toBe('a cat oil painting');- });-});--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',+describe('prompt template snapshots', () => {+ it('sanitizes untrusted values and rejects unusable identities', () => {+ expect(sanitizePromptTemplateSnapshot(template)).toEqual(template);+ expect(sanitizePromptTemplateSnapshot({ id: 'template-1', name: 'Cinematic' })).toEqual({+ id: 'template-1',+ name: 'Cinematic',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();+ expect(sanitizePromptTemplateSnapshot({ id: '', name: 'Cinematic' })).toBeNull();+ expect(sanitizePromptTemplateSnapshot({ id: 'template-1', name: 3 })).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])).toEqual(edited);+ it('recognizes only exact canonical snapshots', () => {+ expect(isCanonicalPromptTemplateSnapshot(template)).toBe(true);+ expect(isCanonicalPromptTemplateSnapshot({ ...template, extra: true })).toBe(false);+ expect(isCanonicalPromptTemplateSnapshot({ ...template, id: '' })).toBe(false);+ expect(isCanonicalPromptTemplateSnapshot({ ...template, positivePrompt: null })).toBe(false);+ expect(isCanonicalPromptTemplateSnapshot(null)).toBe(false);});- // The catalog holds records, which carry `isDefault` and a host-specific- // `imageUrl`. Adopting one wholesale persisted both into project state and- // into every queue item, and put five keys on something the canonical check- // requires to have four.- it('takes only the snapshot fields from the catalog entry', () => {- const stored = template({ positivePrompt: '{prompt}, cinematic' });- const record = {- ...template({ positivePrompt: '{prompt}, cinematic, 35mm' }),- imageUrl: 'http://some-host:9090/api/v1/style_presets/t1/image',- isDefault: false,- };+ it('refreshes changed catalog fields without persisting record metadata', () => {+ const current = { ...template, name: 'Updated', hasImage: true };- expect(syncPromptTemplateWithCatalog(stored, [record])).toEqual({- ...stored,- positivePrompt: '{prompt}, cinematic, 35mm',+ expect(syncPromptTemplateWithCatalog(template, [current])).toEqual({+ id: template.id,+ name: 'Updated',+ negativePrompt: template.negativePrompt,+ positivePrompt: template.positivePrompt,});});- // 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();- });-});--// The whole point of the check is to let normalization hand a stored object-// straight back. It gates `isGenerateSettings`, so a snapshot it wrongly-// rejects re-normalises every settings read for as long as one is applied.-describe('isCanonicalPromptTemplateSnapshot', () => {- it('accepts exactly a snapshot', () => {- expect(isCanonicalPromptTemplateSnapshot(template())).toBe(true);- expect(isCanonicalPromptTemplateSnapshot(template({ name: '', negativePrompt: 'blurry' }))).toBe(true);- });-- // A catalog record is a snapshot plus `isDefault` and a host-specific- // `imageUrl`; storing one of those was how the fast path came to be dead.- it('rejects an object carrying anything more', () => {- expect(isCanonicalPromptTemplateSnapshot({ ...template(), imageUrl: null, isDefault: false })).toBe(false);- });-- it('rejects a missing or mistyped field', () => {- const { negativePrompt: _dropped, ...missing } = template();-- expect(isCanonicalPromptTemplateSnapshot(missing)).toBe(false);- expect(isCanonicalPromptTemplateSnapshot({ ...template(), positivePrompt: 42 })).toBe(false);- });-- it('rejects an empty id, which resolves against no catalog entry', () => {- expect(isCanonicalPromptTemplateSnapshot(template({ id: '' }))).toBe(false);- });-- it('rejects what is not a record at all', () => {- expect(isCanonicalPromptTemplateSnapshot(null)).toBe(false);- expect(isCanonicalPromptTemplateSnapshot([])).toBe(false);- expect(isCanonicalPromptTemplateSnapshot('template-1')).toBe(false);+ it('preserves identity when unchanged and keeps deleted snapshots', () => {+ expect(syncPromptTemplateWithCatalog(template, [{ ...template }])).toBe(template);+ expect(syncPromptTemplateWithCatalog(template, [])).toBe(template);+ 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.tsindex d36ab3d38f..b3a609574b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts@@ -1,27 +1,5 @@-/**- * 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;@@ -37,32 +15,15 @@ export interface EffectivePrompts {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.- *- * The replacement is a function rather than the prompt itself. Passing a string- * makes `$$`, `$&`, `` $` `` and `$'` inside it special even against a string- * pattern, so `a poster reading $$$` lost a character and `x $& y` re-inserted- * the literal `{prompt}` — which then reached the expander and came back as the- * word "prompt", the exact failure merging first is supposed to prevent. It also- * has to stay literal for `getPromptTemplateChunks` below, which splits, to keep- * describing what actually generates.- */+// A function replacement keeps `$` sequences in authored prompts literal.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;@@ -96,19 +57,6 @@ export const flattenPromptTemplateExpansion = ({promptTemplateViewMode: false,});-/**- * 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];@@ -122,17 +70,6 @@ export const getPromptTemplateChunks = (prompt: string, templatePrompt: string):const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null && !Array.isArray(value);-/**- * A snapshot's fields, stated once.- *- * `satisfies` is doing real work here: a field added to the interface and not to- * this list fails to compile, and so does a name here that the interface does- * not have. The check below used to carry a hardcoded `length === 4` alongside- * four `typeof` tests — two spellings of one fact, and a fifth field would have- * quietly made every valid snapshot non-canonical rather than failing the build.- *- * They are all strings; when one is not, this becomes a map of predicates.- */const SNAPSHOT_FIELDS = {id: true,name: true,@@ -142,18 +79,12 @@ const SNAPSHOT_FIELDS = {const SNAPSHOT_FIELD_NAMES = Object.keys(SNAPSHOT_FIELDS);-/**- * 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) &&Object.keys(value).length === SNAPSHOT_FIELD_NAMES.length &&SNAPSHOT_FIELD_NAMES.every((field) => typeof value[field] === 'string') &&value.id !== '';-/** Reads an untrusted persisted/transported snapshot, or `null` when unusable. */export const sanitizePromptTemplateSnapshot = (value: unknown): PromptTemplateSnapshot | null => {if (!isRecord(value)) {return null;@@ -179,17 +110,7 @@ const areSnapshotsEqual = (left: PromptTemplateSnapshot, right: PromptTemplateSnleft.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.- */+// Keep a deleted catalog entry: its snapshot still describes what the project generates.export const syncPromptTemplateWithCatalog = (promptTemplate: PromptTemplateSnapshot | null,catalog: readonly PromptTemplateSnapshot[]@@ -204,9 +125,6 @@ export const syncPromptTemplateWithCatalog = (return promptTemplate;}- // Copied down to the four fields rather than adopted whole: the catalog holds- // records, which carry a couple of extra keys that have no business being- // persisted into project state. See `toPromptTemplateSnapshot`.return {id: current.id,name: current.name,diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.test.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.test.tsindex 0a09137c6e..989955eb65 100644--- a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.test.ts@@ -2,112 +2,57 @@ import { describe, expect, it } from 'vitest';import { filterWildcards, groupWildcardsByPrefix } from './wildcardCatalog';-const wildcard = (name: string, values: string[] = []) => ({ name, values });+const wildcards = [+ { name: 'animals/dogs', values: ['terrier', 'retriever'] },+ { name: 'colours', values: ['red', 'cyberpunk blue'] },+ { name: 'architecture/gothic', values: ['cathedral'] },+];describe('filterWildcards', () => {- it('returns every wildcard for an empty query', () => {- const wildcards = [wildcard('colours'), wildcard('artists')];-- expect(filterWildcards(wildcards, '')).toEqual(wildcards);- expect(filterWildcards(wildcards, ' ')).toEqual(wildcards);- });-- it('returns a copy rather than the caller’s array', () => {- const wildcards = [wildcard('colours')];-- expect(filterWildcards(wildcards, '')).not.toBe(wildcards);- });-- it('matches names fuzzily', () => {- const wildcards = [wildcard('animals/dogs'), wildcard('colours')];-+ it('adapts wildcard names and values to catalog search', () => {expect(filterWildcards(wildcards, 'adg')).toEqual([wildcards[0]]);+ expect(filterWildcards(wildcards, 'CYBERPUNK')).toEqual([wildcards[1]]);+ expect(filterWildcards(wildcards, 'missing')).toEqual([]);});- it('matches values by substring, case-insensitively', () => {- const wildcards = [wildcard('moods', ['Cyberpunk', 'serene']), wildcard('colours', ['red'])];-- expect(filterWildcards(wildcards, 'cyberpunk')).toEqual([wildcards[0]]);- expect(filterWildcards(wildcards, 'CYBER')).toEqual([wildcards[0]]);- });-- it('ranks name matches above value-only matches', () => {- const valueOnly = wildcard('moods', ['red mist']);- const byName = wildcard('red', ['crimson']);+ it('returns a copy for an empty query and ranks a name hit above a value-only hit', () => {+ const all = filterWildcards(wildcards, '');+ const ranked = filterWildcards(+ [+ { name: 'first', values: ['colour study'] },+ { name: 'colours', values: ['red'] },+ ],+ 'colour'+ );- expect(filterWildcards([valueOnly, byName], 'red')).toEqual([byName, valueOnly]);- });-- it('lists a wildcard once when both its name and its values match', () => {- const both = wildcard('red', ['dark red', 'bright red']);-- expect(filterWildcards([both], 'red')).toEqual([both]);- });-- it('returns nothing when neither names nor values match', () => {- expect(filterWildcards([wildcard('colours', ['red'])], 'zzzz')).toEqual([]);- });-- it('finds a match in the last of many values', () => {- const long = wildcard('big', [...Array.from({ length: 500 }, (_, index) => `value-${index}`), 'needle']);-- expect(filterWildcards([long], 'needle')).toEqual([long]);+ expect(all).toEqual(wildcards);+ expect(all).not.toBe(wildcards);+ expect(ranked.map(({ name }) => name)).toEqual(['colours', 'first']);});});describe('groupWildcardsByPrefix', () => {- it('leaves a flat catalog in one unlabelled group', () => {- const wildcards = [wildcard('colours'), wildcard('artists')];-- expect(groupWildcardsByPrefix(wildcards)).toEqual([{ label: null, wildcards }]);- });-- it('groups by the segment before the first slash', () => {- const dogs = wildcard('animals/dogs');- const cats = wildcard('animals/cats');-- expect(groupWildcardsByPrefix([dogs, cats])).toEqual([{ label: 'animals', wildcards: [dogs, cats] }]);- });-- it('splits on the first slash only, so deeper names share one header', () => {- const elves = wildcard('characters/fantasy/elves');- const orcs = wildcard('characters/scifi/orcs');-- expect(groupWildcardsByPrefix([elves, orcs])).toEqual([{ label: 'characters', wildcards: [elves, orcs] }]);- });-- it('puts top-level names first, then labelled groups in first-appearance order', () => {- const dogs = wildcard('animals/dogs');- const colours = wildcard('colours');- const warm = wildcard('moods/warm');-- expect(groupWildcardsByPrefix([dogs, colours, warm])).toEqual([- { label: null, wildcards: [colours] },- { label: 'animals', wildcards: [dogs] },- { label: 'moods', wildcards: [warm] },+ it('groups on the first slash while preserving top-level and incoming order', () => {+ expect(+ groupWildcardsByPrefix([+ { name: 'animals/dogs' },+ { name: 'plain' },+ { name: 'animals/fantasy/elves' },+ { name: 'art/styles' },+ ])+ ).toEqual([+ { label: null, wildcards: [{ name: 'plain' }] },+ { label: 'animals', wildcards: [{ name: 'animals/dogs' }, { name: 'animals/fantasy/elves' }] },+ { label: 'art', wildcards: [{ name: 'art/styles' }] },]);});- it('omits the unlabelled group when every name is nested', () => {- const dogs = wildcard('animals/dogs');-- expect(groupWildcardsByPrefix([dogs])).toEqual([{ label: 'animals', wildcards: [dogs] }]);- });-- it('preserves the incoming order within a group', () => {- const cats = wildcard('animals/cats');- const dogs = wildcard('animals/dogs');-- expect(groupWildcardsByPrefix([dogs, cats])[0]?.wildcards).toEqual([dogs, cats]);- });-- it('treats a leading slash as ungrouped rather than an empty label', () => {- const odd = wildcard('/leading');-- expect(groupWildcardsByPrefix([odd])).toEqual([{ label: null, wildcards: [odd] }]);- });-- it('returns nothing for an empty catalog', () => {+ it('handles flat, all-nested, leading-slash, and empty catalogs', () => {+ expect(groupWildcardsByPrefix([{ name: 'plain' }])).toEqual([{ label: null, wildcards: [{ name: 'plain' }] }]);+ expect(groupWildcardsByPrefix([{ name: 'animals/dogs' }])).toEqual([+ { label: 'animals', wildcards: [{ name: 'animals/dogs' }] },+ ]);+ expect(groupWildcardsByPrefix([{ name: '/odd' }])).toEqual([{ label: null, wildcards: [{ name: '/odd' }] }]);expect(groupWildcardsByPrefix([])).toEqual([]);});});diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.tsindex f032e2980a..2057558044 100644--- a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts@@ -1,15 +1,3 @@-/**- * Finding one wildcard among many, and giving `a/b` names the shape their author- * meant by them.- *- * Nested names have always been legal — `WILDCARD_NAME_SOURCE` in- * `./dynamicPrompts` allows `animals/dogs` — but nothing has ever surfaced the- * nesting, so a namespaced catalog reads as a flat list of unrelated rows. Both- * helpers here are pure and ordering-preserving: the caller decides what order- * the wildcards arrive in (catalog order normally, match order while searching)- * and grouping never reshuffles it.- */-import { searchCatalog } from './catalogSearch';export interface WildcardListEntry {@@ -18,33 +6,16 @@ export interface WildcardListEntry {}export interface WildcardGroup<T> {- /** `null` for names with no `/` — those render without a header. */label: string | null;wildcards: T[];}-/**- * Name matches first, ranked fuzzily, then wildcards whose *values* contain the- * query — `searchCatalog`'s rule, which the template and history lists follow- * too. Values are this record's prose: you remember that "cyberpunk" is in one- * of these lists long before you remember which.- */+// Keep this accessor stable: catalogSearch keys its prose cache by accessor identity.const getWildcardProse = (wildcard: WildcardListEntry): readonly string[] => wildcard.values;export const filterWildcards = <T extends WildcardListEntry>(wildcards: readonly T[], query: string): T[] =>searchCatalog(wildcards, query, getWildcardProse);-/**- * Splits on the *first* `/` only. `characters/fantasy/elves` groups under- * `characters`, not `characters/fantasy` — one level of headers keeps the panel- * scannable, and a deeper tree would need collapsing to stay usable in a 14rem- * box.- *- * Top-level names come first and unlabelled, so a catalog that uses no `/` at- * all renders exactly as it did before grouping existed. Labelled groups follow- * in first-appearance order, which is match order during a search — the best hit- * stays at the top rather than being sorted away.- */export const groupWildcardsByPrefix = <T extends { name: string }>(wildcards: readonly T[]): WildcardGroup<T>[] => {const ungrouped: T[] = [];const groups = new Map<string, T[]>();diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.test.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.test.tsindex 8497c0dd17..a9104bb3ff 100644--- a/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.test.ts@@ -10,308 +10,142 @@ import {wildcardsToNestedRecord,} from './wildcardTransfer';-describe('getWildcardNameFromPath', () => {- it('drops the extension and keeps the nesting', () => {- expect(getWildcardNameFromPath('colours.txt')).toBe('colours');- expect(getWildcardNameFromPath('animals/dogs.txt')).toBe('animals/dogs');- expect(getWildcardNameFromPath('./wildcards/moods.TXT')).toBe('wildcards/moods');- });-- it('leaves an extensionless path alone', () => {- expect(getWildcardNameFromPath('colours')).toBe('colours');- });-});--describe('parseWildcardTextFile', () => {- it('reads one value per line', () => {- expect(parseWildcardTextFile('colours.txt', 'red\ngreen\nblue')).toEqual({+describe('wildcard file formats', () => {+ it.each([+ ['colours.txt', 'colours'],+ ['animals/dogs.txt', 'animals/dogs'],+ ['./wildcards/moods.TXT', 'wildcards/moods'],+ ['colours', 'colours'],+ ])('derives a wildcard name from %s', (path, expected) => {+ expect(getWildcardNameFromPath(path)).toBe(expected);+ });++ it('normalizes text values without damaging dynamic syntax', () => {+ expect(parseWildcardTextFile('colours.txt', '# list\r\n red \r\n\r\n{green|blue} # choice\n__other__')).toEqual({name: 'colours',- values: ['red', 'green', 'blue'],+ values: ['red', '{green|blue}', '__other__'],});});- it('drops comments and blank lines', () => {- const parsed = parseWildcardTextFile('colours.txt', '# a list\nred\n\n green # the good one\n');-- expect(parsed.values).toEqual(['red', 'green']);- });-- it('reads CRLF files', () => {- expect(parseWildcardTextFile('colours.txt', 'red\r\ngreen').values).toEqual(['red', 'green']);- });-- it('keeps dynamic syntax inside a value', () => {- expect(parseWildcardTextFile('c.txt', '{red|green} ball\n__other__').values).toEqual([- '{red|green} ball',- '__other__',- ]);- });-});--describe('wildcardsFromNestedRecord', () => {- it('flattens nesting into slash-separated names', () => {- expect(wildcardsFromNestedRecord({ animals: { cats: ['tabby'], dogs: ['corgi', 'husky'] } })).toEqual([- { name: 'animals/cats', values: ['tabby'] },- { name: 'animals/dogs', values: ['corgi', 'husky'] },- ]);- });-- // The `.txt` reader has always stripped these. A YAML or JSON collection kept- // them, so the same list imported two ways gave two different catalogs — and- // the one that kept the `#` held values that expand to nothing.- it('drops comments the way the text reader does', () => {- expect(wildcardsFromNestedRecord({ colours: ['poster #1', '#ff0000 glow', 'blue'] })).toEqual([- { name: 'colours', values: ['poster', 'blue'] },- ]);- });-- it('takes a key that already contains a slash as written', () => {- expect(wildcardsFromNestedRecord({ 'animals/dogs': ['corgi'] })).toEqual([+ it('flattens nested records, normalizes values, and ignores non-list leaves', () => {+ expect(+ wildcardsFromNestedRecord({+ animals: { dogs: ['corgi'] },+ 'animals/cats': ['tabby'],+ note: 'ignored',+ colours: ['poster #1', '#ff0000', '', 1970, true],+ })+ ).toEqual([{ name: 'animals/dogs', values: ['corgi'] },+ { name: 'animals/cats', values: ['tabby'] },+ { name: 'colours', values: ['poster', '1970', 'true'] },]);- });-- it('stringifies scalars an unquoted file produces', () => {- expect(wildcardsFromNestedRecord({ years: [1970, 3.5, true] })).toEqual([- { name: 'years', values: ['1970', '3.5', 'true'] },- ]);- });-- it('ignores leaves that are not lists, per the spec', () => {- expect(wildcardsFromNestedRecord({ colours: ['red'], note: 'not a list', nothing: null })).toEqual([- { name: 'colours', values: ['red'] },- ]);- });-- it('drops blank entries', () => {- expect(wildcardsFromNestedRecord({ colours: ['red', '', ' '] })).toEqual([{ name: 'colours', values: ['red'] }]);- });-- it('returns nothing for input that is not a mapping', () => {- expect(wildcardsFromNestedRecord(['red'])).toEqual([]);expect(wildcardsFromNestedRecord(null)).toEqual([]);- expect(wildcardsFromNestedRecord('red')).toEqual([]);- });-});--describe('wildcardsToNestedRecord', () => {- it('nests on the slashes', () => {- expect(- wildcardsToNestedRecord([- { name: 'animals/dogs', values: ['corgi'] },- { name: 'animals/cats', values: ['tabby'] },- { name: 'colours', values: ['red'] },- ])- ).toEqual({ animals: { cats: ['tabby'], dogs: ['corgi'] }, colours: ['red'] });});- // `animals` holds a value list, so `animals/dogs` has nowhere to nest into.- it('falls back to a flat key when a prefix is itself a wildcard', () => {- expect(- wildcardsToNestedRecord([- { name: 'animals', values: ['bear'] },- { name: 'animals/dogs', values: ['corgi'] },- ])- ).toEqual({ animals: ['bear'], 'animals/dogs': ['corgi'] });- });-- // Regression: deciding this as the loop went meant the child overwrote the- // parent, or the parent the child, depending on which came first.- it('resolves a parent/child clash the same way whichever order they arrive in', () => {+ it('nests slash names and round-trips parent/child collisions independent of order', () => {const parent = { name: 'animals', values: ['bear'] };const child = { name: 'animals/dogs', values: ['corgi'] };+ const colours = { name: 'colours', values: ['red'] };+ const nested = wildcardsToNestedRecord([child, parent, colours]);- expect(wildcardsToNestedRecord([child, parent])).toEqual(wildcardsToNestedRecord([parent, child]));- });-- it('round-trips through the nested form', () => {- const wildcards = [- { name: 'animals/dogs', values: ['corgi'] },- { name: 'animals', values: ['bear'] },- { name: 'colours', values: ['red', 'green'] },- ];-- expect(- wildcardsFromNestedRecord(wildcardsToNestedRecord(wildcards)).sort((a, b) => a.name.localeCompare(b.name))- ).toEqual(wildcards.sort((a, b) => a.name.localeCompare(b.name)));+ expect(nested).toEqual({ animals: ['bear'], 'animals/dogs': ['corgi'], colours: ['red'] });+ expect(wildcardsToNestedRecord([parent, child])).toEqual(wildcardsToNestedRecord([child, parent]));+ expect(wildcardsFromNestedRecord(nested).sort((a, b) => a.name.localeCompare(b.name))).toEqual(+ [parent, child, colours].sort((a, b) => a.name.localeCompare(b.name))+ );});- // Regression: `node[segment] ??= {}` declines to assign when the inherited- // value is truthy, so the walk stepped onto `Object.prototype` and wrote the- // leaf there. `constructor`, `toString` and `valueOf` are all valid wildcard- // names on both sides of the wire.- it('nests a name that collides with something on Object.prototype', () => {- const inheritedNames = ['constructor', 'toString', 'valueOf', 'hasOwnProperty'];- const wildcards = inheritedNames.map((name) => ({ name: `${name}/keys`, values: ['red', 'blue'] }));+ it('does not traverse Object.prototype for user-authored path segments', () => {+ const names = ['constructor', 'toString', 'valueOf', 'hasOwnProperty'];+ const wildcards = names.map((name) => ({ name: `${name}/keys`, values: ['red'] }));const nested = wildcardsToNestedRecord(wildcards);expect(typeof Object.keys).toBe('function');- expect(Object.keys(nested)).toEqual(inheritedNames);- expect(JSON.parse(JSON.stringify(nested))).toEqual(- Object.fromEntries(inheritedNames.map((name) => [name, { keys: ['red', 'blue'] }]))- );+ expect(Object.keys(nested)).toEqual(names);expect(wildcardsFromNestedRecord(nested)).toEqual(wildcards);- });-- it('keeps such a name as a leaf too', () => {- const nested = wildcardsToNestedRecord([{ name: 'constructor', values: ['red'] }]);-- expect(JSON.stringify(nested)).toBe('{"constructor":["red"]}');+ expect(JSON.stringify(wildcardsToNestedRecord([{ name: 'constructor', values: ['red'] }]))).toBe(+ '{"constructor":["red"]}'+ );});});-describe('planWildcardImport', () => {+describe('wildcard import planning', () => {const existing = [{ id: 'w1', name: 'colours' }];- it('marks a clash with the wildcard it would overwrite', () => {- const [clashing, fresh] = planWildcardImport(+ it('marks catalog clashes and distinguishes rejection causes', () => {+ const entries = planWildcardImport([{ name: 'colours', values: ['red'] },- { name: 'moods', values: ['calm'] },+ { name: 'new', values: ['calm'] },+ { name: 'bad name!', values: ['x'] },+ { name: 'a'.repeat(129), values: ['x'] },+ { name: 'empty', values: [] },+ { name: 'many', values: Array.from({ length: 10_001 }, (_, index) => String(index)) },+ { name: 'long', values: ['x'.repeat(2_001)] },],existing);- expect(clashing).toMatchObject({ conflictId: 'w1', rejection: null });- expect(fresh).toMatchObject({ conflictId: null, rejection: null });- });-- it('reports a name the backend would refuse rather than mangling it', () => {- const [entry] = planWildcardImport([{ name: 'my colours!', values: ['red'] }], existing);-- expect(entry.rejection).toBe('invalid');- });-- it('reports an over-long name', () => {- const [entry] = planWildcardImport([{ name: 'a'.repeat(129), values: ['red'] }], existing);-- expect(entry.rejection).toBe('tooLong');- });-- it('reports an empty list instead of creating a wildcard that expands to nothing', () => {- const [entry] = planWildcardImport([{ name: 'moods', values: [] }], existing);-- expect(entry.rejection).toBe('noValues');- });-- // Two different problems with two different remedies: a list to trim, or a- // single value to shorten. Reporting both as "too many values" left someone- // holding three values and one long paragraph with nothing to act on.- it('tells a long list apart from a long value', () => {- const [tooMany, valueTooLong] = planWildcardImport(- [- { name: 'many', values: Array.from({ length: 10_001 }, (_, index) => `v${index}`) },- { name: 'long', values: ['ok', 'x'.repeat(2_001)] },- ],- existing- );-- expect(tooMany.rejection).toBe('tooManyValues');- expect(valueTooLong.rejection).toBe('valueTooLong');+ expect(entries.map(({ conflictId, rejection }) => ({ conflictId, rejection }))).toEqual([+ { conflictId: 'w1', rejection: null },+ { conflictId: null, rejection: null },+ { conflictId: null, rejection: 'invalid' },+ { conflictId: null, rejection: 'tooLong' },+ { conflictId: null, rejection: 'noValues' },+ { conflictId: null, rejection: 'tooManyValues' },+ { conflictId: null, rejection: 'valueTooLong' },+ ]);});- // Regression: the name was recorded as seen whether or not the entry survived,- // so a rejected one shadowed a perfectly good later entry and neither landed.- it('does not let a rejected entry shadow a good one with the same name', () => {- const entries = planWildcardImport(- [- { name: 'colours', values: [] },- { name: 'colours', values: ['red', 'green'] },- ],- existing- );-- expect(entries.map((entry) => entry.rejection)).toEqual(['noValues', null]);+ it('only lets an accepted entry claim a repeated name', () => {+ expect(+ planWildcardImport(+ [+ { name: 'moods', values: [] },+ { name: 'moods', values: ['calm'] },+ { name: 'moods', values: ['tense'] },+ ],+ []+ ).map(({ rejection }) => rejection)+ ).toEqual(['noValues', null, 'duplicate']);+ });++ it('finds a valid available suffix within the name limit', () => {+ expect(getAvailableWildcardName('colours', new Set(['colours', 'colours-2']))).toBe('colours-3');+ expect(getAvailableWildcardName('a'.repeat(128), new Set())).toMatch(/^a+-2$/);+ expect(getAvailableWildcardName(`${'a'.repeat(125)}b--`, new Set())).toMatch(/^a+b-2$/);});- it('keeps the first of a name repeated within one import and reports the rest', () => {+ it('creates, replaces, skips, and renames planned entries without collisions', () => {const entries = planWildcardImport([+ { name: 'colours', values: ['red'] },+ { name: 'colours-2', values: ['green'] },{ name: 'moods', values: ['calm'] },- { name: 'moods', values: ['tense'] },+ { name: 'bad name!', values: ['x'] },],existing);- expect(entries.map((entry) => entry.rejection)).toEqual([null, 'duplicate']);- });-});--describe('getAvailableWildcardName', () => {- it('suffixes until the name is free', () => {- expect(getAvailableWildcardName('colours', new Set(['colours']))).toBe('colours-2');- expect(getAvailableWildcardName('colours', new Set(['colours', 'colours-2']))).toBe('colours-3');- });-- it('trims the base so the suffix fits the length limit', () => {- const name = getAvailableWildcardName('a'.repeat(128), new Set());-- expect(name).toHaveLength(128);- expect(name.endsWith('-2')).toBe(true);- });-- // A name may not end in a hyphen, so trimming must not leave one exposed.- it('leaves a valid name after trimming', () => {- expect(getAvailableWildcardName(`${'a'.repeat(125)}b--`, new Set())).toMatch(/^a+b-2$/);- });-});--describe('getWildcardImportActions', () => {- const entries = planWildcardImport(- [- { name: 'colours', values: ['red'] },- { name: 'moods', values: ['calm'] },- { name: 'bad name!', values: ['x'] },- ],- [{ id: 'w1', name: 'colours' }]- );- const existingNames = new Set(['colours']);-- it('creates the new ones and skips clashes by default', () => {- expect(getWildcardImportActions(entries, {}, existingNames)).toEqual([{ name: 'moods', values: ['calm'] }]);- });-- it('updates in place when a clash is replaced', () => {- expect(getWildcardImportActions(entries, { colours: 'replace' }, existingNames)).toEqual([- { id: 'w1', name: 'colours', values: ['red'] },- { name: 'moods', values: ['calm'] },- ]);- });-- it('renames when a clash keeps both', () => {- expect(getWildcardImportActions(entries, { colours: 'keepBoth' }, existingNames)).toEqual([- { name: 'colours-2', values: ['red'] },+ expect(getWildcardImportActions(entries, {}, new Set(['colours']))).toEqual([+ { name: 'colours-2', values: ['green'] },{ name: 'moods', values: ['calm'] },]);- });-- // Regression: only the catalog seeded the taken set, so "keep both" picked- // `colours-2` without noticing the same file was already creating one, and the- // two creates raced to the same name — the loser aborting the import.- it('does not rename onto a name the same import is creating', () => {- const clashing = planWildcardImport(- [- { name: 'colours', values: ['red'] },- { name: 'colours-2', values: ['green'] },- ],- [{ id: 'w1', name: 'colours' }]- );-- expect(getWildcardImportActions(clashing, { colours: 'keepBoth' }, new Set(['colours']))).toEqual([+ expect(getWildcardImportActions(entries, { colours: 'replace' }, new Set(['colours']))).toContainEqual({+ id: 'w1',+ name: 'colours',+ values: ['red'],+ });+ expect(getWildcardImportActions(entries, { colours: 'keepBoth' }, new Set(['colours']))).toEqual([{ name: 'colours-3', values: ['red'] },{ name: 'colours-2', values: ['green'] },+ { name: 'moods', values: ['calm'] },]);});- it('never emits an action for a rejected entry', () => {- const actions = getWildcardImportActions(entries, { 'bad name!': 'replace', colours: 'replace' }, existingNames);-- expect(actions.some((action) => action.name === 'bad name!')).toBe(false);- });-- // Two "keep both" clashes must not both land on `-2`.- it('gives each kept-both clash its own name', () => {- const clashes = planWildcardImport(+ it('allocates a distinct suffix to each keep-both clash', () => {+ const entries = planWildcardImport([{ name: 'colours', values: ['red'] },{ name: 'moods', values: ['calm'] },@@ -323,7 +157,7 @@ describe('getWildcardImportActions', () => {);expect(- getWildcardImportActions(clashes, { colours: 'keepBoth', moods: 'keepBoth' }, new Set(['colours', 'moods']))+ getWildcardImportActions(entries, { colours: 'keepBoth', moods: 'keepBoth' }, new Set(['colours', 'moods']))).toEqual([{ name: 'colours-2', values: ['red'] },{ name: 'moods-2', values: ['calm'] },diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.tsindex 5efd60d135..757e093991 100644--- a/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.ts@@ -1,25 +1,3 @@-/**- * Moving wildcards in and out of the app as files.- *- * There are no backend routes for this — wildcards are per-user CRUD, unlike- * style presets whose transfer is admin-only and server-side — so the whole- * format layer lives here and the UI issues ordinary creates and updates.- *- * Formats follow the `adieyal/dynamicprompts` file conventions, so a catalog can- * move between this and an a1111 install:- *- * - **`.txt`** — one file per wildcard, its path supplying the name and each- * line a value. Import only: a folder of them is the shape people already- * have, but writing one back per wildcard would mean a download per row.- * - **`.yaml` / `.json`** — a nested mapping whose arrays are the value lists,- * with nesting standing in for `/` in a name. Both directions.- *- * Everything here is pure and synchronous, over structures somebody else has- * already parsed. That keeps the YAML dependency in the UI layer, behind a- * dynamic import, so it loads only when a file is actually being read or- * written rather than riding along in the generate widget's chunk.- */-import {getWildcardNameError,getWildcardValuesError,@@ -32,25 +10,12 @@ export interface ParsedWildcard {values: string[];}-/** Mirrors the backend's per-wildcard limits, so a doomed request is never sent. */--/**- * `animals/dogs.txt` → `animals/dogs`. Directory picking hands back a relative- * path, which is exactly the nesting the name wants, so it is kept.- */export const getWildcardNameFromPath = (path: string): string =>path.replace(/\.[^./]*$/, '').replace(/^[./]+/, '').trim();-/**- * One `.txt` file: a value per line, `#` comments and blank lines dropped.- *- * `#` is a comment in a prompt too, and a wildcard's values are expanded as- * prompts, so a value that kept its `#` would silently lose everything after it- * at generate time anyway.- */export const parseWildcardTextFile = (path: string, contents: string): ParsedWildcard => ({name: getWildcardNameFromPath(path),values: normalizeWildcardValues(contents.split(/\r?\n/)),@@ -59,13 +24,6 @@ export const parseWildcardTextFile = (path: string, contents: string): ParsedWilconst isPlainObject = (value: unknown): value is Record<string, unknown> =>typeof value === 'object' && value !== null && !Array.isArray(value);-/**- * A value list, or `null` when this leaf is not one.- *- * Scalars are stringified rather than dropped: an unquoted `1970` or `3.5` in a- * hand-written YAML file is a value the author meant, not a type declaration.- * Nulls and nested structures are ignored, per the upstream spec.- */const toValues = (value: unknown): string[] | null => {if (!Array.isArray(value)) {return null;@@ -78,12 +36,6 @@ const toValues = (value: unknown): string[] | null => {);};-/**- * A nested mapping — from YAML or JSON — flattened to `a/b` names.- *- * A key that already contains `/` is taken as written, so a flat file and a- * nested one both round-trip to the same catalog.- */export const wildcardsFromNestedRecord = (value: unknown): ParsedWildcard[] => {const wildcards: ParsedWildcard[] = [];@@ -109,31 +61,13 @@ export const wildcardsFromNestedRecord = (value: unknown): ParsedWildcard[] => {return wildcards;};-/** Every prefix of `a/b/c` that could be a wildcard in its own right: `a`, `a/b`. */const getAncestorNames = (name: string): string[] => {const segments = name.split('/');return segments.slice(0, -1).map((_, index) => segments.slice(0, index + 1).join('/'));};-/**- * The inverse: `animals/dogs` becomes `{ animals: { dogs: [...] } }`.- *- * `animals` alongside `animals/dogs` cannot both nest — one key would have to- * hold a value list and a mapping at once. The *parent* wins its natural key and- * the child keeps its full name as a flat one, which `wildcardsFromNestedRecord`- * reads back identically. Deciding this from the name set rather than from- * whatever the loop has written so far keeps the output independent of the order- * the wildcards arrive in.- *- * Every level is a null-prototype object, and levels are created through an own- * key check rather than `??=`. A name segment is user text, and `constructor`,- * `toString` and `valueOf` are all valid wildcard names: on an ordinary `{}` the- * inherited value is truthy, so `??=` would decline to assign and the walk would- * step onto `Object.prototype` and write the leaf there. `Object.keys` becoming- * an array of colours takes the whole tab down, and the wildcard vanishes from- * the export either way.- */+// Every path segment is user text, so levels must not inherit prototype keys.export const wildcardsToNestedRecord = (wildcards: readonly ParsedWildcard[]): Record<string, unknown> => {const root: Record<string, unknown> = Object.create(null) as Record<string, unknown>;const names = new Set(wildcards.map((wildcard) => wildcard.name));@@ -180,20 +114,10 @@ export type WildcardImportResolution = 'keepBoth' | 'replace' | 'skip';export interface WildcardImportEntry {name: string;values: string[];- /** The wildcard this would overwrite, or `null` when the name is new. */conflictId: string | null;- /** Why this entry cannot be imported at all, or `null`. */rejection: WildcardImportRejection | null;}-/**- * What a file would do to the catalog, before anything is sent.- *- * Nothing is dropped quietly. A name the backend would refuse, a list that is- * empty or too long, and a name repeated within the same import all come back- * as entries carrying their reason, so the dialog can say what it is not going- * to do rather than appearing to have imported everything.- */export const planWildcardImport = (parsed: readonly ParsedWildcard[],existing: readonly { id: string; name: string }[]@@ -207,8 +131,6 @@ export const planWildcardImport = (if (nameError === 'tooLong') {return 'tooLong';}- // An empty name means the file was named something unusable, which is the- // same problem as an invalid one from the reader's side.if (nameError !== null) {return 'invalid';}@@ -224,19 +146,12 @@ export const planWildcardImport = (return parsed.map((wildcard) => {const rejection = getRejection(wildcard);- // Only entries that will actually be written claim the name. Recording- // rejected ones too meant an empty `colours.txt` earlier in the selection- // made a populated `colours.yaml` later in it read as a repeat, and neither- // was imported.if (rejection === null) {seen.add(wildcard.name.trim());}return {conflictId: existingByName.get(wildcard.name.trim()) ?? null,- // The trimmed form throughout: validation trims before deciding, so- // storing the untrimmed one would send the server something the client- // never checked, and look it up under a name it was not filed under.name: wildcard.name.trim(),rejection,values: wildcard.values,@@ -244,13 +159,6 @@ export const planWildcardImport = (});};-/**- * `colours` → `colours-2`, then `-3`, and so on.- *- * The base is trimmed rather than the suffix dropped when the two together- * would exceed the backend's length limit — a name one character over the line- * is not a reason to refuse the import.- */export const getAvailableWildcardName = (name: string, taken: ReadonlySet<string>): string => {for (let suffix = 2; ; suffix++) {const marker = `-${suffix}`;@@ -266,21 +174,9 @@ export const getAvailableWildcardName = (name: string, taken: ReadonlySet<stringexport interface WildcardImportAction {name: string;values: string[];- /** Present for a replacement; absent when this creates a new wildcard. */id?: string;}-/**- * The writes a planned import resolves to, in order.- *- * `taken` grows as it goes, so importing two clashing names as "keep both" gives- * `colours-2` and `colours-3` rather than the same suffix twice.- *- * It is seeded with the names the import itself is about to claim, not just the- * ones already in the catalog. A file holding `colours` (clashing) and a new- * `colours-2` otherwise had the first resolve to `colours-2` as well, and the- * two creates raced each other to the same name.- */export const getWildcardImportActions = (entries: readonly WildcardImportEntry[],resolutions: Readonly<Record<string, WildcardImportResolution>>,diff --git a/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.tsindex dc002d788f..3dc54a054b 100644--- a/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/promptTemplates.ts@@ -1,16 +1,3 @@-/**- * The current user's prompt templates, plus the catalog shipped with the backend.- *- * The route is `/api/v1/style_presets/` — "style preset" is the backend's name- * for the same thing, kept for wire compatibility with the legacy client, which- * writes to and reads from this exact store. Only this module speaks that- * vocabulary; everything above it says "prompt template".- *- * Create and update are multipart because a template may carry a preview image.- * `apiFetchJson` leaves `FormData` bodies alone, so the browser sets its own- * boundary while the injected `Authorization` header still rides along.- */-import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';import type { AccountScope } from '@platform/state/accountLifecycle';import type { QueryClient } from '@tanstack/react-query';@@ -21,7 +8,6 @@ import { queryOptions } from '@tanstack/react-query';const PROMPT_TEMPLATES_BASE = '/api/v1/style_presets';-/** Private snake_case wire shape; never crosses the feature interface. */interface PromptTemplateDTO {id: string;name: string;@@ -33,23 +19,12 @@ interface PromptTemplateDTO {}export interface PromptTemplateRecord extends PromptTemplateSnapshot {- /** `default` templates ship with the backend and are read-only here. */isDefault: boolean;- /** Whether the authenticated image resource should be requested. */hasImage: boolean;isPublic: boolean;userId: string;}-/**- * The four fields a record shares with a snapshot, and no more.- *- * A record is assignable to a snapshot, so applying one type-checks and keeps- * catalog-only fields such as `isDefault` and `hasImage` along for the ride.- * They then land in persisted project state and every queue item's widget- * snapshot. Extra keys also make `isCanonicalPromptTemplateSnapshot` reject the- * object, so the identity short-circuits in settings normalization never fire.- */export const toPromptTemplateSnapshot = ({id,name,@@ -109,11 +84,6 @@ export const promptTemplatesQueryOptions = () =>});})();-/**- * Authored templates are always the user's own and private. The backend also- * models admin-owned `default` templates and an `is_public` share flag; neither- * is authored from here, so both are pinned rather than exposed.- */const toFormData = (draft: PromptTemplateDraftFields): FormData => {const body = new FormData();@@ -188,7 +158,6 @@ export const deletePromptTemplate = async (id: string): Promise<void> => {await apiFetch(`${PROMPT_TEMPLATES_BASE}/i/${encodeURIComponent(id)}`, { method: 'DELETE' });};-/** Accepts the CSV and JSON shapes documented by the backend's importer. */export const importPromptTemplates = async (file: File, owner: AccountScope): Promise<void> => {const body = new FormData();@@ -198,11 +167,6 @@ export const importPromptTemplates = async (file: File, owner: AccountScope): PrassertAccountScopeCurrent(owner);};-/**- * Returns CSV, not JSON, so this goes through `apiFetch` rather than- * `apiFetchJson`. It also cannot be an anchor download: the URL alone carries no- * `Authorization` header, and only the transport injects one.- */export const exportPromptTemplates = async (owner: AccountScope): Promise<Blob> => {const response = await apiFetch(`${PROMPT_TEMPLATES_BASE}/export`, { signal: owner.signal });assertAccountScopeCurrent(owner);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsxindex 52f71a609c..257f5f5c13 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx@@ -12,24 +12,10 @@ import { useTranslation } from 'react-i18next';const LIST_WIDTH_PX = 260;const MAX_LIST_HEIGHT_PX = 220;-/** Clear of the current line, so the list never covers what is being typed. */const CARET_GAP_PX = 4;const VIEWPORT_MARGIN_PX = 8;const OPTION_HOVER_CSS = { bg: 'bg.emphasized' };-/**- * The list that follows the caret while a `__` or `<` is being typed.- *- * Deliberately not a `Popover`: this must never take focus. The user is typing- * in the textarea and the textarea stays the active element throughout — arrow- * keys, Enter and Escape are handled there and only reach here as the- * `activeIndex` prop. That also makes it a plain positioned surface rather than- * a dismissable layer, which is why there is no trigger and no close button.- *- * The old picker anchored to the whole textarea and opened `bottom-start`, so in- * a tall prompt box the list appeared at the bottom-left corner — often hundreds- * of pixels from where the user was looking.- */export const PromptTriggerAutocomplete = ({activeIndex,caretRect,@@ -47,10 +33,6 @@ export const PromptTriggerAutocomplete = ({}) => {const { t } = useTranslation();const listRef = useRef<HTMLDivElement | null>(null);- // Each group carries where it starts in the flat list. The hook selects with- // `options[activeIndex]`, so the ids have to be numbered the same way — and- // counting them up as the rows render, which is what this replaced, only- // agreed with that while grouping happened to be an order-preserving no-op.const groups = useMemo(() =>groupPromptTriggerOptions(options).reduce<(PromptTriggerOptionGroup & { startIndex: number })[]>(@@ -66,13 +48,7 @@ export const PromptTriggerAutocomplete = ({[options]);- // Below the caret when there is room, above it when there is not, and never- // off the right edge of a narrow window.const spaceBelow = window.innerHeight - (caretRect.y + caretRect.height);- // Clamped: in a short viewport with the caret near the top there is room on- // neither side, and the subtraction went negative — `maxH="-2px"` is dropped- // by the browser, so the list sprang to full height and was then positioned- // from that negative number.const height = Math.max(0,Math.min(MAX_LIST_HEIGHT_PX, Math.max(spaceBelow, caretRect.y) - VIEWPORT_MARGIN_PX - CARET_GAP_PX)@@ -84,8 +60,6 @@ export const PromptTriggerAutocomplete = ({);const top = opensBelow ? caretRect.y + caretRect.height + CARET_GAP_PX : caretRect.y - height - CARET_GAP_PX;- // Keyboard navigation moves a highlight the mouse never touches, so the list- // has to follow it rather than waiting to be scrolled.useLayoutEffect(() => {listRef.current?.querySelector(`#${CSS.escape(`${optionIdPrefix}${activeIndex}`)}`)@@ -151,9 +125,6 @@ const AutocompleteOption = ({option: PromptTriggerOption;onSelect: (option: PromptTriggerOption) => void;}) => {- // On mousedown, not click, and with the default prevented: letting the press- // blur the textarea would close the list out from under the pointer. Primary- // button only — a right-click is after the context menu, not an insertion.const handleMouseDown = useCallback((event: MouseEvent<HTMLDivElement>) => {if (event.button !== 0) {@@ -177,8 +148,6 @@ const AutocompleteOption = ({px="2"py="1"role="option"- // Focus stays in the textarea and moves through `aria-activedescendant`;- // the options are only ever reachable that way, never by tabbing.tabIndex={-1}truncate_hover={OPTION_HOVER_CSS}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsxindex 62af58511e..438c417357 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx@@ -1,7 +1,6 @@/* 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 { getTextareaCaretRect } from '@features/generation/ui/promptFields/promptCaret';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act } from 'react';@@ -9,8 +8,6 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';-// The actions row needs Generation's UI port and is not what these tests are-// about; the caret autocomplete underneath it is entirely real.vi.mock('@features/generation/ui/promptFields/PositivePromptActions', () => ({PositivePromptActions: () => null,PromptTriggerPopover: () => null,@@ -41,7 +38,6 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-/** Tall on purpose: the old picker anchored to the whole box, which is the bug. */const TEXTAREA_HEIGHT_PX = 320;const render = async (isTemplateViewMode = false) => {@@ -70,7 +66,6 @@ const render = async (isTemplateViewMode = false) => {);});- // The option list is fed by the wildcard query, which resolves a tick later.await act(async () => {await new Promise((resolve) => {setTimeout(resolve, 0);@@ -114,30 +109,6 @@ afterEach(async () => {});describe('the caret autocomplete', () => {- // Regression: the picker opened on any second underscore and swallowed the- // keystroke, so an ordinary word containing `__` could not be typed at all.- it('leaves an underscore inside a word alone', async () => {- await type('a close_up shot');-- expect(textarea().value).toBe('a close_up shot');- expect(listbox()).toBeNull();- });-- it('types a double underscore mid-word without opening', async () => {- await type('snake__case');-- expect(textarea().value).toBe('snake__case');- expect(listbox()).toBeNull();- });-- it('opens on `__` where a wildcard reference could begin', async () => {- await type('a photo of __');-- expect(optionLabels()).toEqual(['colors', 'moods']);- });-- // Each delimiter offers only what it can actually open. `jugg`, the model's- // trigger phrase, belongs to neither and stays with the `+` button.it('offers embeddings for `<` and wildcards for `__`, and phrases for neither', async () => {await type('a photo of <');@@ -149,33 +120,12 @@ describe('the caret autocomplete', () => {expect(optionLabels()).toEqual(['colors', 'moods']);});- it('inserts an embedding with its angle brackets', async () => {- await type('a photo of <easy');- await press('{Enter}');-- expect(textarea().value).toBe('a photo of <easynegative>');- });-- // The whole point: nothing is swallowed, so there is nothing to give back.- it('leaves the typed characters in the prompt while it is open', async () => {- await type('a photo of __');-- expect(textarea().value).toBe('a photo of __');- });-it('narrows as the name is typed, where the user is already looking', async () => {await type('a photo of __mo');expect(optionLabels()).toEqual(['moods']);});- it('closes when nothing matches, rather than showing an empty list', async () => {- await type('a photo of __zzz');-- expect(listbox()).toBeNull();- expect(textarea().value).toBe('a photo of __zzz');- });-it('opens beside the caret, not at the bottom of a tall box', async () => {await type('a photo of __');@@ -183,52 +133,9 @@ describe('the caret autocomplete', () => {const list = listbox()!.getBoundingClientRect();expect(box.height).toBeGreaterThan(200);- // On the first line of the prompt, so the list belongs at the top of the box.expect(list.top - box.top).toBeLessThan(80);});- // The complaint this whole thing exists to answer: the list used to open at- // the bottom-left of the box no matter where you were typing.- it('follows the caret down the box', async () => {- await type('one\ntwo\nthree\nfour\nfive\nsix __');-- const box = textarea().getBoundingClientRect();- const list = listbox()!.getBoundingClientRect();-- expect(list.top - box.top).toBeGreaterThan(60);- });-- // The rest of the caret coverage uses hard newlines, which any mirror gets- // right. Soft wrapping is the case the mirror's own width decides, and nothing- // exercised it. Asserted on the measurement rather than the rendered list,- // which flips above the caret near the bottom of a full box.- it('agrees with the textarea about where soft wrapping put the caret', () => {- const element = textarea();- // Long enough to overflow the box, so `scrollHeight` reports the real line- // count rather than being floored at the visible height.- const text = 'lorem ipsum dolor sit amet '.repeat(100);-- element.value = text;-- const style = getComputedStyle(element);- const lineHeight = Number.parseFloat(style.lineHeight);- const paddingTop = Number.parseFloat(style.paddingTop);- const lines = Math.round((element.scrollHeight - paddingTop - Number.parseFloat(style.paddingBottom)) / lineHeight);- const rect = getTextareaCaretRect(element, text.length)!;- const line = Math.round((rect.y - element.getBoundingClientRect().top - paddingTop) / lineHeight) + 1;-- expect(lines).toBeGreaterThan(2);- expect(line).toBe(lines);- });-- it('inserts the highlighted option on Enter', async () => {- await type('a photo of __');- await press('{Enter}');-- expect(textarea().value).toBe('a photo of __colors__');- expect(listbox()).toBeNull();- });-it('moves the highlight with the arrow keys', async () => {await type('a photo of __');await press('{ArrowDown}');@@ -237,21 +144,6 @@ describe('the caret autocomplete', () => {expect(textarea().value).toBe('a photo of __moods__');});- it('wraps the highlight around the ends of the list', async () => {- await type('a photo of __');- await press('{ArrowUp}');- await press('{Enter}');-- expect(textarea().value).toBe('a photo of __moods__');- });-- it('replaces what was typed, not just the trigger', async () => {- await type('a photo of __mo');- await press('{Enter}');-- expect(textarea().value).toBe('a photo of __moods__');- });-const mouseDownOnFirstOption = (button: number) => {const option = listbox()!.querySelector('[role="option"]')!;@@ -260,16 +152,6 @@ describe('the caret autocomplete', () => {});};- it('inserts the option the pointer pressed', async () => {- await type('a photo of __');- await mouseDownOnFirstOption(0);-- expect(textarea().value).toBe('a photo of __colors__');- });-- // The press has to insert from the field the query was read from. Reading it- // back off the document instead meant a non-textarea gave `undefined` for the- // current value, and the insert committed the option over the whole prompt.it('keeps the rest of the prompt when the pointer selects', async () => {await type('a photo of __co');const activeElement = vi.spyOn(document, 'activeElement', 'get').mockReturnValue(document.body);@@ -279,16 +161,6 @@ describe('the caret autocomplete', () => {expect(textarea().value).toBe('a photo of __colors__');});- it('ignores a right-click on an option', async () => {- await type('a photo of __');- await mouseDownOnFirstOption(2);-- expect(textarea().value).toBe('a photo of __');- });-- // An IME sends every key through `keydown` while composing. Taking ArrowDown- // and Enter for the list leaves the candidate window unusable, so a Japanese- // or Chinese user cannot commit a word at all.describe('while an IME is composing', () => {const compose = (type: 'compositionend' | 'compositionstart') =>act(() => {@@ -302,48 +174,29 @@ describe('the caret autocomplete', () => {);});- it('leaves Enter to the composition instead of inserting', async () => {+ it('leaves navigation and commit keys to the IME, then reopens on composition end', async () => {await type('a photo of __');await compose('compositionstart');- await pressWhileComposing('Enter');+ expect(listbox()).toBeNull();+ await pressWhileComposing('Enter');+ await pressWhileComposing('ArrowDown');expect(textarea().value).toBe('a photo of __');- });- it('leaves the arrow keys to the candidate window', async () => {- await type('a photo of __');- await compose('compositionstart');- await pressWhileComposing('ArrowDown');await compose('compositionend');- await press('{Enter}');+ expect(optionLabels()).toEqual(['colors', 'moods']);- // Still the first option: the arrow moved an IME candidate, not this list.+ await press('{Enter}');expect(textarea().value).toBe('a photo of __colors__');});-- it('reopens against the committed text once composition ends', async () => {- await type('a photo of __');- await compose('compositionstart');-- expect(listbox()).toBeNull();-- await compose('compositionend');-- expect(optionLabels()).toEqual(['colors', 'moods']);- });});- // The list is placed once from a viewport rect and never re-measured, and the- // textarea keeps focus throughout — so without this it stayed welded to where- // the caret used to be while the prompt scrolled away underneath it.it('closes when something scrolls under it', async () => {await type('a photo of __');expect(listbox()).not.toBeNull();await act(() => {- // Capture-phase, so an element scroll reaches it even though it does not- // bubble.textarea().dispatchEvent(new Event('scroll'));});@@ -361,38 +214,6 @@ describe('the caret autocomplete', () => {expect(listbox()).toBeNull();});- // Previously only a click could reopen the list over a reference already in- // the prompt; arrowing back into one left it shut until another character was- // typed, which reads as the feature having given up.- it('reopens when the caret arrows back into a reference', async () => {- await type('a photo of __co');- await press('{Escape}');-- expect(listbox()).toBeNull();-- await press('{ArrowLeft}');-- expect(optionLabels()).toEqual(['colors']);- });-- it('closes when the caret arrows out of one', async () => {- await type('a photo of __co');-- expect(listbox()).not.toBeNull();-- await press('{Home}');-- expect(listbox()).toBeNull();- });-- it('closes on Escape and leaves the prompt exactly as typed', async () => {- await type('a photo of __');- await press('{Escape}');-- expect(listbox()).toBeNull();- expect(textarea().value).toBe('a photo of __');- });-it('tells assistive tech the textarea is a combobox over the list', async () => {await type('a photo of __');@@ -404,15 +225,6 @@ describe('the caret autocomplete', () => {expect(document.getElementById(activeId!)?.getAttribute('aria-selected')).toBe('true');});- it('closes once the reference is finished', async () => {- await type('a photo of __colors__');-- expect(listbox()).toBeNull();- });-- // Regression: the template view-mode toggle can be on with no template- // applied, which leaves the prompt fully editable. Gating on the toggle alone- // killed the autocomplete outright while the user was still typing.it('still opens when view mode is on but no template is applied', async () => {await act(() => root?.unmount());host?.remove();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsxindex 941624f3f2..4849d677d1 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx@@ -71,21 +71,6 @@ afterEach(async () => {});describe('wildcard import dialog', () => {- it('says how much is new and how much already exists', async () => {- await renderDialog();-- expect(dialog().textContent).toContain('importSummary');- });-- // Import is the one action here that can overwrite a hand-typed list.- it('leaves every clash alone unless told otherwise', async () => {- const onConfirm = await renderDialog();-- await confirm();-- expect(onConfirm).toHaveBeenCalledWith({});- });-it('resolves one clash without touching the other', async () => {const onConfirm = await renderDialog();// The first group is the apply-to-all row; the rest are the clashes.@@ -107,27 +92,6 @@ describe('wildcard import dialog', () => {expect(onConfirm).toHaveBeenCalledWith({ colours: 'keepBoth', moods: 'keepBoth' });});- // Regression: rendered controlled with no value, the apply-to-all row snapped- // back to nothing selected after every use, so it read as not having worked.- it('shows what the apply-to-all row was set to', async () => {- await renderDialog();- const [all] = segmentGroups();-- await clickOption(all!, 'importKeepBoth');-- expect(all!.querySelector('[data-part="item"][data-state="checked"]')?.textContent).toContain('importKeepBoth');- });-- it('stops describing every clash once one of them disagrees', async () => {- await renderDialog();- const [all, colours] = segmentGroups();-- await clickOption(all!, 'importReplace');- await clickOption(colours!, 'importSkip');-- expect(all!.querySelector('[data-part="item"][data-state="checked"]')).toBeNull();- });-it('lets a row override the decision made for all of them', async () => {const onConfirm = await renderDialog();const [all, colours] = segmentGroups();@@ -147,10 +111,4 @@ describe('wildcard import dialog', () => {expect(dialog().textContent).toContain('bad name!');expect(dialog().textContent).toContain('importRejectedInvalid');});-- it('offers no apply-to-all for a single clash', async () => {- await renderDialog([entry({ conflictId: 'w1', name: 'colours' })]);-- expect(segmentGroups()).toHaveLength(1);- });});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.tsindex 538c08f4fb..404a27a25f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts@@ -1,31 +1,3 @@-/**- * Where the caret is on screen, so a list can open beside it.- *- * A textarea gives no geometry for a position within its text, so the standard- * trick is to lay the same text out again in a hidden element that copies every- * property affecting how it wraps, and read the offset of a marker placed at the- * caret.- *- * `PromptTextarea` already renders a mirror for syntax highlighting, and reusing- * it — placing a `Range` in that `<pre>` — would delete everything below. It- * does not work, for two reasons worth writing down so the idea is not tried a- * third time. It renders only when highlighting is on and the prompt is- * non-empty, so it is absent for the first character typed and for anyone with- * the setting off. And it is React-rendered from the state the keystroke is- * updating: measured during `refresh`, which runs inside the change handler, it- * holds the *previous* value. Both confirmed by measurement — with `ab` in the- * field, the rendered mirror still read `a`.- *- * Reusing it would mean rendering it unconditionally and moving the measurement- * into a layout effect, costing a second render on every keystroke while the- * list is live. This mirror reads `textarea.value`, and is never a keystroke- * behind.- *- * Measured on demand rather than tracked: it is read while a picker is opening- * or its query is growing, which is a handful of times per keystroke at most,- * and never while the user is only typing.- */-export interface CaretRect {height: number;width: number;@@ -33,17 +5,6 @@ export interface CaretRect {y: number;}-/**- * Everything that decides where a character lands, copied onto the mirror.- *- * Width is deliberately absent, and set from `clientWidth` below instead.- * Copying the resolved `width` does work — it is the border-box width under- * `box-sizing: border-box`, which the copied borders and padding then reduce to- * the same content width — but it only works because those three travel- * together, and it counts a vertical scrollbar as space for text. `clientWidth`- * is the padding box with the scrollbar already taken out, which is the width- * the field actually wraps at, stated once.- */const MIRRORED_STYLES = ['direction','fontFamily',@@ -65,18 +26,7 @@ const MIRRORED_STYLES = ['wordSpacing',] as const;-/**- * The one mirror, reused.- *- * This runs on every keystroke while a trigger is live, and building it each- * time meant two `createElement`s, an `append` and a `remove` per character —- * each insertion and removal dirtying layout for whatever came next. The- * measurement itself still forces a layout, which is inherent to the technique,- * but the churn around it is not.- *- * It stays in the document between calls. It is `visibility: hidden` and parked- * off-screen, so it costs one detached-looking subtree and no paint.- */+// Reuse the mirror to avoid DOM insertion/removal on each autocomplete keystroke.let mirrorElements: { marker: HTMLSpanElement; mirror: HTMLDivElement } | null = null;const getMirror = (): { marker: HTMLSpanElement; mirror: HTMLDivElement } => {@@ -93,13 +43,6 @@ const getMirror = (): { marker: HTMLSpanElement; mirror: HTMLDivElement } => {return mirrorElements;};-/**- * The caret's viewport rectangle, or `null` when the element is not laid out.- *- * The returned box is a zero-width line at the caret: callers place a popover- * against it, so its height is what decides whether the list sits above or below- * the current line rather than on top of it.- */export const getTextareaCaretRect = (textarea: HTMLTextAreaElement, index: number): CaretRect | null => {const textareaRect = textarea.getBoundingClientRect();@@ -114,7 +57,6 @@ export const getTextareaCaretRect = (textarea: HTMLTextAreaElement, index: numbemirror.style[property] = computed[property];}- // Off-screen rather than `display: none`, which would give every offset zero.mirror.style.position = 'absolute';mirror.style.top = '0';mirror.style.left = '-9999px';@@ -122,23 +64,15 @@ export const getTextareaCaretRect = (textarea: HTMLTextAreaElement, index: numbemirror.style.whiteSpace = 'pre-wrap';mirror.style.overflowWrap = 'break-word';mirror.style.overflow = 'hidden';- // `clientWidth` is the padding box, so with no border of its own the mirror- // gets exactly the field's own wrapping width.mirror.style.boxSizing = 'border-box';mirror.style.border = '0';mirror.style.width = `${textarea.clientWidth}px`;- // Setting `textContent` drops the marker along with the old text, so it is put- // back rather than appended afresh.mirror.textContent = textarea.value.slice(0, index);- // A zero-width space so the marker still occupies a line when the caret sits- // at the very end of the text, or straight after a newline.marker.textContent = textarea.value.slice(index) || '';mirror.append(marker);const lineHeight = Number.parseFloat(computed.lineHeight);- // The offsets are measured from the mirror's padding edge, which the field's- // own border sits outside of, so it has to be added back by hand.const borderLeft = Number.parseFloat(computed.borderLeftWidth) || 0;const borderTop = Number.parseFloat(computed.borderTopWidth) || 0;const rect: CaretRect = {@@ -148,8 +82,6 @@ export const getTextareaCaretRect = (textarea: HTMLTextAreaElement, index: numbey: textareaRect.top + borderTop + marker.offsetTop - textarea.scrollTop,};- // Emptied rather than removed: keeping the element costs nothing, but keeping- // a whole prompt's worth of text laid out between keystrokes would.mirror.textContent = '';return rect;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.tsindex f91a22e61c..4da69e3dc1 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts@@ -74,24 +74,16 @@ export const insertPositivePromptText = ({value: string;}): void => insertPromptText({ onChange, range, textarea: positivePromptElement, text, value });-/** Which trigger keys a field answers to. Wildcards only exist on the positive prompt. */export type PromptTriggerKey = '<' | '_';export interface PromptTriggerQuery {key: PromptTriggerKey;- /** What has been typed since the trigger, for narrowing the list. */query: string;- /** The span a picked option replaces, trigger and typed query included. */range: PromptTextRange;}-/**- * Past this the user is writing prose, not naming a wildcard, and an- * autocomplete still hanging around is in the way.- */const MAX_TRIGGER_QUERY_LENGTH = MAX_WILDCARD_NAME_LENGTH + 2;-/** Whether the final `__` closes the current whitespace-delimited wildcard token. */const isClosingWildcardDelimiter = (value: string, caret: number): boolean => {let tokenStart = caret - 2;@@ -113,29 +105,11 @@ const isClosingWildcardDelimiter = (value: string, caret: number): boolean => {return delimiterCount % 2 === 0;};-/**- * The unfinished trigger the caret is sitting inside, or `null`.- *- * This replaced an open-on-keystroke picker that swallowed the `__` or `<` and- * gave the user a separate search box to type into. Here the trigger is typed- * into the prompt like any other character and whatever follows it narrows the- * list, so you type where you are already looking — and there is nothing to hand- * back when the list is dismissed.- *- * Scanning stops at a newline, at whitespace, and at anything that closes the- * token, so a finished `__colours__` or `<embedding>` behind the caret does not- * re-open the list, and a space ends the attempt rather than leaving it open- * over a sentence.- */export const getActiveTriggerQuery = (value: string,caret: number,keys: readonly PromptTriggerKey[]): PromptTriggerQuery | null => {- // At a closing `__`, the backwards scan reaches that pair before its opening- // pair. Count non-overlapping delimiters in this token so an empty closed- // reference stays closed, while a completed reference followed immediately by- // a new `__` still opens the next trigger.const closingStart = caret - 2;if (keys.includes('_') && value.slice(closingStart, caret) === '__' && isClosingWildcardDelimiter(value, caret)) {@@ -155,11 +129,6 @@ export const getActiveTriggerQuery = (return { key: '<', query: value.slice(index + 1, caret), range: { end: caret, start: index } };}- // A space ends a wildcard attempt but not an embedding one. Embedding model- // names routinely have spaces in them — `bad hands 5` — so stopping here- // meant `<bad ` closed the list for good and the name could never be- // reached inline, even though the filter would have matched it. A wildcard- // name cannot contain a space, so there the space really is the end.if (/\s/.test(char ?? '')) {return keys.includes('<') ? findEnclosingEmbedding(value, caret, limit, index) : null;}@@ -167,8 +136,6 @@ export const getActiveTriggerQuery = (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*- // pair, and the closing one is sitting in the query.return query.includes('__') || query.length > MAX_WILDCARD_NAME_LENGTH? null: { key: '_', query, range: { end: caret, start: index - 1 } };@@ -178,13 +145,6 @@ export const getActiveTriggerQuery = (return null;};-/**- * Keeps scanning back past spaces for an unclosed `<`, having already met one.- *- * Split out so the common path — no space between the caret and the trigger —- * stays a single loop, and so the two stopping rules read separately: this one- * only stops at a newline or a `>`, which closes the token.- */const findEnclosingEmbedding = (value: string,caret: number,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.tsindex 26fb63e7df..ee5cc851a0 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptTriggerOptions.ts@@ -1,12 +1,3 @@-/**- * What `<` and `__` can insert: wildcards, the selected model's and each enabled- * LoRA's trigger phrases, and embeddings compatible with the base.- *- * Shared by the two ways of reaching that list — the `+` button's browsable- * popover and the caret-anchored autocomplete — so the two can never drift into- * offering different things.- */-import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';import type { PromptTriggerKey } from '@features/generation/ui/promptFields/promptFocus';@@ -16,11 +7,6 @@ import { useWildcards } from '@features/generation/ui/useWildcards';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-/**- * What an option inserts. Carried explicitly rather than sniffed back out of- * `value`, because the inline autocomplete offers only the kind its delimiter- * actually stands for.- */export type PromptTriggerKind = 'embedding' | 'phrase' | 'wildcard';export interface PromptTriggerOption {@@ -66,8 +52,6 @@ export const getPromptTriggerOptions = ({}): 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, kind: 'wildcard', label: wildcard.name, value: `__${wildcard.name}__` });}@@ -113,7 +97,6 @@ export const getPromptTriggerOptions = ({});};-/** The `+` button's search box, which browses the whole list by name or group. */export const filterPromptTriggerOptions = (options: readonly PromptTriggerOption[],search: string@@ -130,21 +113,8 @@ export const filterPromptTriggerOptionsByKind = (allowedKinds?: ReadonlySet<PromptTriggerKind>): PromptTriggerOption[] => (allowedKinds ? options.filter((option) => allowedKinds.has(option.kind)) : [...options]);-/** Which kind each delimiter stands for. Trigger phrases have no delimiter. */const KIND_BY_TRIGGER_KEY: Record<PromptTriggerKey, PromptTriggerKind> = { '<': 'embedding', _: 'wildcard' };-/**- * The options an inline `<` or `__` should offer.- *- * Narrowed to the delimiter's own kind: `<` opens an embedding token and `__` a- * wildcard reference, so offering the other under either is offering something- * the user cannot have meant. Model and LoRA trigger phrases belong to no- * delimiter and stay with the `+` button, which browses everything.- *- * Matching is on the label alone, unlike the browse search above. The query here- * is a name being typed, and folding in the group would make `__w` match every- * wildcard on the strength of the word "Wildcards".- */export const getInlineTriggerOptions = (options: readonly PromptTriggerOption[],key: PromptTriggerKey,@@ -169,7 +139,6 @@ export const groupPromptTriggerOptions = (options: readonly PromptTriggerOption[return groups;}, []);-/** The live option list for a field, already localized. */export const usePromptTriggerOptions = (loras: GenerateLora[],selectedModel: GenerateModelConfig | undefineddiff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsxindex 127fa5ef61..b1e33c3255 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/usePromptTriggerAutocomplete.tsx@@ -1,18 +1,3 @@-/**- * Type-as-you-filter trigger insertion, anchored at the caret.- *- * The old behaviour swallowed the `__` or `<` keystroke, opened a popover- * anchored to the whole textarea, and gave you a separate search box: in a tall- * prompt box the list appeared at the bottom-left corner, and you typed in one- * place while looking at another. Here the trigger is typed like any other- * character, whatever follows it narrows the list, and the list sits beside the- * caret. Nothing is swallowed, so there is nothing to give back on dismissal.- *- * Focus never leaves the textarea. That is what makes this a hook returning an- * element rather than a `Popover`: the list is a passive surface, and every key- * that drives it is handled on the textarea itself.- */-import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';import type { CaretRect } from '@features/generation/ui/promptFields/promptCaret';import type { PromptTriggerKey, PromptTriggerQuery } from '@features/generation/ui/promptFields/promptFocus';@@ -29,29 +14,16 @@ import {import { DismissOnViewportChange } from '@features/generation/ui/promptFields/useDismissOnViewportChange';import { useCallback, useId, useMemo, useRef, useState } from 'react';-/** Move the caret whether or not the list is open. */const CARET_KEYS = ['ArrowLeft', 'ArrowRight', 'Home', 'End'];-/** Move the caret only when the list is not open to take them for its own. */const LIST_KEYS = ['ArrowUp', 'ArrowDown'];interface AutocompleteState {caretRect: CaretRect;query: PromptTriggerQuery;- /**- * The field the query was read from. Held rather than looked up again at- * selection time: `document.activeElement` is only the textarea because the- * option suppressed its own mousedown, and if that ever stops holding, the- * insert reads `undefined` for the current value and commits the option on its- * own — silently replacing the whole prompt.- */textarea: HTMLTextAreaElement;}export interface PromptTriggerAutocompleteApi {- /**- * Spread onto the textarea so assistive tech sees a combobox, and so the list- * stays out of the way while an IME is composing.- */comboboxProps: {'aria-activedescendant': string | undefined;'aria-autocomplete': 'list';@@ -64,20 +36,8 @@ export interface PromptTriggerAutocompleteApi {};element: ReactNode;isOpen: boolean;- /** Close without inserting, for anything that invalidates the caret. */close: () => void;- /** Re-read the trigger under the caret. Call on input, and on click. */refresh: (textarea: HTMLTextAreaElement | null) => void;- /**- * Drives the list from the textarea's own keydown.- *- * Returns nothing on purpose. It used to report whether it had consumed the- * key, on the theory that the field would otherwise also act on it — but both- * fields discarded that, and there is no contention to resolve: the only other- * keyboard feature here is prompt history, which is modifier-gated and so- * never reaches this at all. Anything this does take, it takes by calling- * `preventDefault` itself.- */handleKeyDown: (event: KeyboardEvent<HTMLTextAreaElement>) => void;}@@ -110,17 +70,12 @@ export const usePromptTriggerAutocomplete = ({const refresh = useCallback((textarea: HTMLTextAreaElement | null) => {- // Mid-composition the field holds half-committed romaji, which is not a- // wildcard name being typed. Reading it would re-anchor the list on every- // keystroke the IME is still working on.if (!textarea || isDisabled || isComposingRef.current) {setState(null);return;}const query = getActiveTriggerQuery(textarea.value, textarea.selectionStart, keys);- // Anchored at the trigger rather than the caret, so the list holds still- // while the name is typed instead of creeping sideways with it.const caretRect = query ? getTextareaCaretRect(textarea, query.range.start) : null;setState(query && caretRect ? { caretRect, query, textarea } : null);@@ -148,23 +103,16 @@ export const usePromptTriggerAutocomplete = ({const handleKeyDown = useCallback((event: KeyboardEvent<HTMLTextAreaElement>): void => {- // While an IME is composing, the arrows move through its candidate window- // and Enter commits the composition. Taking either would leave a Japanese- // or Chinese user unable to pick a candidate at all. `keyCode === 229` is- // the same signal for the browsers that do not set `isComposing`.if (!isOpen || event.nativeEvent.isComposing || event.keyCode === 229) {return;}- // Caret movement belongs to the textarea. Where it lands is read on the- // way back up, once the browser has actually moved it.if (CARET_KEYS.includes(event.key)) {return;}if (event.key === 'Escape') {event.preventDefault();- // Otherwise the popover or dialog this prompt sits in closes too.event.stopPropagation();setState(null);return;@@ -190,13 +138,6 @@ export const usePromptTriggerAutocomplete = ({[activeIndex, isOpen, matches, selectOption]);- // Read on the way up, not the way down: during keydown the caret has not moved- // yet. This is also what lets the list *open* by arrowing back into a `__col`- // that is already sitting in the prompt, which before only a click could do.- //- // The vertical arrows are excluded while the list is open, because there they- // drove the highlight and the caret never moved — re-reading would reset the- // highlight to the top on every press.const handleKeyUp = useCallback((event: KeyboardEvent<HTMLTextAreaElement>) => {if (CARET_KEYS.includes(event.key) || (!isOpen && LIST_KEYS.includes(event.key))) {@@ -214,8 +155,6 @@ export const usePromptTriggerAutocomplete = ({const handleCompositionEnd = useCallback((event: CompositionEvent<HTMLTextAreaElement>) => {isComposingRef.current = false;- // The composed text is only in the field now, so this is the first point- // at which a trigger under the caret is worth reading again.refresh(event.currentTarget);},[refresh]@@ -228,10 +167,6 @@ export const usePromptTriggerAutocomplete = ({'aria-autocomplete': 'list','aria-controls': isOpen ? listboxId : undefined,'aria-expanded': isOpen,- // No `aria-multiline`: `combobox` does override the textarea's implicit- // `textbox` role and takes multiline-ness with it, but ARIA does not allow- // the attribute on a combobox, and axe rejects it as a critical violation.- // The loss is real and there is no way to state it here.onCompositionEnd: handleCompositionEnd,onCompositionStart: handleCompositionStart,onKeyUp: handleKeyUp,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsxindex 5c0f2741b4..49843de157 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.browser.test.tsx@@ -61,24 +61,15 @@ afterEach(async () => {});describe('useOnPendingPromptTemplateDraft', () => {- it('delivers a draft that was pending before mount', async () => {+ it('delivers pre-mount and live handoffs once', async () => {const onDraft = vi.fn();setPendingPromptTemplateDraft(beforeMountDraft);await act(() => root.render(<Probe onDraft={onDraft} />));-- expect(onDraft).toHaveBeenCalledOnce();- expect(onDraft).toHaveBeenCalledWith(beforeMountDraft);- });-- it('delivers a draft published after mount', async () => {- const onDraft = vi.fn();- await act(() => root.render(<Probe onDraft={onDraft} />));-await act(() => setPendingPromptTemplateDraft(afterMountDraft));+ await act(() => root.render(<Probe onDraft={onDraft} />));- expect(onDraft).toHaveBeenCalledOnce();- expect(onDraft).toHaveBeenCalledWith(afterMountDraft);+ expect(onDraft.mock.calls).toEqual([[beforeMountDraft], [afterMountDraft]]);});it('uses the latest callback for a draft published during an update layout', async () => {@@ -91,16 +82,6 @@ describe('useOnPendingPromptTemplateDraft', () => {expect(onDelivery).toHaveBeenCalledWith('new:after positive');});- it('delivers each pending draft only once across rerenders', async () => {- const onDraft = vi.fn();- await act(() => root.render(<Probe onDraft={onDraft} />));- await act(() => setPendingPromptTemplateDraft(afterMountDraft));-- await act(() => root.render(<Probe onDraft={onDraft} />));-- expect(onDraft).toHaveBeenCalledOnce();- });-it('does not deliver account A draft after account B becomes active', async () => {const onDraft = vi.fn();accountLifecycle.activate('draft-a', ':user:draft-a');diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.tsindex 2a821294c6..768dc28fc9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts@@ -1,16 +1,3 @@-/**- * A one-shot handoff for "save this image's prompt as a template".- *- * The action starts in the gallery's context menu but has to finish in the- * generate widget's template editor, which is inside a popover the menu cannot- * reach. Rather than lifting the editor into a global dialog, the menu leaves a- * draft here and opens the widget; the templates button picks it up and opens- * the editor prefilled.- *- * The draft is consumed on read, so re-opening the popover later starts on the- * list rather than resurrecting an old handoff.- */-import { useMountEffect } from '@platform/react/useMountEffect';import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';@@ -44,15 +31,6 @@ const takePendingPromptTemplateDraft = (): PendingPromptTemplateDraft | null =>return draft;};-/**- * Delivers a handed-over draft to the editor exactly once — on subscribe for one- * left before the widget mounted, and on notification thereafter.- *- * Deliberately a subscription with a callback rather than a rendered value: the- * draft is a one-shot event from outside React, and reading it during render- * would mean clearing it in an effect, which is the cascading-render pattern the- * compiler rejects.- */export const useOnPendingPromptTemplateDraft = (onDraft: (draft: PendingPromptTemplateDraft) => void): void => {const deliver = useEffectEvent(() => {const draft = takePendingPromptTemplateDraft();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.browser.test.tsxindex 7e7c6bfc78..aba7a901c4 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.browser.test.tsx@@ -86,23 +86,6 @@ afterEach(async () => {});describe('prompt template mutation invalidation', () => {- it('invalidates the template list exactly once after creation', async () => {- transport.apiFetchJson.mockResolvedValue(dto);- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries');-- await act(async () => {- await catalogRef.current!.create({- image: null,- name: dto.name,- negativePrompt: '',- positivePrompt: dto.preset_data.positive_prompt,- });- });-- expect(invalidateQueries).toHaveBeenCalledTimes(1);- expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: promptTemplateKeys.list(), exact: true });- });-it.each([['update',diff --git a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.tsindex b0ea33f94b..089f2bec91 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/usePromptTemplates.ts@@ -23,23 +23,12 @@ import { useCallback, useMemo } from 'react';import { useGenerationUi } from './GenerationUiContext';export interface PromptTemplateCatalog {- /** The user's own templates, name-ascending as the backend orders them. */personalTemplates: PromptTemplateRecord[];- /** Public templates owned by somebody else; applicable but read-only. */sharedTemplates: PromptTemplateRecord[];- /** Templates shipped with the backend; applicable but not editable. */defaultTemplates: PromptTemplateRecord[];- /** Every visible template, for resolving a stored snapshot. */templates: PromptTemplateRecord[];isLoading: boolean;- /**- * The catalog has been read at least once, successfully. Distinct from- * `!isLoading`, which is also true of a fetch that failed and of one that- * never ran — telling a deleted template apart from an unread catalog needs- * the difference.- */isLoaded: boolean;- /** Resolves with the saved record so a caller can refresh an applied snapshot. */create: (draft: PromptTemplateCreateDraft) => Promise<PromptTemplateRecord>;update: (template: PromptTemplateRecord, draft: PromptTemplateUpdateDraft) => Promise<PromptTemplateRecord>;remove: (template: PromptTemplateRecord) => Promise<void>;@@ -47,17 +36,9 @@ export interface PromptTemplateCatalog {exportCsv: (owner: AccountScope) => Promise<Blob>;}-/**- * The shared prompt template catalog. Each mutation captures the identity that- * started it, so a sign-out mid-flight does not invalidate the next account's- * cache on the way back — the same rule `useWildcards` follows.- */export const usePromptTemplates = ({ isEnabled = true }: { isEnabled?: boolean } = {}): PromptTemplateCatalog => {const queryClient = useQueryClient();const { account } = useGenerationUi();- // Off by default for the widget, which only wants to re-read an applied- // template and has nothing to re-read when none is applied. The picker asks- // for it in earnest, and shares this cache when it does.const query = useQuery({ ...promptTemplatesQueryOptions(), enabled: isEnabled });const classified = useMemo(() => classifyPromptTemplates(query.data ?? [], account), [account, query.data]);@@ -115,14 +96,6 @@ export const usePromptTemplates = ({ isEnabled = true }: { isEnabled?: boolean }};};-/**- * Whether the applied template has been deleted out from under this tab.- *- * The snapshot keeps applying either way — a queue item has to explain itself- * after its template is gone, and a catalog that is empty because it is still- * loading or because the fetch failed must not silently change what generates.- * That policy is right and stays; this is only what makes it visible.- */export const isPromptTemplateMissing = (catalog: PromptTemplateCatalog,active: PromptTemplateSnapshot | nulldiff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsxindex 45de08ad17..10d53f8762 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx@@ -59,21 +59,7 @@ describe('applyWrites', () => {{ name: 'c', values: ['3'] },];- // Every single-write method invalidates the wildcard cache *and* every- // dynamic-prompt expansion, and awaits the refetch. Doing that between each- // write of a forty-file import meant re-reading a list that grew by one, forty- // times over.it('invalidates once for the whole run, not once per write', async () => {- await act(async () => {- await catalogRef.current!.applyWrites(WRITES, captureAccountScope());- });-- expect(createWildcard).toHaveBeenCalledTimes(2);- expect(updateWildcard).toHaveBeenCalledTimes(1);- expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);- });-- it('reports how many landed', async () => {let done = 0;await act(async () => {@@ -81,10 +67,11 @@ describe('applyWrites', () => {});expect(done).toBe(3);+ expect(createWildcard).toHaveBeenCalledTimes(2);+ expect(updateWildcard).toHaveBeenCalledTimes(1);+ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);});- // The ones already written are real, so the caches are stale whether or not- // the run finished — and the caller needs the count to say how far it got.it('still invalidates, and carries the count, when a write fails', async () => {createWildcard.mockImplementationOnce(() => Promise.resolve());updateWildcard.mockImplementationOnce(() => Promise.reject(new Error('conflict')));diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.tsindex f37bcec5e2..00c2a9e36e 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts@@ -16,7 +16,6 @@ const file = (name: string, contents: string) => new File([contents], name, { tyconst read = (files: readonly File[], source: 'files' | 'folder') =>readWildcardFiles(files, source, accountLifecycle.capture());-/** What a directory pick hands over: a name plus the path relative to the root. */const inFolder = (path: string, contents: string): File => {const picked = file(path.slice(path.lastIndexOf('/') + 1), contents);@@ -50,37 +49,18 @@ describe('readWildcardFiles', () => {]);});- it('takes an extensionless file as text', async () => {- await expect(read([file('colours', 'red')], 'files')).resolves.toEqual([{ name: 'colours', values: ['red'] }]);- });-- // `accept` on a file input is a hint, not a rule, and a wildcard folder- // routinely has a readme sitting in it. Read as text, that imported as a- // wildcard named `README` whose values were the markdown.it('refuses a file that is not a supported format', async () => {await expect(read([file('README.md', '# Wildcards\n\nSome notes.')], 'files')).rejects.toBeInstanceOf(WildcardFileError);});- it('names the file it could not read', async () => {- await expect(read([file('broken.json', '{ nope')], 'files')).rejects.toMatchObject({- fileName: 'broken.json',- });- });-- // Regression: `parsed.push(...entries)` is a call with one argument per entry,- // which overflows the argument stack — at a threshold that differs by engine,- // and reported as though the file had failed to parse.it('refuses a collection too large to import instead of overflowing', async () => {const huge = JSON.stringify(Object.fromEntries(Array.from({ length: 25_000 }, (_, i) => [`w${i}`, ['v']])));await expect(read([file('huge.json', huge)], 'files')).rejects.toBeInstanceOf(WildcardFileError);});- // The whole point of picking a folder: a1111 nests wildcards in directories,- // and only the relative path says that `dogs.txt` is `animals/dogs`. Picking- // the two files by hand gives two wildcards both called `dogs`.it('turns a folder`s nesting into `/` names', async () => {const picked = [inFolder('wildcards/animals/dogs.txt', 'corgi'), inFolder('wildcards/moods/dogs.txt', 'sleepy')];@@ -89,17 +69,9 @@ describe('readWildcardFiles', () => {{ name: 'moods/dogs', values: ['sleepy'] },]);});-- it('retains direct file names even when a relative path is present', async () => {- const picked = inFolder('ignored/animals/dogs.txt', 'corgi');-- await expect(read([picked], 'files')).resolves.toEqual([{ name: 'dogs', values: ['corgi'] }]);- });});describe('isSupportedWildcardFile', () => {- // A folder pick hands over everything in it, so the ones that are not- // wildcards get dropped rather than failing the whole import.it('keeps the wildcard files and drops the rest', () => {const picked = [inFolder('wildcards/colours.txt', 'red'),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.tsindex 5f04ad3959..43deebdeeb 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts@@ -1,13 +1,3 @@-/**- * The file half of wildcard import/export: reading what the user picked, and- * handing back a download.- *- * The format logic itself lives in `core/wildcardTransfer` — this module only- * bridges it to `File`, `Blob` and YAML text. YAML is loaded through a dynamic- * `import('yaml')` so the parser reaches the browser only when somebody actually- * imports or exports, rather than riding along in the generate widget's chunk.- */-import type { ParsedWildcard } from '@features/generation/core/wildcardTransfer';import type { AccountScope } from '@platform/state/accountLifecycle';@@ -19,14 +9,6 @@ import {import { downloadText } from '@platform/browser/downloadBlob';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';-/**- * Every collection format, stated once.- *- * Adding one used to mean editing five places that had no idea about each- * other: a union type, two ternaries here, the export menu's array, and an i18n- * key built by string concatenation — which silently fell back to "Json" for- * anything it did not recognise rather than failing to compile.- */export const WILDCARD_COLLECTION_FORMATS = [{extensions: ['.yaml', '.yml'],@@ -57,7 +39,6 @@ export const WILDCARD_IMPORT_ACCEPT = [export type WildcardFileSource = 'files' | 'folder';-/** Folder picks shed the selected root while direct picks retain their file names. */const getFilePath = (file: File, source: WildcardFileSource): string => {if (source === 'files') {return file.name;@@ -72,10 +53,6 @@ const getFilePath = (file: File, source: WildcardFileSource): string => {const hasExtension = (path: string, ...extensions: string[]): boolean =>extensions.some((extension) => path.toLowerCase().endsWith(extension));-/**- * Thrown when a file cannot be read as any supported format. Carries the file- * name so the notice can say which one, since imports are usually plural.- */export class WildcardFileError extends Error {constructor(readonly fileName: string) {super(`Could not read ${fileName}`);@@ -83,30 +60,9 @@ export class WildcardFileError extends Error {}}-/**- * Bounds on what a selection may contain, so a mistaken pick fails by saying so.- *- * Without the count, `parsed.push(...entries)` on a large collection overflowed- * the argument stack and surfaced as `RangeError` — caught as a parse failure- * and reported as "could not read", about a file that had parsed perfectly. The- * threshold is engine-dependent, so it tripped in Safari well before Chrome.- */const MAX_IMPORT_FILE_BYTES = 32 * 1024 * 1024;const MAX_IMPORT_WILDCARDS = 20_000;-/**- * Every wildcard the picked files describe, in the order the files were given.- *- * A folder of `.txt` files, a single `.yaml` collection, and a `.json` export of- * this app all land in the same list — mixing them in one selection is fine, and- * duplicate names across files are sorted out later by `planWildcardImport`.- */-/**- * `a.txt` and a bare `LICENSE` yes; `README.md`, `preview.png` and `.DS_Store`- * no. An extensionless file is fair game — a wildcard file has no header to- * check — but a name that is nothing *but* an extension is a dotfile, and every- * folder pick brings a few of those along.- */const isTextWildcardFile = (path: string): boolean => {const name = path.slice(path.lastIndexOf('/') + 1);const dot = name.lastIndexOf('.');@@ -114,14 +70,6 @@ const isTextWildcardFile = (path: string): boolean => {return dot < 0 || name.slice(dot).toLowerCase() === '.txt';};-/**- * Whether this file is worth handing to `readWildcardFiles` at all.- *- * For a file the user picked by name, being unreadable is worth saying out loud,- * so `readWildcardFiles` throws. A directory pick is the opposite: it hands over- * everything in the folder, readmes and `.DS_Store` included, and refusing the- * whole import over one of them would make folder picking useless.- */export const isSupportedWildcardFile = (file: File): boolean => {const path = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;@@ -138,8 +86,6 @@ export const readWildcardFiles = async (const parsed: ParsedWildcard[] = [];const collect = (wildcards: readonly ParsedWildcard[], fileName: string): void => {- // Appended one at a time rather than spread: a spread of a large collection- // is a call with that many arguments, which overflows the stack.for (const wildcard of wildcards) {parsed.push(wildcard);}@@ -180,10 +126,6 @@ export const readWildcardFiles = async (continue;}- // Text is read a line at a time, and an extensionless file is fair game — a- // wildcard file has no header to check. Anything else is not: `accept` is- // only a hint on a file input, and a README picked up alongside a wildcard- // folder used to import as a wildcard named `README`.if (!isTextWildcardFile(path)) {throw new WildcardFileError(file.name);}@@ -194,14 +136,6 @@ export const readWildcardFiles = async (return parsed;};-/**- * Downloads the whole catalog.- *- * There is no `.txt` counterpart on purpose: the convention is one file per- * wildcard, so a text export of forty wildcards would be forty downloads. Both- * formats here keep the nesting, and a1111's extension reads YAML collections,- * so the round trip that matters is covered.- */export const downloadWildcards = async (wildcards: readonly ParsedWildcard[],formatId: WildcardExportFormat,