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.

perf(webv2): give the Gallery stable infinite pages and a bounded overlay

joshistoastbde25608f654
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 944d91b343..f04b331738 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,15 +2,15 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 798058,
+ "brotliBytes": 798153,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 798041,
+ "gzipBytes": 798207,
"imageRawBytes": 156376,
- "initialRawBytes": 1830253,
+ "initialRawBytes": 1831516,
"largestAssetRawBytes": 737748,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 57578,
+ "ownedRawBytes": 57670,
"requestCount": 31,
"scriptRequestCount": 15,
"sourceOwners": [
@@ -238,15 +238,15 @@
]
},
"limits": {
- "brotliBytes": 806039,
+ "brotliBytes": 806135,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 806022,
+ "gzipBytes": 806190,
"imageRawBytes": 157940,
- "initialRawBytes": 1848556,
+ "initialRawBytes": 1849832,
"largestAssetRawBytes": 745126,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 57578,
+ "ownedRawBytes": 57670,
"requestCount": 31,
"scriptRequestCount": 15
},
@@ -256,17 +256,17 @@
},
"editor": {
"baseline": {
- "brotliBytes": 965507,
+ "brotliBytes": 971557,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 964313,
+ "gzipBytes": 970237,
"imageRawBytes": 156376,
- "initialRawBytes": 2338864,
+ "initialRawBytes": 2358365,
"largestAssetRawBytes": 737748,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 106091,
- "requestCount": 72,
- "scriptRequestCount": 56,
+ "ownedRawBytes": 106268,
+ "requestCount": 75,
+ "scriptRequestCount": 59,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -398,8 +398,15 @@
"source:src/assets/SplashImage.webp",
"source:src/features/gallery/contracts.ts",
"source:src/features/gallery/core/image.ts",
+ "source:src/features/gallery/core/imagePaths.ts",
+ "source:src/features/gallery/core/recentImages.ts",
"source:src/features/gallery/core/selection.ts",
"source:src/features/gallery/core/settings.ts",
+ "source:src/features/gallery/data/backend.ts",
+ "source:src/features/gallery/data/imageUrls.ts",
+ "source:src/features/gallery/data/queries.ts",
+ "source:src/features/gallery/data/queryCache.ts",
+ "source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
"source:src/features/gallery/ui/GalleryUiContext.tsx",
"source:src/features/gallery/ui/galleryStateView.ts",
@@ -716,17 +723,17 @@
]
},
"limits": {
- "brotliBytes": 975163,
+ "brotliBytes": 981273,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 973957,
+ "gzipBytes": 979940,
"imageRawBytes": 157940,
- "initialRawBytes": 2362253,
+ "initialRawBytes": 2381949,
"largestAssetRawBytes": 745126,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 106091,
- "requestCount": 72,
- "scriptRequestCount": 56
+ "ownedRawBytes": 106268,
+ "requestCount": 75,
+ "scriptRequestCount": 59
},
"owner": "workbench",
"remediationTicket": "deepen-widget-registry-loading",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 6b697705a1..fe79bcddc0 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -25,11 +25,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 140.39999999850988,
+ "domContentLoadedMedianMs": 123,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 140.5,
- "longestTaskMaxMs": 100,
+ "loadMedianMs": 123,
+ "longestTaskMaxMs": 77,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -39,24 +39,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 19,
- "scriptRawBytes": 1452238,
+ "scriptRawBytes": 1453501,
"scriptRequestCount": 15,
- "totalRawBytes": 1567217
+ "totalRawBytes": 1568596
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 19,
- "scriptRawBytes": 1466761,
+ "scriptRawBytes": 1468037,
"scriptRequestCount": 15,
- "totalRawBytes": 1582890
+ "totalRawBytes": 1584282
},
- "routeReadyMedianMs": 297.5,
+ "routeReadyMedianMs": 254.5,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -83,11 +83,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 128.20000000298023,
+ "domContentLoadedMedianMs": 121.79999999701977,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 128.30000000447035,
- "longestTaskMaxMs": 83,
+ "loadMedianMs": 121.89999999850988,
+ "longestTaskMaxMs": 75,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -97,24 +97,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 19,
- "scriptRawBytes": 1452238,
+ "scriptRawBytes": 1453501,
"scriptRequestCount": 15,
- "totalRawBytes": 1567217
+ "totalRawBytes": 1568596
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 19,
- "scriptRawBytes": 1466761,
+ "scriptRawBytes": 1468037,
"scriptRequestCount": 15,
- "totalRawBytes": 1582890
+ "totalRawBytes": 1584282
},
- "routeReadyMedianMs": 323.90000000596046,
+ "routeReadyMedianMs": 314.5,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -141,13 +141,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 142.60000000149012,
+ "domContentLoadedMedianMs": 118.89999999850988,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 142.70000000298023,
- "longestTaskMaxMs": 141,
+ "loadMedianMs": 119,
+ "longestTaskMaxMs": 122,
"owner": "workbench",
- "projectSwitchMedianMs": 66.04346599999917,
+ "projectSwitchMedianMs": 68.03515899999911,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -155,24 +155,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 95,
- "scriptRawBytes": 2899045,
+ "scriptRawBytes": 2919222,
"scriptRequestCount": 89,
- "totalRawBytes": 3185813
+ "totalRawBytes": 3206106
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 95,
- "scriptRawBytes": 2928036,
+ "scriptRawBytes": 2948415,
"scriptRequestCount": 89,
- "totalRawBytes": 3217672
+ "totalRawBytes": 3238168
},
- "routeReadyMedianMs": 686,
+ "routeReadyMedianMs": 650.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -199,13 +199,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 135.89999999850988,
+ "domContentLoadedMedianMs": 124.40000000596046,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 135.89999999850988,
- "longestTaskMaxMs": 152,
+ "loadMedianMs": 124.5,
+ "longestTaskMaxMs": 138,
"owner": "workbench",
- "projectSwitchMedianMs": 110.28066000000035,
+ "projectSwitchMedianMs": 92.14579700000104,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -213,24 +213,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 95,
- "scriptRawBytes": 2899045,
+ "scriptRawBytes": 2919222,
"scriptRequestCount": 89,
- "totalRawBytes": 3185813
+ "totalRawBytes": 3206106
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 95,
- "scriptRawBytes": 2928036,
+ "scriptRawBytes": 2948415,
"scriptRequestCount": 89,
- "totalRawBytes": 3217672
+ "totalRawBytes": 3238168
},
- "routeReadyMedianMs": 726.0999999940395,
+ "routeReadyMedianMs": 702.7000000029802,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -239,29 +239,29 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 136291,
+ "largestAssetRawBytes": 136446,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 290040,
+ "scriptRawBytes": 290434,
"scriptRequestCount": 7,
- "totalRawBytes": 290040
+ "totalRawBytes": 290434
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 137654,
+ "largestAssetRawBytes": 137811,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 292941,
+ "scriptRawBytes": 293339,
"scriptRequestCount": 7,
- "totalRawBytes": 292941
+ "totalRawBytes": 293339
},
- "domContentLoadedMedianMs": 140.5,
+ "domContentLoadedMedianMs": 123.39999999850988,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 628.8000000044703,
- "loadMedianMs": 140.60000000149012,
- "longestTaskMaxMs": 156,
+ "layoutSwitchMedianMs": 626.7000000029802,
+ "loadMedianMs": 123.5,
+ "longestTaskMaxMs": 125,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -271,24 +271,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 99,
- "scriptRawBytes": 3174797,
+ "scriptRawBytes": 3195421,
"scriptRequestCount": 93,
- "totalRawBytes": 3461565
+ "totalRawBytes": 3482305
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 99,
- "scriptRawBytes": 3206545,
+ "scriptRawBytes": 3227376,
"scriptRequestCount": 93,
- "totalRawBytes": 3496181
+ "totalRawBytes": 3517129
},
- "routeReadyMedianMs": 1185.6999999955297,
+ "routeReadyMedianMs": 1083.8000000044703,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -297,28 +297,28 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 136291,
+ "largestAssetRawBytes": 136446,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 290040,
+ "scriptRawBytes": 290434,
"scriptRequestCount": 7,
- "totalRawBytes": 290040
+ "totalRawBytes": 290434
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 137654,
+ "largestAssetRawBytes": 137811,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 292941,
+ "scriptRawBytes": 293339,
"scriptRequestCount": 7,
- "totalRawBytes": 292941
+ "totalRawBytes": 293339
},
- "domContentLoadedMedianMs": 135.5,
+ "domContentLoadedMedianMs": 131.10000000149012,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 831,
- "loadMedianMs": 135.5,
+ "layoutSwitchMedianMs": 806.3000000044703,
+ "loadMedianMs": 131.20000000298023,
"longestTaskMaxMs": 249,
"owner": "canvas",
"projectSwitchMedianMs": 0,
@@ -329,24 +329,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 99,
- "scriptRawBytes": 3174797,
+ "scriptRawBytes": 3195421,
"scriptRequestCount": 93,
- "totalRawBytes": 3461565
+ "totalRawBytes": 3482305
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 99,
- "scriptRawBytes": 3206545,
+ "scriptRawBytes": 3227376,
"scriptRequestCount": 93,
- "totalRawBytes": 3496181
+ "totalRawBytes": 3517129
},
- "routeReadyMedianMs": 1400.7000000029802,
+ "routeReadyMedianMs": 1353.0999999940395,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -358,9 +358,9 @@
"largestAssetRawBytes": 13253,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14288,
+ "scriptRawBytes": 14235,
"scriptRequestCount": 3,
- "totalRawBytes": 14288
+ "totalRawBytes": 14235
},
"activatedResourceLimits": {
"cssRawBytes": 0,
@@ -369,15 +369,15 @@
"largestAssetRawBytes": 13386,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14431,
+ "scriptRawBytes": 14378,
"scriptRequestCount": 3,
- "totalRawBytes": 14431
+ "totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 135.59999999403954,
+ "domContentLoadedMedianMs": 119.89999999850988,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 397.20000000298023,
- "loadMedianMs": 135.59999999403954,
- "longestTaskMaxMs": 140,
+ "layoutSwitchMedianMs": 349.29999999701977,
+ "loadMedianMs": 120,
+ "longestTaskMaxMs": 134,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -387,24 +387,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 95,
- "scriptRawBytes": 2899045,
+ "scriptRawBytes": 2919222,
"scriptRequestCount": 89,
- "totalRawBytes": 3185813
+ "totalRawBytes": 3206106
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 95,
- "scriptRawBytes": 2928036,
+ "scriptRawBytes": 2948415,
"scriptRequestCount": 89,
- "totalRawBytes": 3217672
+ "totalRawBytes": 3238168
},
- "routeReadyMedianMs": 913.8999999985099,
+ "routeReadyMedianMs": 791.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -416,9 +416,9 @@
"largestAssetRawBytes": 13253,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14288,
+ "scriptRawBytes": 14235,
"scriptRequestCount": 3,
- "totalRawBytes": 14288
+ "totalRawBytes": 14235
},
"activatedResourceLimits": {
"cssRawBytes": 0,
@@ -427,15 +427,15 @@
"largestAssetRawBytes": 13386,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14431,
+ "scriptRawBytes": 14378,
"scriptRequestCount": 3,
- "totalRawBytes": 14431
+ "totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 133.70000000298023,
+ "domContentLoadedMedianMs": 122.5,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 530.1999999955297,
- "loadMedianMs": 133.80000000447035,
- "longestTaskMaxMs": 586,
+ "layoutSwitchMedianMs": 555.8999999985099,
+ "loadMedianMs": 122.5,
+ "longestTaskMaxMs": 473,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -445,24 +445,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 95,
- "scriptRawBytes": 2899045,
+ "scriptRawBytes": 2919222,
"scriptRequestCount": 89,
- "totalRawBytes": 3185813
+ "totalRawBytes": 3206106
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 95,
- "scriptRawBytes": 2928036,
+ "scriptRawBytes": 2948415,
"scriptRequestCount": 89,
- "totalRawBytes": 3217672
+ "totalRawBytes": 3238168
},
- "routeReadyMedianMs": 1156.1000000014901,
+ "routeReadyMedianMs": 1064.7000000029802,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -474,9 +474,9 @@
"largestAssetRawBytes": 13253,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14288,
+ "scriptRawBytes": 14235,
"scriptRequestCount": 3,
- "totalRawBytes": 14288
+ "totalRawBytes": 14235
},
"activatedResourceLimits": {
"cssRawBytes": 0,
@@ -485,15 +485,15 @@
"largestAssetRawBytes": 13386,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14431,
+ "scriptRawBytes": 14378,
"scriptRequestCount": 3,
- "totalRawBytes": 14431
+ "totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 160.79999999701977,
+ "domContentLoadedMedianMs": 119.10000000149012,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 484.20000000298023,
- "loadMedianMs": 160.79999999701977,
- "longestTaskMaxMs": 299,
+ "layoutSwitchMedianMs": 333.09999999403954,
+ "loadMedianMs": 119.10000000149012,
+ "longestTaskMaxMs": 132,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -503,24 +503,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 95,
- "scriptRawBytes": 2899045,
+ "scriptRawBytes": 2919222,
"scriptRequestCount": 89,
- "totalRawBytes": 3185813
+ "totalRawBytes": 3206106
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 95,
- "scriptRawBytes": 2928036,
+ "scriptRawBytes": 2948415,
"scriptRequestCount": 89,
- "totalRawBytes": 3217672
+ "totalRawBytes": 3238168
},
- "routeReadyMedianMs": 1125.7000000029802,
+ "routeReadyMedianMs": 795.6999999955297,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -532,9 +532,9 @@
"largestAssetRawBytes": 13253,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14288,
+ "scriptRawBytes": 14235,
"scriptRequestCount": 3,
- "totalRawBytes": 14288
+ "totalRawBytes": 14235
},
"activatedResourceLimits": {
"cssRawBytes": 0,
@@ -543,15 +543,15 @@
"largestAssetRawBytes": 13386,
"otherRawBytes": 0,
"requestCount": 3,
- "scriptRawBytes": 14431,
+ "scriptRawBytes": 14378,
"scriptRequestCount": 3,
- "totalRawBytes": 14431
+ "totalRawBytes": 14378
},
- "domContentLoadedMedianMs": 133.20000000298023,
+ "domContentLoadedMedianMs": 124,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 496.5,
- "loadMedianMs": 133.20000000298023,
- "longestTaskMaxMs": 161,
+ "layoutSwitchMedianMs": 450.20000000298023,
+ "loadMedianMs": 124,
+ "longestTaskMaxMs": 136,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -561,24 +561,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 737748,
- "otherRawBytes": 89156,
+ "otherRawBytes": 89272,
"requestCount": 95,
- "scriptRawBytes": 2899045,
+ "scriptRawBytes": 2919222,
"scriptRequestCount": 89,
- "totalRawBytes": 3185813
+ "totalRawBytes": 3206106
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 745126,
- "otherRawBytes": 90048,
+ "otherRawBytes": 90165,
"requestCount": 95,
- "scriptRawBytes": 2928036,
+ "scriptRawBytes": 2948415,
"scriptRequestCount": 89,
- "totalRawBytes": 3217672
+ "totalRawBytes": 3238168
},
- "routeReadyMedianMs": 1067.3999999985099,
+ "routeReadyMedianMs": 960.7000000029802,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -957,11 +957,13 @@
"source:src/features/gallery/contracts.ts",
"source:src/features/gallery/core/image.ts",
"source:src/features/gallery/core/imagePaths.ts",
+ "source:src/features/gallery/core/recentImages.ts",
"source:src/features/gallery/core/selection.ts",
"source:src/features/gallery/core/settings.ts",
"source:src/features/gallery/data/backend.ts",
"source:src/features/gallery/data/imageUrls.ts",
"source:src/features/gallery/data/queries.ts",
+ "source:src/features/gallery/data/queryCache.ts",
"source:src/features/gallery/index.ts",
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
@@ -1725,11 +1727,13 @@
"source:src/features/gallery/contracts.ts",
"source:src/features/gallery/core/image.ts",
"source:src/features/gallery/core/imagePaths.ts",
+ "source:src/features/gallery/core/recentImages.ts",
"source:src/features/gallery/core/selection.ts",
"source:src/features/gallery/core/settings.ts",
"source:src/features/gallery/data/backend.ts",
"source:src/features/gallery/data/imageUrls.ts",
"source:src/features/gallery/data/queries.ts",
+ "source:src/features/gallery/data/queryCache.ts",
"source:src/features/gallery/index.ts",
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index c3cde20069..a0de5d362d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1914,8 +1914,8 @@
"hideArchivedBoards": "Hide archived boards",
"hideDateBoards": "Hide date boards",
"imageDensity": "Image density",
- "imagesAriaLabel": "Gallery images",
"imageSort": "Image Sort",
+ "imagesAriaLabel": "Gallery images",
"infinite": "Infinite",
"loadingBackendGallery": "Loading backend gallery...",
"loadingBoard": "Loading board...",
@@ -1942,12 +1942,13 @@
"starImage": "Star {{name}}",
"thumbnailFitAspect": "Aspect",
"thumbnailFitSquare": "Square",
- "uncategorized": "Uncategorized",
"unarchiveBoard": "Unarchive Board",
+ "uncategorized": "Uncategorized",
"unknownBoard": "Unknown board",
"unstarImage": "Unstar {{name}}",
"uploadImagesToBoard": "Upload images to {{name}}",
- "uploadsUnavailableForDateBoards": "Uploads are unavailable for date boards"
+ "uploadsUnavailableForDateBoards": "Uploads are unavailable for date boards",
+ "windowLimit": "Showing the first {{count}} images. Narrow the search or switch to Pages to reach the rest."
},
"serverStatus": {
"connected": "Connected to Server",
diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
index 0196f1d4b4..6bcb59652f 100644
--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
@@ -13,10 +13,9 @@ const GalleryImageActionsAdapterComponent = ({
children,
generateValues,
onImagesDeleted,
- onStarredChange,
projectId,
}: GalleryImageActionsOptions & { children: ReactNode }) => {
- const actions = useImageActions({ boards, generateValues, onImagesDeleted, onStarredChange, projectId });
+ const actions = useImageActions({ boards, generateValues, onImagesDeleted, projectId });
return <GalleryImageActionsProvider actions={actions}>{children}</GalleryImageActionsProvider>;
};
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
index 915e65a6ae..ee98afeaa1 100644
--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
@@ -2,8 +2,10 @@ import type { GenerationUiAdapter } from '@features/generation/react';
import type { ReactNode } from 'react';
import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';
+import { invalidateGallery } from '@features/gallery/queries';
import { GenerationUiProvider } from '@features/generation/react';
import { ensureModelsLoaded, getModelBaseColorPalette, getModelBaseLabel, useModelsSelector } from '@features/models';
+import { useQueryClient } from '@tanstack/react-query';
import {
getWorkbenchPreferences,
patchWorkbenchPreferences,
@@ -39,15 +41,16 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
const modelsCatalog = useModelsSelector((snapshot) => snapshot.models);
const modelsError = useModelsSelector((snapshot) => snapshot.error);
const modelsStatus = useModelsSelector((snapshot) => snapshot.status);
- const { gallery, generation, notifications } = useWorkbenchCommands();
+ const { generation, notifications } = useWorkbenchCommands();
+ const queryClient = useQueryClient();
const notify = useNotify();
const galleryGroup = useMemo<GenerationUiAdapter['gallery']>(
() => ({
selectedImage: selectedGalleryImage,
- touchImages: () => gallery.touchImages(),
+ touchImages: () => void invalidateGallery(queryClient),
}),
- [gallery, selectedGalleryImage]
+ [queryClient, selectedGalleryImage]
);
const modelsGroup = useMemo<GenerationUiAdapter['models']>(
() => ({
diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
index 77e979786b..9db0a58e7e 100644
--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
@@ -1,15 +1,18 @@
+import { invalidateGallery } from '@features/gallery/queries';
import { modelLoadActivitySink } from '@features/models';
import { nodeExecutionStore } from '@features/nodes';
import { createProductionQueueRuntime } from '@features/queue';
import { ensureInvocationTemplatesLoaded } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
+import { useQueryClient } from '@tanstack/react-query';
import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSubscription } from '@workbench/WorkbenchContext';
/** App-owned production composition of Queue, Workbench, Gallery, Workflow, Nodes, and Models adapters. */
export const QueueRuntimeAdapter = () => {
const { notifications, queue } = useWorkbenchCommands();
const queries = useWorkbenchQueries();
+ const queryClient = useQueryClient();
const subscribe = useWorkbenchSubscription();
useMountEffect(() => {
@@ -27,7 +30,11 @@ export const QueueRuntimeAdapter = () => {
},
ensureTemplatesLoaded: ensureInvocationTemplatesLoaded,
history: {
- commands: { ...queue, recordError: notifications.reportError },
+ commands: {
+ ...queue,
+ recordError: notifications.reportError,
+ refreshBackendData: () => void invalidateGallery(queryClient),
+ },
getSnapshot: () => {
const snapshot = queries.getSnapshot();
diff --git a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
index 66101be91a..072dc1d163 100644
--- a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
@@ -1,8 +1,10 @@
import type { UpscaleUiAdapter } from '@features/upscale';
import type { ReactNode } from 'react';
+import { invalidateGallery } from '@features/gallery/queries';
import { areProjectPromptDraftsEqual, getPromptDraftFromValues } from '@features/generation/settings';
import { UpscaleUiProvider } from '@features/upscale';
+import { useQueryClient } from '@tanstack/react-query';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useMemo } from 'react';
@@ -30,6 +32,7 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })
left.showPromptSyntaxHighlighting === right.showPromptSyntaxHighlighting
);
const commands = useWorkbenchCommands();
+ const queryClient = useQueryClient();
const adapter = useMemo<UpscaleUiAdapter>(
() => ({
...project,
@@ -37,9 +40,9 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })
patchValues: (values, origin) => commands.widgets.patchValues('upscale', values, project.projectId, origin),
reportError: (message) =>
commands.notifications.reportError({ area: 'upscale', message, namespace: 'generation' }),
- touchGalleryImages: () => commands.gallery.touchImages(),
+ touchGalleryImages: () => void invalidateGallery(queryClient),
}),
- [commands, project]
+ [commands, project, queryClient]
);
return <UpscaleUiProvider adapter={adapter}>{children}</UpscaleUiProvider>;
diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
index 9636e209f5..83eaab3541 100644
--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
@@ -10,6 +10,7 @@ export type {
GeneratedImageContract,
} from './core/types';
export { normalizeGalleryImage } from './core/image';
+export { GALLERY_RECENT_IMAGE_LIMIT, getBoundedRecentImages } from './core/recentImages';
export {
DEFAULT_GALLERY_SETTINGS,
getGallerySettings,
@@ -21,13 +22,14 @@ export {
getGalleryCompareImage,
getGalleryCurrentItem,
getGalleryGenerationSequence,
+ getGalleryPage,
+ getGallerySelectedImagePage,
+ getGallerySelectedImageQuery,
getGalleryPlaceholderInsertionIndex,
- getGalleryImagesRefreshToken,
- getGalleryRecentImagesKey,
- getGalleryRefreshToken,
type GalleryCurrentItem,
type GalleryGenerationSequence,
type GalleryLiveTarget,
type GalleryQueuePlaceholder,
+ type GallerySelectedImageQuery,
} from './ui/galleryStateView';
export { getSelectedGalleryImageFromValues } from './core/selection';
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/recentImages.ts b/invokeai/frontend/webv2/src/features/gallery/core/recentImages.ts
new file mode 100644
index 0000000000..638b3fbaca
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/core/recentImages.ts
@@ -0,0 +1,52 @@
+import type { GeneratedImageContract } from './types';
+
+export const GALLERY_RECENT_IMAGE_LIMIT = 60;
+
+const isGeneratedImageContract = (value: unknown): value is GeneratedImageContract => {
+ if (!value || typeof value !== 'object') {
+ return false;
+ }
+
+ const image = value as Partial<GeneratedImageContract>;
+
+ return (
+ typeof image.height === 'number' &&
+ Number.isFinite(image.height) &&
+ typeof image.imageName === 'string' &&
+ image.imageName.length > 0 &&
+ typeof image.imageUrl === 'string' &&
+ typeof image.queuedAt === 'string' &&
+ typeof image.sourceQueueItemId === 'string' &&
+ typeof image.thumbnailUrl === 'string' &&
+ typeof image.width === 'number' &&
+ Number.isFinite(image.width)
+ );
+};
+
+/**
+ * Validates a newest-first recent-image overlay, retaining the newest occurrence
+ * of each image name and bounding the persisted result.
+ */
+export const getBoundedRecentImages = (value: unknown): GeneratedImageContract[] => {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+
+ const imageNames = new Set<string>();
+ const images: GeneratedImageContract[] = [];
+
+ for (const image of value) {
+ if (!isGeneratedImageContract(image) || imageNames.has(image.imageName)) {
+ continue;
+ }
+
+ imageNames.add(image.imageName);
+ images.push(image);
+
+ if (images.length === GALLERY_RECENT_IMAGE_LIMIT) {
+ break;
+ }
+ }
+
+ return images;
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index e9bdb9606d..13dcfb4a7c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -18,6 +18,7 @@ vi.mock('@platform/transport/http', () => ({
import {
downloadGalleryArchive,
getGalleryImageByName,
+ getGalleryImagesByNames,
imageMakeCanvasAssetChanges,
imageMakeDurableChanges,
imageSaveToGalleryChanges,
@@ -120,6 +121,31 @@ describe('getGalleryImageByName', () => {
});
});
+describe('getGalleryImagesByNames', () => {
+ beforeEach(() => {
+ mocks.apiFetchJson.mockReset();
+ });
+
+ it('restores the requested order when the bulk endpoint responds out of order', async () => {
+ const dto = (imageName: string) => ({
+ board_id: 'none',
+ created_at: '2026-07-09T12:00:00.000Z',
+ height: 512,
+ image_category: 'general',
+ image_name: imageName,
+ image_url: `/images/${imageName}`,
+ is_intermediate: false,
+ thumbnail_url: `/thumbnails/${imageName}`,
+ width: 512,
+ });
+ mocks.apiFetchJson.mockResolvedValue([dto('third.png'), dto('first.png'), dto('second.png')]);
+
+ const images = await getGalleryImagesByNames(['first.png', 'second.png', 'third.png']);
+
+ expect(images.map((image) => image.imageName)).toEqual(['first.png', 'second.png', 'third.png']);
+ });
+});
+
describe('listGalleryImages created-at range', () => {
beforeEach(() => {
mocks.apiFetchJson.mockReset();
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index fbdbc0943a..6dfc36e97f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -209,7 +209,13 @@ export const getGalleryImagesByNames = async (imageNames: string[], signal?: Abo
signal,
});
- return body.map(mapImage);
+ const imagesByName = new Map(body.map((image) => [image.image_name, mapImage(image)]));
+
+ return imageNames.flatMap((imageName) => {
+ const image = imagesByName.get(imageName);
+
+ return image ? [image] : [];
+ });
};
export const getGalleryImageByName = async (imageName: string, signal?: AbortSignal): Promise<GalleryImage> => {
@@ -218,17 +224,21 @@ export const getGalleryImageByName = async (imageName: string, signal?: AbortSig
return mapImage(body);
};
+export interface GalleryDateBoardImageNames {
+ imageNames: string[];
+ total: number;
+}
+
/**
- * Date virtual boards have no offset-paginated DTO endpoint; list the ordered
- * names for the date, slice the requested window, then bulk-hydrate DTOs.
+ * Date virtual boards have no offset-paginated DTO endpoint. The query module
+ * caches this ordered name list once per semantic filter, then each infinite
+ * page hydrates only its own fixed-size slice.
*/
-const listGalleryDateBoardImages = async ({
+export const listGalleryDateBoardImageNames = async ({
boardId,
createdFrom,
createdTo,
galleryView,
- limit,
- offset,
orderDir,
searchTerm,
signal,
@@ -238,20 +248,18 @@ const listGalleryDateBoardImages = async ({
createdFrom?: string;
createdTo?: string;
galleryView: GalleryView;
- limit: number;
- offset: number;
orderDir: GalleryOrderDir;
searchTerm: string;
signal?: AbortSignal;
starredFirst: boolean;
-}): Promise<GalleryImagesPage> => {
+}): Promise<GalleryDateBoardImageNames> => {
// The board already pins a single day; a date filter either contains that
// day (and constrains nothing further) or excludes the whole board.
if (
(createdFrom !== undefined || createdTo !== undefined) &&
!isTimestampInRange(getDateFromBoardId(boardId), { from: createdFrom, to: createdTo })
) {
- return { images: [], total: 0 };
+ return { imageNames: [], total: 0 };
}
const query = toSearchParams({
@@ -264,11 +272,28 @@ const listGalleryDateBoardImages = async ({
`/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/image_names?${query}`,
{ signal }
);
- const images = await getGalleryImagesByNames(body.image_names.slice(offset, offset + limit), signal);
- return { images, total: normalizeTotal(body.total_count, body.image_names.length) };
+ return {
+ imageNames: body.image_names,
+ total: normalizeTotal(body.total_count, body.image_names.length),
+ };
};
+export const hydrateGalleryDateBoardImagePage = async ({
+ imageNames,
+ limit,
+ offset,
+ signal,
+ total,
+}: GalleryDateBoardImageNames & {
+ limit: number;
+ offset: number;
+ signal?: AbortSignal;
+}): Promise<GalleryImagesPage> => ({
+ images: await getGalleryImagesByNames(imageNames.slice(offset, offset + limit), signal),
+ total,
+});
+
export const listGalleryImages = async ({
boardId,
createdFrom,
@@ -293,18 +318,18 @@ export const listGalleryImages = async ({
starredFirst?: boolean;
}): Promise<GalleryImagesPage> => {
if (isDateBoardId(boardId)) {
- return listGalleryDateBoardImages({
+ const names = await listGalleryDateBoardImageNames({
boardId,
createdFrom,
createdTo,
galleryView,
- limit,
- offset,
orderDir,
searchTerm,
signal,
starredFirst,
});
+
+ return hydrateGalleryDateBoardImagePage({ ...names, limit, offset, signal });
}
const query = toSearchParams({
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
index 73a5ecf433..f842bae1f1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
@@ -1,26 +1,96 @@
+import type { GalleryImage, GalleryImagesPage } from '@features/gallery/core/types';
+
import { accountLifecycle } from '@platform/state/accountLifecycle';
-import { QueryClient } from '@tanstack/react-query';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { InfiniteQueryObserver, QueryClient, type InfiniteData } from '@tanstack/react-query';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const backend = vi.hoisted(() => ({
+ hydrateGalleryDateBoardImagePage: vi.fn(),
+ isDateBoardId: vi.fn(),
listGalleryBoards: vi.fn(),
+ listGalleryDateBoardImageNames: vi.fn(),
listGalleryDateBoards: vi.fn(),
listGalleryImages: vi.fn(),
}));
vi.mock('./backend', () => backend);
-import { galleryBoardsOptions, galleryImagesOptions } from './queries';
+import {
+ flattenGalleryImagesData,
+ GALLERY_MAX_ROWS,
+ GALLERY_PAGE_SIZE,
+ galleryBoardsOptions,
+ galleryImagesInfiniteOptions,
+ getGalleryImageListQueries,
+ type GalleryImagesFilter,
+} from './queries';
+import { invalidateGalleryImages } from './queryCache';
+
+const OFFSETS = Array.from({ length: 10 }, (_, index) => index * GALLERY_PAGE_SIZE);
+
+const createQueryClient = (): QueryClient =>
+ new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ },
+ });
+
+const createImage = (index: number, prefix = 'image'): GalleryImage => ({
+ boardId: 'board-1',
+ height: 64,
+ imageCategory: 'general',
+ imageName: `${prefix}-${index}`,
+ imageUrl: `/images/${prefix}-${index}`,
+ queuedAt: new Date(index * 1_000).toISOString(),
+ sourceQueueItemId: 'backend-gallery',
+ starred: false,
+ thumbnailUrl: `/images/${prefix}-${index}/thumbnail`,
+ width: 64,
+});
+
+const createPage = ({
+ count = GALLERY_PAGE_SIZE,
+ offset,
+ prefix,
+ total,
+}: {
+ count?: number;
+ offset: number;
+ prefix?: string;
+ total: number;
+}): GalleryImagesPage => ({
+ images: Array.from({ length: count }, (_, index) => createImage(offset + index, prefix)),
+ total,
+});
+
+const baseFilter: GalleryImagesFilter = {
+ boardId: 'board-1',
+ galleryView: 'images',
+ orderDir: 'DESC',
+ searchTerm: 'portrait',
+ starredFirst: true,
+};
describe('Gallery query read model', () => {
beforeEach(() => {
+ accountLifecycle.activate('gallery-query-test');
+ backend.hydrateGalleryDateBoardImagePage.mockReset();
+ backend.isDateBoardId.mockReset();
backend.listGalleryBoards.mockReset();
+ backend.listGalleryDateBoardImageNames.mockReset();
backend.listGalleryDateBoards.mockReset();
backend.listGalleryImages.mockReset();
+
+ backend.isDateBoardId.mockImplementation((boardId: string) => boardId.startsWith('by_date:'));
+ backend.listGalleryImages.mockResolvedValue({ images: [], total: 0 });
+ });
+
+ afterEach(() => {
+ accountLifecycle.invalidate();
});
it('coalesces board readers through one query key and includes requested virtual boards', async () => {
- const queryClient = new QueryClient();
+ const queryClient = createQueryClient();
const board = { id: 'none', kind: 'uncategorized', name: 'Uncategorized' };
const dateBoard = { id: 'by_date:2026-07-18', kind: 'date', name: 'July 18' };
const options = galleryBoardsOptions({ includeDateBoards: true, orderDir: 'DESC' });
@@ -36,59 +106,267 @@ describe('Gallery query read model', () => {
expect(backend.listGalleryDateBoards).toHaveBeenCalledOnce();
});
- it('keeps pagination, search, and refresh identity in the image query key', () => {
- const base = {
- boardId: 'board-1',
- galleryView: 'images' as const,
- limit: 60,
- offset: 0,
- orderDir: 'DESC' as const,
- revision: 'images:1',
- searchTerm: 'portrait',
- starredFirst: true,
- };
-
- expect(galleryImagesOptions(base).queryKey).not.toEqual(galleryImagesOptions({ ...base, offset: 60 }).queryKey);
- expect(galleryImagesOptions(base).queryKey).not.toEqual(
- galleryImagesOptions({ ...base, revision: 'images:2' }).queryKey
+ it('loads ten fixed pages into one bounded logical query', async () => {
+ const queryClient = createQueryClient();
+ backend.listGalleryImages.mockImplementation(({ offset }: { offset: number }) =>
+ Promise.resolve(createPage({ offset, total: 1_000 }))
);
+ const options = galleryImagesInfiniteOptions(baseFilter);
+ const observer = new InfiniteQueryObserver(queryClient, options);
+
+ try {
+ await observer.refetch();
+ for (let page = 1; page < OFFSETS.length; page += 1) {
+ await observer.fetchNextPage();
+ }
+
+ const data = observer.getCurrentResult().data;
+ const cachedData = queryClient.getQueryData<InfiniteData<GalleryImagesPage, number>>(options.queryKey);
+
+ expect(backend.listGalleryImages.mock.calls.map(([request]) => request.offset)).toEqual(OFFSETS);
+ expect(backend.listGalleryImages.mock.calls.map(([request]) => request.limit)).toEqual(
+ OFFSETS.map(() => GALLERY_PAGE_SIZE)
+ );
+ expect(data?.pageParams).toEqual(OFFSETS);
+ expect(data?.pages.flatMap((page) => page.images)).toHaveLength(GALLERY_MAX_ROWS);
+ expect(flattenGalleryImagesData(data)).toHaveLength(GALLERY_MAX_ROWS);
+ expect(flattenGalleryImagesData(cachedData)).toHaveLength(GALLERY_MAX_ROWS);
+ expect(observer.getCurrentResult().hasNextPage).toBe(false);
+ expect(getGalleryImageListQueries(queryClient)).toHaveLength(1);
+ } finally {
+ observer.destroy();
+ }
});
- it('keeps the created-at range in the image query key', () => {
- const base = {
- boardId: 'board-1',
- galleryView: 'images' as const,
- searchTerm: '',
- };
- const ranged = { ...base, createdFrom: '2026-07-01', createdTo: '2026-07-15' };
-
- expect(galleryImagesOptions(base).queryKey).not.toEqual(galleryImagesOptions(ranged).queryKey);
- expect(galleryImagesOptions(ranged).queryKey).not.toEqual(
- galleryImagesOptions({ ...ranged, createdTo: '2026-07-16' }).queryKey
+ it('keeps semantic filters in the key while infinite page params stay inside one cache entry', async () => {
+ const baseKey = galleryImagesInfiniteOptions(baseFilter).queryKey;
+
+ expect(galleryImagesInfiniteOptions({ ...baseFilter, searchTerm: ' portrait ' }).queryKey).toEqual(baseKey);
+ expect(galleryImagesInfiniteOptions({ ...baseFilter, boardId: 'board-2' }).queryKey).not.toEqual(baseKey);
+ expect(galleryImagesInfiniteOptions({ ...baseFilter, galleryView: 'assets' }).queryKey).not.toEqual(baseKey);
+ expect(galleryImagesInfiniteOptions({ ...baseFilter, searchTerm: 'landscape' }).queryKey).not.toEqual(baseKey);
+ expect(galleryImagesInfiniteOptions({ ...baseFilter, createdFrom: '2026-07-01' }).queryKey).not.toEqual(baseKey);
+ expect(
+ galleryImagesInfiniteOptions({
+ ...baseFilter,
+ createdFrom: '2026-07-01',
+ createdTo: '2026-07-15',
+ }).queryKey
+ ).not.toEqual(
+ galleryImagesInfiniteOptions({
+ ...baseFilter,
+ createdFrom: '2026-07-01',
+ createdTo: '2026-07-16',
+ }).queryKey
);
+
+ const queryClient = createQueryClient();
+ backend.listGalleryImages.mockImplementation(({ offset }: { offset: number }) =>
+ Promise.resolve(createPage({ offset, total: 120 }))
+ );
+ const options = galleryImagesInfiniteOptions(baseFilter);
+ const observer = new InfiniteQueryObserver(queryClient, options);
+
+ try {
+ await observer.refetch();
+ await observer.fetchNextPage();
+
+ expect(observer.getCurrentResult().data?.pageParams).toEqual([0, 60]);
+ expect(getGalleryImageListQueries(queryClient)).toHaveLength(1);
+ expect(getGalleryImageListQueries(queryClient)[0]?.queryKey).toEqual(baseKey);
+ } finally {
+ observer.destroy();
+ }
});
- it('cannot cache an image response from an expired account epoch', async () => {
- accountLifecycle.activate('user-a');
- let resolveImages: ((value: { images: never[]; total: number }) => void) | undefined;
- backend.listGalleryImages.mockReturnValueOnce(
- new Promise((resolve) => {
- resolveImages = resolve;
- })
+ it.each([{ kind: 'anchor' as const }])(
+ 'releases inactive $kind windows immediately instead of accumulating page keys',
+ async ({ kind }) => {
+ const queryClient = createQueryClient();
+ backend.listGalleryImages.mockImplementation(({ offset }: { offset: number }) =>
+ Promise.resolve(createPage({ offset, total: 1_000 }))
+ );
+
+ for (const offset of Array.from({ length: 11 }, (_, index) => index * GALLERY_PAGE_SIZE)) {
+ await queryClient.fetchInfiniteQuery(galleryImagesInfiniteOptions(baseFilter, { kind, offset }));
+ }
+
+ await vi.waitFor(() => {
+ expect(getGalleryImageListQueries(queryClient).length).toBeLessThanOrEqual(1);
+ });
+ const cachedRows = getGalleryImageListQueries(queryClient).reduce((total, query) => {
+ const data = query.state.data as InfiniteData<GalleryImagesPage, number> | undefined;
+
+ return total + (data?.pages.reduce((count, page) => count + page.images.length, 0) ?? 0);
+ }, 0);
+
+ expect(cachedRows).toBeLessThanOrEqual(GALLERY_PAGE_SIZE);
+ }
+ );
+
+ it('does not create image-list cache entries for repeated invalidation events', async () => {
+ const queryClient = createQueryClient();
+ backend.listGalleryImages.mockResolvedValue(createPage({ count: 1, offset: 0, total: 1 }));
+ const options = galleryImagesInfiniteOptions(baseFilter);
+
+ await queryClient.fetchInfiniteQuery(options);
+ expect(getGalleryImageListQueries(queryClient)).toHaveLength(1);
+
+ for (let event = 0; event < 100; event += 1) {
+ await invalidateGalleryImages(queryClient);
+ }
+
+ expect(getGalleryImageListQueries(queryClient)).toHaveLength(1);
+ expect(getGalleryImageListQueries(queryClient)[0]?.queryKey).toEqual(options.queryKey);
+ expect(backend.listGalleryImages).toHaveBeenCalledOnce();
+ });
+
+ it('aborts the old request when an observer switches filters and isolates its late completion', async () => {
+ const queryClient = createQueryClient();
+ const oldOptions = galleryImagesInfiniteOptions({ ...baseFilter, boardId: 'board-old' });
+ const newOptions = galleryImagesInfiniteOptions({ ...baseFilter, boardId: 'board-new' });
+ let oldRequestSignal: AbortSignal | undefined;
+ let resolveOldRequest: ((page: GalleryImagesPage) => void) | undefined;
+ let oldBackendCompleted = false;
+
+ backend.listGalleryImages.mockImplementation(({ boardId, signal }: { boardId: string; signal: AbortSignal }) => {
+ if (boardId === 'board-old') {
+ oldRequestSignal = signal;
+
+ return new Promise<GalleryImagesPage>((resolve) => {
+ resolveOldRequest = (page) => {
+ oldBackendCompleted = true;
+ resolve(page);
+ };
+ });
+ }
+
+ return Promise.resolve(createPage({ count: 1, offset: 0, prefix: 'new', total: 1 }));
+ });
+
+ const observer = new InfiniteQueryObserver(queryClient, oldOptions);
+ const unsubscribe = observer.subscribe(() => undefined);
+
+ try {
+ await vi.waitFor(() => {
+ expect(backend.listGalleryImages).toHaveBeenCalledTimes(1);
+ });
+
+ observer.setOptions(newOptions);
+
+ await vi.waitFor(() => {
+ expect(flattenGalleryImagesData(observer.getCurrentResult().data)[0]?.imageName).toBe('new-0');
+ });
+ expect(oldRequestSignal?.aborted).toBe(true);
+
+ resolveOldRequest?.(createPage({ count: 1, offset: 0, prefix: 'old', total: 1 }));
+ await vi.waitFor(() => {
+ expect(oldBackendCompleted).toBe(true);
+ });
+
+ expect(queryClient.getQueryData(oldOptions.queryKey)).toBeUndefined();
+ expect(
+ flattenGalleryImagesData(
+ queryClient.getQueryData<InfiniteData<GalleryImagesPage, number>>(newOptions.queryKey)
+ )[0]?.imageName
+ ).toBe('new-0');
+ } finally {
+ unsubscribe();
+ observer.destroy();
+ }
+ });
+
+ it('fetches a date-board name list once while hydrating multiple fixed pages', async () => {
+ const queryClient = createQueryClient();
+ const imageNames = Array.from({ length: 180 }, (_, index) => `date-${index}`);
+ backend.listGalleryDateBoardImageNames.mockResolvedValue({ imageNames, total: imageNames.length });
+ backend.hydrateGalleryDateBoardImagePage.mockImplementation(
+ ({
+ imageNames: names,
+ limit,
+ offset,
+ total,
+ }: {
+ imageNames: string[];
+ limit: number;
+ offset: number;
+ total: number;
+ }) =>
+ Promise.resolve({
+ images: names.slice(offset, offset + limit).map((_, index) => createImage(offset + index, 'date')),
+ total,
+ })
);
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- const options = galleryImagesOptions({
- boardId: 'none',
- galleryView: 'images',
- searchTerm: '',
+ const options = galleryImagesInfiniteOptions({
+ ...baseFilter,
+ boardId: 'by_date:2026-07-18',
+ createdFrom: '2026-07-01',
+ createdTo: '2026-07-31',
});
- const oldRequest = queryClient.fetchQuery(options);
+ const observer = new InfiniteQueryObserver(queryClient, options);
- accountLifecycle.invalidate();
- accountLifecycle.activate('user-b');
- resolveImages?.({ images: [], total: 0 });
+ try {
+ await observer.refetch();
+ await observer.fetchNextPage();
+ await observer.fetchNextPage();
+
+ expect(backend.listGalleryDateBoardImageNames).toHaveBeenCalledOnce();
+ expect(backend.hydrateGalleryDateBoardImagePage.mock.calls.map(([request]) => request.offset)).toEqual([
+ 0, 60, 120,
+ ]);
+ expect(backend.hydrateGalleryDateBoardImagePage.mock.calls.map(([request]) => request.limit)).toEqual([
+ 60, 60, 60,
+ ]);
+ expect(observer.getCurrentResult().data?.pageParams).toEqual([0, 60, 120]);
+ expect(flattenGalleryImagesData(observer.getCurrentResult().data)).toHaveLength(180);
+ expect(backend.listGalleryImages).not.toHaveBeenCalled();
+
+ backend.listGalleryDateBoardImageNames.mockResolvedValueOnce({
+ imageNames: [`refreshed-date-image`, ...imageNames],
+ total: imageNames.length + 1,
+ });
+ await invalidateGalleryImages(queryClient);
+ await observer.refetch();
- await expect(oldRequest).rejects.toThrow('no longer active');
- expect(queryClient.getQueryData(options.queryKey)).toBeUndefined();
+ expect(backend.listGalleryDateBoardImageNames).toHaveBeenCalledTimes(2);
+ } finally {
+ observer.destroy();
+ }
+ });
+
+ it('does not cancel a shared date-name request when one list consumer is cancelled', async () => {
+ const queryClient = createQueryClient();
+ let namesSignal: AbortSignal | undefined;
+ let resolveNames: ((value: { imageNames: string[]; total: number }) => void) | undefined;
+ backend.listGalleryDateBoardImageNames.mockImplementation(
+ ({ signal }: { signal: AbortSignal }) =>
+ new Promise<{ imageNames: string[]; total: number }>((resolve) => {
+ namesSignal = signal;
+ resolveNames = resolve;
+ })
+ );
+ backend.hydrateGalleryDateBoardImagePage.mockResolvedValue(
+ createPage({ count: 1, offset: 0, prefix: 'shared-date', total: 1 })
+ );
+ const filter = { ...baseFilter, boardId: 'by_date:2026-07-18' };
+ const infiniteOptions = galleryImagesInfiniteOptions(filter);
+ const pageOptions = galleryImagesInfiniteOptions(filter, { kind: 'anchor', offset: 0 });
+ const infiniteRequest = queryClient.fetchInfiniteQuery(infiniteOptions);
+ const pageRequest = queryClient.fetchInfiniteQuery(pageOptions);
+
+ await vi.waitFor(() => {
+ expect(queryClient.getQueryState(infiniteOptions.queryKey)?.fetchStatus).toBe('fetching');
+ expect(queryClient.getQueryState(pageOptions.queryKey)?.fetchStatus).toBe('fetching');
+ expect(backend.listGalleryDateBoardImageNames).toHaveBeenCalledOnce();
+ });
+
+ await queryClient.cancelQueries({ exact: true, queryKey: pageOptions.queryKey });
+
+ expect(namesSignal?.aborted).toBe(false);
+ resolveNames?.({ imageNames: ['shared-date-0'], total: 1 });
+ await expect(infiniteRequest).resolves.toMatchObject({
+ pages: [{ images: [{ imageName: 'shared-date-0' }], total: 1 }],
+ });
+ await pageRequest.catch(() => undefined);
});
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
index cfaf1bf7d8..875474a313 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
@@ -1,48 +1,242 @@
-import type { GalleryBoardOrderBy, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';
+import type {
+ GalleryBoardOrderBy,
+ GalleryImage,
+ GalleryImagesPage,
+ GalleryOrderDir,
+ GalleryView,
+} from '@features/gallery/core/types';
+import type { AccountScope } from '@platform/state/accountLifecycle';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
-import { queryOptions } from '@tanstack/react-query';
+import {
+ hashKey,
+ infiniteQueryOptions,
+ queryOptions,
+ type InfiniteData,
+ type QueryClient,
+ type QueryKey,
+} from '@tanstack/react-query';
-import { listGalleryBoards, listGalleryDateBoards, listGalleryImages } from './backend';
+import {
+ type GalleryDateBoardImageNames,
+ hydrateGalleryDateBoardImagePage,
+ isDateBoardId,
+ listGalleryBoards,
+ listGalleryDateBoardImageNames,
+ listGalleryDateBoards,
+ listGalleryImages,
+} from './backend';
+
+export const GALLERY_PAGE_SIZE = 60;
+export const GALLERY_MAX_INFINITE_PAGES = 10;
+export const GALLERY_MAX_ROWS = GALLERY_PAGE_SIZE * GALLERY_MAX_INFINITE_PAGES;
export interface GalleryBoardsQuery {
includeArchived?: boolean;
includeDateBoards?: boolean;
orderBy?: GalleryBoardOrderBy;
orderDir?: GalleryOrderDir;
- revision?: string;
}
-export interface GalleryImagesQuery {
+interface CanonicalGalleryBoardsQuery {
+ includeArchived: boolean;
+ includeDateBoards: boolean;
+ orderBy: GalleryBoardOrderBy;
+ orderDir: GalleryOrderDir;
+}
+
+export interface GalleryImagesFilter {
boardId: string;
/** Inclusive lower-bound calendar day (YYYY-MM-DD) on created_at. */
createdFrom?: string;
/** Inclusive upper-bound calendar day (YYYY-MM-DD) on created_at. */
createdTo?: string;
galleryView: GalleryView;
- limit?: number;
- offset?: number;
orderDir?: GalleryOrderDir;
- revision?: string;
searchTerm: string;
starredFirst?: boolean;
}
+export interface CanonicalGalleryImagesFilter {
+ boardId: string;
+ createdFrom?: string;
+ createdTo?: string;
+ galleryView: GalleryView;
+ orderDir: GalleryOrderDir;
+ searchTerm: string;
+ starredFirst: boolean;
+}
+
+export type GalleryImagesWindow = { kind: 'anchor'; offset: number } | { kind: 'infinite' };
+
+interface GalleryAccountKey {
+ accountId: string | null;
+ epoch: number;
+}
+
+type GalleryImagesInfiniteQueryKey = readonly [
+ 'gallery',
+ 'images',
+ 'list',
+ GalleryAccountKey,
+ CanonicalGalleryImagesFilter,
+];
+
+type GalleryImagesAnchorQueryKey = readonly [...GalleryImagesInfiniteQueryKey, 'anchor', number];
+
+export type GalleryImagesListQueryKey = GalleryImagesAnchorQueryKey | GalleryImagesInfiniteQueryKey;
+
+const canonicalizeBoardsQuery = (query: GalleryBoardsQuery): CanonicalGalleryBoardsQuery => ({
+ includeArchived: query.includeArchived ?? false,
+ includeDateBoards: query.includeDateBoards ?? false,
+ orderBy: query.orderBy ?? 'created_at',
+ orderDir: query.orderDir ?? 'DESC',
+});
+
+export const canonicalizeGalleryImagesFilter = (filter: GalleryImagesFilter): CanonicalGalleryImagesFilter => ({
+ boardId: filter.boardId,
+ ...(filter.createdFrom ? { createdFrom: filter.createdFrom } : {}),
+ ...(filter.createdTo ? { createdTo: filter.createdTo } : {}),
+ galleryView: filter.galleryView,
+ orderDir: filter.orderDir ?? 'DESC',
+ searchTerm: filter.searchTerm.trim(),
+ starredFirst: filter.starredFirst ?? false,
+});
+
+const getAccountKey = (owner: AccountScope): GalleryAccountKey => ({
+ accountId: owner.accountId,
+ epoch: owner.epoch,
+});
+
+const normalizePageOffset = (offset: number): number =>
+ Math.max(0, Math.floor(offset / GALLERY_PAGE_SIZE) * GALLERY_PAGE_SIZE);
+
+const getWindowKey = (window: GalleryImagesWindow): readonly [] | readonly ['anchor', number] =>
+ window.kind === 'infinite' ? [] : ([window.kind, normalizePageOffset(window.offset)] as const);
+
export const galleryKeys = {
all: ['gallery'] as const,
- boards: (query: GalleryBoardsQuery) => [...galleryKeys.all, 'boards', query] as const,
- images: (query: GalleryImagesQuery) => [...galleryKeys.all, 'images', query] as const,
+ boardsRoot: () => [...galleryKeys.all, 'boards'] as const,
+ boardsForAccount: (owner: AccountScope) => [...galleryKeys.boardsRoot(), getAccountKey(owner)] as const,
+ boards: (owner: AccountScope, query: CanonicalGalleryBoardsQuery) =>
+ [...galleryKeys.boardsForAccount(owner), query] as const,
+ imagesRoot: () => [...galleryKeys.all, 'images'] as const,
+ imageListsRoot: () => [...galleryKeys.imagesRoot(), 'list'] as const,
+ imageListsForAccount: (owner: AccountScope) => [...galleryKeys.imageListsRoot(), getAccountKey(owner)] as const,
+ images: (
+ owner: AccountScope,
+ filter: CanonicalGalleryImagesFilter,
+ window: GalleryImagesWindow = { kind: 'infinite' }
+ ): GalleryImagesListQueryKey =>
+ [...galleryKeys.imageListsForAccount(owner), filter, ...getWindowKey(window)] as GalleryImagesListQueryKey,
+ dateBoardNamesRoot: () => [...galleryKeys.imagesRoot(), 'date-names'] as const,
+ dateBoardNamesForAccount: (owner: AccountScope) =>
+ [...galleryKeys.dateBoardNamesRoot(), getAccountKey(owner)] as const,
+ dateBoardNames: (owner: AccountScope, filter: CanonicalGalleryImagesFilter) =>
+ [...galleryKeys.dateBoardNamesForAccount(owner), filter] as const,
+};
+
+const galleryDateBoardNamesOptions = (owner: AccountScope, filter: CanonicalGalleryImagesFilter) =>
+ queryOptions({
+ queryFn: async ({ signal }) => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
+ const result = await listGalleryDateBoardImageNames({ ...filter, signal: requestSignal });
+
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+
+ return result;
+ },
+ queryKey: galleryKeys.dateBoardNames(owner, filter),
+ staleTime: 60_000,
+ });
+
+const dateBoardNamesConsumers = new WeakMap<QueryClient, Map<string, number>>();
+
+/**
+ * A date-name request is shared by infinite and paginated consumers. One
+ * consumer may stop waiting immediately without cancelling work still needed
+ * by another; the final departing consumer owns cancellation.
+ */
+const fetchSharedDateBoardNames = (
+ client: QueryClient,
+ queryKey: QueryKey,
+ signal: AbortSignal,
+ fetchNames: () => Promise<GalleryDateBoardImageNames>
+): Promise<GalleryDateBoardImageNames> => {
+ const queryHash = hashKey(queryKey);
+ const consumers = dateBoardNamesConsumers.get(client) ?? new Map<string, number>();
+
+ dateBoardNamesConsumers.set(client, consumers);
+ consumers.set(queryHash, (consumers.get(queryHash) ?? 0) + 1);
+
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const release = (cancelIfLast: boolean) => {
+ const remainingConsumers = Math.max(0, (consumers.get(queryHash) ?? 1) - 1);
+
+ if (remainingConsumers === 0) {
+ consumers.delete(queryHash);
+ if (cancelIfLast) {
+ void client.cancelQueries({ exact: true, queryKey });
+ }
+ } else {
+ consumers.set(queryHash, remainingConsumers);
+ }
+ };
+ const onAbort = () => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ signal.removeEventListener('abort', onAbort);
+ release(true);
+ reject(signal.reason ?? new DOMException('The operation was aborted.', 'AbortError'));
+ };
+ const settle = (complete: () => void) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ signal.removeEventListener('abort', onAbort);
+ release(false);
+ complete();
+ };
+
+ signal.addEventListener('abort', onAbort, { once: true });
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+
+ let namesPromise: Promise<GalleryDateBoardImageNames>;
+
+ try {
+ namesPromise = fetchNames();
+ } catch (error: unknown) {
+ settle(() => reject(error));
+ return;
+ }
+
+ void namesPromise.then(
+ (names) => settle(() => resolve(names)),
+ (error: unknown) => settle(() => reject(error))
+ );
+ });
};
export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) => {
const owner = captureAccountScope();
+ const canonicalQuery = canonicalizeBoardsQuery(query);
return queryOptions({
queryFn: async ({ signal }) => {
const requestSignal = AbortSignal.any([signal, owner.signal]);
const [boards, dateBoards] = await Promise.all([
- listGalleryBoards({ ...query, signal: requestSignal }),
- query.includeDateBoards ? listGalleryDateBoards(requestSignal) : Promise.resolve([]),
+ listGalleryBoards({ ...canonicalQuery, signal: requestSignal }),
+ canonicalQuery.includeDateBoards ? listGalleryDateBoards(requestSignal) : Promise.resolve([]),
]);
assertAccountScopeCurrent(owner);
@@ -50,25 +244,129 @@ export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) => {
return [...boards, ...dateBoards];
},
- queryKey: galleryKeys.boards(query),
+ queryKey: galleryKeys.boards(owner, canonicalQuery),
staleTime: 60_000,
});
};
-export const galleryImagesOptions = (query: GalleryImagesQuery) => {
+const getNextPageParam = (
+ window: GalleryImagesWindow,
+ lastPage: GalleryImagesPage,
+ lastPageParam: number
+): number | undefined => {
+ const nextOffset = lastPageParam + GALLERY_PAGE_SIZE;
+
+ const isInsideWindow = window.kind === 'anchor' || nextOffset < GALLERY_MAX_ROWS;
+
+ return isInsideWindow && nextOffset < lastPage.total ? nextOffset : undefined;
+};
+
+export const galleryImagesInfiniteOptions = (
+ inputFilter: GalleryImagesFilter,
+ window: GalleryImagesWindow = { kind: 'infinite' }
+) => {
const owner = captureAccountScope();
+ const filter = canonicalizeGalleryImagesFilter(inputFilter);
+ const normalizedWindow =
+ window.kind === 'infinite' ? window : ({ ...window, offset: normalizePageOffset(window.offset) } as const);
+ const initialPageParam = normalizedWindow.kind === 'infinite' ? 0 : normalizedWindow.offset;
- return queryOptions({
- queryFn: async ({ signal }) => {
+ return infiniteQueryOptions<
+ GalleryImagesPage,
+ Error,
+ InfiniteData<GalleryImagesPage, number>,
+ GalleryImagesListQueryKey,
+ number
+ >({
+ ...(normalizedWindow.kind === 'infinite' ? {} : { gcTime: 0 }),
+ getNextPageParam: (lastPage, allPages, lastPageParam) =>
+ allPages.length >= GALLERY_MAX_INFINITE_PAGES
+ ? undefined
+ : getNextPageParam(normalizedWindow, lastPage, lastPageParam),
+ getPreviousPageParam: (_firstPage, allPages, firstPageParam) =>
+ allPages.length < GALLERY_MAX_INFINITE_PAGES && firstPageParam >= GALLERY_PAGE_SIZE
+ ? firstPageParam - GALLERY_PAGE_SIZE
+ : undefined,
+ initialPageParam,
+ maxPages: GALLERY_MAX_INFINITE_PAGES,
+ queryFn: async ({ client, pageParam, signal }) => {
const requestSignal = AbortSignal.any([signal, owner.signal]);
- const result = await listGalleryImages({ ...query, signal: requestSignal });
+ let result: GalleryImagesPage;
+
+ if (isDateBoardId(filter.boardId)) {
+ const namesOptions = galleryDateBoardNamesOptions(owner, filter);
+ const names = await fetchSharedDateBoardNames(client, namesOptions.queryKey, requestSignal, () =>
+ client.fetchQuery(namesOptions)
+ );
+
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+ result = await hydrateGalleryDateBoardImagePage({
+ ...names,
+ limit: GALLERY_PAGE_SIZE,
+ offset: pageParam,
+ signal: requestSignal,
+ });
+ } else {
+ result = await listGalleryImages({
+ ...filter,
+ limit: GALLERY_PAGE_SIZE,
+ offset: pageParam,
+ signal: requestSignal,
+ });
+ }
assertAccountScopeCurrent(owner);
requestSignal.throwIfAborted();
- return result;
+ return result.images.length <= GALLERY_PAGE_SIZE
+ ? result
+ : { ...result, images: result.images.slice(0, GALLERY_PAGE_SIZE) };
},
- queryKey: galleryKeys.images(query),
+ queryKey: galleryKeys.images(owner, filter, normalizedWindow),
staleTime: 60_000,
});
};
+
+export const flattenGalleryImagesData = (data: InfiniteData<GalleryImagesPage, number> | undefined): GalleryImage[] => {
+ if (!data) {
+ return [];
+ }
+
+ const imageNames = new Set<string>();
+ const images: GalleryImage[] = [];
+
+ for (const page of data.pages) {
+ for (const image of page.images) {
+ if (imageNames.has(image.imageName)) {
+ continue;
+ }
+
+ imageNames.add(image.imageName);
+ images.push(image);
+
+ if (images.length === GALLERY_MAX_ROWS) {
+ return images;
+ }
+ }
+ }
+
+ return images;
+};
+
+export const getGalleryImagesFilterFromKey = (queryKey: QueryKey): CanonicalGalleryImagesFilter | null => {
+ if (
+ queryKey[0] !== 'gallery' ||
+ queryKey[1] !== 'images' ||
+ queryKey[2] !== 'list' ||
+ !queryKey[4] ||
+ typeof queryKey[4] !== 'object'
+ ) {
+ return null;
+ }
+
+ return queryKey[4] as CanonicalGalleryImagesFilter;
+};
+
+export const getGalleryImageListQueries = (client: QueryClient, owner: AccountScope = captureAccountScope()) =>
+ client.getQueryCache().findAll({ queryKey: galleryKeys.imageListsForAccount(owner) });
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
new file mode 100644
index 0000000000..8f5ef41583
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
@@ -0,0 +1,266 @@
+import type { GalleryImage, GalleryImagesPage } from '@features/gallery/core/types';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
+import { QueryClient, type InfiniteData } from '@tanstack/react-query';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { ALL_READABLE_BOARDS_ID } from './backend';
+import { canonicalizeGalleryImagesFilter, galleryKeys } from './queries';
+import { invalidateGallery, invalidateGalleryImages, patchGalleryImageCaches } from './queryCache';
+
+type GalleryImagesData = InfiniteData<GalleryImagesPage, number>;
+
+const createClient = (): QueryClient =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ gcTime: Infinity,
+ retry: false,
+ },
+ },
+ });
+
+const createImage = (imageName: string, boardId = 'board-1', starred = false): GalleryImage => ({
+ boardId,
+ height: 768,
+ imageCategory: 'general',
+ imageName,
+ imageUrl: `/api/v1/images/i/${imageName}/full`,
+ queuedAt: '2026-07-26T00:00:00.000Z',
+ sourceQueueItemId: 'backend-gallery',
+ starred,
+ thumbnailUrl: `/api/v1/images/i/${imageName}/thumbnail`,
+ width: 512,
+});
+
+const createData = (pages: GalleryImage[][]): GalleryImagesData => {
+ const total = pages.reduce((count, images) => count + images.length, 0);
+
+ return {
+ pageParams: pages.map((_, index) => index * 60),
+ pages: pages.map((images) => ({ images, total })),
+ };
+};
+
+const getImagesKey = (boardId: string, owner: AccountScope = captureAccountScope()) =>
+ galleryKeys.images(
+ owner,
+ canonicalizeGalleryImagesFilter({
+ boardId,
+ galleryView: 'images',
+ searchTerm: '',
+ })
+ );
+
+const getData = (client: QueryClient, queryKey: ReturnType<typeof getImagesKey>): GalleryImagesData => {
+ const data = client.getQueryData<GalleryImagesData>(queryKey);
+
+ expect(data).toBeDefined();
+
+ return data as GalleryImagesData;
+};
+
+describe('Gallery image cache patches', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('gallery-query-cache-test');
+ });
+
+ it('patches a star in place and rolls back without rebuilding untouched pages or page params', () => {
+ const client = createClient();
+ const target = createImage('target.png');
+ const samePageUntouched = createImage('same-page-untouched.png');
+ const untouchedPageImage = createImage('untouched-page.png');
+ const key = getImagesKey('board-1');
+
+ client.setQueryData(key, createData([[target, samePageUntouched], [untouchedPageImage]]));
+ const before = getData(client, key);
+ const firstPageBefore = before.pages[0];
+ const untouchedPageBefore = before.pages[1];
+ const pageParamsBefore = before.pageParams;
+
+ const rollback = patchGalleryImageCaches(client, {
+ imageNames: [target.imageName],
+ kind: 'star',
+ starred: true,
+ });
+ const after = getData(client, key);
+
+ expect(after).not.toBe(before);
+ expect(after.pageParams).toBe(pageParamsBefore);
+ expect(after.pages[0]).not.toBe(firstPageBefore);
+ expect(after.pages[1]).toBe(untouchedPageBefore);
+ expect(after.pages[0]?.images[0]).toEqual({ ...target, starred: true });
+ expect(after.pages[0]?.images[1]).toBe(samePageUntouched);
+
+ rollback();
+
+ const rolledBack = getData(client, key);
+
+ expect(rolledBack).toEqual(before);
+ expect(rolledBack.pageParams).toBe(pageParamsBefore);
+ expect(rolledBack.pages[1]).toBe(untouchedPageBefore);
+ expect(rolledBack.pages[0]?.images[1]).toBe(samePageUntouched);
+ });
+
+ it('deletes matching images across pages and keeps each page total consistent', () => {
+ const client = createClient();
+ const firstTarget = createImage('first-target.png');
+ const firstUntouched = createImage('first-untouched.png');
+ const secondTarget = createImage('second-target.png');
+ const secondUntouched = createImage('second-untouched.png');
+ const key = getImagesKey('board-1');
+
+ client.setQueryData(
+ key,
+ createData([
+ [firstTarget, firstUntouched],
+ [secondTarget, secondUntouched],
+ ])
+ );
+ const before = getData(client, key);
+
+ patchGalleryImageCaches(client, {
+ imageNames: [firstTarget.imageName, secondTarget.imageName],
+ kind: 'delete',
+ });
+ const after = getData(client, key);
+
+ expect(after.pageParams).toBe(before.pageParams);
+ expect(after.pages.map((page) => page.images)).toEqual([[firstUntouched], [secondUntouched]]);
+ expect(after.pages.map((page) => page.total)).toEqual([2, 2]);
+ });
+
+ it('removes moved images from source boards while all-images and date views retain the updated image', () => {
+ const client = createClient();
+ const target = createImage('moved.png', 'board-1');
+ const untouched = createImage('untouched.png', 'board-1');
+ const sourceKey = getImagesKey('board-1');
+ const allKey = getImagesKey(ALL_READABLE_BOARDS_ID);
+ const dateKey = getImagesKey('by_date:2026-07-26');
+
+ client.setQueryData(sourceKey, createData([[target], [untouched]]));
+ client.setQueryData(allKey, createData([[target], [untouched]]));
+ client.setQueryData(dateKey, createData([[target], [untouched]]));
+
+ patchGalleryImageCaches(client, {
+ boardId: 'board-2',
+ imageNames: [target.imageName],
+ kind: 'move',
+ });
+
+ const source = getData(client, sourceKey);
+ const all = getData(client, allKey);
+ const date = getData(client, dateKey);
+
+ expect(source.pages.flatMap((page) => page.images)).toEqual([untouched]);
+ expect(source.pages.map((page) => page.total)).toEqual([1, 1]);
+ for (const retained of [all, date]) {
+ expect(retained.pages.flatMap((page) => page.images)).toEqual([{ ...target, boardId: 'board-2' }, untouched]);
+ expect(retained.pages.map((page) => page.total)).toEqual([2, 2]);
+ }
+ });
+
+ it('does not let rollback clobber a later concurrent cache update', () => {
+ const client = createClient();
+ const target = createImage('target.png');
+ const key = getImagesKey('board-1');
+
+ client.setQueryData(key, createData([[target]]));
+ const rollback = patchGalleryImageCaches(client, {
+ imageNames: [target.imageName],
+ kind: 'star',
+ starred: true,
+ });
+ const concurrent = client.setQueryData<GalleryImagesData>(key, (current) => {
+ if (!current) {
+ return current;
+ }
+
+ return {
+ ...current,
+ pages: current.pages.map((page) => ({
+ ...page,
+ images: page.images.map((image) =>
+ image.imageName === target.imageName ? { ...image, boardId: 'board-concurrent' } : image
+ ),
+ })),
+ };
+ });
+
+ rollback();
+
+ expect(getData(client, key)).toBe(concurrent);
+ expect(getData(client, key).pages[0]?.images[0]).toMatchObject({
+ boardId: 'board-concurrent',
+ imageName: target.imageName,
+ starred: true,
+ });
+ });
+});
+
+describe('Gallery cache invalidation', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('gallery-query-cache-invalidation-test');
+ });
+
+ it('invalidates only current-account Gallery domains and never grows query cardinality', async () => {
+ const client = createClient();
+ const oldOwner = captureAccountScope();
+ const oldImagesKey = getImagesKey('board-1', oldOwner);
+ const oldFilter = canonicalizeGalleryImagesFilter({
+ boardId: 'by_date:2026-07-25',
+ galleryView: 'images',
+ searchTerm: '',
+ });
+ const oldDateNamesKey = galleryKeys.dateBoardNames(oldOwner, oldFilter);
+ const oldBoardsKey = galleryKeys.boards(oldOwner, {
+ includeArchived: false,
+ includeDateBoards: true,
+ orderBy: 'created_at',
+ orderDir: 'DESC',
+ });
+
+ client.setQueryData(oldImagesKey, createData([[createImage('old.png')]]));
+ client.setQueryData(oldDateNamesKey, { imageNames: ['old.png'], total: 1 });
+ client.setQueryData(oldBoardsKey, []);
+
+ accountLifecycle.activate('gallery-query-cache-current-account');
+ const currentOwner = captureAccountScope();
+ const currentImagesKey = getImagesKey('board-1', currentOwner);
+ const currentFilter = canonicalizeGalleryImagesFilter({
+ boardId: 'by_date:2026-07-26',
+ galleryView: 'images',
+ searchTerm: '',
+ });
+ const currentDateNamesKey = galleryKeys.dateBoardNames(currentOwner, currentFilter);
+ const currentBoardsKey = galleryKeys.boards(currentOwner, {
+ includeArchived: false,
+ includeDateBoards: true,
+ orderBy: 'created_at',
+ orderDir: 'DESC',
+ });
+
+ client.setQueryData(currentImagesKey, createData([[createImage('current.png')]]));
+ client.setQueryData(currentDateNamesKey, { imageNames: ['current.png'], total: 1 });
+ client.setQueryData(currentBoardsKey, []);
+ const initialCardinality = client.getQueryCache().getAll().length;
+
+ for (let index = 0; index < 100; index += 1) {
+ await invalidateGalleryImages(client);
+ }
+
+ expect(client.getQueryCache().getAll()).toHaveLength(initialCardinality);
+ expect(client.getQueryState(currentImagesKey)?.isInvalidated).toBe(true);
+ expect(client.getQueryState(currentDateNamesKey)?.isInvalidated).toBe(true);
+ expect(client.getQueryState(currentBoardsKey)?.isInvalidated).toBe(false);
+ expect(client.getQueryState(oldImagesKey)?.isInvalidated).toBe(false);
+ expect(client.getQueryState(oldDateNamesKey)?.isInvalidated).toBe(false);
+
+ await invalidateGallery(client);
+
+ expect(client.getQueryCache().getAll()).toHaveLength(initialCardinality);
+ expect(client.getQueryState(currentBoardsKey)?.isInvalidated).toBe(true);
+ expect(client.getQueryState(oldBoardsKey)?.isInvalidated).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
new file mode 100644
index 0000000000..a7711960ad
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
@@ -0,0 +1,292 @@
+import type { GalleryImage, GalleryImagesPage } from '@features/gallery/core/types';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query';
+
+import { captureAccountScope } from '@platform/state/accountLifecycle';
+import { hashKey } from '@tanstack/react-query';
+
+import { ALL_READABLE_BOARDS_ID, isDateBoardId } from './backend';
+import {
+ galleryKeys,
+ getGalleryImageListQueries,
+ getGalleryImagesFilterFromKey,
+ type CanonicalGalleryImagesFilter,
+} from './queries';
+
+export type GalleryImageCachePatch =
+ | { imageNames: readonly string[]; kind: 'delete' }
+ | { boardId: string; imageNames: readonly string[]; kind: 'move' }
+ | { imageNames: readonly string[]; kind: 'star'; starred: boolean };
+
+interface CacheRollbackEntry {
+ after: InfiniteData<GalleryImagesPage, number>;
+ before: InfiniteData<GalleryImagesPage, number>;
+ queryKey: QueryKey;
+}
+
+const isGalleryImagesData = (value: unknown): value is InfiniteData<GalleryImagesPage, number> => {
+ if (!value || typeof value !== 'object' || !('pages' in value) || !('pageParams' in value)) {
+ return false;
+ }
+
+ const data = value as { pages?: unknown; pageParams?: unknown };
+
+ return Array.isArray(data.pages) && Array.isArray(data.pageParams);
+};
+
+const mapPageImages = (
+ page: GalleryImagesPage,
+ mapImage: (image: GalleryImage) => GalleryImage | null,
+ totalDelta = 0
+): GalleryImagesPage => {
+ let changed = false;
+ const images: GalleryImage[] = [];
+
+ for (const image of page.images) {
+ const nextImage = mapImage(image);
+
+ if (nextImage !== image) {
+ changed = true;
+ }
+ if (nextImage) {
+ images.push(nextImage);
+ }
+ }
+
+ if (!changed && totalDelta === 0) {
+ return page;
+ }
+
+ return {
+ ...page,
+ images: changed ? images : page.images,
+ total: Math.max(0, page.total - totalDelta),
+ };
+};
+
+const patchPage = (
+ page: GalleryImagesPage,
+ filter: CanonicalGalleryImagesFilter,
+ patch: GalleryImageCachePatch,
+ imageNames: ReadonlySet<string>,
+ removedImageCount: number
+): GalleryImagesPage => {
+ if (patch.kind === 'star') {
+ return mapPageImages(page, (image) => {
+ if (!imageNames.has(image.imageName) || image.starred === patch.starred) {
+ return image;
+ }
+
+ return { ...image, starred: patch.starred };
+ });
+ }
+
+ if (patch.kind === 'delete') {
+ return mapPageImages(page, (image) => (imageNames.has(image.imageName) ? null : image), removedImageCount);
+ }
+
+ const keepsMovedImages =
+ filter.boardId === ALL_READABLE_BOARDS_ID || filter.boardId === patch.boardId || isDateBoardId(filter.boardId);
+
+ return mapPageImages(
+ page,
+ (image) => {
+ if (!imageNames.has(image.imageName)) {
+ return image;
+ }
+
+ if (!keepsMovedImages) {
+ return null;
+ }
+
+ return image.boardId === patch.boardId ? image : { ...image, boardId: patch.boardId };
+ },
+ keepsMovedImages ? 0 : removedImageCount
+ );
+};
+
+const patchInfiniteData = (
+ data: InfiniteData<GalleryImagesPage, number>,
+ filter: CanonicalGalleryImagesFilter,
+ patch: GalleryImageCachePatch
+): InfiniteData<GalleryImagesPage, number> => {
+ const imageNames = new Set(patch.imageNames);
+ const removesImages =
+ patch.kind === 'delete' ||
+ (patch.kind === 'move' &&
+ filter.boardId !== ALL_READABLE_BOARDS_ID &&
+ filter.boardId !== patch.boardId &&
+ !isDateBoardId(filter.boardId));
+ const removedImageNames = new Set<string>();
+
+ if (removesImages) {
+ for (const page of data.pages) {
+ for (const image of page.images) {
+ if (imageNames.has(image.imageName)) {
+ removedImageNames.add(image.imageName);
+ }
+ }
+ }
+ }
+
+ let changed = false;
+ const pages = data.pages.map((page) => {
+ const nextPage = patchPage(page, filter, patch, imageNames, removedImageNames.size);
+ changed ||= nextPage !== page;
+
+ return nextPage;
+ });
+
+ return changed ? { ...data, pages } : data;
+};
+
+/**
+ * Applies a small mutation to every currently cached page for this account.
+ * The returned rollback is concurrency-safe: it only restores an entry while
+ * the optimistic value is still the current cache value.
+ */
+export const patchGalleryImageCaches = (client: QueryClient, patch: GalleryImageCachePatch): (() => void) => {
+ if (patch.imageNames.length === 0) {
+ return () => undefined;
+ }
+
+ const rollbackEntries: CacheRollbackEntry[] = [];
+
+ for (const query of getGalleryImageListQueries(client)) {
+ const before = query.state.data;
+ const filter = getGalleryImagesFilterFromKey(query.queryKey);
+
+ if (!filter || !isGalleryImagesData(before)) {
+ continue;
+ }
+
+ // A starred-first query cannot be patched coherently in place: changing
+ // the flag may move an image across pages. Leave that cache untouched and
+ // let the post-mutation invalidation rebuild its server-defined order.
+ if (patch.kind === 'star' && filter.starredFirst) {
+ continue;
+ }
+
+ const after = patchInfiniteData(before, filter, patch);
+
+ if (after === before) {
+ continue;
+ }
+
+ const applied = client.setQueryData<InfiniteData<GalleryImagesPage, number>>(query.queryKey, after);
+
+ if (applied) {
+ rollbackEntries.push({ after: applied, before, queryKey: query.queryKey });
+ }
+ }
+
+ return () => {
+ for (const { after, before, queryKey } of rollbackEntries) {
+ if (client.getQueryData(queryKey) === after) {
+ client.setQueryData(queryKey, before);
+ }
+ }
+ };
+};
+
+const runGalleryInvalidation = async (
+ client: QueryClient,
+ owner: AccountScope,
+ includeBoards: boolean
+): Promise<void> => {
+ // Date-board page queries depend on the supporting names query. Mark that
+ // stale first so an active page refetch cannot observe the old name list.
+ await client.cancelQueries({ queryKey: galleryKeys.dateBoardNamesForAccount(owner) });
+ await client.invalidateQueries({
+ queryKey: galleryKeys.dateBoardNamesForAccount(owner),
+ refetchType: 'none',
+ });
+ await client.cancelQueries({ queryKey: galleryKeys.imageListsForAccount(owner) });
+
+ // Refetching an infinite query replays every retained page. Collapse each
+ // logical window to its pinned page first; users can explicitly load the
+ // surrounding pages again, while a mutation costs one list request.
+ for (const query of getGalleryImageListQueries(client, owner)) {
+ const data = query.state.data;
+
+ if (!isGalleryImagesData(data) || data.pages.length <= 1) {
+ continue;
+ }
+
+ const anchorOffset =
+ query.queryKey[5] === 'anchor' && typeof query.queryKey[6] === 'number' ? query.queryKey[6] : 0;
+ const anchorIndex = Math.max(0, data.pageParams.indexOf(anchorOffset));
+
+ client.setQueryData<InfiniteData<GalleryImagesPage, number>>(query.queryKey, {
+ pageParams: [data.pageParams[anchorIndex] ?? anchorOffset],
+ pages: [data.pages[anchorIndex] ?? data.pages[0]],
+ });
+ }
+
+ await client.invalidateQueries({ queryKey: galleryKeys.imageListsForAccount(owner) });
+
+ if (includeBoards) {
+ await client.invalidateQueries({ queryKey: galleryKeys.boardsForAccount(owner) });
+ }
+};
+
+interface GalleryInvalidationState {
+ includeBoards: boolean;
+ promise: Promise<void> | null;
+ requested: boolean;
+}
+
+const galleryInvalidations = new WeakMap<QueryClient, Map<string, GalleryInvalidationState>>();
+
+/**
+ * Coalesces same-tick mutation/result bursts and performs at most one trailing
+ * pass when another request arrives during an active invalidation. This avoids
+ * repeatedly cancelling and restarting the same observed Gallery refetch.
+ */
+const scheduleGalleryInvalidation = (
+ client: QueryClient,
+ owner: AccountScope,
+ includeBoards: boolean
+): Promise<void> => {
+ const ownerKey = hashKey(galleryKeys.imageListsForAccount(owner));
+ const clientStates = galleryInvalidations.get(client) ?? new Map<string, GalleryInvalidationState>();
+ const state = clientStates.get(ownerKey) ?? { includeBoards: false, promise: null, requested: false };
+
+ galleryInvalidations.set(client, clientStates);
+ clientStates.set(ownerKey, state);
+ state.includeBoards ||= includeBoards;
+ state.requested = true;
+
+ if (!state.promise) {
+ state.promise = (async () => {
+ try {
+ // Let a synchronous burst collapse into one pass.
+ await Promise.resolve();
+
+ while (state.requested) {
+ state.requested = false;
+ const shouldInvalidateBoards = state.includeBoards;
+
+ state.includeBoards = false;
+ await runGalleryInvalidation(client, owner, shouldInvalidateBoards);
+ }
+ } finally {
+ // No await occurs between the final loop check and this cleanup, so a
+ // caller cannot observe a resolved runner while leaving requested work
+ // stranded behind it.
+ state.promise = null;
+ clientStates.delete(ownerKey);
+ }
+ })();
+ }
+
+ return state.promise;
+};
+
+export const invalidateGalleryImages = (
+ client: QueryClient,
+ owner: AccountScope = captureAccountScope()
+): Promise<void> => scheduleGalleryInvalidation(client, owner, false);
+
+export const invalidateGallery = (client: QueryClient, owner: AccountScope = captureAccountScope()): Promise<void> =>
+ scheduleGalleryInvalidation(client, owner, true);
diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.ts
index 4f10c268a0..d3c8c0b730 100644
--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts
@@ -1,2 +1,19 @@
-export { galleryBoardsOptions, galleryImagesOptions, galleryKeys } from './data/queries';
-export type { GalleryBoardsQuery, GalleryImagesQuery } from './data/queries';
+export {
+ canonicalizeGalleryImagesFilter,
+ flattenGalleryImagesData,
+ GALLERY_MAX_INFINITE_PAGES,
+ GALLERY_MAX_ROWS,
+ GALLERY_PAGE_SIZE,
+ galleryBoardsOptions,
+ galleryImagesInfiniteOptions,
+ galleryKeys,
+} from './data/queries';
+export type {
+ CanonicalGalleryImagesFilter,
+ GalleryBoardsQuery,
+ GalleryImagesFilter,
+ GalleryImagesListQueryKey,
+ GalleryImagesWindow,
+} from './data/queries';
+export { invalidateGallery, invalidateGalleryImages, patchGalleryImageCaches } from './data/queryCache';
+export type { GalleryImageCachePatch } from './data/queryCache';
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index b336af940b..bc5b24c550 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -69,7 +69,7 @@ type GridCell =
export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {
const { t } = useTranslation();
- const { actions, gallery, imageActions, runtime } = useGalleryWidget();
+ const { actions, gallery, imageActions, isWindowTruncated, runtime } = useGalleryWidget();
const { account, antialiasProgressImages, ImageContextMenu, widgets } = useGalleryUi();
const [contextMenuTarget, setContextMenuTarget] = useState<GalleryImageContextMenuTarget | null>(null);
const [isDropActive, setIsDropActive] = useState(false);
@@ -479,6 +479,13 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
<Spinner color="fg.subtle" size="xs" />
</Flex>
)}
+ {paginationMode === 'infinite' && !gallery.isLoading && isWindowTruncated && (
+ <Flex align="center" justify="center" py="3">
+ <Text color="fg.subtle" fontSize="xs" textAlign="center">
+ {t('widgets.gallery.windowLimit', { count: gallery.images.length })}
+ </Text>
+ </Flex>
+ )}
</ScrollArea.Content>
</ScrollArea.Viewport>
<ScrollArea.Scrollbar>
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
index 59565c9f46..ff167c099c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
@@ -16,7 +16,6 @@ export interface GalleryImageActionsOptions {
boards: GalleryBoard[];
generateValues: Record<string, unknown>;
onImagesDeleted(imageNames: string[]): void;
- onStarredChange(imageNames: string[], starred: boolean): void;
projectId: string;
}
@@ -34,6 +33,7 @@ export interface GalleryImageContextMenuProps {
}
export interface GalleryCommandsPort {
+ reconcileDeletedBoard(boardId: string, includeImages: boolean): void;
selectBoard(boardId: string): void;
selectImage(image: GalleryImage): void;
setCompareImage(image: GalleryImage | null): void;
@@ -44,7 +44,6 @@ export interface GalleryCommandsPort {
setSearchTerm(searchTerm: string): void;
setView(view: GalleryView): void;
toggleImageSelection(image: GalleryImage): void;
- touch(): void;
updateSettings(settings: Partial<GallerySettings>): void;
}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
index 5aa8ab30d2..8bf6f3d074 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
@@ -35,6 +35,8 @@ export interface GalleryWidgetContextValue {
gallery: GalleryStateView;
actions: GalleryActions;
imageActions: GalleryImageActions;
+ /** The infinite window is full and the board holds images it cannot reach. */
+ isWindowTruncated: boolean;
projectName: string;
runtime: GalleryWidgetRuntime;
}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx
index 1979706574..3888e5ef3a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetFooter.tsx
@@ -1,5 +1,6 @@
import { ButtonGroup, HStack, Pagination } from '@chakra-ui/react';
import { getGallerySettings } from '@features/gallery/core/settings';
+import { GALLERY_PAGE_SIZE } from '@features/gallery/data/queries';
import { IconButton } from '@platform/ui';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { useCallback } from 'react';
@@ -7,7 +8,6 @@ import { useTranslation } from 'react-i18next';
import { getGalleryPage, getGalleryTotalImages } from './galleryStateView';
import { useGalleryUi } from './GalleryUiContext';
-import { GALLERY_PAGE_SIZE } from './useGalleryData';
const PAGINATION_ITEM_VARIANT = { _selected: 'outline', base: 'ghost' } as const;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
index 0f85650037..8b4a2b6dea 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
@@ -1,4 +1,6 @@
+import { getBoundedRecentImages } from '@features/gallery/core/recentImages';
import { getGallerySettings } from '@features/gallery/core/settings';
+import { GALLERY_PAGE_SIZE } from '@features/gallery/data/queries';
import { StatusWidgetChip } from '@platform/ui';
import { ImageIcon } from 'lucide-react';
import { useCallback, useEffect, useEffectEvent, useMemo, useRef } from 'react';
@@ -9,9 +11,6 @@ import { GalleryPanelContent } from './GalleryPanelContent';
import {
getGalleryPage,
getGalleryProjectBoardId,
- getGalleryImagesRefreshToken,
- getGalleryRecentImagesKey,
- getGalleryRefreshToken,
getGallerySearchTerm,
getGallerySelectedBoardId,
getGalleryStateView,
@@ -26,7 +25,7 @@ import {
} from './GalleryUiContext';
import { GalleryWidgetContext, type GalleryActions, type GalleryWidgetContextValue } from './GalleryWidgetContext';
import { useGalleryActions } from './useGalleryActions';
-import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';
+import { useGalleryData } from './useGalleryData';
export const shouldPublishGalleryTotal = ({
knownTotalImages,
@@ -53,24 +52,20 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
} = useGalleryUi();
const galleryView = getGalleryView(galleryValues);
const searchTerm = getGallerySearchTerm(galleryValues);
- const recentImagesKey = getGalleryRecentImagesKey(galleryValues);
- const refreshToken = getGalleryRefreshToken(galleryValues);
- const imageRefreshToken = getGalleryImagesRefreshToken(galleryValues);
+ const recentImages = useMemo(() => getBoundedRecentImages(galleryValues.recentImages), [galleryValues.recentImages]);
const page = getGalleryPage(galleryValues);
const knownTotalImages = getGalleryTotalImages(galleryValues);
const settings = getGallerySettings(galleryValues);
const data = useGalleryData({
galleryView,
- imageRefreshToken,
page,
- recentImagesKey,
- refreshToken,
+ recentImages,
searchTerm,
selectedBoardId: getGallerySelectedBoardId(galleryValues, []),
settings,
});
- const { loadMore, patchImages, total } = data;
+ const { loadMore, total } = data;
const selectedBoardId = getGallerySelectedBoardId(galleryValues, data.boards);
const gallery = getGalleryStateView(
galleryValues,
@@ -82,15 +77,6 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
liveProgressTarget
);
- const onStarredChange = useCallback(
- (imageNames: string[], starred: boolean) => {
- patchImages((images) =>
- images.map((image) => (imageNames.includes(image.imageName) ? { ...image, starred } : image))
- );
- },
- [patchImages]
- );
-
const lastPublishedTotalRef = useRef<number | null>(null);
// After a deletion that takes out the previewed image, move the selection to
@@ -184,11 +170,11 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
generateValues={generateValues}
projectId={projectId}
onImagesDeleted={onImagesDeleted}
- onStarredChange={onStarredChange}
>
<GalleryWidgetContent
actions={actions}
gallery={gallery}
+ isWindowTruncated={data.isWindowTruncated}
layout={isWidePlacement ? 'wide' : 'stacked'}
projectName={projectName}
runtime={runtime}
@@ -200,20 +186,22 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
const GalleryWidgetContent = ({
actions,
gallery,
+ isWindowTruncated,
layout,
projectName,
runtime,
}: {
actions: GalleryActions;
gallery: GalleryStateView;
+ isWindowTruncated: boolean;
layout: 'stacked' | 'wide';
projectName: string;
runtime: GalleryWidgetRuntime;
}) => {
const imageActions = useGalleryImageActions();
const contextValue = useMemo<GalleryWidgetContextValue>(
- () => ({ actions, gallery, imageActions, projectName, runtime }),
- [actions, gallery, imageActions, projectName, runtime]
+ () => ({ actions, gallery, imageActions, isWindowTruncated, projectName, runtime }),
+ [actions, gallery, imageActions, isWindowTruncated, projectName, runtime]
);
return (
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index a99512ba7c..804fffc1c4 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -7,7 +7,6 @@ import {
getBoardCounts,
getGalleryCurrentItem,
getGalleryGenerationSequence,
- getGalleryImagesRefreshToken,
getGalleryQueuePlaceholders,
getGallerySelectedBoardId,
getGalleryStateView,
@@ -114,13 +113,6 @@ describe('gallery state view', () => {
});
});
- it('falls back to the full gallery refresh token when image refresh token is absent', () => {
- expect(getGalleryImagesRefreshToken({ galleryRefreshToken: 'full-refresh' })).toBe('full-refresh');
- expect(
- getGalleryImagesRefreshToken({ galleryImagesRefreshToken: 'image-refresh', galleryRefreshToken: 'full-refresh' })
- ).toBe('image-refresh');
- });
-
it('derives the multi-selection from persisted values with a single-selection fallback', () => {
expect(
getGalleryStateView({ selectedImageNames: ['a.png', 'b.png', 7] }, boards, [], false).selectedImageNames
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
index 45854ee24f..708f99ea9e 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -8,6 +8,7 @@ import type {
import type { QueueItem } from '@features/queue/contracts';
import { normalizeGalleryImage } from '@features/gallery/core/image';
+import { getBoundedRecentImages } from '@features/gallery/core/recentImages';
import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';
import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';
@@ -211,19 +212,61 @@ export const getGalleryPage = (values: Record<string, unknown>): number =>
? Math.max(0, Math.floor(values.galleryPage))
: 0;
+export const getGallerySelectedImagePage = (values: Record<string, unknown>): number =>
+ typeof values.selectedImagePage === 'number' && Number.isFinite(values.selectedImagePage)
+ ? Math.max(0, Math.floor(values.selectedImagePage))
+ : getGalleryPage(values);
+
+export interface GallerySelectedImageQuery {
+ boardId: string;
+ galleryView: GalleryView;
+ imageOrderDir: GalleryOrderDir;
+ page: number;
+ paginationMode: 'infinite' | 'paginated';
+ searchTerm: string;
+ starredFirst: boolean;
+}
+
+export const getGallerySelectedImageQuery = (values: Record<string, unknown>): GallerySelectedImageQuery => {
+ const query =
+ values.selectedImageQuery && typeof values.selectedImageQuery === 'object'
+ ? (values.selectedImageQuery as Partial<GallerySelectedImageQuery>)
+ : null;
+ const settings = getGallerySettings(values);
+
+ return {
+ boardId:
+ query && typeof query.boardId === 'string'
+ ? query.boardId
+ : typeof values.selectedBoardId === 'string'
+ ? values.selectedBoardId
+ : 'none',
+ galleryView:
+ query?.galleryView === 'assets' || query?.galleryView === 'images'
+ ? query.galleryView
+ : values.galleryView === 'assets'
+ ? 'assets'
+ : 'images',
+ imageOrderDir:
+ query?.imageOrderDir === 'ASC' || query?.imageOrderDir === 'DESC' ? query.imageOrderDir : settings.imageOrderDir,
+ page:
+ query && typeof query.page === 'number' && Number.isFinite(query.page)
+ ? Math.max(0, Math.floor(query.page))
+ : getGallerySelectedImagePage(values),
+ paginationMode:
+ query?.paginationMode === 'infinite' || query?.paginationMode === 'paginated'
+ ? query.paginationMode
+ : settings.paginationMode,
+ searchTerm: query && typeof query.searchTerm === 'string' ? query.searchTerm : String(values.searchTerm ?? ''),
+ starredFirst: typeof query?.starredFirst === 'boolean' ? query.starredFirst : settings.starredFirst,
+ };
+};
+
export const getGalleryTotalImages = (values: Record<string, unknown>): number | null =>
typeof values.galleryTotalImages === 'number' && Number.isFinite(values.galleryTotalImages)
? Math.max(0, values.galleryTotalImages)
: null;
-export const getGalleryRefreshToken = (values: Record<string, unknown>): string =>
- typeof values.galleryRefreshToken === 'string' ? values.galleryRefreshToken : '';
-
-export const getGalleryImagesRefreshToken = (values: Record<string, unknown>): string =>
- typeof values.galleryImagesRefreshToken === 'string'
- ? values.galleryImagesRefreshToken
- : getGalleryRefreshToken(values);
-
export const getGalleryProjectBoardId = (values: Record<string, unknown>): string | null =>
typeof values.projectBoardId === 'string' ? values.projectBoardId : null;
@@ -241,14 +284,6 @@ export const getGalleryCompareImage = (values: Record<string, unknown>): Generat
return null;
};
-export const getGalleryRecentImagesKey = (values: Record<string, unknown>): string => {
- if (!Array.isArray(values.recentImages)) {
- return '';
- }
-
- return (values.recentImages as GeneratedImageContract[]).map((image) => image.imageName).join('\0');
-};
-
export const getGalleryQueuePlaceholders = (
queueItems: QueueItem[],
{
@@ -293,11 +328,7 @@ export const getGalleryStateView = (
liveFollowEnabled = false,
liveTarget: GalleryLiveTarget | null = null
): GalleryStateView => {
- const localImages = Array.isArray(values.recentImages)
- ? (values.recentImages as Array<GeneratedImageContract & Partial<GalleryImage>>).map((image) =>
- normalizeGalleryImage(image)
- )
- : [];
+ const localImages = getBoundedRecentImages(values.recentImages).map((image) => normalizeGalleryImage(image));
const images = backendImages ?? (isLoading ? [] : localImages);
const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;
const visibleSelectedImageName = images.some((image) => image.imageName === selectedImageName)
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index b1488e8b54..4ce3b64016 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -7,11 +7,13 @@ import {
updateGalleryBoard,
uploadGalleryImage,
} from '@features/gallery/data/backend';
+import { invalidateGallery } from '@features/gallery/data/queryCache';
import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
+import { useQueryClient } from '@tanstack/react-query';
import { useMemo } from 'react';
import type { GalleryActions } from './GalleryWidgetContext';
@@ -46,12 +48,13 @@ export const useGalleryActions = ({
selectedBoardId: string;
}): GalleryActions => {
const { gallery, notifications } = useGalleryUi();
+ const queryClient = useQueryClient();
return useMemo<GalleryActions>(() => {
const recordError = (error: unknown) =>
notifications.reportError({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery' });
const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });
- const refresh = gallery.touch;
+ const refresh = () => void invalidateGallery(queryClient);
const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';
return {
@@ -109,10 +112,7 @@ export const useGalleryActions = ({
includeImages ? 'Its images were permanently deleted.' : 'Its images were moved to Uncategorized.'
);
- if (boardId === selectedBoardId) {
- gallery.selectBoard('none');
- }
-
+ gallery.reconcileDeletedBoard(boardId, includeImages);
refresh();
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
@@ -232,5 +232,5 @@ export const useGalleryActions = ({
}
},
};
- }, [boards, gallery, loadMore, notifications, projectBoardId, projectName, selectedBoardId]);
+ }, [boards, gallery, loadMore, notifications, projectBoardId, projectName, queryClient, selectedBoardId]);
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts
new file mode 100644
index 0000000000..8658c929e0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts
@@ -0,0 +1,115 @@
+import type { GalleryImage, GeneratedImageContract } from '@features/gallery/core/types';
+
+import { getBoundedRecentImages } from '@features/gallery/core/recentImages';
+import { describe, expect, it } from 'vitest';
+
+import { isGalleryWindowTruncated, mergeGalleryImageWindow } from './useGalleryData';
+
+const createImage = (index: number, overrides: Partial<GalleryImage> = {}): GalleryImage => ({
+ boardId: 'none',
+ height: 512,
+ imageCategory: 'general',
+ imageName: `image-${String(index).padStart(4, '0')}.png`,
+ imageUrl: `/images/${index}`,
+ queuedAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),
+ sourceQueueItemId: `queue-${index}`,
+ starred: false,
+ thumbnailUrl: `/thumbnails/${index}`,
+ width: 512,
+ ...overrides,
+});
+
+const asGenerated = (image: GalleryImage): GeneratedImageContract => image;
+
+const filter = {
+ boardId: 'none',
+ galleryView: 'images' as const,
+ orderDir: 'DESC' as const,
+ searchTerm: '',
+ starredFirst: false,
+};
+
+describe('mergeGalleryImageWindow', () => {
+ it('deduplicates the recent overlay and keeps newest-first ordering', () => {
+ const backend = [createImage(1), createImage(2)];
+ const recent = [asGenerated(createImage(3)), asGenerated(createImage(2))];
+
+ expect(
+ mergeGalleryImageWindow({ backendImages: backend, filter, maxRows: 600, recentImages: recent }).map(
+ (image) => image.imageName
+ )
+ ).toEqual(['image-0003.png', 'image-0002.png', 'image-0001.png']);
+ });
+
+ it('bounds both the optimistic overlay and the rendered infinite window', () => {
+ const backend = Array.from({ length: 600 }, (_, index) => createImage(index));
+ const rawRecent = Array.from({ length: 1_000 }, (_, index) => asGenerated(createImage(1_000 + index)));
+ const recent = getBoundedRecentImages(rawRecent);
+ const images = mergeGalleryImageWindow({ backendImages: backend, filter, maxRows: 600, recentImages: recent });
+
+ expect(recent).toHaveLength(60);
+ expect(images).toHaveLength(600);
+ expect(images.slice(0, 60).map((image) => image.imageName)).toEqual(
+ recent.map((image) => image.imageName).reverse()
+ );
+ });
+
+ it('does not overlay recent images into incompatible board, asset, search, or date filters', () => {
+ const recent = [asGenerated(createImage(2))];
+ const filters = [
+ { ...filter, boardId: 'board-2' },
+ { ...filter, galleryView: 'assets' as const },
+ { ...filter, searchTerm: 'portrait' },
+ { ...filter, createdFrom: '2026-01-01' },
+ { ...filter, boardId: 'by_date:2026-01-01' },
+ ];
+
+ for (const candidate of filters) {
+ expect(
+ mergeGalleryImageWindow({
+ backendImages: [createImage(1)],
+ filter: candidate,
+ maxRows: 600,
+ recentImages: recent,
+ })
+ ).toHaveLength(1);
+ }
+ });
+
+ it('preserves starred-first ordering and the paginated row cap', () => {
+ const images = mergeGalleryImageWindow({
+ backendImages: Array.from({ length: 60 }, (_, index) => createImage(index)),
+ filter: { ...filter, starredFirst: true },
+ maxRows: 60,
+ recentImages: [asGenerated(createImage(100, { starred: true }))],
+ });
+
+ expect(images).toHaveLength(60);
+ expect(images[0]).toMatchObject({ imageName: 'image-0100.png', starred: true });
+ });
+});
+
+describe('isGalleryWindowTruncated', () => {
+ const atCap = { hasNextPage: false, isPaginated: false, loadedRowCount: 600, maxRows: 600, total: 1_000 };
+
+ it('reports truncation only when the full window hides reachable images', () => {
+ expect(isGalleryWindowTruncated(atCap)).toBe(true);
+ });
+
+ it('does not report truncation at the true end of a board', () => {
+ expect(isGalleryWindowTruncated({ ...atCap, total: 600 })).toBe(false);
+ expect(isGalleryWindowTruncated({ ...atCap, loadedRowCount: 240, total: 240 })).toBe(false);
+ });
+
+ it('does not report truncation while more pages can still be loaded', () => {
+ expect(isGalleryWindowTruncated({ ...atCap, hasNextPage: true })).toBe(false);
+ });
+
+ it('never reports truncation in paginated mode, where every page is reachable', () => {
+ expect(isGalleryWindowTruncated({ ...atCap, isPaginated: true, loadedRowCount: 60, maxRows: 60 })).toBe(false);
+ });
+
+ it('does not report truncation before the backend total is known', () => {
+ expect(isGalleryWindowTruncated({ ...atCap, total: null })).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
index 1fd26eba7c..4f49d260fb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
@@ -1,106 +1,223 @@
import type { GallerySettings } from '@features/gallery/core/settings';
-import type { GalleryBoard, GalleryImage, GalleryView } from '@features/gallery/core/types';
+import type { GalleryBoard, GalleryImage, GalleryView, GeneratedImageContract } from '@features/gallery/core/types';
-import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/data/queries';
+import { normalizeGalleryImage } from '@features/gallery/core/image';
+import { GALLERY_RECENT_IMAGE_LIMIT } from '@features/gallery/core/recentImages';
+import { ALL_READABLE_BOARDS_ID, isDateBoardId } from '@features/gallery/data/backend';
+import {
+ flattenGalleryImagesData,
+ GALLERY_MAX_ROWS,
+ GALLERY_PAGE_SIZE,
+ galleryBoardsOptions,
+ galleryImagesInfiniteOptions,
+ type GalleryImagesFilter,
+} from '@features/gallery/data/queries';
import { parseDateTokens } from '@platform/search/dateTokens';
-import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query';
-import { useCallback, useMemo, useState } from 'react';
-
-export const GALLERY_PAGE_SIZE = 60;
+import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
+import { useCallback, useMemo } from 'react';
export interface GalleryData {
boards: GalleryBoard[];
hasMore: boolean;
images: GalleryImage[] | null;
isLoadingImages: boolean;
+ /**
+ * True when the infinite window is full *and* the board holds more images
+ * than it can reach. `hasMore` is false in that case exactly as it is at the
+ * true end of a board, so the two must be distinguishable: stopping at the
+ * end is complete, stopping at the cap is not, and only one of them owes the
+ * user an explanation.
+ */
+ isWindowTruncated: boolean;
loadMore: () => void;
- patchImages: (getImages: (images: GalleryImage[]) => GalleryImage[]) => void;
total: number | null;
}
-const useGalleryBoards = ({ refreshToken, settings }: { refreshToken: string; settings: GallerySettings }) => {
+const useGalleryBoards = ({ settings }: { settings: GallerySettings }) => {
const query = useQuery(
galleryBoardsOptions({
includeArchived: settings.showArchivedBoards,
includeDateBoards: settings.showDateBoards,
orderBy: settings.boardOrderBy,
orderDir: settings.boardOrderDir,
- revision: refreshToken,
})
);
return { boards: query.data ?? [] };
};
+const isRecentImageVisible = (image: GalleryImage, filter: GalleryImagesFilter): boolean => {
+ if (
+ filter.searchTerm !== '' ||
+ filter.createdFrom !== undefined ||
+ filter.createdTo !== undefined ||
+ isDateBoardId(filter.boardId)
+ ) {
+ return false;
+ }
+
+ const hasMatchingBoard = filter.boardId === ALL_READABLE_BOARDS_ID || filter.boardId === image.boardId;
+ const hasMatchingCategory =
+ filter.galleryView === 'images' ? image.imageCategory === 'general' : image.imageCategory !== 'general';
+
+ return hasMatchingBoard && hasMatchingCategory;
+};
+
+const compareGalleryImages = (
+ a: GalleryImage,
+ b: GalleryImage,
+ { orderDir = 'DESC', starredFirst = false }: GalleryImagesFilter
+): number => {
+ if (starredFirst && a.starred !== b.starred) {
+ return a.starred ? -1 : 1;
+ }
+
+ const chronologicalOrder = a.queuedAt.localeCompare(b.queuedAt);
+
+ return orderDir === 'ASC' ? chronologicalOrder : -chronologicalOrder;
+};
+
+export const mergeGalleryImageWindow = ({
+ backendImages,
+ filter,
+ maxRows,
+ recentImages,
+}: {
+ backendImages: readonly GalleryImage[];
+ filter: GalleryImagesFilter;
+ maxRows: number;
+ recentImages: readonly GeneratedImageContract[];
+}): GalleryImage[] => {
+ const backendImageNames = new Set(backendImages.map((image) => image.imageName));
+ const missingRecentImages = recentImages
+ .slice(0, GALLERY_RECENT_IMAGE_LIMIT)
+ .map((image) => normalizeGalleryImage(image))
+ .filter((image) => !backendImageNames.has(image.imageName) && isRecentImageVisible(image, filter));
+
+ if (missingRecentImages.length === 0) {
+ return backendImages.length <= maxRows ? (backendImages as GalleryImage[]) : backendImages.slice(0, maxRows);
+ }
+
+ return [...missingRecentImages, ...backendImages]
+ .sort((a, b) => compareGalleryImages(a, b, filter))
+ .slice(0, maxRows);
+};
+
+/**
+ * Distinguishes "this board has no more images" from "this board has more
+ * images than the infinite window can reach".
+ *
+ * Both leave `hasNextPage` false, but only the second one is incomplete, and a
+ * gallery that silently stops scrolling with a thousand images on the server
+ * reads as a bug. Paginated mode is never truncated: every page is reachable
+ * by asking for it.
+ */
+export const isGalleryWindowTruncated = ({
+ hasNextPage,
+ isPaginated,
+ loadedRowCount,
+ maxRows,
+ total,
+}: {
+ hasNextPage: boolean;
+ isPaginated: boolean;
+ loadedRowCount: number;
+ maxRows: number;
+ total: number | null;
+}): boolean => !isPaginated && !hasNextPage && total !== null && loadedRowCount >= maxRows && total > loadedRowCount;
+
export const useGalleryData = ({
galleryView,
- imageRefreshToken,
page,
- recentImagesKey,
- refreshToken,
+ recentImages,
searchTerm,
selectedBoardId,
settings,
}: {
galleryView: GalleryView;
- imageRefreshToken: string;
page: number;
- recentImagesKey: string;
- refreshToken: string;
+ recentImages: readonly GeneratedImageContract[];
searchTerm: string;
selectedBoardId: string;
settings: GallerySettings;
}): GalleryData => {
- const queryClient = useQueryClient();
- const { boards } = useGalleryBoards({ refreshToken, settings });
+ const { boards } = useGalleryBoards({ settings });
const boardId =
boards.length === 0 || boards.some((board) => board.id === selectedBoardId) ? selectedBoardId : 'none';
- const baseKey = [galleryView, boardId, searchTerm.trim(), settings.imageOrderDir, String(settings.starredFirst)].join(
- '\0'
- );
- const [infiniteWindow, setInfiniteWindow] = useState({ baseKey, pageCount: 1 });
const isPaginated = settings.paginationMode === 'paginated';
- const pageCount = infiniteWindow.baseKey === baseKey ? infiniteWindow.pageCount : 1;
- const offset = isPaginated ? page * GALLERY_PAGE_SIZE : 0;
- const limit = isPaginated ? GALLERY_PAGE_SIZE : pageCount * GALLERY_PAGE_SIZE;
- // The raw search term stays the source of truth; date tokens are derived
- // here so both the text filter and the range reach the query together.
const dateParse = useMemo(() => parseDateTokens(searchTerm), [searchTerm]);
- const options = galleryImagesOptions({
- boardId,
- createdFrom: dateParse.range?.from,
- createdTo: dateParse.range?.to,
- galleryView,
- limit,
- offset,
- orderDir: settings.imageOrderDir,
- revision: `${imageRefreshToken}:${recentImagesKey}`,
- searchTerm: dateParse.text,
- starredFirst: settings.starredFirst,
+ const filter = useMemo<GalleryImagesFilter>(
+ () => ({
+ boardId,
+ createdFrom: dateParse.range?.from,
+ createdTo: dateParse.range?.to,
+ galleryView,
+ orderDir: settings.imageOrderDir,
+ searchTerm: dateParse.text,
+ starredFirst: settings.starredFirst,
+ }),
+ [
+ boardId,
+ dateParse.range?.from,
+ dateParse.range?.to,
+ dateParse.text,
+ galleryView,
+ settings.imageOrderDir,
+ settings.starredFirst,
+ ]
+ );
+ const {
+ data: queryData,
+ fetchNextPage,
+ hasNextPage,
+ isFetching,
+ isFetchingNextPage,
+ } = useInfiniteQuery(
+ galleryImagesInfiniteOptions(
+ filter,
+ isPaginated ? { kind: 'anchor', offset: page * GALLERY_PAGE_SIZE } : { kind: 'infinite' }
+ )
+ );
+ const backendImages = useMemo(() => {
+ if (!isPaginated) {
+ return flattenGalleryImagesData(queryData);
+ }
+
+ const pageOffset = page * GALLERY_PAGE_SIZE;
+ const pageIndex = queryData?.pageParams.indexOf(pageOffset) ?? -1;
+
+ return pageIndex === -1 ? [] : (queryData?.pages[pageIndex]?.images ?? []).slice(0, GALLERY_PAGE_SIZE);
+ }, [isPaginated, page, queryData]);
+ const shouldOverlayRecentImages = !isPaginated;
+ const maxRows = isPaginated ? GALLERY_PAGE_SIZE : GALLERY_MAX_ROWS;
+ const images = useMemo(
+ () =>
+ queryData || (shouldOverlayRecentImages && recentImages.length > 0)
+ ? mergeGalleryImageWindow({
+ backendImages,
+ filter,
+ maxRows,
+ recentImages: shouldOverlayRecentImages ? recentImages : [],
+ })
+ : null,
+ [backendImages, filter, maxRows, queryData, recentImages, shouldOverlayRecentImages]
+ );
+ const total = queryData?.pages[0]?.total ?? null;
+ const hasMore = !isPaginated && Boolean(hasNextPage);
+ const isWindowTruncated = isGalleryWindowTruncated({
+ hasNextPage: Boolean(hasNextPage),
+ isPaginated,
+ loadedRowCount: backendImages.length,
+ maxRows,
+ total,
});
- const query = useQuery({ ...options, placeholderData: keepPreviousData });
- const images = query.data?.images ?? null;
- const total = query.data?.total ?? null;
- const hasMore = !isPaginated && total !== null && images !== null && images.length < total;
const loadMore = useCallback(() => {
- if (!hasMore || query.isFetching) {
+ if (!hasMore || isFetchingNextPage) {
return;
}
- setInfiniteWindow((current) => ({
- baseKey,
- pageCount: current.baseKey === baseKey ? current.pageCount + 1 : 2,
- }));
- }, [baseKey, hasMore, query.isFetching]);
-
- const patchImages = useCallback(
- (getImages: (images: GalleryImage[]) => GalleryImage[]) => {
- queryClient.setQueryData(options.queryKey, (current) =>
- current ? { ...current, images: getImages(current.images) } : current
- );
- },
- [options.queryKey, queryClient]
- );
+ void fetchNextPage();
+ }, [fetchNextPage, hasMore, isFetchingNextPage]);
- return { boards, hasMore, images, isLoadingImages: query.isFetching, loadMore, patchImages, total };
+ return { boards, hasMore, images, isLoadingImages: isFetching, isWindowTruncated, loadMore, total };
};
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 a5864225d4..e95e6bafdb 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
@@ -23,6 +23,11 @@ import { generatedImageToReferenceImage, getEffectiveReferenceImage } from '@fea
import { clampDimension, deriveAspectRatioId } from '@features/generation/core/settings';
import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';
import { GenerateCollapsibleSection } from '@features/generation/ui/shared/GenerateCollapsibleSection';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, DropZone } from '@platform/ui';
import { UploadIcon } from 'lucide-react';
import { useCallback, useMemo, useRef } from 'react';
@@ -138,14 +143,23 @@ export const GenerateReferenceImagesSection = ({
return;
}
+ const owner = captureAccountScope();
+
try {
const uploaded = await Promise.all(
- files.slice(0, maxReferenceImages - referenceImageCount).map((file) => galleryTransfers.upload(file, 'none'))
+ files
+ .slice(0, maxReferenceImages - referenceImageCount)
+ .map((file) => galleryTransfers.upload(file, 'none', { signal: owner.signal }))
);
+ assertAccountScopeCurrent(owner);
appendReferenceImages(uploaded.map(generatedImageToReferenceImage));
gallery.touchImages();
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notifications.reportError({
area: 'reference-images',
message: error instanceof Error ? error.message : String(error),
diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
index 5be39bfe97..8d43f3b43c 100644
--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
@@ -57,6 +57,11 @@ import {
UPSCALE_TILE_SIZE_MIN,
} from '@features/upscale/core/settings';
import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, Combobox, DropZone, Field, IconButton, Select, Slider, Tooltip } from '@platform/ui';
import { toaster } from '@platform/ui/toaster';
import { DicesIcon, ImagePlusIcon, Trash2Icon, UploadIcon, XIcon } from 'lucide-react';
@@ -382,14 +387,20 @@ const UpscaleImageField = ({
return;
}
+ const owner = captureAccountScope();
setIsLoading(true);
try {
- const image = await galleryTransfers.upload(file, 'none');
+ const image = await galleryTransfers.upload(file, 'none', { signal: owner.signal });
+ assertAccountScopeCurrent(owner);
onChange({ height: image.height, image_name: image.imageName, width: image.width });
touchGalleryImages();
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
const message = error instanceof Error ? error.message : String(error);
setErrorMessage(message);
reportError(message);
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index 117c975e24..bb8c4ed10d 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -1,5 +1,6 @@
import type { ImageRecallKind } from '@workbench/image-actions/imageRecall';
+import { invalidateGallery } from '@features/gallery/queries';
import {
adjustFocusedPromptAttention,
flushGenerateDrafts,
@@ -16,6 +17,7 @@ import {
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
import { getConnectionStatus } from '@platform/transport/connectionStore';
+import { useQueryClient } from '@tanstack/react-query';
import { isInvocationRouteValid, resolveInvocationRoute } from '@workbench/invocation';
import { submitResolvedInvocation } from '@workbench/invocationSubmit';
import { toggleCommandPalette } from '@workbench/palette/paletteStore';
@@ -69,6 +71,7 @@ export const useRegisterFirstPartyCommands = () => {
const commands = useWorkbenchCommands();
const { commands: commandApi } = useWorkbenchExtensions();
const queries = useWorkbenchQueries();
+ const queryClient = useQueryClient();
const { layout, notifications, queue, widgets } = commands;
useInvocationTemplatesSelector((snapshot) => snapshot.status);
@@ -177,7 +180,15 @@ export const useRegisterFirstPartyCommands = () => {
commandApi.register({ handler: submitInvocation, id: 'app.invoke', title: 'Invoke' }),
commandApi.register({ handler: submitInvocation, id: 'app.invokeFront', title: 'Invoke front' }),
commandApi.register({
- handler: () => void queueCommands.cancelCurrentItem().finally(queue.refreshBackendData),
+ handler: () => {
+ const owner = captureAccountScope();
+
+ void queueCommands.cancelCurrentItem().finally(() => {
+ if (isAccountScopeCurrent(owner)) {
+ return invalidateGallery(queryClient, owner);
+ }
+ });
+ },
id: 'app.cancelQueueItem',
title: 'Cancel current queue item',
}),
@@ -346,5 +357,5 @@ export const useRegisterFirstPartyCommands = () => {
return () => {
disposers.forEach((dispose) => dispose());
};
- }, [commandApi, commands, layout, notifications, queries, queue, widgets]);
+ }, [commandApi, commands, layout, notifications, queries, queryClient, queue, widgets]);
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index ccf250031c..9f4c8e5be6 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -7,6 +7,7 @@ import {
type GalleryBoard,
type GalleryImage,
} from '@features/gallery';
+import { invalidateGallery, invalidateGalleryImages, patchGalleryImageCaches } from '@features/gallery/queries';
import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { useMountEffect } from '@platform/react/useMountEffect';
@@ -15,6 +16,7 @@ import {
captureAccountScope,
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
+import { useQueryClient } from '@tanstack/react-query';
import {
getCanvasImportNotice,
getCanvasEngine,
@@ -39,8 +41,8 @@ import {
/**
* Image operations shared by every surface that shows backend images (gallery
- * grid, preview, image context menus). Each mutation notifies the gallery via
- * a refresh action so any mounted gallery widget refetches affected backend data.
+ * grid, preview, image context menus). Mutations patch the shared Gallery cache
+ * when possible and explicitly invalidate the affected server state.
*/
export interface ImageActions {
/** Whether the generate widget's current model can accept another reference image. */
@@ -91,7 +93,6 @@ export const useImageActions = ({
boards,
generateValues,
onImagesDeleted,
- onStarredChange,
projectId,
}: {
boards: GalleryBoard[];
@@ -99,13 +100,12 @@ export const useImageActions = ({
projectId?: string;
/** Called after a successful deletion so the host can select a neighboring image. */
onImagesDeleted?: (imageNames: string[]) => void;
- /** Optional optimistic hook, called before the request and re-called inverted on failure. */
- onStarredChange?: (imageNames: string[], starred: boolean) => void;
}): ImageActions => {
const openWorkbenchWidget = useOpenWorkbenchWidget();
const commands = useWorkbenchCommands();
const { gallery, generation, notifications } = commands;
const queries = useWorkbenchQueries();
+ const queryClient = useQueryClient();
const { t } = useTranslation();
const models = useModelsSelector((snapshot) => snapshot.models);
const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);
@@ -127,8 +127,6 @@ export const useImageActions = ({
projectId,
});
const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });
- const refreshGallery = () => gallery.touch(projectId);
- const refreshGalleryImages = () => gallery.touchImages(projectId);
const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';
const getLatestGenerateValues = () => {
const snapshot = queries.getSnapshot();
@@ -169,10 +167,11 @@ export const useImageActions = ({
await galleryOrganization.deleteImages(imageNames, owner.signal);
assertAccountScopeCurrent(owner);
- gallery.removeImages(imageNames, projectId);
+ patchGalleryImageCaches(queryClient, { imageNames, kind: 'delete' });
+ gallery.removeImages(imageNames);
onImagesDeleted?.(imageNames);
recordSuccess(imageNames.length === 1 ? 'Deleted image' : `Deleted ${imageNames.length} images`);
- refreshGallery();
+ void invalidateGallery(queryClient);
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
@@ -269,12 +268,14 @@ export const useImageActions = ({
}
assertAccountScopeCurrent(owner);
+ patchGalleryImageCaches(queryClient, { boardId, imageNames, kind: 'move' });
+ gallery.patchImages(imageNames, { boardId });
recordSuccess(
imageNames.length === 1
? `Moved image to ${getBoardName(boardId)}`
: `Moved ${imageNames.length} images to ${getBoardName(boardId)}`
);
- refreshGallery();
+ void invalidateGallery(queryClient);
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
@@ -351,20 +352,22 @@ export const useImageActions = ({
},
setImagesStarred: async (imageNames, starred) => {
const owner = captureAccountScope();
-
- onStarredChange?.(imageNames, starred);
+ const rollback = patchGalleryImageCaches(queryClient, { imageNames, kind: 'star', starred });
try {
await galleryOrganization.setStarred(imageNames, starred, owner.signal);
assertAccountScopeCurrent(owner);
- refreshGalleryImages();
+ gallery.patchImages(imageNames, { starred });
+ void invalidateGalleryImages(queryClient);
} catch (error: unknown) {
+ rollback();
+
if (!isAccountScopeCurrent(owner)) {
return;
}
- onStarredChange?.(imageNames, !starred);
+ void invalidateGalleryImages(queryClient);
recordError(error);
}
},
@@ -393,9 +396,9 @@ export const useImageActions = ({
models,
notifications,
onImagesDeleted,
- onStarredChange,
openWorkbenchWidget,
projectId,
+ queryClient,
queries,
supportedModels,
t,
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts
index ef77dc26b1..fea5e5ead4 100644
--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts
@@ -93,6 +93,46 @@ describe('normalizeWorkbenchQueueHistory', () => {
expect(normalizeWorkbenchQueueHistory(queue, createContext())).toBe(queue);
});
+ it('strips transient recent images from both current queue snapshot representations', () => {
+ const context = createContext();
+ const galleryInstance = context.widgetInstances.gallery!;
+ const recentImages = [{ imageName: 'transient.png' }];
+ const current = {
+ ...createLegacyItem('workflow'),
+ snapshot: {
+ ...createLegacyItem('workflow').snapshot,
+ backendSubmission: { batchCount: 1, graph: backendGraph, kind: 'workflow' },
+ filterIntermediateResults: true,
+ galleryBoardId: null,
+ presentation: { batchCount: 1, height: 512, width: 512 },
+ widgetInstances: {
+ ...context.widgetInstances,
+ gallery: {
+ ...galleryInstance,
+ state: {
+ ...galleryInstance.state,
+ values: { ...galleryInstance.state.values, recentImages },
+ },
+ },
+ },
+ widgetStates: {
+ gallery: state('gallery', { recentImages, selectedBoardId: 'none' }),
+ },
+ },
+ };
+
+ const queue = { items: [current] };
+ const normalized = normalizeWorkbenchQueueHistory(queue, context);
+ const snapshot = normalized.items[0]!.snapshot;
+ const normalizedGalleryInstance = Object.values(snapshot.widgetInstances).find(
+ (instance) => instance.typeId === 'gallery'
+ );
+
+ expect(normalized).not.toBe(queue);
+ expect(snapshot.widgetStates.gallery?.values.recentImages).toBeUndefined();
+ expect(normalizedGalleryInstance?.state.values.recentImages).toBeUndefined();
+ });
+
it.each(['pending', 'completed'] as const)('upgrades legacy Generate items with %s status', (status) => {
const values = createGenerateValues();
const item = createLegacyItem('generate', {
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
index 87b8bf78ff..02485ffdbb 100644
--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
@@ -25,6 +25,58 @@ export interface QueueHistoryNormalizationContext {
const isRecord = (value: unknown): value is UnknownRecord => value !== null && typeof value === 'object';
+const stripGalleryRecentImagesFromState = (value: unknown): unknown => {
+ if (!isRecord(value) || !isRecord(value.values) || !Object.hasOwn(value.values, 'recentImages')) {
+ return value;
+ }
+
+ const values = { ...value.values };
+
+ delete values.recentImages;
+ return { ...value, values };
+};
+
+const stripGalleryRecentImagesFromWidgetStates = (value: unknown): unknown => {
+ if (!isRecord(value)) {
+ return value;
+ }
+
+ const gallery = stripGalleryRecentImagesFromState(value.gallery);
+
+ return gallery === value.gallery ? value : { ...value, gallery };
+};
+
+const stripGalleryRecentImagesFromWidgetInstances = (value: unknown): unknown => {
+ if (!isRecord(value)) {
+ return value;
+ }
+
+ let didChange = false;
+ const instances = Object.fromEntries(
+ Object.entries(value).map(([instanceId, instance]) => {
+ if (!isRecord(instance) || instance.typeId !== 'gallery') {
+ return [instanceId, instance];
+ }
+
+ const state = stripGalleryRecentImagesFromState(instance.state);
+
+ didChange ||= state !== instance.state;
+ return [instanceId, state === instance.state ? instance : { ...instance, state }];
+ })
+ );
+
+ return didChange ? instances : value;
+};
+
+const stripGalleryRecentImagesFromSnapshot = (snapshot: UnknownRecord): UnknownRecord => {
+ const widgetStates = stripGalleryRecentImagesFromWidgetStates(snapshot.widgetStates);
+ const widgetInstances = stripGalleryRecentImagesFromWidgetInstances(snapshot.widgetInstances);
+
+ return widgetStates === snapshot.widgetStates && widgetInstances === snapshot.widgetInstances
+ ? snapshot
+ : { ...snapshot, widgetInstances, widgetStates };
+};
+
const normalizeSourceId = (value: unknown): QueueSourceId | null => {
if (value === 'project-graph') {
return 'workflow';
@@ -188,7 +240,7 @@ const normalizeLegacyQueueItem = (
const item = isRecord(value) ? value : {};
const snapshot = isRecord(item.snapshot) ? item.snapshot : {};
const sourceId = normalizeSourceId(snapshot.sourceId);
- const widgetStates = getWidgetStates(snapshot);
+ const widgetStates = stripGalleryRecentImagesFromWidgetStates(getWidgetStates(snapshot)) as WidgetStateMap;
const { presentationSource, submission } = getBackendSubmission(sourceId, snapshot, widgetStates);
const upscaleValues =
sourceId === 'upscale' ? normalizeUpscaleWidgetValues(getWidgetValues(widgetStates, 'upscale')) : null;
@@ -240,9 +292,9 @@ const normalizeLegacyQueueItem = (
: {}),
sourceId: safeSourceId,
submittedAt: typeof snapshot.submittedAt === 'string' ? snapshot.submittedAt : new Date(0).toISOString(),
- widgetInstances: isRecord(snapshot.widgetInstances)
- ? (snapshot.widgetInstances as Record<WidgetInstanceId, WidgetInstanceContract>)
- : context.widgetInstances,
+ widgetInstances: stripGalleryRecentImagesFromWidgetInstances(
+ isRecord(snapshot.widgetInstances) ? snapshot.widgetInstances : context.widgetInstances
+ ) as Record<WidgetInstanceId, WidgetInstanceContract>,
widgetStates,
},
status:
@@ -269,7 +321,14 @@ export const normalizeWorkbenchQueueHistory = (
const items = value.items.map((item, index) => {
const snapshot = isRecord(item) && isRecord(item.snapshot) ? item.snapshot : null;
if (snapshot && isCurrentSnapshot(snapshot)) {
- return item as unknown as WorkbenchQueueItem;
+ const strippedSnapshot = stripGalleryRecentImagesFromSnapshot(snapshot);
+
+ if (strippedSnapshot === snapshot) {
+ return item as unknown as WorkbenchQueueItem;
+ }
+
+ didChange = true;
+ return { ...item, snapshot: strippedSnapshot } as unknown as WorkbenchQueueItem;
}
didChange = true;
return normalizeLegacyQueueItem(item, index, context);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
index 4ceb567f38..3368222cc5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
@@ -1,5 +1,12 @@
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
+import { invalidateGallery } from '@features/gallery/queries';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { useQueryClient } from '@tanstack/react-query';
import { saveCanvasToGallery, type CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';
import { useNotify } from '@workbench/useNotify';
import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
@@ -16,7 +23,8 @@ export const useCanvasGallerySave = (
const { t } = useTranslation();
const notify = useNotify();
const queries = useWorkbenchQueries();
- const { gallery, notifications } = useWorkbenchCommands();
+ const { notifications } = useWorkbenchCommands();
+ const queryClient = useQueryClient();
const isSavingRef = useRef(false);
const [isSaving, setIsSaving] = useState(false);
@@ -27,6 +35,7 @@ export const useCanvasGallerySave = (
}
const project = queries.getSnapshot().activeProject;
+ const owner = captureAccountScope();
await withMatchingCanvasProject(engine, project.id, async (matchedEngine) => {
isSavingRef.current = true;
@@ -35,8 +44,9 @@ export const useCanvasGallerySave = (
try {
const result = await saveCanvasToGallery({ engine: matchedEngine, project, region });
+ assertAccountScopeCurrent(owner);
if (result.status === 'saved') {
- gallery.touchImages(project.id);
+ void invalidateGallery(queryClient, owner);
notify.success(
t('widgets.canvas.contextMenu.saved'),
t('widgets.canvas.contextMenu.savedDescription', { name: result.imageName })
@@ -49,6 +59,10 @@ export const useCanvasGallerySave = (
notify.info(t('widgets.canvas.contextMenu.notReady'));
}
} catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notifications.reportError(
getCanvasGallerySaveErrorAction(error, project.id, t('widgets.canvas.contextMenu.saveError'))
);
@@ -58,7 +72,7 @@ export const useCanvasGallerySave = (
}
});
},
- [engine, gallery, notifications, notify, queries, t]
+ [engine, notifications, notify, queries, queryClient, t]
);
return { isSaving, save };
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
index d09021c232..4648fe4f82 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
@@ -14,10 +14,17 @@ import type { ChangeEvent, CSSProperties, FocusEvent } from 'react';
import { Box, createListCollection, HStack, IconButton, Input, Stack, Switch, Text } from '@chakra-ui/react';
import { useDndMonitor, useDroppable } from '@dnd-kit/core';
import { galleryImages, galleryTransfers } from '@features/gallery';
+import { invalidateGallery } from '@features/gallery/queries';
import { isGalleryImageDragData } from '@features/gallery/utility';
import { FluxReduxControls, PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generation/components';
import { useModelsSelector } from '@features/models';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, ColorPicker, DropZone, Field, Select, Slider } from '@platform/ui';
+import { useQueryClient } from '@tanstack/react-query';
import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { ImageIcon, PlusIcon, XIcon } from 'lucide-react';
@@ -88,7 +95,8 @@ interface RegionalGuidanceSettingsProps {
export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {
const { t } = useTranslation();
const dispatch = useCanvasProjectMutationDispatch();
- const { gallery, notifications } = useWorkbenchCommands();
+ const { notifications } = useWorkbenchCommands();
+ const queryClient = useQueryClient();
const models = useModelsSelector((snapshot) => snapshot.models);
const base = useSelectedModelBase();
const showSyntaxHighlighting = useActiveProjectSelector((project) => project.settings.showPromptSyntaxHighlighting);
@@ -264,11 +272,19 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
const uploadReferenceImageAsset = useCallback(
async (refId: string, file: File) => {
+ const owner = captureAccountScope();
+
try {
- const uploaded = await galleryTransfers.upload(file, 'none');
+ const uploaded = await galleryTransfers.upload(file, 'none', { signal: owner.signal });
+
+ assertAccountScopeCurrent(owner);
setReferenceImageAsset(refId, uploaded);
- gallery.touchImages();
+ void invalidateGallery(queryClient, owner);
} catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
notifications.reportError({
area: 'regional-guidance',
message: error instanceof Error ? error.message : String(error),
@@ -276,7 +292,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
});
}
},
- [gallery, notifications, setReferenceImageAsset]
+ [notifications, queryClient, setReferenceImageAsset]
);
// A single monitor routes gallery-image drops to the region's ref slot the drop
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
index df68769d41..6511b0ed7f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
@@ -5,6 +5,7 @@ import type { FormEvent } from 'react';
import { chakra, createListCollection, Dialog, Portal, Stack, Text } from '@chakra-ui/react';
import { galleryDurability, galleryImages } from '@features/gallery';
+import { invalidateGalleryImages } from '@features/gallery/queries';
import { runUtilityGraph } from '@features/queue/utility';
import {
buildLayerWorkflowGraph,
@@ -18,8 +19,10 @@ import {
type WorkflowImageBinding,
} from '@features/workflow/graph';
import { useInvocationTemplatesSnapshot, type InvocationTemplatesSnapshot } from '@features/workflow/react';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { socketHub } from '@platform/transport/socketHub';
import { Button, CloseButton, Field, Select } from '@platform/ui';
+import { useQueryClient } from '@tanstack/react-query';
import { getCanvasOperations } from '@workbench/canvas-operations/api';
import { useNotify } from '@workbench/useNotify';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
@@ -190,7 +193,8 @@ export const RunLayerWorkflowDialog = ({
}: RunLayerWorkflowDialogProps) => {
const { t } = useTranslation();
const notify = useNotify();
- const { canvas, gallery } = useWorkbenchCommands();
+ const { canvas } = useWorkbenchCommands();
+ const queryClient = useQueryClient();
const projectId = useActiveProjectSelector((project) => project.id);
const [session] = useState(createLayerActionSession);
const [selectionState, setSelectionState] = useState<SelectionState>(() => ({
@@ -323,17 +327,17 @@ export const RunLayerWorkflowDialog = ({
engine,
layerId,
notify,
- gallery,
projectId,
+ queryClient,
selection,
session,
t,
}),
- [availability, canvas, close, engine, gallery, layerId, notify, projectId, selection, session, t]
+ [availability, canvas, close, engine, layerId, notify, projectId, queryClient, selection, session, t]
);
const run = useCallback(async (): Promise<void> => {
- const { availability, canvas, close, engine, gallery, layerId, notify, projectId, selection, session, t } =
+ const { availability, canvas, close, engine, layerId, notify, projectId, queryClient, selection, session, t } =
runContext;
const { input, output } = selection;
@@ -347,6 +351,7 @@ export const RunLayerWorkflowDialog = ({
return;
}
+ const owner = captureAccountScope();
const destination = selection.destination;
setError(null);
setIsRunning(true);
@@ -366,7 +371,11 @@ export const RunLayerWorkflowDialog = ({
makeDurable: galleryDurability.makeCanvasAsset,
runGraph: (options) => runUtilityGraph({ ...options, hub: socketHub }),
saveToGallery: galleryDurability.save,
- touchGallery: (targetProjectId) => gallery.touchImages(targetProjectId),
+ touchGallery: () => {
+ if (isAccountScopeCurrent(owner)) {
+ void invalidateGalleryImages(queryClient, owner);
+ }
+ },
uploadIntermediate: (blob, signal) => {
if (signal?.aborted) {
throw new DOMException('Layer workflow aborted', 'AbortError');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
index d5a3fadcc6..a774e5bcfd 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
@@ -1,10 +1,11 @@
/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { GalleryImage, GalleryImagesPage } from '@features/gallery';
import type { QueueItem } from '@features/queue/contracts';
import type { WidgetViewProps } from '@workbench/widgetContracts';
import { ChakraProvider } from '@chakra-ui/react';
import { DndContext } from '@dnd-kit/core';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { QueryClient, QueryClientProvider, type InfiniteData } from '@tanstack/react-query';
import { system } from '@theme/system';
import i18next from 'i18next';
import { act } from 'react';
@@ -74,6 +75,8 @@ const mocks = vi.hoisted(() => {
preview: { state: { values: {} }, typeId: 'preview' },
},
},
+ galleryImagePageOffsets: [] as number[],
+ galleryImagePages: [] as GalleryImagesPage[],
recentImages,
useActiveProgressTarget: vi.fn(() => null as unknown),
useProgressImage: vi.fn(() => null as unknown),
@@ -94,11 +97,41 @@ vi.mock('@features/queue/react', async (importOriginal) => ({
}));
vi.mock('@features/gallery/queries', () => ({
- galleryBoardsOptions: () => ({ enabled: false, queryFn: () => [], queryKey: ['test-boards'] }),
- galleryImagesOptions: (query: { boardId: string }) => ({
- queryFn: () => new Promise<never>(() => {}),
- queryKey: ['test-images', query.boardId],
- }),
+ GALLERY_MAX_ROWS: 600,
+ GALLERY_PAGE_SIZE: 60,
+ flattenGalleryImagesData: (data: InfiniteData<GalleryImagesPage, number> | undefined): GalleryImage[] =>
+ data?.pages.flatMap((page) => page.images) ?? [],
+ galleryBoardsOptions: () => ({ queryFn: () => [], queryKey: ['test-boards'], staleTime: Infinity }),
+ galleryImagesInfiniteOptions: (
+ query: { boardId: string; orderDir?: 'ASC' | 'DESC' },
+ window: { kind: 'anchor' | 'infinite' | 'page'; offset?: number } = { kind: 'infinite' }
+ ) => {
+ const pages = mocks.galleryImagePages.map((page) => {
+ const images = page.images.filter((image) => image.boardId === query.boardId);
+
+ return {
+ ...page,
+ images: query.orderDir === 'ASC' ? images.reverse() : images,
+ };
+ });
+ const initialOffset = window.kind === 'infinite' ? 0 : (window.offset ?? 0);
+ const initialPage = pages[initialOffset / 60] ?? { images: [], total: 0 };
+
+ return {
+ getNextPageParam: (_lastPage: GalleryImagesPage, _allPages: GalleryImagesPage[], lastPageParam: number) =>
+ pages[lastPageParam / 60 + 1] ? lastPageParam + 60 : undefined,
+ getPreviousPageParam: (_firstPage: GalleryImagesPage, _allPages: GalleryImagesPage[], firstPageParam: number) =>
+ firstPageParam >= 60 ? firstPageParam - 60 : undefined,
+ initialData: { pageParams: [initialOffset], pages: [initialPage] },
+ initialPageParam: initialOffset,
+ queryFn: ({ pageParam }: { pageParam: number }) => {
+ mocks.galleryImagePageOffsets.push(pageParam);
+ return Promise.resolve(pages[pageParam / 60] ?? { images: [], total: 0 });
+ },
+ queryKey: ['test-images', query.boardId, query.orderDir, window.kind, initialOffset],
+ staleTime: Infinity,
+ };
+ },
}));
vi.mock('@workbench/image-actions', () => ({
@@ -195,13 +228,27 @@ beforeEach(() => {
mocks.project.queue.items = [];
mocks.project.settings.showProgressImagesInViewer = false;
delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).compareImage;
+ delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).galleryPage;
delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).imageOrderDir;
+ delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).paginationMode;
mocks.project.widgetInstances.gallery.state.values.recentImages = mocks.recentImages;
mocks.project.widgetInstances.gallery.state.values.selectedImage = {
...mocks.recentImages[0],
boardId: 'none',
};
mocks.project.widgetInstances.gallery.state.values.selectedImageName = 'newest';
+ mocks.galleryImagePageOffsets.length = 0;
+ mocks.galleryImagePages = [
+ {
+ images: mocks.recentImages.map((image) => ({
+ ...image,
+ boardId: 'none',
+ imageCategory: 'general',
+ starred: false,
+ })),
+ total: mocks.recentImages.length,
+ },
+ ];
mocks.useActiveProgressTarget.mockReturnValue(null);
mocks.useProgressImage.mockReturnValue(null);
});
@@ -226,13 +273,97 @@ describe('preview keyboard navigation boundary', () => {
await pressArrow('ArrowRight');
expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(expect.objectContaining({ imageName: 'oldest' }));
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
+ expect.objectContaining({ imageName: 'oldest' }),
+ undefined,
+ expect.any(Number),
+ true
+ );
expect(documentKeydown).not.toHaveBeenCalled();
} finally {
document.removeEventListener('keydown', documentKeydown);
}
});
+ it('fetches the next infinite page before stepping past the loaded backend boundary', async () => {
+ const newest: GalleryImage = {
+ ...mocks.recentImages[0],
+ boardId: 'none',
+ imageCategory: 'general',
+ starred: false,
+ };
+ const oldest: GalleryImage = {
+ ...mocks.recentImages[1],
+ boardId: 'none',
+ imageCategory: 'general',
+ starred: false,
+ };
+ mocks.project.widgetInstances.gallery.state.values.recentImages = [mocks.recentImages[0]];
+ mocks.galleryImagePages = [
+ { images: [newest], total: 2 },
+ { images: [oldest], total: 2 },
+ ];
+
+ await render();
+ await pressArrow('ArrowRight');
+
+ await vi.waitFor(() => {
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
+ expect.objectContaining({ imageName: 'oldest' }),
+ undefined,
+ expect.any(Number),
+ true
+ );
+ });
+ expect(mocks.galleryImagePageOffsets).toEqual([60]);
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
+ });
+
+ it('anchors Preview navigation to the selected paginated Gallery page', async () => {
+ const pageZero = {
+ ...mocks.recentImages[0],
+ boardId: 'none',
+ imageCategory: 'general' as const,
+ imageName: 'page-zero',
+ starred: false,
+ };
+ const selected = {
+ ...mocks.recentImages[0],
+ boardId: 'none',
+ imageCategory: 'general' as const,
+ imageName: 'page-one-selected',
+ starred: false,
+ };
+ const neighbor = {
+ ...mocks.recentImages[1],
+ boardId: 'none',
+ imageCategory: 'general' as const,
+ imageName: 'page-one-neighbor',
+ starred: false,
+ };
+ const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;
+
+ galleryValues.galleryPage = 1;
+ galleryValues.paginationMode = 'paginated';
+ galleryValues.recentImages = [];
+ galleryValues.selectedImage = selected;
+ galleryValues.selectedImageName = selected.imageName;
+ mocks.galleryImagePages = [
+ { images: [pageZero], total: 3 },
+ { images: [selected, neighbor], total: 3 },
+ ];
+
+ await render();
+ await pressArrow('ArrowRight');
+
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
+ expect.objectContaining({ imageName: neighbor.imageName }),
+ undefined,
+ 1,
+ true
+ );
+ });
+
it('enables live-follow when stepping onto the active placeholder', async () => {
mocks.project.queue.items = [queueItem];
mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });
@@ -276,7 +407,12 @@ describe('preview keyboard navigation boundary', () => {
await pressArrow('ArrowRight');
expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(expect.objectContaining({ imageName: 'newest' }));
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
+ expect.objectContaining({ imageName: 'newest' }),
+ undefined,
+ expect.any(Number),
+ true
+ );
});
it('uses the active placeholder board while following live, even before an image frame arrives', async () => {
@@ -298,7 +434,10 @@ describe('preview keyboard navigation boundary', () => {
await pressArrow('ArrowRight');
expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
- expect.objectContaining({ boardId: 'board-live', imageName: 'live-board-image' })
+ expect.objectContaining({ boardId: 'board-live', imageName: 'live-board-image' }),
+ undefined,
+ expect.any(Number),
+ true
);
});
@@ -308,7 +447,12 @@ describe('preview keyboard navigation boundary', () => {
await render();
await pressArrow('ArrowLeft');
- expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(expect.objectContaining({ imageName: 'oldest' }));
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
+ expect.objectContaining({ imageName: 'oldest' }),
+ undefined,
+ expect.any(Number),
+ true
+ );
});
it('does not consume arrow keys in comparison mode', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
index a690b34009..f50fd6b35d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
@@ -1,16 +1,7 @@
+import { GALLERY_MAX_ROWS } from '@features/gallery/queries';
import { describe, expect, it } from 'vitest';
-import { getMatchingProgressImage, getPreviewBoardsRequestKey, mergePreviewBoardImages } from './PreviewWidgetView';
-
-describe('getPreviewBoardsRequestKey', () => {
- it('requests boards for local generated images, not only backend gallery images', () => {
- expect(getPreviewBoardsRequestKey({ hasSelectedImage: true, refreshToken: 'refresh-1' })).toBe('refresh-1');
- });
-
- it('does not request boards without a selected image', () => {
- expect(getPreviewBoardsRequestKey({ hasSelectedImage: false, refreshToken: 'refresh-1' })).toBeNull();
- });
-});
+import { getMatchingProgressImage, mergePreviewBoardImages } from './PreviewWidgetView';
describe('getMatchingProgressImage', () => {
const placeholder = {
@@ -75,4 +66,18 @@ describe('mergePreviewBoardImages', () => {
existing,
]);
});
+
+ it('never renders more than the bounded Gallery window after merging optimistic images', () => {
+ const backend = Array.from({ length: GALLERY_MAX_ROWS }, (_, index) =>
+ image(`backend-${index}`, new Date(index * 1_000).toISOString())
+ );
+ const optimistic = Array.from({ length: 60 }, (_, index) =>
+ image(`optimistic-${index}`, new Date((GALLERY_MAX_ROWS + index) * 1_000).toISOString())
+ );
+
+ const merged = mergePreviewBoardImages(backend, optimistic, 'DESC', false);
+
+ expect(merged).toHaveLength(GALLERY_MAX_ROWS);
+ expect(merged[0]?.imageName).toBe('optimistic-59');
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 88159dcfc9..4a90fc4ceb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -13,22 +13,28 @@ import {
import {
getGalleryCompareImage,
getGalleryGenerationSequence,
- getGalleryImagesRefreshToken,
- getGalleryRecentImagesKey,
- getGalleryRefreshToken,
+ getGallerySelectedImageQuery,
getGallerySettings,
+ getBoundedRecentImages,
normalizeGalleryImage,
type GalleryQueuePlaceholder,
} from '@features/gallery/contracts';
-import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/queries';
+import {
+ flattenGalleryImagesData,
+ GALLERY_MAX_ROWS,
+ GALLERY_PAGE_SIZE,
+ galleryBoardsOptions,
+ galleryImagesInfiniteOptions,
+} from '@features/gallery/queries';
import { createGenerateFormValuesSelector } from '@features/generation/react';
import { useActiveProgressTarget, useProgressImage, type LatestProgressImageSnapshot } from '@features/queue/react';
+import { parseDateTokens } from '@platform/search/dateTokens';
import {
imageUrlToStreamingSource,
progressImageToStreamingSource,
} from '@platform/ui/streaming-image/streamingImageSource';
import { useStreamingImageSource } from '@platform/ui/streaming-image/useStreamingImageSource';
-import { useQuery } from '@tanstack/react-query';
+import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import {
ImageContextMenu,
useImageActions,
@@ -73,18 +79,13 @@ const fallbackBoards: GalleryBoard[] = [
{ archived: false, assetCount: 0, id: 'none', imageCount: 0, kind: 'uncategorized', name: 'Uncategorized' },
];
-const getGalleryImages = (values: Record<string, unknown>, queueItems: QueueItem[]): PreviewImage[] =>
- Array.isArray(values.recentImages)
- ? (() => {
- const queueBoardIds = new Map(
- queueItems.map((item) => [item.id, item.snapshot.galleryBoardId ?? 'none'] as const)
- );
+const getGalleryImages = (values: Record<string, unknown>, queueItems: QueueItem[]): PreviewImage[] => {
+ const queueBoardIds = new Map(queueItems.map((item) => [item.id, item.snapshot.galleryBoardId ?? 'none'] as const));
- return (values.recentImages as Array<GeneratedImageContract & Partial<GalleryImage>>).map((image) =>
- normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId))
- );
- })()
- : [];
+ return getBoundedRecentImages(values.recentImages).map((image) =>
+ normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId))
+ );
+};
const getSelectedImage = (values: Record<string, unknown>, localImages: PreviewImage[]): PreviewImage | null => {
const selectedImage = values.selectedImage;
@@ -158,10 +159,15 @@ export const mergePreviewBoardImages = (
const missingLocalImages = localImages.filter((image) => !backendNames.has(image.imageName));
if (missingLocalImages.length === 0) {
- return backendImages;
+ return backendImages.slice(0, GALLERY_MAX_ROWS);
}
- return getOrderedPreviewImages([...backendImages, ...missingLocalImages], imageOrderDir, starredFirst, 'display');
+ return getOrderedPreviewImages(
+ [...backendImages, ...missingLocalImages],
+ imageOrderDir,
+ starredFirst,
+ 'display'
+ ).slice(0, GALLERY_MAX_ROWS);
};
/**
@@ -172,6 +178,15 @@ export const mergePreviewBoardImages = (
*/
const getImageBoardId = (image: PreviewImage): string => (typeof image.boardId === 'string' ? image.boardId : 'none');
+/**
+ * Which gallery tab an image belongs to. Mirrors the category split the
+ * gallery filters on: `general` is a gallery image, everything else (canvas
+ * pixels, control layers, uploads) is an asset. A freshly generated local
+ * image carries no category yet and is a gallery image by default.
+ */
+const getImageGalleryView = (image: PreviewImage): GalleryView =>
+ (image.imageCategory ?? 'general') === 'general' ? 'images' : 'assets';
+
const getDisplayBoardId = (image: PreviewImage, values: Record<string, unknown>): string => {
if (typeof image.boardId === 'string') {
return image.boardId;
@@ -180,19 +195,6 @@ const getDisplayBoardId = (image: PreviewImage, values: Record<string, unknown>)
return typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none';
};
-const getImageGalleryView = (image: PreviewImage): GalleryView => {
- if (
- image.imageCategory === 'control' ||
- image.imageCategory === 'mask' ||
- image.imageCategory === 'user' ||
- image.imageCategory === 'other'
- ) {
- return 'assets';
- }
-
- return 'images';
-};
-
const getBoardName = (
boards: GalleryBoard[],
boardId: string,
@@ -201,14 +203,6 @@ const getBoardName = (
): string =>
boardId === 'none' ? uncategorizedLabel : (boards.find((board) => board.id === boardId)?.name ?? unknownBoardLabel);
-export const getPreviewBoardsRequestKey = ({
- hasSelectedImage,
- refreshToken,
-}: {
- hasSelectedImage: boolean;
- refreshToken: string;
-}): string | null => (hasSelectedImage ? refreshToken : null);
-
export const getMatchingProgressImage = (
progressImage: LatestProgressImageSnapshot | null,
placeholder: GalleryQueuePlaceholder | null
@@ -239,16 +233,19 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const activeProgressTarget = useActiveProgressTarget();
const { account, gallery, notifications, widgets } = useWorkbenchCommands();
const { density, rootRef } = usePreviewDensity(region);
- const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : null;
+ const recentImages = galleryValues.recentImages;
const localImages = useMemo(() => getGalleryImages({ recentImages }, queueItems), [queueItems, recentImages]);
const selectedImage = useMemo(() => getSelectedImage(galleryValues, localImages), [galleryValues, localImages]);
const compareImage = getGalleryCompareImage(galleryValues);
const comparisonMode = getPreviewComparisonMode(previewValues);
- const imageBoardId = selectedImage ? getImageBoardId(selectedImage) : 'none';
const displayBoardId = selectedImage ? getDisplayBoardId(selectedImage, galleryValues) : 'none';
- const selectedGalleryView = selectedImage ? getImageGalleryView(selectedImage) : 'images';
const hasSelectedImage = selectedImage !== null;
const { imageOrderDir, starredFirst } = getGallerySettings(galleryValues);
+ const selectedImageQuery = getGallerySelectedImageQuery(galleryValues);
+ const selectedImageSearch = useMemo(
+ () => parseDateTokens(selectedImageQuery.searchTerm),
+ [selectedImageQuery.searchTerm]
+ );
const selectedImageName = selectedImage?.imageName ?? null;
const isComparing =
selectedImage !== null && compareImage !== null && compareImage.imageName !== selectedImage.imageName;
@@ -258,35 +255,85 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
);
const matchingProgressImage = getMatchingProgressImage(progressImage, activeGalleryPlaceholder);
const shouldFollowLive = showProgressImagesInViewer && activeGalleryPlaceholder !== null && !isComparing;
- const navigationBoardId = shouldFollowLive ? activeGalleryPlaceholder.boardId : imageBoardId;
- const navigationGalleryView = shouldFollowLive ? 'images' : selectedGalleryView;
+ const navigationBoardId = shouldFollowLive ? activeGalleryPlaceholder.boardId : selectedImageQuery.boardId;
+ const navigationGalleryView = shouldFollowLive ? 'images' : selectedImageQuery.galleryView;
+ const navigationOrderDir = shouldFollowLive ? imageOrderDir : selectedImageQuery.imageOrderDir;
+ const navigationStarredFirst = shouldFollowLive ? starredFirst : selectedImageQuery.starredFirst;
const hasNavigationContext = shouldFollowLive || hasSelectedImage;
- const boardRefreshToken = getGalleryRefreshToken(galleryValues);
- const imageRefreshToken = getGalleryImagesRefreshToken(galleryValues);
- const recentImagesKey = getGalleryRecentImagesKey(galleryValues);
const { t } = useTranslation();
const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);
+ const navigationContextKey = `${shouldFollowLive}:${selectedImageName ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${navigationStarredFirst}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}`;
+ const navigationQueryKey = `${shouldFollowLive}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${navigationStarredFirst}:${selectedImageQuery.paginationMode}:${selectedImageQuery.searchTerm}`;
+
+ // Lets a boundary fetch that resolves after the user has moved on compare the
+ // context it started in against the one now on screen, and drop its stale
+ // result. Written from an effect rather than during render: the compiler
+ // rejects render-phase ref writes, and an effect event cannot be called from
+ // a promise continuation.
+ const navigationContextKeyRef = useRef(navigationContextKey);
- const boardsRequestKey = getPreviewBoardsRequestKey({
- hasSelectedImage,
- refreshToken: boardRefreshToken,
+ useEffect(() => {
+ navigationContextKeyRef.current = navigationContextKey;
+ }, [navigationContextKey]);
+
+ // A paginated navigation stays anchored to the page the preview opened on,
+ // and re-anchors only when the underlying query identity changes. Derived
+ // state rather than a ref so the compiler can see the dependency.
+ const [navigationAnchor, setNavigationAnchor] = useState({
+ page: selectedImageQuery.page,
+ queryKey: navigationQueryKey,
});
- const boardImagesRequestKey = `${navigationBoardId}:${navigationGalleryView}:${imageOrderDir}:${starredFirst}:${imageRefreshToken}:${recentImagesKey}`;
+ const hasStaleNavigationAnchor = navigationAnchor.queryKey !== navigationQueryKey;
+
+ if (hasStaleNavigationAnchor) {
+ setNavigationAnchor({ page: selectedImageQuery.page, queryKey: navigationQueryKey });
+ }
+
+ const navigationAnchorPage = hasStaleNavigationAnchor ? selectedImageQuery.page : navigationAnchor.page;
+
const boardsQuery = useQuery({
- ...galleryBoardsOptions({ revision: boardsRequestKey ?? undefined }),
- enabled: boardsRequestKey !== null,
+ ...galleryBoardsOptions(),
+ enabled: hasSelectedImage,
});
- const boardImagesQuery = useQuery({
- ...galleryImagesOptions({
- boardId: navigationBoardId,
- galleryView: navigationGalleryView,
- orderDir: imageOrderDir,
- revision: boardImagesRequestKey,
- searchTerm: '',
- starredFirst,
- }),
+ const {
+ data: boardImagesData,
+ fetchNextPage: fetchNextBoardImagesPage,
+ fetchPreviousPage: fetchPreviousBoardImagesPage,
+ hasNextPage: hasNextBoardImagesPage,
+ hasPreviousPage: hasPreviousBoardImagesPage,
+ isFetching: isFetchingBoardImages,
+ isFetchingNextPage: isFetchingNextBoardImagesPage,
+ isFetchingPreviousPage: isFetchingPreviousBoardImagesPage,
+ } = useInfiniteQuery({
+ ...galleryImagesInfiniteOptions(
+ {
+ boardId: navigationBoardId,
+ createdFrom: shouldFollowLive ? undefined : selectedImageSearch.range?.from,
+ createdTo: shouldFollowLive ? undefined : selectedImageSearch.range?.to,
+ galleryView: navigationGalleryView,
+ orderDir: navigationOrderDir,
+ searchTerm: shouldFollowLive ? '' : selectedImageSearch.text,
+ starredFirst: navigationStarredFirst,
+ },
+ !shouldFollowLive && selectedImageQuery.paginationMode === 'paginated'
+ ? { kind: 'anchor', offset: navigationAnchorPage * GALLERY_PAGE_SIZE }
+ : { kind: 'infinite' }
+ ),
enabled: hasNavigationContext,
});
+ const selectPreviewImage = useCallback(
+ (image: GeneratedImageContract) => {
+ const pageIndex = boardImagesData?.pages.findIndex((page) =>
+ page.images.some((candidate) => candidate.imageName === image.imageName)
+ );
+ const pageParam = pageIndex === undefined || pageIndex < 0 ? undefined : boardImagesData?.pageParams[pageIndex];
+ const selectionPage =
+ typeof pageParam === 'number' ? Math.floor(pageParam / GALLERY_PAGE_SIZE) : selectedImageQuery.page;
+
+ gallery.selectImage(image, undefined, selectionPage, true);
+ },
+ [boardImagesData, gallery, selectedImageQuery.page]
+ );
const boards = boardsQuery.data ?? fallbackBoards;
const optimisticQueueItemIds = useMemo(
() =>
@@ -297,39 +344,49 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
);
const navigationLocalImages = useMemo(() => {
const refreshingSelectedSourceId =
- !shouldFollowLive && boardImagesQuery.isFetching ? selectedImage?.sourceQueueItemId : null;
+ !shouldFollowLive && isFetchingBoardImages ? selectedImage?.sourceQueueItemId : null;
return localImages.filter(
(image) =>
optimisticQueueItemIds.has(image.sourceQueueItemId) || image.sourceQueueItemId === refreshingSelectedSourceId
);
- }, [
- boardImagesQuery.isFetching,
- localImages,
- optimisticQueueItemIds,
- selectedImage?.sourceQueueItemId,
- shouldFollowLive,
- ]);
+ }, [isFetchingBoardImages, localImages, optimisticQueueItemIds, selectedImage?.sourceQueueItemId, shouldFollowLive]);
const localBoardImages = useMemo(
() =>
getOrderedLocalImages({
boardId: navigationBoardId,
galleryView: navigationGalleryView,
images: navigationLocalImages,
- imageOrderDir,
- starredFirst,
+ imageOrderDir: navigationOrderDir,
+ starredFirst: navigationStarredFirst,
}),
- [imageOrderDir, navigationBoardId, navigationGalleryView, navigationLocalImages, starredFirst]
+ [navigationBoardId, navigationGalleryView, navigationLocalImages, navigationOrderDir, navigationStarredFirst]
);
- const backendBoardImages = boardImagesQuery.data?.images ?? EMPTY_PREVIEW_IMAGES;
+ const previewLocalBoardImages = useMemo(() => {
+ if (
+ shouldFollowLive ||
+ !selectedImage ||
+ localBoardImages.some((image) => image.imageName === selectedImage.imageName)
+ ) {
+ return localBoardImages;
+ }
+
+ return [selectedImage, ...localBoardImages];
+ }, [localBoardImages, selectedImage, shouldFollowLive]);
+ const backendBoardImages = useMemo(() => flattenGalleryImagesData(boardImagesData), [boardImagesData]);
const boardImages = useMemo(
() =>
!hasNavigationContext
? EMPTY_PREVIEW_IMAGES
- : mergePreviewBoardImages(backendBoardImages, localBoardImages, imageOrderDir, starredFirst),
- [backendBoardImages, hasNavigationContext, imageOrderDir, localBoardImages, starredFirst]
+ : mergePreviewBoardImages(
+ backendBoardImages,
+ previewLocalBoardImages,
+ navigationOrderDir,
+ navigationStarredFirst
+ ),
+ [backendBoardImages, hasNavigationContext, navigationOrderDir, navigationStarredFirst, previewLocalBoardImages]
);
- const isLoadingBoard = hasNavigationContext && boardImagesQuery.isFetching;
+ const isLoadingBoard = hasNavigationContext && isFetchingBoardImages;
const boardName = getBoardName(
boards,
displayBoardId,
@@ -343,10 +400,17 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
boardId: navigationBoardId,
boardImages,
galleryView: navigationGalleryView,
- imageOrderDir,
- starredFirst,
+ imageOrderDir: navigationOrderDir,
+ starredFirst: navigationStarredFirst,
}),
- [activeGalleryPlaceholder, boardImages, imageOrderDir, navigationBoardId, navigationGalleryView, starredFirst]
+ [
+ activeGalleryPlaceholder,
+ boardImages,
+ navigationBoardId,
+ navigationGalleryView,
+ navigationOrderDir,
+ navigationStarredFirst,
+ ]
);
const navigationCursor = getPreviewNavigationCursor(navigationSequence, {
isFollowingLive: shouldFollowLive,
@@ -362,18 +426,87 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
}
const target = getPreviewNavigationTarget(navigationSequence, navigationCursor, offset);
-
- if (!target) {
+ const isAtLoadedBackendBoundary =
+ selectedImageName !== null &&
+ (offset === 1
+ ? backendBoardImages.at(-1)?.imageName === selectedImageName && hasNextBoardImagesPage
+ : backendBoardImages[0]?.imageName === selectedImageName && hasPreviousBoardImagesPage);
+
+ if (!isAtLoadedBackendBoundary) {
+ if (!target) {
+ return;
+ }
+
+ if (target.kind === 'image') {
+ selectPreviewImage(target.image);
+ } else {
+ account.updateProjectPreferences({ showProgressImagesInViewer: true });
+ }
return;
}
- if (target.kind === 'image') {
- gallery.selectImage(target.image);
- } else {
- account.updateProjectPreferences({ showProgressImagesInViewer: true });
+ if (offset === 1 ? isFetchingNextBoardImagesPage : isFetchingPreviousBoardImagesPage) {
+ return;
}
+
+ const fetchBoundaryPage = offset === 1 ? fetchNextBoardImagesPage : fetchPreviousBoardImagesPage;
+
+ void fetchBoundaryPage().then((result) => {
+ if (result.isError || navigationContextKeyRef.current !== navigationContextKey) {
+ return;
+ }
+
+ const nextBackendBoardImages = flattenGalleryImagesData(result.data);
+ const nextBoardImages = mergePreviewBoardImages(
+ nextBackendBoardImages,
+ previewLocalBoardImages,
+ navigationOrderDir,
+ navigationStarredFirst
+ );
+ const nextNavigationSequence = getPreviewNavigationSequence({
+ activePlaceholder: activeGalleryPlaceholder,
+ boardId: navigationBoardId,
+ boardImages: nextBoardImages,
+ galleryView: navigationGalleryView,
+ imageOrderDir: navigationOrderDir,
+ starredFirst: navigationStarredFirst,
+ });
+ const nextNavigationCursor = getPreviewNavigationCursor(nextNavigationSequence, {
+ isFollowingLive: shouldFollowLive,
+ selectedImageName,
+ });
+ const nextTarget = getPreviewNavigationTarget(nextNavigationSequence, nextNavigationCursor, offset);
+
+ if (nextTarget?.kind === 'image') {
+ selectPreviewImage(nextTarget.image);
+ } else if (nextTarget?.kind === 'placeholder') {
+ account.updateProjectPreferences({ showProgressImagesInViewer: true });
+ }
+ });
},
- [account, gallery, isComparing, navigationCursor, navigationSequence]
+ [
+ account,
+ activeGalleryPlaceholder,
+ backendBoardImages,
+ fetchNextBoardImagesPage,
+ fetchPreviousBoardImagesPage,
+ hasNextBoardImagesPage,
+ hasPreviousBoardImagesPage,
+ isComparing,
+ isFetchingNextBoardImagesPage,
+ isFetchingPreviousBoardImagesPage,
+ navigationBoardId,
+ navigationContextKey,
+ navigationCursor,
+ navigationGalleryView,
+ navigationOrderDir,
+ navigationSequence,
+ navigationStarredFirst,
+ previewLocalBoardImages,
+ selectedImageName,
+ selectPreviewImage,
+ shouldFollowLive,
+ ]
);
const handleNavigationKeyDown = useCallback(
@@ -419,10 +552,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;
if (nextImage) {
- gallery.selectImage(nextImage);
+ selectPreviewImage(nextImage);
}
},
- [boardImages, gallery, selectedImage]
+ [boardImages, selectPreviewImage, selectedImage]
);
const projectId = useActiveProjectId();
const imageActions = useImageActions({
@@ -448,10 +581,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const exitCompare = useCallback(() => gallery.setCompareImage(null), [gallery]);
const swapCompareImages = useCallback(() => {
if (selectedImage && compareImage) {
- gallery.selectImage(compareImage);
+ selectPreviewImage(compareImage);
gallery.setCompareImage(selectedImage);
}
- }, [compareImage, gallery, selectedImage]);
+ }, [compareImage, gallery, selectPreviewImage, selectedImage]);
const setComparisonMode = useCallback(
(comparisonMode: PreviewComparisonMode) => widgets.patchValues('preview', { comparisonMode }),
[widgets]
@@ -462,7 +595,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
[isMetadataOpen, widgets]
);
const isFilmstripVisible = getPreviewFilmstripVisible(previewValues);
- const selectImage = useCallback((image: GeneratedImageContract) => gallery.selectImage(image), [gallery]);
+ const selectImage = selectPreviewImage;
// Drop-to-compare: any gallery-image drag dropped on the frame's drop zone
// arms that image for comparison. The drag payload only carries names, so
@@ -550,7 +683,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
}
if (commandId === 'viewer.swapImages' && selectedImage && compareImage) {
- gallery.selectImage(compareImage);
+ selectPreviewImage(compareImage);
gallery.setCompareImage(selectedImage);
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 8b05a821a9..eb18d2d168 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -10,6 +10,7 @@ import type {
import type { GraphContract } from '@workbench/graphContracts';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
+import { GALLERY_RECENT_IMAGE_LIMIT } from '@features/gallery/contracts';
import { MAX_PROMPT_HISTORY } from '@features/generation/settings';
import { describe, expect, it, vi } from 'vitest';
@@ -1843,6 +1844,106 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(values.imageBoards).toBeUndefined();
});
+ it('retains only the newest 60 images after 1,000 routed Gallery results', () => {
+ let state = primeGenerate();
+
+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });
+ state = submitGenerate(state);
+
+ const project = getActiveProject(state);
+ const queueItem = project.queue.items[0];
+
+ for (let index = 0; index < 1_000; index += 1) {
+ state = workbenchReducer(state, {
+ images: [createImage(`gallery-image-${index}.png`, queueItem.id)],
+ projectId: project.id,
+ queueItemId: queueItem.id,
+ type: 'routeQueueItemResults',
+ });
+ }
+
+ const galleryValues = getProjectWidgetValues(getActiveProject(state), 'gallery');
+ const recentImageNames = (galleryValues.recentImages as GeneratedImageContract[]).map((image) => image.imageName);
+
+ expect(GALLERY_RECENT_IMAGE_LIMIT).toBe(60);
+ expect(recentImageNames).toEqual(
+ Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) => `gallery-image-${999 - index}.png`)
+ );
+ expect(galleryValues.selectedImageName).toBe('gallery-image-999.png');
+ expect(galleryValues.selectedImageNames).toEqual(['gallery-image-999.png']);
+ });
+
+ it('omits transient recent images from immutable queue snapshots', () => {
+ let state = primeGenerate();
+ const recentImages = Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) =>
+ createImage(`recent-${index}.png`, 'previous-queue-item')
+ );
+
+ state = workbenchReducer(state, {
+ type: 'patchWidgetValues',
+ values: { recentImages },
+ widgetId: 'gallery',
+ });
+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });
+ state = submitGenerate(state);
+
+ const snapshot = getActiveProject(state).queue.items[0]!.snapshot;
+ const galleryInstance = Object.values(snapshot.widgetInstances).find((instance) => instance.typeId === 'gallery');
+
+ expect(snapshot.widgetStates.gallery?.values.recentImages).toBeUndefined();
+ expect(galleryInstance?.state.values.recentImages).toBeUndefined();
+ });
+
+ it('validates, deduplicates, and truncates persisted recent images during hydration', () => {
+ const initial = createInitialWorkbenchState();
+ const legacyImages = Array.from({ length: 1_000 }, (_, index) =>
+ createImage(`persisted-image-${999 - index}.png`, 'legacy-queue-item')
+ );
+ const selectedImage = legacyImages.at(-1)!;
+ const legacyRecentImages: unknown[] = [
+ legacyImages[0],
+ null,
+ legacyImages[0],
+ { imageName: 42 },
+ ...legacyImages.slice(1),
+ ];
+ const persisted: WorkbenchState = {
+ ...initial,
+ projects: initial.projects.map((project) => {
+ const galleryInstance = project.widgetInstances.gallery!;
+
+ return {
+ ...project,
+ widgetInstances: {
+ ...project.widgetInstances,
+ gallery: {
+ ...galleryInstance,
+ state: {
+ ...galleryInstance.state,
+ values: {
+ ...galleryInstance.state.values,
+ recentImages: legacyRecentImages,
+ selectedImage,
+ selectedImageName: selectedImage.imageName,
+ },
+ },
+ },
+ },
+ };
+ }),
+ };
+
+ const hydrated = workbenchReducer(initial, { state: persisted, type: 'hydrateWorkbench' });
+ const galleryValues = getProjectWidgetValues(getActiveProject(hydrated), 'gallery');
+ const recentImageNames = (galleryValues.recentImages as GeneratedImageContract[]).map((image) => image.imageName);
+
+ expect(recentImageNames).toEqual(
+ Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) => `persisted-image-${999 - index}.png`)
+ );
+ expect(galleryValues.selectedImage).toEqual(selectedImage);
+ expect(galleryValues.selectedImageName).toBe(selectedImage.imageName);
+ });
+
it('routes partial Gallery destination results without completing the local queue item', () => {
let state = primeGenerate(undefined, { batchCount: 2 });
@@ -2122,58 +2223,35 @@ describe('workbench backend connection recovery', () => {
expect(state.backendConnection.lastConnectedAt).toBeDefined();
});
- it('refreshes every project gallery when backend data may have changed', () => {
- const initial = createInitialWorkbenchState();
- const previousTokens = initial.projects.map(
- (project) => getProjectWidgetValues(project, 'gallery').galleryRefreshToken
- );
- const previousImageTokens = initial.projects.map(
- (project) => getProjectWidgetValues(project, 'gallery').galleryImagesRefreshToken
- );
- const state = workbenchReducer(initial, { type: 'refreshBackendData' });
-
- expect(state.projects).toHaveLength(initial.projects.length);
-
- for (const [index, project] of state.projects.entries()) {
- const galleryValues = getProjectWidgetValues(project, 'gallery');
-
- expect(galleryValues.galleryRefreshToken).toBeDefined();
- expect(galleryValues.galleryRefreshToken).not.toBe(previousTokens[index]);
- expect(galleryValues.galleryImagesRefreshToken).toBeDefined();
- expect(galleryValues.galleryImagesRefreshToken).not.toBe(previousImageTokens[index]);
- }
- });
-
- it('can refresh gallery images without invalidating board data', () => {
- const initial = createInitialWorkbenchState();
- const state = workbenchReducer(initial, { type: 'touchGalleryImagesRefresh' });
- const previousValues = getProjectWidgetValues(getActiveProject(initial), 'gallery');
- const values = getProjectWidgetValues(getActiveProject(state), 'gallery');
-
- expect(values.galleryRefreshToken).toBe(previousValues.galleryRefreshToken);
- expect(values.galleryImagesRefreshToken).toBeDefined();
- expect(values.galleryImagesRefreshToken).not.toBe(previousValues.galleryImagesRefreshToken);
- });
-
- it('can refresh gallery images in a non-active project without touching the active project', () => {
+ it('reconciles moved and starred metadata across every project recent-image overlay', () => {
let state = createInitialWorkbenchState();
- const firstProjectId = state.activeProjectId;
+ const image = createImage('patched.png', 'backend-gallery');
state = workbenchReducer(state, { type: 'createProject' });
- const secondProjectId = state.activeProjectId;
- const firstPreviousValues = getProjectWidgetValues(getProject(state, firstProjectId), 'gallery');
- const secondPreviousValues = getProjectWidgetValues(getProject(state, secondProjectId), 'gallery');
-
- state = workbenchReducer(state, { projectId: firstProjectId, type: 'touchGalleryImagesRefresh' });
+ for (const project of state.projects) {
+ state = workbenchReducer(state, {
+ projectId: project.id,
+ type: 'patchWidgetValues',
+ values: { compareImage: image, recentImages: [image], selectedImage: image },
+ widgetId: 'gallery',
+ });
+ }
+ state = workbenchReducer(state, {
+ changes: { boardId: 'board-2', starred: true },
+ imageNames: [image.imageName],
+ type: 'patchGalleryImages',
+ });
- const firstValues = getProjectWidgetValues(getProject(state, firstProjectId), 'gallery');
- const secondValues = getProjectWidgetValues(getProject(state, secondProjectId), 'gallery');
+ for (const project of state.projects) {
+ const values = getProjectWidgetValues(project, 'gallery');
- expect(firstValues.galleryImagesRefreshToken).not.toBe(firstPreviousValues.galleryImagesRefreshToken);
- expect(secondValues.galleryImagesRefreshToken).toBe(secondPreviousValues.galleryImagesRefreshToken);
+ expect(values.recentImages).toEqual([{ ...image, boardId: 'board-2', starred: true }]);
+ expect(values.selectedImage).toEqual({ ...image, boardId: 'board-2', starred: true });
+ expect(values.compareImage).toEqual({ ...image, boardId: 'board-2', starred: true });
+ }
});
- it('can remove gallery images from a non-active project without touching the active project', () => {
+ it('removes deleted backend images and upscale references from every project', () => {
let state = createInitialWorkbenchState();
const firstProjectId = state.activeProjectId;
const image = createImage('shared.png', 'backend-gallery');
@@ -2203,16 +2281,13 @@ describe('workbench backend connection recovery', () => {
state = workbenchReducer(state, {
imageNames: [image.imageName],
- projectId: firstProjectId,
type: 'removeGalleryImages',
});
expect(getProjectWidgetValues(getProject(state, firstProjectId), 'gallery').recentImages).toEqual([]);
- expect(getProjectWidgetValues(getProject(state, secondProjectId), 'gallery').recentImages).toEqual([image]);
+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'gallery').recentImages).toEqual([]);
expect(getProjectWidgetValues(getProject(state, firstProjectId), 'upscale').inputImage).toBeNull();
- expect(getProjectWidgetValues(getProject(state, secondProjectId), 'upscale').inputImage).toMatchObject({
- image_name: image.imageName,
- });
+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'upscale').inputImage).toBeNull();
});
it('does not hydrate stale persisted backend connection state', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 50e6487238..979945ab8b 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -41,6 +41,8 @@ import type {
} from '@workbench/widgetContracts';
import {
+ getBoundedRecentImages,
+ getGallerySettings,
normalizeGalleryImage,
type GalleryImage,
type GallerySettings,
@@ -240,7 +242,13 @@ type WorkbenchReducerAction =
| { type: 'markQueueItemBackendCancelled'; projectId: string; queueItemId: string; backendItemId: number }
| { type: 'routeQueueItemResults'; projectId: string; queueItemId: string; images: GeneratedImageContract[] }
| { type: 'appendCanvasStagingCandidate'; projectId: string; candidate: CanvasStagingCandidateContract }
- | { type: 'selectGalleryImage'; image: GeneratedImageContract; projectId?: string }
+ | {
+ type: 'selectGalleryImage';
+ image: GeneratedImageContract;
+ preserveNavigationQuery?: boolean;
+ projectId?: string;
+ selectionPage?: number;
+ }
| { type: 'toggleGalleryImageInSelection'; image: GeneratedImageContract; projectId?: string }
| { type: 'setGalleryMultiSelection'; imageNames: string[]; primaryImage: GeneratedImageContract; projectId?: string }
| { type: 'setGalleryCompareImage'; image: GeneratedImageContract | null; projectId?: string }
@@ -250,9 +258,13 @@ type WorkbenchReducerAction =
| { type: 'updateGallerySettings'; settings: Partial<GallerySettings>; projectId?: string }
| { type: 'setGalleryPage'; page: number; projectId?: string }
| { type: 'setGalleryPageInfo'; totalImages: number; projectId?: string }
- | { type: 'touchGalleryRefresh'; projectId?: string }
- | { type: 'touchGalleryImagesRefresh'; projectId?: string }
- | { type: 'removeGalleryImages'; imageNames: string[]; projectId?: string }
+ | {
+ type: 'patchGalleryImages';
+ changes: Partial<Pick<GalleryImage, 'boardId' | 'starred'>>;
+ imageNames: string[];
+ }
+ | { type: 'removeGalleryImages'; imageNames: string[] }
+ | { type: 'reconcileDeletedGalleryBoard'; boardId: string; includeImages: boolean }
| { type: 'setGalleryProjectBoardId'; boardId: string; projectId?: string }
| {
type: 'applyCanvasProjectMutation';
@@ -294,7 +306,6 @@ type WorkbenchReducerAction =
projectId?: string;
}
| { type: 'setBackendConnectionStatus'; status: WorkbenchState['backendConnection']['status']; error?: string }
- | { type: 'refreshBackendData' }
| { type: 'recordNotice'; kind: WorkbenchNotificationKind; title: string; message?: string };
const HISTORY_LIMIT = 40;
@@ -671,7 +682,7 @@ const clampCanvasStagingSelection = (project: Project): Project => {
};
const getGalleryImages = (values: Record<string, unknown>): GeneratedImageContract[] =>
- Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : [];
+ getBoundedRecentImages(values.recentImages);
const getGallerySelectedImageNames = (values: Record<string, unknown>): string[] => {
if (Array.isArray(values.selectedImageNames)) {
@@ -718,6 +729,16 @@ const cloneWidgetInstance = (widgetInstance: WidgetInstanceContract): WidgetInst
state: cloneWidgetState(widgetInstance.state),
});
+const cloneQueueWidgetState = (widgetState: WidgetStateContract, typeId: WidgetTypeId): WidgetStateContract => {
+ const state = cloneWidgetState(widgetState);
+
+ if (typeId === 'gallery') {
+ delete state.values.recentImages;
+ }
+
+ return state;
+};
+
const cloneWidgetInstances = (
widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>
): Record<WidgetInstanceId, WidgetInstanceContract> =>
@@ -728,11 +749,24 @@ const cloneWidgetInstances = (
])
);
+const cloneQueueWidgetInstances = (
+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>
+): Record<WidgetInstanceId, WidgetInstanceContract> =>
+ Object.fromEntries(
+ Object.entries({ ...createWidgetInstances(), ...widgetInstances }).map(([instanceId, widgetInstance]) => [
+ instanceId,
+ {
+ ...widgetInstance,
+ state: cloneQueueWidgetState(widgetInstance.state, widgetInstance.typeId),
+ },
+ ])
+ );
+
const getWidgetStatesSnapshot = (widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>): WidgetStateMap => {
const widgetStates: WidgetStateMap = {};
for (const widgetInstance of Object.values(widgetInstances)) {
- widgetStates[widgetInstance.typeId] ??= cloneWidgetState(widgetInstance.state);
+ widgetStates[widgetInstance.typeId] ??= cloneQueueWidgetState(widgetInstance.state, widgetInstance.typeId);
}
return widgetStates;
@@ -1206,6 +1240,23 @@ export const normalizeWorkbenchProject = (project: Project): Project => {
widgetInstances.upscale = createWidgetInstance('upscale');
}
+ for (const [instanceId, instance] of Object.entries(widgetInstances)) {
+ if (instance.typeId !== 'gallery' || !('recentImages' in instance.state.values)) {
+ continue;
+ }
+
+ widgetInstances[instanceId] = {
+ ...instance,
+ state: {
+ ...instance.state,
+ values: {
+ ...instance.state.values,
+ recentImages: getBoundedRecentImages(instance.state.values.recentImages),
+ },
+ },
+ };
+ }
+
const canvas = cloneCanvas(migrateCanvasStateToV2(project.canvas));
return {
@@ -1689,6 +1740,80 @@ const updateGalleryValues = (
);
};
+const updateAllProjectGalleryValues = (
+ state: WorkbenchState,
+ getValues: (values: Record<string, unknown>) => Record<string, unknown>
+): WorkbenchState => {
+ let didChange = false;
+ const projects = state.projects.map((project) => {
+ const nextProject = updateProjectWidgetValues(project, 'gallery', getValues);
+
+ didChange ||= nextProject !== project;
+ return nextProject;
+ });
+
+ return didChange ? { ...state, projects } : state;
+};
+
+const removeGalleryImagesFromAllProjects = (
+ state: WorkbenchState,
+ removedImageNames: ReadonlySet<string>
+): WorkbenchState => {
+ if (removedImageNames.size === 0) {
+ return state;
+ }
+
+ let didChange = false;
+ const projects = state.projects.map((project) => {
+ const withoutGalleryImages = updateProjectWidgetValues(project, 'gallery', (values) => {
+ const selectedImage = values.selectedImage as GeneratedImageContract | null | undefined;
+ const compareImage = values.compareImage as GeneratedImageContract | null | undefined;
+ const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;
+ const recentImages = getGalleryImages(values);
+ const selectedImageNames = getGallerySelectedImageNames(values);
+ const nextRecentImages = recentImages.filter((image) => !removedImageNames.has(image.imageName));
+ const nextSelectedImageNames = selectedImageNames.filter((name) => !removedImageNames.has(name));
+ const nextSelectedImage = selectedImage && removedImageNames.has(selectedImage.imageName) ? null : selectedImage;
+ const nextCompareImage = compareImage && removedImageNames.has(compareImage.imageName) ? null : compareImage;
+ const nextSelectedImageName =
+ selectedImageName && removedImageNames.has(selectedImageName) ? null : selectedImageName;
+
+ if (
+ nextRecentImages.length === recentImages.length &&
+ nextSelectedImageNames.length === selectedImageNames.length &&
+ nextSelectedImage === selectedImage &&
+ nextCompareImage === compareImage &&
+ nextSelectedImageName === selectedImageName
+ ) {
+ return values;
+ }
+
+ return {
+ ...values,
+ compareImage: nextCompareImage,
+ recentImages: nextRecentImages,
+ selectedImage: nextSelectedImage,
+ selectedImageName: nextSelectedImageName,
+ selectedImageNames: nextSelectedImageNames,
+ };
+ });
+ const withoutUpscaleInput = updateProjectWidgetValues(withoutGalleryImages, 'upscale', (rawValues) => {
+ const values = normalizeUpscaleWidgetValues(rawValues);
+
+ if (!values?.inputImage || !removedImageNames.has(values.inputImage.image_name)) {
+ return rawValues;
+ }
+
+ return { ...clearDeletedUpscaleInput(values, removedImageNames) };
+ });
+
+ didChange ||= withoutUpscaleInput !== project;
+ return withoutUpscaleInput;
+ });
+
+ return didChange ? { ...state, projects } : state;
+};
+
const updateGalleryValuesAndPauseLiveFollow = (
state: WorkbenchState,
getValues: (values: Record<string, unknown>) => Record<string, unknown>,
@@ -1705,14 +1830,6 @@ const updateGalleryValuesAndPauseLiveFollow = (
)
);
-const refreshProjectBackendData = (project: Project): Project => ({
- ...updateProjectWidgetValues(project, 'gallery', (values) => ({
- ...values,
- galleryImagesRefreshToken: createId('gallery-images-refresh'),
- galleryRefreshToken: createId('gallery-refresh'),
- })),
-});
-
const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => {
let didChange = false;
const items = project.queue.items.map((item) => {
@@ -1785,19 +1902,35 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageC
const queueBoardIds = new Map(
project.queue.items.map((item) => [item.id, item.snapshot.galleryBoardId ?? 'none'] as const)
);
- const newImages: GalleryImage[] = images
+ const incomingImages = getBoundedRecentImages([...images].reverse());
+ const newImages: GalleryImage[] = incomingImages
.filter((image) => !previousImageNames.has(image.imageName))
.map((image) => normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId)));
const shouldSelectIncomingImage =
project.settings.showProgressImagesInViewer || typeof galleryValues.selectedImageName !== 'string';
- const nextSelectedImage = shouldSelectIncomingImage ? newImages.at(-1) : undefined;
+ const nextSelectedImage = shouldSelectIncomingImage ? newImages[0] : undefined;
+ const gallerySettings = getGallerySettings(galleryValues);
return updateProjectWidgetValues(project, 'gallery', () => ({
...galleryValues,
- recentImages: [...[...newImages].reverse(), ...previousImages],
+ recentImages: getBoundedRecentImages([...newImages, ...previousImages]),
selectedImage: nextSelectedImage ?? galleryValues.selectedImage,
selectedImageName: nextSelectedImage?.imageName ?? galleryValues.selectedImageName,
selectedImageNames: nextSelectedImage ? [nextSelectedImage.imageName] : getGallerySelectedImageNames(galleryValues),
+ ...(nextSelectedImage
+ ? {
+ selectedImagePage: 0,
+ selectedImageQuery: {
+ boardId: nextSelectedImage.boardId,
+ galleryView: nextSelectedImage.imageCategory === 'general' ? 'images' : 'assets',
+ imageOrderDir: gallerySettings.imageOrderDir,
+ page: 0,
+ paginationMode: 'infinite',
+ searchTerm: '',
+ starredFirst: gallerySettings.starredFirst,
+ },
+ }
+ : {}),
}));
};
@@ -1880,7 +2013,11 @@ const enqueueCompiledSnapshot = (
const submittedAt = now();
const queueItemId = createId('queue-item');
const { generate, graph } = compiled;
- const widgetStates = applyQueueGenerateSnapshotToWidgetStates(compiled.widgetStates, generate);
+ const widgetStates = Object.fromEntries(
+ Object.entries(applyQueueGenerateSnapshotToWidgetStates(compiled.widgetStates, generate)).map(
+ ([typeId, widgetState]) => [typeId, cloneQueueWidgetState(widgetState, typeId as WidgetTypeId)]
+ )
+ ) as WidgetStateMap;
const graphHistorySnapshot = createGraphHistorySnapshot(`Queue snapshot ${queueItemId}`, graph);
const generateSettings =
route.sourceId === 'generate' ? normalizeGenerateSettings(widgetStates.generate.values) : null;
@@ -1950,7 +2087,7 @@ const enqueueCompiledSnapshot = (
? { resultNodeIds: ['upscale_output'] }
: {}),
submittedAt,
- widgetInstances: cloneWidgetInstances(project.widgetInstances),
+ widgetInstances: cloneQueueWidgetInstances(project.widgetInstances),
widgetStates,
},
status: 'pending',
@@ -2691,12 +2828,40 @@ export const __workbenchReducerInternal = (
case 'selectGalleryImage': {
return updateGalleryValuesAndPauseLiveFollow(
state,
- (values) => ({
- ...values,
- selectedImage: action.image,
- selectedImageName: action.image.imageName,
- selectedImageNames: [action.image.imageName],
- }),
+ (values) => {
+ const selectedImagePage =
+ typeof action.selectionPage === 'number' && Number.isFinite(action.selectionPage)
+ ? Math.max(0, Math.floor(action.selectionPage))
+ : typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)
+ ? Math.max(0, Math.floor(values.galleryPage))
+ : 0;
+ const settings = getGallerySettings(values);
+ const existingNavigationQuery =
+ values.selectedImageQuery && typeof values.selectedImageQuery === 'object'
+ ? (values.selectedImageQuery as Record<string, unknown>)
+ : null;
+ const selectedImageQuery =
+ action.preserveNavigationQuery && existingNavigationQuery
+ ? { ...existingNavigationQuery, page: selectedImagePage }
+ : {
+ boardId: typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none',
+ galleryView: values.galleryView === 'assets' ? 'assets' : 'images',
+ imageOrderDir: settings.imageOrderDir,
+ page: selectedImagePage,
+ paginationMode: settings.paginationMode,
+ searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',
+ starredFirst: settings.starredFirst,
+ };
+
+ return {
+ ...values,
+ selectedImage: action.image,
+ selectedImageName: action.image.imageName,
+ selectedImageNames: [action.image.imageName],
+ selectedImagePage,
+ selectedImageQuery,
+ };
+ },
action.projectId
);
}
@@ -2708,11 +2873,27 @@ export const __workbenchReducerInternal = (
const selectedImageNames = getGallerySelectedImageNames(values);
if (!selectedImageNames.includes(imageName)) {
+ const settings = getGallerySettings(values);
+ const selectedImagePage =
+ typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)
+ ? Math.max(0, Math.floor(values.galleryPage))
+ : 0;
+
return {
...values,
selectedImage: action.image,
selectedImageName: imageName,
selectedImageNames: [...selectedImageNames, imageName],
+ selectedImagePage,
+ selectedImageQuery: {
+ boardId: typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none',
+ galleryView: values.galleryView === 'assets' ? 'assets' : 'images',
+ imageOrderDir: settings.imageOrderDir,
+ page: selectedImagePage,
+ paginationMode: settings.paginationMode,
+ searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',
+ starredFirst: settings.starredFirst,
+ },
};
}
@@ -2734,12 +2915,30 @@ export const __workbenchReducerInternal = (
case 'setGalleryMultiSelection': {
return updateGalleryValuesAndPauseLiveFollow(
state,
- (values) => ({
- ...values,
- selectedImage: action.primaryImage,
- selectedImageName: action.primaryImage.imageName,
- selectedImageNames: action.imageNames,
- }),
+ (values) => {
+ const settings = getGallerySettings(values);
+ const selectedImagePage =
+ typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)
+ ? Math.max(0, Math.floor(values.galleryPage))
+ : 0;
+
+ return {
+ ...values,
+ selectedImage: action.primaryImage,
+ selectedImageName: action.primaryImage.imageName,
+ selectedImageNames: action.imageNames,
+ selectedImagePage,
+ selectedImageQuery: {
+ boardId: typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none',
+ galleryView: values.galleryView === 'assets' ? 'assets' : 'images',
+ imageOrderDir: settings.imageOrderDir,
+ page: selectedImagePage,
+ paginationMode: settings.paginationMode,
+ searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',
+ starredFirst: settings.starredFirst,
+ },
+ };
+ },
action.projectId
);
}
@@ -2823,59 +3022,160 @@ export const __workbenchReducerInternal = (
action.projectId
);
}
- case 'touchGalleryRefresh': {
- return updateGalleryValues(
- state,
- (values) => ({
- ...values,
- galleryImagesRefreshToken: createId('gallery-images-refresh'),
- galleryRefreshToken: createId('gallery-refresh'),
- }),
- action.projectId
- );
- }
- case 'touchGalleryImagesRefresh': {
- return updateGalleryValues(
- state,
- (values) => ({
- ...values,
- galleryImagesRefreshToken: createId('gallery-images-refresh'),
- }),
- action.projectId
- );
+ case 'patchGalleryImages': {
+ const imageNames = new Set(action.imageNames);
+
+ return updateAllProjectGalleryValues(state, (values) => {
+ let didChange = false;
+ const patchImage = (value: unknown): unknown => {
+ if (
+ !value ||
+ typeof value !== 'object' ||
+ typeof (value as Partial<GeneratedImageContract>).imageName !== 'string' ||
+ !imageNames.has((value as GeneratedImageContract).imageName)
+ ) {
+ return value;
+ }
+
+ didChange = true;
+ return { ...value, ...action.changes };
+ };
+ const recentImages = getGalleryImages(values).map(patchImage) as GeneratedImageContract[];
+ const selectedImage = patchImage(values.selectedImage);
+ const compareImage = patchImage(values.compareImage);
+ const selectedImageMoved = action.changes.boardId !== undefined && selectedImage !== values.selectedImage;
+ const selectedImageQuery =
+ selectedImageMoved && values.selectedImageQuery && typeof values.selectedImageQuery === 'object'
+ ? {
+ ...(values.selectedImageQuery as Record<string, unknown>),
+ boardId: action.changes.boardId,
+ page: 0,
+ paginationMode: 'infinite',
+ searchTerm: '',
+ }
+ : values.selectedImageQuery;
+
+ return didChange
+ ? {
+ ...values,
+ compareImage,
+ recentImages,
+ selectedImage,
+ ...(selectedImageMoved ? { selectedImagePage: 0, selectedImageQuery } : {}),
+ }
+ : values;
+ });
}
case 'removeGalleryImages': {
- const removedImageNames = new Set(action.imageNames);
- const nextState = updateGalleryValues(
- state,
- (values) => {
- const selectedImage = values.selectedImage as GeneratedImageContract | null | undefined;
- const compareImage = values.compareImage as GeneratedImageContract | null | undefined;
- const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;
+ return removeGalleryImagesFromAllProjects(state, new Set(action.imageNames));
+ }
+ case 'reconcileDeletedGalleryBoard': {
+ const imageNames = new Set<string>();
+
+ for (const project of state.projects) {
+ const values = getWidgetValues(project, 'gallery');
+ const candidates = [
+ ...getGalleryImages(values),
+ values.selectedImage as GeneratedImageContract | null | undefined,
+ values.compareImage as GeneratedImageContract | null | undefined,
+ ];
+
+ for (const candidate of candidates) {
+ if (
+ candidate &&
+ typeof candidate === 'object' &&
+ (candidate as Partial<GalleryImage>).boardId === action.boardId
+ ) {
+ imageNames.add(candidate.imageName);
+ }
+ }
+ }
- return {
- ...values,
- compareImage: compareImage && removedImageNames.has(compareImage.imageName) ? null : compareImage,
- recentImages: getGalleryImages(values).filter((image) => !removedImageNames.has(image.imageName)),
- selectedImage: selectedImage && removedImageNames.has(selectedImage.imageName) ? null : selectedImage,
- selectedImageName: selectedImageName && removedImageNames.has(selectedImageName) ? null : selectedImageName,
- selectedImageNames: getGallerySelectedImageNames(values).filter((name) => !removedImageNames.has(name)),
- };
- },
- action.projectId
- );
+ const reconciledState = action.includeImages
+ ? removeGalleryImagesFromAllProjects(state, imageNames)
+ : updateAllProjectGalleryValues(state, (values) => {
+ let didChange = false;
+ const patchBoard = (value: unknown): unknown => {
+ if (!value || typeof value !== 'object' || (value as Partial<GalleryImage>).boardId !== action.boardId) {
+ return value;
+ }
- return updateProjectById(nextState, action.projectId ?? state.activeProjectId, (project) =>
- updateProjectWidgetValues(project, 'upscale', (rawValues) => {
- const values = normalizeUpscaleWidgetValues(rawValues);
+ didChange = true;
+ return { ...value, boardId: 'none' };
+ };
+ const recentImages = getGalleryImages(values).map(patchBoard) as GeneratedImageContract[];
+ const selectedImage = patchBoard(values.selectedImage);
+ const compareImage = patchBoard(values.compareImage);
+ const selectedImageMoved = selectedImage !== values.selectedImage;
+
+ return didChange
+ ? {
+ ...values,
+ compareImage,
+ recentImages,
+ selectedImage,
+ ...(selectedImageMoved
+ ? {
+ selectedImagePage: 0,
+ selectedImageQuery: {
+ ...(values.selectedImageQuery && typeof values.selectedImageQuery === 'object'
+ ? (values.selectedImageQuery as Record<string, unknown>)
+ : {}),
+ boardId: 'none',
+ page: 0,
+ paginationMode: 'infinite',
+ searchTerm: '',
+ },
+ }
+ : {}),
+ }
+ : values;
+ });
+
+ const boardReferencesState = updateAllProjectGalleryValues(reconciledState, (values) => {
+ const selectedBoardWasDeleted = values.selectedBoardId === action.boardId;
+ const projectBoardWasDeleted = values.projectBoardId === action.boardId;
+
+ if (!selectedBoardWasDeleted && !projectBoardWasDeleted) {
+ return values;
+ }
- if (!values?.inputImage || !removedImageNames.has(values.inputImage.image_name)) {
- return rawValues;
+ return {
+ ...values,
+ ...(selectedBoardWasDeleted
+ ? {
+ galleryPage: 0,
+ selectedBoardId: 'none',
+ ...(action.includeImages ? { selectedImageNames: [] } : {}),
+ }
+ : {}),
+ ...(projectBoardWasDeleted ? { projectBoardId: null } : {}),
+ };
+ });
+ let didChangeQueue = false;
+ const projects = boardReferencesState.projects.map((project) => {
+ let didChangeItems = false;
+ const items = project.queue.items.map((item) => {
+ if (
+ (item.status !== 'pending' && item.status !== 'running') ||
+ item.snapshot.galleryBoardId !== action.boardId
+ ) {
+ return item;
}
- return { ...clearDeletedUpscaleInput(values, removedImageNames) };
- })
- );
+ didChangeItems = true;
+ return { ...item, snapshot: { ...item.snapshot, galleryBoardId: 'none' } };
+ });
+
+ if (!didChangeItems) {
+ return project;
+ }
+
+ didChangeQueue = true;
+ return { ...project, queue: { ...project.queue, items } };
+ });
+
+ return didChangeQueue ? { ...boardReferencesState, projects } : boardReferencesState;
}
case 'setGalleryProjectBoardId': {
return updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }), action.projectId);
@@ -3203,9 +3503,6 @@ export const __workbenchReducerInternal = (
},
};
}
- case 'refreshBackendData': {
- return { ...state, projects: state.projects.map((project) => refreshProjectBackendData(project)) };
- }
case 'recordNotice': {
return addNotification(
state,
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
index d85ef774d8..1a56bad57d 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
@@ -79,14 +79,32 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchSt
appendStagingCandidate: command('appendCanvasStagingCandidate'),
},
gallery: {
- removeImages: command('removeGalleryImages', (imageNames: string[], projectId?: string) => ({
- imageNames,
- projectId,
+ patchImages: command(
+ 'patchGalleryImages',
+ (imageNames: string[], changes: ActionPayload<'patchGalleryImages'>['changes']) => ({
+ changes,
+ imageNames,
+ })
+ ),
+ removeImages: command('removeGalleryImages', (imageNames: string[]) => ({ imageNames })),
+ reconcileDeletedBoard: command('reconcileDeletedGalleryBoard', (boardId: string, includeImages: boolean) => ({
+ boardId,
+ includeImages,
})),
selectBoard: command('selectGalleryBoard', (boardId: string, projectId?: string) => ({ boardId, projectId })),
selectImage: command(
'selectGalleryImage',
- (image: ActionPayload<'selectGalleryImage'>['image'], projectId?: string) => ({ image, projectId })
+ (
+ image: ActionPayload<'selectGalleryImage'>['image'],
+ projectId?: string,
+ selectionPage?: number,
+ preserveNavigationQuery?: boolean
+ ) => ({
+ image,
+ preserveNavigationQuery,
+ projectId,
+ selectionPage,
+ })
),
setCompareImage: command(
'setGalleryCompareImage',
@@ -127,8 +145,6 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchSt
projectId,
})
),
- touch: command('touchGalleryRefresh', (projectId?: string) => ({ projectId })),
- touchImages: command('touchGalleryImagesRefresh', (projectId?: string) => ({ projectId })),
updateSettings: command(
'updateGallerySettings',
(settings: ActionPayload<'updateGallerySettings'>['settings'], projectId?: string) => ({
@@ -279,7 +295,6 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchSt
clearCompleted: command('clearCompletedQueueItems'),
markBackendCancelled: command('markQueueItemBackendCancelled'),
markBackendSubmitted: command('markQueueItemBackendSubmitted'),
- refreshBackendData: command('refreshBackendData'),
routePartialResults: command('routeQueueItemPartialResults'),
routeResults: command('routeQueueItemResults'),
setConnectionStatus: command('setBackendConnectionStatus'),