Skip to content

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

feat(web): show built-in pipelines in the agents list as read-only items (#20656)

xugangqiang9e658aef4a33
diff --git a/web/src/components/home-card.tsx b/web/src/components/home-card.tsx
index 48296f1cd1..ecaf4aafa1 100644
--- a/web/src/components/home-card.tsx
+++ b/web/src/components/home-card.tsx
@@ -63,8 +63,10 @@ export function HomeCard({
// navigateToSearch(data?.id);
onClick?.();
}}
- tabIndex={0}
- className="px-2.5 py-4 flex gap-2 items-start group h-full w-full hover:shadow-md"
+ tabIndex={onClick ? 0 : undefined}
+ className={`px-2.5 py-4 flex gap-2 items-start group h-full w-full${
+ onClick ? ' hover:shadow-md cursor-pointer' : ''
+ }`}
>
<div>
<RAGFlowAvatar
diff --git a/web/src/hooks/use-agent-request.ts b/web/src/hooks/use-agent-request.ts
index e82311ae17..b68961fc0f 100644
--- a/web/src/hooks/use-agent-request.ts
+++ b/web/src/hooks/use-agent-request.ts
@@ -237,6 +237,7 @@ export const useFetchAgentListByPage = () => {
data: data?.canvas ?? [],
loading,
searchString,
+ debouncedSearchString,
setSearchString,
handleInputChange: onInputChange,
pagination: { ...pagination, total: data?.total ?? 0 },
diff --git a/web/src/interfaces/database/agent.ts b/web/src/interfaces/database/agent.ts
index 9be9bc43fd..7190dc8250 100644
--- a/web/src/interfaces/database/agent.ts
+++ b/web/src/interfaces/database/agent.ts
@@ -91,6 +91,19 @@ export declare interface IFlow {
export enum AgentListItemType {
Agent = 'agent',
CompilationTemplateGroup = 'compilation_template_group',
+ BuiltinPipeline = 'builtin_pipeline',
+}
+
+// A built-in ingestion pipeline rendered as a read-only list item. Built-in
+// pipelines are static, non-DB resources served by GET /api/v1/pipelines; they
+// are composed into the agents list on the front end (mirroring PR #20603's
+// unified parser dropdown) rather than stored as user canvases, and are always
+// marked read-only (builtin: true). They are kept out of the AgentListItem
+// union because they never come from the server's agent list.
+export interface IBuiltinPipelineListItem extends IBuiltinPipeline {
+ canvas_category: string;
+ type: AgentListItemType.BuiltinPipeline;
+ builtin: true;
}
export type AgentListItem =
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index 0290bb249f..95ad3cca29 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -666,6 +666,8 @@ Example: A 1 KB message with 1024-dim embedding uses ~9 KB. The 5 MB default lim
},
knowledgeConfiguration: {
builtInSuffix: 'Built in',
+ builtInBadge: 'Built in',
+ builtInPipelines: 'Built-in pipelines',
parserSelectPlaceholder: 'Select a parser',
parserOptionUnavailable: 'unavailable',
randomSeedTip:
diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts
index 3429796dc8..a887e91174 100644
--- a/web/src/locales/zh.ts
+++ b/web/src/locales/zh.ts
@@ -605,6 +605,8 @@ export default {
},
knowledgeConfiguration: {
builtInSuffix: '内置',
+ builtInBadge: '内置',
+ builtInPipelines: '内置解析流程',
parserSelectPlaceholder: '选择解析方式',
parserOptionUnavailable: '不可用',
randomSeedTip:
diff --git a/web/src/pages/agents/builtin-catalog-probe.tsx b/web/src/pages/agents/builtin-catalog-probe.tsx
new file mode 100644
index 0000000000..39130a0f74
--- /dev/null
+++ b/web/src/pages/agents/builtin-catalog-probe.tsx
@@ -0,0 +1,25 @@
+import { useEffect } from 'react';
+import { useBuiltinItems } from './builtin-pipeline-list';
+
+// Reports the filtered built-in pipeline catalog state (matched item count and
+// loading flag) up to the agents list so it can decide the empty-state without
+// re-deriving the filtering logic. Mounted only when the built-in section is
+// category-eligible, so the catalog request stays gated on the "All"/"Pipeline"
+// views (React Query dedupes it with the section's own call).
+export function BuiltinCatalogProbe({
+ rawCategory,
+ searchString,
+ onReport,
+}: {
+ rawCategory?: string | string[] | Record<string, string[]>;
+ searchString?: string;
+ onReport: (state: { length: number; loading: boolean }) => void;
+}) {
+ const { items, loading } = useBuiltinItems(rawCategory, searchString);
+
+ useEffect(() => {
+ onReport({ length: items.length, loading });
+ }, [items.length, loading, onReport]);
+
+ return null;
+}
diff --git a/web/src/pages/agents/builtin-pipeline-card.test.tsx b/web/src/pages/agents/builtin-pipeline-card.test.tsx
new file mode 100644
index 0000000000..9672d9a37e
--- /dev/null
+++ b/web/src/pages/agents/builtin-pipeline-card.test.tsx
@@ -0,0 +1,107 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { BuiltinPipelineCard } from './builtin-pipeline-card';
+
+jest.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ key === 'knowledgeConfiguration.builtInBadge'
+ ? 'Built in'
+ : key === 'common.copy'
+ ? 'Copy'
+ : key,
+ }),
+}));
+
+const mockCopy = jest.fn();
+// Mutable so a test can flip the copying state before rendering.
+var copyState = { copying: false };
+jest.mock('./use-copy-builtin-pipeline', () => ({
+ useCopyBuiltinPipeline: () => ({
+ copy: mockCopy,
+ copying: copyState.copying,
+ }),
+}));
+
+const baseData: any = {
+ id: 'general',
+ title: 'General',
+ description: 'Default parsing method',
+ filename: 'ingestion_pipeline_general.json',
+ canvas_category: 'dataflow_canvas',
+ type: 'builtin_pipeline',
+ builtin: true,
+};
+
+beforeEach(() => {
+ mockCopy.mockClear();
+ copyState.copying = false;
+});
+
+describe('BuiltinPipelineCard', () => {
+ it('renders the title, description and a Built-in badge', () => {
+ render(
+ <TooltipProvider>
+ <BuiltinPipelineCard data={baseData} />
+ </TooltipProvider>,
+ );
+ expect(screen.getByText('General')).toBeInTheDocument();
+ expect(screen.getByText('Default parsing method')).toBeInTheDocument();
+ expect(screen.getByTestId('builtin-badge')).toHaveTextContent('Built in');
+ });
+
+ it('renders a Copy button and no edit/delete dropdown', () => {
+ render(
+ <TooltipProvider>
+ <BuiltinPipelineCard data={baseData} />
+ </TooltipProvider>,
+ );
+ const copyButton = screen.getByTestId('copy-builtin-pipeline');
+ expect(copyButton).toBeInTheDocument();
+ expect(copyButton).toHaveTextContent('Copy');
+ // Read-only: there is no "more" menu for built-in items.
+ expect(screen.queryByText('common.rename')).not.toBeInTheDocument();
+ });
+
+ it('calls copy with the builtin id and title', () => {
+ render(
+ <TooltipProvider>
+ <BuiltinPipelineCard data={baseData} />
+ </TooltipProvider>,
+ );
+ fireEvent.click(screen.getByTestId('copy-builtin-pipeline'));
+ expect(mockCopy).toHaveBeenCalledWith({ id: 'general', title: 'General' });
+ });
+
+ it('is read-only: clicking the card body does not trigger copy', () => {
+ render(
+ <TooltipProvider>
+ <BuiltinPipelineCard data={baseData} />
+ </TooltipProvider>,
+ );
+ fireEvent.click(screen.getByTestId('builtin-pipeline-card'));
+ expect(mockCopy).not.toHaveBeenCalled();
+ });
+
+ it('disables the Copy button while copying', () => {
+ copyState.copying = true;
+ render(
+ <TooltipProvider>
+ <BuiltinPipelineCard data={baseData} />
+ </TooltipProvider>,
+ );
+ expect(screen.getByTestId('copy-builtin-pipeline')).toBeDisabled();
+ });
+
+ it('falls back gracefully when title or description is missing', () => {
+ render(
+ <TooltipProvider>
+ <BuiltinPipelineCard
+ data={{ ...baseData, title: undefined, description: undefined }}
+ />
+ </TooltipProvider>,
+ );
+ expect(screen.getByTestId('builtin-pipeline-card')).toBeInTheDocument();
+ expect(screen.getByTestId('builtin-badge')).toBeInTheDocument();
+ });
+});
diff --git a/web/src/pages/agents/builtin-pipeline-card.tsx b/web/src/pages/agents/builtin-pipeline-card.tsx
new file mode 100644
index 0000000000..33afc2e526
--- /dev/null
+++ b/web/src/pages/agents/builtin-pipeline-card.tsx
@@ -0,0 +1,63 @@
+import { HomeCard } from '@/components/home-card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { IBuiltinPipelineListItem } from '@/interfaces/database/agent';
+import { Copy } from 'lucide-react';
+import type { MouseEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useCopyBuiltinPipeline } from './use-copy-builtin-pipeline';
+
+// BuiltinPipelineCard renders a read-only built-in ingestion pipeline in the
+// agents list. Built-in pipelines are static, non-user resources: they cannot
+// be opened, renamed, or deleted, but can be copied into a user-owned dataflow
+// canvas via the Copy action.
+export function BuiltinPipelineCard({
+ data,
+}: {
+ data: IBuiltinPipelineListItem;
+}) {
+ const { t } = useTranslation();
+ const { copy, copying } = useCopyBuiltinPipeline();
+
+ const handleCopyClick = (e: MouseEvent) => {
+ e.stopPropagation();
+ copy({ id: data.id, title: data.title ?? '' });
+ };
+
+ // The built-in marker is rendered as a badge. Use a dedicated translation
+ // key (builtInBadge) rather than the parser dropdown's builtInSuffix, so the
+ // badge label is decoupled from that unrelated feature. Fall back to a plain
+ // label if the locale is missing it.
+ const builtInLabel = t('knowledgeConfiguration.builtInBadge') || 'Built in';
+
+ return (
+ <HomeCard
+ testId="builtin-pipeline-card"
+ data={{
+ name: data.title ?? '',
+ description: data.description || '',
+ }}
+ // Read-only: a built-in pipeline cannot be opened for editing.
+ onClick={undefined}
+ // No rename / delete / edit-tags menu for built-in items.
+ moreDropdown={null}
+ icon={
+ <Badge variant="secondary" data-testid="builtin-badge">
+ {builtInLabel}
+ </Badge>
+ }
+ extra={
+ <Button
+ data-testid="copy-builtin-pipeline"
+ variant="static"
+ size="auto"
+ disabled={copying}
+ onClick={handleCopyClick}
+ >
+ <Copy className="size-4" />
+ {t('common.copy')}
+ </Button>
+ }
+ />
+ );
+}
diff --git a/web/src/pages/agents/builtin-pipeline-list.test.ts b/web/src/pages/agents/builtin-pipeline-list.test.ts
new file mode 100644
index 0000000000..33f8347e31
--- /dev/null
+++ b/web/src/pages/agents/builtin-pipeline-list.test.ts
@@ -0,0 +1,215 @@
+import {
+ shouldShowBuiltinForRaw,
+ filterBuiltinByKeyword,
+ toBuiltinListItem,
+ resolveAgentsEmptyState,
+} from './builtin-pipeline-list';
+import { AgentCategory } from '@/constants/agent';
+import { AgentListItemType } from '@/interfaces/database/agent';
+
+jest.mock('@/hooks/use-agent-request', () => ({
+ useFetchBuiltinPipelines: jest.fn(),
+}));
+
+const sample = [
+ {
+ id: 'general',
+ title: 'General',
+ description: 'Default parsing method',
+ filename: 'ingestion_pipeline_general.json',
+ },
+ {
+ id: 'book',
+ title: 'Book',
+ description: 'Long document parsing',
+ filename: 'ingestion_pipeline_book.json',
+ },
+ {
+ id: 'naive',
+ title: 'Naive',
+ description: undefined,
+ filename: 'ingestion_pipeline_naive.json',
+ },
+];
+
+describe('shouldShowBuiltinForRaw', () => {
+ it('shows builtin in the "All" view (no category filter)', () => {
+ expect(shouldShowBuiltinForRaw(undefined)).toBe(true);
+ });
+
+ it('shows builtin in the Pipeline (dataflow) view', () => {
+ expect(shouldShowBuiltinForRaw(AgentCategory.DataflowCanvas)).toBe(true);
+ expect(shouldShowBuiltinForRaw([AgentCategory.DataflowCanvas])).toBe(true);
+ });
+
+ it('shows builtin when dataflow is among several selected categories', () => {
+ expect(
+ shouldShowBuiltinForRaw([
+ AgentCategory.AgentCanvas,
+ AgentCategory.DataflowCanvas,
+ ]),
+ ).toBe(true);
+ });
+
+ it('hides builtin in the pure Agent view', () => {
+ expect(shouldShowBuiltinForRaw(AgentCategory.AgentCanvas)).toBe(false);
+ expect(shouldShowBuiltinForRaw([AgentCategory.AgentCanvas])).toBe(false);
+ });
+
+ it('hides builtin in the compilation template group view', () => {
+ expect(shouldShowBuiltinForRaw('compilation_template_group')).toBe(false);
+ expect(shouldShowBuiltinForRaw(['compilation_template_group'])).toBe(false);
+ });
+
+ it('hides builtin when only non-dataflow categories are selected', () => {
+ expect(
+ shouldShowBuiltinForRaw([
+ AgentCategory.AgentCanvas,
+ 'compilation_template_group',
+ ]),
+ ).toBe(false);
+ });
+
+ it('hides builtin for an array carrying no plain ids', () => {
+ // An array of structured filters has no plain category ids, so the
+ // "All"/"Pipeline" intent cannot be assumed and built-ins stay hidden.
+ expect(
+ shouldShowBuiltinForRaw([
+ { operator: 'or', values: [] } as unknown as string,
+ ]),
+ ).toBe(false);
+ });
+
+ it('hides builtin for a structured (non-string) category filter', () => {
+ // A Record-typed filter carries no plain ids; the "All"/"Pipeline" intent
+ // cannot be assumed, so built-ins stay hidden rather than guessing.
+ expect(
+ shouldShowBuiltinForRaw({
+ operator: 'or',
+ values: [AgentCategory.DataflowCanvas],
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('filterBuiltinByKeyword', () => {
+ it('returns all items when the keyword is empty/undefined', () => {
+ expect(filterBuiltinByKeyword(sample, undefined)).toHaveLength(3);
+ expect(filterBuiltinByKeyword(sample, '')).toHaveLength(3);
+ expect(filterBuiltinByKeyword(sample, ' ')).toHaveLength(3);
+ });
+
+ it('matches case-insensitively against the title', () => {
+ const result = filterBuiltinByKeyword(sample, 'BOOK');
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('book');
+ });
+
+ it('matches against the description', () => {
+ const result = filterBuiltinByKeyword(sample, 'long document');
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('book');
+ });
+
+ it('matches a partial substring', () => {
+ const result = filterBuiltinByKeyword(sample, 'parsing');
+ // "General" -> "Default parsing method", "Book" -> "Long document parsing"
+ expect(result.map((r) => r.id).sort()).toEqual(['book', 'general']);
+ });
+
+ it('returns an empty list when nothing matches', () => {
+ expect(filterBuiltinByKeyword(sample, 'zzz-no-match')).toEqual([]);
+ });
+
+ it('does not throw on items with undefined description', () => {
+ expect(() => filterBuiltinByKeyword(sample, 'naive')).not.toThrow();
+ const result = filterBuiltinByKeyword(sample, 'naive');
+ expect(result[0].id).toBe('naive');
+ });
+});
+
+describe('toBuiltinListItem', () => {
+ it('tags the item as a read-only builtin dataflow canvas', () => {
+ const item = toBuiltinListItem(sample[0]);
+ expect(item.type).toBe(AgentListItemType.BuiltinPipeline);
+ expect(item.builtin).toBe(true);
+ expect(item.canvas_category).toBe(AgentCategory.DataflowCanvas);
+ });
+
+ it('preserves the source fields', () => {
+ const item = toBuiltinListItem(sample[0]);
+ expect(item.id).toBe('general');
+ expect(item.title).toBe('General');
+ expect(item.description).toBe('Default parsing method');
+ expect(item.filename).toBe('ingestion_pipeline_general.json');
+ });
+
+ it('keeps an undefined description as undefined', () => {
+ const item = toBuiltinListItem(sample[2]);
+ expect(item.description).toBeUndefined();
+ });
+});
+
+describe('resolveAgentsEmptyState', () => {
+ const base = {
+ dataLength: 0,
+ builtinItemsLength: 0,
+ searchString: '',
+ listLoading: false,
+ builtinVisible: true,
+ builtinLoading: false,
+ };
+
+ it('shows the empty card (no search) when there is nothing at all', () => {
+ expect(resolveAgentsEmptyState(base)).toBe('empty');
+ });
+
+ it('shows the search empty card when a search yields no user or builtin hits', () => {
+ expect(
+ resolveAgentsEmptyState({ ...base, searchString: 'zzz-no-match' }),
+ ).toBe('search-empty');
+ });
+
+ it('renders content when user items exist even with no search', () => {
+ expect(resolveAgentsEmptyState({ ...base, dataLength: 3 })).toBe('content');
+ });
+
+ it('renders content when filtered builtin items exist (the zero-match-search regression)', () => {
+ // Category-eligible view (builtinVisible true) + search that did not match
+ // anything would previously leave a blank CardContainer; the matched
+ // builtin count now drives the decision.
+ expect(
+ resolveAgentsEmptyState({
+ ...base,
+ searchString: 'zzz-no-match',
+ builtinItemsLength: 2,
+ }),
+ ).toBe('content');
+ });
+
+ it('keeps the container mounted while the eligible builtin catalog loads', () => {
+ expect(resolveAgentsEmptyState({ ...base, builtinLoading: true })).toBe(
+ 'content',
+ );
+ });
+
+ it('renders nothing while the user list is loading', () => {
+ expect(resolveAgentsEmptyState({ ...base, listLoading: true })).toBe(
+ 'loading',
+ );
+ });
+
+ it('treats a non-eligible (Agent) view as if builtins were absent', () => {
+ // builtinVisible false => the builtin probe is not mounted, so the reported
+ // builtin count stays 0; with no user items and a search, it is a
+ // search-empty, not content.
+ expect(
+ resolveAgentsEmptyState({
+ ...base,
+ builtinVisible: false,
+ searchString: 'zzz-no-match',
+ builtinItemsLength: 0,
+ }),
+ ).toBe('search-empty');
+ });
+});
diff --git a/web/src/pages/agents/builtin-pipeline-list.ts b/web/src/pages/agents/builtin-pipeline-list.ts
new file mode 100644
index 0000000000..8a4a6a2f51
--- /dev/null
+++ b/web/src/pages/agents/builtin-pipeline-list.ts
@@ -0,0 +1,130 @@
+import { AgentCategory } from '@/constants/agent';
+import { useFetchBuiltinPipelines } from '@/hooks/use-agent-request';
+import {
+ AgentListItemType,
+ IBuiltinPipeline,
+ IBuiltinPipelineListItem,
+} from '@/interfaces/database/agent';
+import { useMemo } from 'react';
+
+// Whether the built-in pipeline section should be shown for the given
+// canvas_category filter as stored on the agents list's filter value. Built-in
+// pipelines are parsing methods => dataflow canvases, so they appear in the
+// "All" view (undefined) and the "Pipeline" view, but not the pure "Agent" or
+// "Compilation template group" views. A structured (Record-typed) filter
+// carries no plain ids, so the "All"/"Pipeline" intent cannot be assumed and
+// built-ins stay hidden rather than guessing. This mirrors how PR #20603
+// surfaces built-in pipelines only alongside user pipelines.
+export function shouldShowBuiltinForRaw(
+ rawCategory?: string | string[] | Record<string, string[]>,
+): boolean {
+ if (!rawCategory) {
+ return true; // "All" view
+ }
+ if (typeof rawCategory === 'string') {
+ return rawCategory === AgentCategory.DataflowCanvas;
+ }
+ if (Array.isArray(rawCategory)) {
+ const ids = rawCategory.filter((x): x is string => typeof x === 'string');
+ if (ids.length === 0) {
+ return false; // structured filter with no plain ids => hide
+ }
+ return ids.includes(AgentCategory.DataflowCanvas);
+ }
+ // A single structured (Record) filter carries no plain ids; the "All"/
+ // "Pipeline" intent cannot be assumed, so built-ins stay hidden.
+ return false;
+}
+
+// Filters built-in pipelines by a case-insensitive keyword over title and
+// description. An empty/whitespace/undefined keyword returns the list
+// unchanged.
+export function filterBuiltinByKeyword(
+ items: IBuiltinPipeline[],
+ keywords?: string,
+): IBuiltinPipeline[] {
+ if (!keywords || keywords.trim() === '') {
+ return items;
+ }
+ const kw = keywords.trim().toLowerCase();
+ return items.filter((item) => {
+ const title = (item.title ?? '').toLowerCase();
+ const description = (item.description ?? '').toLowerCase();
+ return title.includes(kw) || description.includes(kw);
+ });
+}
+
+// Normalises a built-in pipeline catalog entry into the list-item shape the
+// agents list renders, tagging it as a read-only built-in dataflow canvas.
+export function toBuiltinListItem(
+ item: IBuiltinPipeline,
+): IBuiltinPipelineListItem {
+ return {
+ ...item,
+ canvas_category: AgentCategory.DataflowCanvas,
+ type: AgentListItemType.BuiltinPipeline,
+ builtin: true,
+ };
+}
+
+// Shared hook that resolves the filtered, rendered built-in pipeline items for
+// the given category view and search keyword. Both the section and the
+// agents-list empty-state probe call this with the same arguments; React Query
+// dedupes the underlying catalog request by key, so the request fires once.
+export function useBuiltinItems(
+ rawCategory?: string | string[] | Record<string, string[]>,
+ searchString?: string,
+): { items: IBuiltinPipelineListItem[]; loading: boolean } {
+ const { data: builtinData, loading } = useFetchBuiltinPipelines();
+ const items = useMemo(() => {
+ if (!shouldShowBuiltinForRaw(rawCategory)) {
+ return [];
+ }
+ return filterBuiltinByKeyword(builtinData?.canvas ?? [], searchString).map(
+ toBuiltinListItem,
+ );
+ }, [rawCategory, builtinData, searchString]);
+ return { items, loading };
+}
+
+export type AgentsEmptyState = 'content' | 'search-empty' | 'loading' | 'empty';
+
+// Decides what the agents list should render when there are no user-owned
+// canvases. The decision must account for *filtered* built-in pipeline matches,
+// not merely whether the built-in section is *eligible* for the current
+// category (a category-eligibility boolean would wrongly keep the empty
+// CardContainer mounted on a zero-result search). `builtinVisible` and
+// `builtinLoading` describe the eligible built-in catalog; `listLoading`
+// describes the user-owned list.
+export function resolveAgentsEmptyState(params: {
+ dataLength: number;
+ builtinItemsLength: number;
+ searchString?: string;
+ listLoading: boolean;
+ builtinVisible: boolean;
+ builtinLoading: boolean;
+}): AgentsEmptyState {
+ const hasContent = params.dataLength > 0 || params.builtinItemsLength > 0;
+
+ // While the user-owned list is still loading, render nothing.
+ if (params.listLoading) {
+ return 'loading';
+ }
+
+ // Keep the container mounted while the eligible built-in catalog is still
+ // loading, so we don't briefly flash an empty card before its items arrive
+ // (matches the prior behaviour of showing the bare container during load).
+ if (params.builtinVisible && params.builtinLoading && !hasContent) {
+ return 'content';
+ }
+
+ if (hasContent) {
+ return 'content';
+ }
+
+ if (params.searchString) {
+ return 'search-empty';
+ }
+
+ return 'empty';
+}
diff --git a/web/src/pages/agents/builtin-pipeline-section.test.tsx b/web/src/pages/agents/builtin-pipeline-section.test.tsx
new file mode 100644
index 0000000000..93ebb3f13b
--- /dev/null
+++ b/web/src/pages/agents/builtin-pipeline-section.test.tsx
@@ -0,0 +1,156 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { renderHook } from '@testing-library/react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { BuiltinPipelineSection } from './builtin-pipeline-section';
+import { AgentCategory } from '@/constants/agent';
+
+jest.mock('@/hooks/use-agent-request', () => ({
+ useFetchBuiltinPipelines: jest.fn(),
+}));
+
+const mockCopy = jest.fn();
+jest.mock('./use-copy-builtin-pipeline', () => ({
+ useCopyBuiltinPipeline: () => ({ copy: mockCopy, copying: false }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const agentRequest = require('@/hooks/use-agent-request');
+
+const catalog = [
+ {
+ id: 'general',
+ title: 'General',
+ description: 'Default',
+ filename: 'a.json',
+ },
+ {
+ id: 'book',
+ title: 'Book',
+ description: 'Long doc',
+ filename: 'b.json',
+ },
+];
+
+const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={new QueryClient()}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </QueryClientProvider>
+);
+
+beforeEach(() => {
+ mockCopy.mockReset();
+ agentRequest.useFetchBuiltinPipelines.mockReturnValue({
+ data: { canvas: catalog, total: catalog.length },
+ loading: false,
+ });
+});
+
+describe('BuiltinPipelineSection', () => {
+ it('renders the section with cards in the "All" view', () => {
+ const { container } = render(
+ <BuiltinPipelineSection rawCategory={undefined} searchString="" />,
+ { wrapper },
+ );
+ expect(screen.getByTestId('builtin-pipeline-section')).toBeInTheDocument();
+ expect(
+ screen.getByText('knowledgeConfiguration.builtInPipelines'),
+ ).toBeInTheDocument();
+ // Two built-in cards rendered (each carries a copy button).
+ expect(screen.getAllByTestId('copy-builtin-pipeline')).toHaveLength(2);
+ // The cards are laid out in the same responsive grid as the user items
+ // (not a single long column).
+ const grid = container.querySelector('.grid');
+ expect(grid).not.toBeNull();
+ expect(
+ grid?.querySelectorAll('[data-testid="copy-builtin-pipeline"]'),
+ ).toHaveLength(2);
+ });
+
+ it('still renders when the user list is empty (built-ins are not gated on user items)', () => {
+ // This is the empty-user-list visibility scenario: the section must appear
+ // in the All view even though there are zero user-owned canvases.
+ const { container } = render(
+ <BuiltinPipelineSection rawCategory={undefined} searchString="general" />,
+ { wrapper },
+ );
+ expect(screen.getByTestId('builtin-pipeline-section')).toBeInTheDocument();
+ expect(screen.getAllByTestId('copy-builtin-pipeline')).toHaveLength(1);
+ expect(
+ container.querySelector('[data-testid="builtin-badge"]'),
+ ).toBeTruthy();
+ });
+
+ it('hides the section in the pure Agent view', () => {
+ render(
+ <BuiltinPipelineSection
+ rawCategory={AgentCategory.AgentCanvas}
+ searchString=""
+ />,
+ { wrapper },
+ );
+ expect(
+ screen.queryByTestId('builtin-pipeline-section'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('hides the section for a structured (non-string) category filter', () => {
+ render(
+ <BuiltinPipelineSection
+ rawCategory={{ operator: 'or', values: [AgentCategory.DataflowCanvas] }}
+ searchString=""
+ />,
+ { wrapper },
+ );
+ expect(
+ screen.queryByTestId('builtin-pipeline-section'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('hides the section when the catalog is empty', () => {
+ agentRequest.useFetchBuiltinPipelines.mockReturnValue({
+ data: { canvas: [], total: 0 },
+ loading: false,
+ });
+ render(<BuiltinPipelineSection rawCategory={undefined} searchString="" />, {
+ wrapper,
+ });
+ expect(
+ screen.queryByTestId('builtin-pipeline-section'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders a divider before the section only when showDivider is set', () => {
+ const { rerender } = render(
+ <BuiltinPipelineSection
+ rawCategory={undefined}
+ searchString=""
+ showDivider={false}
+ />,
+ { wrapper },
+ );
+ expect(document.querySelector('.border-t')).toBeNull();
+
+ rerender(
+ <BuiltinPipelineSection
+ rawCategory={undefined}
+ searchString=""
+ showDivider
+ />,
+ { wrapper },
+ );
+ expect(document.querySelector('.border-t')).not.toBeNull();
+ });
+
+ it('triggers the copy mutation when a card copy button is clicked', () => {
+ render(<BuiltinPipelineSection rawCategory={undefined} searchString="" />, {
+ wrapper,
+ });
+ fireEvent.click(screen.getAllByTestId('copy-builtin-pipeline')[0]);
+ expect(mockCopy).toHaveBeenCalledTimes(1);
+ expect(mockCopy.mock.calls[0][0]).toEqual({
+ id: 'general',
+ title: 'General',
+ });
+ });
+});
diff --git a/web/src/pages/agents/builtin-pipeline-section.tsx b/web/src/pages/agents/builtin-pipeline-section.tsx
new file mode 100644
index 0000000000..34f235f67e
--- /dev/null
+++ b/web/src/pages/agents/builtin-pipeline-section.tsx
@@ -0,0 +1,47 @@
+import { useTranslation } from 'react-i18next';
+import { CardContainer } from '@/components/card-container';
+import { useBuiltinItems } from './builtin-pipeline-list';
+import { BuiltinPipelineCard } from './builtin-pipeline-card';
+
+// BuiltinPipelineSection renders the read-only built-in pipeline catalog after
+// the user's own canvases. It owns the catalog query so the request is issued
+// only when this component is mounted (the agents page mounts it solely for the
+// "All" and "Pipeline" views), keeping the "fire a query where its data is
+// rendered" convention and avoiding a needless request in the Agent /
+// compilation-template views. The cards use the same responsive CardContainer
+// grid as the user items so the section does not stretch into one long column.
+export function BuiltinPipelineSection({
+ rawCategory,
+ searchString,
+ showDivider,
+}: {
+ rawCategory?: string | string[] | Record<string, string[]>;
+ searchString?: string;
+ showDivider?: boolean;
+}) {
+ const { t } = useTranslation();
+ const { items: builtinItems } = useBuiltinItems(rawCategory, searchString);
+
+ if (builtinItems.length === 0) {
+ return null;
+ }
+
+ // col-span-full lets the section span the full width of the parent grid so
+ // its own CardContainer grid lays the cards out in multiple columns.
+ return (
+ <section
+ className="mt-6 col-span-full"
+ data-testid="builtin-pipeline-section"
+ >
+ {showDivider && <div className="border-t border-line-divider my-2" />}
+ <h2 className="text-sm font-medium text-text-secondary mb-3">
+ {t('knowledgeConfiguration.builtInPipelines')}
+ </h2>
+ <CardContainer>
+ {builtinItems.map((b) => (
+ <BuiltinPipelineCard key={b.id} data={b} />
+ ))}
+ </CardContainer>
+ </section>
+ );
+}
diff --git a/web/src/pages/agents/index.test.tsx b/web/src/pages/agents/index.test.tsx
new file mode 100644
index 0000000000..6dca6d3ae9
--- /dev/null
+++ b/web/src/pages/agents/index.test.tsx
@@ -0,0 +1,217 @@
+import { render, screen } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { MemoryRouter } from 'react-router';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { AgentCategory } from '@/constants/agent';
+import Agents from './index';
+
+// Fully isolate the agents list from the request/router/modal layers.
+// The two list/builtin hooks are controlled per-test; every other hook the
+// rendered subtree touches (AgentCard's dropdown/tag-editor, etc.) is stubbed
+// to return an empty object so render never calls into real request code.
+jest.mock(
+ '@/hooks/use-agent-request',
+ () =>
+ new Proxy(
+ {
+ useFetchAgentListByPage: jest.fn(),
+ useFetchBuiltinPipelines: jest.fn(),
+ },
+ {
+ get: (target, prop: string) =>
+ prop in target
+ ? (target as Record<string, unknown>)[prop]
+ : jest.fn(() => ({})),
+ },
+ ),
+);
+jest.mock('@/hooks/use-compilation-template-group-request', () => ({
+ useDeleteCompilationTemplateGroup: () => ({ deleteGroup: jest.fn() }),
+}));
+jest.mock('@/hooks/logic-hooks', () => ({
+ useGoToPreviousPageOnEmpty: jest.fn(),
+}));
+jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({
+ useNavigatePage: () => ({
+ navigateToAgent: jest.fn(),
+ navigateToAgentTemplates: jest.fn(),
+ }),
+}));
+// Avoid loading routes.tsx (it builds a data router that needs the `Request`
+// global jsdom lacks); the route constants are only passed to mocked navigators.
+jest.mock('@/routes', () => ({
+ Routes: new Proxy({}, { get: () => '' }),
+}));
+jest.mock('@/pages/agents/hooks/use-create-agent', () => ({
+ useCreateAgentOrPipeline: () => ({
+ creatingVisible: false,
+ hideCreatingModal: jest.fn(),
+ showCreatingModal: jest.fn(),
+ loading: false,
+ handleCreateAgentOrPipeline: jest.fn(),
+ }),
+}));
+jest.mock('@/pages/agents/hooks/use-select-filters', () => ({
+ useSelectFilters: () => [],
+}));
+jest.mock('@/pages/agents/use-import-json', () => ({
+ useHandleImportJsonFile: () => ({
+ handleImportJson: jest.fn(),
+ fileUploadVisible: false,
+ onFileUploadOk: jest.fn(),
+ hideFileUploadModal: jest.fn(),
+ }),
+}));
+jest.mock('@/pages/agents/use-rename-agent', () => ({
+ useRenameAgent: () => ({
+ agentRenameLoading: false,
+ initialAgentName: '',
+ onAgentRenameOk: jest.fn(),
+ agentRenameVisible: false,
+ hideAgentRenameModal: jest.fn(),
+ showAgentRenameModal: jest.fn(),
+ }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const agentRequest = jest.requireMock('@/hooks/use-agent-request');
+
+const catalog = [
+ {
+ id: 'general',
+ title: 'General',
+ description: 'Default',
+ filename: 'a.json',
+ },
+ { id: 'book', title: 'Book', description: 'Long doc', filename: 'b.json' },
+];
+
+const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <MemoryRouter>
+ <QueryClientProvider client={new QueryClient()}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </QueryClientProvider>
+ </MemoryRouter>
+);
+
+const defaultListPage = {
+ data: [] as Array<Record<string, unknown>>,
+ loading: false,
+ pagination: { current: 1, pageSize: 10, total: 0 },
+ setPagination: jest.fn(),
+ searchString: '',
+ setSearchString: jest.fn(),
+ handleInputChange: jest.fn(),
+ filterValue: undefined as Record<string, unknown> | undefined,
+ setFilterValue: jest.fn(),
+ handleFilterSubmit: jest.fn(),
+ checkValue: jest.fn(),
+ debouncedSearchString: '',
+};
+
+function setListPage(overrides: Partial<typeof defaultListPage> = {}) {
+ agentRequest.useFetchAgentListByPage.mockReturnValue({
+ ...defaultListPage,
+ ...overrides,
+ });
+}
+
+function setBuiltin(canvas = catalog, loading = false) {
+ agentRequest.useFetchBuiltinPipelines.mockReturnValue({
+ data: { canvas, total: canvas.length },
+ loading,
+ });
+}
+
+beforeEach(() => {
+ setBuiltin();
+ setListPage();
+});
+
+describe('Agents empty-state (built-in pipeline regression)', () => {
+ it('shows the search-empty card on a zero-match search in the All view', () => {
+ // The bug: builtinVisible (category eligibility) kept the empty
+ // CardContainer mounted instead of the search-empty card.
+ setListPage({
+ filterValue: undefined,
+ data: [],
+ debouncedSearchString: 'zzz-no-match',
+ });
+ render(<Agents />, { wrapper });
+
+ expect(screen.getByTestId('agents-search-empty')).toBeInTheDocument();
+ expect(
+ screen.queryByTestId('builtin-pipeline-section'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('keeps the built-in section when the search matches a built-in pipeline', () => {
+ setListPage({
+ filterValue: undefined,
+ data: [],
+ debouncedSearchString: 'general',
+ });
+ render(<Agents />, { wrapper });
+
+ expect(screen.getByTestId('builtin-pipeline-section')).toBeInTheDocument();
+ expect(screen.queryByTestId('agents-search-empty')).not.toBeInTheDocument();
+ });
+
+ it('shows the non-search empty card when there is nothing and no search', () => {
+ setListPage({
+ filterValue: undefined,
+ data: [],
+ debouncedSearchString: '',
+ });
+ setBuiltin([]); // empty catalog
+ render(<Agents />, { wrapper });
+
+ expect(screen.queryByTestId('agents-search-empty')).not.toBeInTheDocument();
+ // The non-search empty card exposes the create actions.
+ expect(screen.getByTestId('agents-empty-create')).toBeInTheDocument();
+ });
+
+ it('shows the search-empty card in the Agent view (built-ins not eligible)', () => {
+ setListPage({
+ filterValue: { canvasCategory: AgentCategory.AgentCanvas },
+ data: [],
+ debouncedSearchString: 'zzz-no-match',
+ });
+ render(<Agents />, { wrapper });
+
+ expect(screen.getByTestId('agents-search-empty')).toBeInTheDocument();
+ expect(
+ screen.queryByTestId('builtin-pipeline-section'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders nothing while the user list is loading', () => {
+ setListPage({ filterValue: undefined, data: [], loading: true });
+ render(<Agents />, { wrapper });
+
+ expect(screen.queryByTestId('agents-search-empty')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('agents-empty-create')).not.toBeInTheDocument();
+ });
+
+ it('renders the content branch with user items (and footer) without an empty card', () => {
+ setListPage({
+ filterValue: undefined,
+ data: [
+ {
+ id: 'user-1',
+ title: 'My Agent',
+ canvas_category: AgentCategory.AgentCanvas,
+ type: 'agent',
+ },
+ ],
+ debouncedSearchString: '',
+ });
+ render(<Agents />, { wrapper });
+
+ // No empty state is shown when there is at least one user item.
+ expect(screen.queryByTestId('agents-search-empty')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('agents-empty-create')).not.toBeInTheDocument();
+ // The user card itself is rendered.
+ expect(screen.getByText('My Agent')).toBeInTheDocument();
+ });
+});
diff --git a/web/src/pages/agents/index.tsx b/web/src/pages/agents/index.tsx
index 7eb189d6aa..714700eaef 100644
--- a/web/src/pages/agents/index.tsx
+++ b/web/src/pages/agents/index.tsx
@@ -18,11 +18,17 @@ import { useFetchAgentListByPage } from '@/hooks/use-agent-request';
import { useDeleteCompilationTemplateGroup } from '@/hooks/use-compilation-template-group-request';
import { Routes } from '@/routes';
import { pick } from 'lodash';
+import { BuiltinPipelineSection } from './builtin-pipeline-section';
import { Clipboard, ClipboardPlus, FileInput, Plus } from 'lucide-react';
-import { useCallback, useEffect } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router';
import { AgentCard } from './agent-card';
+import { BuiltinCatalogProbe } from './builtin-catalog-probe';
+import {
+ resolveAgentsEmptyState,
+ shouldShowBuiltinForRaw,
+} from './builtin-pipeline-list';
import { CompilationTemplateCard } from './compilation-template-card';
import { CreateAgentDialog } from './create-agent-dialog';
import { useCreateAgentOrPipeline } from './hooks/use-create-agent';
@@ -48,8 +54,24 @@ export default function Agents() {
setFilterValue,
handleFilterSubmit,
checkValue,
+ debouncedSearchString,
} = useFetchAgentListByPage();
+ // Built-in pipelines surface only in the "All" and "Pipeline" views. Compute
+ // this from the raw filter value so the section (and its catalog request) is
+ // mounted only when eligible, matching the "fire a query where its data is
+ // rendered" convention.
+ const rawCategory = filterValue?.canvasCategory;
+ const builtinVisible = shouldShowBuiltinForRaw(rawCategory);
+
+ // Lifted filtered built-in catalog state, reported by BuiltinCatalogProbe so
+ // the empty-state decision can use *matched* built-in items rather than just
+ // category eligibility.
+ const [builtinState, setBuiltinState] = useState<{
+ length: number;
+ loading: boolean;
+ }>({ length: 0, loading: false });
+
const { navigateToAgentTemplates } = useNavigatePage();
const navigate = useNavigate();
@@ -124,8 +146,24 @@ export default function Agents() {
}
}, [isCreate, showCreatingModal, searchUrl, setSearchUrl]);
+ const emptyState = resolveAgentsEmptyState({
+ dataLength: data.length,
+ builtinItemsLength: builtinState.length,
+ searchString: debouncedSearchString,
+ listLoading,
+ builtinVisible,
+ builtinLoading: builtinState.loading,
+ });
+
return (
<>
+ {builtinVisible && (
+ <BuiltinCatalogProbe
+ rawCategory={rawCategory}
+ searchString={debouncedSearchString}
+ onReport={setBuiltinState}
+ />
+ )}
<article
className="size-full min-w-0 flex flex-col"
data-testid="agents-list"
@@ -174,7 +212,7 @@ export default function Agents() {
</ListFilterBar>
</header>
- {data.length ? (
+ {emptyState === 'content' ? (
<>
<CardContainer className="flex-1 overflow-auto px-5">
{data.map((x) =>
@@ -193,28 +231,39 @@ export default function Agents() {
/>
),
)}
+
+ {builtinVisible && (
+ <BuiltinPipelineSection
+ rawCategory={rawCategory}
+ searchString={debouncedSearchString}
+ showDivider={data.length > 0}
+ />
+ )}
</CardContainer>
- <footer className="mt-4 px-5 pb-5">
- <RAGFlowPagination
- {...pick(pagination, 'current', 'pageSize')}
- total={pagination.total}
- onChange={handlePageChange}
- />
- </footer>
+ {data.length > 0 && (
+ <footer className="mt-4 px-5 pb-5">
+ <RAGFlowPagination
+ {...pick(pagination, 'current', 'pageSize')}
+ total={pagination.total}
+ onChange={handlePageChange}
+ />
+ </footer>
+ )}
</>
- ) : searchString ? (
+ ) : emptyState === 'search-empty' ? (
<div className="flex-1 flex items-center justify-center">
<EmptyAppCard
showIcon
size="large"
className="w-[480px] p-14"
isSearch
+ testId="agents-search-empty"
type={EmptyCardType.Agent}
onClick={() => showCreatingModal()}
/>
</div>
- ) : listLoading ? null : (
+ ) : emptyState === 'loading' ? null : (
<div className="flex-1 flex items-center justify-center">
<EmptyAppCard
showIcon
diff --git a/web/src/pages/agents/use-copy-builtin-pipeline.test.tsx b/web/src/pages/agents/use-copy-builtin-pipeline.test.tsx
new file mode 100644
index 0000000000..6320492a04
--- /dev/null
+++ b/web/src/pages/agents/use-copy-builtin-pipeline.test.tsx
@@ -0,0 +1,122 @@
+import { renderHook } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { useCopyBuiltinPipeline } from './use-copy-builtin-pipeline';
+
+jest.mock('@/services/agent-service', () => ({
+ __esModule: true,
+ default: {
+ getBuiltinPipeline: jest.fn(),
+ createAgent: jest.fn(),
+ },
+}));
+
+// Mock the heavy agent-request module so its transitive react-router/routes
+// import (which needs browser globals not present under jest) is not loaded.
+// Only the query-key builders used for cache invalidation are needed here.
+jest.mock('@/hooks/use-agent-request', () => ({
+ AgentKeys: {
+ list: () => ['fetchAgentListByPage'],
+ filters: () => ['fetchAgentFilters'],
+ },
+}));
+
+jest.mock('@/components/ui/message', () => ({
+ __esModule: true,
+ default: {
+ success: jest.fn(),
+ error: jest.fn(),
+ },
+}));
+
+jest.mock('@/locales/config', () => ({
+ __esModule: true,
+ default: {
+ t: (key: string, opts?: { defaultValue?: string }) =>
+ opts?.defaultValue ?? key,
+ },
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const agentService = require('@/services/agent-service').default;
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const message = require('@/components/ui/message').default;
+
+const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={new QueryClient()}>
+ {children}
+ </QueryClientProvider>
+);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+describe('useCopyBuiltinPipeline', () => {
+ it('fetches the builtin DSL and creates a user-owned dataflow pipeline', async () => {
+ agentService.getBuiltinPipeline.mockResolvedValue({
+ data: { code: 0, message: 'ok', data: { dsl: { components: {} } } },
+ });
+ agentService.createAgent.mockResolvedValue({
+ data: { code: 0, message: 'ok', data: null },
+ });
+
+ const { result } = renderHook(() => useCopyBuiltinPipeline(), {
+ wrapper,
+ });
+ const ret = await result.current.copy({ id: 'general', title: 'General' });
+
+ expect(agentService.getBuiltinPipeline).toHaveBeenCalledWith('general');
+ expect(agentService.createAgent).toHaveBeenCalledWith({
+ title: 'General (Copy)',
+ dsl: { components: {} },
+ canvas_category: 'dataflow_canvas',
+ });
+ expect(message.success).toHaveBeenCalled();
+ expect(message.error).not.toHaveBeenCalled();
+ expect(ret).not.toBeNull();
+ });
+
+ it('shows an error and does not create when the builtin DSL is missing', async () => {
+ agentService.getBuiltinPipeline.mockResolvedValue({
+ data: { code: 0, message: 'ok', data: { dsl: undefined } },
+ });
+
+ const { result } = renderHook(() => useCopyBuiltinPipeline(), {
+ wrapper,
+ });
+ const ret = await result.current.copy({ id: 'general', title: 'General' });
+
+ expect(agentService.createAgent).not.toHaveBeenCalled();
+ expect(message.error).toHaveBeenCalled();
+ expect(ret).toBeNull();
+ });
+
+ it('shows an error when createAgent reports a failure code', async () => {
+ agentService.getBuiltinPipeline.mockResolvedValue({
+ data: { code: 0, message: 'ok', data: { dsl: { components: {} } } },
+ });
+ agentService.createAgent.mockResolvedValue({
+ data: { code: 1, message: 'boom', data: null },
+ });
+
+ const { result } = renderHook(() => useCopyBuiltinPipeline(), {
+ wrapper,
+ });
+ await result.current.copy({ id: 'general', title: 'General' });
+
+ expect(message.error).toHaveBeenCalledWith('boom');
+ expect(message.success).not.toHaveBeenCalled();
+ });
+
+ it('shows a request error when the fetch rejects', async () => {
+ agentService.getBuiltinPipeline.mockRejectedValue(new Error('network'));
+
+ const { result } = renderHook(() => useCopyBuiltinPipeline(), {
+ wrapper,
+ });
+ await result.current.copy({ id: 'general', title: 'General' });
+
+ expect(message.error).toHaveBeenCalled();
+ expect(agentService.createAgent).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/pages/agents/use-copy-builtin-pipeline.ts b/web/src/pages/agents/use-copy-builtin-pipeline.ts
new file mode 100644
index 0000000000..8a90019b9a
--- /dev/null
+++ b/web/src/pages/agents/use-copy-builtin-pipeline.ts
@@ -0,0 +1,52 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import message from '@/components/ui/message';
+import { AgentCategory } from '@/constants/agent';
+import { AgentKeys } from '@/hooks/use-agent-request';
+import agentService from '@/services/agent-service';
+import i18n from '@/locales/config';
+
+// useCopyBuiltinPipeline turns a read-only built-in pipeline into a user-owned
+// dataflow canvas. It fetches the built-in DSL via GET /api/v1/pipelines/:id
+// and creates a new user canvas with that DSL, mirroring useDuplicateAgent's
+// "fetch detail + create" flow but sourcing the DSL from the built-in registry.
+export function useCopyBuiltinPipeline() {
+ const queryClient = useQueryClient();
+ const { mutateAsync, isPending } = useMutation({
+ mutationFn: async ({ id, title }: { id: string; title: string }) => {
+ try {
+ // request (umi-request) resolves to the backend envelope
+ // { code, message, data }, so data here is that envelope.
+ const { data } = await agentService.getBuiltinPipeline(id);
+ const dsl = data?.data?.dsl;
+ if (!dsl) {
+ message.error(i18n.t('message.requestError'));
+ return null;
+ }
+
+ const { data: created } = await agentService.createAgent({
+ title: i18n.t('flow.copyOfAgentName', {
+ name: title,
+ defaultValue: `${title} (Copy)`,
+ }),
+ dsl,
+ canvas_category: AgentCategory.DataflowCanvas,
+ });
+
+ if (created?.code === 0) {
+ message.success(i18n.t('message.created'));
+ queryClient.invalidateQueries({ queryKey: AgentKeys.list() });
+ queryClient.invalidateQueries({ queryKey: AgentKeys.filters() });
+ return created;
+ }
+
+ message.error(created?.message ?? i18n.t('message.requestError'));
+ return null;
+ } catch {
+ message.error(i18n.t('message.requestError'));
+ return null;
+ }
+ },
+ });
+
+ return { copy: mutateAsync, copying: isPending };
+}