Skip to content

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

feat(webv2): import and export wildcards

joshistoast005efdd297a9
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 9adfadd11a..6a29d3f9e4 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -59,6 +59,7 @@
"socket.io-client": "^4.8.3",
"tinykeys": "^4.0.0",
"use-sync-external-store": "^1.6.0",
+ "yaml": "^2.9.0",
"zod": "^4.4.3"
},
"devDependencies": {
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 107e24e679..7b2093ac1c 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -25,11 +25,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 115.10000000149012,
+ "domContentLoadedMedianMs": 112.39999999850988,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 115.10000000149012,
- "longestTaskMaxMs": 71,
+ "loadMedianMs": 112.39999999850988,
+ "longestTaskMaxMs": 70,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -39,24 +39,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 19,
"scriptRawBytes": 1454462,
"scriptRequestCount": 15,
- "totalRawBytes": 1573753
+ "totalRawBytes": 1575052
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 19,
"scriptRawBytes": 1469007,
"scriptRequestCount": 15,
- "totalRawBytes": 1589491
+ "totalRawBytes": 1590803
},
- "routeReadyMedianMs": 238.90000000223517,
+ "routeReadyMedianMs": 231.09999999403954,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -83,11 +83,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 118,
+ "domContentLoadedMedianMs": 113.20000000298023,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 118,
- "longestTaskMaxMs": 74,
+ "loadMedianMs": 113.30000000447035,
+ "longestTaskMaxMs": 72,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -97,24 +97,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 19,
"scriptRawBytes": 1454462,
"scriptRequestCount": 15,
- "totalRawBytes": 1573753
+ "totalRawBytes": 1575052
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 19,
"scriptRawBytes": 1469007,
"scriptRequestCount": 15,
- "totalRawBytes": 1589491
+ "totalRawBytes": 1590803
},
- "routeReadyMedianMs": 305.5,
+ "routeReadyMedianMs": 293.1000000014901,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -141,13 +141,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 120.5,
+ "domContentLoadedMedianMs": 113.5,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 120.59999999776483,
- "longestTaskMaxMs": 125,
+ "loadMedianMs": 113.5,
+ "longestTaskMaxMs": 113,
"owner": "workbench",
- "projectSwitchMedianMs": 67.16945699999997,
+ "projectSwitchMedianMs": 67.2813270000006,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -155,24 +155,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2982602,
+ "scriptRawBytes": 2995457,
"scriptRequestCount": 89,
- "totalRawBytes": 3273682
+ "totalRawBytes": 3287836
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3012429,
+ "scriptRawBytes": 3025412,
"scriptRequestCount": 89,
- "totalRawBytes": 3306419
+ "totalRawBytes": 3320715
},
- "routeReadyMedianMs": 643.5,
+ "routeReadyMedianMs": 618.8000000044703,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -199,13 +199,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 118.20000000298023,
+ "domContentLoadedMedianMs": 111.20000000298023,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 118.20000000298023,
- "longestTaskMaxMs": 131,
+ "loadMedianMs": 111.20000000298023,
+ "longestTaskMaxMs": 123,
"owner": "workbench",
- "projectSwitchMedianMs": 89.83035799999925,
+ "projectSwitchMedianMs": 85.25958499999979,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -213,24 +213,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2982602,
+ "scriptRawBytes": 2995457,
"scriptRequestCount": 89,
- "totalRawBytes": 3273682
+ "totalRawBytes": 3287836
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3012429,
+ "scriptRawBytes": 3025412,
"scriptRequestCount": 89,
- "totalRawBytes": 3306419
+ "totalRawBytes": 3320715
},
- "routeReadyMedianMs": 684.1000000014901,
+ "routeReadyMedianMs": 666,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -257,11 +257,11 @@
"scriptRequestCount": 7,
"totalRawBytes": 293334
},
- "domContentLoadedMedianMs": 117.19999999925494,
+ "domContentLoadedMedianMs": 111.20000000298023,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 85.90000000223517,
- "loadMedianMs": 117.19999999925494,
- "longestTaskMaxMs": 120,
+ "layoutSwitchMedianMs": 80.90000000596046,
+ "loadMedianMs": 111.20000000298023,
+ "longestTaskMaxMs": 113,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -271,24 +271,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 99,
- "scriptRawBytes": 3258796,
+ "scriptRawBytes": 3271651,
"scriptRequestCount": 93,
- "totalRawBytes": 3549876
+ "totalRawBytes": 3564030
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 99,
- "scriptRawBytes": 3291384,
+ "scriptRawBytes": 3304368,
"scriptRequestCount": 93,
- "totalRawBytes": 3585375
+ "totalRawBytes": 3599671
},
- "routeReadyMedianMs": 801.1000000014901,
+ "routeReadyMedianMs": 761.3999999985099,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -315,11 +315,11 @@
"scriptRequestCount": 7,
"totalRawBytes": 293334
},
- "domContentLoadedMedianMs": 117.90000000223517,
+ "domContentLoadedMedianMs": 110.79999999701977,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 341.29999999701977,
- "loadMedianMs": 117.90000000223517,
- "longestTaskMaxMs": 400,
+ "layoutSwitchMedianMs": 320.80000000447035,
+ "loadMedianMs": 110.89999999850988,
+ "longestTaskMaxMs": 372,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -329,24 +329,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 99,
- "scriptRawBytes": 3258796,
+ "scriptRawBytes": 3271651,
"scriptRequestCount": 93,
- "totalRawBytes": 3549876
+ "totalRawBytes": 3564030
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 99,
- "scriptRawBytes": 3291384,
+ "scriptRawBytes": 3304368,
"scriptRequestCount": 93,
- "totalRawBytes": 3585375
+ "totalRawBytes": 3599671
},
- "routeReadyMedianMs": 1231.5999999977648,
+ "routeReadyMedianMs": 1159,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -373,11 +373,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 117.89999999850988,
+ "domContentLoadedMedianMs": 108.5,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 78.30000000074506,
- "loadMedianMs": 118,
- "longestTaskMaxMs": 120,
+ "layoutSwitchMedianMs": 72.70000000298023,
+ "loadMedianMs": 108.5,
+ "longestTaskMaxMs": 114,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -387,24 +387,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2982602,
+ "scriptRawBytes": 2995457,
"scriptRequestCount": 89,
- "totalRawBytes": 3273682
+ "totalRawBytes": 3287836
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3012429,
+ "scriptRawBytes": 3025412,
"scriptRequestCount": 89,
- "totalRawBytes": 3306419
+ "totalRawBytes": 3320715
},
- "routeReadyMedianMs": 796.3999999985099,
+ "routeReadyMedianMs": 763.6000000014901,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -431,11 +431,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 118.40000000223517,
+ "domContentLoadedMedianMs": 111.5,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 137.89999999850988,
- "loadMedianMs": 118.5,
- "longestTaskMaxMs": 462,
+ "layoutSwitchMedianMs": 124.69999999552965,
+ "loadMedianMs": 111.5,
+ "longestTaskMaxMs": 426,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -445,24 +445,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2982602,
+ "scriptRawBytes": 2995457,
"scriptRequestCount": 89,
- "totalRawBytes": 3273682
+ "totalRawBytes": 3287836
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3012429,
+ "scriptRawBytes": 3025412,
"scriptRequestCount": 89,
- "totalRawBytes": 3306419
+ "totalRawBytes": 3320715
},
- "routeReadyMedianMs": 1016,
+ "routeReadyMedianMs": 956.2999999970198,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -489,11 +489,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 117.10000000149012,
+ "domContentLoadedMedianMs": 111.39999999850988,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 29.199999999254942,
- "loadMedianMs": 117.10000000149012,
- "longestTaskMaxMs": 123,
+ "layoutSwitchMedianMs": 28.80000000447035,
+ "loadMedianMs": 111.39999999850988,
+ "longestTaskMaxMs": 113,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -503,24 +503,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2982602,
+ "scriptRawBytes": 2995457,
"scriptRequestCount": 89,
- "totalRawBytes": 3273682
+ "totalRawBytes": 3287836
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3012429,
+ "scriptRawBytes": 3025412,
"scriptRequestCount": 89,
- "totalRawBytes": 3306419
+ "totalRawBytes": 3320715
},
- "routeReadyMedianMs": 761.7999999970198,
+ "routeReadyMedianMs": 722.3999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -547,11 +547,11 @@
"scriptRequestCount": 3,
"totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 119.30000000074506,
+ "domContentLoadedMedianMs": 113,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 41.69999999925494,
- "loadMedianMs": 119.30000000074506,
- "longestTaskMaxMs": 129,
+ "layoutSwitchMedianMs": 38.600000001490116,
+ "loadMedianMs": 113,
+ "longestTaskMaxMs": 130,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -561,24 +561,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 93468,
+ "otherRawBytes": 94767,
"requestCount": 95,
- "scriptRawBytes": 2982602,
+ "scriptRawBytes": 2995457,
"scriptRequestCount": 89,
- "totalRawBytes": 3273682
+ "totalRawBytes": 3287836
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 94403,
+ "otherRawBytes": 95715,
"requestCount": 95,
- "scriptRawBytes": 3012429,
+ "scriptRawBytes": 3025412,
"scriptRequestCount": 89,
- "totalRawBytes": 3306419
+ "totalRawBytes": 3320715
},
- "routeReadyMedianMs": 927,
+ "routeReadyMedianMs": 882.1000000014901,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1002,6 +1002,8 @@
"source:src/features/generation/core/promptTemplates.ts",
"source:src/features/generation/core/referenceImage.ts",
"source:src/features/generation/core/settings.ts",
+ "source:src/features/generation/core/wildcardCatalog.ts",
+ "source:src/features/generation/core/wildcardTransfer.ts",
"source:src/features/generation/data/dynamicPromptsQueries.ts",
"source:src/features/generation/data/promptTemplates.ts",
"source:src/features/generation/data/promptUtilities.ts",
@@ -1038,6 +1040,8 @@
"source:src/features/generation/ui/promptFields/PromptTemplatesButton.tsx",
"source:src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
+ "source:src/features/generation/ui/promptFields/WildcardImportDialog.tsx",
+ "source:src/features/generation/ui/promptFields/WildcardTransferActions.tsx",
"source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
"source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts",
@@ -1058,6 +1062,7 @@
"source:src/features/generation/ui/useDynamicPrompts.ts",
"source:src/features/generation/ui/usePromptTemplates.ts",
"source:src/features/generation/ui/useWildcards.ts",
+ "source:src/features/generation/ui/wildcardFiles.ts",
"source:src/features/generation/widget.ts",
"source:src/features/identity/capabilities.ts",
"source:src/features/identity/core/schemas.ts",
@@ -1794,6 +1799,8 @@
"source:src/features/generation/core/promptTemplates.ts",
"source:src/features/generation/core/referenceImage.ts",
"source:src/features/generation/core/settings.ts",
+ "source:src/features/generation/core/wildcardCatalog.ts",
+ "source:src/features/generation/core/wildcardTransfer.ts",
"source:src/features/generation/data/dynamicPromptsQueries.ts",
"source:src/features/generation/data/promptTemplates.ts",
"source:src/features/generation/data/promptUtilities.ts",
@@ -1830,6 +1837,8 @@
"source:src/features/generation/ui/promptFields/PromptTemplatesButton.tsx",
"source:src/features/generation/ui/promptFields/PromptTemplatesPanel.tsx",
"source:src/features/generation/ui/promptFields/PromptTextarea.tsx",
+ "source:src/features/generation/ui/promptFields/WildcardImportDialog.tsx",
+ "source:src/features/generation/ui/promptFields/WildcardTransferActions.tsx",
"source:src/features/generation/ui/promptFields/WildcardsPanel.tsx",
"source:src/features/generation/ui/promptFields/index.ts",
"source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts",
@@ -1850,6 +1859,7 @@
"source:src/features/generation/ui/useDynamicPrompts.ts",
"source:src/features/generation/ui/usePromptTemplates.ts",
"source:src/features/generation/ui/useWildcards.ts",
+ "source:src/features/generation/ui/wildcardFiles.ts",
"source:src/features/generation/widget.ts",
"source:src/features/identity/capabilities.ts",
"source:src/features/identity/core/schemas.ts",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index d0d5c9e9fc..d50490cf45 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -83,13 +83,16 @@ importers:
use-sync-external-store:
specifier: ^1.6.0
version: 1.6.0([email protected])
+ yaml:
+ specifier: ^2.9.0
+ version: 2.9.0
zod:
specifier: ^4.4.3
version: 4.4.3
devDependencies:
'@rolldown/plugin-babel':
specifier: ^0.2.3
'@types/node':
specifier: ^26.1.1
version: 26.1.1
@@ -104,10 +107,10 @@ importers:
version: 1.5.0
'@vitejs/plugin-react':
specifier: ^6.0.3
'@vitest/browser-playwright':
specifier: 4.1.10
axe-core:
specifier: ^4.12.1
version: 4.12.1
@@ -131,10 +134,10 @@ importers:
vite:
specifier: ^8.1.5
- version: 8.1.5(@types/[email protected])([email protected])
vitest:
specifier: ^4.1.10
packages:
@@ -2072,6 +2075,11 @@ packages:
resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==}
+ engines: {node: '>= 14.6'}
+ hasBin: true
+
resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
@@ -2691,14 +2699,14 @@ snapshots:
'@rolldown/[email protected]':
optional: true
dependencies:
'@babel/core': 7.29.7
picomatch: 4.0.5
rolldown: 1.1.5
optionalDependencies:
'@babel/runtime': 7.29.7
- vite: 8.1.5(@types/[email protected])([email protected])
'@rolldown/[email protected]': {}
@@ -2863,37 +2871,37 @@ snapshots:
'@typescript/[email protected]':
optional: true
dependencies:
'@rolldown/pluginutils': 1.0.1
- vite: 8.1.5(@types/[email protected])([email protected])
optionalDependencies:
babel-plugin-react-compiler: 1.0.0
dependencies:
- '@vitest/mocker': 4.1.10([email protected](@types/[email protected])([email protected]))
playwright: 1.61.1
tinyrainbow: 3.1.0
transitivePeerDependencies:
- bufferutil
- msw
- utf-8-validate
- vite
dependencies:
'@blazediff/core': 1.9.1
- '@vitest/mocker': 4.1.10([email protected](@types/[email protected])([email protected]))
'@vitest/utils': 4.1.10
magic-string: 0.30.21
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.1.0
ws: 8.21.1
transitivePeerDependencies:
- bufferutil
@@ -2910,13 +2918,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
dependencies:
'@vitest/spy': 4.1.10
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 8.1.5(@types/[email protected])([email protected])
'@vitest/[email protected]':
dependencies:
@@ -4085,7 +4093,7 @@ snapshots:
dependencies:
react: 19.2.7
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.5
@@ -4096,11 +4104,12 @@ snapshots:
'@types/node': 26.1.1
esbuild: 0.27.7
fsevents: 2.3.3
+ yaml: 2.9.0
dependencies:
'@vitest/expect': 4.1.10
- '@vitest/mocker': 4.1.10([email protected](@types/[email protected])([email protected]))
'@vitest/pretty-format': 4.1.10
'@vitest/runner': 4.1.10
'@vitest/snapshot': 4.1.10
@@ -4117,11 +4126,11 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
- vite: 8.1.5(@types/[email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 26.1.1
transitivePeerDependencies:
- msw
@@ -4140,6 +4149,8 @@ snapshots:
+
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index cdb9909d19..ac43cbbdea 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -982,7 +982,31 @@
"deleteWildcardBody": "Delete __{{name}}__ and its values? This cannot be undone.",
"resizeWildcardValues": "Resize wildcard values",
"mode": "Mode",
- "newSeedPerImage": "New seed for every image"
+ "newSeedPerImage": "New seed for every image",
+ "import": "Import",
+ "export": "Export",
+ "exportAsYaml": "As YAML",
+ "exportAsJson": "As JSON",
+ "importWildcards": "Import wildcards",
+ "importSummary": "{{fresh}} new, {{conflicts}} already in your library",
+ "importAlreadyExist": "Already in your library",
+ "importSkip": "Skip",
+ "importReplace": "Replace",
+ "importKeepBoth": "Keep both",
+ "importValueCount_one": "{{count}} value",
+ "importValueCount_other": "{{count}} values",
+ "importCannotImport": "Cannot be imported",
+ "importUnnamed": "(no name)",
+ "importRejectedInvalid": "Unusable name",
+ "importRejectedTooLong": "Name too long",
+ "importRejectedDuplicate": "Repeated in this import",
+ "importRejectedNoValues": "No values",
+ "importRejectedTooManyValues": "Too long for the server",
+ "importedCount_one": "Imported {{count}} wildcard",
+ "importedCount_other": "Imported {{count}} wildcards",
+ "couldNotImport": "Could not import these wildcards",
+ "couldNotExport": "Could not export your wildcards",
+ "couldNotReadFile": "Could not read {{name}}"
},
"promptTemplates": {
"title": "Prompt templates",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.test.ts b/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.test.ts
new file mode 100644
index 0000000000..9e6ed914d2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.test.ts
@@ -0,0 +1,265 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getAvailableWildcardName,
+ getWildcardImportActions,
+ getWildcardNameFromPath,
+ parseWildcardTextFile,
+ planWildcardImport,
+ wildcardsFromNestedRecord,
+ 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({
+ name: 'colours',
+ values: ['red', 'green', 'blue'],
+ });
+ });
+
+ 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'] },
+ ]);
+ });
+
+ it('takes a key that already contains a slash as written', () => {
+ expect(wildcardsFromNestedRecord({ 'animals/dogs': ['corgi'] })).toEqual([
+ { name: 'animals/dogs', values: ['corgi'] },
+ ]);
+ });
+
+ 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', () => {
+ const parent = { name: 'animals', values: ['bear'] };
+ const child = { name: 'animals/dogs', values: ['corgi'] };
+
+ 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)));
+ });
+});
+
+describe('planWildcardImport', () => {
+ const existing = [{ id: 'w1', name: 'colours' }];
+
+ it('marks a clash with the wildcard it would overwrite', () => {
+ const [clashing, fresh] = planWildcardImport(
+ [
+ { name: 'colours', values: ['red'] },
+ { name: 'moods', values: ['calm'] },
+ ],
+ 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');
+ });
+
+ it('reports a list past the backend limits', () => {
+ const [tooMany, tooLong] = planWildcardImport(
+ [
+ { name: 'many', values: Array.from({ length: 10_001 }, (_, index) => `v${index}`) },
+ { name: 'long', values: ['x'.repeat(2_001)] },
+ ],
+ existing
+ );
+
+ expect(tooMany.rejection).toBe('tooManyValues');
+ expect(tooLong.rejection).toBe('tooManyValues');
+ });
+
+ it('keeps the first of a name repeated within one import and reports the rest', () => {
+ const entries = planWildcardImport(
+ [
+ { name: 'moods', values: ['calm'] },
+ { name: 'moods', values: ['tense'] },
+ ],
+ 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'] },
+ { 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(
+ [
+ { name: 'colours', values: ['red'] },
+ { name: 'moods', values: ['calm'] },
+ ],
+ [
+ { id: 'w1', name: 'colours' },
+ { id: 'w2', name: 'moods' },
+ ]
+ );
+
+ expect(
+ getWildcardImportActions(clashes, { 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.ts
new file mode 100644
index 0000000000..b1c8e094ca
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/wildcardTransfer.ts
@@ -0,0 +1,296 @@
+/**
+ * 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, MAX_WILDCARD_NAME_LENGTH } from './dynamicPrompts';
+
+export interface ParsedWildcard {
+ name: string;
+ values: string[];
+}
+
+/** Mirrors the backend's per-wildcard limits, so a doomed request is never sent. */
+const MAX_WILDCARD_VALUES = 10_000;
+const MAX_WILDCARD_VALUE_LENGTH = 2_000;
+
+/**
+ * `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: contents
+ .split(/\r?\n/)
+ .map((line) => line.split('#')[0].trim())
+ .filter((line) => line.length > 0),
+});
+
+const 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;
+ }
+
+ return value
+ .filter((entry): entry is boolean | number | string => ['boolean', 'number', 'string'].includes(typeof entry))
+ .map((entry) => String(entry).trim())
+ .filter((entry) => entry.length > 0);
+};
+
+/**
+ * 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[] = [];
+
+ const walk = (node: unknown, prefix: string): void => {
+ if (!isPlainObject(node)) {
+ return;
+ }
+
+ for (const [key, child] of Object.entries(node)) {
+ const name = prefix ? `${prefix}/${key}` : key;
+ const values = toValues(child);
+
+ if (values) {
+ wildcards.push({ name: name.trim(), values });
+ } else {
+ walk(child, name);
+ }
+ }
+ };
+
+ walk(value, '');
+
+ 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.
+ */
+export const wildcardsToNestedRecord = (wildcards: readonly ParsedWildcard[]): Record<string, unknown> => {
+ const root: Record<string, unknown> = {};
+ const names = new Set(wildcards.map((wildcard) => wildcard.name));
+
+ for (const wildcard of wildcards) {
+ if (getAncestorNames(wildcard.name).some((ancestor) => names.has(ancestor))) {
+ root[wildcard.name] = wildcard.values;
+ continue;
+ }
+
+ const segments = wildcard.name.split('/');
+ const leaf = segments.pop();
+
+ if (leaf === undefined) {
+ continue;
+ }
+
+ let node = root;
+
+ for (const segment of segments) {
+ node[segment] ??= {};
+ node = node[segment] as Record<string, unknown>;
+ }
+
+ node[leaf] = wildcard.values;
+ }
+
+ return root;
+};
+
+export type WildcardImportRejection = 'duplicate' | 'invalid' | 'noValues' | 'tooLong' | 'tooManyValues';
+
+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 }[]
+): WildcardImportEntry[] => {
+ const existingByName = new Map(existing.map((wildcard) => [wildcard.name, wildcard.id]));
+ const seen = new Set<string>();
+
+ const getRejection = (wildcard: ParsedWildcard): WildcardImportRejection | null => {
+ const nameError = getWildcardNameError(wildcard.name);
+
+ 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';
+ }
+ if (seen.has(wildcard.name)) {
+ return 'duplicate';
+ }
+ if (wildcard.values.length === 0) {
+ return 'noValues';
+ }
+ if (
+ wildcard.values.length > MAX_WILDCARD_VALUES ||
+ wildcard.values.some((value) => value.length > MAX_WILDCARD_VALUE_LENGTH)
+ ) {
+ return 'tooManyValues';
+ }
+
+ return null;
+ };
+
+ return parsed.map((wildcard) => {
+ const rejection = getRejection(wildcard);
+
+ seen.add(wildcard.name);
+
+ return {
+ conflictId: existingByName.get(wildcard.name) ?? null,
+ name: wildcard.name,
+ rejection,
+ values: wildcard.values,
+ };
+ });
+};
+
+/**
+ * `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}`;
+ const base = name.slice(0, MAX_WILDCARD_NAME_LENGTH - marker.length).replace(/[^A-Za-z0-9]+$/, '');
+ const candidate = `${base}${marker}`;
+
+ if (!taken.has(candidate)) {
+ return candidate;
+ }
+ }
+};
+
+export 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.
+ */
+export const getWildcardImportActions = (
+ entries: readonly WildcardImportEntry[],
+ resolutions: Readonly<Record<string, WildcardImportResolution>>,
+ existingNames: ReadonlySet<string>
+): WildcardImportAction[] => {
+ const taken = new Set(existingNames);
+ const actions: WildcardImportAction[] = [];
+
+ for (const entry of entries) {
+ if (entry.rejection) {
+ continue;
+ }
+
+ if (entry.conflictId === null) {
+ taken.add(entry.name);
+ actions.push({ name: entry.name, values: entry.values });
+ continue;
+ }
+
+ const resolution = resolutions[entry.name] ?? 'skip';
+
+ if (resolution === 'skip') {
+ continue;
+ }
+
+ if (resolution === 'replace') {
+ actions.push({ id: entry.conflictId, name: entry.name, values: entry.values });
+ continue;
+ }
+
+ const name = getAvailableWildcardName(entry.name, taken);
+
+ taken.add(name);
+ actions.push({ name, values: entry.values });
+ }
+
+ return actions;
+};
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.tsx
new file mode 100644
index 0000000000..3e650ec7c6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.browser.test.tsx
@@ -0,0 +1,135 @@
+import type { WildcardImportEntry } from '@features/generation/core/wildcardTransfer';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { WildcardImportDialog } from '@features/generation/ui/promptFields/WildcardImportDialog';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+let root: Root | null = null;
+let host: HTMLDivElement | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const entry = (overrides: Partial<WildcardImportEntry> & { name: string }): WildcardImportEntry => ({
+ conflictId: null,
+ rejection: null,
+ values: ['a'],
+ ...overrides,
+});
+
+const ENTRIES: WildcardImportEntry[] = [
+ entry({ name: 'fresh' }),
+ entry({ conflictId: 'w1', name: 'colours', values: ['red', 'green'] }),
+ entry({ conflictId: 'w2', name: 'moods' }),
+ entry({ name: 'bad name!', rejection: 'invalid' }),
+];
+
+const renderDialog = async (entries = ENTRIES) => {
+ const onConfirm = vi.fn(() => Promise.resolve());
+
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <WildcardImportDialog entries={entries} onCancel={vi.fn()} onConfirm={onConfirm} />
+ </ChakraProvider>
+ );
+ });
+
+ return onConfirm;
+};
+
+const dialog = () => document.querySelector('[role="alertdialog"]')!;
+const segmentGroups = () => [
+ ...dialog().querySelectorAll<HTMLElement>('[data-scope="segment-group"][data-part="root"]'),
+];
+const clickOption = async (group: HTMLElement, label: string) => {
+ const option = [...group.querySelectorAll<HTMLElement>('label')].find((item) => item.textContent?.includes(label));
+
+ await act(async () => {
+ await userEvent.click(option!);
+ });
+};
+const confirm = async () => {
+ const button = [...dialog().querySelectorAll('button')].find((item) => item.textContent?.includes('import'));
+
+ await act(async () => {
+ await userEvent.click(button!);
+ });
+};
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+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.
+ const [, colours] = segmentGroups();
+
+ await clickOption(colours, 'importReplace');
+ await confirm();
+
+ expect(onConfirm).toHaveBeenCalledWith({ colours: 'replace' });
+ });
+
+ it('applies one decision to every clash', async () => {
+ const onConfirm = await renderDialog();
+ const [all] = segmentGroups();
+
+ await clickOption(all, 'importKeepBoth');
+ await confirm();
+
+ expect(onConfirm).toHaveBeenCalledWith({ colours: 'keepBoth', moods: 'keepBoth' });
+ });
+
+ it('lets a row override the decision made for all of them', async () => {
+ const onConfirm = await renderDialog();
+ const [all, colours] = segmentGroups();
+
+ await clickOption(all, 'importReplace');
+ await clickOption(colours, 'importSkip');
+ await confirm();
+
+ expect(onConfirm).toHaveBeenCalledWith({ colours: 'skip', moods: 'replace' });
+ });
+
+ // A count that said "3 imported" while quietly dropping the fourth would be
+ // the worst version of this dialog.
+ it('names what it cannot import, and why', async () => {
+ await renderDialog();
+
+ 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/WildcardImportDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx
new file mode 100644
index 0000000000..4864ca195b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardImportDialog.tsx
@@ -0,0 +1,197 @@
+import type {
+ WildcardImportEntry,
+ WildcardImportRejection,
+ WildcardImportResolution,
+} from '@features/generation/core/wildcardTransfer';
+
+import { HStack, SegmentGroup, Stack, Text } from '@chakra-ui/react';
+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const RESOLUTIONS: WildcardImportResolution[] = ['skip', 'replace', 'keepBoth'];
+
+const RESOLUTION_LABEL_KEY: Record<WildcardImportResolution, string> = {
+ keepBoth: 'widgets.generate.dynamicPrompts.importKeepBoth',
+ replace: 'widgets.generate.dynamicPrompts.importReplace',
+ skip: 'widgets.generate.dynamicPrompts.importSkip',
+};
+
+const REJECTION_KEY: Record<WildcardImportRejection, string> = {
+ duplicate: 'widgets.generate.dynamicPrompts.importRejectedDuplicate',
+ invalid: 'widgets.generate.dynamicPrompts.importRejectedInvalid',
+ noValues: 'widgets.generate.dynamicPrompts.importRejectedNoValues',
+ tooLong: 'widgets.generate.dynamicPrompts.importRejectedTooLong',
+ tooManyValues: 'widgets.generate.dynamicPrompts.importRejectedTooManyValues',
+};
+
+/**
+ * What an import is about to do, one clashing name at a time.
+ *
+ * Import is the one action here that can overwrite a hand-typed list, so nothing
+ * is decided on the user's behalf: every clash defaults to being left alone, and
+ * anything the backend would refuse is listed with its reason rather than
+ * dropped behind a count that says everything worked.
+ */
+export const WildcardImportDialog = ({
+ entries,
+ onCancel,
+ onConfirm,
+}: {
+ entries: readonly WildcardImportEntry[];
+ onCancel: () => void;
+ onConfirm: (resolutions: Record<string, WildcardImportResolution>) => Promise<void>;
+}) => {
+ const { t } = useTranslation();
+ const [resolutions, setResolutions] = useState<Record<string, WildcardImportResolution>>({});
+
+ 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 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 setAllResolutions = useCallback(
+ (resolution: WildcardImportResolution) =>
+ setResolutions(Object.fromEntries(conflicts.map((entry) => [entry.name, resolution]))),
+ [conflicts]
+ );
+
+ const handleConfirm = useCallback(() => onConfirm(resolutions), [onConfirm, resolutions]);
+
+ // `ConfirmDialog` takes its body as a node. This one is rebuilt on every
+ // resolution change regardless, so memoizing it would save nothing.
+ // oxlint-disable-next-line react-perf/jsx-no-jsx-as-prop
+ const body = (
+ <Stack gap="3">
+ <Text color="fg.subtle" fontSize="xs">
+ {t('widgets.generate.dynamicPrompts.importSummary', { conflicts: conflicts.length, fresh: freshCount })}
+ </Text>
+
+ {conflicts.length > 0 ? (
+ <Stack gap="2">
+ <HStack justify="space-between">
+ <Text fontSize="xs" fontWeight="600">
+ {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}
+ </HStack>
+ <Scrollable maxH="12rem" label={t('widgets.generate.dynamicPrompts.importAlreadyExist')}>
+ <Stack gap="1" pr="1">
+ {conflicts.map((entry) => (
+ <ConflictRow
+ key={entry.name}
+ name={entry.name}
+ resolution={resolutions[entry.name] ?? 'skip'}
+ valueCount={entry.values.length}
+ onChange={setResolution}
+ />
+ ))}
+ </Stack>
+ </Scrollable>
+ </Stack>
+ ) : null}
+
+ {rejected.length > 0 ? (
+ <Stack gap="1">
+ <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>
+ ))}
+ </Stack>
+ ) : null}
+ </Stack>
+ );
+
+ return (
+ <ConfirmDialog
+ body={body}
+ confirmLabel={t('widgets.generate.dynamicPrompts.import')}
+ isDestructive={false}
+ isOpen
+ title={t('widgets.generate.dynamicPrompts.importWildcards')}
+ onClose={onCancel}
+ onConfirm={handleConfirm}
+ />
+ );
+};
+
+const ResolutionControl = ({
+ onChange,
+ value,
+}: {
+ onChange: (resolution: WildcardImportResolution) => void;
+ value?: WildcardImportResolution;
+}) => {
+ const { t } = useTranslation();
+ const handleValueChange = useCallback(
+ (event: { value: string | null }) => {
+ if (event.value) {
+ onChange(event.value as WildcardImportResolution);
+ }
+ },
+ [onChange]
+ );
+
+ return (
+ <SegmentGroup.Root size="xs" value={value ?? null} onValueChange={handleValueChange}>
+ <SegmentGroup.Indicator />
+ {RESOLUTIONS.map((resolution) => (
+ <SegmentGroup.Item key={resolution} value={resolution}>
+ <SegmentGroup.ItemHiddenInput />
+ <SegmentGroup.ItemText>{t(RESOLUTION_LABEL_KEY[resolution])}</SegmentGroup.ItemText>
+ </SegmentGroup.Item>
+ ))}
+ </SegmentGroup.Root>
+ );
+};
+
+const ConflictRow = ({
+ name,
+ onChange,
+ resolution,
+ valueCount,
+}: {
+ name: string;
+ resolution: WildcardImportResolution;
+ valueCount: number;
+ onChange: (name: string, resolution: WildcardImportResolution) => void;
+}) => {
+ const { t } = useTranslation();
+ const handleChange = useCallback((next: WildcardImportResolution) => onChange(name, next), [name, onChange]);
+
+ return (
+ <HStack gap="2" justify="space-between">
+ <Stack gap="0" minW="0">
+ <Text fontFamily="mono" fontSize="2xs" truncate>
+ __{name}__
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('widgets.generate.dynamicPrompts.importValueCount', { count: valueCount })}
+ </Text>
+ </Stack>
+ <ResolutionControl value={resolution} onChange={handleChange} />
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
new file mode 100644
index 0000000000..fa2d4b272d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardTransferActions.tsx
@@ -0,0 +1,188 @@
+import type { WildcardImportEntry, WildcardImportResolution } from '@features/generation/core/wildcardTransfer';
+import type { WildcardCatalog } from '@features/generation/ui/useWildcards';
+import type { WildcardExportFormat } from '@features/generation/ui/wildcardFiles';
+import type { ChangeEvent } from 'react';
+
+import { HStack, Menu, Portal } from '@chakra-ui/react';
+import { getWildcardImportActions, planWildcardImport } from '@features/generation/core/wildcardTransfer';
+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
+import { WildcardImportDialog } from '@features/generation/ui/promptFields/WildcardImportDialog';
+import {
+ downloadWildcards,
+ readWildcardFiles,
+ WILDCARD_IMPORT_ACCEPT,
+ WildcardFileError,
+} from '@features/generation/ui/wildcardFiles';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { Button } from '@platform/ui/Button';
+import { MenuContent } from '@platform/ui/Menu';
+import { DownloadIcon, UploadIcon } from 'lucide-react';
+import { useCallback, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const EXPORT_FORMATS: WildcardExportFormat[] = ['yaml', 'json'];
+
+/**
+ * Import and export for the whole catalog.
+ *
+ * Both directions are pure client work — wildcards are per-user CRUD, so an
+ * import is a run of ordinary creates and updates rather than a route of its
+ * own. Writes go one at a time and stop at the first failure, so a half-finished
+ * import says how far it got instead of reporting success over a silent error.
+ */
+export const WildcardTransferActions = ({ catalog }: { catalog: WildcardCatalog }) => {
+ const { t } = useTranslation();
+ const { notifications } = useGenerationUi();
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const [isBusy, setIsBusy] = useState(false);
+ const [pendingEntries, setPendingEntries] = useState<WildcardImportEntry[] | null>(null);
+
+ const reportError = useCallback(
+ (area: string, caught: unknown, fallback: string) =>
+ notifications.reportError({
+ area,
+ message: getApiErrorMessage(caught, fallback),
+ namespace: 'generation',
+ }),
+ [notifications]
+ );
+
+ const applyImport = useCallback(
+ async (entries: readonly WildcardImportEntry[], resolutions: Record<string, WildcardImportResolution>) => {
+ const actions = getWildcardImportActions(entries, resolutions, new Set(catalog.wildcards.map((w) => w.name)));
+ let done = 0;
+
+ setIsBusy(true);
+
+ try {
+ for (const action of actions) {
+ if (action.id === undefined) {
+ await catalog.create({ name: action.name, values: action.values });
+ } else {
+ await catalog.update(action.id, { name: action.name, values: action.values });
+ }
+ done++;
+ }
+
+ notifications.info(t('widgets.generate.dynamicPrompts.importedCount', { count: done }));
+ } catch (caught) {
+ reportError('import-wildcards', caught, t('widgets.generate.dynamicPrompts.couldNotImport'));
+ } finally {
+ setIsBusy(false);
+ setPendingEntries(null);
+ }
+ },
+ [catalog, notifications, reportError, t]
+ );
+
+ const startImport = useCallback(
+ async (files: readonly File[]) => {
+ setIsBusy(true);
+
+ try {
+ const entries = planWildcardImport(await readWildcardFiles(files), catalog.wildcards);
+
+ // Nothing to decide and nothing to explain — the file pick was the
+ // confirmation, so a dialog with only an Import button would be a click
+ // that tells the user what they already know.
+ if (entries.every((entry) => entry.rejection === null && entry.conflictId === null)) {
+ await applyImport(entries, {});
+ return;
+ }
+
+ setPendingEntries(entries);
+ } catch (caught) {
+ reportError(
+ 'import-wildcards',
+ caught,
+ caught instanceof WildcardFileError
+ ? t('widgets.generate.dynamicPrompts.couldNotReadFile', { name: caught.fileName })
+ : t('widgets.generate.dynamicPrompts.couldNotImport')
+ );
+ } finally {
+ setIsBusy(false);
+ }
+ },
+ [applyImport, catalog.wildcards, reportError, t]
+ );
+
+ const runExport = useCallback(
+ async (format: WildcardExportFormat) => {
+ try {
+ await downloadWildcards(catalog.wildcards, format);
+ } catch (caught) {
+ reportError('export-wildcards', caught, t('widgets.generate.dynamicPrompts.couldNotExport'));
+ }
+ },
+ [catalog.wildcards, reportError, t]
+ );
+
+ const pickFiles = useCallback(() => fileInputRef.current?.click(), []);
+
+ const handleFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const files = [...(event.currentTarget.files ?? [])];
+
+ if (files.length > 0) {
+ void startImport(files);
+ }
+
+ event.currentTarget.value = '';
+ },
+ [startImport]
+ );
+
+ const handleExportSelect = useCallback(
+ (details: { value: string }) => void runExport(details.value as WildcardExportFormat),
+ [runExport]
+ );
+
+ const cancelImport = useCallback(() => setPendingEntries(null), []);
+
+ const confirmImport = useCallback(
+ (resolutions: Record<string, WildcardImportResolution>) => applyImport(pendingEntries ?? [], resolutions),
+ [applyImport, pendingEntries]
+ );
+
+ return (
+ <HStack gap="0.5">
+ <Button disabled={isBusy} size="2xs" variant="ghost" onClick={pickFiles}>
+ <UploadIcon />
+ {t('widgets.generate.dynamicPrompts.import')}
+ </Button>
+ <Menu.Root onSelect={handleExportSelect}>
+ <Menu.Trigger asChild>
+ <Button disabled={isBusy || catalog.wildcards.length === 0} size="2xs" variant="ghost">
+ <DownloadIcon />
+ {t('widgets.generate.dynamicPrompts.export')}
+ </Button>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="10rem">
+ {EXPORT_FORMATS.map((format) => (
+ <Menu.Item key={format} value={format}>
+ <Menu.ItemText fontSize="xs">
+ {t(`widgets.generate.dynamicPrompts.exportAs${format === 'yaml' ? 'Yaml' : 'Json'}`)}
+ </Menu.ItemText>
+ </Menu.Item>
+ ))}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ {/* Multiple, because a wildcard folder is a file per wildcard. */}
+ <input
+ accept={WILDCARD_IMPORT_ACCEPT}
+ hidden
+ multiple
+ ref={fileInputRef}
+ type="file"
+ onChange={handleFileChange}
+ />
+ {pendingEntries ? (
+ <WildcardImportDialog entries={pendingEntries} onCancel={cancelImport} onConfirm={confirmImport} />
+ ) : null}
+ </HStack>
+ );
+};
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 fc635f36fc..aac004f1d6 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
@@ -222,11 +222,12 @@ describe('finding a wildcard', () => {
describe('deleting a wildcard', () => {
const clickDelete = async () => {
- // Insert, edit, delete — the trash is the last control on the row.
- const buttons = [...host!.querySelectorAll('button')];
+ // By label, not by position: the panel footer has its own controls after the
+ // rows, so "the last button" is no longer the trash.
+ const trash = host!.querySelector<HTMLButtonElement>('button[aria-label="common.delete"]');
await act(async () => {
- await userEvent.click(buttons.at(-1)!);
+ await userEvent.click(trash!);
});
};
const dialogButton = (label: string) =>
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 8875f727c4..6ccf9e530c 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx
@@ -9,6 +9,7 @@ import { filterWildcards, groupWildcardsByPrefix } from '@features/generation/co
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 { WildcardTransferActions } from '@features/generation/ui/promptFields/WildcardTransferActions';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton } from '@platform/ui/Button';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
@@ -249,6 +250,9 @@ export const WildcardsPanel = ({
)}
</Scrollable>
+ <Separator />
+ <WildcardTransferActions catalog={catalog} />
+
{/* 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
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
new file mode 100644
index 0000000000..db8e01f7e0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/wildcardFiles.ts
@@ -0,0 +1,105 @@
+/**
+ * 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 {
+ parseWildcardTextFile,
+ wildcardsFromNestedRecord,
+ wildcardsToNestedRecord,
+} from '@features/generation/core/wildcardTransfer';
+
+export type WildcardExportFormat = 'json' | 'yaml';
+
+export const WILDCARD_IMPORT_ACCEPT = '.txt,.yaml,.yml,.json,text/plain,application/json';
+
+/** Directory picking supplies a relative path; a plain pick only has a name. */
+const getFilePath = (file: File): string =>
+ (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
+
+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}`);
+ this.name = 'WildcardFileError';
+ }
+}
+
+/**
+ * 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`.
+ */
+export const readWildcardFiles = async (files: readonly File[]): Promise<ParsedWildcard[]> => {
+ const parsed: ParsedWildcard[] = [];
+
+ for (const file of files) {
+ const path = getFilePath(file);
+ const contents = await file.text();
+
+ if (hasExtension(path, '.yaml', '.yml')) {
+ const { parse } = await import('yaml');
+
+ try {
+ parsed.push(...wildcardsFromNestedRecord(parse(contents)));
+ } catch {
+ throw new WildcardFileError(file.name);
+ }
+ continue;
+ }
+
+ if (hasExtension(path, '.json')) {
+ try {
+ parsed.push(...wildcardsFromNestedRecord(JSON.parse(contents)));
+ } 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));
+ }
+
+ 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[],
+ format: WildcardExportFormat
+): Promise<void> => {
+ const nested = wildcardsToNestedRecord(wildcards);
+ const text = format === 'json' ? `${JSON.stringify(nested, null, 2)}\n` : (await import('yaml')).stringify(nested);
+ const blob = new Blob([text], { type: format === 'json' ? 'application/json' : 'text/yaml' });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+
+ anchor.href = url;
+ anchor.download = `wildcards.${format}`;
+ anchor.click();
+ URL.revokeObjectURL(url);
+};
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 2123da0b61..9b0632fd5e 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -46,6 +46,14 @@ export default defineConfig({
return 'ag-psd';
}
+ // Same story as ag-psd: `yaml` is reached only through a dynamic
+ // `import('yaml')` in wildcard import/export, and the catch-all below
+ // would otherwise make a parser nobody has asked for part of the
+ // initial load.
+ if (id.includes('/node_modules/yaml/')) {
+ return 'yaml';
+ }
+
if (id.includes('/node_modules/react-icons/')) {
return 'react-icons';
}