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): preload boot widgets during hydration and add preset apply deadline

joshistoast823f9c06384d
diff --git a/invokeai/frontend/webv2/src/app/BootWidgetHintController.tsx b/invokeai/frontend/webv2/src/app/BootWidgetHintController.tsx
new file mode 100644
index 0000000000..e64261dfdf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/BootWidgetHintController.tsx
@@ -0,0 +1,20 @@
+import { getBootWidgetTypeIds, writeBootWidgetHint } from '@workbench/bootWidgetPreload';
+import { shallowEqual, useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { useEffect } from 'react';
+
+/**
+ * Persists the active layout's widget set so the next boot can start those
+ * chunk downloads in parallel with project hydration (`preloadBootWidgets`).
+ * Mirrors the theme hint in `ThemeController`: a dedicated key, written after
+ * the store has the real layout, read before anyone knows who is signed in.
+ * Renders nothing.
+ */
+export const BootWidgetHintController = () => {
+ const typeIds = useActiveProjectSelector(getBootWidgetTypeIds, shallowEqual);
+
+ useEffect(() => {
+ writeBootWidgetHint(typeIds);
+ }, [typeIds]);
+
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
index d65e06f65b..efd662b80e 100644
--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
@@ -1,7 +1,9 @@
import type { WorkbenchSearch } from '@workbench/projects/session';
import { LLMTaskProgressRuntime } from '@features/generation/react';
+import { useMountEffect } from '@platform/react/useMountEffect';
import { useSearch } from '@tanstack/react-router';
+import { preloadBootWidgets } from '@workbench/bootWidgetPreload';
import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';
import { WorkbenchCommandPalette } from '@workbench/palette/WorkbenchCommandPalette';
import { WorkbenchShell } from '@workbench/shell';
@@ -13,6 +15,7 @@ import { WorkbenchSessionController } from '@workbench/WorkbenchSessionControlle
import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';
import { useMemo } from 'react';
+import { BootWidgetHintController } from './BootWidgetHintController';
import { GenerateWidgetSyncRuntime } from './GenerateWidgetSyncRuntime';
import { QueueRuntimeAdapter } from './QueueRuntimeAdapter';
import { WorkbenchUiPorts } from './workbenchPorts';
@@ -34,9 +37,15 @@ export const WorkbenchApp = () => {
[search.new, search.project]
);
+ // Start widget chunk downloads now, while project hydration is still in
+ // flight — the provider below withholds the shell until hydration, and
+ // without this the first widget byte doesn't move until after it.
+ useMountEffect(preloadBootWidgets);
+
return (
<WorkbenchProvider loadOptions={loadOptions}>
<WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}>
+ <BootWidgetHintController />
<GenerateWidgetSyncRuntime />
<LLMTaskProgressRuntime />
<WorkbenchUiPorts>
diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsx
index 85d22b99be..64879fefc4 100644
--- a/invokeai/frontend/webv2/src/app/router.tsx
+++ b/invokeai/frontend/webv2/src/app/router.tsx
@@ -160,6 +160,12 @@ const usersHomeRoute = createRoute({
const workbenchRoute = createRoute({
beforeLoad: async ({ cause, search }) => {
+ // Warm the editor bundle while the guard's session peek is in flight. The
+ // module loader dedupes against `lazyRouteComponent`'s own import, so on a
+ // cold deep link the chunk downloads in parallel with the peek instead of
+ // after it.
+ void import('./WorkbenchApp');
+
// Photoshop semantics: the editor without documents is Home. A definite
// empty session redirects unless the URL explicitly asks for a project or
// a fresh draft; an unknowable session (first run, legacy blob, backend
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index c598eaf9c8..8518cecd03 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -86,6 +86,7 @@
"WorkbenchWidgetRegistryContext.tsx": "workbench",
"activeInvocationSubmission.ts": "workbench",
"autoRoutePolicy.ts": "workbench",
+ "bootWidgetPreload.ts": "workbench",
"canvasDimsSync.ts": "workbench",
"canvasLayerContent.ts": "workbench",
"canvasLayerOps.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.test.ts b/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.test.ts
new file mode 100644
index 0000000000..4f51816a15
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getBootWidgetTypeIds, readBootWidgetHint, writeBootWidgetHint } from './bootWidgetPreload';
+import { defaultLayoutPreset } from './layoutPresets';
+
+const storage = new Map<string, string>();
+
+vi.stubGlobal('window', {
+ localStorage: {
+ getItem: (key: string): string | null => storage.get(key) ?? null,
+ setItem: (key: string, value: string): void => {
+ storage.set(key, value);
+ },
+ },
+});
+
+const HINT_KEY = 'invokeai:v7:webv2:boot-widgets';
+
+describe('boot widget preload', () => {
+ it('derives the default layout boot set: active instances plus every bottom item', () => {
+ const typeIds = getBootWidgetTypeIds(defaultLayoutPreset.snapshot);
+
+ for (const region of Object.values(defaultLayoutPreset.snapshot.widgetRegions)) {
+ const activeTypeId = defaultLayoutPreset.snapshot.widgetInstances[region.activeInstanceId]?.typeId;
+
+ if (activeTypeId) {
+ expect(typeIds).toContain(activeTypeId);
+ }
+ }
+
+ // The status bar mounts all bottom items, not just the active one.
+ for (const instanceId of defaultLayoutPreset.snapshot.widgetRegions.bottom.instanceIds) {
+ const typeId = defaultLayoutPreset.snapshot.widgetInstances[instanceId]?.typeId;
+
+ if (typeId) {
+ expect(typeIds).toContain(typeId);
+ }
+ }
+
+ expect(typeIds).toEqual([...typeIds].sort());
+ expect(new Set(typeIds).size).toBe(typeIds.length);
+ });
+
+ it('round-trips the hint through storage', () => {
+ writeBootWidgetHint(['canvas', 'gallery', 'server-status']);
+
+ expect(readBootWidgetHint()).toEqual(['canvas', 'gallery', 'server-status']);
+ });
+
+ it('rejects malformed hints instead of throwing', () => {
+ storage.set(HINT_KEY, 'not json {');
+ expect(readBootWidgetHint()).toBeNull();
+
+ storage.set(HINT_KEY, '{"widgets":"canvas"}');
+ expect(readBootWidgetHint()).toBeNull();
+
+ storage.set(HINT_KEY, '[]');
+ expect(readBootWidgetHint()).toBeNull();
+
+ storage.set(HINT_KEY, '[1, "", "canvas"]');
+ expect(readBootWidgetHint()).toEqual(['canvas']);
+ });
+
+ it('caps an oversized hint instead of fanning out unbounded preloads', () => {
+ storage.set(HINT_KEY, JSON.stringify(Array.from({ length: 100 }, (_, index) => `widget-${index}`)));
+
+ expect(readBootWidgetHint()).toHaveLength(32);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.ts b/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.ts
new file mode 100644
index 0000000000..f5a963d34c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/bootWidgetPreload.ts
@@ -0,0 +1,102 @@
+import type { WidgetTypeId } from '@workbench/widgetContracts';
+
+import { defaultLayoutPreset } from './layoutPresets';
+import { getWidgetHosts, preloadWidget } from './widgetRegistry';
+
+/**
+ * The widget implementations a boot will render are only knowable for certain
+ * after the project has hydrated from the backend — but that hydration fetch
+ * is exactly the window the network sits idle. This hint records the active
+ * layout's widget set so the next boot can start those chunk downloads in
+ * parallel with hydration instead of after it.
+ *
+ * Dedicated hint key rather than the workbench snapshot for the same reason as
+ * the theme hint: the snapshot is per-user on multi-user backends, and a
+ * preload is harmless when the signed-in user turns out to differ — unknown or
+ * disabled type ids are ignored, and a stale set merely warms chunks the boot
+ * would have fetched moments later.
+ */
+const BOOT_WIDGET_HINT_STORAGE_KEY = 'invokeai:v7:webv2:boot-widgets';
+
+/** Sanity cap so a corrupt hint cannot fan out unbounded chunk fetches. */
+const BOOT_WIDGET_HINT_LIMIT = 32;
+
+/**
+ * The subset of a project or preset snapshot the boot preloader reads. Both
+ * `Project` and `LayoutPresetSnapshot` satisfy it structurally.
+ */
+interface BootWidgetLayout {
+ widgetInstances: Record<string, { typeId: WidgetTypeId }>;
+ widgetRegions: Record<string, { activeInstanceId: string; instanceIds: string[] }>;
+}
+
+/**
+ * The widget types a layout renders at boot: each region's active instance,
+ * plus every placed bottom instance — the status bar mounts all of its items
+ * as compact widgets, not just the active one.
+ */
+export const getBootWidgetTypeIds = (layout: BootWidgetLayout): WidgetTypeId[] => {
+ const typeIds = new Set<WidgetTypeId>();
+
+ for (const [region, state] of Object.entries(layout.widgetRegions)) {
+ const instanceIds = region === 'bottom' ? [state.activeInstanceId, ...state.instanceIds] : [state.activeInstanceId];
+
+ for (const instanceId of instanceIds) {
+ const typeId = layout.widgetInstances[instanceId]?.typeId;
+
+ if (typeId) {
+ typeIds.add(typeId);
+ }
+ }
+ }
+
+ return [...typeIds].sort();
+};
+
+export const readBootWidgetHint = (): WidgetTypeId[] | null => {
+ try {
+ const raw = window.localStorage.getItem(BOOT_WIDGET_HINT_STORAGE_KEY);
+
+ if (!raw) {
+ return null;
+ }
+
+ const parsed: unknown = JSON.parse(raw);
+
+ if (!Array.isArray(parsed)) {
+ return null;
+ }
+
+ const typeIds = parsed.filter((value): value is WidgetTypeId => typeof value === 'string' && value.length > 0);
+
+ return typeIds.length > 0 ? typeIds.slice(0, BOOT_WIDGET_HINT_LIMIT) : null;
+ } catch {
+ return null;
+ }
+};
+
+export const writeBootWidgetHint = (typeIds: readonly WidgetTypeId[]): void => {
+ try {
+ window.localStorage.setItem(BOOT_WIDGET_HINT_STORAGE_KEY, JSON.stringify(typeIds.slice(0, BOOT_WIDGET_HINT_LIMIT)));
+ } catch {
+ // Storage unavailable — the next boot preloads the default layout's set.
+ }
+};
+
+/**
+ * Starts the widget chunk downloads a boot will need, called when the editor
+ * route mounts — while project hydration is still in flight. Host widgets are
+ * known statically from the registry; panel widgets come from the last boot's
+ * hint, falling back to the default layout for a first run. Loads are cached
+ * by the implementation resource, so a wrong guess costs one idle download and
+ * a right one lets the shell mount without ever suspending.
+ */
+export const preloadBootWidgets = (): void => {
+ for (const widget of getWidgetHosts()) {
+ widget.implementation.preload();
+ }
+
+ for (const typeId of readBootWidgetHint() ?? getBootWidgetTypeIds(defaultLayoutPreset.snapshot)) {
+ preloadWidget(typeId);
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts
index 7c5e847144..6a617cfacf 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.test.ts
@@ -34,4 +34,37 @@ describe('layout preset activation', () => {
expect(appliedPresetIds).toEqual(['edit']);
});
+
+ it('applies at the deadline when a widget implementation is still loading', async () => {
+ const appliedPresetIds: string[] = [];
+ const activator = createLayoutPresetActivator({
+ apply: (presetId) => appliedPresetIds.push(presetId),
+ applyDeadlineMs: 0,
+ getActiveProjectId: () => 'project-a',
+ isCurrent: () => true,
+ load: () => new Promise(() => {}),
+ });
+
+ await activator.activate(layoutPresets[0]);
+
+ expect(appliedPresetIds).toEqual([layoutPresets[0].id]);
+ });
+
+ it('discards a deadline apply when the request was superseded before it fired', async () => {
+ const appliedPresetIds: string[] = [];
+ const activator = createLayoutPresetActivator({
+ apply: (presetId) => appliedPresetIds.push(presetId),
+ applyDeadlineMs: 0,
+ getActiveProjectId: () => 'project-a',
+ isCurrent: () => true,
+ load: () => new Promise(() => {}),
+ });
+
+ const activation = activator.activate(layoutPresets[0]);
+
+ activator.invalidate();
+ await activation;
+
+ expect(appliedPresetIds).toEqual([]);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts
index 4f01b4d66d..599e55c792 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetActivation.ts
@@ -2,15 +2,43 @@ import type { LayoutPreset, LayoutPresetId } from './layoutContracts';
import { loadWidget, preloadWidget } from './widgetRegistry';
+/**
+ * How long an activation waits for widget implementations before applying the
+ * preset anyway. Warm widgets — the common case, given boot preloading and the
+ * strip's hover preload — settle immediately and keep the atomic, no-fallback
+ * reveal. A cold or failing chunk stops gating the entire layout at this
+ * deadline: the switch commits and the stragglers reveal progressively behind
+ * their own per-widget fallbacks.
+ */
+const APPLY_DEADLINE_MS = 250;
+
interface LayoutPresetActivatorDependencies {
apply: (presetId: LayoutPresetId) => void;
+ /** Test seam; omit for the production deadline. */
+ applyDeadlineMs?: number;
getActiveProjectId: () => string;
isCurrent: (preset: LayoutPreset) => boolean;
load: (preset: LayoutPreset) => Promise<unknown>;
}
+const waitForLoadOrDeadline = async (pending: Promise<unknown>, deadlineMs: number): Promise<void> => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ try {
+ await Promise.race([
+ pending,
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, deadlineMs);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
export const createLayoutPresetActivator = ({
apply,
+ applyDeadlineMs = APPLY_DEADLINE_MS,
getActiveProjectId,
isCurrent,
load,
@@ -21,7 +49,7 @@ export const createLayoutPresetActivator = ({
activate: async (preset: LayoutPreset): Promise<void> => {
const projectId = getActiveProjectId();
const requestId = ++latestRequestId;
- await load(preset);
+ await waitForLoadOrDeadline(load(preset), applyDeadlineMs);
if (requestId === latestRequestId && projectId === getActiveProjectId() && isCurrent(preset)) {
apply(preset.id);