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.

fix(ui): validate preset drafts

joshistoastee51e72c833b
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
index 7e25abab2f..3bb6945431 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
@@ -2,7 +2,7 @@ import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { createWorkbenchPersistenceRuntime, type PersistenceClock } from '@workbench/persistenceRuntime';
-import { createDraftProject, createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createDraftProject, createInitialWorkbenchState, normalizeWorkbenchAccount } from '@workbench/workbenchState';
import { createWorkbenchStore } from '@workbench/workbenchStore';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -237,11 +237,50 @@ describe('loadWorkbench session hydration', () => {
expect(api.getProject).not.toHaveBeenCalled();
});
+ it('honors a new-project request while importing legacy local projects', async () => {
+ const state = createInitialWorkbenchState();
+ const existingProjectId = state.activeProjectId;
+ storage.set(
+ 'invokeai:v7:webv2:workbench',
+ JSON.stringify({ savedAt: '2026-07-19T00:00:00.000Z', state, version: 1 })
+ );
+
+ const snapshot = await service.loadWorkbench({ createNew: true });
+
+ expect(snapshot?.state.projects).toHaveLength(state.projects.length + 1);
+ expect(snapshot?.state.activeProjectId).not.toBe(existingProjectId);
+ expect(service.hasPendingChanges()).toBe(true);
+ });
+
+ it('keeps the server account while importing legacy local projects', async () => {
+ const local = createInitialWorkbenchState();
+ const serverAccount = {
+ ...local.account,
+ layoutPresetMetadataOverrides: { compose: { label: 'Writing' } },
+ layoutPresetRouteOverrides: { compose: { destination: 'canvas' as const, sourceId: 'canvas' as const } },
+ };
+ storage.set(
+ 'invokeai:v7:webv2:workbench',
+ JSON.stringify({ savedAt: '2026-07-19T00:00:00.000Z', state: local, version: 1 })
+ );
+ seedSessionBlob({ account: serverAccount, activeProjectId: '', openProjectIds: [] });
+
+ const snapshot = await service.loadWorkbench({ createNew: true });
+
+ expect(snapshot?.state.account).toMatchObject(serverAccount);
+ expect(
+ snapshot?.state.projects.find((project) => project.id === snapshot.state.activeProjectId)?.invocation
+ ).toMatchObject({
+ destination: 'canvas',
+ sourceId: 'canvas',
+ });
+ });
+
it('hydrates only the open set and seeds the full library', async () => {
const first = seedServerProject('First');
const second = seedServerProject('Second');
const third = seedServerProject('Third');
- const account = createInitialWorkbenchState().account;
+ const account = normalizeWorkbenchAccount(createInitialWorkbenchState().account);
seedSessionBlob({ account, activeProjectId: second.id, openProjectIds: [second.id] });
@@ -294,6 +333,22 @@ describe('loadWorkbench session hydration', () => {
expect(service.hasPendingChanges()).toBe(true);
});
+ it('normalizes malformed account preset data before creating an empty-session draft', async () => {
+ const account = {
+ ...createInitialWorkbenchState().account,
+ layoutPresetOverrides: { compose: { malformed: true } },
+ };
+
+ seedSessionBlob({ account, activeProjectId: '', openProjectIds: [] });
+
+ const snapshot = await service.loadWorkbench();
+
+ expect(snapshot?.state.projects).toHaveLength(1);
+ expect(snapshot?.state.account.layoutPresetOverrides).toEqual({});
+ expect(snapshot?.state.projects[0]?.layout.presetId).toBe('compose');
+ expect(snapshot?.state.projects[0]?.invocation).toMatchObject({ destination: 'gallery', sourceId: 'generate' });
+ });
+
it('joins a deep-linked project into the open set and focuses it', async () => {
const first = seedServerProject('First');
const second = seedServerProject('Second');
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
index 12a11fae2e..5f0a2b0f7b 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
@@ -11,6 +11,7 @@ import {
import {
createDraftProject,
createInitialWorkbenchState,
+ normalizeWorkbenchAccount,
normalizeWorkbenchProject,
withAuthoritativeProjectBoard,
} from '@workbench/workbenchState';
@@ -637,6 +638,11 @@ const loadFromBackend = async (
// First contact: a backend with no projects adopts the browser's existing
// workbench (one-time import of the pre-backend localStorage data).
if (summaries.length === 0 && local && local.state.projects.length > 0) {
+ const importedState: WorkbenchState = {
+ ...local.state,
+ account: normalizeWorkbenchAccount(sessionBlob?.account ?? local.state.account),
+ };
+
for (const project of local.state.projects) {
if (!(await pushNewProject(syncState, project))) {
assertOwner(syncState);
@@ -649,11 +655,25 @@ const loadFromBackend = async (
upsertProjectSummary({ id: project.id, name: project.name, revision: entry?.revision ?? null }, syncState.owner);
}
- await pushSessionState(syncState, local.state);
+ await pushSessionState(syncState, importedState);
assertOwner(syncState);
persistSyncMap(syncState);
- return local;
+ if (!options?.createNew) {
+ return { ...local, state: importedState };
+ }
+
+ const draft = createDraftProject(importedState.projects, importedState.account);
+ syncState.hasPending = true;
+
+ return {
+ ...local,
+ state: {
+ ...importedState,
+ activeProjectId: draft.id,
+ projects: [...importedState.projects, draft],
+ },
+ };
}
// The session blob says which projects are open as tabs; blobs from before
@@ -721,7 +741,7 @@ const loadFromBackend = async (
}
const base = local?.state ?? createInitialWorkbenchState();
- const account = sessionBlob?.account ?? base.account;
+ const account = normalizeWorkbenchAccount(sessionBlob?.account ?? base.account);
let activeProjectId =
options?.openProjectId && projects.some((project) => project.id === options.openProjectId)
? options.openProjectId
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index bf1a2ec05f..86cce4055e 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -22,7 +22,7 @@ import { layoutPresets } from './layoutPresets';
import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';
import { DEFAULT_PROJECT_SETTINGS } from './settings/store';
import { getProjectWidgetValues } from './widgetState';
-import { GRAPH_HISTORY_BYTE_BUDGET, normalizeGraphHistory } from './workbenchState';
+import { GRAPH_HISTORY_BYTE_BUDGET, normalizeGraphHistory, normalizeWorkbenchAccount } from './workbenchState';
import {
createInitialWorkbenchState,
nextLayerName,
@@ -660,6 +660,41 @@ describe('workbench layout presets', () => {
expect(project.layout).toMatchObject({ centerViewId: 'gallery', presetId: 'compose' });
});
+ it('repairs a stale saved Compose route when its source is absent from the saved layout', () => {
+ const initial = createInitialWorkbenchState();
+ const compose = layoutPresets[0]!;
+ const left = compose.snapshot.widgetRegions.left;
+ const { upscale: _removedUpscale, ...widgetInstances } = compose.snapshot.widgetInstances;
+ const customized: WorkbenchState = {
+ ...initial,
+ account: {
+ ...initial.account,
+ layoutPresetOverrides: {
+ compose: {
+ ...compose.snapshot,
+ widgetInstances,
+ widgetRegions: {
+ ...compose.snapshot.widgetRegions,
+ left: { ...left, instanceIds: left.instanceIds.filter((id) => id !== 'upscale') },
+ },
+ },
+ },
+ layoutPresetRouteOverrides: {
+ compose: { destination: 'gallery', sourceId: 'upscale' },
+ },
+ },
+ };
+
+ const withNewProject = workbenchReducer(customized, { type: 'createProject' });
+
+ expect(getProject(withNewProject, withNewProject.activeProjectId).invocation).toEqual({
+ destination: 'canvas',
+ destinationLocked: false,
+ sourceId: 'generate',
+ sourceLocked: false,
+ });
+ });
+
it('applies each built-in preset default route with its layout', () => {
let state = createInitialWorkbenchState();
@@ -976,6 +1011,64 @@ describe('workbench layout presets', () => {
expect(state.account.layoutPresetRouteOverrides).toEqual({ edit: route });
});
+ it('preserves a saved preset with an empty side region during hydration', () => {
+ const initial = createInitialWorkbenchState();
+ const snapshot = layoutPresets[0]!.snapshot;
+ const emptyRightSnapshot = {
+ ...snapshot,
+ widgetRegions: {
+ ...snapshot.widgetRegions,
+ right: { ...snapshot.widgetRegions.right, instanceIds: [] },
+ },
+ };
+ const state = workbenchReducer(initial, {
+ state: {
+ ...initial,
+ account: {
+ ...initial.account,
+ layoutPresetOverrides: { compose: emptyRightSnapshot },
+ },
+ },
+ type: 'hydrateWorkbench',
+ });
+
+ expect(state.account.layoutPresetOverrides).toEqual({ compose: emptyRightSnapshot });
+ });
+
+ it('drops preset snapshots with invalid widget and layout references', () => {
+ const snapshot = layoutPresets[0]!.snapshot;
+ const invalidSnapshots = [
+ { ...snapshot, layout: { ...snapshot.layout, centerViewId: 'retired-view' } },
+ {
+ ...snapshot,
+ widgetInstances: { ...snapshot.widgetInstances, generate: true },
+ },
+ {
+ ...snapshot,
+ widgetRegions: {
+ ...snapshot.widgetRegions,
+ left: {
+ ...snapshot.widgetRegions.left,
+ instanceIds: [...snapshot.widgetRegions.left.instanceIds, 'missing'],
+ },
+ },
+ },
+ {
+ ...snapshot,
+ widgetRegions: {
+ ...snapshot.widgetRegions,
+ right: { ...snapshot.widgetRegions.right, sizePx: Number.POSITIVE_INFINITY },
+ },
+ },
+ ];
+
+ for (const invalidSnapshot of invalidSnapshots) {
+ expect(
+ normalizeWorkbenchAccount({ layoutPresetOverrides: { compose: invalidSnapshot } }).layoutPresetOverrides
+ ).toEqual({});
+ }
+ });
+
it('captures the live source and destination without routing locks when creating a custom preset', () => {
let state = createInitialWorkbenchState();
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index a49314b2e2..0c7f3f6e4e 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -1427,7 +1427,7 @@ const createProject = (index: number, id: string, preset: LayoutPreset): Project
],
graphHistory: [],
id,
- invocation: { ...defaultInvocationRoute, ...preset.defaultRoute },
+ invocation: getInvocationAfterLayoutPreset(defaultInvocationRoute, preset),
layout: { ...defaultLayoutPreset.snapshot.layout, panels: { ...defaultLayoutPreset.snapshot.layout.panels } },
name: `Project Name #${index}`,
promptHistory: [],
@@ -1457,7 +1457,7 @@ export const createDraftProject = (projects: Project[], account?: WorkbenchState
createProject(
getNextProjectIndex(projects),
createId('project'),
- account ? resolveSavedLayoutPreset(account, defaultLayoutPreset.id) : defaultLayoutPreset
+ account ? resolveSavedLayoutPreset(normalizeWorkbenchAccount(account), defaultLayoutPreset.id) : defaultLayoutPreset
);
const updateActiveProject = (state: WorkbenchState, getProject: (project: Project) => Project): WorkbenchState => {
@@ -1539,19 +1539,47 @@ const cloneLayoutPresetSnapshot = (snapshot: LayoutPresetSnapshot): LayoutPreset
widgetRegions: cloneLayoutPresetWidgetRegions(snapshot.widgetRegions),
});
-const isWidgetRegionState = (value: unknown): value is WidgetRegionState => {
+const centerViewIds = new Set<CenterViewId>(['canvas', 'gallery', 'preview', 'workflow']);
+
+const isLayoutPresetWidgetInstance = (instanceId: string, value: unknown): boolean => {
+ if (!value || typeof value !== 'object') {
+ return false;
+ }
+
+ const record = value as { id?: unknown; title?: unknown; typeId?: unknown };
+
+ return (
+ instanceId.length > 0 &&
+ record.id === instanceId &&
+ typeof record.typeId === 'string' &&
+ record.typeId.length > 0 &&
+ (record.title === undefined || typeof record.title === 'string')
+ );
+};
+
+const isWidgetRegionState = (
+ value: unknown,
+ widgetInstances: Readonly<Record<string, unknown>>
+): value is WidgetRegionState => {
if (!value || typeof value !== 'object') {
return false;
}
const record = value as Partial<WidgetRegionState>;
+ const instanceIds = record.instanceIds;
return (
typeof record.activeInstanceId === 'string' &&
- Array.isArray(record.instanceIds) &&
- record.instanceIds.every((instanceId) => typeof instanceId === 'string') &&
+ record.activeInstanceId.length > 0 &&
+ Array.isArray(instanceIds) &&
+ instanceIds.every((instanceId) => typeof instanceId === 'string' && instanceId in widgetInstances) &&
+ new Set(instanceIds).size === instanceIds.length &&
+ record.activeInstanceId in widgetInstances &&
+ (instanceIds.length === 0 || instanceIds.includes(record.activeInstanceId)) &&
typeof record.isCollapsed === 'boolean' &&
- typeof record.sizePx === 'number'
+ typeof record.sizePx === 'number' &&
+ Number.isFinite(record.sizePx) &&
+ record.sizePx >= 0
);
};
@@ -1562,22 +1590,31 @@ const isLayoutPresetSnapshot = (value: unknown): value is LayoutPresetSnapshot =
const snapshot = value as Partial<LayoutPresetSnapshot>;
const layout = snapshot.layout as Partial<ProjectLayoutState> | undefined;
+ const widgetInstances = snapshot.widgetInstances as Record<string, unknown> | undefined;
return (
!!layout &&
typeof layout.presetId === 'string' &&
+ layout.presetId.length > 0 &&
typeof layout.centerViewId === 'string' &&
+ centerViewIds.has(layout.centerViewId as CenterViewId) &&
!!layout.panels &&
typeof layout.panels.isBottomOpen === 'boolean' &&
typeof layout.panels.isLeftOpen === 'boolean' &&
typeof layout.panels.isRightOpen === 'boolean' &&
- !!snapshot.widgetInstances &&
- typeof snapshot.widgetInstances === 'object' &&
+ !!widgetInstances &&
+ typeof widgetInstances === 'object' &&
+ !Array.isArray(widgetInstances) &&
+ Object.keys(widgetInstances).length > 0 &&
+ Object.entries(widgetInstances).every(([instanceId, instance]) =>
+ isLayoutPresetWidgetInstance(instanceId, instance)
+ ) &&
!!snapshot.widgetRegions &&
- isWidgetRegionState(snapshot.widgetRegions.left) &&
- isWidgetRegionState(snapshot.widgetRegions.right) &&
- isWidgetRegionState(snapshot.widgetRegions.bottom) &&
- isWidgetRegionState(snapshot.widgetRegions.center)
+ typeof snapshot.widgetRegions === 'object' &&
+ isWidgetRegionState(snapshot.widgetRegions.left, widgetInstances) &&
+ isWidgetRegionState(snapshot.widgetRegions.right, widgetInstances) &&
+ isWidgetRegionState(snapshot.widgetRegions.bottom, widgetInstances) &&
+ isWidgetRegionState(snapshot.widgetRegions.center, widgetInstances)
);
};
@@ -1696,7 +1733,8 @@ const normalizeLayoutPresetOverrides = (overrides: unknown): LayoutPresetOverrid
);
};
-const normalizeAccount = (account: Partial<WorkbenchState['account']> | undefined): WorkbenchState['account'] => {
+export const normalizeWorkbenchAccount = (value: unknown): WorkbenchState['account'] => {
+ const account = value && typeof value === 'object' ? (value as Partial<WorkbenchState['account']>) : undefined;
const customLayoutPresets = normalizeCustomLayoutPresets(account?.customLayoutPresets);
const resolvedActivePresetId = resolveLayoutPresetId(account?.activeLayoutPresetId ?? defaultLayoutPreset.id);
const activeLayoutPresetId =
@@ -1723,7 +1761,7 @@ const normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => ({
backendConnection: { status: 'connecting' },
// Built explicitly: legacy snapshots carried preferences inside the account
// (they live in the settings store now) and must not resurface here.
- account: normalizeAccount(state.account),
+ account: normalizeWorkbenchAccount(state.account),
notifications: [],
projects: state.projects.map(normalizeWorkbenchProject),
});