Skip to content

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

perf(webv2): keep widgets mounted across switches

joshistoast1889d965d8f3
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 206c822fca..67598e9c04 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -25,13 +25,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 114.30000000074506,
+ "domContentLoadedMedianMs": 114.20000000111759,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 114.5,
- "longestTaskMaxMs": 70,
+ "loadMedianMs": 114.30000000074506,
+ "longestTaskMaxMs": 69,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -58,7 +58,7 @@
"scriptRequestCount": 32,
"totalRawBytes": 1790087
},
- "routeReadyMedianMs": 251.39999999850988,
+ "routeReadyMedianMs": 255.80000000074506,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -85,13 +85,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 113.40000000037253,
+ "domContentLoadedMedianMs": 115.5,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 113.40000000037253,
- "longestTaskMaxMs": 70,
+ "loadMedianMs": 115.5,
+ "longestTaskMaxMs": 69,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -118,7 +118,7 @@
"scriptRequestCount": 32,
"totalRawBytes": 1790087
},
- "routeReadyMedianMs": 271,
+ "routeReadyMedianMs": 270.80000000074506,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -145,15 +145,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 113.5,
+ "domContentLoadedMedianMs": 116.5,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 113.59999999962747,
- "longestTaskMaxMs": 91,
+ "loadMedianMs": 116.59999999962747,
+ "longestTaskMaxMs": 94,
"owner": "workbench",
- "projectSwitchMedianMs": 35.899999998509884,
+ "projectSwitchMedianMs": 33.19999999925494,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -163,9 +163,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 109,
- "scriptRawBytes": 3046810,
+ "scriptRawBytes": 3047695,
"scriptRequestCount": 104,
- "totalRawBytes": 3365435
+ "totalRawBytes": 3366320
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -174,11 +174,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 109,
- "scriptRawBytes": 3077279,
+ "scriptRawBytes": 3078172,
"scriptRequestCount": 104,
- "totalRawBytes": 3399090
+ "totalRawBytes": 3399984
},
- "routeReadyMedianMs": 645.5999999996275,
+ "routeReadyMedianMs": 650.1999999992549,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -205,15 +205,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 112,
+ "domContentLoadedMedianMs": 116.60000000149012,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 112.09999999962747,
- "longestTaskMaxMs": 190,
+ "loadMedianMs": 116.80000000074506,
+ "longestTaskMaxMs": 187,
"owner": "workbench",
- "projectSwitchMedianMs": 51.70000000111759,
+ "projectSwitchMedianMs": 53.69999999925494,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -223,9 +223,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 109,
- "scriptRawBytes": 3046810,
+ "scriptRawBytes": 3047695,
"scriptRequestCount": 104,
- "totalRawBytes": 3365435
+ "totalRawBytes": 3366320
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -234,11 +234,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 109,
- "scriptRawBytes": 3077279,
+ "scriptRawBytes": 3078172,
"scriptRequestCount": 104,
- "totalRawBytes": 3399090
+ "totalRawBytes": 3399984
},
- "routeReadyMedianMs": 433.09999999962747,
+ "routeReadyMedianMs": 434.90000000037253,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -265,13 +265,13 @@
"scriptRequestCount": 6,
"totalRawBytes": 287337
},
- "domContentLoadedMedianMs": 110.29999999888241,
+ "domContentLoadedMedianMs": 115.79999999888241,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.199999999254942,
- "layoutReturnSwitchMedianMs": 41.69999999925494,
- "layoutSwitchMedianMs": 68.79999999888241,
- "loadMedianMs": 110.39999999850988,
- "longestTaskMaxMs": 93,
+ "layoutAckMedianMs": 2.300000000745058,
+ "layoutReturnSwitchMedianMs": 37.399999998509884,
+ "layoutSwitchMedianMs": 72.19999999925494,
+ "loadMedianMs": 115.90000000037253,
+ "longestTaskMaxMs": 96,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -283,9 +283,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 115,
- "scriptRawBytes": 3331302,
+ "scriptRawBytes": 3332187,
"scriptRequestCount": 110,
- "totalRawBytes": 3649927
+ "totalRawBytes": 3650812
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -294,11 +294,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 115,
- "scriptRawBytes": 3364616,
+ "scriptRawBytes": 3365509,
"scriptRequestCount": 110,
- "totalRawBytes": 3686427
+ "totalRawBytes": 3687321
},
- "routeReadyMedianMs": 989.3999999985099,
+ "routeReadyMedianMs": 995.6999999992549,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -325,13 +325,13 @@
"scriptRequestCount": 6,
"totalRawBytes": 287337
},
- "domContentLoadedMedianMs": 111.90000000037253,
+ "domContentLoadedMedianMs": 111.10000000149012,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.399999998509884,
- "layoutReturnSwitchMedianMs": 145.59999999962747,
- "layoutSwitchMedianMs": 173.5,
- "loadMedianMs": 112,
- "longestTaskMaxMs": 332,
+ "layoutAckMedianMs": 2.400000000372529,
+ "layoutReturnSwitchMedianMs": 34.79999999888241,
+ "layoutSwitchMedianMs": 174.7999999988824,
+ "loadMedianMs": 111.30000000074506,
+ "longestTaskMaxMs": 340,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -343,9 +343,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 115,
- "scriptRawBytes": 3331302,
+ "scriptRawBytes": 3332187,
"scriptRequestCount": 110,
- "totalRawBytes": 3649927
+ "totalRawBytes": 3650812
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -354,11 +354,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 115,
- "scriptRawBytes": 3364616,
+ "scriptRawBytes": 3365509,
"scriptRequestCount": 110,
- "totalRawBytes": 3686427
+ "totalRawBytes": 3687321
},
- "routeReadyMedianMs": 1174.4000000003725,
+ "routeReadyMedianMs": 1181,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -385,13 +385,13 @@
"scriptRequestCount": 7,
"totalRawBytes": 361200
},
- "domContentLoadedMedianMs": 106.80000000074506,
+ "domContentLoadedMedianMs": 109.59999999962747,
"id": "editor-workflow",
- "layoutAckMedianMs": 1.900000000372529,
- "layoutReturnSwitchMedianMs": 43.899999998509884,
- "layoutSwitchMedianMs": 81.79999999888241,
- "loadMedianMs": 106.90000000037253,
- "longestTaskMaxMs": 85,
+ "layoutAckMedianMs": 2.200000001117587,
+ "layoutReturnSwitchMedianMs": 31.5,
+ "layoutSwitchMedianMs": 83.59999999962747,
+ "loadMedianMs": 109.69999999925494,
+ "longestTaskMaxMs": 88,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -403,9 +403,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 117,
- "scriptRawBytes": 3389020,
+ "scriptRawBytes": 3389905,
"scriptRequestCount": 111,
- "totalRawBytes": 3723058
+ "totalRawBytes": 3723943
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -414,11 +414,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 117,
- "scriptRawBytes": 3422911,
+ "scriptRawBytes": 3423805,
"scriptRequestCount": 111,
- "totalRawBytes": 3760289
+ "totalRawBytes": 3761183
},
- "routeReadyMedianMs": 999.8000000007451,
+ "routeReadyMedianMs": 1010.4000000003725,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -445,13 +445,13 @@
"scriptRequestCount": 7,
"totalRawBytes": 361200
},
- "domContentLoadedMedianMs": 108.09999999962747,
+ "domContentLoadedMedianMs": 110.59999999962747,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.299999998882413,
- "layoutReturnSwitchMedianMs": 78.30000000074506,
- "layoutSwitchMedianMs": 128,
- "loadMedianMs": 108.19999999925494,
- "longestTaskMaxMs": 335,
+ "layoutAckMedianMs": 2.300000000745058,
+ "layoutReturnSwitchMedianMs": 40,
+ "layoutSwitchMedianMs": 128.80000000074506,
+ "loadMedianMs": 110.69999999925494,
+ "longestTaskMaxMs": 338,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -463,9 +463,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 117,
- "scriptRawBytes": 3389020,
+ "scriptRawBytes": 3389905,
"scriptRequestCount": 111,
- "totalRawBytes": 3723058
+ "totalRawBytes": 3723943
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -474,11 +474,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 117,
- "scriptRawBytes": 3422911,
+ "scriptRawBytes": 3423805,
"scriptRequestCount": 111,
- "totalRawBytes": 3760289
+ "totalRawBytes": 3761183
},
- "routeReadyMedianMs": 1133.5,
+ "routeReadyMedianMs": 1139.9000000003725,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -505,13 +505,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 108.30000000074506,
+ "domContentLoadedMedianMs": 111.59999999962747,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 24.90000000037253,
- "loadMedianMs": 108.40000000037253,
- "longestTaskMaxMs": 88,
+ "layoutSwitchMedianMs": 24.59999999962747,
+ "loadMedianMs": 111.80000000074506,
+ "longestTaskMaxMs": 87,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -523,9 +523,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 109,
- "scriptRawBytes": 3046810,
+ "scriptRawBytes": 3047695,
"scriptRequestCount": 104,
- "totalRawBytes": 3365435
+ "totalRawBytes": 3366320
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -534,11 +534,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 109,
- "scriptRawBytes": 3077279,
+ "scriptRawBytes": 3078172,
"scriptRequestCount": 104,
- "totalRawBytes": 3399090
+ "totalRawBytes": 3399984
},
- "routeReadyMedianMs": 1209,
+ "routeReadyMedianMs": 1215,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -565,13 +565,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 104.79999999888241,
+ "domContentLoadedMedianMs": 113.19999999925494,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 84.5,
- "loadMedianMs": 104.90000000037253,
- "longestTaskMaxMs": 170,
+ "layoutSwitchMedianMs": 85.59999999962747,
+ "loadMedianMs": 113.29999999888241,
+ "longestTaskMaxMs": 163,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -583,9 +583,9 @@
"largestAssetRawBytes": 746305,
"otherRawBytes": 136426,
"requestCount": 109,
- "scriptRawBytes": 3046810,
+ "scriptRawBytes": 3047695,
"scriptRequestCount": 104,
- "totalRawBytes": 3365435
+ "totalRawBytes": 3366320
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -594,11 +594,11 @@
"largestAssetRawBytes": 753769,
"otherRawBytes": 137791,
"requestCount": 109,
- "scriptRawBytes": 3077279,
+ "scriptRawBytes": 3078172,
"scriptRequestCount": 104,
- "totalRawBytes": 3399090
+ "totalRawBytes": 3399984
},
- "routeReadyMedianMs": 1393.2999999988824,
+ "routeReadyMedianMs": 1394.2999999988824,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1713,6 +1713,7 @@
"source:src/workbench/shell/topbar/useInvocationState.ts",
"source:src/workbench/shell/topbar/useLayoutDrift.ts",
"source:src/workbench/shell/topbar/useTopbarShortcut.ts",
+ "source:src/workbench/shell/useMountedInstanceIds.ts",
"source:src/workbench/useNotify.ts",
"source:src/workbench/useOpenWorkbenchWidget.ts",
"source:src/workbench/widget-frame/FloatingWidgetLayer.tsx",
@@ -2609,6 +2610,7 @@
"source:src/workbench/shell/topbar/useInvocationState.ts",
"source:src/workbench/shell/topbar/useLayoutDrift.ts",
"source:src/workbench/shell/topbar/useTopbarShortcut.ts",
+ "source:src/workbench/shell/useMountedInstanceIds.ts",
"source:src/workbench/useCanvasProjectMutationDispatch.ts",
"source:src/workbench/useNotify.ts",
"source:src/workbench/useOpenWorkbenchWidget.ts",
@@ -3661,6 +3663,7 @@
"source:src/workbench/shell/topbar/useInvocationState.ts",
"source:src/workbench/shell/topbar/useLayoutDrift.ts",
"source:src/workbench/shell/topbar/useTopbarShortcut.ts",
+ "source:src/workbench/shell/useMountedInstanceIds.ts",
"source:src/workbench/useNotify.ts",
"source:src/workbench/useOpenWorkbenchWidget.ts",
"source:src/workbench/widget-frame/FloatingWidgetLayer.tsx",
diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
index 4445b367db..78d4bf29c5 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
@@ -15,6 +15,7 @@ import {
useWidgetIntentPreloadProps,
type WidgetEnableMenuItem,
} from '@workbench/widget-frame';
+import { areWidgetRenderInstancesEqual } from '@workbench/widget-frame/widgetRenderInstance';
import { resolveWidgetLabel } from '@workbench/widgetLabels';
import { closeWidgetPlacement, openWidgetPlacement, revealWidgetPlacement } from '@workbench/widgetPlacementCommands';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
@@ -26,9 +27,11 @@ import {
import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { CheckIcon, ChevronDownIcon, XIcon } from 'lucide-react';
-import { Suspense, useCallback, useMemo, useRef, type ReactNode } from 'react';
+import { Activity, Suspense, useCallback, useMemo, useRef, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
+import { useMountedInstanceIds } from './useMountedInstanceIds';
+
type CenterWidgetItem = PlacedWidgetRegionItem<WidgetPlacementInstanceMeta>;
const CENTER_MENU_POSITIONING = { placement: 'bottom-start' } as const;
@@ -75,6 +78,7 @@ export const CenterArea = () => {
? centerRegion.activeInstanceId
: centerViewItems[0]?.id;
const activeItem = centerViewItems.find((item) => item.id === activeCenterViewId);
+ const mountedCenterIds = useMountedInstanceIds(activeCenterViewId);
const focusRegionProps = useFocusRegionProps('center');
const openCenterWidget = useCallback(
@@ -136,7 +140,15 @@ export const CenterArea = () => {
>
<Box flex="1" minH="0" position="relative">
<Box aria-label={t('widgets.centerRegion')} h="full" role="region">
- {activeItem ? <CenterViewSlot item={activeItem} /> : <FallbackCenterView label="Center widget unavailable" />}
+ {mountedCenterIds.length > 0 ? (
+ mountedCenterIds.map((instanceId) => (
+ <Activity key={instanceId} mode={instanceId === activeCenterViewId ? 'visible' : 'hidden'}>
+ <KeptCenterViewSlot instanceId={instanceId} />
+ </Activity>
+ ))
+ ) : (
+ <FallbackCenterView label="Center widget unavailable" />
+ )}
</Box>
<Flex
@@ -347,14 +359,25 @@ const CenterViewMenuRow = ({
);
};
-const CenterViewSlot = ({ item }: { item: CenterWidgetItem }) => {
- if (item.widget.status !== 'enabled') {
+/**
+ * One kept center view. It resolves its own instance and widget rather than
+ * taking a region view-model item: a kept instance is by definition no longer
+ * in the region's item list, because applying a preset replaces `instanceIds`
+ * wholesale. `applyLayoutPresetToProject` merges `widgetInstances`, so the
+ * instance itself survives and can still be resolved here.
+ */
+const KeptCenterViewSlot = ({ instanceId }: { instanceId: string }) => {
+ const instance = useActiveProjectSelector(
+ (project) => project.widgetInstances[instanceId],
+ areWidgetRenderInstancesEqual
+ );
+ const widget = instance ? getWidgetById(instance.typeId) : undefined;
+
+ if (!instance || !widget || widget.status !== 'enabled') {
return <FallbackCenterView label="Center widget unavailable" />;
}
- return (
- <WidgetRendererById key={item.instance.id} instanceId={item.instance.id} widget={item.widget} region="center" />
- );
+ return <WidgetRendererById instanceId={instance.id} widget={widget} region="center" />;
};
const FallbackCenterView = ({ label }: { label: string }) => (
diff --git a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx
index 1f8365d33d..a58a59daec 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx
@@ -5,8 +5,11 @@ import { areWidgetRenderInstancesEqual } from '@workbench/widget-frame/widgetRen
import { resolveWidgetLabel } from '@workbench/widgetLabels';
import { getWidgetById } from '@workbench/widgetRegistry';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { Activity } from 'react';
import { useTranslation } from 'react-i18next';
+import { useMountedInstanceIds } from './useMountedInstanceIds';
+
/** Left panel — hosts the active registered widget panel view. */
export const LeftPanel = ({ instanceId }: { instanceId: WidgetInstanceId }) => (
<WidgetPanelSlot instanceId={instanceId} panel="leftPanel" />
@@ -22,7 +25,33 @@ const panelRegions = {
rightPanel: 'right',
} as const satisfies Record<string, WorkbenchRegion>;
+/**
+ * Keeps the panel widgets this session has already shown mounted behind the
+ * active one, so switching a layout preset hides them rather than destroying
+ * their scroll position, selection and virtualizer state. The remembered set is
+ * independent of the region's `instanceIds`, which a preset replaces wholesale.
+ */
const WidgetPanelSlot = ({ instanceId, panel }: { instanceId: WidgetInstanceId; panel: keyof typeof panelRegions }) => {
+ const mountedIds = useMountedInstanceIds(instanceId);
+
+ return (
+ <>
+ {mountedIds.map((id) => (
+ <Activity key={id} mode={id === instanceId ? 'visible' : 'hidden'}>
+ <WidgetPanelInstance instanceId={id as WidgetInstanceId} panel={panel} />
+ </Activity>
+ ))}
+ </>
+ );
+};
+
+const WidgetPanelInstance = ({
+ instanceId,
+ panel,
+}: {
+ instanceId: WidgetInstanceId;
+ panel: keyof typeof panelRegions;
+}) => {
const { t } = useTranslation();
const instance = useActiveProjectSelector(
(project) => project.widgetInstances[instanceId],
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
new file mode 100644
index 0000000000..ece93ca622
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
@@ -0,0 +1,223 @@
+import { Box, ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * A store whose center region is replaced the way `applyLayoutPresetToProject`
+ * replaces it: `instanceIds` is rewritten wholesale, so the outgoing widget is
+ * no longer in the region at all. The widget instances are merged and survive,
+ * which is what the keep-alive set resolves against.
+ */
+const keepAliveMocks = vi.hoisted(() => {
+ const icon = () => null;
+ const widgets: Record<string, { manifest: unknown; status: string }> = {
+ canvas: {
+ manifest: { centerPlacement: 'view', chrome: { header: 'visible' }, icon, id: 'canvas' },
+ status: 'enabled',
+ },
+ workflow: {
+ manifest: { centerPlacement: 'view', chrome: { header: 'visible' }, icon, id: 'workflow' },
+ status: 'enabled',
+ },
+ };
+ const typeIdByInstanceId: Record<string, string> = { canvas: 'canvas', 'workflow:center': 'workflow' };
+ const widgetInstances = {
+ canvas: { createdAt: 1, id: 'canvas', typeId: 'canvas' },
+ 'workflow:center': { createdAt: 1, id: 'workflow:center', typeId: 'workflow' },
+ };
+ const createProject = (activeInstanceId: string) => ({
+ floatingWidgets: [],
+ id: 'test-project',
+ invocation: { sourceId: 'generate' },
+ queue: { items: [] },
+ widgetInstances,
+ widgetRegions: {
+ center: { activeInstanceId, instanceIds: [activeInstanceId], isCollapsed: false, sizePx: 0 },
+ },
+ });
+
+ let project = createProject('canvas');
+ const listeners = new Set<() => void>();
+
+ return {
+ getProject: () => project,
+ getWidgetById: (typeId: string) => widgets[typeId],
+ reset: () => {
+ project = createProject('canvas');
+ },
+ setActiveInstanceId: (activeInstanceId: string) => {
+ project = createProject(activeInstanceId);
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+
+ return () => listeners.delete(listener);
+ },
+ typeIdByInstanceId,
+ widgets,
+ };
+});
+
+vi.mock('@features/models', () => ({ useModelLoads: () => [] }));
+vi.mock('@features/queue/contracts', () => ({
+ getProjectQueueIndicatorState: () => ({ hasOpenQueueWork: false, progressState: null, runningQueueItemId: null }),
+}));
+vi.mock('@features/queue/react', () => ({ useQueueItemProgress: () => null }));
+vi.mock('@workbench/focusRegions', () => ({ useFocusRegionProps: () => ({}) }));
+vi.mock('@workbench/widgetRegionViewModel', () => ({
+ createWidgetRegionViewModelFromState: ({ regionState }: { regionState: { instanceIds: string[] } }) => ({
+ placedItems: regionState.instanceIds.map((instanceId) => {
+ const typeId = keepAliveMocks.typeIdByInstanceId[instanceId] ?? instanceId;
+
+ return {
+ icon: () => null,
+ id: instanceId,
+ instance: { id: instanceId, typeId },
+ label: typeId,
+ status: 'enabled',
+ typeId,
+ widget: keepAliveMocks.widgets[typeId],
+ };
+ }),
+ }),
+ getWidgetRegionItems: () => [],
+ isRequiredCenterView: () => true,
+}));
+vi.mock('@workbench/widgetRegistry', () => ({
+ getWidgetById: (typeId: string) => keepAliveMocks.getWidgetById(typeId),
+ getWidgetsForRegion: () => [],
+}));
+vi.mock('@workbench/WorkbenchContext', async () => {
+ const { useSyncExternalStore } = await import('react');
+
+ return {
+ useActiveProjectSelector: (selector: (project: unknown) => unknown) =>
+ selector(useSyncExternalStore(keepAliveMocks.subscribe, keepAliveMocks.getProject)),
+ useWorkbenchCommands: () => ({ widgets: {} }),
+ useWorkbenchSelector: (selector: (snapshot: { backendConnection: { status: string } }) => unknown) =>
+ selector({ backendConnection: { status: 'connected' } }),
+ };
+});
+vi.mock('@workbench/widget-frame', () => ({
+ WidgetChromeSlotById: () => null,
+ WidgetRendererById: ({ instanceId }: { instanceId: string }) => (
+ <Box
+ data-hotkey-widget-instance-id={instanceId}
+ data-hotkey-widget-type-id={keepAliveMocks.typeIdByInstanceId[instanceId] ?? instanceId}
+ h="full"
+ w="full"
+ />
+ ),
+ WidgetSourceLockBadge: () => null,
+ useWidgetIntentPreloadProps: () => ({}),
+}));
+
+import { CenterArea } from './CenterArea';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: { en: { translation: {} } },
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderCenterArea = async () => {
+ host = document.createElement('div');
+ host.style.cssText = 'display:flex;height:320px;width:571px;';
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(async () => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <CenterArea />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ await Promise.resolve();
+ });
+
+ return {
+ setActiveInstanceId: async (instanceId: string) => {
+ await act(async () => {
+ keepAliveMocks.setActiveInstanceId(instanceId);
+ await Promise.resolve();
+ });
+ },
+ };
+};
+
+const centerWidget = (instanceId: string) =>
+ host?.querySelector<HTMLElement>(`[data-hotkey-widget-instance-id="${instanceId}"]`) ?? null;
+
+afterEach(async () => {
+ await act(async () => {
+ root?.unmount();
+ await Promise.resolve();
+ });
+ host?.remove();
+ host = null;
+ root = null;
+ keepAliveMocks.reset();
+});
+
+describe('preset switch keep-alive', () => {
+ it('keeps a center widget mounted when the layout switches away and back', async () => {
+ const { setActiveInstanceId } = await renderCenterArea();
+ const canvasNode = centerWidget('canvas');
+
+ expect(canvasNode).not.toBeNull();
+ if (!canvasNode) {
+ throw new Error('Expected the canvas center widget to mount.');
+ }
+
+ await setActiveInstanceId('workflow:center');
+
+ // Still in the DOM, still the same element, and hidden rather than destroyed.
+ expect(centerWidget('canvas')).toBe(canvasNode);
+ expect(getComputedStyle(canvasNode).display).toBe('none');
+ expect(getComputedStyle(centerWidget('workflow:center') as Element).display).not.toBe('none');
+
+ await setActiveInstanceId('canvas');
+
+ expect(centerWidget('canvas')).toBe(canvasNode);
+ expect(getComputedStyle(canvasNode).display).not.toBe('none');
+ expect(getComputedStyle(centerWidget('workflow:center') as Element).display).toBe('none');
+ });
+
+ it('leaves a hidden widget out of the tab order', async () => {
+ const { setActiveInstanceId } = await renderCenterArea();
+
+ await setActiveInstanceId('workflow:center');
+
+ const hiddenCanvas = centerWidget('canvas');
+
+ expect(hiddenCanvas).not.toBeNull();
+ // `display: none` takes the subtree out of the accessibility tree, so it is
+ // unreachable by pointer hit-testing and by sequential focus navigation.
+ expect(hiddenCanvas?.getClientRects().length).toBe(0);
+ });
+
+ it('keeps chrome on the live region rather than on the kept widget', async () => {
+ const { setActiveInstanceId } = await renderCenterArea();
+
+ await setActiveInstanceId('workflow:center');
+
+ const chrome = host?.querySelector<HTMLElement>('[data-hotkey-widget-region="center"]');
+
+ expect(chrome?.dataset.hotkeyWidgetInstanceId).toBe('workflow:center');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx
new file mode 100644
index 0000000000..aa03478730
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.browser.test.tsx
@@ -0,0 +1,102 @@
+import { act, useEffect } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { useMountedInstanceIds } from './useMountedInstanceIds';
+
+// `@testing-library/react` is not a dependency of this package, so the hook is
+// driven through a probe component the way the other browser suites here do.
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+/**
+ * The value the probe last produced. Module scope keeps the probe prop-free, and
+ * it is published from an effect so the probe stays render-pure.
+ */
+const latest: { ids: string[] } = { ids: [] };
+
+const Probe = ({ activeId, limit }: { activeId: string | undefined; limit?: number }) => {
+ const ids = useMountedInstanceIds(activeId, limit);
+
+ useEffect(() => {
+ latest.ids = ids;
+ }, [ids]);
+
+ return null;
+};
+
+const renderHook = async (activeId: string | undefined, limit?: number) => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ const rerender = async (nextActiveId: string | undefined) => {
+ await act(async () => {
+ root?.render(<Probe activeId={nextActiveId} limit={limit} />);
+ await Promise.resolve();
+ });
+ };
+
+ await rerender(activeId);
+
+ return { rerender };
+};
+
+afterEach(async () => {
+ await act(async () => {
+ root?.unmount();
+ await Promise.resolve();
+ });
+ host?.remove();
+ host = null;
+ root = null;
+ latest.ids = [];
+});
+
+describe('mounted instance ids', () => {
+ it('remembers instances that have been shown', async () => {
+ const { rerender } = await renderHook('canvas');
+
+ expect(latest.ids).toEqual(['canvas']);
+
+ await rerender('workflow:center');
+ expect(latest.ids).toEqual(['canvas', 'workflow:center']);
+
+ await rerender('canvas');
+ expect(latest.ids).toEqual(['workflow:center', 'canvas']);
+ });
+
+ it('evicts least-recently-shown beyond the limit', async () => {
+ const { rerender } = await renderHook('a', 2);
+
+ await rerender('b');
+ await rerender('c');
+
+ expect(latest.ids).toEqual(['b', 'c']);
+ });
+
+ it('keeps the set stable when the active id does not change', async () => {
+ const { rerender } = await renderHook('canvas');
+ const first = latest.ids;
+
+ await rerender('canvas');
+
+ expect(latest.ids).toBe(first);
+ });
+
+ it('tolerates no active instance', async () => {
+ await renderHook(undefined);
+
+ expect(latest.ids).toEqual([]);
+ });
+
+ it('starts remembering once an instance finally arrives', async () => {
+ const { rerender } = await renderHook(undefined);
+
+ await rerender('canvas');
+
+ expect(latest.ids).toEqual(['canvas']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts
new file mode 100644
index 0000000000..fac1fda9a5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/useMountedInstanceIds.ts
@@ -0,0 +1,34 @@
+import { useState } from 'react';
+
+/**
+ * How many instances a region keeps mounted behind it. A kept canvas holds its
+ * WebGL context and a kept gallery holds its virtualizer, so this is bounded
+ * rather than unlimited; three covers every realistic back-and-forth.
+ */
+export const MOUNTED_INSTANCE_LIMIT = 3;
+
+/**
+ * The instance ids a region keeps mounted, most-recently-shown last.
+ *
+ * Deliberately independent of the region's own `instanceIds`: applying a preset
+ * replaces those wholesale, so a widget the user is switching away from is no
+ * longer in the region at all. Remembering it here is what lets `<Activity>`
+ * hold it — and with it the canvas viewport, gallery scroll and selection that
+ * a full unmount would take.
+ *
+ * Ephemeral by design. A remembered mount is a session affordance, not state
+ * worth persisting.
+ */
+export const useMountedInstanceIds = (activeId: string | undefined, limit = MOUNTED_INSTANCE_LIMIT): string[] => {
+ const [ids, setIds] = useState<string[]>(() => (activeId === undefined ? [] : [activeId]));
+ const next =
+ activeId === undefined || ids.at(-1) === activeId
+ ? ids
+ : [...ids.filter((id) => id !== activeId), activeId].slice(-limit);
+
+ if (next !== ids) {
+ setIds(next);
+ }
+
+ return next;
+};