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(workflow): bound history during loads
joshistoasta1bfbadf4f0c
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex 4def7c8357..c6af20e10f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -1,7 +1,7 @@/* eslint-disable react/react-compiler, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */import type { ProjectGraphState } from '@features/workflow/contracts';-import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Stack, Tabs, Text } from '@chakra-ui/react';+import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Spinner, Stack, Tabs, Text } from '@chakra-ui/react';import {createLibraryWorkflow,deleteLibraryWorkflow,@@ -35,8 +35,11 @@ interface WorkflowPreviewState {document: ProjectGraphState;item: WorkflowLibraryListItem;raw: Record<string, unknown>;+ warnings: string[];}+type WorkflowLoadPhase = 'fetching' | 'applying';+const WorkflowPreviewPane = ({isLoadingWorkflow,preview,@@ -109,13 +112,15 @@ export const WorkflowLibraryDialog = ({const [pages, setPages] = useState(0);const [page, setPage] = useState(0);const [isLoading, setIsLoading] = useState(false);- const [loadingWorkflowId, setLoadingWorkflowId] = useState<string | null>(null);+ const [workflowLoad, setWorkflowLoad] = useState<{ id: string; phase: WorkflowLoadPhase } | null>(null);const [previewingWorkflowId, setPreviewingWorkflowId] = useState<string | null>(null);const [preview, setPreview] = useState<WorkflowPreviewState | null>(null);const [pendingDelete, setPendingDelete] = useState<WorkflowLibraryListItem | null>(null);const [isSaving, setIsSaving] = useState(false);const hasAutoSwitchedRef = useRef(false);const refreshTokenRef = useRef(0);+ const workflowLoadInFlightRef = useRef(false);+ const isWorkflowLoadPending = workflowLoad !== null;const refresh = useCallback((nextPage: number) => {@@ -181,30 +186,45 @@ export const WorkflowLibraryDialog = ({return { document, raw, warnings };};- const applyLoadedWorkflow = (item: WorkflowLibraryListItem, document: ProjectGraphState, warnings: string[]) => {- replace(document, `Loaded "${item.name}" from library`);-- for (const warning of warnings) {- notify.info('Workflow load warning', warning);+ const loadWorkflow = async (+ item: WorkflowLibraryListItem,+ loaded?: { document: ProjectGraphState; warnings: string[] }+ ) => {+ if (workflowLoadInFlightRef.current) {+ return;}+ workflowLoadInFlightRef.current = true;- void touchLibraryWorkflowOpenedAt(item.workflow_id).catch(() => {- // Recency bookkeeping only; loading already succeeded.- });- onOpenChange(false);- };+ try {+ let parsed = loaded;- const loadWorkflow = async (item: WorkflowLibraryListItem) => {- setLoadingWorkflowId(item.workflow_id);+ if (!parsed) {+ setWorkflowLoad({ id: item.workflow_id, phase: 'fetching' });+ parsed = await fetchParsedWorkflow(item);+ }- try {- const { document, warnings } = await fetchParsedWorkflow(item);+ setWorkflowLoad({ id: item.workflow_id, phase: 'applying' });+ // Synchronous graph replacement can be expensive for large workflows.+ // Give React a full frame to commit and paint the busy overlay first.+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });- applyLoadedWorkflow(item, document, warnings);+ replace(parsed.document, `Loaded "${item.name}" from library`);++ for (const warning of parsed.warnings) {+ notify.info('Workflow load warning', warning);+ }++ void touchLibraryWorkflowOpenedAt(item.workflow_id).catch(() => {+ // Recency bookkeeping only; loading already succeeded.+ });+ onOpenChange(false);} catch (error) {notify.error('Failed to load workflow', getApiErrorMessage(error, `Could not load "${item.name}".`));} finally {- setLoadingWorkflowId(null);+ workflowLoadInFlightRef.current = false;+ setWorkflowLoad(null);}};@@ -212,9 +232,9 @@ export const WorkflowLibraryDialog = ({setPreviewingWorkflowId(item.workflow_id);try {- const { document, raw } = await fetchParsedWorkflow(item);+ const { document, raw, warnings } = await fetchParsedWorkflow(item);- setPreview({ document, item, raw });+ setPreview({ document, item, raw, warnings });} catch (error) {notify.error('Failed to preview workflow', getApiErrorMessage(error, `Could not preview "${item.name}".`));} finally {@@ -249,11 +269,44 @@ export const WorkflowLibraryDialog = ({return (<>- <Dialog.Root placement="center" open={isOpen} size="lg" onOpenChange={(event) => onOpenChange(event.open)}>+ <Dialog.Root+ placement="center"+ open={isOpen}+ size="lg"+ onOpenChange={(event) => {+ if (!isWorkflowLoadPending) {+ onOpenChange(event.open);+ }+ }}+ ><Portal><Dialog.Backdrop /><Dialog.Positioner>- <Dialog.Content bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg">+ <Dialog.Content+ aria-busy={isWorkflowLoadPending}+ bg="bg.subtle"+ borderColor="border.subtle"+ borderWidth="1px"+ color="fg"+ position="relative"+ >+ {workflowLoad ? (+ <Stack+ alignItems="center"+ aria-live="polite"+ bg="bg/85"+ inset="0"+ justifyContent="center"+ position="absolute"+ role="status"+ zIndex="modal"+ >+ <Spinner color="accent.solid" size="lg" />+ <Text fontSize="xs" fontWeight="600">+ {workflowLoad.phase === 'fetching' ? 'Fetching workflow…' : 'Applying workflow…'}+ </Text>+ </Stack>+ ) : null}<Dialog.Header><Dialog.Title fontSize="sm" fontWeight="700">Workflow Library@@ -262,10 +315,10 @@ export const WorkflowLibraryDialog = ({<Dialog.Body>{preview ? (<WorkflowPreviewPane- isLoadingWorkflow={loadingWorkflowId === preview.item.workflow_id}+ isLoadingWorkflow={workflowLoad?.id === preview.item.workflow_id}preview={preview}onBack={() => setPreview(null)}- onLoad={() => applyLoadedWorkflow(preview.item, preview.document, [])}+ onLoad={() => void loadWorkflow(preview.item, preview)}/>) : (<Stack gap="3">@@ -315,7 +368,7 @@ export const WorkflowLibraryDialog = ({<Boxas="button"_focusVisible={{ outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' }}- aria-disabled={previewingWorkflowId !== null}+ aria-disabled={previewingWorkflowId !== null || isWorkflowLoadPending}cursor="pointer"flex="1"minW="0"@@ -325,7 +378,7 @@ export const WorkflowLibraryDialog = ({textAlign="start"title={`Preview "${item.name || 'Untitled Workflow'}"`}onClick={() => {- if (previewingWorkflowId === null) {+ if (previewingWorkflowId === null && !isWorkflowLoadPending) {void previewWorkflow(item);}}}@@ -342,6 +395,7 @@ export const WorkflowLibraryDialog = ({</Stack></Box><Button+ disabled={previewingWorkflowId !== null || isWorkflowLoadPending}flexShrink={0}loading={previewingWorkflowId === item.workflow_id}size="2xs"@@ -351,8 +405,9 @@ export const WorkflowLibraryDialog = ({Preview</Button><Button+ disabled={previewingWorkflowId !== null || isWorkflowLoadPending}flexShrink={0}- loading={loadingWorkflowId === item.workflow_id}+ loading={workflowLoad?.id === item.workflow_id}size="2xs"variant="outline"onClick={() => void loadWorkflow(item)}@@ -436,7 +491,7 @@ export const WorkflowLibraryDialog = ({)}</Dialog.Body><Dialog.CloseTrigger asChild>- <CloseButton color="fg.muted" size="sm" />+ <CloseButton color="fg.muted" disabled={isWorkflowLoadPending} size="sm" /></Dialog.CloseTrigger></Dialog.Content></Dialog.Positioner>diff --git a/invokeai/frontend/webv2/src/workbench/persistence.test.ts b/invokeai/frontend/webv2/src/workbench/persistence.test.tsindex d10549ecb3..51dac6bb05 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.test.ts@@ -95,6 +95,24 @@ describe('workbench persistence migration', () => {expect(persisted.state.notifications).toEqual([]);});+ it('persists empty project undo and redo stacks and normalizes legacy cache entries', async () => {+ let state = createInitialWorkbenchState();+ state = workbenchReducer(state, {+ sourceId: 'workflow',+ type: 'setInvocationSource',+ });+ expect(state.projects[0]?.undoRedo.past.length).toBeGreaterThan(0);++ const snapshot = await localStorageWorkbenchPersistence.saveWorkbench(state);+ expect(snapshot.state.projects[0]?.undoRedo).toEqual({ future: [], past: [] });++ const raw = storage.get('invokeai:v7:webv2:workbench');+ const hydrated = await localStorageWorkbenchPersistence.loadWorkbench();++ expect(raw).toBeDefined();+ expect(hydrated?.state.projects[0]?.undoRedo).toEqual({ future: [], past: [] });+ });+it('treats localStorage quota failures as cache misses, not save failures', async () => {const originalSet = window.localStorage.setItem;diff --git a/invokeai/frontend/webv2/src/workbench/persistence.ts b/invokeai/frontend/webv2/src/workbench/persistence.tsindex a5a692614c..20f077c66e 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.ts@@ -29,6 +29,13 @@ export const stripTransientWorkbenchState = (state: WorkbenchState): WorkbenchStreturn {...nextState,notifications: [],+ // Project undo/redo is deliberately session-only. Normalize legacy cache+ // snapshots immediately and never let full-project undo entries consume+ // localStorage quota or grow across browser sessions.+ projects: nextState.projects.map((project) => ({+ ...project,+ undoRedo: { future: [], past: [] },+ })),};};diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.tsindex c01c7b993e..fe00eb06f6 100644--- a/invokeai/frontend/webv2/src/workbench/projectContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts@@ -88,6 +88,8 @@ export interface GraphHistorySnapshot {id: string;createdAt: string;label: string;+ /** UTF-8 serialized bytes retained by this snapshot, populated during creation or hydration. */+ retainedBytes?: number;graph?: GraphContract;document?: ProjectGraphState;}diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 0007fd4d42..97c3384ed2 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -19,6 +19,7 @@ import { createEmptyCanvasDocumentV2 } from './canvasMigration';import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './canvasStagingView';import { DEFAULT_PROJECT_SETTINGS } from './settings/store';import { getProjectWidgetValues } from './widgetState';+import { GRAPH_HISTORY_BYTE_BUDGET, normalizeGraphHistory } from './workbenchState';import {createInitialWorkbenchState,nextLayerName,@@ -1491,6 +1492,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(project.projectGraph.id).toBe('replacement-graph');expect(project.graphHistory[0]?.document?.id).toBe(originalGraphId);+ expect(project.graphHistory[0]?.retainedBytes).toBeGreaterThan(0);+ expect(project.graphHistory[0]?.document).toBe(project.undoRedo.past.at(-1)?.project.projectGraph);state = workbenchReducer(state, {snapshotId: project.graphHistory[0]?.id ?? '',@@ -1500,6 +1503,25 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).projectGraph.id).toBe(originalGraphId);});+ it('normalizes graph history within count and UTF-8 retained-byte budgets', () => {+ const entries = Array.from({ length: 50 }, (_, index) => ({+ createdAt: `2026-07-19T00:00:${String(index).padStart(2, '0')}.000Z`,+ document: { edges: [], nodes: [], version: 1 as const },+ id: `snapshot-${index}`,+ label: `Snapshot ${index}`,+ retainedBytes: 2 * 1024 * 1024,+ }));+ const normalized = normalizeGraphHistory(entries);++ expect(normalized).toHaveLength(32);+ expect(normalized.reduce((total, entry) => total + (entry.retainedBytes ?? 0), 0)).toBeLessThanOrEqual(+ GRAPH_HISTORY_BYTE_BUDGET+ );++ const legacy = normalizeGraphHistory([{ ...entries[0], retainedBytes: undefined }]);+ expect(legacy[0]?.retainedBytes).toBeGreaterThan(0);+ });+it('does not queue Upscale while its required settings are incomplete', () => {let state = createInitialWorkbenchState();diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 089b30df44..266be41b4e 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -255,6 +255,7 @@ type WorkbenchReducerAction =| { type: 'recordNotice'; kind: WorkbenchNotificationKind; title: string; message?: string };const HISTORY_LIMIT = 40;+export const GRAPH_HISTORY_BYTE_BUDGET = 64 * 1024 * 1024;const NOTIFICATION_LIMIT = 100;const MIN_PANEL_SIZE_PX = 180;const MAX_PANEL_SIZE_PX = 520;@@ -801,10 +802,13 @@ const cloneWidgetGraphs = (widgetGraphs: Project['widgetGraphs']): Project['widg// engine owns its own pixel-patch history, so project-level undo/redo neither// snapshots nor restores canvas — `restoreUndoSnapshot` passes the live// `project.canvas` straight through via the `...project` spread.-const createUndoSnapshot = (project: Project): ProjectUndoSnapshot => ({+const createUndoSnapshot = (+ project: Project,+ projectGraph = cloneProjectGraph(project.projectGraph)+): ProjectUndoSnapshot => ({invocation: { ...project.invocation },layout: { ...project.layout, panels: { ...project.layout.panels } },- projectGraph: cloneProjectGraph(project.projectGraph),+ projectGraph,widgetGraphs: cloneWidgetGraphs(project.widgetGraphs),widgetInstances: cloneWidgetInstances(project.widgetInstances),widgetRegions: cloneWidgetRegions(project.widgetRegions),@@ -820,22 +824,96 @@ const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): PwidgetRegions: cloneWidgetRegions(snapshot.widgetRegions),});-const createGraphHistorySnapshot = (label: string, graph: GraphContract): GraphHistorySnapshot => ({- createdAt: now(),- graph: cloneGraph(graph),- id: createId('graph-history'),- label,+const UTF8_ENCODER = new TextEncoder();++const getGraphHistorySnapshotBytes = (snapshot: GraphHistorySnapshot): number => {+ const { retainedBytes: _retainedBytes, ...serialized } = snapshot;+ let retainedBytes = 0;++ // Include the metadata field itself in the serialized-size budget. Its digit+ // count can change the answer, so converge on the stable JSON byte length.+ for (;;) {+ const nextRetainedBytes = UTF8_ENCODER.encode(JSON.stringify({ ...serialized, retainedBytes })).byteLength;+ if (nextRetainedBytes === retainedBytes) {+ return retainedBytes;+ }+ retainedBytes = nextRetainedBytes;+ }+};++const withRetainedBytes = (snapshot: GraphHistorySnapshot): GraphHistorySnapshot => ({+ ...snapshot,+ retainedBytes: getGraphHistorySnapshotBytes(snapshot),});+export const normalizeGraphHistory = (value: unknown): GraphHistorySnapshot[] => {+ if (!Array.isArray(value)) {+ return [];+ }++ const history: GraphHistorySnapshot[] = [];+ let retainedBytes = 0;++ for (const item of value) {+ if (history.length >= HISTORY_LIMIT || !item || typeof item !== 'object') {+ continue;+ }++ const snapshot = item as GraphHistorySnapshot;+ if (+ typeof snapshot.id !== 'string' ||+ typeof snapshot.createdAt !== 'string' ||+ typeof snapshot.label !== 'string'+ ) {+ continue;+ }++ const normalized =+ typeof snapshot.retainedBytes === 'number' &&+ Number.isFinite(snapshot.retainedBytes) &&+ snapshot.retainedBytes >= 0+ ? snapshot+ : withRetainedBytes(snapshot);+ const snapshotBytes = normalized.retainedBytes ?? 0;++ if (snapshotBytes > GRAPH_HISTORY_BYTE_BUDGET || retainedBytes + snapshotBytes > GRAPH_HISTORY_BYTE_BUDGET) {+ continue;+ }++ retainedBytes += snapshotBytes;+ history.push(normalized);+ }++ return history;+};++const prependGraphHistory = (+ history: readonly GraphHistorySnapshot[],+ snapshot: GraphHistorySnapshot+): GraphHistorySnapshot[] => normalizeGraphHistory([snapshot, ...history]);++const createGraphHistorySnapshot = (label: string, graph: GraphContract): GraphHistorySnapshot =>+ withRetainedBytes({+ createdAt: now(),+ graph: cloneGraph(graph),+ id: createId('graph-history'),+ label,+ });+/** A restorable history entry carrying the editable workflow document. */-const createDocumentHistorySnapshot = (label: string, document: ProjectGraphState): GraphHistorySnapshot => ({- createdAt: now(),- document: cloneProjectGraph(document),- id: createId('graph-history'),- label,-});+const createDocumentHistorySnapshot = (+ label: string,+ document: ProjectGraphState,+ cloneDocument = true+): GraphHistorySnapshot =>+ withRetainedBytes({+ createdAt: now(),+ document: cloneDocument ? cloneProjectGraph(document) : document,+ id: createId('graph-history'),+ label,+ });-const pushUndo = (project: Project, label: string): Project => ({+const pushUndo = (project: Project, label: string, projectGraph?: ProjectGraphState): Project => ({...project,undoRedo: {future: [],@@ -845,7 +923,7 @@ const pushUndo = (project: Project, label: string): Project => ({createdAt: now(),id: createId('undo'),label,- project: createUndoSnapshot(project),+ project: createUndoSnapshot(project, projectGraph),},].slice(-HISTORY_LIMIT),},@@ -1075,6 +1153,7 @@ export const normalizeWorkbenchProject = (project: Project): Project => {// `project` may come straight from persisted storage (an unsafe cast boundary), so its// canvas can still be v1-shaped, malformed, or missing — migrate before cloning.canvas,+ graphHistory: normalizeGraphHistory((project as Partial<Project>).graphHistory),projectGraph: normalizeProjectGraph(project.projectGraph),promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),queue: normalizeWorkbenchQueueHistory(project.queue, { canvas, widgetInstances }),@@ -1777,7 +1856,7 @@ const enqueueCompiledSnapshot = (},...project.events,],- graphHistory: [graphHistorySnapshot, ...project.graphHistory].slice(0, HISTORY_LIMIT),+ graphHistory: prependGraphHistory(project.graphHistory, graphHistorySnapshot),promptHistory: generateSettings? addPromptHistoryItem(project.promptHistory, getPromptHistoryItemFromGenerateSettings(generateSettings)): upscaleSettings@@ -2225,8 +2304,14 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe});}case 'replaceProjectGraph': {+ let didRetainOutgoingGraph = true;const nextState = updateActiveProject(state, (project) => {- const nextProject = pushUndo(project, 'Replace project graph');+ // One immutable clone is shared by undo and graph history; neither+ // snapshot path mutates the document.+ const outgoingGraph = cloneProjectGraph(project.projectGraph);+ const nextProject = pushUndo(project, 'Replace project graph', outgoingGraph);+ const historySnapshot = createDocumentHistorySnapshot(`Before: ${action.label}`, outgoingGraph, false);+ didRetainOutgoingGraph = (historySnapshot.retainedBytes ?? 0) <= GRAPH_HISTORY_BYTE_BUDGET;return {...nextProject,@@ -2239,10 +2324,7 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe},...nextProject.events,],- graphHistory: [- createDocumentHistorySnapshot(`Before: ${action.label}`, project.projectGraph),- ...nextProject.graphHistory,- ].slice(0, HISTORY_LIMIT),+ graphHistory: prependGraphHistory(nextProject.graphHistory, historySnapshot),projectGraph: cloneProjectGraph(action.document),};});@@ -2252,7 +2334,9 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: WorkbenextState,createNotification({kind: 'info',- message: `The previous project graph was saved to graph history.`,+ message: didRetainOutgoingGraph+ ? 'The previous project graph was saved to graph history.'+ : 'The previous project graph exceeded the 64 MiB history budget, so its graph-history snapshot was skipped. Undo remains available for this session.',projectId: activeProject?.id,title: `Project graph replaced (${action.label})`,})@@ -2270,13 +2354,13 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe},...project.events,],- graphHistory: [+ graphHistory: prependGraphHistory(+ project.graphHistory,createDocumentHistorySnapshot(`Manual save: ${project.projectGraph.name || 'Untitled Workflow'}`,project.projectGraph- ),- ...project.graphHistory,- ].slice(0, HISTORY_LIMIT),+ )+ ),}));}case 'restoreProjectGraphSnapshot': {@@ -2291,10 +2375,10 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbereturn {...nextProject,- graphHistory: [- createDocumentHistorySnapshot('Before restore', project.projectGraph),- ...nextProject.graphHistory,- ].slice(0, HISTORY_LIMIT),+ graphHistory: prependGraphHistory(+ nextProject.graphHistory,+ createDocumentHistorySnapshot('Before restore', project.projectGraph)+ ),projectGraph: cloneProjectGraph(normalizeProjectGraph(snapshot.document)),};});