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
Feat: Use a tree select component to display different versions of the pipeline. (#21628)
balibabu2c8ca0857c05
diff --git a/internal/handler/agent_version_test.go b/internal/handler/agent_version_test.goindex 0f7d058790..a1b4d5d40a 100644--- a/internal/handler/agent_version_test.go+++ b/internal/handler/agent_version_test.go@@ -130,7 +130,9 @@ func TestAgentVersionActions(t *testing.T) {wantDSL, wantRelease, wantCount := current.DSL, current.Release, initialCountif wantCode == common.CodeSuccess {if action.name == "apply" {- wantDSL, wantRelease, wantCount = version.DSL, false, initialCount+1+ // Restoring overwrites only the live draft; it never+ // creates a user_canvas_version row.+ wantDSL, wantRelease = version.DSL, false} else {wantCount--}diff --git a/internal/service/agent.go b/internal/service/agent.goindex 44ac8c4f9d..53268a2318 100644--- a/internal/service/agent.go+++ b/internal/service/agent.go@@ -1229,10 +1229,11 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,aliasPtr = &s}}- // ApplyVersion restore path: re-applying a version whose DSL already matches- // the latest draft must reuse that draft instead of minting a duplicate- // version row. We signal this with the "apply" flag so the version save can- // fall back to the SameDSL reuse branch instead of always inserting.+ // ApplyVersion restore path: restoring a version refreshes only the live+ // draft and must not write user_canvas_version at all. The restored DSL+ // already exists as a historical row, so a new row would be a pure+ // duplicate counting against the per-canvas version cap. The "apply" flag+ // signals this so the version save below is skipped entirely.applyVersion := falseif value, ok := patch["apply"]; ok && value != nil {applyVersion = true@@ -1293,12 +1294,10 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,opts := s.saveOrReplaceVersionOptions(ctx, userID, canvasID, dsl, title, nil, aliasPtr, release)// Manual Save (autosave != true) always mints a new version row, even// when the DSL is identical to the previous one (design §5.1). Auto-save- // never mints a version at all, so versionOpts stays nil and only the- // live draft is refreshed below. ApplyVersion restores a historical DSL- // and must reuse the latest draft when the DSL is unchanged, so it does- // NOT force a new row (the SameDSL branch governs instead).- opts.ForceNew = !autosave && !applyVersion- if !autosave {+ // never mints a version, and neither does an ApplyVersion restore; both+ // leave versionOpts nil so only the live draft is refreshed below.+ opts.ForceNew = true+ if !autosave && !applyVersion {versionOpts = &opts}}@@ -1585,8 +1584,11 @@ func (s *AgentService) UpdateVersion(ctx context.Context, userID, canvasID, vers})}-// ApplyVersion restores a saved version's DSL through the normal draft-save-// path, preserving the agent's metadata and version history.+// ApplyVersion restores a saved version's DSL as the live draft, preserving+// the agent's metadata and version history. It never writes+// user_canvas_version: the restored DSL already exists as a historical row,+// so a new one would be a pure duplicate counting against the per-canvas+// version cap.func (s *AgentService) ApplyVersion(ctx context.Context, userID, canvasID, versionID string) error {version, err := s.GetVersion(ctx, userID, canvasID, versionID)if err != nil {@@ -1598,8 +1600,8 @@ func (s *AgentService) ApplyVersion(ctx context.Context, userID, canvasID, versiif version.DSL == nil {return errors.New("agent version has no DSL to apply")}- // The "apply" flag tells UpdateAgent to reuse the latest draft version when- // the restored DSL already matches it, instead of minting a duplicate row.+ // The "apply" flag tells UpdateAgent to skip the version write and refresh+ // only the live draft.return s.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": version.DSL, "apply": true})}diff --git a/internal/service/agent_version_test.go b/internal/service/agent_version_test.goindex 5dc7d79b7f..835163afe8 100644--- a/internal/service/agent_version_test.go+++ b/internal/service/agent_version_test.go@@ -22,14 +22,12 @@ import ("reflect""testing"- "gorm.io/gorm"-"ragflow/internal/dao""ragflow/internal/entity")func TestApplyVersionDraftSave(t *testing.T) {- for _, scenario := range []string{"repeat", "version_save_failure", "canceled"} {+ for _, scenario := range []string{"repeat", "canceled"} {t.Run(scenario, func(t *testing.T) {setupAgentSessionServiceTest(t)current := entity.UserCanvas{@@ -58,16 +56,7 @@ func TestApplyVersionDraftSave(t *testing.T) {ctx := serviceTestContext(t, "user-1", "user-1")var wantErr error- if scenario == "version_save_failure" {- wantErr = errors.New("version write failed")- if err := dao.DB.Callback().Create().Before("gorm:create").Register("fail_version_save", func(tx *gorm.DB) {- if tx.Statement.Table == "user_canvas_version" {- tx.AddError(wantErr)- }- }); err != nil {- t.Fatal(err)- }- } else if scenario == "canceled" {+ if scenario == "canceled" {var cancel context.CancelFuncctx, cancel = context.WithCancel(ctx)cancel()@@ -78,23 +67,12 @@ func TestApplyVersionDraftSave(t *testing.T) {if !errors.Is(err, wantErr) {t.Fatalf("ApplyVersion error = %v, want %v", err, wantErr)}- wantDSL, wantRelease, wantCount := current.DSL, true, 2+ wantDSL, wantRelease := current.DSL, trueif wantErr == nil {- latest, err := dao.NewUserCanvasVersionDAO().GetLatest(ctx, dao.DB, current.ID)- if err != nil {- t.Fatal(err)- }if err := svc.ApplyVersion(ctx, "user-1", current.ID, version.ID); err != nil {t.Fatalf("repeated ApplyVersion failed: %v", err)}- after, err := dao.NewUserCanvasVersionDAO().GetLatest(ctx, dao.DB, current.ID)- if err != nil {- t.Fatal(err)- }- if after.ID != latest.ID || after.Release {- t.Fatal("repeated apply did not reuse the latest draft")- }- wantDSL, wantRelease, wantCount = version.DSL, false, 3+ wantDSL, wantRelease = version.DSL, false}persisted, err := dao.NewUserCanvasDAO().GetByID(t.Context(), dao.DB, current.ID)if err != nil {@@ -103,12 +81,15 @@ func TestApplyVersionDraftSave(t *testing.T) {if !reflect.DeepEqual(persisted.DSL, wantDSL) || persisted.Release != wantRelease {t.Fatalf("unexpected agent after apply: dsl=%v release=%v", persisted.DSL, persisted.Release)}+ // Restoring must never write user_canvas_version: the restored DSL+ // already exists as a historical row, so a new one would be a pure+ // duplicate counting against the per-canvas version cap.versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(t.Context(), dao.DB, current.ID)if err != nil {t.Fatal(err)}- if len(versions) != wantCount {- t.Fatalf("version count = %d, want %d", len(versions), wantCount)+ if len(versions) != 2 {+ t.Fatalf("version count = %d, want 2: apply must not create version rows", len(versions))}})}diff --git a/web/src/components/document-pipeline-dialog/index.tsx b/web/src/components/document-pipeline-dialog/index.tsxindex 81a9c756f2..85beac4ac7 100644--- a/web/src/components/document-pipeline-dialog/index.tsx+++ b/web/src/components/document-pipeline-dialog/index.tsx@@ -14,9 +14,8 @@* limitations under the License.*/-import { ParserSelect } from '@/components/parser-select';+import { ParserTreeSelect } from '@/components/parser-tree-select';import PipelineOperatorTabs from '@/components/pipeline-operator-tabs';-import { PipelineVersionSelect } from '@/components/pipeline-version-select';import { ButtonLoading } from '@/components/ui/button';import {Dialog,@@ -26,14 +25,12 @@ import {DialogTitle,} from '@/components/ui/dialog';import { Form, FormField, FormItem, FormMessage } from '@/components/ui/form';-import { RAGFlowTooltip } from '@/components/ui/tooltip';import { ParseType } from '@/constants/knowledge';import { IModalProps } from '@/interfaces/common';import { IChangeParserRequestBody } from '@/interfaces/request/document';import { useCallback } from 'react';import { FieldErrors, useFormState, useWatch } from 'react-hook-form';import { useTranslation } from 'react-i18next';-import { buildParserSelectValue } from '@/hooks/use-parser-options';import { useParserSelectHandler } from '@/hooks/use-parser-select-handler';import {IDocumentPipelineDialogProps,@@ -61,6 +58,7 @@ export function DocumentPipelineDialog({const {form,parseType,+ parserSelectValue,operatorNodes,operatorNodesLoading,activeTab,@@ -69,10 +67,8 @@ export function DocumentPipelineDialog({operatorValues,showOperatorTabs,buildSubmitData,- versions,latestVersionId,- versionListLoading,- versionListError,+ parserOptionMissing,} = useDocumentPipelineForm({parserId,pipelineId,@@ -82,47 +78,28 @@ export function DocumentPipelineDialog({const handleParserSelect = useParserSelectHandler(form);- const selectedParserId = useWatch({- control: form.control,- name: 'parser_id',- });- const selectedPipelineId = useWatch({- control: form.control,- name: 'pipeline_id',- });const selectedVersionId = useWatch({control: form.control,name: 'pipeline_version_id',});- // versions / latestVersionId / versionListLoading / versionListError come- // from the form hook, which fetches the canvas version list reactively.- // versions is newest-first, so versions[0] is the latest.- // A selected version is only Missing when the list has finished loading and- // the id is genuinely absent. While loading (initial mount of a pinned doc,- // or after switching pipelines) the list is empty, so treating absence as- // Missing would flash the banner and disable save before the fetch resolves.- // A fetch error must NOT be treated as Missing either: an errored list is an- // unknown state, not proof the version is gone, so we neither warn nor block- // the save on it.- const versionMissing =- !!selectedVersionId &&- !versionListLoading &&- !versionListError &&- !versions.some((v) => v.id === selectedVersionId);+ // Outdated = pinned to a non-latest version. A pinned version that was+ // deleted entirely is covered by the select's missing display plus the+ // parserOptionMissing guard below, so no separate Missing banner lives here.const versionOutdated =- !!selectedVersionId &&- !versionMissing &&- selectedVersionId !== latestVersionId;+ !!selectedVersionId && selectedVersionId !== latestVersionId;const onSubmit = useCallback(async (data: Parameters<typeof buildSubmitData>[0]) => {+ // A deleted pinned version/parser never reaches the backend; the+ // missing message beside the select is already visible.+ if (parserOptionMissing) return;const ret = await onOk?.(buildSubmitData(data));if (ret) {hideModal?.();}},- [buildSubmitData, hideModal, onOk],+ [buildSubmitData, hideModal, onOk, parserOptionMissing],);const onInvalid = useCallback(@@ -147,12 +124,6 @@ export function DocumentPipelineDialog({<DialogTitle>{t('knowledgeDetails.parsingMode')}</DialogTitle></DialogHeader>- {versionMissing && (- <div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">- {t('flow.version.missingContent')}- </div>- )}-<Form {...form}><formonSubmit={form.handleSubmit(onSubmit, onInvalid)}@@ -164,48 +135,25 @@ export function DocumentPipelineDialog({name={parseType === ParseType.BuiltIn ? 'parser_id' : 'pipeline_id'}- render={() => (+ render={({ fieldState }) => (<FormItem>- <ParserSelect- value={buildParserSelectValue({- parseType,- parserId: selectedParserId,- pipelineId: selectedPipelineId,- })}+ <ParserTreeSelect+ value={parserSelectValue}onChange={handleParserSelect}+ outdated={versionOutdated}+ invalid={fieldState.invalid || parserOptionMissing}/><FormMessage />+ {parserOptionMissing && (+ <p className="text-sm font-medium text-state-error">+ {t(+ 'knowledgeConfiguration.parserOptionUnavailableMessage',+ )}+ </p>+ )}</FormItem>)}/>- {parseType === ParseType.Pipeline && !!selectedPipelineId && (- <FormField- control={form.control}- name="pipeline_version_id"- render={({ field }) => (- <FormItem>- <div className="flex items-center gap-1.5">- <span className="text-sm text-text-secondary">- {t('flow.version.label')}- </span>- {versionOutdated && (- <RAGFlowTooltip tooltip={t('flow.version.outdated')}>- <span className="text-destructive cursor-help font-bold">- !- </span>- </RAGFlowTooltip>- )}- </div>- <PipelineVersionSelect- versions={versions}- value={field.value ?? ''}- onChange={field.onChange}- />- <FormMessage />- </FormItem>- )}- />- )}{showOperatorTabs && (<PipelineOperatorTabsnodes={operatorNodes}@@ -227,7 +175,6 @@ export function DocumentPipelineDialog({<ButtonLoadingtype="submit"form={FormId}- disabled={versionMissing}loading={loading || (operatorNodesLoading && operatorNodes.length === 0)}diff --git a/web/src/components/document-pipeline-dialog/use-document-pipeline-form.ts b/web/src/components/document-pipeline-dialog/use-document-pipeline-form.tsindex 8bc8b69fa4..22b5237b62 100644--- a/web/src/components/document-pipeline-dialog/use-document-pipeline-form.ts+++ b/web/src/components/document-pipeline-dialog/use-document-pipeline-form.ts@@ -29,12 +29,14 @@ import {} from '@/utils/pipeline-operator';import { zodResolver } from '@hookform/resolvers/zod';import { isEqual } from 'lodash';-import { useCallback, useEffect, useMemo } from 'react';+import { useCallback, useMemo } from 'react';import { useForm, useWatch } from 'react-hook-form';import { useTranslation } from 'react-i18next';import { z } from 'zod';+import { buildParserSelectValue } from '@/hooks/use-parser-options';+import { useParserTreeData } from '../parser-tree-select/use-parser-tree-data';+import { usePrefillLatestPipelineVersion } from '../parser-tree-select/use-prefill-latest-pipeline-version';import { addParserConfigIssues } from '../pipeline-operator-tabs/parser-config-validation';-export interface IDocumentPipelineDialogProps {parserId: string;pipelineId?: string;@@ -114,21 +116,39 @@ export function useDocumentPipelineForm({control: form.control,name: 'parser_id',});+ const selectedVersionId = useWatch({+ control: form.control,+ name: 'pipeline_version_id',+ });++ const parserSelectValue = buildParserSelectValue({+ parseType,+ parserId: selectedBuiltinId,+ pipelineId: selectedDataFlowId,+ pipelineVersionId: selectedVersionId,+ });++ // The merged parser tree owns the option data; reusing its existence+ // verdict (same React Query cache, no extra fetches) flags a saved parser+ // or pinned pipeline version that has since been deleted. The verdict+ // drives the dialog display and submit guard directly — it never enters+ // RHF's error lifecycle, so it can never go stale after the user picks a+ // valid option (programmatic setValue does not revalidate).+ const { selectedLeafExists, loading: parserOptionsLoading } =+ useParserTreeData({ value: parserSelectValue });+ const parserOptionMissing =+ !!parserSelectValue && !parserOptionsLoading && !selectedLeafExists;const isPipelineMode = parseType === ParseType.Pipeline;const selectedPipelineId = isPipelineMode? selectedDataFlowId: selectedBuiltinId;- // The canvas version list drives the selector, the D1/D2/D3 non-latest `!`- // indicator and the T29 Missing (unparseable) detection. We fetch it inside- // the hook so the latest id is a *reactive* value: it resolves after mount- // and the adoption effect below re-fires when it does. (Reading it from a- // static prop captured before the fetch would freeze it at undefined.)- const {- data: versions = [],- loading: versionListLoading,- isError: versionListError,- } = useFetchCanvasVersionList(+ // The canvas version list drives the latest-version prefill and the D1/D2/D3+ // non-latest indicator. We fetch it inside the hook so the latest id is a+ // *reactive* value: it resolves after mount and the adoption effect below+ // re-fires when it does. (Reading it from a static prop captured before the+ // fetch would freeze it at undefined.) versions is newest-first.+ const { data: versions = [] } = useFetchCanvasVersionList(isPipelineMode ? selectedDataFlowId : undefined,);const latestVersionId = versions[0]?.id;@@ -159,42 +179,16 @@ export function useDocumentPipelineForm({operatorNodes,);- // A pinned version belongs to the canvas it was pinned on (design section 5/B4- // sticky snapshot). Switching the dataflow canvas invalidates any previously- // pinned version, so clear it; otherwise a version id from the old canvas- // would be submitted against the new pipeline. The initial load keeps the- // saved version (selected equals saved).- useEffect(() => {- if (selectedPipelineId !== savedPipelineId) {- form.setValue('pipeline_version_id', '');- }- }, [selectedPipelineId, savedPipelineId, form]);-- // Design section 8 (T37): an unpinned document must never show the "Latest- // version" pseudo-value, so adopt the latest concrete version id once the- // version list resolves (it loads asynchronously, hence the effect rather- // than the form default). `latestVersionId` is reactive (derived from the- // fetch above), so this re-fires when the list arrives. We only adopt while- // the field is still empty, so a user's manual selection of an older version- // is preserved and a stable latest id will not re-fire this effect.- useEffect(() => {- if (- !pipelineVersionId &&- latestVersionId &&- !form.getValues('pipeline_version_id')- ) {- form.setValue('pipeline_version_id', latestVersionId);- }- }, [pipelineVersionId, latestVersionId, form]);+ // Design section 8 (T37): an unpinned document still pre-selects the latest+ // concrete version once the version list resolves. The "switch pipeline+ // clears the pinned version" sync (design 5/B4) needs no effect here: the+ // merged parser tree select writes pipeline_id and pipeline_version_id+ // atomically on every selection, so a stale version from another canvas+ // cannot survive a switch.+ usePrefillLatestPipelineVersion(form, pipelineVersionId, latestVersionId);const { activeTab, setActiveTab } = useActiveTab(operatorNodes);- useEffect(() => {- if (parseType === ParseType.BuiltIn) {- form.setValue('pipeline_id', '');- }- }, [parseType, form]);-const handleOperatorValuesChange = useCallback((operatorId: string, values: any) => {const currentParserConfig = form.getValues('parser_config') || {};@@ -249,6 +243,7 @@ export function useDocumentPipelineForm({return {form,parseType,+ parserSelectValue,operatorNodes,operatorNodesLoading,activeTab,@@ -257,9 +252,7 @@ export function useDocumentPipelineForm({operatorValues,showOperatorTabs,buildSubmitData,- versions,latestVersionId,- versionListLoading,- versionListError,+ parserOptionMissing,};}diff --git a/web/src/components/parser-select/index.test.tsx b/web/src/components/parser-select/index.test.tsxdeleted file mode 100644index 656a19e6fa..0000000000--- a/web/src/components/parser-select/index.test.tsx+++ /dev/null@@ -1,118 +0,0 @@-import { render } from '@testing-library/react';-import { ParserSelect } from '@/components/parser-select';--jest.mock('react-i18next', () => ({- useTranslation: () => ({ t: (k: string) => k }),-}));--const mockSelectProps: any = { onChange: jest.fn() };-jest.mock('@/components/originui/select-with-search', () => ({- SelectWithSearch: (props: any) => {- mockSelectProps.value = props.value;- mockSelectProps.options = props.options;- mockSelectProps.loading = props.loading;- mockSelectProps.placeholder = props.placeholder;- mockSelectProps.onChange = props.onChange;- return <select data-testid="mock-select" />;- },-}));--jest.mock('@/hooks/use-parser-options', () => {- const parserOptions = {- options: [- { value: 'pipeline:pipe-1', label: 'My Flow', kind: 'pipeline' },- {- value: 'builtin:general',- label: 'General',- kind: 'builtin',- },- ],- loading: false,- };- return {- __setLoading: (v: boolean) => {- parserOptions.loading = v;- },- ParserOptionKind: { BuiltIn: 'builtin', Pipeline: 'pipeline' },- useParserOptions: () => parserOptions,- buildParserOptionValue: (kind: string, id: string) => `${kind}:${id}`,- parseParserOptionValue: (v?: string) => {- if (- !v ||- (v.startsWith('builtin:') === false &&- v.startsWith('pipeline:') === false)- ) {- return null;- }- const idx = v.indexOf(':');- return { kind: v.slice(0, idx), rawId: v.slice(idx + 1) };- },- };-});--// The mocked SelectWithSearch stores its (internal) onChange handler in-// mockSelectProps.onChange. Firing it exercises ParserSelect's decode logic,-// which calls the real user onChange we pass to ParserSelect below.-beforeEach(() => {- mockSelectProps.onChange.mockClear?.();-});--describe('ParserSelect', () => {- it('passes the prefixed value through to the underlying select', () => {- render(<ParserSelect value="builtin:general" onChange={jest.fn()} />);- expect(mockSelectProps.value).toBe('builtin:general');- });-- it('passes the merged option list through', () => {- render(<ParserSelect value={undefined} onChange={jest.fn()} />);- expect(mockSelectProps.options).toHaveLength(2);- expect(mockSelectProps.options[0].value).toBe('pipeline:pipe-1');- });-- it('renders the builtin marker as a tag with searchable keywords', () => {- render(<ParserSelect value={undefined} onChange={jest.fn()} />);- const pipelineOption = mockSelectProps.options[0];- const builtinOption = mockSelectProps.options[1];-- // Pipeline options keep their plain string label.- expect(pipelineOption.label).toBe('My Flow');-- // Builtin options get a ReactNode label (label + tag) and explicit- // keywords so cmdk search still matches the plain label text.- expect(builtinOption.keywords).toEqual(['General']);- const { container } = render(<>{builtinOption.label}</>);- expect(container.textContent).toContain('General');- expect(container.textContent).toContain(- 'knowledgeConfiguration.builtInSuffix',- );- });-- it('decodes a builtin selection into kind + rawId', () => {- const onChange = jest.fn();- render(<ParserSelect value={undefined} onChange={onChange} />);- mockSelectProps.onChange('builtin:general');- expect(onChange).toHaveBeenCalledWith('builtin', 'general');- });-- it('decodes a pipeline selection into kind + rawId', () => {- const onChange = jest.fn();- render(<ParserSelect value={undefined} onChange={onChange} />);- mockSelectProps.onChange('pipeline:pipe-1');- expect(onChange).toHaveBeenCalledWith('pipeline', 'pipe-1');- });-- it('emits null for an unrecognized/empty selection', () => {- const onChange = jest.fn();- render(<ParserSelect value={undefined} onChange={onChange} />);- mockSelectProps.onChange('garbage');- expect(onChange).toHaveBeenCalledWith(null, '');- });-- it('forwards the loading flag from the options hook', () => {- const parserOptions = jest.requireMock('@/hooks/use-parser-options');- parserOptions.__setLoading(true);- render(<ParserSelect value={undefined} onChange={jest.fn()} />);- expect(mockSelectProps.loading).toBe(true);- parserOptions.__setLoading(false);- });-});diff --git a/web/src/components/parser-select/index.tsx b/web/src/components/parser-select/index.tsxdeleted file mode 100644index d023e7799c..0000000000--- a/web/src/components/parser-select/index.tsx+++ /dev/null@@ -1,114 +0,0 @@-/*- * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import {- SelectWithSearch,- type SelectWithSearchFlagOptionType,-} from '@/components/originui/select-with-search';-import {- parseParserOptionValue,- ParserOptionKind,- useParserOptions,-} from '@/hooks/use-parser-options';-import { useCallback, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--interface IProps {- // Prefixed value produced by buildParserOptionValue, e.g. "builtin:general".- value?: string;- // Called with the resolved kind and the raw backend id on selection.- onChange: (kind: ParserOptionKind | null, rawId: string) => void;- placeholder?: string;- disabled?: boolean;-}--// ParserSelect is the single dropdown that merges pipeline (canvas) and builtin-// parser options. It is a controlled component: the parent owns the form fields-// and translates the kind/id pair into parser_id / pipeline_id / parse_type.-export function ParserSelect({- value,- onChange,- placeholder,- disabled,-}: IProps) {- const { t } = useTranslation();- const { options, loading } = useParserOptions();-- // Trim: some locales still define the marker with surrounding whitespace- // from when it was appended to the label text.- const builtInTag = t('knowledgeConfiguration.builtInSuffix').trim();-- // Render the builtin marker as a tag next to the label instead of baking it- // into the label text; keywords keep the plain label searchable via cmdk.- const selectOptions = useMemo<SelectWithSearchFlagOptionType[]>(- () =>- options.map((option) => {- if (option.kind !== ParserOptionKind.BuiltIn) {- return option;- }- return {- ...option,- label: (- <>- {option.label}- <span className="shrink-0 rounded-md bg-bg-card px-1.5 py-0.5 text-xs text-text-secondary">- {builtInTag}- </span>- </>- ),- keywords: [option.label],- };- }),- [options, builtInTag],- );-- // When the saved value references a parser that no longer exists (e.g. a- // deleted pipeline) and options have finished loading, render a localized- // "unavailable" label instead of the raw internal value.- const renderMissingParser = useCallback(- () =>- t('knowledgeConfiguration.parserOptionUnavailable', {- defaultValue: 'unavailable',- }),- [t],- );-- const handleChange = useCallback(- (v: string) => {- const parsed = parseParserOptionValue(v);- if (!parsed) {- onChange(null, '');- return;- }- onChange(parsed.kind, parsed.rawId);- },- [onChange],- );-- return (- <SelectWithSearch- value={value}- loading={loading}- renderMissingValue={renderMissingParser}- onChange={handleChange}- placeholder={- placeholder ?? t('knowledgeConfiguration.parserSelectPlaceholder')- }- options={selectOptions}- disabled={disabled}- />- );-}diff --git a/web/src/components/parser-tree-select/index.test.tsx b/web/src/components/parser-tree-select/index.test.tsxnew file mode 100644index 0000000000..23e875ade5--- /dev/null+++ b/web/src/components/parser-tree-select/index.test.tsx@@ -0,0 +1,220 @@+import { act, render } from '@testing-library/react';+import { ParserTreeSelect } from './index';++const mockTreeProps: any = {};+jest.mock('@/components/tree-select', () => ({+ TreeSelect: (props: any) => {+ Object.assign(mockTreeProps, props);+ return null;+ },+}));++jest.mock('@/components/ui/tooltip', () => ({+ RAGFlowTooltip: ({ children }: any) => children,+}));++jest.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (k: string) => k }),+}));++const VersionList = [+ { id: 'v1', title: 'v1 title', created_at: '', alias: 'jin' },+];++// Index-aligned with the sorted canvas ids the hook requests: pipe-1 is the+// selected pipeline and always fetched; pipe-2 appears once its branch is+// expanded in a test.+let mockVersionQueries: any[] = [];+jest.mock('@/hooks/use-agent-request', () => ({+ useFetchBuiltinPipelines: () => ({+ options: [{ label: 'General', value: 'general' }],+ loading: false,+ }),+ useFetchAgentList: () => ({+ data: {+ canvas: [+ { id: 'pipe-1', title: 'My Flow', type: 'pipeline' },+ { id: 'pipe-2', title: 'Empty Flow', type: 'pipeline' },+ // AgentListItemType.CompilationTemplateGroup — referenced as a literal+ // because the jest.mock factory cannot capture an imported enum.+ { id: 'grp-1', title: 'Group', type: 'compilation_template_group' },+ ],+ total: 2,+ },+ loading: false,+ }),+ useFetchCanvasVersions: () => mockVersionQueries,+}));++beforeEach(() => {+ for (const key of Object.keys(mockTreeProps)) delete mockTreeProps[key];+ mockVersionQueries = [{ isSuccess: true, data: VersionList }];+});++describe('ParserTreeSelect', () => {+ it('builds pipeline branches with version leaves and builtin root leaves', () => {+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ const [branch, , builtin] = mockTreeProps.data;++ expect(branch.id).toBe('pipeline:pipe-1');+ expect(branch.title).toBe('My Flow');+ expect(branch.children).toHaveLength(1);+ expect(branch.children[0].id).toBe('pipeline:pipe-1:v1');++ expect(builtin.id).toBe('builtin:general');+ expect(builtin.children).toBeUndefined();+ });++ it('excludes compilation template groups from the pipeline branches', () => {+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ const ids = mockTreeProps.data.map((node: any) => node.id);+ expect(ids).toEqual([+ 'pipeline:pipe-1',+ 'pipeline:pipe-2',+ 'builtin:general',+ ]);+ });++ it('renders the alias as secondary text and keeps it searchable', () => {+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ const leaf = mockTreeProps.data[0].children[0];++ expect(leaf.title).toBe('v1 title jin');+ expect(leaf.searchKeywords).toEqual(['jin']);++ const { container } = render(<>{leaf.label}</>);+ expect(container.textContent).toContain('v1 title');+ expect(container.textContent).toContain('jin');+ });++ it('auto-expands the branch holding the selection', () => {+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ expect([...mockTreeProps.expandedIds]).toEqual(['pipeline:pipe-1']);+ });++ it('keeps an unrequested branch non-selectable via a loading placeholder', () => {+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ const emptyFlow = mockTreeProps.data[1];++ // pipe-2's versions were never requested, so it must not collapse into a+ // selectable leaf — a disabled placeholder child keeps it a branch.+ expect(emptyFlow.children).toHaveLength(1);+ expect(emptyFlow.children[0].id).toBe('pipeline:pipe-2:loading');+ expect(emptyFlow.children[0].disabled).toBe(true);+ });++ it('lazily fetches versions for a freshly expanded branch', () => {+ mockVersionQueries = [+ { isSuccess: true, data: VersionList },+ { isSuccess: false, data: undefined },+ ];+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ act(() => {+ mockTreeProps.onExpandedChange(+ new Set(['pipeline:pipe-1', 'pipeline:pipe-2']),+ );+ });++ const emptyFlow = mockTreeProps.data[1];+ expect(emptyFlow.children[0].id).toBe('pipeline:pipe-2:loading');+ expect([...mockTreeProps.loadingIds]).toContain('pipeline:pipe-2');+ });++ it('shows a disabled empty row for a branch with no published versions', () => {+ mockVersionQueries = [+ { isSuccess: true, data: VersionList },+ { isSuccess: true, data: [] },+ ];+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ act(() => {+ mockTreeProps.onExpandedChange(+ new Set(['pipeline:pipe-1', 'pipeline:pipe-2']),+ );+ });++ const emptyFlow = mockTreeProps.data[1];+ expect(emptyFlow.children[0].id).toBe('pipeline:pipe-2:empty');+ expect(emptyFlow.children[0].disabled).toBe(true);+ });++ it('decodes a version leaf into kind + pipeline id + version id', () => {+ const onChange = jest.fn();+ render(<ParserTreeSelect value={undefined} onChange={onChange} />);+ mockTreeProps.onChange('pipeline:pipe-1:v1');+ expect(onChange).toHaveBeenCalledWith('pipeline', 'pipe-1', 'v1');+ });++ it('decodes a builtin leaf into kind + raw id', () => {+ const onChange = jest.fn();+ render(<ParserTreeSelect value={undefined} onChange={onChange} />);+ mockTreeProps.onChange('builtin:general');+ expect(onChange).toHaveBeenCalledWith('builtin', 'general', undefined);+ });++ it('emits null for an unrecognized selection', () => {+ const onChange = jest.fn();+ render(<ParserTreeSelect value={undefined} onChange={onChange} />);+ mockTreeProps.onChange('garbage');+ expect(onChange).toHaveBeenCalledWith(null, '');+ });++ it('marks the select as loading while the selected versions arrive', () => {+ mockVersionQueries = [{ isSuccess: false, data: undefined }];+ render(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ expect(mockTreeProps.loading).toBe(true);+ });++ it('shows the outdated icon only when the selected leaf exists', () => {+ const { rerender } = render(+ <ParserTreeSelect+ value="pipeline:pipe-1:v1"+ onChange={jest.fn()}+ outdated+ />,+ );+ expect(mockTreeProps.trailingAddon).toBeTruthy();++ // A pinned version missing from the loaded list renders the missing+ // display instead — the outdated icon would be noise next to it.+ rerender(+ <ParserTreeSelect+ value="pipeline:pipe-1:pruned"+ onChange={jest.fn()}+ outdated+ />,+ );+ expect(mockTreeProps.trailingAddon).toBeUndefined();+ });++ it('flags the trigger border only while the owning field is invalid', () => {+ const { rerender } = render(+ <ParserTreeSelect+ value="pipeline:pipe-1:v1"+ onChange={jest.fn()}+ invalid+ />,+ );+ expect(mockTreeProps.className).toContain('border-destructive');++ rerender(+ <ParserTreeSelect value="pipeline:pipe-1:v1" onChange={jest.fn()} />,+ );+ expect(mockTreeProps.className ?? '').not.toContain('border-destructive');+ });+});diff --git a/web/src/components/parser-tree-select/index.tsx b/web/src/components/parser-tree-select/index.tsxnew file mode 100644index 0000000000..b28a011f4a--- /dev/null+++ b/web/src/components/parser-tree-select/index.tsx@@ -0,0 +1,137 @@+import { RAGFlowTooltip } from '@/components/ui/tooltip';+import {+ parseParserOptionValue,+ ParserOptionKind,+} from '@/hooks/use-parser-options';+import { cn } from '@/lib/utils';+import { AlertCircle, TriangleAlert } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import { TreeSelect, TreeSelectNode } from '../tree-select';+import { useParserTreeData } from './use-parser-tree-data';++export interface ParserTreeSelectProps {+ // Packed value produced by buildParserSelectValue, e.g. "builtin:general" or+ // "pipeline:<pipelineId>:<versionId>".+ value?: string;+ // Called with the resolved kind, the raw backend id and (for pipeline+ // version leaves) the version id on selection.+ onChange: (+ kind: ParserOptionKind | null,+ rawId: string,+ versionId?: string,+ ) => void;+ // Shows a non-interactive warning icon at the end of the trigger when the+ // pinned version is no longer the latest. The two callers define "outdated"+ // differently (dataset settings: only while the saved pin is still held;+ // document dialog: whenever the selection differs from latest), so the+ // component only renders what the caller computes.+ outdated?: boolean;+ // True when the owning form field failed validation (e.g. the saved parser+ // option no longer exists) — paints the trigger border like other invalid+ // form controls.+ invalid?: boolean;+ placeholder?: string;+ disabled?: boolean;+}++// ParserTreeSelect is the single dropdown that merges builtin parsers and+// dataflow pipelines with their published versions: builtin parsers are+// selectable root-level leaves, pipelines are non-selectable branches (the+// draft) whose version leaves are the only pipeline-side choices. It is a+// controlled component: the parent owns the form fields and translates the+// kind/id pair into parser_id / pipeline_id / pipeline_version_id /+// parse_type (see useParserSelectHandler).+export function ParserTreeSelect({+ value,+ onChange,+ outdated,+ invalid,+ placeholder,+ disabled,+}: ParserTreeSelectProps) {+ const { t } = useTranslation();+ const {+ treeData,+ expandedIds,+ onExpandedChange,+ onSearchChange,+ loadingIds,+ loading,+ selectedLeafExists,+ } = useParserTreeData({ value });++ const handleChange = useCallback(+ (id: string) => {+ const parsed = parseParserOptionValue(id);+ if (!parsed) {+ onChange(null, '');+ return;+ }+ onChange(parsed.kind, parsed.rawId, parsed.versionId);+ },+ [onChange],+ );++ // Reuse the leaf's rich label (title + secondary alias / builtin tag) for+ // the closed-select display. While the option list is still loading the+ // node is undefined — fall back to the placeholder instead of a blank.+ const renderSelected = useCallback(+ (node: TreeSelectNode | undefined) =>+ node+ ? (node.label ?? node.title)+ : (placeholder ?? t('common.pleaseSelect')),+ [placeholder, t],+ );++ // When the saved value references a parser or version that no longer exists+ // (e.g. a deleted pipeline or pruned version) and options have finished+ // loading, render a localized "unavailable" label instead of the raw+ // internal value.+ const renderMissingParser = useCallback(+ () => (+ <span className="flex items-center gap-1.5">+ <TriangleAlert className="size-4 flex-shrink-0" />+ <span className="truncate">+ {t('knowledgeConfiguration.parserOptionUnavailable', {+ defaultValue: 'unavailable',+ })}+ </span>+ </span>+ ),+ [t],+ );++ // The outdated icon is pure decoration (no click action); clicks pass+ // through to the trigger and open the dropdown as usual. It is hidden while+ // the value is already reported as missing — a deleted pin is the stronger+ // signal.+ const trailingAddon =+ outdated && (loading || selectedLeafExists) ? (+ <RAGFlowTooltip tooltip={t('flow.version.outdated')}>+ <AlertCircle className="size-4 text-destructive flex-shrink-0" />+ </RAGFlowTooltip>+ ) : undefined;++ return (+ <TreeSelect+ data={treeData}+ value={value}+ onChange={handleChange}+ placeholder={+ placeholder ?? t('knowledgeConfiguration.parserSelectPlaceholder')+ }+ disabled={disabled}+ className={cn(invalid && 'border-destructive')}+ showSearch+ expandedIds={expandedIds}+ onExpandedChange={onExpandedChange}+ onSearchChange={onSearchChange}+ loadingIds={loadingIds}+ loading={loading}+ renderSelected={renderSelected}+ renderMissingValue={renderMissingParser}+ trailingAddon={trailingAddon}+ />+ );+}diff --git a/web/src/components/parser-tree-select/use-parser-tree-data.tsx b/web/src/components/parser-tree-select/use-parser-tree-data.tsxnew file mode 100644index 0000000000..7582040c50--- /dev/null+++ b/web/src/components/parser-tree-select/use-parser-tree-data.tsx@@ -0,0 +1,237 @@+import { AgentCategory } from '@/constants/agent';+import {+ ICanvasVersionRow,+ useFetchAgentList,+ useFetchBuiltinPipelines,+ useFetchCanvasVersions,+} from '@/hooks/use-agent-request';+import {+ buildParserOptionValue,+ parseParserOptionValue,+ ParserOptionKind,+} from '@/hooks/use-parser-options';+import { AgentListItemType } from '@/interfaces/database/agent';+import { Loader2 } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import {+ filterTreeNodes,+ TreeSelectNode,+ withBranchIds,+} from '../tree-select-utils';++// Node id of a pipeline branch (the pipeline draft itself). Branches are never+// selectable in TreeSelect — only their version leaves are — so this id is+// never emitted as a value.+const buildPipelineNodeId = (pipelineId: string) =>+ buildParserOptionValue(ParserOptionKind.Pipeline, pipelineId);++// useParserTreeData assembles the merged parser tree: dataflow pipelines as+// branches with their published versions as leaves, builtin parsers as+// root-level leaves. Versions are fetched lazily — for the currently selected+// pipeline (needed for the closed-select display) and for every branch the+// user has expanded.+export function useParserTreeData({ value }: { value?: string }) {+ const { t } = useTranslation();+ const { options: builtinOptions, loading: builtinLoading } =+ useFetchBuiltinPipelines();+ const { data: pipelineData, loading: pipelineLoading } = useFetchAgentList({+ canvas_category: AgentCategory.DataflowCanvas,+ });++ const selectedPipelineId = useMemo(() => {+ const parsed = parseParserOptionValue(value);+ return parsed?.kind === ParserOptionKind.Pipeline+ ? parsed.rawId+ : undefined;+ }, [value]);++ // Expansion is controlled here (not inside TreeSelect) so that expansion+ // drives the lazy version fetch below.+ const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());++ // Render-phase adjustment (React's endorsed "adjust state when a prop+ // changes" pattern): the branch holding the selection starts expanded. The+ // previous-id comparison keeps a user's later manual collapse intact.+ const [prevSelectedPipelineId, setPrevSelectedPipelineId] = useState<+ string | undefined+ >(undefined);+ if (selectedPipelineId !== prevSelectedPipelineId) {+ setPrevSelectedPipelineId(selectedPipelineId);+ if (selectedPipelineId) {+ const nodeId = buildPipelineNodeId(selectedPipelineId);+ setExpandedIds((prev) => {+ if (prev.has(nodeId)) return prev;+ const next = new Set(prev);+ next.add(nodeId);+ return next;+ });+ }+ }++ // Versions load for the selected pipeline plus every expanded branch. The+ // set is derived, so collapsing a branch drops its observer and a re-expand+ // refetches (gcTime: 0) — always-fresh data over a cached shortcut.+ const versionCanvasIds = useMemo(() => {+ const ids = new Set<string>();+ if (selectedPipelineId) ids.add(selectedPipelineId);+ expandedIds.forEach((nodeId) => {+ const parsed = parseParserOptionValue(nodeId);+ if (parsed?.kind === ParserOptionKind.Pipeline) ids.add(parsed.rawId);+ });+ // Sorted so the useQueries array stays stable across expansion changes.+ return [...ids].sort();+ }, [selectedPipelineId, expandedIds]);+ const versionResults = useFetchCanvasVersions(versionCanvasIds);++ const { versionsByCanvas, loadingCanvasIds } = useMemo(() => {+ const versionsByCanvas = new Map<string, ICanvasVersionRow[]>();+ const loadingCanvasIds = new Set<string>();+ versionCanvasIds.forEach((canvasId, index) => {+ const query = versionResults[index];+ if (query?.isSuccess) {+ versionsByCanvas.set(canvasId, query.data ?? []);+ } else {+ loadingCanvasIds.add(canvasId);+ }+ });+ return { versionsByCanvas, loadingCanvasIds };+ }, [versionResults, versionCanvasIds]);++ // Trim: some locales still define the marker with surrounding whitespace+ // from when it was appended to the label text.+ const builtInTag = t('knowledgeConfiguration.builtInSuffix').trim();++ const treeData = useMemo<TreeSelectNode[]>(() => {+ const pipelines = (pipelineData?.canvas ?? [])+ .filter(+ (item) => item.type !== AgentListItemType.CompilationTemplateGroup,+ )+ .map((item): TreeSelectNode => {+ const nodeId = buildPipelineNodeId(item.id);+ const versions = versionsByCanvas.get(item.id);+ let children: TreeSelectNode[];+ if (!versions) {+ children = [+ {+ id: `${nodeId}:loading`,+ title: '',+ disabled: true,+ label: (+ <Loader2 className="size-3.5 animate-spin text-text-disabled" />+ ),+ },+ ];+ } else if (versions.length === 0) {+ // A pipeline draft without published versions stays visible but+ // offers nothing to select. The disabled placeholder row also keeps+ // the branch non-empty, so TreeSelect never treats the draft itself+ // as a selectable leaf.+ children = [+ {+ id: `${nodeId}:empty`,+ title: '',+ disabled: true,+ label: (+ <span className="text-text-disabled">+ {t('flow.version.noPublished')}+ </span>+ ),+ },+ ];+ } else {+ children = versions.map((version): TreeSelectNode => ({+ id: buildParserOptionValue(+ ParserOptionKind.Pipeline,+ item.id,+ version.id,+ ),+ // The alias joins the plain-text title so TreeSelect search+ // matches it; `label` renders it as secondary text instead.+ title: version.alias+ ? `${version.title} ${version.alias}`+ : version.title,+ searchKeywords: version.alias ? [version.alias] : undefined,+ label: (+ <span className="flex items-center gap-1.5 min-w-0">+ <span className="truncate">{version.title}</span>+ {version.alias && (+ <span className="text-text-secondary truncate flex-shrink-0">+ {version.alias}+ </span>+ )}+ </span>+ ),+ }));+ }+ return { id: nodeId, title: item.title, children };+ });++ const builtins = builtinOptions.map((option): TreeSelectNode => ({+ id: buildParserOptionValue(ParserOptionKind.BuiltIn, option.value),+ title: option.label,+ searchKeywords: [option.label],+ label: (+ <span className="flex items-center gap-1.5 min-w-0">+ <span className="truncate">{option.label}</span>+ <span className="shrink-0 rounded-md bg-bg-card px-1.5 py-0.5 text-xs text-text-secondary">+ {builtInTag}+ </span>+ </span>+ ),+ }));++ // Pipeline branches first, builtin leaves below — the same ordering the+ // flat parser select used.+ return [...pipelines, ...builtins];+ }, [pipelineData, builtinOptions, versionsByCanvas, t, builtInTag]);++ // TreeSelect's built-in search auto-expansion only runs for uncontrolled+ // expansion; with expansion owned here, matching branches are expanded from+ // the search event instead. filterTreeNodes mirrors TreeSelect's keep-rule+ // exactly, and every branch surviving the filter gets expanded, matching+ // the built-in behavior.+ const handleSearchChange = useCallback(+ (term: string) => {+ if (!term.trim()) return;+ const visible = filterTreeNodes(treeData, term);+ setExpandedIds((prev) => withBranchIds(prev, visible));+ },+ [treeData],+ );++ // An unmatched value is "missing" only once everything that could contain+ // it has loaded; while the selected pipeline's versions are still arriving+ // the select must not flash the missing display.+ const loading =+ builtinLoading ||+ pipelineLoading ||+ (!!selectedPipelineId && loadingCanvasIds.has(selectedPipelineId));++ const selectedLeafExists = useMemo(() => {+ if (!value) return false;+ const find = (nodes: TreeSelectNode[]): boolean =>+ nodes.some(+ (node) =>+ node.id === value || (node.children ? find(node.children) : false),+ );+ return find(treeData);+ }, [treeData, value]);++ // Node-id keyed (not canvas-id keyed) so TreeSelect can spin the chevron of+ // a branch whose versions are being fetched.+ const loadingIds = useMemo(+ () => new Set([...loadingCanvasIds].map(buildPipelineNodeId)),+ [loadingCanvasIds],+ );++ return {+ treeData,+ expandedIds,+ onExpandedChange: setExpandedIds,+ onSearchChange: handleSearchChange,+ loadingIds,+ loading,+ selectedLeafExists,+ };+}diff --git a/web/src/components/parser-tree-select/use-prefill-latest-pipeline-version.ts b/web/src/components/parser-tree-select/use-prefill-latest-pipeline-version.tsnew file mode 100644index 0000000000..d8733a3a82--- /dev/null+++ b/web/src/components/parser-tree-select/use-prefill-latest-pipeline-version.ts@@ -0,0 +1,35 @@+import { useEffect } from 'react';+import type { UseFormReturn, UseFormSetValue } from 'react-hook-form';++interface PipelineVersionField {+ pipeline_version_id?: string;+}++// Design section 8 (T37): an unpinned dataset/document must not keep an empty+// version — once the selected pipeline's version list resolves, prefill the+// field with the latest concrete version id so the merged parser tree select+// displays an actual version leaf. Only an empty field is filled, so a saved+// pin or a manual selection always wins. `latestVersionId` is reactive (it+// resolves after the async fetch), so this re-fires when the list arrives and+// stays silent while the id is stable.+export function usePrefillLatestPipelineVersion<T extends PipelineVersionField>(+ form: UseFormReturn<T>,+ savedPinnedVersionId: string | undefined,+ latestVersionId: string | undefined,+) {+ useEffect(() => {+ // Same narrowing trick as useParserSelectHandler: UseFormReturn is+ // invariant in its values type, and the constraint above guarantees the+ // field exists.+ const narrowed = form as unknown as UseFormReturn<PipelineVersionField>;+ if (+ !savedPinnedVersionId &&+ latestVersionId &&+ !narrowed.getValues('pipeline_version_id')+ ) {+ const setValue =+ form.setValue as unknown as UseFormSetValue<PipelineVersionField>;+ setValue('pipeline_version_id', latestVersionId);+ }+ }, [form, savedPinnedVersionId, latestVersionId]);+}diff --git a/web/src/components/pipeline-version-select/index.test.tsx b/web/src/components/pipeline-version-select/index.test.tsxdeleted file mode 100644index 9bcbad0291..0000000000--- a/web/src/components/pipeline-version-select/index.test.tsx+++ /dev/null@@ -1,73 +0,0 @@-import { render, screen } from '@testing-library/react';-import React from 'react';--jest.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}));--import { PipelineVersionSelect, filterVersionsByAlias } from './index';--describe('filterVersionsByAlias', () => {- const versions = [- { id: 'v1', title: 'First', alias: 'prod' },- { id: 'v2', title: 'Second', alias: null },- { id: 'v3', title: 'Third', alias: 'PROD-2' },- ];-- it('returns all versions when the filter is empty or whitespace', () => {- expect(filterVersionsByAlias(versions, '')).toHaveLength(3);- expect(filterVersionsByAlias(versions, ' ')).toHaveLength(3);- });-- it('filters case-insensitively by alias', () => {- expect(filterVersionsByAlias(versions, 'prod').map((v) => v.id)).toEqual([- 'v1',- 'v3',- ]);- });-- it('treats a null alias as non-matching', () => {- expect(filterVersionsByAlias(versions, 'second')).toHaveLength(0);- });-});--describe('PipelineVersionSelect (G1/v5.2: no latest pseudo-option)', () => {- it('renders the alias filter input', () => {- render(- React.createElement(PipelineVersionSelect, {- versions: [],- value: '',- onChange: jest.fn(),- }),- );- expect(- screen.getByPlaceholderText('flow.version.filterByAlias'),- ).toBeInTheDocument();- });-- it('shows the latest placeholder when unbound, with no __latest__ option', () => {- render(- React.createElement(PipelineVersionSelect, {- versions: [{ id: 'v1', title: 'First', alias: null }],- value: '',- onChange: jest.fn(),- }),- );- // The "latest" label is only a placeholder; there is no selectable- // __latest__ sentinel item (design G1 / v5.2).- expect(screen.getByText('flow.version.latest')).toBeInTheDocument();- expect(screen.queryByText('__latest__')).toBeNull();- });-- it('passes the concrete version id through unchanged', () => {- const onChange = jest.fn();- render(- React.createElement(PipelineVersionSelect, {- versions: [{ id: 'v1', title: 'First', alias: 'prod' }],- value: 'v1',- onChange,- }),- );- expect(screen.queryByText('__latest__')).toBeNull();- });-});diff --git a/web/src/components/pipeline-version-select/index.tsx b/web/src/components/pipeline-version-select/index.tsxdeleted file mode 100644index 9cea1dac7c..0000000000--- a/web/src/components/pipeline-version-select/index.tsx+++ /dev/null@@ -1,86 +0,0 @@-/*- * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import { Input } from '@/components/ui/input';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select';-import { useState } from 'react';-import { useTranslation } from 'react-i18next';--export type PipelineVersion = {- id: string;- title: string;- alias?: string | null;-};--// filterVersionsByAlias applies the free-text alias filter (design A2/F1).-// An empty or whitespace-only filter keeps every version; matching is-// case-insensitive; a null alias never matches.-export function filterVersionsByAlias<V extends PipelineVersion>(- versions: V[],- aliasFilter: string,-): V[] {- const needle = aliasFilter.trim().toLowerCase();- if (!needle) return versions;- return versions.filter((v) => (v.alias ?? '').toLowerCase().includes(needle));-}--// PipelineVersionSelect lets the user pin a specific dataflow canvas version-// (design section 5/C2) or leave it empty to track the latest version.-// Versions can be filtered by their free-text alias (design A2/F1). Shared by-// the document pipeline dialog and the dataset settings page.-export function PipelineVersionSelect({- versions,- value,- onChange,-}: {- versions: PipelineVersion[];- value: string;- onChange: (v: string) => void;-}) {- const { t } = useTranslation();- const [aliasFilter, setAliasFilter] = useState('');-- const filtered = filterVersionsByAlias(versions, aliasFilter);-- return (- <div className="space-y-2">- <Input- className="h-8"- placeholder={t('flow.version.filterByAlias')}- value={aliasFilter}- onChange={(e) => setAliasFilter(e.target.value)}- />- <Select value={value} onValueChange={(v) => onChange(v)}>- <SelectTrigger>- <SelectValue placeholder={t('flow.version.latest')} />- </SelectTrigger>- <SelectContent>- {filtered.map((v) => (- <SelectItem key={v.id} value={v.id}>- {v.alias ? v.alias + ' (' + v.title + ')' : v.title}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- );-}diff --git a/web/src/components/tree-select-utils.ts b/web/src/components/tree-select-utils.tsnew file mode 100644index 0000000000..8c38a596df--- /dev/null+++ b/web/src/components/tree-select-utils.ts@@ -0,0 +1,86 @@+import type { ReactNode } from 'react';++export interface TreeSelectNode {+ id: string;+ title: string;+ label?: ReactNode;+ children?: TreeSelectNode[];+ disabled?: boolean;+ /**+ * Extra strings the search box matches against, for text that only lives in+ * `label` (e.g. an alias rendered next to the title).+ */+ searchKeywords?: string[];+ data?: Record<string, any>;+}++// treeNodeMatchesTerm is the row-level search predicate.+export function treeNodeMatchesTerm(+ node: TreeSelectNode,+ loweredTerm: string,+): boolean {+ return (+ node.title.toLowerCase().includes(loweredTerm) ||+ !!node.searchKeywords?.some((keyword) =>+ keyword.toLowerCase().includes(loweredTerm),+ )+ );+}++// filterTreeNodes keeps matching rows. A matching parent keeps its entire+// subtree so its children stay visible; otherwise only branches containing+// matching descendants are kept.+export function filterTreeNodes(+ nodes: TreeSelectNode[],+ term: string,+): TreeSelectNode[] {+ if (!term) return nodes;+ const lowered = term.toLowerCase();+ return nodes.reduce<TreeSelectNode[]>((acc, node) => {+ if (treeNodeMatchesTerm(node, lowered)) {+ acc.push(node);+ return acc;+ }+ const filteredChildren = node.children+ ? filterTreeNodes(node.children, term)+ : undefined;+ if (filteredChildren?.length) {+ acc.push({ ...node, children: filteredChildren });+ }+ return acc;+ }, []);+}++// collectBranchIds returns the ids of every branch node in the tree.+export function collectBranchIds(nodes: TreeSelectNode[]): Set<string> {+ const ids = new Set<string>();+ const walk = (list: TreeSelectNode[]) => {+ for (const node of list) {+ if (node.children?.length) {+ ids.add(node.id);+ walk(node.children);+ }+ }+ };+ walk(nodes);+ return ids;+}++// withBranchIds returns a new set with every branch id from `nodes` added, or+// the previous set (same reference) when nothing changed, so React bails out+// of the state update instead of looping on a fresh-but-identical Set.+export function withBranchIds(+ prev: Set<string>,+ nodes: TreeSelectNode[],+): Set<string> {+ const branchIds = collectBranchIds(nodes);+ let added = false;+ const next = new Set(prev);+ branchIds.forEach((id) => {+ if (!next.has(id)) {+ next.add(id);+ added = true;+ }+ });+ return added ? next : prev;+}diff --git a/web/src/components/tree-select.tsx b/web/src/components/tree-select.tsxindex 558067cf2f..72c769de13 100644--- a/web/src/components/tree-select.tsx+++ b/web/src/components/tree-select.tsx@@ -7,20 +7,206 @@ import { cn } from '@/lib/utils';import {ChevronDown,ChevronRight,+ Loader2,Search,TriangleAlert,X,} from 'lucide-react';-import { forwardRef, useCallback, useEffect, useMemo, useState } from 'react';+import { forwardRef, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import {+ collectBranchIds,+ filterTreeNodes,+ withBranchIds,+ type TreeSelectNode,+} from './tree-select-utils';-export interface TreeSelectNode {- id: string;- title: string;- label?: React.ReactNode;- children?: TreeSelectNode[];- disabled?: boolean;- data?: Record<string, any>;+export type { TreeSelectNode } from './tree-select-utils';++interface TreeSelectValueDisplayProps {+ selectedNode?: TreeSelectNode;+ missingValue?: string;+ renderSelected?: (node: TreeSelectNode | undefined) => React.ReactNode;+ renderMissingValue?: (value: string) => React.ReactNode;+ placeholder?: string;+}++function TreeSelectValueDisplay({+ selectedNode,+ missingValue,+ renderSelected,+ renderMissingValue,+ placeholder,+}: TreeSelectValueDisplayProps) {+ const { t } = useTranslation();++ let content: React.ReactNode;+ if (missingValue) {+ content = renderMissingValue ? (+ renderMissingValue(missingValue)+ ) : (+ <span className="flex items-center gap-1.5">+ <TriangleAlert className="size-4 flex-shrink-0" />+ <span className="truncate">{missingValue}</span>+ </span>+ );+ } else if (renderSelected) {+ content = renderSelected(selectedNode);+ } else {+ content = selectedNode?.title || placeholder || t('common.pleaseSelect');+ }++ return (+ <span className={cn('truncate', !selectedNode && 'text-text-secondary')}>+ {content}+ </span>+ );+}++interface TreeSelectRowsProps {+ nodes: TreeSelectNode[];+ level: number;+ expandedIds: Set<string>;+ loadingIds?: Set<string>;+ value?: string;+ onSelectNode: (node: TreeSelectNode) => void;+}++function TreeSelectRow({+ node,+ level,+ expandedIds,+ loadingIds,+ value,+ onSelectNode,+}: TreeSelectRowsProps & { node: TreeSelectNode }) {+ const leaf = !node.children?.length;+ const expanded = expandedIds.has(node.id);+ const selected = value === node.id;++ const handleClick = useCallback(() => {+ onSelectNode(node);+ }, [node, onSelectNode]);++ return (+ <div>+ <div+ className={cn(+ 'flex items-center rounded-sm cursor-pointer text-sm',+ 'hover:bg-accent transition-colors',+ !leaf && 'text-text-primary font-medium',+ selected && 'bg-accent text-accent-foreground',+ node.disabled && 'opacity-50 pointer-events-none',+ )}+ style={{+ paddingLeft: `${level * 20 + 4}px`,+ paddingRight: '8px',+ paddingTop: '6px',+ paddingBottom: '6px',+ }}+ onClick={handleClick}+ >+ <span className="w-4 h-4 mr-0.5 flex-shrink-0 flex items-center justify-center">+ {!leaf && (+ <>+ {loadingIds?.has(node.id) ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin text-text-secondary" />+ ) : expanded ? (+ <ChevronDown className="h-3.5 w-3.5 text-text-secondary" />+ ) : (+ <ChevronRight className="h-3.5 w-3.5 text-text-secondary" />+ )}+ </>+ )}+ </span>+ <span className="truncate">{node.label ?? node.title}</span>+ </div>+ {!leaf && expanded && node.children && (+ <div>+ <TreeSelectNodeList+ nodes={node.children}+ level={level + 1}+ expandedIds={expandedIds}+ loadingIds={loadingIds}+ value={value}+ onSelectNode={onSelectNode}+ />+ </div>+ )}+ </div>+ );+}++function TreeSelectNodeList(props: TreeSelectRowsProps) {+ return (+ <>+ {props.nodes.map((node) => (+ <TreeSelectRow key={node.id} {...props} node={node} />+ ))}+ </>+ );+}++interface TreeSelectDropdownProps {+ showSearch?: boolean;+ searchTerm: string;+ onSearchTermChange: (e: React.ChangeEvent<HTMLInputElement>) => void;+ filteredData: TreeSelectNode[];+ expandedIds: Set<string>;+ loadingIds?: Set<string>;+ value?: string;+ onSelectNode: (node: TreeSelectNode) => void;+}++function TreeSelectDropdown({+ showSearch,+ searchTerm,+ onSearchTermChange,+ filteredData,+ expandedIds,+ loadingIds,+ value,+ onSelectNode,+}: TreeSelectDropdownProps) {+ const { t } = useTranslation();++ // Keep the popover from scrolling the page behind it.+ const handleWheel = useCallback((e: React.WheelEvent) => {+ e.stopPropagation();+ }, []);++ return (+ <>+ {showSearch && (+ <div className="flex items-center border-b px-3 py-2">+ <Search className="h-4 w-4 mr-2 flex-shrink-0 text-text-disabled" />+ <input+ type="text"+ className="flex-1 bg-transparent text-sm outline-none placeholder:text-text-disabled"+ placeholder={t('common.search')}+ value={searchTerm}+ onChange={onSearchTermChange}+ />+ </div>+ )}+ <div className="max-h-60 overflow-auto p-1" onWheel={handleWheel}>+ {filteredData.length > 0 ? (+ <TreeSelectNodeList+ nodes={filteredData}+ level={0}+ expandedIds={expandedIds}+ loadingIds={loadingIds}+ value={value}+ onSelectNode={onSelectNode}+ />+ ) : (+ <div className="py-6 text-center text-sm text-slate-400">+ {t('common.noData')}+ </div>+ )}+ </div>+ </>+ );}interface TreeSelectProps {@@ -45,6 +231,31 @@ interface TreeSelectProps {* missing, so the missing-value display doesn't flash before `data` arrives.*/loading?: boolean;+ /**+ * Controlled expansion. When `expandedIds` is provided the component defers+ * to the caller and reports user toggles through `onExpandedChange`, which+ * lets the caller lazy-load children for freshly expanded branches. In+ * controlled mode `defaultExpandAll` and the built-in search auto-expansion+ * are disabled — the caller owns expansion and can combine `onSearchChange`+ * with filterTreeNodes to implement its own.+ */+ expandedIds?: Set<string>;+ onExpandedChange?: (ids: Set<string>) => void;+ /**+ * Reports search-box edits (event context), so a controlled-expansion+ * caller can auto-expand matching branches itself.+ */+ onSearchChange?: (term: string) => void;+ /**+ * Branch nodes currently loading their children; their expand chevron is+ * replaced by a spinner.+ */+ loadingIds?: Set<string>;+ /**+ * Extra content rendered in the trigger's trailing icon cluster, before the+ * clear/chevron icons (e.g. a status badge).+ */+ trailingAddon?: React.ReactNode;testId?: string;}@@ -63,29 +274,38 @@ export const TreeSelect = forwardRef<HTMLButtonElement, TreeSelectProps>(renderSelected,renderMissingValue,loading,+ expandedIds: controlledExpandedIds,+ onExpandedChange,+ onSearchChange,+ loadingIds,+ trailingAddon,testId,},ref,) {const [open, setOpen] = useState(false);const [searchTerm, setSearchTerm] = useState('');- const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());- const { t } = useTranslation();+ const [internalExpandedIds, setInternalExpandedIds] = useState<Set<string>>(+ new Set(),+ );- useEffect(() => {- if (!defaultExpandAll) return;- const ids = new Set<string>();- const walk = (nodes: TreeSelectNode[]) => {- for (const node of nodes) {- if (node.children?.length) {- ids.add(node.id);- walk(node.children);- }- }- };- walk(data);- setExpandedIds(ids);- }, [data, defaultExpandAll]);+ const isExpansionControlled = controlledExpandedIds !== undefined;+ const expandedIds = isExpansionControlled+ ? controlledExpandedIds+ : internalExpandedIds;++ // Uncontrolled-only: in controlled mode the caller owns the expansion set.+ // Render-phase adjustment (React's endorsed "adjust state when a prop+ // changes" pattern) rather than an effect, so the expansion is settled+ // before paint. The previous-value guards keep each adjustment firing+ // only on a real change.+ const [prevExpandData, setPrevExpandData] = useState(data);+ if (data !== prevExpandData) {+ setPrevExpandData(data);+ if (defaultExpandAll && !isExpansionControlled) {+ setInternalExpandedIds(collectBranchIds(data));+ }+ }const selectedNode = useMemo(() => {const find = (nodes: TreeSelectNode[]): TreeSelectNode | undefined => {@@ -104,35 +324,35 @@ export const TreeSelect = forwardRef<HTMLButtonElement, TreeSelectProps>(// deleted) — unless `data` may simply not have loaded yet.const missingValue = value && !selectedNode && !loading ? value : undefined;- const isLeaf = useCallback(- (node: TreeSelectNode) => !node.children?.length,- [],- );-- const handleToggle = useCallback((id: string) => {- setExpandedIds((prev) => {- const next = new Set(prev);+ const handleToggle = useCallback(+ (id: string) => {+ const next = new Set(expandedIds);if (next.has(id)) {next.delete(id);} else {next.add(id);}- return next;- });- }, []);+ if (isExpansionControlled) {+ onExpandedChange?.(next);+ } else {+ setInternalExpandedIds(next);+ }+ },+ [expandedIds, isExpansionControlled, onExpandedChange],+ );const handleSelect = useCallback((node: TreeSelectNode) => {if (node.disabled) return;- if (isLeaf(node)) {+ if (node.children?.length) {+ handleToggle(node.id);+ } else {onChange?.(node.id);setOpen(false);setSearchTerm('');- } else {- handleToggle(node.id);}},- [isLeaf, onChange, handleToggle],+ [onChange, handleToggle],);const handleClear = useCallback(@@ -143,104 +363,31 @@ export const TreeSelect = forwardRef<HTMLButtonElement, TreeSelectProps>([onChange],);- const filterTree = useCallback(- (nodes: TreeSelectNode[], term: string): TreeSelectNode[] => {- if (!term) return nodes;- return nodes.reduce<TreeSelectNode[]>((acc, node) => {- const titleMatch = node.title- .toLowerCase()- .includes(term.toLowerCase());- // A matching parent keeps its entire subtree so its children stay- // visible; otherwise only branches containing matching descendants- // are kept.- if (titleMatch) {- acc.push(node);- return acc;- }- const filteredChildren = node.children- ? filterTree(node.children, term)- : undefined;- if (filteredChildren?.length) {- acc.push({ ...node, children: filteredChildren });- }- return acc;- }, []);- },- [],- );-const filteredData = useMemo(- () => filterTree(data, searchTerm),- [data, searchTerm, filterTree],+ () => filterTreeNodes(data, searchTerm),+ [data, searchTerm],);// Auto-expand all matching parents when the search term changes so users- // can see search results. The effect only depends on searchTerm and- // filteredData, so a manual collapse (which updates expandedIds) won't- // trigger re-expansion — the user's collapse choice is respected.- useEffect(() => {- if (!searchTerm) return;- setExpandedIds((prev) => {- const next = new Set(prev);- const walk = (nodes: TreeSelectNode[]) => {- for (const node of nodes) {- if (node.children?.length) {- next.add(node.id);- walk(node.children);- }- }- };- walk(filteredData);- return next;- });- }, [searchTerm, filteredData]);-- const renderTree = useCallback(- (nodes: TreeSelectNode[], level = 0): React.ReactNode => {- return nodes.map((node) => {- const leaf = isLeaf(node);- const expanded = expandedIds.has(node.id);- const selected = value === node.id;+ // can see search results (render-phase adjustment, same pattern as the+ // defaultExpandAll block above; withBranchIds returns the previous set+ // unchanged when nothing new was added, so React bails out of no-op+ // updates). Uncontrolled-only: controlled callers get `onSearchChange`+ // and own auto-expansion themselves.+ const [prevFilteredData, setPrevFilteredData] = useState(filteredData);+ if (filteredData !== prevFilteredData) {+ setPrevFilteredData(filteredData);+ if (searchTerm && !isExpansionControlled) {+ setInternalExpandedIds((prev) => withBranchIds(prev, filteredData));+ }+ }- return (- <div key={node.id}>- <div- className={cn(- 'flex items-center rounded-sm cursor-pointer text-sm',- 'hover:bg-accent transition-colors',- !leaf && 'text-text-primary font-medium',- selected && 'bg-accent text-accent-foreground',- node.disabled && 'opacity-50 pointer-events-none',- )}- style={{- paddingLeft: `${level * 20 + 4}px`,- paddingRight: '8px',- paddingTop: '6px',- paddingBottom: '6px',- }}- onClick={() => handleSelect(node)}- >- <span className="w-4 h-4 mr-0.5 flex-shrink-0 flex items-center justify-center">- {!leaf && (- <>- {expanded ? (- <ChevronDown className="h-3.5 w-3.5 text-text-secondary" />- ) : (- <ChevronRight className="h-3.5 w-3.5 text-text-secondary" />- )}- </>- )}- </span>- <span className="truncate">{node.label ?? node.title}</span>- </div>- {!leaf && expanded && node.children && (- <div>{renderTree(node.children, level + 1)}</div>- )}- </div>- );- });+ const handleSearchTermChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ setSearchTerm(e.target.value);+ onSearchChange?.(e.target.value);},- [isLeaf, expandedIds, value, handleSelect],+ [onSearchChange],);return (@@ -258,25 +405,15 @@ export const TreeSelect = forwardRef<HTMLButtonElement, TreeSelectProps>(className,)}>- <span- className={cn('truncate', !selectedNode && 'text-text-secondary')}- >- {missingValue ? (- renderMissingValue ? (- renderMissingValue(missingValue)- ) : (- <span className="flex items-center gap-1.5">- <TriangleAlert className="size-4 flex-shrink-0" />- <span className="truncate">{missingValue}</span>- </span>- )- ) : renderSelected ? (- renderSelected(selectedNode)- ) : (- selectedNode?.title || placeholder || t('common.pleaseSelect')- )}- </span>- <div className="flex items-center ml-2 flex-shrink-0">+ <TreeSelectValueDisplay+ selectedNode={selectedNode}+ missingValue={missingValue}+ renderSelected={renderSelected}+ renderMissingValue={renderMissingValue}+ placeholder={placeholder}+ />+ <div className="flex items-center ml-2 flex-shrink-0 gap-1">+ {trailingAddon}{allowClear && value ? (<XclassName="h-4 w-4 opacity-50 hover:opacity-100"@@ -293,30 +430,16 @@ export const TreeSelect = forwardRef<HTMLButtonElement, TreeSelectProps>(align="start"sideOffset={4}>- {showSearch && (- <div className="flex items-center border-b px-3 py-2">- <Search className="h-4 w-4 mr-2 flex-shrink-0 text-text-disabled" />- <input- type="text"- className="flex-1 bg-transparent text-sm outline-none placeholder:text-text-disabled"- placeholder={t('common.search')}- value={searchTerm}- onChange={(e) => setSearchTerm(e.target.value)}- />- </div>- )}- <div- className="max-h-60 overflow-auto p-1"- onWheel={(e) => e.stopPropagation()}- >- {filteredData.length > 0 ? (- renderTree(filteredData)- ) : (- <div className="py-6 text-center text-sm text-slate-400">- {t('common.noData')}- </div>- )}- </div>+ <TreeSelectDropdown+ showSearch={showSearch}+ searchTerm={searchTerm}+ onSearchTermChange={handleSearchTermChange}+ filteredData={filteredData}+ expandedIds={expandedIds}+ loadingIds={loadingIds}+ value={value}+ onSelectNode={handleSelect}+ /></PopoverContent></Popover>);diff --git a/web/src/hooks/use-agent-request.ts b/web/src/hooks/use-agent-request.tsindex 9a20be698f..560ef2e76d 100644--- a/web/src/hooks/use-agent-request.ts+++ b/web/src/hooks/use-agent-request.ts@@ -59,7 +59,12 @@ import agentService, {} from '@/services/agent-service';import { buildMessageListWithUuid } from '@/utils/chat';import { markListItemsDeleted } from '@/utils/list-deletion-util';-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import {+ useMutation,+ useQueries,+ useQuery,+ useQueryClient,+} from '@tanstack/react-query';import { useDebounce } from 'ahooks';import { get, isEmpty, set } from 'lodash';import { useCallback, useState } from 'react';@@ -800,30 +805,43 @@ export const useFetchVersionList = () => {return { data, loading };};+// Row shape of a published canvas version, newest-first (design section 7/E1),+// including the free-text alias (A2/F1).+export interface ICanvasVersionRow {+ id: string;+ title: string;+ created_at: string;+ release?: boolean;+ alias?: string;+}++// Shared query key/options for a canvas's published version list. The raw+// 'canvasVersionList' key predates the AgentKeys factory; both the single- and+// multi-canvas hooks must keep using it verbatim so the version delete/alias+// mutations below invalidate every observer.+const canvasVersionListQuery = (canvasId: string) => ({+ queryKey: ['canvasVersionList', canvasId] as const,+ queryFn: async (): Promise<ICanvasVersionRow[]> => {+ const { data } = await agentService.fetchVersionList(canvasId);+ return data?.data ?? [];+ },+});+// useFetchCanvasVersionList lists the published versions of an arbitrary canvas// (dataflow or agent) by id. Unlike useFetchVersionList it takes the canvas id// explicitly (not from route params) so the document pipeline dialog can load-// versions for the currently selected dataflow canvas. The backend returns them-// newest-first (design section 7/E1) and includes the free-text alias (A2/F1).+// versions for the currently selected dataflow canvas.export const useFetchCanvasVersionList = (canvasId?: string) => {const {data,isFetching: loading,isError,- } = useQuery<- Array<{- id: string;- title: string;- created_at: string;- release?: boolean;- alias?: string;- }>- >({+ } = useQuery({queryKey: ['canvasVersionList', canvasId],initialData: [],gcTime: 0,enabled: !!canvasId,- queryFn: async () => {+ queryFn: async (): Promise<ICanvasVersionRow[]> => {if (!canvasId) return [];const { data } = await agentService.fetchVersionList(canvasId);return data?.data ?? [];@@ -833,6 +851,20 @@ export const useFetchCanvasVersionList = (canvasId?: string) => {return { data, loading, isError };};+// useFetchCanvasVersions lazily loads the published versions of several+// canvases at once (the parser tree select fetches a canvas's versions only+// when the user expands it). Unlike useFetchCanvasVersionList it sets no+// initialData, so `isSuccess` distinguishes "loaded and empty" from "still+// loading". The returned array aligns index-by-index with `canvasIds`.+export const useFetchCanvasVersions = (canvasIds: string[]) => {+ return useQueries({+ queries: canvasIds.map((canvasId) => ({+ ...canvasVersionListQuery(canvasId),+ gcTime: 0,+ })),+ });+};+// useDeleteVersion removes a single canvas version (design section 7/B2). The// backend still allows deletion when the version is referenced by a dataset or// file; the binding then enters a Missing (unparseable) state, so the UI shows adiff --git a/web/src/hooks/use-parser-options.test.ts b/web/src/hooks/use-parser-options.test.tsindex c5e000dcbb..10a61777b9 100644--- a/web/src/hooks/use-parser-options.test.ts+++ b/web/src/hooks/use-parser-options.test.ts@@ -1,34 +1,12 @@-import { renderHook } from '@testing-library/react';import { ParseType } from '@/constants/knowledge';-import { AgentListItemType } from '@/interfaces/database/agent';import {buildParserOptionValue,buildParserSelectValue,parseParserOptionValue,ParserOptionKind,resolveBuiltinParserId,- useParserOptions,} from '@/hooks/use-parser-options';-jest.mock('@/hooks/use-agent-request', () => ({- useFetchBuiltinPipelines: jest.fn(),- useFetchAgentList: jest.fn(),-}));--// eslint-disable-next-line @typescript-eslint/no-var-requires-const agentRequest = require('@/hooks/use-agent-request');--beforeEach(() => {- agentRequest.useFetchBuiltinPipelines.mockReturnValue({- options: [],- loading: false,- });- agentRequest.useFetchAgentList.mockReturnValue({- data: { canvas: [] },- loading: false,- });-});-describe('parser option value encoding', () => {it('prefixes builtin and pipeline ids distinctly', () => {expect(buildParserOptionValue(ParserOptionKind.BuiltIn, 'general')).toBe(@@ -39,6 +17,12 @@ describe('parser option value encoding', () => {);});+ it('packs the version id into pipeline leaf values', () => {+ expect(+ buildParserOptionValue(ParserOptionKind.Pipeline, 'abc123', 'v9'),+ ).toBe('pipeline:abc123:v9');+ });+it('round-trips builtin and pipeline values', () => {expect(parseParserOptionValue('builtin:general')).toEqual({kind: ParserOptionKind.BuiltIn,@@ -48,6 +32,11 @@ describe('parser option value encoding', () => {kind: ParserOptionKind.Pipeline,rawId: 'abc123',});+ expect(parseParserOptionValue('pipeline:abc123:v9')).toEqual({+ kind: ParserOptionKind.Pipeline,+ rawId: 'abc123',+ versionId: 'v9',+ });});it('keeps builtin and pipeline ids with the same bare value distinct', () => {@@ -67,12 +56,14 @@ describe('parser option value encoding', () => {);});- it('handles ids that themselves contain a colon', () => {- const value = buildParserOptionValue(ParserOptionKind.Pipeline, 'a:b:c');- expect(value).toBe('pipeline:a:b:c');- expect(parseParserOptionValue(value)).toEqual({+ it('splits pipeline leaf values on the first colon after the prefix', () => {+ // Pipeline and version ids are colon-free hex strings, so the first ':'+ // after the prefix separates them; anything further stays in the version+ // part. "pipeline:a:b:c" therefore decodes as pipeline "a", version "b:c".+ expect(parseParserOptionValue('pipeline:a:b:c')).toEqual({kind: ParserOptionKind.Pipeline,- rawId: 'a:b:c',+ rawId: 'a',+ versionId: 'b:c',});});@@ -106,12 +97,13 @@ describe('buildParserSelectValue', () => {).toBe('builtin:general');});- it('builds the value from the id of the active parse type', () => {+ it('builds the value from the ids of the active parse type', () => {expect(buildParserSelectValue({parseType: ParseType.BuiltIn,parserId: 'book',pipelineId: 'pipe-1',+ pipelineVersionId: 'v1',}),).toBe('builtin:book');expect(@@ -119,8 +111,9 @@ describe('buildParserSelectValue', () => {parseType: ParseType.Pipeline,parserId: 'book',pipelineId: 'pipe-1',+ pipelineVersionId: 'v1',}),- ).toBe('pipeline:pipe-1');+ ).toBe('pipeline:pipe-1:v1');});it('returns undefined when the active id is empty', () => {@@ -131,83 +124,22 @@ describe('buildParserSelectValue', () => {buildParserSelectValue({ parseType: ParseType.Pipeline }),).toBeUndefined();});-});--describe('useParserOptions merged list', () => {- it('puts pipeline options first, then builtin options with plain labels', () => {- agentRequest.useFetchBuiltinPipelines.mockReturnValue({- options: [- { label: 'General', value: 'general' },- { label: 'Book', value: 'book' },- ],- loading: false,- });- agentRequest.useFetchAgentList.mockReturnValue({- data: {- canvas: [- { id: 'pipe-1', title: 'My Flow', type: 'dataflow' },- { id: 'pipe-2', title: 'Other', type: 'dataflow' },- ],- },- loading: false,- });-- const { result } = renderHook(() => useParserOptions());- const opts = result.current.options;- expect(opts).toHaveLength(4);- // Pipelines first, in original order.- expect(opts[0]).toEqual({- value: 'pipeline:pipe-1',- label: 'My Flow',- kind: ParserOptionKind.Pipeline,- });- expect(opts[1].value).toBe('pipeline:pipe-2');- // Builtin appended below; the label stays plain and the "built in" tag is- // rendered by the select component based on `kind`.- expect(opts[2]).toEqual({- value: 'builtin:general',- label: 'General',- kind: ParserOptionKind.BuiltIn,- });- expect(opts[3].label).toBe('Book');- });-- it('excludes compilation template groups from pipeline options', () => {- agentRequest.useFetchAgentList.mockReturnValue({- data: {- canvas: [- { id: 'pipe-1', title: 'Real', type: 'dataflow' },- {- id: 'grp-1',- title: 'Group',- type: AgentListItemType.CompilationTemplateGroup,- },- ],- },- loading: false,- });-- const { result } = renderHook(() => useParserOptions());- const pipelineOpts = result.current.options.filter(- (o) => o.kind === ParserOptionKind.Pipeline,- );- expect(pipelineOpts).toHaveLength(1);- expect(pipelineOpts[0].value).toBe('pipeline:pipe-1');- });-- it('handles empty results from both sources', () => {- const { result } = renderHook(() => useParserOptions());- expect(result.current.options).toEqual([]);- expect(result.current.loading).toBe(false);- });-- it('surfaces loading while either source is fetching', () => {- agentRequest.useFetchBuiltinPipelines.mockReturnValue({- options: [],- loading: true,- });- const { result } = renderHook(() => useParserOptions());- expect(result.current.loading).toBe(true);+ it('returns undefined for a pipeline without a concrete version', () => {+ // An unpinned binding has no leaf to select; the select shows its+ // placeholder until the latest-version prefill fills the field in.+ expect(+ buildParserSelectValue({+ parseType: ParseType.Pipeline,+ pipelineId: 'pipe-1',+ }),+ ).toBeUndefined();+ expect(+ buildParserSelectValue({+ parseType: ParseType.Pipeline,+ pipelineId: 'pipe-1',+ pipelineVersionId: '',+ }),+ ).toBeUndefined();});});diff --git a/web/src/hooks/use-parser-options.ts b/web/src/hooks/use-parser-options.tsindex db1a9efcef..e91085fc64 100644--- a/web/src/hooks/use-parser-options.ts+++ b/web/src/hooks/use-parser-options.ts@@ -1,40 +1,45 @@-import { AgentCategory } from '@/constants/agent';import { ParseType } from '@/constants/knowledge';-import { AgentListItemType } from '@/interfaces/database/agent';-import {- useFetchAgentList,- useFetchBuiltinPipelines,-} from '@/hooks/use-agent-request';-import { useMemo } from 'react';export enum ParserOptionKind {BuiltIn = 'builtin',Pipeline = 'pipeline',}-export interface IParserOption {- value: string;- label: string;- kind: ParserOptionKind;-}--// buildParserOptionValue packs the parser kind and the raw backend id into a-// single select value. Prefixing avoids collisions between short builtin ids-// (e.g. "general") and 32-char canvas pipeline ids, and keeps the value safe-// to serialize.-export function buildParserOptionValue(kind: ParserOptionKind, rawId: string) {- return `${kind}:${rawId}`;+// buildParserOptionValue packs the parser kind, the raw backend id and (for+// pipelines) the pinned version id into a single select value, e.g.+// "builtin:general" or "pipeline:<pipelineId>:<versionId>". Prefixing avoids+// collisions between short builtin ids (e.g. "general") and 32-char canvas+// pipeline ids, and keeps the value safe to serialize. Pipeline and version+// ids are colon-free hex strings, so splitting on ':' is unambiguous.+export function buildParserOptionValue(+ kind: ParserOptionKind,+ rawId: string,+ versionId?: string,+) {+ return versionId ? `${kind}:${rawId}:${versionId}` : `${kind}:${rawId}`;}export function parseParserOptionValue(value?: string): {kind: ParserOptionKind;rawId: string;+ versionId?: string;} | null {if (!value) return null;for (const kind of Object.values(ParserOptionKind)) {const prefix = `${kind}:`;if (value.startsWith(prefix)) {- return { kind, rawId: value.slice(prefix.length) };+ const rest = value.slice(prefix.length);+ if (kind === ParserOptionKind.Pipeline) {+ const separator = rest.indexOf(':');+ if (separator > 0) {+ return {+ kind,+ rawId: rest.slice(0, separator),+ versionId: rest.slice(separator + 1),+ };+ }+ }+ return { kind, rawId: rest };}}return null;@@ -53,19 +58,23 @@ export function resolveBuiltinParserId(rawId: string) {return LegacyBuiltinParserAliases[rawId] ?? rawId;}-// buildParserSelectValue derives the ParserSelect value from the form's-// parse_type / parser_id / pipeline_id triple. Builtin ids pass through the-// legacy alias map so old saved values keep matching an option. An empty id-// yields undefined so the select shows its placeholder instead of a dangling-// "kind:" value.+// buildParserSelectValue derives the ParserTreeSelect value from the form's+// parse_type / parser_id / pipeline_id / pipeline_version_id fields. Builtin+// ids pass through the legacy alias map so old saved values keep matching an+// option. A pipeline without a concrete version (an unpinned binding whose+// version list has not resolved yet) yields no value, so the select shows its+// placeholder until the latest-version prefill fills the field in. An empty id+// likewise yields undefined instead of a dangling "kind:" value.export function buildParserSelectValue({parseType,parserId,pipelineId,+ pipelineVersionId,}: {parseType?: ParseType;parserId?: string;pipelineId?: string;+ pipelineVersionId?: string;}): string | undefined {if (parseType === ParseType.BuiltIn) {return parserId@@ -75,43 +84,11 @@ export function buildParserSelectValue({): undefined;}- return pipelineId- ? buildParserOptionValue(ParserOptionKind.Pipeline, pipelineId)- : undefined;-}--// useParserOptions returns the unified list of parser options shown in the-// merged dataset/document parser dropdown: pipeline (canvas) options first,-// followed by builtin options. Builtin options carry their plain label; the-// "built in" marker is rendered as a tag by the select component via `kind`.-export function useParserOptions() {- const { options: builtinOptions, loading: builtinLoading } =- useFetchBuiltinPipelines();- const { data: pipelineData, loading: pipelineLoading } = useFetchAgentList({- canvas_category: AgentCategory.DataflowCanvas,- });-- const options = useMemo<IParserOption[]>(() => {- const pipeline = (pipelineData?.canvas ?? [])- .filter(- (item) => item.type !== AgentListItemType.CompilationTemplateGroup,+ return pipelineId && pipelineVersionId+ ? buildParserOptionValue(+ ParserOptionKind.Pipeline,+ pipelineId,+ pipelineVersionId,)- .map((item) => ({- value: buildParserOptionValue(ParserOptionKind.Pipeline, item.id),- label: item.title,- kind: ParserOptionKind.Pipeline,- }));-- const builtin = builtinOptions.map((o) => ({- value: buildParserOptionValue(ParserOptionKind.BuiltIn, o.value),- label: o.label,- kind: ParserOptionKind.BuiltIn,- }));-- // Pipeline options keep their existing order; builtin options are appended- // below, matching the desired "pipeline first, builtin below" UI.- return [...pipeline, ...builtin];- }, [pipelineData, builtinOptions]);-- return { options, loading: builtinLoading || pipelineLoading };+ : undefined;}diff --git a/web/src/hooks/use-parser-select-handler.ts b/web/src/hooks/use-parser-select-handler.tsindex 87197bfff9..83f4acd274 100644--- a/web/src/hooks/use-parser-select-handler.ts+++ b/web/src/hooks/use-parser-select-handler.ts@@ -10,17 +10,20 @@ interface ParserFormFields {parse_type?: ParseType;parser_id?: string;pipeline_id?: string;+ pipeline_version_id?: string;}-// useParserSelectHandler returns a stable onChange handler for ParserSelect that-// maps the resolved (kind, rawId) pair onto the form's parser fields. Extracting-// it keeps the duplicated logic in one place and avoids a fresh closure on every-// render, which would otherwise defeat SelectWithSearch's memoization.+// useParserSelectHandler returns a stable onChange handler for+// ParserTreeSelect that maps the resolved (kind, rawId, versionId) triple onto+// the form's parser fields. A version leaf selection writes pipeline_id and+// pipeline_version_id atomically, so a stale version from a previously+// selected pipeline can never survive a switch. Extracting the handler keeps+// the logic in one place and avoids a fresh closure on every render.export function useParserSelectHandler<T extends ParserFormFields>(form: UseFormReturn<T>,) {return useCallback(- (kind: ParserOptionKind | null, rawId: string) => {+ (kind: ParserOptionKind | null, rawId: string, versionId?: string) => {// UseFormReturn is invariant in its values type, so the full form cannot// be narrowed to ParserFormFields directly. The constraint above// guarantees these fields exist; narrowing setValue once keeps the field@@ -31,13 +34,16 @@ export function useParserSelectHandler<T extends ParserFormFields>(setValue('parse_type', ParseType.BuiltIn);setValue('parser_id', rawId);setValue('pipeline_id', '');+ setValue('pipeline_version_id', '');} else if (kind === ParserOptionKind.Pipeline) {setValue('parse_type', ParseType.Pipeline);setValue('pipeline_id', rawId);+ setValue('pipeline_version_id', versionId ?? '');setValue('parser_id', '');} else {setValue('parser_id', '');setValue('pipeline_id', '');+ setValue('pipeline_version_id', '');}},[form],diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 78499fef24..1a5a6ca384 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -690,6 +690,8 @@ Example: A 1 KB message with 1024-dim embedding uses ~9 KB. The 5 MB default limbuiltInPipelines: 'Built-in pipelines',parserSelectPlaceholder: 'Select a parser',parserOptionUnavailable: 'unavailable',+ parserOptionUnavailableMessage:+ 'The selected parser or pipeline version is no longer available. Please select again.',randomSeedTip:'Seed is the starting point for a pseudo-random algorithm that ensures reproducibility of the same output across different runs.',datasetDescription: 'Describe your dataset',@@ -3436,6 +3438,7 @@ This delimiter is used to split the input text into several text pieces echo ofselect: 'No version selected',label: 'Pipeline version',latest: 'Latest version',+ noPublished: 'No published versions',filterByAlias: 'Filter by alias',alias: 'Alias',addAlias: 'Add alias',@@ -3454,8 +3457,6 @@ This delimiter is used to split the input text into several text pieces echo ofrestoreConfirmTitle: 'Restore this version as the current agent?',restoreConfirmContent:'The current agent DSL will be replaced by this version. Save again to create a new version.',- missingContent:- 'The pinned pipeline version no longer exists, so this file cannot be parsed. Please choose a version (or the latest) to continue.',},setting: 'Settings',settings: {diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.tsindex 2ab4597b70..75be405591 100644--- a/web/src/locales/zh.ts+++ b/web/src/locales/zh.ts@@ -627,6 +627,8 @@ export default {builtInPipelines: '内置解析流程',parserSelectPlaceholder: '选择解析方式',parserOptionUnavailable: '不可用',+ parserOptionUnavailableMessage:+ '所选的解析方式或流水线版本已不可用,请重新选择。',randomSeedTip:'种子是伪随机算法的起点,它确保在不同运行中产生相同的输出,从而保证可重复性。',datasetDescription: '你的知识库描述。',@@ -2470,6 +2472,7 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 Rversion: '版本',label: '流水线版本',latest: '最新版本',+ noPublished: '暂无已发布版本',filterByAlias: '按别名筛选',alias: '别名',addAlias: '添加别名',@@ -2487,8 +2490,6 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 RrestoreConfirmTitle: '恢复此版本为当前智能体?',restoreConfirmContent:'当前智能体 DSL 将被此版本替换。再次保存会创建新版本。',- missingContent:- '所固定的流水线版本已不存在,该文件无法解析。请重新选择版本(或选择最新版本)后继续。',},cite: '显示引文',citeTip: '引用',diff --git a/web/src/pages/dataset/dataset/change-parser-dialog.test.tsx b/web/src/pages/dataset/dataset/change-parser-dialog.test.tsxindex d0e44a2411..307c49c39e 100644--- a/web/src/pages/dataset/dataset/change-parser-dialog.test.tsx+++ b/web/src/pages/dataset/dataset/change-parser-dialog.test.tsx@@ -1,3 +1,4 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { fireEvent, render, screen, waitFor } from '@testing-library/react';import {ChangeParserDialog,@@ -36,29 +37,56 @@ const mockDsl = {const mockBuiltinDsl =require('../../../../../internal/ingestion/pipeline/template/ingestion_pipeline_general.json').dsl;let mockCustomDsl = mockDsl;+// Published versions of the mocked pipeline; a test can empty this to model a+// pinned version that has been pruned since the document was saved.+let mockVersions: { id: string; title: string; created_at: string }[] = [+ { id: 'version-1', title: 'v1', created_at: '' },+];jest.mock('@/hooks/use-agent-request', () => ({useFetchPipelineDslByPipelineId: (_id: string, isBuiltin: boolean) => ({dsl: isBuiltin ? mockBuiltinDsl : mockCustomDsl,loading: false,}),- // The version selector in DocumentPipelineDialog lists canvas versions;- // these tests do not exercise version pinning, so an empty list suffices.- useFetchCanvasVersionList: (_id?: string) => ({- data: [],+ // The mocked ParserTreeSelect below emits version-1 on every pipeline+ // pick, so the canvas version list must contain it — otherwise the dialog+ // treats the selection as missing and form validation rejects the save.+ // An undefined canvas id models the hook's enabled gate (no fetch outside+ // pipeline mode).+ useFetchCanvasVersionList: (canvasId?: string) => ({+ data: canvasId ? mockVersions : [],loading: false,+ isError: false,}),+ // The three hooks below back useParserTreeData, which the form hook now+ // consults for the missing-option validation.+ useFetchBuiltinPipelines: () => ({+ options: [{ label: 'General', value: 'general' }],+ loading: false,+ }),+ useFetchAgentList: () => ({+ data: {+ canvas: [{ id: 'pipeline', title: 'Pipeline', type: 'pipeline' }],+ total: 1,+ },+ loading: false,+ }),+ useFetchCanvasVersions: (canvasIds: string[]) =>+ canvasIds.map(() => ({ isSuccess: true, data: mockVersions })),}));jest.mock('@/hooks/use-document-request', () => ({+ DocumentKeys: { all: () => ['documents'] },useRunDocument: () => ({ runDocumentByIds: mockRun, loading: false }),useSetDocumentPipelineParser: () => ({setDocumentPipelineParser: mockSave,loading: false,}),}));-jest.mock('@/components/parser-select', () => ({- ParserSelect: ({ onChange }: any) => {- const choosePipeline = () => onChange('pipeline', 'pipeline');+jest.mock('@/components/parser-tree-select', () => ({+ ParserTreeSelect: ({ onChange }: any) => {+ // A pipeline-side choice always carries a concrete version id: only+ // version leaves are selectable in the merged parser tree select.+ const choosePipeline = () => onChange('pipeline', 'pipeline', 'version-1');const chooseBuiltin = () => onChange('builtin', 'general');const clearParser = () => onChange(null, '');return (@@ -77,6 +105,15 @@ jest.mock('@/components/parser-select', () => ({},}));jest.mock('@/routes', () => ({ Routes: {} }));+// The real module drags the compilation-template graph (markdown editor →+// mermaid/lexical ESM) into jsdom; these tests never exercise parser_config+// validation.+jest.mock(+ '@/components/pipeline-operator-tabs/parser-config-validation',+ () => ({+ addParserConfigIssues: () => {},+ }),+);jest.mock('@/components/pipeline-operator-tabs/pipeline-operator-form', () => {const { useForm } = require('react-hook-form');const {@@ -107,9 +144,11 @@ jest.mock('react-i18next', () => ({function Harness({builtin = false,chunkCount = 0,+ versionId = '',}: {builtin?: boolean;chunkCount?: number;+ versionId?: string;}) {const state = useChangeDocumentParser();const openDialog = () => {@@ -119,6 +158,7 @@ function Harness({chunk_count: chunkCount,chunk_method: builtin ? 'general' : '',pipeline_id: builtin ? '' : 'pipeline',+ pipeline_version_id: versionId,parser_config: builtin? {}: {@@ -156,10 +196,28 @@ beforeEach(() => {mockSave.mockReset().mockResolvedValue(0);mockRun.mockReset().mockResolvedValue(0);mockCustomDsl = mockDsl;+ mockVersions = [{ id: 'version-1', title: 'v1', created_at: '' }];});+// useChangeDocumentParser (and the dialog's data hooks) need a query client;+// retry: false keeps a failed fetch from re-firing the global notification.+function renderHarness(props: {+ builtin?: boolean;+ chunkCount?: number;+ versionId?: string;+}) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <Harness {...props} />+ </QueryClientProvider>,+ );+}+it('keeps existing chunks when re-parsing is declined after saving', async () => {- render(<Harness builtin chunkCount={5} />);+ renderHarness({ builtin: true, chunkCount: 5 });fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'common.save' }));expect(@@ -177,7 +235,7 @@ it('keeps existing chunks when re-parsing is declined after saving', async () =>});it('re-parses with the saved document settings only after confirmation', async () => {- render(<Harness chunkCount={5} />);+ renderHarness({ chunkCount: 5 });fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'common.save' }));const confirm = await screen.findByRole('button', { name: 'common.yes' });@@ -194,7 +252,7 @@ it('re-parses with the saved document settings only after confirmation', async (it('does not offer re-parsing when saving fails', async () => {mockSave.mockResolvedValueOnce(102);- render(<Harness builtin chunkCount={5} />);+ renderHarness({ builtin: true, chunkCount: 5 });fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'common.save' }));await waitFor(() => expect(mockSave).toHaveBeenCalledTimes(1));@@ -208,7 +266,7 @@ it('does not offer re-parsing when saving fails', async () => {});it('saves the built-in parser', async () => {- render(<Harness builtin />);+ renderHarness({ builtin: true });fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'common.save' }));await waitFor(() => expect(mockSave).toHaveBeenCalledTimes(1));@@ -226,7 +284,7 @@ it('saves the built-in parser', async () => {});it('saves after switching from a built-in parser to a pipeline', async () => {- render(<Harness builtin />);+ renderHarness({ builtin: true });fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'Choose pipeline' }));fireEvent.click(screen.getByRole('button', { name: 'common.save' }));@@ -235,6 +293,7 @@ it('saves after switching from a built-in parser to a pipeline', async () => {expect.objectContaining({parserId: '',pipelineId: 'pipeline',+ pipelineVersionId: 'version-1',parse_type: 2,}),);@@ -243,7 +302,7 @@ it('saves after switching from a built-in parser to a pipeline', async () => {it('saves the repository advanced ingestion pipeline template', async () => {mockCustomDsl =require('../../../../../internal/agent/templates/advanced_ingestion_pipeline.json').dsl;- render(<Harness builtin />);+ renderHarness({ builtin: true });fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'Choose pipeline' }));fireEvent.click(screen.getByRole('button', { name: 'common.save' }));@@ -252,7 +311,7 @@ it('saves the repository advanced ingestion pipeline template', async () => {});it('saves after switching from a pipeline back to a built-in parser', async () => {- render(<Harness />);+ renderHarness({});fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'Choose builtin' }));fireEvent.click(screen.getByRole('button', { name: 'common.save' }));@@ -261,13 +320,14 @@ it('saves after switching from a pipeline back to a built-in parser', async () =expect.objectContaining({parserId: 'general',pipelineId: '',+ pipelineVersionId: '',parse_type: 1,}),);});it('still rejects a pipeline selection without a pipeline ID', async () => {- render(<Harness builtin />);+ renderHarness({ builtin: true });fireEvent.click(screen.getByRole('button', { name: 'Open' }));fireEvent.click(screen.getByRole('button', { name: 'Choose pipeline' }));fireEvent.click(screen.getByRole('button', { name: 'Clear parser' }));@@ -275,3 +335,26 @@ it('still rejects a pipeline selection without a pipeline ID', async () => {expect(await screen.findByText('common.pleaseSelect')).toBeInTheDocument();expect(mockSave).not.toHaveBeenCalled();});++it('blocks saving when the pinned pipeline version no longer exists', async () => {+ mockVersions = [];+ renderHarness({ versionId: 'version-1' });+ fireEvent.click(screen.getByRole('button', { name: 'Open' }));++ // The missing verdict derives from the loaded parser tree, so the+ // unavailable message shows as soon as the dialog opens, without waiting+ // for a save attempt.+ expect(+ await screen.findByText(+ 'knowledgeConfiguration.parserOptionUnavailableMessage',+ ),+ ).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'common.save' }));+ await waitFor(() =>+ expect(+ screen.getByText('knowledgeConfiguration.parserOptionUnavailableMessage'),+ ).toBeInTheDocument(),+ );+ expect(mockSave).not.toHaveBeenCalled();+});diff --git a/web/src/pages/dataset/setting/form-schema.test.ts b/web/src/pages/dataset/setting/form-schema.test.tsnew file mode 100644index 0000000000..6e886263cf--- /dev/null+++ b/web/src/pages/dataset/setting/form-schema.test.ts@@ -0,0 +1,63 @@+import { ParseType } from '@/constants/knowledge';+import { buildFormSchema } from './form-schema';++// The real module drags the compilation-template graph (markdown editor →+// mermaid/lexical ESM) into jsdom; these tests never exercise parser_config+// validation.+jest.mock(+ '@/components/pipeline-operator-tabs/parser-config-validation',+ () => ({+ addParserConfigIssues: () => {},+ }),+);++const BaseValues = {+ name: 'kb',+ embedding_model: 'text-embedding',+ pagerank: 0,+};++function missingIssuePaths(result: {+ success: boolean;+ error?: { issues: { path: (string | number)[] }[] };+}) {+ return (result.error?.issues ?? []).map((issue) => issue.path.join('.'));+}++describe('buildFormSchema parser-option-missing rule', () => {+ it('rejects a missing pipeline selection on the pipeline_id field', () => {+ const schema = buildFormSchema(() => true);+ const result = schema.safeParse({+ ...BaseValues,+ parse_type: ParseType.Pipeline,+ pipeline_id: 'deleted-pipeline',+ pipeline_version_id: 'v1',+ });++ expect(result.success).toBe(false);+ expect(missingIssuePaths(result)).toContain('pipeline_id');+ });++ it('rejects a missing builtin selection on the parser_id field', () => {+ const schema = buildFormSchema(() => true);+ const result = schema.safeParse({+ ...BaseValues,+ parse_type: ParseType.BuiltIn,+ parser_id: 'deleted-parser',+ });++ expect(result.success).toBe(false);+ expect(missingIssuePaths(result)).toContain('parser_id');+ });++ it('passes when the selected option still exists', () => {+ const schema = buildFormSchema(() => false);+ const result = schema.safeParse({+ ...BaseValues,+ parse_type: ParseType.BuiltIn,+ parser_id: 'general',+ });++ expect(result.success).toBe(true);+ });+});diff --git a/web/src/pages/dataset/setting/form-schema.ts b/web/src/pages/dataset/setting/form-schema.tsindex 238a55953a..a32f74d063 100644--- a/web/src/pages/dataset/setting/form-schema.ts+++ b/web/src/pages/dataset/setting/form-schema.ts@@ -4,57 +4,78 @@ import { ParseType } from '@/constants/knowledge';import { t } from 'i18next';import { z } from 'zod';-export const formSchema = z- .object({- parse_type: z.nativeEnum(ParseType).optional(),- pipeline_id: z.string().optional(),- // Pinned dataflow canvas version (design section 5/C2). Empty means- // track the canvas latest version.- pipeline_version_id: z.string().optional(),- name: z.string().min(1, {- message: 'Username must be at least 2 characters.',- }),- description: z- .string()- .max(DESCRIPTION_MAX_LENGTH, {- message: t('common.descriptionMaxLength', {- max: DESCRIPTION_MAX_LENGTH,- }),- })- .optional(),- parser_id: z.string().optional(),- avatar: z.any().nullish(),- permission: z.string().optional(),- language: z.string().optional(),- embedding_model: z.string(),- pagerank: z.number(),- parser_config: z.record(z.string(), z.any()).optional(),- connectors: z- .array(- z.object({- id: z.string().optional(),- name: z.string().optional(),- source: z.string().optional(),- ststus: z.string().optional(),- auto_parse: z.string().optional(),- }),- )- .optional(),- })- .superRefine((data, ctx) => {- if (data.parse_type === ParseType.Pipeline && !data.pipeline_id) {- ctx.addIssue({- path: ['pipeline_id'],- message: t('common.pleaseSelect'),- code: 'custom',- });- }- if (data.parse_type === ParseType.BuiltIn && !data.parser_id?.trim()) {- ctx.addIssue({- path: ['parser_id'],- message: t('common.pleaseSelect'),- code: 'custom',- });- }- addParserConfigIssues(data.parser_config, ctx, t);- });+// The missing verdict arrives as a getter, not a value: the schema must exist+// before useForm runs, but whether the saved parser option still exists can+// only be derived from the form's watched values plus the lazily loaded+// parser tree. Reading the verdict through a ref-backed getter keeps every+// validation run on the latest state without rebuilding the resolver.+export const buildFormSchema = (isParserOptionMissing: () => boolean) =>+ z+ .object({+ parse_type: z.nativeEnum(ParseType).optional(),+ pipeline_id: z.string().optional(),+ // Pinned dataflow canvas version (design section 5/C2). Empty means+ // track the canvas latest version.+ pipeline_version_id: z.string().optional(),+ name: z.string().min(1, {+ message: 'Username must be at least 2 characters.',+ }),+ description: z+ .string()+ .max(DESCRIPTION_MAX_LENGTH, {+ message: t('common.descriptionMaxLength', {+ max: DESCRIPTION_MAX_LENGTH,+ }),+ })+ .optional(),+ parser_id: z.string().optional(),+ avatar: z.any().nullish(),+ permission: z.string().optional(),+ language: z.string().optional(),+ embedding_model: z.string(),+ pagerank: z.number(),+ parser_config: z.record(z.string(), z.any()).optional(),+ connectors: z+ .array(+ z.object({+ id: z.string().optional(),+ name: z.string().optional(),+ source: z.string().optional(),+ ststus: z.string().optional(),+ auto_parse: z.string().optional(),+ }),+ )+ .optional(),+ })+ .superRefine((data, ctx) => {+ if (data.parse_type === ParseType.Pipeline && !data.pipeline_id) {+ ctx.addIssue({+ path: ['pipeline_id'],+ message: t('common.pleaseSelect'),+ code: 'custom',+ });+ }+ if (data.parse_type === ParseType.BuiltIn && !data.parser_id?.trim()) {+ ctx.addIssue({+ path: ['parser_id'],+ message: t('common.pleaseSelect'),+ code: 'custom',+ });+ }+ if (isParserOptionMissing()) {+ ctx.addIssue({+ path: [+ data.parse_type === ParseType.Pipeline+ ? 'pipeline_id'+ : 'parser_id',+ ],+ message: t('knowledgeConfiguration.parserOptionUnavailableMessage'),+ code: 'custom',+ });+ }+ addParserConfigIssues(data.parser_config, ctx, t);+ });++export type DatasetSettingFormValues = z.infer<+ ReturnType<typeof buildFormSchema>+>;diff --git a/web/src/pages/dataset/setting/hooks.ts b/web/src/pages/dataset/setting/hooks.tsindex ccbeb51050..35f8713f85 100644--- a/web/src/pages/dataset/setting/hooks.ts+++ b/web/src/pages/dataset/setting/hooks.ts@@ -19,8 +19,7 @@ import {useMemo,} from 'react';import { UseFormReturn } from 'react-hook-form';-import { z } from 'zod';-import { formSchema } from './form-schema';+import { DatasetSettingFormValues } from './form-schema';export function useHasParsedDocument(isEdit?: boolean) {const { data: knowledgeDetails } = useFetchDatasetPipelineConfiguration({@@ -30,7 +29,7 @@ export function useHasParsedDocument(isEdit?: boolean) {}export const useFetchDatasetSettingOnMount = (- form: UseFormReturn<z.infer<typeof formSchema>>,+ form: UseFormReturn<DatasetSettingFormValues>,) => {const { data: knowledgeDetails, loading } =useFetchDatasetPipelineConfiguration();@@ -74,7 +73,7 @@ export const useFetchDatasetSettingOnMount = (// renders as the empty (track latest) form value.pipeline_version_id: knowledgeDetails.pipeline_version_id ?? '',parser_config: formParserConfig,- } as z.infer<typeof formSchema>;+ } as DatasetSettingFormValues;form.reset(formValues);}, [form, knowledgeDetails, sourceData]);@@ -85,7 +84,7 @@ export const useSaveDatasetSetting = () => {const { saveKnowledgeConfiguration, loading } = useUpdateKnowledge();const handleSave = useCallback(- async (values: z.infer<typeof formSchema>) => {+ async (values: DatasetSettingFormValues) => {const payload = { ...values };// Apply forward transforms to parser_config if in pipeline mode. Each nodediff --git a/web/src/pages/dataset/setting/index.tsx b/web/src/pages/dataset/setting/index.tsxindex 36ec57523d..222745fcdd 100644--- a/web/src/pages/dataset/setting/index.tsx+++ b/web/src/pages/dataset/setting/index.tsx@@ -1,4 +1,6 @@-import { ParserSelect } from '@/components/parser-select';+import { ParserTreeSelect } from '@/components/parser-tree-select';+import { useParserTreeData } from '@/components/parser-tree-select/use-parser-tree-data';+import { usePrefillLatestPipelineVersion } from '@/components/parser-tree-select/use-prefill-latest-pipeline-version';import PipelineOperatorTabs from '@/components/pipeline-operator-tabs';import { Button, ButtonLoading } from '@/components/ui/button';import {@@ -27,15 +29,14 @@ import {import { buildParserConfigFromNodes } from '@/utils/pipeline-operator';import { zodResolver } from '@hookform/resolvers/zod';import { isEqual } from 'lodash';-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { FieldErrors, useForm, useFormState, useWatch } from 'react-hook-form';import { useTranslation } from 'react-i18next';-import { z } from 'zod';import ChunkMethodLearnMore from './chunk-method-learn-more';import LinkDataSource, {IDataSourceNodeProps,} from './components/link-data-source';-import { formSchema } from './form-schema';+import { buildFormSchema, DatasetSettingFormValues } from './form-schema';import { GeneralForm } from './general-form';import {useConnectorHandlers,@@ -44,8 +45,6 @@ import {useSaveDatasetSetting,} from './hooks';import { normalizeParserConfigForComparison } from './parser-config';-import { PipelineVersionSelect } from '@/components/pipeline-version-select';-import { RAGFlowTooltip } from '@/components/ui/tooltip';import { useFetchCanvasVersionList } from '@/hooks/use-agent-request';import { useRevealSubmitErrors } from './use-reveal-submit-errors';import { ApplyParserConfigDialog } from './apply-parser-config-dialog';@@ -53,7 +52,16 @@ import { ApplyParserConfigDialog } from './apply-parser-config-dialog';export default function DatasetSetting() {const { t } = useTranslation();- const form = useForm<z.infer<typeof formSchema>>({+ // The missing verdict lives behind a ref because the schema must exist+ // before useForm runs, while the verdict derives from the form's watched+ // values — see buildFormSchema.+ const parserOptionMissingRef = useRef(false);+ const formSchema = useMemo(+ () => buildFormSchema(() => parserOptionMissingRef.current),+ [],+ );++ const form = useForm<DatasetSettingFormValues>({resolver: zodResolver(formSchema),defaultValues: {parse_type: ParseType.BuiltIn,@@ -110,6 +118,40 @@ export default function DatasetSetting() {defaultValue: '',});+ const parserSelectValue = buildParserSelectValue({+ parseType,+ parserId: builtinPipelineId,+ pipelineId,+ pipelineVersionId,+ });++ // The merged parser tree owns the option data; reusing its existence+ // verdict (same React Query cache, no extra fetches) flags a saved parser+ // or pinned pipeline version that has since been deleted.+ const { selectedLeafExists, loading: parserOptionsLoading } =+ useParserTreeData({ value: parserSelectValue });+ const parserOptionMissing =+ !!parserSelectValue && !parserOptionsLoading && !selectedLeafExists;++ // Keep the schema's missing verdict current; declared before the+ // revalidation effect below so trigger() reads the fresh value.+ useEffect(() => {+ parserOptionMissingRef.current = parserOptionMissing;+ }, [parserOptionMissing]);++ // A persisted value never fires onChange validation, so once the parser+ // options have loaded, revalidate explicitly — the saved parser or pinned+ // version may have been deleted, and the error should be visible before+ // submit. Re-running on selection changes clears the error as soon as a+ // valid option is picked. (Same pattern as ModelTreeSelectFormField.)+ const trigger = form.trigger;+ const parserFieldName =+ parseType === ParseType.Pipeline ? 'pipeline_id' : 'parser_id';+ useEffect(() => {+ if (parserOptionsLoading || !parserSelectValue) return;+ trigger(parserFieldName);+ }, [trigger, parserOptionsLoading, parserSelectValue, parserFieldName]);+const pipelineParserConfig = knowledgeDetails?.parser_config as| Record<string, any>| undefined;@@ -129,7 +171,9 @@ export default function DatasetSetting() {: knowledgeDetails?.parser_id: undefined;- // Published versions of the selected dataflow canvas (design C1/C2).+ // Published versions of the selected dataflow canvas, fetched here only to+ // prefill the latest version for unpinned datasets (design C1/C2); the+ // select itself lazy-loads whatever branches the user expands.const { data: canvasVersions } = useFetchCanvasVersionList(parseType === ParseType.Pipeline && pipelineId ? pipelineId : undefined,);@@ -140,21 +184,13 @@ export default function DatasetSetting() {!!knowledgeDetails?.pipeline_version_outdated &&(pipelineVersionId ?? '') === (knowledgeDetails?.pipeline_version_id ?? '');- // Design section 8 (T37): an unpinned dataset must still pre-select the latest- // concrete canvas version instead of the "Latest version" placeholder. We only- // fill an empty field, so a saved pin or a user selection wins. This effect- // runs after the on-mount form.reset (which sets an unpinned dataset to ''),- // so the latest concrete id wins once the version list resolves.- useEffect(() => {- const savedPin = knowledgeDetails?.pipeline_version_id;- if (- !savedPin &&- canvasVersions?.length &&- !form.getValues('pipeline_version_id')- ) {- form.setValue('pipeline_version_id', canvasVersions[0].id);- }- }, [knowledgeDetails, canvasVersions, form]);+ // Design section 8 (T37): an unpinned dataset still pre-selects the latest+ // concrete canvas version once the version list resolves.+ usePrefillLatestPipelineVersion(+ form,+ knowledgeDetails?.pipeline_version_id,+ canvasVersions?.[0]?.id,+ );const { operatorNodes, loading: operatorNodesLoading } =usePipelineOperatorNodes(@@ -172,30 +208,13 @@ export default function DatasetSetting() {operatorNodes,);- // A pinned version belongs to the canvas it was pinned on (design section- // 5/B4 sticky snapshot). Switching the dataflow canvas invalidates any- // previously pinned version, so clear it; otherwise a version id from the- // old canvas would be submitted against the new pipeline. The initial load- // keeps the saved version (selected equals saved).- useEffect(() => {- if (selectedPipelineId !== savedPipelineId) {- form.setValue('pipeline_version_id', '');- }- }, [selectedPipelineId, savedPipelineId, form]);-const { activeTab, setActiveTab } = useActiveTab(operatorNodes);const { scrollContainerRef, handleInvalidSubmit } =useRevealSubmitErrors(setActiveTab);- useEffect(() => {- if (parseType === ParseType.BuiltIn) {- form.setValue('pipeline_id', '');- }- }, [parseType, form]);-const handleSubmit = useCallback(- async (data: z.infer<typeof formSchema>) => {+ async (data: DatasetSettingFormValues) => {const savedValues = form.formState.defaultValues;const operatorDefaults = buildParserConfigFromNodes(operatorNodes);const [savedParserConfig, parserConfig] = [@@ -312,15 +331,13 @@ export default function DatasetSetting() {? 'parser_id': 'pipeline_id'}- render={() => (+ render={({ fieldState }) => (<FormItem className="space-y-1">- <ParserSelect- value={buildParserSelectValue({- parseType,- parserId: builtinPipelineId,- pipelineId,- })}+ <ParserTreeSelect+ value={parserSelectValue}onChange={handleParserSelect}+ outdated={savedVersionOutdated}+ invalid={fieldState.invalid}/><FormMessage /></FormItem>@@ -329,42 +346,6 @@ export default function DatasetSetting() {</div></div></FormItem>- {parseType === ParseType.Pipeline && !!pipelineId && (- <FormItem className="items-center space-y-0">- <div className="flex items-center gap-1">- <FormLabel className="text-sm text-text-secondary whitespace-wrap w-1/4">- {t('flow.version.label')}- </FormLabel>- <div className="text-muted-foreground w-3/4">- <FormField- control={form.control}- name="pipeline_version_id"- render={({ field }) => (- <FormItem className="space-y-1">- <div className="flex items-center gap-2">- <PipelineVersionSelect- versions={canvasVersions}- value={field.value ?? ''}- onChange={field.onChange}- />- {savedVersionOutdated && (- <RAGFlowTooltip- tooltip={t('flow.version.outdated')}- >- <span className="text-destructive cursor-help font-bold">- !- </span>- </RAGFlowTooltip>- )}- </div>- <FormMessage />- </FormItem>- )}- />- </div>- </div>- </FormItem>- )}{showOperatorTabs && (<PipelineOperatorTabsnodes={operatorNodes}diff --git a/web/src/pages/datasets/dataset-creating-dialog.tsx b/web/src/pages/datasets/dataset-creating-dialog.tsxindex 1b3b739f35..227f4aafb8 100644--- a/web/src/pages/datasets/dataset-creating-dialog.tsx+++ b/web/src/pages/datasets/dataset-creating-dialog.tsx@@ -1,4 +1,4 @@-import { ParserSelect } from '@/components/parser-select';+import { ParserTreeSelect } from '@/components/parser-tree-select';import { ButtonLoading } from '@/components/ui/button';import {Dialog,@@ -53,6 +53,7 @@ export function InputForm({ onOk }: IModalProps<any>) {.trim(),parser_id: z.string().optional(),pipeline_id: z.string().optional(),+ pipeline_version_id: z.string().optional(),}).superRefine((data, ctx) => {// When parse_type === BuiltIn, parser_id is required@@ -80,6 +81,7 @@ export function InputForm({ onOk }: IModalProps<any>) {parse_type: ParseType.BuiltIn,parser_id: 'general',pipeline_id: '',+ pipeline_version_id: '',embedding_model: defaultModelDictionary?.embd_id,},});@@ -96,13 +98,17 @@ export function InputForm({ onOk }: IModalProps<any>) {control: form.control,name: 'pipeline_id',});+ const pipelineVersionId = useWatch({+ control: form.control,+ name: 'pipeline_version_id',+ });const handleParserSelect = useParserSelectHandler(form);function onSubmit(data: z.infer<typeof FormSchema>) {const nextData =parseType === ParseType.BuiltIn- ? omit(data, ['pipeline_id'])+ ? omit(data, ['pipeline_id', 'pipeline_version_id']): omit(data, ['parser_id']);onOk?.(nextData);}@@ -147,11 +153,12 @@ export function InputForm({ onOk }: IModalProps<any>) {name={parseType === ParseType.BuiltIn ? 'parser_id' : 'pipeline_id'}render={() => (<FormItem>- <ParserSelect+ <ParserTreeSelectvalue={buildParserSelectValue({parseType,parserId,pipelineId,+ pipelineVersionId,})}onChange={handleParserSelect}/>