Skip to content

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

refactor(webv2): search every prompt catalog by one rule

joshistoastb76a5bbaf06b
diff --git a/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.test.ts b/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.test.ts
new file mode 100644
index 0000000000..a0e6519b22
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest';
+
+import { searchCatalog, searchProse } from './catalogSearch';
+
+interface Record {
+ name: string;
+ body: string[];
+}
+
+const record = (name: string, ...body: string[]): Record => ({ body, name });
+
+/** Module-level, as every real caller's accessor is — the cache is keyed by it. */
+const getBody = (item: Record): readonly string[] => item.body;
+
+describe('searchCatalog', () => {
+ it('returns a copy of everything for an empty query', () => {
+ const items = [record('colours', 'red'), record('animals', 'dog')];
+
+ expect(searchCatalog(items, '', getBody)).toEqual(items);
+ expect(searchCatalog(items, ' ', getBody)).toEqual(items);
+ expect(searchCatalog(items, '', getBody)).not.toBe(items);
+ });
+
+ it('matches a name fuzzily', () => {
+ const dogs = record('animals/dogs', 'poodle');
+ const colours = record('colours', 'red');
+
+ expect(searchCatalog([dogs, colours], 'adg', getBody)).toEqual([dogs]);
+ });
+
+ it('ranks name matches above prose matches', () => {
+ const byProse = record('animals', 'red panda');
+ const byName = record('red', 'crimson');
+
+ expect(searchCatalog([byProse, byName], 'red', getBody)).toEqual([byName, byProse]);
+ });
+
+ it('lists a record once when both its name and its prose match', () => {
+ const both = record('red', 'red');
+
+ expect(searchCatalog([both], 'red', getBody)).toEqual([both]);
+ });
+
+ it('matches prose without regard to case', () => {
+ const item = record('colours', 'Crimson', 'CYBERPUNK');
+
+ expect(searchCatalog([item], 'cyber', getBody)).toEqual([item]);
+ expect(searchCatalog([item], 'CRIM', getBody)).toEqual([item]);
+ });
+
+ it('matches prose by substring, not fuzzily', () => {
+ const item = record('colours', 'crimson');
+
+ // Fuzzy would find these; on free text they are noise.
+ expect(searchCatalog([item], 'cmn', getBody)).toEqual([]);
+ expect(searchCatalog([item], 'crn', getBody)).toEqual([]);
+ });
+
+ it('never matches across the boundary between two prose fields', () => {
+ const item = record('colours', 'deep red', 'blue steel');
+
+ expect(searchCatalog([item], 'redblue', getBody)).toEqual([]);
+ // A space is what a joined haystack would have left matchable here.
+ expect(searchCatalog([item], 'red blue', getBody)).toEqual([]);
+ expect(searchCatalog([item], 'deep red', getBody)).toEqual([item]);
+ });
+
+ it('returns nothing when neither the name nor the prose matches', () => {
+ expect(searchCatalog([record('colours', 'red')], 'zzzz', getBody)).toEqual([]);
+ });
+
+ it('scans long prose to the end rather than sampling it', () => {
+ const long = record('big', ...Array.from({ length: 500 }, (_, index) => `value-${index}`), 'needle');
+
+ expect(searchCatalog([long], 'needle', getBody)).toEqual([long]);
+ });
+
+ it('reads an edited record afresh', () => {
+ const before = record('colours', 'red');
+ const after = { ...before, body: ['blue'] };
+
+ expect(searchCatalog([before], 'blue', getBody)).toEqual([]);
+ expect(searchCatalog([after], 'blue', getBody)).toEqual([after]);
+ });
+
+ it('keeps two accessors over one record apart', () => {
+ const item = { ...record('colours', 'red'), extra: ['moody'] };
+ const getExtra = (candidate: typeof item): readonly string[] => candidate.extra;
+
+ expect(searchCatalog([item], 'red', getBody)).toEqual([item]);
+ expect(searchCatalog([item], 'red', getExtra)).toEqual([]);
+ expect(searchCatalog([item], 'moody', getExtra)).toEqual([item]);
+ expect(searchCatalog([item], 'moody', getBody)).toEqual([]);
+ });
+});
+
+describe('searchProse', () => {
+ it('returns a copy of everything for an empty query', () => {
+ const items = [record('a', 'red'), record('b', 'blue')];
+
+ expect(searchProse(items, ' ', getBody)).toEqual(items);
+ expect(searchProse(items, ' ', getBody)).not.toBe(items);
+ });
+
+ it('ignores the name entirely', () => {
+ const item = record('crimson', 'red');
+
+ expect(searchProse([item], 'crimson', getBody)).toEqual([]);
+ expect(searchProse([item], 'red', getBody)).toEqual([item]);
+ });
+
+ it('keeps the given order', () => {
+ const first = record('a', 'red one');
+ const second = record('b', 'red two');
+
+ expect(searchProse([first, second], 'red', getBody)).toEqual([first, second]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.ts b/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.ts
new file mode 100644
index 0000000000..95dc032dcb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/catalogSearch.ts
@@ -0,0 +1,123 @@
+/**
+ * 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.
+ */
+const proseCaches = new WeakMap<object, WeakMap<object, readonly string[]>>();
+
+const matchesProse = <T extends object>(item: T, getProse: ProseOf<T>, needle: string): boolean => {
+ let cache = proseCaches.get(getProse);
+
+ if (!cache) {
+ cache = new WeakMap<object, readonly string[]>();
+ proseCaches.set(getProse, cache);
+ }
+
+ let lowercased = cache.get(item);
+
+ if (lowercased === undefined) {
+ lowercased = getProse(item).map((field) => field.toLowerCase());
+ cache.set(item, lowercased);
+ }
+
+ return 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();
+
+ if (needle.length === 0) {
+ return [...items];
+ }
+
+ return 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,
+ getProse: ProseOf<T>
+): T[] => {
+ const trimmed = query.trim();
+
+ if (trimmed.length === 0) {
+ 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[] = [];
+
+ for (const match of nameMatches) {
+ named.add(match.obj);
+ results.push(match.obj);
+ }
+
+ const needle = trimmed.toLowerCase();
+
+ for (const item of items) {
+ if (!named.has(item) && matchesProse(item, getProse, needle)) {
+ results.push(item);
+ }
+ }
+
+ return results;
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptHistory.ts b/invokeai/frontend/webv2/src/features/generation/core/promptHistory.ts
index b0de160b99..748e3fdbdc 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/promptHistory.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/promptHistory.ts
@@ -2,6 +2,8 @@ import type { PromptHistoryItem } from '@features/generation/core/contracts';
import type { GenerateSettings } from './types';
+import { searchProse } from './catalogSearch';
+
export const MAX_PROMPT_HISTORY = 100;
export const normalizePromptHistoryItem = (item: PromptHistoryItem): PromptHistoryItem | null => {
@@ -36,18 +38,14 @@ export const removePromptHistoryItem = (
item: PromptHistoryItem
): PromptHistoryItem[] => history.filter((entry) => !isSamePromptHistoryItem(entry, item));
-export const filterPromptHistory = (history: readonly PromptHistoryItem[], searchTerm: string): PromptHistoryItem[] => {
- const query = searchTerm.trim().toLowerCase();
+/** A history entry has no name — it is its two prompts. */
+const getPromptHistoryProse = (item: PromptHistoryItem): readonly string[] => [
+ item.positivePrompt,
+ item.negativePrompt ?? '',
+];
- if (!query) {
- return [...history];
- }
-
- return history.filter(
- (item) =>
- item.positivePrompt.toLowerCase().includes(query) || (item.negativePrompt ?? '').toLowerCase().includes(query)
- );
-};
+export const filterPromptHistory = (history: readonly PromptHistoryItem[], searchTerm: string): PromptHistoryItem[] =>
+ searchProse(history, searchTerm, getPromptHistoryProse);
export const getPromptHistoryItemFromGenerateSettings = (settings: GenerateSettings): PromptHistoryItem => ({
negativePrompt: settings.negativePromptEnabled ? settings.negativePrompt : null,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts
index 09d9edb552..f032e2980a 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardCatalog.ts
@@ -10,16 +10,13 @@
* and grouping never reshuffles it.
*/
-import fuzzysort from 'fuzzysort';
+import { searchCatalog } from './catalogSearch';
export interface WildcardListEntry {
name: string;
values: readonly string[];
}
-/** Matches below this fuzzysort score (0–1) are noise, not results. */
-const NAME_MATCH_THRESHOLD = 0.2;
-
export interface WildcardGroup<T> {
/** `null` for names with no `/` — those render without a header. */
label: string | null;
@@ -28,41 +25,14 @@ export interface WildcardGroup<T> {
/**
* Name matches first, ranked fuzzily, then wildcards whose *values* contain the
- * query.
- *
- * The split is deliberate. Names are short slugs, where fuzzy matching earns its
- * keep (`adg` finds `animals/dogs`); values are free text, where a fuzzy match
- * would fire on almost anything, so they take a plain substring test. Searching
- * values at all matters because a wildcard is mostly its values — you remember
- * that "cyberpunk" is in one of these lists long before you remember which.
- *
- * Values are 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. `.some`
- * exits on the first hit.
+ * 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.
*/
-export const filterWildcards = <T extends WildcardListEntry>(wildcards: readonly T[], query: string): T[] => {
- const trimmed = query.trim();
-
- if (trimmed.length === 0) {
- return [...wildcards];
- }
-
- const nameMatches = fuzzysort.go(trimmed, wildcards, {
- key: (wildcard: T) => wildcard.name,
- threshold: NAME_MATCH_THRESHOLD,
- });
- const matched = new Set<T>(nameMatches.map((result) => result.obj));
- const results = nameMatches.map((result) => result.obj);
- const needle = trimmed.toLowerCase();
+const getWildcardProse = (wildcard: WildcardListEntry): readonly string[] => wildcard.values;
- for (const wildcard of wildcards) {
- if (!matched.has(wildcard) && wildcard.values.some((value) => value.toLowerCase().includes(needle))) {
- results.push(wildcard);
- }
- }
-
- return results;
-};
+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
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
index d08f7483f4..8b796069db 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplates.browser.test.tsx
@@ -280,6 +280,28 @@ describe('the prompt templates panel', () => {
expect(host!.textContent).toContain('Photography');
expect(host!.textContent).not.toContain('Cinematic');
});
+
+ // The same fuzzy name rule the wildcards panel beside it has always used —
+ // these two sit in one popover and used to disagree about what typing means.
+ it('matches a name fuzzily', async () => {
+ await render(
+ <PromptTemplatesPanel
+ activeTemplate={null}
+ catalog={createCatalog()}
+ onApply={vi.fn()}
+ onCreate={vi.fn()}
+ onDetach={vi.fn()}
+ onEdit={vi.fn()}
+ />
+ );
+
+ await act(async () => {
+ await userEvent.fill(host!.querySelector('input')!, 'cnmt');
+ });
+
+ expect(host!.textContent).toContain('Cinematic');
+ expect(host!.textContent).not.toContain('Photography');
+ });
});
describe('the prompt template editor', () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
index 481729de34..65ed5775bb 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx
@@ -4,6 +4,7 @@ import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTem
import type { ChangeEvent } from 'react';
import { Box, HStack, Image, Input, Separator, Stack, Text } from '@chakra-ui/react';
+import { searchCatalog } from '@features/generation/core/catalogSearch';
import { PROMPT_TEMPLATE_PLACEHOLDER } from '@features/generation/core/promptTemplates';
import { toPromptTemplateSnapshot } from '@features/generation/data/promptTemplates';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
@@ -33,12 +34,11 @@ interface PromptTemplatesPanelProps {
onCreate: () => void;
}
-/** Matches on name and on prompt text — a template is mostly its prompt. */
-const matchesSearch = (template: PromptTemplateRecord, query: string): boolean =>
- !query ||
- template.name.toLowerCase().includes(query) ||
- template.positivePrompt.toLowerCase().includes(query) ||
- template.negativePrompt.toLowerCase().includes(query);
+/** A template's prose is its two prompts; `searchCatalog` handles the name. */
+const getTemplateProse = (template: PromptTemplateRecord): readonly string[] => [
+ template.positivePrompt,
+ template.negativePrompt,
+];
export const PromptTemplatesPanel = ({
activeTemplate,
@@ -53,15 +53,14 @@ export const PromptTemplatesPanel = ({
const canManagePromptTemplates = capabilities.canManagePromptTemplates;
const [searchTerm, setSearchTerm] = useState('');
const [pendingDelete, setPendingDelete] = useState<PromptTemplateRecord | null>(null);
- const query = searchTerm.trim().toLowerCase();
const userTemplates = useMemo(
- () => catalog.userTemplates.filter((template) => matchesSearch(template, query)),
- [catalog.userTemplates, query]
+ () => searchCatalog(catalog.userTemplates, searchTerm, getTemplateProse),
+ [catalog.userTemplates, searchTerm]
);
const defaultTemplates = useMemo(
- () => catalog.defaultTemplates.filter((template) => matchesSearch(template, query)),
- [catalog.defaultTemplates, query]
+ () => searchCatalog(catalog.defaultTemplates, searchTerm, getTemplateProse),
+ [catalog.defaultTemplates, searchTerm]
);
const hasResults = userTemplates.length > 0 || defaultTemplates.length > 0;
@@ -124,7 +123,7 @@ export const PromptTemplatesPanel = ({
<PanelMessage>{t('widgets.generate.promptTemplates.loading')}</PanelMessage>
) : !hasResults ? (
<PanelMessage>
- {query
+ {searchTerm.trim()
? t('widgets.generate.promptTemplates.noMatches')
: t('widgets.generate.promptTemplates.noTemplatesYet')}
</PanelMessage>