diff --git a/stores/workflow/store.ts b/stores/workflow/store.ts index 48b681386f..99f63f41cb 100644 --- a/stores/workflow/store.ts +++ b/stores/workflow/store.ts @@ -194,10 +194,10 @@ export const useWorkflowStore = create()( const newEdges = [...get().edges, newEdge] const { hasCycle, path } = detectCycle(newEdges, edge.source) - // Create new loops state + // Only create a loop if we have a valid cycle with at least 2 unique nodes const newLoops = { ...get().loops } - if (hasCycle) { + if (hasCycle && path.length > 1) { const loopId = crypto.randomUUID() newLoops[loopId] = { id: loopId, diff --git a/stores/workflow/utils.ts b/stores/workflow/utils.ts index e3afec448a..5a09c1a310 100644 --- a/stores/workflow/utils.ts +++ b/stores/workflow/utils.ts @@ -43,16 +43,23 @@ export function detectCycle(edges: Edge[], startNode: string): { hasCycle: boole // Perform DFS and construct cycle path if found const hasCycle = dfs(startNode) - // If cycle found, construct the path + // If cycle found, construct the path and ensure no duplicates const cyclePath: string[] = [] if (hasCycle) { let current = startNode + const seenNodes = new Set() + do { - cyclePath.unshift(current) + // Only add node if we haven't seen it before + if (!seenNodes.has(current)) { + cyclePath.unshift(current) + seenNodes.add(current) + } current = pathMap.get(current)! } while (current !== startNode && current !== undefined) - if (current === startNode) { + // Add starting node only if it's not already in the path + if (current === startNode && !seenNodes.has(startNode)) { cyclePath.unshift(startNode) } }