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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(workbench): harden persistence for large projects
joshistoastd84db2e23821
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 59ebdd9489..dfc6404517 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -26,7 +26,7 @@ import {type WorkbenchSaveResult,} from './projects/syncedPersistence';import { getProjectWidgetValues } from './widgetState';-import { getAutosaveScheduleDecision, getPersistedStateKey, isAutosaveCompletionCurrent } from './workbenchAutosave';+import { getAutosaveScheduleDecision, isAutosaveCompletionCurrent } from './workbenchAutosave';import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from './workbenchSelectors';import {createWorkbenchStore,@@ -79,9 +79,7 @@ export const WorkbenchProvider = ({const [hasHydrated, setHasHydrated] = useState(store.getSnapshot().hasHydrated);const hasLoadedPersistenceRef = useRef(false);const lastSavedPersistedRevisionRef = useRef(store.getPersistedRevision());- const lastSavedStateKeyRef = useRef(getPersistedStateKey(store.getState()));const failedPersistedRevisionRef = useRef<number | null>(null);- const failedStateKeyRef = useRef<string | null>(null);// Captured once: the options describe how this mount of the editor boots.// Later search-param changes are handled live by WorkbenchSessionController.const bootOptionsRef = useRef(loadOptions);@@ -100,11 +98,13 @@ export const WorkbenchProvider = ({}if (snapshot) {- if (!syncedWorkbenchPersistence.hasPendingChanges()) {- lastSavedStateKeyRef.current = getPersistedStateKey(snapshot.state);- }+ const isPendingSnapshot = syncedWorkbenchPersistence.hasPendingChanges();dispatch({ state: snapshot.state, type: 'hydrateWorkbench' });++ if (!isPendingSnapshot) {+ lastSavedPersistedRevisionRef.current = store.getPersistedRevision();+ }}const requestedId = bootOptions?.openProjectId;@@ -181,10 +181,6 @@ export const WorkbenchProvider = ({scheduledPersistedRevision,});- if (failedPersistedRevisionRef.current !== null && decision.failedPersistedRevision === null) {- failedStateKeyRef.current = null;- }-failedPersistedRevisionRef.current = decision.failedPersistedRevision;if (!decision.shouldSchedule) {@@ -200,21 +196,6 @@ export const WorkbenchProvider = ({timeoutId = window.setTimeout(() => {const stateToSave = store.getState();const revisionToSave = store.getPersistedRevision();- const stateKeyToSave = getPersistedStateKey(stateToSave);-- if (stateKeyToSave === lastSavedStateKeyRef.current) {- lastSavedPersistedRevisionRef.current = revisionToSave;- failedStateKeyRef.current = null;- failedPersistedRevisionRef.current = null;- scheduledPersistedRevision = null;- return;- }-- if (stateKeyToSave === failedStateKeyRef.current) {- failedPersistedRevisionRef.current = revisionToSave;- scheduledPersistedRevision = null;- return;- }dispatch({ type: 'autosaveStarted' });@@ -225,9 +206,7 @@ export const WorkbenchProvider = ({return;}- lastSavedStateKeyRef.current = stateKeyToSave;lastSavedPersistedRevisionRef.current = revisionToSave;- failedStateKeyRef.current = null;failedPersistedRevisionRef.current = null;scheduledPersistedRevision = null;dispatch({ savedAt: result.snapshot.savedAt, type: 'autosaveSucceeded' });@@ -238,7 +217,6 @@ export const WorkbenchProvider = ({return;}- failedStateKeyRef.current = stateKeyToSave;failedPersistedRevisionRef.current = revisionToSave;scheduledPersistedRevision = null;dispatch({@@ -283,7 +261,6 @@ export const WorkbenchProvider = ({const stateToSave = store.getState();const revisionToSave = store.getPersistedRevision();- const stateKeyToSave = getPersistedStateKey(stateToSave);void syncedWorkbenchPersistence.saveWorkbench(stateToSave)@@ -291,17 +268,13 @@ export const WorkbenchProvider = ({if (!isAutosaveCompletionCurrent({completedPersistedRevision: revisionToSave,- completedStateKey: stateKeyToSave,currentPersistedRevision: store.getPersistedRevision(),- currentStateKey: getPersistedStateKey(store.getState()),})) {return;}- lastSavedStateKeyRef.current = stateKeyToSave;lastSavedPersistedRevisionRef.current = revisionToSave;- failedStateKeyRef.current = null;failedPersistedRevisionRef.current = null;dispatch({ savedAt: result.snapshot.savedAt, type: 'autosaveSucceeded' });applySaveResult(result);@@ -310,15 +283,12 @@ export const WorkbenchProvider = ({if (!isAutosaveCompletionCurrent({completedPersistedRevision: revisionToSave,- completedStateKey: stateKeyToSave,currentPersistedRevision: store.getPersistedRevision(),- currentStateKey: getPersistedStateKey(store.getState()),})) {return;}- failedStateKeyRef.current = stateKeyToSave;failedPersistedRevisionRef.current = revisionToSave;dispatch({error: error instanceof Error ? error.message : 'Failed to autosave workbench.',diff --git a/invokeai/frontend/webv2/src/workbench/persistence.test.ts b/invokeai/frontend/webv2/src/workbench/persistence.test.tsindex c4ec00e884..f9439fb7a7 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.test.ts@@ -71,4 +71,52 @@ describe('workbench persistence migration', () => {expect(persisted.state.notifications).toEqual([]);});++ it('treats localStorage quota failures as cache misses, not save failures', async () => {+ const originalSet = window.localStorage.setItem;++ try {+ window.localStorage.setItem = (key: string, value: string): void => {+ if (key === 'invokeai:v7:webv2:workbench') {+ throw new DOMException('Quota exceeded', 'QuotaExceededError');+ }++ originalSet.call(window.localStorage, key, value);+ };++ await expect(+ localStorageWorkbenchPersistence.saveWorkbench(createInitialWorkbenchState())+ ).resolves.toMatchObject({+ version: 1,+ });+ } finally {+ window.localStorage.setItem = originalSet;+ }+ });++ it('still attempts localStorage cache writes for large open workflow projects', async () => {+ const state = createInitialWorkbenchState();+ const project = state.projects[0]!;+ const largeState = {+ ...state,+ projects: [+ {+ ...project,+ projectGraph: {+ ...project.projectGraph,+ nodes: Array.from({ length: 300 }, (_, index) => ({+ data: { label: '', notes: '' },+ id: `node-${index}`,+ position: { x: 0, y: 0 },+ type: 'notes' as const,+ })),+ },+ },+ ],+ };++ await localStorageWorkbenchPersistence.saveWorkbench(largeState);++ expect(storage.has('invokeai:v7:webv2:workbench')).toBe(true);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/persistence.ts b/invokeai/frontend/webv2/src/workbench/persistence.tsindex 540e53ea69..6d498cb49b 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.ts@@ -1,6 +1,7 @@import type { WorkbenchPersistenceSnapshot, WorkbenchState } from './types';import { getUserStorageScope } from './auth/session';+import { timeWorkbenchPerf } from './performanceMarks';const BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';const WORKBENCH_SCHEMA_VERSION = 1;@@ -96,7 +97,14 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {return Promise.resolve(snapshot);}- window.localStorage.setItem(getStorageKey(), JSON.stringify(snapshot));+ try {+ window.localStorage.setItem(+ getStorageKey(),+ timeWorkbenchPerf('workbench:persistence-localstorage-stringify', () => JSON.stringify(snapshot))+ );+ } catch {+ // The backend remains the source of truth; localStorage is only an offline cache.+ }return Promise.resolve(snapshot);},diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex 8169ba46f9..c33e68d1f3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -1,6 +1,7 @@import type { Project, WorkbenchPersistenceSnapshot, WorkbenchState } from '@workbench/types';import { getUserStorageScope } from '@workbench/auth/session';+import { timeWorkbenchPerf } from '@workbench/performanceMarks';import { localStorageWorkbenchPersistence, stripTransientWorkbenchState } from '@workbench/persistence';import { createDraftProject, createInitialWorkbenchState } from '@workbench/workbenchState';@@ -81,6 +82,7 @@ const syncEntries = new Map<string, SyncEntry>();const deletedProjectIds = new Set<string>();let lastPushedAccount: string | null = null;let hasPending = false;+const projectDocumentJsonCache = new WeakMap<Project, { document: Record<string, unknown>; json: string }>();/*** Undo/redo stacks are session-only (each entry is a full project snapshot,@@ -93,6 +95,22 @@ export const serializeProjectDocument = (project: Project): Record<string, unknoreturn document;};+const getSerializedProjectDocument = (project: Project): { document: Record<string, unknown>; json: string } => {+ const cached = projectDocumentJsonCache.get(project);++ if (cached) {+ return cached;+ }++ const document = serializeProjectDocument(project);+ const json = timeWorkbenchPerf('workbench:project-document-stringify', () => JSON.stringify(document));+ const serialized = { document, json };++ projectDocumentJsonCache.set(project, serialized);++ return serialized;+};+const normalizeInvocationSourceId = (sourceId: unknown): unknown => {if (sourceId === 'project-graph') {return 'workflow';@@ -315,8 +333,7 @@ const recoverConflictingProject = async (};const pushProject = async (project: Project, conflicts: ProjectConflictResolution[]): Promise<string> => {- const document = serializeProjectDocument(project);- const documentJson = JSON.stringify(document);+ const { document, json: documentJson } = getSerializedProjectDocument(project);const entry = syncEntries.get(project.id);if (deletedProjectIds.has(project.id) || entry?.pushedDoc === documentJson) {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.tsindex f6b4f65fe8..7b9f0a09f9 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts@@ -69,20 +69,25 @@ describe('isAutosaveCompletionCurrent', () => {expect(isAutosaveCompletionCurrent({completedPersistedRevision: 2,- completedStateKey: 'state-2',currentPersistedRevision: 3,- currentStateKey: 'state-3',})).toBe(false);});- it('accepts save completions for the current durable revision and state key', () => {+ it('accepts save completions for the current durable revision', () => {expect(isAutosaveCompletionCurrent({completedPersistedRevision: 2,- completedStateKey: 'state-2',currentPersistedRevision: 2,- currentStateKey: 'state-2',+ })+ ).toBe(true);+ });++ it('does not require serializing full workbench state to compare completions', () => {+ expect(+ isAutosaveCompletionCurrent({+ completedPersistedRevision: 4,+ currentPersistedRevision: 4,})).toBe(true);});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.tsindex 907e053dea..5d87de9103 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts@@ -1,14 +1,3 @@-import type { WorkbenchState } from './types';--export const getPersistedStateKey = (state: WorkbenchState): string =>- JSON.stringify({- account: state.account,- activeProjectId: state.activeProjectId,- errorLog: state.errorLog,- projects: state.projects,- widgetFailures: state.widgetFailures,- });-interface AutosaveScheduleDecisionInput {failedPersistedRevision: number | null;lastSavedPersistedRevision: number;@@ -44,12 +33,8 @@ export const getAutosaveScheduleDecision = ({export const isAutosaveCompletionCurrent = ({completedPersistedRevision,- completedStateKey,currentPersistedRevision,- currentStateKey,}: {completedPersistedRevision: number;- completedStateKey: string;currentPersistedRevision: number;- currentStateKey: string;-}): boolean => completedPersistedRevision === currentPersistedRevision && completedStateKey === currentStateKey;+}): boolean => completedPersistedRevision === currentPersistedRevision;