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): account-scope library autosaves and stop re-rendering the dialog host per edit
joshistoast76a4796a78a6
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.tsxindex 796ba3c6bd..47e5b60e17 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx@@ -1,15 +1,28 @@import { ChakraProvider } from '@chakra-ui/react';import { createProjectGraph } from '@features/workflow/utility';+import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';-import { act, StrictMode } from 'react';+import { act, Profiler, 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 { workflowLibrarySyncStore } from './library/workflowLibrarySyncStore';import { WorkflowUiProvider } from './WorkflowUiContext';import { WorkflowDialogHost } from './WorkflowWidgetChrome';+const deferred = <T,>() => {+ let reject!: (reason?: unknown) => void;+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });++ return { promise, reject, resolve };+};+// 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.@@ -147,7 +160,194 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);expect(updateLibraryWorkflowMock).toHaveBeenCalledWith('library-workflow-1',- expect.objectContaining({ name: 'Edited name' })+ expect.objectContaining({ name: 'Edited name' }),+ expect.any(AbortSignal));});++ /**+ * The host used to learn about graph edits through a selector+ * (`useWorkflowProjectSelector`) feeding a change-detecting effect, which+ * re-rendered this component on every graph edit just to notice the+ * autosaver should be poked. Edits reach the project store through+ * imperative commands, not through this component's own props or state, so+ * there is nothing here that needs re-rendering to learn about them — a+ * direct store subscription (held in the same mount effect that owns the+ * autosaver) can notify the autosaver without forcing React back through+ * this component's render.+ */+ it('schedules an autosave for graph edits made outside React renders', async () => {+ workflowLibrarySyncStore.setSnapshot({ status: 'idle' });++ 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);++ let renderCount = 0;+ // eslint-disable-next-line react-perf/jsx-no-new-function-as-prop -- test-only render probe, not app code+ const countRender = () => {+ renderCount += 1;+ };++ await act(() => {+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <Profiler id="dialog-host" onRender={countRender}>+ <WorkflowDialogHost />+ </Profiler>+ </WorkflowUiProvider>+ </ChakraProvider>+ </StrictMode>+ );+ });++ // Only the edit dispatched below is under test; the mount itself renders+ // (StrictMode doubles it).+ renderCount = 0;++ // Dispatch a graph edit straight through the project store — the same+ // path an imperative command handler uses — rather than through a prop+ // that would force this component to re-render.+ await act(() => {+ project.setSnapshot({+ ...project.port.getSnapshot(),+ projectGraph: { ...boundGraph, name: 'Edited outside React' },+ });+ });++ expect(renderCount).toBe(0);+ expect(workflowLibrarySyncStore.getSnapshot().status).toBe('dirty');+ });++ /**+ * Account rotation (`accountLifecycle.activate`/`.invalidate`) aborts the+ * signal a save started under and synchronously resets+ * `workflowLibrarySyncStore` to 'idle' (it is an account-owned resource,+ * cleared by `clearResources()` inside `rotateScope`) — but the aborted+ * write's rejection lands a tick later, after that reset. A save's own+ * `assertAccountScopeCurrent` throw (which turns a late resolution into a+ * rejection so a stale write never gets treated as successful) is not+ * enough by itself: `runSave()`'s `.catch` still calls `onStatus('error')`+ * unconditionally, and without a scope guard on that callback the late+ * write would land 'error' in the *next* account's store. Modeled on the+ * account-rotation tests in `useScopedAction.browser.test.tsx`, which use+ * the real `accountLifecycle` singleton directly.+ */+ it('does not park a stale save error in the sync store after an account switch', async () => {+ const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };+ const project = createMutablePort({+ galleryValues: {},+ graphHistory: [],+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph: boundGraph,+ workflowValues: {},+ });++ const request = deferred<void>();++ updateLibraryWorkflowMock.mockReturnValue(request.promise);++ // 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>+ );+ });++ await act(() => {+ project.setSnapshot({+ ...project.port.getSnapshot(),+ projectGraph: { ...boundGraph, name: 'Edited before switch' },+ });+ });++ // Past the debounce: the save has started (captured the pre-switch+ // account scope) and is now awaiting the still-pending request below.+ await act(+ () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 2100);+ })+ );++ expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);++ try {+ // Switch accounts mid-flight: aborts the pre-switch scope's signal and+ // synchronously resets the sync store to 'idle' via clearResources().+ accountLifecycle.activate('workflow-dialog-host-test-account', ':user:workflow-dialog-host-test-account');++ expect(workflowLibrarySyncStore.getSnapshot().status).toBe('idle');++ // The deferred request settles after the switch — the same lag as an+ // in-flight fetch whose abort rejection arrives after the synchronous+ // store reset. Resolving (rather than rejecting) exercises the path+ // the review flagged: `assertAccountScopeCurrent` turns this into a+ // rejection inside `save()`, so a stale write is never mistaken for a+ // successful one.+ await act(async () => {+ request.resolve();+ await request.promise.catch(() => undefined);+ // Give the save's `.then`/`.catch` continuation a turn to run.+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(workflowLibrarySyncStore.getSnapshot().status).toBe('idle');+ } finally {+ accountLifecycle.invalidate();+ }+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 2f09168f51..87c20d2def 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -1,6 +1,6 @@import type { InvocationTemplate, XYPosition } from '@features/workflow/contracts';-import { HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { updateLibraryWorkflow } from '@features/workflow/queries';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {@@ -17,6 +17,11 @@ import {parseWorkflowJson,serializeWorkflowJson,} from '@features/workflow/utility';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';import { Button, IconButton, ConfirmDialog, Tooltip } from '@platform/ui';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import {@@ -35,7 +40,7 @@ import type { WorkflowWidgetLabelProps, WorkflowWidgetViewProps } from './contraimport { AddNodeDialog } from './editor/AddNodeDialog';import { getWorkflowFlowInstance } from './editor/flowInstanceStore';-import { createLibraryAutosaver } from './library/libraryAutosave';+import { createLibraryAutosaver, type LibrarySyncStatus } from './library/libraryAutosave';import { registerLibraryGraphSyncedHandler, releaseLibraryGraphSyncedHandler } from './library/librarySyncBridge';import { useSaveWorkflowToLibrary } from './library/useSaveWorkflowToLibrary';import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';@@ -64,6 +69,15 @@ import {* (always mounted) and are driven through `workflowUiStore`.*/+/** Icon + tooltip for each library sync status, shared by the sync control's error and non-error presentations. */+const SYNC_STATUS_VIEW: Record<LibrarySyncStatus, { icon: typeof CloudCheckIcon; tooltipKey: string }> = {+ dirty: { icon: RefreshCwIcon, tooltipKey: 'widgets.workflow.librarySyncSaving' },+ error: { icon: CloudAlertIcon, tooltipKey: 'widgets.workflow.librarySyncError' },+ idle: { icon: CloudCheckIcon, tooltipKey: 'widgets.workflow.librarySyncSaved' },+ saved: { icon: CloudCheckIcon, tooltipKey: 'widgets.workflow.librarySyncSaved' },+ saving: { icon: RefreshCwIcon, tooltipKey: 'widgets.workflow.librarySyncSaving' },+};+export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {const { t } = useTranslation();const workflowName = useWorkflowProjectSelector((project) => project.projectGraph.name);@@ -205,33 +219,30 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {</Tooltip>)}{libraryWorkflowId ? (- <Tooltip- content={- syncStatus === 'error'- ? t('widgets.workflow.librarySyncError')- : syncStatus === 'saving' || syncStatus === 'dirty'- ? t('widgets.workflow.librarySyncSaving')- : t('widgets.workflow.librarySyncSaved')- }- >- <IconButton- aria-label={t('widgets.workflow.librarySyncState')}- color={syncStatus === 'error' ? 'fg.error' : 'fg.subtle'}- size="2xs"- variant="ghost"- onClick={syncStatus === 'error' ? handleSaveToLibrary : undefined}- >- <Icon- as={- syncStatus === 'error'- ? CloudAlertIcon- : syncStatus === 'saving' || syncStatus === 'dirty'- ? RefreshCwIcon- : CloudCheckIcon- }- boxSize="3.5"- />- </IconButton>+ <Tooltip content={t(SYNC_STATUS_VIEW[syncStatus].tooltipKey)}>+ {syncStatus === 'error' ? (+ <IconButton+ aria-label={t('widgets.workflow.librarySyncState')}+ color="fg.error"+ size="2xs"+ variant="ghost"+ onClick={handleSaveToLibrary}+ >+ <Icon as={SYNC_STATUS_VIEW.error.icon} boxSize="3.5" />+ </IconButton>+ ) : (+ <Box+ alignItems="center"+ aria-label={t(SYNC_STATUS_VIEW[syncStatus].tooltipKey)}+ boxSize="6"+ color="fg.subtle"+ display="flex"+ justifyContent="center"+ role="status"+ >+ <Icon as={SYNC_STATUS_VIEW[syncStatus].icon} boxSize="3.5" />+ </Box>+ )}</Tooltip>) : (<Tooltip content={t('widgets.workflow.saveToLibrary')}>@@ -316,43 +327,64 @@ export const WorkflowDialogHost = () => {// 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 autosaverRef = useRef<ReturnType<typeof createLibraryAutosaver> | null>(null);-+ // debounce timer or `flush()` calls it. The same effect subscribes+ // directly to the project store to notify the autosaver of edits (skipping+ // the initial snapshot so loading a workflow does not itself count as an+ // edit) — a plain subscription rather than a selector, since nothing here+ // needs to re-render on graph edits, only to poke the autosaver.+ //+ // `hostScope` guards `onStatus`: account rotation aborts the in-flight+ // save's signal and synchronously resets the (account-owned)+ // `workflowLibrarySyncStore` back to 'idle', but the aborted write's+ // rejection lands a tick later, after that reset. Without this guard,+ // `runSave()`'s `.catch` would still write 'error' into the *next*+ // account's store — `save()`'s own `assertAccountScopeCurrent` throw stops+ // the write from being trusted, but does not by itself stop that throw's+ // `onStatus('error')` from landing. `hostScope` is captured once per mount+ // — safe because this host remounts every account epoch (keyed by+ // `session.accountEpoch` above it in the tree), so a mount-captured scope+ // never outlives the account it was captured for.useEffect(() => {+ const hostScope = captureAccountScope();const autosaver = createLibraryAutosaver({- onStatus: setWorkflowLibrarySyncStatus,+ onStatus: (status) => {+ if (isAccountScopeCurrent(hostScope)) {+ setWorkflowLibrarySyncStatus(status);+ }+ },read: () => {const graph = projectStore.getSnapshot().projectGraph;return { libraryWorkflowId: graph.libraryWorkflowId, serialized: serializeWorkflowJson(graph) };},- save: (workflowId, serialized) => updateLibraryWorkflow(workflowId, serialized),+ save: async (workflowId, serialized) => {+ // Same scope discipline as the manual save paths: never let a+ // debounced write land in the next account's library.+ const owner = captureAccountScope();+ await updateLibraryWorkflow(workflowId, serialized, owner.signal);+ assertAccountScopeCurrent(owner);+ },});- autosaverRef.current = autosaver;+ let lastGraph = projectStore.getSnapshot().projectGraph;+ const unsubscribe = projectStore.subscribe(() => {+ const graph = projectStore.getSnapshot().projectGraph;+ if (graph !== lastGraph) {+ lastGraph = graph;+ autosaver.notifyGraphChanged();+ }+ });const handler = (serialized: Record<string, unknown>) => autosaver.markSynced(serialized);registerLibraryGraphSyncedHandler(handler);return () => {+ unsubscribe();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;- autosaverRef.current?.notifyGraphChanged();- }- }, [projectGraph]);-useEffect(() => {if (importRequestCount > lastImportRequestRef.current) {fileInputRef.current?.click();