Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-11431): bound the FlowRenderer dimension->layout feedback loop (#6824)
Aaron Perez5968124299a4
diff --git a/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsx b/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsxindex 82fe7632e..b482c58e0 100644--- a/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/FlowRenderer.tsx@@ -44,6 +44,7 @@ import {useNodesInitialized,useReactFlow,NodeChange,+ NodeDimensionChange,EdgeChange,} from "@xyflow/react";import "@xyflow/react/dist/style.css";@@ -123,6 +124,11 @@ import {upgradeWorkflowDefinitionToVersionTwo,getWorkflowErrors,} from "./workflowEditorUtils";+import {+ createDimensionConvergenceState,+ processDimensionChanges,+ resetDimensionConvergence,+} from "./dimensionConvergence";import { toast } from "@/components/ui/use-toast";import { useAutoPan } from "./useAutoPan";import { useAutoGenerateWorkflowTitle } from "../hooks/useAutoGenerateWorkflowTitle";@@ -600,6 +606,13 @@ function FlowRenderer({// Track if we're currently in a layout operation to prevent infinite loopsconst isLayoutingRef = useRef(false);+ // Bounds the dimension->layout feedback cycle (React error #185) when a+ // ResizeObserver oscillation re-arms layout faster than the rAF guard resets.+ const dimensionConvergenceRef = useRef(createDimensionConvergenceState());++ // Ensures the targeted-block status-row relayout runs once per focus.+ const lastLaidOutTargetLabelRef = useRef<string | undefined>(undefined);+useEffect(() => {if (nodesInitialized) {setShouldConstrainPan(true);@@ -702,18 +715,32 @@ function FlowRenderer({// eslint-disable-next-line react-hooks/exhaustive-deps}, [nodesInitialized]);- // Re-layout when the targetted block changes to account for the status row+ // Re-layout when the targeted block changes to account for the status row// that appears when a block is being debuggeduseEffect(() => {- if (nodesInitialized && targettedBlockLabel) {+ // Clear the focus marker when focus is removed (e.g. navigating from+ // /:run/:label/build back to /build) so re-focusing the same label later+ // still triggers the status-row relayout and budget reset.+ if (!targettedBlockLabel) {+ lastLaidOutTargetLabelRef.current = undefined;+ return;+ }+ if (+ nodesInitialized &&+ lastLaidOutTargetLabelRef.current !== targettedBlockLabel+ ) {+ // A new focus is a genuine change, so re-arm the convergence budget that+ // the previous block's status-row resize may have exhausted.+ lastLaidOutTargetLabelRef.current = targettedBlockLabel;+ resetDimensionConvergence(dimensionConvergenceRef.current);doLayout(nodes, edges);}- // Re-layout only when the targetted (debugged) block label changes.+ // Re-layout only when the targeted (debugged) block label changes.// nodes/edges/doLayout intentionally omitted: a normal edit already// triggers its own layout pass, and re-running here would fight the// user's interactive position changes.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [targettedBlockLabel]);+ }, [targettedBlockLabel, nodesInitialized]);// Re-layout when a loop node's header height changes (e.g., data schema toggled)useEffect(() => {@@ -1774,41 +1801,40 @@ function FlowRenderer({nodes={nodes}edges={edges}onNodesChange={(changes) => {+ // User drag-drop. `dragging === false` fires once at the end+ // of a drag gesture. Programmatic position updates (mount-time+ // layout, setNodes from node components) leave `dragging`+ // undefined, so this filter doesn't falsely trip for them.+ const hasStructuralChange = changes.some(+ (change) =>+ change.type === "add" ||+ change.type === "remove" ||+ change.type === "replace" ||+ (change.type === "position" && change.dragging === false),+ );++ // A genuine structural edit re-arms the convergence budget so+ // a real resize that follows isn't starved by a prior loop.+ if (hasStructuralChange) {+ resetDimensionConvergence(dimensionConvergenceRef.current);+ }+const dimensionChanges = changes.filter(- (change) => change.type === "dimensions",+ (change): change is NodeDimensionChange =>+ change.type === "dimensions",);// Only process dimension changes if we're not already in a layout operation// This prevents infinite loops (React error #185) during copy-pasteif (dimensionChanges.length > 0 && !isLayoutingRef.current) {- const tempNodes = [...nodes];- let hasActualChanges = false;-- dimensionChanges.forEach((change) => {- const node = tempNodes.find(- (node) => node.id === change.id,+ const { nodes: tempNodes, shouldLayout } =+ processDimensionChanges(+ nodes,+ dimensionChanges,+ dimensionConvergenceRef.current,);- if (node) {- const newWidth = change.dimensions?.width;- const newHeight = change.dimensions?.height;-- // Only update if dimensions actually changed- if (- node.measured?.width !== newWidth ||- node.measured?.height !== newHeight- ) {- hasActualChanges = true;- node.measured = {- ...node.measured,- width: newWidth,- height: newHeight,- };- }- }- });-- // Only trigger layout if there were actual dimension changes- if (hasActualChanges) {++ if (shouldLayout) {debouncedLayoutForDimensions(tempNodes, edges);}}@@ -1822,20 +1848,7 @@ function FlowRenderer({!readOnly &&!isInitialLoadRef.current &&internalUpdateCount === 0 &&- changes.some((change) => {- return (- change.type === "add" ||- change.type === "remove" ||- change.type === "replace" ||- // User drag-drop. `dragging === false` fires once at the- // end of a drag gesture. Programmatic position updates- // (mount-time layout, setNodes from node components)- // leave `dragging` undefined, so this filter doesn't- // falsely trip for them.- (change.type === "position" &&- change.dragging === false)- );- })+ hasStructuralChange) {workflowChangesStore.setHasChanges(true);}diff --git a/skyvern-frontend/src/routes/workflows/editor/dimensionConvergence.test.ts b/skyvern-frontend/src/routes/workflows/editor/dimensionConvergence.test.tsnew file mode 100644index 000000000..eb04a6199--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/dimensionConvergence.test.ts@@ -0,0 +1,250 @@+import type { NodeDimensionChange } from "@xyflow/react";+import { describe, expect, test } from "vitest";++import type { AppNode } from "./nodes";+import {+ DIMENSION_CONVERGENCE_QUIET_WINDOW_MS,+ MAX_DIMENSION_LAYOUT_PASSES,+ createDimensionConvergenceState,+ processDimensionChanges,+ quantizeDimension,+ resetDimensionConvergence,+} from "./dimensionConvergence";++function makeNode(id: string, width: number, height: number): AppNode {+ return {+ id,+ type: "task",+ position: { x: 0, y: 0 },+ data: { label: id },+ measured: { width, height },+ } as AppNode;+}++function dimensionChange(+ id: string,+ width: number,+ height: number,+): NodeDimensionChange {+ return { id, type: "dimensions", dimensions: { width, height } };+}++describe("quantizeDimension", () => {+ test("rounds to the nearest integer pixel", () => {+ expect(quantizeDimension(200.4)).toBe(200);+ expect(quantizeDimension(200.6)).toBe(201);+ });++ test("passes through undefined", () => {+ expect(quantizeDimension(undefined)).toBeUndefined();+ });+});++describe("processDimensionChanges", () => {+ test("sub-pixel jitter never re-triggers layout", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ let layoutCount = 0;+ for (const subpixel of [200.1, 200.4, 199.7, 200.49, 199.51]) {+ const result = processDimensionChanges(+ nodes,+ [dimensionChange("a", subpixel, 100.2)],+ state,+ );+ if (result.shouldLayout) layoutCount += 1;+ }++ expect(layoutCount).toBe(0);+ });++ test("a single genuine resize triggers exactly one layout", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ const first = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, 140)],+ state,+ );+ const second = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, 140)],+ state,+ );++ expect(first.shouldLayout).toBe(true);+ expect(second.shouldLayout).toBe(false);+ expect(nodes[0]!.measured?.height).toBe(140);+ });++ test("a sustained oscillation is bounded by the pass budget", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ let layoutCount = 0;+ for (let i = 0; i < 25; i += 1) {+ const height = i % 2 === 0 ? 120 : 160;+ const result = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, height)],+ state,+ );+ if (result.shouldLayout) layoutCount += 1;+ }++ expect(layoutCount).toBeLessThanOrEqual(MAX_DIMENSION_LAYOUT_PASSES);+ });++ test("budget re-arms across genuine resizes separated by the quiet window", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ const heights = [140, 180, 220, 260, 300, 340];+ expect(heights.length).toBeGreaterThan(MAX_DIMENSION_LAYOUT_PASSES);++ let layoutCount = 0;+ let now = 1_000;+ for (const height of heights) {+ const result = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, height)],+ state,+ { now },+ );+ if (result.shouldLayout) layoutCount += 1;+ now += DIMENSION_CONVERGENCE_QUIET_WINDOW_MS;+ }++ // Each resize sits a full quiet window apart, so none can be a feedback+ // loop: every one re-arms and lays out, never starving into stale positions.+ expect(layoutCount).toBe(heights.length);+ });++ test("a tight back-to-back loop stays bounded despite the quiet-window re-arm", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ let layoutCount = 0;+ let now = 1_000;+ for (let i = 0; i < 25; i += 1) {+ const height = i % 2 === 0 ? 120 : 160;+ const result = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, height)],+ state,+ { now },+ );+ if (result.shouldLayout) layoutCount += 1;+ // Changes arrive far faster than the quiet window, so the budget never+ // re-arms and the React #185 loop stays bounded.+ now += 50;+ }++ expect(layoutCount).toBeLessThanOrEqual(MAX_DIMENSION_LAYOUT_PASSES);+ });++ test("a genuine edit reset re-arms the pass budget", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ let height = 120;+ for (let i = 0; i < 10; i += 1) {+ height = i % 2 === 0 ? 120 : 160;+ processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, height)],+ state,+ );+ }++ resetDimensionConvergence(state);++ const afterReset = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, 220)],+ state,+ );+ expect(afterReset.shouldLayout).toBe(true);+ });++ test("an intermittent resize after the layout settles is not starved", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ const grow = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, 140)],+ state,+ );+ const settle = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, 140)],+ state,+ );+ const growAgain = processDimensionChanges(+ nodes,+ [dimensionChange("a", 200, 180)],+ state,+ );++ expect(grow.shouldLayout).toBe(true);+ expect(settle.shouldLayout).toBe(false);+ expect(growAgain.shouldLayout).toBe(true);+ });++ test("a burst of distinct node resizes is never suppressed as a loop", () => {+ const ids = ["a", "b", "c", "d", "e"];+ const nodes = ids.map((id) => makeNode(id, 200, 100));+ const state = createDimensionConvergenceState();++ let layoutCount = 0;+ for (const id of ids) {+ const result = processDimensionChanges(+ nodes,+ [dimensionChange(id, 200, 140)],+ state,+ );+ if (result.shouldLayout) layoutCount += 1;+ }++ expect(layoutCount).toBe(ids.length);+ });++ test("a per-node budget bounds a loop without starving other nodes", () => {+ const nodes = [makeNode("loop", 200, 100), makeNode("calm", 200, 100)];+ const state = createDimensionConvergenceState();++ let loopLayouts = 0;+ for (let i = 0; i < 12; i += 1) {+ const result = processDimensionChanges(+ nodes,+ [dimensionChange("loop", 200, i % 2 === 0 ? 120 : 160)],+ state,+ );+ if (result.shouldLayout) loopLayouts += 1;+ }++ const calm = processDimensionChanges(+ nodes,+ [dimensionChange("calm", 200, 150)],+ state,+ );++ expect(loopLayouts).toBeLessThanOrEqual(MAX_DIMENSION_LAYOUT_PASSES);+ expect(calm.shouldLayout).toBe(true);+ });++ test("ignores dimension changes for unknown node ids", () => {+ const nodes = [makeNode("a", 200, 100)];+ const state = createDimensionConvergenceState();++ const result = processDimensionChanges(+ nodes,+ [dimensionChange("ghost", 300, 300)],+ state,+ );++ expect(result.shouldLayout).toBe(false);+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/dimensionConvergence.ts b/skyvern-frontend/src/routes/workflows/editor/dimensionConvergence.tsnew file mode 100644index 000000000..344205974--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/dimensionConvergence.ts@@ -0,0 +1,125 @@+import type { NodeDimensionChange } from "@xyflow/react";++import type { AppNode } from "./nodes";++// React Flow's ResizeObserver reports sub-pixel measurements that drift between+// render cycles. Quantizing to whole pixels before comparison keeps that jitter+// from registering as a real dimension change and re-arming the layout pass.+export function quantizeDimension(+ value: number | undefined,+): number | undefined {+ return value === undefined ? undefined : Math.round(value);+}++// Upper bound on how many consecutive layout-triggering passes a single node may+// drive before its layouts are suppressed. A Dagre relayout normally converges+// in one pass; this only trips when one node's measurement and layout feed back+// into each other (the React error #185 "Maximum update depth exceeded" loop).+// Counting per node id keeps a burst of distinct nodes settling one after+// another (paste, recorded blocks, async content) from looking like a loop.+export const MAX_DIMENSION_LAYOUT_PASSES = 3;++// Re-arm a node's pass budget once it has been quiet for this long. React Flow+// emits a dimensions change only when measured size differs, so a node can never+// re-arm itself via a no-op "settled" event; without a time-based signal a node+// that legitimately resizes more than MAX_DIMENSION_LAYOUT_PASSES times (typing+// into an auto-growing block, toggling expandable content) would stay suppressed+// and leave the canvas laid out with stale positions. The debounced layout is+// hard-capped at maxWait=200ms, so a sustained #185 feedback loop re-emits a+// node's dimensions at most ~250ms apart and never opens a gap this wide; only a+// human-paced resize sequence does. Revisit this if that debounce changes.+export const DIMENSION_CONVERGENCE_QUIET_WINDOW_MS = 500;++export type DimensionConvergenceState = {+ passCounts: Map<string, number>;+ lastChangeAt: Map<string, number>;+};++export function createDimensionConvergenceState(): DimensionConvergenceState {+ return { passCounts: new Map(), lastChangeAt: new Map() };+}++// Re-arm every node's budget after a genuine user action (an edit, or focusing a+// different block) so intentional resizes are never starved by a prior loop.+export function resetDimensionConvergence(+ state: DimensionConvergenceState,+): void {+ state.passCounts.clear();+ state.lastChangeAt.clear();+}++type ProcessDimensionChangesOptions = {+ maxPasses?: number;+ quietWindowMs?: number;+ now?: number;+};++// Updates measured dimensions on the matching nodes IN PLACE so that successive+// change batches within the same render cycle don't re-count one settling+// resize; the returned array intentionally shares those node objects with the+// caller's input.+export function processDimensionChanges(+ nodes: Array<AppNode>,+ dimensionChanges: Array<NodeDimensionChange>,+ state: DimensionConvergenceState,+ options: ProcessDimensionChangesOptions = {},+): { nodes: Array<AppNode>; shouldLayout: boolean } {+ const {+ maxPasses = MAX_DIMENSION_LAYOUT_PASSES,+ quietWindowMs = DIMENSION_CONVERGENCE_QUIET_WINDOW_MS,+ now = Date.now(),+ } = options;++ const tempNodes = [...nodes];+ const changedNodeIds: Array<string> = [];++ for (const change of dimensionChanges) {+ const node = tempNodes.find((candidate) => candidate.id === change.id);+ if (!node) {+ continue;+ }++ const newWidth = quantizeDimension(change.dimensions?.width);+ const newHeight = quantizeDimension(change.dimensions?.height);++ if (+ quantizeDimension(node.measured?.width) !== newWidth ||+ quantizeDimension(node.measured?.height) !== newHeight+ ) {+ changedNodeIds.push(change.id);+ node.measured = {+ ...node.measured,+ width: newWidth,+ height: newHeight,+ };+ }+ }++ if (changedNodeIds.length === 0) {+ return { nodes: tempNodes, shouldLayout: false };+ }++ // Lay out as long as at least one changed node is still within its budget.+ // A feedback loop keeps re-changing the same node(s) and exhausts theirs; a+ // burst of distinct nodes each carries its own fresh budget.+ let withinBudget = false;+ for (const id of changedNodeIds) {+ // Re-arm a node whose last real change predates the quiet window: it can't+ // be part of an in-progress feedback loop, so a fresh resize starts over.+ // Anchored on every real change (including budget-exhausted ones) so a live+ // loop, which keeps firing inside the window, can never re-arm itself.+ const lastChangeAt = state.lastChangeAt.get(id);+ if (lastChangeAt !== undefined && now - lastChangeAt >= quietWindowMs) {+ state.passCounts.delete(id);+ }+ state.lastChangeAt.set(id, now);++ const count = (state.passCounts.get(id) ?? 0) + 1;+ state.passCounts.set(id, count);+ if (count <= maxPasses) {+ withinBudget = true;+ }+ }++ return { nodes: tempNodes, shouldLayout: withinBudget };+}