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(webv2): fix library autosaver StrictMode disposal
joshistoast37de34504bc4
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsxnew file mode 100644index 0000000000..796ba3c6bd--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx@@ -0,0 +1,153 @@+import { ChakraProvider } from '@chakra-ui/react';+import { createProjectGraph } from '@features/workflow/utility';+import { system } from '@theme/system';+import { act, StrictMode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { WorkflowUiAdapter } from './WorkflowUiContext';++import { WorkflowUiProvider } from './WorkflowUiContext';+import { WorkflowDialogHost } from './WorkflowWidgetChrome';++// The dialogs pull in heavy leaf UI (node search, the library browser, graph+// previews) that is irrelevant to the autosave wiring under test here; stub+// them out so this stays a focused wiring-layer test.+vi.mock('./editor/AddNodeDialog', () => ({ AddNodeDialog: () => null }));+vi.mock('./library/WorkflowLibraryDialog', () => ({ WorkflowLibraryDialog: () => null }));+vi.mock('./PendingLibraryWorkflowLoader', () => ({ PendingLibraryWorkflowLoader: () => null }));++const { updateLibraryWorkflowMock } = vi.hoisted(() => ({ updateLibraryWorkflowMock: vi.fn() }));++vi.mock('@features/workflow/queries', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ updateLibraryWorkflow: updateLibraryWorkflowMock,+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {+ let snapshot = initialSnapshot;+ const listeners = new Set<() => void>();+ return {+ port: {+ getSnapshot: () => snapshot,+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ setSnapshot: (next: Snapshot) => {+ snapshot = next;+ for (const listener of listeners) {+ listener();+ }+ },+ };+};++/**+ * Regression coverage for the StrictMode autosaver-disposal bug: the+ * autosaver used to be created once via a `useState` initializer and+ * disposed in a separate effect's cleanup. React StrictMode's dev-only+ * mount→cleanup→mount simulation ran that cleanup without ever re-running+ * the initializer (state is preserved across the simulation, effects are+ * not), permanently disposing the one live instance — autosave then+ * silently no-oped for the rest of the session. The fix creates AND+ * disposes the autosaver within a single mount effect (held in a ref), so+ * the simulation produces a fresh, live instance instead. Mounting under a+ * real `<StrictMode>` here reproduces that simulation; a test that mounted+ * without it would not have caught the bug.+ */+describe('WorkflowDialogHost library autosave under StrictMode', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ updateLibraryWorkflowMock.mockReset();+ updateLibraryWorkflowMock.mockResolvedValue(undefined);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('still autosaves a bound workflow after a graph edit', async () => {+ const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };+ const project = createMutablePort({+ galleryValues: {},+ graphHistory: [],+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph: boundGraph,+ workflowValues: {},+ });++ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime+ const adapter = {+ commands: {+ bindLibraryWorkflow: vi.fn(),+ editGraph: vi.fn(),+ redo: vi.fn(),+ replace: vi.fn(),+ restoreSnapshot: vi.fn(),+ saveSnapshot: vi.fn(),+ undo: vi.fn(),+ },+ getProjectGraph: () => project.port.getSnapshot().projectGraph,+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ project: project.port,+ widgets: { open: vi.fn(), patchValues: vi.fn() },+ } as unknown as WorkflowUiAdapter;++ root = createRoot(host);++ await act(() => {+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <WorkflowDialogHost />+ </WorkflowUiProvider>+ </ChakraProvider>+ </StrictMode>+ );+ });++ expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();++ // A graph edit on the already-bound project: a new object identity so the+ // dialog host's graph-changed effect fires and schedules the debounced+ // autosave.+ await act(() => {+ project.setSnapshot({+ ...project.port.getSnapshot(),+ projectGraph: { ...boundGraph, name: 'Edited name' },+ });+ });++ // Past the 2s debounce.+ await act(+ () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 2100);+ })+ );+ // Let the autosaver's save promise settle.+ await act(+ () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ })+ );++ expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);+ expect(updateLibraryWorkflowMock).toHaveBeenCalledWith(+ 'library-workflow-1',+ expect.objectContaining({ name: 'Edited name' })+ );+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 4fa687dd33..2f09168f51 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -28,7 +28,7 @@ import {PlusIcon,RefreshCwIcon,} from 'lucide-react';-import { useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent } from 'react';+import { useCallback, useEffect, useId, useMemo, useRef, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';import type { WorkflowWidgetLabelProps, WorkflowWidgetViewProps } from './contracts';@@ -303,43 +303,55 @@ export const WorkflowDialogHost = () => {// Library autosave: bound project graphs save themselves back to the// library after edits settle. This host is always mounted alongside the- // workflow widget, so one autosaver instance (created once via the lazy- // useState initializer) tracks the graph for the widget's whole lifetime.- // `read()` pulls straight from the project store's synchronous snapshot- // (`projectStore.getSnapshot()`, the same accessor `useWorkflowProjectSelector`- // subscribes through) rather than a component-owned ref, so it is always- // current whenever the autosaver's debounce timer or `flush()` calls it —- // no ref-freshness bookkeeping, and nothing here reads a ref during render.+ // workflow widget, so one autosaver instance tracks the graph for the+ // widget's whole lifetime — but that instance is created AND disposed+ // within a single mount effect (held in a ref, not a `useState`+ // initializer). A `useState` initializer only runs once per fiber, while+ // its disposal lived in a separate effect's cleanup; React StrictMode's+ // dev-only mount→cleanup→mount simulation ran that cleanup once without+ // ever re-running the initializer, permanently disposing the one instance+ // still in use (autosave silently no-oped for the rest of the session).+ // Creating and disposing in the same effect makes the simulation produce a+ // fresh, live instance instead. `read()` pulls straight from the project+ // store's synchronous snapshot (`projectStore.getSnapshot()`, the same+ // accessor `useWorkflowProjectSelector` subscribes through) rather than a+ // component-owned ref, so it is always current whenever the autosaver's+ // debounce timer or `flush()` calls it.const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);- const [autosaver] = useState(() =>- createLibraryAutosaver({+ const autosaverRef = useRef<ReturnType<typeof createLibraryAutosaver> | null>(null);++ useEffect(() => {+ const autosaver = createLibraryAutosaver({onStatus: setWorkflowLibrarySyncStatus,read: () => {const graph = projectStore.getSnapshot().projectGraph;return { libraryWorkflowId: graph.libraryWorkflowId, serialized: serializeWorkflowJson(graph) };},save: (workflowId, serialized) => updateLibraryWorkflow(workflowId, serialized),- })- );+ });++ autosaverRef.current = autosaver;++ const handler = (serialized: Record<string, unknown>) => autosaver.markSynced(serialized);- // External-system sync: notify the autosaver of edits (skipping the mount- // run so loading a workflow does not itself count as an edit), register- // the markSynced seam other surfaces reach through `librarySyncBridge`,- // and dispose on unmount.+ registerLibraryGraphSyncedHandler(handler);++ return () => {+ releaseLibraryGraphSyncedHandler(handler);+ autosaver.dispose();+ autosaverRef.current = null;+ };+ }, [projectStore]);++ // Notify the autosaver of edits, skipping the mount run so loading a+ // workflow does not itself count as an edit.const lastGraphRef = useRef(projectGraph);useEffect(() => {if (lastGraphRef.current !== projectGraph) {lastGraphRef.current = projectGraph;- autosaver.notifyGraphChanged();+ autosaverRef.current?.notifyGraphChanged();}- }, [autosaver, projectGraph]);- useEffect(() => {- const handler = (serialized: Record<string, unknown>) => autosaver.markSynced(serialized);-- registerLibraryGraphSyncedHandler(handler);- return () => releaseLibraryGraphSyncedHandler(handler);- }, [autosaver]);- useEffect(() => () => autosaver.dispose(), [autosaver]);+ }, [projectGraph]);useEffect(() => {if (importRequestCount > lastImportRequestRef.current) {