Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Fix: No connecting line appeared after adding an iteration operator following a conditional operator. (#20833)

balibabuf07116337d2e
diff --git a/web/src/pages/agent/canvas/node/handle-readd-group-node.test.tsx b/web/src/pages/agent/canvas/node/handle-readd-group-node.test.tsx
new file mode 100644
index 0000000000..2dcfde7f24
--- /dev/null
+++ b/web/src/pages/agent/canvas/node/handle-readd-group-node.test.tsx
@@ -0,0 +1,178 @@
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import { Position, ReactFlow } from '@xyflow/react';
+import { MemoryRouter } from 'react-router';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { NodeHandleId, Operator } from '../../constant';
+import { AgentInstanceContext } from '../../context';
+import { useAddNode } from '../../hooks/use-add-node';
+import useGraphStore from '../../store';
+import { DropdownProvider } from '../context';
+import { CommonHandle } from './handle';
+
+// This file uses jest.mock, so it is transformed by esbuild-jest's babel
+// pass: imported bindings must not be used in type positions (type-only
+// imports break the pass), but annotations over global types are fine.
+
+jest.mock('react-i18next', () => ({
+ ...jest.requireActual('react-i18next'),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+jest.mock('@/hooks/use-llm-request', () => ({
+ useFetchDefaultModelDictionary: () => ({ llm_id: '' }),
+}));
+
+// The global human-id mock returns the same id for every call, which would
+// mask duplicate-id regressions in the group start nodes; make ids unique.
+jest.mock('human-id', () => {
+ let counter = 0;
+ return () => `human-id-${++counter}`;
+});
+
+beforeAll(() => {
+ // React Flow measures nodes with ResizeObserver and parses zoom transforms
+ // with DOMMatrixReadOnly; jsdom has neither (xyflow testing guide recipe).
+ class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ if (!window.ResizeObserver) {
+ window.ResizeObserver = ResizeObserverStub;
+ }
+
+ class DOMMatrixReadOnlyStub {
+ m22: number;
+ constructor(transform?: string) {
+ const scale = transform?.match(/scale\(([\d.]+)\)/)?.[1];
+ this.m22 = scale ? Number(scale) : 1;
+ }
+ }
+ if (!window.DOMMatrixReadOnly) {
+ window.DOMMatrixReadOnly =
+ DOMMatrixReadOnlyStub as unknown as typeof DOMMatrixReadOnly;
+ }
+});
+
+function SourceNode({ id }: { id: string }) {
+ return (
+ <div>
+ source
+ <CommonHandle
+ id="end_cpn_ids"
+ type="source"
+ position={Position.Right}
+ nodeId={id}
+ isConnectable
+ />
+ </div>
+ );
+}
+
+function DummyGroupNode() {
+ return <div>group node</div>;
+}
+
+const nodeTypes = {
+ sourceNode: SourceNode,
+ iterationNode: DummyGroupNode,
+ iterationStartNode: DummyGroupNode,
+};
+
+function Canvas() {
+ const nodes = useGraphStore((state) => state.nodes);
+ const edges = useGraphStore((state) => state.edges);
+ const onNodesChange = useGraphStore((state) => state.onNodesChange);
+ const onEdgesChange = useGraphStore((state) => state.onEdgesChange);
+ const { addCanvasNode } = useAddNode();
+
+ return (
+ <AgentInstanceContext.Provider
+ value={{ addCanvasNode, showFormDrawer: () => {} }}
+ >
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ nodeTypes={nodeTypes}
+ />
+ </AgentInstanceContext.Provider>
+ );
+}
+
+const createSwitchNode = () => ({
+ id: 'switch:0',
+ type: 'sourceNode',
+ position: { x: 0, y: 0 },
+ data: { label: Operator.Switch, name: 'switch_0', form: {} },
+});
+
+function openMenuAndPickIteration() {
+ const handle = document.querySelector(
+ '.react-flow__handle[data-handleid="end_cpn_ids"]',
+ );
+ expect(handle).not.toBeNull();
+ fireEvent.click(handle as Element);
+
+ const item = screen.getByText('flow.iteration');
+ fireEvent.click(item);
+}
+
+describe('re-adding a group node from a handle menu after deletion', () => {
+ beforeEach(() => {
+ useGraphStore.setState({ nodes: [createSwitchNode()], edges: [] });
+ });
+
+ it('adds an iteration node twice from the same else handle', () => {
+ render(
+ <MemoryRouter>
+ <TooltipProvider>
+ <DropdownProvider>
+ <Canvas />
+ </DropdownProvider>
+ </TooltipProvider>
+ </MemoryRouter>,
+ );
+
+ openMenuAndPickIteration();
+
+ const firstIteration = useGraphStore
+ .getState()
+ .nodes.find((x) => x.data.label === Operator.Iteration);
+ expect(firstIteration).toBeTruthy();
+ expect(useGraphStore.getState().edges).toHaveLength(1);
+
+ act(() => {
+ useGraphStore.getState().deleteIterationNodeById(firstIteration!.id);
+ });
+ expect(
+ useGraphStore
+ .getState()
+ .nodes.some((x) => x.data.label === Operator.Iteration),
+ ).toBe(false);
+ expect(useGraphStore.getState().edges).toHaveLength(0);
+
+ openMenuAndPickIteration();
+
+ const { nodes, edges } = useGraphStore.getState();
+ const secondIteration = nodes.find(
+ (x) => x.data.label === Operator.Iteration,
+ );
+ expect(secondIteration).toBeTruthy();
+ expect(
+ nodes.some(
+ (x) =>
+ x.data.label === Operator.IterationStart &&
+ x.parentId === secondIteration!.id,
+ ),
+ ).toBe(true);
+ expect(edges).toHaveLength(1);
+ expect(edges[0]).toMatchObject({
+ source: 'switch:0',
+ target: secondIteration!.id,
+ sourceHandle: 'end_cpn_ids',
+ targetHandle: NodeHandleId.End,
+ });
+ });
+});
diff --git a/web/src/pages/agent/constant/index.tsx b/web/src/pages/agent/constant/index.tsx
index 42e8eaf42a..cca80edc8d 100644
--- a/web/src/pages/agent/constant/index.tsx
+++ b/web/src/pages/agent/constant/index.tsx
@@ -960,6 +960,7 @@ export const NodeMap = {
[Operator.GeneralChunker]: 'chunkerNode',
[Operator.TokenChunker]: 'chunkerNode',
[Operator.TitleChunker]: 'chunkerNode',
+ [Operator.ManualChunker]: 'chunkerNode',
[Operator.Extractor]: 'contextNode',
[Operator.Compiler]: 'compilationNode',
[Operator.DataOperations]: 'dataOperationsNode',
diff --git a/web/src/pages/agent/hooks/use-add-node.test.tsx b/web/src/pages/agent/hooks/use-add-node.test.tsx
new file mode 100644
index 0000000000..a115c3e577
--- /dev/null
+++ b/web/src/pages/agent/hooks/use-add-node.test.tsx
@@ -0,0 +1,188 @@
+import { act, renderHook } from '@testing-library/react';
+import { Position } from '@xyflow/react';
+import { NodeHandleId, Operator } from '../constant';
+import useGraphStore from '../store';
+import { useAddNode } from './use-add-node';
+
+// This file uses jest.mock, so it is transformed by esbuild-jest's babel
+// pass: imported bindings must not be used in type positions (type-only
+// imports break the pass), but annotations over global types are fine.
+
+jest.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+jest.mock('@/hooks/use-llm-request', () => ({
+ useFetchDefaultModelDictionary: () => ({ llm_id: '' }),
+}));
+
+// The global human-id mock returns the same id for every call, which would
+// mask duplicate-id regressions in the group start nodes; make ids unique.
+jest.mock('human-id', () => {
+ let counter = 0;
+ return () => `human-id-${++counter}`;
+});
+
+const createSwitchNode = () => ({
+ id: 'switch:0',
+ type: 'switchNode',
+ position: { x: 0, y: 0 },
+ data: { label: Operator.Switch, name: 'switch_0', form: {} },
+});
+
+describe('useAddNode', () => {
+ beforeEach(() => {
+ useGraphStore.setState({ nodes: [], edges: [] });
+ });
+
+ it('connects a new iteration node to the switch branch handle that opened the dropdown', () => {
+ useGraphStore.setState({ nodes: [createSwitchNode()], edges: [] });
+
+ const { result } = renderHook(() => useAddNode());
+
+ let newNodeId: string | undefined;
+ act(() => {
+ newNodeId = result.current.addCanvasNode(Operator.Iteration, {
+ nodeId: 'switch:0',
+ id: 'Case 1',
+ position: Position.Right,
+ isFromConnectionDrag: false,
+ })();
+ });
+
+ const { nodes, edges } = useGraphStore.getState();
+
+ expect(nodes.some((x) => x.id === newNodeId)).toBe(true);
+ // The iteration start child is created inside the group
+ expect(
+ nodes.some(
+ (x) =>
+ x.data.label === Operator.IterationStart && x.parentId === newNodeId,
+ ),
+ ).toBe(true);
+
+ expect(edges).toHaveLength(1);
+ expect(edges[0]).toMatchObject({
+ source: 'switch:0',
+ target: newNodeId,
+ sourceHandle: 'Case 1',
+ targetHandle: NodeHandleId.End,
+ });
+
+ // The group node must not overlap its parent: with nodeOrigin [0.5, 0]
+ // position.x is the node's center, so its left edge is x - width / 2.
+ // The switch node at x = 0 with the default 200 width has its right
+ // edge at 100, plus the 100 gap the left edge must be at 200.
+ const iterationNode = nodes.find((x) => x.id === newNodeId);
+ expect(iterationNode!.position.x - (iterationNode!.width ?? 0) / 2).toBe(
+ 200,
+ );
+ });
+
+ it('stacks the next sibling below a group child without overlap', () => {
+ useGraphStore.setState({ nodes: [createSwitchNode()], edges: [] });
+
+ const { result } = renderHook(() => useAddNode());
+
+ let iterationId: string | undefined;
+ act(() => {
+ iterationId = result.current.addCanvasNode(Operator.Iteration, {
+ nodeId: 'switch:0',
+ id: 'Case 1',
+ position: Position.Right,
+ isFromConnectionDrag: false,
+ })();
+ });
+
+ let messageId: string | undefined;
+ act(() => {
+ messageId = result.current.addCanvasNode(Operator.Message, {
+ nodeId: 'switch:0',
+ id: 'Case 1',
+ position: Position.Right,
+ isFromConnectionDrag: false,
+ })();
+ });
+
+ const { nodes } = useGraphStore.getState();
+ const iterationNode = nodes.find((x) => x.id === iterationId);
+ const messageNode = nodes.find((x) => x.id === messageId);
+ // A group child is 250 tall; the +150 stacking step of plain nodes
+ // would land inside it.
+ expect(messageNode!.position.y).toBeGreaterThanOrEqual(
+ iterationNode!.position.y + (iterationNode!.height ?? 0),
+ );
+ });
+
+ it('falls back to the start handle when no specific handle was picked', () => {
+ useGraphStore.setState({ nodes: [createSwitchNode()], edges: [] });
+
+ const { result } = renderHook(() => useAddNode());
+
+ let newNodeId: string | undefined;
+ act(() => {
+ newNodeId = result.current.addCanvasNode(Operator.Loop, {
+ nodeId: 'switch:0',
+ position: Position.Right,
+ isFromConnectionDrag: false,
+ })();
+ });
+
+ const { edges } = useGraphStore.getState();
+
+ expect(edges).toHaveLength(1);
+ expect(edges[0]).toMatchObject({
+ source: 'switch:0',
+ target: newNodeId,
+ sourceHandle: NodeHandleId.Start,
+ targetHandle: NodeHandleId.End,
+ });
+ });
+
+ it('adds an iteration node again after the previous one was deleted', () => {
+ useGraphStore.setState({ nodes: [createSwitchNode()], edges: [] });
+
+ const { result } = renderHook(() => useAddNode());
+
+ const addIteration = () => {
+ let newNodeId: string | undefined;
+ act(() => {
+ newNodeId = result.current.addCanvasNode(Operator.Iteration, {
+ nodeId: 'switch:0',
+ id: 'end_cpn_ids',
+ position: Position.Right,
+ isFromConnectionDrag: false,
+ })();
+ });
+ return newNodeId;
+ };
+
+ const firstId = addIteration();
+ act(() => {
+ useGraphStore.getState().deleteIterationNodeById(firstId!);
+ });
+
+ expect(useGraphStore.getState().nodes).toHaveLength(1);
+ expect(useGraphStore.getState().edges).toHaveLength(0);
+
+ const secondId = addIteration();
+ expect(secondId).not.toBe(firstId);
+
+ const { nodes, edges } = useGraphStore.getState();
+ expect(nodes.some((x) => x.id === secondId)).toBe(true);
+ // The new group gets its own start child bound to it — not a reused
+ // (frozen) object still pointing at the deleted iteration node
+ const startChildren = nodes.filter(
+ (x) => x.data.label === Operator.IterationStart,
+ );
+ expect(startChildren).toHaveLength(1);
+ expect(startChildren[0].parentId).toBe(secondId);
+ expect(edges).toHaveLength(1);
+ expect(edges[0]).toMatchObject({
+ source: 'switch:0',
+ target: secondId,
+ sourceHandle: 'end_cpn_ids',
+ targetHandle: NodeHandleId.End,
+ });
+ });
+});
diff --git a/web/src/pages/agent/hooks/use-add-node.ts b/web/src/pages/agent/hooks/use-add-node.ts
index d0ed36bb02..27804925d8 100644
--- a/web/src/pages/agent/hooks/use-add-node.ts
+++ b/web/src/pages/agent/hooks/use-add-node.ts
@@ -76,19 +76,33 @@ function isBottomSubAgent(type: string, position: Position) {
);
}
-const GroupStartNodeMap = {
- [Operator.Iteration]: {
+// The canvas uses nodeOrigin [0.5, 0], so position.x is a node's horizontal
+// center and position.y its top edge.
+const DefaultNodeWidth = 200;
+const DefaultNodeHeight = 100;
+const GroupNodeWidth = 500;
+const GroupNodeHeight = 250;
+const HorizontalNodeGap = 100;
+const VerticalNodeGap = 50;
+
+// Each add must produce a fresh start node object (and id): nodes are stored
+// by reference in the zustand store and immer freezes them, so a shared
+// object would be frozen after the first add and duplicate ids after the
+// second.
+const GroupStartNodeBuilders = {
+ [Operator.Iteration]: (parentId: string): Node<any> => ({
id: `${Operator.IterationStart}:${humanId()}`,
type: 'iterationStartNode',
position: { x: 50, y: 100 },
data: {
label: Operator.IterationStart,
name: Operator.IterationStart,
- form: initialIterationStartValues,
+ form: { ...initialIterationStartValues },
},
extent: 'parent' as const,
- },
- [Operator.Loop]: {
+ parentId,
+ }),
+ [Operator.Loop]: (parentId: string): Node<any> => ({
id: `${Operator.LoopStart}:${humanId()}`,
type: 'loopStartNode',
position: { x: 50, y: 100 },
@@ -98,21 +112,26 @@ const GroupStartNodeMap = {
form: {},
},
extent: 'parent' as const,
- },
+ parentId,
+ }),
};
function useAddGroupNode() {
const { addEdge, addNode } = useGraphStore((state) => state);
const addGroupNode = useCallback(
- (operatorType: string, newNode: Node<any>, nodeId?: string) => {
- newNode.width = 500;
- newNode.height = 250;
-
- const startNode: Node<any> =
- GroupStartNodeMap[operatorType as keyof typeof GroupStartNodeMap];
-
- startNode.parentId = newNode.id;
+ (
+ operatorType: string,
+ newNode: Node<any>,
+ nodeId?: string,
+ sourceHandle?: string,
+ ) => {
+ newNode.width = GroupNodeWidth;
+ newNode.height = GroupNodeHeight;
+
+ const startNode = GroupStartNodeBuilders[
+ operatorType as keyof typeof GroupStartNodeBuilders
+ ](newNode.id);
addNode(newNode);
addNode(startNode);
@@ -121,7 +140,7 @@ function useAddGroupNode() {
addEdge({
source: nodeId,
target: newNode.id,
- sourceHandle: NodeHandleId.Start,
+ sourceHandle: sourceHandle || NodeHandleId.Start,
targetHandle: NodeHandleId.End,
});
}
@@ -191,6 +210,9 @@ export const useInitializeOperatorParams = () => {
[Operator.TokenChunker]: initialTokenChunkerValues,
[Operator.GeneralChunker]: initialGeneralChunkerValues,
[Operator.TitleChunker]: initialTitleChunkerValues,
+ // The manual chunker shares the title chunker's form (TitleChunkerForm
+ // with pinMethodGroup) and initial values, like normalizeOperatorForm.
+ [Operator.ManualChunker]: initialTitleChunkerValues,
[Operator.Extractor]: {
...getInitialExtractorValues(),
llm_id: llmId,
@@ -211,7 +233,10 @@ export const useInitializeOperatorParams = () => {
const initializeOperatorParams = useCallback(
(operatorName: Operator, position: Position) => {
- const initialValues = initialFormValuesMap[operatorName];
+ // The map only covers canvas operators; parser-internal chunkers
+ // (Table/QA/One/Page) are never added through this path.
+ const initialValues =
+ initialFormValuesMap[operatorName as keyof typeof initialFormValuesMap];
if (isBottomSubAgent(operatorName, position)) {
return {
...initialValues,
@@ -243,7 +268,7 @@ export function useCalculateNewlyChildPosition() {
const edges = useGraphStore((state) => state.edges);
const calculateNewlyBackChildPosition = useCallback(
- (id?: string, sourceHandle?: string) => {
+ (id?: string, sourceHandle?: string, childWidth = DefaultNodeWidth) => {
const parentNode = getNode(id);
// Calculate the coordinates of child nodes to prevent newly added child nodes from covering other child nodes
@@ -251,15 +276,31 @@ export function useCalculateNewlyChildPosition() {
.filter((x) => x.source === id && x.sourceHandle === sourceHandle)
.map((x) => x.target);
- const yAxises = nodes
- .filter((x) => allChildNodeIds.some((y) => y === x.id))
- .map((x) => x.position.y);
+ const childNodes = nodes.filter((x) =>
+ allChildNodeIds.some((y) => y === x.id),
+ );
- const maxY = Math.max(...yAxises);
+ const childTops = childNodes.map((x) => x.position.y);
+ const childBottoms = childNodes.map(
+ (x) =>
+ x.position.y + (x.height ?? x.measured?.height ?? DefaultNodeHeight),
+ );
+
+ // nodeOrigin is [0.5, 0]: position.x is the node's horizontal center,
+ // so the gap must account for both the parent's and the child's width.
+ const parentWidth =
+ parentNode?.width ?? parentNode?.measured?.width ?? DefaultNodeWidth;
+ const parentRight = (parentNode?.position.x || 0) + parentWidth / 2;
const position = {
- y: yAxises.length > 0 ? maxY + 150 : parentNode?.position.y || 0,
- x: (parentNode?.position.x || 0) + 300,
+ y:
+ childTops.length > 0
+ ? Math.max(
+ Math.max(...childTops) + 150,
+ Math.max(...childBottoms) + VerticalNodeGap,
+ )
+ : parentNode?.position.y || 0,
+ x: parentRight + HorizontalNodeGap + childWidth / 2,
};
return position;
@@ -417,12 +458,20 @@ export function useAddNode(reactFlowInstance?: ReactFlowInstance<any, any>) {
type !== Operator.Note &&
!params.isFromConnectionDrag
) {
- position = calculateNewlyBackChildPosition(nodeId, params.id);
+ position = calculateNewlyBackChildPosition(
+ nodeId,
+ params.id,
+ [Operator.Iteration, Operator.Loop].includes(type as Operator)
+ ? GroupNodeWidth
+ : DefaultNodeWidth,
+ );
}
const newNode: Node<any> = {
id: `${type}:${humanId()}`,
- type: NodeMap[type as Operator] || 'ragNode',
+ // NodeMap only covers canvas operators; unknown types fall back to
+ // the generic ragNode renderer.
+ type: NodeMap[type as keyof typeof NodeMap] || 'ragNode',
position: position || {
x: 0,
y: 0,
@@ -451,7 +500,7 @@ export function useAddNode(reactFlowInstance?: ReactFlowInstance<any, any>) {
}
if ([Operator.Iteration, Operator.Loop].includes(type as Operator)) {
- return addGroupNode(type, newNode, nodeId);
+ return addGroupNode(type, newNode, nodeId, params.id);
} else if (
type === Operator.Agent &&
params.position === Position.Bottom