Skip to content

Automate browser based workflows with AI

[oncall] Fix inline add inside nested conditional loops (#6069)

Marc Kelechavab5a158283d18
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 9e3d1c458..e120eeabd 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -119,6 +119,7 @@ import { WorkflowHistoryPanel } from "./panels/WorkflowHistoryPanel";
import { WorkflowSchedulePanel } from "./panels/schedulePanel/WorkflowSchedulePanel";
import { WorkflowVersion } from "../hooks/useWorkflowVersionsQuery";
import { WorkflowSettings } from "../types/workflowTypes";
+import { shouldKeepExistingEdgeForInsertion } from "./workflowInsertion";
import { constructCacheKeyValue, getInitialParameters } from "./utils";
import { WorkflowCopilotChat } from "../copilot/WorkflowCopilotChat";
@@ -1109,21 +1110,9 @@ function Workspace({
}
const editedEdges = previous
- ? edges.filter((edge) => {
- // Don't remove edges from the previous node
- if (edge.source !== previous) {
- return true;
- }
- // If we're in a branch, only remove the edge for this branch
- if (branch) {
- const edgeData = edge.data as
- | { conditionalBranchId?: string }
- | undefined;
- return edgeData?.conditionalBranchId !== branch.branchId;
- }
- // Otherwise remove all edges from previous
- return false;
- })
+ ? edges.filter((edge) =>
+ shouldKeepExistingEdgeForInsertion(edge, { branch, next, previous }),
+ )
: edges;
const previousNode = nodes.find((node) => node.id === previous);
diff --git a/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.test.tsx b/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.test.tsx
new file mode 100644
index 000000000..b37fbbb90
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.test.tsx
@@ -0,0 +1,185 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import type { EdgeProps } from "@xyflow/react";
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DebugStoreContext } from "@/store/DebugStoreContext";
+import { useRecordingStore } from "@/store/useRecordingStore";
+import { useSettingsStore } from "@/store/SettingsStore";
+import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";
+
+import { EdgeWithAddButton } from "./EdgeWithAddButton";
+
+const useNodesMock = vi.fn();
+
+vi.mock("@xyflow/react", async () => {
+ const actual =
+ await vi.importActual<typeof import("@xyflow/react")>("@xyflow/react");
+
+ return {
+ ...actual,
+ BaseEdge: () => null,
+ EdgeLabelRenderer: ({ children }: { children: ReactNode }) => (
+ <>{children}</>
+ ),
+ getBezierPath: () => ["M 0 0", 0, 0],
+ useNodes: () => useNodesMock(),
+ };
+});
+
+vi.mock("react-router-dom", async () => {
+ const actual =
+ await vi.importActual<typeof import("react-router-dom")>(
+ "react-router-dom",
+ );
+
+ return {
+ ...actual,
+ useParams: () => ({ workflowPermanentId: "wpid_test" }),
+ };
+});
+
+vi.mock("@/routes/browserSessions/hooks/useProcessRecordingMutation", () => ({
+ useProcessRecordingMutation: () => ({
+ isPending: false,
+ mutate: vi.fn(),
+ }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useSopToBlocksMutation", () => ({
+ useSopToBlocksMutation: () => ({
+ cancel: vi.fn(),
+ isPending: false,
+ mutate: vi.fn(),
+ }),
+}));
+
+const initialSettings = useSettingsStore.getState();
+const initialRecording = useRecordingStore.getState();
+
+function renderEdge(props: Partial<EdgeProps> = {}) {
+ return render(
+ <DebugStoreContext.Provider value={{ isDebugMode: false }}>
+ <EdgeWithAddButton
+ {...({
+ id: "edge",
+ markerEnd: undefined,
+ source: "source",
+ sourcePosition: "bottom",
+ sourceX: 0,
+ sourceY: 0,
+ target: "target",
+ targetPosition: "top",
+ targetX: 0,
+ targetY: 0,
+ ...props,
+ } as EdgeProps)}
+ />
+ </DebugStoreContext.Provider>,
+ );
+}
+
+describe("EdgeWithAddButton", () => {
+ beforeEach(() => {
+ useSettingsStore.setState(initialSettings, true);
+ useRecordingStore.setState(initialRecording, true);
+ useWorkflowPanelStore.setState({
+ workflowPanelState: {
+ active: false,
+ content: "parameters",
+ },
+ });
+
+ useSettingsStore.getState().setIsUsingABrowser(false);
+ useSettingsStore.getState().setIsLoadingABrowser(false);
+ useRecordingStore.setState({ isRecording: false });
+ useNodesMock.mockReset();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("keeps the loop as parent and inherits branch context for nested-loop edge inserts", () => {
+ useNodesMock.mockReturnValue([
+ {
+ id: "conditional",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ {
+ id: "loop",
+ parentId: "conditional",
+ type: "loop",
+ data: {
+ conditionalBranchId: "branch-a",
+ conditionalLabel: "conditional",
+ conditionalMergeLabel: null,
+ conditionalNodeId: "conditional",
+ label: "block_8",
+ },
+ },
+ {
+ id: "source",
+ parentId: "loop",
+ type: "start",
+ data: {},
+ },
+ ]);
+
+ renderEdge({ source: "source", target: "target" });
+
+ fireEvent.click(screen.getByRole("button"));
+
+ expect(useWorkflowPanelStore.getState().workflowPanelState).toMatchObject({
+ active: true,
+ content: "nodeLibrary",
+ data: {
+ branchContext: {
+ branchId: "branch-a",
+ conditionalNodeId: "conditional",
+ },
+ next: "target",
+ parent: "loop",
+ previous: "source",
+ },
+ });
+ });
+
+ it("does not branch-scope the post-merge edge after a top-level conditional", () => {
+ useNodesMock.mockReturnValue([
+ {
+ id: "conditional",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ ]);
+
+ renderEdge({ source: "conditional", target: "after-conditional" });
+
+ fireEvent.click(screen.getByRole("button"));
+
+ expect(useWorkflowPanelStore.getState().workflowPanelState).toMatchObject({
+ active: true,
+ content: "nodeLibrary",
+ data: {
+ branchContext: undefined,
+ next: "after-conditional",
+ parent: undefined,
+ previous: "conditional",
+ },
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.tsx b/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.tsx
index fa11b8853..fbfca469f 100644
--- a/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/edges/EdgeWithAddButton.tsx
@@ -24,9 +24,9 @@ import { cn } from "@/util/utils";
import { toast } from "@/components/ui/use-toast";
import { REACT_FLOW_EDGE_Z_INDEX } from "../constants";
-import type { NodeBaseData } from "../nodes/types";
import { WorkflowAddMenu } from "../WorkflowAddMenu";
import { WorkflowAdderBusy } from "../WorkflowAdderBusy";
+import { findBranchContextForInsertion } from "../workflowInsertion";
function EdgeWithAddButton({
source,
@@ -105,51 +105,8 @@ function EdgeWithAddButton({
const isDisabled = !isBusy && recordingStore.isRecording;
- const deriveBranchContext = (): BranchContext | undefined => {
- if (
- sourceNode &&
- "data" in sourceNode &&
- (sourceNode.data as NodeBaseData).conditionalBranchId &&
- (sourceNode.data as NodeBaseData).conditionalNodeId
- ) {
- const sourceData = sourceNode.data as NodeBaseData;
- return {
- conditionalNodeId: sourceData.conditionalNodeId!,
- conditionalLabel: sourceData.conditionalLabel ?? sourceData.label,
- branchId: sourceData.conditionalBranchId!,
- mergeLabel: sourceData.conditionalMergeLabel ?? null,
- };
- }
-
- // If source node doesn't have branch context, check if it's inside a conditional block
- // (e.g., StartNode or NodeAdderNode inside a conditional)
- if (sourceNode?.parentId) {
- const parentNode = nodes.find((n) => n.id === sourceNode.parentId);
- if (parentNode?.type === "conditional" && "data" in parentNode) {
- const conditionalData = parentNode.data as {
- activeBranchId: string | null;
- branches: Array<{ id: string }>;
- label: string;
- mergeLabel: string | null;
- };
- const activeBranchId = conditionalData.activeBranchId;
- const activeBranch = conditionalData.branches?.find(
- (b) => b.id === activeBranchId,
- );
-
- if (activeBranch) {
- return {
- conditionalNodeId: parentNode.id,
- conditionalLabel: conditionalData.label,
- branchId: activeBranch.id,
- mergeLabel: conditionalData.mergeLabel ?? null,
- };
- }
- }
- }
-
- return undefined;
- };
+ const deriveBranchContext = (): BranchContext | undefined =>
+ findBranchContextForInsertion(nodes, source, sourceNode?.parentId);
const updateWorkflowPanelState = (
active: boolean,
@@ -161,7 +118,7 @@ function EdgeWithAddButton({
data: {
previous: source,
next: target,
- parent: branchContext?.conditionalNodeId ?? sourceNode?.parentId,
+ parent: sourceNode?.parentId,
connectingEdgeType: "edgeWithAddButton",
branchContext,
},
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
new file mode 100644
index 000000000..aa62611b5
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.test.tsx
@@ -0,0 +1,159 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import type { Edge, NodeProps } from "@xyflow/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DebugStoreContext } from "@/store/DebugStoreContext";
+import { useRecordingStore } from "@/store/useRecordingStore";
+import { useSettingsStore } from "@/store/SettingsStore";
+import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";
+import { useWorkflowSettingsStore } from "@/store/WorkflowSettingsStore";
+
+import { NodeAdderNode } from "./NodeAdderNode";
+import type { NodeAdderNode as NodeAdderNodeType } from "./types";
+
+const useEdgesMock = vi.fn();
+const useNodesMock = vi.fn();
+
+vi.mock("@xyflow/react", async () => {
+ const actual =
+ await vi.importActual<typeof import("@xyflow/react")>("@xyflow/react");
+
+ return {
+ ...actual,
+ Handle: () => null,
+ useEdges: () => useEdgesMock(),
+ useNodes: () => useNodesMock(),
+ };
+});
+
+vi.mock("react-router-dom", async () => {
+ const actual =
+ await vi.importActual<typeof import("react-router-dom")>(
+ "react-router-dom",
+ );
+
+ return {
+ ...actual,
+ useParams: () => ({ workflowPermanentId: "wpid_test" }),
+ };
+});
+
+vi.mock("@/routes/browserSessions/hooks/useProcessRecordingMutation", () => ({
+ useProcessRecordingMutation: () => ({
+ isPending: false,
+ mutate: vi.fn(),
+ }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useSopToBlocksMutation", () => ({
+ useSopToBlocksMutation: () => ({
+ cancel: vi.fn(),
+ isPending: false,
+ mutate: vi.fn(),
+ }),
+}));
+
+const initialSettings = useSettingsStore.getState();
+const initialRecording = useRecordingStore.getState();
+const initialWorkflowSettings = useWorkflowSettingsStore.getState();
+
+function renderNodeAdder(props: Partial<NodeProps<NodeAdderNodeType>>) {
+ return render(
+ <DebugStoreContext.Provider value={{ isDebugMode: false }}>
+ <NodeAdderNode
+ {...({
+ id: "adder",
+ parentId: "loop",
+ ...props,
+ } as NodeProps<NodeAdderNodeType>)}
+ />
+ </DebugStoreContext.Provider>,
+ );
+}
+
+describe("NodeAdderNode", () => {
+ beforeEach(() => {
+ useSettingsStore.setState(initialSettings, true);
+ useRecordingStore.setState(initialRecording, true);
+ useWorkflowSettingsStore.setState(initialWorkflowSettings, true);
+ useWorkflowPanelStore.setState({
+ workflowPanelState: {
+ active: false,
+ content: "parameters",
+ },
+ });
+
+ useSettingsStore.getState().setIsUsingABrowser(false);
+ useSettingsStore.getState().setIsLoadingABrowser(false);
+ useRecordingStore.setState({ isRecording: false });
+ useWorkflowSettingsStore.setState({ finallyBlockLabel: null });
+ useEdgesMock.mockReset();
+ useNodesMock.mockReset();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("keeps the loop as parent and inherits branch context when adding the first block in a nested loop", () => {
+ const edges: Array<Edge> = [
+ {
+ id: "edge",
+ source: "start",
+ target: "adder",
+ },
+ ];
+
+ useEdgesMock.mockReturnValue(edges);
+ useNodesMock.mockReturnValue([
+ {
+ id: "conditional",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ {
+ id: "loop",
+ parentId: "conditional",
+ type: "loop",
+ data: {
+ conditionalBranchId: "branch-a",
+ conditionalLabel: "conditional",
+ conditionalMergeLabel: null,
+ conditionalNodeId: "conditional",
+ label: "block_8",
+ },
+ },
+ {
+ id: "start",
+ parentId: "loop",
+ type: "start",
+ data: {},
+ },
+ ]);
+
+ renderNodeAdder({});
+
+ fireEvent.click(screen.getByTestId("node-adder-button"));
+
+ expect(useWorkflowPanelStore.getState().workflowPanelState).toMatchObject({
+ active: true,
+ content: "nodeLibrary",
+ data: {
+ branchContext: {
+ branchId: "branch-a",
+ conditionalNodeId: "conditional",
+ },
+ next: "adder",
+ parent: "loop",
+ previous: "start",
+ },
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx
index 662ed3c03..7666e769a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NodeAdderNode/NodeAdderNode.tsx
@@ -11,7 +11,6 @@ import {
useWorkflowPanelStore,
} from "@/store/WorkflowPanelStore";
import { useWorkflowSettingsStore } from "@/store/WorkflowSettingsStore";
-import type { NodeBaseData } from "../types";
import { useRecordedBlocksStore } from "@/store/RecordedBlocksStore";
import { useRecordingStore } from "@/store/useRecordingStore";
import { useSettingsStore } from "@/store/SettingsStore";
@@ -21,6 +20,7 @@ import { toast } from "@/components/ui/use-toast";
import type { NodeAdderNode } from "./types";
import { WorkflowAddMenu } from "../../WorkflowAddMenu";
import { WorkflowAdderBusy } from "../../WorkflowAdderBusy";
+import { findBranchContextForInsertion } from "../../workflowInsertion";
function NodeAdderNode({ id, parentId }: NodeProps<NodeAdderNode>) {
const { workflowPermanentId } = useParams();
@@ -41,51 +41,8 @@ function NodeAdderNode({ id, parentId }: NodeProps<NodeAdderNode>) {
// SOP upload
const fileInputRef = useRef<HTMLInputElement>(null);
- const deriveBranchContext = (previousNodeId: string | undefined) => {
- const previousNode = nodes.find((node) => node.id === previousNodeId);
- if (
- previousNode &&
- "data" in previousNode &&
- (previousNode.data as NodeBaseData).conditionalBranchId &&
- (previousNode.data as NodeBaseData).conditionalNodeId
- ) {
- const prevData = previousNode.data as NodeBaseData;
- return {
- conditionalNodeId: prevData.conditionalNodeId!,
- conditionalLabel: prevData.conditionalLabel ?? prevData.label,
- branchId: prevData.conditionalBranchId!,
- mergeLabel: prevData.conditionalMergeLabel ?? null,
- } satisfies BranchContext;
- }
-
- // If previous node doesn't have branch context, check if this NodeAdderNode is inside a conditional block
- if (parentId) {
- const parentNode = nodes.find((n) => n.id === parentId);
- if (parentNode?.type === "conditional" && "data" in parentNode) {
- const conditionalData = parentNode.data as {
- activeBranchId: string | null;
- branches: Array<{ id: string }>;
- label: string;
- mergeLabel: string | null;
- };
- const activeBranchId = conditionalData.activeBranchId;
- const activeBranch = conditionalData.branches?.find(
- (b) => b.id === activeBranchId,
- );
-
- if (activeBranch) {
- return {
- conditionalNodeId: parentNode.id,
- conditionalLabel: conditionalData.label,
- branchId: activeBranch.id,
- mergeLabel: conditionalData.mergeLabel ?? null,
- } satisfies BranchContext;
- }
- }
- }
-
- return undefined;
- };
+ const deriveBranchContext = (previousNodeId: string | undefined) =>
+ findBranchContextForInsertion(nodes, previousNodeId, parentId);
// Find the edge that targets this NodeAdder
// If inside a conditional, find the edge for the active branch
@@ -172,7 +129,7 @@ function NodeAdderNode({ id, parentId }: NodeProps<NodeAdderNode>) {
data: {
previous: previous ?? null,
next: id,
- parent: branchContext?.conditionalNodeId ?? parentId,
+ parent: parentId,
connectingEdgeType: "default",
branchContext,
},
@@ -231,6 +188,7 @@ function NodeAdderNode({ id, parentId }: NodeProps<NodeAdderNode>) {
const adder = (
<div
+ data-testid="node-adder-button"
className={cn("rounded-full bg-slate-50 p-2", {
"cursor-not-allowed bg-[grey]": isDisabled,
})}
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.test.ts b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.test.ts
new file mode 100644
index 000000000..ca17dd0a2
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.test.ts
@@ -0,0 +1,199 @@
+import type { Edge } from "@xyflow/react";
+import { describe, expect, it } from "vitest";
+
+import type { BranchContext } from "@/store/WorkflowPanelStore";
+
+import {
+ findBranchContextForInsertion,
+ shouldKeepExistingEdgeForInsertion,
+} from "./workflowInsertion";
+
+const branch: BranchContext = {
+ branchId: "branch-a",
+ conditionalLabel: "conditional",
+ conditionalNodeId: "conditional-node",
+ mergeLabel: null,
+};
+
+function edge(overrides: Partial<Edge>): Edge {
+ return {
+ id: "edge",
+ source: "previous",
+ target: "next",
+ ...overrides,
+ };
+}
+
+describe("shouldKeepExistingEdgeForInsertion", () => {
+ it("removes the selected outgoing edge for non-branch insertions", () => {
+ expect(
+ shouldKeepExistingEdgeForInsertion(edge({}), {
+ previous: "previous",
+ next: "next",
+ }),
+ ).toBe(false);
+ });
+
+ it("keeps unrelated outgoing edges from the same previous node", () => {
+ expect(
+ shouldKeepExistingEdgeForInsertion(edge({ target: "other-next" }), {
+ previous: "previous",
+ next: "next",
+ }),
+ ).toBe(true);
+ });
+
+ it("removes the selected edge for the active conditional branch", () => {
+ expect(
+ shouldKeepExistingEdgeForInsertion(
+ edge({ data: { conditionalBranchId: "branch-a" } }),
+ {
+ branch,
+ previous: "previous",
+ next: "next",
+ },
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps selected edges for other conditional branches", () => {
+ expect(
+ shouldKeepExistingEdgeForInsertion(
+ edge({ data: { conditionalBranchId: "branch-b" } }),
+ {
+ branch,
+ previous: "previous",
+ next: "next",
+ },
+ ),
+ ).toBe(true);
+ });
+
+ it("removes untagged selected edges when branch context comes from a nested parent", () => {
+ expect(
+ shouldKeepExistingEdgeForInsertion(edge({ data: undefined }), {
+ branch,
+ previous: "previous",
+ next: "next",
+ }),
+ ).toBe(false);
+ });
+});
+
+describe("findBranchContextForInsertion", () => {
+ it("uses branch metadata from the insertion node", () => {
+ expect(
+ findBranchContextForInsertion(
+ [
+ {
+ id: "previous",
+ data: {
+ conditionalBranchId: "branch-a",
+ conditionalLabel: "conditional",
+ conditionalMergeLabel: null,
+ conditionalNodeId: "conditional-node",
+ label: "block_1",
+ },
+ },
+ ],
+ "previous",
+ ),
+ ).toEqual(branch);
+ });
+
+ it("climbs to a parent loop when an empty nested loop inserts from its start node", () => {
+ expect(
+ findBranchContextForInsertion(
+ [
+ {
+ id: "loop",
+ parentId: "conditional-node",
+ type: "loop",
+ data: {
+ conditionalBranchId: "branch-a",
+ conditionalLabel: "conditional",
+ conditionalMergeLabel: null,
+ conditionalNodeId: "conditional-node",
+ label: "block_8",
+ },
+ },
+ {
+ id: "start",
+ parentId: "loop",
+ type: "start",
+ data: {},
+ },
+ ],
+ "start",
+ "loop",
+ ),
+ ).toEqual(branch);
+ });
+
+ it("uses the active branch from a direct conditional parent", () => {
+ expect(
+ findBranchContextForInsertion(
+ [
+ {
+ id: "conditional-node",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }, { id: "branch-b" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ {
+ id: "start",
+ parentId: "conditional-node",
+ type: "start",
+ data: {},
+ },
+ ],
+ "start",
+ ),
+ ).toEqual(branch);
+ });
+
+ it("does not branch-scope insertion after a top-level conditional node", () => {
+ expect(
+ findBranchContextForInsertion(
+ [
+ {
+ id: "conditional-node",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }, { id: "branch-b" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ ],
+ "conditional-node",
+ ),
+ ).toBeUndefined();
+ });
+
+ it("uses the active branch when the caller only has a conditional parent", () => {
+ expect(
+ findBranchContextForInsertion(
+ [
+ {
+ id: "conditional-node",
+ type: "conditional",
+ data: {
+ activeBranchId: "branch-a",
+ branches: [{ id: "branch-a" }, { id: "branch-b" }],
+ label: "conditional",
+ mergeLabel: null,
+ },
+ },
+ ],
+ undefined,
+ "conditional-node",
+ ),
+ ).toEqual(branch);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.ts b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.ts
new file mode 100644
index 000000000..318b23d12
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowInsertion.ts
@@ -0,0 +1,143 @@
+import type { Edge } from "@xyflow/react";
+
+import type { BranchContext } from "@/store/WorkflowPanelStore";
+
+import type { NodeBaseData } from "./nodes/types";
+
+type InsertionEdgeContext = {
+ branch?: BranchContext;
+ next: string | null;
+ previous: string | null;
+};
+
+type InsertionNode = {
+ id: string;
+ parentId?: string;
+ type?: string;
+ data?: unknown;
+};
+
+function branchContextFromNodeData(
+ data: Partial<NodeBaseData> | undefined,
+): BranchContext | undefined {
+ if (!data?.conditionalBranchId || !data.conditionalNodeId) {
+ return undefined;
+ }
+
+ return {
+ conditionalNodeId: data.conditionalNodeId,
+ conditionalLabel:
+ data.conditionalLabel ?? data.label ?? data.conditionalNodeId,
+ branchId: data.conditionalBranchId,
+ mergeLabel: data.conditionalMergeLabel ?? null,
+ };
+}
+
+function branchContextFromConditionalNode(
+ node: InsertionNode | undefined,
+): BranchContext | undefined {
+ if (
+ node?.type !== "conditional" ||
+ !node.data ||
+ typeof node.data !== "object"
+ ) {
+ return undefined;
+ }
+
+ const conditionalData = node.data as {
+ activeBranchId: string | null;
+ branches: Array<{ id: string }>;
+ label: string;
+ mergeLabel: string | null;
+ };
+ const activeBranch = conditionalData.branches?.find(
+ (branch) => branch.id === conditionalData.activeBranchId,
+ );
+
+ if (!activeBranch) {
+ return undefined;
+ }
+
+ return {
+ conditionalNodeId: node.id,
+ conditionalLabel: conditionalData.label,
+ branchId: activeBranch.id,
+ mergeLabel: conditionalData.mergeLabel ?? null,
+ };
+}
+
+export function findBranchContextForInsertion(
+ nodes: Array<InsertionNode>,
+ nodeId: string | undefined,
+ parentId?: string,
+): BranchContext | undefined {
+ const nodeById = new Map(nodes.map((node) => [node.id, node]));
+
+ const findFromNode = (
+ startId: string | undefined,
+ { includeStartingConditional }: { includeStartingConditional: boolean },
+ ) => {
+ const visited = new Set<string>();
+ let currentId = startId;
+ let isStartingNode = true;
+
+ while (currentId && !visited.has(currentId)) {
+ visited.add(currentId);
+
+ const node = nodeById.get(currentId);
+ if (!node) {
+ return undefined;
+ }
+
+ const nodeBranchContext = branchContextFromNodeData(
+ node.data as Partial<NodeBaseData> | undefined,
+ );
+ if (nodeBranchContext) {
+ return nodeBranchContext;
+ }
+
+ const conditionalBranchContext =
+ (includeStartingConditional || !isStartingNode) &&
+ branchContextFromConditionalNode(node);
+ if (conditionalBranchContext) {
+ return conditionalBranchContext;
+ }
+
+ isStartingNode = false;
+ currentId = node.parentId;
+ }
+
+ return undefined;
+ };
+
+ return (
+ findFromNode(nodeId, { includeStartingConditional: false }) ??
+ findFromNode(parentId, { includeStartingConditional: true })
+ );
+}
+
+export function shouldKeepExistingEdgeForInsertion(
+ edge: Edge,
+ { branch, next, previous }: InsertionEdgeContext,
+): boolean {
+ if (!previous || edge.source !== previous) {
+ return true;
+ }
+
+ // Only replace the selected insertion edge; preserve any other outgoing
+ // edges from the same node, such as inactive conditional branch edges.
+ if (next && edge.target !== next) {
+ return true;
+ }
+
+ if (!branch) {
+ return false;
+ }
+
+ const edgeData = edge.data as { conditionalBranchId?: string } | undefined;
+
+ return Boolean(
+ edgeData?.conditionalBranchId &&
+ edgeData.conditionalBranchId !== branch.branchId,
+ );
+}