Skip to content

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

fix(webv2): harden the wildcards editor

joshistoast2481cc013d30
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 31630edcc2..8a5d9f8066 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -956,9 +956,6 @@
"shuffle": "Shuffle the sample",
"maxPrompts": "Max prompts",
"numberOfPrompts": "Number of prompts",
- "seedBehaviour": "Seed",
- "seedPerIteration": "Per iteration",
- "seedPerImage": "Per image",
"promptsPreview": "Prompts preview",
"usePrompt": "Use this prompt",
"andMore": "and {{count}} more",
@@ -969,12 +966,18 @@
"editWildcard": "Edit wildcard",
"wildcardName": "Name",
"wildcardNamePlaceholder": "colors",
+ "wildcardNameInvalid": "Letters, numbers, underscores and hyphens only, starting and ending with a letter or number. Nest with '/', e.g. animals/dogs.",
+ "wildcardNameTaken": "You already have a wildcard with this name",
+ "wildcardNameTooLong": "Name must be at most 128 characters",
"wildcardValues": "Values",
"wildcardValuesPlaceholder": "One value per line",
"wildcardHasNoValues": "No values yet",
"noWildcardsYet": "No wildcards yet. Create one to reuse a list of values as __name__.",
"insertWildcard": "Insert into the prompt",
"couldNotSaveWildcard": "Could not save this wildcard",
+ "couldNotDeleteWildcard": "Could not delete this wildcard",
+ "deleteWildcardTitle": "Delete wildcard",
+ "deleteWildcardBody": "Delete __{{name}}__ and its values? This cannot be undone.",
"resizeWildcardValues": "Resize wildcard values",
"mode": "Mode",
"newSeedPerImage": "New seed for every image"
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
index 7db01a0d62..da46d39e0c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { hasDynamicPromptSyntax, sanitizeDynamicPromptsConfig, sanitizeMaxPrompts } from './dynamicPrompts';
+import {
+ getWildcardNameError,
+ hasDynamicPromptSyntax,
+ sanitizeDynamicPromptsConfig,
+ sanitizeMaxPrompts,
+} from './dynamicPrompts';
describe('hasDynamicPromptSyntax', () => {
it('detects a variant anywhere in the prompt', () => {
@@ -58,3 +63,28 @@ describe('sanitizeDynamicPromptsConfig', () => {
expect(sanitizeDynamicPromptsConfig({ seedBehaviour: 'PER_PROMPT' })?.seedBehaviour).toBe('per-iteration');
});
});
+
+describe('getWildcardNameError', () => {
+ it('accepts the names the backend accepts', () => {
+ expect(getWildcardNameError('colors')).toBeNull();
+ expect(getWildcardNameError('animals/dogs')).toBeNull();
+ expect(getWildcardNameError('sci-fi_props')).toBeNull();
+ expect(getWildcardNameError(' colors ')).toBeNull();
+ });
+
+ it('rejects the names the backend rejects', () => {
+ expect(getWildcardNameError('')).toBe('empty');
+ expect(getWildcardNameError(' ')).toBe('empty');
+ expect(getWildcardNameError('colors list')).toBe('invalid');
+ // A leading or trailing underscore would run into the `__` delimiters.
+ expect(getWildcardNameError('_colors')).toBe('invalid');
+ expect(getWildcardNameError('colors_')).toBe('invalid');
+ expect(getWildcardNameError('a'.repeat(129))).toBe('tooLong');
+ expect(getWildcardNameError('a'.repeat(128))).toBeNull();
+ });
+
+ it('reports a name the user already owns', () => {
+ expect(getWildcardNameError('colors', new Set(['colors']))).toBe('taken');
+ expect(getWildcardNameError('shades', new Set(['colors']))).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
index 7b7526666b..c585ef80ce 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
@@ -31,13 +31,53 @@ export interface DynamicPromptsConfig {
}
/**
- * `__name__`, the reference form for a wildcard. Mirrors the backend's name rule
- * exactly — each `/`-separated segment must begin and end alphanumerically, so
- * `snake__case` is ordinary text rather than a reference. Shared with the syntax
- * scanner so highlighting and expansion agree on what counts as a wildcard.
+ * 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.
*/
-export const WILDCARD_REFERENCE_RE =
- /__([A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?(?:\/[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?)*)__/;
+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})*`;
+
+/**
+ * `__name__`, the reference form for a wildcard. Shared with the syntax scanner
+ * so highlighting and expansion agree on what counts as a wildcard.
+ */
+export const WILDCARD_REFERENCE_RE = new RegExp(`__(${WILDCARD_NAME_SOURCE})__`);
+
+/** The same rule anchored, for validating a name the user is typing. */
+export const WILDCARD_NAME_RE = new RegExp(`^${WILDCARD_NAME_SOURCE}$`);
+
+/** Mirrors the backend's `MAX_WILDCARD_NAME_LENGTH`. */
+export const MAX_WILDCARD_NAME_LENGTH = 128;
+
+/**
+ * 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()
+): 'empty' | 'invalid' | 'taken' | 'tooLong' | null => {
+ const normalized = name.trim();
+
+ if (!normalized) {
+ return 'empty';
+ }
+ if (normalized.length > MAX_WILDCARD_NAME_LENGTH) {
+ return 'tooLong';
+ }
+ if (!WILDCARD_NAME_RE.test(normalized)) {
+ return 'invalid';
+ }
+ if (existingNames.has(normalized)) {
+ return 'taken';
+ }
+
+ return null;
+};
/**
* Whether a prompt is worth sending to the expansion route at all. A prompt with
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
index abab281daa..fa9fd7e081 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx
@@ -13,6 +13,12 @@ import { userEvent } from 'vitest/browser';
const parseDynamicPrompts = vi.hoisted(() => vi.fn());
vi.mock('@features/generation/data/promptUtilities', () => ({ parseDynamicPrompts }));
+// The wildcards tab reports delete failures through Generation's UI port, which
+// only the app composes.
+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useGenerationUi: () => ({ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() } }),
+}));
vi.mock('@features/generation/data/wildcards', () => ({
createWildcard: vi.fn(),
deleteWildcard: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
index 39d63b828b..844ad02543 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx
@@ -8,6 +8,13 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
+// The panel reports delete failures through Generation's UI port, which only the
+// app composes. Everything else in the module stays real.
+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useGenerationUi: () => ({ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() } }),
+}));
+
let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -21,7 +28,7 @@ const catalog: WildcardCatalog = {
wildcards: [{ id: 'w1', name: 'colors', values: ['red', 'green'] }],
};
-const openEditor = async (showSyntaxHighlighting: boolean) => {
+const renderPanel = async (showSyntaxHighlighting = true) => {
host = document.createElement('div');
host.style.width = '380px';
document.body.append(host);
@@ -34,6 +41,10 @@ const openEditor = async (showSyntaxHighlighting: boolean) => {
</ChakraProvider>
);
});
+};
+
+const openEditor = async (showSyntaxHighlighting: boolean) => {
+ await renderPanel(showSyntaxHighlighting);
await act(async () => {
await userEvent.click([...host!.querySelectorAll('button')][0]!);
@@ -90,3 +101,97 @@ describe('wildcard values editor', () => {
expect(host!.querySelectorAll('[aria-hidden="true"] pre span')).toHaveLength(0);
});
});
+
+describe('wildcard name validation', () => {
+ const nameInput = () => host!.querySelector('input')!;
+ const saveButton = () => [...host!.querySelectorAll('button')].find((b) => b.textContent?.includes('common.save'))!;
+ const fillName = async (name: string) => {
+ await act(async () => {
+ await userEvent.fill(nameInput(), name);
+ });
+ };
+
+ const startCreate = async () => {
+ await renderPanel();
+ await act(async () => {
+ await userEvent.click([...host!.querySelectorAll('button')][0]!);
+ });
+ };
+
+ it('cannot save an empty name, and says nothing about it', async () => {
+ await startCreate();
+
+ expect(saveButton().disabled).toBe(true);
+ expect(host!.querySelector('[role="alert"]')).toBeNull();
+ });
+
+ it('explains an unusable name before any request is made', async () => {
+ await startCreate();
+ await fillName('colors list');
+
+ expect(host!.querySelector('[role="alert"]')?.textContent).toContain('wildcardNameInvalid');
+ expect(saveButton().disabled).toBe(true);
+ expect(catalog.create).not.toHaveBeenCalled();
+ });
+
+ it('flags a name the user already owns', async () => {
+ await startCreate();
+ await fillName('colors');
+
+ expect(host!.querySelector('[role="alert"]')?.textContent).toContain('wildcardNameTaken');
+ });
+
+ it('accepts a nested name', async () => {
+ await startCreate();
+ await fillName('animals/dogs');
+
+ expect(host!.querySelector('[role="alert"]')).toBeNull();
+ expect(saveButton().disabled).toBe(false);
+ });
+});
+
+describe('deleting a wildcard', () => {
+ const clickDelete = async () => {
+ // Insert, edit, delete — the trash is the last control on the row.
+ const buttons = [...host!.querySelectorAll('button')];
+
+ await act(async () => {
+ await userEvent.click(buttons.at(-1)!);
+ });
+ };
+ const dialogButton = (label: string) =>
+ [...document.querySelectorAll<HTMLElement>('[role="alertdialog"] button')].find(
+ (button) => button.textContent === label
+ );
+
+ // Regression: the trash icon deleted a wildcard and all of its values outright.
+ it('asks before deleting', async () => {
+ await renderPanel();
+ await clickDelete();
+
+ expect(document.querySelector('[role="alertdialog"]')).toBeTruthy();
+ expect(catalog.remove).not.toHaveBeenCalled();
+ });
+
+ it('leaves the wildcard alone when the dialog is cancelled', async () => {
+ await renderPanel();
+ await clickDelete();
+
+ await act(async () => {
+ await userEvent.click(dialogButton('Cancel')!);
+ });
+
+ expect(catalog.remove).not.toHaveBeenCalled();
+ });
+
+ it('deletes once confirmed', async () => {
+ await renderPanel();
+ await clickDelete();
+
+ await act(async () => {
+ await userEvent.click(dialogButton('common.delete')!);
+ });
+
+ expect(catalog.remove).toHaveBeenCalledWith('w1');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
index bb38ea77ff..36b142a88b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
@@ -4,19 +4,30 @@ import type { WildcardCatalog } from '@features/generation/ui/useWildcards';
import type { ChangeEvent } from 'react';
import { HStack, Input, Stack, Text } from '@chakra-ui/react';
+import { getWildcardNameError } from '@features/generation/core/dynamicPrompts';
+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';
import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';
+import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton } from '@platform/ui/Button';
+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
+import { Field } from '@platform/ui/Field';
import { Scrollable } from '@platform/ui/Scrollable';
import { Tooltip } from '@platform/ui/Tooltip';
import { CheckIcon, PencilIcon, PlusIcon, TrashIcon, XIcon } from 'lucide-react';
-import { useCallback, useState } from 'react';
+import { useCallback, useId, useState } from 'react';
import { useTranslation } from 'react-i18next';
/** One value per line: the same shape the user is editing a variant in. */
const toValuesText = (values: string[]): string => values.join('\n');
const fromValuesText = (text: string): string[] => text.split('\n');
+const NAME_ERROR_KEY = {
+ invalid: 'widgets.generate.dynamicPrompts.wildcardNameInvalid',
+ taken: 'widgets.generate.dynamicPrompts.wildcardNameTaken',
+ tooLong: 'widgets.generate.dynamicPrompts.wildcardNameTooLong',
+} as const;
+
interface WildcardDraft {
id: string | null;
name: string;
@@ -34,8 +45,16 @@ export const WildcardsPanel = ({
onInsert: (reference: string) => void;
}) => {
const { t } = useTranslation();
+ const { notifications } = useGenerationUi();
+ const nameFieldId = useId();
const [draft, setDraft] = useState<WildcardDraft | null>(null);
const [error, setError] = useState<string | null>(null);
+ const [pendingDelete, setPendingDelete] = useState<WildcardRecord | null>(null);
+ // Renaming to your own current name is not a clash, so the wildcard being
+ // edited is excluded from the taken-names set.
+ const nameError = draft
+ ? getWildcardNameError(draft.name, new Set(catalog.wildcards.filter((w) => w.id !== draft.id).map((w) => w.name)))
+ : null;
const startCreate = useCallback(() => {
setError(null);
@@ -68,10 +87,34 @@ export const WildcardsPanel = ({
setDraft(null);
setError(null);
} catch (caught) {
- setError(caught instanceof Error ? caught.message : t('widgets.generate.dynamicPrompts.couldNotSaveWildcard'));
+ // `ApiError.message` is the raw response body, so the backend's own
+ // explanation only reads properly once it is unwrapped.
+ setError(getApiErrorMessage(caught, t('widgets.generate.dynamicPrompts.couldNotSaveWildcard')));
}
}, [catalog, draft, t]);
+ const closeDeleteDialog = useCallback(() => setPendingDelete(null), []);
+
+ /**
+ * The dialog closes whether or not this throws, so a failure has nowhere inline
+ * to land — it goes to the notification centre like the other Generation errors.
+ */
+ const confirmDelete = useCallback(async () => {
+ if (!pendingDelete) {
+ return;
+ }
+
+ try {
+ await catalog.remove(pendingDelete.id);
+ } catch (caught) {
+ notifications.reportError({
+ area: 'delete-wildcard',
+ message: getApiErrorMessage(caught, t('widgets.generate.dynamicPrompts.couldNotDeleteWildcard')),
+ namespace: 'generation',
+ });
+ }
+ }, [catalog, notifications, pendingDelete, t]);
+
if (draft) {
return (
<Stack gap="2">
@@ -82,13 +125,21 @@ export const WildcardsPanel = ({
: t('widgets.generate.dynamicPrompts.editWildcard')
}
/>
- <Input
- aria-label={t('widgets.generate.dynamicPrompts.wildcardName')}
- placeholder={t('widgets.generate.dynamicPrompts.wildcardNamePlaceholder')}
- size="xs"
- value={draft.name}
- onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft({ ...draft, name: event.currentTarget.value })}
- />
+ {/* An empty name is the starting state rather than a mistake, so it
+ disables Save without being called out. */}
+ <Field
+ error={nameError === null || nameError === 'empty' ? null : t(NAME_ERROR_KEY[nameError])}
+ id={nameFieldId}
+ label={t('widgets.generate.dynamicPrompts.wildcardName')}
+ >
+ <Input
+ aria-invalid={nameError !== null && nameError !== 'empty' ? true : undefined}
+ placeholder={t('widgets.generate.dynamicPrompts.wildcardNamePlaceholder')}
+ size="xs"
+ value={draft.name}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft({ ...draft, name: event.currentTarget.value })}
+ />
+ </Field>
{/* Values are expanded by dynamicprompts too, so a nested `{a|b}` or
`__other__` is live syntax here and is coloured as such. The gutter
numbers the values, which is what a line means in this editor. */}
@@ -120,7 +171,7 @@ export const WildcardsPanel = ({
<XIcon />
{t('common.cancel')}
</Button>
- <Button disabled={!draft.name.trim()} size="xs" onClick={() => void save()}>
+ <Button disabled={nameError !== null} size="xs" onClick={() => void save()}>
<CheckIcon />
{t('common.save')}
</Button>
@@ -148,8 +199,8 @@ export const WildcardsPanel = ({
{catalog.wildcards.map((wildcard) => (
<WildcardRow
key={wildcard.id}
- catalog={catalog}
wildcard={wildcard}
+ onDelete={setPendingDelete}
onEdit={startEdit}
onInsert={onInsert}
/>
@@ -157,18 +208,29 @@ export const WildcardsPanel = ({
</Stack>
)}
</Scrollable>
+
+ {/* A wildcard's values are typed by hand and there is no undo, so deleting
+ one asks first — as every other destructive action here does. */}
+ <ConfirmDialog
+ body={t('widgets.generate.dynamicPrompts.deleteWildcardBody', { name: pendingDelete?.name ?? '' })}
+ confirmLabel={t('common.delete')}
+ isOpen={pendingDelete !== null}
+ title={t('widgets.generate.dynamicPrompts.deleteWildcardTitle')}
+ onClose={closeDeleteDialog}
+ onConfirm={confirmDelete}
+ />
</Stack>
);
};
const WildcardRow = ({
- catalog,
+ onDelete,
onEdit,
onInsert,
wildcard,
}: {
- catalog: WildcardCatalog;
wildcard: WildcardRecord;
+ onDelete: (wildcard: WildcardRecord) => void;
onEdit: (wildcard: WildcardRecord) => void;
onInsert: (reference: string) => void;
}) => {
@@ -211,7 +273,7 @@ const WildcardRow = ({
colorPalette="red"
size="2xs"
variant="ghost"
- onClick={() => void catalog.remove(wildcard.id)}
+ onClick={() => onDelete(wildcard)}
>
<TrashIcon />
</IconButton>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
index cef7a1aef8..ec23db0fa3 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts
@@ -7,6 +7,7 @@ import {
updateWildcard,
wildcardsQueryOptions,
} from '@features/generation/data/wildcards';
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
@@ -36,9 +37,14 @@ export const useWildcards = (): WildcardCatalog => {
[wildcards]
);
+ // Each mutation captures the identity that started it, so a sign-out mid-flight
+ // does not invalidate the next account's caches on the way back.
const create = useCallback(
async (wildcard: { name: string; values: string[] }) => {
+ const owner = captureAccountScope();
+
await createWildcard(wildcard);
+ assertAccountScopeCurrent(owner);
await invalidateWildcardDependents(queryClient);
},
[queryClient]
@@ -46,7 +52,10 @@ export const useWildcards = (): WildcardCatalog => {
const update = useCallback(
async (id: string, changes: { name?: string; values?: string[] }) => {
+ const owner = captureAccountScope();
+
await updateWildcard(id, changes);
+ assertAccountScopeCurrent(owner);
await invalidateWildcardDependents(queryClient);
},
[queryClient]
@@ -54,7 +63,10 @@ export const useWildcards = (): WildcardCatalog => {
const remove = useCallback(
async (id: string) => {
+ const owner = captureAccountScope();
+
await deleteWildcard(id);
+ assertAccountScopeCurrent(owner);
await invalidateWildcardDependents(queryClient);
},
[queryClient]