Skip to content

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

feat(webv2): add the Intermediates settings section

Josh Corbett30b7acebd24e
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index a171d6e303..76fa0b12fa 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -40,6 +40,8 @@ The queue pilot is the first migrated feature. Its private `QueueBackendPort` is
Queue exposes board-independent active backend sessions, including preparation and result settlement. The Gallery progress section includes every unfinished batch slot, including queued work; Preview follows executing and settling sessions. Both use gallery-destination projections of the active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions do not participate in board counts, saved-image selection, or navigation. Saved outputs retain their actual backend board destinations; automatic result selection does not change the browsed board or its paging window.
+Intermediates owns the manager for temporary media behind `@features/intermediates`: transport mapping, account-fenced query keys, the selection core, the confirmation dialog and the operation panel. It is a Settings section, contributed as metadata through `settingsContribution` so the dialog's catalog never loads the manager or its transport until the section opens. The eligibility policy (safe, referenced, active, recent) is server-owned; the client only freezes a server preview and confirms it. Realtime updates attach for the section's mounted lifetime through the Platform socket hub and invalidate the account's summaries when an operation settles, by either the socket or the polled record, or when the socket reconnects. Workbench supplies the entry points (the Data & workspace link, the project actions menu, the Users page callback) and hands the manager a one-shot focus intent (a project to preselect or an account to filter by) rather than route state.
+
Fonts owns its authenticated catalog, managed-library UI, and browser font-registration lifetime behind `@features/fonts`. App composes the session runtime; Canvas receives a font-resolution port and owns text geometry, rendering, and output readiness. Persisted text references and project-file remapping remain in Workbench. Launchpad font previews and Canvas share the same account lifetime; font binaries and browser registration names are not project state. The browser registry admits at most 64 faces and 128 MiB of font input data, including faces currently being parsed. Active references are protected from eviction; if they exhaust the budget, further loads fail until references are released. This bounds retained input, not browser-specific decoded font memory. Canvas reconciles active references only when the document forests or text draft source change.
Font runtime composition and project-file option state travel in the existing shared route chunk. Catalog transport, the Fonts page, and project-file option dialogs load on demand. Missing-font recovery loads only for documents containing custom references. The locale asset plugin serves font-library strings as a separate namespace in development and production, loaded when the library or recovery UI opens; source translations remain in the canonical locale files. Text tool controls load when selected; their shared Canvas/Layer form and interaction dependencies remain grouped to avoid extra widget-activation requests. Catalog query keys have a lightweight public entry so invalidating an imported font does not pull the transport into startup.
@@ -85,16 +87,17 @@ The target dependency graph intentionally records the current migration cycle: W
Feature interfaces remain ordinary module interfaces unless two adapters add leverage. Queue's backend port has production transport/realtime and test adapters; Identity's token/session port has browser-session and test adapters; Models and Nodes use production event/transport adapters; their sinks (model-load activity, node execution) are injected into Queue's runtime at the App composition root, with test doubles in Queue's runtime tests. Gallery, Generation, Workflow, and Upscale keep their compilation and UI seams internal until their feature tickets demonstrate another independent adapter. Workbench image actions likewise remain internal rather than becoming a shallow Image Feature.
-| Feature | Responsibility and representative callers | Allowed dependencies and candidate public interface |
-| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Identity | Session/token policy and user administration; App guards/login, Queue capabilities, Workbench account/Launchpad surfaces | Platform plus Models' public capability reads; session reads/commands, token port, user queries and manager contribution |
-| Models | Catalog, configuration, install/load lifecycle; Generation, Queue, Workflow, Upscale, Identity, model manager | Platform plus Identity's public authorization reads; descriptors/capabilities, catalog/load commands and manager contribution |
-| Nodes | Custom-node catalog/templates and execution lifecycle; Workflow editor and node manager | Platform; descriptors, catalog commands, execution snapshots and manager contribution |
-| Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution |
-| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |
-| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |
-| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution |
-| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |
+| Feature | Responsibility and representative callers | Allowed dependencies and candidate public interface |
+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Identity | Session/token policy and user administration; App guards/login, Queue capabilities, Workbench account/Launchpad surfaces | Platform plus Models' public capability reads; session reads/commands, token port, user queries and manager contribution |
+| Models | Catalog, configuration, install/load lifecycle; Generation, Queue, Workflow, Upscale, Identity, model manager | Platform plus Identity's public authorization reads; descriptors/capabilities, catalog/load commands and manager contribution |
+| Nodes | Custom-node catalog/templates and execution lifecycle; Workflow editor and node manager | Platform; descriptors, catalog commands, execution snapshots and manager contribution |
+| Queue | Backend queue state, realtime interpretation, submission/reconciliation and Queue UI; App runtime, Workbench aggregate/shell, Generation/Gallery/Workflow | Platform and public envelopes/capabilities from Identity, Models, Generation, Workflow, Upscale; backend port, queue reads/commands and widget contribution |
+| Gallery | Image collection, selection, board policy and Gallery UI; App adapter, Generation, Workflow, Upscale, Workbench image actions | Platform and Queue's public progress reads; gallery reads/commands and widget contribution |
+| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |
+| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue/Generation interfaces; document reads/commands, compiled submission envelope and widget contribution |
+| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |
+| Intermediates | Per-project intermediates read models, cleanup previews/operations and the Settings section that manages them; Workbench settings, project menus, account administration | Platform plus Identity's public session/capability reads; query keys, read models, the focus intent and the `settingsContribution` metadata whose loader owns the section body |
## Settings contributions
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index efff9e36cf..859f909014 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": 895804,
+ "brotliBytes": 896474,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 894617,
+ "gzipBytes": 895268,
"imageRawBytes": 156376,
- "initialRawBytes": 2128478,
+ "initialRawBytes": 2130239,
"largestAssetRawBytes": 778953,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 89515,
+ "ownedRawBytes": 90438,
"requestCount": 37,
"scriptRequestCount": 21,
"sourceOwners": [
@@ -155,6 +155,8 @@
"source:src/features/identity/ui/UserManagement.tsx",
"source:src/features/identity/ui/UsersPage.tsx",
"source:src/features/identity/ui/useIdentityNotify.ts",
+ "source:src/features/intermediates/data/focus.ts",
+ "source:src/features/intermediates/index.ts",
"source:src/features/models/core/baseIdentity.ts",
"source:src/features/models/data/api.ts",
"source:src/features/models/data/apiKeys.ts",
@@ -324,15 +326,15 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1233253,
+ "brotliBytes": 1236046,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1227029,
+ "gzipBytes": 1229608,
"imageRawBytes": 156376,
- "initialRawBytes": 3164374,
+ "initialRawBytes": 3171535,
"largestAssetRawBytes": 778953,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 141887,
+ "ownedRawBytes": 141890,
"requestCount": 86,
"scriptRequestCount": 70,
"sourceOwners": [
@@ -582,6 +584,9 @@
"source:src/features/identity/ui/UserManagement.tsx",
"source:src/features/identity/ui/UsersPage.tsx",
"source:src/features/identity/ui/useIdentityNotify.ts",
+ "source:src/features/intermediates/data/focus.ts",
+ "source:src/features/intermediates/index.ts",
+ "source:src/features/intermediates/settingsContribution.ts",
"source:src/features/models/core/baseIdentity.ts",
"source:src/features/models/data/api.ts",
"source:src/features/models/data/apiKeys.ts",
@@ -1044,7 +1049,7 @@
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-09-22",
+ "capturedAt": "2026-09-23",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
@@ -1083,6 +1088,7 @@
"_ag-psd",
"src/app/WorkbenchApp.tsx",
"src/features/gallery/ui/launchpad/RecentOutputs.tsx",
+ "src/features/intermediates/ui/IntermediatesManager.tsx",
"src/features/models/ui/ModelManagerView.tsx",
"src/features/models/ui/launchpad/ModelsNotice.tsx",
"src/features/nodes/ui/NodeManagerView.tsx",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 9010e39765..cf2c6ec868 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1,6 +1,6 @@
{
"browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome",
- "capturedAt": "2026-09-22",
+ "capturedAt": "2026-09-23",
"routes": [
{
"activatedResourceBaseline": {
@@ -14,13 +14,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 123.90000000596046,
+ "domContentLoadedMedianMs": 126.20000000111759,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 124.10000000149012,
- "longestTaskMaxMs": 78,
+ "loadMedianMs": 126.30000000074506,
+ "longestTaskMaxMs": 82,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -30,13 +30,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 32,
- "scriptRawBytes": 1810772,
+ "scriptRawBytes": 1813288,
"scriptRequestCount": 28,
- "totalRawBytes": 1997713
+ "totalRawBytes": 2006972
},
- "routeReadyMedianMs": 265.20000000298023,
+ "routeReadyMedianMs": 272.2000000011176,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -52,13 +52,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 154.10000000149012,
+ "domContentLoadedMedianMs": 125.89999999850988,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 154.29999999701977,
- "longestTaskMaxMs": 140,
+ "loadMedianMs": 126.09999999962747,
+ "longestTaskMaxMs": 79,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -68,13 +68,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 32,
- "scriptRawBytes": 1810772,
+ "scriptRawBytes": 1813288,
"scriptRequestCount": 28,
- "totalRawBytes": 1997713
+ "totalRawBytes": 2006972
},
- "routeReadyMedianMs": 352.5,
+ "routeReadyMedianMs": 279.40000000037253,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -90,15 +90,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 135.5,
+ "domContentLoadedMedianMs": 132.7999999988824,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 135.60000000149012,
- "longestTaskMaxMs": 202,
+ "loadMedianMs": 132.89999999850988,
+ "longestTaskMaxMs": 163,
"owner": "workbench",
- "projectSwitchMedianMs": 35.100000001490116,
+ "projectSwitchMedianMs": 34.40000000037253,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -106,13 +106,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 99,
- "scriptRawBytes": 3736608,
+ "scriptRawBytes": 3760244,
"scriptRequestCount": 94,
- "totalRawBytes": 4079925
+ "totalRawBytes": 4110304
},
- "routeReadyMedianMs": 459.90000000596046,
+ "routeReadyMedianMs": 435.2999999988824,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -128,15 +128,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 127.29999999701977,
+ "domContentLoadedMedianMs": 128.19999999925494,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 127.39999999850988,
- "longestTaskMaxMs": 193,
+ "loadMedianMs": 128.40000000037253,
+ "longestTaskMaxMs": 151,
"owner": "workbench",
- "projectSwitchMedianMs": 46.399999998509884,
+ "projectSwitchMedianMs": 45.5,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -144,13 +144,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 99,
- "scriptRawBytes": 3736608,
+ "scriptRawBytes": 3760244,
"scriptRequestCount": 94,
- "totalRawBytes": 4079925
+ "totalRawBytes": 4110304
},
- "routeReadyMedianMs": 441.19999999552965,
+ "routeReadyMedianMs": 426.90000000037253,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -159,20 +159,20 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 309239,
+ "largestAssetRawBytes": 309242,
"otherRawBytes": 0,
"requestCount": 9,
- "scriptRawBytes": 502842,
+ "scriptRawBytes": 502849,
"scriptRequestCount": 9,
- "totalRawBytes": 502842
+ "totalRawBytes": 502849
},
- "domContentLoadedMedianMs": 124.70000000298023,
+ "domContentLoadedMedianMs": 128,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.600000001490116,
- "layoutReturnSwitchMedianMs": 45.79999999701977,
- "layoutSwitchMedianMs": 83.09999999403954,
- "loadMedianMs": 124.80000000447035,
- "longestTaskMaxMs": 152,
+ "layoutAckMedianMs": 2.900000000372529,
+ "layoutReturnSwitchMedianMs": 47.29999999888241,
+ "layoutSwitchMedianMs": 82.30000000074506,
+ "loadMedianMs": 128.10000000149012,
+ "longestTaskMaxMs": 155,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -182,13 +182,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 108,
- "scriptRawBytes": 4239450,
+ "scriptRawBytes": 4263093,
"scriptRequestCount": 103,
- "totalRawBytes": 4582767
+ "totalRawBytes": 4613153
},
- "routeReadyMedianMs": 1109.8000000044703,
+ "routeReadyMedianMs": 1130.6000000014901,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -197,20 +197,20 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 309239,
+ "largestAssetRawBytes": 309242,
"otherRawBytes": 0,
"requestCount": 9,
- "scriptRawBytes": 502842,
+ "scriptRawBytes": 502849,
"scriptRequestCount": 9,
- "totalRawBytes": 502842
+ "totalRawBytes": 502849
},
- "domContentLoadedMedianMs": 130.29999999701977,
+ "domContentLoadedMedianMs": 123.30000000074506,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.7999999970197678,
- "layoutReturnSwitchMedianMs": 49,
- "layoutSwitchMedianMs": 84.20000000298023,
- "loadMedianMs": 130.39999999850988,
- "longestTaskMaxMs": 207,
+ "layoutAckMedianMs": 2.800000000745058,
+ "layoutReturnSwitchMedianMs": 47.90000000037253,
+ "layoutSwitchMedianMs": 85.19999999925494,
+ "loadMedianMs": 123.5,
+ "longestTaskMaxMs": 189,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -220,13 +220,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 108,
- "scriptRawBytes": 4239450,
+ "scriptRawBytes": 4263093,
"scriptRequestCount": 103,
- "totalRawBytes": 4582767
+ "totalRawBytes": 4613153
},
- "routeReadyMedianMs": 1133.1999999955297,
+ "routeReadyMedianMs": 1110.9000000003725,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -238,17 +238,17 @@
"largestAssetRawBytes": 175033,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 397914,
+ "scriptRawBytes": 397917,
"scriptRequestCount": 6,
- "totalRawBytes": 413327
+ "totalRawBytes": 413330
},
- "domContentLoadedMedianMs": 127.29999999701977,
+ "domContentLoadedMedianMs": 129.2000000011176,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.5,
- "layoutReturnSwitchMedianMs": 34.100000001490116,
- "layoutSwitchMedianMs": 101.10000000149012,
- "loadMedianMs": 127.39999999850988,
- "longestTaskMaxMs": 161,
+ "layoutAckMedianMs": 3.399999998509884,
+ "layoutReturnSwitchMedianMs": 33.09999999962747,
+ "layoutSwitchMedianMs": 96.79999999888241,
+ "loadMedianMs": 129.30000000074506,
+ "longestTaskMaxMs": 158,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -258,13 +258,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 106,
- "scriptRawBytes": 4134522,
+ "scriptRawBytes": 4158161,
"scriptRequestCount": 100,
- "totalRawBytes": 4493252
+ "totalRawBytes": 4523634
},
- "routeReadyMedianMs": 1145,
+ "routeReadyMedianMs": 1145.300000000745,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -276,17 +276,17 @@
"largestAssetRawBytes": 175033,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 397914,
+ "scriptRawBytes": 397917,
"scriptRequestCount": 6,
- "totalRawBytes": 413327
+ "totalRawBytes": 413330
},
- "domContentLoadedMedianMs": 120.60000000149012,
+ "domContentLoadedMedianMs": 132.5,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.600000001490116,
- "layoutReturnSwitchMedianMs": 39.5,
- "layoutSwitchMedianMs": 137,
- "loadMedianMs": 120.70000000298023,
- "longestTaskMaxMs": 380,
+ "layoutAckMedianMs": 2.5,
+ "layoutReturnSwitchMedianMs": 40.79999999888241,
+ "layoutSwitchMedianMs": 130.90000000037253,
+ "loadMedianMs": 132.7999999988824,
+ "longestTaskMaxMs": 389,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -296,13 +296,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 106,
- "scriptRawBytes": 4134522,
+ "scriptRawBytes": 4158161,
"scriptRequestCount": 100,
- "totalRawBytes": 4493252
+ "totalRawBytes": 4523634
},
- "routeReadyMedianMs": 1156.4000000059605,
+ "routeReadyMedianMs": 1186.0999999996275,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -318,13 +318,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 122.70000000298023,
+ "domContentLoadedMedianMs": 125.10000000149012,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 44.70000000298023,
- "loadMedianMs": 122.80000000447035,
- "longestTaskMaxMs": 163,
+ "layoutSwitchMedianMs": 46.09999999962747,
+ "loadMedianMs": 125.10000000149012,
+ "longestTaskMaxMs": 155,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -334,13 +334,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 99,
- "scriptRawBytes": 3736608,
+ "scriptRawBytes": 3760244,
"scriptRequestCount": 94,
- "totalRawBytes": 4079925
+ "totalRawBytes": 4110304
},
- "routeReadyMedianMs": 1342.7000000029802,
+ "routeReadyMedianMs": 1349.7999999988824,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -356,13 +356,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 124.89999999850988,
+ "domContentLoadedMedianMs": 125.70000000111759,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 52.19999999552965,
- "loadMedianMs": 125.10000000149012,
- "longestTaskMaxMs": 150,
+ "layoutSwitchMedianMs": 54.5,
+ "loadMedianMs": 125.80000000074506,
+ "longestTaskMaxMs": 155,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -372,13 +372,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778953,
- "otherRawBytes": 161118,
+ "otherRawBytes": 167861,
"requestCount": 99,
- "scriptRawBytes": 3736608,
+ "scriptRawBytes": 3760244,
"scriptRequestCount": 94,
- "totalRawBytes": 4079925
+ "totalRawBytes": 4110304
},
- "routeReadyMedianMs": 1359.6000000014901,
+ "routeReadyMedianMs": 1370,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -546,6 +546,8 @@
"source:src/features/identity/ui/UserManagement.tsx",
"source:src/features/identity/ui/UsersPage.tsx",
"source:src/features/identity/ui/useIdentityNotify.ts",
+ "source:src/features/intermediates/data/focus.ts",
+ "source:src/features/intermediates/index.ts",
"source:src/features/models/core/baseIdentity.ts",
"source:src/features/models/core/library.ts",
"source:src/features/models/core/taxonomy.ts",
@@ -1077,6 +1079,9 @@
"source:src/features/identity/ui/UserManagement.tsx",
"source:src/features/identity/ui/UsersPage.tsx",
"source:src/features/identity/ui/useIdentityNotify.ts",
+ "source:src/features/intermediates/data/focus.ts",
+ "source:src/features/intermediates/index.ts",
+ "source:src/features/intermediates/settingsContribution.ts",
"source:src/features/models/core/baseIdentity.ts",
"source:src/features/models/core/library.ts",
"source:src/features/models/core/taxonomy.ts",
@@ -2123,6 +2128,9 @@
"source:src/features/identity/ui/UserManagement.tsx",
"source:src/features/identity/ui/UsersPage.tsx",
"source:src/features/identity/ui/useIdentityNotify.ts",
+ "source:src/features/intermediates/data/focus.ts",
+ "source:src/features/intermediates/index.ts",
+ "source:src/features/intermediates/settingsContribution.ts",
"source:src/features/models/core/baseIdentity.ts",
"source:src/features/models/core/library.ts",
"source:src/features/models/core/taxonomy.ts",
@@ -3327,6 +3335,9 @@
"source:src/features/identity/ui/UserManagement.tsx",
"source:src/features/identity/ui/UsersPage.tsx",
"source:src/features/identity/ui/useIdentityNotify.ts",
+ "source:src/features/intermediates/data/focus.ts",
+ "source:src/features/intermediates/index.ts",
+ "source:src/features/intermediates/settingsContribution.ts",
"source:src/features/models/core/baseIdentity.ts",
"source:src/features/models/core/library.ts",
"source:src/features/models/core/taxonomy.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 5fb0ac385c..9be43acc3d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -544,7 +544,8 @@
"quotaDescription": "This server has insufficient font storage. Import with font references, then install or replace missing fonts before generating or exporting images.",
"importReferences": "Import without font files",
"installing": "Installing fonts {{completed}} / {{total}}"
- }
+ },
+ "clearIntermediates": "Clear intermediates…"
},
"users": {
"accountCount_one": "{{count}} account in this workspace.",
@@ -596,7 +597,8 @@
"title": "Users",
"updated": "User updated",
"user": "User",
- "you": "You"
+ "you": "You",
+ "manageIntermediatesNamed": "Manage intermediates of {{name}}"
},
"fonts": {
"title": "Fonts",
@@ -1776,7 +1778,7 @@
},
"workspaceActions": {
"label": "Data & workspace",
- "description": "Reset the layout or permanently delete saved projects and settings."
+ "description": "Reset the layout, manage intermediates, or permanently delete saved projects and settings."
},
"about": {
"label": "About InvokeAI",
@@ -1821,7 +1823,8 @@
"developer": "Developer",
"server": "Server",
"workspace": "Data & workspace",
- "about": "About"
+ "about": "About",
+ "intermediates": "Intermediates"
},
"developerConsoleOutputEnabled": {
"label": "Mirror logs to the browser console",
@@ -1832,7 +1835,8 @@
"description": "Restore the default level, namespaces, console and timing settings, including namespaces added in newer versions."
},
"resetLoggingDefaults": "Reset to defaults",
- "loggingDefaultsActive": "Default logging settings are active."
+ "loggingDefaultsActive": "Default logging settings are active.",
+ "manageIntermediates": "Manage intermediates…"
}
},
"shell": {
@@ -4194,5 +4198,106 @@
},
"changedFromDefault": "Changed from default",
"changedSetting": "{{setting}}: changed from default"
+ },
+ "intermediates": {
+ "title": "Intermediates",
+ "description": "Temporary images and videos that generation leaves behind. Clear the ones nothing needs to reclaim disk space.",
+ "refresh": "Refresh",
+ "searchLabel": "Search projects",
+ "searchPlaceholder": "Search projects…",
+ "searchPlaceholderAdmin": "Search projects or accounts…",
+ "counts": {
+ "images_one": "{{count, number}} image",
+ "images_other": "{{count, number}} images",
+ "videos_one": "{{count, number}} video",
+ "videos_other": "{{count, number}} videos",
+ "projects_one": "{{count, number}} project",
+ "projects_other": "{{count, number}} projects",
+ "items_one": "{{count, number}} item",
+ "items_other": "{{count, number}} items"
+ },
+ "dialog": {
+ "title": "Delete intermediates?",
+ "forceTitle": "Force clear intermediates?",
+ "loadingPreview": "Checking what can be cleared…",
+ "previewFailed": "Could not check what can be cleared.",
+ "summary": "Clear {{images}} and {{videos}} from {{projects}}?",
+ "reclaim": "Approximately {{size}} can be reclaimed.",
+ "reclaimUnknown": "Reclaimable space is still being measured.",
+ "reclaimPartial_one": "{{count}} item is not measured yet.",
+ "reclaimPartial_other": "{{count}} items are not measured yet.",
+ "kept_one": "{{count}} in-use item will be kept.",
+ "kept_other": "{{count}} in-use items will be kept.",
+ "nothing": "Nothing is safe to clear right now.",
+ "forceWarning": "Force clearing also deletes intermediates that saved projects or workflows still reference. Those documents will show missing images and undo may no longer restore them. Queued, running and recently created work stays protected. Deletion cannot be undone.",
+ "affected": "Documents that will lose references",
+ "affectedProject_one": "Project “{{name}}” ({{count}} item)",
+ "affectedProject_other": "Project “{{name}}” ({{count}} items)",
+ "affectedWorkflow_one": "Workflow “{{name}}” ({{count}} item)",
+ "affectedWorkflow_other": "Workflow “{{name}}” ({{count}} items)",
+ "affectedHidden_one": "{{count}} document in another account",
+ "affectedHidden_other": "{{count}} documents in other accounts",
+ "acknowledge": "I understand this may break saved projects and workflows and cannot be undone.",
+ "typeToConfirm": "Type {{word}} to confirm",
+ "confirm": "Delete",
+ "forceConfirm": "Force delete",
+ "startFailed": "Could not start the cleanup.",
+ "keptReasons": "{{referenced}} referenced by saved projects or workflows, {{active}} used by queued or running work, {{recent}} created recently.",
+ "forceToggle": "Also delete items that saved projects or workflows still reference (advanced)",
+ "previewExpired": "This check is no longer current. Check again before deleting.",
+ "tooManyRows": "More than {{count}} projects match. Narrow the search or clear the selection and choose projects."
+ },
+ "operation": {
+ "pending": "Preparing cleanup…",
+ "status": {
+ "pending": "Cleanup queued",
+ "running": "Clearing intermediates…",
+ "completed": "Cleanup finished",
+ "failed": "Cleanup stopped"
+ },
+ "progress": "{{done}} of {{total}} processed",
+ "deleted": "Deleted",
+ "retained": "Kept",
+ "failed": "Failed",
+ "pendingDisk": "Awaiting disk cleanup",
+ "reclaimed": "Reclaimed",
+ "retry": "Retry unresolved",
+ "dismiss": "Dismiss",
+ "retryFailed": "Could not retry the cleanup.",
+ "pendingDiskNote": "Some files could not be removed yet. They are cleaned up on the next server start and their space is not counted as reclaimed."
+ },
+ "empty": {
+ "title": "No intermediates",
+ "description": "There is nothing to clean up.",
+ "noMatches": "No matching projects",
+ "noMatchesDescription": "No project matches your search."
+ },
+ "errors": {
+ "couldNotLoad": "Could not load intermediates."
+ },
+ "owner": {
+ "filtered": "Account: {{name}}",
+ "showEveryone": "Show everyone"
+ },
+ "list": {
+ "selectAll": "Select all",
+ "selectRow": "Select {{name}}",
+ "delete": "Delete",
+ "used": "Used",
+ "unused": "Unused",
+ "unassigned": "Unassigned",
+ "unassignedBadge": "No project",
+ "rowSummary": "{{size}} reclaimable {{unmeasured}}",
+ "unmeasured_one": "({{count, number}} unmeasured)",
+ "unmeasured_other": "({{count, number}} unmeasured)",
+ "ownerAndSize": "{{owner}} · {{size}}"
+ },
+ "stats": {
+ "measuringNote": "Sizes are still being measured; figures grow as measurement finishes."
+ },
+ "selection": {
+ "estimate": "{{count, number}} selected · {{images}}, {{videos}}, about {{size}}",
+ "available": "{{images}}, {{videos}} unused · about {{size}} reclaimable"
+ }
}
}
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
index 91501746ec..9b01573e69 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
@@ -700,9 +700,53 @@ const createWorkflows = (count) =>
};
});
+/** Per-project intermediates rows for the Settings manager; ids match the projects fixture so entry points preselect. */
+const createIntermediates = () => [
+ {
+ user_id: 'fixture-user',
+ user_display_name: 'Fixture User',
+ user_email: '[email protected]',
+ project_id: 'fixture-project-001',
+ project_name: 'Fixture Project 001',
+ cover_image_name: 'fixture-image-0002.png',
+ images: { safe: 128, referenced: 6, active: 2, recent: 4 },
+ videos: { safe: 3, referenced: 1, active: 0, recent: 0 },
+ reclaimable_bytes: 2_580_000_000,
+ referenced_bytes: 120_000_000,
+ unknown_size_count: 0,
+ },
+ {
+ user_id: 'fixture-user',
+ user_display_name: 'Fixture User',
+ user_email: '[email protected]',
+ project_id: 'fixture-project-002',
+ project_name: 'Fixture Project 002',
+ cover_image_name: null,
+ images: { safe: 12, referenced: 0, active: 0, recent: 1 },
+ videos: { safe: 0, referenced: 0, active: 0, recent: 0 },
+ reclaimable_bytes: 96_000_000,
+ referenced_bytes: 0,
+ unknown_size_count: 3,
+ },
+ {
+ user_id: 'fixture-user',
+ user_display_name: 'Fixture User',
+ user_email: '[email protected]',
+ project_id: null,
+ project_name: null,
+ cover_image_name: null,
+ images: { safe: 40, referenced: 0, active: 0, recent: 0 },
+ videos: { safe: 1, referenced: 0, active: 0, recent: 0 },
+ reclaimable_bytes: 410_000_000,
+ referenced_bytes: 0,
+ unknown_size_count: 0,
+ },
+];
+
const createEmptyFixture = () => ({
boards: [],
images: [],
+ intermediates: [],
models: [],
nodeCatalog: { custom_nodes_path: '/opt/invokeai/nodes', node_packs: [] },
openApiDocument: createOpenApiDocument(0),
@@ -721,6 +765,7 @@ const createRepresentativeFixture = () => {
return {
boards: createBoards(images, videos, counts.projects),
images,
+ intermediates: createIntermediates(),
models: createModels(counts.models),
nodeCatalog: {
custom_nodes_path: '/opt/invokeai/nodes',
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 618636f532..609b411dae 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -93,6 +93,9 @@ const createState = (profile) => {
openApiDocument: clone(fixture.openApiDocument),
profile,
projects: new Map(fixture.projects.map((project) => [project.project_id, clone(project)])),
+ intermediates: fixture.intermediates.map(clone),
+ intermediatesOperations: new Map(),
+ intermediatesPreviews: new Map(),
queueItems: new Map(fixture.queueItems.map((item) => [item.item_id, clone(item)])),
videos: new Map(fixture.videos.map((video) => [video.video_name, clone(video)])),
workflows: new Map(fixture.workflows.map((workflow) => [workflow.workflow_id, clone(workflow)])),
@@ -1063,6 +1066,183 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, []);
}
+ if (method === 'GET' && path === '/api/v1/intermediates/summary') {
+ const search = (url.searchParams.get('search') ?? '').trim().toLowerCase();
+ const sort = url.searchParams.get('sort') ?? 'reclaimable_bytes';
+ const descending = (url.searchParams.get('order') ?? 'desc') === 'desc';
+ const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0));
+ const limit = Math.max(1, Number(url.searchParams.get('limit') ?? 50));
+ const rows = state.intermediates
+ .filter((row) => !search || (row.project_name ?? '').toLowerCase().includes(search))
+ .sort((left, right) =>
+ sort === 'project_name'
+ ? (left.project_name ?? '').localeCompare(right.project_name ?? '') * (descending ? -1 : 1)
+ : (right.reclaimable_bytes - left.reclaimable_bytes) * (descending ? 1 : -1)
+ );
+ const totals = rows.reduce(
+ (acc, row) => ({
+ rows: acc.rows + 1,
+ safe_images: acc.safe_images + row.images.safe,
+ safe_videos: acc.safe_videos + row.videos.safe,
+ in_use_images: acc.in_use_images + row.images.referenced + row.images.active + row.images.recent,
+ in_use_videos: acc.in_use_videos + row.videos.referenced + row.videos.active + row.videos.recent,
+ reclaimable_bytes: acc.reclaimable_bytes + row.reclaimable_bytes,
+ unknown_size_count: acc.unknown_size_count + row.unknown_size_count,
+ }),
+ {
+ rows: 0,
+ safe_images: 0,
+ safe_videos: 0,
+ in_use_images: 0,
+ in_use_videos: 0,
+ reclaimable_bytes: 0,
+ unknown_size_count: 0,
+ }
+ );
+ return json(200, {
+ items: rows.slice(offset, offset + limit),
+ total: rows.length,
+ offset,
+ limit,
+ totals,
+ recent_grace_seconds: 1800,
+ measuring: false,
+ can_manage_everyone: true,
+ });
+ }
+
+ if (method === 'POST' && path === '/api/v1/intermediates/previews') {
+ const requested = await readJsonBody(request);
+ const previewId = `preview-${state.intermediatesPreviews.size + 1}`;
+ const targets =
+ requested?.scope?.kind === 'selection'
+ ? state.intermediates.filter((row) =>
+ requested.scope.targets.some(
+ (target) => target.user_id === row.user_id && (target.project_id ?? null) === row.project_id
+ )
+ )
+ : state.intermediates;
+ const force = requested?.mode === 'force';
+ const impact = targets.reduce(
+ (acc, row) => ({
+ delete_images: acc.delete_images + row.images.safe + (force ? row.images.referenced : 0),
+ delete_videos: acc.delete_videos + row.videos.safe + (force ? row.videos.referenced : 0),
+ keep_referenced_images: acc.keep_referenced_images + (force ? 0 : row.images.referenced),
+ keep_referenced_videos: acc.keep_referenced_videos + (force ? 0 : row.videos.referenced),
+ keep_active_images: acc.keep_active_images + row.images.active,
+ keep_active_videos: acc.keep_active_videos + row.videos.active,
+ keep_recent_images: acc.keep_recent_images + row.images.recent,
+ keep_recent_videos: acc.keep_recent_videos + row.videos.recent,
+ reclaimable_bytes: acc.reclaimable_bytes + row.reclaimable_bytes + (force ? row.referenced_bytes : 0),
+ unknown_size_count: acc.unknown_size_count + row.unknown_size_count,
+ }),
+ {
+ delete_images: 0,
+ delete_videos: 0,
+ keep_referenced_images: 0,
+ keep_referenced_videos: 0,
+ keep_active_images: 0,
+ keep_active_videos: 0,
+ keep_recent_images: 0,
+ keep_recent_videos: 0,
+ reclaimable_bytes: 0,
+ unknown_size_count: 0,
+ }
+ );
+ const preview = {
+ preview_id: previewId,
+ mode: requested?.mode ?? 'safe',
+ scope: {
+ kind: requested?.scope?.kind ?? 'owner',
+ targets: requested?.scope?.targets ?? [],
+ user_id: requested?.scope?.user_id ?? null,
+ },
+ created_at: new Date().toISOString(),
+ expires_at: new Date(Date.now() + 600_000).toISOString(),
+ target_rows: targets.length,
+ impact,
+ affected_documents: force
+ ? targets
+ .filter((row) => row.images.referenced + row.videos.referenced > 0)
+ .map((row) => ({
+ kind: 'project',
+ user_id: row.user_id,
+ owner_id: row.project_id ?? 'unassigned',
+ name: row.project_name,
+ references: row.images.referenced + row.videos.referenced,
+ }))
+ : [],
+ affected_documents_hidden: 0,
+ };
+ state.intermediatesPreviews.set(previewId, { preview, targets });
+ return json(201, preview);
+ }
+
+ if (method === 'POST' && path === '/api/v1/intermediates/operations') {
+ const requested = await readJsonBody(request);
+ const frozen = state.intermediatesPreviews.get(requested?.preview_id);
+ if (!frozen) {
+ return json(404, { detail: 'Preview expired or unknown; request a new one' });
+ }
+ state.intermediatesPreviews.delete(requested.preview_id);
+ const operationId = `operation-${state.intermediatesOperations.size + 1}`;
+ const { impact } = frozen.preview;
+ const operation = {
+ operation_id: operationId,
+ user_id: 'fixture-user',
+ mode: frozen.preview.mode,
+ scope: frozen.preview.scope,
+ status: 'completed',
+ created_at: new Date().toISOString(),
+ started_at: new Date().toISOString(),
+ completed_at: new Date().toISOString(),
+ error: null,
+ target_images: impact.delete_images,
+ target_videos: impact.delete_videos,
+ progress: {
+ processed_images: impact.delete_images,
+ processed_videos: impact.delete_videos,
+ deleted_images: impact.delete_images,
+ deleted_videos: impact.delete_videos,
+ retained_images: 0,
+ retained_videos: 0,
+ failed_images: 0,
+ failed_videos: 0,
+ reclaimed_bytes: impact.reclaimable_bytes,
+ unknown_size_count: impact.unknown_size_count,
+ pending_disk_cleanup: 0,
+ unresolved_images: 0,
+ unresolved_videos: 0,
+ },
+ retried_from_operation_id: null,
+ retried_by_operation_id: null,
+ };
+ for (const row of frozen.targets) {
+ row.images = {
+ ...row.images,
+ safe: 0,
+ referenced: frozen.preview.mode === 'force' ? 0 : row.images.referenced,
+ };
+ row.videos = {
+ ...row.videos,
+ safe: 0,
+ referenced: frozen.preview.mode === 'force' ? 0 : row.videos.referenced,
+ };
+ row.reclaimable_bytes = 0;
+ row.unknown_size_count = 0;
+ }
+ state.intermediatesOperations.set(operationId, operation);
+ return json(202, operation);
+ }
+
+ {
+ const operationMatch = /^\/api\/v1\/intermediates\/operations\/([^/]+)$/.exec(path);
+ if (method === 'GET' && operationMatch) {
+ const operation = state.intermediatesOperations.get(decodeURIComponent(operationMatch[1]));
+ return operation ? json(200, operation) : json(404, { detail: 'Not found' });
+ }
+ }
+
if (method === 'GET' && path === '/api/v1/fonts') {
return json(200, {
items: [],
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 44bce7223b..1fcc597412 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -162,6 +162,21 @@ const surfaces = [
path: '/#/projects',
ready: waitForProjects,
},
+ {
+ id: 'launchpad-settings-intermediates-representative',
+ path: '/#/projects',
+ ready: async (page) => {
+ await page.getByRole('button', { exact: true, name: 'Settings' }).click();
+ const dialog = page.getByRole('dialog', { name: /^Settings:/ });
+ await dialog
+ .getByRole('navigation', { exact: true, name: 'Settings' })
+ .getByRole('button', { name: 'Intermediates' })
+ .click();
+ await page.getByRole('textbox', { exact: true, name: 'Search projects' }).waitFor();
+ await page.getByRole('checkbox', { exact: true, name: 'Select Fixture Project 001' }).waitFor();
+ },
+ representative: true,
+ },
{
id: 'launchpad-fonts-empty',
path: '/#/fonts',
diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
index 6e1a582dfc..52c460984b 100644
--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
@@ -31,6 +31,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[
'widget',
],
identity: [],
+ intermediates: ['settingsContribution'],
models: ['launchpad', 'react'],
nodes: [],
queue: ['contracts', 'devices', 'launchpad', 'menu', 'queries', 'react', 'reveal', 'utility', 'widget'],
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
index ceb3443924..3ed83d8d43 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
@@ -26,6 +26,7 @@ describe('Identity route capabilities', () => {
canManagePromptTemplates: false,
canManageSharedSystemPrompts: false,
canManageUsers: false,
+ canClearOthersIntermediates: false,
});
});
@@ -39,6 +40,7 @@ describe('Identity route capabilities', () => {
canManagePromptTemplates: true,
canManageSharedSystemPrompts: true,
canManageUsers: false,
+ canClearOthersIntermediates: false,
});
});
@@ -62,6 +64,7 @@ describe('Identity route capabilities', () => {
canManagePromptTemplates: false,
canManageSharedSystemPrompts: false,
canManageUsers: false,
+ canClearOthersIntermediates: false,
});
expect(getCapabilities(session({ user: { ...baseUser, is_admin: true } }))).toEqual({
canManageAppConfig: true,
@@ -72,6 +75,7 @@ describe('Identity route capabilities', () => {
canManagePromptTemplates: true,
canManageSharedSystemPrompts: true,
canManageUsers: true,
+ canClearOthersIntermediates: true,
});
});
});
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
index 7ec13c751b..48e62396e8 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
@@ -14,6 +14,8 @@ export interface Capabilities {
/** Edit prompts shared with everyone. Never covers another user's private prompt. */
canManageSharedSystemPrompts: boolean;
canManageUsers: boolean;
+ /** Clear intermediates of other accounts or of everyone; the routes are admin-only. */
+ canClearOthersIntermediates: boolean;
}
export const getCapabilities = (session: AuthSession): Capabilities => {
@@ -27,6 +29,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {
canManagePromptTemplates: false,
canManageSharedSystemPrompts: false,
canManageUsers: false,
+ canClearOthersIntermediates: false,
};
}
@@ -45,6 +48,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {
// Offer admin edits only for shared prompts to avoid accidental edits to another user's private content.
canManageSharedSystemPrompts: isAdmin,
canManageUsers: session.multiuserEnabled && session.user?.is_admin === true,
+ canClearOthersIntermediates: session.multiuserEnabled && session.user?.is_admin === true,
};
};
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx
index 495952871e..14444ece96 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx
@@ -4,7 +4,7 @@ import { useAuthSession } from '@features/identity/session';
import { useIdentityNotify } from '@features/identity/ui/useIdentityNotify';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, IconButton, ConfirmDialog, Scrollable, Tooltip } from '@platform/ui';
-import { PencilIcon, Trash2Icon, UserPlusIcon } from 'lucide-react';
+import { BrushCleaningIcon, PencilIcon, Trash2Icon, UserPlusIcon } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -25,7 +25,12 @@ export const UserManagement = () => {
);
};
-export const UsersManagementPanel = () => {
+/** `onManageIntermediates` is supplied by the shell that owns the intermediates manager's home. */
+export const UsersManagementPanel = ({
+ onManageIntermediates,
+}: {
+ onManageIntermediates?: (userId: string) => void;
+}) => {
const { t } = useTranslation();
const session = useAuthSession();
@@ -39,10 +44,16 @@ export const UsersManagementPanel = () => {
);
}
- return <UsersDirectory currentUserId={session.user.user_id} />;
+ return <UsersDirectory currentUserId={session.user.user_id} onManageIntermediates={onManageIntermediates} />;
};
-const UsersDirectory = ({ currentUserId }: { currentUserId: string }) => {
+const UsersDirectory = ({
+ currentUserId,
+ onManageIntermediates,
+}: {
+ currentUserId: string;
+ onManageIntermediates?: (userId: string) => void;
+}) => {
const { t } = useTranslation();
const notify = useIdentityNotify();
const [users, setUsers] = useState<UserDTO[] | null>(null);
@@ -155,6 +166,7 @@ const UsersDirectory = ({ currentUserId }: { currentUserId: string }) => {
<Table.Body>
{users.map((user) => (
<UserRow
+ onManageIntermediates={onManageIntermediates}
key={user.user_id}
isSelf={user.user_id === currentUserId}
setDeleteTarget={setDeleteTarget}
@@ -196,12 +208,14 @@ const formatLastSignIn = (lastLoginAt: string | null, neverLabel: string): strin
const UserRow = ({
isSelf,
+ onManageIntermediates,
setDeleteTarget,
setFormTarget,
setUserActive,
user,
}: {
isSelf: boolean;
+ onManageIntermediates?: (userId: string) => void;
setDeleteTarget: (user: UserDTO) => void;
setFormTarget: (target: UserFormTarget) => void;
setUserActive: (user: UserDTO, isActive: boolean) => void;
@@ -210,6 +224,10 @@ const UserRow = ({
const { t } = useTranslation();
const handleDelete = useCallback(() => setDeleteTarget(user), [setDeleteTarget, user]);
const handleEdit = useCallback(() => setFormTarget({ mode: 'edit', user }), [setFormTarget, user]);
+ const handleIntermediates = useCallback(
+ () => onManageIntermediates?.(user.user_id),
+ [onManageIntermediates, user.user_id]
+ );
const handleSetActive = useCallback(
(event: { checked: boolean }) => void setUserActive(user, event.checked),
[setUserActive, user]
@@ -267,6 +285,19 @@ const UserRow = ({
</Table.Cell>
<Table.Cell borderColor="border.subtle" pe="4" textAlign="end">
<HStack gap="0.5" justify="flex-end">
+ {onManageIntermediates ? (
+ <Tooltip content={t('users.manageIntermediatesNamed', { name: getUserLabel(user) })} showArrow>
+ <IconButton
+ aria-label={t('users.manageIntermediatesNamed', { name: getUserLabel(user) })}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={handleIntermediates}
+ >
+ <BrushCleaningIcon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
<IconButton
aria-label={t('users.editUserNamed', { name: getUserLabel(user) })}
color="fg.muted"
diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx
index f179c586dc..a567a644d4 100644
--- a/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx
+++ b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.tsx
@@ -3,12 +3,12 @@ import { useTranslation } from 'react-i18next';
import { UsersManagementPanel } from './UserManagement';
-export const UsersPage = () => {
+export const UsersPage = ({ onManageIntermediates }: { onManageIntermediates?: (userId: string) => void }) => {
const { t } = useTranslation();
return (
<PageShell description={t('users.description')} regionLabel={t('users.management')} title={t('users.title')}>
- <UsersManagementPanel />
+ <UsersManagementPanel onManageIntermediates={onManageIntermediates} />
</PageShell>
);
};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts b/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
new file mode 100644
index 0000000000..3a6439564b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it } from 'vitest';
+
+import type { IntermediatesRow } from './types';
+
+import {
+ EMPTY_SELECTION,
+ getPageSelectionState,
+ isRowSelected,
+ resolveScope,
+ selectAllMatching,
+ summarizeSelection,
+ toggleRowSelection,
+ withRowSelected,
+} from './selection';
+
+const row = (projectId: string | null, overrides: Partial<IntermediatesRow> = {}): IntermediatesRow => ({
+ coverImageName: null,
+ images: { active: 0, recent: 0, referenced: 1, safe: 3 },
+ projectId,
+ projectName: projectId,
+ reclaimableBytes: 100,
+ referencedBytes: 10,
+ unknownSizeCount: 0,
+ userDisplayName: 'Alice',
+ userEmail: '[email protected]',
+ userId: 'alice',
+ videos: { active: 0, recent: 0, referenced: 0, safe: 2 },
+ ...overrides,
+});
+
+const page = [row('a'), row('b'), row(null)];
+const totals = { reclaimableBytes: 5_000, rows: 12, safeImages: 40, safeVideos: 4, unknownSizeCount: 2 };
+
+describe('row selection', () => {
+ it('toggles rows and reports the page state', () => {
+ let selection = toggleRowSelection(EMPTY_SELECTION, page[0]!, page);
+ expect(isRowSelected(selection, page[0]!)).toBe(true);
+ expect(getPageSelectionState(selection, page)).toBe('some');
+
+ for (const candidate of page.slice(1)) {
+ selection = toggleRowSelection(selection, candidate, page);
+ }
+ expect(page.every((candidate) => isRowSelected(selection, candidate))).toBe(true);
+ expect(getPageSelectionState(selection, page)).toBe('all');
+ expect(getPageSelectionState(selectAllMatching(), page)).toBe('all');
+ expect(getPageSelectionState(EMPTY_SELECTION, page)).toBe('none');
+ });
+
+ it('keeps the unassigned row distinct from a project row of the same owner', () => {
+ const selection = toggleRowSelection(EMPTY_SELECTION, page[2]!, page);
+
+ expect(isRowSelected(selection, page[2]!)).toBe(true);
+ expect(isRowSelected(selection, page[0]!)).toBe(false);
+ });
+
+ it('keeps picks from an earlier page when the page changes', () => {
+ const firstPage = [row('a'), row('b')];
+ const secondPage = [row('c'), row('d')];
+ let selection = toggleRowSelection(EMPTY_SELECTION, firstPage[0]!, firstPage);
+ selection = toggleRowSelection(selection, secondPage[1]!, secondPage);
+
+ expect(summarizeSelection(selection, totals).rows).toBe(2);
+ expect(resolveScope({ hasSearch: false, loadedRows: secondPage, ownerId: 'alice', selection })).toEqual({
+ kind: 'selection',
+ targets: [
+ { projectId: 'a', userId: 'alice' },
+ { projectId: 'd', userId: 'alice' },
+ ],
+ });
+ expect(getPageSelectionState(selection, firstPage)).toBe('some');
+ });
+
+ it('adds a row without disturbing an existing pick or an all-matching selection', () => {
+ const picked = withRowSelected(withRowSelected(EMPTY_SELECTION, page[0]!), page[0]!);
+ expect(summarizeSelection(picked, totals).rows).toBe(1);
+ expect(withRowSelected(selectAllMatching(), page[1]!)).toEqual(selectAllMatching());
+ });
+
+ it('leaving all-matching by toggling a row keeps the rest of the visible page', () => {
+ const selection = toggleRowSelection(selectAllMatching(), page[1]!, page);
+
+ expect(selection.mode).toBe('rows');
+ expect(isRowSelected(selection, page[0]!)).toBe(true);
+ expect(isRowSelected(selection, page[1]!)).toBe(false);
+ expect(isRowSelected(selection, page[2]!)).toBe(true);
+ });
+});
+
+describe('selection summary', () => {
+ it('sums explicit picks from their snapshots', () => {
+ const selection = toggleRowSelection(toggleRowSelection(EMPTY_SELECTION, page[0]!, page), page[2]!, page);
+
+ expect(summarizeSelection(selection, totals)).toEqual({
+ referencedBytes: 20,
+ referencedImages: 2,
+ referencedVideos: 0,
+ reclaimableBytes: 200,
+ rows: 2,
+ safeImages: 6,
+ safeVideos: 4,
+ unknownSizeCount: 0,
+ });
+ });
+
+ it('uses the server totals for all matching rows, which may exceed the loaded page', () => {
+ expect(summarizeSelection(selectAllMatching(), totals)).toMatchObject({
+ reclaimableBytes: 5_000,
+ rows: 12,
+ safeImages: 40,
+ safeVideos: 4,
+ unknownSizeCount: 2,
+ });
+ });
+});
+
+describe('scope resolution', () => {
+ it('turns all-matching without a search into the owner or everyone scope', () => {
+ expect(
+ resolveScope({ hasSearch: false, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
+ ).toEqual({ kind: 'owner', userId: 'alice' });
+ expect(resolveScope({ hasSearch: false, loadedRows: page, ownerId: null, selection: selectAllMatching() })).toEqual(
+ {
+ kind: 'everyone',
+ }
+ );
+ });
+
+ it('turns picks, and all-matching under a search, into explicit targets', () => {
+ const picks = toggleRowSelection(EMPTY_SELECTION, page[2]!, page);
+
+ expect(resolveScope({ hasSearch: false, loadedRows: page, ownerId: 'alice', selection: picks })).toEqual({
+ kind: 'selection',
+ targets: [{ projectId: null, userId: 'alice' }],
+ });
+ expect(
+ resolveScope({ hasSearch: true, loadedRows: page, ownerId: 'alice', selection: selectAllMatching() })
+ ).toEqual({
+ kind: 'selection',
+ targets: page.map(({ projectId, userId }) => ({ projectId, userId })),
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
new file mode 100644
index 0000000000..142f4d4b01
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/selection.ts
@@ -0,0 +1,164 @@
+import type { IntermediatesRow, IntermediatesScope, IntermediatesScopeTarget } from './types';
+
+import { getIntermediatesRowKey } from './types';
+
+/**
+ * Row selection for the manager. `rows` keeps a snapshot of every picked row, so picks survive paging and can be
+ * summarized and targeted without the page that showed them; `all-matching` stands for every row the current
+ * filters match, including rows never loaded, and resolves against the server when a preview is requested.
+ */
+export type IntermediatesSelection =
+ | { mode: 'rows'; rows: ReadonlyMap<string, IntermediatesRow> }
+ | { mode: 'all-matching' };
+
+export const EMPTY_SELECTION: IntermediatesSelection = { mode: 'rows', rows: new Map() };
+
+export const isRowSelected = (selection: IntermediatesSelection, row: IntermediatesRow): boolean =>
+ selection.mode === 'all-matching' || selection.rows.has(getIntermediatesRowKey(row));
+
+export const isSelectionEmpty = (selection: IntermediatesSelection): boolean =>
+ selection.mode === 'rows' && selection.rows.size === 0;
+
+const materialize = (
+ selection: IntermediatesSelection,
+ visibleRows: readonly IntermediatesRow[]
+): Map<string, IntermediatesRow> =>
+ new Map(
+ selection.mode === 'all-matching'
+ ? visibleRows.map((row) => [getIntermediatesRowKey(row), row] as const)
+ : selection.rows
+ );
+
+export const withRowSelected = (selection: IntermediatesSelection, row: IntermediatesRow): IntermediatesSelection => {
+ if (selection.mode === 'all-matching' || selection.rows.has(getIntermediatesRowKey(row))) {
+ return selection;
+ }
+ const rows = new Map(selection.rows);
+
+ rows.set(getIntermediatesRowKey(row), row);
+
+ return { mode: 'rows', rows };
+};
+
+export const toggleRowSelection = (
+ selection: IntermediatesSelection,
+ row: IntermediatesRow,
+ visibleRows: readonly IntermediatesRow[]
+): IntermediatesSelection => {
+ const key = getIntermediatesRowKey(row);
+ // Leaving "all matching" materializes the visible page minus the toggled row; rows beyond the page cannot be kept.
+ const rows = materialize(selection, visibleRows);
+
+ if (rows.has(key)) {
+ rows.delete(key);
+ } else {
+ rows.set(key, row);
+ }
+
+ return { mode: 'rows', rows };
+};
+
+export const selectAllMatching = (): IntermediatesSelection => ({ mode: 'all-matching' });
+
+export type PageSelectionState = 'none' | 'some' | 'all';
+
+export const getPageSelectionState = (
+ selection: IntermediatesSelection,
+ visibleRows: readonly IntermediatesRow[]
+): PageSelectionState => {
+ if (visibleRows.length === 0) {
+ return 'none';
+ }
+ if (selection.mode === 'all-matching') {
+ return 'all';
+ }
+
+ const selected = visibleRows.filter((row) => selection.rows.has(getIntermediatesRowKey(row))).length;
+
+ return selected === 0 ? 'none' : selected === visibleRows.length ? 'all' : 'some';
+};
+
+export interface SelectionSummary {
+ rows: number;
+ safeImages: number;
+ safeVideos: number;
+ referencedImages: number;
+ referencedVideos: number;
+ reclaimableBytes: number;
+ referencedBytes: number;
+ unknownSizeCount: number;
+}
+
+/**
+ * Sums the selection. Explicit picks are summed from their snapshots, whichever page showed them; "all matching"
+ * uses the server's totals, which cover every matching row.
+ */
+export const summarizeSelection = (
+ selection: IntermediatesSelection,
+ totals: { rows: number; safeImages: number; safeVideos: number; reclaimableBytes: number; unknownSizeCount: number }
+): SelectionSummary => {
+ if (selection.mode === 'all-matching') {
+ return {
+ referencedBytes: 0,
+ referencedImages: 0,
+ referencedVideos: 0,
+ reclaimableBytes: totals.reclaimableBytes,
+ rows: totals.rows,
+ safeImages: totals.safeImages,
+ safeVideos: totals.safeVideos,
+ unknownSizeCount: totals.unknownSizeCount,
+ };
+ }
+
+ const summary: SelectionSummary = {
+ referencedBytes: 0,
+ referencedImages: 0,
+ referencedVideos: 0,
+ reclaimableBytes: 0,
+ rows: 0,
+ safeImages: 0,
+ safeVideos: 0,
+ unknownSizeCount: 0,
+ };
+
+ for (const row of selection.rows.values()) {
+ summary.rows += 1;
+ summary.safeImages += row.images.safe;
+ summary.safeVideos += row.videos.safe;
+ summary.referencedImages += row.images.referenced;
+ summary.referencedVideos += row.videos.referenced;
+ summary.reclaimableBytes += row.reclaimableBytes;
+ summary.referencedBytes += row.referencedBytes;
+ summary.unknownSizeCount += row.unknownSizeCount;
+ }
+
+ return summary;
+};
+
+export const selectionToTargets = (
+ selection: IntermediatesSelection,
+ loadedRows: readonly IntermediatesRow[]
+): IntermediatesScopeTarget[] =>
+ [...(selection.mode === 'all-matching' ? loadedRows : selection.rows.values())].map(({ projectId, userId }) => ({
+ projectId,
+ userId,
+ }));
+
+/**
+ * The scope a confirmation acts on. With no search, "all matching" is exactly the owner filter (or everyone), which
+ * the server can freeze without the client enumerating rows.
+ */
+export const resolveScope = (options: {
+ selection: IntermediatesSelection;
+ loadedRows: readonly IntermediatesRow[];
+ hasSearch: boolean;
+ ownerId: string | null;
+}): IntermediatesScope => {
+ const { hasSearch, loadedRows, ownerId, selection } = options;
+
+ if (selection.mode === 'all-matching' && !hasSearch) {
+ return ownerId === null ? { kind: 'everyone' } : { kind: 'owner', userId: ownerId };
+ }
+
+ return { kind: 'selection', targets: selectionToTargets(selection, loadedRows) };
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/core/types.ts b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
new file mode 100644
index 0000000000..e3e9965dd9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/core/types.ts
@@ -0,0 +1,162 @@
+/**
+ * Read models of the intermediates manager. Pure: no transport, React or UI imports.
+ *
+ * An intermediate is classified once by the server under the cleanup policy: `safe` (deleted by either mode),
+ * `referenced` (named by a saved project or workflow; deleted only by a force clear), `active` (produced or
+ * consumed by queued or running work) and `recent` (inside the grace window). The last two are never deleted.
+ */
+
+export type IntermediatesCleanupMode = 'safe' | 'force';
+
+export type IntermediatesSummarySort = 'reclaimable_bytes' | 'project_name';
+
+export type IntermediatesOperationStatus = 'pending' | 'running' | 'completed' | 'failed';
+
+export interface IntermediatesKindCounts {
+ safe: number;
+ referenced: number;
+ active: number;
+ recent: number;
+}
+
+export interface IntermediatesScopeTarget {
+ userId: string;
+ /** `null` is the owner's unassigned intermediates: no project, or a project that no longer exists. */
+ projectId: string | null;
+}
+
+export interface IntermediatesRow extends IntermediatesScopeTarget {
+ userDisplayName: string | null;
+ userEmail: string | null;
+ projectName: string | null;
+ /** The newest durable image on the project's board, for a thumbnail; null for unassigned rows. */
+ coverImageName: string | null;
+ images: IntermediatesKindCounts;
+ videos: IntermediatesKindCounts;
+ /** Measured bytes of the safe items. */
+ reclaimableBytes: number;
+ /** Measured bytes a force clear adds. */
+ referencedBytes: number;
+ /** Safe or referenced items not yet measured. */
+ unknownSizeCount: number;
+}
+
+export interface IntermediatesSummaryTotals {
+ rows: number;
+ safeImages: number;
+ safeVideos: number;
+ inUseImages: number;
+ inUseVideos: number;
+ reclaimableBytes: number;
+ unknownSizeCount: number;
+}
+
+export interface IntermediatesSummary {
+ items: IntermediatesRow[];
+ /** Rows matching the request across every page. */
+ total: number;
+ offset: number;
+ limit: number;
+ /** Over every matching row, not only the returned page. */
+ totals: IntermediatesSummaryTotals;
+ recentGraceSeconds: number;
+ /** Sizes are still being measured in the background. */
+ measuring: boolean;
+ canManageEveryone: boolean;
+}
+
+export type IntermediatesScope =
+ | { kind: 'selection'; targets: IntermediatesScopeTarget[] }
+ | { kind: 'owner'; userId: string }
+ | { kind: 'everyone' };
+
+export interface IntermediatesImpact {
+ deleteImages: number;
+ deleteVideos: number;
+ keepReferencedImages: number;
+ keepReferencedVideos: number;
+ keepActiveImages: number;
+ keepActiveVideos: number;
+ keepRecentImages: number;
+ keepRecentVideos: number;
+ reclaimableBytes: number;
+ unknownSizeCount: number;
+}
+
+export interface IntermediatesAffectedDocument {
+ kind: 'project' | 'workflow';
+ userId: string;
+ ownerId: string;
+ name: string | null;
+ references: number;
+}
+
+export interface IntermediatesPreview {
+ previewId: string;
+ mode: IntermediatesCleanupMode;
+ scope: IntermediatesScope;
+ createdAt: string;
+ expiresAt: string;
+ targetRows: number;
+ impact: IntermediatesImpact;
+ affectedDocuments: IntermediatesAffectedDocument[];
+ affectedDocumentsHidden: number;
+}
+
+export interface IntermediatesOperationProgress {
+ processedImages: number;
+ processedVideos: number;
+ deletedImages: number;
+ deletedVideos: number;
+ retainedImages: number;
+ retainedVideos: number;
+ failedImages: number;
+ failedVideos: number;
+ reclaimedBytes: number;
+ /** Deleted items whose size was never measured; their bytes are not in `reclaimedBytes`. */
+ unknownSizeCount: number;
+ pendingDiskCleanup: number;
+ unresolvedImages: number;
+ unresolvedVideos: number;
+}
+
+export interface IntermediatesOperation {
+ operationId: string;
+ userId: string;
+ mode: IntermediatesCleanupMode;
+ scope: IntermediatesScope;
+ status: IntermediatesOperationStatus;
+ createdAt: string;
+ startedAt: string | null;
+ completedAt: string | null;
+ error: string | null;
+ targetImages: number;
+ targetVideos: number;
+ progress: IntermediatesOperationProgress;
+ retriedFromOperationId: string | null;
+ retriedByOperationId: string | null;
+}
+
+export const getIntermediatesRowKey = (target: IntermediatesScopeTarget): string =>
+ `${target.userId}\u0000${target.projectId ?? ''}`;
+
+export const getKindTotal = (counts: IntermediatesKindCounts): number =>
+ counts.safe + counts.referenced + counts.active + counts.recent;
+
+export const getKindInUse = (counts: IntermediatesKindCounts): number =>
+ counts.referenced + counts.active + counts.recent;
+
+export const getOperationTotalTargets = (operation: IntermediatesOperation): number =>
+ operation.targetImages + operation.targetVideos;
+
+export const getOperationProcessed = (operation: IntermediatesOperation): number =>
+ operation.progress.processedImages + operation.progress.processedVideos;
+
+export const isOperationSettled = (operation: IntermediatesOperation): boolean =>
+ operation.status === 'completed' || operation.status === 'failed';
+
+/** Only unresolved targets can be retried, once the operation has stopped and no retry has taken them over. */
+export const isOperationRetryable = (operation: IntermediatesOperation): boolean =>
+ isOperationSettled(operation) &&
+ operation.retriedByOperationId === null &&
+ operation.progress.unresolvedImages + operation.progress.unresolvedVideos > 0;
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
new file mode 100644
index 0000000000..5b87560f3c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.test.ts
@@ -0,0 +1,156 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createIntermediatesPreview, getIntermediatesSummary, mapIntermediatesOperation } from './api';
+
+const summaryDto = {
+ can_manage_everyone: false,
+ items: [
+ {
+ cover_image_name: null,
+ images: { active: 1, recent: 2, referenced: 3, safe: 4 },
+ project_id: null,
+ project_name: null,
+ reclaimable_bytes: 42,
+ referenced_bytes: 7,
+ unknown_size_count: 1,
+ user_display_name: null,
+ user_email: '[email protected]',
+ user_id: 'a',
+ videos: { active: 0, recent: 0, referenced: 0, safe: 1 },
+ },
+ ],
+ limit: 50,
+ measuring: true,
+ offset: 0,
+ recent_grace_seconds: 1800,
+ total: 1,
+ totals: {
+ in_use_images: 6,
+ in_use_videos: 0,
+ reclaimable_bytes: 42,
+ rows: 1,
+ safe_images: 4,
+ safe_videos: 1,
+ unknown_size_count: 1,
+ },
+};
+
+const fetchJson = (body: unknown, status = 200) =>
+ vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
+ Promise.resolve(new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }))
+ );
+
+describe('intermediates transport', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('maps the summary to camelCase read models and only sends set filters', async () => {
+ const fetchMock = fetchJson(summaryDto);
+ vi.stubGlobal('fetch', fetchMock);
+
+ const summary = await getIntermediatesSummary({ limit: 50, ownerId: null, search: ' ', sort: 'project_name' });
+
+ expect(String(fetchMock.mock.calls[0]?.[0])).toMatch(
+ /\/api\/v1\/intermediates\/summary\?sort=project_name&limit=50$/
+ );
+ expect(summary.items[0]).toMatchObject({
+ images: { active: 1, recent: 2, referenced: 3, safe: 4 },
+ projectId: null,
+ reclaimableBytes: 42,
+ referencedBytes: 7,
+ unknownSizeCount: 1,
+ userId: 'a',
+ });
+ expect(summary.totals).toEqual({
+ inUseImages: 6,
+ inUseVideos: 0,
+ reclaimableBytes: 42,
+ rows: 1,
+ safeImages: 4,
+ safeVideos: 1,
+ unknownSizeCount: 1,
+ });
+ expect(summary.measuring).toBe(true);
+ expect(summary.recentGraceSeconds).toBe(1800);
+ });
+
+ it('serializes a selection scope with snake_case targets', async () => {
+ const fetchMock = fetchJson(
+ {
+ affected_documents: [],
+ affected_documents_hidden: 0,
+ created_at: 'now',
+ expires_at: 'later',
+ impact: {
+ delete_images: 1,
+ delete_videos: 0,
+ keep_active_images: 0,
+ keep_active_videos: 0,
+ keep_recent_images: 0,
+ keep_recent_videos: 0,
+ keep_referenced_images: 0,
+ keep_referenced_videos: 0,
+ reclaimable_bytes: 5,
+ unknown_size_count: 0,
+ },
+ mode: 'safe',
+ preview_id: 'p1',
+ scope: { kind: 'selection', targets: [{ project_id: null, user_id: 'a' }], user_id: null },
+ target_rows: 1,
+ },
+ 201
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ const preview = await createIntermediatesPreview({
+ mode: 'safe',
+ scope: { kind: 'selection', targets: [{ projectId: null, userId: 'a' }] },
+ });
+
+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;
+ expect(JSON.parse(String(init.body))).toEqual({
+ mode: 'safe',
+ scope: { kind: 'selection', targets: [{ project_id: null, user_id: 'a' }], user_id: null },
+ });
+ expect(preview.scope).toEqual({ kind: 'selection', targets: [{ projectId: null, userId: 'a' }] });
+ expect(preview.impact.deleteImages).toBe(1);
+ });
+
+ it('maps operation progress including the unresolved counts a retry depends on', () => {
+ const operation = mapIntermediatesOperation({
+ completed_at: null,
+ created_at: 'now',
+ error: null,
+ mode: 'force',
+ operation_id: 'op',
+ progress: {
+ deleted_images: 1,
+ deleted_videos: 0,
+ failed_images: 2,
+ failed_videos: 0,
+ pending_disk_cleanup: 1,
+ processed_images: 3,
+ processed_videos: 0,
+ reclaimed_bytes: 10,
+ retained_images: 0,
+ retained_videos: 0,
+ unknown_size_count: 1,
+ unresolved_images: 2,
+ unresolved_videos: 0,
+ },
+ retried_by_operation_id: null,
+ retried_from_operation_id: 'previous',
+ scope: { kind: 'everyone', targets: [], user_id: null },
+ started_at: 'now',
+ status: 'running',
+ target_images: 3,
+ target_videos: 0,
+ user_id: 'admin',
+ });
+
+ expect(operation.progress).toMatchObject({ pendingDiskCleanup: 1, unknownSizeCount: 1, unresolvedImages: 2 });
+ expect(operation.scope).toEqual({ kind: 'everyone' });
+ expect(operation.retriedFromOperationId).toBe('previous');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/api.ts b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
new file mode 100644
index 0000000000..e4a216605b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/api.ts
@@ -0,0 +1,353 @@
+import type {
+ IntermediatesAffectedDocument,
+ IntermediatesCleanupMode,
+ IntermediatesImpact,
+ IntermediatesKindCounts,
+ IntermediatesOperation,
+ IntermediatesOperationProgress,
+ IntermediatesPreview,
+ IntermediatesRow,
+ IntermediatesScope,
+ IntermediatesScopeTarget,
+ IntermediatesSummary,
+} from '@features/intermediates/core/types';
+
+import { apiFetchJson } from '@platform/transport/http';
+
+import type { IntermediatesSummaryParams } from './keys';
+
+const BASE = '/api/v1/intermediates';
+
+// Wire DTOs are private; every consumer reads the camelCase read models.
+
+interface KindCountsDTO {
+ safe: number;
+ referenced: number;
+ active: number;
+ recent: number;
+}
+
+interface ScopeTargetDTO {
+ user_id: string;
+ project_id: string | null;
+}
+
+interface ScopeDTO {
+ kind: 'selection' | 'owner' | 'everyone';
+ targets: ScopeTargetDTO[];
+ user_id: string | null;
+}
+
+interface RowDTO extends ScopeTargetDTO {
+ user_display_name: string | null;
+ user_email: string | null;
+ project_name: string | null;
+ cover_image_name: string | null;
+ images: KindCountsDTO;
+ videos: KindCountsDTO;
+ reclaimable_bytes: number;
+ referenced_bytes: number;
+ unknown_size_count: number;
+}
+
+interface SummaryDTO {
+ items: RowDTO[];
+ total: number;
+ offset: number;
+ limit: number;
+ totals: {
+ rows: number;
+ safe_images: number;
+ safe_videos: number;
+ in_use_images: number;
+ in_use_videos: number;
+ reclaimable_bytes: number;
+ unknown_size_count: number;
+ };
+ recent_grace_seconds: number;
+ measuring: boolean;
+ can_manage_everyone: boolean;
+}
+
+interface ImpactDTO {
+ delete_images: number;
+ delete_videos: number;
+ keep_referenced_images: number;
+ keep_referenced_videos: number;
+ keep_active_images: number;
+ keep_active_videos: number;
+ keep_recent_images: number;
+ keep_recent_videos: number;
+ reclaimable_bytes: number;
+ unknown_size_count: number;
+}
+
+interface AffectedDocumentDTO {
+ kind: 'project' | 'workflow';
+ user_id: string;
+ owner_id: string;
+ name: string | null;
+ references: number;
+}
+
+interface PreviewDTO {
+ preview_id: string;
+ mode: IntermediatesCleanupMode;
+ scope: ScopeDTO;
+ created_at: string;
+ expires_at: string;
+ target_rows: number;
+ impact: ImpactDTO;
+ affected_documents: AffectedDocumentDTO[];
+ affected_documents_hidden: number;
+}
+
+interface ProgressDTO {
+ processed_images: number;
+ processed_videos: number;
+ deleted_images: number;
+ deleted_videos: number;
+ retained_images: number;
+ retained_videos: number;
+ failed_images: number;
+ failed_videos: number;
+ reclaimed_bytes: number;
+ unknown_size_count: number;
+ pending_disk_cleanup: number;
+ unresolved_images: number;
+ unresolved_videos: number;
+}
+
+export interface IntermediatesOperationDTO {
+ operation_id: string;
+ user_id: string;
+ mode: IntermediatesCleanupMode;
+ scope: ScopeDTO;
+ status: 'pending' | 'running' | 'completed' | 'failed';
+ created_at: string;
+ started_at: string | null;
+ completed_at: string | null;
+ error: string | null;
+ target_images: number;
+ target_videos: number;
+ progress: ProgressDTO;
+ retried_from_operation_id: string | null;
+ retried_by_operation_id: string | null;
+}
+
+const mapCounts = (dto: KindCountsDTO): IntermediatesKindCounts => ({
+ active: dto.active,
+ recent: dto.recent,
+ referenced: dto.referenced,
+ safe: dto.safe,
+});
+
+const mapTarget = (dto: ScopeTargetDTO): IntermediatesScopeTarget => ({
+ projectId: dto.project_id,
+ userId: dto.user_id,
+});
+
+const mapRow = (dto: RowDTO): IntermediatesRow => ({
+ coverImageName: dto.cover_image_name,
+ images: mapCounts(dto.images),
+ projectId: dto.project_id,
+ projectName: dto.project_name,
+ reclaimableBytes: dto.reclaimable_bytes,
+ referencedBytes: dto.referenced_bytes,
+ unknownSizeCount: dto.unknown_size_count,
+ userDisplayName: dto.user_display_name,
+ userEmail: dto.user_email,
+ userId: dto.user_id,
+ videos: mapCounts(dto.videos),
+});
+
+const mapScope = (dto: ScopeDTO): IntermediatesScope => {
+ if (dto.kind === 'everyone') {
+ return { kind: 'everyone' };
+ }
+ if (dto.kind === 'owner') {
+ return { kind: 'owner', userId: dto.user_id ?? '' };
+ }
+
+ return { kind: 'selection', targets: dto.targets.map(mapTarget) };
+};
+
+const toScopeDTO = (scope: IntermediatesScope): ScopeDTO => {
+ if (scope.kind === 'everyone') {
+ return { kind: 'everyone', targets: [], user_id: null };
+ }
+ if (scope.kind === 'owner') {
+ return { kind: 'owner', targets: [], user_id: scope.userId };
+ }
+
+ return {
+ kind: 'selection',
+ targets: scope.targets.map((target) => ({ project_id: target.projectId, user_id: target.userId })),
+ user_id: null,
+ };
+};
+
+const mapImpact = (dto: ImpactDTO): IntermediatesImpact => ({
+ deleteImages: dto.delete_images,
+ deleteVideos: dto.delete_videos,
+ keepActiveImages: dto.keep_active_images,
+ keepActiveVideos: dto.keep_active_videos,
+ keepRecentImages: dto.keep_recent_images,
+ keepRecentVideos: dto.keep_recent_videos,
+ keepReferencedImages: dto.keep_referenced_images,
+ keepReferencedVideos: dto.keep_referenced_videos,
+ reclaimableBytes: dto.reclaimable_bytes,
+ unknownSizeCount: dto.unknown_size_count,
+});
+
+const mapAffectedDocument = (dto: AffectedDocumentDTO): IntermediatesAffectedDocument => ({
+ kind: dto.kind,
+ name: dto.name,
+ ownerId: dto.owner_id,
+ references: dto.references,
+ userId: dto.user_id,
+});
+
+const mapProgress = (dto: ProgressDTO): IntermediatesOperationProgress => ({
+ deletedImages: dto.deleted_images,
+ deletedVideos: dto.deleted_videos,
+ failedImages: dto.failed_images,
+ failedVideos: dto.failed_videos,
+ pendingDiskCleanup: dto.pending_disk_cleanup,
+ processedImages: dto.processed_images,
+ processedVideos: dto.processed_videos,
+ reclaimedBytes: dto.reclaimed_bytes,
+ retainedImages: dto.retained_images,
+ retainedVideos: dto.retained_videos,
+ unknownSizeCount: dto.unknown_size_count,
+ unresolvedImages: dto.unresolved_images,
+ unresolvedVideos: dto.unresolved_videos,
+});
+
+export const mapIntermediatesOperation = (dto: IntermediatesOperationDTO): IntermediatesOperation => ({
+ completedAt: dto.completed_at,
+ createdAt: dto.created_at,
+ error: dto.error,
+ mode: dto.mode,
+ operationId: dto.operation_id,
+ progress: mapProgress(dto.progress),
+ retriedByOperationId: dto.retried_by_operation_id,
+ retriedFromOperationId: dto.retried_from_operation_id,
+ scope: mapScope(dto.scope),
+ startedAt: dto.started_at,
+ status: dto.status,
+ targetImages: dto.target_images,
+ targetVideos: dto.target_videos,
+ userId: dto.user_id,
+});
+
+const buildSummaryUrl = (params: IntermediatesSummaryParams): string => {
+ const query = new URLSearchParams();
+
+ if (params.ownerId) {
+ query.set('owner_id', params.ownerId);
+ }
+ if (params.search?.trim()) {
+ query.set('search', params.search.trim());
+ }
+ if (params.sort) {
+ query.set('sort', params.sort);
+ }
+ if (params.order) {
+ query.set('order', params.order);
+ }
+ if (params.offset !== undefined && params.offset > 0) {
+ query.set('offset', String(params.offset));
+ }
+ if (params.limit !== undefined) {
+ query.set('limit', String(params.limit));
+ }
+
+ const encoded = query.toString();
+
+ return encoded ? `${BASE}/summary?${encoded}` : `${BASE}/summary`;
+};
+
+export const getIntermediatesSummary = async (
+ params: IntermediatesSummaryParams,
+ signal?: AbortSignal
+): Promise<IntermediatesSummary> => {
+ const dto = await apiFetchJson<SummaryDTO>(buildSummaryUrl(params), { signal });
+
+ return {
+ canManageEveryone: dto.can_manage_everyone,
+ items: dto.items.map(mapRow),
+ limit: dto.limit,
+ measuring: dto.measuring,
+ offset: dto.offset,
+ recentGraceSeconds: dto.recent_grace_seconds,
+ total: dto.total,
+ totals: {
+ inUseImages: dto.totals.in_use_images,
+ inUseVideos: dto.totals.in_use_videos,
+ reclaimableBytes: dto.totals.reclaimable_bytes,
+ rows: dto.totals.rows,
+ safeImages: dto.totals.safe_images,
+ safeVideos: dto.totals.safe_videos,
+ unknownSizeCount: dto.totals.unknown_size_count,
+ },
+ };
+};
+
+export const createIntermediatesPreview = async (
+ request: { mode: IntermediatesCleanupMode; scope: IntermediatesScope },
+ signal?: AbortSignal
+): Promise<IntermediatesPreview> => {
+ const dto = await apiFetchJson<PreviewDTO>(`${BASE}/previews`, {
+ body: JSON.stringify({ mode: request.mode, scope: toScopeDTO(request.scope) }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal,
+ });
+
+ return {
+ affectedDocuments: dto.affected_documents.map(mapAffectedDocument),
+ affectedDocumentsHidden: dto.affected_documents_hidden,
+ createdAt: dto.created_at,
+ expiresAt: dto.expires_at,
+ impact: mapImpact(dto.impact),
+ mode: dto.mode,
+ previewId: dto.preview_id,
+ scope: mapScope(dto.scope),
+ targetRows: dto.target_rows,
+ };
+};
+
+export const startIntermediatesOperation = async (
+ request: { previewId: string; idempotencyKey: string },
+ signal?: AbortSignal
+): Promise<IntermediatesOperation> =>
+ mapIntermediatesOperation(
+ await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations`, {
+ body: JSON.stringify({ idempotency_key: request.idempotencyKey, preview_id: request.previewId }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal,
+ })
+ );
+
+export const getIntermediatesOperation = async (
+ operationId: string,
+ signal?: AbortSignal
+): Promise<IntermediatesOperation> =>
+ mapIntermediatesOperation(
+ await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations/${encodeURIComponent(operationId)}`, {
+ signal,
+ })
+ );
+
+export const retryIntermediatesOperation = async (
+ operationId: string,
+ signal?: AbortSignal
+): Promise<IntermediatesOperation> =>
+ mapIntermediatesOperation(
+ await apiFetchJson<IntermediatesOperationDTO>(`${BASE}/operations/${encodeURIComponent(operationId)}/retry`, {
+ method: 'POST',
+ signal,
+ })
+ );
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts b/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts
new file mode 100644
index 0000000000..8d6fc0af15
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/focus.ts
@@ -0,0 +1,30 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+
+/**
+ * What an entry point wants the manager to start on: a project to preselect, or an account to filter by. Consumed
+ * once by the manager when it mounts, so a stale intent never resurfaces on a later visit.
+ */
+export interface IntermediatesFocus {
+ projectId?: string;
+ ownerId?: string;
+}
+
+const focusStore = createExternalStore<{ focus: IntermediatesFocus | null }>({ focus: null });
+
+registerAccountOwnedResource({
+ clear: () => focusStore.setSnapshot({ focus: null }),
+ name: 'intermediates-focus',
+});
+
+export const requestIntermediatesFocus = (focus: IntermediatesFocus): void => {
+ focusStore.setSnapshot({ focus });
+};
+
+export const takeIntermediatesFocus = (): IntermediatesFocus | null => {
+ const { focus } = focusStore.getSnapshot();
+
+ focusStore.setSnapshot({ focus: null });
+
+ return focus;
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/keys.ts b/invokeai/frontend/webv2/src/features/intermediates/data/keys.ts
new file mode 100644
index 0000000000..dbd2d08f94
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/keys.ts
@@ -0,0 +1,24 @@
+import type { IntermediatesSummarySort } from '@features/intermediates/core/types';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+export interface IntermediatesSummaryParams {
+ ownerId?: string | null;
+ search?: string;
+ sort?: IntermediatesSummarySort;
+ order?: 'asc' | 'desc';
+ offset?: number;
+ limit?: number;
+}
+
+const getAccountKey = (owner: AccountScope) => ({ accountId: owner.accountId, epoch: owner.epoch });
+
+/** Keys carry the account so a sign-out never serves one account's counts to the next. */
+export const intermediatesKeys = {
+ all: ['intermediates'] as const,
+ forAccount: (owner: AccountScope) => [...intermediatesKeys.all, getAccountKey(owner)] as const,
+ summary: (owner: AccountScope, params: IntermediatesSummaryParams) =>
+ [...intermediatesKeys.forAccount(owner), 'summary', params] as const,
+ summaries: (owner: AccountScope) => [...intermediatesKeys.forAccount(owner), 'summary'] as const,
+ operation: (owner: AccountScope, operationId: string) =>
+ [...intermediatesKeys.forAccount(owner), 'operation', operationId] as const,
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
new file mode 100644
index 0000000000..f91fd2197c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/operationStore.ts
@@ -0,0 +1,17 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+
+/**
+ * The operation the manager is following. Kept outside the component so closing Settings while a cleanup runs and
+ * reopening it later shows the same operation, its result and its retry affordance.
+ */
+export const activeOperationStore = createExternalStore<{ operationId: string | null }>({ operationId: null });
+
+registerAccountOwnedResource({
+ clear: () => activeOperationStore.setSnapshot({ operationId: null }),
+ name: 'intermediates-active-operation',
+});
+
+export const followIntermediatesOperation = (operationId: string | null): void => {
+ activeOperationStore.setSnapshot({ operationId });
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts b/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts
new file mode 100644
index 0000000000..834e0c2bb1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/queries.ts
@@ -0,0 +1,38 @@
+import type { IntermediatesOperation, IntermediatesSummary } from '@features/intermediates/core/types';
+
+import { isOperationSettled } from '@features/intermediates/core/types';
+import { assertAccountScopeCurrent, captureAccountScope, type AccountScope } from '@platform/state/accountLifecycle';
+import { queryOptions } from '@tanstack/react-query';
+
+import type { IntermediatesSummaryParams } from './keys';
+
+import { getIntermediatesOperation, getIntermediatesSummary } from './api';
+import { intermediatesKeys } from './keys';
+
+export const INTERMEDIATES_PAGE_SIZE = 50;
+
+/** The largest single request the API accepts; used to resolve "all matching" into explicit targets. */
+export const INTERMEDIATES_MAX_ROWS = 1000;
+
+const fenced = <T>(owner: AccountScope, request: (signal: AbortSignal) => Promise<T>, signal: AbortSignal) =>
+ request(AbortSignal.any([signal, owner.signal])).then((result) => {
+ assertAccountScopeCurrent(owner);
+ return result;
+ });
+
+export const intermediatesSummaryQueryOptions = (params: IntermediatesSummaryParams, owner = captureAccountScope()) =>
+ queryOptions<IntermediatesSummary>({
+ queryFn: ({ signal }) => fenced(owner, (fencedSignal) => getIntermediatesSummary(params, fencedSignal), signal),
+ queryKey: intermediatesKeys.summary(owner, params),
+ staleTime: 15_000,
+ });
+
+/** Polls while the operation runs as a fallback for a missed socket event; stops once it settles. */
+export const intermediatesOperationQueryOptions = (operationId: string, owner = captureAccountScope()) =>
+ queryOptions<IntermediatesOperation>({
+ queryFn: ({ signal }) =>
+ fenced(owner, (fencedSignal) => getIntermediatesOperation(operationId, fencedSignal), signal),
+ queryKey: intermediatesKeys.operation(owner, operationId),
+ refetchInterval: (query) => (query.state.data && isOperationSettled(query.state.data) ? false : 2_000),
+ staleTime: 1_000,
+ });
diff --git a/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
new file mode 100644
index 0000000000..ccb5ef3c08
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/data/realtime.ts
@@ -0,0 +1,79 @@
+import type { QueryClient } from '@tanstack/react-query';
+
+import { isOperationSettled, type IntermediatesOperation } from '@features/intermediates/core/types';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { socketHub } from '@platform/transport/socketHub';
+
+import type { IntermediatesOperationDTO } from './api';
+
+import { mapIntermediatesOperation } from './api';
+import { intermediatesKeys } from './keys';
+
+const isOperationKey = (queryKey: readonly unknown[], accountKey: readonly unknown[]): boolean =>
+ queryKey.length === accountKey.length + 2 &&
+ queryKey[accountKey.length] === 'operation' &&
+ accountKey.every((segment, index) =>
+ typeof segment === 'object' && segment !== null
+ ? JSON.stringify(segment) === JSON.stringify(queryKey[index])
+ : segment === queryKey[index]
+ );
+
+/**
+ * Keeps the open manager current. Socket events replace the operation record; whichever path delivers a settled
+ * operation first (socket or the polled query) invalidates the account's counts exactly once, since every row the
+ * operation touched changed. Admins receive other accounts' events too, which is exactly when their totals change.
+ * A reconnect invalidates everything, since events during the gap were lost.
+ */
+export const attachIntermediatesRealtime = (queryClient: QueryClient): (() => void) => {
+ const owner = captureAccountScope();
+ const accountKey = intermediatesKeys.forAccount(owner);
+ const settledOperationIds = new Set<string>();
+
+ const noteSettled = (operation: IntermediatesOperation) => {
+ if (!isOperationSettled(operation) || settledOperationIds.has(operation.operationId)) {
+ return;
+ }
+ settledOperationIds.add(operation.operationId);
+ void queryClient.invalidateQueries({ queryKey: intermediatesKeys.summaries(owner) });
+ };
+
+ const detachCache = queryClient.getQueryCache().subscribe((event) => {
+ if (event.type !== 'updated' || event.action.type !== 'success' || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+ if (isOperationKey(event.query.queryKey, accountKey)) {
+ noteSettled(event.action.data as IntermediatesOperation);
+ }
+ });
+
+ const detachOperation = socketHub.on('intermediates_operation_changed', (payload: never) => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+ const event = payload as unknown as { operation?: IntermediatesOperationDTO } | undefined;
+
+ if (!event?.operation) {
+ return;
+ }
+ const operation = mapIntermediatesOperation(event.operation);
+
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ noteSettled(operation);
+ });
+
+ let wasConnected = false;
+ const detachConnection = socketHub.onConnectionChange((status) => {
+ const isConnected = status === 'connected';
+
+ if (isConnected && !wasConnected && isAccountScopeCurrent(owner)) {
+ void queryClient.invalidateQueries({ queryKey: accountKey });
+ }
+ wasConnected = isConnected;
+ });
+
+ return () => {
+ detachCache();
+ detachOperation();
+ detachConnection();
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/index.ts b/invokeai/frontend/webv2/src/features/intermediates/index.ts
new file mode 100644
index 0000000000..c65e2a518c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/index.ts
@@ -0,0 +1,11 @@
+export type {
+ IntermediatesCleanupMode,
+ IntermediatesOperation,
+ IntermediatesPreview,
+ IntermediatesRow,
+ IntermediatesScope,
+ IntermediatesScopeTarget,
+ IntermediatesSummary,
+} from './core/types';
+export { requestIntermediatesFocus, type IntermediatesFocus } from './data/focus';
+export { intermediatesKeys, type IntermediatesSummaryParams } from './data/keys';
diff --git a/invokeai/frontend/webv2/src/features/intermediates/settingsContribution.ts b/invokeai/frontend/webv2/src/features/intermediates/settingsContribution.ts
new file mode 100644
index 0000000000..e5ab007225
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/settingsContribution.ts
@@ -0,0 +1,20 @@
+import type { SettingsContribution } from '@platform/ui/settings/contracts';
+
+/** Metadata only: the manager and its transport load when the section opens. */
+export const intermediatesSettingsContribution: SettingsContribution = {
+ id: 'intermediates',
+ label: (t) => t('intermediates.title'),
+ fields: [
+ {
+ id: 'intermediatesManager',
+ kind: 'custom',
+ fill: true,
+ label: (t) => t('intermediates.title'),
+ description: (t) => t('intermediates.description'),
+ keywords: 'intermediates cleanup disk space clear temporary delete',
+ scope: 'none',
+ },
+ ],
+ load: () =>
+ import('./ui/IntermediatesSettingsField').then((module) => ({ Field: module.IntermediatesSettingsField })),
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
new file mode 100644
index 0000000000..9950984981
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/ClearDialog.tsx
@@ -0,0 +1,289 @@
+import type { IntermediatesCleanupMode, IntermediatesPreview } from '@features/intermediates/core/types';
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+import type { RefObject } from 'react';
+
+import { Alert, Box, chakra, Checkbox, Dialog, Input, Portal, Spinner, Stack, Text } from '@chakra-ui/react';
+import { Button, CloseButton } from '@platform/ui/Button';
+import { useCallback, useId, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatBytes } from './format';
+
+const CONFIRM_WORD = 'CLEAR';
+
+export interface ClearDialogState {
+ mode: IntermediatesCleanupMode;
+ /** Minted with each preview and reused for every Confirm of it, so a lost response replays the same operation. */
+ idempotencyKey: string;
+ /** Null until the server preview arrives; a confirmation is only ever offered for a fresh preview. */
+ preview: IntermediatesPreview | null;
+ previewError: string | null;
+ isStarting: boolean;
+ startError: string | null;
+}
+
+export interface ClearDialogProps {
+ state: ClearDialogState | null;
+ finalFocusRef: RefObject<HTMLElement | null>;
+ /** Receives focus when the trigger can no longer take it, e.g. a Delete button disabled by the cleared selection. */
+ fallbackFocusRef: RefObject<HTMLElement | null>;
+ onClose: () => void;
+ onConfirm: () => void;
+ onRetryPreview: () => void;
+ /** Re-previews in the other mode; force also deletes items saved documents still reference. */
+ onModeChange: (mode: IntermediatesCleanupMode) => void;
+}
+
+const Impact = ({ preview }: { preview: IntermediatesPreview }) => {
+ const { t } = useTranslation();
+ const { impact } = preview;
+ const referenced = impact.keepReferencedImages + impact.keepReferencedVideos;
+ const active = impact.keepActiveImages + impact.keepActiveVideos;
+ const recent = impact.keepRecentImages + impact.keepRecentVideos;
+ const kept = referenced + active + recent;
+ const nothing = impact.deleteImages + impact.deleteVideos === 0;
+
+ return (
+ <Stack gap="1.5">
+ <Text fontSize="sm" fontWeight="600">
+ {nothing
+ ? t('intermediates.dialog.nothing')
+ : t('intermediates.dialog.summary', {
+ images: t('intermediates.counts.images', { count: impact.deleteImages }),
+ projects: t('intermediates.counts.projects', { count: preview.targetRows }),
+ videos: t('intermediates.counts.videos', { count: impact.deleteVideos }),
+ })}
+ </Text>
+ {nothing ? null : (
+ <Text fontSize="xs">
+ {impact.unknownSizeCount > 0 && impact.reclaimableBytes === 0
+ ? t('intermediates.dialog.reclaimUnknown')
+ : t('intermediates.dialog.reclaim', { size: formatBytes(impact.reclaimableBytes) })}
+ {impact.unknownSizeCount > 0 && impact.reclaimableBytes > 0
+ ? ` ${t('intermediates.dialog.reclaimPartial', { count: impact.unknownSizeCount })}`
+ : ''}
+ </Text>
+ )}
+ {kept > 0 ? (
+ <Text color="fg.muted" fontSize="xs">
+ {t('intermediates.dialog.kept', { count: kept })}{' '}
+ {t('intermediates.dialog.keptReasons', {
+ active: t('intermediates.counts.items', { count: active }),
+ recent: t('intermediates.counts.items', { count: recent }),
+ referenced: t('intermediates.counts.items', { count: referenced }),
+ })}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+};
+
+const AffectedDocuments = ({ preview }: { preview: IntermediatesPreview }) => {
+ const { t } = useTranslation();
+
+ if (preview.affectedDocuments.length === 0 && preview.affectedDocumentsHidden === 0) {
+ return null;
+ }
+
+ return (
+ <Stack gap="1">
+ <Text fontSize="xs" fontWeight="600">
+ {t('intermediates.dialog.affected')}
+ </Text>
+ <Stack as="ul" gap="0.5" maxH="32" overflowY="auto" ps="4">
+ {preview.affectedDocuments.map((document) => (
+ <Text as="li" fontSize="xs" key={`${document.kind}:${document.userId}:${document.ownerId}`}>
+ {t(
+ document.kind === 'project'
+ ? 'intermediates.dialog.affectedProject'
+ : 'intermediates.dialog.affectedWorkflow',
+ { count: document.references, name: document.name ?? document.ownerId }
+ )}
+ </Text>
+ ))}
+ {preview.affectedDocumentsHidden > 0 ? (
+ <Text as="li" color="fg.muted" fontSize="xs">
+ {t('intermediates.dialog.affectedHidden', { count: preview.affectedDocumentsHidden })}
+ </Text>
+ ) : null}
+ </Stack>
+ </Stack>
+ );
+};
+
+/**
+ * One confirmation for both modes. The default deletes only safe items; the advanced disclosure switches to a
+ * force preview, which adds the affected documents, an acknowledgement and a typed confirmation.
+ */
+export const ClearDialog = ({
+ fallbackFocusRef,
+ finalFocusRef,
+ onClose,
+ onConfirm,
+ onModeChange,
+ onRetryPreview,
+ state,
+}: ClearDialogProps) => {
+ const { t } = useTranslation();
+ // The acknowledgement and typed word belong to one preview; a re-preview (mode switch, retry) starts over.
+ const [confirmation, setConfirmation] = useState<{ previewId: string; acknowledged: boolean; typed: string }>({
+ acknowledged: false,
+ previewId: '',
+ typed: '',
+ });
+ const confirmInputId = useId();
+ const isForce = state?.mode === 'force';
+ const preview = state?.preview ?? null;
+ const acknowledged = confirmation.previewId === preview?.previewId && confirmation.acknowledged;
+ const typed = confirmation.previewId === preview?.previewId ? confirmation.typed : '';
+ const setAcknowledged = (value: boolean) =>
+ setConfirmation({ acknowledged: value, previewId: preview?.previewId ?? '', typed });
+ const setTyped = (value: string) =>
+ setConfirmation({ acknowledged, previewId: preview?.previewId ?? '', typed: value });
+ const nothingToDelete = preview !== null && preview.impact.deleteImages + preview.impact.deleteVideos === 0;
+ const forceReady = !isForce || (acknowledged && typed.trim() === CONFIRM_WORD);
+ const canConfirm = preview !== null && !nothingToDelete && forceReady && !state?.isStarting;
+
+ const handleOpenChange = useCallback(
+ (event: { open: boolean }) => {
+ if (!event.open && !state?.isStarting) {
+ onClose();
+ }
+ },
+ [onClose, state?.isStarting]
+ );
+ const handleExitComplete = useCallback(() => {
+ setConfirmation({ acknowledged: false, previewId: '', typed: '' });
+ }, []);
+
+ return (
+ <Dialog.Root
+ closeOnEscape={!state?.isStarting}
+ closeOnInteractOutside={!state?.isStarting}
+ finalFocusEl={() => {
+ const trigger = finalFocusRef.current;
+
+ return trigger && !(trigger as HTMLButtonElement).disabled ? trigger : fallbackFocusRef.current;
+ }}
+ lazyMount
+ open={state !== null}
+ role="alertdialog"
+ size="sm"
+ unmountOnExit
+ onExitComplete={handleExitComplete}
+ onOpenChange={handleOpenChange}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>
+ {isForce ? t('intermediates.dialog.forceTitle') : t('intermediates.dialog.title')}
+ </Dialog.Title>
+ </Dialog.Header>
+ <Dialog.Body>
+ <Stack gap="3">
+ {/* zag snapshots aria-describedby at open, so the Description must exist before the preview lands. */}
+ <Dialog.Description asChild>
+ <Box>
+ {state?.previewError ? (
+ <Alert.Root size="sm" status="error" variant="surface">
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Description>{state.previewError}</Alert.Description>
+ </Alert.Content>
+ <Button size="2xs" variant="outline" onClick={onRetryPreview}>
+ {t('common.retry')}
+ </Button>
+ </Alert.Root>
+ ) : preview === null ? (
+ <Stack align="center" direction="row" gap="2">
+ <Spinner color="fg.muted" size="xs" />
+ <Text color="fg.muted" fontSize="xs">
+ {t('intermediates.dialog.loadingPreview')}
+ </Text>
+ </Stack>
+ ) : (
+ <Impact preview={preview} />
+ )}
+ </Box>
+ </Dialog.Description>
+ <Checkbox.Root
+ checked={isForce}
+ colorPalette="red"
+ disabled={state?.isStarting}
+ size="sm"
+ onCheckedChange={(event) => onModeChange(event.checked === true ? 'force' : 'safe')}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label fontSize="xs">{t('intermediates.dialog.forceToggle')}</Checkbox.Label>
+ </Checkbox.Root>
+ {isForce ? (
+ <Alert.Root size="sm" status="warning" variant="surface">
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Description>{t('intermediates.dialog.forceWarning')}</Alert.Description>
+ </Alert.Content>
+ </Alert.Root>
+ ) : null}
+ {isForce && preview ? <AffectedDocuments preview={preview} /> : null}
+ {isForce && preview && !nothingToDelete ? (
+ <Stack gap="2">
+ <Checkbox.Root
+ checked={acknowledged}
+ colorPalette="red"
+ size="sm"
+ onCheckedChange={(event) => setAcknowledged(event.checked === true)}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label fontSize="xs">{t('intermediates.dialog.acknowledge')}</Checkbox.Label>
+ </Checkbox.Root>
+ <Stack gap="1">
+ <chakra.label fontSize="xs" htmlFor={confirmInputId}>
+ {t('intermediates.dialog.typeToConfirm', { word: CONFIRM_WORD })}
+ </chakra.label>
+ <Input
+ autoComplete="off"
+ id={confirmInputId}
+ size="xs"
+ spellCheck={false}
+ value={typed}
+ onChange={(event) => setTyped(event.currentTarget.value)}
+ />
+ </Stack>
+ </Stack>
+ ) : null}
+ {state?.startError ? (
+ <Text color="fg.error" fontSize="xs" role="alert">
+ {state.startError}
+ </Text>
+ ) : null}
+ </Stack>
+ </Dialog.Body>
+ <Dialog.Footer>
+ <Button disabled={state?.isStarting} size="xs" variant="ghost" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ colorPalette="red"
+ disabled={!canConfirm}
+ loading={state?.isStarting}
+ size="xs"
+ variant="solid"
+ onClick={onConfirm}
+ >
+ {isForce ? t('intermediates.dialog.forceConfirm') : t('intermediates.dialog.confirm')}
+ </Button>
+ </Dialog.Footer>
+ <Dialog.CloseTrigger asChild>
+ <CloseButton disabled={state?.isStarting} />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
new file mode 100644
index 0000000000..c7d383b272
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesList.tsx
@@ -0,0 +1,142 @@
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+import type { IntermediatesRow } from '@features/intermediates/core/types';
+import type { TFunction } from 'i18next';
+
+import { Badge, Checkbox, Flex, HStack, Icon, Image, Stack, Text } from '@chakra-ui/react';
+import { getIntermediatesRowKey, getKindInUse } from '@features/intermediates/core/types';
+import { absolutizeApiUrl } from '@platform/transport/http';
+import { Row } from '@platform/ui/Row';
+import { FolderIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { formatBytes, formatCount } from './format';
+
+export const getRowLabel = (row: IntermediatesRow, unassignedLabel: string): string =>
+ row.projectId === null ? unassignedLabel : row.projectName || row.projectId;
+
+export const getOwnerLabel = (row: IntermediatesRow): string => row.userDisplayName || row.userEmail || row.userId;
+
+const Cover = ({ imageName }: { imageName: string | null }) =>
+ imageName ? (
+ <Image
+ alt=""
+ boxSize="9"
+ fit="cover"
+ flexShrink={0}
+ loading="lazy"
+ rounded="md"
+ src={absolutizeApiUrl(`/api/v1/images/i/${imageName}/thumbnail`)}
+ />
+ ) : (
+ <Flex
+ align="center"
+ bg="bg.emphasized"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ boxSize="9"
+ color="fg.subtle"
+ flexShrink={0}
+ justify="center"
+ rounded="md"
+ >
+ <Icon as={FolderIcon} boxSize="4" />
+ </Flex>
+ );
+
+const Figure = ({ label, value }: { label: string; value: number }) => (
+ <Stack align="flex-end" flexShrink={0} gap="0" minW="3.25rem">
+ <Text
+ color={value === 0 ? 'fg.muted' : 'fg'}
+ fontSize="xs"
+ fontVariantNumeric="tabular-nums"
+ fontWeight="600"
+ lineHeight="shorter"
+ >
+ {formatCount(value)}
+ </Text>
+ <Text color="fg.muted" fontSize="2xs" lineHeight="shorter">
+ {label}
+ </Text>
+ </Stack>
+);
+
+const describeRow = (row: IntermediatesRow, showOwner: boolean, t: TFunction): string => {
+ const size = t('intermediates.list.rowSummary', {
+ size: formatBytes(row.reclaimableBytes),
+ unmeasured: row.unknownSizeCount > 0 ? t('intermediates.list.unmeasured', { count: row.unknownSizeCount }) : '',
+ }).trim();
+
+ return showOwner ? t('intermediates.list.ownerAndSize', { owner: getOwnerLabel(row), size }) : size;
+};
+
+export interface IntermediatesListProps {
+ rows: readonly IntermediatesRow[];
+ showOwner: boolean;
+ isSelected: (row: IntermediatesRow) => boolean;
+ onToggleRow: (row: IntermediatesRow) => void;
+}
+
+/** One row per project, as the sketch: checkbox, cover, name over owner, then the used and unused counts. */
+export const IntermediatesList = ({ isSelected, onToggleRow, rows, showOwner }: IntermediatesListProps) => {
+ const { t } = useTranslation();
+ const unassigned = t('intermediates.list.unassigned');
+
+ return (
+ <Stack as="ul" aria-label={t('intermediates.title')} gap="0.5" listStyleType="none" m="0" p="0" role="list">
+ {rows.map((row) => {
+ const label = getRowLabel(row, unassigned);
+ const selected = isSelected(row);
+ const used = getKindInUse(row.images) + getKindInUse(row.videos);
+ const unused = row.images.safe + row.videos.safe;
+
+ return (
+ <Row
+ as="li"
+ active={selected ? 'selected' : 'none'}
+ cursor="pointer"
+ data-selected={selected || undefined}
+ gap="2.5"
+ key={getIntermediatesRowKey(row)}
+ minW="0"
+ px="2"
+ py="1.5"
+ rounded="md"
+ onClick={() => onToggleRow(row)}
+ >
+ <Checkbox.Root
+ aria-label={t('intermediates.list.selectRow', { name: label })}
+ checked={selected}
+ colorPalette="accent"
+ size="xs"
+ onCheckedChange={() => onToggleRow(row)}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ </Checkbox.Root>
+ <Cover imageName={row.coverImageName} />
+ <Stack flex="1" gap="0.5" minW="0">
+ <HStack gap="1.5" minW="0">
+ <Text fontSize="xs" fontWeight="600" truncate>
+ {label}
+ </Text>
+ {row.projectId === null ? (
+ <Badge flexShrink={0} fontSize="2xs" variant="surface">
+ {t('intermediates.list.unassignedBadge')}
+ </Badge>
+ ) : null}
+ </HStack>
+ <Text color="fg.muted" fontSize="2xs" truncate>
+ {describeRow(row, showOwner, t)}
+ </Text>
+ </Stack>
+ <HStack flexShrink={0} gap="4" pe="1">
+ <Figure label={t('intermediates.list.used')} value={used} />
+ <Figure label={t('intermediates.list.unused')} value={unused} />
+ </HStack>
+ </Row>
+ );
+ })}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
new file mode 100644
index 0000000000..b3065d7cfc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.browser.test.tsx
@@ -0,0 +1,371 @@
+import type {
+ IntermediatesOperation,
+ IntermediatesPreview,
+ IntermediatesRow,
+ IntermediatesSummary,
+} from '@features/intermediates/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const dependencies = vi.hoisted(() => ({
+ createIntermediatesPreview: vi.fn(),
+ getIntermediatesOperation: vi.fn(),
+ getIntermediatesSummary: vi.fn(),
+ retryIntermediatesOperation: vi.fn(),
+ startIntermediatesOperation: vi.fn(),
+}));
+
+vi.mock('@features/intermediates/data/api', () => ({
+ createIntermediatesPreview: dependencies.createIntermediatesPreview,
+ getIntermediatesOperation: dependencies.getIntermediatesOperation,
+ getIntermediatesSummary: dependencies.getIntermediatesSummary,
+ retryIntermediatesOperation: dependencies.retryIntermediatesOperation,
+ startIntermediatesOperation: dependencies.startIntermediatesOperation,
+}));
+vi.mock('@features/intermediates/data/realtime', () => ({ attachIntermediatesRealtime: () => () => undefined }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options && Object.keys(options).length > 0
+ ? `${key}(${Object.entries(options)
+ .map(([name, value]) => `${name}=${String(value)}`)
+ .join(',')})`
+ : key,
+ }),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const row = (projectId: string | null, name: string | null, safe: number): IntermediatesRow => ({
+ coverImageName: null,
+ images: { active: 1, recent: 0, referenced: 2, safe },
+ projectId,
+ projectName: name,
+ reclaimableBytes: safe * 1_048_576,
+ referencedBytes: 0,
+ unknownSizeCount: 0,
+ userDisplayName: 'Alice',
+ userEmail: '[email protected]',
+ userId: 'alice',
+ videos: { active: 0, recent: 0, referenced: 0, safe: 0 },
+});
+
+const summaryOf = (items: IntermediatesRow[]): IntermediatesSummary => ({
+ canManageEveryone: false,
+ items,
+ limit: 50,
+ measuring: false,
+ offset: 0,
+ recentGraceSeconds: 1800,
+ total: items.length,
+ totals: {
+ inUseImages: items.length * 3,
+ inUseVideos: 0,
+ reclaimableBytes: items.reduce((sum, item) => sum + item.reclaimableBytes, 0),
+ rows: items.length,
+ safeImages: items.reduce((sum, item) => sum + item.images.safe, 0),
+ safeVideos: 0,
+ unknownSizeCount: 0,
+ },
+});
+
+const previewOf = (mode: 'safe' | 'force', deleteImages: number): IntermediatesPreview => ({
+ affectedDocuments:
+ mode === 'force' ? [{ kind: 'project', name: 'Portraits', ownerId: 'p1', references: 2, userId: 'alice' }] : [],
+ affectedDocumentsHidden: 0,
+ createdAt: 'now',
+ expiresAt: 'later',
+ impact: {
+ deleteImages,
+ deleteVideos: 0,
+ keepActiveImages: 1,
+ keepActiveVideos: 0,
+ keepRecentImages: 0,
+ keepRecentVideos: 0,
+ keepReferencedImages: mode === 'safe' ? 2 : 0,
+ keepReferencedVideos: 0,
+ reclaimableBytes: deleteImages * 1_048_576,
+ unknownSizeCount: 0,
+ },
+ mode,
+ previewId: `preview-${mode}`,
+ scope: { kind: 'owner', userId: 'alice' },
+ targetRows: 1,
+});
+
+const operationOf = (status: IntermediatesOperation['status']): IntermediatesOperation => ({
+ completedAt: status === 'completed' ? 'later' : null,
+ createdAt: 'now',
+ error: null,
+ mode: 'safe',
+ operationId: 'op-1',
+ progress: {
+ deletedImages: status === 'completed' ? 4 : 2,
+ deletedVideos: 0,
+ failedImages: 0,
+ failedVideos: 0,
+ pendingDiskCleanup: 0,
+ processedImages: status === 'completed' ? 4 : 2,
+ processedVideos: 0,
+ reclaimedBytes: 4_194_304,
+ retainedImages: 0,
+ retainedVideos: 0,
+ unknownSizeCount: 0,
+ unresolvedImages: 0,
+ unresolvedVideos: 0,
+ },
+ retriedByOperationId: null,
+ retriedFromOperationId: null,
+ scope: { kind: 'owner', userId: 'alice' },
+ startedAt: 'now',
+ status,
+ targetImages: 4,
+ targetVideos: 0,
+ userId: 'alice',
+});
+
+let host: HTMLDivElement;
+let root: Root;
+let queryClient: QueryClient;
+
+const renderManager = async (
+ options: { focusProjectId?: string; currentUserId?: string | null } = {}
+): Promise<void> => {
+ host = document.createElement('div');
+ host.style.height = '640px';
+ host.style.width = '900px';
+ host.style.display = 'flex';
+ host.style.flexDirection = 'column';
+ document.body.append(host);
+ root = createRoot(host);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { requestIntermediatesFocus } = await import('@features/intermediates/data/focus');
+ const { IntermediatesManager } = await import('./IntermediatesManager');
+
+ if (options.focusProjectId) {
+ requestIntermediatesFocus({ projectId: options.focusProjectId });
+ }
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <IntermediatesManager
+ canClearOthersIntermediates={false}
+ currentUserId={options.currentUserId === undefined ? 'alice' : options.currentUserId}
+ />
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
+ });
+};
+
+/** Chakra puts the accessible name on the checkbox root; the hidden input inside it carries the state. */
+const checkbox = (label: string): { click: () => void; checked: boolean } => {
+ const rootElement = host.querySelector<HTMLElement>(`[aria-label="${label}"]`);
+ expect(rootElement, label).not.toBeNull();
+ const input = rootElement!.querySelector<HTMLInputElement>('input');
+ expect(input, `${label} input`).not.toBeNull();
+ return { checked: input!.checked, click: () => input!.click() };
+};
+
+const buttonWithText = (text: string, scope: ParentNode = document): HTMLButtonElement => {
+ const button = [...scope.querySelectorAll<HTMLButtonElement>('button')].find((candidate) =>
+ candidate.textContent?.includes(text)
+ );
+ expect(button, text).toBeDefined();
+ return button!;
+};
+
+const setInputValue = (input: HTMLInputElement, value: string) => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setter.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+};
+
+describe('IntermediatesManager', () => {
+ beforeEach(() => {
+ dependencies.getIntermediatesSummary
+ .mockReset()
+ .mockImplementation((params: { search?: string }) =>
+ Promise.resolve(
+ summaryOf(
+ params.search?.trim()
+ ? [row('p1', 'Portraits', 4)]
+ : [row('p1', 'Portraits', 4), row('p2', 'Landscapes', 1), row(null, null, 7)]
+ )
+ )
+ );
+ dependencies.createIntermediatesPreview
+ .mockReset()
+ .mockImplementation(({ mode }: { mode: 'safe' | 'force' }) => Promise.resolve(previewOf(mode, 4)));
+ dependencies.startIntermediatesOperation.mockReset().mockResolvedValue(operationOf('running'));
+ dependencies.getIntermediatesOperation.mockReset().mockResolvedValue(operationOf('completed'));
+ dependencies.retryIntermediatesOperation.mockReset();
+ });
+
+ afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ });
+
+ it('lists projects with used and unused counts and keeps Delete disabled until something is selected', async () => {
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+
+ expect(host.textContent).toContain('intermediates.list.unassigned');
+ expect(host.querySelectorAll('[role="list"] li')).toHaveLength(3);
+ expect(host.textContent).toContain('intermediates.list.used');
+ expect(host.textContent).toContain('intermediates.list.unused');
+ expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(true);
+
+ await act(() => checkbox('intermediates.list.selectRow(name=Portraits)').click());
+ expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(false);
+ expect(host.textContent).toContain('count=1');
+
+ await act(() => checkbox('intermediates.list.selectAll').click());
+ expect(host.textContent).toContain('count=3');
+
+ const search = host.querySelector<HTMLInputElement>('input[aria-label="intermediates.searchLabel"]');
+ expect(search).not.toBeNull();
+ await act(() => setInputValue(search!, 'Port'));
+ await vi.waitFor(() =>
+ expect(dependencies.getIntermediatesSummary).toHaveBeenLastCalledWith(
+ expect.objectContaining({ search: 'Port' }),
+ expect.anything()
+ )
+ );
+ // A search hides rows; hidden selections must not survive it.
+ expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(true);
+ });
+
+ it('previews the delete, starts the operation, and reports it once it settles', async () => {
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ expect(checkbox('intermediates.list.selectRow(name=Portraits)').checked).toBe(true);
+
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ await vi.waitFor(() =>
+ expect(dependencies.createIntermediatesPreview).toHaveBeenCalledWith(
+ { mode: 'safe', scope: { kind: 'selection', targets: [{ projectId: 'p1', userId: 'alice' }] } },
+ expect.anything()
+ )
+ );
+ const dialog = document.querySelector('[role="alertdialog"]');
+ expect(dialog).not.toBeNull();
+ await vi.waitFor(() => expect(dialog!.textContent).toContain('intermediates.dialog.reclaim(size=4.0 MB)'));
+ expect(dialog!.textContent).toContain('intermediates.dialog.kept(count=3)');
+ // The impact is the dialog's accessible description even though it arrives after the dialog opens.
+ const describedBy = dialog!.getAttribute('aria-describedby');
+ expect(describedBy).not.toBeNull();
+ expect(document.getElementById(describedBy!)?.textContent).toContain('intermediates.dialog.reclaim(size=4.0 MB)');
+
+ const confirm = buttonWithText('intermediates.dialog.confirm', dialog!);
+ expect(confirm.disabled).toBe(false);
+ await act(() => confirm.click());
+ await vi.waitFor(() =>
+ expect(dependencies.startIntermediatesOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ previewId: 'preview-safe' }),
+ expect.anything()
+ )
+ );
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"]')).toBeNull());
+ expect(host.textContent).toContain('intermediates.operation.status.running');
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.operation.status.completed'), {
+ timeout: 5_000,
+ });
+ expect(host.textContent).not.toContain('intermediates.operation.retry');
+ });
+
+ it('gates a force delete behind the disclosure, an acknowledgement and the typed word', async () => {
+ await renderManager({ focusProjectId: 'p1' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Portraits'));
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ const dialog = await vi.waitFor(() => {
+ const element = document.querySelector<HTMLElement>('[role="alertdialog"]');
+ expect(element).not.toBeNull();
+ return element!;
+ });
+ await vi.waitFor(() => expect(dialog.textContent).toContain('intermediates.dialog.reclaim'));
+
+ const toggles = () => [...dialog.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
+ await act(() => toggles()[0]!.click());
+ await vi.waitFor(() =>
+ expect(dependencies.createIntermediatesPreview).toHaveBeenLastCalledWith(
+ expect.objectContaining({ mode: 'force' }),
+ expect.anything()
+ )
+ );
+ await vi.waitFor(() => expect(dialog.textContent).toContain('Portraits'));
+ const confirm = () => buttonWithText('intermediates.dialog.forceConfirm', dialog);
+ expect(confirm().disabled).toBe(true);
+
+ await act(() => toggles()[1]!.click());
+ expect(confirm().disabled).toBe(true);
+
+ const typed = dialog.querySelector<HTMLInputElement>('input:not([type="checkbox"])');
+ expect(typed).not.toBeNull();
+ await act(() => setInputValue(typed!, 'CLEAR'));
+ expect(confirm().disabled).toBe(false);
+ });
+
+ it('reports a failed load with a retry and an empty library plainly', async () => {
+ dependencies.getIntermediatesSummary
+ .mockReset()
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockResolvedValue(summaryOf([]));
+ await renderManager();
+
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.errors.couldNotLoad'));
+ await act(() => buttonWithText('common.retry', host).click());
+ await vi.waitFor(() => expect(host.textContent).toContain('intermediates.empty.title'));
+ });
+
+ it('preselects the requested project in single-user mode, where the session names no account', async () => {
+ await renderManager({ currentUserId: null, focusProjectId: 'p2' });
+ await vi.waitFor(() => expect(host.textContent).toContain('Landscapes'));
+
+ expect(checkbox('intermediates.list.selectRow(name=Landscapes)').checked).toBe(true);
+ expect(checkbox('intermediates.list.selectRow(name=Portraits)').checked).toBe(false);
+ expect(buttonWithText('intermediates.list.delete', host).disabled).toBe(false);
+ expect(host.textContent).toContain('count=1');
+ });
+
+ it('keeps picks from another page in the estimate and the targets', async () => {
+ const manyRows = Array.from({ length: 60 }, (_, index) => row(`p${index}`, `Project ${index}`, 1));
+ dependencies.getIntermediatesSummary.mockReset().mockImplementation((params: { offset?: number }) => {
+ const offset = params.offset ?? 0;
+ const summary = summaryOf(manyRows.slice(offset, offset + 50));
+ return Promise.resolve({ ...summary, offset, total: manyRows.length });
+ });
+ await renderManager();
+ await vi.waitFor(() => expect(host.textContent).toContain('Project 0'));
+
+ await act(() => checkbox('intermediates.list.selectRow(name=Project 1)').click());
+ await act(() => buttonWithText('common.nextPage', host).click());
+ await vi.waitFor(() => expect(host.textContent).toContain('Project 55'));
+ await act(() => checkbox('intermediates.list.selectRow(name=Project 55)').click());
+ expect(host.textContent).toContain('count=2');
+
+ await act(() => buttonWithText('intermediates.list.delete', host).click());
+ await vi.waitFor(() =>
+ expect(dependencies.createIntermediatesPreview).toHaveBeenCalledWith(
+ {
+ mode: 'safe',
+ scope: {
+ kind: 'selection',
+ targets: [
+ { projectId: 'p1', userId: 'alice' },
+ { projectId: 'p55', userId: 'alice' },
+ ],
+ },
+ },
+ expect.anything()
+ )
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
new file mode 100644
index 0000000000..d1695fe077
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesManager.tsx
@@ -0,0 +1,527 @@
+import type {
+ IntermediatesCleanupMode,
+ IntermediatesPreview,
+ IntermediatesRow,
+ IntermediatesScope,
+} from '@features/intermediates/core/types';
+/* eslint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */
+import type { IntermediatesSummaryParams } from '@features/intermediates/data/keys';
+
+import {
+ Badge,
+ Box,
+ Center,
+ Checkbox,
+ HStack,
+ Icon,
+ Input,
+ InputGroup,
+ Separator,
+ Spinner,
+ Stack,
+ Text,
+} from '@chakra-ui/react';
+import {
+ EMPTY_SELECTION,
+ getPageSelectionState,
+ isRowSelected,
+ isSelectionEmpty,
+ resolveScope,
+ selectAllMatching,
+ summarizeSelection,
+ toggleRowSelection,
+ withRowSelected,
+ type IntermediatesSelection,
+} from '@features/intermediates/core/selection';
+import {
+ createIntermediatesPreview,
+ getIntermediatesSummary,
+ retryIntermediatesOperation,
+ startIntermediatesOperation,
+} from '@features/intermediates/data/api';
+import { takeIntermediatesFocus } from '@features/intermediates/data/focus';
+import { intermediatesKeys } from '@features/intermediates/data/keys';
+import { activeOperationStore, followIntermediatesOperation } from '@features/intermediates/data/operationStore';
+import {
+ INTERMEDIATES_MAX_ROWS,
+ INTERMEDIATES_PAGE_SIZE,
+ intermediatesOperationQueryOptions,
+ intermediatesSummaryQueryOptions,
+} from '@features/intermediates/data/queries';
+import { attachIntermediatesRealtime } from '@features/intermediates/data/realtime';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { ApiError, getApiErrorMessage } from '@platform/transport/http';
+import { Button, IconButton } from '@platform/ui/Button';
+import { EmptyState } from '@platform/ui/EmptyState';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { BrushCleaningIcon, RefreshCwIcon, SearchIcon, Trash2Icon, XIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ClearDialogState } from './ClearDialog';
+
+import { ClearDialog } from './ClearDialog';
+import { formatBytes } from './format';
+import { getOwnerLabel, IntermediatesList } from './IntermediatesList';
+import { OperationPanel } from './OperationPanel';
+
+export interface IntermediatesManagerProps {
+ /** The current account, or null in single-user mode where the install is the only account. */
+ currentUserId: string | null;
+ canClearOthersIntermediates: boolean;
+}
+
+const SEARCH_ICON = <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />;
+const EMPTY_ROWS: readonly IntermediatesRow[] = [];
+const EMPTY_TOTALS = { reclaimableBytes: 0, rows: 0, safeImages: 0, safeVideos: 0, unknownSizeCount: 0 };
+
+let nextIdempotencyKey = 1;
+const createIdempotencyKey = (): string => `intermediates:${Date.now().toString(36)}:${nextIdempotencyKey++}`;
+
+/** The Settings section: search, a select-all row with the delete action, and one row per project. */
+export const IntermediatesManager = ({ canClearOthersIntermediates, currentUserId }: IntermediatesManagerProps) => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ // An entry point's intent is read once, when the section mounts; a later visit starts clean.
+ const [focus] = useState(takeIntermediatesFocus);
+ const [search, setSearch] = useState('');
+ const [ownerFilter, setOwnerFilter] = useState<string | null>(() =>
+ focus?.ownerId && canClearOthersIntermediates ? focus.ownerId : null
+ );
+ const [offset, setOffset] = useState(0);
+ const [selection, setSelection] = useState<IntermediatesSelection>(EMPTY_SELECTION);
+ // A project to preselect is resolved against loaded rows, whichever page and owner it turns out to have; the
+ // intent is consumed by the first selection change.
+ const [pendingProjectId, setPendingProjectId] = useState<string | null>(focus?.projectId ?? null);
+ const [dialog, setDialog] = useState<ClearDialogState | null>(null);
+ const activeOperationId = activeOperationStore.useSelector((snapshot) => snapshot.operationId);
+ const [retryError, setRetryError] = useState<string | null>(null);
+ const [isRetrying, setIsRetrying] = useState(false);
+ const dialogTriggerRef = useRef<HTMLElement | null>(null);
+ const searchRef = useRef<HTMLInputElement | null>(null);
+ const previewRequestRef = useRef(0);
+ const pendingScopeRef = useRef<IntermediatesScope | null>(null);
+
+ useMountEffect(() => attachIntermediatesRealtime(queryClient));
+
+ // Non-admins are confined to their own rows by the server whatever is sent; admins see everyone unless filtered.
+ const ownerId: string | null = canClearOthersIntermediates ? ownerFilter : currentUserId;
+ const params = useMemo<IntermediatesSummaryParams>(
+ () => ({ limit: INTERMEDIATES_PAGE_SIZE, offset, order: 'desc', ownerId, search, sort: 'reclaimable_bytes' }),
+ [offset, ownerId, search]
+ );
+ const query = useQuery(intermediatesSummaryQueryOptions(params));
+ const rows = query.data?.items ?? EMPTY_ROWS;
+ const totals = query.data?.totals;
+ const hasSearch = search.trim().length > 0;
+ // Rows disappearing (a cleanup, a narrower search) can leave the offset past the end; step back to a valid page.
+ if (query.data && offset > 0 && offset >= query.data.total) {
+ setOffset(
+ Math.max(0, Math.floor(Math.max(query.data.total - 1, 0) / INTERMEDIATES_PAGE_SIZE) * INTERMEDIATES_PAGE_SIZE)
+ );
+ }
+ const focusedRow = pendingProjectId ? rows.find((row) => row.projectId === pendingProjectId) : undefined;
+ const effectiveSelection = focusedRow ? withRowSelected(selection, focusedRow) : selection;
+ const operationQuery = useQuery({
+ ...intermediatesOperationQueryOptions(activeOperationId ?? ''),
+ enabled: activeOperationId !== null,
+ });
+
+ const resetSelection = useCallback(() => {
+ setPendingProjectId(null);
+ setSelection(EMPTY_SELECTION);
+ }, []);
+ const handleSearchChange = useCallback(
+ (value: string) => {
+ setSearch(value);
+ setOffset(0);
+ // A filter change hides rows; hidden selections would act on what the user can no longer see.
+ resetSelection();
+ },
+ [resetSelection]
+ );
+ const clearOwnerFilter = useCallback(() => {
+ setOwnerFilter(null);
+ setOffset(0);
+ resetSelection();
+ }, [resetSelection]);
+ const handleToggleRow = useCallback(
+ (row: IntermediatesRow) => {
+ setPendingProjectId(null);
+ setSelection(toggleRowSelection(effectiveSelection, row, rows));
+ },
+ [effectiveSelection, rows]
+ );
+ // Select all selects every matching row, including pages not loaded; only a complete selection clears.
+ const handleToggleAll = useCallback(() => {
+ setPendingProjectId(null);
+ setSelection(getPageSelectionState(effectiveSelection, rows) === 'all' ? EMPTY_SELECTION : selectAllMatching());
+ }, [effectiveSelection, rows]);
+
+ const selectionSummary = useMemo(
+ () => summarizeSelection(effectiveSelection, totals ?? EMPTY_TOTALS),
+ [effectiveSelection, totals]
+ );
+
+ const loadPreview = useCallback(
+ async (mode: IntermediatesCleanupMode, scope: IntermediatesScope) => {
+ const requestId = ++previewRequestRef.current;
+ const owner = captureAccountScope();
+ setDialog((current) => ({
+ idempotencyKey: current?.idempotencyKey ?? createIdempotencyKey(),
+ isStarting: false,
+ mode,
+ preview: null,
+ previewError: null,
+ startError: null,
+ }));
+ try {
+ let resolvedScope = scope;
+ // "All matching" under a search cannot be expressed to the server; resolve it to explicit rows.
+ if (effectiveSelection.mode === 'all-matching' && hasSearch && scope.kind === 'selection') {
+ const everything = await getIntermediatesSummary(
+ { ...params, limit: INTERMEDIATES_MAX_ROWS, offset: 0 },
+ owner.signal
+ );
+ assertAccountScopeCurrent(owner);
+ if (everything.total > everything.items.length) {
+ throw new Error(t('intermediates.dialog.tooManyRows', { count: everything.items.length }));
+ }
+ resolvedScope = {
+ kind: 'selection',
+ targets: everything.items.map(({ projectId, userId }) => ({ projectId, userId })),
+ };
+ }
+ const preview = await createIntermediatesPreview({ mode, scope: resolvedScope }, owner.signal);
+ assertAccountScopeCurrent(owner);
+ if (previewRequestRef.current === requestId) {
+ // One key per preview: every Confirm of this preview replays the same operation, and a later preview
+ // (mode switch, retry) starts clean instead of colliding with a key the server already settled.
+ setDialog((current) => (current ? { ...current, idempotencyKey: createIdempotencyKey(), preview } : current));
+ }
+ } catch (error) {
+ if (previewRequestRef.current === requestId && isAccountScopeCurrent(owner)) {
+ setDialog((current) =>
+ current
+ ? { ...current, previewError: getApiErrorMessage(error, t('intermediates.dialog.previewFailed')) }
+ : current
+ );
+ }
+ }
+ },
+ [effectiveSelection.mode, hasSearch, params, t]
+ );
+ const openDialog = useCallback(
+ (scope: IntermediatesScope, trigger: HTMLElement | null) => {
+ dialogTriggerRef.current = trigger;
+ pendingScopeRef.current = scope;
+ setRetryError(null);
+ setDialog(null);
+ void loadPreview('safe', scope);
+ },
+ [loadPreview]
+ );
+ const closeDialog = useCallback(() => {
+ previewRequestRef.current += 1;
+ setDialog(null);
+ }, []);
+ const retryPreview = useCallback(() => {
+ if (dialog && pendingScopeRef.current) {
+ void loadPreview(dialog.mode, pendingScopeRef.current);
+ }
+ }, [dialog, loadPreview]);
+ const changeMode = useCallback(
+ (mode: IntermediatesCleanupMode) => {
+ if (pendingScopeRef.current) {
+ void loadPreview(mode, pendingScopeRef.current);
+ }
+ },
+ [loadPreview]
+ );
+ const confirmDialog = useCallback(async () => {
+ const preview: IntermediatesPreview | null = dialog?.preview ?? null;
+
+ if (!dialog || !preview) {
+ return;
+ }
+ const owner = captureAccountScope();
+ setDialog((current) => (current ? { ...current, isStarting: true, startError: null } : current));
+ try {
+ const operation = await startIntermediatesOperation(
+ { idempotencyKey: dialog.idempotencyKey, previewId: preview.previewId },
+ owner.signal
+ );
+ assertAccountScopeCurrent(owner);
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ followIntermediatesOperation(operation.operationId);
+ resetSelection();
+ setDialog(null);
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+ // A 404 means the preview expired or was consumed by a request whose response was lost; only a new
+ // preview can move forward, so offer that instead of a dead Confirm.
+ const previewGone = error instanceof ApiError && error.status === 404;
+ setDialog((current) =>
+ current
+ ? {
+ ...current,
+ isStarting: false,
+ preview: previewGone ? null : current.preview,
+ previewError: previewGone ? t('intermediates.dialog.previewExpired') : current.previewError,
+ startError: previewGone ? null : getApiErrorMessage(error, t('intermediates.dialog.startFailed')),
+ }
+ : current
+ );
+ }
+ }, [dialog, queryClient, resetSelection, t]);
+
+ const handleRetry = useCallback(async () => {
+ if (!activeOperationId) {
+ return;
+ }
+ const owner = captureAccountScope();
+ setIsRetrying(true);
+ setRetryError(null);
+ try {
+ const operation = await retryIntermediatesOperation(activeOperationId, owner.signal);
+ assertAccountScopeCurrent(owner);
+ queryClient.setQueryData(intermediatesKeys.operation(owner, operation.operationId), operation);
+ followIntermediatesOperation(operation.operationId);
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ setRetryError(getApiErrorMessage(error, t('intermediates.operation.retryFailed')));
+ }
+ } finally {
+ if (isAccountScopeCurrent(owner)) {
+ setIsRetrying(false);
+ }
+ }
+ }, [activeOperationId, queryClient, t]);
+ const dismissOperation = useCallback(() => {
+ followIntermediatesOperation(null);
+ setRetryError(null);
+ // The Dismiss button unmounts with the panel; keep keyboard focus in the section.
+ searchRef.current?.focus();
+ }, []);
+ const handleRefresh = useCallback(() => {
+ void queryClient.invalidateQueries({ queryKey: intermediatesKeys.all });
+ }, [queryClient]);
+
+ const selectedScope = resolveScope({ hasSearch, loadedRows: rows, ownerId, selection: effectiveSelection });
+ const hasSelection = !isSelectionEmpty(effectiveSelection);
+ const pageSelection = getPageSelectionState(effectiveSelection, rows);
+ const filteredOwnerRow = ownerFilter ? rows[0] : undefined;
+ const hasPreviousPage = offset > 0;
+ const hasNextPage = query.data !== undefined && offset + rows.length < query.data.total;
+ const showPagination = offset > 0 || (query.data?.total ?? 0) > INTERMEDIATES_PAGE_SIZE;
+
+ return (
+ <Stack gap="3" h="full" minH="0">
+ <HStack align="flex-start" gap="3" justify="space-between">
+ <Stack gap="0.5" minW="0">
+ <Text fontSize="sm" fontWeight="600">
+ {t('intermediates.title')}
+ </Text>
+ <Text color="fg.muted" fontSize="xs">
+ {t('intermediates.description')}
+ </Text>
+ </Stack>
+ <Tooltip content={t('intermediates.refresh')}>
+ <IconButton
+ aria-label={t('intermediates.refresh')}
+ disabled={query.isFetching}
+ flexShrink={0}
+ size="xs"
+ variant="outline"
+ onClick={handleRefresh}
+ >
+ <RefreshCwIcon />
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ <HStack gap="2">
+ <InputGroup flex="1" startElement={SEARCH_ICON}>
+ <Input
+ ref={searchRef}
+ aria-label={t('intermediates.searchLabel')}
+ placeholder={
+ canClearOthersIntermediates
+ ? t('intermediates.searchPlaceholderAdmin')
+ : t('intermediates.searchPlaceholder')
+ }
+ size="xs"
+ value={search}
+ onChange={(event) => handleSearchChange(event.currentTarget.value)}
+ />
+ </InputGroup>
+ {ownerFilter ? (
+ <Badge flexShrink={0} fontSize="2xs" gap="1" pe="0.5" variant="surface">
+ {t('intermediates.owner.filtered', {
+ name: filteredOwnerRow ? getOwnerLabel(filteredOwnerRow) : ownerFilter,
+ })}
+ <Tooltip content={t('intermediates.owner.showEveryone')}>
+ <IconButton
+ aria-label={t('intermediates.owner.showEveryone')}
+ minW="4"
+ size="2xs"
+ variant="ghost"
+ onClick={clearOwnerFilter}
+ >
+ <Icon as={XIcon} boxSize="3" />
+ </IconButton>
+ </Tooltip>
+ </Badge>
+ ) : null}
+ </HStack>
+ {activeOperationId ? (
+ <OperationPanel
+ isLoading={operationQuery.isPending}
+ isRetrying={isRetrying}
+ operation={operationQuery.data ?? null}
+ retryError={retryError}
+ onDismiss={dismissOperation}
+ onRetry={() => void handleRetry()}
+ />
+ ) : null}
+ <Stack flex="1" gap="0" minH="0" mt="-3">
+ {/* Keep the bar mounted so a selection never shifts the rows beneath it. */}
+ <HStack borderBottomWidth="1px" borderColor="border.subtle" flexShrink={0} gap="2" minH="8" py="1.5">
+ <Checkbox.Root
+ aria-label={t('intermediates.list.selectAll')}
+ checked={pageSelection === 'all' ? true : pageSelection === 'some' ? 'indeterminate' : false}
+ colorPalette="accent"
+ disabled={rows.length === 0}
+ size="xs"
+ onCheckedChange={handleToggleAll}
+ pl="2"
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label color="fg.muted" fontSize="2xs" fontWeight="600">
+ {t('intermediates.list.selectAll')}
+ </Checkbox.Label>
+ </Checkbox.Root>
+ <Text color="fg.muted" flex="1" fontSize="2xs" minW="0" textAlign="end" truncate>
+ {hasSelection
+ ? t('intermediates.selection.estimate', {
+ count: selectionSummary.rows,
+ images: t('intermediates.counts.images', { count: selectionSummary.safeImages }),
+ size: formatBytes(selectionSummary.reclaimableBytes),
+ videos: t('intermediates.counts.videos', { count: selectionSummary.safeVideos }),
+ })
+ : totals
+ ? t('intermediates.selection.available', {
+ images: t('intermediates.counts.images', { count: totals.safeImages }),
+ size: formatBytes(totals.reclaimableBytes),
+ videos: t('intermediates.counts.videos', { count: totals.safeVideos }),
+ })
+ : ''}
+ </Text>
+ {query.data?.measuring ? (
+ <Tooltip content={t('intermediates.stats.measuringNote')}>
+ <Spinner aria-label={t('intermediates.stats.measuringNote')} color="fg.muted" size="xs" />
+ </Tooltip>
+ ) : null}
+ <Separator borderColor="border.subtle" h="4" orientation="vertical" />
+ <Button
+ colorPalette="red"
+ disabled={!hasSelection}
+ size="2xs"
+ variant="ghost"
+ onClick={(event) => openDialog(selectedScope, event.currentTarget)}
+ >
+ <Icon as={Trash2Icon} boxSize="3" />
+ {t('intermediates.list.delete')}
+ </Button>
+ </HStack>
+ {query.isPending ? (
+ <Center flex="1" minH="32">
+ <Spinner color="fg.subtle" size="sm" />
+ </Center>
+ ) : query.isError ? (
+ <Center flex="1" px="4">
+ <EmptyState
+ danger
+ description={getApiErrorMessage(query.error, t('intermediates.errors.couldNotLoad'))}
+ title={t('intermediates.errors.couldNotLoad')}
+ >
+ <Button size="xs" variant="outline" onClick={() => void query.refetch()}>
+ {t('common.retry')}
+ </Button>
+ </EmptyState>
+ </Center>
+ ) : rows.length === 0 ? (
+ <Center flex="1" px="4">
+ <EmptyState
+ description={
+ hasSearch ? t('intermediates.empty.noMatchesDescription') : t('intermediates.empty.description')
+ }
+ icon={<Icon as={hasSearch ? SearchIcon : BrushCleaningIcon} />}
+ title={hasSearch ? t('intermediates.empty.noMatches') : t('intermediates.empty.title')}
+ >
+ {hasSearch ? (
+ <Button size="xs" variant="outline" onClick={() => handleSearchChange('')}>
+ {t('common.clearSearch')}
+ </Button>
+ ) : null}
+ </EmptyState>
+ </Center>
+ ) : (
+ <Scrollable flex="1" h="full" label={t('intermediates.title')} minH="0">
+ <Box py="1">
+ <IntermediatesList
+ isSelected={(row) => isRowSelected(effectiveSelection, row)}
+ rows={rows}
+ showOwner={canClearOthersIntermediates && ownerId === null}
+ onToggleRow={handleToggleRow}
+ />
+ </Box>
+ </Scrollable>
+ )}
+ {showPagination ? (
+ <HStack borderColor="border.subtle" borderTopWidth="1px" flexShrink={0} justify="center" minH="8">
+ <Button
+ aria-label={t('common.previousPage')}
+ disabled={!hasPreviousPage || query.isFetching}
+ size="2xs"
+ variant="ghost"
+ onClick={() => setOffset((current) => Math.max(0, current - INTERMEDIATES_PAGE_SIZE))}
+ >
+ {t('common.previousPage')}
+ </Button>
+ <Text aria-live="polite" color="fg.muted" fontSize="2xs">
+ {t('common.pageNumber', { page: Math.floor(offset / INTERMEDIATES_PAGE_SIZE) + 1 })}
+ </Text>
+ <Button
+ aria-label={t('common.nextPage')}
+ disabled={!hasNextPage || query.isFetching}
+ size="2xs"
+ variant="ghost"
+ onClick={() => setOffset((current) => current + INTERMEDIATES_PAGE_SIZE)}
+ >
+ {t('common.nextPage')}
+ </Button>
+ </HStack>
+ ) : null}
+ </Stack>
+ <ClearDialog
+ fallbackFocusRef={searchRef}
+ finalFocusRef={dialogTriggerRef}
+ state={dialog}
+ onClose={closeDialog}
+ onConfirm={() => void confirmDialog()}
+ onModeChange={changeMode}
+ onRetryPreview={retryPreview}
+ />
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesSettingsField.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesSettingsField.tsx
new file mode 100644
index 0000000000..3290ba8ada
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/IntermediatesSettingsField.tsx
@@ -0,0 +1,19 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { Box } from '@chakra-ui/react';
+import { useAuthSession, useCapabilities } from '@features/identity';
+
+import { IntermediatesManager } from './IntermediatesManager';
+
+/** The Settings section body: a filling editor that owns its own scrolling. */
+export const IntermediatesSettingsField = (_props: SettingFieldProps) => {
+ const session = useAuthSession();
+ const { canClearOthersIntermediates } = useCapabilities();
+ const currentUserId = session.phase === 'ready' ? (session.user?.user_id ?? null) : null;
+
+ return (
+ <Box display="flex" flex="1" flexDirection="column" minH="0">
+ <IntermediatesManager canClearOthersIntermediates={canClearOthersIntermediates} currentUserId={currentUserId} />
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx b/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
new file mode 100644
index 0000000000..6b0d886741
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/OperationPanel.tsx
@@ -0,0 +1,142 @@
+import type { IntermediatesOperation } from '@features/intermediates/core/types';
+
+import { Alert, HStack, Progress, Stack, Text } from '@chakra-ui/react';
+import {
+ getOperationProcessed,
+ getOperationTotalTargets,
+ isOperationRetryable,
+ isOperationSettled,
+} from '@features/intermediates/core/types';
+import { Button } from '@platform/ui/Button';
+import { useTranslation } from 'react-i18next';
+
+import { formatBytes, formatCount } from './format';
+
+export interface OperationPanelProps {
+ operation: IntermediatesOperation | null;
+ isLoading: boolean;
+ retryError: string | null;
+ isRetrying: boolean;
+ onRetry: () => void;
+ onDismiss: () => void;
+}
+
+const Stat = ({ label, value }: { label: string; value: string }) => (
+ <Stack gap="0" minW="4rem">
+ <Text fontSize="xs" fontVariantNumeric="tabular-nums" fontWeight="600" lineHeight="shorter">
+ {value}
+ </Text>
+ <Text color="fg.muted" fontSize="2xs" lineHeight="shorter">
+ {label}
+ </Text>
+ </Stack>
+);
+
+/** The active or most recent cleanup: progress while it runs, a breakdown once it stops, retry for what failed. */
+export const OperationPanel = ({
+ isLoading,
+ isRetrying,
+ onDismiss,
+ onRetry,
+ operation,
+ retryError,
+}: OperationPanelProps) => {
+ const { t } = useTranslation();
+
+ if (!operation) {
+ return isLoading ? (
+ <Text color="fg.muted" fontSize="xs">
+ {t('intermediates.operation.pending')}
+ </Text>
+ ) : null;
+ }
+
+ const total = getOperationTotalTargets(operation);
+ const processed = getOperationProcessed(operation);
+ const settled = isOperationSettled(operation);
+ const { progress } = operation;
+ const statusLabel = t(`intermediates.operation.status.${operation.status}`);
+ const failed = progress.failedImages + progress.failedVideos;
+
+ return (
+ <Alert.Root
+ aria-live="polite"
+ role="status"
+ size="sm"
+ status={operation.status === 'failed' ? 'error' : operation.status === 'completed' ? 'success' : 'info'}
+ variant="surface"
+ >
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Title>{statusLabel}</Alert.Title>
+ <Alert.Description asChild>
+ <Stack gap="2" mt="1">
+ {settled ? null : (
+ <Stack gap="1">
+ <Progress.Root
+ aria-label={statusLabel}
+ colorPalette="accent"
+ max={Math.max(total, 1)}
+ size="xs"
+ value={processed}
+ >
+ <Progress.Track>
+ <Progress.Range />
+ </Progress.Track>
+ </Progress.Root>
+ <Text color="fg.muted" fontSize="2xs">
+ {t('intermediates.operation.progress', { done: formatCount(processed), total: formatCount(total) })}
+ </Text>
+ </Stack>
+ )}
+ {operation.error ? (
+ <Text fontSize="xs" fontWeight="600">
+ {operation.error}
+ </Text>
+ ) : null}
+ <HStack gap="5" wrap="wrap">
+ <Stat
+ label={t('intermediates.operation.deleted')}
+ value={formatCount(progress.deletedImages + progress.deletedVideos)}
+ />
+ <Stat
+ label={t('intermediates.operation.retained')}
+ value={formatCount(progress.retainedImages + progress.retainedVideos)}
+ />
+ <Stat label={t('intermediates.operation.failed')} value={formatCount(failed)} />
+ {progress.pendingDiskCleanup > 0 ? (
+ <Stat
+ label={t('intermediates.operation.pendingDisk')}
+ value={formatCount(progress.pendingDiskCleanup)}
+ />
+ ) : null}
+ <Stat label={t('intermediates.operation.reclaimed')} value={formatBytes(progress.reclaimedBytes)} />
+ </HStack>
+ {progress.pendingDiskCleanup > 0 ? (
+ <Text color="fg.muted" fontSize="2xs">
+ {t('intermediates.operation.pendingDiskNote')}
+ </Text>
+ ) : null}
+ {retryError ? (
+ <Text color="fg.error" fontSize="xs" role="alert">
+ {retryError}
+ </Text>
+ ) : null}
+ {settled ? (
+ <HStack gap="2">
+ {isOperationRetryable(operation) ? (
+ <Button loading={isRetrying} size="2xs" variant="outline" onClick={onRetry}>
+ {t('intermediates.operation.retry')}
+ </Button>
+ ) : null}
+ <Button size="2xs" variant="ghost" onClick={onDismiss}>
+ {t('intermediates.operation.dismiss')}
+ </Button>
+ </HStack>
+ ) : null}
+ </Stack>
+ </Alert.Description>
+ </Alert.Content>
+ </Alert.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/intermediates/ui/format.ts b/invokeai/frontend/webv2/src/features/intermediates/ui/format.ts
new file mode 100644
index 0000000000..c7e2323526
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/intermediates/ui/format.ts
@@ -0,0 +1,20 @@
+const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;
+
+/** Binary units, one decimal from KB up, so a summary card and a confirmation quote the same figure. */
+export const formatBytes = (bytes: number): string => {
+ if (!Number.isFinite(bytes) || bytes < 1) {
+ return '0 B';
+ }
+
+ let value = bytes;
+ let unit = 0;
+
+ while (value >= 1024 && unit < UNITS.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+
+ return unit === 0 ? `${Math.round(value)} B` : `${value.toFixed(1)} ${UNITS[unit]}`;
+};
+
+export const formatCount = (count: number): string => new Intl.NumberFormat().format(count);
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
index eee30909a4..89a29b85b4 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
@@ -1,11 +1,13 @@
import { Box, Flex, VisuallyHidden, type SystemStyleObject } from '@chakra-ui/react';
import { FontsPage } from '@features/fonts/launchpad';
import { useCapabilities, UsersPage } from '@features/identity';
+import { requestIntermediatesFocus } from '@features/intermediates';
import { ModelsPage } from '@features/models';
import { NodesPage } from '@features/nodes';
import { Tabs } from '@platform/ui';
import { useLocation, useNavigate } from '@tanstack/react-router';
import { LaunchpadCommandPalette } from '@workbench/palette/LaunchpadCommandPalette';
+import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
import { BlocksIcon, BoxIcon, FolderIcon, HouseIcon, TypeIcon, UsersIcon, type LucideIcon } from 'lucide-react';
import { useCallback, useMemo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -74,6 +76,11 @@ const getActiveSectionId = (
? requestedSectionId
: DEFAULT_SECTION_ID;
+const manageIntermediatesOf = (userId: string): void => {
+ requestIntermediatesFocus({ ownerId: userId });
+ openWorkbenchSettings('intermediates');
+};
+
export const Launchpad = () => {
const { canManageModels, canManageNodes, canManageUsers } = useCapabilities();
const { t } = useTranslation();
@@ -125,7 +132,7 @@ export const Launchpad = () => {
icon: UsersIcon,
id: 'users',
label: t('launchpad.sections.users'),
- render: () => <UsersPage />,
+ render: () => <UsersPage onManageIntermediates={manageIntermediatesOf} />,
},
] satisfies (LaunchpadSection & { condition?: boolean })[]
).filter((section) => section.condition ?? true),
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
index 45bf51ccbd..688e1243ec 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenu.tsx
@@ -1,7 +1,16 @@
import { Icon, Menu } from '@chakra-ui/react';
import { MenuContent } from '@platform/ui/Menu';
import { Link } from '@tanstack/react-router';
-import { ArrowRightIcon, CopyIcon, FileDownIcon, PencilIcon, PinIcon, PinOffIcon, Trash2Icon } from 'lucide-react';
+import {
+ ArrowRightIcon,
+ BrushCleaningIcon,
+ CopyIcon,
+ FileDownIcon,
+ PencilIcon,
+ PinIcon,
+ PinOffIcon,
+ Trash2Icon,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
/**
@@ -11,6 +20,7 @@ import { useTranslation } from 'react-i18next';
export const ProjectActionsMenuBody = ({
isCompatible,
isPinned,
+ onClearIntermediates,
onDelete,
onDuplicate,
onExport,
@@ -21,6 +31,7 @@ export const ProjectActionsMenuBody = ({
isCompatible: boolean;
isPinned: boolean;
projectSearch: { project: string };
+ onClearIntermediates: () => void;
onDelete: () => void;
onDuplicate: () => void;
onExport: () => void;
@@ -61,6 +72,10 @@ export const ProjectActionsMenuBody = ({
<Icon as={FileDownIcon} boxSize="3.5" />
{t('common.export')}
</Menu.Item>
+ <Menu.Item value="intermediates" onClick={onClearIntermediates}>
+ <Icon as={BrushCleaningIcon} boxSize="3.5" />
+ {t('projects.clearIntermediates')}
+ </Menu.Item>
<Menu.Separator />
<Menu.Item data-danger="" value="delete" onClick={onDelete}>
<Icon as={Trash2Icon} boxSize="3.5" />
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx
index 40d7abb15b..9cbd61f61a 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx
@@ -2,9 +2,11 @@ import type { ProjectSummary } from '@workbench/projects/library';
import type { MouseEvent, ReactNode } from 'react';
import { Menu, Portal } from '@chakra-ui/react';
+import { requestIntermediatesFocus } from '@features/intermediates';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
import { RenameDialog } from '@platform/ui/RenameDialog';
import { isProjectSummaryCompatible } from '@workbench/projects/library';
+import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -207,6 +209,12 @@ const HostedProjectActionsMenu = ({
() => onRequestDialog({ actions, kind: 'rename', name: request.summary.name }),
[actions, onRequestDialog, request.summary.name]
);
+ const handleClearIntermediates = useCallback(() => {
+ // The manager lives in Settings; it reads this intent once when its section mounts.
+ requestIntermediatesFocus({ projectId: request.summary.id });
+ openWorkbenchSettings('intermediates', request.returnFocus ?? undefined);
+ onClose();
+ }, [onClose, request.returnFocus, request.summary.id]);
const handleDelete = useCallback(
() => onRequestDialog({ actions, kind: 'delete', name: request.summary.name }),
[actions, onRequestDialog, request.summary.name]
@@ -223,6 +231,7 @@ const HostedProjectActionsMenu = ({
isPinned={request.isPinned}
isCompatible={isCompatible}
projectSearch={projectSearch}
+ onClearIntermediates={handleClearIntermediates}
onDelete={handleDelete}
onDuplicate={handleDuplicate}
onExport={handleExport}
diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
index f58c30ee5c..573fd1d9a9 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
@@ -11,7 +11,7 @@ import { previewSwatches, THEMES, type ThemeDefinition } from '@theme/system';
import { areLoggingPreferencesDefault, resetLoggingPreferences } from '@workbench/diagnostics/loggingPreferences';
import { clearAllWorkbenchData } from '@workbench/projects/syncedPersistence';
import { useOptionalWorkbenchCommands, useOptionalWorkbenchPersistenceService } from '@workbench/WorkbenchContext';
-import { CheckIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';
+import { BrushCleaningIcon, CheckIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';
import { useCallback, useMemo, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,6 +20,7 @@ import { clearWorkspaceData, rememberWorkspaceClearFailure } from './clearWorksp
import { GenerationDevicesSettings } from './GenerationDevicesSettings';
import { HotkeysSettingsSection } from './HotkeysSettingsSection';
import { ImageMapVocabularySettings } from './ImageMapVocabularySettings';
+import { setWorkbenchSettingsSection } from './settingsDialogStore';
import {
clearWorkbenchSettings,
DEFAULT_PREFERENCES,
@@ -159,6 +160,7 @@ export const LoggingResetSettings = () => {
};
export const WorkspaceSettings = () => {
+ const { t } = useTranslation();
const commands = useOptionalWorkbenchCommands();
const mountedPersistence = useOptionalWorkbenchPersistenceService();
const scope = useWorkbenchSettingsSelector((snapshot) => snapshot.scope);
@@ -183,6 +185,7 @@ export const WorkspaceSettings = () => {
const resetLayout = useCallback(() => commands?.layout.reset(), [commands]);
const openClearConfirm = useCallback(() => setIsClearConfirmOpen(true), []);
const closeClearConfirm = useCallback(() => setIsClearConfirmOpen(false), []);
+ const openIntermediates = useCallback(() => setWorkbenchSettingsSection('intermediates', 'intermediatesManager'), []);
return (
<Stack gap="3">
@@ -193,6 +196,10 @@ export const WorkspaceSettings = () => {
Reset layout
</Button>
) : null}
+ <Button size="sm" variant="outline" onClick={openIntermediates}>
+ <BrushCleaningIcon />
+ {t('settings.catalog.manageIntermediates')}
+ </Button>
<Button
borderColor="border.emphasized"
color="fg.error"
diff --git a/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
index 0d70b84c0d..f62dce4c4b 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
@@ -1,5 +1,6 @@
import type { SettingDefinition, SettingsContribution, SettingsText } from '@platform/ui/settings/contracts';
+import { intermediatesSettingsContribution } from '@features/intermediates/settingsContribution';
import { WORKBENCH_LANGUAGE_OPTIONS } from '@platform/i18n/languages';
const text =
@@ -146,6 +147,7 @@ export const applicationSettingsContributions = [
developerSettings,
serverSettings,
workspaceSettings,
+ intermediatesSettingsContribution,
aboutSettings,
];
/** These are the same descriptors rendered in settings and used by palette preference actions. */
diff --git a/invokeai/frontend/webv2/src/workbench/settings/catalog.ts b/invokeai/frontend/webv2/src/workbench/settings/catalog.ts
index 62a53ebf13..9954f5095b 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/catalog.ts
@@ -7,6 +7,7 @@ import { resolveSettingsText } from '@platform/ui/settings/contracts';
import { createDeferredResource } from '@workbench/deferredResource';
import { firstPartyWidgetManifests } from '@workbench/widgets/manifests';
import {
+ BrushCleaningIcon,
Code2Icon,
DatabaseIcon,
FolderIcon,
@@ -40,6 +41,7 @@ const sectionPresentation = {
developer: { group: 'system', icon: Code2Icon },
server: { group: 'system', icon: ServerIcon },
workspace: { group: 'system', icon: DatabaseIcon },
+ intermediates: { group: 'system', icon: BrushCleaningIcon },
about: { group: 'system', icon: InfoIcon },
} as const;
const groupOrder = ['application', 'project', 'widgets', 'system'];