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: Split the agent list page into three separate tabs. (#21529)
balibabu71bf40b2ae52
diff --git a/internal/dao/user_canvas.go b/internal/dao/user_canvas.goindex c350573cf8..42ab7d958e 100644--- a/internal/dao/user_canvas.go+++ b/internal/dao/user_canvas.go@@ -284,13 +284,18 @@ type CategoryFilterItem struct {}// GetOwnerFilterByCanvasIDs aggregates permission-filtered canvases by owner.-func (dao *UserCanvasDAO) GetOwnerFilterByCanvasIDs(ctx context.Context, db *gorm.DB, canvasIDs []string) ([]*OwnerFilterItem, error) {+// A non-empty canvasCategory scopes the aggregation to that category.+func (dao *UserCanvasDAO) GetOwnerFilterByCanvasIDs(ctx context.Context, db *gorm.DB, canvasIDs []string, canvasCategory string) ([]*OwnerFilterItem, error) {if len(canvasIDs) == 0 {return nil, nil}var items []*OwnerFilterItem- err := db.WithContext(ctx).Model(&entity.UserCanvas{}).- Where("user_canvas.id IN ?", canvasIDs).+ q := db.WithContext(ctx).Model(&entity.UserCanvas{}).+ Where("user_canvas.id IN ?", canvasIDs)+ if canvasCategory != "" {+ q = q.Where("user_canvas.canvas_category = ?", canvasCategory)+ }+ err := q.Select("user_canvas.user_id AS id, user.nickname AS label, COUNT(user_canvas.id) AS count").Joins("LEFT JOIN user ON user_canvas.user_id = user.id").Group("user_canvas.user_id, user.nickname").diff --git a/internal/dao/user_canvas_test.go b/internal/dao/user_canvas_test.goindex e0c152df4b..2ce25453ae 100644--- a/internal/dao/user_canvas_test.go+++ b/internal/dao/user_canvas_test.go@@ -290,7 +290,7 @@ func TestUserCanvasDAOOwnerAndCategoryFilters(t *testing.T) {}visibleCanvasIDs := []string{"c1", "c2", "c3"}- owners, err := d.GetOwnerFilterByCanvasIDs(ctx, db, visibleCanvasIDs)+ owners, err := d.GetOwnerFilterByCanvasIDs(ctx, db, visibleCanvasIDs, "")if err != nil {t.Fatalf("GetOwnerFilterByCanvasIDs failed: %v", err)}@@ -327,6 +327,18 @@ func TestUserCanvasDAOOwnerAndCategoryFilters(t *testing.T) {if catByID["dataflow_canvas"] != 1 {t.Fatalf("dataflow_canvas count = %d, want 1", catByID["dataflow_canvas"])}++ // Scoped to dataflow_canvas, only c2 remains visible to the aggregation.+ scopedOwners, err := d.GetOwnerFilterByCanvasIDs(ctx, db, visibleCanvasIDs, "dataflow_canvas")+ if err != nil {+ t.Fatalf("GetOwnerFilterByCanvasIDs with category failed: %v", err)+ }+ if len(scopedOwners) != 1 {+ t.Fatalf("scoped owner filter rows = %d, want 1", len(scopedOwners))+ }+ if scopedOwners[0].ID != "user-1" || scopedOwners[0].Count != 1 {+ t.Fatalf("scoped owner = %+v, want user-1 with count 1", scopedOwners[0])+ }}// TestUserCanvasDAOKeywordSearchIncludesTags verifies that the keyworddiff --git a/internal/handler/agent.go b/internal/handler/agent.goindex 847d4166b4..f764dec694 100644--- a/internal/handler/agent.go+++ b/internal/handler/agent.go@@ -176,7 +176,7 @@ func (h *AgentHandler) ListAgents(c *gin.Context) {// GET /api/v1/agents?type=filter and expects// {filter: {owner, canvas_category}, total} instead of a canvas list.if c.Query("type") == "filter" {- filters, code, err := h.agentService.ListAgentFilters(c.Request.Context(), user.ID)+ filters, code, err := h.agentService.ListAgentFilters(c.Request.Context(), user.ID, strings.TrimSpace(c.Query("canvas_category")))if err != nil {common.ResponseWithCodeData(c, code, false, err.Error())returndiff --git a/internal/service/agent.go b/internal/service/agent.goindex bcf68f6307..3eb52daac2 100644--- a/internal/service/agent.go+++ b/internal/service/agent.go@@ -498,13 +498,19 @@ type AgentFiltersResponse struct {// ListAgentFilters returns the owner/category aggregations backing the// agents page filter bar. Mirrors the ?type=filter branch of Python-// agent_api.list_agents.-func (s *AgentService) ListAgentFilters(ctx context.Context, userID string) (*AgentFiltersResponse, common.ErrorCode, error) {+// agent_api.list_agents. A non-empty canvasCategory scopes the owner counts+// to one tab: canvas categories aggregate only that category's canvases,+// while CompilationTemplateGroupCategory reports the tenant's groups.+func (s *AgentService) ListAgentFilters(ctx context.Context, userID, canvasCategory string) (*AgentFiltersResponse, common.ErrorCode, error) {+ if canvasCategory == CompilationTemplateGroupCategory {+ return s.listCompilationGroupFilters(ctx, userID)+ }+canvasIDs, err := AccessibleCanvasIDs(ctx, permission.Subject{UserID: userID}, permission.OperationRead)if err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to scope accessible canvases: %w", err)}- owners, err := s.canvasDAO.GetOwnerFilterByCanvasIDs(ctx, dao.DB, canvasIDs)+ owners, err := s.canvasDAO.GetOwnerFilterByCanvasIDs(ctx, dao.DB, canvasIDs, canvasCategory)if err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to aggregate agent owners: %w", err)}@@ -512,9 +518,14 @@ func (s *AgentService) ListAgentFilters(ctx context.Context, userID string) (*Agif err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to aggregate agent categories: %w", err)}- groupCount, err := s.compilationTemplateGroupDAO.CountSavedByTenant(ctx, dao.DB, userID)- if err != nil {- return nil, common.CodeServerError, fmt.Errorf("failed to count compilation template groups: %w", err)+ // Compilation groups only belong in the unscoped aggregation; a scoped+ // canvas-category request never includes them.+ groupCount := int64(0)+ if canvasCategory == "" {+ groupCount, err = s.compilationTemplateGroupDAO.CountSavedByTenant(ctx, dao.DB, userID)+ if err != nil {+ return nil, common.CodeServerError, fmt.Errorf("failed to count compilation template groups: %w", err)+ }}ownerFilters := make([]AgentOwnerFilter, 0, len(owners)+1)@@ -563,6 +574,29 @@ func (s *AgentService) ListAgentFilters(ctx context.Context, userID string) (*Agreturn resp, common.CodeSuccess, nil}+// listCompilationGroupFilters reports the tenant's compilation template groups+// as the only owner/category option: groups are tenant-owned and carry neither+// canvas categories nor per-canvas owners.+func (s *AgentService) listCompilationGroupFilters(ctx context.Context, userID string) (*AgentFiltersResponse, common.ErrorCode, error) {+ groupCount, err := s.compilationTemplateGroupDAO.CountSavedByTenant(ctx, dao.DB, userID)+ if err != nil {+ return nil, common.CodeServerError, fmt.Errorf("failed to count compilation template groups: %w", err)+ }++ resp := &AgentFiltersResponse{Total: groupCount}+ resp.Filter.Owner = []AgentOwnerFilter{}+ resp.Filter.CanvasCategory = []AgentCategoryFilter{}+ if groupCount > 0 {+ nickname, nerr := s.userDAO.GetNicknameByID(ctx, dao.DB, userID)+ if nerr != nil {+ nickname = ""+ }+ resp.Filter.Owner = append(resp.Filter.Owner, AgentOwnerFilter{ID: userID, Label: nickname, Count: groupCount})+ resp.Filter.CanvasCategory = append(resp.Filter.CanvasCategory, AgentCategoryFilter{ID: CompilationTemplateGroupCategory, Count: groupCount})+ }+ return resp, common.CodeSuccess, nil+}+type AgentTagCount struct {Tag string `json:"tag"`Count int `json:"count"`diff --git a/web/src/components/compilation-template-form-field.tsx b/web/src/components/compilation-template-form-field.tsxindex 7b938bc048..7633d1d7a9 100644--- a/web/src/components/compilation-template-form-field.tsx+++ b/web/src/components/compilation-template-form-field.tsx@@ -38,6 +38,12 @@ export function CompilationTemplateFormField({const { options, isFetched, isError } =useCompilationTemplateGroupOptions(ownerTenantId);+ // Zero-arg wrapper: labelLink.onClick is wired to a DOM click, which would+ // feed the event into navigateToAgents' canvasCategory parameter.+ const handleCreateTemplateClick = useCallback(() => {+ navigateToAgents();+ }, [navigateToAgents]);+// No owner-scoped name lookup exists for template groups (strictly// owner-tenant, no sharing mechanism) — the raw id is all the missing// display can show. Styled like MissingModelLabel.@@ -57,7 +63,7 @@ export function CompilationTemplateFormField({label={t('knowledgeConfiguration.compilationTemplate')}labelLink={{text: t('knowledgeConfiguration.createTemplate'),- onClick: navigateToAgents,+ onClick: handleCreateTemplateClick,}}className="pb-4"horizontal={horizontal}diff --git a/web/src/components/pill-toggle-group.tsx b/web/src/components/pill-toggle-group.tsxnew file mode 100644index 0000000000..10e62c9d30--- /dev/null+++ b/web/src/components/pill-toggle-group.tsx@@ -0,0 +1,77 @@+/*+ * 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 { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';+import { LucideIcon } from 'lucide-react';+import { ReactNode, useCallback } from 'react';++export interface PillToggleGroupOption {+ value: string;+ label: ReactNode;+ icon?: LucideIcon;+}++// Single-select pill-style tab group built on the shared ToggleGroup. Unlike+// the default joined button bar, each option renders as a separate rounded+// pill with a border; the active pill uses the card background.+export function PillToggleGroup({+ options,+ value,+ onChange,+ className,+}: {+ options: PillToggleGroupOption[];+ value: string;+ onChange: (value: string) => void;+ className?: string;+}) {+ // Radix single-mode emits '' when the selected item is clicked again;+ // a tab group must keep a selection, so the empty value is dropped here.+ const handleValueChange = useCallback(+ (nextValue: string) => {+ if (nextValue) {+ onChange(nextValue);+ }+ },+ [onChange],+ );++ return (+ <ToggleGroup+ type="single"+ value={value}+ onValueChange={handleValueChange}+ className={className ?? 'gap-3'}+ >+ {options.map((option) => (+ <ToggleGroupItem+ key={option.value}+ value={option.value}+ className="flex-initial rounded-full border-0.5 border-border-default px-4 text-text-disabled first:rounded-l-full last:rounded-r-full hover:text-text-primary data-[state=on]:bg-bg-card data-[state=on]:text-text-primary"+ >+ {option.icon ? (+ <span className="flex items-center gap-1.5">+ <option.icon className="size-4" />+ {option.label}+ </span>+ ) : (+ option.label+ )}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ );+}diff --git a/web/src/constants/agent.tsx b/web/src/constants/agent.tsxindex 066b984da0..235df89365 100644--- a/web/src/constants/agent.tsx+++ b/web/src/constants/agent.tsx@@ -79,6 +79,7 @@ export enum AgentCategory {export enum AgentQuery {Category = 'category',+ CanvasCategory = 'canvas_category',}export enum Operator {diff --git a/web/src/hooks/__tests__/use-agent-list-by-page.test.tsx b/web/src/hooks/__tests__/use-agent-list-by-page.test.tsxnew file mode 100644index 0000000000..5a3d3ade11--- /dev/null+++ b/web/src/hooks/__tests__/use-agent-list-by-page.test.tsx@@ -0,0 +1,128 @@+/*+ * 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 { renderHook, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { MemoryRouter } from 'react-router';+import { AgentCategory } from '@/constants/agent';+import {+ useFetchAgentFilters,+ useFetchAgentListByPage,+} from '../use-agent-request';++jest.mock('@/services/agent-service', () => ({+ __esModule: true,+ default: {+ listAgents: jest.fn(),+ },+}));++// eslint-disable-next-line @typescript-eslint/no-var-requires+const agentService = require('@/services/agent-service').default;++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <MemoryRouter>+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ {children}+ </QueryClientProvider>+ </MemoryRouter>+);++beforeEach(() => {+ jest.clearAllMocks();+ agentService.listAgents.mockResolvedValue({+ data: { data: { canvas: [], total: 0 } },+ });+});++describe('useFetchAgentListByPage', () => {+ it('requests a single canvas_category for the active tab', async () => {+ renderHook(() => useFetchAgentListByPage(AgentCategory.DataflowCanvas), {+ wrapper,+ });++ await waitFor(() => expect(agentService.listAgents).toHaveBeenCalled());+ expect(agentService.listAgents).toHaveBeenCalledWith(+ {+ params: {+ page: 1,+ page_size: 50,+ canvas_category: AgentCategory.DataflowCanvas,+ },+ },+ true,+ );+ });++ it('requests the compilation template groups category', async () => {+ renderHook(() => useFetchAgentListByPage('compilation_template_group'), {+ wrapper,+ });++ await waitFor(() => expect(agentService.listAgents).toHaveBeenCalled());+ expect(+ agentService.listAgents.mock.calls[0][0].params.canvas_category,+ ).toBe('compilation_template_group');+ });++ it('keeps the home view unscoped when no category is given', async () => {+ renderHook(() => useFetchAgentListByPage(), { wrapper });++ await waitFor(() => expect(agentService.listAgents).toHaveBeenCalled());+ expect(agentService.listAgents.mock.calls[0][0].params).not.toHaveProperty(+ 'canvas_category',+ );+ });+});++describe('useFetchAgentFilters', () => {+ beforeEach(() => {+ agentService.listAgents.mockResolvedValue({+ data: { data: { filter: { owner: [], canvas_category: [] }, total: 0 } },+ });+ });++ it('passes the active tab category to the filter aggregation', async () => {+ renderHook(() => useFetchAgentFilters(AgentCategory.DataflowCanvas), {+ wrapper,+ });++ await waitFor(() => expect(agentService.listAgents).toHaveBeenCalled());+ expect(agentService.listAgents).toHaveBeenCalledWith(+ {+ params: {+ type: 'filter',+ canvas_category: AgentCategory.DataflowCanvas,+ },+ },+ true,+ );+ });++ it('requests the unscoped aggregation without a category', async () => {+ renderHook(() => useFetchAgentFilters(), { wrapper });++ await waitFor(() => expect(agentService.listAgents).toHaveBeenCalled());+ expect(agentService.listAgents).toHaveBeenCalledWith(+ { params: { type: 'filter' } },+ true,+ );+ });+});diff --git a/web/src/hooks/logic-hooks/navigate-hooks.ts b/web/src/hooks/logic-hooks/navigate-hooks.tsindex e2999f31ca..1f6fef5db6 100644--- a/web/src/hooks/logic-hooks/navigate-hooks.ts+++ b/web/src/hooks/logic-hooks/navigate-hooks.ts@@ -15,6 +15,7 @@*/import { AgentCategory, AgentQuery } from '@/constants/agent';+import { AgentListItemType } from '@/interfaces/database/agent';import { NavigateToDataflowResultProps } from '@/pages/dataflow-result/interface';import { Routes } from '@/routes';import { useCallback } from 'react';@@ -110,9 +111,19 @@ export const useNavigatePage = () => {[navigate],);- const navigateToAgents = useCallback(() => {- navigate(Routes.Agents);- }, [navigate]);+ // The agents list selects its tab from the canvas_category query param, so+ // callers back on a canvas page pass their own category to land on the+ // matching tab instead of the default workflow tab.+ const navigateToAgents = useCallback(+ (canvasCategory?: AgentCategory) => {+ navigate(+ canvasCategory+ ? `${Routes.Agents}?${AgentQuery.CanvasCategory}=${canvasCategory}`+ : Routes.Agents,+ );+ },+ [navigate],+ );const navigateToAgentList = useCallback(() => {navigate(Routes.AgentList);@@ -151,9 +162,29 @@ export const useNavigatePage = () => {[navigate],);- const navigateToAgentTemplates = useCallback(() => {- navigate(Routes.AgentTemplates);- }, [navigate]);+ const navigateToAgentTemplates = useCallback(+ (canvasCategory: string) => {+ const params = new URLSearchParams({+ [AgentQuery.CanvasCategory]: canvasCategory,+ });+ navigate(`${Routes.AgentTemplates}?${params.toString()}`);+ },+ [navigate],+ );++ const navigateToCompilationEditor = useCallback(+ (id?: string) => {+ const params = new URLSearchParams({+ source: 'agents',+ [AgentQuery.CanvasCategory]: AgentListItemType.CompilationTemplateGroup,+ });+ const path = id+ ? `${Routes.CompilationTemplatesEditNext}/${id}`+ : Routes.CompilationTemplatesEditNext;+ navigate(`${path}?${params.toString()}`);+ },+ [navigate],+ );const navigateToSearchList = useCallback(() => {navigate(Routes.Searches);@@ -263,6 +294,7 @@ export const useNavigatePage = () => {navigateToAgentExplore,navigateToAgentLogs,navigateToAgentTemplates,+ navigateToCompilationEditor,navigateToBuiltinPipeline,navigateToSearchList,navigateToSearch,diff --git a/web/src/hooks/use-agent-request.ts b/web/src/hooks/use-agent-request.tsindex 1fe2f442d0..285f832647 100644--- a/web/src/hooks/use-agent-request.ts+++ b/web/src/hooks/use-agent-request.ts@@ -22,6 +22,7 @@ import { ListDeletionKey } from '@/constants/list-deletion';import { useFetchTenantInfo } from '@/hooks/use-user-setting-request';import {AgentListItem,+ DSL,IAgentLogResponse,IAgentLogsRequest,IAgentLogsResponse,@@ -77,7 +78,8 @@ export const enum AgentApiAction {DeleteAgent = 'deleteAgent',FetchAgentDetail = 'fetchAgentDetail',ResetAgent = 'resetAgent',- SetAgent = 'setAgent',+ CreateAgent = 'createAgent',+ SaveAgent = 'saveAgent',FetchAgentTemplates = 'fetchAgentTemplates',UploadAgentFile = 'uploadAgentFile',UploadAgentFileWithProgress = 'uploadAgentFileWithProgress',@@ -109,6 +111,13 @@ export const enum AgentApiAction {FetchBuiltinPipelineDetail = 'fetchBuiltinPipelineDetail',}+// Invalidation rule for the list-page queries (list/filters/tags): they all+// use gcTime: 0 and refetch on mount, so invalidating them only matters while+// the agents list page is still mounted — i.e. from the list page's own+// mutations (delete, rename, tag edits, compilation group delete). Create and+// save flows navigate away or run on the canvas page, where these queries are+// inactive; invalidating them there only fires wasted refetches from the list+// page still mounted behind the create dialog.export const AgentKeys = {templates: () => [AgentApiAction.FetchAgentTemplates] as const,list: (params?: unknown) =>@@ -118,7 +127,10 @@ export const AgentKeys = {all: () => [AgentApiAction.FetchAllAgentList] as const,listAll: (canvasCategory?: string) =>[AgentApiAction.FetchAgentList, canvasCategory] as const,- filters: () => [AgentApiAction.FetchAgentFilters] as const,+ filters: (canvasCategory?: string) =>+ canvasCategory === undefined+ ? ([AgentApiAction.FetchAgentFilters] as const)+ : ([AgentApiAction.FetchAgentFilters, canvasCategory] as const),tags: (canvasCategory?: string) =>canvasCategory === undefined? ([AgentApiAction.FetchAgentTags] as const)@@ -149,14 +161,14 @@ const buildAgentListParams = ({page,pageSize,keywords,- canvasCategoryIds,+ canvasCategory,ownerIds,tags,}: {page: number;pageSize: number;keywords?: string;- canvasCategoryIds?: string[];+ canvasCategory?: string;ownerIds?: string[];tags?: string[];}) => {@@ -168,8 +180,8 @@ const buildAgentListParams = ({if (keywords) {params.keywords = keywords;}- if (Array.isArray(canvasCategoryIds) && canvasCategoryIds.length > 0) {- params.canvas_category = canvasCategoryIds.join(',');+ if (canvasCategory) {+ params.canvas_category = canvasCategory;}if (Array.isArray(ownerIds) && ownerIds.length > 0) {params.owner_ids = ownerIds.join(',');@@ -181,16 +193,13 @@ const buildAgentListParams = ({return params;};-export const useFetchAgentListByPage = () => {+export const useFetchAgentListByPage = (canvasCategory?: string) => {const { searchString, setSearchString, handleInputChange } =useHandleSearchChange();const { pagination, setPagination } = useGetPaginationWithRouter();const debouncedSearchString = useDebounce(searchString, { wait: 500 });const { filterValue, setFilterValue, handleFilterSubmit, checkValue } =useHandleFilterSubmit();- const canvasCategoryIds = Array.isArray(filterValue.canvasCategory)- ? (filterValue.canvasCategory as string[])- : undefined;const owner = filterValue.owner;const tags = Array.isArray(filterValue.tags) ? filterValue.tags : undefined;@@ -198,7 +207,7 @@ export const useFetchAgentListByPage = () => {page: pagination.current,pageSize: pagination.pageSize,keywords: debouncedSearchString,- canvasCategoryIds,+ canvasCategory,ownerIds: Array.isArray(owner) ? owner : undefined,tags,});@@ -210,6 +219,7 @@ export const useFetchAgentListByPage = () => {queryKey: AgentKeys.list({debouncedSearchString,...pagination,+ canvasCategory,filterValue,}),placeholderData: (previousData) => {@@ -265,7 +275,7 @@ export const fetchAllAgents = async (): Promise<AgentListItem[]> => {params: buildAgentListParams({page,pageSize: 100,- canvasCategoryIds: [AgentCategory.AgentCanvas],+ canvasCategory: AgentCategory.AgentCanvas,}),},true,@@ -319,62 +329,6 @@ export const useUpdateAgentSetting = () => {return { data, loading, updateAgentSetting: mutateAsync };};-export const useDuplicateAgent = () => {- const queryClient = useQueryClient();- const {- data,- isPending: loading,- mutateAsync,- } = useMutation({- mutationKey: [AgentApiAction.SetAgent, 'duplicate'],- mutationFn: async (agent: Pick<IFlow, 'id' | 'title'>) => {- try {- const { data: detail } = await agentService.getAgent(agent.id);- const source = detail?.data;- if (!source) {- message.error(i18n.t('message.requestError'));- return null;- }-- const sourceTitle = agent.title ?? source.title ?? '';- const { data } = await agentService.createAgent({- title: i18n.t('flow.copyOfAgentName', {- name: sourceTitle,- defaultValue: `${sourceTitle} (Copy)`,- }),- dsl: source.dsl,- avatar: source.avatar,- description: source.description,- canvas_category: source.canvas_category,- });-- if (data?.code === 0) {- message.success(i18n.t('message.created'));- queryClient.invalidateQueries({- queryKey: AgentKeys.list(),- });- queryClient.invalidateQueries({- queryKey: AgentKeys.filters(),- });- return data;- }-- message.error(data?.message ?? i18n.t('message.requestError'));- return null;- } catch (error) {- console.error('useDuplicateAgent failed:', error);- message.error(- (error as { message?: string })?.message ??- i18n.t('message.requestError'),- );- return null;- }- },- });-- return { data, loading, duplicateAgent: mutateAsync };-};-export const useDeleteAgent = () => {const queryClient = useQueryClient();const {@@ -517,9 +471,36 @@ export const useResetAgent = () => {return { data, loading, resetAgent: mutateAsync };};-export const useSetAgent = (+// Every create flow (blank, template, JSON import, built-in pipeline copy)+// navigates to the new canvas on success, and the list-page queries refetch on+// remount (gcTime: 0) — so creation intentionally invalidates nothing.+export const useCreateAgent = (showMessage: boolean = true) => {+ const {+ data,+ isPending: loading,+ mutateAsync,+ } = useMutation({+ mutationKey: [AgentApiAction.CreateAgent],+ mutationFn: async (params: {+ title?: string;+ dsl?: DSL | Record<string, any>;+ avatar?: string;+ canvas_category?: string;+ }) => {+ const { data = {} } = await agentService.createAgent(params);+ if (data.code === 0 && showMessage) {+ message.success(i18n.t('message.created'));+ }+ return data;+ },+ });++ return { data, loading, createAgent: mutateAsync };+};++export const useSaveAgent = (showMessage: boolean = true,- skipInvalidation: boolean = false,+ skipDetailRefresh: boolean = false,) => {const { id } = useParams();const queryClient = useQueryClient();@@ -528,13 +509,12 @@ export const useSetAgent = (isPending: loading,mutateAsync,} = useMutation({- mutationKey: [AgentApiAction.SetAgent],+ mutationKey: [AgentApiAction.SaveAgent],mutationFn: async (params: {id?: string;title?: string;- dsl?: Record<string, any>;- avatar?: string;- canvas_category?: string;+ dsl?: DSL | Record<string, any>;+ avatar?: string | null;release?: string;description?: string | null;permission?: string;@@ -542,41 +522,30 @@ export const useSetAgent = (alias?: string;}) => {const agentId = params.id ?? id;- const { data = {} } = agentId- ? await updateAgent(agentId, {- title: params.title,- dsl: params.dsl,- avatar: params.avatar,- description: params.description,- permission: params.permission,- release: params.release,- autosave: params.autosave,- alias: params.alias,- })- : await agentService.createAgent(params);+ if (!agentId) {+ return {};+ }+ const { data = {} } = await updateAgent(agentId, {+ title: params.title,+ dsl: params.dsl,+ avatar: params.avatar,+ description: params.description,+ permission: params.permission,+ release: params.release,+ autosave: params.autosave,+ alias: params.alias,+ });if (data.code === 0) {if (showMessage) {- message.success(- i18n.t(`message.${agentId ? 'modified' : 'created'}`),- );+ message.success(i18n.t('message.modified'));}- queryClient.invalidateQueries({- queryKey: AgentKeys.list(),- });// Every save can prune the oldest unpublished versions server-side,// so the version history list must refetch even when autosave skips- // detail invalidation.- if (agentId) {- queryClient.invalidateQueries({- queryKey: AgentKeys.versionList(agentId),- });- }- if (!agentId) {- queryClient.invalidateQueries({- queryKey: AgentKeys.filters(),- });- }- if (agentId && !skipInvalidation) {+ // the detail refresh.+ queryClient.invalidateQueries({+ queryKey: AgentKeys.versionList(agentId),+ });+ if (!skipDetailRefresh) {queryClient.invalidateQueries({queryKey: AgentKeys.detail(agentId),});@@ -586,7 +555,7 @@ export const useSetAgent = (},});- return { data, loading, setAgent: mutateAsync };+ return { data, loading, saveAgent: mutateAsync };};// Only one file can be uploaded at a time@@ -1143,7 +1112,7 @@ export interface IAgentCategoryFilter {count: number;}-export const useFetchAgentFilters = () => {+export const useFetchAgentFilters = (canvasCategory?: string) => {const { data, isFetching: loading } = useQuery<{filter: {owner: IAgentOwnerFilter[];@@ -1151,12 +1120,17 @@ export const useFetchAgentFilters = () => {};total: number;}>({- queryKey: AgentKeys.filters(),+ queryKey: AgentKeys.filters(canvasCategory),initialData: { filter: { owner: [], canvas_category: [] }, total: 0 },gcTime: 0,queryFn: async () => {const { data } = await agentService.listAgents(- { params: { type: 'filter' } },+ {+ params: {+ type: 'filter',+ ...(canvasCategory ? { canvas_category: canvasCategory } : {}),+ },+ },true,);return (diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex b1a080b263..9ee34c98ef 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -3391,6 +3391,8 @@ Best for: Documents with flowing, contextually connected content — such as boocontentTip: 'content: Email content (Optional)',jsonUploadTypeErrorMessage: 'Please upload json file',jsonUploadContentErrorMessage: 'json file error',+ jsonUploadCategoryMismatch:+ 'The JSON file type does not match the current tab. Please switch to the corresponding tab and import again.',nameExists: 'Name already exists',iteration: 'Iteration',iterationDescription: `A looping component that iterates over an input array and executes a defined logic for each item.`,@@ -3597,18 +3599,17 @@ This process aggregates variables from multiple branches into a single variablecreateFromBlank: 'Create from blank',createFromTemplate: 'Create from template',importJsonFile: 'Import JSON file',- duplicate: 'Duplicate',copyOfAgentName: '{{name}} (copy)',ceateAgent: 'Workflow',createPipeline: 'Ingestion pipeline',createIngestionPipeline: 'Create ingestion pipeline',createWorkflow: 'Create workflow',+ createCompilationOperator: 'Create compilation operator',tabList: {ingestionPipeline: 'Ingestion pipeline',compilationOperator: 'Compilation operator',workflow: 'Workflow',},- chooseAgentType: 'Choose agent type',parser: 'Parser',parserDescription:'Extracts raw text and structure from files for downstream processing.',diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.tsindex a5ac3631fd..7980a62550 100644--- a/web/src/locales/zh.ts+++ b/web/src/locales/zh.ts@@ -2983,6 +2983,8 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 RcontentTip: 'content: 邮件内容(可选)',jsonUploadTypeErrorMessage: '请上传 json 文件',jsonUploadContentErrorMessage: 'json 文件错误',+ jsonUploadCategoryMismatch:+ 'JSON 文件类型与当前分类不符,请切换到对应分类后再导入',nameExists: '名称已存在',iteration: '迭代',iterationDescription: `该组件负责迭代生成新的内容,对列表对象执行多次步骤直至输出所有结果。`,@@ -3115,12 +3117,11 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 RcreateFromBlank: '从空白创建',createFromTemplate: '从模板创建',importJsonFile: '导入 JSON 文件',- duplicate: '复制',copyOfAgentName: '{{name}} (副本)',- chooseAgentType: '选择智能体类型',createPipeline: '数据管道',createIngestionPipeline: '创建数据管道',createWorkflow: '创建工作流',+ createCompilationOperator: '创建编译算子',tabList: {ingestionPipeline: '数据管道',compilationOperator: '编译算子',diff --git a/web/src/pages/agent/hooks/use-run-preflight.test.ts b/web/src/pages/agent/hooks/use-run-preflight.test.tsindex 59ea3291bd..c2867453be 100644--- a/web/src/pages/agent/hooks/use-run-preflight.test.ts+++ b/web/src/pages/agent/hooks/use-run-preflight.test.ts@@ -7,7 +7,7 @@ import {useSaveGraphBeforeOpeningDebugDrawer,} from './use-save-graph';-const mockSetAgent = jest.fn();+const mockSaveAgent = jest.fn();const mockResetAgent = jest.fn();const mockBuildDslData = jest.fn();@@ -21,7 +21,7 @@ jest.mock('@/components/model-tree-select', () => ({jest.mock('@/hooks/use-agent-request', () => ({useFetchAgent: () => ({ data: { title: 'Draft' } }),- useSetAgent: () => ({ setAgent: mockSetAgent, loading: false }),+ useSaveAgent: () => ({ saveAgent: mockSaveAgent, loading: false }),useResetAgent: () => ({ resetAgent: mockResetAgent }),}));jest.mock('./use-build-dsl', () => ({@@ -51,7 +51,7 @@ const node = (label: string, form: Record<string, unknown>) =>describe('Run preflight', () => {beforeEach(() => {jest.clearAllMocks();- mockSetAgent.mockResolvedValue({ code: 0 });+ mockSaveAgent.mockResolvedValue({ code: 0 });mockResetAgent.mockResolvedValue({ code: 0 });useGraphStore.setState({ nodes: [], edges: [], editedNodeFormIds: [] });});@@ -77,7 +77,7 @@ describe('Run preflight', () => {expect(message.error).toHaveBeenCalledWith('Future block: future.emptyEntry',);- expect(mockSetAgent).not.toHaveBeenCalled();+ expect(mockSaveAgent).not.toHaveBeenCalled();expect(mockResetAgent).not.toHaveBeenCalled();expect(show).not.toHaveBeenCalled();});@@ -112,7 +112,7 @@ describe('Run preflight', () => {await result.current.handleRun();});expect(message.error).not.toHaveBeenCalled();- expect(mockSetAgent).toHaveBeenCalled();+ expect(mockSaveAgent).toHaveBeenCalled();expect(mockResetAgent).toHaveBeenCalled();expect(show).toHaveBeenCalledTimes(1);});@@ -140,7 +140,7 @@ describe('Run preflight', () => {await act(async () => {await result.current.saveGraph();});- expect(mockSetAgent).toHaveBeenCalled();+ expect(mockSaveAgent).toHaveBeenCalled();expect(message.error).not.toHaveBeenCalled();});diff --git a/web/src/pages/agent/hooks/use-save-graph.ts b/web/src/pages/agent/hooks/use-save-graph.tsindex 635af9e0e1..2bdf0cd36c 100644--- a/web/src/pages/agent/hooks/use-save-graph.ts+++ b/web/src/pages/agent/hooks/use-save-graph.ts@@ -5,7 +5,7 @@ import { Operator } from '../constant';import {useFetchAgent,useResetAgent,- useSetAgent,+ useSaveAgent,} from '@/hooks/use-agent-request';import {GlobalVariableType,@@ -22,10 +22,10 @@ import { useBuildDslData } from './use-build-dsl';export const useSaveGraph = (showMessage: boolean = true,- skipInvalidation: boolean = false,+ skipDetailRefresh: boolean = false,) => {const { data } = useFetchAgent();- const { setAgent, loading } = useSetAgent(showMessage, skipInvalidation);+ const { saveAgent, loading } = useSaveAgent(showMessage, skipDetailRefresh);const { id } = useParams();const { buildDslData } = useBuildDslData();@@ -59,9 +59,9 @@ export const useSaveGraph = (params.autosave = true;}- return setAgent(params);+ return saveAgent(params);},- [id, data.title, buildDslData, setAgent],+ [id, data.title, buildDslData, saveAgent],);return { saveGraph, loading };diff --git a/web/src/pages/agent/index.tsx b/web/src/pages/agent/index.tsxindex bd487b2a71..1c0868bcac 100644--- a/web/src/pages/agent/index.tsx+++ b/web/src/pages/agent/index.tsx@@ -21,10 +21,11 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import message from '@/components/ui/message';+import { AgentCategory } from '@/constants/agent';import { SharedFrom } from '@/constants/chat';import { useSetModalState } from '@/hooks/common-hooks';import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';-import { useSetAgent } from '@/hooks/use-agent-request';+import { useSaveAgent } from '@/hooks/use-agent-request';import { ReactFlowProvider } from '@xyflow/react';import {ChevronDown,@@ -118,6 +119,13 @@ export default function Agent() {const handleSave = useCallback(() => {saveGraph();}, [saveGraph]);+ // Back-link lands on the agents list tab matching this canvas: ingestion+ // pipeline canvases return to the pipeline tab, agent canvases to workflow.+ const handleBackToAgents = useCallback(() => {+ navigateToAgents(+ isPipeline ? AgentCategory.DataflowCanvas : AgentCategory.AgentCanvas,+ );+ }, [isPipeline, navigateToAgents]);const { flowDetail: agentDetail } = useFetchDataOnMount();// The checklist displays all issues; Run separately checks blocking rules.const { issues } = useCanvasChecklist({@@ -125,7 +133,7 @@ export default function Agent() {canvasID: id,});const { buildDslData } = useBuildDslData();- const { setAgent, loading: savingWidgetSettings } = useSetAgent(false);+ const { saveAgent, loading: savingWidgetSettings } = useSaveAgent(false);const { handleRun } = useSaveGraphBeforeOpeningDebugDrawer(showChatDrawer);const {visible: versionDialogVisible,@@ -273,7 +281,7 @@ export default function Agent() {async (widgetSettings: WidgetSettings) => {const dsl = buildDslData();- return setAgent({+ return saveAgent({id: id!,title: agentDetail.title,dsl: {@@ -285,7 +293,7 @@ export default function Agent() {},});},- [agentDetail.title, buildDslData, id, setAgent],+ [agentDetail.title, buildDslData, id, saveAgent],);return (@@ -295,7 +303,7 @@ export default function Agent() {<Breadcrumb><BreadcrumbList><BreadcrumbItem>- <BreadcrumbLink onClick={navigateToAgents}>+ <BreadcrumbLink onClick={handleBackToAgents}>{t('header.flow')}</BreadcrumbLink></BreadcrumbItem>diff --git a/web/src/pages/agent/setting-dialog/index.tsx b/web/src/pages/agent/setting-dialog/index.tsxindex c09255868f..18ecc7bd5e 100644--- a/web/src/pages/agent/setting-dialog/index.tsx+++ b/web/src/pages/agent/setting-dialog/index.tsx@@ -6,7 +6,7 @@ import {DialogHeader,DialogTitle,} from '@/components/ui/dialog';-import { useSetAgent } from '@/hooks/use-agent-request';+import { useSaveAgent } from '@/hooks/use-agent-request';import { IModalProps } from '@/interfaces/common';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -18,16 +18,16 @@ import {export function SettingDialog({ hideModal }: IModalProps<any>) {const { t } = useTranslation();- const { setAgent } = useSetAgent();+ const { saveAgent } = useSaveAgent();const submit = useCallback(async (values: SettingFormSchemaType) => {- const ret = await setAgent(values);+ const ret = await saveAgent(values);if (ret?.code === 0) {hideModal?.();}},- [hideModal, setAgent],+ [hideModal, saveAgent],);return (diff --git a/web/src/pages/agent/version-dialog/index.test.tsx b/web/src/pages/agent/version-dialog/index.test.tsxindex 6ac46f8809..225e0e5a6d 100644--- a/web/src/pages/agent/version-dialog/index.test.tsx+++ b/web/src/pages/agent/version-dialog/index.test.tsx@@ -15,7 +15,6 @@*/import { fireEvent, render, screen } from '@testing-library/react';-import React from 'react';jest.mock('react-i18next', () => {const actual = jest.requireActual('react-i18next');@@ -68,6 +67,7 @@ jest.mock('@/hooks/use-agent-request', () => ({loading: false,isError: false,}),+ useSaveAgent: () => ({ saveAgent: jest.fn(), loading: false }),useApplyVersion: () => ({ applyVersion: jest.fn(), loading: false }),useUpdateVersion: () => ({updateVersion: mockUpdateVersion,diff --git a/web/src/pages/agent/version-dialog/index.tsx b/web/src/pages/agent/version-dialog/index.tsxindex c4285c0c9e..665059a2fa 100644--- a/web/src/pages/agent/version-dialog/index.tsx+++ b/web/src/pages/agent/version-dialog/index.tsx@@ -28,6 +28,7 @@ import {useDeleteVersion,useFetchVersion,useFetchVersionList,+ useSaveAgent,useUpdateVersion,} from '@/hooks/use-agent-request';import { IModalProps } from '@/interfaces/common';@@ -59,14 +60,10 @@ type PendingAction =// keystrokes the way an uncontrolled defaultValue input with a volatile key could.const AliasInput = ({placeholder,- versionId,- canvasId,initialAlias,onCommit,}: {placeholder: string;- versionId: string;- canvasId: string;initialAlias: string;onCommit: (alias: string) => void;}) => {@@ -103,7 +100,8 @@ export function VersionDialog({const [pending, setPending] = useState<PendingAction>(null);const { deleteVersion, loading: deleting } = useDeleteVersion();- const { applyVersion, loading: restoring } = useApplyVersion();+ const { saveAgent, loading: restoring } = useSaveAgent(false);+ const { applyVersion, loading: applyRestoring } = useApplyVersion();const { updateVersion } = useUpdateVersion();// Backend returns the list newest-first (design section 7/E1); the first@@ -146,6 +144,12 @@ export function VersionDialog({});if (ok && selectedId === pending.versionId) setSelectedId('');} else if (pending.kind === 'restore') {+ await saveAgent({+ id: canvasId,+ dsl: agent?.dsl,+ title: agent?.title,+ });+const ok = await applyVersion({canvasId,versionId: pending.versionId,@@ -153,7 +157,15 @@ export function VersionDialog({if (ok) hideModal?.();}setPending(null);- }, [pending, canvasId, deleteVersion, selectedId, applyVersion, hideModal]);+ }, [+ pending,+ canvasId,+ deleteVersion,+ selectedId,+ saveAgent,+ agent?.dsl,+ agent?.title,+ ]);// Keep the current selection across list refreshes; only fall back to the// newest version when the selected one was pruned server-side.@@ -214,8 +226,6 @@ export function VersionDialog({so re-renders never wipe in-progress keystrokes. */}<AliasInputplaceholder={t('flow.version.alias')}- versionId={x.id}- canvasId={canvasId ?? ''}initialAlias={x.alias ?? ''}onCommit={(alias) =>updateVersion({@@ -292,7 +302,10 @@ export function VersionDialog({}title={t('flow.version.restore')}disabled={- selectedId === latestId || !selectedId || restoring+ selectedId === latestId ||+ !selectedId ||+ restoring ||+ applyRestoring}><RotateCcw />diff --git a/web/src/pages/agents/agent-create-actions.tsx b/web/src/pages/agents/agent-create-actions.tsxnew file mode 100644index 0000000000..de9b7e37a6--- /dev/null+++ b/web/src/pages/agents/agent-create-actions.tsx@@ -0,0 +1,94 @@+/*+ * 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 { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { Plus } from 'lucide-react';+import { AgentCreateAction } from './hooks/use-agent-create-actions';++export function AgentCreateMenu({+ actions,+ directOnClick,+}: {+ actions: AgentCreateAction[];+ // Compilation has no template/import entries, so its + button skips the+ // dropdown and creates directly.+ directOnClick?: () => void;+}) {+ if (directOnClick) {+ return (+ <Button data-testid="create-agent" onClick={directOnClick}>+ <Plus className="size-[1em]" />+ </Button>+ );+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger data-testid="create-agent" asChild>+ <Button>+ <Plus className="size-[1em]" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent data-testid="agent-create-menu">+ {actions.map((action) => (+ <DropdownMenuItem+ key={action.key}+ data-testid={action.testId}+ justifyBetween={false}+ onClick={action.onClick}+ >+ <action.icon />+ {action.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++// The non-search empty card exposes the same per-tab create actions as the ++// dropdown, rendered as plain buttons.+export function AgentsEmptyStateActions({+ actions,+}: {+ actions: AgentCreateAction[];+}) {+ return (+ <ul className="flex flex-col gap-y-5 text-text-secondary text-sm pt-5">+ {actions.map((action) => (+ <li key={action.key}>+ <Button+ variant="static"+ size="auto"+ data-testid={+ action.key === 'blank' ? 'agents-empty-create' : undefined+ }+ onClick={action.onClick}+ >+ <action.icon className="size-[1em]" />+ {action.label}+ </Button>+ </li>+ ))}+ </ul>+ );+}diff --git a/web/src/pages/agents/agent-log-page.tsx b/web/src/pages/agents/agent-log-page.tsxindex 7d48ec7a1b..a575a13abf 100644--- a/web/src/pages/agents/agent-log-page.tsx+++ b/web/src/pages/agents/agent-log-page.tsx@@ -50,6 +50,11 @@ const getEndOfToday = (): Date => {const AgentLogPage: React.FC = () => {const { t } = useTranslation();const { navigateToAgents, navigateToAgent } = useNavigatePage();+ // Zero-arg wrapper: passing navigateToAgents straight to onClick would feed+ // the click event into its canvasCategory parameter.+ const handleBackToAgents = useCallback(() => {+ navigateToAgents();+ }, [navigateToAgents]);const { flowDetail: agentDetail } = useFetchDataOnMount();const { id: canvasId } = useParams();const init = {@@ -252,7 +257,7 @@ const AgentLogPage: React.FC = () => {<Breadcrumb><BreadcrumbList><BreadcrumbItem>- <BreadcrumbLink onClick={navigateToAgents}>+ <BreadcrumbLink onClick={handleBackToAgents}>{t('flow.agent')}</BreadcrumbLink></BreadcrumbItem>diff --git a/web/src/pages/agents/agent-tab-group.tsx b/web/src/pages/agents/agent-tab-group.tsxnew file mode 100644index 0000000000..bf1bbbb70d--- /dev/null+++ b/web/src/pages/agents/agent-tab-group.tsx@@ -0,0 +1,53 @@+/*+ * 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 { PillToggleGroup } from '@/components/pill-toggle-group';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { AgentTabCategory, AgentTabs, FlowTypeConfig } from './constant';++// The Compilation / Pipeline / Workflow tab group at the top of the agents+// list, driven by the canvas_category URL param.+export function AgentTabGroup({+ activeCategory,+ onTabChange,+}: {+ activeCategory: AgentTabCategory;+ onTabChange: (value: string) => void;+}) {+ const { t } = useTranslation();++ const tabOptions = useMemo(+ () =>+ AgentTabs.map((flowType) => {+ const config = FlowTypeConfig[flowType];+ return {+ value: config.canvasCategory,+ label: t(`flow.${config.labelKey}`),+ icon: config.icon,+ };+ }),+ [t],+ );++ return (+ <PillToggleGroup+ options={tabOptions}+ value={activeCategory}+ onChange={onTabChange}+ />+ );+}diff --git a/web/src/pages/agents/agent-templates.test.tsx b/web/src/pages/agents/agent-templates.test.tsxnew file mode 100644index 0000000000..5d08ec18bb--- /dev/null+++ b/web/src/pages/agents/agent-templates.test.tsx@@ -0,0 +1,122 @@+/*+ * 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 { fireEvent, render, screen } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { MemoryRouter } from 'react-router';+import AgentTemplates from './agent-templates';++const mockCreateAgent = jest.fn();+const mockNavigateToAgent = jest.fn(() => jest.fn());++jest.mock('@/hooks/use-agent-request', () => ({+ useFetchAgentTemplates: jest.fn(),+ useCreateAgent: () => ({ loading: false, createAgent: mockCreateAgent }),+}));++jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({+ useNavigatePage: () => ({ navigateToAgent: mockNavigateToAgent }),+}));++// The dialog path is covered by create-agent-dialog tests; stub it so these+// tests stay focused on template scoping.+jest.mock('./create-agent-dialog', () => ({+ CreateAgentDialog: () => null,+}));++// eslint-disable-next-line @typescript-eslint/no-var-requires+const agentRequest = jest.requireMock('@/hooks/use-agent-request');++function makeTemplate(id: string, canvasType: string, canvasCategory?: string) {+ return {+ id,+ avatar: '',+ canvas_type: canvasType,+ canvas_category: canvasCategory,+ create_date: '',+ create_time: 0,+ update_date: '',+ update_time: 0,+ dsl: { graph: { nodes: [], edges: [] }, components: {}, history: [] },+ title: { en: id, zh: id, de: id },+ description: { en: `${id} description`, zh: '', de: '' },+ };+}++const templates = [+ makeTemplate('agent-recommended', 'Recommended'),+ makeTemplate('agent-marketing', 'Marketing'),+ makeTemplate('agent-uncategorized', 'Marketing', undefined),+ makeTemplate('pipeline-general', 'Ingestion Pipeline', 'dataflow_canvas'),+];++function renderTemplates(initialEntry = '/agent-templates') {+ return render(+ <MemoryRouter initialEntries={[initialEntry]}>+ <QueryClientProvider client={new QueryClient()}>+ <AgentTemplates />+ </QueryClientProvider>+ </MemoryRouter>,+ );+}++beforeEach(() => {+ jest.clearAllMocks();+ agentRequest.useFetchAgentTemplates.mockReturnValue(templates);+});++describe('AgentTemplates source scoping', () => {+ it('defaults to the Workflow catalog on the Recommended theme', () => {+ renderTemplates();++ expect(screen.getByText('agent-recommended')).toBeInTheDocument();+ // A template without canvas_category is treated as a workflow template.+ expect(screen.queryByText('pipeline-general')).toBeNull();+ });++ it('shows only pipeline templates without a sidebar on the Pipeline source', () => {+ renderTemplates('/agent-templates?canvas_category=dataflow_canvas');++ expect(screen.getByText('pipeline-general')).toBeInTheDocument();+ expect(screen.queryByText('agent-recommended')).toBeNull();+ expect(screen.queryByText('agent-marketing')).toBeNull();+ // The pipeline catalog has no theme breakdown, so the sidebar is hidden.+ expect(screen.queryByText('Recommended')).toBeNull();+ });++ it('treats a missing canvas_category as a workflow template', () => {+ renderTemplates('/agent-templates');++ // agent-uncategorized is a Marketing theme without canvas_category; it is+ // scoped to Workflow but hidden until the Marketing theme is selected.+ fireEvent.click(screen.getByText('Marketing'));+ expect(screen.getByText('agent-uncategorized')).toBeInTheDocument();+ expect(screen.queryByText('pipeline-general')).toBeNull();+ });++ it('keeps pipeline templates out of the workflow themes', () => {+ renderTemplates('/agent-templates');++ fireEvent.click(screen.getByText('Other'));+ expect(screen.queryByText('pipeline-general')).toBeNull();+ });++ it('renders the theme sidebar for the Workflow source', () => {+ renderTemplates('/agent-templates');+ expect(screen.getByText('Recommended')).toBeInTheDocument();+ expect(screen.getByText('Marketing')).toBeInTheDocument();+ });+});diff --git a/web/src/pages/agents/agent-templates.tsx b/web/src/pages/agents/agent-templates.tsxindex 14d5c71fa3..dee47613a3 100644--- a/web/src/pages/agents/agent-templates.tsx+++ b/web/src/pages/agents/agent-templates.tsx@@ -1,11 +1,16 @@import { useSetModalState } from '@/hooks/common-hooks';import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';-import { useFetchAgentTemplates, useSetAgent } from '@/hooks/use-agent-request';+import {+ useFetchAgentTemplates,+ useCreateAgent,+} from '@/hooks/use-agent-request';import { CardContainer } from '@/components/card-container';-import { AgentCategory } from '@/constants/agent';-import { IFlowTemplate } from '@/interfaces/database/agent';+import { AgentCategory, AgentQuery } from '@/constants/agent';+import { DSL, IFlowTemplate } from '@/interfaces/database/agent';import { useCallback, useEffect, useMemo, useState } from 'react';+import { useSearchParams } from 'react-router';+import { CanvasCategoryToFlowType } from './constant';import { CreateAgentDialog } from './create-agent-dialog';import { TemplateCard } from './template-card';import {@@ -15,14 +20,36 @@ import {} from './template-retrieval-binding';import { MenuItemKey, SideBar } from './template-sidebar';+function resolveSourceCategory(value: string | null): AgentCategory {+ return value === AgentCategory.DataflowCanvas+ ? AgentCategory.DataflowCanvas+ : AgentCategory.AgentCanvas;+}++function normalizeTemplateCategory(template: IFlowTemplate): AgentCategory {+ return template.canvas_category === AgentCategory.DataflowCanvas+ ? AgentCategory.DataflowCanvas+ : AgentCategory.AgentCanvas;+}+export default function AgentTemplates() {const list = useFetchAgentTemplates();- const { loading, setAgent } = useSetAgent();+ const { loading, createAgent } = useCreateAgent();+ const [searchParams] = useSearchParams();+ // canvas_category is the source tab; canvas_type(s) remain the secondary+ // theme filter rendered by the sidebar.+ const sourceCategory = resolveSourceCategory(+ searchParams.get(AgentQuery.CanvasCategory),+ );const [templateList, setTemplateList] = useState<IFlowTemplate[]>([]);const [selectMenuItem, setSelectMenuItem] = useState<string>(MenuItemKey.Recommended,);+ // The Pipeline catalog has no theme breakdown, so it renders without the+ // sidebar; the theme filter only applies to Workflow templates.+ const showSidebar = sourceCategory === AgentCategory.AgentCanvas;+useEffect(() => {setTemplateList(list);}, [list]);@@ -48,7 +75,9 @@ export default function AgentTemplates() {const handleOk = useCallback(async (payload: any) => {const dsl = template?.dsl;- const canvasCategory = template?.canvas_category;+ const canvasCategory = template+ ? normalizeTemplateCategory(template)+ : AgentCategory.AgentCanvas;const memoryIds: string[] = payload?.memory_ids ?? [];const modelId: string = payload?.llm_id ?? '';const datasetBlocks = collectUnboundRetrievalBindings(dsl).datasetBlocks;@@ -60,7 +89,7 @@ export default function AgentTemplates() {: (payload?.dataset_bindings?.[index] ?? []),]),);- let boundDsl =+ let boundDsl: DSL | Record<string, any> | undefined =dsl &&(Object.values(datasetBindings).some((ids) => ids.length > 0) ||memoryIds.length > 0)@@ -68,7 +97,7 @@ export default function AgentTemplates() {: dsl;boundDsl = bindUnboundModel(boundDsl, modelId);- const ret = await setAgent({+ const ret = await createAgent({title: payload.name,dsl: boundDsl,avatar: template?.avatar,@@ -84,25 +113,21 @@ export default function AgentTemplates() {}}},- [- hideCreatingModal,- navigateToAgent,- setAgent,- template?.avatar,- template?.canvas_category,- template?.dsl,- ],+ [hideCreatingModal, navigateToAgent, createAgent, template],);const handleSiderBarChange = (keyword: string) => {setSelectMenuItem(keyword);};const tempListFilter = useMemo(() => {- if (!selectMenuItem) {- return templateList;+ const scoped = templateList.filter(+ (item) => normalizeTemplateCategory(item) === sourceCategory,+ );+ if (!showSidebar || !selectMenuItem) {+ return scoped;}const selectedCanvasType = selectMenuItem.toLocaleLowerCase();- return templateList.filter((item) => {+ return scoped.filter((item) => {if (Array.isArray(item.canvas_types) && item.canvas_types.length > 0) {return item.canvas_types.some((canvasType) =>@@ -112,15 +137,17 @@ export default function AgentTemplates() {}return item.canvas_type?.toLocaleLowerCase() === selectedCanvasType;});- }, [selectMenuItem, templateList]);+ }, [selectMenuItem, templateList, sourceCategory, showSidebar]);return (<section><div className="flex flex-1 h-dvh">- <SideBar- change={handleSiderBarChange}- selected={selectMenuItem}- ></SideBar>+ {showSidebar && (+ <SideBar+ change={handleSiderBarChange}+ selected={selectMenuItem}+ ></SideBar>+ )}<main className="flex-1 bg-text-title-invert/50 h-dvh"><CardContainer className="max-h-[94vh] overflow-auto px-8 pt-8">@@ -139,7 +166,13 @@ export default function AgentTemplates() {loading={loading}visible={creatingVisible}hideModal={hideCreatingModal}- canvasCategory={template?.canvas_category as AgentCategory}+ selectedType={+ CanvasCategoryToFlowType[+ template+ ? normalizeTemplateCategory(template)+ : sourceCategory+ ]+ }template={template}onOk={handleOk}></CreateAgentDialog>diff --git a/web/src/pages/agents/builtin-catalog-probe.tsx b/web/src/pages/agents/builtin-catalog-probe.tsxindex 39130a0f74..ce65e9b3b3 100644--- a/web/src/pages/agents/builtin-catalog-probe.tsx+++ b/web/src/pages/agents/builtin-catalog-probe.tsx@@ -3,19 +3,19 @@ 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).+// re-deriving the filtering logic. Mounted only for the Pipeline tab, so the+// catalog request stays gated on that view (React Query dedupes it with the+// section's own call).export function BuiltinCatalogProbe({- rawCategory,+ canvasCategory,searchString,onReport,}: {- rawCategory?: string | string[] | Record<string, string[]>;+ canvasCategory: string;searchString?: string;onReport: (state: { length: number; loading: boolean }) => void;}) {- const { items, loading } = useBuiltinItems(rawCategory, searchString);+ const { items, loading } = useBuiltinItems(canvasCategory, searchString);useEffect(() => {onReport({ length: items.length, loading });diff --git a/web/src/pages/agents/builtin-pipeline-list.test.ts b/web/src/pages/agents/builtin-pipeline-list.test.tsindex 33f8347e31..4a8ae45241 100644--- a/web/src/pages/agents/builtin-pipeline-list.test.ts+++ b/web/src/pages/agents/builtin-pipeline-list.test.ts@@ -1,5 +1,5 @@import {- shouldShowBuiltinForRaw,+ shouldShowBuiltinForCategory,filterBuiltinByKeyword,toBuiltinListItem,resolveAgentsEmptyState,@@ -32,62 +32,20 @@ const sample = [},];-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);+describe('shouldShowBuiltinForCategory', () => {+ it('shows builtin in the Pipeline (dataflow) tab', () => {+ expect(shouldShowBuiltinForCategory(AgentCategory.DataflowCanvas)).toBe(+ true,+ );});- 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 in the Workflow tab', () => {+ expect(shouldShowBuiltinForCategory(AgentCategory.AgentCanvas)).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.+ it('hides builtin in the Compilation tab', () => {expect(- shouldShowBuiltinForRaw({- operator: 'or',- values: [AgentCategory.DataflowCanvas],- }),+ shouldShowBuiltinForCategory(AgentListItemType.CompilationTemplateGroup),).toBe(false);});});diff --git a/web/src/pages/agents/builtin-pipeline-list.ts b/web/src/pages/agents/builtin-pipeline-list.tsindex 8a4a6a2f51..fbc0f20f52 100644--- a/web/src/pages/agents/builtin-pipeline-list.ts+++ b/web/src/pages/agents/builtin-pipeline-list.ts@@ -7,33 +7,10 @@ import {} 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;+// Built-in pipelines are parsing methods, so they appear only in the Pipeline+// tab alongside user-owned dataflow canvases.+export function shouldShowBuiltinForCategory(canvasCategory: string): boolean {+ return canvasCategory === AgentCategory.DataflowCanvas;}// Filters built-in pipelines by a case-insensitive keyword over title and@@ -72,18 +49,18 @@ export function toBuiltinListItem(// 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[]>,+ canvasCategory: string,searchString?: string,): { items: IBuiltinPipelineListItem[]; loading: boolean } {const { data: builtinData, loading } = useFetchBuiltinPipelines();const items = useMemo(() => {- if (!shouldShowBuiltinForRaw(rawCategory)) {+ if (!shouldShowBuiltinForCategory(canvasCategory)) {return [];}return filterBuiltinByKeyword(builtinData?.canvas ?? [], searchString).map(toBuiltinListItem,);- }, [rawCategory, builtinData, searchString]);+ }, [canvasCategory, builtinData, searchString]);return { items, loading };}diff --git a/web/src/pages/agents/builtin-pipeline-section.test.tsx b/web/src/pages/agents/builtin-pipeline-section.test.tsxindex 9805483bb2..1faba3add3 100644--- a/web/src/pages/agents/builtin-pipeline-section.test.tsx+++ b/web/src/pages/agents/builtin-pipeline-section.test.tsx@@ -55,9 +55,12 @@ beforeEach(() => {});describe('BuiltinPipelineSection', () => {- it('renders the section with cards in the "All" view', () => {+ it('renders the section with cards in the Pipeline tab', () => {const { container } = render(- <BuiltinPipelineSection rawCategory={undefined} searchString="" />,+ <BuiltinPipelineSection+ canvasCategory={AgentCategory.DataflowCanvas}+ searchString=""+ />,{ wrapper },);expect(screen.getByTestId('builtin-pipeline-section')).toBeInTheDocument();@@ -77,9 +80,12 @@ describe('BuiltinPipelineSection', () => {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.+ // in the Pipeline tab even though there are zero user-owned canvases.const { container } = render(- <BuiltinPipelineSection rawCategory={undefined} searchString="general" />,+ <BuiltinPipelineSection+ canvasCategory={AgentCategory.DataflowCanvas}+ searchString="general"+ />,{ wrapper },);expect(screen.getByTestId('builtin-pipeline-section')).toBeInTheDocument();@@ -89,10 +95,10 @@ describe('BuiltinPipelineSection', () => {).toBeTruthy();});- it('hides the section in the pure Agent view', () => {+ it('hides the section in the Workflow tab', () => {render(<BuiltinPipelineSection- rawCategory={AgentCategory.AgentCanvas}+ canvasCategory={AgentCategory.AgentCanvas}searchString=""/>,{ wrapper },@@ -102,10 +108,14 @@ describe('BuiltinPipelineSection', () => {).not.toBeInTheDocument();});- it('hides the section for a structured (non-string) category filter', () => {+ it('hides the section when the catalog is empty', () => {+ agentRequest.useFetchBuiltinPipelines.mockReturnValue({+ data: { canvas: [], total: 0 },+ loading: false,+ });render(<BuiltinPipelineSection- rawCategory={{ operator: 'or', values: [AgentCategory.DataflowCanvas] }}+ canvasCategory={AgentCategory.DataflowCanvas}searchString=""/>,{ wrapper },@@ -115,23 +125,10 @@ describe('BuiltinPipelineSection', () => {).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}+ canvasCategory={AgentCategory.DataflowCanvas}searchString=""showDivider={false}/>,@@ -141,19 +138,22 @@ describe('BuiltinPipelineSection', () => {rerender(<BuiltinPipelineSection- rawCategory={undefined}+ canvasCategory={AgentCategory.DataflowCanvas}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,- });+ render(+ <BuiltinPipelineSection+ canvasCategory={AgentCategory.DataflowCanvas}+ searchString=""+ />,+ { wrapper },+ );fireEvent.click(screen.getAllByTestId('copy-builtin-pipeline')[0]);expect(mockCopy).toHaveBeenCalledTimes(1);expect(mockCopy.mock.calls[0][0]).toEqual({diff --git a/web/src/pages/agents/builtin-pipeline-section.tsx b/web/src/pages/agents/builtin-pipeline-section.tsxindex 34f235f67e..5f935117ac 100644--- a/web/src/pages/agents/builtin-pipeline-section.tsx+++ b/web/src/pages/agents/builtin-pipeline-section.tsx@@ -5,22 +5,19 @@ 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.+// only when this component is mounted by the Pipeline tab. The cards use the+// same responsive CardContainer grid as the user items.export function BuiltinPipelineSection({- rawCategory,+ canvasCategory,searchString,showDivider,}: {- rawCategory?: string | string[] | Record<string, string[]>;+ canvasCategory: string;searchString?: string;showDivider?: boolean;}) {const { t } = useTranslation();- const { items: builtinItems } = useBuiltinItems(rawCategory, searchString);+ const { items: builtinItems } = useBuiltinItems(canvasCategory, searchString);if (builtinItems.length === 0) {return null;diff --git a/web/src/pages/agents/constant.ts b/web/src/pages/agents/constant.tsindex b943fe0a88..d1383b1dea 100644--- a/web/src/pages/agents/constant.ts+++ b/web/src/pages/agents/constant.ts@@ -1,4 +1,5 @@import { AgentCategory } from '@/constants/agent';+import { AgentListItemType } from '@/interfaces/database/agent';import { LucideIcon, Network, Route, Shapes } from 'lucide-react';export enum FlowType {@@ -7,31 +8,62 @@ export enum FlowType {Flow = 'flow',}+export type AgentTabCategory =+ | AgentCategory+ | AgentListItemType.CompilationTemplateGroup;+export const FlowTypeConfig: Record<FlowType,- { icon: LucideIcon; labelKey: string; color: string }+ {+ icon: LucideIcon;+ labelKey: string;+ createTitleKey: string;+ color: string;+ canvasCategory: AgentTabCategory;+ supportsTemplates: boolean;+ supportsImport: boolean;+ }> = {[FlowType.Agent]: {icon: Network,labelKey: 'tabList.workflow',+ createTitleKey: 'createWorkflow',color: 'var(--team-member)',+ canvasCategory: AgentCategory.AgentCanvas,+ supportsTemplates: true,+ supportsImport: true,},[FlowType.Compiler]: {icon: Shapes,labelKey: 'tabList.compilationOperator',+ createTitleKey: 'createCompilationOperator',color: 'var(--team-department)',+ canvasCategory: AgentListItemType.CompilationTemplateGroup,+ supportsTemplates: false,+ supportsImport: false,},[FlowType.Flow]: {icon: Route,labelKey: 'tabList.ingestionPipeline',+ createTitleKey: 'createIngestionPipeline',color: 'var(--team-group)',+ canvasCategory: AgentCategory.DataflowCanvas,+ supportsTemplates: true,+ supportsImport: true,},};+export const AgentTabs = [+ FlowType.Compiler,+ FlowType.Flow,+ FlowType.Agent,+] as const;+/*** Map canvas_category → FlowType for resolving icons in agent cards.*/export const CanvasCategoryToFlowType: Record<string, FlowType> = {[AgentCategory.AgentCanvas]: FlowType.Agent,[AgentCategory.DataflowCanvas]: FlowType.Flow,+ [AgentListItemType.CompilationTemplateGroup]: FlowType.Compiler,};diff --git a/web/src/pages/agents/create-agent-dialog.test.tsx b/web/src/pages/agents/create-agent-dialog.test.tsxnew file mode 100644index 0000000000..133eeef01a--- /dev/null+++ b/web/src/pages/agents/create-agent-dialog.test.tsx@@ -0,0 +1,124 @@+/*+ * 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 { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { CreateAgentDialog } from './create-agent-dialog';+import { FlowType } from './constant';++const mockNavigateToCompilationEditor = jest.fn();+jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({+ useNavigatePage: () => ({+ navigateToCompilationEditor: mockNavigateToCompilationEditor,+ }),+}));++const TitleByType = {+ [FlowType.Agent]: 'Create workflow',+ [FlowType.Flow]: 'Create ingestion pipeline',+ [FlowType.Compiler]: 'Create compilation operator',+};++beforeEach(() => {+ jest.clearAllMocks();+});++describe('CreateAgentDialog', () => {+ it.each([FlowType.Agent, FlowType.Flow, FlowType.Compiler] as const)(+ 'shows the %s title and no type selector',+ (selectedType) => {+ render(+ <CreateAgentDialog+ visible+ hideModal={jest.fn()}+ onOk={jest.fn()}+ selectedType={selectedType}+ />,+ );++ expect(screen.getByText(TitleByType[selectedType])).toBeInTheDocument();+ // The canvas type now comes from the active tab; the dialog no longer+ // renders the three-way card selector.+ expect(screen.queryByText('Choose agent type')).toBeNull();+ },+ );++ it('submits the Workflow type when confirmed', async () => {+ const onOk = jest.fn().mockResolvedValue(true);+ render(+ <CreateAgentDialog+ visible+ hideModal={jest.fn()}+ onOk={onOk}+ selectedType={FlowType.Agent}+ />,+ );++ fireEvent.change(screen.getByTestId('agent-name-input'), {+ target: { value: 'My workflow' },+ });+ fireEvent.click(screen.getByTestId('agent-save'));++ await waitFor(() => expect(onOk).toHaveBeenCalled());+ expect(onOk.mock.calls[0][0]).toMatchObject({+ name: 'My workflow',+ type: FlowType.Agent,+ });+ });++ it('submits the Pipeline type when confirmed', async () => {+ const onOk = jest.fn().mockResolvedValue(true);+ render(+ <CreateAgentDialog+ visible+ hideModal={jest.fn()}+ onOk={onOk}+ selectedType={FlowType.Flow}+ />,+ );++ fireEvent.change(screen.getByTestId('agent-name-input'), {+ target: { value: 'My pipeline' },+ });+ fireEvent.click(screen.getByTestId('agent-save'));++ await waitFor(() => expect(onOk).toHaveBeenCalled());+ expect(onOk.mock.calls[0][0]).toMatchObject({+ name: 'My pipeline',+ type: FlowType.Flow,+ });+ });++ it('navigates to the compilation editor instead of creating on Next', () => {+ const onOk = jest.fn();+ render(+ <CreateAgentDialog+ visible+ hideModal={jest.fn()}+ onOk={onOk}+ selectedType={FlowType.Compiler}+ />,+ );++ // Compilation operators are configured on the edit-next page, so the+ // dialog has no name field and no confirm button.+ expect(screen.queryByTestId('agent-name-input')).toBeNull();+ expect(screen.queryByTestId('agent-save')).toBeNull();++ fireEvent.click(screen.getByTestId('agent-next'));+ expect(mockNavigateToCompilationEditor).toHaveBeenCalledWith();+ expect(onOk).not.toHaveBeenCalled();+ });+});diff --git a/web/src/pages/agents/create-agent-dialog.tsx b/web/src/pages/agents/create-agent-dialog.tsxindex f99cbf8896..fef6634daf 100644--- a/web/src/pages/agents/create-agent-dialog.tsx+++ b/web/src/pages/agents/create-agent-dialog.tsx@@ -4,11 +4,10 @@ import {DialogHeader,DialogTitle,} from '@/components/ui/dialog';-import { AgentCategory } from '@/constants/agent';import { IFlowTemplate } from '@/interfaces/database/agent';-import { BrainCircuit, Route } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { FlowTypeConfig } from './constant';import { CreateAgentForm, CreateAgentFormProps } from './create-agent-form';import {collectUnboundRetrievalBindings,@@ -16,7 +15,6 @@ import {} from './template-retrieval-binding';type CreateAgentDialogProps = CreateAgentFormProps & {- canvasCategory?: AgentCategory;template?: IFlowTemplate;};@@ -24,7 +22,7 @@ export function CreateAgentDialog({hideModal,onOk,loading,- canvasCategory,+ selectedType,template,}: CreateAgentDialogProps) {const { t } = useTranslation();@@ -39,26 +37,15 @@ export function CreateAgentDialog({[template],);- const dialogTitle =- canvasCategory === AgentCategory.DataflowCanvas- ? t('flow.createIngestionPipeline')- : canvasCategory === AgentCategory.AgentCanvas- ? t('flow.createWorkflow')- : t('common.create');-- const DialogIcon =- canvasCategory === AgentCategory.DataflowCanvas- ? Route- : canvasCategory === AgentCategory.AgentCanvas- ? BrainCircuit- : undefined;+ const dialogTitle = t(`flow.${FlowTypeConfig[selectedType].createTitleKey}`);+ const DialogIcon = FlowTypeConfig[selectedType].icon;return (<Dialog open onOpenChange={hideModal}><DialogContent data-testid="agent-create-modal" className="max-w-[800px]"><DialogHeader><DialogTitle className="flex items-center gap-2">- {DialogIcon && <DialogIcon className="size-5" />}+ <DialogIcon className="size-5" />{dialogTitle}</DialogTitle></DialogHeader>@@ -66,7 +53,7 @@ export function CreateAgentDialog({hideModal={hideModal}onOk={onOk}loading={loading}- showTypeCards={!canvasCategory}+ selectedType={selectedType}retrievalBindings={retrievalBindings}modelBindings={modelBindings}></CreateAgentForm>diff --git a/web/src/pages/agents/create-agent-form.tsx b/web/src/pages/agents/create-agent-form.tsxindex d78d0cd6cc..5a03ec7e6a 100644--- a/web/src/pages/agents/create-agent-form.tsx+++ b/web/src/pages/agents/create-agent-form.tsx@@ -2,26 +2,21 @@import { zodResolver } from '@hookform/resolvers/zod';import { isEmpty } from 'lodash';-import { useForm, useWatch } from 'react-hook-form';+import { useForm } from 'react-hook-form';import { z } from 'zod';import { KnowledgeBaseFormField } from '@/components/knowledge-base-item';import { ModelTreeSelectFormField } from '@/components/model-tree-select';import { MemoriesFormField } from '@/components/memories-form-field';-import { RAGFlowFormItem } from '@/components/ragflow-form';import { Button, ButtonLoading } from '@/components/ui/button';-import { Card, CardContent } from '@/components/ui/card';import { DialogFooter } from '@/components/ui/dialog';import { Form } from '@/components/ui/form';import { TagRenameId } from '@/constants/knowledge';+import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';import { IModalProps } from '@/interfaces/common';-import { cn } from '@/lib/utils';-import { Routes } from '@/routes';-import { Check } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router';-import { FlowType, FlowTypeConfig } from './constant';+import { FlowType } from './constant';import { NameFormField, NameFormSchema } from './name-form-field';import {ModelBindingCount,@@ -30,7 +25,7 @@ import {export type CreateAgentFormProps = IModalProps<any> & {loading?: boolean;- showTypeCards?: boolean;+ selectedType: FlowType;// Templates may ship retrieval steps without any dataset/memory bound. When// set, the form asks the user to bind them before creating the agent, so// the canvas never ends up with a retrieval that fails at runtime.@@ -38,61 +33,11 @@ export type CreateAgentFormProps = IModalProps<any> & {modelBindings?: ModelBindingCount;};-type FlowTypeCardProps = {- value?: FlowType;- onChange?: (value: FlowType) => void;-};--function FlowTypeCards({ value, onChange }: FlowTypeCardProps) {- const { t } = useTranslation();- const handleChange = useCallback(- (value: FlowType) => () => {- onChange?.(value);- },- [onChange],- );-- return (- <section className="flex gap-10">- {[FlowType.Agent, FlowType.Flow, FlowType.Compiler].map((val) => {- const isActive = value === val;- const config = FlowTypeConfig[val];- const Icon = config.icon;- return (- <Card- key={val}- className={cn('flex-1 rounded-lg border bg-transparent', {- 'border-text-primary': isActive,- 'border-border-default': !isActive,- })}- >- <CardContent- onClick={handleChange(val)}- className={cn(- 'cursor-pointer p-5 text-text-secondary flex justify-between items-center',- {- 'text-text-primary': isActive,- },- )}- >- <div className="flex gap-2">- <Icon className="size-6" />- <p>{t(`flow.${config.labelKey}`)}</p>- </div>- {isActive && <Check />}- </CardContent>- </Card>- );- })}- </section>- );-}-export const FormSchema = z.object({...NameFormSchema,tag: z.string().trim().optional(),description: z.string().trim().optional(),- type: z.nativeEnum(FlowType).optional(),+ type: z.nativeEnum(FlowType),dataset_ids: z.array(z.string()).optional(),dataset_bindings: z.array(z.array(z.string())).optional(),memory_ids: z.array(z.string()).optional(),@@ -105,27 +50,26 @@ export function CreateAgentForm({hideModal,onOk,loading,- showTypeCards = false,+ selectedType,retrievalBindings,modelBindings,}: CreateAgentFormProps) {const { t } = useTranslation();- const navigate = useNavigate();+ const { navigateToCompilationEditor } = useNavigatePage();const form = useForm<FormSchemaType>({resolver: zodResolver(FormSchema),- defaultValues: { name: '', type: FlowType.Agent },+ defaultValues: { name: '', type: selectedType },});- const selectedType = useWatch({ control: form.control, name: 'type' });// Compilation operators are configured on the edit-next page, so the dialog// skips the name field and turns the submit button into a navigation step.- const isCompiler = showTypeCards && selectedType === FlowType.Compiler;+ const isCompiler = selectedType === FlowType.Compiler;const modelRequired = (modelBindings?.modelCount ?? 0) > 0;const handleNext = useCallback(() => {- navigate(`${Routes.CompilationTemplatesEditNext}?source=agents`);- }, [navigate]);+ navigateToCompilationEditor();+ }, [navigateToCompilationEditor]);async function onSubmit(data: FormSchemaType) {if (modelRequired && !data.llm_id) {@@ -188,15 +132,6 @@ export function CreateAgentForm({className="space-y-6"id={TagRenameId}>- {showTypeCards && (- <RAGFlowFormItem- required- name="type"- label={t('flow.chooseAgentType')}- >- <FlowTypeCards></FlowTypeCards>- </RAGFlowFormItem>- )}{!isCompiler && <NameFormField></NameFormField>}{!isCompiler && modelRequired && (<ModelTreeSelectFormFielddiff --git a/web/src/pages/agents/hooks/use-agent-create-actions.tsx b/web/src/pages/agents/hooks/use-agent-create-actions.tsxnew file mode 100644index 0000000000..37bf1bd8d9--- /dev/null+++ b/web/src/pages/agents/hooks/use-agent-create-actions.tsx@@ -0,0 +1,96 @@+/*+ * 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 { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';+import { Clipboard, ClipboardPlus, FileInput, LucideIcon } from 'lucide-react';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { AgentTabCategory, FlowType, FlowTypeConfig } from '../constant';++export interface AgentCreateAction {+ key: 'blank' | 'template' | 'import';+ icon: LucideIcon;+ label: string;+ testId?: string;+ onClick: () => void;+}++// The active tab decides which create actions exist: compilation groups only+// support blank creation, while workflow/pipeline also offer templates and+// JSON import.+export function useAgentCreateActions(+ activeType: FlowType,+ activeCategory: AgentTabCategory,+ showCreatingModal: () => void,+ handleImportJson: () => void,+): AgentCreateAction[] {+ const { t } = useTranslation();+ const { navigateToAgentTemplates, navigateToCompilationEditor } =+ useNavigatePage();++ const handleCreateFromTemplate = useCallback(() => {+ navigateToAgentTemplates(activeCategory);+ }, [navigateToAgentTemplates, activeCategory]);++ const handleNavigateToCompilationEditor = useCallback(() => {+ navigateToCompilationEditor();+ }, [navigateToCompilationEditor]);++ return useMemo(() => {+ const config = FlowTypeConfig[activeType];+ return [+ {+ key: 'blank' as const,+ icon: Clipboard,+ label: t('flow.createFromBlank'),+ testId: undefined,+ onClick:+ activeType === FlowType.Compiler+ ? handleNavigateToCompilationEditor+ : showCreatingModal,+ },+ ...(config.supportsTemplates+ ? [+ {+ key: 'template' as const,+ icon: ClipboardPlus,+ label: t('flow.createFromTemplate'),+ testId: undefined,+ onClick: handleCreateFromTemplate,+ },+ ]+ : []),+ ...(config.supportsImport+ ? [+ {+ key: 'import' as const,+ icon: FileInput,+ label: t('flow.importJsonFile'),+ testId: 'agent-import-json',+ onClick: handleImportJson,+ },+ ]+ : []),+ ];+ }, [+ activeType,+ t,+ handleNavigateToCompilationEditor,+ showCreatingModal,+ handleCreateFromTemplate,+ handleImportJson,+ ]);+}diff --git a/web/src/pages/agents/hooks/use-agent-tab.ts b/web/src/pages/agents/hooks/use-agent-tab.tsnew file mode 100644index 0000000000..65dd660dca--- /dev/null+++ b/web/src/pages/agents/hooks/use-agent-tab.ts@@ -0,0 +1,63 @@+/*+ * 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 { AgentQuery } from '@/constants/agent';+import { useCallback } from 'react';+import { useSearchParams } from 'react-router';+import {+ AgentTabCategory,+ CanvasCategoryToFlowType,+ FlowType,+ FlowTypeConfig,+} from '../constant';++const DefaultTabCategory = FlowTypeConfig[FlowType.Agent].canvasCategory;++function resolveTabCategory(value: string | null): AgentTabCategory {+ return value && CanvasCategoryToFlowType[value] !== undefined+ ? (value as AgentTabCategory)+ : DefaultTabCategory;+}++export function useAgentTab() {+ const [searchUrl, setSearchUrl] = useSearchParams();++ const activeCategory = resolveTabCategory(+ searchUrl.get(AgentQuery.CanvasCategory),+ );++ const handleTabChange = useCallback(+ (value: string | number) => {+ const nextCategory = resolveTabCategory(String(value));+ if (nextCategory === activeCategory) {+ return;+ }+ const nextParams = new URLSearchParams(searchUrl);+ nextParams.set(AgentQuery.CanvasCategory, nextCategory);+ nextParams.set('page', '1');+ setSearchUrl(nextParams, { replace: true });+ },+ [activeCategory, searchUrl, setSearchUrl],+ );++ return {+ searchUrl,+ setSearchUrl,+ activeCategory,+ activeType: CanvasCategoryToFlowType[activeCategory],+ handleTabChange,+ };+}diff --git a/web/src/pages/agents/hooks/use-create-agent.test.ts b/web/src/pages/agents/hooks/use-create-agent.test.tsindex f7a31c88e9..9097103c7d 100644--- a/web/src/pages/agents/hooks/use-create-agent.test.ts+++ b/web/src/pages/agents/hooks/use-create-agent.test.ts@@ -12,7 +12,7 @@ jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({}));jest.mock('@/hooks/use-agent-request', () => ({- useSetAgent: jest.fn(),+ useCreateAgent: jest.fn(),}));jest.mock('@/pages/agent/utils/dsl-bridge', () => ({@@ -29,7 +29,7 @@ const mockAgentRequest = require('@/hooks/use-agent-request');const mockDslBridge = require('@/pages/agent/utils/dsl-bridge');const hideCreatingModal = jest.fn();-const setAgent = jest.fn();+const createAgent = jest.fn();const navigate = jest.fn();const navigateToAgent = jest.fn(() => navigate);@@ -52,9 +52,9 @@ beforeEach(() => {showModal: jest.fn(),});mockNavigateHooks.useNavigatePage.mockReturnValue({ navigateToAgent });- mockAgentRequest.useSetAgent.mockReturnValue({+ mockAgentRequest.useCreateAgent.mockReturnValue({loading: false,- setAgent,+ createAgent,});});@@ -62,7 +62,7 @@ describe('useCreateAgentOrPipeline', () => {it.each(CreateScenarios)('navigates $flowType to its canvas after creation',async ({ flowType, canvasCategory }) => {- setAgent.mockResolvedValue({+ createAgent.mockResolvedValue({code: 0,data: { id: 'canvas-id' },});@@ -75,7 +75,7 @@ describe('useCreateAgentOrPipeline', () => {});});- expect(setAgent).toHaveBeenCalledWith({+ expect(createAgent).toHaveBeenCalledWith({title: 'New agent',dsl: {},canvas_category: canvasCategory,@@ -90,7 +90,7 @@ describe('useCreateAgentOrPipeline', () => {);it('stays on the list when creation fails', async () => {- setAgent.mockResolvedValue({ code: 1 });+ createAgent.mockResolvedValue({ code: 1 });const { result } = renderHook(() => useCreateAgentOrPipeline());await act(async () => {diff --git a/web/src/pages/agents/hooks/use-create-agent.ts b/web/src/pages/agents/hooks/use-create-agent.tsindex 8624809dc1..176e5c5367 100644--- a/web/src/pages/agents/hooks/use-create-agent.ts+++ b/web/src/pages/agents/hooks/use-create-agent.ts@@ -1,7 +1,7 @@import { AgentCategory } from '@/constants/agent';import { useSetModalState } from '@/hooks/common-hooks';import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';-import { useSetAgent } from '@/hooks/use-agent-request';+import { useCreateAgent } from '@/hooks/use-agent-request';import { initialEmptyDsl } from '@/pages/agent/utils/dsl-bridge';import { useCallback } from 'react';@@ -9,7 +9,7 @@ import { FlowType } from '../constant';import { FormSchemaType } from '../create-agent-form';export function useCreateAgentOrPipeline() {- const { loading, setAgent } = useSetAgent();+ const { loading, createAgent } = useCreateAgent();const { navigateToAgent } = useNavigatePage();const {visible: creatingVisible,@@ -23,7 +23,7 @@ export function useCreateAgentOrPipeline() {const canvasCategory = isAgent? AgentCategory.AgentCanvas: AgentCategory.DataflowCanvas;- const ret = await setAgent({+ const ret = await createAgent({title: data.name,dsl: initialEmptyDsl(isAgent),canvas_category: canvasCategory,@@ -34,7 +34,7 @@ export function useCreateAgentOrPipeline() {navigateToAgent(ret.data.id, canvasCategory)();}},- [hideCreatingModal, navigateToAgent, setAgent],+ [hideCreatingModal, navigateToAgent, createAgent],);return {diff --git a/web/src/pages/agents/hooks/use-select-filters.ts b/web/src/pages/agents/hooks/use-select-filters.tsindex b2360f8ccd..d4d41f38f7 100644--- a/web/src/pages/agents/hooks/use-select-filters.ts+++ b/web/src/pages/agents/hooks/use-select-filters.ts@@ -1,17 +1,15 @@import { FilterCollection } from '@/components/list-filter-bar/interface';-import { AgentCategory } from '@/constants/agent';import {useFetchAgentFilters,useFetchAgentTags,} from '@/hooks/use-agent-request';-import { AgentListItemType } from '@/interfaces/database/agent';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-export function useSelectFilters() {+export function useSelectFilters(canvasCategory?: string) {const { t } = useTranslation();- const { data: agentFilters } = useFetchAgentFilters();- const { data: tagCounts } = useFetchAgentTags();+ const { data: agentFilters } = useFetchAgentFilters(canvasCategory);+ const { data: tagCounts } = useFetchAgentTags(canvasCategory);const tagList = useMemo(() =>@@ -30,37 +28,6 @@ export function useSelectFilters() {list: agentFilters?.owner,label: t('common.owner'),},- {- field: 'canvasCategory',- list: [- {- id: AgentCategory.DataflowCanvas,- label: t('flow.tabList.ingestionPipeline'),- count:- agentFilters?.canvas_category.find(- (item) => item.id === AgentCategory.DataflowCanvas,- )?.count ?? 0,- },- {- id: AgentListItemType.CompilationTemplateGroup,- label: t('flow.tabList.compilationOperator'),- count:- agentFilters?.canvas_category.find(- (item) =>- item.id === AgentListItemType.CompilationTemplateGroup,- )?.count ?? 0,- },- {- id: AgentCategory.AgentCanvas,- label: t('flow.tabList.workflow'),- count:- agentFilters?.canvas_category.find(- (item) => item.id === AgentCategory.AgentCanvas,- )?.count ?? 0,- },- ],- label: t('flow.agentCategory'),- },{field: 'tags',list: tagList,diff --git a/web/src/pages/agents/index.test.tsx b/web/src/pages/agents/index.test.tsxindex 2e4bc2210d..802a8863d3 100644--- a/web/src/pages/agents/index.test.tsx+++ b/web/src/pages/agents/index.test.tsx@@ -1,8 +1,9 @@-import { render, screen } from '@testing-library/react';+import { render, screen, fireEvent } from '@testing-library/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import { MemoryRouter } from 'react-router';+import { MemoryRouter, useLocation } from 'react-router';import { TooltipProvider } from '@/components/ui/tooltip';import { AgentCategory } from '@/constants/agent';+import { AgentListItemType } from '@/interfaces/database/agent';import Agents from './index';// Fully isolate the agents list from the request/router/modal layers.@@ -31,10 +32,13 @@ jest.mock('@/hooks/use-compilation-template-group-request', () => ({jest.mock('@/hooks/logic-hooks', () => ({useGoToPreviousPageOnEmpty: jest.fn(),}));+const mockNavigateToAgentTemplates = jest.fn();+const mockNavigateToCompilationEditor = jest.fn();jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({useNavigatePage: () => ({navigateToAgent: jest.fn(),- navigateToAgentTemplates: jest.fn(),+ navigateToAgentTemplates: mockNavigateToAgentTemplates,+ navigateToCompilationEditor: mockNavigateToCompilationEditor,navigateToBuiltinPipeline: jest.fn(() => jest.fn()),}),}));@@ -53,15 +57,16 @@ jest.mock('@/pages/agents/hooks/use-create-agent', () => ({}),}));jest.mock('@/pages/agents/hooks/use-select-filters', () => ({- useSelectFilters: () => [],+ useSelectFilters: jest.fn(() => []),}));+const mockHandleImportJson = jest.fn();jest.mock('@/pages/agents/use-import-json', () => ({- useHandleImportJsonFile: () => ({- handleImportJson: jest.fn(),+ useHandleImportJsonFile: jest.fn(() => ({+ handleImportJson: mockHandleImportJson,fileUploadVisible: false,onFileUploadOk: jest.fn(),hideFileUploadModal: jest.fn(),- }),+ })),}));jest.mock('@/pages/agents/use-rename-agent', () => ({useRenameAgent: () => ({@@ -76,6 +81,8 @@ jest.mock('@/pages/agents/use-rename-agent', () => ({// eslint-disable-next-line @typescript-eslint/no-var-requiresconst agentRequest = jest.requireMock('@/hooks/use-agent-request');+// eslint-disable-next-line @typescript-eslint/no-var-requires+const importJson = jest.requireMock('@/pages/agents/use-import-json');const catalog = [{@@ -87,13 +94,24 @@ const catalog = [{ 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>-);+let currentSearch = '';+function LocationProbe() {+ currentSearch = useLocation().search;+ return null;+}++function renderAgents(initialEntry = '/') {+ return render(+ <MemoryRouter initialEntries={[initialEntry]}>+ <QueryClientProvider client={new QueryClient()}>+ <TooltipProvider>+ <Agents />+ <LocationProbe />+ </TooltipProvider>+ </QueryClientProvider>+ </MemoryRouter>,+ );+}const defaultListPage = {data: [] as Array<Record<string, unknown>>,@@ -125,20 +143,137 @@ function setBuiltin(canvas = catalog, loading = false) {}beforeEach(() => {+ jest.clearAllMocks();setBuiltin();setListPage();+ currentSearch = '';+});++describe('Agents tabs', () => {+ it('defaults to the Workflow tab and requests the agent canvas list', () => {+ renderAgents();+ expect(agentRequest.useFetchAgentListByPage).toHaveBeenCalledWith(+ AgentCategory.AgentCanvas,+ );+ });++ it('renders the three tabs in Compilation / Pipeline / Workflow order', () => {+ renderAgents();+ expect(screen.getByText('Compilation operator')).toBeInTheDocument();+ expect(screen.getByText('Ingestion pipeline')).toBeInTheDocument();+ expect(screen.getByText('Workflow')).toBeInTheDocument();+ });++ it('switches the tab through the URL and resets the page', () => {+ renderAgents('/?page=3');+ fireEvent.click(screen.getByText('Ingestion pipeline'));++ expect(currentSearch).toContain(+ `canvas_category=${AgentCategory.DataflowCanvas}`,+ );+ expect(currentSearch).toContain('page=1');+ expect(agentRequest.useFetchAgentListByPage.mock.calls.at(-1)?.[0]).toBe(+ AgentCategory.DataflowCanvas,+ );+ });++ it('falls back to the Workflow tab for an unknown canvas_category', () => {+ renderAgents('/?canvas_category=bogus');+ expect(agentRequest.useFetchAgentListByPage).toHaveBeenCalledWith(+ AgentCategory.AgentCanvas,+ );+ });+});++describe('Agents create actions per tab', () => {+ // The + dropdown and the non-search empty state render the same action+ // list; the empty state exposes them as plain buttons, which jsdom can+ // click reliably (radix dropdowns require pointer-capture polyfills).+ it('shows all three actions on the Workflow tab', () => {+ setListPage({ data: [], debouncedSearchString: '' });+ renderAgents();+ expect(screen.getByText('Create from blank')).toBeInTheDocument();+ expect(screen.getByText('Create from template')).toBeInTheDocument();+ expect(screen.getByText('Import JSON file')).toBeInTheDocument();+ expect(screen.getByTestId('create-agent')).toBeInTheDocument();+ });++ it('shows all three actions on the Pipeline tab', () => {+ setListPage({ data: [], debouncedSearchString: '' });+ // An empty built-in catalog keeps the Pipeline tab on the empty card.+ setBuiltin([]);+ renderAgents(`/?canvas_category=${AgentCategory.DataflowCanvas}`);+ expect(screen.getByText('Create from blank')).toBeInTheDocument();+ expect(screen.getByText('Create from template')).toBeInTheDocument();+ expect(screen.getByText('Import JSON file')).toBeInTheDocument();+ });++ it('shows only blank creation on the Compilation tab', () => {+ setListPage({ data: [], debouncedSearchString: '' });+ renderAgents(+ `/?canvas_category=${AgentListItemType.CompilationTemplateGroup}`,+ );+ expect(screen.getByText('Create from blank')).toBeInTheDocument();+ expect(screen.queryByText('Create from template')).toBeNull();+ expect(screen.queryByText('Import JSON file')).toBeNull();+ });++ it('navigates straight to the compilation editor from the + button (no dropdown)', () => {+ renderAgents(+ `/?canvas_category=${AgentListItemType.CompilationTemplateGroup}`,+ );+ fireEvent.click(screen.getByTestId('create-agent'));+ expect(mockNavigateToCompilationEditor).toHaveBeenCalledWith();+ expect(screen.queryByTestId('agent-create-menu')).toBeNull();+ });++ it('carries the active category when navigating to templates', () => {+ setListPage({ data: [], debouncedSearchString: '' });+ setBuiltin([]);+ renderAgents(`/?canvas_category=${AgentCategory.DataflowCanvas}`);+ fireEvent.click(screen.getByText('Create from template'));+ expect(mockNavigateToAgentTemplates).toHaveBeenCalledWith(+ AgentCategory.DataflowCanvas,+ );+ });++ it('opens the compilation editor for blank creation on the Compilation tab', () => {+ setListPage({ data: [], debouncedSearchString: '' });+ renderAgents(+ `/?canvas_category=${AgentListItemType.CompilationTemplateGroup}`,+ );+ fireEvent.click(screen.getByTestId('agents-empty-create'));+ expect(mockNavigateToCompilationEditor).toHaveBeenCalledWith();+ });++ it('scopes JSON import to the active tab category', () => {+ renderAgents(`/?canvas_category=${AgentCategory.DataflowCanvas}`);+ expect(importJson.useHandleImportJsonFile).toHaveBeenCalledWith(+ AgentCategory.DataflowCanvas,+ );+ });++ it('scopes the filter popover data to the active tab category', () => {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ const selectFilters = jest.requireMock(+ '@/pages/agents/hooks/use-select-filters',+ );+ renderAgents(`/?canvas_category=${AgentCategory.DataflowCanvas}`);+ expect(selectFilters.useSelectFilters).toHaveBeenCalledWith(+ AgentCategory.DataflowCanvas,+ );+ });});describe('Agents empty-state (built-in pipeline regression)', () => {- it('shows the search-empty card on a zero-match search in the All view', () => {+ it('shows the search-empty card on a zero-match search in the Pipeline tab', () => {// 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 });+ renderAgents(`/?canvas_category=${AgentCategory.DataflowCanvas}`);expect(screen.getByTestId('agents-search-empty')).toBeInTheDocument();expect(@@ -148,37 +283,43 @@ describe('Agents empty-state (built-in pipeline regression)', () => {it('keeps the built-in section when the search matches a built-in pipeline', () => {setListPage({- filterValue: undefined,data: [],debouncedSearchString: 'general',});- render(<Agents />, { wrapper });+ renderAgents(`/?canvas_category=${AgentCategory.DataflowCanvas}`);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 });+ it('shows the non-search empty card with the tab-scoped actions', () => {+ setListPage({ data: [], debouncedSearchString: '' });+ renderAgents();expect(screen.queryByTestId('agents-search-empty')).not.toBeInTheDocument();- // The non-search empty card exposes the create actions.+ // Workflow tab: the empty card exposes all three create actions.+ expect(screen.getByTestId('agents-empty-create')).toBeInTheDocument();+ expect(screen.getByText('Create from template')).toBeInTheDocument();+ expect(screen.getByText('Import JSON file')).toBeInTheDocument();+ });++ it('shows only blank creation in the Compilation empty card', () => {+ setListPage({ data: [], debouncedSearchString: '' });+ renderAgents(+ `/?canvas_category=${AgentListItemType.CompilationTemplateGroup}`,+ );+expect(screen.getByTestId('agents-empty-create')).toBeInTheDocument();+ expect(screen.queryByText('Create from template')).toBeNull();+ expect(screen.queryByText('Import JSON file')).toBeNull();});- it('shows the search-empty card in the Agent view (built-ins not eligible)', () => {+ it('shows the search-empty card in the Workflow tab (built-ins not eligible)', () => {setListPage({- filterValue: { canvasCategory: AgentCategory.AgentCanvas },data: [],debouncedSearchString: 'zzz-no-match',});- render(<Agents />, { wrapper });+ renderAgents();expect(screen.getByTestId('agents-search-empty')).toBeInTheDocument();expect(@@ -187,8 +328,8 @@ describe('Agents empty-state (built-in pipeline regression)', () => {});it('renders nothing while the user list is loading', () => {- setListPage({ filterValue: undefined, data: [], loading: true });- render(<Agents />, { wrapper });+ setListPage({ data: [], loading: true });+ renderAgents();expect(screen.queryByTestId('agents-search-empty')).not.toBeInTheDocument();expect(screen.queryByTestId('agents-empty-create')).not.toBeInTheDocument();@@ -196,7 +337,6 @@ describe('Agents empty-state (built-in pipeline regression)', () => {it('renders the content branch with user items (and footer) without an empty card', () => {setListPage({- filterValue: undefined,data: [{id: 'user-1',@@ -207,7 +347,7 @@ describe('Agents empty-state (built-in pipeline regression)', () => {],debouncedSearchString: '',});- render(<Agents />, { wrapper });+ renderAgents();// No empty state is shown when there is at least one user item.expect(screen.queryByTestId('agents-search-empty')).not.toBeInTheDocument();diff --git a/web/src/pages/agents/index.tsx b/web/src/pages/agents/index.tsxindex 714700eaef..1fcc697475 100644--- a/web/src/pages/agents/index.tsx+++ b/web/src/pages/agents/index.tsx@@ -3,44 +3,46 @@ import { EmptyCardType } from '@/components/empty/constant';import { EmptyAppCard } from '@/components/empty/empty';import ListFilterBar from '@/components/list-filter-bar';import { RenameDialog } from '@/components/rename-dialog';-import { Button } from '@/components/ui/button';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';import { RAGFlowPagination } from '@/components/ui/ragflow-pagination';import { ListDeletionKey } from '@/constants/list-deletion';import { useGoToPreviousPageOnEmpty } from '@/hooks/logic-hooks';import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';import { useFetchAgentListByPage } from '@/hooks/use-agent-request';import { useDeleteCompilationTemplateGroup } from '@/hooks/use-compilation-template-group-request';-import { Routes } from '@/routes';+import { AgentListItemType } from '@/interfaces/database/agent';import { pick } from 'lodash';-import { BuiltinPipelineSection } from './builtin-pipeline-section';-import { Clipboard, ClipboardPlus, FileInput, Plus } from 'lucide-react';import { useCallback, useEffect, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { useNavigate, useSearchParams } from 'react-router';import { AgentCard } from './agent-card';+import {+ AgentCreateMenu,+ AgentsEmptyStateActions,+} from './agent-create-actions';+import { AgentTabGroup } from './agent-tab-group';import { BuiltinCatalogProbe } from './builtin-catalog-probe';+import { BuiltinPipelineSection } from './builtin-pipeline-section';import {resolveAgentsEmptyState,- shouldShowBuiltinForRaw,+ shouldShowBuiltinForCategory,} from './builtin-pipeline-list';import { CompilationTemplateCard } from './compilation-template-card';+import { FlowType } from './constant';import { CreateAgentDialog } from './create-agent-dialog';+import { useAgentCreateActions } from './hooks/use-agent-create-actions';+import { useAgentTab } from './hooks/use-agent-tab';import { useCreateAgentOrPipeline } from './hooks/use-create-agent';import { useSelectFilters } from './hooks/use-select-filters';import { UploadAgentDialog } from './upload-agent-dialog';import { useHandleImportJsonFile } from './use-import-json';import { useRenameAgent } from './use-rename-agent';-const CompilationGroupCategory = 'compilation_template_group';-export default function Agents() {- const { t } = useTranslation();+ const {+ searchUrl,+ setSearchUrl,+ activeCategory,+ activeType,+ handleTabChange,+ } = useAgentTab();const {data,@@ -55,14 +57,11 @@ export default function Agents() {handleFilterSubmit,checkValue,debouncedSearchString,- } = useFetchAgentListByPage();+ } = useFetchAgentListByPage(activeCategory);- // 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);+ // Built-in pipelines are parsing methods => dataflow canvases, so the section+ // (and its catalog request) is mounted only for the Pipeline tab.+ const builtinVisible = shouldShowBuiltinForCategory(activeCategory);// Lifted filtered built-in catalog state, reported by BuiltinCatalogProbe so// the empty-state decision can use *matched* built-in items rather than just@@ -72,8 +71,11 @@ export default function Agents() {loading: boolean;}>({ length: 0, loading: false });- const { navigateToAgentTemplates } = useNavigatePage();- const navigate = useNavigate();+ useEffect(() => {+ if (!builtinVisible) {+ setBuiltinState({ length: 0, loading: false });+ }+ }, [builtinVisible]);const {agentRenameLoading,@@ -97,11 +99,18 @@ export default function Agents() {fileUploadVisible,onFileUploadOk,hideFileUploadModal,- } = useHandleImportJsonFile();+ } = useHandleImportJsonFile(activeCategory);++ const createActions = useAgentCreateActions(+ activeType,+ activeCategory,+ showCreatingModal,+ handleImportJson,+ );const { deleteGroup } = useDeleteCompilationTemplateGroup();- const filters = useSelectFilters();+ const filters = useSelectFilters(activeCategory);useEffect(() => {checkValue(filters);@@ -121,11 +130,17 @@ export default function Agents() {setFilterValue,});+ const { navigateToCompilationEditor } = useNavigatePage();++ const handleCreateCompilation = useCallback(() => {+ navigateToCompilationEditor();+ }, [navigateToCompilationEditor]);+const handleEditCompilation = useCallback((id: string) => () => {- navigate(`${Routes.CompilationTemplatesEditNext}/${id}?source=agents`);+ navigateToCompilationEditor(id);},- [navigate],+ [navigateToCompilationEditor],);const handleDeleteCompilation = useCallback(@@ -135,14 +150,14 @@ export default function Agents() {[deleteGroup],);- const [searchUrl, setSearchUrl] = useSearchParams();const isCreate = searchUrl.get('isCreate') === 'true';useEffect(() => {if (isCreate) {showCreatingModal();- searchUrl.delete('isCreate');- setSearchUrl(searchUrl);+ const nextParams = new URLSearchParams(searchUrl);+ nextParams.delete('isCreate');+ setSearchUrl(nextParams, { replace: true });}}, [isCreate, showCreatingModal, searchUrl, setSearchUrl]);@@ -159,7 +174,7 @@ export default function Agents() {<>{builtinVisible && (<BuiltinCatalogProbe- rawCategory={rawCategory}+ canvasCategory={activeCategory}searchString={debouncedSearchString}onReport={setBuiltinState}/>@@ -170,45 +185,26 @@ export default function Agents() {><header className="mb-4 min-w-0 px-5 pt-8"><ListFilterBar- title={t('flow.agents')}- icon="agents"searchString={searchString}onSearchChange={handleInputChange}filters={filters}onChange={handleFilterSubmit}value={filterValue}+ leftPanel={+ <AgentTabGroup+ activeCategory={activeCategory}+ onTabChange={handleTabChange}+ />+ }>- <DropdownMenu>- <DropdownMenuTrigger data-testid="create-agent" asChild>- <Button>- <Plus className="size-[1em]" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent data-testid="agent-create-menu">- <DropdownMenuItem- justifyBetween={false}- onClick={showCreatingModal}- >- <Clipboard />- {t('flow.createFromBlank')}- </DropdownMenuItem>- <DropdownMenuItem- justifyBetween={false}- onClick={() => navigateToAgentTemplates()}- >- <ClipboardPlus />- {t('flow.createFromTemplate')}- </DropdownMenuItem>- <DropdownMenuItem- data-testid="agent-import-json"- justifyBetween={false}- onClick={handleImportJson}- >- <FileInput />- {t('flow.importJsonFile')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <AgentCreateMenu+ actions={createActions}+ directOnClick={+ activeType === FlowType.Compiler+ ? handleCreateCompilation+ : undefined+ }+ /></ListFilterBar></header>@@ -216,7 +212,7 @@ export default function Agents() {<><CardContainer className="flex-1 overflow-auto px-5">{data.map((x) =>- x.type === CompilationGroupCategory ? (+ x.type === AgentListItemType.CompilationTemplateGroup ? (<CompilationTemplateCardkey={x.id}data={x}@@ -234,7 +230,7 @@ export default function Agents() {{builtinVisible && (<BuiltinPipelineSection- rawCategory={rawCategory}+ canvasCategory={activeCategory}searchString={debouncedSearchString}showDivider={data.length > 0}/>@@ -260,7 +256,7 @@ export default function Agents() {isSearchtestId="agents-search-empty"type={EmptyCardType.Agent}- onClick={() => showCreatingModal()}+ onClick={showCreatingModal}/></div>) : emptyState === 'loading' ? null : (@@ -271,43 +267,8 @@ export default function Agents() {className="w-[480px] p-14 !cursor-default"type={EmptyCardType.Agent}tabIndex={-1}- // onClick={() => showCreatingModal()}>- <ul className="flex flex-col gap-y-5 text-text-secondary text-sm pt-5">- <li data-testid="agents-empty-create">- <Button- variant="static"- size="auto"- onClick={showCreatingModal}- >- <Clipboard className="size-[1em]" />- {t('flow.createFromBlank')}- </Button>- </li>-- <li>- <Button- asLink- variant="static"- size="auto"- to={Routes.AgentTemplates}- >- <ClipboardPlus className="size-[1em]" />- {t('flow.createFromTemplate')}- </Button>- </li>-- <li>- <Button- variant="static"- size="auto"- onClick={handleImportJson}- >- <FileInput className="size-[1em]" />- {t('flow.importJsonFile')}- </Button>- </li>- </ul>+ <AgentsEmptyStateActions actions={createActions} /></EmptyAppCard></div>)}@@ -326,6 +287,7 @@ export default function Agents() {loading={loading}visible={creatingVisible}hideModal={hideCreatingModal}+ selectedType={activeType}onOk={handleCreateAgentOrPipeline}></CreateAgentDialog>)}diff --git a/web/src/pages/agents/template-sidebar.tsx b/web/src/pages/agents/template-sidebar.tsxindex 4772709588..f70484650a 100644--- a/web/src/pages/agents/template-sidebar.tsx+++ b/web/src/pages/agents/template-sidebar.tsx@@ -7,7 +7,6 @@ import {Component,MessageCircleCode,PencilRuler,- Route,Sparkle,} from 'lucide-react';import { useMemo } from 'react';@@ -18,7 +17,6 @@ export enum MenuItemKey {CustomerSupport = 'Customer Support',Marketing = 'Marketing',ConsumerApp = 'Consumer App',- Pipeline = 'Ingestion Pipeline',Other = 'Other',}@@ -71,13 +69,6 @@ export function SideBar({),key: MenuItemKey.ConsumerApp,},- {- icon: Route,- label: t(- 'flow.' + lowerFirst(MenuItemKey.Pipeline.replace(' ', '')),- ),- key: MenuItemKey.Pipeline,- },{icon: PencilRuler,label: t('flow.' + lowerFirst(MenuItemKey.Other)),diff --git a/web/src/pages/agents/use-copy-builtin-pipeline.test.tsx b/web/src/pages/agents/use-copy-builtin-pipeline.test.tsxindex 6320492a04..eee1ed04e8 100644--- a/web/src/pages/agents/use-copy-builtin-pipeline.test.tsx+++ b/web/src/pages/agents/use-copy-builtin-pipeline.test.tsx@@ -1,5 +1,22 @@-import { renderHook } from '@testing-library/react';+/*+ * 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 { act, renderHook } from '@testing-library/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { AgentCategory } from '@/constants/agent';import { useCopyBuiltinPipeline } from './use-copy-builtin-pipeline';jest.mock('@/services/agent-service', () => ({@@ -10,14 +27,10 @@ jest.mock('@/services/agent-service', () => ({},}));-// 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'],- },+const mockNavigate = jest.fn();+const mockNavigateToAgent = jest.fn(() => mockNavigate);+jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({+ useNavigatePage: () => ({ navigateToAgent: mockNavigateToAgent }),}));jest.mock('@/components/ui/message', () => ({@@ -52,18 +65,21 @@ beforeEach(() => {});describe('useCopyBuiltinPipeline', () => {- it('fetches the builtin DSL and creates a user-owned dataflow pipeline', async () => {+ it('fetches the builtin DSL, creates a user-owned pipeline and opens it for editing', async () => {agentService.getBuiltinPipeline.mockResolvedValue({data: { code: 0, message: 'ok', data: { dsl: { components: {} } } },});agentService.createAgent.mockResolvedValue({- data: { code: 0, message: 'ok', data: null },+ data: { code: 0, message: 'ok', data: { id: 'new-canvas' } },});const { result } = renderHook(() => useCopyBuiltinPipeline(), {wrapper,});- const ret = await result.current.copy({ id: 'general', title: 'General' });+ let ret;+ await act(async () => {+ ret = await result.current.copy({ id: 'general', title: 'General' });+ });expect(agentService.getBuiltinPipeline).toHaveBeenCalledWith('general');expect(agentService.createAgent).toHaveBeenCalledWith({@@ -73,10 +89,15 @@ describe('useCopyBuiltinPipeline', () => {});expect(message.success).toHaveBeenCalled();expect(message.error).not.toHaveBeenCalled();+ expect(mockNavigateToAgent).toHaveBeenCalledWith(+ 'new-canvas',+ AgentCategory.DataflowCanvas,+ );+ expect(mockNavigate).toHaveBeenCalledTimes(1);expect(ret).not.toBeNull();});- it('shows an error and does not create when the builtin DSL is missing', async () => {+ it('shows an error and does not create or navigate when the builtin DSL is missing', async () => {agentService.getBuiltinPipeline.mockResolvedValue({data: { code: 0, message: 'ok', data: { dsl: undefined } },});@@ -84,14 +105,18 @@ describe('useCopyBuiltinPipeline', () => {const { result } = renderHook(() => useCopyBuiltinPipeline(), {wrapper,});- const ret = await result.current.copy({ id: 'general', title: 'General' });+ let ret;+ await act(async () => {+ ret = await result.current.copy({ id: 'general', title: 'General' });+ });expect(agentService.createAgent).not.toHaveBeenCalled();expect(message.error).toHaveBeenCalled();+ expect(mockNavigateToAgent).not.toHaveBeenCalled();expect(ret).toBeNull();});- it('shows an error when createAgent reports a failure code', async () => {+ it('shows an error and stays on the list when createAgent reports a failure code', async () => {agentService.getBuiltinPipeline.mockResolvedValue({data: { code: 0, message: 'ok', data: { dsl: { components: {} } } },});@@ -102,10 +127,13 @@ describe('useCopyBuiltinPipeline', () => {const { result } = renderHook(() => useCopyBuiltinPipeline(), {wrapper,});- await result.current.copy({ id: 'general', title: 'General' });+ await act(async () => {+ await result.current.copy({ id: 'general', title: 'General' });+ });expect(message.error).toHaveBeenCalledWith('boom');expect(message.success).not.toHaveBeenCalled();+ expect(mockNavigateToAgent).not.toHaveBeenCalled();});it('shows a request error when the fetch rejects', async () => {@@ -114,9 +142,12 @@ describe('useCopyBuiltinPipeline', () => {const { result } = renderHook(() => useCopyBuiltinPipeline(), {wrapper,});- await result.current.copy({ id: 'general', title: 'General' });+ await act(async () => {+ await result.current.copy({ id: 'general', title: 'General' });+ });expect(message.error).toHaveBeenCalled();expect(agentService.createAgent).not.toHaveBeenCalled();+ expect(mockNavigateToAgent).not.toHaveBeenCalled();});});diff --git a/web/src/pages/agents/use-copy-builtin-pipeline.ts b/web/src/pages/agents/use-copy-builtin-pipeline.tsindex 8a90019b9a..bc35529c36 100644--- a/web/src/pages/agents/use-copy-builtin-pipeline.ts+++ b/web/src/pages/agents/use-copy-builtin-pipeline.ts@@ -1,16 +1,16 @@-import { useMutation, useQueryClient } from '@tanstack/react-query';+import { useMutation } from '@tanstack/react-query';import message from '@/components/ui/message';import { AgentCategory } from '@/constants/agent';-import { AgentKeys } from '@/hooks/use-agent-request';+import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';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.+// dataflow canvas: it fetches the built-in DSL via GET /api/v1/pipelines/:id,+// creates a new canvas with that DSL, and opens it for editing. The agents+// list refetches on return (gcTime: 0), so no list invalidation is needed.export function useCopyBuiltinPipeline() {- const queryClient = useQueryClient();+ const { navigateToAgent } = useNavigatePage();const { mutateAsync, isPending } = useMutation({mutationFn: async ({ id, title }: { id: string; title: string }) => {try {@@ -34,8 +34,7 @@ export function useCopyBuiltinPipeline() {if (created?.code === 0) {message.success(i18n.t('message.created'));- queryClient.invalidateQueries({ queryKey: AgentKeys.list() });- queryClient.invalidateQueries({ queryKey: AgentKeys.filters() });+ navigateToAgent(created.data.id, AgentCategory.DataflowCanvas)();return created;}diff --git a/web/src/pages/agents/use-import-json.test.ts b/web/src/pages/agents/use-import-json.test.tsnew file mode 100644index 0000000000..5299ad154f--- /dev/null+++ b/web/src/pages/agents/use-import-json.test.ts@@ -0,0 +1,188 @@+/*+ * 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 { act, renderHook } from '@testing-library/react';+import { AgentCategory } from '@/constants/agent';+import { useHandleImportJsonFile } from './use-import-json';++jest.mock('@/hooks/common-hooks', () => ({+ useSetModalState: jest.fn(),+}));++jest.mock('@/hooks/use-agent-request', () => ({+ useCreateAgent: jest.fn(),+}));++const mockNavigate = jest.fn();+const mockNavigateToAgent = jest.fn(() => mockNavigate);+jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({+ useNavigatePage: () => ({ navigateToAgent: mockNavigateToAgent }),+}));++jest.mock('@/components/hooks/use-toast', () => ({+ useToast: () => ({ toast: jest.fn() }),+}));++jest.mock('@/components/ui/message', () => ({+ __esModule: true,+ default: { error: jest.fn() },+}));++jest.mock('@/pages/agent/utils/dsl-bridge', () => ({+ importDsl: jest.fn(() => ({ graph: {} })),+ inferIsAgentFromImport: jest.fn(),+}));++// eslint-disable-next-line @typescript-eslint/no-var-requires+const mockCommonHooks = require('@/hooks/common-hooks');+// eslint-disable-next-line @typescript-eslint/no-var-requires+const mockAgentRequest = require('@/hooks/use-agent-request');+// eslint-disable-next-line @typescript-eslint/no-var-requires+const mockDslBridge = require('@/pages/agent/utils/dsl-bridge');+// eslint-disable-next-line @typescript-eslint/no-var-requires+const mockMessage = require('@/components/ui/message').default;++const createAgent = jest.fn();+const hideFileUploadModal = jest.fn();++function jsonFile(content: unknown): File {+ return {+ type: 'application/json',+ text: async () => JSON.stringify(content),+ } as unknown as File;+}++function uploadPayload(content: unknown) {+ return { fileList: [jsonFile(content)], name: 'Imported' };+}++beforeEach(() => {+ jest.clearAllMocks();+ mockCommonHooks.useSetModalState.mockReturnValue({+ visible: true,+ hideModal: hideFileUploadModal,+ showModal: jest.fn(),+ });+ mockAgentRequest.useCreateAgent.mockReturnValue({+ loading: false,+ createAgent,+ });+});++describe('useHandleImportJsonFile', () => {+ it('imports a workflow JSON on the Workflow tab and opens the new canvas', async () => {+ mockDslBridge.inferIsAgentFromImport.mockReturnValue(true);+ createAgent.mockResolvedValue({ code: 0, data: { id: '1' } });++ const { result } = renderHook(() =>+ useHandleImportJsonFile(AgentCategory.AgentCanvas),+ );+ await act(async () => {+ await result.current.onFileUploadOk(uploadPayload({ graph: {} }));+ });++ expect(mockDslBridge.importDsl).toHaveBeenCalled();+ expect(createAgent).toHaveBeenCalledWith({+ title: 'Imported',+ dsl: { graph: {} },+ canvas_category: AgentCategory.AgentCanvas,+ });+ expect(hideFileUploadModal).toHaveBeenCalled();+ expect(mockNavigateToAgent).toHaveBeenCalledWith(+ '1',+ AgentCategory.AgentCanvas,+ );+ expect(mockNavigate).toHaveBeenCalledTimes(1);+ });++ it('imports a pipeline JSON on the Pipeline tab and opens the new canvas', async () => {+ mockDslBridge.inferIsAgentFromImport.mockReturnValue(false);+ createAgent.mockResolvedValue({ code: 0, data: { id: '2' } });++ const { result } = renderHook(() =>+ useHandleImportJsonFile(AgentCategory.DataflowCanvas),+ );+ await act(async () => {+ await result.current.onFileUploadOk(uploadPayload({ graph: {} }));+ });++ expect(createAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ canvas_category: AgentCategory.DataflowCanvas,+ }),+ );+ expect(mockNavigateToAgent).toHaveBeenCalledWith(+ '2',+ AgentCategory.DataflowCanvas,+ );+ expect(mockNavigate).toHaveBeenCalledTimes(1);+ });++ it('stays on the list when creation fails', async () => {+ mockDslBridge.inferIsAgentFromImport.mockReturnValue(true);+ createAgent.mockResolvedValue({ code: 1 });++ const { result } = renderHook(() =>+ useHandleImportJsonFile(AgentCategory.AgentCanvas),+ );+ await act(async () => {+ await result.current.onFileUploadOk(uploadPayload({ graph: {} }));+ });++ expect(hideFileUploadModal).not.toHaveBeenCalled();+ expect(mockNavigateToAgent).not.toHaveBeenCalled();+ expect(mockNavigate).not.toHaveBeenCalled();+ });++ it.each([+ ['pipeline file on the Workflow tab', false, AgentCategory.AgentCanvas],+ ['workflow file on the Pipeline tab', true, AgentCategory.DataflowCanvas],+ ])(+ 'rejects a %s without converting, creating or navigating',+ async (_label, isAgent, expectedCategory) => {+ mockDslBridge.inferIsAgentFromImport.mockReturnValue(isAgent);++ const { result } = renderHook(() =>+ useHandleImportJsonFile(expectedCategory),+ );+ await act(async () => {+ await result.current.onFileUploadOk(uploadPayload({ graph: {} }));+ });++ expect(mockMessage.error).toHaveBeenCalledWith(+ 'flow.jsonUploadCategoryMismatch',+ );+ expect(mockDslBridge.importDsl).not.toHaveBeenCalled();+ expect(createAgent).not.toHaveBeenCalled();+ expect(mockNavigateToAgent).not.toHaveBeenCalled();+ },+ );++ it('rejects empty JSON content as before', async () => {+ const { result } = renderHook(() =>+ useHandleImportJsonFile(AgentCategory.AgentCanvas),+ );+ await act(async () => {+ await result.current.onFileUploadOk(uploadPayload({}));+ });++ expect(mockMessage.error).toHaveBeenCalledWith(+ 'flow.jsonUploadContentErrorMessage',+ );+ expect(createAgent).not.toHaveBeenCalled();+ expect(mockNavigateToAgent).not.toHaveBeenCalled();+ });+});diff --git a/web/src/pages/agents/use-import-json.ts b/web/src/pages/agents/use-import-json.tsindex 55b38d3297..063677bd97 100644--- a/web/src/pages/agents/use-import-json.ts+++ b/web/src/pages/agents/use-import-json.ts@@ -3,7 +3,8 @@ import message from '@/components/ui/message';import { AgentCategory } from '@/constants/agent';import { FileMimeType } from '@/constants/common';import { useSetModalState } from '@/hooks/common-hooks';-import { useSetAgent } from '@/hooks/use-agent-request';+import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';+import { useCreateAgent } from '@/hooks/use-agent-request';import * as bridge from '@/pages/agent/utils/dsl-bridge';import { inferIsAgentFromImport } from '@/pages/agent/utils/dsl-bridge';import isEmpty from 'lodash/isEmpty';@@ -11,7 +12,7 @@ import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { FormSchemaType } from './upload-agent-dialog/upload-agent-form';-export const useHandleImportJsonFile = () => {+export const useHandleImportJsonFile = (expectedCategory: string) => {const {visible: fileUploadVisible,hideModal: hideFileUploadModal,@@ -19,7 +20,8 @@ export const useHandleImportJsonFile = () => {} = useSetModalState();const { t } = useTranslation();const { toast } = useToast();- const { loading, setAgent } = useSetAgent();+ const { loading, createAgent } = useCreateAgent();+ const { navigateToAgent } = useNavigatePage();const onFileUploadOk = useCallback(async ({ fileList, name }: FormSchemaType) => {@@ -36,14 +38,29 @@ export const useHandleImportJsonFile = () => {const rawParsed = JSON.parse(graphOrDslStr);if (graphOrDslStr && !isEmpty(rawParsed)) {const isAgent = inferIsAgentFromImport(rawParsed);+ // The active tab decides what this import must produce; a file of+ // the other canvas kind is rejected instead of silently creating+ // a canvas in the wrong category.+ const inferredCategory = isAgent+ ? AgentCategory.AgentCanvas+ : AgentCategory.DataflowCanvas;+ if (inferredCategory !== expectedCategory) {+ message.error(t('flow.jsonUploadCategoryMismatch'));+ return;+ }const dsl = bridge.importDsl(rawParsed, isAgent);- return await setAgent({+ const ret = await createAgent({title: name,dsl,- canvas_category: isAgent- ? AgentCategory.AgentCanvas- : AgentCategory.DataflowCanvas,+ canvas_category: expectedCategory,});+ if (ret?.code === 0) {+ hideFileUploadModal();+ // Import is only offered on the Workflow/Pipeline tabs, so the+ // tab category is always a canvas category here.+ navigateToAgent(ret.data.id, expectedCategory as AgentCategory)();+ }+ return ret;} else {message.error(errorMessage);}@@ -52,7 +69,14 @@ export const useHandleImportJsonFile = () => {}}},- [setAgent, t, toast],+ [+ expectedCategory,+ createAgent,+ hideFileUploadModal,+ navigateToAgent,+ t,+ toast,+ ],);return {diff --git a/web/src/pages/builtin-pipeline/index.tsx b/web/src/pages/builtin-pipeline/index.tsxindex fa126b7c01..ac6f6033aa 100644--- a/web/src/pages/builtin-pipeline/index.tsx+++ b/web/src/pages/builtin-pipeline/index.tsx@@ -9,9 +9,11 @@ import {BreadcrumbSeparator,} from '@/components/ui/breadcrumb';import { Spin } from '@/components/ui/spin';+import { AgentCategory } from '@/constants/agent';import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';import { useFetchBuiltinPipelines } from '@/hooks/use-agent-request';import { ReactFlowProvider } from '@xyflow/react';+import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';import AgentCanvas from '../agent/canvas';@@ -32,6 +34,11 @@ export default function BuiltinPipelinePage() {const { loading } = useFetchBuiltinPipelineDataOnMount();const { data } = useFetchBuiltinPipelines();const title = data.canvas.find((x) => x.id === id)?.title ?? '';+ // Built-in pipelines live under the ingestion pipeline tab of the agents+ // list, so the back-link targets that tab rather than the workflow default.+ const handleBackToAgents = useCallback(() => {+ navigateToAgents(AgentCategory.DataflowCanvas);+ }, [navigateToAgents]);return (<section className="h-full" data-testid="builtin-pipeline-page">@@ -40,7 +47,7 @@ export default function BuiltinPipelinePage() {<Breadcrumb><BreadcrumbList><BreadcrumbItem>- <BreadcrumbLink onClick={navigateToAgents}>+ <BreadcrumbLink onClick={handleBackToAgents}>{t('flow.agents')}</BreadcrumbLink></BreadcrumbItem>diff --git a/web/src/pages/user-setting/compilation-templates/edit-next/index.test.ts b/web/src/pages/user-setting/compilation-templates/edit-next/index.test.tsnew file mode 100644index 0000000000..55f14df6ba--- /dev/null+++ b/web/src/pages/user-setting/compilation-templates/edit-next/index.test.ts@@ -0,0 +1,30 @@+/*+ * 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 { resolveAgentsUrl } from './utils';++describe('resolveAgentsUrl', () => {+ it('restores the Compilation tab for the agents source', () => {+ expect(resolveAgentsUrl('agents')).toBe(+ '/agents?canvas_category=compilation_template_group',+ );+ });++ it('keeps the plain agents route for other entry points', () => {+ expect(resolveAgentsUrl(null)).toBe('/agents');+ expect(resolveAgentsUrl('settings')).toBe('/agents');+ });+});diff --git a/web/src/pages/user-setting/compilation-templates/edit-next/index.tsx b/web/src/pages/user-setting/compilation-templates/edit-next/index.tsxindex c56398e92b..6afd0d7d62 100644--- a/web/src/pages/user-setting/compilation-templates/edit-next/index.tsx+++ b/web/src/pages/user-setting/compilation-templates/edit-next/index.tsx@@ -19,27 +19,27 @@ import { Button } from '@/components/ui/button';import { Form } from '@/components/ui/form';import { CompilationTemplateKind } from '@/constants/compilation';import { useFetchCompilationTemplateGroup } from '@/hooks/use-compilation-template-group-request';-import { Routes } from '@/routes';import { useCallback, useMemo } from 'react';import { useWatch } from 'react-hook-form';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router';+import { useNavigate, useSearchParams } from 'react-router';import { BlueprintSection } from './components/blueprint-section';import { TemplateConfiguration } from './components/template-configuration';import { useEditNextCompilationTemplateGroup } from './hooks/use-edit-next-compilation-template-group';+import { resolveAgentsUrl } from './utils';const SelectedTemplateIndex = 0;-const agentsUrl = Routes.Agents;-export default function EditNextCompilationTemplate() {const { t } = useTranslation();const navigate = useNavigate();+ const [searchParams] = useSearchParams();+ const agentsUrl = resolveAgentsUrl(searchParams.get('source'));const navigateToAgents = useCallback(() => {navigate(agentsUrl);- }, [navigate]);+ }, [navigate, agentsUrl]);const { form, kindOptions, builtins, onSubmit, isCreate, isLoading } =useEditNextCompilationTemplateGroup({diff --git a/web/src/pages/user-setting/compilation-templates/edit-next/utils.ts b/web/src/pages/user-setting/compilation-templates/edit-next/utils.tsindex 8369d11917..3c3f0fbe9c 100644--- a/web/src/pages/user-setting/compilation-templates/edit-next/utils.ts+++ b/web/src/pages/user-setting/compilation-templates/edit-next/utils.ts@@ -16,6 +16,9 @@import { isEqual } from 'lodash';+import { AgentQuery } from '@/constants/agent';+import { CompilationTemplateKind } from '@/constants/compilation';+import { AgentListItemType } from '@/interfaces/database/agent';import {ICompilationTemplate,ICompilationTemplateBuiltin,@@ -24,8 +27,7 @@ import {ICompilationTemplateSection,} from '@/interfaces/database/compilation-template';import { ICompilationTemplateConfigRequest } from '@/interfaces/request/compilation-template';--import { CompilationTemplateKind } from '@/constants/compilation';+import { Routes } from '@/routes';import { FormSchemaType, TemplateSchemaType } from './schema';import {@@ -340,3 +342,15 @@ export const getAvailableTypeOptions = ((option) => !usedTypes.has(option.value),);};++export const resolveAgentsUrl = (source: string | null): string => {+ // Only the Agents page owns the canvas_category tab param; other entry+ // points keep the plain Agents route on return.+ if (source !== 'agents') {+ return Routes.Agents;+ }+ const params = new URLSearchParams({+ [AgentQuery.CanvasCategory]: AgentListItemType.CompilationTemplateGroup,+ });+ return `${Routes.Agents}?${params.toString()}`;+};diff --git a/web/src/services/agent-service.ts b/web/src/services/agent-service.tsindex 29140aa73a..22bfad1f37 100644--- a/web/src/services/agent-service.ts+++ b/web/src/services/agent-service.ts@@ -15,6 +15,7 @@*/import {+ DSL,IAgentLogsRequest,IPipeLineListRequest,} from '@/interfaces/database/agent';@@ -173,8 +174,8 @@ export const updateAgent = (agentId: string,params: {title?: string;- dsl?: Record<string, any>;- avatar?: string;+ dsl?: DSL | Record<string, any>;+ avatar?: string | null;description?: string | null;permission?: string;release?: string;