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): fit workflows into view whenever an editor first shows them
Josh Corbett99695c3bf527
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsxindex 8f38c41a7f..1456d302d4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx@@ -1,6 +1,5 @@import { getLibraryWorkflowRecord, touchLibraryWorkflowOpenedAt } from '@features/workflow/data/api';import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';-import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import { useWorkflowNotifications, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';import { parseWorkflowJson } from '@features/workflow/utility';@@ -80,7 +79,6 @@ export const PendingWorkflowLoader = () => {? { source: { libraryWorkflowId: source.workflowId, revision: libraryRevision } }: {}),});- requestWorkflowFitView(document.nodes);if (source.kind === 'library') {void touchLibraryWorkflowOpenedAt(source.workflowId, owner.signal).catch(() => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex 97d5acce05..e73cc9c7e5 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -292,6 +292,10 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {);// XYFlow recreates its controller when React Activity reveals this view and reads this object on reconnect.const defaultViewport = useMemo(() => getWorkflowViewport(viewportKey) ?? { ...DEFAULT_VIEWPORT }, [viewportKey]);+ // A workflow this editor has not shown yet (a load, a switch, a reload) opens fitted rather than at the origin.+ const [fitOnMount] = useState(() =>+ getWorkflowViewport(viewportKey) === null ? projectGraph.nodes.map(({ id, position }) => ({ id, position })) : null+ );const perfSource = useMemo<WorkflowPerfSource>(() => ({area: 'editor',@@ -1234,9 +1238,13 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {) : null}{flowInstance ? (<WorkflowSelectionRequestRuntime+ fitOnMount={fitOnMount}flowInstance={flowInstance}+ isLargeGraph={isLargeGraph}+ projectId={projectId}reduceMotion={reduceMotion}selectNodes={selectNodes}+ workflowId={workflowId}/>) : null}{lassoOverlay}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.tsxindex 75dedc1532..b2f4630e87 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,4 +1,7 @@-import { ReactFlowProvider, type Node } from '@xyflow/react';+import type { InvocationTemplatesSnapshot } from '@features/workflow/react';++import { useMountEffect } from '@platform/react/useMountEffect';+import { ReactFlowProvider, useStoreApi, 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';@@ -8,6 +11,22 @@ import { requestWorkflowFitView, workflowFitViewRequestStore, type WorkflowFlowIimport { requestNodeSelection, workflowSelectionStore } from './selectionStore';import { WorkflowSelectionRequestRuntime } from './WorkflowSelectionRequestRuntime';+const templates = vi.hoisted(() => ({+ catalog: {} as Record<string, unknown>,+ listeners: new Set<() => void>(),+ status: 'loaded' as InvocationTemplatesSnapshot['status'],+}));++vi.mock('@features/workflow/react', () => ({+ getInvocationTemplatesSnapshot: () => ({ error: null, status: templates.status, templates: templates.catalog }),+ subscribeInvocationTemplates: (listener: () => void) => {+ templates.listeners.add(listener);+ return () => templates.listeners.delete(listener);+ },+}));++const SCOPE = { projectId: 'project-1', workflowId: 'workflow-1' };+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const waitForPendingSelection = () =>@@ -15,6 +34,15 @@ const waitForPendingSelection = () =>window.setTimeout(resolve, 0);});+/** A ready fit lands two frames later, after the resize observer has measured the rebuilt nodes. */+const settleFrames = () =>+ act(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+ })+ );+describe('WorkflowSelectionRequestRuntime', () => {let host: HTMLDivElement;let root: Root | null;@@ -22,6 +50,8 @@ describe('WorkflowSelectionRequestRuntime', () => {beforeEach(() => {workflowSelectionStore.patchSnapshot({ hoveredNodeId: null, selectedNodeIds: [], selectionRequest: null });workflowFitViewRequestStore.setSnapshot({ request: null });+ templates.status = 'loaded';+ templates.catalog = {};host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -43,7 +73,14 @@ describe('WorkflowSelectionRequestRuntime', () => {await act(() => {root?.render(<ReactFlowProvider>- <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion={false} selectNodes={selectNodes} />+ <WorkflowSelectionRequestRuntime+ {...SCOPE}+ fitOnMount={null}+ flowInstance={flowInstance}+ isLargeGraph={false}+ reduceMotion={false}+ selectNodes={selectNodes}+ /></ReactFlowProvider>);});@@ -59,7 +96,14 @@ describe('WorkflowSelectionRequestRuntime', () => {await act(() => {root?.render(<ReactFlowProvider>- <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion selectNodes={selectNodes} />+ <WorkflowSelectionRequestRuntime+ {...SCOPE}+ fitOnMount={null}+ flowInstance={flowInstance}+ isLargeGraph={false}+ reduceMotion+ selectNodes={selectNodes}+ /></ReactFlowProvider>);});@@ -83,59 +127,193 @@ describe('WorkflowSelectionRequestRuntime', () => {measured: measured ? { height: 40, width: 80 } : undefined,position: { x, y },});+ const fakeFlow = () => {+ const fitBounds = vi.fn(() => Promise.resolve(true));++ return { fitBounds, flowInstance: { fitBounds } as unknown as WorkflowFlowInstance };+ };let providerKey = 0;// `initialNodes` only seed a provider on mount, so each step renders a fresh provider.- const renderFit = async (flowInstance: WorkflowFlowInstance, initialNodes: Node[]) => {+ const renderFit = async (+ flowInstance: WorkflowFlowInstance,+ initialNodes: Node[],+ {+ fitOnMount = null,+ isLargeGraph = false,+ workflowId = SCOPE.workflowId,+ }: { fitOnMount?: ReturnType<typeof target>[] | null; isLargeGraph?: boolean; workflowId?: string } = {}+ ) => {providerKey += 1;await act(() => {root?.render(<ReactFlowProvider key={providerKey} initialNodes={initialNodes}>- <WorkflowSelectionRequestRuntime flowInstance={flowInstance} reduceMotion selectNodes={vi.fn()} />+ <WorkflowSelectionRequestRuntime+ fitOnMount={fitOnMount}+ flowInstance={flowInstance}+ isLargeGraph={isLargeGraph}+ projectId={SCOPE.projectId}+ reduceMotion+ selectNodes={vi.fn()}+ workflowId={workflowId}+ /></ReactFlowProvider>);});await act(waitForPendingSelection);+ await settleFrames();};- 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)]);+ it('fits a request once the flow shows the requested nodes measured at their positions, then clears it', async () => {+ const { fitBounds, flowInstance } = fakeFlow();+ requestWorkflowFitView(SCOPE, [target('a', 0, 0), target('b', 100, 60)]);- await renderFit(flowInstance, [flowNode('a', 0, 0)]);+ await renderFit(flowInstance, [flowNode('a', 0, 0), flowNode('b', 100, 60)]);- expect(fitView).toHaveBeenCalledWith({ duration: 0 });+ expect(fitBounds).toHaveBeenCalledWith({ height: 100, width: 180, x: 0, y: 0 }, { 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)]);+ const { fitBounds, flowInstance } = fakeFlow();+ requestWorkflowFitView(SCOPE, [target('a', 10, 10)]);await renderFit(flowInstance, [flowNode('a', 0, 0)]);- expect(fitView).not.toHaveBeenCalled();+ expect(fitBounds).not.toHaveBeenCalled();await renderFit(flowInstance, [flowNode('a', 10, 10, false)]);- expect(fitView).not.toHaveBeenCalled();+ expect(fitBounds).not.toHaveBeenCalled();await renderFit(flowInstance, [flowNode('a', 10, 10), flowNode('b', 0, 0)]);- expect(fitView).not.toHaveBeenCalled();+ expect(fitBounds).not.toHaveBeenCalled();expect(workflowFitViewRequestStore.getSnapshot().request).not.toBeNull();await renderFit(flowInstance, [flowNode('a', 10, 10)]);- expect(fitView).toHaveBeenCalledTimes(1);+ expect(fitBounds).toHaveBeenCalledTimes(1);+ });++ // The editor being replaced can show the same ids and positions (another copy of the same template).+ it('leaves a request for another workflow to that workflow’s editor', async () => {+ const { fitBounds, flowInstance } = fakeFlow();+ requestWorkflowFitView(SCOPE, [target('a', 0, 0)]);++ await renderFit(flowInstance, [flowNode('a', 0, 0)], { workflowId: 'workflow-2' });++ expect(fitBounds).not.toHaveBeenCalled();+ expect(workflowFitViewRequestStore.getSnapshot().request).not.toBeNull();});it('drops a fit request for an empty document instead of leaving it armed', async () => {- const fitView = vi.fn(() => Promise.resolve(true));- requestWorkflowFitView([]);+ const { fitBounds, flowInstance } = fakeFlow();+ requestWorkflowFitView(SCOPE, []);- await renderFit({ fitView } as unknown as WorkflowFlowInstance, []);+ await renderFit(flowInstance, []);- expect(fitView).not.toHaveBeenCalled();+ expect(fitBounds).not.toHaveBeenCalled();expect(workflowFitViewRequestStore.getSnapshot().request).toBeNull();});++ it('fits a newly shown workflow once on mount without animating, and not again as the flow changes', async () => {+ const { fitBounds, flowInstance } = fakeFlow();+ // A zero-duration fit moves the viewport synchronously, so the flow store notifies before the fit returns.+ fitBounds.mockImplementation(() => {+ templates.listeners.forEach((listener) => listener());+ return Promise.resolve(true);+ });++ await renderFit(flowInstance, [flowNode('a', 0, 0)], { fitOnMount: [target('a', 0, 0)] });++ expect(fitBounds).toHaveBeenCalledExactlyOnceWith({ height: 40, width: 80, x: 0, y: 0 }, { duration: 0 });++ await act(() => templates.listeners.forEach((listener) => listener()));+ await settleFrames();++ expect(fitBounds).toHaveBeenCalledTimes(1);+ });++ // Nodes rendered before templates arrive are placeholder cards that grow once their template is known.+ it('holds the fit until the node templates have settled', async () => {+ const { fitBounds, flowInstance } = fakeFlow();+ templates.status = 'loading';++ await renderFit(flowInstance, [flowNode('a', 0, 0)], { fitOnMount: [target('a', 0, 0)] });+ expect(fitBounds).not.toHaveBeenCalled();++ templates.status = 'error';+ await act(() => templates.listeners.forEach((listener) => listener()));+ await settleFrames();++ expect(fitBounds).toHaveBeenCalledTimes(1);+ });++ // Templates load before the rebuilt nodes carry them; the placeholder's size must not be what gets fitted.+ it('waits for a node with a known template to be rebuilt with it', async () => {+ const { fitBounds, flowInstance } = fakeFlow();+ const invocation = (template: object | null): Node => ({+ ...flowNode('a', 0, 0),+ data: { documentNode: { data: { type: 'noise' } }, template },+ type: 'invocation',+ });+ templates.catalog = { noise: {} };++ await renderFit(flowInstance, [invocation(null)], { fitOnMount: [target('a', 0, 0)] });+ expect(fitBounds).not.toHaveBeenCalled();++ await renderFit(flowInstance, [invocation({})], { fitOnMount: [target('a', 0, 0)] });+ expect(fitBounds).toHaveBeenCalledTimes(1);+ });++ it('gives up the mount fit once the user moves the view first', async () => {+ const { fitBounds, flowInstance } = fakeFlow();+ templates.status = 'loading';+ const captured: { store: ReturnType<typeof useStoreApi> | null } = { store: null };+ // No pane is mounted here, so the move is written where a pan would land: the flow store's transform.+ const CaptureStore = () => {+ const store = useStoreApi();++ useMountEffect(() => {+ captured.store = store;+ });++ return null;+ };++ await act(() => {+ root?.render(+ <ReactFlowProvider initialNodes={[flowNode('a', 0, 0)]}>+ <CaptureStore />+ <WorkflowSelectionRequestRuntime+ fitOnMount={[target('a', 0, 0)]}+ flowInstance={flowInstance}+ isLargeGraph={false}+ projectId={SCOPE.projectId}+ reduceMotion+ selectNodes={vi.fn()}+ workflowId={SCOPE.workflowId}+ />+ </ReactFlowProvider>+ );+ });+ await act(waitForPendingSelection);+ await act(() => captured.store?.setState({ transform: [200, 100, 1.5] }));++ templates.status = 'loaded';+ await act(() => templates.listeners.forEach((listener) => listener()));+ await settleFrames();++ expect(fitBounds).not.toHaveBeenCalled();+ });++ it('counts the unmeasured nodes of a large graph at a typical node size', async () => {+ const { fitBounds, flowInstance } = fakeFlow();+ const nodes = [flowNode('a', 0, 0), flowNode('far', 5000, 3000, false)];+ const targets = [target('a', 0, 0), target('far', 5000, 3000)];++ await renderFit(flowInstance, nodes, { fitOnMount: targets });+ expect(fitBounds).not.toHaveBeenCalled();++ await renderFit(flowInstance, nodes, { fitOnMount: targets, isLargeGraph: true });+ expect(fitBounds).toHaveBeenCalledWith({ height: 3160, width: 5288, x: 0, y: 0 }, { duration: 0 });+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsxindex f67bca8cce..2fe290d3e7 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx@@ -1,29 +1,111 @@+import type { InvocationTemplates } from '@features/workflow/contracts';+import type { InternalNode, Rect, Transform } from '@xyflow/react';++import { getInvocationTemplatesSnapshot, subscribeInvocationTemplates } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';import { useStoreApi } from '@xyflow/react';-import { useEffectEvent } from 'react';+import { useEffectEvent, useRef } from 'react';import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';import {clearWorkflowFitViewRequest,workflowFitViewRequestStore,+ type WorkflowFitViewTarget,type WorkflowFlowInstance,} from './flowInstanceStore';import { clearNodeSelectionRequest, workflowSelectionStore } from './selectionStore';+// A large graph renders only visible nodes, so xyflow never measures the rest; they count at a typical node size.+const UNMEASURED_NODE_SIZE = { height: 160, width: 288 };++/** A node whose template exists renders as a placeholder card until its rebuilt data carries that template. */+const isAwaitingTemplate = (internal: InternalNode<WorkflowFlowNode>, templates: InvocationTemplates): boolean => {+ const { userNode } = internal.internals;++ return (+ userNode.type === 'invocation' &&+ userNode.data.template === null &&+ templates[userNode.data.documentNode.data.type] !== undefined+ );+};++/**+ * The bounds of exactly the target nodes once the flow shows them at their positions with their templates, measured+ * unless the graph is large; null while the flow still shows another document, an older position, a placeholder+ * card, or unmeasured nodes.+ */+const getWorkflowFitBounds = (+ nodeLookup: ReadonlyMap<string, InternalNode<WorkflowFlowNode>>,+ targets: readonly WorkflowFitViewTarget[],+ { allowUnmeasured, templates }: { allowUnmeasured: boolean; templates: InvocationTemplates }+): Rect | null => {+ if (targets.length === 0 || nodeLookup.size !== targets.length) {+ return null;+ }++ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const target of targets) {+ const internal = nodeLookup.get(target.id);+ const position = internal?.internals.positionAbsolute;++ if (+ !internal ||+ position?.x !== target.position.x ||+ position.y !== target.position.y ||+ isAwaitingTemplate(internal, templates)+ ) {+ return null;+ }++ const isMeasured = Boolean(internal.measured.width && internal.measured.height);++ if (!isMeasured && !allowUnmeasured) {+ return null;+ }++ const width = isMeasured ? internal.measured.width! : UNMEASURED_NODE_SIZE.width;+ const height = isMeasured ? internal.measured.height! : UNMEASURED_NODE_SIZE.height;++ minX = Math.min(minX, position.x);+ minY = Math.min(minY, position.y);+ maxX = Math.max(maxX, position.x + width);+ maxY = Math.max(maxY, position.y + height);+ }++ return { height: maxY - minY, width: maxX - minX, x: minX, y: minY };+};+interface WorkflowSelectionRequestRuntimeProps {+ /** The document's nodes when this editor opened without a remembered viewport; fitted once they are shown. */+ fitOnMount: readonly WorkflowFitViewTarget[] | null;flowInstance: WorkflowFlowInstance;+ isLargeGraph: boolean;+ projectId: string;reduceMotion: boolean;selectNodes: (nodeIds: string[]) => void;+ workflowId: string;}/** Applies outside selection and fit-view requests while a workflow flow instance is mounted. */export const WorkflowSelectionRequestRuntime = ({+ fitOnMount,flowInstance,+ isLargeGraph,+ projectId,reduceMotion,selectNodes,+ workflowId,}: WorkflowSelectionRequestRuntimeProps) => {const store = useStoreApi<WorkflowFlowNode, WorkflowFlowEdge>();+ const pendingMountFit = useRef(fitOnMount);+ // The viewport the editor opened at; a move away from it before the mount fit lands is the user's, and wins.+ const mountTransform = useRef<Transform | null>(null);+ const settleFrame = useRef<number | null>(null);const applyRequestedSelection = useEffectEvent(() => {const selectionRequest = workflowSelectionStore.getSnapshot().selectionRequest;@@ -39,41 +121,80 @@ 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;+ const getBounds = (targets: readonly WorkflowFitViewTarget[]): Rect | null => {+ const templatesSnapshot = getInvocationTemplatesSnapshot();- if (!fitViewRequest) {- return;+ // Nodes rendered before templates load are placeholder cards that grow once their template arrives.+ if (templatesSnapshot.status === 'idle' || templatesSnapshot.status === 'loading') {+ return null;}- if (fitViewRequest.nodes.length === 0) {- clearWorkflowFitViewRequest();- return;+ return getWorkflowFitBounds(store.getState().nodeLookup, targets, {+ allowUnmeasured: isLargeGraph,+ templates: templatesSnapshot.templates,+ });+ };+ const getRequestTargets = () => {+ const request = workflowFitViewRequestStore.getSnapshot().request;++ return request && request.scope.projectId === projectId && request.scope.workflowId === workflowId+ ? request.nodes+ : null;+ };+ // Each target is released before fitting: a zero-duration fit updates the flow store synchronously, which+ // re-enters here.+ const fitReadyTargets = useEffectEvent(() => {+ settleFrame.current = null;++ const mountTargets = pendingMountFit.current;+ const mountBounds = mountTargets ? getBounds(mountTargets) : null;++ if (mountBounds) {+ pendingMountFit.current = null;+ void flowInstance.fitBounds(mountBounds, { duration: 0 });}- const { nodeLookup } = store.getState();+ const requestTargets = getRequestTargets();+ const requestBounds = requestTargets ? getBounds(requestTargets) : null;- if (nodeLookup.size !== fitViewRequest.nodes.length) {- return;+ if (requestBounds) {+ clearWorkflowFitViewRequest();+ void flowInstance.fitBounds(requestBounds, { duration: reduceMotion ? 0 : 300 });+ }+ });+ // Targets are the document's nodes; the flow shows them only after React commits the rebuilt model (and, for a+ // large graph, its full mount). Rebuilt nodes keep their previous measured size until the resize observer runs,+ // so a ready target is fitted two frames later, from bounds read again then.+ const applyRequestedFit = useEffectEvent(() => {+ const { transform } = store.getState();++ if (pendingMountFit.current?.length === 0) {+ pendingMountFit.current = null;}- for (const node of fitViewRequest.nodes) {- const internal = nodeLookup.get(node.id);+ if (pendingMountFit.current) {+ mountTransform.current ??= transform;- if (- !internal?.measured.width ||- !internal.measured.height ||- internal.internals.positionAbsolute.x !== node.position.x ||- internal.internals.positionAbsolute.y !== node.position.y- ) {- return;+ if (mountTransform.current.some((value, index) => value !== transform[index])) {+ pendingMountFit.current = null;}}- clearWorkflowFitViewRequest();- void flowInstance.fitView({ duration: reduceMotion ? 0 : 300 });+ const requestTargets = getRequestTargets();++ if (requestTargets?.length === 0) {+ clearWorkflowFitViewRequest();+ }++ const isReady =+ (pendingMountFit.current !== null && getBounds(pendingMountFit.current) !== null) ||+ (requestTargets !== null && requestTargets.length > 0 && getBounds(requestTargets) !== null);++ if (isReady && settleFrame.current === null) {+ settleFrame.current = requestAnimationFrame(() => {+ settleFrame.current = requestAnimationFrame(fitReadyTargets);+ });+ }});/* eslint-disable react-hooks/rules-of-hooks -- useMountEffect is the repository's explicit useEffect wrapper */@@ -84,13 +205,20 @@ export const WorkflowSelectionRequestRuntime = ({}, 0);const unsubscribeSelection = workflowSelectionStore.subscribe(applyRequestedSelection);const unsubscribeFitRequests = workflowFitViewRequestStore.subscribe(applyRequestedFit);+ const unsubscribeTemplates = subscribeInvocationTemplates(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);++ if (settleFrame.current !== null) {+ cancelAnimationFrame(settleFrame.current);+ }+unsubscribeSelection();unsubscribeFitRequests();+ unsubscribeTemplates();unsubscribeFlow();};});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.tsindex 950a65c257..2397e701ba 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts@@ -29,9 +29,15 @@ export interface WorkflowFitViewTarget {position: XYPosition;}+/** The project workflow a fit request is for; other editors (including the one being replaced) ignore it. */+export interface WorkflowFitViewScope {+ projectId: string;+ workflowId: string;+}+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;+ request: { nodes: readonly WorkflowFitViewTarget[]; scope: WorkflowFitViewScope; token: number } | null;}/** Lives here rather than in the selection store so the library load paths stay out of the editor's startup graph. */@@ -42,11 +48,16 @@ registerAccountOwnedResource({name: 'workflow-fit-view-request',});-export const requestWorkflowFitView = (nodes: readonly WorkflowFitViewTarget[]): void => {+/** Fits a document whose editor stays mounted across the change; a newly mounted editor fits on its own. */+export const requestWorkflowFitView = (scope: WorkflowFitViewScope, nodes: readonly WorkflowFitViewTarget[]): void => {const previousToken = workflowFitViewRequestStore.getSnapshot().request?.token ?? 0;workflowFitViewRequestStore.setSnapshot({- request: { nodes: nodes.map(({ id, position }) => ({ id, position })), token: previousToken + 1 },+ request: {+ nodes: nodes.map(({ id, position }) => ({ id, position })),+ scope: { projectId: scope.projectId, workflowId: scope.workflowId },+ token: previousToken + 1,+ },});};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.tsindex 1bed5c2c48..c975c2e3af 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts@@ -3,7 +3,6 @@ import type { WorkflowLibraryListItem } from '@features/workflow/queries';import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';import { getLibraryWorkflowRecordCached, touchLibraryWorkflowOpenedAt } from '@features/workflow/queries';-import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import { useWorkflowNotifications, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';import { parseWorkflowJson } from '@features/workflow/utility';@@ -139,7 +138,6 @@ export const useOpenLibraryWorkflow = (onOpened: () => void): OpenLibraryWorkfloreusePlaceholder: mode === 'resume-or-add',source: { libraryWorkflowId: record.workflow_id, revision: record.revision },});- requestWorkflowFitView(document.nodes);for (const warning of warnings) {notify.info(t('workflowLibrary.loadWarning'), warning);