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
fix(webv2): report and bound wildcard import
joshistoast1bbaedd6d911
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 52008e5a03..1b88a76905 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1006,6 +1006,7 @@"importedCount_one": "Imported {{count}} wildcard","importedCount_other": "Imported {{count}} wildcards","couldNotImport": "Could not import these wildcards",+ "couldNotImportAfter": "Stopped after importing {{done}} of {{total}} wildcards","couldNotExport": "Could not export your wildcards","couldNotReadFile": "Could not read {{name}}"},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 3e650ec7c6..941624f3f2 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@@ -107,6 +107,27 @@ 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();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsxindex eb172df6ae..27e4605bd6 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx@@ -46,26 +46,36 @@ export const WildcardImportDialog = ({}) => {const { t } = useTranslation();const [resolutions, setResolutions] = useState<Record<string, WildcardImportResolution>>({});+ // The set-all row is a control in its own right, so it has to hold what it was+ // last set to. Rendered without a value it read as nothing selected however+ // often it was used, which invited a second click — and that reapplied the+ // choice over every per-row override made in between.+ const [allResolution, setAllResolution] = useState<WildcardImportResolution | null>(null);const conflicts = useMemo(() => entries.filter((entry) => entry.rejection === null && entry.conflictId !== null),[entries]);- const freshCount = entries.filter((entry) => entry.rejection === null && entry.conflictId === null).length;+ const freshCount = useMemo(+ () => entries.filter((entry) => entry.rejection === null && entry.conflictId === null).length,+ [entries]+ );const rejected = useMemo(() => entries.flatMap((entry) => (entry.rejection ? [{ name: entry.name, rejection: entry.rejection }] : [])),[entries]);- const setResolution = useCallback(- (name: string, resolution: WildcardImportResolution) =>- setResolutions((current) => ({ ...current, [name]: resolution })),- []- );+ const setResolution = useCallback((name: string, resolution: WildcardImportResolution) => {+ // A single row disagreeing means the set-all row no longer describes them.+ setAllResolution(null);+ setResolutions((current) => ({ ...current, [name]: resolution }));+ }, []);const setAllResolutions = useCallback(- (resolution: WildcardImportResolution) =>- setResolutions(Object.fromEntries(conflicts.map((entry) => [entry.name, resolution]))),+ (resolution: WildcardImportResolution) => {+ setAllResolution(resolution);+ setResolutions(Object.fromEntries(conflicts.map((entry) => [entry.name, resolution])));+ },[conflicts]);@@ -87,7 +97,7 @@ export const WildcardImportDialog = ({{t('widgets.generate.dynamicPrompts.importAlreadyExist')}</Text>{/* One decision for a folder of forty; the rows below still win. */}- {conflicts.length > 1 ? <ResolutionControl onChange={setAllResolutions} /> : null}+ {conflicts.length > 1 ? <ResolutionControl value={allResolution} onChange={setAllResolutions} /> : null}</HStack><Scrollable maxH="12rem" label={t('widgets.generate.dynamicPrompts.importAlreadyExist')}><Stack gap="1" pr="1">@@ -110,16 +120,23 @@ export const WildcardImportDialog = ({<Text fontSize="xs" fontWeight="600">{t('widgets.generate.dynamicPrompts.importCannotImport')}</Text>- {rejected.map((entry) => (- <HStack justify="space-between" key={entry.name}>- <Text fontFamily="mono" fontSize="2xs" truncate>- {entry.name || t('widgets.generate.dynamicPrompts.importUnnamed')}- </Text>- <Text color="fg.subtle" fontSize="2xs" flexShrink="0">- {t(REJECTION_KEY[entry.rejection])}- </Text>- </HStack>- ))}+ {/* Bounded like the conflicts above it. Pointed at a folder where most+ files are unusable, this list grew past the viewport and pushed the+ dialog's own buttons out of reach. */}+ <Scrollable maxH="8rem" label={t('widgets.generate.dynamicPrompts.importCannotImport')}>+ <Stack gap="1" pr="1">+ {rejected.map((entry, index) => (+ <HStack justify="space-between" key={`${entry.name}-${index}`}>+ <Text fontFamily="mono" fontSize="2xs" truncate>+ {entry.name || t('widgets.generate.dynamicPrompts.importUnnamed')}+ </Text>+ <Text color="fg.subtle" fontSize="2xs" flexShrink="0">+ {t(REJECTION_KEY[entry.rejection])}+ </Text>+ </HStack>+ ))}+ </Stack>+ </Scrollable></Stack>) : null}</Stack>@@ -143,7 +160,7 @@ const ResolutionControl = ({value,}: {onChange: (resolution: WildcardImportResolution) => void;- value?: WildcardImportResolution;+ value?: WildcardImportResolution | null;}) => {const { t } = useTranslation();const handleValueChange = useCallback(diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsxindex fa2d4b272d..b80e4591f8 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx@@ -66,7 +66,16 @@ export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalognotifications.info(t('widgets.generate.dynamicPrompts.importedCount', { count: done }));} catch (caught) {- reportError('import-wildcards', caught, t('widgets.generate.dynamicPrompts.couldNotImport'));+ // Writes go one at a time, so a failure part-way leaves real wildcards+ // behind. Saying only that the import failed sent people back for a+ // second run that then clashed with everything the first one had made.+ reportError(+ 'import-wildcards',+ caught,+ done > 0+ ? t('widgets.generate.dynamicPrompts.couldNotImportAfter', { done, total: actions.length })+ : t('widgets.generate.dynamicPrompts.couldNotImport')+ );} finally {setIsBusy(false);setPendingEntries(null);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.tsnew file mode 100644index 0000000000..f64118ba30--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.browser.test.ts@@ -0,0 +1,52 @@+import { readWildcardFiles, WildcardFileError } from '@features/generation/ui/wildcardFiles';+import { describe, expect, it } from 'vitest';++const file = (name: string, contents: string) => new File([contents], name, { type: 'text/plain' });++describe('readWildcardFiles', () => {+ it('reads a text file as one wildcard named after it', async () => {+ await expect(readWildcardFiles([file('colours.txt', 'red\n# a note\n\ngreen')])).resolves.toEqual([+ { name: 'colours', values: ['red', 'green'] },+ ]);+ });++ it('reads a nested yaml collection', async () => {+ await expect(readWildcardFiles([file('all.yaml', 'animals:\n dogs:\n - corgi\n')])).resolves.toEqual([+ { name: 'animals/dogs', values: ['corgi'] },+ ]);+ });++ it('reads a json collection', async () => {+ await expect(readWildcardFiles([file('all.json', '{"moods":["calm"]}')])).resolves.toEqual([+ { name: 'moods', values: ['calm'] },+ ]);+ });++ it('takes an extensionless file as text', async () => {+ await expect(readWildcardFiles([file('colours', 'red')])).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(readWildcardFiles([file('README.md', '# Wildcards\n\nSome notes.')])).rejects.toBeInstanceOf(+ WildcardFileError+ );+ });++ it('names the file it could not read', async () => {+ await expect(readWildcardFiles([file('broken.json', '{ nope')])).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(readWildcardFiles([file('huge.json', huge)])).rejects.toBeInstanceOf(WildcardFileError);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.tsindex db8e01f7e0..7276530765 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts@@ -38,6 +38,17 @@ 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.*@@ -45,18 +56,43 @@ export class WildcardFileError extends Error {* 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 `wildcards` yes, `README.md` and `preview.png` no. */+const isTextWildcardFile = (path: string): boolean => {+ const name = path.slice(path.lastIndexOf('/') + 1);+ const dot = name.lastIndexOf('.');++ return dot <= 0 || name.slice(dot).toLowerCase() === '.txt';+};+export const readWildcardFiles = async (files: readonly File[]): Promise<ParsedWildcard[]> => {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);+ }++ if (parsed.length > MAX_IMPORT_WILDCARDS) {+ throw new WildcardFileError(fileName);+ }+ };+for (const file of files) {const path = getFilePath(file);++ if (file.size > MAX_IMPORT_FILE_BYTES) {+ throw new WildcardFileError(file.name);+ }+const contents = await file.text();if (hasExtension(path, '.yaml', '.yml')) {const { parse } = await import('yaml');try {- parsed.push(...wildcardsFromNestedRecord(parse(contents)));+ collect(wildcardsFromNestedRecord(parse(contents)), file.name);} catch {throw new WildcardFileError(file.name);}@@ -65,16 +101,22 @@ export const readWildcardFiles = async (files: readonly File[]): Promise<ParsedWif (hasExtension(path, '.json')) {try {- parsed.push(...wildcardsFromNestedRecord(JSON.parse(contents)));+ collect(wildcardsFromNestedRecord(JSON.parse(contents)), file.name);} catch {throw new WildcardFileError(file.name);}continue;}- // Anything else is read a line at a time. A wildcard file has no header to- // check, and refusing an extensionless one would only be pedantry.- parsed.push(parseWildcardTextFile(path, contents));+ // 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);+ }++ collect([parseWildcardTextFile(path, contents)], file.name);}return parsed;