RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(web): block saving an agent when an edited Parser node is invalid (#18967)
chanxdf01facad6d0
diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 3f595ef2a9..2721e82089 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -567,6 +567,9 @@ Example: A 1 KB message with 1024-dim embedding uses ~9 KB. The 5 MB default limfromMessage: 'Missing start page number',toPlaceholder: 'to',toMessage: 'Missing end page number (excluded)',+ pageRangeFromInvalid: 'Start page must be an integer greater than 0',+ pageRangeToInvalid:+ 'End page must be an integer no less than the start page',layoutRecognize: 'PDF parser',layoutRecognizeTip:'Use a visual model for PDF layout analysis to effectively locate document titles, text blocks, images, and tables. If the naive option is chosen, only the plain text in the PDF will be retrieved. Please note that this option currently works ONLY for PDF documents.',@@ -3362,6 +3365,8 @@ This process aggregates variables from multiple branches into a single variable'Extracts raw text and structure from files for downstream processing.',tokenizer: 'Indexer',tokenizerRequired: 'Please add the Indexer node first',+ nodeFormInvalid:+ 'Cannot save: "{{name}}" has invalid settings. Please fix them first',tokenizerDescription:'Transforms text into the required data structure (e.g., vector embeddings for Embedding Search) depending on the chosen search method.',tokenChunker: 'Token Chunker',diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.tsindex 5bcae2d457..e1f08ca893 100644--- a/web/src/locales/zh.ts+++ b/web/src/locales/zh.ts@@ -511,6 +511,8 @@ export default {fromMessage: '缺少起始页码',toPlaceholder: '到',toMessage: '缺少结束页码(不包含)',+ pageRangeFromInvalid: '起始页码必须为大于 0 的整数',+ pageRangeToInvalid: '结束页码必须为不小于起始页码的整数',layoutRecognize: 'PDF解析器',layoutRecognizeTip:'使用视觉模型进行 PDF 布局分析,以更好地识别文档结构,找到标题、文本块、图像和表格的位置。 如果选择 Naive 选项,则只能获取 PDF 的纯文本。请注意该功能只适用于 PDF 文档,对其他文档不生效。欲了解更多信息,请参阅 https://ragflow.io/docs/dataset_configuration#document-parsing-configuration。',@@ -2924,6 +2926,7 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 RparserDescription: '从文件中提取原始文本和结构以供下游处理。',tokenizer: '分词器',tokenizerRequired: '请先添加 Tokenizer 节点',+ nodeFormInvalid: '无法保存:“{{name}}” 配置有误,请先修正',tokenizerDescription:'根据所选的搜索方法,将文本转换为所需的数据结构(例如,用于嵌入搜索的 Embedding)。',tokenChunker: '按 Token 分块',diff --git a/web/src/pages/agent/form/parser-form/index.tsx b/web/src/pages/agent/form/parser-form/index.tsxindex 9d2f15189f..0107aca88d 100644--- a/web/src/pages/agent/form/parser-form/index.tsx+++ b/web/src/pages/agent/form/parser-form/index.tsx@@ -7,6 +7,7 @@ import { BlockButton, Button } from '@/components/ui/button';import { Form } from '@/components/ui/form';import { Separator } from '@/components/ui/separator';import { cn } from '@/lib/utils';+import i18n from '@/locales/config';import { buildOptions } from '@/utils/form';import { zodResolver } from '@hookform/resolvers/zod';import { useHover } from 'ahooks';@@ -87,7 +88,27 @@ export const FormSchema = z.object({remove_toc: z.boolean().optional(),remove_header_footer: z.boolean().optional(),pages: z- .array(z.object({ from: z.coerce.number(), to: z.coerce.number() }))+ .array(+ z+ .object({+ // Keep these checks on the fields themselves: an object-level+ // `superRefine` is skipped whenever the base shape fails to+ // parse, so one missing sibling would silently swallow the+ // other field's error.+ from: z.coerce+ .number()+ .int(i18n.t('knowledgeDetails.pageRangeFromInvalid'))+ .min(1, i18n.t('knowledgeDetails.pageRangeFromInvalid')),+ to: z.coerce+ .number()+ .int(i18n.t('knowledgeDetails.pageRangeToInvalid'))+ .min(1, i18n.t('knowledgeDetails.pageRangeToInvalid')),+ })+ .refine(({ from, to }) => to >= from, {+ path: ['to'],+ message: i18n.t('knowledgeDetails.pageRangeToInvalid'),+ }),+ ).optional(),}),),@@ -201,6 +222,7 @@ const ParserForm = ({const form = useForm<z.infer<typeof FormSchema>>({defaultValues,resolver: zodResolver(FormSchema),+ mode: 'onChange',shouldUnregister: true,});diff --git a/web/src/pages/agent/hooks/use-save-graph.ts b/web/src/pages/agent/hooks/use-save-graph.tsindex d7f5332c46..7eb07643a1 100644--- a/web/src/pages/agent/hooks/use-save-graph.ts+++ b/web/src/pages/agent/hooks/use-save-graph.ts@@ -1,3 +1,4 @@+import message from '@/components/ui/message';import {useFetchAgent,useResetAgent,@@ -10,10 +11,58 @@ import {import { formatDate } from '@/utils/date';import { useDebounceEffect } from 'ahooks';import { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';+import { Operator } from '../constant';+import { FormSchema as ParserFormSchema } from '../form/parser-form';import useGraphStore from '../store';import { useBuildDslData } from './use-build-dsl';+/**+ * A node's form only validates while its panel is mounted, so bad values can+ * sit in the store long after the user has moved on. Re-check them against the+ * same schema before persisting, but only for nodes the user actually edited —+ * a node still carrying stale DSL from an older version must not wedge saving.+ */+function findInvalidNode(nodes: RAGFlowNodeType[], editedNodeIds: string[]) {+ return nodes.find(+ (node) =>+ editedNodeIds.includes(node.id) &&+ node.data?.label === Operator.Parser &&+ !ParserFormSchema.safeParse(node.data?.form).success,+ );+}++export const useValidateNodeForms = () => {+ const { t } = useTranslation();+ const nodes = useGraphStore((state) => state.nodes);+ const editedNodeFormIds = useGraphStore((state) => state.editedNodeFormIds);++ const getInvalidNode = useCallback(+ (currentNodes?: RAGFlowNodeType[]) =>+ findInvalidNode(currentNodes ?? nodes, editedNodeFormIds),+ [editedNodeFormIds, nodes],+ );++ // Only the entry points the user drives explicitly should warn; autosave and+ // publish stay silent and just skip the write.+ const notifyIfInvalid = useCallback(+ (currentNodes?: RAGFlowNodeType[]) => {+ const invalidNode = getInvalidNode(currentNodes);+ if (invalidNode) {+ message.warning(+ t('flow.nodeFormInvalid', { name: invalidNode.data?.name }),+ );+ return false;+ }+ return true;+ },+ [getInvalidNode, t],+ );++ return { getInvalidNode, notifyIfInvalid };+};+export const useSaveGraph = (showMessage: boolean = true,skipInvalidation: boolean = false,@@ -22,6 +71,7 @@ export const useSaveGraph = (const { setAgent, loading } = useSetAgent(showMessage, skipInvalidation);const { id } = useParams();const { buildDslData } = useBuildDslData();+ const { getInvalidNode } = useValidateNodeForms();const saveGraph = useCallback(async (@@ -35,6 +85,10 @@ export const useSaveGraph = (return;}+ if (getInvalidNode(currentNodes)) {+ return;+ }+const params: Record<string, any> = {id,title: data.title,@@ -47,7 +101,7 @@ export const useSaveGraph = (return setAgent(params);},- [setAgent, data, id, buildDslData],+ [id, getInvalidNode, data.title, buildDslData, setAgent],);return { saveGraph, loading };@@ -56,9 +110,14 @@ export const useSaveGraph = (export const useSaveGraphBeforeOpeningDebugDrawer = (show: () => void) => {const { saveGraph, loading } = useSaveGraph();const { resetAgent } = useResetAgent();+ const { notifyIfInvalid } = useValidateNodeForms();const handleRun = useCallback(async (nextNodes?: RAGFlowNodeType[]) => {+ if (!notifyIfInvalid(nextNodes)) {+ return;+ }+const saveRet = await saveGraph(nextNodes);if (saveRet?.code === 0) {// Call the reset api before opening the run drawer each time@@ -69,7 +128,7 @@ export const useSaveGraphBeforeOpeningDebugDrawer = (show: () => void) => {}}},- [saveGraph, resetAgent, show],+ [notifyIfInvalid, saveGraph, resetAgent, show],);return { handleRun, loading };diff --git a/web/src/pages/agent/hooks/use-watch-form-change.ts b/web/src/pages/agent/hooks/use-watch-form-change.tsindex acd65f42d4..dd4cc56788 100644--- a/web/src/pages/agent/hooks/use-watch-form-change.ts+++ b/web/src/pages/agent/hooks/use-watch-form-change.ts@@ -8,15 +8,21 @@ export function useWatchFormChange(enableReplacement = false,) {let values = useWatch({ control: form?.control });- const { updateNodeForm, replaceNodeForm } = useGraphStore((state) => state);+ const { updateNodeForm, replaceNodeForm, markNodeFormEdited } = useGraphStore(+ (state) => state,+ );useEffect(() => {// Manually triggered form updates are synchronized to the canvasif (id) {+ if (form?.formState.isDirty) {+ markNodeFormEdited(id);+ }+values = form?.getValues() || {};const nextValues: any = values;(enableReplacement ? replaceNodeForm : updateNodeForm)(id, nextValues);}- }, [form?.formState.isDirty, id, updateNodeForm, values]);+ }, [form?.formState.isDirty, id, markNodeFormEdited, updateNodeForm, values]);}diff --git a/web/src/pages/agent/index.tsx b/web/src/pages/agent/index.tsxindex 8d35fbe7f6..69d8e6de7c 100644--- a/web/src/pages/agent/index.tsx+++ b/web/src/pages/agent/index.tsx@@ -62,6 +62,7 @@ import { useRunDataflow } from './hooks/use-run-dataflow';import {useSaveGraph,useSaveGraphBeforeOpeningDebugDrawer,+ useValidateNodeForms,useWatchAgentChange,} from './hooks/use-save-graph';import { PipelineLogSheet } from './pipeline-log-sheet';@@ -105,6 +106,12 @@ export default function Agent() {const { handleExportJson } = useHandleExportJsonFile();const { saveGraph, loading } = useSaveGraph();+ const { notifyIfInvalid } = useValidateNodeForms();+ const handleSave = useCallback(() => {+ if (notifyIfInvalid()) {+ saveGraph();+ }+ }, [notifyIfInvalid, saveGraph]);const { flowDetail: agentDetail } = useFetchDataOnMount();const { buildDslData } = useBuildDslData();const { setAgent, loading: savingWidgetSettings } = useSetAgent(false);@@ -282,7 +289,7 @@ export default function Agent() {<div className="flex items-center gap-5"><ButtonLoadingvariant={'secondary'}- onClick={() => saveGraph()}+ onClick={handleSave}loading={loading}><LaptopMinimalCheck /> {t('flow.save')}diff --git a/web/src/pages/agent/store.ts b/web/src/pages/agent/store.tsindex 6a71706671..71ccdd74b0 100644--- a/web/src/pages/agent/store.ts+++ b/web/src/pages/agent/store.ts@@ -211,6 +211,11 @@ export type RFState = {toggleBottomCollapse: (nodeId: string, handleId: NodeHandleId) => void;hasDownstreamNode: (nodeId: string) => boolean;hasUpstreamNode: (nodeId: string) => boolean;+ // Nodes whose form the user has actually edited this session. The save gate+ // only validates these, so a node carrying stale DSL from an older version+ // never blocks a save the user did not cause.+ editedNodeFormIds: string[];+ markNodeFormEdited: (nodeId: string) => void;};// this is our useStore hook that we can use in our components to get parts of the store and call actions@@ -224,6 +229,15 @@ const useGraphStore = create<RFState>()(collapsedBottomHandles: {} as CollapsedBottomHandles,clickedNodeId: '',clickedToolId: '',+ editedNodeFormIds: [] as string[],+ markNodeFormEdited: (nodeId: string) => {+ if (get().editedNodeFormIds.includes(nodeId)) {+ return;+ }+ set((state) => {+ state.editedNodeFormIds.push(nodeId);+ });+ },onNodesChange: (changes) => {set({nodes: applyNodeChanges(changes, get().nodes),