Skip to content

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

refactor(canvas): judge canvas generation inputs once for readiness and invoke (#10308)

Josh Corbettfa2889a26059
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 189a9f80b3..cf69cec1af 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,15 +2,15 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 825939,
+ "brotliBytes": 827521,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 824908,
+ "gzipBytes": 826297,
"imageRawBytes": 44398,
- "initialRawBytes": 2140669,
+ "initialRawBytes": 2143904,
"largestAssetRawBytes": 770754,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 116630,
+ "ownedRawBytes": 116635,
"requestCount": 34,
"scriptRequestCount": 18,
"sourceOwners": [
@@ -363,15 +363,15 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1297167,
+ "brotliBytes": 1302629,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1289769,
+ "gzipBytes": 1294831,
"imageRawBytes": 44398,
- "initialRawBytes": 3598707,
+ "initialRawBytes": 3611751,
"largestAssetRawBytes": 770754,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 174944,
+ "ownedRawBytes": 177699,
"requestCount": 70,
"scriptRequestCount": 54,
"sourceOwners": [
@@ -908,6 +908,7 @@
"source:src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts",
"source:src/workbench/canvas-engine/transform/transformMath.ts",
"source:src/workbench/canvasDimsSync.ts",
+ "source:src/workbench/canvasGenerationInputs.ts",
"source:src/workbench/canvasLayerContent.ts",
"source:src/workbench/canvasMigration.ts",
"source:src/workbench/canvasProjectMutations.ts",
@@ -1143,6 +1144,7 @@
"source:src/workbench/widgets/canvas/bboxGrid.ts",
"source:src/workbench/widgets/canvas/canvasSettings.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
+ "source:src/workbench/widgets/canvas/invoke/canvasInvocationFailure.ts",
"source:src/workbench/widgets/canvas/invoke/canvasScaling.ts",
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/manifest.ts",
@@ -1183,7 +1185,7 @@
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-11-16",
+ "capturedAt": "2026-11-19",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 00fbf3482d..9d8671d5a6 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1,6 +1,6 @@
{
"browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome",
- "capturedAt": "2026-11-16",
+ "capturedAt": "2026-11-19",
"routes": [
{
"activatedResourceBaseline": {
@@ -14,13 +14,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 117.5,
+ "domContentLoadedMedianMs": 131.5,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 117.59999999776483,
- "longestTaskMaxMs": 74,
+ "loadMedianMs": 131.5,
+ "longestTaskMaxMs": 87,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -30,13 +30,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 28,
- "scriptRawBytes": 1968136,
+ "scriptRawBytes": 1971379,
"scriptRequestCount": 24,
- "totalRawBytes": 2324138
+ "totalRawBytes": 2332599
},
- "routeReadyMedianMs": 241.90000000223517,
+ "routeReadyMedianMs": 270.59999999962747,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -52,13 +52,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 118.30000000074506,
+ "domContentLoadedMedianMs": 133.19999999925494,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 118.5,
- "longestTaskMaxMs": 79,
+ "loadMedianMs": 133.39999999850988,
+ "longestTaskMaxMs": 95,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -68,13 +68,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 28,
- "scriptRawBytes": 1968136,
+ "scriptRawBytes": 1971379,
"scriptRequestCount": 24,
- "totalRawBytes": 2324138
+ "totalRawBytes": 2332599
},
- "routeReadyMedianMs": 261.30000000074506,
+ "routeReadyMedianMs": 293.09999999962747,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -90,15 +90,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 118.39999999850988,
+ "domContentLoadedMedianMs": 129.40000000037253,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 118.39999999850988,
- "longestTaskMaxMs": 182,
+ "loadMedianMs": 129.59999999962747,
+ "longestTaskMaxMs": 221,
"owner": "workbench",
- "projectSwitchMedianMs": 37.70000000298023,
+ "projectSwitchMedianMs": 47.79999999888241,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -106,13 +106,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 84,
- "scriptRawBytes": 4699847,
+ "scriptRawBytes": 4732676,
"scriptRequestCount": 79,
- "totalRawBytes": 5100247
+ "totalRawBytes": 5138294
},
- "routeReadyMedianMs": 421.19999999925494,
+ "routeReadyMedianMs": 468.5,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -128,15 +128,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 115.69999999925494,
+ "domContentLoadedMedianMs": 129.7000000011176,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 115.80000000074506,
- "longestTaskMaxMs": 181,
+ "loadMedianMs": 129.80000000074506,
+ "longestTaskMaxMs": 221,
"owner": "workbench",
- "projectSwitchMedianMs": 46.899999998509884,
+ "projectSwitchMedianMs": 68.80000000074506,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -144,13 +144,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 84,
- "scriptRawBytes": 4699847,
+ "scriptRawBytes": 4732676,
"scriptRequestCount": 79,
- "totalRawBytes": 5100247
+ "totalRawBytes": 5138294
},
- "routeReadyMedianMs": 423.19999999925494,
+ "routeReadyMedianMs": 464.59999999962747,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -159,20 +159,20 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 347117,
+ "largestAssetRawBytes": 354198,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 613179,
+ "scriptRawBytes": 620754,
"scriptRequestCount": 7,
- "totalRawBytes": 613179
+ "totalRawBytes": 620754
},
- "domContentLoadedMedianMs": 117.5,
+ "domContentLoadedMedianMs": 133.89999999850988,
"id": "editor-canvas",
- "layoutAckMedianMs": 3.5,
- "layoutReturnSwitchMedianMs": 65.19999999925494,
- "layoutSwitchMedianMs": 88.59999999776483,
- "loadMedianMs": 117.59999999776483,
- "longestTaskMaxMs": 181,
+ "layoutAckMedianMs": 5,
+ "layoutReturnSwitchMedianMs": 59,
+ "layoutSwitchMedianMs": 99.20000000111759,
+ "loadMedianMs": 134,
+ "longestTaskMaxMs": 240,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -182,13 +182,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 91,
- "scriptRawBytes": 5302626,
+ "scriptRawBytes": 5353430,
"scriptRequestCount": 86,
- "totalRawBytes": 5703026
+ "totalRawBytes": 5759048
},
- "routeReadyMedianMs": 1158.2999999970198,
+ "routeReadyMedianMs": 1293.800000000745,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -197,20 +197,20 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 347117,
+ "largestAssetRawBytes": 354198,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 613179,
+ "scriptRawBytes": 620754,
"scriptRequestCount": 7,
- "totalRawBytes": 613179
+ "totalRawBytes": 620754
},
- "domContentLoadedMedianMs": 117.60000000149012,
+ "domContentLoadedMedianMs": 133.90000000037253,
"id": "editor-canvas",
- "layoutAckMedianMs": 4.099999997764826,
- "layoutReturnSwitchMedianMs": 60.30000000074506,
- "layoutSwitchMedianMs": 90.30000000074506,
- "loadMedianMs": 117.79999999701977,
- "longestTaskMaxMs": 209,
+ "layoutAckMedianMs": 5.5,
+ "layoutReturnSwitchMedianMs": 67.5,
+ "layoutSwitchMedianMs": 99,
+ "loadMedianMs": 134,
+ "longestTaskMaxMs": 279,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -220,13 +220,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 91,
- "scriptRawBytes": 5302626,
+ "scriptRawBytes": 5353430,
"scriptRequestCount": 86,
- "totalRawBytes": 5703026
+ "totalRawBytes": 5759048
},
- "routeReadyMedianMs": 1150.699999999255,
+ "routeReadyMedianMs": 1294.300000000745,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -235,20 +235,20 @@
"cssRawBytes": 15413,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 221160,
+ "largestAssetRawBytes": 221147,
"otherRawBytes": 0,
"requestCount": 6,
- "scriptRawBytes": 442652,
+ "scriptRawBytes": 442639,
"scriptRequestCount": 5,
- "totalRawBytes": 458065
+ "totalRawBytes": 458052
},
- "domContentLoadedMedianMs": 117.90000000223517,
+ "domContentLoadedMedianMs": 133.40000000037253,
"id": "editor-workflow",
- "layoutAckMedianMs": 3.699999999254942,
- "layoutReturnSwitchMedianMs": 39.30000000074506,
- "layoutSwitchMedianMs": 77.30000000074506,
- "loadMedianMs": 118,
- "longestTaskMaxMs": 177,
+ "layoutAckMedianMs": 5.099999999627471,
+ "layoutReturnSwitchMedianMs": 47.5,
+ "layoutSwitchMedianMs": 89.5,
+ "loadMedianMs": 133.5,
+ "longestTaskMaxMs": 229,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -258,13 +258,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 90,
- "scriptRawBytes": 5142499,
+ "scriptRawBytes": 5175315,
"scriptRequestCount": 84,
- "totalRawBytes": 5558312
+ "totalRawBytes": 5596346
},
- "routeReadyMedianMs": 1151.300000000745,
+ "routeReadyMedianMs": 1276.699999999255,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -273,20 +273,20 @@
"cssRawBytes": 15413,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 221160,
+ "largestAssetRawBytes": 221147,
"otherRawBytes": 0,
"requestCount": 6,
- "scriptRawBytes": 442652,
+ "scriptRawBytes": 442639,
"scriptRequestCount": 5,
- "totalRawBytes": 458065
+ "totalRawBytes": 458052
},
- "domContentLoadedMedianMs": 116.19999999925494,
+ "domContentLoadedMedianMs": 132.30000000074506,
"id": "editor-workflow",
- "layoutAckMedianMs": 3.900000002235174,
- "layoutReturnSwitchMedianMs": 49.099999997764826,
- "layoutSwitchMedianMs": 144.89999999850988,
- "loadMedianMs": 116.30000000074506,
- "longestTaskMaxMs": 281,
+ "layoutAckMedianMs": 5.800000000745058,
+ "layoutReturnSwitchMedianMs": 58.5,
+ "layoutSwitchMedianMs": 173,
+ "loadMedianMs": 132.40000000037253,
+ "longestTaskMaxMs": 388,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -296,13 +296,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 90,
- "scriptRawBytes": 5142499,
+ "scriptRawBytes": 5175315,
"scriptRequestCount": 84,
- "totalRawBytes": 5558312
+ "totalRawBytes": 5596346
},
- "routeReadyMedianMs": 1185.5,
+ "routeReadyMedianMs": 1363.5999999996275,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -318,13 +318,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 117.19999999925494,
+ "domContentLoadedMedianMs": 127.80000000074506,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 48.600000001490116,
- "loadMedianMs": 117.40000000223517,
- "longestTaskMaxMs": 176,
+ "layoutSwitchMedianMs": 54.20000000111759,
+ "loadMedianMs": 127.90000000037253,
+ "longestTaskMaxMs": 225,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -334,13 +334,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 84,
- "scriptRawBytes": 4699847,
+ "scriptRawBytes": 4732676,
"scriptRequestCount": 79,
- "totalRawBytes": 5100247
+ "totalRawBytes": 5138294
},
- "routeReadyMedianMs": 1400.199999999255,
+ "routeReadyMedianMs": 1494.300000000745,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -356,13 +356,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 117.39999999850988,
+ "domContentLoadedMedianMs": 127.5,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 58.399999998509884,
- "loadMedianMs": 117.39999999850988,
- "longestTaskMaxMs": 186,
+ "layoutSwitchMedianMs": 72,
+ "loadMedianMs": 127.59999999962747,
+ "longestTaskMaxMs": 221,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -372,13 +372,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 770754,
- "otherRawBytes": 330179,
+ "otherRawBytes": 335397,
"requestCount": 84,
- "scriptRawBytes": 4699847,
+ "scriptRawBytes": 4732676,
"scriptRequestCount": 79,
- "totalRawBytes": 5100247
+ "totalRawBytes": 5138294
},
- "routeReadyMedianMs": 1382.699999999255,
+ "routeReadyMedianMs": 1513.5,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1615,6 +1615,7 @@
"source:src/workbench/canvas-operations/selectObjectSession.ts",
"source:src/workbench/canvas-operations/toolMemory.ts",
"source:src/workbench/canvasDimsSync.ts",
+ "source:src/workbench/canvasGenerationInputs.ts",
"source:src/workbench/canvasLayerContent.ts",
"source:src/workbench/canvasMigration.ts",
"source:src/workbench/canvasProjectMutations.ts",
@@ -1873,6 +1874,7 @@
"source:src/workbench/widgets/canvas/bboxGrid.ts",
"source:src/workbench/widgets/canvas/canvasSettings.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
+ "source:src/workbench/widgets/canvas/invoke/canvasInvocationFailure.ts",
"source:src/workbench/widgets/canvas/invoke/canvasScaling.ts",
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/manifest.ts",
@@ -2799,6 +2801,7 @@
"source:src/workbench/canvas-operations/toolMemory.ts",
"source:src/workbench/canvas-operations/useCanvasEngine.ts",
"source:src/workbench/canvasDimsSync.ts",
+ "source:src/workbench/canvasGenerationInputs.ts",
"source:src/workbench/canvasLayerContent.ts",
"source:src/workbench/canvasMigration.ts",
"source:src/workbench/canvasProjectMutationPort.ts",
@@ -3106,6 +3109,7 @@
"source:src/workbench/widgets/canvas/gallerySaveToast.ts",
"source:src/workbench/widgets/canvas/implementation.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
+ "source:src/workbench/widgets/canvas/invoke/canvasInvocationFailure.ts",
"source:src/workbench/widgets/canvas/invoke/canvasScaling.ts",
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts",
@@ -4206,6 +4210,7 @@
"source:src/workbench/canvas-operations/selectObjectSession.ts",
"source:src/workbench/canvas-operations/toolMemory.ts",
"source:src/workbench/canvasDimsSync.ts",
+ "source:src/workbench/canvasGenerationInputs.ts",
"source:src/workbench/canvasLayerContent.ts",
"source:src/workbench/canvasMigration.ts",
"source:src/workbench/canvasProjectMutations.ts",
@@ -4464,6 +4469,7 @@
"source:src/workbench/widgets/canvas/bboxGrid.ts",
"source:src/workbench/widgets/canvas/canvasSettings.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
+ "source:src/workbench/widgets/canvas/invoke/canvasInvocationFailure.ts",
"source:src/workbench/widgets/canvas/invoke/canvasScaling.ts",
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/manifest.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index ba01e4092e..001a556b14 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4591,6 +4591,22 @@
"success_other": "Added {{count}} images as canvas layers",
"controlFilled": "Filled {{name}}"
},
+ "invoke": {
+ "adjustmentRefused": {
+ "error": "Clarity, Texture or Dehaze failed on “{{name}}”. Change a setting or disable them, then invoke again.",
+ "overBudget": "Not enough canvas memory to apply Clarity, Texture or Dehaze to “{{name}}”. Delete layers you no longer need, then invoke again.",
+ "tooLarge": "Clarity, Texture and Dehaze can’t run on “{{name}}”: its content is larger than 16.8 megapixels (4096 × 4096 px). Disable or remove them, or crop the content, then invoke again."
+ },
+ "captureFailed": "The canvas could not be captured for generation ({{status}}).",
+ "failed": "Canvas generation failed",
+ "noDocument": "The canvas has no active document to generate from.",
+ "noModel": "Select a supported model before invoking the canvas.",
+ "notOpen": "Open the canvas before invoking it.",
+ "notReady": "Some layers are still loading. Wait a moment, then invoke again.",
+ "overBudget": "Generation exceeds the browser’s canvas-memory limit. Try again after layers finish loading. If it still fails, crop or resize large source images, or disable unnecessary layers. A smaller generation frame alone may not help.",
+ "stale": "The canvas changed while generation was being prepared. Please invoke again.",
+ "unreadable": "“{{name}}” could not be read (its image may have been deleted or damaged). Disable or delete that layer, then invoke again."
+ },
"nextStagedCandidate": "Next staged candidate",
"previousStagedCandidate": "Previous staged candidate",
"selectStagedCandidate": "Select staged candidate {{number}}",
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index 46c6dc0755..0325536559 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -88,6 +88,7 @@
"autoRoutePolicy.ts": "workbench",
"bootWidgetPreload.ts": "workbench",
"canvasDimsSync.ts": "workbench",
+ "canvasGenerationInputs.ts": "workbench",
"canvasLayerContent.ts": "workbench",
"canvasLoadContracts.ts": "workbench",
"canvasMigration.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index ae41acb88a..2d7545f8e2 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -158,7 +158,7 @@ const addIPAdapterReferenceImages = (
return collector;
};
-const FLUX_REDUX_INFLUENCE = {
+export const FLUX_REDUX_INFLUENCE = {
lowest: { downsampling_factor: 5, weight: 1 },
low: { downsampling_factor: 4, weight: 1 },
medium: { downsampling_factor: 3, weight: 1 },
diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.ts
index 6011d8fc80..7643f9a3f0 100644
--- a/invokeai/frontend/webv2/src/features/generation/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts
@@ -3,6 +3,7 @@ export {
addLoraCollectionLoader,
addTransformerLoraCollectionLoader,
compileGenerateGraph,
+ FLUX_REDUX_INFLUENCE,
resolveGenerateSeed,
} from './core/graph';
export {
diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts
index 9ba6e34a52..ec49531343 100644
--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts
@@ -42,7 +42,7 @@ const owner = { signal: new AbortController().signal } as AccountScope;
const createArgs = (state = createInitialWorkbenchState()) => {
return {
commands: {} as WorkbenchCommands,
- formatControlLayerError: ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`,
+ formatCanvasInvocationFailure: () => ({ message: 'canvas failure', title: 'canvas failure' }),
formatUpscaleMetadataFailure: (name: string) => name,
getModels: () => undefined,
queries: {
@@ -329,7 +329,7 @@ describe('active invocation submission', () => {
* former submission path and hold for this one.
*/
describe('active invocation submission for a graph preview’s source', () => {
- const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;
+ const formatCanvasInvocationFailure = () => ({ message: 'canvas failure', title: 'canvas failure' });
const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };
const animaVae: VaeModelConfig = { base: 'qwen-image', key: 'anima-vae', name: 'Anima VAE', type: 'vae' };
const qwen3Encoder: ComponentModelConfig = {
@@ -383,7 +383,7 @@ describe('active invocation submission for a graph preview’s source', () => {
await submitActiveInvocation(
{
commands: store.commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure: (name: string) => name,
getModels: () => undefined,
onStarted,
diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts
index 1384c81274..631d95fed1 100644
--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts
+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts
@@ -21,8 +21,7 @@ import { submitResolvedInvocation } from './invocationSubmit';
export interface ActiveInvocationSubmissionArgs {
commands: WorkbenchCommands;
destinationOverride?: ResultDestination;
- /** Words a control-layer rejection from the locale; its error message is for logs only. */
- formatControlLayerError: PrepareCanvasInvocationArgs['formatControlLayerError'];
+ formatCanvasInvocationFailure: PrepareCanvasInvocationArgs['formatCanvasInvocationFailure'];
formatUpscaleMetadataFailure: SubmitResolvedInvocationDeps['formatUpscaleMetadataFailure'];
getModels: () => readonly ModelConfig[] | undefined;
/** Invoke Front: the backend runs this batch ahead of the user's other pending work. */
@@ -75,7 +74,7 @@ export const submitActiveInvocation = async (
{
commands,
destinationOverride,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
getModels,
prepend,
@@ -120,7 +119,7 @@ export const submitActiveInvocation = async (
activeRuntime.assertCurrent(owner);
await activeRuntime.submit({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
models,
owner,
diff --git a/invokeai/frontend/webv2/src/workbench/canvasGenerationInputs.test.ts b/invokeai/frontend/webv2/src/workbench/canvasGenerationInputs.test.ts
new file mode 100644
index 0000000000..c8fb166530
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvasGenerationInputs.test.ts
@@ -0,0 +1,423 @@
+import type { GenerateModelConfig, MainModelConfig } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+import type {
+ CanvasControlLayerContract,
+ CanvasLayerContract,
+ CanvasRegionalGuidanceLayerContract,
+ RegionalGuidanceReferenceImage,
+ RegionalGuidanceReferenceImageAsset,
+} from '@workbench/canvas-engine/contracts';
+
+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { createInstance } from 'i18next';
+import { describe, expect, it } from 'vitest';
+
+import {
+ createCanvasInputJudge,
+ describeCanvasInputIssue,
+ getCanvasInputIssues,
+ type CanvasInputJudgeParams,
+} from './canvasGenerationInputs';
+
+const model = (key: string, base: string, type: string): ModelConfig => ({ base, key, name: key, type }) as ModelConfig;
+const main = (base: string, variant?: string): MainModelConfig => ({
+ base,
+ key: `${base}-main`,
+ name: `${base} main`,
+ type: 'main',
+ ...(variant ? { variant } : {}),
+});
+const hostedModel: GenerateModelConfig = {
+ base: 'external',
+ capabilities: { modes: ['txt2img'] },
+ format: 'external_api',
+ key: 'hosted',
+ name: 'OpenAI Image',
+ provider_id: 'openai',
+ type: 'external_image_generator',
+};
+
+const controlLayer = (
+ id: string,
+ overrides: {
+ isEnabled?: boolean;
+ kind?: CanvasControlLayerContract['adapter']['kind'];
+ model?: string | null;
+ source?: CanvasControlLayerContract['source'];
+ weight?: number;
+ derivation?: Pick<CanvasControlLayerContract, 'controlType' | 'detection' | 'filter' | 'original'>;
+ } = {}
+): CanvasControlLayerContract => ({
+ ...overrides.derivation,
+ adapter: {
+ beginEndStepPct: [0, 1],
+ controlMode: null,
+ kind: overrides.kind ?? 'controlnet',
+ model: overrides.model ?? null,
+ weight: overrides.weight ?? 1,
+ },
+ blendMode: 'normal',
+ id,
+ isEnabled: overrides.isEnabled ?? true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: overrides.source ?? { image: { height: 64, imageName: `${id}.png`, width: 64 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'control',
+ withTransparencyEffect: true,
+});
+
+const region = (
+ id: string,
+ overrides: Partial<CanvasRegionalGuidanceLayerContract> = {}
+): CanvasRegionalGuidanceLayerContract => ({
+ autoNegative: false,
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ mask: { bitmap: { height: 64, imageName: `${id}.png`, width: 64 }, fill: { color: '#00ff00', style: 'solid' } },
+ name: id,
+ negativePrompt: null,
+ opacity: 1,
+ positivePrompt: 'a red hat',
+ referenceImages: [],
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'regional_guidance',
+ ...overrides,
+});
+
+const judgeParams = (
+ mainModel: GenerateModelConfig,
+ models: readonly ModelConfig[] | undefined,
+ controlModelMemory: Record<string, string> = {}
+): CanvasInputJudgeParams => ({ cfgScale: 7, controlModelMemory, model: mainModel, models });
+
+const readinessIssues = (
+ layers: CanvasLayerContract[],
+ params: CanvasInputJudgeParams,
+ options: { prompt?: string; rasterInFrame?: boolean } = {}
+) =>
+ getCanvasInputIssues({
+ ...params,
+ layers,
+ prompt: options.prompt ?? 'a prompt',
+ rasterInFrame: options.rasterInFrame ?? false,
+ regionalLayersInFrame: layers.filter(
+ (layer): layer is CanvasRegionalGuidanceLayerContract => layer.type === 'regional_guidance'
+ ),
+ });
+
+const invocationVerdicts = (layers: CanvasLayerContract[], params: CanvasInputJudgeParams) => {
+ const judge = createCanvasInputJudge(params);
+ return layers.map((layer) =>
+ layer.type === 'control' ? judge.control(layer) : judge.regional(layer as CanvasRegionalGuidanceLayerContract)
+ );
+};
+
+const englishCatalogModules = import.meta.glob('../../public/locales/en.json', { eager: true, import: 'default' });
+const english = createInstance();
+await english.init({
+ initAsync: false,
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: Object.values(englishCatalogModules)[0] as Record<string, unknown> } },
+});
+const t = english.t.bind(english) as (key: string, options?: Record<string, unknown>) => string;
+
+seedArchitectureCapabilities();
+
+describe('readiness and the invocation judge layers alike', () => {
+ it('refuse every compositable control and regional layer of a hosted model, by name and in layer order', () => {
+ const layers = [controlLayer('Canny guide'), region('Hat region'), controlLayer('off', { isEnabled: false })];
+ const refusals = [
+ {
+ kind: 'hosted_refusal',
+ modelName: 'OpenAI Image',
+ refusal: { kind: 'control_layer', layerName: 'Canny guide' },
+ },
+ {
+ kind: 'hosted_refusal',
+ modelName: 'OpenAI Image',
+ refusal: { kind: 'regional_guidance', layerName: 'Hat region' },
+ },
+ ];
+
+ for (const models of [undefined, []]) {
+ const params = judgeParams(hostedModel, models);
+ expect(readinessIssues(layers, params)).toEqual(refusals);
+ expect(invocationVerdicts(layers.slice(0, 2), params)).toEqual(
+ refusals.map((issue) => ({ issue, status: 'blocked' }))
+ );
+ }
+ expect(
+ readinessIssues(layers, judgeParams(hostedModel, [])).map((issue) => describeCanvasInputIssue(t, issue))
+ ).toEqual([
+ 'OpenAI Image does not support control layer "Canny guide". Disable it to generate.',
+ 'OpenAI Image does not support regional guidance layer "Hat region". Disable it to generate.',
+ ]);
+ });
+
+ it('let the first Control LoRA through and block the second, counting only layers that passed', () => {
+ const lora = model('flux-lora', 'flux', 'control_lora');
+ const layers = [
+ controlLayer('invalid', { kind: 'control_lora', model: 'sdxl-lora' }),
+ controlLayer('first', { kind: 'control_lora', model: 'flux-lora' }),
+ controlLayer('second', { kind: 'control_lora', model: 'flux-lora' }),
+ ];
+ const params = judgeParams(main('flux'), [lora, model('sdxl-lora', 'sdxl', 'control_lora')]);
+ const blocked = { code: 'control_lora_limit', kind: 'control_layer', layerId: 'second', layerName: 'second' };
+
+ expect(readinessIssues(layers, params)).toEqual([
+ { code: 'incompatible_base', kind: 'control_layer', layerId: 'invalid', layerName: 'invalid' },
+ blocked,
+ ]);
+ expect(invocationVerdicts(layers, params).map((verdict) => verdict.status)).toEqual([
+ 'blocked',
+ 'contributes',
+ 'blocked',
+ ]);
+ expect(invocationVerdicts(layers, params)[2]).toEqual({ issue: blocked, status: 'blocked' });
+ });
+
+ it('leave out a region a layout base cannot place, without blocking', () => {
+ const layers = [region('uncaptioned', { positivePrompt: null }), region('sign', { positivePrompt: 'a shop sign' })];
+ const params = judgeParams(main('moss-image'), []);
+
+ expect(readinessIssues(layers, params)).toEqual([]);
+ expect(invocationVerdicts(layers, params)).toEqual([
+ { status: 'skipped' },
+ {
+ input: {
+ autoNegative: false,
+ id: 'sign',
+ negativePrompt: null,
+ positivePrompt: 'a shop sign',
+ referenceImages: [],
+ },
+ status: 'contributes',
+ },
+ ]);
+ expect(readinessIssues(layers, params, { prompt: ' ' })).toEqual([
+ {
+ kind: 'layout_prompt',
+ message:
+ 'MOSS-Image needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.',
+ },
+ ]);
+ });
+
+ it('differ only while models load: readiness waits, the invocation refuses', () => {
+ const layers = [controlLayer('sketch', { derivation: { controlType: 'depth', detection: null } })];
+ const params = judgeParams(main('sdxl'), undefined);
+
+ expect(readinessIssues(layers, params)).toEqual([]);
+ expect(invocationVerdicts(layers, params)).toEqual([
+ {
+ issue: { code: 'models_unavailable', kind: 'control_layer', layerId: 'sketch', layerName: 'sketch' },
+ status: 'awaiting_models',
+ },
+ ]);
+ });
+});
+
+describe('getCanvasInputIssues', () => {
+ const sdxl = main('sdxl');
+ const models = [model('sdxl-control', 'sdxl', 'controlnet')];
+ const controlIssues = (
+ layers: CanvasLayerContract[],
+ mainModel: GenerateModelConfig,
+ installed: readonly ModelConfig[],
+ controlModelMemory?: Record<string, string>
+ ) => readinessIssues(layers, judgeParams(mainModel, installed, controlModelMemory));
+ const codes = (issues: ReturnType<typeof controlIssues>) =>
+ issues.map((issue) => (issue.kind === 'control_layer' ? [issue.layerId, issue.code] : issue));
+
+ it('names raster content in the frame first for a text-only hosted model', () => {
+ const editing: GenerateModelConfig = { ...hostedModel, capabilities: { modes: ['txt2img', 'img2img'] } };
+
+ expect(readinessIssues([controlLayer('guide')], judgeParams(hostedModel, []), { rasterInFrame: true })).toEqual([
+ { kind: 'hosted_refusal', modelName: 'OpenAI Image', refusal: { kind: 'raster_content' } },
+ { kind: 'hosted_refusal', modelName: 'OpenAI Image', refusal: { kind: 'control_layer', layerName: 'guide' } },
+ ]);
+ expect(readinessIssues([], judgeParams(editing, []), { rasterInFrame: true })).toEqual([]);
+ });
+
+ it('blocks an untyped layer whose model is no longer installed', () => {
+ expect(codes(controlIssues([controlLayer('legacy', { model: 'uninstalled' })], sdxl, models))).toEqual([
+ ['legacy', 'missing_model'],
+ ]);
+ });
+
+ it('reports a typed content-bearing layer no model resolves', () => {
+ const pose = controlLayer('pose', { derivation: { controlType: 'pose', detection: null } });
+ expect(codes(controlIssues([pose], sdxl, models))).toEqual([['pose', 'no_model_for_type']]);
+ });
+
+ it('skips disabled, content-less, and non-control layers', () => {
+ expect(
+ controlIssues(
+ [
+ controlLayer('disabled', { isEnabled: false, model: 'uninstalled' }),
+ controlLayer('empty', { model: 'uninstalled', source: { bitmap: null, type: 'paint' } }),
+ region('masked', { isEnabled: false }),
+ ],
+ sdxl,
+ models
+ )
+ ).toEqual([]);
+ });
+
+ it('reports Anima LLLite layers the denoiser would refuse, and only those', () => {
+ const animaModels = [
+ { ...model('sketch', 'anima', 'controlnet'), cond_in_channels: 3 },
+ { ...model('depth', 'anima', 'controlnet'), cond_in_channels: 3 },
+ { ...model('inpaint', 'anima', 'controlnet'), cond_in_channels: 4 },
+ ];
+ const lllite = (id: string, key: string) => controlLayer(id, { kind: 'anima_lllite', model: key });
+
+ expect(
+ codes(
+ controlIssues(
+ [
+ lllite('sketch', 'sketch'),
+ lllite('depth', 'depth'),
+ lllite('again', 'sketch'),
+ lllite('inpaint', 'inpaint'),
+ controlLayer('saved-as-controlnet', { model: 'depth' }),
+ ],
+ main('anima'),
+ animaModels
+ )
+ )
+ ).toEqual([
+ ['again', 'duplicate_lllite_model'],
+ ['inpaint', 'lllite_inpaint_adapter'],
+ ['saved-as-controlnet', 'switch_adapter_kind'],
+ ]);
+ });
+
+ it.each([
+ [
+ 'Qwen-Image',
+ 'qwen-image',
+ 'qwen_image_control',
+ 0.85,
+ 'qwen_image_control_limit',
+ 'edit',
+ 'qwen_image_edit_control',
+ ],
+ ['FLUX.2', 'flux2', 'flux2_control', 0.75, 'flux2_control_limit', 'klein_9b', 'flux2_klein_control'],
+ ] as const)('lets one %s control through, and none on a model that cannot run it', (...args) => {
+ const [, base, kind, weight, limitCode, refusingVariant, refusalCode] = args;
+ const union = [model(`${base}-union`, base, 'controlnet')];
+ const layers = ['first', 'second'].map((id) => controlLayer(id, { kind, model: `${base}-union`, weight }));
+
+ expect(codes(controlIssues(layers, main(base, base === 'flux2' ? 'dev' : undefined), union))).toEqual([
+ ['second', limitCode],
+ ]);
+ expect(codes(controlIssues(layers, main(base, refusingVariant), union))).toEqual([
+ ['first', refusalCode],
+ ['second', refusalCode],
+ ]);
+ });
+
+ describe('typed control layers', () => {
+ const depthModels = [model('sdxl-depth-a', 'sdxl', 'controlnet'), model('sdxl-depth-b', 'sdxl', 'controlnet')];
+ const typed = (id: string, detection: CanvasControlLayerContract['detection'] = null) =>
+ controlLayer(id, { derivation: { controlType: 'depth', detection } });
+
+ it('asks for a model when several fit, and resolves with the remembered pick', () => {
+ expect(codes(controlIssues([typed('depth')], sdxl, depthModels))).toEqual([['depth', 'choose_model']]);
+ expect(controlIssues([typed('depth')], sdxl, depthModels, { 'sdxl:depth': 'sdxl-depth-b' })).toEqual([]);
+ });
+
+ it('blocks on a map detection has not caught up with, after the model reasons', () => {
+ const pending = typed('pending', { settings: {}, type: 'depth_anything_depth_estimation' });
+
+ expect(codes(controlIssues([pending], sdxl, [depthModels[0]!]))).toEqual([['pending', 'detection_pending']]);
+ expect(codes(controlIssues([pending], sdxl, depthModels))).toEqual([['pending', 'choose_model']]);
+ });
+ });
+});
+
+describe('createCanvasInputJudge', () => {
+ it('hands a contributing control layer its adapter values and the model it resolves to', () => {
+ const depth = { ...model('sdxl-depth', 'sdxl', 'controlnet'), hash: 'blake3:depth' };
+ const layer = controlLayer('depth', { derivation: { controlType: 'depth', detection: null }, weight: 0.6 });
+
+ expect(createCanvasInputJudge(judgeParams(main('sdxl'), [depth])).control(layer)).toEqual({
+ input: {
+ beginEndStepPct: [0, 1],
+ controlMode: null,
+ id: 'depth',
+ instantxControlMode: null,
+ kind: 'controlnet',
+ model: { base: 'sdxl', hash: 'blake3:depth', key: 'sdxl-depth', name: 'sdxl-depth', type: 'controlnet' },
+ modelCondInChannels: undefined,
+ modelControlArchitecture: undefined,
+ weight: 0.6,
+ },
+ status: 'contributes',
+ });
+ });
+
+ describe('regional reference images', () => {
+ const asset = { imageName: 'ref.png' } as RegionalGuidanceReferenceImageAsset;
+ const ipAdapterModel = { base: 'sd-1', key: 'ipa', name: 'IP Adapter', type: 'ip_adapter' };
+ const fluxReduxModel = { base: 'flux', key: 'redux', name: 'FLUX Redux', type: 'flux_redux' };
+ const ipAdapterRef = (image: RegionalGuidanceReferenceImageAsset | null): RegionalGuidanceReferenceImage => ({
+ config: {
+ beginEndStepPct: [0, 1],
+ clipVisionModel: 'ViT-H',
+ image,
+ method: 'full',
+ model: ipAdapterModel,
+ type: 'ip_adapter',
+ weight: 1,
+ },
+ id: 'ref-ipa',
+ isEnabled: true,
+ });
+ const fluxReduxRef = (image: RegionalGuidanceReferenceImageAsset | null): RegionalGuidanceReferenceImage => ({
+ config: { image, imageInfluence: 'highest', model: fluxReduxModel, type: 'flux_redux' },
+ id: 'ref-redux',
+ isEnabled: true,
+ });
+ const withModelBase = (base: string): RegionalGuidanceReferenceImage => {
+ const ref = ipAdapterRef(asset);
+ return { ...ref, config: { ...ref.config, model: { ...ipAdapterModel, base } } };
+ };
+
+ it.each<[string, RegionalGuidanceReferenceImage, string, Record<string, unknown>[]]>([
+ ['drops an IP-Adapter ref with no image assigned', ipAdapterRef(null), 'sd-1', []],
+ [
+ 'keeps an IP-Adapter ref once an image is assigned for a supported SD base',
+ ipAdapterRef(asset),
+ 'sd-1',
+ [{ id: 'ref-ipa', imageName: 'ref.png', type: 'ip_adapter' }],
+ ],
+ ['drops regional reference images for FLUX.2', ipAdapterRef(asset), 'flux2', []],
+ ['drops regional reference images for krea-2', withModelBase('krea-2'), 'krea-2', []],
+ ['drops regional reference images for z-image', withModelBase('z-image'), 'z-image', []],
+ ['drops regional reference images for anima', withModelBase('anima'), 'anima', []],
+ ['keeps an SD2 IP-Adapter ref whose model matches the base', withModelBase('sd-2'), 'sd-2', [{ id: 'ref-ipa' }]],
+ ['drops a FLUX Redux ref with no image assigned', fluxReduxRef(null), 'flux', []],
+ [
+ 'sends a FLUX Redux ref its influence as redux settings once an image is assigned',
+ fluxReduxRef(asset),
+ 'flux',
+ [{ id: 'ref-redux', settings: { downsampling_factor: 1, weight: 1 }, type: 'flux_redux' }],
+ ],
+ ['drops a disabled ref even when an image is assigned', { ...ipAdapterRef(asset), isEnabled: false }, 'sd-1', []],
+ ])('%s', (_, ref, base, expected) => {
+ const verdict = createCanvasInputJudge(judgeParams(main(base), [])).regional(
+ region('r', { referenceImages: [ref] })
+ );
+ expect(verdict.status === 'contributes' ? verdict.input.referenceImages : []).toEqual(
+ expected.map((input) => expect.objectContaining(input))
+ );
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasGenerationInputs.ts b/invokeai/frontend/webv2/src/workbench/canvasGenerationInputs.ts
new file mode 100644
index 0000000000..64b008a318
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvasGenerationInputs.ts
@@ -0,0 +1,258 @@
+import type { GenerateModelConfig } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+import type {
+ CanvasControlLayerContract,
+ CanvasLayerContract,
+ CanvasRegionalGuidanceLayerContract,
+} from '@workbench/canvas-engine/api';
+
+import {
+ FLUX_REDUX_INFLUENCE,
+ getLayoutPromptRejectionReason,
+ getRegionalGuidanceRejectionReason,
+ getRegionalGuidanceSupport,
+ type ControlLayerGraphInput,
+ type RegionalGuidanceInput,
+ type RegionalReferenceImageInput,
+} from '@features/generation/graph';
+import { describeExternalCanvasRefusal, isExternalTextOnlyCanvasModel } from '@features/generation/settings';
+import { isCompositableControlLayer, isCompositableRegionalGuidanceLayer } from '@workbench/canvasLayerContent';
+
+import type { ControlModelMemory } from './controlModelResolution';
+
+import {
+ createControlLayerCheckContext,
+ createControlLayerSequence,
+ describeControlLayerIssue,
+ type ControlLayerIssue,
+} from './controlLayerChecks';
+
+export type HostedCanvasRefusal = Parameters<typeof describeExternalCanvasRefusal>[1];
+
+export type CanvasInputIssue =
+ | ({ kind: 'control_layer' } & ControlLayerIssue)
+ | { kind: 'hosted_refusal'; modelName: string; refusal: HostedCanvasRefusal }
+ | { kind: 'layout_prompt'; message: string };
+
+export type ControlLayerVerdict =
+ | { status: 'blocked'; issue: CanvasInputIssue }
+ /** Readiness waits for the model list; an invocation refuses. */
+ | { status: 'awaiting_models'; issue: CanvasInputIssue }
+ | { status: 'skipped' }
+ | { status: 'contributes'; input: Omit<ControlLayerGraphInput, 'imageName'> };
+
+export type RegionalLayerVerdict =
+ | { status: 'blocked'; issue: CanvasInputIssue }
+ | { status: 'skipped' }
+ | { status: 'contributes'; input: Omit<RegionalGuidanceInput, 'maskImageName' | 'maskBounds'> };
+
+export interface CanvasInputJudgeParams {
+ model: GenerateModelConfig;
+ models: readonly ModelConfig[] | undefined;
+ controlModelMemory: ControlModelMemory;
+ cfgScale: number;
+}
+
+/** Call `control` in generation order on one judge per invocation: per-generation limits count passed layers. */
+export interface CanvasInputJudge {
+ control(layer: CanvasControlLayerContract): ControlLayerVerdict;
+ regional(layer: CanvasRegionalGuidanceLayerContract): RegionalLayerVerdict;
+}
+
+/** Unlike Generation's `toModelIdentifier`: these graph inputs carry no `submodel_type`. */
+const toModelReference = (model: { base: string; key: string; name: string; type: string; hash?: unknown }) => ({
+ base: model.base,
+ key: model.key,
+ name: model.name,
+ type: model.type,
+ ...(typeof model.hash === 'string' ? { hash: model.hash } : {}),
+});
+
+const resolveRegionalReferenceImages = (
+ region: CanvasRegionalGuidanceLayerContract,
+ base: string
+): RegionalReferenceImageInput[] => {
+ const inputs: RegionalReferenceImageInput[] = [];
+ const kind = getRegionalGuidanceSupport(base)?.referenceImages ?? null;
+ for (const ref of region.referenceImages) {
+ if (!ref.isEnabled) {
+ continue;
+ }
+ const { config } = ref;
+ if (config.type === 'ip_adapter' && kind === 'ip_adapter') {
+ if (!config.image || !config.model || config.model.base !== base) {
+ continue;
+ }
+ inputs.push({
+ beginEndStepPct: config.beginEndStepPct,
+ clipVisionModel: config.clipVisionModel,
+ id: ref.id,
+ imageName: config.image.imageName,
+ method: config.method,
+ model: toModelReference(config.model),
+ type: 'ip_adapter',
+ weight: config.weight,
+ });
+ } else if (config.type === 'flux_redux' && kind === 'flux_redux') {
+ if (!config.image || !config.model || config.model.base !== base) {
+ continue;
+ }
+ inputs.push({
+ id: ref.id,
+ imageName: config.image.imageName,
+ model: toModelReference(config.model),
+ settings: FLUX_REDUX_INFLUENCE[config.imageInfluence],
+ type: 'flux_redux',
+ });
+ }
+ }
+ return inputs;
+};
+
+export const createCanvasInputJudge = ({
+ cfgScale,
+ controlModelMemory,
+ model,
+ models,
+}: CanvasInputJudgeParams): CanvasInputJudge => {
+ const isHosted = model.type === 'external_image_generator';
+ const judgeControl = models
+ ? createControlLayerSequence(model, models, createControlLayerCheckContext(model.base, controlModelMemory))
+ : null;
+ const controlIssue = (layer: CanvasControlLayerContract, code: ControlLayerIssue['code']): CanvasInputIssue => ({
+ code,
+ kind: 'control_layer',
+ layerId: layer.id,
+ layerName: layer.name,
+ });
+
+ return {
+ control: (layer) => {
+ if (isHosted) {
+ return {
+ issue: {
+ kind: 'hosted_refusal',
+ modelName: model.name,
+ refusal: { kind: 'control_layer', layerName: layer.name },
+ },
+ status: 'blocked',
+ };
+ }
+ if (!judgeControl) {
+ return { issue: controlIssue(layer, 'models_unavailable'), status: 'awaiting_models' };
+ }
+ const { reason, resolution, skip } = judgeControl(layer);
+ if (skip) {
+ return { status: 'skipped' };
+ }
+ const resolved = resolution.model;
+ if (reason || !resolved) {
+ return { issue: controlIssue(layer, reason ?? 'missing_model'), status: 'blocked' };
+ }
+ const { adapter } = layer;
+ return {
+ input: {
+ beginEndStepPct: adapter.beginEndStepPct,
+ controlMode: adapter.controlMode,
+ id: layer.id,
+ instantxControlMode: resolution.instantxControlMode,
+ kind: resolution.kind,
+ model: toModelReference(resolved),
+ modelCondInChannels: resolved.cond_in_channels,
+ modelControlArchitecture: resolved.control_architecture,
+ weight: adapter.weight,
+ },
+ status: 'contributes',
+ };
+ },
+ regional: (layer) => {
+ if (isHosted) {
+ return {
+ issue: {
+ kind: 'hosted_refusal',
+ modelName: model.name,
+ refusal: { kind: 'regional_guidance', layerName: layer.name },
+ },
+ status: 'blocked',
+ };
+ }
+ const referenceImages = resolveRegionalReferenceImages(layer, model.base);
+ const rejection = getRegionalGuidanceRejectionReason({
+ cfgScale,
+ hasContent: true,
+ layerName: layer.name,
+ layout: layer.layout,
+ mainBase: model.base,
+ negativePrompt: layer.negativePrompt,
+ positivePrompt: layer.positivePrompt,
+ referenceImageCount: referenceImages.length,
+ });
+ if (rejection) {
+ return { status: 'skipped' };
+ }
+ return {
+ input: {
+ autoNegative: layer.autoNegative,
+ id: layer.id,
+ // Typed against Generation's layout roles: a persisted role the graph cannot send fails to compile here.
+ ...(layer.layout ? { layout: layer.layout } : {}),
+ negativePrompt: layer.negativePrompt,
+ positivePrompt: layer.positivePrompt,
+ referenceImages,
+ },
+ status: 'contributes',
+ };
+ },
+ };
+};
+
+/** Control layers wait for the model list rather than block on its absence. */
+export const getCanvasInputIssues = (
+ params: CanvasInputJudgeParams & {
+ layers: readonly CanvasLayerContract[];
+ /** Measured only for a text-only hosted model. */
+ rasterInFrame: boolean;
+ regionalLayersInFrame: readonly CanvasRegionalGuidanceLayerContract[];
+ prompt: string;
+ }
+): CanvasInputIssue[] => {
+ const { layers, model, prompt, rasterInFrame, regionalLayersInFrame } = params;
+ const judge = createCanvasInputJudge(params);
+ const issues: CanvasInputIssue[] = [];
+
+ if (rasterInFrame && isExternalTextOnlyCanvasModel(model)) {
+ issues.push({ kind: 'hosted_refusal', modelName: model.name, refusal: { kind: 'raster_content' } });
+ }
+ for (const layer of layers) {
+ const verdict = isCompositableControlLayer(layer)
+ ? judge.control(layer)
+ : isCompositableRegionalGuidanceLayer(layer)
+ ? judge.regional(layer)
+ : null;
+ if (verdict?.status === 'blocked') {
+ issues.push(verdict.issue);
+ }
+ }
+ const layoutPromptReason = getLayoutPromptRejectionReason({
+ base: model.base,
+ prompt,
+ regions: regionalLayersInFrame,
+ });
+ if (layoutPromptReason) {
+ issues.push({ kind: 'layout_prompt', message: layoutPromptReason });
+ }
+ return issues;
+};
+
+type Translate = (key: string, options?: Record<string, unknown>) => string;
+
+export const describeCanvasInputIssue = (t: Translate, issue: CanvasInputIssue): string => {
+ switch (issue.kind) {
+ case 'control_layer':
+ return describeControlLayerIssue(t, issue);
+ case 'hosted_refusal':
+ return describeExternalCanvasRefusal({ name: issue.modelName }, issue.refusal);
+ case 'layout_prompt':
+ return issue.message;
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.ts b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.ts
index d707c35717..382fa8c8d4 100644
--- a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.test.ts
@@ -10,18 +10,11 @@ import {
describeControlLayer,
describeControlLayerIssue,
describeControlLayerReason,
- getBlockingControlLayerIssues,
hasControlLayerContent,
} from './controlLayerChecks';
const model = (key: string, base: string, type: string): ModelConfig => ({ base, key, name: key, type }) as ModelConfig;
-type MainModel = { base: string; variant?: string };
-
-/** The ambient warning the panel and the layer row show: per-generation limits left to Invoke. */
-const ambientReason = (layer: CanvasControlLayerContract, mainModel: MainModel, models: readonly ModelConfig[]) =>
- describeControlLayer(layer, { ...createControlLayerCheckContext(mainModel.base), mainModel, models }).reason;
-
const controlLayer = (
id: string,
overrides: {
@@ -54,7 +47,6 @@ const controlLayer = (
});
const sdxl = { base: 'sdxl' };
-const models = [model('sdxl-control', 'sdxl', 'controlnet'), model('sd1-control', 'sd-1', 'controlnet')];
seedArchitectureCapabilities();
@@ -70,132 +62,6 @@ describe('hasControlLayerContent', () => {
});
});
-describe('getBlockingControlLayerIssues', () => {
- it('blocks an untyped layer whose model is no longer installed', () => {
- expect(
- getBlockingControlLayerIssues({
- layers: [controlLayer('legacy', { model: 'uninstalled' })],
- mainModel: sdxl,
- models,
- })
- ).toMatchObject([{ code: 'missing_model', layerId: 'legacy' }]);
- });
-
- it('reports a typed content-bearing layer no model resolves, in structured form', () => {
- const issues = getBlockingControlLayerIssues({
- layers: [controlLayer('Control Layer 1', { derivation: { controlType: 'pose', detection: null } })],
- mainModel: sdxl,
- models,
- });
-
- expect(issues).toEqual([
- {
- code: 'no_model_for_type',
- layerId: 'Control Layer 1',
- layerName: 'Control Layer 1',
- },
- ]);
- });
-
- it('skips disabled, content-less, and non-control layers', () => {
- const issues = getBlockingControlLayerIssues({
- layers: [
- controlLayer('disabled', { isEnabled: false }),
- controlLayer('empty', { source: { bitmap: null, type: 'paint' } }),
- ],
- mainModel: sdxl,
- models,
- });
-
- expect(issues).toEqual([]);
- });
-
- it('advances the control LoRA limit counter only past valid layers', () => {
- const fluxModels = [model('flux-lora', 'flux', 'control_lora')];
- const issues = getBlockingControlLayerIssues({
- layers: [
- controlLayer('first', { kind: 'control_lora', model: 'flux-lora' }),
- controlLayer('second', { kind: 'control_lora', model: 'flux-lora' }),
- ],
- mainModel: { base: 'flux' },
- models: fluxModels,
- });
-
- expect(issues).toEqual([
- {
- code: 'control_lora_limit',
- layerId: 'second',
- layerName: 'second',
- },
- ]);
- });
-
- it('reports Anima LLLite layers the denoiser would refuse, and only those', () => {
- const animaModels = [
- { ...model('sketch', 'anima', 'controlnet'), cond_in_channels: 3 },
- { ...model('depth', 'anima', 'controlnet'), cond_in_channels: 3 },
- { ...model('inpaint', 'anima', 'controlnet'), cond_in_channels: 4 },
- ];
- const lllite = (id: string, key: string) => controlLayer(id, { kind: 'anima_lllite', model: key });
-
- const issues = getBlockingControlLayerIssues({
- layers: [
- lllite('sketch', 'sketch'),
- lllite('depth', 'depth'),
- lllite('again', 'sketch'),
- lllite('inpaint', 'inpaint'),
- controlLayer('saved-as-controlnet', { model: 'depth' }),
- ],
- mainModel: { base: 'anima' },
- models: animaModels,
- });
-
- expect(issues.map(({ code, layerId }) => [layerId, code])).toEqual([
- ['again', 'duplicate_lllite_model'],
- ['inpaint', 'lllite_inpaint_adapter'],
- ['saved-as-controlnet', 'switch_adapter_kind'],
- ]);
- });
-
- it('lets one Qwen-Image control through, and none on an Edit model', () => {
- const qwenModels = [model('qwen-union', 'qwen-image', 'controlnet')];
- const layers = [
- controlLayer('first', { kind: 'qwen_image_control', model: 'qwen-union', weight: 0.85 }),
- controlLayer('second', { kind: 'qwen_image_control', model: 'qwen-union', weight: 0.85 }),
- ];
- const codes = (mainModel: { base: string; variant?: string }) =>
- getBlockingControlLayerIssues({ layers, mainModel, models: qwenModels }).map(({ code, layerId }) => [
- layerId,
- code,
- ]);
-
- expect(codes({ base: 'qwen-image' })).toEqual([['second', 'qwen_image_control_limit']]);
- expect(codes({ base: 'qwen-image', variant: 'edit' })).toEqual([
- ['first', 'qwen_image_edit_control'],
- ['second', 'qwen_image_edit_control'],
- ]);
- });
-
- it('lets one FLUX.2 control through on [dev], and none on Klein', () => {
- const flux2Models = [model('flux2-union', 'flux2', 'controlnet')];
- const layers = [
- controlLayer('first', { kind: 'flux2_control', model: 'flux2-union', weight: 0.75 }),
- controlLayer('second', { kind: 'flux2_control', model: 'flux2-union', weight: 0.75 }),
- ];
- const codes = (mainModel: { base: string; variant?: string }) =>
- getBlockingControlLayerIssues({ layers, mainModel, models: flux2Models }).map(({ code, layerId }) => [
- layerId,
- code,
- ]);
-
- expect(codes({ base: 'flux2', variant: 'dev' })).toEqual([['second', 'flux2_control_limit']]);
- expect(codes({ base: 'flux2', variant: 'klein_9b' })).toEqual([
- ['first', 'flux2_klein_control'],
- ['second', 'flux2_klein_control'],
- ]);
- });
-});
-
describe('describeControlLayer after earlier layers', () => {
const fluxModels = [model('flux-lora', 'flux', 'control_lora'), model('sdxl-lora', 'sdxl', 'control_lora')];
const target = controlLayer('target', { kind: 'control_lora', model: 'flux-lora' });
@@ -215,44 +81,6 @@ describe('describeControlLayer after earlier layers', () => {
});
});
-describe('typed control layers', () => {
- const depthModels = [model('sdxl-depth-a', 'sdxl', 'controlnet'), model('sdxl-depth-b', 'sdxl', 'controlnet')];
- const typed = (
- id: string,
- derivation: Partial<Pick<CanvasControlLayerContract, 'detection' | 'filter' | 'original'>> = {},
- overrides: Parameters<typeof controlLayer>[1] = {}
- ) => controlLayer(id, { ...overrides, derivation: { controlType: 'depth', detection: null, ...derivation } });
- const depthDetection = { settings: {}, type: 'depth_anything_depth_estimation' };
-
- it('asks for a model when several fit, and resolves with the remembered pick', () => {
- const layers = [typed('depth')];
-
- expect(getBlockingControlLayerIssues({ layers, mainModel: sdxl, models: depthModels })).toMatchObject([
- { code: 'choose_model' },
- ]);
- expect(
- getBlockingControlLayerIssues({
- context: createControlLayerCheckContext('sdxl', { 'sdxl:depth': 'sdxl-depth-b' }),
- layers,
- mainModel: sdxl,
- models: depthModels,
- })
- ).toEqual([]);
- });
-
- it('blocks on a map detection has not caught up with, after the model reasons', () => {
- const pending = typed('pending', { detection: depthDetection });
-
- expect(
- getBlockingControlLayerIssues({ layers: [pending], mainModel: sdxl, models: [depthModels[0]!] })
- ).toMatchObject([{ code: 'detection_pending' }]);
- expect(getBlockingControlLayerIssues({ layers: [pending], mainModel: sdxl, models: depthModels })).toMatchObject([
- { code: 'choose_model' },
- ]);
- expect(ambientReason(pending, sdxl, [depthModels[0]!])).toBe('detection_pending');
- });
-});
-
describe('describeControlLayer', () => {
const sdxlDepth = [model('sdxl-depth', 'sdxl', 'controlnet')];
const ctx = { ...createControlLayerCheckContext('sdxl'), mainModel: sdxl, models: sdxlDepth };
diff --git a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.ts b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.ts
index af0da9ef83..4b80b4795f 100644
--- a/invokeai/frontend/webv2/src/workbench/controlLayerChecks.ts
+++ b/invokeai/frontend/webv2/src/workbench/controlLayerChecks.ts
@@ -1,5 +1,5 @@
import type { ModelConfig } from '@features/models';
-import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/api';
+import type { CanvasControlLayerContract } from '@workbench/canvas-engine/api';
import {
createControlValidationSequence,
@@ -9,7 +9,7 @@ import {
} from '@features/generation/graph';
import { hasArchitectureCapabilities } from '@features/generation/settings';
import { getControlDetectionInput, isControlMapCurrent, needsControlDetection } from '@workbench/canvas-engine/api';
-import { hasControlLayerContent, isCompositableControlLayer } from '@workbench/canvasLayerContent';
+import { hasControlLayerContent } from '@workbench/canvasLayerContent';
import { resolveControlModel, type ControlModelMemory, type ControlModelResolution } from './controlModelResolution';
@@ -53,10 +53,7 @@ export interface ControlLayerJudgement {
skip: boolean;
}
-/**
- * Judges control layers in generation order, as the invocation does: per-generation limits count only layers that
- * passed. Invoke readiness, the settings panel and the invocation collector share it.
- */
+/** Per-generation limits count only layers that passed earlier in generation order. */
export const createControlLayerSequence = (
mainModel: MainModel,
models: readonly ModelConfig[],
@@ -85,32 +82,6 @@ export const createControlLayerSequence = (
};
};
-/**
- * Validate the same enabled, content-bearing layers as createControlLayerCollector; invalid layers do not consume
- * per-generation limits, and layers without a type or model are left out.
- */
-export const getBlockingControlLayerIssues = (params: {
- layers: readonly CanvasLayerContract[];
- mainModel: MainModel;
- models: readonly ModelConfig[];
- context?: ControlLayerCheckContext;
-}): ControlLayerIssue[] => {
- const { layers, mainModel, models } = params;
- const judge = createControlLayerSequence(mainModel, models, params.context);
- const issues: ControlLayerIssue[] = [];
-
- for (const layer of layers) {
- if (!isCompositableControlLayer(layer)) {
- continue;
- }
- const { reason, skip } = judge(layer);
- if (reason && !skip) {
- issues.push({ code: reason, layerId: layer.id, layerName: layer.name });
- }
- }
- return issues;
-};
-
/**
* Where a layer's control map stands. `empty`: no pixels yet. `none`: no type or no detection, so the pixels are the
* map. `current`: the map matches its detection. `stale`: detection must run again. `no-input`: the map is all the
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx
index 6a15f105dd..bd9917e30f 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx
@@ -1,7 +1,7 @@
import type { GalleryImage, GalleryVideoItem } from '@features/gallery';
import type * as GalleryBackendModule from '@features/gallery/data/backend';
import type { ModelConfig } from '@features/models';
-import type { ControlLayerRejection } from '@workbench/widgets/canvas/invoke/prepareCanvasInvocation';
+import type { CanvasInvocationFailure } from '@workbench/widgets/canvas/invoke/canvasInvocationFailure';
import { setArchitectureCapabilities } from '@features/generation/core/architectureCapabilities';
import {
@@ -22,9 +22,11 @@ import { useRegisterFirstPartyCommands } from './firstPartyCommands';
const handlers = vi.hoisted(() => new Map<string, () => unknown>());
const submitActiveInvocation = vi.hoisted(() =>
- vi.fn<(args: { formatControlLayerError: (rejection: ControlLayerRejection) => string }) => Promise<void>>(() =>
- Promise.resolve()
- )
+ vi.fn<
+ (args: {
+ formatCanvasInvocationFailure: (failure: CanvasInvocationFailure) => { message: string; title: string };
+ }) => Promise<void>
+ >(() => Promise.resolve())
);
const workbench = vi.hoisted(() => ({
@@ -332,7 +334,7 @@ describe('viewer recall keys on a selected video', () => {
});
});
-it('words a blocked control layer from the locale when Invoke runs from its hotkey', async () => {
+it('words a blocked control layer and its notice title from the locale when Invoke runs from its hotkey', async () => {
await renderCommands();
await act(async () => {
@@ -340,7 +342,13 @@ it('words a blocked control layer from the locale when Invoke runs from its hotk
});
const [args] = submitActiveInvocation.mock.calls[0] ?? [];
- expect(args?.formatControlLayerError({ code: 'switch_adapter_kind', layerName: 'Sketch' })).toBe(
- 'Control layer "Sketch": Choose a control type so a model for the selected main model can be picked.'
- );
+ expect(
+ args?.formatCanvasInvocationFailure({
+ issue: { code: 'switch_adapter_kind', kind: 'control_layer', layerId: 'sketch', layerName: 'Sketch' },
+ kind: 'canvas_input',
+ })
+ ).toEqual({
+ message: 'Control layer "Sketch": Choose a control type so a model for the selected main model can be picked.',
+ title: 'Canvas generation failed',
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index b99a697dc9..f042abacea 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -21,7 +21,6 @@ import {
} from '@platform/state/accountLifecycle';
import { useQueryClient } from '@tanstack/react-query';
import { submitActiveInvocation } from '@workbench/activeInvocationSubmission';
-import { describeControlLayerIssue } from '@workbench/controlLayerChecks';
import { useWorkbenchFocus, useWorkbenchFocusTarget } from '@workbench/focusRegions';
import { builtInLayoutPresetDescriptors } from '@workbench/layoutPresets';
import { toggleCommandPalette } from '@workbench/palette/paletteStore';
@@ -37,6 +36,7 @@ import {
} from '@workbench/widgetPlacementCommands';
import { getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
import { getWidgetsForRegion } from '@workbench/widgetRegistry';
+import { describeCanvasInvocationFailure } from '@workbench/widgets/canvas/invoke/canvasInvocationFailure';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useWorkbenchCommands, useWorkbenchExtensions, useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { resolvePanelToggle } from '@workbench/workbenchState';
@@ -138,7 +138,7 @@ export const useRegisterFirstPartyCommands = () => {
await submitActiveInvocation({
commands,
destinationOverride,
- formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),
+ formatCanvasInvocationFailure: (failure) => describeCanvasInvocationFailure(t, failure),
formatUpscaleMetadataFailure: (name) => t('widgets.gallery.itemActions.upscale.metadataFailed', { name }),
getModels: getAvailableModels,
...(prepend ? { prepend } : {}),
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index 7e7d422b80..66048f6e63 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -33,7 +33,11 @@ const preferences = vi.hoisted(() => ({ controlModelMemory: {} as Record<string,
/** A route reason as text: Generate issues carry their English beside the locale key. */
const reasonText = (reason: InvocationValidationReason) =>
- typeof reason === 'object' && 'generationIssue' in reason ? reason.generationIssue.message : reason;
+ typeof reason === 'object' && 'generationIssue' in reason
+ ? reason.generationIssue.message
+ : typeof reason === 'object' && 'canvasInputIssue' in reason
+ ? describeCanvasInputIssue((key) => key, reason.canvasInputIssue)
+ : reason;
vi.mock('./settings/store', async (importOriginal) => {
const actual = await importOriginal<typeof settingsStoreModule>();
@@ -48,6 +52,7 @@ vi.mock('./settings/store', async (importOriginal) => {
import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { describeCanvasInputIssue } from './canvasGenerationInputs';
import {
areInvocationRouteInputsEqual,
getInvocationRouteInput,
@@ -59,7 +64,7 @@ import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.
import { createWorkbenchStore } from './workbenchStore';
// Production words rejections from the locale; tests only need the structured rejection to reach the notice.
-const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;
+const formatCanvasInvocationFailure = () => ({ message: 'canvas failure', title: 'canvas failure' });
const formatUpscaleMetadataFailure = (name: string) => `metadataFailed: ${name}`;
const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };
@@ -270,7 +275,7 @@ describe('resolveInvocationRoute — canvas source', () => {
canvasInputFor({ generateValues: createGenerateValues(textOnly), rasterInFrame: true }),
'global',
canvasRoute
- ).validationReasons
+ ).validationReasons.map(reasonText)
).toEqual([
'Unknown External Provider cannot use image content in the generation frame. Hide or move raster content out of the frame to generate.',
]);
@@ -301,8 +306,9 @@ describe('resolveInvocationRoute — canvas source', () => {
expect(route.sourceValid).toBe(false);
// Kept structured so the shell words it from the locale.
expect(route.validationReasons).toContainEqual({
- controlLayerIssue: {
+ canvasInputIssue: {
code: 'no_control_models',
+ kind: 'control_layer',
layerId: expect.any(String),
layerName: 'Control Layer 1',
},
@@ -372,7 +378,7 @@ describe('resolveInvocationRoute — canvas source', () => {
{ ...inputFor(model, overrides, layers), mountedWidgetIds: ['canvas', 'generate'] as WidgetId[] },
'global',
canvasRoute
- ).validationReasons;
+ ).validationReasons.map(reasonText);
const blankPromptReason = (label: string) =>
`${label} needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.`;
@@ -446,7 +452,7 @@ describe('submitResolvedInvocation', () => {
submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -482,7 +488,7 @@ describe('submitResolvedInvocation', () => {
const submission = submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -517,7 +523,7 @@ describe('submitResolvedInvocation', () => {
submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -544,7 +550,7 @@ describe('submitResolvedInvocation', () => {
submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -568,7 +574,7 @@ describe('submitResolvedInvocation', () => {
submitResolvedInvocation({
commands: store.commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -609,7 +615,7 @@ describe('submitResolvedInvocation', () => {
accountLifecycle.invalidate();
submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index aea958ddc3..6f9c35511f 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -14,9 +14,8 @@ import type {
import type { Project } from '@workbench/projectContracts';
import type { WidgetId } from '@workbench/widgetContracts';
-import { getLayoutDraftRejectionReason, getLayoutPromptRejectionReason } from '@features/generation/graph';
+import { getLayoutDraftRejectionReason } from '@features/generation/graph';
import {
- describeExternalCanvasRefusal,
describeGenerationIssue,
expandsDynamicPrompts,
getEffectivePrompts,
@@ -44,13 +43,9 @@ import {
isBaseRasterContentLayer,
lookupDocumentNode,
} from '@workbench/canvas-engine/api';
-import { isCompositableControlLayer, isCompositableRegionalGuidanceLayer } from '@workbench/canvasLayerContent';
+import { isCompositableRegionalGuidanceLayer } from '@workbench/canvasLayerContent';
-import {
- createControlLayerCheckContext,
- describeControlLayerIssue,
- getBlockingControlLayerIssues,
-} from './controlLayerChecks';
+import { describeCanvasInputIssue, getCanvasInputIssues } from './canvasGenerationInputs';
import { getActiveProjectGraph } from './projectWorkflows';
import { getWorkbenchPreferences } from './settings/store';
import { getProjectWidgetValues } from './widgetState';
@@ -407,43 +402,19 @@ export const resolveInvocationRouteInput = (
}
const values = normalizeGenerateWidgetValues(input.generateValues);
- if (values?.model.type === 'external_image_generator') {
- const { model } = values;
-
- if (input.canvasRasterInFrame && isExternalTextOnlyCanvasModel(model)) {
- validationReasons.push(describeExternalCanvasRefusal(model, { kind: 'raster_content' }));
- }
- for (const layer of input.canvasLayers) {
- if (isCompositableControlLayer(layer)) {
- validationReasons.push(
- describeExternalCanvasRefusal(model, { kind: 'control_layer', layerName: layer.name })
- );
- } else if (isCompositableRegionalGuidanceLayer(layer)) {
- validationReasons.push(
- describeExternalCanvasRefusal(model, { kind: 'regional_guidance', layerName: layer.name })
- );
- }
- }
- } else if (values && isSupportedGenerateModel(values.model)) {
- // Wait for models before validating local adapters to avoid false missing-model errors.
- if (models) {
- validationReasons.push(
- ...getBlockingControlLayerIssues({
- context: createControlLayerCheckContext(values.model.base, getWorkbenchPreferences().controlModelMemory),
- layers: input.canvasLayers,
- mainModel: values.model,
- models,
- }).map((controlLayerIssue) => ({ controlLayerIssue }))
- );
- }
- const layoutPromptReason = getLayoutPromptRejectionReason({
- base: values.model.base,
- prompt: getEffectivePrompts(values).positivePrompt,
- regions: input.canvasRegionalLayersInFrame,
- });
- if (layoutPromptReason) {
- validationReasons.push(layoutPromptReason);
- }
+ if (values && (values.model.type === 'external_image_generator' || isSupportedGenerateModel(values.model))) {
+ validationReasons.push(
+ ...getCanvasInputIssues({
+ cfgScale: values.cfgScale,
+ controlModelMemory: getWorkbenchPreferences().controlModelMemory,
+ layers: input.canvasLayers,
+ model: values.model,
+ models,
+ prompt: getEffectivePrompts(values).positivePrompt,
+ rasterInFrame: input.canvasRasterInFrame,
+ regionalLayersInFrame: input.canvasRegionalLayersInFrame,
+ }).map((canvasInputIssue) => ({ canvasInputIssue }))
+ );
}
}
@@ -498,8 +469,8 @@ export const localizeInvocationValidationReason = (
reason: InvocationValidationReason,
t: (key: string, options?: Record<string, unknown>) => string
): string =>
- typeof reason === 'object' && 'controlLayerIssue' in reason
- ? describeControlLayerIssue(t, reason.controlLayerIssue)
+ typeof reason === 'object' && 'canvasInputIssue' in reason
+ ? describeCanvasInputIssue(t, reason.canvasInputIssue)
: typeof reason === 'object' && 'generationIssue' in reason
? describeGenerationIssue(t, reason.generationIssue)
: typeof reason === 'object' && 'routeIssue' in reason
diff --git a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
index e50ea72c4f..9b1491ca7c 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts
@@ -1,6 +1,6 @@
import type { GenerationIssue } from '@features/generation/contracts';
import type { InvocationTemplatesSnapshot, WorkflowReadinessReason } from '@features/workflow/contracts';
-import type { ControlLayerIssue } from '@workbench/controlLayerChecks';
+import type { CanvasInputIssue } from '@workbench/canvasGenerationInputs';
export type InvocationSourceId = 'generate' | 'workflow' | 'upscale' | 'video' | 'canvas';
@@ -39,9 +39,8 @@ export interface InvocationRoute {
destinationLocked: boolean;
}
-/** A blocking control layer, kept structured so the shell words it from the locale. */
-export interface ControlLayerValidationReason {
- controlLayerIssue: ControlLayerIssue;
+export interface CanvasInputValidationReason {
+ canvasInputIssue: CanvasInputIssue;
}
/**
@@ -67,7 +66,7 @@ export interface RouteValidationReason {
export type InvocationValidationReason =
| string
| WorkflowReadinessReason
- | ControlLayerValidationReason
+ | CanvasInputValidationReason
| GenerationValidationReason
| RouteValidationReason;
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx
index 9c0bda3f04..7a10cad803 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx
@@ -106,7 +106,7 @@ const submitGenerate = () => {
const submission = submitResolvedInvocation({
commands,
- formatControlLayerError: ({ code, layerName }) => `${layerName}: ${code}`,
+ formatCanvasInvocationFailure: () => ({ message: 'canvas failure', title: 'canvas failure' }),
formatUpscaleMetadataFailure: (name) => name,
scopedDefaults: {},
models: undefined,
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
index d6b04d01a8..b09aa1a856 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
@@ -72,8 +72,7 @@ const getActiveProject = (state: ReturnType<typeof createInitialWorkbenchState>)
};
import { createWorkbenchStore } from './workbenchStore';
-// Production words rejections from the locale; tests only need the structured rejection to reach the notice.
-const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;
+const formatCanvasInvocationFailure = () => ({ message: 'canvas failure', title: 'canvas failure' });
const formatUpscaleMetadataFailure = (name: string) => `metadataFailed: ${name}`;
const field = (name: string, typeName: string, overrides: Record<string, unknown> = {}) => ({
@@ -210,7 +209,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -255,7 +254,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {
try {
const submission = submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -324,7 +323,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -345,7 +344,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -448,7 +447,7 @@ describe('submitResolvedInvocation with a random dynamic prompt', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -509,7 +508,7 @@ describe('submitResolvedInvocation without dynamic prompts', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -561,7 +560,7 @@ describe('submitResolvedInvocation without dynamic prompts', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: undefined,
@@ -614,7 +613,7 @@ describe('submitResolvedInvocation for Video', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: [wanModel],
@@ -708,7 +707,7 @@ describe('submitResolvedInvocation when the prompt changes while it expands', ()
try {
const submission = submitResolvedInvocation({
commands: store.commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models,
@@ -782,7 +781,7 @@ describe("submitResolvedInvocation reads the user's defaults", () => {
await submitResolvedInvocation({
commands: createWorkbenchStore().commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {
canvas: { outputOnlyMaskedRegions: false },
@@ -846,7 +845,7 @@ describe('submitResolvedInvocation for Upscale', () => {
await submitResolvedInvocation({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
scopedDefaults: {},
models: [upscaler],
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
index 701798893b..da5fbcad38 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
@@ -84,7 +84,7 @@ export interface SubmitResolvedInvocationDeps {
prepend?: boolean;
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
prepareCanvasInvocation: (args: PrepareCanvasInvocationArgs) => Promise<void> | void;
- formatControlLayerError: PrepareCanvasInvocationArgs['formatControlLayerError'];
+ formatCanvasInvocationFailure: PrepareCanvasInvocationArgs['formatCanvasInvocationFailure'];
formatUpscaleMetadataFailure: (imageName: string) => string;
}
@@ -179,7 +179,7 @@ const resolveWorkflowGeneratorsForRoute = async (
export const submitResolvedInvocation = async ({
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
models,
owner,
@@ -250,7 +250,7 @@ export const submitResolvedInvocation = async ({
await dispatchResolvedInvocation(
{
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
models,
owner,
@@ -274,7 +274,7 @@ export const submitResolvedInvocation = async ({
await dispatchResolvedInvocation(
{
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
models,
owner,
@@ -296,7 +296,7 @@ export const submitResolvedInvocation = async ({
const dispatchResolvedInvocation = async (
{
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
formatUpscaleMetadataFailure,
models,
owner,
@@ -345,7 +345,7 @@ const dispatchResolvedInvocation = async (
compositing: readCanvasCompositingSettings(canvasValues),
destination: route.destination,
commands,
- formatControlLayerError,
+ formatCanvasInvocationFailure,
generateValues: getProjectWidgetValues(project, 'generate'),
models,
owner,
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.test.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.test.ts
index 45ad3792ab..752fbfbea8 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.test.ts
@@ -28,6 +28,29 @@ describe('getInvocationIssueTarget', () => {
});
});
+ it('leads a blocking control layer to that layer, and a hosted refusal to the Canvas', () => {
+ expect(
+ getInvocationIssueTarget(
+ {
+ canvasInputIssue: { code: 'missing_model', kind: 'control_layer', layerId: 'control-1', layerName: 'Sketch' },
+ },
+ 'canvas'
+ )
+ ).toEqual({ kind: 'layer', layerId: 'control-1' });
+ expect(
+ getInvocationIssueTarget(
+ {
+ canvasInputIssue: {
+ kind: 'hosted_refusal',
+ modelName: 'OpenAI Image',
+ refusal: { kind: 'regional_guidance', layerName: 'Hat' },
+ },
+ },
+ 'canvas'
+ )
+ ).toEqual({ kind: 'widget', widgetId: 'canvas' });
+ });
+
it('leads a plain reason to the source widget that owns it', () => {
expect(getInvocationIssueTarget('Upscale settings are incomplete.', 'upscale')).toEqual({
kind: 'widget',
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts
index 74f340efea..cf009737a9 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts
@@ -33,8 +33,8 @@ export const getInvocationIssueTarget = (
sourceId: InvocationSourceId
): InvocationIssueTarget => {
if (typeof reason === 'object') {
- if ('controlLayerIssue' in reason) {
- return { kind: 'layer', layerId: reason.controlLayerIssue.layerId };
+ if ('canvasInputIssue' in reason && reason.canvasInputIssue.kind === 'control_layer') {
+ return { kind: 'layer', layerId: reason.canvasInputIssue.layerId };
}
if ('generationIssue' in reason) {
return { issue: reason.generationIssue, kind: 'generation' };
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
index fd2f154f96..561e4407c3 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts
@@ -22,7 +22,6 @@ import { getInvocationTemplatesSnapshot, subscribeInvocationTemplates } from '@f
import { useMountEffect } from '@platform/react/useMountEffect';
import { useExternalStoreSelector } from '@platform/state/selectors';
import { submitActiveInvocation } from '@workbench/activeInvocationSubmission';
-import { describeControlLayerIssue } from '@workbench/controlLayerChecks';
import { getPlacedWidgetTypeIds, getVisibleWidgetTypeIds, graphWidgetSources } from '@workbench/graphWidgets';
import {
createInvocationRouteInputSelector,
@@ -32,6 +31,7 @@ import {
} from '@workbench/invocation';
import { useIsInvocationPreparing } from '@workbench/invocationPreparation';
import { getWorkbenchPreferences, subscribeWorkbenchPreferences } from '@workbench/settings/store';
+import { describeCanvasInvocationFailure } from '@workbench/widgets/canvas/invoke/canvasInvocationFailure';
import {
useActiveProjectSelector,
useWorkbenchCommands,
@@ -242,7 +242,7 @@ export const useInvocationState = ({ sourceId }: { sourceId?: InvocationSourceId
onStarted,
prepend,
sourceId,
- formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),
+ formatCanvasInvocationFailure: (failure) => describeCanvasInvocationFailure(t, failure),
formatUpscaleMetadataFailure: (name) => t('widgets.gallery.itemActions.upscale.metadataFailed', { name }),
getModels: () => availabilityModels,
queries,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasInvocationFailure.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasInvocationFailure.ts
new file mode 100644
index 0000000000..ba875ceb09
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasInvocationFailure.ts
@@ -0,0 +1,64 @@
+import type { ComposeForGenerationResult } from '@workbench/canvas-operations/api';
+
+import { describeCanvasInputIssue, type CanvasInputIssue } from '@workbench/canvasGenerationInputs';
+
+export type CanvasInvocationFailure =
+ | { kind: 'canvas_input'; issue: CanvasInputIssue }
+ | { kind: 'capture'; result: Exclude<ComposeForGenerationResult, { status: 'ok' }> }
+ | { kind: 'no_model' }
+ | { kind: 'canvas_not_open' }
+ | { kind: 'error'; message: string };
+
+export interface CanvasInvocationNotice {
+ title: string;
+ message: string;
+}
+
+type Translate = (key: string, options?: Record<string, unknown>) => string;
+
+const describeAdjustmentRefusal = (t: Translate, reason: 'error' | 'over-budget' | 'too-large', name: string) => {
+ switch (reason) {
+ case 'error':
+ return t('widgets.canvas.invoke.adjustmentRefused.error', { name });
+ case 'over-budget':
+ return t('widgets.canvas.invoke.adjustmentRefused.overBudget', { name });
+ case 'too-large':
+ return t('widgets.canvas.invoke.adjustmentRefused.tooLarge', { name });
+ }
+};
+
+const describeCapture = (t: Translate, result: Extract<CanvasInvocationFailure, { kind: 'capture' }>['result']) => {
+ switch (result.status) {
+ case 'no-document':
+ return t('widgets.canvas.invoke.noDocument');
+ case 'stale':
+ return t('widgets.canvas.invoke.stale');
+ case 'adjustment-refused':
+ return describeAdjustmentRefusal(t, result.reason, result.ownerName);
+ case 'unreadable':
+ return t('widgets.canvas.invoke.unreadable', { name: result.layerName });
+ case 'not-ready':
+ return t('widgets.canvas.invoke.notReady');
+ case 'over-budget':
+ return t('widgets.canvas.invoke.overBudget');
+ case 'aborted':
+ return t('widgets.canvas.invoke.captureFailed', { status: result.status });
+ }
+};
+
+export const describeCanvasInvocationFailure = (
+ t: Translate,
+ failure: CanvasInvocationFailure
+): CanvasInvocationNotice => ({
+ message:
+ failure.kind === 'canvas_input'
+ ? describeCanvasInputIssue(t, failure.issue)
+ : failure.kind === 'capture'
+ ? describeCapture(t, failure.result)
+ : failure.kind === 'no_model'
+ ? t('widgets.canvas.invoke.noModel')
+ : failure.kind === 'canvas_not_open'
+ ? t('widgets.canvas.invoke.notOpen')
+ : failure.message,
+ title: t('widgets.canvas.invoke.failed'),
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index dd65c64be5..da8ebf6c0c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -5,8 +5,6 @@ import type {
CanvasLayerContract,
CanvasRasterLayerContractV2,
CanvasStateContractV3,
- RegionalGuidanceReferenceImage,
- RegionalGuidanceReferenceImageAsset,
} from '@workbench/canvas-engine/contracts';
import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
@@ -27,13 +25,15 @@ import {
type GenerationCompositeHost,
} from '@workbench/canvas-operations/api';
import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
+import { createInstance } from 'i18next';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { RunCanvasInvocationDeps } from './prepareCanvasInvocation';
import { DEFAULT_CANVAS_COMPOSITING } from './canvasCompositing';
+import { describeCanvasInvocationFailure } from './canvasInvocationFailure';
import { DEFAULT_CANVAS_SCALING } from './canvasScaling';
-import { resolveRegionalReferenceImages, runCanvasInvocation } from './prepareCanvasInvocation';
+import { runCanvasInvocation } from './prepareCanvasInvocation';
const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };
const externalModel: GenerateModelConfig = {
@@ -67,6 +67,19 @@ const rasterLayer = (id: string, size = 64): CanvasRasterLayerContractV2 => ({
type: 'raster',
});
+const englishCatalogModules = import.meta.glob('../../../../../public/locales/en.json', {
+ eager: true,
+ import: 'default',
+});
+const english = createInstance();
+await english.init({
+ initAsync: false,
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: Object.values(englishCatalogModules)[0] as Record<string, unknown> } },
+});
+const t = english.t.bind(english) as (key: string, options?: Record<string, unknown>) => string;
+
const makeDoc = (layers: CanvasRasterLayerContractV2[], size = 64): CanvasDocumentContractV3 => ({
background: 'transparent',
bbox: { height: size, width: size, x: 0, y: 0 },
@@ -236,7 +249,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {
} as WorkbenchCommands['notifications'],
},
flushPendingUploads: flushPendingUploads as () => Promise<void>,
- formatControlLayerError: ({ code, layerName }) => `${layerName}: ${code}`,
+ formatCanvasInvocationFailure: (failure) => describeCanvasInvocationFailure(t, failure),
generateValues: { ...generateValuesFor(model), ...options.generateValues },
inFlight: options.inFlight ?? new Set<string>(),
models: options.models,
@@ -537,6 +550,21 @@ describe('runCanvasInvocation', () => {
type: 'controlnet',
});
});
+
+ it('refuses a layer the judge blocks with a localized notice, before uploading anything', async () => {
+ const harness = makeHarness({ document: docWithLayers([typed('depth-layer', 'depth')]) });
+
+ await runCanvasInvocation(harness.deps);
+
+ expect(harness.notices()).toEqual([
+ expect.objectContaining({
+ message: `Control layer "depth-layer": ${t('widgets.layers.control.validation.models_unavailable')}`,
+ title: 'Canvas generation failed',
+ }),
+ ]);
+ expect(harness.submittedGraphs()).toHaveLength(0);
+ expect(harness.uploadImage).not.toHaveBeenCalled();
+ });
});
it('prepares a Z-Image control with exact adapter and model configuration', async () => {
@@ -980,61 +1008,3 @@ describe('runCanvasInvocation — inpaint / outpaint dispatch', () => {
expect(harness.notices()).toHaveLength(0);
});
});
-
-describe('resolveRegionalReferenceImages', () => {
- const asset = { imageName: 'ref.png' } as RegionalGuidanceReferenceImageAsset;
- const ipAdapterModel = { base: 'sd-1', key: 'ipa', name: 'IP Adapter', type: 'ip_adapter' };
- const fluxReduxModel = { base: 'flux', key: 'redux', name: 'FLUX Redux', type: 'flux_redux' };
-
- const ipAdapterRef = (image: RegionalGuidanceReferenceImageAsset | null): RegionalGuidanceReferenceImage => ({
- config: {
- beginEndStepPct: [0, 1],
- clipVisionModel: 'ViT-H',
- image,
- method: 'full',
- model: ipAdapterModel,
- type: 'ip_adapter',
- weight: 1,
- },
- id: 'ref-ipa',
- isEnabled: true,
- });
-
- const fluxReduxRef = (image: RegionalGuidanceReferenceImageAsset | null): RegionalGuidanceReferenceImage => ({
- config: { image, imageInfluence: 'highest', model: fluxReduxModel, type: 'flux_redux' },
- id: 'ref-redux',
- isEnabled: true,
- });
-
- const withModelBase = (base: string): RegionalGuidanceReferenceImage => {
- const ref = ipAdapterRef(asset);
- return { ...ref, config: { ...ref.config, model: { ...ipAdapterModel, base } } };
- };
-
- it.each<[string, RegionalGuidanceReferenceImage, string, Record<string, unknown>[]]>([
- ['drops an IP-Adapter ref with no image assigned', ipAdapterRef(null), 'sd-1', []],
- [
- 'keeps an IP-Adapter ref once an image is assigned for a supported SD base',
- ipAdapterRef(asset),
- 'sd-1',
- [{ id: 'ref-ipa', imageName: 'ref.png', type: 'ip_adapter' }],
- ],
- ['drops regional reference images for FLUX.2', ipAdapterRef(asset), 'flux2', []],
- ['drops regional reference images for krea-2', withModelBase('krea-2'), 'krea-2', []],
- ['drops regional reference images for z-image', withModelBase('z-image'), 'z-image', []],
- ['drops regional reference images for anima', withModelBase('anima'), 'anima', []],
- ['keeps an SD2 IP-Adapter ref whose model matches the base', withModelBase('sd-2'), 'sd-2', [{ id: 'ref-ipa' }]],
- ['drops a FLUX Redux ref with no image assigned', fluxReduxRef(null), 'flux', []],
- [
- 'keeps a FLUX Redux ref once an image is assigned (FLUX base)',
- fluxReduxRef(asset),
- 'flux',
- [{ id: 'ref-redux', imageName: 'ref.png', type: 'flux_redux' }],
- ],
- ['drops a disabled ref even when an image is assigned', { ...ipAdapterRef(asset), isEnabled: false }, 'sd-1', []],
- ])('%s', (_, ref, base, expected) => {
- expect(resolveRegionalReferenceImages({ referenceImages: [ref] }, base)).toEqual(
- expected.map((input) => expect.objectContaining(input))
- );
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 0174154351..2ed43aaa3e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -5,34 +5,17 @@ import type {
GenerateModelConfig,
GenerationProjectSettings,
} from '@features/generation/contracts';
+import type { ControlLayerGraphInput, RegionalGuidanceInput } from '@features/generation/graph';
import type { ModelConfig } from '@features/models';
-import type {
- CanvasControlLayerContract,
- CanvasRegionalGuidanceLayerContract,
- RegionalGuidanceReferenceImage,
-} from '@workbench/canvas-engine/api';
import type { ComposeForGenerationOptions, ComposeForGenerationResult } from '@workbench/canvas-operations/api';
-import type { ControlLayerIssueCode } from '@workbench/controlLayerChecks';
+import type { CanvasInputIssue, ControlLayerVerdict, RegionalLayerVerdict } from '@workbench/canvasGenerationInputs';
import type { ControlModelMemory } from '@workbench/controlModelResolution';
import type { ExpandedPositivePrompts, ResultDestination } from '@workbench/invocationContracts';
-import type { WorkbenchNotificationKind } from '@workbench/projectContracts';
import type { WorkbenchCommands, WorkbenchNotificationCommands } from '@workbench/workbenchStore';
import { compileCanvasGraph, type CanvasCompileMode } from '@features/generation/canvasGraph';
-import {
- detectCanvasMode,
- getRegionalGuidanceRejectionReason,
- getRegionalGuidanceSupport,
- type ControlLayerGraphInput,
- type RegionalGuidanceInput,
- type RegionalReferenceImageInput,
- resolveGenerateSeed,
-} from '@features/generation/graph';
-import {
- describeExternalCanvasRefusal,
- normalizeGenerateWidgetValues,
- syncGenerateWidgetValuesWithModels,
-} from '@features/generation/settings';
+import { detectCanvasMode, resolveGenerateSeed } from '@features/generation/graph';
+import { normalizeGenerateWidgetValues, syncGenerateWidgetValuesWithModels } from '@features/generation/settings';
import { getGenerationDevicesSnapshot, resolveRandDeviceMetadata } from '@features/queue/devices';
import {
captureAccountScope,
@@ -41,31 +24,22 @@ import {
type AccountScope,
} from '@platform/state/accountLifecycle';
import { getCanvasEngine, getCanvasOperations, recordCanvasMetadata } from '@workbench/canvas-operations/api';
-import { createControlLayerCheckContext, createControlLayerSequence } from '@workbench/controlLayerChecks';
+import { createCanvasInputJudge } from '@workbench/canvasGenerationInputs';
import { getWorkbenchPreferences } from '@workbench/settings/store';
import {
DEFAULT_CANVAS_COMPOSITING,
type CanvasCompositingSettings,
} from '@workbench/widgets/canvas/invoke/canvasCompositing';
-import { readCanvasScaling } from './canvasScaling';
+import type { CanvasInvocationFailure, CanvasInvocationNotice } from './canvasInvocationFailure';
-export const CANVAS_INVOKE_ERROR_TITLE = 'Canvas generation failed';
-
-/** A control layer that blocks the invocation, as `formatControlLayerError` words it for the notice. */
-export interface ControlLayerRejection {
- code: ControlLayerIssueCode;
- layerName: string;
-}
+import { readCanvasScaling } from './canvasScaling';
-/** Structured control-layer rejection: callers word it from the locale; the message is for logs only. */
-export class ControlLayerValidationError extends Error implements ControlLayerRejection {
- constructor(
- readonly code: ControlLayerIssueCode,
- readonly layerName: string
- ) {
- super(`Control layer "${layerName}" is invalid: ${code}.`);
- this.name = 'ControlLayerValidationError';
+/** Composition aborts and rethrows this, carrying the blocking layer out. */
+class CanvasInputRefusal extends Error {
+ constructor(readonly issue: CanvasInputIssue) {
+ super(`Canvas input refused: ${issue.kind}.`);
+ this.name = 'CanvasInputRefusal';
}
}
@@ -105,198 +79,30 @@ export interface RunCanvasInvocationDeps {
/** Persisted "scale before processing" policy, defaulted. */
scaling: CanvasScalingSettings;
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
- /** Words a control-layer rejection from the locale; its error message is for logs only. */
- formatControlLayerError: (rejection: ControlLayerRejection) => string;
+ formatCanvasInvocationFailure: (failure: CanvasInvocationFailure) => CanvasInvocationNotice;
}
-const recordNotice = (
+const recordFailure = (
notifications: WorkbenchNotificationCommands,
- kind: WorkbenchNotificationKind,
- message: string
+ formatCanvasInvocationFailure: RunCanvasInvocationDeps['formatCanvasInvocationFailure'],
+ failure: CanvasInvocationFailure
): void => {
- notifications.add({ kind, message, title: CANVAS_INVOKE_ERROR_TITLE });
+ notifications.add({ kind: 'error', ...formatCanvasInvocationFailure(failure) });
};
-/** Validates controls with Invoke readiness's judge; invalid ones throw, untyped or modelless ones are skipped. */
-const createControlLayerCollector = (
- model: GenerateModelConfig,
- models: readonly ModelConfig[] | undefined,
- remembered: ControlModelMemory
-): {
- shouldComposite(layer: CanvasControlLayerContract): boolean;
- toGraphInputs(images: readonly { layerId: string; imageName: string }[]): ControlLayerGraphInput[];
-} => {
- const metadata = new Map<string, Omit<ControlLayerGraphInput, 'imageName'>>();
- const judge = models
- ? createControlLayerSequence(model, models, createControlLayerCheckContext(model.base, remembered))
- : null;
-
- return {
- shouldComposite: (layer) => {
- if (model.type === 'external_image_generator') {
- throw new Error(describeExternalCanvasRefusal(model, { kind: 'control_layer', layerName: layer.name }));
- }
- const { adapter } = layer;
- // Readiness skips control checks until models load; resolving against nothing would drop or misjudge layers.
- if (!judge) {
- throw new ControlLayerValidationError('models_unavailable', layer.name);
- }
- const { reason, resolution, skip } = judge(layer);
- if (skip) {
- return false;
- }
- const resolved = resolution.model;
- if (reason || !resolved) {
- throw new ControlLayerValidationError(reason ?? 'missing_model', layer.name);
- }
- metadata.set(layer.id, {
- beginEndStepPct: adapter.beginEndStepPct,
- controlMode: adapter.controlMode,
- id: layer.id,
- instantxControlMode: resolution.instantxControlMode,
- kind: resolution.kind,
- model: {
- base: resolved.base,
- key: resolved.key,
- name: resolved.name,
- type: resolved.type,
- ...(typeof resolved.hash === 'string' ? { hash: resolved.hash } : {}),
- },
- modelCondInChannels: resolved.cond_in_channels,
- modelControlArchitecture: resolved.control_architecture,
- weight: adapter.weight,
- });
- return true;
- },
- toGraphInputs: (images) =>
- images.flatMap(({ imageName, layerId }) => {
- const meta = metadata.get(layerId);
- return meta ? [{ ...meta, imageName }] : [];
- }),
- };
-};
-
-/** FLUX Redux image-influence → backend redux settings (mirrors `graph.ts` FLUX_REDUX_INFLUENCE). */
-const FLUX_REDUX_INFLUENCE_SETTINGS = {
- lowest: { downsampling_factor: 5, weight: 1 },
- low: { downsampling_factor: 4, weight: 1 },
- medium: { downsampling_factor: 3, weight: 1 },
- high: { downsampling_factor: 2, weight: 1 },
- highest: { downsampling_factor: 1, weight: 1 },
-} as const;
-
-/** Resolves a regional-guidance layer's reference images into graph inputs (drops incomplete/incompatible ones). */
-export const resolveRegionalReferenceImages = (
- region: { referenceImages: RegionalGuidanceReferenceImage[] },
- base: string
-): RegionalReferenceImageInput[] => {
- const inputs: RegionalReferenceImageInput[] = [];
- const kind = getRegionalGuidanceSupport(base)?.referenceImages ?? null;
- for (const ref of region.referenceImages) {
- if (!ref.isEnabled) {
- continue;
- }
- const { config } = ref;
- if (config.type === 'ip_adapter' && kind === 'ip_adapter') {
- if (!config.image || !config.model || config.model.base !== base) {
- continue;
- }
- inputs.push({
- beginEndStepPct: config.beginEndStepPct,
- clipVisionModel: config.clipVisionModel,
- id: ref.id,
- imageName: config.image.imageName,
- method: config.method,
- model: {
- base: config.model.base,
- key: config.model.key,
- name: config.model.name,
- type: config.model.type,
- ...(typeof config.model.hash === 'string' ? { hash: config.model.hash } : {}),
- },
- type: 'ip_adapter',
- weight: config.weight,
- });
- } else if (config.type === 'flux_redux' && kind === 'flux_redux') {
- if (!config.image || !config.model || config.model.base !== base) {
- continue;
- }
- inputs.push({
- id: ref.id,
- imageName: config.image.imageName,
- model: {
- base: config.model.base,
- key: config.model.key,
- name: config.model.name,
- type: config.model.type,
- ...(typeof config.model.hash === 'string' ? { hash: config.model.hash } : {}),
- },
- settings: FLUX_REDUX_INFLUENCE_SETTINGS[config.imageInfluence],
- type: 'flux_redux',
- });
- }
+const admitLayer = <Verdict extends ControlLayerVerdict | RegionalLayerVerdict>(
+ verdict: Verdict,
+ layerId: string,
+ inputs: Map<string, Extract<Verdict, { status: 'contributes' }>['input']>
+): boolean => {
+ if (verdict.status === 'contributes') {
+ inputs.set(layerId, verdict.input);
+ return true;
}
- return inputs;
-};
-
-/** Rejects hosted-provider regions; skips unsupported or noncontributing local ones. */
-const createRegionalGuidanceCollector = (
- model: GenerateModelConfig,
- cfgScale: number
-): {
- shouldComposite(layer: CanvasRegionalGuidanceLayerContract): boolean;
- toGraphInputs(
- images: readonly { layerId: string; imageName: string; bounds: RegionalGuidanceInput['maskBounds'] }[]
- ): RegionalGuidanceInput[];
-} => {
- const metadata = new Map<string, Omit<RegionalGuidanceInput, 'maskImageName' | 'maskBounds'>>();
-
- return {
- shouldComposite: (layer) => {
- if (model.type === 'external_image_generator') {
- throw new Error(describeExternalCanvasRefusal(model, { kind: 'regional_guidance', layerName: layer.name }));
- }
- const referenceImages = resolveRegionalReferenceImages(layer, model.base);
- const rejection = getRegionalGuidanceRejectionReason({
- cfgScale,
- hasContent: true,
- layerName: layer.name,
- layout: layer.layout,
- mainBase: model.base,
- negativePrompt: layer.negativePrompt,
- positivePrompt: layer.positivePrompt,
- referenceImageCount: referenceImages.length,
- });
- if (rejection) {
- return false;
- }
- metadata.set(layer.id, {
- autoNegative: layer.autoNegative,
- id: layer.id,
- // Typed against Generation's layout roles: a persisted role the graph cannot send fails to compile here.
- ...(layer.layout ? { layout: layer.layout } : {}),
- negativePrompt: layer.negativePrompt,
- positivePrompt: layer.positivePrompt,
- referenceImages,
- });
- return true;
- },
- toGraphInputs: (images) =>
- images.flatMap(({ bounds, imageName, layerId }) => {
- const meta = metadata.get(layerId);
- return meta ? [{ ...meta, maskBounds: bounds, maskImageName: imageName }] : [];
- }),
- };
-};
-
-/** Why generation refused a layer's or group's Clarity, Texture or Dehaze, which it never leaves out. */
-const ADJUSTMENT_REFUSAL_NOTICES: Record<'too-large' | 'over-budget' | 'error', (name: string) => string> = {
- error: (name) =>
- `Clarity, Texture or Dehaze failed on “${name}”. Change a setting or disable them, then invoke again.`,
- 'over-budget': (name) =>
- `Not enough canvas memory to apply Clarity, Texture or Dehaze to “${name}”. Delete layers you no longer need, then invoke again.`,
- 'too-large': (name) =>
- `Clarity, Texture and Dehaze can’t run on “${name}”: its content is larger than 16.8 megapixels (4096 × 4096 px). Disable or remove them, or crop the content, then invoke again.`,
+ if (verdict.status === 'skipped') {
+ return false;
+ }
+ throw new CanvasInputRefusal(verdict.issue);
};
/** Never throws: failures become notices and the in-flight guard always clears. */
@@ -313,7 +119,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
try {
const values = normalizeGenerateWidgetValues(deps.generateValues);
if (!values) {
- recordNotice(commands.notifications, 'error', 'Select a supported model before invoking the canvas.');
+ recordFailure(commands.notifications, deps.formatCanvasInvocationFailure, { kind: 'no_model' });
return;
}
@@ -325,8 +131,14 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
// Flush persisted paint before capture so planning sees current bitmap references and bbox.
await deps.flushPendingUploads();
- const controls = createControlLayerCollector(model, deps.models, deps.controlModelMemory);
- const regions = createRegionalGuidanceCollector(model, settings.cfgScale);
+ const judge = createCanvasInputJudge({
+ cfgScale: settings.cfgScale,
+ controlModelMemory: deps.controlModelMemory,
+ model,
+ models: deps.models,
+ });
+ const controlInputs = new Map<string, Omit<ControlLayerGraphInput, 'imageName'>>();
+ const regionalInputs = new Map<string, Omit<RegionalGuidanceInput, 'maskImageName' | 'maskBounds'>>();
const composed = await deps.composeForGeneration({
// Mode-union drift guard: `detectCanvasMode`'s facts/mode types must stay structurally identical to
// canvas-operations' `GenerationModeFacts` / `GenerationCompositeMode` — tsc fails here on drift in either
@@ -334,36 +146,23 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
// frame with nothing visible inside it leave an empty frame, which it generates from text.
detectMode: (facts) =>
model.type === 'external_image_generator' && !facts.bboxHasContent ? 'txt2img' : detectCanvasMode(facts),
- shouldCompositeControlLayer: controls.shouldComposite,
- shouldCompositeRegionalMask: regions.shouldComposite,
+ shouldCompositeControlLayer: (layer) => admitLayer(judge.control(layer), layer.id, controlInputs),
+ shouldCompositeRegionalMask: (layer) => admitLayer(judge.regional(layer), layer.id, regionalInputs),
signal: deps.signal,
});
deps.signal.throwIfAborted();
if (composed.status !== 'ok') {
- recordNotice(
- commands.notifications,
- 'error',
- composed.status === 'no-document'
- ? 'The canvas has no active document to generate from.'
- : composed.status === 'stale'
- ? 'The canvas changed while generation was being prepared. Please invoke again.'
- : composed.status === 'adjustment-refused'
- ? ADJUSTMENT_REFUSAL_NOTICES[composed.reason](composed.ownerName)
- : composed.status === 'unreadable'
- ? `“${composed.layerName}” could not be read (its image may have been deleted or damaged). Disable or delete that layer, then invoke again.`
- : composed.status === 'not-ready'
- ? 'Some layers are still loading. Wait a moment, then invoke again.'
- : composed.status === 'over-budget'
- ? 'Generation exceeds the browser’s canvas-memory limit. Try again after layers finish loading. If it still fails, crop or resize large source images, or disable unnecessary layers. A smaller generation frame alone may not help.'
- : `The canvas could not be captured for generation (${composed.status}).`
- );
+ recordFailure(commands.notifications, deps.formatCanvasInvocationFailure, { kind: 'capture', result: composed });
return;
}
const { composites } = composed;
// The other half of the mode-union drift guard (see `detectMode` above).
const mode: CanvasCompileMode = composites.mode;
- const controlLayers = controls.toGraphInputs(composites.controlImages);
+ const controlLayers = composites.controlImages.flatMap(({ imageName, layerId }) => {
+ const input = controlInputs.get(layerId);
+ return input ? [{ ...input, imageName }] : [];
+ });
const compiled = compileCanvasGraph({
canvasMetadata: recordCanvasMetadata(composites.canvas.document, {
controls: controlLayers,
@@ -381,7 +180,10 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
noiseMaskImageName: composites.noiseMaskImageName,
projectSettings: deps.projectSettings,
randDevice: deps.randDevice,
- regionalGuidance: regions.toGraphInputs(composites.regionalMaskImages),
+ regionalGuidance: composites.regionalMaskImages.flatMap(({ bounds, imageName, layerId }) => {
+ const input = regionalInputs.get(layerId);
+ return input ? [{ ...input, maskBounds: bounds, maskImageName: imageName }] : [];
+ }),
scaling: deps.scaling,
settings,
strength: deps.strength,
@@ -408,13 +210,13 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
return;
}
- const message =
- error instanceof ControlLayerValidationError
- ? deps.formatControlLayerError(error)
- : error instanceof Error
- ? error.message
- : String(error);
- recordNotice(commands.notifications, 'error', message);
+ recordFailure(
+ commands.notifications,
+ deps.formatCanvasInvocationFailure,
+ error instanceof CanvasInputRefusal
+ ? { issue: error.issue, kind: 'canvas_input' }
+ : { kind: 'error', message: error instanceof Error ? error.message : String(error) }
+ );
} finally {
inFlight.delete(inFlightKey);
}
@@ -448,7 +250,7 @@ export interface PrepareCanvasInvocationArgs {
/** Persisted compositing settings, already defaulted and clamped by the caller; legacy defaults when omitted. */
compositing?: CanvasCompositingSettings;
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
- formatControlLayerError: (rejection: ControlLayerRejection) => string;
+ formatCanvasInvocationFailure: RunCanvasInvocationDeps['formatCanvasInvocationFailure'];
}
/** Settles after dispatch or a reported failure, keeping the preparing acknowledgement until queued. */
@@ -460,7 +262,7 @@ export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs)
const engine = getCanvasEngine(args.projectId);
if (!engine) {
- recordNotice(args.commands.notifications, 'error', 'Open the canvas before invoking it.');
+ recordFailure(args.commands.notifications, args.formatCanvasInvocationFailure, { kind: 'canvas_not_open' });
return;
}
const operations = getCanvasOperations(engine);
@@ -474,7 +276,7 @@ export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs)
composeForGeneration: (composeOptions) => operations.composeForGeneration(composeOptions),
controlModelMemory: getWorkbenchPreferences().controlModelMemory,
flushPendingUploads: () => engine.lifecycle.flushPendingUploads(),
- formatControlLayerError: args.formatControlLayerError,
+ formatCanvasInvocationFailure: args.formatCanvasInvocationFailure,
generateValues: args.generateValues,
inFlight: inFlightProjects,
inFlightKey: `${owner.epoch}:${args.projectId}`,