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.

feat(webv2): autosave bound workflows to the library with a header sync indicator

joshistoast375500086a8b
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index daa9a1599e..8a33e59c05 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2217,6 +2217,7 @@
"about": "About",
"addNode": "Add node",
"author": "Author",
+ "autosavesToLibrary": "Autosaves to library",
"class": "Class",
"connectorNode": "Connector node",
"contact": "Contact",
@@ -2239,6 +2240,10 @@
"template": "Template"
},
"library": "Workflow library",
+ "librarySyncError": "Library save failed — click to retry",
+ "librarySyncSaved": "Saved to library",
+ "librarySyncSaving": "Saving to library…",
+ "librarySyncState": "Library sync state",
"nodeData": "Node data",
"nodeInspector": "Node Inspector",
"nodeNotes": "Node notes",
@@ -2255,6 +2260,7 @@
"runOutputsNotRecorded": "Run outputs are not recorded per node yet; results currently route to the Gallery or Canvas. This tab will show the node's outputs from its most recent run once run records land.",
"newWorkflowWithEllipsis": "New workflow…",
"saveGraphSnapshot": "Save graph snapshot",
+ "saveToLibrary": "Save to library",
"selectNodeToInspect": "Select a node in the Workflow editor to inspect it.",
"selectedNodeInspector": "Selected node inspector",
"tags": "Tags",
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
index 4193617674..ae590a94e6 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
@@ -1,7 +1,7 @@
import { getLibraryWorkflow, touchLibraryWorkflowOpenedAt } from '@features/workflow/data/api';
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';
-import { parseWorkflowJson } from '@features/workflow/utility';
+import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
assertAccountScopeCurrent,
@@ -11,6 +11,7 @@ import {
import { getApiErrorMessage } from '@platform/transport/http';
import { useTranslation } from 'react-i18next';
+import { markLibraryGraphSynced } from './library/librarySyncBridge';
import { startWorkflowUiPendingLoadRuntime } from './pendingLibraryWorkflowLoadRuntime';
/**
@@ -36,6 +37,10 @@ export const PendingLibraryWorkflowLoader = () => {
const name = typeof raw.name === 'string' && raw.name.length > 0 ? raw.name : 'workflow';
replace(document, t('commandPalette.workflowLoad.loaded', { name }));
+ // Same reasoning as the library dialog's load path: the graph just
+ // loaded is already in sync with the library record it came from, so
+ // mark it synced before the autosaver's graph-changed effect sees it.
+ markLibraryGraphSynced(serializeWorkflowJson(document));
for (const warning of warnings) {
notify.info(t('commandPalette.workflowLoad.warning'), warning);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
index 061509335b..4fa687dd33 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
@@ -1,6 +1,7 @@
import type { InvocationTemplate, XYPosition } from '@features/workflow/contracts';
import { HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';
+import { updateLibraryWorkflow } from '@features/workflow/queries';
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import {
buildConnectorNode,
@@ -14,18 +15,31 @@ import {
getCompatibleInputTemplate,
getCompatibleOutputTemplate,
parseWorkflowJson,
+ serializeWorkflowJson,
} from '@features/workflow/utility';
import { Button, IconButton, ConfirmDialog, Tooltip } from '@platform/ui';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
-import { HistoryIcon, LibraryIcon, PlusIcon } from 'lucide-react';
-import { useCallback, useEffect, useId, useMemo, useRef, type ChangeEvent } from 'react';
+import {
+ CloudAlertIcon,
+ CloudCheckIcon,
+ CloudUploadIcon,
+ HistoryIcon,
+ LibraryIcon,
+ PlusIcon,
+ RefreshCwIcon,
+} from 'lucide-react';
+import { useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent } from 'react';
import { useTranslation } from 'react-i18next';
import type { WorkflowWidgetLabelProps, WorkflowWidgetViewProps } from './contracts';
import { AddNodeDialog } from './editor/AddNodeDialog';
import { getWorkflowFlowInstance } from './editor/flowInstanceStore';
+import { createLibraryAutosaver } from './library/libraryAutosave';
+import { registerLibraryGraphSyncedHandler, releaseLibraryGraphSyncedHandler } from './library/librarySyncBridge';
+import { useSaveWorkflowToLibrary } from './library/useSaveWorkflowToLibrary';
import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';
+import { setWorkflowLibrarySyncStatus, workflowLibrarySyncStore } from './library/workflowLibrarySyncStore';
import { PendingLibraryWorkflowLoader } from './PendingLibraryWorkflowLoader';
import { copyWorkflowJson, downloadWorkflowJson } from './workflowTransfer';
import {
@@ -142,11 +156,15 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {
export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {
const { t } = useTranslation();
const graphHistory = useWorkflowProjectSelector((project) => project.graphHistory);
+ const libraryWorkflowId = useWorkflowProjectSelector((project) => project.projectGraph.libraryWorkflowId);
+ const syncStatus = workflowLibrarySyncStore.useSelector((snapshot) => snapshot.status);
const { restoreSnapshot } = useProjectGraphCommands();
+ const { saveToLibrary } = useSaveWorkflowToLibrary();
const restorableHistory = graphHistory.filter((entry) => entry.document);
const historyTriggerId = useId();
const openAddNode = useCallback(() => setAddNodeOpen(true), []);
const openWorkflowLibrary = useCallback(() => setWorkflowLibraryOpen(true), []);
+ const handleSaveToLibrary = useCallback(() => void saveToLibrary(), [saveToLibrary]);
const historyIds = useMemo(() => ({ trigger: historyTriggerId }), [historyTriggerId]);
const historyPositioning = useMemo(() => ({ placement: 'bottom-end' as const }), []);
const restoreHistoryEntry = useCallback(
@@ -186,6 +204,48 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {
</IconButton>
</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>
+ ) : (
+ <Tooltip content={t('widgets.workflow.saveToLibrary')}>
+ <IconButton
+ aria-label={t('widgets.workflow.saveToLibrary')}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={handleSaveToLibrary}
+ >
+ <Icon as={CloudUploadIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ )}
<Menu.Root ids={historyIds} positioning={historyPositioning} onSelect={restoreHistoryEntry}>
<Tooltip content={t('widgets.workflow.graphHistorySnapshots')} ids={historyIds}>
<Menu.Trigger asChild>
@@ -230,6 +290,7 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {
export const WorkflowDialogHost = () => {
const { editGraph, replace } = useProjectGraphCommands();
+ const { project: projectStore } = useWorkflowUi();
const notify = useWorkflowNotifications();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const addNodeConnection = workflowUiStore.useSelector((snapshot) => snapshot.addNodeConnection);
@@ -240,6 +301,46 @@ export const WorkflowDialogHost = () => {
const isNewWorkflowConfirmOpen = workflowUiStore.useSelector((snapshot) => snapshot.isNewWorkflowConfirmOpen);
const lastImportRequestRef = useRef(importRequestCount);
+ // 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.
+ const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);
+ const [autosaver] = useState(() =>
+ createLibraryAutosaver({
+ onStatus: setWorkflowLibrarySyncStatus,
+ read: () => {
+ const graph = projectStore.getSnapshot().projectGraph;
+ return { libraryWorkflowId: graph.libraryWorkflowId, serialized: serializeWorkflowJson(graph) };
+ },
+ save: (workflowId, serialized) => updateLibraryWorkflow(workflowId, 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.
+ const lastGraphRef = useRef(projectGraph);
+ useEffect(() => {
+ if (lastGraphRef.current !== projectGraph) {
+ lastGraphRef.current = projectGraph;
+ autosaver.notifyGraphChanged();
+ }
+ }, [autosaver, projectGraph]);
+ useEffect(() => {
+ const handler = (serialized: Record<string, unknown>) => autosaver.markSynced(serialized);
+
+ registerLibraryGraphSyncedHandler(handler);
+ return () => releaseLibraryGraphSyncedHandler(handler);
+ }, [autosaver]);
+ useEffect(() => () => autosaver.dispose(), [autosaver]);
+
useEffect(() => {
if (importRequestCount > lastImportRequestRef.current) {
fileInputRef.current?.click();
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
index f96bdd5a90..41eb5896a4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
@@ -3,14 +3,12 @@ import type { ProjectGraphState } from '@features/workflow/contracts';
import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Spinner, Stack, Tabs, Text } from '@chakra-ui/react';
import {
- createLibraryWorkflow,
deleteLibraryWorkflow,
getCachedWorkflowPage,
getLibraryWorkflowCached,
invalidateWorkflowLibraryCache,
listLibraryWorkflowsCached,
touchLibraryWorkflowOpenedAt,
- updateLibraryWorkflow,
type WorkflowLibraryCategory,
type WorkflowLibraryListItem,
} from '@features/workflow/queries';
@@ -30,6 +28,9 @@ import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
import { useTranslation } from 'react-i18next';
+import { markLibraryGraphSynced } from './librarySyncBridge';
+import { useSaveWorkflowToLibrary } from './useSaveWorkflowToLibrary';
+
/**
* Backend workflow library browser: list/search user and default workflows,
* preview one (read-only nodes / JSON) before loading it into the project
@@ -108,9 +109,11 @@ export const WorkflowLibraryDialog = ({
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
}) => {
+ const { t } = useTranslation();
const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);
- const { bindLibraryWorkflow, replace } = useProjectGraphCommands();
+ const { replace } = useProjectGraphCommands();
const notify = useWorkflowNotifications();
+ const { saveAsNew, saveToLibrary: saveExistingToLibrary } = useSaveWorkflowToLibrary();
const [category, setCategory] = useState<WorkflowLibraryCategory>('user');
const [searchTerm, setSearchTerm] = useState('');
const [items, setItems] = useState<WorkflowLibraryListItem[]>([]);
@@ -222,6 +225,10 @@ export const WorkflowLibraryDialog = ({
assertAccountScopeCurrent(owner);
replace(parsed.document, `Loaded "${item.name}" from library`);
+ // The freshly-loaded graph is already in sync with the library record it
+ // came from — mark it synced so the autosaver does not immediately
+ // queue a redundant (echo) save the moment the graph reference changes.
+ markLibraryGraphSynced(serializeWorkflowJson(parsed.document));
for (const warning of parsed.warnings) {
notify.info('Workflow load warning', warning);
@@ -274,29 +281,14 @@ export const WorkflowLibraryDialog = ({
setIsSaving(true);
try {
- const serialized = serializeWorkflowJson(projectGraph);
-
- if (!asNew && projectGraph.libraryWorkflowId) {
- await updateLibraryWorkflow(projectGraph.libraryWorkflowId, serialized, owner.signal);
+ // useSaveWorkflowToLibrary already notifies on success/failure and
+ // invalidates the library cache; this dialog only needs to refresh its
+ // own list once the save (and any resulting bind) has landed.
+ const workflowId = asNew ? await saveAsNew() : await saveExistingToLibrary();
- assertAccountScopeCurrent(owner);
- notify.success('Workflow saved', `Updated "${projectGraph.name || 'Untitled Workflow'}" in the library.`);
- } else {
- const workflowId = await createLibraryWorkflow(serialized, owner.signal);
-
- assertAccountScopeCurrent(owner);
- bindLibraryWorkflow(workflowId);
- notify.success('Workflow saved', `Saved "${projectGraph.name || 'Untitled Workflow'}" to the library.`);
+ if (workflowId && isAccountScopeCurrent(owner)) {
+ refresh(page, owner);
}
-
- invalidateWorkflowLibraryCache();
- refresh(page, owner);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notify.error('Failed to save workflow', getApiErrorMessage(error, 'The workflow could not be saved.'));
} finally {
if (isAccountScopeCurrent(owner)) {
setIsSaving(false);
@@ -500,15 +492,19 @@ export const WorkflowLibraryDialog = ({
</Text>
<HStack flexShrink={0} gap="2">
{projectGraph.libraryWorkflowId ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('widgets.workflow.autosavesToLibrary')}
+ </Text>
+ ) : (
<Button
loading={isSaving}
size="2xs"
variant="outline"
onClick={() => void saveToLibrary(false)}
>
- Save
+ {t('widgets.workflow.saveToLibrary')}
</Button>
- ) : null}
+ )}
<Button
loading={isSaving}
size="2xs"
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts
new file mode 100644
index 0000000000..6bf6d9e9ef
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts
@@ -0,0 +1,27 @@
+/**
+ * Module-level bridge to the single mounted `WorkflowDialogHost`'s library
+ * autosaver, mirroring `editor/flowInstanceStore.ts`'s pattern for surfaces
+ * that need to reach a widget-scoped instance without threading it through
+ * props or importing the chrome component (which would cycle back through
+ * this directory). `WorkflowDialogHost` registers its autosaver's
+ * `markSynced` in a mount effect; `WorkflowLibraryDialog`'s load path and
+ * `useSaveWorkflowToLibrary` call `markLibraryGraphSynced` after a
+ * load/save so the freshly-synced content is not immediately queued for
+ * another autosave pass.
+ */
+
+type MarkSyncedFn = (serialized: Record<string, unknown>) => void;
+
+let markSyncedImpl: MarkSyncedFn | null = null;
+
+export const registerLibraryGraphSyncedHandler = (fn: MarkSyncedFn): void => {
+ markSyncedImpl = fn;
+};
+
+export const releaseLibraryGraphSyncedHandler = (fn: MarkSyncedFn): void => {
+ if (markSyncedImpl === fn) {
+ markSyncedImpl = null;
+ }
+};
+
+export const markLibraryGraphSynced: MarkSyncedFn = (serialized) => markSyncedImpl?.(serialized);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts
new file mode 100644
index 0000000000..d52695479a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts
@@ -0,0 +1,78 @@
+import {
+ createLibraryWorkflow,
+ invalidateWorkflowLibraryCache,
+ updateLibraryWorkflow,
+} from '@features/workflow/queries';
+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
+import { useWorkflowNotifications, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';
+import { serializeWorkflowJson } from '@features/workflow/utility';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { useCallback } from 'react';
+
+import { markLibraryGraphSynced } from './librarySyncBridge';
+import { setWorkflowLibrarySyncStatus } from './workflowLibrarySyncStore';
+
+/**
+ * Saves the project graph to the backend workflow library — shared by the
+ * library dialog's Save/Save as new buttons and the header's one-click save
+ * for unbound graphs. A successful save also marks the autosaver's baseline
+ * (`markLibraryGraphSynced`) so the freshly-saved content is not immediately
+ * queued for another autosave pass.
+ */
+export const useSaveWorkflowToLibrary = (): {
+ saveAsNew: () => Promise<string | null>;
+ saveToLibrary: () => Promise<string | null>;
+} => {
+ const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);
+ const { bindLibraryWorkflow } = useProjectGraphCommands();
+ const notify = useWorkflowNotifications();
+
+ const save = useCallback(
+ async (asNew: boolean): Promise<string | null> => {
+ const owner = captureAccountScope();
+
+ try {
+ const serialized = serializeWorkflowJson(projectGraph);
+ let workflowId: string;
+
+ if (!asNew && projectGraph.libraryWorkflowId) {
+ workflowId = projectGraph.libraryWorkflowId;
+ await updateLibraryWorkflow(workflowId, serialized, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ notify.success('Workflow saved', `Updated "${projectGraph.name || 'Untitled Workflow'}" in the library.`);
+ } else {
+ workflowId = await createLibraryWorkflow(serialized, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ bindLibraryWorkflow(workflowId);
+ notify.success('Workflow saved', `Saved "${projectGraph.name || 'Untitled Workflow'}" to the library.`);
+ }
+
+ markLibraryGraphSynced(serialized);
+ setWorkflowLibrarySyncStatus('saved');
+ invalidateWorkflowLibraryCache();
+
+ return workflowId;
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return null;
+ }
+
+ notify.error('Failed to save workflow', getApiErrorMessage(error, 'The workflow could not be saved.'));
+ return null;
+ }
+ },
+ [bindLibraryWorkflow, notify, projectGraph]
+ );
+
+ const saveToLibrary = useCallback(() => save(false), [save]);
+ const saveAsNew = useCallback(() => save(true), [save]);
+
+ return { saveAsNew, saveToLibrary };
+};