Skip to content

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

feat(webv2): find conditioning media in the gallery from its thumbnail

Lincoln Stein90d31952d195
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 66bfbf61fe..dfe6d67396 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,10 +2,10 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 859335,
+ "brotliBytes": 859351,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 858507,
+ "gzipBytes": 858522,
"imageRawBytes": 156376,
"initialRawBytes": 2010911,
"largestAssetRawBytes": 747218,
@@ -311,10 +311,10 @@
]
},
"limits": {
- "brotliBytes": 867929,
+ "brotliBytes": 867945,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 867093,
+ "gzipBytes": 867108,
"imageRawBytes": 157940,
"initialRawBytes": 2031021,
"largestAssetRawBytes": 754691,
@@ -329,15 +329,15 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1182691,
+ "brotliBytes": 1183096,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1176792,
+ "gzipBytes": 1177212,
"imageRawBytes": 156376,
- "initialRawBytes": 2993632,
+ "initialRawBytes": 2994831,
"largestAssetRawBytes": 747218,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 133058,
+ "ownedRawBytes": 134160,
"requestCount": 106,
"scriptRequestCount": 90,
"sourceOwners": [
@@ -828,6 +828,7 @@
"source:src/workbench/hotkeys/targetWidget.ts",
"source:src/workbench/iconResolver.tsx",
"source:src/workbench/image-actions/recallParametersBridge.ts",
+ "source:src/workbench/image-actions/useFindGalleryItem.ts",
"source:src/workbench/invocation.ts",
"source:src/workbench/invocationSubmit.ts",
"source:src/workbench/launchpad/HelpMenu.tsx",
@@ -1026,15 +1027,15 @@
]
},
"limits": {
- "brotliBytes": 1194518,
+ "brotliBytes": 1194927,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1188560,
+ "gzipBytes": 1188985,
"imageRawBytes": 157940,
- "initialRawBytes": 3023569,
+ "initialRawBytes": 3024780,
"largestAssetRawBytes": 754691,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 133058,
+ "ownedRawBytes": 134160,
"requestCount": 106,
"scriptRequestCount": 90
},
@@ -1043,7 +1044,7 @@
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-09-13",
+ "capturedAt": "2026-09-14",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 878275812a..4c78a5c7c2 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1,6 +1,6 @@
{
"browserExecutable": "/home/lstein/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome",
- "capturedAt": "2026-09-13",
+ "capturedAt": "2026-09-14",
"routes": [
{
"activatedResourceBaseline": {
@@ -25,13 +25,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 104,
+ "domContentLoadedMedianMs": 94.70000004768372,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 104.19999992847443,
- "longestTaskMaxMs": 75,
+ "loadMedianMs": 94.70000004768372,
+ "longestTaskMaxMs": 57,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -41,24 +41,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 39,
- "scriptRawBytes": 1692314,
+ "scriptRawBytes": 1692362,
"scriptRequestCount": 35,
- "totalRawBytes": 1871108
+ "totalRawBytes": 1871238
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 39,
- "scriptRawBytes": 1709238,
+ "scriptRawBytes": 1709286,
"scriptRequestCount": 35,
- "totalRawBytes": 1889820
+ "totalRawBytes": 1889951
},
- "routeReadyMedianMs": 237.29999995231628,
+ "routeReadyMedianMs": 218.60000002384186,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -85,13 +85,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 98.60000002384186,
+ "domContentLoadedMedianMs": 94.60000002384186,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 98.69999992847443,
- "longestTaskMaxMs": 66,
+ "loadMedianMs": 94.79999995231628,
+ "longestTaskMaxMs": 56,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -101,24 +101,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 39,
- "scriptRawBytes": 1692314,
+ "scriptRawBytes": 1692362,
"scriptRequestCount": 35,
- "totalRawBytes": 1871108
+ "totalRawBytes": 1871238
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 39,
- "scriptRawBytes": 1709238,
+ "scriptRawBytes": 1709286,
"scriptRequestCount": 35,
- "totalRawBytes": 1889820
+ "totalRawBytes": 1889951
},
- "routeReadyMedianMs": 244.69999992847443,
+ "routeReadyMedianMs": 227.5,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -145,15 +145,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 98.5,
+ "domContentLoadedMedianMs": 96.10000002384186,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 98.70000004768372,
- "longestTaskMaxMs": 111,
+ "loadMedianMs": 96.20000004768372,
+ "longestTaskMaxMs": 106,
"owner": "workbench",
- "projectSwitchMedianMs": 32.699999928474426,
+ "projectSwitchMedianMs": 30.899999976158142,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -161,24 +161,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 122,
- "scriptRawBytes": 3549693,
+ "scriptRawBytes": 3552481,
"scriptRequestCount": 117,
- "totalRawBytes": 3884863
+ "totalRawBytes": 3887733
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 122,
- "scriptRawBytes": 3585190,
+ "scriptRawBytes": 3588006,
"scriptRequestCount": 117,
- "totalRawBytes": 3923712
+ "totalRawBytes": 3926611
},
- "routeReadyMedianMs": 372.8000000715256,
+ "routeReadyMedianMs": 361.7000000476837,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -205,15 +205,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 97.80000007152557,
+ "domContentLoadedMedianMs": 94.89999997615814,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 97.80000007152557,
- "longestTaskMaxMs": 112,
+ "loadMedianMs": 95,
+ "longestTaskMaxMs": 100,
"owner": "workbench",
- "projectSwitchMedianMs": 38.5,
+ "projectSwitchMedianMs": 35.89999997615814,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -221,24 +221,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 122,
- "scriptRawBytes": 3549693,
+ "scriptRawBytes": 3552481,
"scriptRequestCount": 117,
- "totalRawBytes": 3884863
+ "totalRawBytes": 3887733
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 122,
- "scriptRawBytes": 3585190,
+ "scriptRawBytes": 3588006,
"scriptRequestCount": 117,
- "totalRawBytes": 3923712
+ "totalRawBytes": 3926611
},
- "routeReadyMedianMs": 379.7999999523163,
+ "routeReadyMedianMs": 363.2000000476837,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -265,13 +265,13 @@
"scriptRequestCount": 10,
"totalRawBytes": 506663
},
- "domContentLoadedMedianMs": 96.39999997615814,
+ "domContentLoadedMedianMs": 97.39999997615814,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.700000047683716,
- "layoutReturnSwitchMedianMs": 52.60000002384186,
- "layoutSwitchMedianMs": 86.10000002384186,
- "loadMedianMs": 96.5,
- "longestTaskMaxMs": 133,
+ "layoutAckMedianMs": 2.100000023841858,
+ "layoutReturnSwitchMedianMs": 50.60000002384186,
+ "layoutSwitchMedianMs": 79.79999995231628,
+ "loadMedianMs": 97.5,
+ "longestTaskMaxMs": 122,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -281,24 +281,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 132,
- "scriptRawBytes": 4051339,
+ "scriptRawBytes": 4054127,
"scriptRequestCount": 127,
- "totalRawBytes": 4386509
+ "totalRawBytes": 4389379
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 132,
- "scriptRawBytes": 4091853,
+ "scriptRawBytes": 4094669,
"scriptRequestCount": 127,
- "totalRawBytes": 4430375
+ "totalRawBytes": 4433273
},
- "routeReadyMedianMs": 1051.5,
+ "routeReadyMedianMs": 1037.8000000715256,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -325,12 +325,12 @@
"scriptRequestCount": 10,
"totalRawBytes": 506663
},
- "domContentLoadedMedianMs": 101.60000002384186,
+ "domContentLoadedMedianMs": 96,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.899999976158142,
- "layoutReturnSwitchMedianMs": 47.299999952316284,
- "layoutSwitchMedianMs": 81.19999992847443,
- "loadMedianMs": 101.70000004768372,
+ "layoutAckMedianMs": 3.6999999284744263,
+ "layoutReturnSwitchMedianMs": 47.199999928474426,
+ "layoutSwitchMedianMs": 77.5,
+ "loadMedianMs": 96.20000004768372,
"longestTaskMaxMs": 159,
"owner": "canvas",
"projectSwitchMedianMs": 0,
@@ -341,24 +341,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 132,
- "scriptRawBytes": 4051339,
+ "scriptRawBytes": 4054127,
"scriptRequestCount": 127,
- "totalRawBytes": 4386509
+ "totalRawBytes": 4389379
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 132,
- "scriptRawBytes": 4091853,
+ "scriptRawBytes": 4094669,
"scriptRequestCount": 127,
- "totalRawBytes": 4430375
+ "totalRawBytes": 4433273
},
- "routeReadyMedianMs": 1060.3000000715256,
+ "routeReadyMedianMs": 1058.0999999046326,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -385,13 +385,13 @@
"scriptRequestCount": 6,
"totalRawBytes": 387535
},
- "domContentLoadedMedianMs": 103.29999995231628,
+ "domContentLoadedMedianMs": 96.70000004768372,
"id": "editor-workflow",
- "layoutAckMedianMs": 1.9000000953674316,
- "layoutReturnSwitchMedianMs": 30.399999976158142,
- "layoutSwitchMedianMs": 78.59999990463257,
- "loadMedianMs": 103.39999997615814,
- "longestTaskMaxMs": 112,
+ "layoutAckMedianMs": 1.899999976158142,
+ "layoutReturnSwitchMedianMs": 29.899999976158142,
+ "layoutSwitchMedianMs": 77.60000002384186,
+ "loadMedianMs": 96.90000009536743,
+ "longestTaskMaxMs": 111,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -401,24 +401,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 129,
- "scriptRawBytes": 3917978,
+ "scriptRawBytes": 3920766,
"scriptRequestCount": 123,
- "totalRawBytes": 4268561
+ "totalRawBytes": 4271431
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 129,
- "scriptRawBytes": 3957158,
+ "scriptRawBytes": 3959974,
"scriptRequestCount": 123,
- "totalRawBytes": 4311247
+ "totalRawBytes": 4314146
},
- "routeReadyMedianMs": 1048.3999999761581,
+ "routeReadyMedianMs": 1034.7000000476837,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -445,13 +445,13 @@
"scriptRequestCount": 6,
"totalRawBytes": 387535
},
- "domContentLoadedMedianMs": 100.60000002384186,
+ "domContentLoadedMedianMs": 98.60000002384186,
"id": "editor-workflow",
- "layoutAckMedianMs": 3.6999999284744263,
- "layoutReturnSwitchMedianMs": 36.89999997615814,
- "layoutSwitchMedianMs": 108.5,
- "loadMedianMs": 100.69999992847443,
- "longestTaskMaxMs": 294,
+ "layoutAckMedianMs": 3.399999976158142,
+ "layoutReturnSwitchMedianMs": 35.5,
+ "layoutSwitchMedianMs": 109.79999995231628,
+ "loadMedianMs": 98.70000004768372,
+ "longestTaskMaxMs": 285,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -461,24 +461,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 129,
- "scriptRawBytes": 3917978,
+ "scriptRawBytes": 3920766,
"scriptRequestCount": 123,
- "totalRawBytes": 4268561
+ "totalRawBytes": 4271431
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 129,
- "scriptRawBytes": 3957158,
+ "scriptRawBytes": 3959974,
"scriptRequestCount": 123,
- "totalRawBytes": 4311247
+ "totalRawBytes": 4314146
},
- "routeReadyMedianMs": 1107.3000000715256,
+ "routeReadyMedianMs": 1091.2999999523163,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -505,13 +505,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 103.30000007152557,
+ "domContentLoadedMedianMs": 93.79999995231628,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 23.899999976158142,
- "loadMedianMs": 103.40000009536743,
- "longestTaskMaxMs": 112,
+ "layoutSwitchMedianMs": 20.899999976158142,
+ "loadMedianMs": 93.89999997615814,
+ "longestTaskMaxMs": 109,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -521,24 +521,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 122,
- "scriptRawBytes": 3549693,
+ "scriptRawBytes": 3552481,
"scriptRequestCount": 117,
- "totalRawBytes": 3884863
+ "totalRawBytes": 3887733
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 122,
- "scriptRawBytes": 3585190,
+ "scriptRawBytes": 3588006,
"scriptRequestCount": 117,
- "totalRawBytes": 3923712
+ "totalRawBytes": 3926611
},
- "routeReadyMedianMs": 1259.5,
+ "routeReadyMedianMs": 1234.7000000476837,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -565,12 +565,12 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 101.69999992847443,
+ "domContentLoadedMedianMs": 95.89999997615814,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 33,
- "loadMedianMs": 101.79999995231628,
+ "layoutSwitchMedianMs": 28.200000047683716,
+ "loadMedianMs": 96,
"longestTaskMaxMs": 102,
"owner": "gallery",
"projectSwitchMedianMs": 0,
@@ -581,24 +581,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 747218,
- "otherRawBytes": 152971,
+ "otherRawBytes": 153053,
"requestCount": 122,
- "scriptRawBytes": 3549693,
+ "scriptRawBytes": 3552481,
"scriptRequestCount": 117,
- "totalRawBytes": 3884863
+ "totalRawBytes": 3887733
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 754691,
- "otherRawBytes": 154501,
+ "otherRawBytes": 154584,
"requestCount": 122,
- "scriptRawBytes": 3585190,
+ "scriptRawBytes": 3588006,
"scriptRequestCount": 117,
- "totalRawBytes": 3923712
+ "totalRawBytes": 3926611
},
- "routeReadyMedianMs": 1278.0999999046326,
+ "routeReadyMedianMs": 1259.2000000476837,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1102,6 +1102,7 @@
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
"source:src/features/gallery/settingsContribution.ts",
+ "source:src/features/gallery/ui/FindInGalleryButton.tsx",
"source:src/features/gallery/ui/GalleryBoardCover.tsx",
"source:src/features/gallery/ui/GalleryBoardDragMonitor.tsx",
"source:src/features/gallery/ui/GalleryBoardFilters.tsx",
@@ -1722,6 +1723,7 @@
"source:src/workbench/image-actions/recallParametersBridge.ts",
"source:src/workbench/image-actions/selectedImage.ts",
"source:src/workbench/image-actions/useDeletionConfirmation.tsx",
+ "source:src/workbench/image-actions/useFindGalleryItem.ts",
"source:src/workbench/image-actions/useImageActions.ts",
"source:src/workbench/image-actions/videoRecall.ts",
"source:src/workbench/image-map/api.ts",
@@ -2120,6 +2122,7 @@
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
"source:src/features/gallery/settingsContribution.ts",
+ "source:src/features/gallery/ui/FindInGalleryButton.tsx",
"source:src/features/gallery/ui/GalleryBoardCover.tsx",
"source:src/features/gallery/ui/GalleryBoardDragMonitor.tsx",
"source:src/features/gallery/ui/GalleryBoardFilters.tsx",
@@ -2757,6 +2760,7 @@
"source:src/workbench/image-actions/recallParametersBridge.ts",
"source:src/workbench/image-actions/selectedImage.ts",
"source:src/workbench/image-actions/useDeletionConfirmation.tsx",
+ "source:src/workbench/image-actions/useFindGalleryItem.ts",
"source:src/workbench/image-actions/useImageActions.ts",
"source:src/workbench/image-actions/videoRecall.ts",
"source:src/workbench/image-map/api.ts",
@@ -3308,6 +3312,7 @@
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
"source:src/features/gallery/settingsContribution.ts",
+ "source:src/features/gallery/ui/FindInGalleryButton.tsx",
"source:src/features/gallery/ui/GalleryBoardCover.tsx",
"source:src/features/gallery/ui/GalleryBoardDragMonitor.tsx",
"source:src/features/gallery/ui/GalleryBoardFilters.tsx",
@@ -3995,6 +4000,7 @@
"source:src/workbench/image-actions/recallParametersBridge.ts",
"source:src/workbench/image-actions/selectedImage.ts",
"source:src/workbench/image-actions/useDeletionConfirmation.tsx",
+ "source:src/workbench/image-actions/useFindGalleryItem.ts",
"source:src/workbench/image-actions/useImageActions.ts",
"source:src/workbench/image-actions/videoRecall.ts",
"source:src/workbench/image-map/api.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 7361441384..0d0a03c452 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3599,6 +3599,8 @@
"exportProjectFromBoard": "Export project (.invk)",
"expandStarredItems": "Expand starred items",
"filterAndSortBoards": "Filter & sort boards",
+ "findInGallery": "Find in Gallery",
+ "findNamedInGallery": "Find {{name}} in Gallery",
"generationProgress": "Generation progress",
"generationProgressPercent": "Generation {{percentage}}%",
"imageCount_one": "{{count}} image",
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
index 9bbe2a8525..d95e7e5304 100644
--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
@@ -18,6 +18,7 @@ import {
import { createUuid } from '@platform/browser/randomUuid';
import { useMountEffect } from '@platform/react/useMountEffect';
import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';
import {
getWorkbenchPreferences,
patchWorkbenchPreferences,
@@ -26,7 +27,7 @@ import {
import { useNotify } from '@workbench/useNotify';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
-import { lazy, useMemo } from 'react';
+import { lazy, useCallback, useMemo } from 'react';
export const getGenerationSelectedGalleryImage = getSelectedGalleryImageFromValues;
@@ -142,12 +143,22 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
const session = useAuthSession();
const queryClient = useQueryClient();
const notify = useNotify();
+ const findGalleryItem = useFindGalleryItem();
+ // Hoisted out of the group: the group's identity turns over on every gallery
+ // selection change, and the reference-image cards are memoized against
+ // exactly that — a fresh handler per selection would re-render the whole
+ // stack, model pickers and all, on every click in the grid.
+ const findImage = useCallback<GenerationUiAdapter['gallery']['findImage']>(
+ (imageName) => findGalleryItem({ kind: 'image', name: imageName }),
+ [findGalleryItem]
+ );
const galleryGroup = useMemo<GenerationUiAdapter['gallery']>(
() => ({
+ findImage,
selectedImage: selectedGalleryImage,
touchImages: () => void invalidateGallery(queryClient),
}),
- [queryClient, selectedGalleryImage]
+ [findImage, queryClient, selectedGalleryImage]
);
const modelsGroup = useMemo<GenerationUiAdapter['models']>(
() => ({
diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx
index 3f16844d15..5cd9fd3978 100644
--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx
@@ -1,8 +1,9 @@
-import type { GalleryVideoItem } from '@features/gallery';
+import type { GalleryItemRef, GalleryVideoItem } from '@features/gallery';
import type { VideoUiAdapter } from '@features/video';
import type { OpenWorkbenchWidgetResult } from '@workbench/useOpenWorkbenchWidget';
import type { ReactNode } from 'react';
+import { claimGalleryNavigationSequence } from '@features/gallery/contracts';
import { getGalleryRevealRequest } from '@features/gallery/core/selection';
import {
clearVideoSpanPlaybackState,
@@ -32,6 +33,12 @@ let activeProjectId: string;
const openWorkbenchWidget = vi.fn(() => openResult);
const selectItem = vi.fn();
+const reportError = vi.fn();
+const revealGalleryItem = vi.fn(
+ (_context: unknown, _ref: GalleryItemRef, _ticket: { projectId: string; sequence: number }) => Promise.resolve()
+);
+/** The regions the project's single gallery instance occupies. */
+let galleryRegions: string[] = ['right'];
vi.mock('@features/video', () => ({
VideoUiProvider: ({ adapter: next, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {
@@ -40,6 +47,9 @@ vi.mock('@features/video', () => ({
},
}));
vi.mock('@features/gallery/queries', () => ({ invalidateGallery: vi.fn() }));
+// What a landed reveal does to the grid belongs to `useSelectMapImage.browser.test.tsx`;
+// this file is about which gestures move the user's selection at all.
+vi.mock('@workbench/image-actions/revealGalleryItem', () => ({ revealGalleryItem }));
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({}) }));
vi.mock('@workbench/settings/store', () => ({ useWorkbenchPreferenceSelector: () => false }));
vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => openWorkbenchWidget }));
@@ -48,9 +58,24 @@ vi.mock('@workbench/WorkbenchContext', () => ({
selector({ id: activeProjectId, widgetInstances: {} }),
useWorkbenchCommands: () => ({
gallery: { selectItem },
- notifications: { reportError: vi.fn() },
+ notifications: { reportError },
widgets: { patchValues: vi.fn() },
}),
+ useWorkbenchQueries: () => ({
+ isActiveProject: (projectId: string) => projectId === activeProjectId,
+ getSnapshot: () => ({
+ activeProject: {
+ id: activeProjectId,
+ widgetInstances: { 'gallery-1': { typeId: 'gallery' } },
+ widgetRegions: Object.fromEntries(
+ (['left', 'right', 'bottom', 'center'] as const).map((region) => [
+ region,
+ { instanceIds: galleryRegions.includes(region) ? ['gallery-1'] : [] },
+ ])
+ ),
+ },
+ }),
+ }),
}));
const videoItem = { kind: 'video', name: 'clip.mp4' } as unknown as GalleryVideoItem;
@@ -69,6 +94,9 @@ beforeEach(async () => {
activeProjectId = 'project-1';
openWorkbenchWidget.mockClear();
selectItem.mockClear();
+ revealGalleryItem.mockClear();
+ reportError.mockClear();
+ galleryRegions = ['right'];
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -104,6 +132,85 @@ describe('videoSpanPlayback', () => {
});
});
+describe('findInGallery', () => {
+ it('raises the grid where it already lives, not where the manifest would place it', async () => {
+ act(() => adapter.findInGallery({ kind: 'video', name: 'clip.mp4' }));
+
+ // Unlike a play press, a find IS a request to rearrange the workspace: the
+ // panel is the far side of the app from the grid, and a selection the user
+ // cannot see is not a find. But an unqualified open resolves to `center`
+ // off the manifest and the reducer ADOPTS the existing instance there
+ // without vacating the right panel, listing one grid in two regions.
+ // Preview goes first so the grid wins a region they might share.
+ expect(openWorkbenchWidget.mock.calls).toEqual([
+ ['preview', { preferredRegions: ['center'], requireCenterView: true }],
+ ['gallery', { preferredRegions: ['right'] }],
+ ]);
+
+ await vi.waitFor(() => expect(revealGalleryItem).toHaveBeenCalledTimes(1));
+
+ expect(revealGalleryItem.mock.calls[0]?.[1]).toEqual({ kind: 'video', name: 'clip.mp4' });
+ });
+
+ it('falls back to default placement when the project has no grid at all', async () => {
+ galleryRegions = [];
+ await renderAdapter();
+
+ act(() => adapter.findInGallery({ kind: 'image', name: 'still.png' }));
+
+ expect(openWorkbenchWidget.mock.calls.at(-1)).toEqual(['gallery', undefined]);
+ });
+
+ it('describes the press, not the moment its chunk lands', async () => {
+ // The reveal module is fetched lazily; the image map's, statically imported
+ // inside an already-loaded chunk, claims synchronously. A ticket minted
+ // after the import would let a map click made AFTER this press supersede
+ // it, and would fence the reveal to whichever project the user had reached
+ // by then — the exact write the fence exists to stop.
+ const before = claimGalleryNavigationSequence();
+
+ act(() => adapter.findInGallery({ kind: 'image', name: 'still.png' }));
+
+ const afterPress = claimGalleryNavigationSequence();
+
+ activeProjectId = 'project-2';
+ await renderAdapter();
+
+ await vi.waitFor(() => expect(revealGalleryItem).toHaveBeenCalledTimes(1));
+
+ expect(revealGalleryItem.mock.calls[0]?.[2]).toEqual({ projectId: 'project-1', sequence: before + 1 });
+ expect(afterPress).toBe(before + 2);
+ });
+
+ it('tells the user when the media cannot be revealed', async () => {
+ revealGalleryItem.mockReturnValueOnce(Promise.reject(new Error('Image not found')));
+
+ act(() => adapter.findInGallery({ kind: 'image', name: 'deleted.png' }));
+
+ // The widgets are already raised by then, so a silent failure leaves a
+ // rearranged workspace and no account of why the grid did not move.
+ await vi.waitFor(() =>
+ expect(reportError).toHaveBeenCalledWith({
+ area: 'find-in-gallery',
+ message: 'Image not found',
+ namespace: 'gallery',
+ })
+ );
+ });
+
+ it('says nothing about a failed gesture the user has already moved past', async () => {
+ revealGalleryItem.mockReturnValueOnce(Promise.reject(new Error('Image not found')));
+
+ act(() => adapter.findInGallery({ kind: 'image', name: 'deleted.png' }));
+ // Any later navigation supersedes it — here, a second press.
+ act(() => adapter.findInGallery({ kind: 'image', name: 'other.png' }));
+
+ await vi.waitFor(() => expect(revealGalleryItem).toHaveBeenCalledTimes(2));
+
+ expect(reportError).not.toHaveBeenCalled();
+ });
+});
+
describe('playVideoSpanInPreview', () => {
it('puts the clip in front of the user without disturbing their place in the gallery', () => {
const revealBefore = getGalleryRevealRequest()?.token;
diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
index 8c161949ad..ec09518925 100644
--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
@@ -5,6 +5,7 @@ import { toGalleryItemKey } from '@features/gallery/contracts';
import { invalidateGallery } from '@features/gallery/queries';
import { VideoUiProvider } from '@features/video';
import { useQueryClient } from '@tanstack/react-query';
+import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
import {
@@ -103,9 +104,11 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>
[commands, openWorkbenchWidget, projectId]
);
const getUploadBoardId = useCallback(() => uploadBoardIdRef.current, []);
+ const findInGallery = useFindGalleryItem();
const adapter = useMemo<VideoUiAdapter>(
() => ({
...project,
+ findInGallery,
getUploadBoardId,
patchValues,
playVideoSpanInPreview,
@@ -115,6 +118,7 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>
videoSpanPlayback: VIDEO_SPAN_PLAYBACK_PORT,
}),
[
+ findInGallery,
getUploadBoardId,
patchValues,
playVideoSpanInPreview,
diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
index 64d7c870bb..e17dae3b2c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
@@ -68,9 +68,11 @@ export {
type GallerySelectedImageQuery,
} from './ui/galleryStateView';
export {
+ claimGalleryNavigationSequence,
getGalleryDeletionSuccessor,
getPersistedSelectedGalleryItemKeys,
getSelectedGalleryImageFromValues,
getSelectedGalleryItemFromValues,
+ isGalleryNavigationCurrent,
requestGalleryItemReveal,
} from './core/selection';
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.ts
index fedfe46294..cac198abd0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.ts
@@ -174,3 +174,26 @@ export const subscribeGalleryRevealRequests = (listener: () => void): (() => voi
listeners.delete(listener);
};
};
+
+/*
+ * Navigation ordering. A reveal resolves its item over the network before it
+ * touches anything, so two gestures in flight can land out of order; the newer
+ * one must win. The counter is module-scoped for the same reason the reveal
+ * channel above is: the thing it guards — the gallery selection — is global, so
+ * a per-mount ref leaves a hole whenever a caller unmounts with a hydrate in
+ * flight (switching the right-panel tab away and back), where the abandoned
+ * closure compares against its own dead ref, passes, and overwrites the newer
+ * mount's selection. One counter spans every surface that navigates the grid.
+ *
+ * It lives here rather than beside the reveal that uses it because that module
+ * is loaded on demand, and a caller which defers it still has to take its place
+ * in the ordering at the moment of the press.
+ */
+
+let navigationSequence = 0;
+
+/** Claims this navigation's place in the global ordering; every later claim supersedes it. */
+export const claimGalleryNavigationSequence = (): number => ++navigationSequence;
+
+/** False once a newer navigation has been claimed, which is when a slow hydrate must stand down. */
+export const isGalleryNavigationCurrent = (sequence: number): boolean => sequence === navigationSequence;
diff --git a/invokeai/frontend/webv2/src/features/gallery/mediaSlot.ts b/invokeai/frontend/webv2/src/features/gallery/mediaSlot.ts
index 643efd6530..6a711f7489 100644
--- a/invokeai/frontend/webv2/src/features/gallery/mediaSlot.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/mediaSlot.ts
@@ -1,3 +1,8 @@
+export {
+ FindInGalleryButton,
+ FindInGalleryThumbnailButton,
+ type FindInGalleryButtonProps,
+} from './ui/FindInGalleryButton';
export {
GalleryMediaSlot,
type GalleryMediaSlotLabels,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/FindInGalleryButton.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/FindInGalleryButton.tsx
new file mode 100644
index 0000000000..f77ba82d34
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/FindInGalleryButton.tsx
@@ -0,0 +1,77 @@
+import type { IconButtonProps } from '@platform/ui/Button';
+
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { ImageIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * "Find in gallery", for the panels that condition on media they did not pick
+ * from the grid they are looking at. The mark is the Gallery widget's own rail
+ * icon at control scale, so the badge names its destination.
+ *
+ * Presentation is the caller's: this owns the icon, the accessible name, and
+ * the tooltip, which are what must not drift between the four thumbnails that
+ * offer the gesture.
+ */
+export type FindInGalleryButtonProps = Omit<
+ IconButtonProps,
+ 'aria-label' | 'aria-labelledby' | 'children' | 'onClick'
+> & {
+ /**
+ * The media's file name. A field can show several of these at once (a clip's
+ * two trim bounds, a stack of references), which as bare "Find in Gallery"
+ * buttons are indistinguishable to a screen reader.
+ */
+ name?: string;
+ onFind: () => void;
+};
+
+export const FindInGalleryButton = ({ name, onFind, ...buttonProps }: FindInGalleryButtonProps) => {
+ const { t } = useTranslation();
+ // One string for both: a tooltip that is not part of the accessible name
+ // leaves speech input with nothing to match when the user says what they see.
+ const label =
+ name === undefined ? t('widgets.gallery.findInGallery') : t('widgets.gallery.findNamedInGallery', { name });
+
+ return (
+ <Tooltip content={label}>
+ <IconButton aria-label={label} size="2xs" {...buttonProps} onClick={onFind}>
+ <ImageIcon />
+ </IconButton>
+ </Tooltip>
+ );
+};
+
+// Keyboard users never see a hover, so focus has to reveal it too — and the
+// control is only a tab stop worth having once it is visible, hence the
+// pointer-events pair rather than `display`, which would drop it from the tab
+// order entirely.
+const REVEALED = { opacity: 1, pointerEvents: 'auto' } as const;
+
+/**
+ * The same gesture pinned to the bottom-right corner of a thumbnail and
+ * revealed with it. The host thumbnail supplies `className="group"` and a
+ * positioning context; the solid neutral chip is the workbench's treatment for
+ * a control that has to stay legible over arbitrary imagery.
+ *
+ * The inset is the focus ring's own reach (2px outline, 2px offset): thumbnails
+ * clip their overflow, so anything tighter crops the ring rather than the chip,
+ * and takes the focus indicator with it.
+ */
+export const FindInGalleryThumbnailButton = (buttonProps: FindInGalleryButtonProps) => (
+ <FindInGalleryButton
+ bottom="1"
+ colorPalette="gray"
+ insetInlineEnd="1"
+ opacity={0}
+ pointerEvents="none"
+ position="absolute"
+ transition="opacity var(--wb-motion-duration-medium) ease"
+ variant="solid"
+ zIndex="1"
+ _groupFocusWithin={REVEALED}
+ _groupHover={REVEALED}
+ {...buttonProps}
+ />
+);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
index aa9a65ad13..8bde3e8052 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
@@ -355,6 +355,62 @@ describe('GalleryMediaSlot', () => {
expect(onChange).toHaveBeenCalledExactlyOnceWith(null);
});
+ it('badges the thumbnail with a find control that reveals on focus, pinned inside the tile', async () => {
+ const onFind = vi.fn();
+ const value: GalleryMediaSlotValue = { height: 96, kind: 'image', name: 'chosen.png', width: 128 };
+
+ await renderSlot({ onFind, value });
+
+ const find = host?.querySelector<HTMLButtonElement>(
+ 'button[aria-label="widgets.gallery.findNamedInGallery:chosen.png"]'
+ );
+
+ expect(find).not.toBeNull();
+
+ // Hidden until the slot is hovered or holds focus. A mouse hover cannot be
+ // synthesised, but both come from the same `.group` ancestor, so focus
+ // proves the wiring the badge depends on entirely.
+ expect(getComputedStyle(find!).opacity).toBe('0');
+
+ await act(() => {
+ find!.focus();
+ });
+
+ // Polled: the reveal is a CSS transition, which does not exist to be
+ // awaited until the style recalc that starts it has run.
+ await vi.waitFor(() => expect(getComputedStyle(find!).opacity).toBe('1'));
+
+ // The badge is a SIBLING of the slot's face — the face is a <button> and
+ // may not contain one — so its position is hand-mirrored from the value
+ // row's box metrics. Nothing but this ties the two together.
+ const tile = host?.querySelector('img')?.parentElement?.getBoundingClientRect();
+ const badge = find!.getBoundingClientRect();
+
+ expect(badge.right).toBeLessThanOrEqual(tile!.right);
+ expect(badge.bottom).toBeLessThanOrEqual(tile!.bottom);
+ expect(badge.left).toBeGreaterThanOrEqual(tile!.left);
+ expect(badge.top).toBeGreaterThanOrEqual(tile!.top);
+
+ await interact(() => find!.click());
+
+ expect(onFind).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves the badge off a slot with nothing to reveal', async () => {
+ const value: GalleryMediaSlotValue = { height: 96, kind: 'image', name: 'chosen.png', width: 128 };
+
+ // A slot whose media the gallery does not own (the prompt-template editor
+ // holds its own upload) passes no `onFind`, and an empty slot has nothing
+ // to find — neither may show the badge.
+ await renderSlot({ value });
+
+ expect(host?.querySelector('button[aria-label^="widgets.gallery.findNamedInGallery"]')).toBeNull();
+
+ await renderSlot({ onFind: vi.fn(), value: null });
+
+ expect(host?.querySelector('button[aria-label^="widgets.gallery.findNamedInGallery"]')).toBeNull();
+ });
+
it('stands down while disabled, showing the reason', async () => {
await renderSlot({ disabled: true, disabledReason: 'Frames come from the video' });
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
index ebccb44c7a..ec05d24ecb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.tsx
@@ -7,6 +7,7 @@ import { classifyGalleryUpload, getGalleryItemByRef } from '@features/gallery/da
import { getGalleryImageThumbnailUrl } from '@features/gallery/data/imageUrls';
import { galleryBoardsOptions } from '@features/gallery/data/queries';
import { getGalleryVideoThumbnailUrl } from '@features/gallery/data/videoUrls';
+import { FindInGalleryThumbnailButton } from '@features/gallery/ui/FindInGalleryButton';
import { isGalleryItemDragData, useGalleryItemDroppable } from '@features/gallery/ui/galleryDnd';
import { useGalleryUi } from '@features/gallery/ui/GalleryUiContext';
import { useGalleryUploadAction } from '@features/gallery/ui/useGalleryUploadAction';
@@ -86,6 +87,7 @@ export const GalleryMediaSlot = ({
uploadBoardId = 'none',
value,
onChange,
+ onFind,
onUploadFile,
}: {
accept: GalleryPickerAccept;
@@ -101,6 +103,12 @@ export const GalleryMediaSlot = ({
uploadBoardId?: string | (() => string);
value: GalleryMediaSlotValue | null;
onChange: (item: GalleryItem | null) => void;
+ /**
+ * Reveals the current value in the Gallery grid. Given, the thumbnail carries
+ * a find badge on hover; omitted, it stays a plain preview — a slot holding
+ * media the gallery does not own has nothing to reveal.
+ */
+ onFind?: () => void;
/** Takes an uploaded file directly instead of sending it to the gallery. */
onUploadFile?: (file: File) => void;
}) => {
@@ -228,7 +236,7 @@ export const GalleryMediaSlot = ({
return (
<Stack gap="2">
- <Box ref={setNodeRef} position="relative">
+ <Box ref={setNodeRef} className="group" position="relative">
<GalleryPickerPopover accept={accept} label={labels.choose} onPick={handlePick}>
<DropZone
as="button"
@@ -304,6 +312,19 @@ export const GalleryMediaSlot = ({
)}
</DropZone>
</GalleryPickerPopover>
+ {value && onFind ? (
+ /* A sibling of the slot's face, not a child of it: that face is a
+ <button>, which may not contain another. The row repeats the value
+ row's own box metrics — its height, padding, and tile size — so the
+ badge lands on the thumbnail's corner without measuring anything.
+ It rides a pixel high, by the face's border; nothing a corner badge
+ can show. */
+ <HStack gap="3" h="20" insetInline="0" p="2" pointerEvents="none" position="absolute" top="0">
+ <Box boxSize="16" flexShrink="0" position="relative">
+ <FindInGalleryThumbnailButton name={value.name} onFind={onFind} />
+ </Box>
+ </HStack>
+ ) : null}
<DropTargetOverlay isActive={acceptsActiveDrag} isOver={isOver} label={labels.drop} />
</Box>
<HStack justify="end">
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
index a381bb6aa2..7dc250d223 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
@@ -58,6 +58,12 @@ export interface GenerationUiAdapter {
canManageSharedSystemPrompts: boolean;
};
gallery: {
+ /**
+ * Locate one image in the Gallery grid and put it in front of the user:
+ * the Gallery and Preview widgets come on screen and the grid lands on the
+ * image's board, page, and cell.
+ */
+ findImage(imageName: string): void;
selectedImage: GenerationSelectedImage | null;
touchImages(): void;
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
index 9c721c9a34..57b3928d1f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
@@ -339,6 +339,7 @@ export const GenerateReferenceImagesContent = ({
index={index}
referenceImage={referenceImage}
selectedModel={selectedModel}
+ onFindInGallery={gallery.findImage}
onMove={handleMoveReferenceImage}
onPatch={patchReferenceImage}
onRemove={removeReferenceImage}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx
index 33dc5d7d30..e52b2f7631 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx
@@ -8,6 +8,7 @@ import type {
import type { CSSProperties } from 'react';
import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';
+import { FindInGalleryButton } from '@features/gallery/mediaSlot';
import { getEffectiveReferenceImage } from '@features/generation/core/referenceImage';
import { getReferenceImageUrls } from '@features/generation/data/referenceImageUrls';
import { GenerationModelSelect as ModelSelect } from '@features/generation/ui/GenerationUiContext';
@@ -48,6 +49,7 @@ interface ReferenceImageCardProps {
index: number;
referenceImage: GenerateReferenceImage;
selectedModel: GenerateModelConfig | undefined;
+ onFindInGallery: (imageName: string) => void;
onMove: (id: string, direction: -1 | 1) => void;
onPatch: (id: string, patch: Partial<GenerateReferenceImage>) => void;
onRemove: (id: string) => void;
@@ -57,6 +59,7 @@ interface ReferenceImageCardProps {
const ReferenceImageCardBase = ({
count,
index,
+ onFindInGallery,
onMove,
onPatch,
onRemove,
@@ -224,6 +227,7 @@ const ReferenceImageCardBase = ({
disabled={!isEnabled}
image={config.image}
onCrop={handleCrop}
+ onFindInGallery={onFindInGallery}
onUseSize={onUseSize}
/>
<Stack flex="1" gap="2" minW="0">
@@ -362,11 +366,13 @@ const ReferenceImageThumbnail = ({
disabled,
image,
onCrop,
+ onFindInGallery,
onUseSize,
}: {
disabled: boolean;
image: GenerateReferenceImageAsset | null;
onCrop: (image: GenerateReferenceImageAsset) => void;
+ onFindInGallery: (imageName: string) => void;
onUseSize: (image: GenerateReferenceImageAsset) => void;
}) => {
const { t } = useTranslation();
@@ -383,18 +389,31 @@ const ReferenceImageThumbnail = ({
}
}, [image, onUseSize]);
+ // The ORIGINAL, not the effective image: a crop is uploaded as an
+ // intermediate, so the derivative this thumbnail shows has no cell in the
+ // grid to land on.
+ const originalImageName = image?.original.image.image_name;
+ const handleFindInGallery = useCallback(() => {
+ if (originalImageName !== undefined) {
+ onFindInGallery(originalImageName);
+ }
+ }, [onFindInGallery, originalImageName]);
+
return (
<>
+ {/* 24 rather than 20: the action row now holds three controls, and three
+ `2xs` buttons plus their gaps overflowed an 80px tile — `overflow:
+ hidden` then clipped the outer two and, with them, their focus ring. */}
<Box
bg="bg.muted"
borderWidth="1px"
css={THUMBNAIL_ACTIONS_CSS}
flexShrink="0"
- h="20"
+ h="24"
overflow="hidden"
position="relative"
rounded="md"
- w="20"
+ w="24"
>
{effectiveImage && urls ? (
<img alt={effectiveImage.image_name} draggable={false} src={urls.thumbnailUrl} style={COVER_IMG_STYLE} />
@@ -417,6 +436,9 @@ const ReferenceImageThumbnail = ({
style={OVERLAY_GRADIENT_STYLE}
transition="opacity var(--wb-motion-duration-fast)"
>
+ {/* Leads the row: locating the source is what you do BEFORE
+ deciding to crop it or take its size. */}
+ <FindInGalleryButton name={originalImageName} variant="ghost" onFind={handleFindInGallery} />
<Tooltip content={t('common.crop')}>
<IconButton
aria-label={t('common.crop')}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx
new file mode 100644
index 0000000000..b10eb66002
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx
@@ -0,0 +1,116 @@
+import type { GenerateReferenceImage } from '@features/generation/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ReferenceImageCard } from './ReferenceImageCard';
+
+/**
+ * A cropped reference image is TWO gallery records: the original the user
+ * picked, and the intermediate upload the crop produced. The card shows the
+ * crop, so the naive wiring sends the crop's name — and an intermediate is
+ * never listed in the grid, leaving the badge silently inert.
+ */
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ widgets: {
+ gallery: { findNamedInGallery: 'Find {{name}} in Gallery' },
+ generate: { referenceImage: 'Reference Image' },
+ },
+ },
+ },
+ },
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const onFindInGallery = vi.fn();
+const noop = vi.fn();
+
+const CROPPED_REFERENCE: GenerateReferenceImage = {
+ config: {
+ image: {
+ crop: {
+ box: { height: 128, width: 128, x: 16, y: 16 },
+ image: { height: 128, image_name: 'crop-intermediate.png', width: 128 },
+ ratio: 1,
+ },
+ original: { image: { height: 512, image_name: 'original.png', width: 512 } },
+ },
+ type: 'external_reference_image',
+ },
+ id: 'cropped',
+ isEnabled: true,
+};
+
+const renderCard = async (referenceImage: GenerateReferenceImage) => {
+ await act(() =>
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <ReferenceImageCard
+ count={1}
+ index={0}
+ referenceImage={referenceImage}
+ selectedModel={undefined}
+ onFindInGallery={onFindInGallery}
+ onMove={noop}
+ onPatch={noop}
+ onRemove={noop}
+ onUseSize={noop}
+ />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+};
+
+// Named after the media, not a bare "Find in Gallery": a stack of reference
+// cards otherwise renders N controls a screen reader cannot tell apart.
+const findButton = (): HTMLButtonElement | null =>
+ document.querySelector<HTMLButtonElement>('button[aria-label="Find original.png in Gallery"]');
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ onFindInGallery.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+});
+
+describe('reference image find-in-gallery badge', () => {
+ it('reveals the original image a crop was taken from, not the crop upload', async () => {
+ await renderCard(CROPPED_REFERENCE);
+
+ // The thumbnail is showing the crop, which is what makes this worth pinning.
+ expect(document.querySelector('img')?.src).toContain('crop-intermediate.png');
+
+ await act(() => findButton()?.click());
+
+ expect(onFindInGallery).toHaveBeenCalledWith('original.png');
+ });
+
+ it('stays available while the reference is toggled off', async () => {
+ await renderCard({ ...CROPPED_REFERENCE, isEnabled: false });
+
+ // Crop and Use size are edits and go dead with the reference; locating its
+ // source changes nothing about the generation, so it must not.
+ expect(findButton()?.disabled).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx
index 0f3a311fae..140739381a 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx
@@ -47,6 +47,7 @@ let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const onUseSize = vi.fn();
+const onFindInGallery = vi.fn();
const onPatch = vi.fn();
const onRemove = vi.fn();
@@ -75,6 +76,7 @@ const Stack = ({ ids }: { ids: string[] }) => {
index={index}
referenceImage={referenceImage}
selectedModel={undefined}
+ onFindInGallery={onFindInGallery}
onMove={handleMove}
onPatch={onPatch}
onRemove={onRemove}
diff --git a/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsx b/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsx
index 046069c3c2..9beea10f34 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/TrimBoundThumb.tsx
@@ -1,4 +1,5 @@
import { Badge, Box } from '@chakra-ui/react';
+import { FindInGalleryThumbnailButton } from '@features/gallery/mediaSlot';
import { memo, useEffect, useRef } from 'react';
/**
@@ -26,12 +27,18 @@ export const TrimBoundThumb = memo(function TrimBoundThumb({
fps,
frame,
label,
+ name,
src,
+ onFindInGallery,
}: {
fps: number;
frame: number;
label: string;
+ /** The clip's file name, which names the find control among its siblings. */
+ name?: string;
src: string;
+ /** Reveals the clip these bounds are cut from; omitted, the thumb is display only. */
+ onFindInGallery?: () => void;
}) {
const videoRef = useRef<HTMLVideoElement | null>(null);
@@ -59,11 +66,21 @@ export const TrimBoundThumb = memo(function TrimBoundThumb({
}, [fps, frame, src]);
return (
- <Box bg="blackAlpha.300" flexShrink={0} h="14" overflow="hidden" position="relative" rounded="sm" w="20">
+ <Box
+ bg="blackAlpha.300"
+ className="group"
+ flexShrink={0}
+ h="14"
+ overflow="hidden"
+ position="relative"
+ rounded="sm"
+ w="20"
+ >
<video key={src} ref={videoRef} muted preload="metadata" src={src} style={PREVIEW_VIDEO_STYLE} />
<Badge bottom="0.5" insetInlineStart="0.5" pointerEvents="none" position="absolute" size="xs" variant="solid">
{label}
</Badge>
+ {onFindInGallery ? <FindInGalleryThumbnailButton name={name} onFind={onFindInGallery} /> : null}
</Box>
);
});
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
index 6a63583072..1eb467fb42 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFrameImageField.tsx
@@ -32,7 +32,7 @@ export const VideoFrameImageField = memo(
image: ImageWithDims | null;
onChange: (image: ImageWithDims | null) => void;
}) {
- const { getUploadBoardId } = useVideoUiActions();
+ const { findInGallery, getUploadBoardId } = useVideoUiActions();
const value = useMemo<GalleryMediaSlotValue | null>(
() => (image ? { height: image.height, kind: 'image', name: image.image_name, width: image.width } : null),
[image]
@@ -43,6 +43,12 @@ export const VideoFrameImageField = memo(
onChange(item?.kind === 'image' ? { height: item.height, image_name: item.name, width: item.width } : null),
[onChange]
);
+ const imageName = image?.image_name;
+ const handleFind = useCallback(() => {
+ if (imageName !== undefined) {
+ findInGallery({ kind: 'image', name: imageName });
+ }
+ }, [findInGallery, imageName]);
return (
<GalleryMediaSlot
@@ -54,6 +60,7 @@ export const VideoFrameImageField = memo(
uploadBoardId={getUploadBoardId}
value={value}
onChange={handleChange}
+ onFind={handleFind}
/>
);
},
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
index 4252b82d8d..4e6120411e 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
@@ -11,6 +11,7 @@ import type { ChangeEvent } from 'react';
import { Badge, Box, createListCollection, HStack, Icon, Image, Input, Spinner, Stack, Text } from '@chakra-ui/react';
import { useDndContext, useDndMonitor, useDroppable } from '@dnd-kit/core';
import { galleryItems, galleryTransfers, toGalleryItemKey } from '@features/gallery';
+import { FindInGalleryThumbnailButton } from '@features/gallery/mediaSlot';
import { GalleryPickerPopover } from '@features/gallery/picker';
import { galleryImageUrls, galleryVideoUrls, isGalleryItemDragData } from '@features/gallery/utility';
import { resolveMiniMaxH3ReferenceImage } from '@features/video/core/dimensions';
@@ -153,9 +154,17 @@ const ReferenceCard = memo(function ReferenceCard({
targetArea: number | null;
}) {
const { t } = useTranslation();
+ const { findInGallery } = useVideoUiActions();
const moveUpRef = useRef<HTMLButtonElement>(null);
const moveDownRef = useRef<HTMLButtonElement>(null);
const name = reference.kind === 'video' ? reference.clip.video_name : reference.image.image_name;
+ const kind = reference.kind;
+ // Never gated on `disabled`, for the same reason the play button is not:
+ // locating the media changes nothing about the generation. Offered once per
+ // card — from the poster, or from the START bound of a clip: both bounds are
+ // frames of one gallery record, so badging each would be two controls with
+ // one destination and one name for a screen reader to tell apart.
+ const findReferenceInGallery = useCallback(() => findInGallery({ kind, name }), [findInGallery, kind, name]);
const promptLabels = useMemo(
() => formatReferencePromptLabels({ audio: audioLabel, picture: pictureLabel, video: videoLabel }),
[audioLabel, pictureLabel, videoLabel]
@@ -305,8 +314,18 @@ const ReferenceCard = memo(function ReferenceCard({
an audio reference, whose frames are a drawing of the sound, nothing can. */}
{reference.kind === 'video' ? <PlayClipSpanButton clip={reference.clip} /> : null}
{reference.kind === 'image' ? (
- <Box bg="blackAlpha.300" flexShrink={0} h="12" overflow="hidden" rounded="sm" w="16">
+ <Box
+ bg="blackAlpha.300"
+ className="group"
+ flexShrink={0}
+ h="12"
+ overflow="hidden"
+ position="relative"
+ rounded="sm"
+ w="16"
+ >
<Image alt="" fit="cover" h="100%" src={galleryImageUrls.thumbnail(name)} w="100%" />
+ <FindInGalleryThumbnailButton name={name} onFind={findReferenceInGallery} />
</Box>
) : null}
<Stack flex="1" gap="1" minW="0">
@@ -360,7 +379,9 @@ const ReferenceCard = memo(function ReferenceCard({
fps={reference.clip.fps}
frame={reference.clip.startFrame}
label={t('widgets.video.trimStartShort')}
+ name={name}
src={galleryVideoUrls.full(name)}
+ onFindInGallery={findReferenceInGallery}
/>
<Stack flex="1" gap="0.5" minW="0">
<FieldLabel>{t('widgets.video.trimStart')}</FieldLabel>
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
index bfb13836cb..88414d4c09 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoSourceClipField.tsx
@@ -78,7 +78,7 @@ export const VideoSourceClipField = memo(
sourceVideo: VideoSourceClip | null;
}) {
const { t } = useTranslation();
- const { getUploadBoardId, reportError, touchGalleryImages } = useVideoUiActions();
+ const { findInGallery, getUploadBoardId, reportError, touchGalleryImages } = useVideoUiActions();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
@@ -230,6 +230,15 @@ export const VideoSourceClipField = memo(
);
const previewSrc = sourceVideo ? galleryVideoUrls.full(sourceVideo.video_name) : null;
+ // Offered from the START bound only: both thumbs are frames of one gallery
+ // record, so badging each would be two controls with one destination and
+ // one name for a screen reader to tell apart.
+ const videoName = sourceVideo?.video_name;
+ const findClipInGallery = useCallback(() => {
+ if (videoName !== undefined) {
+ findInGallery({ kind: 'video', name: videoName });
+ }
+ }, [findInGallery, videoName]);
return (
<Stack gap="2">
@@ -321,7 +330,9 @@ export const VideoSourceClipField = memo(
fps={sourceVideo.fps}
frame={sourceVideo.startFrame}
label={t('widgets.video.trimStartShort')}
+ name={sourceVideo.video_name}
src={previewSrc}
+ onFindInGallery={findClipInGallery}
/>
<Box flex="1" minW="0">
<SliderNumberField
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
index aeeb656f7b..079cc1e1be 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
@@ -1,4 +1,4 @@
-import type { GalleryVideoItem } from '@features/gallery';
+import type { GalleryItemRef, GalleryVideoItem } from '@features/gallery';
import type { VideoWidgetValues } from '@features/video/core/types';
import type { ReactNode } from 'react';
@@ -9,6 +9,13 @@ import { createContext, use, useMemo } from 'react';
* may not import workbench), not a test seam; no second adapter is expected.
*/
export interface VideoUiAdapter {
+ /**
+ * Locate one of the panel's conditioning media in the Gallery grid and put it
+ * in front of the user: the Gallery and Preview widgets come on screen and
+ * the grid lands on the item's board, page, and cell. The panel's thumbnails
+ * are the only handle the user has on media picked long ago.
+ */
+ findInGallery(ref: GalleryItemRef): void;
/**
* The board a file upload from the video panel should land on — the gallery's
* currently selected board. A callback rather than a value so upload handlers
@@ -58,6 +65,7 @@ export interface VideoSpanPlaybackPort {
/** The adapter's callbacks, which are stable for the lifetime of a project. */
export type VideoUiActions = Pick<
VideoUiAdapter,
+ | 'findInGallery'
| 'getUploadBoardId'
| 'patchValues'
| 'playVideoSpanInPreview'
@@ -76,10 +84,18 @@ const VideoUiContext = createContext<VideoUiAdapter | null>(null);
const VideoUiActionsContext = createContext<VideoUiActions | null>(null);
export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {
- const { getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages, videoSpanPlayback } =
- adapter;
+ const {
+ findInGallery,
+ getUploadBoardId,
+ patchValues,
+ playVideoSpanInPreview,
+ reportError,
+ touchGalleryImages,
+ videoSpanPlayback,
+ } = adapter;
const actions = useMemo<VideoUiActions>(
() => ({
+ findInGallery,
getUploadBoardId,
patchValues,
playVideoSpanInPreview,
@@ -87,7 +103,15 @@ export const VideoUiProvider = ({ adapter, children }: { adapter: VideoUiAdapter
touchGalleryImages,
videoSpanPlayback,
}),
- [getUploadBoardId, patchValues, playVideoSpanInPreview, reportError, touchGalleryImages, videoSpanPlayback]
+ [
+ findInGallery,
+ getUploadBoardId,
+ patchValues,
+ playVideoSpanInPreview,
+ reportError,
+ touchGalleryImages,
+ videoSpanPlayback,
+ ]
);
return (
diff --git a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx
index 631ebaaa41..8be40edd51 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/referenceConditioningDefault.browser.test.tsx
@@ -57,6 +57,7 @@ const videoItem = (mediaOrigin?: string): GalleryVideoItem => ({
});
const adapter = {
+ findInGallery: () => undefined,
getUploadBoardId: () => 'none',
patchValues: (_values: Partial<VideoWidgetValues>) => undefined,
playVideoSpanInPreview: () => null,
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx
new file mode 100644
index 0000000000..eb7d49aa07
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningFindInGallery.browser.test.tsx
@@ -0,0 +1,164 @@
+import type { GalleryUiAdapter } from '@features/gallery/react';
+import type { VideoSourceClip } from '@features/video/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { GalleryUiProvider } from '@features/gallery/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { VideoFrameImageField } from './VideoFrameImageField';
+import { VideoSourceClipField } from './VideoSourceClipField';
+import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';
+
+/**
+ * The two conditioning fields the Ref2VA reference list does not cover: the
+ * keyframe slots, whose badge comes from the shared gallery media slot, and the
+ * initial video, badged on its start bound alone because both trim thumbs are
+ * frames of one clip. Both hand a kind+name to the port, and a video asked for
+ * as an image resolves against the wrong endpoint and dies in a rejected
+ * promise.
+ */
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ widgets: {
+ gallery: {
+ findNamedInGallery: 'Find {{name}} in Gallery',
+ picker: {
+ chooseImage: 'Choose image',
+ dropHint: 'Drop',
+ removeImage: 'Remove image',
+ replaceHint: 'Replace',
+ replaceImage: 'Replace image',
+ upload: 'Upload',
+ },
+ },
+ video: {
+ playSelection: 'Play selection in Preview',
+ removeClip: 'Remove clip',
+ trim: 'Trim',
+ trimEnd: 'Trim end',
+ trimEndShort: 'End',
+ trimHelp: 'help',
+ trimStart: 'Trim start',
+ trimStartShort: 'Start',
+ },
+ },
+ },
+ },
+ },
+});
+
+let host: HTMLDivElement;
+let root: Root;
+let queryClient: QueryClient;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const findInGallery = vi.fn();
+const videoAdapter = {
+ findInGallery,
+ getUploadBoardId: () => 'none',
+ patchValues: vi.fn(),
+ playVideoSpanInPreview: vi.fn(),
+ reportError: vi.fn(),
+ touchGalleryImages: vi.fn(),
+ videoSpanPlayback: { getState: () => null, subscribe: () => () => undefined },
+} as unknown as VideoUiAdapter;
+
+const galleryAdapter = {
+ gallery: { selectBoard: vi.fn(), selectItem: vi.fn(), setView: vi.fn() },
+ galleryValues: {},
+ notifications: { add: vi.fn(), reportError: vi.fn() },
+ widgets: { openGallery: () => true, patchGalleryValues: vi.fn() },
+} as unknown as GalleryUiAdapter;
+
+const FIRST_FRAME = { height: 512, image_name: 'first.png', width: 512 };
+const CLIP: VideoSourceClip = {
+ endFrame: 47,
+ fps: 24,
+ height: 480,
+ numFrames: 48,
+ startFrame: 0,
+ video_name: 'source.mp4',
+ width: 832,
+};
+
+const render = async (children: ReactNode): Promise<void> => {
+ await act(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <GalleryUiProvider adapter={galleryAdapter}>
+ <DndContext>
+ <VideoUiProvider adapter={videoAdapter}>{children}</VideoUiProvider>
+ </DndContext>
+ </GalleryUiProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+};
+
+const findButtons = (name: string): HTMLButtonElement[] => [
+ ...host.querySelectorAll<HTMLButtonElement>(`button[aria-label="Find ${name} in Gallery"]`),
+];
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ findInGallery.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ queryClient.clear();
+});
+
+describe('video conditioning find-in-gallery badges', () => {
+ it('reveals a keyframe image as an image', async () => {
+ await render(
+ <VideoFrameImageField dropId="first-frame" dropLabel="Drop First Frame" image={FIRST_FRAME} onChange={vi.fn()} />
+ );
+
+ await act(() => findButtons('first.png')[0]?.click());
+
+ expect(findInGallery).toHaveBeenCalledExactlyOnceWith({ kind: 'image', name: 'first.png' });
+ });
+
+ it('reveals the initial video as a video, once, from its start bound', async () => {
+ await render(<VideoSourceClipField sourceVideo={CLIP} onChange={vi.fn()} />);
+
+ // The end bound shows the same clip, so a second badge there would be a
+ // second control with one destination — and one name to tell them apart.
+ const bounds = findButtons('source.mp4');
+
+ expect(bounds).toHaveLength(1);
+
+ await act(() => bounds[0]?.click());
+
+ expect(findInGallery).toHaveBeenCalledExactlyOnceWith({ kind: 'video', name: 'source.mp4' });
+ });
+
+ it('offers no badge on an empty keyframe slot', async () => {
+ await render(
+ <VideoFrameImageField dropId="last-frame" dropLabel="Drop Last Frame" image={null} onChange={vi.fn()} />
+ );
+
+ expect(host.querySelector('button[aria-label^="Find "]')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoReferenceFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceFindInGallery.browser.test.tsx
new file mode 100644
index 0000000000..da8d410624
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/ui/videoReferenceFindInGallery.browser.test.tsx
@@ -0,0 +1,177 @@
+import type { VideoReferenceItem } from '@features/video/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { VideoReferenceListField } from './VideoReferenceListField';
+import { VideoUiProvider, type VideoUiAdapter } from './VideoUiContext';
+
+/**
+ * A reference card carries ONE find badge — an image reference's poster, or the
+ * START bound of a video reference, whose two trim thumbs are frames of a single
+ * gallery record. It reveals the card's own media, so the kind has to travel
+ * with the name: a video asked for as an image resolves against the wrong
+ * endpoint and the gesture dies in a rejected promise, silently.
+ */
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ widgets: {
+ gallery: { findNamedInGallery: 'Find {{name}} in Gallery', picker: { dropHint: 'Drop', upload: 'Upload' } },
+ video: {
+ chooseReference: 'Choose from Gallery',
+ moveReferenceDown: 'Move reference down',
+ moveReferenceUp: 'Move reference up',
+ playSelection: 'Play selection in Preview',
+ referenceConditioningAudio: 'Audio only',
+ referenceConditioningVideo: 'Video only',
+ referenceConditioningVideoAudio: 'Video + audio',
+ referenceDetailMatch: 'Match generation size',
+ referenceDetailMax: 'Max detail',
+ referencesHelp: 'help',
+ removeReference: 'Remove reference',
+ sampleLength: 'Sample Length',
+ sampleLengthWithSeconds: 'Sample Length ({{seconds}}s)',
+ trimEndShort: 'End',
+ trimStart: 'Start Frame',
+ trimStartShort: 'Start',
+ uploadImageReference: 'Upload image',
+ uploadVideoReference: 'Upload video',
+ },
+ },
+ },
+ },
+ },
+});
+
+let host: HTMLDivElement;
+let root: Root;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const findInGallery = vi.fn();
+const adapter = {
+ findInGallery,
+ getUploadBoardId: () => 'none',
+ patchValues: vi.fn(),
+ playVideoSpanInPreview: vi.fn(),
+ reportError: vi.fn(),
+ touchGalleryImages: vi.fn(),
+ videoSpanPlayback: { getState: () => null, subscribe: () => () => undefined },
+} as unknown as VideoUiAdapter;
+
+const REFERENCES: VideoReferenceItem[] = [
+ { detail: 'match', image: { height: 512, image_name: 'still.png', width: 512 }, kind: 'image' },
+ {
+ clip: { endFrame: 47, fps: 24, height: 480, numFrames: 48, startFrame: 0, video_name: 'clip.mp4', width: 832 },
+ conditioning: 'video_audio',
+ kind: 'video',
+ },
+];
+
+const noop = () => REFERENCES;
+
+const render = async (): Promise<void> => {
+ await act(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <VideoUiProvider adapter={adapter}>
+ <VideoReferenceListField
+ maxImages={9}
+ maxVideos={3}
+ references={REFERENCES}
+ targetArea={null}
+ onChange={noop}
+ />
+ </VideoUiProvider>
+ </DndContext>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+};
+
+const findButtons = (name: string): HTMLButtonElement[] => [
+ ...host.querySelectorAll<HTMLButtonElement>(`button[aria-label="Find ${name} in Gallery"]`),
+];
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ findInGallery.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+describe('video reference find-in-gallery badges', () => {
+ it('reveals an image reference as an image', async () => {
+ await render();
+
+ expect(findButtons('still.png')).toHaveLength(1);
+
+ await act(() => findButtons('still.png')[0]?.click());
+
+ expect(findInGallery).toHaveBeenCalledWith({ kind: 'image', name: 'still.png' });
+ });
+
+ it('keeps the badge out of the way until its own thumbnail is hovered or focused', async () => {
+ await render();
+
+ // Each badge is scoped to its own thumbnail's `.group`, which is the whole
+ // mechanism that makes it a hover overlay rather than permanent chrome. A
+ // mouse hover cannot be synthesised, but focus-within comes from the same
+ // ancestor, so it proves the scoping either way.
+ const badges = [...findButtons('still.png'), ...findButtons('clip.mp4')];
+ const opacities = () => badges.map((button) => getComputedStyle(button).opacity);
+
+ expect(badges).toHaveLength(2);
+ expect(opacities()).toEqual(['0', '0']);
+
+ // Each in turn: the one holding focus lights and only it. A badge whose
+ // thumbnail lost its `.group` would never light; a `.group` hoisted to the
+ // card would light both at once.
+ //
+ // Polled rather than settled once: the reveal is a CSS transition, which
+ // does not exist to be awaited until the style recalc that starts it has
+ // run. Settling at the moment of the focus call can therefore return
+ // before the transition is even scheduled, and reads its start value.
+ for (const [index] of badges.entries()) {
+ await act(() => {
+ badges[index]!.focus();
+ });
+
+ await vi.waitFor(() =>
+ expect(opacities()).toEqual(badges.map((_button, other) => (other === index ? '1' : '0')))
+ );
+ }
+ });
+
+ it('reveals a video reference as a video, once, from its start bound', async () => {
+ await render();
+
+ // The end bound shows the same clip, so a second badge there would be a
+ // second control with one destination — and one name to tell them apart.
+ const bounds = findButtons('clip.mp4');
+
+ expect(bounds).toHaveLength(1);
+
+ await act(() => bounds[0]?.click());
+
+ expect(findInGallery).toHaveBeenCalledExactlyOnceWith({ kind: 'video', name: 'clip.mp4' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts b/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts
new file mode 100644
index 0000000000..e0f55464e0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts
@@ -0,0 +1,230 @@
+import type { GalleryView } from '@features/gallery';
+import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryItemsFilter } from '@features/gallery/queries';
+import type { QueryClient } from '@tanstack/react-query';
+import type { WorkbenchCommands, WorkbenchQueries } from '@workbench/workbenchStore';
+
+import { galleryItems, toGalleryItemKey } from '@features/gallery';
+import { getGallerySettings, isGalleryNavigationCurrent, requestGalleryItemReveal } from '@features/gallery/contracts';
+import {
+ GALLERY_MAX_ROWS,
+ GALLERY_PAGE_SIZE,
+ galleryBoardsOptions,
+ galleryItemNamesOptions,
+ galleryItemsInfiniteOptions,
+} from '@features/gallery/queries';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+
+/**
+ * What a reveal needs from the workbench. Passed in rather than read from hooks
+ * so this module can be loaded on the press that needs it — the panels' find
+ * badges are on the editor's initial route, and eagerly importing the gallery
+ * item/transfer barrel from there cost two more initial script requests.
+ */
+export interface GalleryRevealContext {
+ commands: WorkbenchCommands;
+ queries: WorkbenchQueries;
+ queryClient: QueryClient;
+}
+
+/**
+ * What the gesture was, at the moment it was made. Both fields are claimed by
+ * the CALLER and neither may be re-read here: a caller that loads this module
+ * on demand would otherwise take its ordering, and its project, from whenever
+ * the chunk happened to land.
+ */
+export interface GalleryRevealTicket {
+ /** The project the press belongs to; its writes may not land in another. */
+ projectId: string;
+ /** This navigation's place in the global ordering; see `claimGalleryNavigationSequence`. */
+ sequence: number;
+}
+
+/**
+ * Extends the infinite window until it covers `pagesNeeded` pages. This must
+ * NOT be a plain prefetch: the mounted gallery keeps the query fresh, and
+ * `fetchQuery` returns fresh cache without honoring the `pages` option — the
+ * reveal has to force the fetch (staleTime 0) or the window never grows. Two
+ * passes because a concurrent fetch already in flight (a second rapid click)
+ * absorbs the call without extending; the retry runs after it settles.
+ */
+const ensureGalleryPagesLoaded = async (
+ queryClient: QueryClient,
+ listingFilter: GalleryItemsFilter,
+ pagesNeeded: number
+): Promise<void> => {
+ const options = galleryItemsInfiniteOptions(listingFilter, { kind: 'infinite' });
+
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const data = queryClient.getQueryData<{ pages: unknown[] }>(options.queryKey);
+
+ if ((data?.pages.length ?? 0) >= pagesNeeded) {
+ return;
+ }
+
+ await queryClient.fetchInfiniteQuery({ ...options, pages: pagesNeeded, staleTime: 0 });
+ }
+};
+
+/**
+ * Lands the gallery on one item: its board and view, any search or similarity
+ * filter cleared (the item may not match it), and its position in the board's
+ * ordering looked up so the grid can reach it — the page is selected in
+ * paginated mode, and in infinite mode the pages down to it are loaded. The
+ * grid scrolls to the newly selected item on its own once it is in the loaded
+ * window. Preview follows the gallery selection by itself.
+ *
+ * The caller knows an item's kind and name; the selection contract wants a full
+ * gallery item, so each is hydrated through the by-ref resolver — always fresh,
+ * since a cached DTO's star/board state can drift, and kind-aware, since the
+ * item can be a video. A slow fetch can never overwrite a newer selection.
+ *
+ * This is navigation only: no widget is raised, because the caller that sits
+ * beside the grid (the image map) must not rearrange the workspace to scroll it.
+ * `useFindGalleryItem` is the panels' gesture, which does both.
+ *
+ * The `ticket` is minted by the CALLER, at the moment of the gesture, so a
+ * caller that loads this module on demand is still ordered — and fenced to its
+ * project — by when it was pressed rather than by when its chunk landed. The
+ * returned promise rejects if the item cannot be hydrated — a click on a
+ * just-deleted item, or a blip mid-backend-restart — leaving the selection
+ * unchanged; what to say about that is the caller's, since only it knows whether
+ * it has already rearranged the workspace on the user's behalf.
+ */
+export const revealGalleryItem = (
+ { commands, queries, queryClient }: GalleryRevealContext,
+ ref: GalleryItemRef,
+ { projectId, sequence }: GalleryRevealTicket
+): Promise<void> => {
+ // The press belongs to the project it was made in. This resolves over the
+ // network, and a switch in that window would otherwise clear the INCOMING
+ // project's search and move its selection — the same fence the video panel's
+ // play button carries.
+ const isCurrent = () => isGalleryNavigationCurrent(sequence) && queries.isActiveProject(projectId);
+
+ return galleryItems.resolve(ref).then(async (image) => {
+ if (!isCurrent()) {
+ return;
+ }
+
+ const getGalleryValues = () => getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');
+ const settings = getGallerySettings(getGalleryValues());
+ const targetView: GalleryView = image.category === 'general' ? 'images' : 'assets';
+ // The board listing the gallery will show once the reveal below has
+ // cleared any search: identical filter shape, so the name list (and
+ // the prefetched pages) land in the cache the gallery reads.
+ // The grid partitions on the flag: a starred image is revealed in
+ // the starred-only listing, an unstarred one in the plain listing.
+ const wantsStarredOnly = image.starred === true;
+ const listingFilter = {
+ boardId: image.boardId,
+ galleryView: targetView,
+ orderDir: settings.imageOrderDir,
+ searchTerm: '',
+ starred: wantsStarredOnly,
+ };
+ // The image's position within its board's ordering, which is what
+ // lets the gallery land on the right page rather than page 0. A
+ // failure here only costs the scroll, not the selection. The boards
+ // list rides along because the gallery falls back to Uncategorized
+ // when the target board is not listable (archived with "show
+ // archived" off) — landing on the hidden board's page number there
+ // would jump to an unrelated page of the wrong board.
+ let boardIndex: number | null = null;
+
+ try {
+ const boardsPromise = queryClient
+ .fetchQuery(
+ galleryBoardsOptions({
+ includeArchived: settings.showArchivedBoards,
+ includeDateBoards: settings.showDateBoards,
+ orderBy: settings.boardOrderBy,
+ orderDir: settings.boardOrderDir,
+ })
+ )
+ // Unknown beats blocked: without the boards list the reveal
+ // proceeds as if the board were listable.
+ .catch(() => null);
+ const names = await queryClient.fetchQuery(galleryItemNamesOptions(listingFilter));
+ const boards = await boardsPromise;
+ const index = names.items.findIndex((item) => item.kind === ref.kind && item.name === ref.name);
+ const isBoardListable =
+ image.boardId === 'none' ||
+ boards === null ||
+ boards.length === 0 ||
+ boards.some((board) => board.id === image.boardId);
+
+ boardIndex = index >= 0 && isBoardListable ? index : null;
+ } catch {
+ boardIndex = null;
+ }
+
+ if (!isCurrent()) {
+ return;
+ }
+
+ const values = getGalleryValues();
+ const settingsNow = getGallerySettings(values);
+
+ // The listing's ordering may have changed while the name list was
+ // in flight (sort direction); the computed index describes the old
+ // ordering, so the page landing is dropped.
+ if (settingsNow.imageOrderDir !== settings.imageOrderDir) {
+ boardIndex = null;
+ }
+
+ const currentView: GalleryView = values.galleryView === 'assets' ? 'assets' : 'images';
+ const hasSearch = typeof values.searchTerm === 'string' && values.searchTerm !== '';
+
+ // Filters would hide the listing the index was computed against
+ // (the image may not match them), so the reveal clears them and sets
+ // the starred filter to the image's own side of the partition.
+ if (
+ hasSearch ||
+ (values.starredOnly === true) !== wantsStarredOnly ||
+ (values.semanticImageQuery !== null && values.semanticImageQuery !== undefined)
+ ) {
+ commands.widgets.patchValues('gallery', {
+ searchTerm: '',
+ semanticImageQuery: null,
+ starredOnly: wantsStarredOnly,
+ });
+ }
+
+ if (currentView !== targetView) {
+ commands.gallery.setView(targetView);
+ }
+
+ // Select the image's board before the image. A reveal spans every
+ // accessible board, but `selectGalleryItem` stamps the navigation
+ // query from whatever list the gallery is CURRENTLY showing — a
+ // cross-board reveal without this left Preview's next/prev with no
+ // cursor. Mirrors the command palette's reveal-in-gallery.
+ commands.gallery.selectBoard(image.boardId);
+
+ const page = boardIndex !== null ? Math.floor(boardIndex / GALLERY_PAGE_SIZE) : null;
+
+ if (page !== null && settingsNow.paginationMode === 'paginated') {
+ commands.gallery.setPage(page);
+ }
+
+ if (boardIndex !== null && page !== null && settingsNow.paginationMode === 'infinite') {
+ if (boardIndex < GALLERY_MAX_ROWS) {
+ // Within the base window's reach: load every page down to the
+ // image so the grid can scroll to it. Fire and forget — the
+ // selection must not wait on page hydration, and the grid's
+ // pending reveal settles whenever the item appears.
+ void ensureGalleryPagesLoaded(queryClient, listingFilter, page + 1).catch(() => {});
+ } else {
+ // Deeper than the base window can ever load: anchor the
+ // infinite window at the image's page instead (the mounted
+ // gallery query fetches it on its own). Any board, search, or
+ // view change resets the anchor back to the top.
+ commands.gallery.setPage(page);
+ }
+ }
+
+ commands.gallery.selectItem(image, projectId, page ?? undefined);
+ requestGalleryItemReveal(toGalleryItemKey(ref));
+ });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useFindGalleryItem.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useFindGalleryItem.ts
new file mode 100644
index 0000000000..1fd3de0cc2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useFindGalleryItem.ts
@@ -0,0 +1,99 @@
+import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { GalleryRevealTicket } from '@workbench/image-actions/revealGalleryItem';
+import type { WidgetRegion } from '@workbench/layoutContracts';
+import type { Project } from '@workbench/projectContracts';
+
+import { claimGalleryNavigationSequence, isGalleryNavigationCurrent } from '@features/gallery/contracts';
+import { useQueryClient } from '@tanstack/react-query';
+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { useCallback } from 'react';
+
+/**
+ * Where to raise the grid, when it is already somewhere. `openWorkbenchWidget`
+ * picks a region from the MANIFEST rather than from the layout, and the reducer
+ * then adopts the existing instance into that region WITHOUT vacating the one
+ * it came from — so an unqualified open lists one grid in two regions at once
+ * and leaves it permanently in the centre tab strip. Naming the region it
+ * already occupies keeps the open a raise.
+ *
+ * Centre is the last resort: it is Preview's home, and the two would contest
+ * one slot. A project with no grid at all falls through to default placement.
+ */
+const SIDE_REGIONS: readonly WidgetRegion[] = ['right', 'left', 'bottom', 'center'];
+
+const getGalleryRegions = (project: Project): WidgetRegion[] =>
+ SIDE_REGIONS.filter((region) =>
+ project.widgetRegions[region].instanceIds.some(
+ (instanceId) => project.widgetInstances[instanceId]?.typeId === 'gallery'
+ )
+ );
+
+/**
+ * "Find in gallery", as the Generate and Video panels offer it on the media
+ * they are conditioning on: bring the Gallery and Preview widgets on screen,
+ * then reveal the item in the grid. Unlike the image map's reveal this DOES
+ * rearrange the workspace — the panels are the far side of the app from the
+ * grid, and a selection the user cannot see is not a find.
+ *
+ * Preview is raised first so that the grid wins if the two share a region:
+ * the gesture is named for the grid, and Preview follows the selection anyway
+ * once it is on screen. Both are raised on the press itself, ahead of the
+ * reveal, so the gesture reads as immediate; a widget no region can host is
+ * simply skipped, and the reveal still runs.
+ *
+ * The reveal is fetched on the press. Loading it eagerly pulled the gallery
+ * item/transfer barrel into the editor's initial graph, costing two more
+ * initial script requests (measured against the request-count budgets), for a
+ * control most sessions never touch. Its own sequence number is claimed HERE,
+ * before the import, so a press still takes its place in the global ordering
+ * at the moment it happened rather than whenever the chunk lands.
+ */
+export const useFindGalleryItem = (): ((ref: GalleryItemRef) => void) => {
+ const commands = useWorkbenchCommands();
+ const queries = useWorkbenchQueries();
+ const queryClient = useQueryClient();
+ const openWorkbenchWidget = useOpenWorkbenchWidget();
+
+ return useCallback(
+ (ref: GalleryItemRef) => {
+ const activeProject = queries.getSnapshot().activeProject;
+ // Minted here, not inside the import below: both the ordering and the
+ // project fence describe the PRESS, and reading either after the chunk
+ // lands would pin whatever the workspace had become by then.
+ const ticket: GalleryRevealTicket = {
+ projectId: activeProject.id,
+ sequence: claimGalleryNavigationSequence(),
+ };
+ const galleryRegions = getGalleryRegions(activeProject);
+
+ openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });
+ openWorkbenchWidget('gallery', galleryRegions.length > 0 ? { preferredRegions: galleryRegions } : undefined);
+
+ void import('@workbench/image-actions/revealGalleryItem')
+ .then(({ revealGalleryItem }) => revealGalleryItem({ commands, queries, queryClient }, ref, ticket))
+ .catch((error: unknown) => {
+ // Either the chunk 404'd (a tab left open across a redeploy) or the
+ // media is gone from the gallery — an ordinary state, since a
+ // reference outlives the image it was taken from. The widgets are
+ // already raised, so failing silently would leave the user with a
+ // rearranged workspace and no explanation for the grid not moving.
+ //
+ // Only for the gesture still in force: a press the user has since
+ // superseded, or left behind in another project, has no claim on
+ // their attention. The claim itself is not given back — a later press
+ // was a later intent, and it stands even though it could not be met.
+ if (!isGalleryNavigationCurrent(ticket.sequence) || !queries.isActiveProject(ticket.projectId)) {
+ return;
+ }
+
+ commands.notifications.reportError({
+ area: 'find-in-gallery',
+ message: error instanceof Error ? error.message : String(error),
+ namespace: 'gallery',
+ });
+ });
+ },
+ [commands, openWorkbenchWidget, queries, queryClient]
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
index c6d998f49c..6807e73462 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
@@ -3,6 +3,7 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ activeProjectId: 'project-1',
/** Simulated page count of the cached infinite window; null = no cache. */
cachedPageCount: null as number | null,
fetchBoards: vi.fn(),
@@ -25,7 +26,10 @@ vi.mock('@features/gallery', () => ({
toGalleryItemKey: (ref: { kind: string; name: string }) => `${ref.kind}:${ref.name}`,
}));
-vi.mock('@features/gallery/contracts', () => ({
+vi.mock('@features/gallery/contracts', async (importOriginal) => ({
+ // The navigation sequence is real: the staleness guarantees below are exactly
+ // what it implements, and a stubbed counter would assert nothing.
+ ...(await importOriginal<Record<string, unknown>>()),
getGallerySettings: () => mocks.settings,
registerImageCluster: mocks.registerImageCluster,
requestGalleryItemReveal: mocks.requestReveal,
@@ -68,7 +72,10 @@ vi.mock('@workbench/WorkbenchContext', () => ({
},
widgets: { patchValues: mocks.patchValues },
}),
- useWorkbenchQueries: () => ({ getSnapshot: () => ({ activeProject: { id: 'project-1' } }) }),
+ useWorkbenchQueries: () => ({
+ getSnapshot: () => ({ activeProject: { id: mocks.activeProjectId } }),
+ isActiveProject: (projectId: string) => projectId === mocks.activeProjectId,
+ }),
}));
import { useMapSelection } from './useSelectMapImage';
@@ -147,6 +154,7 @@ const namesWithImageAt = (imageName: string, index: number) => ({
});
beforeEach(() => {
+ mocks.activeProjectId = 'project-1';
mocks.cachedPageCount = null;
mocks.galleryValues = {};
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };
@@ -663,6 +671,28 @@ describe('useMapSelection', () => {
expect(mocks.selectItem.mock.calls.map((call) => call[0].name)).toEqual(['fresh.png']);
});
+ it('drops a reveal whose hydrate landed after the user switched projects', async () => {
+ // The reveal writes a board, a page, a filter reset and a selection. The
+ // sequence guard does not cover this: nothing newer was clicked, so a
+ // reveal in flight across a project switch would land every one of those
+ // writes in the project the user just arrived at.
+ const inFlight = deferred<{ boardId: string; category: string; kind: string; name: string }>();
+
+ mocks.resolve.mockReturnValueOnce(inFlight.promise);
+ await mount();
+
+ await flush(() => handle.click?.({ kind: 'image', name: 'left-behind.png' }));
+ mocks.activeProjectId = 'project-2';
+
+ await flush(() =>
+ inFlight.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'left-behind.png' })
+ );
+
+ expect(mocks.selectBoard).not.toHaveBeenCalled();
+ expect(mocks.selectItem).not.toHaveBeenCalled();
+ expect(mocks.patchValues).not.toHaveBeenCalled();
+ });
+
it('leaves the selection alone when hydrate fails or the item is gone', async () => {
mocks.resolve.mockRejectedValueOnce(new Error('deleted')).mockRejectedValueOnce(new Error('missing'));
await mount();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
index 8f033f2f0c..0bda170439 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
@@ -1,19 +1,14 @@
-import type { GalleryView } from '@features/gallery';
import type { GalleryItemKey, GalleryItemRef } from '@features/gallery/contracts';
-import type { GalleryItemsFilter } from '@features/gallery/queries';
-import type { QueryClient } from '@tanstack/react-query';
import { galleryItems, toGalleryItemKey } from '@features/gallery';
-import { getGallerySettings, registerImageCluster, requestGalleryItemReveal } from '@features/gallery/contracts';
import {
- GALLERY_MAX_ROWS,
- GALLERY_PAGE_SIZE,
- galleryBoardsOptions,
- galleryItemNamesOptions,
- galleryItemsInfiniteOptions,
-} from '@features/gallery/queries';
+ claimGalleryNavigationSequence,
+ isGalleryNavigationCurrent,
+ registerImageCluster,
+ requestGalleryItemReveal,
+} from '@features/gallery/contracts';
import { useQueryClient } from '@tanstack/react-query';
-import { getProjectWidgetValues } from '@workbench/widgetState';
+import { revealGalleryItem } from '@workbench/image-actions/revealGalleryItem';
import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useCallback, useMemo } from 'react';
@@ -25,56 +20,11 @@ export interface MapSelectionActions {
}
/**
- * Module-scoped, deliberately: the thing being guarded — the gallery selection —
- * is global, so the counter has to be too. A `useRef` is per-mount, which leaves
- * a hole whenever the widget unmounts with a hydrate in flight (switching the
- * right-panel tab away and back): the abandoned closure compares against its own
- * dead ref, still passes, and overwrites the newer mount's selection.
- */
-let selectionSequence = 0;
-
-/**
- * Extends the infinite window until it covers `pagesNeeded` pages. This must
- * NOT be a plain prefetch: the mounted gallery keeps the query fresh, and
- * `fetchQuery` returns fresh cache without honoring the `pages` option — the
- * reveal has to force the fetch (staleTime 0) or the window never grows. Two
- * passes because a concurrent fetch already in flight (a second rapid click)
- * absorbs the call without extending; the retry runs after it settles.
- */
-const ensureGalleryPagesLoaded = async (
- queryClient: QueryClient,
- listingFilter: GalleryItemsFilter,
- pagesNeeded: number
-): Promise<void> => {
- const options = galleryItemsInfiniteOptions(listingFilter, { kind: 'infinite' });
-
- for (let attempt = 0; attempt < 2; attempt += 1) {
- const data = queryClient.getQueryData<{ pages: unknown[] }>(options.queryKey);
-
- if ((data?.pages.length ?? 0) >= pagesNeeded) {
- return;
- }
-
- await queryClient.fetchInfiniteQuery({ ...options, pages: pagesNeeded, staleTime: 0 });
- }
-};
-
-/**
- * Turns map clicks into gallery navigation. The map knows an item's kind and
- * name; the selection contract wants a full gallery item, so each is hydrated
- * through the by-ref resolver — always fresh, since a cached DTO's star/board
- * state can drift, and kind-aware, since a point can be a video. ONE monotonic
- * sequence spans both selection kinds, so rapid clicks always resolve to the
- * latest click regardless of which mode each went through; a slow fetch can
- * never overwrite a newer selection. Preview follows the gallery selection on
- * its own.
- *
- * A single click is a full reveal: the gallery lands on the item's board and
- * view, any search or similarity filter is cleared (the item may not match
- * it), and the item's position in the board's ordering is looked up so the
- * grid can reach it — the page is selected in paginated mode, and in infinite
- * mode the pages down to it are loaded. The grid scrolls to the newly selected
- * item on its own once it is in the loaded window.
+ * Turns map clicks into gallery navigation. A single click is a full reveal,
+ * which `revealGalleryItem` owns; the map raises no widget of its own, since it
+ * sits beside the grid it is scrolling. The sequence guard those reveals claim
+ * spans BOTH selection kinds, so rapid clicks always resolve to the latest
+ * click regardless of which mode each went through.
*
* A cluster click instead behaves like a search: the cluster's members (in
* proximity order from the clicked point) become the gallery's list via a
@@ -85,158 +35,31 @@ export const useMapSelection = (): MapSelectionActions => {
const commands = useWorkbenchCommands();
const queries = useWorkbenchQueries();
const queryClient = useQueryClient();
-
const selectItem = useCallback(
(ref: GalleryItemRef) => {
- const sequence = ++selectionSequence;
-
- galleryItems
- .resolve(ref)
- .then(async (image) => {
- if (sequence !== selectionSequence) {
- return;
- }
-
- const getGalleryValues = () => getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');
- const settings = getGallerySettings(getGalleryValues());
- const targetView: GalleryView = image.category === 'general' ? 'images' : 'assets';
- // The board listing the gallery will show once the reveal below has
- // cleared any search: identical filter shape, so the name list (and
- // the prefetched pages) land in the cache the gallery reads.
- // The grid partitions on the flag: a starred image is revealed in
- // the starred-only listing, an unstarred one in the plain listing.
- const wantsStarredOnly = image.starred === true;
- const listingFilter = {
- boardId: image.boardId,
- galleryView: targetView,
- orderDir: settings.imageOrderDir,
- searchTerm: '',
- starred: wantsStarredOnly,
- };
- // The image's position within its board's ordering, which is what
- // lets the gallery land on the right page rather than page 0. A
- // failure here only costs the scroll, not the selection. The boards
- // list rides along because the gallery falls back to Uncategorized
- // when the target board is not listable (archived with "show
- // archived" off) — landing on the hidden board's page number there
- // would jump to an unrelated page of the wrong board.
- let boardIndex: number | null = null;
-
- try {
- const boardsPromise = queryClient
- .fetchQuery(
- galleryBoardsOptions({
- includeArchived: settings.showArchivedBoards,
- includeDateBoards: settings.showDateBoards,
- orderBy: settings.boardOrderBy,
- orderDir: settings.boardOrderDir,
- })
- )
- // Unknown beats blocked: without the boards list the reveal
- // proceeds as if the board were listable.
- .catch(() => null);
- const names = await queryClient.fetchQuery(galleryItemNamesOptions(listingFilter));
- const boards = await boardsPromise;
- const index = names.items.findIndex((item) => item.kind === ref.kind && item.name === ref.name);
- const isBoardListable =
- image.boardId === 'none' ||
- boards === null ||
- boards.length === 0 ||
- boards.some((board) => board.id === image.boardId);
-
- boardIndex = index >= 0 && isBoardListable ? index : null;
- } catch {
- boardIndex = null;
- }
+ const ticket = { projectId: queries.getSnapshot().activeProject.id, sequence: claimGalleryNavigationSequence() };
- if (sequence !== selectionSequence) {
- return;
- }
-
- const values = getGalleryValues();
- const settingsNow = getGallerySettings(values);
-
- // The listing's ordering may have changed while the name list was
- // in flight (sort direction); the computed index describes the old
- // ordering, so the page landing is dropped.
- if (settingsNow.imageOrderDir !== settings.imageOrderDir) {
- boardIndex = null;
- }
-
- const currentView: GalleryView = values.galleryView === 'assets' ? 'assets' : 'images';
- const hasSearch = typeof values.searchTerm === 'string' && values.searchTerm !== '';
-
- // Filters would hide the listing the index was computed against
- // (the image may not match them), so the reveal clears them and sets
- // the starred filter to the image's own side of the partition.
- if (
- hasSearch ||
- (values.starredOnly === true) !== wantsStarredOnly ||
- (values.semanticImageQuery !== null && values.semanticImageQuery !== undefined)
- ) {
- commands.widgets.patchValues('gallery', {
- searchTerm: '',
- semanticImageQuery: null,
- starredOnly: wantsStarredOnly,
- });
- }
-
- if (currentView !== targetView) {
- commands.gallery.setView(targetView);
- }
-
- // Select the image's board before the image. The map spans every
- // accessible board, but `selectGalleryItem` stamps the navigation
- // query from whatever list the gallery is CURRENTLY showing — a
- // cross-board click without this left Preview's next/prev with no
- // cursor. Mirrors the command palette's reveal-in-gallery.
- commands.gallery.selectBoard(image.boardId);
-
- const page = boardIndex !== null ? Math.floor(boardIndex / GALLERY_PAGE_SIZE) : null;
-
- if (page !== null && settingsNow.paginationMode === 'paginated') {
- commands.gallery.setPage(page);
- }
-
- if (boardIndex !== null && page !== null && settingsNow.paginationMode === 'infinite') {
- if (boardIndex < GALLERY_MAX_ROWS) {
- // Within the base window's reach: load every page down to the
- // image so the grid can scroll to it. Fire and forget — the
- // selection must not wait on page hydration, and the grid's
- // pending reveal settles whenever the item appears.
- void ensureGalleryPagesLoaded(queryClient, listingFilter, page + 1).catch(() => {});
- } else {
- // Deeper than the base window can ever load: anchor the
- // infinite window at the image's page instead (the mounted
- // gallery query fetches it on its own). Any board, search, or
- // view change resets the anchor back to the top.
- commands.gallery.setPage(page);
- }
- }
-
- commands.gallery.selectItem(image, undefined, page ?? undefined);
- requestGalleryItemReveal(toGalleryItemKey(ref));
- })
- .catch(() => {
- // A click on a just-deleted item, or a blip mid-backend-restart,
- // simply leaves the selection unchanged.
- });
+ void revealGalleryItem({ commands, queries, queryClient }, ref, ticket).catch(() => {
+ // A click on a just-deleted point, or a blip mid-backend-restart, simply
+ // leaves the selection unchanged. The map sits beside the grid and has
+ // moved nothing, so there is nothing to explain.
+ });
},
[commands, queries, queryClient]
);
const selectCluster = useCallback(
(primaryItem: GalleryItemRef, itemKeys: GalleryItemKey[], label: string) => {
- const sequence = ++selectionSequence;
+ const sequence = claimGalleryNavigationSequence();
galleryItems
.resolve(primaryItem)
.then((image) => {
- if (sequence !== selectionSequence) {
+ if (!isGalleryNavigationCurrent(sequence)) {
return;
}
- // Same reason as `selectItem` above: the selection stamps the
+ // Same reason as a single-item reveal: the selection stamps the
// navigation query from the board the gallery is showing, so land
// on the primary item's board first to keep that query coherent.
commands.gallery.selectBoard(image.boardId);