Skip to content

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

fix(agent): preserve Switch routing when recreating ElseIf branches (#21663)

Sbaaoui Idrissc835bf02735d
diff --git a/web/src/pages/agent/form/switch-form/index.tsx b/web/src/pages/agent/form/switch-form/index.tsx
index 137aed291b..55efb9f9a0 100644
--- a/web/src/pages/agent/form/switch-form/index.tsx
+++ b/web/src/pages/agent/form/switch-form/index.tsx
@@ -11,6 +11,7 @@ import { useBuildSwitchOperatorOptions } from '@/hooks/logic-hooks/use-build-ope
import { useBuildSwitchLogicOperatorOptions } from '@/hooks/logic-hooks/use-build-options';
import { cn } from '@/lib/utils';
import { zodResolver } from '@hookform/resolvers/zod';
+import { reconnectEdge } from '@xyflow/react';
import { t } from 'i18next';
import { X } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
@@ -24,6 +25,8 @@ import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import { useFilterQueryVariableOptionsByTypes } from '../../hooks/use-get-begin-query';
import { IOperatorForm } from '../../interface';
+import useGraphStore from '../../store';
+import { generateSwitchHandleText, getOperatorIndex } from '../../utils';
import { FormWrapper } from '../components/form-wrapper';
import { GroupedSelectWithSecondaryMenu } from '../components/select-with-secondary-menu';
import { useValues } from './use-values';
@@ -252,6 +255,44 @@ function SwitchForm({ node }: IOperatorForm) {
control: form.control,
});
+ const removeCondition = useCallback(
+ (index: number) => {
+ if (node?.id) {
+ const { edges, setEdges } = useGraphStore.getState();
+ setEdges(
+ edges
+ .filter(
+ (edge) =>
+ edge.source !== node.id ||
+ edge.sourceHandle !== generateSwitchHandleText(index),
+ )
+ .map((edge) => {
+ const branchIndex =
+ Number(getOperatorIndex(edge.sourceHandle ?? '')) - 1;
+ if (
+ edge.source !== node.id ||
+ !Number.isInteger(branchIndex) ||
+ branchIndex <= index
+ )
+ return edge;
+ return reconnectEdge(
+ edge,
+ {
+ source: edge.source,
+ target: edge.target,
+ sourceHandle: generateSwitchHandleText(branchIndex - 1),
+ targetHandle: edge.targetHandle ?? null,
+ },
+ [edge],
+ )[0];
+ }),
+ );
+ }
+ remove(index);
+ },
+ [node?.id, remove],
+ );
+
const switchLogicOperatorOptions = useBuildSwitchLogicOperatorOptions();
useWatchFormChange(node?.id, form);
@@ -274,7 +315,7 @@ function SwitchForm({ node }: IOperatorForm) {
<Button
variant={'secondary'}
className="-translate-y-1"
- onClick={() => remove(index)}
+ onClick={() => removeCondition(index)}
>
{t('common.remove')} <X />
</Button>
@@ -294,7 +335,7 @@ function SwitchForm({ node }: IOperatorForm) {
)}
<ConditionCards
name={name}
- removeParent={remove}
+ removeParent={removeCondition}
parentIndex={index}
parentLength={fields.length}
></ConditionCards>
diff --git a/web/src/pages/agent/form/switch-form/use-watch-change.ts b/web/src/pages/agent/form/switch-form/use-watch-change.ts
index bb6d5b1b15..314b7af572 100644
--- a/web/src/pages/agent/form/switch-form/use-watch-change.ts
+++ b/web/src/pages/agent/form/switch-form/use-watch-change.ts
@@ -3,13 +3,12 @@ import { useEffect } from 'react';
import { UseFormReturn, useWatch } from 'react-hook-form';
import useGraphStore from '../../store';
-export function useWatchFormChange(id?: string, form?: UseFormReturn) {
+export function useWatchFormChange(id?: string, form?: UseFormReturn<any>) {
let values = useWatch({ control: form?.control });
const updateNodeForm = useGraphStore((state) => state.updateNodeForm);
useEffect(() => {
// Manually triggered form updates are synchronized to the canvas
- console.log('🚀 ~ useWatchFormChange ~ values:', form?.formState.isDirty);
if (id) {
values = form?.getValues() || {};
const nextValues: any = {
@@ -20,5 +19,5 @@ export function useWatchFormChange(id?: string, form?: UseFormReturn) {
updateNodeForm(id, nextValues);
}
- }, [form?.formState.isDirty, id, updateNodeForm, values]);
+ }, [form, form?.formState.isDirty, id, updateNodeForm, values]);
}
diff --git a/web/src/pages/agent/utils.ts b/web/src/pages/agent/utils.ts
index c59e48ce86..a0750265b4 100644
--- a/web/src/pages/agent/utils.ts
+++ b/web/src/pages/agent/utils.ts
@@ -7,6 +7,7 @@ import {
ICategorizeForm,
ICategorizeItem,
ICategorizeItemResult,
+ ISwitchForm,
RAGFlowNodeType,
} from '@/interfaces/database/agent';
import { buildSelectOptions } from '@/utils/component-util';
@@ -33,6 +34,7 @@ import {
NoDebugOperatorsList,
NodeHandleId,
Operator,
+ SwitchElseTo,
TitleChunkerMethod,
TypesWithArray,
WebhookSecurityAuthType,
@@ -135,6 +137,10 @@ function buildAgentTools(edges: Edge[], nodes: Node[], nodeId: string) {
};
}
+export const generateSwitchHandleText = (idx: number) => {
+ return `Case ${idx + 1}`;
+};
+
function filterTargetsBySourceHandleId(edges: Edge[], handleId: string) {
return edges.filter((x) => x.sourceHandle === handleId).map((x) => x.target);
}
@@ -736,6 +742,28 @@ export const buildDslComponentsByGraph = (
params = buildCategorize(edges, nodes, id);
break;
+ case Operator.Switch: {
+ const switchParams = params as ISwitchForm;
+ const branchEdges = edges.filter((edge) => edge.source === id);
+ params = {
+ ...switchParams,
+ conditions: (switchParams.conditions ?? []).map(
+ (condition, index) => ({
+ ...condition,
+ to: filterTargetsBySourceHandleId(
+ branchEdges,
+ generateSwitchHandleText(index),
+ ),
+ }),
+ ),
+ [SwitchElseTo]: filterTargetsBySourceHandleId(
+ branchEdges,
+ SwitchElseTo,
+ ),
+ };
+ break;
+ }
+
case Operator.Parser:
params = transformParserParams(params);
break;
@@ -910,10 +938,6 @@ export const getOperatorIndex = (handleTitle: string) => {
return handleTitle.split(' ').at(-1);
};
-export const generateSwitchHandleText = (idx: number) => {
- return `Case ${idx + 1}`;
-};
-
export const getNodeDragHandle = (nodeType?: string) => {
return nodeType === Operator.Note ? '.note-drag-handle' : undefined;
};