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): add debounced library autosave core for bound workflows

joshistoast32c95587ca07
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts
new file mode 100644
index 0000000000..27575e14ba
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createLibraryAutosaver, type LibrarySyncStatus } from './libraryAutosave';
+
+const createManualTimers = () => {
+ const pending = new Map<number, () => void>();
+ let nextHandle = 1;
+ return {
+ fire: () => {
+ const jobs = [...pending.values()];
+ pending.clear();
+ for (const job of jobs) {
+ job();
+ }
+ },
+ pendingCount: () => pending.size,
+ timers: {
+ clearTimeout: (handle: number) => void pending.delete(handle),
+ setTimeout: (fn: () => void, _ms: number) => {
+ const handle = nextHandle++;
+ pending.set(handle, fn);
+ return handle;
+ },
+ },
+ };
+};
+
+const createHarness = (initial: { id?: string; graph?: Record<string, unknown> } = {}) => {
+ let current = { libraryWorkflowId: initial.id ?? 'wf-1', serialized: initial.graph ?? { nodes: [1] } };
+ const statuses: LibrarySyncStatus[] = [];
+ const save = vi.fn(() => Promise.resolve());
+ const manual = createManualTimers();
+ const autosaver = createLibraryAutosaver({
+ onStatus: (status) => void statuses.push(status),
+ read: () => current,
+ save,
+ timers: manual.timers,
+ });
+ return { autosaver, manual, save, setCurrent: (next: typeof current) => (current = next), statuses };
+};
+
+describe('createLibraryAutosaver', () => {
+ it('debounces a change and saves the bound workflow', async () => {
+ const h = createHarness();
+ h.autosaver.notifyGraphChanged();
+ expect(h.save).not.toHaveBeenCalled();
+ h.manual.fire();
+ await h.autosaver.flush();
+ expect(h.save).toHaveBeenCalledWith('wf-1', { nodes: [1] });
+ expect(h.statuses).toEqual(['dirty', 'saving', 'saved']);
+ });
+
+ it('skips saving when the serialized graph has not changed since the last save', async () => {
+ const h = createHarness();
+ h.autosaver.notifyGraphChanged();
+ h.manual.fire();
+ await h.autosaver.flush();
+ h.autosaver.notifyGraphChanged(); // same content
+ h.manual.fire();
+ await h.autosaver.flush();
+ expect(h.save).toHaveBeenCalledTimes(1);
+ });
+
+ it('markSynced suppresses the echo save after a load/bind', async () => {
+ const h = createHarness();
+ h.autosaver.markSynced({ nodes: [1] });
+ h.autosaver.notifyGraphChanged();
+ h.manual.fire();
+ await h.autosaver.flush();
+ expect(h.save).not.toHaveBeenCalled();
+ });
+
+ it('does nothing for an unbound workflow', () => {
+ const h = createHarness();
+ h.setCurrent({ libraryWorkflowId: undefined as unknown as string, serialized: { nodes: [1] } });
+ h.autosaver.notifyGraphChanged();
+ expect(h.manual.pendingCount()).toBe(0);
+ expect(h.statuses).toEqual([]);
+ });
+
+ it('reports error status on a failed save and retries on the next change', async () => {
+ const h = createHarness();
+ h.save.mockRejectedValueOnce(new Error('offline'));
+ h.autosaver.notifyGraphChanged();
+ h.manual.fire();
+ await h.autosaver.flush();
+ expect(h.statuses.at(-1)).toBe('error');
+ h.setCurrent({ libraryWorkflowId: 'wf-1', serialized: { nodes: [2] } });
+ h.autosaver.notifyGraphChanged();
+ h.manual.fire();
+ await h.autosaver.flush();
+ expect(h.save).toHaveBeenCalledTimes(2);
+ expect(h.statuses.at(-1)).toBe('saved');
+ });
+
+ it('dispose cancels pending work', () => {
+ const h = createHarness();
+ h.autosaver.notifyGraphChanged();
+ h.autosaver.dispose();
+ h.manual.fire();
+ expect(h.save).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts
new file mode 100644
index 0000000000..25ee284c8f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts
@@ -0,0 +1,107 @@
+/**
+ * Figma-style library sync: a project graph bound to a library workflow saves
+ * itself back to the library after edits settle. Content-addressed dedupe (the
+ * serialized JSON string) prevents echo saves; a failed save parks in 'error'
+ * and is retried by the next graph change or an explicit flush(). No automatic
+ * retry loop — persistent failures must not spin (cf. bitmapStore anti-spin).
+ */
+
+export type LibrarySyncStatus = 'idle' | 'dirty' | 'saving' | 'saved' | 'error';
+
+export interface LibraryAutosaverDeps {
+ read(): { libraryWorkflowId: string | undefined; serialized: Record<string, unknown> };
+ save(workflowId: string, serialized: Record<string, unknown>): Promise<void>;
+ onStatus(status: LibrarySyncStatus): void;
+ /** Idle window before a save (default 2000ms). */
+ debounceMs?: number;
+ timers?: {
+ setTimeout(fn: () => void, ms: number): number;
+ clearTimeout(handle: number): void;
+ };
+}
+
+export const DEFAULT_LIBRARY_AUTOSAVE_DEBOUNCE_MS = 2000;
+
+export const createLibraryAutosaver = (deps: LibraryAutosaverDeps) => {
+ const debounceMs = deps.debounceMs ?? DEFAULT_LIBRARY_AUTOSAVE_DEBOUNCE_MS;
+ const timers = deps.timers ?? {
+ clearTimeout: (handle: number) => globalThis.clearTimeout(handle),
+ setTimeout: (fn: () => void, ms: number) => globalThis.setTimeout(fn, ms),
+ };
+
+ let timerHandle: number | null = null;
+ let inFlight: Promise<void> | null = null;
+ let lastSavedJson: string | null = null;
+ let disposed = false;
+
+ const clearTimer = (): void => {
+ if (timerHandle !== null) {
+ timers.clearTimeout(timerHandle);
+ timerHandle = null;
+ }
+ };
+
+ const runSave = (): Promise<void> => {
+ if (inFlight) {
+ return inFlight;
+ }
+
+ const { libraryWorkflowId, serialized } = deps.read();
+
+ if (disposed || !libraryWorkflowId) {
+ return Promise.resolve();
+ }
+
+ const json = JSON.stringify(serialized);
+
+ if (json === lastSavedJson) {
+ return Promise.resolve();
+ }
+
+ deps.onStatus('saving');
+ inFlight = deps
+ .save(libraryWorkflowId, serialized)
+ .then(() => {
+ lastSavedJson = json;
+ if (!disposed) {
+ deps.onStatus('saved');
+ }
+ })
+ .catch(() => {
+ if (!disposed) {
+ deps.onStatus('error');
+ }
+ })
+ .finally(() => {
+ inFlight = null;
+ });
+
+ return inFlight;
+ };
+
+ return {
+ dispose: (): void => {
+ disposed = true;
+ clearTimer();
+ },
+ flush: (): Promise<void> => {
+ clearTimer();
+ return runSave();
+ },
+ /** Marks the last save as matching `serialized` — call after load/bind so the loaded state is not re-saved. */
+ markSynced: (serialized: Record<string, unknown>): void => {
+ lastSavedJson = JSON.stringify(serialized);
+ },
+ notifyGraphChanged: (): void => {
+ if (disposed || !deps.read().libraryWorkflowId) {
+ return;
+ }
+ deps.onStatus('dirty');
+ clearTimer();
+ timerHandle = timers.setTimeout(() => {
+ timerHandle = null;
+ void runSave();
+ }, debounceMs);
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibrarySyncStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibrarySyncStore.ts
new file mode 100644
index 0000000000..3e07966ebd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibrarySyncStore.ts
@@ -0,0 +1,17 @@
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+
+import type { LibrarySyncStatus } from './libraryAutosave';
+
+export const workflowLibrarySyncStore = createExternalStore<{ status: LibrarySyncStatus }>({ status: 'idle' });
+
+registerAccountOwnedResource({
+ clear: () => {
+ workflowLibrarySyncStore.setSnapshot({ status: 'idle' });
+ },
+ name: 'workflow-library-sync',
+});
+
+export const setWorkflowLibrarySyncStatus = (status: LibrarySyncStatus): void => {
+ workflowLibrarySyncStore.setSnapshot({ status });
+};