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.

fix(webv2): fit the editor to a workflow loaded from the library

Josh Corbett66e764d55999
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
index ae590a94e6..3927750081 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
@@ -1,4 +1,5 @@
import { getLibraryWorkflow, touchLibraryWorkflowOpenedAt } from '@features/workflow/data/api';
+import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';
import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';
@@ -37,6 +38,7 @@ export const PendingLibraryWorkflowLoader = () => {
const name = typeof raw.name === 'string' && raw.name.length > 0 ? raw.name : 'workflow';
replace(document, t('commandPalette.workflowLoad.loaded', { name }));
+ requestWorkflowFitView(document.nodes);
// 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.
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx
index c29c523b2a..75dedc1532 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx
@@ -1,10 +1,10 @@
-/* eslint-disable react-perf/jsx-no-new-object-as-prop -- test injects stable fakes into the runtime */
+import { ReactFlowProvider, type Node } from '@xyflow/react';
+/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop -- test injects stable fakes into the runtime */
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { WorkflowFlowInstance } from './flowInstanceStore';
-
+import { requestWorkflowFitView, workflowFitViewRequestStore, type WorkflowFlowInstance } from './flowInstanceStore';
import { requestNodeSelection, workflowSelectionStore } from './selectionStore';
import { WorkflowSelectionRequestRuntime } from './WorkflowSelectionRequestRuntime';
@@ -21,6 +21,7 @@ describe('WorkflowSelectionRequestRuntime', () => {
beforeEach(() => {
workflowSelectionStore.patchSnapshot({ hoveredNodeId: null, selectedNodeIds: [], selectionRequest: null });
+ workflowFitViewRequestStore.setSnapshot({ request: null });
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -41,7 +42,9 @@ describe('WorkflowSelectionRequestRuntime', () => {
await act(() => {
root?.render(
- <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion={false} selectNodes={selectNodes} />
+ <ReactFlowProvider>
+ <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion={false} selectNodes={selectNodes} />
+ </ReactFlowProvider>
);
});
await act(waitForPendingSelection);
@@ -55,7 +58,9 @@ describe('WorkflowSelectionRequestRuntime', () => {
await act(() => {
root?.render(
- <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion selectNodes={selectNodes} />
+ <ReactFlowProvider>
+ <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion selectNodes={selectNodes} />
+ </ReactFlowProvider>
);
});
act(() => requestNodeSelection(['later-node']));
@@ -70,4 +75,67 @@ describe('WorkflowSelectionRequestRuntime', () => {
expect(selectNodes).toHaveBeenCalledTimes(2);
expect(fitView).toHaveBeenCalledTimes(2);
});
+
+ const target = (id: string, x: number, y: number) => ({ id, position: { x, y } });
+ const flowNode = (id: string, x: number, y: number, measured = true): Node => ({
+ data: {},
+ id,
+ measured: measured ? { height: 40, width: 80 } : undefined,
+ position: { x, y },
+ });
+
+ let providerKey = 0;
+
+ // `initialNodes` only seed a provider on mount, so each step renders a fresh provider.
+ const renderFit = async (flowInstance: WorkflowFlowInstance, initialNodes: Node[]) => {
+ providerKey += 1;
+ await act(() => {
+ root?.render(
+ <ReactFlowProvider key={providerKey} initialNodes={initialNodes}>
+ <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion selectNodes={vi.fn()} />
+ </ReactFlowProvider>
+ );
+ });
+ await act(waitForPendingSelection);
+ };
+
+ it('fits once the flow shows the requested nodes measured at their positions, then clears the request', async () => {
+ const fitView = vi.fn(() => Promise.resolve(true));
+ const flowInstance = { fitView } as unknown as WorkflowFlowInstance;
+ requestWorkflowFitView([target('a', 0, 0)]);
+
+ await renderFit(flowInstance, [flowNode('a', 0, 0)]);
+
+ expect(fitView).toHaveBeenCalledWith({ duration: 0 });
+ expect(workflowFitViewRequestStore.getSnapshot().request).toBeNull();
+ });
+
+ it('waits while the flow still shows other nodes, stale positions, or unmeasured nodes', async () => {
+ const fitView = vi.fn(() => Promise.resolve(true));
+ const flowInstance = { fitView } as unknown as WorkflowFlowInstance;
+ requestWorkflowFitView([target('a', 10, 10)]);
+
+ await renderFit(flowInstance, [flowNode('a', 0, 0)]);
+ expect(fitView).not.toHaveBeenCalled();
+
+ await renderFit(flowInstance, [flowNode('a', 10, 10, false)]);
+ expect(fitView).not.toHaveBeenCalled();
+
+ await renderFit(flowInstance, [flowNode('a', 10, 10), flowNode('b', 0, 0)]);
+ expect(fitView).not.toHaveBeenCalled();
+ expect(workflowFitViewRequestStore.getSnapshot().request).not.toBeNull();
+
+ await renderFit(flowInstance, [flowNode('a', 10, 10)]);
+ expect(fitView).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops a fit request for an empty document instead of leaving it armed', async () => {
+ const fitView = vi.fn(() => Promise.resolve(true));
+ requestWorkflowFitView([]);
+
+ await renderFit({ fitView } as unknown as WorkflowFlowInstance, []);
+
+ expect(fitView).not.toHaveBeenCalled();
+ expect(workflowFitViewRequestStore.getSnapshot().request).toBeNull();
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
index 4b79ee3764..f67bca8cce 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx
@@ -1,8 +1,14 @@
import { useMountEffect } from '@platform/react/useMountEffect';
+import { useStoreApi } from '@xyflow/react';
import { useEffectEvent } from 'react';
-import type { WorkflowFlowInstance } from './flowInstanceStore';
+import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';
+import {
+ clearWorkflowFitViewRequest,
+ workflowFitViewRequestStore,
+ type WorkflowFlowInstance,
+} from './flowInstanceStore';
import { clearNodeSelectionRequest, workflowSelectionStore } from './selectionStore';
interface WorkflowSelectionRequestRuntimeProps {
@@ -11,12 +17,13 @@ interface WorkflowSelectionRequestRuntimeProps {
selectNodes: (nodeIds: string[]) => void;
}
-/** Applies outside selection requests while a workflow flow instance is mounted. */
+/** Applies outside selection and fit-view requests while a workflow flow instance is mounted. */
export const WorkflowSelectionRequestRuntime = ({
flowInstance,
reduceMotion,
selectNodes,
}: WorkflowSelectionRequestRuntimeProps) => {
+ const store = useStoreApi<WorkflowFlowNode, WorkflowFlowEdge>();
const applyRequestedSelection = useEffectEvent(() => {
const selectionRequest = workflowSelectionStore.getSnapshot().selectionRequest;
@@ -32,15 +39,59 @@ export const WorkflowSelectionRequestRuntime = ({
});
clearNodeSelectionRequest();
});
+ // The requested nodes are the loaded document's; the flow shows them only after React commits the
+ // rebuilt model (and, for a large graph, its full mount), so the fit waits for that exact set.
+ const applyRequestedFit = useEffectEvent(() => {
+ const fitViewRequest = workflowFitViewRequestStore.getSnapshot().request;
+
+ if (!fitViewRequest) {
+ return;
+ }
+
+ if (fitViewRequest.nodes.length === 0) {
+ clearWorkflowFitViewRequest();
+ return;
+ }
+
+ const { nodeLookup } = store.getState();
+
+ if (nodeLookup.size !== fitViewRequest.nodes.length) {
+ return;
+ }
+
+ for (const node of fitViewRequest.nodes) {
+ const internal = nodeLookup.get(node.id);
+
+ if (
+ !internal?.measured.width ||
+ !internal.measured.height ||
+ internal.internals.positionAbsolute.x !== node.position.x ||
+ internal.internals.positionAbsolute.y !== node.position.y
+ ) {
+ return;
+ }
+ }
+
+ clearWorkflowFitViewRequest();
+ void flowInstance.fitView({ duration: reduceMotion ? 0 : 300 });
+ });
/* eslint-disable react-hooks/rules-of-hooks -- useMountEffect is the repository's explicit useEffect wrapper */
useMountEffect(() => {
- const pendingRequestTimer = window.setTimeout(applyRequestedSelection, 0);
- const unsubscribe = workflowSelectionStore.subscribe(applyRequestedSelection);
+ const pendingRequestTimer = window.setTimeout(() => {
+ applyRequestedSelection();
+ applyRequestedFit();
+ }, 0);
+ const unsubscribeSelection = workflowSelectionStore.subscribe(applyRequestedSelection);
+ const unsubscribeFitRequests = workflowFitViewRequestStore.subscribe(applyRequestedFit);
+ // The flow store ticks when nodes mount, measure, or move, which is when a pending fit becomes applicable.
+ const unsubscribeFlow = store.subscribe(applyRequestedFit);
return () => {
window.clearTimeout(pendingRequestTimer);
- unsubscribe();
+ unsubscribeSelection();
+ unsubscribeFitRequests();
+ unsubscribeFlow();
};
});
/* eslint-enable react-hooks/rules-of-hooks */
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts
index 2f1d651d42..a8e8e8837b 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts
@@ -1,5 +1,9 @@
+import type { XYPosition } from '@features/workflow/contracts';
import type { ReactFlowInstance } from '@xyflow/react';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+
import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';
/**
@@ -24,3 +28,33 @@ export const releaseWorkflowFlowInstance = (instance: WorkflowFlowInstance): voi
};
export const getWorkflowFlowInstance = (): WorkflowFlowInstance | null => flowInstance;
+
+export interface WorkflowFitViewTarget {
+ id: string;
+ position: XYPosition;
+}
+
+export interface WorkflowFitViewRequestSnapshot {
+ /** A pending request to fit the graph once exactly these nodes are mounted and measured (e.g. after a load). */
+ request: { nodes: readonly WorkflowFitViewTarget[]; token: number } | null;
+}
+
+/** Lives here rather than in the selection store so the library load paths stay out of the editor's startup graph. */
+export const workflowFitViewRequestStore = createExternalStore<WorkflowFitViewRequestSnapshot>({ request: null });
+
+registerAccountOwnedResource({
+ clear: () => workflowFitViewRequestStore.setSnapshot({ request: null }),
+ name: 'workflow-fit-view-request',
+});
+
+export const requestWorkflowFitView = (nodes: readonly WorkflowFitViewTarget[]): void => {
+ const previousToken = workflowFitViewRequestStore.getSnapshot().request?.token ?? 0;
+
+ workflowFitViewRequestStore.setSnapshot({
+ request: { nodes: nodes.map(({ id, position }) => ({ id, position })), token: previousToken + 1 },
+ });
+};
+
+export const clearWorkflowFitViewRequest = (): void => {
+ workflowFitViewRequestStore.setSnapshot({ request: null });
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts
index 278559818f..7cf9b91be0 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts
@@ -1,6 +1,7 @@
import type { WorkflowLibraryListItem } from '@features/workflow/queries';
import { getLibraryWorkflowCached, touchLibraryWorkflowOpenedAt } from '@features/workflow/queries';
+import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';
import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';
@@ -65,6 +66,7 @@ export const useLoadLibraryWorkflow = (onLoaded: () => void): LoadLibraryWorkflo
assertAccountScopeCurrent(owner);
replace(document, t('workflowLibrary.loadedLabel', { name: item.name }));
+ requestWorkflowFitView(document.nodes);
// 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.